yonatan-sevenai opened a new pull request, #21491:
URL: https://github.com/apache/datafusion/pull/21491

   ## Which issue does this PR close?
   
     - Closes #21490.
   
     ## Rationale for this change
   
     When `plan_to_sql` encounters a `Projection → Sort → Projection → 
SubqueryAlias` plan where the outer Projection excludes a Sort
     column defined as an alias in the inner Projection (e.g. `Z AS c`), the 
function `rewrite_plan_for_sort_on_non_projected_fields`
     flattens the two Projections into one but only keeps the outer 
Projection's columns. This drops the alias definition, leaving
     `ORDER BY c` referencing a column that no longer exists in the generated 
SQL.
   
     ## What changes are included in this PR?
   
     In `rewrite_plan_for_sort_on_non_projected_fields` 
(`datafusion/sql/src/unparser/rewrite.rs`), when the inner Projection is
     trimmed to only the outer Projection's expressions, sort expressions that 
reference dropped aliases are now inlined to the
     underlying physical expression. For example, `ORDER BY c` becomes `ORDER 
BY t."Z"` when `c` was defined as `Z AS c` in the
     dropped inner Projection.
   
     ## Are these changes tested?
   
     Yes. A new regression test 
`test_sort_on_aliased_column_dropped_by_outer_projection` in
     `datafusion/sql/tests/cases/plan_to_sql.rs` constructs the exact plan 
shape that triggers the bug and asserts the correct SQL
     output:
   
     ```sql
     SELECT t."X" AS a, t."Y" AS b FROM phys_table AS t ORDER BY t."Z" DESC 
NULLS FIRST LIMIT 1
     ```
   
     All existing `plan_to_sql` tests (118 tests) continue to pass.
   
     ## Are there any user-facing changes?
   
     No API changes. Previously invalid SQL is now generated correctly.


-- 
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: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to