Skip to content

Commit 7f6bc87

Browse files
authored
Merge pull request #873 from utopia-php/optimize-sum-count-methods
Optimize sum count method with no limit
2 parents 609ebcd + 5bc3e26 commit 7f6bc87

2 files changed

Lines changed: 46 additions & 29 deletions

File tree

composer.lock

Lines changed: 27 additions & 27 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/Database/Adapter/SQL.php

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3331,14 +3331,22 @@ public function count(Document $collection, array $queries = [], ?int $max = nul
33313331
? 'WHERE ' . \implode(' AND ', $where)
33323332
: '';
33333333

3334-
$sql = "
3334+
if (empty($limit)) {
3335+
$sql = "
3336+
SELECT COUNT(1) as sum
3337+
FROM {$this->getSQLTable($name)} AS {$this->quote($alias)}
3338+
{$sqlWhere}
3339+
";
3340+
} else {
3341+
$sql = "
33353342
SELECT COUNT(1) as sum FROM (
33363343
SELECT 1
33373344
FROM {$this->getSQLTable($name)} AS {$this->quote($alias)}
33383345
{$sqlWhere}
33393346
{$limit}
33403347
) table_count
33413348
";
3349+
}
33423350

33433351
$sql = $this->trigger(Database::EVENT_DOCUMENT_COUNT, $sql);
33443352

@@ -3417,14 +3425,23 @@ public function sum(Document $collection, string $attribute, array $queries = []
34173425
? 'WHERE ' . \implode(' AND ', $where)
34183426
: '';
34193427

3420-
$sql = "
3428+
if (empty($limit)) {
3429+
$sql = "
3430+
SELECT SUM({$this->quote($attribute)}) as sum
3431+
FROM {$this->getSQLTable($name)} AS {$this->quote($alias)}
3432+
{$sqlWhere}
3433+
";
3434+
} else {
3435+
$sql = "
34213436
SELECT SUM({$this->quote($attribute)}) as sum FROM (
34223437
SELECT {$this->quote($attribute)}
34233438
FROM {$this->getSQLTable($name)} AS {$this->quote($alias)}
34243439
{$sqlWhere}
34253440
{$limit}
34263441
) table_count
34273442
";
3443+
}
3444+
34283445

34293446
$sql = $this->trigger(Database::EVENT_DOCUMENT_SUM, $sql);
34303447

0 commit comments

Comments
 (0)