czhang06 opened a new pull request, #27802:
URL: https://github.com/apache/datafusion/pull/27802
## Which issue does this PR close?
- Closes #27795.
## Rationale for this change
`ORDER BY` on a SELECT alias, by name or by position, silently sorts by a
different column when the alias reuses the name of an unqualified input column
that another SELECT item reads:
```sql
SELECT price AS old_price, 10 - price AS price
FROM (SELECT 1 AS price UNION ALL SELECT 5)
ORDER BY price;
-- before: (1, 9), (5, 5) sorted by old_price
-- after: (5, 5), (1, 9) sorted by price
```
The same happens with `ORDER BY 2` and with swapped `VALUES` column names
(`SELECT column1 AS column2, column2 AS column1 FROM (VALUES ...) ORDER BY
column1`). Adding an alias to the subquery hid the bug.
## What changes are included in this PR?
The SQL planner already resolves the sort key to the output column `price`.
`LogicalPlanBuilder::sort` then calls `rewrite_in_terms_of_projection`, which
compares the key with the projection's expressions. Those expressions are
written over the input, and the comparison looks inside aliases. So the input
column `price` inside `price AS old_price` compared equal to the output column
`price`, and the key was rewritten to `old_price`.
`rewrite_in_terms_of_projection` now receives the projection's output
schema. It leaves a column as is when the column already resolves in that
schema. Expressions over the input, such as `10 - price` or `min(c2)`, still
resolve to their output column as before. A column that exists only in the
input, such as `ORDER BY price` with `SELECT price AS old_price`, does too.
## What is the testing strategy for this PR?
- New unit test `output_column_not_matched_against_unqualified_input` in
`datafusion/expr/src/expr_rewriter/order_by.rs`.
- New cases in `datafusion/sqllogictest/test_files/order.slt`:
- the four queries from the issue
- an `ORDER BY ... DESC` variant
- an input-only column that still resolves to its alias
- an `EXPLAIN` showing `Sort: price ASC NULLS LAST`
- With the new check disabled, the unit test and the new `order.slt` cases
fail.
- The full sqllogictest suite and the `datafusion-expr` / `datafusion-sql`
tests pass, as do `cargo fmt` and `cargo clippy -D warnings`.
## Are there any user-facing changes?
Queries that hit this case now return correctly sorted results. There are no
public API changes, since the touched functions are private.
--
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]