Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 33 additions & 6 deletions src/Builder.php
Original file line number Diff line number Diff line change
Expand Up @@ -818,12 +818,7 @@ private function buildHavingClause(ParsedQuery $grouped): string
foreach ($grouped->having as $havingQuery) {
foreach ($havingQuery->getValues() as $subQuery) {
/** @var Query $subQuery */
$attr = $subQuery->getAttribute();
if (isset($aliasToExpr[$attr])) {
$havingClauses[] = $this->compileHavingCondition($subQuery, $aliasToExpr[$attr]);
} else {
$havingClauses[] = $this->compileFilter($subQuery);
}
$havingClauses[] = $this->compileHavingQuery($subQuery, $aliasToExpr);
}
}
}
Expand All @@ -840,6 +835,38 @@ private function buildHavingClause(ParsedQuery $grouped): string
return 'HAVING ' . \implode(' AND ', $havingClauses);
}

/**
* @param array<string, string> $aliasToExpr
*/
private function compileHavingQuery(Query $query, array $aliasToExpr): string
{
$operator = match ($query->getMethod()) {
Method::And => 'AND',
Method::Or => 'OR',
default => null,
};

if ($operator === null) {
$attr = $query->getAttribute();

return isset($aliasToExpr[$attr])
? $this->compileHavingCondition($query, $aliasToExpr[$attr])
: $this->compileFilter($query);
}

$parts = [];
foreach ($query->getValues() as $subQuery) {
/** @var Query $subQuery */
$parts[] = $this->compileHavingQuery($subQuery, $aliasToExpr);
}

if ($parts === []) {
return $operator === 'OR' ? '1 = 0' : '1 = 1';
}

return '(' . \implode(' ' . $operator . ' ', $parts) . ')';
}

/**
* Build a map of aggregation alias -> compiled aggregate expression so
* HAVING can refer to aliases portably across dialects that don't allow
Expand Down
2 changes: 1 addition & 1 deletion tests/Builder/ClickHouseTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -5098,7 +5098,7 @@ public function testHavingWithOrLogic(): void
])])
->build();
$this->assertBindingCount($result);
$this->assertSame('SELECT COUNT(*) AS `total` FROM `t` GROUP BY `status` HAVING (`total` > ? OR `total` < ?)', $result->query);
$this->assertSame('SELECT COUNT(*) AS `total` FROM `t` GROUP BY `status` HAVING (COUNT(*) > ? OR COUNT(*) < ?)', $result->query);
}

public function testResetClearsClickHouseProperties(): void
Expand Down
4 changes: 2 additions & 2 deletions tests/Builder/MySQLTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1404,7 +1404,7 @@ public function testHavingWithLogicalOr(): void
->build();
$this->assertBindingCount($result);

$this->assertSame('SELECT COUNT(*) AS `total` FROM `t` GROUP BY `status` HAVING (`total` > ? OR `total` < ?)', $result->query);
$this->assertSame('SELECT COUNT(*) AS `total` FROM `t` GROUP BY `status` HAVING (COUNT(*) > ? OR COUNT(*) < ?)', $result->query);
$this->assertSame([10, 2], $result->bindings);
}

Expand Down Expand Up @@ -13955,7 +13955,7 @@ public function testHavingWithMultipleConditionsAndLogicalOr(): void
->build();
$this->assertBindingCount($result);

$this->assertSame('SELECT COUNT(*) AS `cnt`, SUM(`amount`) AS `total` FROM `t` GROUP BY `category` HAVING COUNT(*) > ? AND (`total` > ? OR `total` < ?)', $result->query);
$this->assertSame('SELECT COUNT(*) AS `cnt`, SUM(`amount`) AS `total` FROM `t` GROUP BY `category` HAVING COUNT(*) > ? AND (SUM(`amount`) > ? OR SUM(`amount`) < ?)', $result->query);
$this->assertSame([5, 10000, 100], $result->bindings);
}

Expand Down
36 changes: 36 additions & 0 deletions tests/Builder/PostgreSQLTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -6534,4 +6534,40 @@ public function testNextValRejectsInvalidName(): void

new Builder()->nextVal('bad name; DROP TABLE x');
}

public function testHavingResolvesAliasesInsideLogicalQueries(): void
{
$result = (new Builder())
->from('orders')
->count('*', 'cnt')
->sum('amount', 'total')
->groupBy(['status'])
->having([
Query::or([
Query::greaterThan('cnt', 1),
Query::and([
Query::equal('status', ['refunded']),
Query::lessThan('total', 100),
]),
]),
])
->build();
$this->assertBindingCount($result);

$this->assertSame('SELECT COUNT(*) AS "cnt", SUM("amount") AS "total" FROM "orders" GROUP BY "status" HAVING (COUNT(*) > ? OR ("status" IN (?) AND SUM("amount") < ?))', $result->query);
$this->assertSame([1, 'refunded', 100], $result->bindings);
}

public function testHavingWithEmptyLogicalQueries(): void
{
$result = (new Builder())
->from('t')
->count('*', 'cnt')
->groupBy(['status'])
->having([Query::or([]), Query::and([])])
->build();
$this->assertBindingCount($result);

$this->assertSame('SELECT COUNT(*) AS "cnt" FROM "t" GROUP BY "status" HAVING 1 = 0 AND 1 = 1', $result->query);
}
}