jayzhan211 commented on code in PR #27802:
URL: https://github.com/apache/datafusion/pull/27802#discussion_r4727278859
##########
datafusion/expr/src/expr_rewriter/order_by.rs:
##########
@@ -61,14 +67,33 @@ 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"
+///
+/// An expression that references a column resolving against
+/// `output_schema` is left as is: the column already names an output column,
+/// and the expression is evaluated over the output. 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 such an expression
+/// against the projection would read the input column instead.
+/// Sub-expressions that reference only input columns, such as `min(c2)` in
+/// `c1 + min(c2)`, are still rewritten.
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 expr
+ .column_refs()
+ .iter()
+ .any(|col| output_schema.has_column(col))
+ {
+ return Ok(Transformed::no(expr));
+ }
Review Comment:
This check also blocks pass-through columns like `a`, which mean the same
above and below the projection. That changes results from main when the key
repeats a volatile SELECT item:
```sql
CREATE TABLE u(a INT) AS VALUES (1), (2), (3), (4), (5), (6), (7), (8);
SELECT a, a * random() AS s FROM u ORDER BY a * random();
-- main: sorted by s; this PR: sorted by a second random(), so s is out of
order
```
For deterministic keys it adds a hidden column instead: `ORDER BY a + b`
with `a + b AS s` now plans `Sort: u.a + u.b` over an extra `u.b` rather than
`Sort: s`. Could you block only output columns that a projection item
redefines, and keep the current check for other plan types (an `Aggregate` or
`DistinctOn` can alias an input name too)? With this, the issue queries and all
new `order.slt` cases give the same results as now, the volatile query sorts by
`s` again, and `cargo test -p datafusion-expr` plus the full sqllogictest suite
pass.
```diff
@@ pub fn rewrite_sort_cols_by_aggs(
} else {
vec![]
};
+ let shadowed = shadowed_output_columns(plan);
@@
&proj_exprs,
- plan.schema(),
+ &shadowed,
)?,
@@ fn rewrite_sort_col_by_aggs(
proj_exprs: &[Expr],
- output_schema: &DFSchema,
+ shadowed: &[Column],
) -> Result<Expr> {
@@
- rewrite_in_terms_of_projection(expr, proj_exprs, plan_inputs[0],
output_schema)
+ rewrite_in_terms_of_projection(expr, proj_exprs, plan_inputs[0],
shadowed)
@@ fn rewrite_in_terms_of_projection(
input: &LogicalPlan,
- output_schema: &DFSchema,
+ shadowed: &[Column],
) -> Result<Expr> {
@@
- if expr
- .column_refs()
- .iter()
- .any(|col| output_schema.has_column(col))
- {
+ if expr.column_refs().iter().any(|col| {
+ shadowed.iter().any(|out| {
+ out.name == col.name
+ && (col.relation.is_none() || col.relation ==
out.relation)
+ })
+ }) {
return Ok(Transformed::no(expr));
}
@@
+/// Output columns that may mean something different above `plan` than the
+/// same name means inside its expressions (e.g. `price` in
+/// `10 - price AS price`). A projection's pass-through column means the
same
+/// on both sides; other plans can alias too (`Aggregate`, `DistinctOn`), so
+/// all of their output columns count.
+fn shadowed_output_columns(plan: &LogicalPlan) -> Vec<Column> {
+ let LogicalPlan::Projection(projection) = plan else {
+ return plan.schema().columns();
+ };
+ projection
+ .expr
+ .iter()
+ .zip(projection.schema.columns())
+ .filter(|(expr, out)| !matches!(expr, Expr::Column(c) if c == out))
+ .map(|(_, out)| out)
+ .collect()
+}
```
(Also drop `DFSchema` from the import, and change "a column resolving
against `output_schema`" in the doc comment to "a `shadowed` output column".)
<details><summary>Tests for each condition (each one fails when its
condition is removed)</summary>
```rs
/// A column passed through unchanged means the same above and below the
/// projection, so an expression using it still matches a SELECT item.
#[test]
fn pass_through_column_still_matches_projection() {
let plan = LogicalPlanBuilder::values(vec![vec![lit(1), lit(20)]])
.unwrap()
.project(vec![
col("column1"),
(col("column1") + col("column2")).alias("s"),
])
.unwrap()
.build()
.unwrap();
TestCase {
desc: "column1 + column2 resolves to s",
input: sort(col("column1") + col("column2")),
expected: sort(col("s")),
}
.run(&plan);
}
/// An aggregate alias can reuse an input column name too.
#[test]
fn aggregate_alias_not_matched_against_unqualified_input() {
let plan = LogicalPlanBuilder::values(vec![vec![lit(1), lit(20)]])
.unwrap()
.aggregate(
vec![col("column1").alias("k")],
vec![sum(col("column2")).alias("column1")],
)
.unwrap()
.build()
.unwrap();
TestCase {
desc: "column1 is the sum, not the group key k",
input: sort(col("column1")),
expected: sort(col("column1")),
}
.run(&plan);
}
/// A shadowed output column is matched by qualifier, as
/// `DFSchema::has_column` does.
#[test]
fn shadowed_output_column_matched_by_qualifier() {
let plan = LogicalPlanBuilder::values(vec![vec![lit(1), lit(20)]])
.unwrap()
.project(vec![
col("column1").alias("k"),
(lit(10) - col("column1")).alias_qualified(Some("u"), "column1"),
])
.unwrap()
.build()
.unwrap();
TestCase {
desc: "unqualified column1 is the output u.column1, not k",
input: sort(col("column1")),
expected: sort(col("column1")),
}
.run(&plan);
let plan = make_input()
.project(vec![
col("t.c1").alias("old_c1"),
(lit(10) - col("t.c1")).alias("c1"),
])
.unwrap()
.build()
.unwrap();
TestCase {
desc: "qualified t.c1 is the input column, so it resolves to old_c1",
input: sort(col("t.c1")),
expected: sort(col("old_c1")),
}
.run(&plan);
}
```
</details>
##########
datafusion/expr/src/expr_rewriter/order_by.rs:
##########
@@ -285,6 +310,85 @@ mod test {
}
}
+ /// A sort key that references an output column must use that output
+ /// column, even when an unqualified input column of the same name is
+ /// read by another projection expression.
+ /// See <https://github.com/apache/datafusion/issues/27795>
+ #[test]
+ fn output_column_not_matched_against_unqualified_input() {
+ let plan = LogicalPlanBuilder::values(vec![vec![lit(1), lit(20)]])
+ .unwrap()
+ .project(vec![
+ col("column1").alias("column2"),
+ col("column2").alias("column1"),
+ (lit(10) - col("column1")).alias("diff"),
+ ])
+ .unwrap()
+ .build()
+ .unwrap();
+
+ let cases = vec![
+ TestCase {
+ desc: "column1 is an output column and stays column1",
+ input: sort(col("column1")),
+ expected: sort(col("column1")),
+ },
+ TestCase {
+ desc: "column2 is an output column and stays column2",
+ input: sort(col("column2")),
+ expected: sort(col("column2")),
+ },
+ TestCase {
+ desc: "column1 inside an expression is the output column too,
so the expression is not matched to diff",
Review Comment:
Optional cleanup: the line break inside this string literal leaves about 24
spaces in the message. A trailing `\` drops them:
```suggestion
desc: "column1 inside an expression is the output column
too, \
so the expression is not matched to diff",
```
--
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]