tlfua commented on code in PR #27802:
URL: https://github.com/apache/datafusion/pull/27802#discussion_r4724009060


##########
datafusion/expr/src/expr_rewriter/order_by.rs:
##########
@@ -61,14 +67,27 @@ fn rewrite_sort_col_by_aggs(
 /// Remember that:
 /// 1. given a projection with exprs: [a, b + c]
 /// 2. t produces an output schema with two columns "a", "b + c"
+///
+/// A column that already resolves against `output_schema` is left as is.
+/// Projection expressions are written over the input, so an unqualified
+/// input column can share its name with a different output column (e.g.
+/// `price AS old_price, 10 - price AS price`); matching it against the
+/// projection would sort by the wrong output column.
 fn rewrite_in_terms_of_projection(
     expr: Expr,
     proj_exprs: &[Expr],
     input: &LogicalPlan,
+    output_schema: &DFSchema,
 ) -> Result<Expr> {
     // assumption is that each item in exprs, such as "b + c" is
     // available as an output column named "b + c"
     expr.transform(|expr| {
+        if let Expr::Column(col) = &expr
+            && output_schema.has_column(col)

Review Comment:
   Because `transform` is bottom-up, this check applies to every column leaf, 
but the parent expression is still matched against the projection, which is 
written over the input. So inside an expression, the colliding `price` now 
means the output column or the input column depending on whether the whole 
expression happens to equal a SELECT item:
   
   <details><summary>Repro (Codespace, main vs this PR)</summary>
   
   ```sql
   SELECT price AS old_price, 10 - price AS price
   FROM (SELECT 1 AS price UNION ALL SELECT 5)
   ORDER BY <key>;
   ```
   
   | `<key>` | main | this PR | same query with `AS s` (main = PR) |
   |---|---|---|---|
   | `price` | (1,9),(5,5) | (5,5),(1,9) | (5,5),(1,9) |
   | `10 - price` | (5,5),(1,9) | (5,5),(1,9): input `price` | (1,9),(5,5): 
output `price` |
   | `0 - price`, `-price` | (5,5),(1,9) | (1,9),(5,5): output `price` | 
(1,9),(5,5) |
   | `price + 0` | (1,9),(5,5) | (5,5),(1,9): output `price` | |
   | `CAST(price AS BIGINT)` | (1,9),(5,5) | (1,9),(5,5): input `price` (via 
the `Cast` branch below) | |
   
   </details>
   
   So this PR changes the results of `-price`, `0 - price` and `price + 0` 
compared with main, and none of the new tests cover that. Treating `price` as 
the output column does match the planner's "select list first" rule and the `AS 
s` behavior. But `10 - price` and `CAST(price AS BIGINT)` still treat it as the 
input column, unlike `AS s`. The unit test encodes both meanings: case 1 treats 
`col("column1")` as the output column, and case 3 (`10 - column1` → `diff`) 
treats it as the input column. The description's "expressions over the input, 
such as `10 - price`" has the same mix-up, because the planner resolves that 
`price` to the output column.
   
   Could you pick one meaning and apply it to the whole sort key? For example:
   - Output wins everywhere, consistent with `AS s`: skip the projection and 
`normalize_col` matching for any expression that contains a column resolving in 
`output_schema`.
   - PostgreSQL's rule, where an output name counts only when it stands alone: 
apply the check only when the whole sort key is a column (`matches!(&expr, 
Expr::Column(_))` before `transform`). That keeps main's results for 
expressions.
   
   Either way, adding `ORDER BY 10 - price`, `ORDER BY -price` and `ORDER BY 
price + 0` (with and without `AS s`) to `order.slt` would pin the behavior. If 
results change from main, the "Are there any user-facing changes?" section 
should mention it.



##########
datafusion/sqllogictest/test_files/order.slt:
##########
@@ -2660,3 +2660,77 @@ statement ok
 DROP TABLE volatile_eq_t;
 
 
+
+# ORDER BY an output column whose name is also an unqualified input column
+# read by another SELECT item must sort by the output column.
+# https://github.com/apache/datafusion/issues/27795
+query II
+SELECT price AS old_price, 10 - price AS price
+FROM (SELECT 1 AS price UNION ALL SELECT 5)
+ORDER BY price;
+----
+5 5
+1 9
+
+query II
+SELECT price AS old_price, 10 - price AS price
+FROM (SELECT 1 AS price UNION ALL SELECT 5)
+ORDER BY 2;
+----
+5 5
+1 9
+
+query II
+SELECT price AS old_price, 10 - price AS price
+FROM (SELECT 1 AS price UNION ALL SELECT 5) AS s
+ORDER BY price;
+----
+5 5
+1 9
+
+query II
+SELECT column1 AS column2, column2 AS column1
+FROM (VALUES (1, 20), (2, 10))
+ORDER BY column1;
+----
+2 10
+1 20
+
+query II
+SELECT column1 AS column2, column2 AS column1
+FROM (VALUES (1, 20), (2, 10))
+ORDER BY column2 DESC;
+----
+2 10
+1 20
+
+# ORDER BY an input column that is not in the output still resolves to its 
alias
+query I
+SELECT price AS old_price
+FROM (SELECT 1 AS price UNION ALL SELECT 5)
+ORDER BY price DESC;
+----
+5
+1
+
+query TT
+EXPLAIN SELECT price AS old_price, 10 - price AS price

Review Comment:
   Optional: the bug is only visible in the logical plan (`Sort: price ASC 
NULLS LAST`). The `physical_plan` part depends on partitioning and union 
planning that this PR doesn't touch, so it may churn for unrelated reasons. 
Consider wrapping this query in `set datafusion.explain.logical_plan_only = 
true` / `false`, as other `.slt` files do.



-- 
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