jayzhan211 commented on code in PR #27802:
URL: https://github.com/apache/datafusion/pull/27802#discussion_r4754932750
##########
datafusion/sql/src/select.rs:
##########
@@ -1486,6 +1486,18 @@ impl<S: ContextProvider> SqlToRel<'_, S> {
let rewritten_expr =
rebase_expr(&sort_expr.expr, &aggr_projection_exprs,
input)?;
+ // `ORDER BY v` (or its position) where `v` is a SELECT alias
+ // already names that output column. Matching it below would
+ // pick the alias of a same-named input column instead.
+ if let Expr::Column(c) = &sort_expr.expr
+ && c.relation.is_none()
+ && select_exprs
+ .iter()
+ .any(|e| matches!(e, Expr::Alias(a) if a.name ==
c.name))
+ {
+ return Ok(sort_expr.with_expr(rewritten_expr));
+ }
Review Comment:
@czhang06 thanks for applying it! With `GROUP BY`, an `ORDER BY` expression
that equals a SELECT item and reads a colliding alias now sorts by the wrong
column, while `main` gets it right:
```sql
SELECT price AS old_price, 10 - price AS price
FROM (SELECT 1 AS price UNION ALL SELECT 5)
GROUP BY price
ORDER BY 10 - price;
-- main and with `AS s`: (1, 9), (5, 5) this PR: (5, 5), (1, 9)
```
It's the same cancellation as before, for expression keys: the `find_map`
matches `10 - price` to `10 - price AS price`, and `main`'s builder then mapped
`price` back to `old_price`. Extending this check from a bare alias to any
alias name outside aggregate/window arguments (the rule `references_shadowed`
already uses) fixes it:
```suggestion
// A SELECT alias in ORDER BY names that output column, also
// inside an expression (`ORDER BY 10 - price`). The SELECT
// expressions below are written over the input, so matching
// against them would read a same-named input column instead.
if references_select_alias(&sort_expr.expr, select_exprs)? {
return Ok(sort_expr.with_expr(rewritten_expr));
}
```
```diff
+/// Does `expr` read a SELECT alias by its unqualified name? The arguments
of
+/// an aggregate or window function are evaluated over the input, so a name
+/// inside them is the input column.
+fn references_select_alias(expr: &Expr, select_exprs: &[Expr]) ->
Result<bool> {
+ let mut found = false;
+ expr.apply(|e| {
+ Ok(match e {
+ Expr::AggregateFunction(_) | Expr::WindowFunction(_) => {
+ TreeNodeRecursion::Jump
+ }
+ Expr::Column(c)
+ if c.relation.is_none()
+ && select_exprs
+ .iter()
+ .any(|s| matches!(s, Expr::Alias(a) if a.name ==
c.name)) =>
+ {
+ found = true;
+ TreeNodeRecursion::Stop
+ }
+ _ => TreeNodeRecursion::Continue,
+ })
+ })?;
+ Ok(found)
+}
+
/// Returns true if the expression recursively contains an `Expr::Unnest`
expression
fn has_unnest_expr_recursively(expr: &Expr) -> bool {
```
Three shapes that return rows on `main` fail to plan with this, the same way
they already fail with `FROM (...) AS s`: `SELECT DISTINCT ... GROUP BY` with
`ORDER BY` an expression over an alias (two forms below), and `ORDER BY alias
IN (subquery)`. Could you list them under user-facing changes, and update the
description's "Expressions and qualified names are still matched as before"?
With the fix, the full sqllogictest suite, `cargo test -p datafusion-sql`,
clippy and `cargo doc` pass. Could you also add the two tests below? Both fail
on this head.
<details>
<summary>Tests for order.slt, and the comment to update</summary>
```
# With GROUP BY, a SELECT alias inside an ORDER BY expression also means the
# output column, even when the expression equals another SELECT item.
query II
SELECT price AS old_price, 10 - price AS price
FROM (SELECT 1 AS price UNION ALL SELECT 5)
GROUP BY price
ORDER BY 10 - price;
----
1 9
5 5
query II
SELECT column1 AS column2, column2 + 0 AS column1
FROM (VALUES (1, 20), (2, 10))
GROUP BY column1, column2
ORDER BY column2 + 0;
----
1 20
2 10
```
The comment above the `SELECT DISTINCT sum(price) + 1 AS total` test ("Only
a bare alias skips the match") is no longer true. Suggested replacement:
```
# A name inside an aggregate argument is the input column, so an expression
# that equals a SELECT item still sorts by it.
```
The existing tests catch dropping the aggregate/window `Jump` (the
`sum(price) + 1` test) and dropping `c.relation.is_none()` (the `ORDER BY
t.column1` test).
</details>
<details>
<summary>Results on main, this PR and with the fix</summary>
Each is compared with the same query over `FROM (...) AS s` (or `AS t`),
which is the same on all three builds.
| Query | main | this PR | with fix | aliased FROM |
|---|---|---|---|---|
| `GROUP BY price ORDER BY 10 - price` | (1,9),(5,5) | (5,5),(1,9) |
(1,9),(5,5) | (1,9),(5,5) |
| same + `HAVING count(*) > 0` | (1,9),(5,5) | (5,5),(1,9) | (1,9),(5,5) | |
| `column1 AS column2, column2 + 0 AS column1 ... GROUP BY column1, column2
ORDER BY column2 + 0` | (1,20),(2,10) | (2,10),(1,20) | (1,20),(2,10) |
(1,20),(2,10) |
| `x + y AS total, y AS x ... GROUP BY x, y ORDER BY x + y` |
(4,3),(7,2),(11,1) | same as main | (11,1),(7,2),(4,3) | (11,1),(7,2),(4,3) |
| `-column1 AS column1 ... GROUP BY column1 ORDER BY -column1` | -2, -1 |
-2, -1 | -1, -2 | -1, -2 |
| `SELECT DISTINCT x + y AS total, 10 - y AS x ... GROUP BY x, y ORDER BY x
+ y` | rows | rows | error: `y` must appear in select list | same error (also
without `GROUP BY`) |
| `SELECT DISTINCT column1 AS column2, column2 + column3 AS z ... GROUP BY
column1, column2, column3 ORDER BY column2 + column3` | rows | rows | error:
`column3` must appear in select list | same error |
| `column1 AS column2, column2 IN (SELECT 2) AS f ... GROUP BY column1,
column2 ORDER BY column2 IN (SELECT 2)` | rows | rows | error: `IN` subquery
not allowed in Sort | same error |
</details>
--
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]