ArangoDB-PHP Collection exists check

400 Views Asked by At

I want to make a check if a Collection already exist with ArangoDB-PHP.

$collectionHandler = new CollectionHandler($arango);
$userCollection = new Collection();
$userCollection->setName('_profiles');

Because I get the following error:

Server error: 1207:cannot create collection: duplicate name cannot create collection: duplicate name

How can I check if a collection already exists with ArangoDB-PHP?

2

There are 2 best solutions below

0
On BEST ANSWER

I should use try/catch statement

try { 
    $collectionHandler = new CollectionHandler($arango);
    $userCollection = new Collection();
    $userCollection->setName('_profiles');
    $collectionHandler->create($userCollection);
} catch (ServerException $e) {
    // do something
}
0
On

It is considered bad style to use exception handling to drive program flow -- it should be used for real exceptions. In your case the prior existence of the collection containing user profiles is the rule, I assume, not an exception.

The correct way to check for the existence of a collection is CollectionHandler::has($id). The correct way to create a collection is to use CollectionHandler::create($collection). create accepts a string as parameter, the name of collection to create.

$userCollectionName = '_profiles';

$collectionHandler = new CollectionHandler($arango);
$userCollection = $collectionHandler->has($userCollectionName) ?
    $collectionHandler->get($userCollectionName) 
    : 
    $collectionHandler->create($userCollectionName);