From f5b1eccb6875d1c4dee56ea2f0f697ac165f6fa9 Mon Sep 17 00:00:00 2001 From: Jake Barnby Date: Tue, 1 Dec 2026 14:09:01 +1300 Subject: [PATCH] fix(builder): resolve aggregate aliases inside having logical groups Conditions nested in and()/or() compiled with the bare alias, which Postgres and ClickHouse reject in HAVING. Aliases now resolve to the aggregate expression at any depth. Co-Authored-By: Claude Opus 5.5 --- src/Builder.php | 39 +++++++++++++++++++++++++++----- tests/Builder/ClickHouseTest.php | 2 +- tests/Builder/MySQLTest.php | 4 ++-- tests/Builder/PostgreSQLTest.php | 36 +++++++++++++++++++++++++++++ 4 files changed, 72 insertions(+), 9 deletions(-) diff --git a/src/Builder.php b/src/Builder.php index c5c75f9..48c54e1 100644 --- a/src/Builder.php +++ b/src/Builder.php @@ -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); } } } @@ -840,6 +835,38 @@ private function buildHavingClause(ParsedQuery $grouped): string return 'HAVING ' . \implode(' AND ', $havingClauses); } + /** + * @param array $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 diff --git a/tests/Builder/ClickHouseTest.php b/tests/Builder/ClickHouseTest.php index 28a860e..dfe8704 100644 --- a/tests/Builder/ClickHouseTest.php +++ b/tests/Builder/ClickHouseTest.php @@ -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 diff --git a/tests/Builder/MySQLTest.php b/tests/Builder/MySQLTest.php index e2f61b1..fc9df52 100644 --- a/tests/Builder/MySQLTest.php +++ b/tests/Builder/MySQLTest.php @@ -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); } @@ -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); } diff --git a/tests/Builder/PostgreSQLTest.php b/tests/Builder/PostgreSQLTest.php index e47b2b2..56a4cf7 100644 --- a/tests/Builder/PostgreSQLTest.php +++ b/tests/Builder/PostgreSQLTest.php @@ -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); + } }