naman-modi opened a new pull request, #23789:
URL: https://github.com/apache/datafusion/pull/23789
## Which issue does this PR close?
- Closes #23668.
## Rationale for this change
- When printing a GROUP BY query, the unparser sometimes wraps the
aggregate's input in an inner subquery (`... FROM (SELECT ...)`).
- Table aliases like `cs` only exist inside that subquery. Any clause
outside it (SELECT, GROUP BY, HAVING, QUALIFY, ORDER BY) must use the
subquery's output columns, not the aliases, so the unparser drops the alias.
- Each clause does that dropping on its own, so it is easy to miss one.
- ORDER BY on an aggregate that is not in the SELECT list was missed: it
printed `ORDER BY round(sum("cs"."total_revenue"), 2)`, while the SELECT list
in the same query correctly printed `sum("total_revenue")`.
- DataFusion reads that SQL back fine, but stricter databases reject it
because `cs` is out of scope there.
## What changes are included in this PR?
I moved the rule into one helper, `UnparserAggScope`, that checks once per
aggregate whether the input is an inner subquery and then prepares expressions
for each clause. SELECT, GROUP BY, HAVING, QUALIFY, and both ORDER BY paths now
go through it, which fixes the ORDER BY case. The window-over-aggregate path is
left as-is with a comment: it is only reachable from hand-built plans, since a
window in SQL always sits inside a SELECT that already drops the alias. Only
ORDER BY output changes; every already-correct case stays the same.
## Are these changes tested?
Yes. New tests in `datafusion/core/tests/sql/unparser.rs` cover the
inner-subquery shape for a window sorting by an aggregate, ORDER BY on an
unselected aggregate (the fixed case), and a top-level ORDER BY (the second
sort path). Existing unparser tests and the TPC-H/Clickbench roundtrips still
pass.
## Are there any user-facing changes?
ORDER BY over an aggregate is now printed without an out-of-scope table
qualifier, so the generated SQL is valid for stricter databases. No API changes.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]