Skip to content

fix(expr): preserve unique right-branch aliases in set operations - #27936

Open
warrenzhu25 wants to merge 1 commit into
apache:mainfrom
warrenzhu25:fix-set-expr-right-branch-aliases
Open

warrenzhu25 wants to merge 1 commit into
apache:mainfrom
warrenzhu25:fix-set-expr-right-branch-aliases

Conversation

@warrenzhu25

Copy link
Copy Markdown

Which issue does this PR close?

Rationale for this change

#27473 updated project_with_validation to unconditionally rename every Expr::Alias in the right branch of a set operation to the corresponding field name from the left branch's schema. Because select_to_plan runs self.project(...) before resolving GROUP BY, HAVING, QUALIFY, and DISTINCT ON, renaming unique user aliases caused those clauses to either fail with No field named ... or silently resolve to the wrong expression when alias names were swapped between branches.

What changes are included in this PR?

  • In project_with_validation (datafusion/expr/src/logical_plan/builder.rs), count output names before renaming and preserve unique Expr::Alias names so downstream clauses in the right branch can still resolve them.
  • Rename only colliding aliases (e.g. 1 AS x, 2 AS x or count(*), count(*)) and non-Column/non-Alias expressions, tracking reserved names so renaming never introduces a secondary collision with a preserved user alias or column.
  • Add SQL logic tests in datafusion/sqllogictest/test_files/union.slt covering UNION ALL/UNION/INTERSECT/EXCEPT with GROUP BY, swapped-alias HAVING, QUALIFY, DISTINCT ON, and collision edge cases.

Are these changes tested?

  • cargo test --test sqllogictests -- union
  • cargo test -p datafusion-sql --test sql_integration union (10/10 passed, existing snapshots unchanged)
  • cargo test -p datafusion-expr --lib logical_plan::builder (30/30 passed)
  • cargo fmt --all and cargo clippy -p datafusion-expr -p datafusion-sql --all-targets -- -D warnings

Are there any user-facing changes?

Fixes a regression on main (unreleased) so right branches of set operations can again reference their own SELECT aliases in GROUP BY, HAVING, QUALIFY, and DISTINCT ON. No public API changes.

Note: Developed with AI assistance; all changes and tests were reviewed and verified by me.

@github-actions github-actions Bot added logical-expr Logical plan and expressions sqllogictest SQL Logic Tests (.slt) labels Dec 2, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

logical-expr Logical plan and expressions sqllogictest SQL Logic Tests (.slt)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Regression: right branch of a set operation cannot use its own aliases in GROUP BY / HAVING (error or wrong results)

1 participant