You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@datafusion.apache.org by "blinding-pixels (via GitHub)" <gi...@apache.org> on 2026/08/31 02:56:30 UTC
[PR] fix: avoid invalid qualifiers in unparsed subqueries [datafusion]
blinding-pixels opened a new pull request, #24808:
URL: https://github.com/apache/datafusion/pull/24808
## Which issue does this PR close?
- Closes #13027.
## Rationale for this change
I noticed that this issue had an earlier PR from almost two years ago. That implementation was closed because it used broad identifier cleanup, and maintainers were concerned it could introduce subtle bugs.
Since then, DataFusion has added much of the machinery needed for the approaches recommended in that review. This solution uses that newer machinery and combines both approaches. It removes the qualifier when the derived table does not need an alias, and rewrites the reference to the derived alias when the dialect requires one.
## What changes are included in this PR?
This PR detects when a projection enters a new derived-table scope and prevents its outer expressions from referring to an inner table alias that is no longer visible.
For dialects that do not require a derived-table alias, the invalid inner qualifier is removed. For dialects such as MySQL that require an alias, the outer reference is rewritten to the generated derived-table alias. Explicitly named subquery scopes remain unchanged.
## What is the testing strategy for this PR?
The SQL unparser round-trip tests cover the issue's original query with both the generic and MySQL dialects. They also cover filtered and distinct derived inputs, and update existing limit and nested-projection cases to assert valid outer references.
The required formatting, Clippy, and extended workspace test suite all pass, including all 505 SQL logic test files.
## Are there any user-facing changes?
Yes. SQL produced by the unparser no longer contains qualifiers that refer to tables outside their visible scope. Dialects that require derived-table aliases now qualify the outer reference with the generated alias. There are no public 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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] fix: avoid invalid qualifiers in unparsed subqueries [datafusion]
Posted by "codecov-commenter (via GitHub)" <gi...@apache.org>.
codecov-commenter commented on PR #24808:
URL: https://github.com/apache/datafusion/pull/24808#issuecomment-5473279712
## [Codecov](https://app.codecov.io/gh/apache/datafusion/pull/24808?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) Report
:x: Patch coverage is `93.33333%` with `3 lines` in your changes missing coverage. Please review.
:white_check_mark: Project coverage is 81.52%. Comparing base ([`e4cf35c`](https://app.codecov.io/gh/apache/datafusion/commit/e4cf35cbca92e6fda855d5eac4104b47e0e600e9?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)) to head ([`78fd46f`](https://app.codecov.io/gh/apache/datafusion/commit/78fd46f9261be26271faa062c023a7b994d52196?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)).
| [Files with missing lines](https://app.codecov.io/gh/apache/datafusion/pull/24808?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Patch % | Lines |
|---|---|---|
| [datafusion/sql/src/unparser/plan.rs](https://app.codecov.io/gh/apache/datafusion/pull/24808?src=pr&el=tree&filepath=datafusion%2Fsql%2Fsrc%2Funparser%2Fplan.rs&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-ZGF0YWZ1c2lvbi9zcWwvc3JjL3VucGFyc2VyL3BsYW4ucnM=) | 91.17% | [2 Missing and 1 partial :warning: ](https://app.codecov.io/gh/apache/datafusion/pull/24808?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
<details><summary>Additional details and impacted files</summary>
```diff
@@ Coverage Diff @@
## main #24808 +/- ##
==========================================
- Coverage 81.52% 81.52% -0.01%
==========================================
Files 1123 1123
Lines 406148 406193 +45
Branches 406148 406193 +45
==========================================
+ Hits 331124 331159 +35
- Misses 55659 55665 +6
- Partials 19365 19369 +4
```
</details>
[:umbrella: View full report in Codecov by Harness](https://app.codecov.io/gh/apache/datafusion/pull/24808?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).
:loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).
<details><summary> :rocket: New features to boost your workflow: </summary>
- :snowflake: [Test Analytics](https://docs.codecov.com/docs/test-analytics): Detect flaky tests, report on failures, and find test suite problems.
- :package: [JS Bundle Analysis](https://docs.codecov.com/docs/javascript-bundle-analysis): Save yourself from yourself by tracking and limiting bundle sizes in JS merges.
</details>
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] fix: avoid invalid qualifiers in unparsed subqueries [datafusion]
Posted by "blinding-pixels (via GitHub)" <gi...@apache.org>.
blinding-pixels commented on code in PR #24808:
URL: https://github.com/apache/datafusion/pull/24808#discussion_r3901231616
##########
datafusion/sql/src/unparser/plan.rs:
##########
@@ -451,6 +457,92 @@ impl Unparser<'_> {
}
}
+ /// Return the alias recursion would assign when `plan` must become a
+ /// derived relation below an already rendered projection.
+ fn derived_input_alias(plan: &LogicalPlan) -> Option<&'static str> {
+ match plan {
+ LogicalPlan::Projection(_) => Some("derived_projection"),
+ LogicalPlan::Limit(_) => Some("derived_limit"),
+ LogicalPlan::Sort(_) => Some("derived_sort"),
+ LogicalPlan::Distinct(_) => Some("derived_distinct"),
+ LogicalPlan::Filter(filter) => {
+ Self::derived_input_alias(filter.input.as_ref())
+ }
+ LogicalPlan::Repartition(repartition) => {
+ Self::derived_input_alias(repartition.input.as_ref())
+ }
+ _ => None,
+ }
+ }
+
+ fn derived_input_scope<'a>(
+ plan: &'a LogicalPlan,
+ select: &SelectBuilder,
+ ) -> Option<DerivedInputScope<'a>> {
+ if select.inside_subquery_alias() {
+ return None;
+ }
+
+ match plan {
+ LogicalPlan::Projection(projection) => {
+ let alias = Self::derived_input_alias(projection.input.as_ref())?;
Review Comment:
Whoa, I totally missed that case. Is there any part of the codebase you would recommend digging into so I can get better at catching cases like this in the future?
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] fix: avoid invalid qualifiers in unparsed subqueries [datafusion]
Posted by "kumarUjjawal (via GitHub)" <gi...@apache.org>.
kumarUjjawal commented on code in PR #24808:
URL: https://github.com/apache/datafusion/pull/24808#discussion_r3911018379
##########
datafusion/sql/src/unparser/plan.rs:
##########
@@ -451,6 +457,92 @@ impl Unparser<'_> {
}
}
+ /// Return the alias recursion would assign when `plan` must become a
+ /// derived relation below an already rendered projection.
+ fn derived_input_alias(plan: &LogicalPlan) -> Option<&'static str> {
+ match plan {
+ LogicalPlan::Projection(_) => Some("derived_projection"),
+ LogicalPlan::Limit(_) => Some("derived_limit"),
+ LogicalPlan::Sort(_) => Some("derived_sort"),
+ LogicalPlan::Distinct(_) => Some("derived_distinct"),
+ LogicalPlan::Filter(filter) => {
+ Self::derived_input_alias(filter.input.as_ref())
+ }
+ LogicalPlan::Repartition(repartition) => {
+ Self::derived_input_alias(repartition.input.as_ref())
+ }
+ _ => None,
+ }
+ }
+
+ fn derived_input_scope<'a>(
+ plan: &'a LogicalPlan,
+ select: &SelectBuilder,
+ ) -> Option<DerivedInputScope<'a>> {
+ if select.inside_subquery_alias() {
+ return None;
+ }
+
+ match plan {
+ LogicalPlan::Projection(projection) => {
+ let alias = Self::derived_input_alias(projection.input.as_ref())?;
Review Comment:
> Is there any part of the codebase you would recommend digging into so I can get better at catching cases like this in the future?
Most of these comes as you spend more time with the codebase. One of the things which I like to do is to follow the branch end to end for whatever problem I am currently working on this gives you a pretty good path to move along without being bogged down by all the other details present which might not be relevant with that particular problem.
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] fix: avoid invalid qualifiers in unparsed subqueries [datafusion]
Posted by "kumarUjjawal (via GitHub)" <gi...@apache.org>.
kumarUjjawal commented on PR #24808:
URL: https://github.com/apache/datafusion/pull/24808#issuecomment-5521635875
Thank you @blinding-pixels
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] fix: avoid invalid qualifiers in unparsed subqueries [datafusion]
Posted by "kumarUjjawal (via GitHub)" <gi...@apache.org>.
kumarUjjawal merged PR #24808:
URL: https://github.com/apache/datafusion/pull/24808
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] fix: avoid invalid qualifiers in unparsed subqueries [datafusion]
Posted by "blinding-pixels (via GitHub)" <gi...@apache.org>.
blinding-pixels commented on PR #24808:
URL: https://github.com/apache/datafusion/pull/24808#issuecomment-5475749871
Thanks so much for the quick review. I've addressed both the issues.
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] fix: avoid invalid qualifiers in unparsed subqueries [datafusion]
Posted by "kumarUjjawal (via GitHub)" <gi...@apache.org>.
kumarUjjawal commented on code in PR #24808:
URL: https://github.com/apache/datafusion/pull/24808#discussion_r3893159409
##########
datafusion/sql/src/unparser/plan.rs:
##########
@@ -451,6 +457,92 @@ impl Unparser<'_> {
}
}
+ /// Return the alias recursion would assign when `plan` must become a
+ /// derived relation below an already rendered projection.
+ fn derived_input_alias(plan: &LogicalPlan) -> Option<&'static str> {
+ match plan {
+ LogicalPlan::Projection(_) => Some("derived_projection"),
+ LogicalPlan::Limit(_) => Some("derived_limit"),
+ LogicalPlan::Sort(_) => Some("derived_sort"),
+ LogicalPlan::Distinct(_) => Some("derived_distinct"),
+ LogicalPlan::Filter(filter) => {
+ Self::derived_input_alias(filter.input.as_ref())
+ }
+ LogicalPlan::Repartition(repartition) => {
+ Self::derived_input_alias(repartition.input.as_ref())
+ }
+ _ => None,
+ }
+ }
+
+ fn derived_input_scope<'a>(
+ plan: &'a LogicalPlan,
+ select: &SelectBuilder,
+ ) -> Option<DerivedInputScope<'a>> {
+ if select.inside_subquery_alias() {
+ return None;
+ }
+
+ match plan {
+ LogicalPlan::Projection(projection) => {
+ let alias = Self::derived_input_alias(projection.input.as_ref())?;
Review Comment:
`derived_input_scope` examines only the input of this `Projection`. It misses this projection when `select.already_projected()` is already true.
For example:
`Projection(lit(1)) -> Filter(ta.id > 0) -> Projection(ta.id) -> TableScan`
The filter sees no scope. The lower projection later becomes `derived_projection`, but the SQL keeps `WHERE ta.id > 0` outside it.
Please return the first boundary that the recursive handlers will create for the current `SelectBuilder`. also add this manual-plan regression.
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] fix: avoid invalid qualifiers in unparsed subqueries [datafusion]
Posted by "kumarUjjawal (via GitHub)" <gi...@apache.org>.
kumarUjjawal commented on code in PR #24808:
URL: https://github.com/apache/datafusion/pull/24808#discussion_r3891533233
##########
datafusion/sql/src/unparser/plan.rs:
##########
@@ -829,6 +847,61 @@ impl Unparser<'_> {
columns,
);
}
+
+ let qualified_projection = p.expr.iter().try_fold(false, |found, expr| {
+ if found {
+ Ok(true)
+ } else {
+ expr.exists(|expr| {
+ Ok(matches!(expr, Expr::Column(column) if column.relation.is_some()))
+ })
+ }
+ })?;
+ let mut input_names = HashSet::new();
+ let unique_input_names = p
+ .input
+ .schema()
+ .fields()
+ .iter()
+ .all(|field| input_names.insert(field.name()));
+ if let Some(input_alias) = Self::derived_input_alias(p.input.as_ref())
+ && qualified_projection
+ && unique_input_names
+ && find_unnest_node_within_select(plan).is_none()
+ && !select.inside_subquery_alias()
+ {
+ // The input is about to enter a new SQL scope. Preserve that
+ // boundary explicitly and make the outer expressions resolve
+ // against the relation that will actually be visible there.
+ let requires_alias = self.dialect.requires_derived_table_alias();
+ let alias = requires_alias
+ .then(|| self.new_table_alias(input_alias.to_string(), vec![]));
+ self.derive(p.input.as_ref(), relation, alias, false)?;
Review Comment:
The new scope rewrite changes only the `SELECT` items. An outer `Sort` is rendered before this branch and keeps the old qualifier.
For example, `SELECT j1_id FROM (...) ORDER BY j1_id` can still emit `ORDER BY ta.j1_id`. Only `derived_projection` is visible there.
The same problem applies to an outer filter rendered before this branch. Please rebase all outer clauses and add an `ORDER BY` regression.
##########
datafusion/sql/src/unparser/ast.rs:
##########
@@ -195,6 +197,19 @@ impl SelectBuilder {
self.flatten_table_aliases.iter().any(|a| a == alias)
}
+ pub fn enter_subquery_alias(&mut self) {
Review Comment:
These methods are public because `ast` is a public module. Only the unparser uses this scope state.
Please use `pub(super)` for these three methods.
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] fix: avoid invalid qualifiers in unparsed subqueries [datafusion]
Posted by "blinding-pixels (via GitHub)" <gi...@apache.org>.
blinding-pixels commented on code in PR #24808:
URL: https://github.com/apache/datafusion/pull/24808#discussion_r3892770274
##########
datafusion/sql/src/unparser/plan.rs:
##########
@@ -829,6 +847,61 @@ impl Unparser<'_> {
columns,
);
}
+
+ let qualified_projection = p.expr.iter().try_fold(false, |found, expr| {
+ if found {
+ Ok(true)
+ } else {
+ expr.exists(|expr| {
+ Ok(matches!(expr, Expr::Column(column) if column.relation.is_some()))
+ })
+ }
+ })?;
+ let mut input_names = HashSet::new();
+ let unique_input_names = p
+ .input
+ .schema()
+ .fields()
+ .iter()
+ .all(|field| input_names.insert(field.name()));
+ if let Some(input_alias) = Self::derived_input_alias(p.input.as_ref())
+ && qualified_projection
+ && unique_input_names
+ && find_unnest_node_within_select(plan).is_none()
+ && !select.inside_subquery_alias()
+ {
+ // The input is about to enter a new SQL scope. Preserve that
+ // boundary explicitly and make the outer expressions resolve
+ // against the relation that will actually be visible there.
+ let requires_alias = self.dialect.requires_derived_table_alias();
+ let alias = requires_alias
+ .then(|| self.new_table_alias(input_alias.to_string(), vec![]));
+ self.derive(p.input.as_ref(), relation, alias, false)?;
Review Comment:
Fixed. The shared derived-input scope now rebases projection, Filter/HAVING/QUALIFY, and Sort expressions. I added Generic and MySQL ORDER BY regressions plus a manually layered outer-Filter case so the filter path cannot pass through planner pushdown.
##########
datafusion/sql/src/unparser/ast.rs:
##########
@@ -195,6 +197,19 @@ impl SelectBuilder {
self.flatten_table_aliases.iter().any(|a| a == alias)
}
+ pub fn enter_subquery_alias(&mut self) {
Review Comment:
Fixed. These three scope helpers are now `pub(super)`.
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] fix: avoid invalid qualifiers in unparsed subqueries [datafusion]
Posted by "blinding-pixels (via GitHub)" <gi...@apache.org>.
blinding-pixels commented on code in PR #24808:
URL: https://github.com/apache/datafusion/pull/24808#discussion_r3892770274
##########
datafusion/sql/src/unparser/plan.rs:
##########
@@ -829,6 +847,61 @@ impl Unparser<'_> {
columns,
);
}
+
+ let qualified_projection = p.expr.iter().try_fold(false, |found, expr| {
+ if found {
+ Ok(true)
+ } else {
+ expr.exists(|expr| {
+ Ok(matches!(expr, Expr::Column(column) if column.relation.is_some()))
+ })
+ }
+ })?;
+ let mut input_names = HashSet::new();
+ let unique_input_names = p
+ .input
+ .schema()
+ .fields()
+ .iter()
+ .all(|field| input_names.insert(field.name()));
+ if let Some(input_alias) = Self::derived_input_alias(p.input.as_ref())
+ && qualified_projection
+ && unique_input_names
+ && find_unnest_node_within_select(plan).is_none()
+ && !select.inside_subquery_alias()
+ {
+ // The input is about to enter a new SQL scope. Preserve that
+ // boundary explicitly and make the outer expressions resolve
+ // against the relation that will actually be visible there.
+ let requires_alias = self.dialect.requires_derived_table_alias();
+ let alias = requires_alias
+ .then(|| self.new_table_alias(input_alias.to_string(), vec![]));
+ self.derive(p.input.as_ref(), relation, alias, false)?;
Review Comment:
Fixed. The shared derived-input scope now rebases projection, Filter/HAVING/QUALIFY, and Sort expressions. I added Generic and MySQL ORDER BY regressions plus a manually layered outer-Filter case so the filter path cannot pass through planner pushdown.
##########
datafusion/sql/src/unparser/ast.rs:
##########
@@ -195,6 +197,19 @@ impl SelectBuilder {
self.flatten_table_aliases.iter().any(|a| a == alias)
}
+ pub fn enter_subquery_alias(&mut self) {
Review Comment:
Fixed. These three scope helpers are now `pub(super)`.
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org