Skip to content

Commit 3496b9e

Browse files
fix: unparse columns of stacked pushdown projections unqualified (#23176)
## 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 #123` indicates that this PR will close issue #123. --> - Closes #23138 . ## 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. --> For an optimized plan, common subexpression elimination can leave a `SubqueryAlias` over two stacked `Projection`s (it factors a shared expression into an extra inner projection). The plan is correct; the unparser just cannot render it accurately. When unparsing such a subquery, `unparse_table_scan_pushdown` pushes the subquery alias down to the aliased table scan and rebases each projection's columns to that alias. That is correct for the projection directly above the scan, but an *outer* stacked projection sits over a derived table where the alias is no longer in scope, so rebasing its qualified pass-through columns emits references the surrounding query cannot resolve. For the reproducer in the issue the generated SQL is (note the middle `"o"."order_id"`): ```sql ... INNER JOIN ( SELECT "o"."order_id", CASE WHEN "__common_expr_1" ... END AS "discount_pct_2" FROM (SELECT CAST("o"."discount_pct" ...) AS "__common_expr_1", "o"."order_id" FROM "warehouse"."main"."orders" AS "o") ) AS "o" ON ... ``` DuckDB rejects it with Binder Error: Referenced table "o" not found!, because "o" is only the base-table alias one level deeper, not visible in the intermediate derived table. ## 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. --> In unparse_table_scan_pushdown's Projection arm, detect the stacked case: if the recursive pushdown result is itself a Projection, this projection sits over a derived table rather than directly over the aliased scan. In that case, strip the table qualifier from the projection's pass-through columns so they reference the derived table's output unqualified, instead of being rebased to the (out-of-scope) scan alias. The projection is built directly (Projection::try_new) so the unqualified columns are not re-normalized back to the alias. The projection directly above the scan is unchanged and still rebases to the alias. After the fix the middle column is unqualified and the SQL is valid: ```sql ... INNER JOIN ( SELECT "order_id", CASE WHEN "__common_expr_1" ... END AS "discount_pct_2" FROM (SELECT CAST("o"."discount_pct" ...) AS "__common_expr_1", "o"."order_id" FROM "warehouse"."main"."orders" AS "o") ) AS "o" ON ... ``` ## 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)? --> New test `optimized_duckdb_unparse_qualifies_nested_passthrough_column` in `datafusion/core/tests/sql/unparser.rs`, asserting the intermediate derived table no longer carries the out-of-scope alias. ## 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 public API changes. --------- Signed-off-by: Jiawei Zhao <Phoenix500526@163.com>
1 parent 4d898e9 commit 3496b9e

2 files changed

Lines changed: 98 additions & 0 deletions

File tree

datafusion/core/tests/sql/unparser.rs

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -343,6 +343,62 @@ async fn optimized_duckdb_unparse_preserves_derived_table_scope() -> Result<()>
343343
Ok(())
344344
}
345345

346+
// https://github.com/apache/datafusion/issues/23138
347+
//
348+
// CSE on `coalesce(discount_pct, 0)` factors a shared CAST into an extra inner
349+
// projection, so `SubqueryAlias: o` ends up over two stacked projections. When
350+
// the unparser renders that as nested derived tables it must qualify the
351+
// pass-through `order_id` with a name in scope at each level -- it must not
352+
// rebase it to the outer subquery alias `o`, which is not visible inside the
353+
// inner derived table.
354+
const ISSUE_23138_QUERY: &str = r#"
355+
SELECT * FROM
356+
(
357+
SELECT order_id FROM "warehouse"."main"."order_items"
358+
) oi
359+
JOIN (
360+
SELECT order_id, coalesce(discount_pct, 0) AS discount_pct_2
361+
FROM "warehouse"."main"."orders"
362+
) o USING (order_id)
363+
"#;
364+
365+
#[tokio::test]
366+
async fn optimized_duckdb_unparse_qualifies_nested_passthrough_column() -> Result<()> {
367+
let ctx = issue_22961_context()?;
368+
let plan = ctx.sql(ISSUE_23138_QUERY).await?.into_optimized_plan()?;
369+
let dialect = DuckDBDialect::new();
370+
let unparser = Unparser::new(&dialect);
371+
let sql = unparser.plan_to_sql(&plan)?.to_string();
372+
373+
// The intermediate derived table has no `o` in scope, so the pass-through
374+
// `order_id` must be unqualified there, not rebased to the subquery alias
375+
// `o` (which is only the base-table alias one level deeper). The bug emitted
376+
// `"o"."order_id"` inside that derived table; the fix emits a bare column.
377+
let expected = concat!(
378+
r#"SELECT "o"."order_id", "o"."discount_pct_2" "#,
379+
r#"FROM "warehouse"."main"."order_items" AS "oi" "#,
380+
r#"INNER JOIN (SELECT "order_id", "#,
381+
r#"CASE WHEN "__common_expr_1" IS NOT NULL "#,
382+
r#"THEN "__common_expr_1" ELSE 0.00 END AS "discount_pct_2" "#,
383+
r#"FROM (SELECT CAST("o"."discount_pct" AS DECIMAL(22,2)) "#,
384+
r#"AS "__common_expr_1", "o"."order_id" "#,
385+
r#"FROM "warehouse"."main"."orders" AS "o")) AS "o" "#,
386+
r#"ON "oi"."order_id" = "o"."order_id""#,
387+
);
388+
assert_eq!(sql, expected);
389+
390+
assert!(
391+
sql.contains(r#"(SELECT "order_id", CASE WHEN"#),
392+
"pass-through order_id should be unqualified in derived table: {sql}"
393+
);
394+
assert!(
395+
!sql.contains(r#"(SELECT "o"."order_id", CASE WHEN"#),
396+
"derived table must not reference out-of-scope alias o: {sql}"
397+
);
398+
399+
Ok(())
400+
}
401+
346402
/// The outcome of running a single roundtrip test.
347403
///
348404
/// A successful test produces [`TestCaseResult::Success`].

datafusion/sql/src/unparser/plan.rs

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1992,6 +1992,21 @@ impl Unparser<'_> {
19921992
Ok(Some(relation))
19931993
}
19941994

1995+
/// Strip the table qualifier from every column in a pushdown pass-through
1996+
/// projection expression, so it resolves against the unnamed derived table
1997+
/// rendered for the inner pushdown projection rather than a deeper table
1998+
/// alias that is out of scope at this nesting level.
1999+
fn strip_pushdown_column_qualifiers(expr: Expr) -> Result<Expr> {
2000+
expr.transform(|e| match e {
2001+
Expr::Column(mut column) => {
2002+
column.relation = None;
2003+
Ok(Transformed::yes(Expr::Column(column)))
2004+
}
2005+
other => Ok(Transformed::no(other)),
2006+
})
2007+
.data()
2008+
}
2009+
19952010
/// Try to unparse a table scan with pushdown operations into a new subquery plan.
19962011
/// If the table scan is without any pushdown operations, return None.
19972012
fn unparse_table_scan_pushdown(
@@ -2121,6 +2136,33 @@ impl Unparser<'_> {
21212136
alias.clone(),
21222137
already_projected,
21232138
)? {
2139+
// The pushed-down scan alias is only in scope for the
2140+
// projection directly above the aliased table scan. `plan`
2141+
// is the result of pushing the alias further down: if it is
2142+
// itself a `Projection`, the input was another projection
2143+
// (e.g. common subexpression elimination stacked one), so
2144+
// this projection sits over a derived table rather than
2145+
// directly over the aliased scan, and the alias is out of
2146+
// scope here. Its qualified pass-through columns must then
2147+
// reference the derived table's output unqualified instead
2148+
// of being rebased to the alias. Build it directly so the
2149+
// unqualified columns are not re-normalized back to the
2150+
// alias. (Otherwise `plan` is the scan-derived plan and we
2151+
// fall through to rebase to the alias, correct one level
2152+
// above the scan.)
2153+
if alias.is_some() && matches!(plan, LogicalPlan::Projection(_)) {
2154+
let exprs = projection
2155+
.expr
2156+
.iter()
2157+
.cloned()
2158+
.map(Self::strip_pushdown_column_qualifiers)
2159+
.collect::<Result<Vec<_>>>()?;
2160+
return Ok(Some(LogicalPlan::Projection(Projection::try_new(
2161+
exprs,
2162+
Arc::new(plan),
2163+
)?)));
2164+
}
2165+
21242166
let exprs = if alias.is_some() {
21252167
let mut alias_rewriter =
21262168
alias.as_ref().map(|alias_name| TableAliasRewriter {

0 commit comments

Comments
 (0)