Skip to content

fix: preserve aggregate scope when unparsing - #23327

Merged
alamb merged 3 commits into
apache:mainfrom
Phoenix500526:fix/23317
Jul 16, 2026
Merged

fix: preserve aggregate scope when unparsing#23327
alamb merged 3 commits into
apache:mainfrom
Phoenix500526:fix/23317

Conversation

@Phoenix500526

Copy link
Copy Markdown
Contributor

Which issue does this PR close?

Rationale for this change

The unparser can fold a Projection into its Aggregate and then keep walking into the Aggregate input. When that input is another Aggregate or an unnamed derived Projection, the generated SQL moved references above the SELECT block that defined them. Optimizer aliases such as group_alias_0 and base-table qualifiers such as c.signup_date were no longer in scope.

Stop crossing those scope boundaries blindly. Render nested aggregate inputs as derived relations, and when an aggregate reads from a derived Projection, rewrite only input-schema columns to the derived output names before rendering SELECT and GROUP BY expressions.

What changes are included in this PR?

Are these changes tested?

Yes

Are there any user-facing changes?

No

@Phoenix500526
Phoenix500526 marked this pull request as draft July 5, 2026 13:30
@github-actions github-actions Bot added sql SQL Planner core Core DataFusion crate labels Jul 5, 2026
@Phoenix500526
Phoenix500526 marked this pull request as ready for review July 5, 2026 14:59

@kosiew kosiew left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Phoenix500526
Thanks for the fix here.
I think there is one remaining correctness gap around aggregate expression normalization in HAVING.
I also left one test suggestion that would make this regression coverage a bit stronger.

} else if let Some(agg) = agg {
let unprojected =
unproject_agg_exprs(filter.predicate.clone(), agg, None)?;
let filter_expr = self.expr_to_sql(&unprojected)?;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice work applying the new aggregate input normalization to SELECT and GROUP BY.

I think the same path is needed for HAVING predicates that come from a Filter over an Aggregate.

For the same plan shape being fixed here, where Aggregate reads from an unnamed derived Projection, a query like ... GROUP BY 1 HAVING count(DISTINCT cs.customer_id) > 0 still unparses to HAVING (count(DISTINCT \"cs\".\"customer_id\") > 0). The FROM item is (SELECT \"cs\".\"customer_id\", ... FROM ...), so the cs qualifier is no longer in scope.

Could we apply the same normalize_agg_input_columns path after unproject_agg_exprs here, and also in the QUALIFY branch when it unprojects aggregate expressions? That should make all expressions rendered in the aggregate SELECT resolve against the derived projection output.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in commit b56a339

FROM
"warehouse"."main"."sales" cs
JOIN "warehouse"."main"."customers" c USING (customer_id)
GROUP BY

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Small suggestion for the regression coverage: it would be great if the issue_23317 tests executed, or at least parsed, the unparsed SQL rather than only checking string fragments.

The bug here is invalid SQL caused by out-of-scope aliases, so a parse or roundtrip execution assertion would be more likely to catch similar missed clauses like HAVING or ORDER BY even if the exact formatting changes later.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch. The sql has already parsed in assert_issue_23317_unparsed_sql_plans now.

The unparser can fold a Projection into its Aggregate and then keep
walking into the Aggregate input. When that input is another Aggregate
or an unnamed derived Projection, the generated SQL moved references
above the SELECT block that defined them. Optimizer aliases such as
`group_alias_0` and base-table qualifiers such as `c.signup_date`
were no longer in scope.

Stop crossing those scope boundaries blindly. Render nested aggregate
inputs as derived relations, and when an aggregate reads from a derived
Projection, rewrite only input-schema columns to the derived output
names before rendering SELECT and GROUP BY expressions.

CLOSES apache#23317
Signed-off-by: Jiawei Zhao <Phoenix500526@163.com>
HAVING and QUALIFY predicates can reference aggregate inputs after
unprojection. Normalize those inputs when the aggregate reads from a
derived projection so unparsed SQL does not leak inner aliases.

Refs apache#23317

@kosiew kosiew left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Phoenix500526

Thanks for the iteration.

Looks 👍 to me

@alamb
alamb enabled auto-merge July 16, 2026 18:36
@alamb

alamb commented Jul 16, 2026

Copy link
Copy Markdown
Contributor

I took a quick look and it looks reasonable to me -- than k you @Phoenix500526 and @kosiew

@codecov-commenter

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 94.44444% with 4 lines in your changes missing coverage. Please review.
⚠️ Please upload report for BASE (main@95de385). Learn more about missing BASE report.

Files with missing lines Patch % Lines
datafusion/sql/src/unparser/plan.rs 94.44% 4 Missing ⚠️
Additional details and impacted files
@@           Coverage Diff           @@
##             main   #23327   +/-   ##
=======================================
  Coverage        ?   80.65%           
=======================================
  Files           ?     1086           
  Lines           ?   366165           
  Branches        ?   366165           
=======================================
  Hits            ?   295334           
  Misses          ?    53238           
  Partials        ?    17593           

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@alamb
alamb added this pull request to the merge queue Jul 16, 2026
Merged via the queue into apache:main with commit a29f70c Jul 16, 2026
40 checks passed
@Phoenix500526
Phoenix500526 deleted the fix/23317 branch July 17, 2026 10:00
Omega359 pushed a commit to Omega359/arrow-datafusion that referenced this pull request Jul 18, 2026
## Which issue does this PR close?

<!--
We generally require a GitHub issue to be filed for all bug fixes and
enhancements and this helps us generate change logs for our releases.
You can link an issue to this PR using the GitHub syntax. For example
`Closes apache#123` indicates that this PR will close issue apache#123.
-->

- Closes apache#23317.

## Rationale for this change

<!--
Why are you proposing this change? If this is already explained clearly
in the issue then this section is not needed.
Explaining clearly why changes are proposed helps reviewers understand
your changes and offer better suggestions for fixes.
-->


The unparser can fold a Projection into its Aggregate and then keep
walking into the Aggregate input. When that input is another Aggregate
or an unnamed derived Projection, the generated SQL moved references
above the SELECT block that defined them. Optimizer aliases such as
`group_alias_0` and base-table qualifiers such as `c.signup_date` were
no longer in scope.

Stop crossing those scope boundaries blindly. Render nested aggregate
inputs as derived relations, and when an aggregate reads from a derived
Projection, rewrite only input-schema columns to the derived output
names before rendering SELECT and GROUP BY expressions.
## What changes are included in this PR?

<!--
There is no need to duplicate the description in the issue here but it
is sometimes worth providing a summary of the individual changes in this
PR.
-->

## Are these changes tested?

<!--
We typically require tests for all PRs in order to:
1. Prevent the code from being accidentally broken by subsequent changes
2. Serve as another way to document the expected behavior of the code

If tests are not included in your PR, please explain why (for example,
are they covered by existing tests)?
-->

Yes

## Are there any user-facing changes?

<!--
If there are user-facing changes then we may require documentation to be
updated before approving the PR.
-->

<!--
If there are any breaking changes to public APIs, please add the `api
change` label.
-->

No

---------

Signed-off-by: Jiawei Zhao <Phoenix500526@163.com>
Co-authored-by: Andrew Lamb <andrew@nerdnetworks.org>
kosiew pushed a commit to kosiew/datafusion that referenced this pull request Aug 12, 2026
## Which issue does this PR close?

<!--
We generally require a GitHub issue to be filed for all bug fixes and
enhancements and this helps us generate change logs for our releases.
You can link an issue to this PR using the GitHub syntax. For example
`Closes apache#123` indicates that this PR will close issue apache#123.
-->

- Closes apache#23317.

## Rationale for this change

<!--
Why are you proposing this change? If this is already explained clearly
in the issue then this section is not needed.
Explaining clearly why changes are proposed helps reviewers understand
your changes and offer better suggestions for fixes.
-->


The unparser can fold a Projection into its Aggregate and then keep
walking into the Aggregate input. When that input is another Aggregate
or an unnamed derived Projection, the generated SQL moved references
above the SELECT block that defined them. Optimizer aliases such as
`group_alias_0` and base-table qualifiers such as `c.signup_date` were
no longer in scope.

Stop crossing those scope boundaries blindly. Render nested aggregate
inputs as derived relations, and when an aggregate reads from a derived
Projection, rewrite only input-schema columns to the derived output
names before rendering SELECT and GROUP BY expressions.
## What changes are included in this PR?

<!--
There is no need to duplicate the description in the issue here but it
is sometimes worth providing a summary of the individual changes in this
PR.
-->

## Are these changes tested?

<!--
We typically require tests for all PRs in order to:
1. Prevent the code from being accidentally broken by subsequent changes
2. Serve as another way to document the expected behavior of the code

If tests are not included in your PR, please explain why (for example,
are they covered by existing tests)?
-->

Yes

## Are there any user-facing changes?

<!--
If there are user-facing changes then we may require documentation to be
updated before approving the PR.
-->

<!--
If there are any breaking changes to public APIs, please add the `api
change` label.
-->

No

---------

Signed-off-by: Jiawei Zhao <Phoenix500526@163.com>
Co-authored-by: Andrew Lamb <andrew@nerdnetworks.org>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

core Core DataFusion crate sql SQL Planner

Projects

None yet

Development

Successfully merging this pull request may close these issues.

SQL Unparser generates incorrect column references

4 participants