/** * @covers Phossa\Db\Pdo\Statement::prepare() * @covers Phossa\Db\Pdo\Statement::execute() */ public function testExecute2() { // must emulate $this->driver->setAttribute('PDO::ATTR_EMULATE_PREPARES', true); $this->statement->prepare("SELECT :idx, :color"); $res = $this->statement->execute(['idx' => 1, 'color' => 'red']); $this->assertEquals([[1 => "1", "red" => "red"]], $res->fetchRow()); }
public function find() { $f = []; /* get all fields and build a sentence to AQL find with params */ if (!empty($this->post)) { foreach ($this->post as $k => $v) { $f[] = "u.{$k} == @{$k}"; } } $filter = !empty($f) ? ' filter ' . implode($f, ' && ') : ''; $query = "FOR u IN " . COLLECTION_NAME . $filter . $this->limit . $this->sort . " RETURN u"; $statement = new Statement($this->connection, ["query" => $query, "count" => true, "bindVars" => $this->post]); $cursor = $statement->execute(); $total = $this->collectionHandler->count(COLLECTION_NAME); $result = ['count' => $cursor->getCount(), 'total' => $total, 'pages' => $total > 0 ? $total / PER_PAGE : $total]; /* transform in array */ foreach ($cursor->getAll() as $key => $value) { if (is_object($cursor->getAll()[$key])) { $result["result"][$key] = get_object_vars($cursor->getAll()[$key]); } } echo json_encode($result); }
/** * Executes a prepared statement. * * @link http://php.net/manual/en/pdostatement.execute.php * * @param array $input_parameters (optional) * * @return bool */ public function execute($input_parameters = []) { $start = microtime(true); if (func_num_args() === 0) { $result = parent::execute(); } else { $result = parent::execute($input_parameters); } $statement = (string) $this->queryString; $executedIn = microtime(true) - $start; if ($this->database->logger->limit === -1 || $this->database->logger->count < $this->database->logger->limit) { // Only interpolate the query if it's going to be logged. $params = count($input_parameters) === 0 ? $this->params : $input_parameters; $statement = $this->interpolate($statement, $params); } $this->database->logger->append($statement, array('duration' => $executedIn)); if ($result === false) { $this->database->reportError($statement, $this->errorInfo()); } else { $this->database->checkWarnings($statement); } return $result; }
/** * Execute a query * * @param string $statement sql query * @param int $mode PDO query() mode * @param int $p1 PDO query() first parameter * @param int $p2 PDO query() second parameter * * @return Statement * @throws \PDOException */ public function query($statement, $mode = null, $p1 = null, $p2 = null) { // TODO: use mode and parameters $stmt = null; try { $stmt = new Statement($this, $statement); $stmt->execute(); $this->setError(); return $stmt; } catch (\Exception $e) { throw new \PDOException($e->getMessage()); } return $stmt; }
/** * Test export some documents */ public function testExportDocumentsWithSmallBatchSize() { if (!$this->hasExportApi) { return; } $connection = $this->connection; $statement = new Statement($connection, array("query" => "FOR i IN 1..5000 INSERT { _key: CONCAT('test', i), value: i } IN " . $this->collection->getName())); $statement->execute(); $export = new Export($connection, $this->collection, array("batchSize" => 100)); $cursor = $export->execute(); $this->assertEquals(1, $cursor->getFetches()); $this->assertNotNull($cursor->getId()); $this->assertEquals(5000, $cursor->getCount()); $all = array(); while ($more = $cursor->getNextBatch()) { $all = array_merge($all, $more); } $this->assertEquals(50, $cursor->getFetches()); $this->assertEquals(5000, count($all)); $this->assertFalse($cursor->getNextBatch()); }
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 var_dump($handler->getCount('example'));
public function testBindReservedName() { $connection = $this->connection; $collection = $this->collection; $documentHandler = new DocumentHandler($connection); $document = new Document(); $document->test = 'file'; $documentHandler->add($collection->getId(), $document); $statement = new Statement($connection, array("query" => 'FOR a IN `ArangoDB_PHP_TestSuite_TestCollection_01` FILTER a.test == @test RETURN a.test', "bindVars" => array("test" => "file"), "_sanitize" => true)); $cursor = $statement->execute(); $rows = $cursor->getAll(); $this->assertEquals("file", $rows[0]); }
function execute() { $platform = $this->getPlatform(); return $platform->add() . parent::execute(); }
/** * Get the <a href="http://en.wikipedia.org/wiki/Eccentricity_%28graph_theory%29">diameter</a> of a graph. * * This will throw if the list cannot be fetched from the server * This does not support 'batchsize', 'limit' and 'count'.<br><br> * * @throws Exception * * @param mixed $graph - graph name as a string or instance of Graph * * @param bool|array $options - an array of optional parameters: * <ul><br> * <li><b>direction</b> - The direction of the edges as a string. * Possible values are *outbound*, *inbound* and *any* (default).</li> * <li><b>algorithm</b> - The algorithm to calculate the shortest paths. If both start and end vertex examples are empty * <a href="http://en.wikipedia.org/wiki/Floyd%E2%80%93Warshall_algorithm">Floyd-Warshall</a> is used, otherwise the * default is <a "href=http://en.wikipedia.org/wiki/Dijkstra's_algorithm">Dijkstra</a>. * <li><b>weight</b> - The name of the attribute of the edges containing the length as a string. * <li><b>defaultWeight</b> - Only used with the option *weight*. If an edge does not have the attribute named as * defined in option *weight* this default. * </ul> * * * @return double */ public function getDiameter($graph, $options = array()) { if ($graph instanceof Graph) { $graph = $graph->getKey(); } $options['objectType'] = 'figure'; $data = array_merge($options, $this->getCursorOptions($options)); $statement = new Statement($this->getConnection(), array("query" => '')); $statement->setResultType($options['objectType']); $aql = "RETURN GRAPH_DIAMETER(@graphName, @options) "; if (isset($options['direction'])) { if ($options['direction'] === "in") { $options['direction'] = "inbound"; } if ($options['direction'] === "out") { $options['direction'] = "outbound"; } } $statement->bind('graphName', $graph); $statement->bind('options', $options); $statement->setQuery($aql); $a = $statement->execute()->getAll(); return $a[0]; }
/** * executeLogFindMany * * Voer een zoekacties op meerdere records uit in de log-tabellen. * @param Statement $stmt * @return KVDdom_DomainObjectLogCollection */ protected function executeLogFindMany($stmt) { $stmt->execute(); $domainObjects = array(); while ($row = $stmt->fetch(PDO::FETCH_OBJ)) { $logObject = $this->doLogLoad($row->id, $row); $domainObjects[] = $logObject; } return new KVDdom_DomainObjectLogCollection($domainObjects); }
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(); }
/** * Test getting correct Timeout Exception * * @expectedException \triagens\ArangoDb\ClientException */ public function testTimeoutException() { $query = 'RETURN SLEEP(13)'; $statement = new Statement($this->connection, array("query" => $query)); try { $statement->execute(); } catch (ClientException $exception) { $this->assertEquals($exception->getCode(), 408); throw $exception; } }
/** * Try to create and delete an edge with wrong encoding * We expect an exception here: * * @expectedException \triagens\ArangoDb\ClientException */ public function testCreateAndDeleteEdgeWithWrongEncoding() { $connection = $this->connection; $this->collection; $edgeCollection = $this->edgeCollection; $this->collectionHandler; $document1 = new Document(); $document2 = new Document(); $documentHandler = new DocumentHandler($connection); $edgeDocument = new Edge(); $edgeDocumentHandler = new EdgeHandler($connection); $document1->someAttribute = 'someValue1'; $document2->someAttribute = 'someValue2'; $documentHandler->add('ArangoDBPHPTestSuiteTestCollection01', $document1); $documentHandler->add('ArangoDBPHPTestSuiteTestCollection01', $document2); $documentHandle1 = $document1->getHandle(); $documentHandle2 = $document2->getHandle(); $isoValue = iconv("UTF-8", "ISO-8859-1//TRANSLIT", "knowsü"); $edgeDocument->set('label', $isoValue); $edgeDocumentId = $edgeDocumentHandler->saveEdge($edgeCollection->getId(), $documentHandle1, $documentHandle2, $edgeDocument); // $resultingDocument = $documentHandler->get($edgeCollection->getId(), $edgeDocumentId); $resultingEdge = $edgeDocumentHandler->get($edgeCollection->getId(), $edgeDocumentId); $resultingAttribute = $resultingEdge->label; $this->assertTrue($resultingAttribute === 'knows', 'Attribute set on the Edge is different from the one retrieved!'); $edgesQuery1Result = $edgeDocumentHandler->edges($edgeCollection->getId(), $documentHandle1, 'out'); $this->assertEquals(2, count($edgesQuery1Result)); $statement = new Statement($connection, array("query" => '', "count" => true, "batchSize" => 1000, "sanitize" => true)); $statement->setQuery('FOR p IN PATHS(ArangoDBPHPTestSuiteTestCollection01, ArangoDBPHPTestSuiteTestEdgeCollection01, "outbound") RETURN p'); $cursor = $statement->execute(); $result = $cursor->current(); $this->assertInstanceOf('triagens\\ArangoDb\\Document', $result, "IN PATHS statement did not return a document object!"); $resultingEdge->set('label', 'knows not'); $documentHandler->update($resultingEdge); $resultingEdge = $edgeDocumentHandler->get($edgeCollection->getId(), $edgeDocumentId); $resultingAttribute = $resultingEdge->label; $this->assertTrue($resultingAttribute === 'knows not', 'Attribute "knows not" set on the Edge is different from the one retrieved (' . $resultingAttribute . ')!'); $documentHandler->delete($document1); $documentHandler->delete($document2); // On ArangoDB 1.0 deleting a vertex doesn't delete the associated edge. Caution! $edgeDocumentHandler->delete($resultingEdge); }
/** * Test timeout, no exception */ public function testSetTimeout() { $connection = getConnection(); $connection->setOption(ConnectionOptions::OPTION_TIMEOUT, 5); $query = 'RETURN SLEEP(1)'; $statement = new Statement($connection, array("query" => $query)); // should work $cursor = $statement->execute(); $this->assertEquals(1, count($cursor->getAll())); }
/** * test for import of documents by giving an array of documents */ public function testImportFromStringUsingDocumentsUsingResultset() { if (isCluster($this->connection)) { // don't execute this test in a cluster return; } $collectionHandler = $this->collectionHandler; $data = '[{ "firstName" : "Joe", "lastName" : "Public", "age" : 42, "gender" : "male", "_key" : "test1"}, { "firstName" : "Jane", "lastName" : "Doe", "age" : 31, "gender" : "female", "_key" : "test2"}]'; $result = $collectionHandler->import('importCollection_01_arango_unittests', $data, $options = array('createCollection' => true, 'type' => 'array')); $this->assertTrue($result['error'] === false && $result['created'] == 2); $statement = new Statement($this->connection, array("query" => '', "count" => true, "batchSize" => 1000, "sanitize" => true)); $query = 'FOR u IN `importCollection_01_arango_unittests` SORT u._id ASC RETURN u'; $statement->setQuery($query); $cursor = $statement->execute(); $resultingDocument = null; foreach ($cursor as $key => $value) { $resultingDocument[$key] = $value; } $this->assertTrue($resultingDocument[0]->getKey() == 'test1' && $resultingDocument[0]->firstName == 'Joe', 'Document returned did not contain expected data.'); $this->assertTrue($resultingDocument[1]->getKey() == 'test2' && $resultingDocument[1]->firstName == 'Jane', 'Document returned did not contain expected data.'); $this->assertTrue(count($resultingDocument) == 2, 'Should be 2, was: ' . count($resultingDocument)); }
<?php namespace triagens\ArangoDb; require dirname(__FILE__) . DIRECTORY_SEPARATOR . 'init.php'; /* set up some example statements */ $statements = array("for u in users return u" => array(), "for u in users return u" => null, "for u in users filter u.id == @id return u" => array("id" => 6), "for u in users filter u.id == @id && u.name != @name return u" => array("id" => 1, "name" => "fox")); try { $connection = new Connection($connectionOptions); foreach ($statements as $query => $bindVars) { $statement = new Statement($connection, array("query" => $query, "count" => true, "batchSize" => 1000, "bindVars" => $bindVars, "sanitize" => true)); print $statement . "\n\n"; $cursor = $statement->execute(); var_dump($cursor->getAll()); } } catch (ConnectException $e) { print $e . PHP_EOL; } catch (ServerException $e) { print $e . PHP_EOL; } catch (ClientException $e) { print $e . PHP_EOL; }
/** * Execute statement and returns first row of results as an associative array. * * @param Statement $SQL * * @return mixed|void */ public function selectRow(Statement $SQL) { try { // Execute the statement $sth = $SQL->execute($this->PDO); // Return the first row fetched return $sth->fetch(\PDO::FETCH_ASSOC); } catch (\Exception $ex) { // Execution failed return $this->dbFail($ex->getMessage()); } }
function execute() { $platform = $this->getPlatform(); return $platform->change($this->Parameters['Name']) . parent::execute(); }
public function query($sql, $params = []) { $statement = new Statement($this->mysqli, $sql, $params); $statement->execute(); return $statement; }