Commit 0d223f9
fix: preserve subquery structure when unparsing SubqueryAlias over Aggregate
When the SQL unparser encountered a SubqueryAlias node whose direct
child was an Aggregate (or other clause-building plan like Window, Sort,
Limit, Union), it would flatten the subquery into a simple table alias,
losing the aggregate entirely.
For example, a plan representing:
SELECT j1.col FROM j1 JOIN (SELECT max(id) AS m FROM j2) AS b ON j1.id = b.m
would unparse to:
SELECT j1.col FROM j1 INNER JOIN j2 AS b ON j1.id = b.m
dropping the MAX aggregate and the subquery.
Root cause: the SubqueryAlias handler in select_to_sql_recursively would
call subquery_alias_inner_query_and_columns (which only unwraps
Projection children) and unparse_table_scan_pushdown (which only handles
TableScan/SubqueryAlias/Projection). When both returned nothing useful
for an Aggregate child, the code recursed directly into the Aggregate,
merging its GROUP BY into the outer SELECT instead of wrapping it in a
derived subquery.
The fix adds an early check: if the SubqueryAlias's direct child is a
plan type that builds its own SELECT clauses (Aggregate, Window, Sort,
Limit, Union), emit it as a derived subquery via self.derive() with the
alias always attached, rather than falling through to the recursive
path that would flatten it.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>1 parent 2f8f667 commit 0d223f9
2 files changed
Lines changed: 5 additions & 2 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1085 | 1085 | | |
1086 | 1086 | | |
1087 | 1087 | | |
1088 | | - | |
| 1088 | + | |
1089 | 1089 | | |
1090 | 1090 | | |
1091 | 1091 | | |
| |||
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
2916 | 2916 | | |
2917 | 2917 | | |
2918 | 2918 | | |
2919 | | - | |
| 2919 | + | |
| 2920 | + | |
| 2921 | + | |
| 2922 | + | |
2920 | 2923 | | |
2921 | 2924 | | |
2922 | 2925 | | |
| |||
0 commit comments