ArangoDB-Community / pyArango

Python Driver for ArangoDB with built-in validation
https://pyarango.readthedocs.io/en/latest/
Apache License 2.0
238 stars 90 forks source link

Best way to check if collection exists #162

Closed igaln closed 4 years ago

igaln commented 5 years ago

Trying to check if a collection exists before creating

Options

These seems to an isCollection in Collection object, but I assumed that is for initialized collections already.

Please advice, Thank you

subfxnet commented 4 years ago

in pyArango/database.py there is a method Database().hasCollection(name): bool. You could also call Database().reloadCollections() first to ensure you have the latest collection set loaded into the client.

Something like:

from pyArango.connection import Connection

conn = Connection(**params)
sess = conn[DB_NAME]
#sess.reloadCollections()
if sess.hasCollection(name):
    return sess.collections[name]
return sess.createCollection(name)
tariqdaouda commented 4 years ago

As @subfxnet pointed out you could use the hasCollection() function. You could also just do a try/except:

try:
  DB[col_name]
except KeyError:
  print("collection not found")