From dd7468e9da33b7ce8f6eb52cdbc3c20c5bafa352 Mon Sep 17 00:00:00 2001 From: Andreas Heigl Date: Tue, 24 Mar 2020 19:31:57 +0100 Subject: [PATCH] Implement countDocs from DocumentStore interface This implements the countDoc feature from the DocumentStore interface so it can be used together with the latest version of the DocumentStore. This allows top retrieve the number of affected documents without having to actually retrieve all the documents. --- src/PostgresDocumentStore.php | 23 +++++++++++++++++++++++ tests/PostgresDocumentStoreTest.php | 26 ++++++++++++++++++++++++++ 2 files changed, 49 insertions(+) diff --git a/src/PostgresDocumentStore.php b/src/PostgresDocumentStore.php index d242afa..ba9fb81 100644 --- a/src/PostgresDocumentStore.php +++ b/src/PostgresDocumentStore.php @@ -524,6 +524,29 @@ public function filterDocs(string $collectionName, Filter $filter, int $skip = n } } + /** + * @param string $collectionName + * @param Filter $filter + * @return int number of docs + */ + public function countDocs(string $collectionName, Filter $filter): int + { + [$filterStr, $args] = $this->filterToWhereClause($filter); + + $where = $filterStr? "WHERE $filterStr" : ''; + + $query = <<schemaName($collectionName)}.{$this->tableName($collectionName)} +$where; +EOT; + $stmt = $this->connection->prepare($query); + + $stmt->execute($args); + + return (int) $stmt->fetchColumn(0); + } + private function transactional(callable $callback) { if($this->manageTransactions) { diff --git a/tests/PostgresDocumentStoreTest.php b/tests/PostgresDocumentStoreTest.php index a5dcf9c..e76c6b4 100644 --- a/tests/PostgresDocumentStoreTest.php +++ b/tests/PostgresDocumentStoreTest.php @@ -434,6 +434,32 @@ public function it_handles_not_filter_nested_in_and_filter() $this->assertEquals([$thirdDocId], $refs); } + /** + * @test + */ + public function it_counts_any_of_filter() + { + $collectionName = 'test_any_of_filter'; + $this->documentStore->addCollection($collectionName); + + $doc1 = ["foo" => "bar"]; + $doc2 = ["foo" => "baz"]; + $doc3 = ["foo" => "bat"]; + + $docs = [$doc1, $doc2, $doc3]; + + array_walk($docs, function (array $doc) use ($collectionName) { + $this->documentStore->addDoc($collectionName, Uuid::uuid4()->toString(), $doc); + }); + + $count = $this->documentStore->countDocs( + $collectionName, + new AnyOfFilter("foo", ["bar", "bat"]) + ); + + $this->assertSame(2, $count); + } + private function getIndexes(string $collectionName): array { return TestUtil::getIndexes($this->connection, self::TABLE_PREFIX.$collectionName);