Skip to content

Commit 1a557bf

Browse files
committed
feat: distinct param for count
1 parent fc01613 commit 1a557bf

File tree

3 files changed

+37
-4
lines changed

3 files changed

+37
-4
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -202,7 +202,7 @@ use Tpetry\QueryExpressions\Function\Aggregate\{
202202
use Tpetry\QueryExpressions\Operator\Value\Value;
203203

204204
new Avg(string|Expression $value);
205-
new Count(string|Expression $value);
205+
new Count(string|Expression $value, bool $distinct = false);
206206
new CountFilter(string|Expression $filter);
207207
new Max(string|Expression $value);
208208
new Min(string|Expression $value);

src/Function/Aggregate/Count.php

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,27 @@
44

55
namespace Tpetry\QueryExpressions\Function\Aggregate;
66

7-
class Count extends AggregateExpression
7+
use Illuminate\Contracts\Database\Query\Expression;
8+
use Illuminate\Database\Grammar;
9+
use Tpetry\QueryExpressions\Concerns\StringizeExpression;
10+
11+
class Count implements Expression
812
{
9-
protected function aggregate(): string
13+
use StringizeExpression;
14+
15+
public function __construct(
16+
private readonly string|Expression $value,
17+
private readonly bool $distinct = false,
18+
) {
19+
}
20+
21+
public function getValue(Grammar $grammar): string
1022
{
11-
return 'count';
23+
$value = $this->stringize($grammar, $this->value);
24+
25+
return match ($this->distinct) {
26+
true => "count(distinct {$value})",
27+
false => "count({$value})",
28+
};
1229
}
1330
}

tests/Function/Aggregate/CountTest.php

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,10 +13,26 @@
1313
->toBeSqlite('count("val")')
1414
->toBeSqlsrv('count([val])');
1515

16+
it('can aggregate a column by COUNT with DISTINCT')
17+
->expect(new Count('val', true))
18+
->toBeExecutable(['val int'])
19+
->toBeMysql('count(distinct `val`)')
20+
->toBePgsql('count(distinct "val")')
21+
->toBeSqlite('count(distinct "val")')
22+
->toBeSqlsrv('count(distinct [val])');
23+
1624
it('can aggregate an expression by COUNT')
1725
->expect(new Count(new Expression(1)))
1826
->toBeExecutable()
1927
->toBeMysql('count(1)')
2028
->toBePgsql('count(1)')
2129
->toBeSqlite('count(1)')
2230
->toBeSqlsrv('count(1)');
31+
32+
it('can aggregate an expression by COUNT with DISTINCT')
33+
->expect(new Count(new Expression(1), true))
34+
->toBeExecutable()
35+
->toBeMysql('count(distinct 1)')
36+
->toBePgsql('count(distinct 1)')
37+
->toBeSqlite('count(distinct 1)')
38+
->toBeSqlsrv('count(distinct 1)');

0 commit comments

Comments
 (0)