Skip to content

Commit ebf2dfa

Browse files
author
Alexander Miertsch
authored
Merge pull request #9 from heiglandreas/implementCountDocs
Implement countDocs from DocumentStore interface
2 parents e74bfe4 + dd7468e commit ebf2dfa

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

src/PostgresDocumentStore.php

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -524,6 +524,29 @@ public function filterDocs(string $collectionName, Filter $filter, int $skip = n
524524
}
525525
}
526526

527+
/**
528+
* @param string $collectionName
529+
* @param Filter $filter
530+
* @return int number of docs
531+
*/
532+
public function countDocs(string $collectionName, Filter $filter): int
533+
{
534+
[$filterStr, $args] = $this->filterToWhereClause($filter);
535+
536+
$where = $filterStr? "WHERE $filterStr" : '';
537+
538+
$query = <<<EOT
539+
SELECT count(doc)
540+
FROM {$this->schemaName($collectionName)}.{$this->tableName($collectionName)}
541+
$where;
542+
EOT;
543+
$stmt = $this->connection->prepare($query);
544+
545+
$stmt->execute($args);
546+
547+
return (int) $stmt->fetchColumn(0);
548+
}
549+
527550
private function transactional(callable $callback)
528551
{
529552
if($this->manageTransactions) {

tests/PostgresDocumentStoreTest.php

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -434,6 +434,32 @@ public function it_handles_not_filter_nested_in_and_filter()
434434
$this->assertEquals([$thirdDocId], $refs);
435435
}
436436

437+
/**
438+
* @test
439+
*/
440+
public function it_counts_any_of_filter()
441+
{
442+
$collectionName = 'test_any_of_filter';
443+
$this->documentStore->addCollection($collectionName);
444+
445+
$doc1 = ["foo" => "bar"];
446+
$doc2 = ["foo" => "baz"];
447+
$doc3 = ["foo" => "bat"];
448+
449+
$docs = [$doc1, $doc2, $doc3];
450+
451+
array_walk($docs, function (array $doc) use ($collectionName) {
452+
$this->documentStore->addDoc($collectionName, Uuid::uuid4()->toString(), $doc);
453+
});
454+
455+
$count = $this->documentStore->countDocs(
456+
$collectionName,
457+
new AnyOfFilter("foo", ["bar", "bat"])
458+
);
459+
460+
$this->assertSame(2, $count);
461+
}
462+
437463
private function getIndexes(string $collectionName): array
438464
{
439465
return TestUtil::getIndexes($this->connection, self::TABLE_PREFIX.$collectionName);

0 commit comments

Comments
 (0)