/** * Initialize the export * * @throws Exception * * @param Connection $connection - the connection to be used * @param string $collection - the collection to export * @param array $data - export options */ public function __construct(Connection $connection, $collection, array $data = array()) { $this->_connection = $connection; if (!$collection instanceof Collection) { $collectionHandler = new CollectionHandler($this->_connection); $collection = $collectionHandler->get($collection); } $this->_collection = $collection; // check if we're working with an edge collection or not $this->_type = $this->_collection->getType(); if (isset($data[self::ENTRY_FLUSH])) { // set a default value $this->_flush = $data[self::ENTRY_FLUSH]; } if (isset($data[self::ENTRY_BATCHSIZE])) { $this->setBatchSize($data[self::ENTRY_BATCHSIZE]); } if (isset($data[self::ENTRY_LIMIT])) { $this->_limit = (int) $data[self::ENTRY_LIMIT]; } if (isset($data[self::ENTRY_RESTRICT]) && is_array($data[self::ENTRY_RESTRICT])) { $restrictions = $data[self::ENTRY_RESTRICT]; if (!isset($restrictions["type"]) || !in_array($restrictions["type"], array("include", "exclude"), true)) { // validate restrictions.type throw new ClientException('Invalid restrictions type definition'); } if (!isset($restrictions["fields"]) || !is_array($restrictions["fields"])) { // validate restrictions.fields throw new ClientException('Invalid restrictions fields definition'); } // all valid $this->_restrictions = $restrictions; } if (isset($data[ExportCursor::ENTRY_FLAT])) { $this->_flat = (bool) $data[ExportCursor::ENTRY_FLAT]; } }
<?php namespace triagens\ArangoDb; require dirname(__FILE__) . DIRECTORY_SEPARATOR . 'init.php'; try { $connection = new Connection($connectionOptions); $handler = new CollectionHandler($connection); if ($handler->has('example')) { $handler->delete('example'); } $col = new Collection(); $col->setName('example'); $result = $handler->add($col); // create a statement to insert 100 example documents $statement = new Statement($connection, array('query' => 'FOR i IN 1..100 INSERT { _key: CONCAT("example", i) } IN example')); $statement->execute(); // print number of documents var_dump($handler->getCount('example')); // later on, we can assemble a list of document keys $keys = array(); for ($i = 1; $i <= 100; ++$i) { $keys[] = 'example' . $i; } // and fetch all the documents at once by their keys $documents = $handler->lookupByKeys('example', $keys); var_dump($documents); // we can also bulk-remove them: $result = $handler->removeByKeys('example', $keys); var_dump($result); // print number of documents after bulk removal
$v = new Document(); $v->set("name", $id + 1); $v->set("component", $id); $v->set("distance", -1); $v->set("pr", 1.0 / $nv); $documents->add("vertices", $v); return $v->getHandle(); } if (count($argv) < 3) { $prog = $argv[0]; print "Usage {$prog} graphfile actionsfile"; exit; } print "Setting up DB connection...\n"; $connection = new Connection($connectionOptions); $collections = new CollectionHandler($connection); $documents = new DocumentHandler($connection); $edges = new EdgeHandler($connection); /* drop vertex if it exists */ try { $vertex = $collections->get("vertices"); $collections->drop($vertex); } catch (Exception $e) { // do nothing } /* drop edge if it exists */ try { $edge = $collections->get("edges"); $collections->drop($edge); } catch (Exception $e) { // do nothing
public function testCreateMixedBatchWithPartIds() { $edgeCollection = $this->edgeCollection; $batch = new Batch($this->connection); $this->assertInstanceOf('\\triagens\\ArangoDb\\Batch', $batch); // Create collection $connection = $this->connection; $collection = new Collection(); $collectionHandler = new CollectionHandler($connection); $name = 'ArangoDB_PHP_TestSuite_TestCollection_02'; $collection->setName($name); $batch->nextBatchPartId('testCollection1'); $response = $collectionHandler->add($collection); $this->assertTrue(is_numeric($response), 'Did not return a fake numeric id!'); $batch->process(); $resultingCollectionId = $batch->getProcessedPartResponse('testCollection1'); $testCollection1Part = $batch->getPart('testCollection1'); $this->assertTrue($testCollection1Part->getHttpCode() == 200, 'Did not return an HttpCode 200!'); $resultingCollection = $collectionHandler->get($batch->getProcessedPartResponse('testCollection1')); $resultingAttribute = $resultingCollection->getName(); $this->assertTrue($name === $resultingAttribute, 'The created collection name and resulting collection name do not match!'); $this->assertEquals(Collection::getDefaultType(), $resultingCollection->getType()); $batch = new Batch($this->connection); // Create documents $documentHandler = $this->documentHandler; $batch->nextBatchPartId('doc1'); $document = Document::createFromArray(array('someAttribute' => 'someValue', 'someOtherAttribute' => 'someOtherValue')); $documentId = $documentHandler->add($resultingCollectionId, $document); $this->assertTrue(is_numeric($documentId), 'Did not return a fake numeric id!'); for ($i = 0; $i <= 10; ++$i) { $document = Document::createFromArray(array('someAttribute' => 'someValue' . $i, 'someOtherAttribute' => 'someOtherValue2' . $i)); $documentId = $documentHandler->add($resultingCollectionId, $document); } $this->assertTrue(is_numeric($documentId), 'Did not return a fake numeric id!'); $batch->process(); // try getting processed response through batchpart $testDocument1PartResponse = $batch->getPart('doc1')->getProcessedResponse(); // try getting it from batch $testDocument2PartResponse = $batch->getProcessedPartResponse(1); $batch = new Batch($this->connection); $docId1 = explode('/', $testDocument1PartResponse); $docId2 = explode('/', $testDocument2PartResponse); $documentHandler->getById($resultingCollectionId, $docId1[1]); $documentHandler->getById($resultingCollectionId, $docId2[1]); $batch->process(); $document1 = $batch->getProcessedPartResponse(0); $document2 = $batch->getProcessedPartResponse(1); $batch = new Batch($this->connection); // test edge creation $edgeDocument = new Edge(); $edgeDocumentHandler = new EdgeHandler($connection); $edgeDocument->set('label', 'knows'); $edgeDocumentHandler->saveEdge($edgeCollection->getName(), $document1->getHandle(), $document2->getHandle(), $edgeDocument); $batch->process(); $edge = $batch->getProcessedPartResponse(0); $this->assertFalse(is_a($edge, 'triagens\\ArangoDb\\HttpResponse'), 'Edge batch creation did return an error: ' . print_r($edge, true)); $this->assertTrue($edge == !'', 'Edge batch creation did return empty string: ' . print_r($edge, true)); $batch = new Batch($this->connection); $document = new Document(); $documentHandler = new DocumentHandler($connection); $document->someAttribute = 'someValue'; $documentHandler->add($resultingCollection->getId(), $document); // set the next batchpart id $batch->nextBatchPartId('myBatchPart'); // set cursor options for the next batchpart $batch->nextBatchPartCursorOptions(array("sanitize" => true)); // set batchsize to 10, so we can test if an additional http request is done when we getAll() a bit later $statement = new Statement($connection, array("query" => '', "count" => true, "batchSize" => 10, "sanitize" => true)); $statement->setQuery('FOR a IN `ArangoDB_PHP_TestSuite_TestCollection_02` RETURN a'); $statement->execute(); $documentHandler->removeById($resultingCollectionId, $docId1[1]); $documentHandler->removeById($resultingCollectionId, $docId2[1]); $batch->nextBatchPartId('docsAfterRemoval'); $collectionHandler->getAllIds($resultingCollectionId); $batch->process(); $stmtCursor = $batch->getProcessedPartResponse('myBatchPart'); $this->assertTrue(count($stmtCursor->getAll()) == 13, 'At the time of statement execution there should be 13 documents found! Found: ' . count($stmtCursor->getAll())); // This fails but we'll just make a note because such a query is not needed to be batched. // $docsAfterRemoval=$batch->getProcessedPartResponse('docsAfterRemoval'); // $this->assertTrue(count($docsAfterRemoval) == 1, 'At the time of statement execution there should be 3 documents found! Found: '.count($stmtCursor->getAll())); // Get previously created collection and delete it, from inside a batch $batch = new Batch($this->connection); $collectionHandler->delete($resultingCollectionId); $batch->process(); }
<?php namespace triagens\ArangoDb; require dirname(__FILE__) . DIRECTORY_SEPARATOR . 'init.php'; try { $connection = new Connection($connectionOptions); $handler = new CollectionHandler($connection); // create a new collection $col = new Collection(); $col->setName("hihi"); $result = $handler->add($col); var_dump($result); // check if a collection exists $result = $handler->has("foobar"); var_dump($result); // get an existing collection $result = $handler->get("hihi"); var_dump($result); // get an existing collection $result = $handler->get("hihi"); var_dump($result); // get number of documents from an existing collection $result = $handler->getCount("hihi"); var_dump($result); // get figures for an existing collection $result = $handler->getFigures("hihi"); var_dump($result); // delete the collection $result = $handler->delete("hihi"); var_dump($result);
/** * Try to create and delete an edge collection not using an edge object */ public function testCreateAndDeleteSystemCollectionWithoutCreatingObject() { $connection = $this->connection; $collectionHandler = new CollectionHandler($connection); $name = '_ArangoDB_PHP_TestSuite_TestCollection_02'; try { $collectionHandler->drop($name); } catch (Exception $e) { //Silence the exception } $options = array('isSystem' => true, 'waitForSync' => true); $collectionHandler->create($name, $options); $resultingCollection = $collectionHandler->get($name); $resultingAttribute = $resultingCollection->getName(); $this->assertTrue($name === $resultingAttribute, 'The created collection name and resulting collection name do not match!'); $resultingCollectionProperties = $collectionHandler->getProperties($name); $this->assertTrue($resultingCollectionProperties->getIsSystem()); $this->assertTrue($resultingCollectionProperties->getWaitForSync()); $collectionHandler->delete($name); }
<?php namespace triagens\ArangoDb; require dirname(__FILE__) . DIRECTORY_SEPARATOR . 'init.php'; try { $connection = new Connection($connectionOptions); $collectionHandler = new CollectionHandler($connection); $documentHandler = new DocumentHandler($connection); $edgeHandler = new EdgeHandler($connection); // set up two document collections $collection = new Collection("employees"); try { $collectionHandler->add($collection); } catch (\Exception $e) { // collection may already exist - ignore this error for now } $collection = new Collection("departments"); try { $collectionHandler->add($collection); } catch (\Exception $e) { // collection may already exist - ignore this error for now } // set up an edge collection to link the two previous collections $collection = new Collection("worksFor"); $collection->setType(3); try { $collectionHandler->add($collection); } catch (\Exception $e) { // collection may already exist - ignore this error for now }
<?php namespace triagens\ArangoDb; require dirname(__FILE__) . DIRECTORY_SEPARATOR . 'init.php'; try { $connection = new Connection($connectionOptions); $collectionHandler = new CollectionHandler($connection); $handler = new DocumentHandler($connection); // set up a document collection "users" $collection = new Collection("users"); try { $collectionHandler->add($collection); } catch (\Exception $e) { // collection may already exist - ignore this error for now } // create a new document $user = new Document(); $user->set("name", "John"); $user->age = 19; $id = $handler->save("users", $user); // get documents by example $cursor = $collectionHandler->byExample("users", array("name" => "John", "age" => 19)); var_dump($cursor->getAll()); // get the ids of all documents in the collection $result = $handler->getAllIds("users"); var_dump($result); // create another new document $user = new Document(); $user->set("name", "j-lo"); $user->level = 1;
/** * Get document(s) by specifying an example * * This will throw if the list cannot be fetched from the server * * * @throws Exception * * @param mixed $collectionId - collection id as string or number * @param mixed $document - the example document as a Document object or an array * @param bool|array $options - optional, prior to v1.0.0 this was a boolean value for sanitize, since v1.0.0 it's an array of options. * <p>Options are :<br> * <li>'_sanitize' - True to remove _id and _rev attributes from result documents. Defaults to false.</li> * <li>'sanitize' - Deprecated, please use '_sanitize'.</li> * <li>'_hiddenAttributes' - Set an array of hidden attributes for created documents. * <li>'hiddenAttributes' - Deprecated, please use '_hiddenAttributes'.</li> * <p> * This is actually the same as setting hidden attributes using setHiddenAttributes() on a document. <br> * The difference is, that if you're returning a resultset of documents, the getAll() is already called <br> * and the hidden attributes would not be applied to the attributes.<br> * </p> * </li> * <li>'batchSize' - can optionally be used to tell the server to limit the number of results to be transferred in one batch</li> * <li>'skip' - Optional, The number of documents to skip in the query.</li> * <li>'limit' - Optional, The maximal amount of documents to return. 'skip' is applied before the limit restriction.</li> * </p> * * @return cursor - Returns a cursor containing the result * * @deprecated to be removed in version 2.0 - This function is being replaced by CollectionHandler::byExample() */ public function getByExample($collectionId, $document, $options = false) { $collectionHandler = new CollectionHandler($this->getConnection()); return $collectionHandler->byExample($collectionId, $document, $options); }
/** * Test the enhanced tracer */ public function testEnhancedTracer() { //Setup $self = $this; //Hack for PHP 5.3 compatibility $enhancedTracer = function ($data) use($self) { $self->assertTrue($data instanceof TraceRequest || $data instanceof TraceResponse, '$data must be instance of TraceRequest or TraceResponse.'); $self->assertInternalType('array', $data->getHeaders(), 'Headers should be an array!'); $self->assertNotEmpty($data->getHeaders(), 'Headers should not be an empty array!'); $self->assertInternalType('string', $data->getBody(), 'Body must be a string!'); if ($data instanceof TraceRequest) { $self->assertContains($data->getMethod(), array(HttpHelper::METHOD_DELETE, HttpHelper::METHOD_GET, HttpHelper::METHOD_HEAD, HttpHelper::METHOD_PATCH, HttpHelper::METHOD_POST, HttpHelper::METHOD_PUT), 'Invalid http method!'); $self->assertInternalType('string', $data->getRequestUrl(), 'Request url must be a string!'); $self->assertEquals('request', $data->getType()); foreach ($data->getHeaders() as $header => $value) { $self->assertInternalType('string', $value, "The header value should be a string"); $self->assertInternalType('string', $header, "The header should be a string"); } } else { $self->assertInternalType('integer', $data->getHttpCode(), 'Http code must be an integer!'); $self->assertInternalType('string', $data->getHttpCodeDefinition(), 'Http code definition must be a string!'); $self->assertEquals('response', $data->getType()); $self->assertInternalType('float', $data->getTimeTaken()); } }; $options = getConnectionOptions(); $options[ConnectionOptions::OPTION_TRACE] = $enhancedTracer; $options[ConnectionOptions::OPTION_ENHANCED_TRACE] = true; $connection = new Connection($options); $collectionHandler = new CollectionHandler($connection); //Try creating a collection $collectionHandler->create('ArangoDB_PHP_TestSuite_TestTracer'); //Delete the collection try { $collectionHandler->drop('ArangoDB_PHP_TestSuite_TestTracer'); } catch (Exception $e) { } }