Skip to content

Commit

Permalink
Fix: correctly handle agg subexpressions with no selections (#2390)
Browse files Browse the repository at this point in the history
  • Loading branch information
ginter authored Oct 9, 2023
1 parent cca58dd commit e08c1c0
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 2 deletions.
10 changes: 8 additions & 2 deletions sqlglot/optimizer/pushdown_projections.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,9 @@
SELECT_ALL = object()

# Selection to use if selection list is empty
DEFAULT_SELECTION = lambda: alias("1", "_")
DEFAULT_SELECTION = lambda is_agg: alias(
exp.Max(this=exp.Literal.number(1)) if is_agg else "1", "_"
)


def pushdown_projections(expression, schema=None, remove_unused_selections=True):
Expand Down Expand Up @@ -98,6 +100,7 @@ def _remove_unused_selections(scope, parent_selections, schema, alias_count):
new_selections = []
removed = False
star = False
is_agg = False

select_all = SELECT_ALL in parent_selections

Expand All @@ -112,6 +115,9 @@ def _remove_unused_selections(scope, parent_selections, schema, alias_count):
star = True
removed = True

if not is_agg and selection.find(exp.AggFunc):
is_agg = True

if star:
resolver = Resolver(scope, schema)
names = {s.alias_or_name for s in new_selections}
Expand All @@ -124,7 +130,7 @@ def _remove_unused_selections(scope, parent_selections, schema, alias_count):

# If there are no remaining selections, just select a single constant
if not new_selections:
new_selections.append(DEFAULT_SELECTION())
new_selections.append(DEFAULT_SELECTION(is_agg))

scope.expression.select(*new_selections, append=False, copy=False)

Expand Down
9 changes: 9 additions & 0 deletions tests/fixtures/optimizer/pushdown_projections.sql
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,15 @@ WITH cte AS (SELECT 1 AS x, 3 AS z) SELECT cte.a AS a, cte.z AS z FROM cte AS ct
WITH cte(x, y, z) AS (SELECT 1, 2, 3) SELECT a, z FROM (SELECT * FROM cte AS cte(b)) AS cte(a);
WITH cte AS (SELECT 1 AS x, 3 AS z) SELECT cte.a AS a, cte.z AS z FROM (SELECT cte.b AS a, cte.z AS z FROM cte AS cte(b)) AS cte;

WITH y AS (SELECT a FROM x) SELECT 1 FROM y;
WITH y AS (SELECT 1 AS _ FROM x AS x) SELECT 1 AS "1" FROM y;

WITH y AS (SELECT SUM(a) FROM x) SELECT 1 FROM y;
WITH y AS (SELECT MAX(1) AS _ FROM x AS x) SELECT 1 AS "1" FROM y;

WITH y AS (SELECT a FROM x GROUP BY a) SELECT 1 FROM y;
WITH y AS (SELECT 1 AS _ FROM x AS x GROUP BY x.a) SELECT 1 AS "1" FROM y;

--------------------------------------
-- Unknown Star Expansion
--------------------------------------
Expand Down

0 comments on commit e08c1c0

Please sign in to comment.