You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@datafusion.apache.org by gi...@apache.org on 2026/07/02 10:42:15 UTC

(datafusion) 01/01: fix: unparse columns of stacked pushdown projections unqualified (#23176)

This is an automated email from the ASF dual-hosted git repository.

github-merge-queue[bot] pushed a commit to branch gh-readonly-queue/main/pr-23176-4d898e93f09fbdce278a95964b9a61e4ac4b5249
in repository https://gitbox.apache.org/repos/asf/datafusion.git

commit 3496b9e9a1cf0b4fc43975cdc90b42790bafafc6
Author: Phoenix <Ph...@163.com>
AuthorDate: Thu Jul 2 18:41:50 2026 +0800

    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 <Ph...@163.com>
---
 datafusion/core/tests/sql/unparser.rs | 56 +++++++++++++++++++++++++++++++++++
 datafusion/sql/src/unparser/plan.rs   | 42 ++++++++++++++++++++++++++
 2 files changed, 98 insertions(+)

diff --git a/datafusion/core/tests/sql/unparser.rs b/datafusion/core/tests/sql/unparser.rs
index 7762512fac..4597b7e640 100644
--- a/datafusion/core/tests/sql/unparser.rs
+++ b/datafusion/core/tests/sql/unparser.rs
@@ -343,6 +343,62 @@ async fn optimized_duckdb_unparse_preserves_derived_table_scope() -> Result<()>
     Ok(())
 }
 
+// https://github.com/apache/datafusion/issues/23138
+//
+// CSE on `coalesce(discount_pct, 0)` factors a shared CAST into an extra inner
+// projection, so `SubqueryAlias: o` ends up over two stacked projections. When
+// the unparser renders that as nested derived tables it must qualify the
+// pass-through `order_id` with a name in scope at each level -- it must not
+// rebase it to the outer subquery alias `o`, which is not visible inside the
+// inner derived table.
+const ISSUE_23138_QUERY: &str = r#"
+SELECT * FROM
+(
+    SELECT order_id FROM "warehouse"."main"."order_items"
+) oi
+JOIN (
+    SELECT order_id, coalesce(discount_pct, 0) AS discount_pct_2
+    FROM "warehouse"."main"."orders"
+) o USING (order_id)
+"#;
+
+#[tokio::test]
+async fn optimized_duckdb_unparse_qualifies_nested_passthrough_column() -> Result<()> {
+    let ctx = issue_22961_context()?;
+    let plan = ctx.sql(ISSUE_23138_QUERY).await?.into_optimized_plan()?;
+    let dialect = DuckDBDialect::new();
+    let unparser = Unparser::new(&dialect);
+    let sql = unparser.plan_to_sql(&plan)?.to_string();
+
+    // The intermediate derived table has no `o` in scope, so the pass-through
+    // `order_id` must be unqualified there, not rebased to the subquery alias
+    // `o` (which is only the base-table alias one level deeper). The bug emitted
+    // `"o"."order_id"` inside that derived table; the fix emits a bare column.
+    let expected = concat!(
+        r#"SELECT "o"."order_id", "o"."discount_pct_2" "#,
+        r#"FROM "warehouse"."main"."order_items" AS "oi" "#,
+        r#"INNER JOIN (SELECT "order_id", "#,
+        r#"CASE WHEN "__common_expr_1" IS NOT NULL "#,
+        r#"THEN "__common_expr_1" ELSE 0.00 END AS "discount_pct_2" "#,
+        r#"FROM (SELECT CAST("o"."discount_pct" AS DECIMAL(22,2)) "#,
+        r#"AS "__common_expr_1", "o"."order_id" "#,
+        r#"FROM "warehouse"."main"."orders" AS "o")) AS "o" "#,
+        r#"ON "oi"."order_id" = "o"."order_id""#,
+    );
+    assert_eq!(sql, expected);
+
+    assert!(
+        sql.contains(r#"(SELECT "order_id", CASE WHEN"#),
+        "pass-through order_id should be unqualified in derived table: {sql}"
+    );
+    assert!(
+        !sql.contains(r#"(SELECT "o"."order_id", CASE WHEN"#),
+        "derived table must not reference out-of-scope alias o: {sql}"
+    );
+
+    Ok(())
+}
+
 /// The outcome of running a single roundtrip test.
 ///
 /// A successful test produces [`TestCaseResult::Success`].
diff --git a/datafusion/sql/src/unparser/plan.rs b/datafusion/sql/src/unparser/plan.rs
index 5e4a353f8f..b538b31a76 100644
--- a/datafusion/sql/src/unparser/plan.rs
+++ b/datafusion/sql/src/unparser/plan.rs
@@ -1992,6 +1992,21 @@ impl Unparser<'_> {
         Ok(Some(relation))
     }
 
+    /// Strip the table qualifier from every column in a pushdown pass-through
+    /// projection expression, so it resolves against the unnamed derived table
+    /// rendered for the inner pushdown projection rather than a deeper table
+    /// alias that is out of scope at this nesting level.
+    fn strip_pushdown_column_qualifiers(expr: Expr) -> Result<Expr> {
+        expr.transform(|e| match e {
+            Expr::Column(mut column) => {
+                column.relation = None;
+                Ok(Transformed::yes(Expr::Column(column)))
+            }
+            other => Ok(Transformed::no(other)),
+        })
+        .data()
+    }
+
     /// Try to unparse a table scan with pushdown operations into a new subquery plan.
     /// If the table scan is without any pushdown operations, return None.
     fn unparse_table_scan_pushdown(
@@ -2121,6 +2136,33 @@ impl Unparser<'_> {
                     alias.clone(),
                     already_projected,
                 )? {
+                    // The pushed-down scan alias is only in scope for the
+                    // projection directly above the aliased table scan. `plan`
+                    // is the result of pushing the alias further down: if it is
+                    // itself a `Projection`, the input was another projection
+                    // (e.g. common subexpression elimination stacked one), so
+                    // this projection sits over a derived table rather than
+                    // directly over the aliased scan, and the alias is out of
+                    // scope here. Its qualified pass-through columns must then
+                    // reference the derived table's output unqualified instead
+                    // of being rebased to the alias. Build it directly so the
+                    // unqualified columns are not re-normalized back to the
+                    // alias. (Otherwise `plan` is the scan-derived plan and we
+                    // fall through to rebase to the alias, correct one level
+                    // above the scan.)
+                    if alias.is_some() && matches!(plan, LogicalPlan::Projection(_)) {
+                        let exprs = projection
+                            .expr
+                            .iter()
+                            .cloned()
+                            .map(Self::strip_pushdown_column_qualifiers)
+                            .collect::<Result<Vec<_>>>()?;
+                        return Ok(Some(LogicalPlan::Projection(Projection::try_new(
+                            exprs,
+                            Arc::new(plan),
+                        )?)));
+                    }
+
                     let exprs = if alias.is_some() {
                         let mut alias_rewriter =
                             alias.as_ref().map(|alias_name| TableAliasRewriter {


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@datafusion.apache.org
For additional commands, e-mail: commits-help@datafusion.apache.org