jayzhan211 commented on code in PR #27802:
URL: https://github.com/apache/datafusion/pull/27802#discussion_r4731276870
##########
datafusion/expr/src/expr_rewriter/order_by.rs:
##########
@@ -40,16 +46,35 @@ fn rewrite_sort_col_by_aggs(
expr: Expr,
plan_inputs: &[&LogicalPlan],
proj_exprs: &[Expr],
+ shadowed: &[Column],
) -> Result<Expr> {
// Joins, and Unions are not yet handled (should have a projection
// on top of them)
if plan_inputs.len() == 1 {
- rewrite_in_terms_of_projection(expr, proj_exprs, plan_inputs[0])
+ rewrite_in_terms_of_projection(expr, proj_exprs, plan_inputs[0],
shadowed)
} else {
Ok(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> {
Review Comment:
@czhang06 thanks for applying the patch! It has a gap that came from my own
suggestion: a DataFrame sort directly over an `Aggregate`, `Window` or
`DISTINCT ON` now fails to plan where main succeeds. For example,
`df.aggregate(vec![col("column1")],
vec![count(col("column1"))])?.sort(vec![count(col("column1")).sort(false,
true)])` fails with `Aggregate function 'count(column1)' is not supported in
this position`. The gate treats every output column of those plans as
redefined, and it also checks the arguments of aggregate and window functions,
which always read the input. Could you apply the diff below? It returns main's
rows for every probe in the first details block and keeps this PR's
aggregate-alias fix. The full sqllogictest suite, the `datafusion-expr` and
`datafusion-sql` tests and the DataFrame integration tests all pass with it,
and removing any one of its conditions makes a test fail.
<details><summary>DataFrame probes: main vs this PR (SQL is unaffected; the
SQL planner turns aggregates in ORDER BY into columns first)</summary>
Input: `VALUES (1,10),(1,20),(2,5),(2,6),(2,7),(3,1)`, or table `t(a, b)`
with the same rows.
| Call | main | this PR |
|---|---|---|
| `aggregate([column1], [count(column1)]).sort(count(column1))` | sorted |
`Aggregate function 'count(column1)' is not supported in this position` |
| table `t`: `aggregate([t.a], [sum(t.a)]).sort(sum(t.a))` | sorted | same
error |
| `window([row_number() PARTITION BY column1 ORDER BY column2]).sort(<that
window expr>)` | sorted | `Window function '…' is not supported in this
position` |
| `distinct_on([column1], [column1, column1 + column2 AS s]).sort(column1 +
column2)` | `Sort: s` | `No field named column2` |
| `aggregate([column1], [min(column2)]).select([column1, min(column2) AS
column2]).sort(min(column2))` | `Sort: column2` | `Aggregate function
'min(column2)' is not supported in this position` |
| `aggregate([column1 AS k], [max(column2) AS column1]).sort(column1)` |
`Sort: k` (the bug) | `Sort: column1`, also with the diff |
</details>
```diff
-use crate::{Cast, Expr, LogicalPlan, TryCast, expr::Sort};
+use crate::{Cast, Distinct, Expr, LogicalPlan, TryCast, expr::Sort};
-use datafusion_common::tree_node::{Transformed, TransformedResult,
TreeNode};
+use datafusion_common::tree_node::{
+ Transformed, TransformedResult, TreeNode, TreeNodeRecursion,
+};
@@ pub fn rewrite_sort_cols_by_aggs(
- let shadowed = shadowed_output_columns(plan);
+ let shadowed = shadowed_output_columns(plan)?;
@@
/// 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();
+/// `10 - price AS price`). A projection item, group key or `DISTINCT ON`
+/// item that is a plain column means the same on both sides. Other plans
+/// count all of their output columns.
+fn shadowed_output_columns(plan: &LogicalPlan) -> Result<Vec<Column>> {
+ let columns = plan.schema().columns();
+ let output_exprs = match plan {
+ LogicalPlan::Projection(projection) =>
projection.expr.iter().collect(),
+ LogicalPlan::Aggregate(aggregate) =>
aggregate.output_expressions()?,
+ LogicalPlan::Distinct(Distinct::On(distinct_on)) => {
+ distinct_on.select_expr.iter().collect()
+ }
+ _ => return Ok(columns),
};
- projection
- .expr
- .iter()
- .zip(projection.schema.columns())
+ Ok(output_exprs
+ .into_iter()
+ .zip(columns)
.filter(|(expr, out)| !matches!(expr, Expr::Column(c) if c == out))
.map(|(_, out)| out)
- .collect()
+ .collect())
+}
+
+/// Does `expr` read a `shadowed` output column? The arguments of an
aggregate
+/// or window function are evaluated over the input, so a same-named column
+/// inside them is the input column and is not checked.
+fn references_shadowed(expr: &Expr, shadowed: &[Column]) -> Result<bool> {
+ let mut found = false;
+ expr.apply(|e| {
+ Ok(match e {
+ Expr::AggregateFunction(_) | Expr::WindowFunction(_) => {
+ TreeNodeRecursion::Jump
+ }
+ Expr::Column(col)
+ if shadowed.iter().any(|out| {
+ out.name == col.name
+ && (col.relation.is_none() || col.relation ==
out.relation)
+ }) =>
+ {
+ found = true;
+ TreeNodeRecursion::Stop
+ }
+ _ => TreeNodeRecursion::Continue,
+ })
+ })?;
+ Ok(found)
}
@@ fn rewrite_in_terms_of_projection(
- if expr.column_refs().iter().any(|col| {
- shadowed.iter().any(|out| {
- out.name == col.name
- && (col.relation.is_none() || col.relation ==
out.relation)
- })
- }) {
+ if references_shadowed(&expr, shadowed)? {
return Ok(Transformed::no(expr));
}
```
and in `datafusion/expr/src/logical_plan/plan.rs`:
```diff
/// Get the output expressions.
- fn output_expressions(&self) -> Result<Vec<&Expr>> {
+ pub(crate) fn output_expressions(&self) -> Result<Vec<&Expr>> {
```
<details><summary>Tests for each new condition (each fails when its
condition is removed)</summary>
```rs
// test module imports
use crate::expr::WindowFunction;
use crate::{
LogicalPlanBuilder, WindowFunctionDefinition, cast, col, lit,
logical_plan::builder::LogicalTableSource, try_cast,
};
use crate::test::function_stub::max_udaf;
/// Group keys and plain `DISTINCT ON` items pass through unchanged, and
/// window function arguments read the input, so these expressions still
/// resolve to the matching output column.
#[test]
fn pass_through_columns_of_other_plans_still_match() {
let values = || LogicalPlanBuilder::values(vec![vec![lit(1),
lit(20)]]).unwrap();
let plan = values()
.aggregate(
vec![col("column1"), col("column1") + col("column2")],
Vec::<Expr>::new(),
)
.unwrap()
.build()
.unwrap();
TestCase {
desc: "a group expression over a group key resolves to its output",
input: sort(col("column1") + col("column2")),
expected: sort(Expr::Column(Column::new_unqualified("column1 +
column2"))),
}
.run(&plan);
let window = Expr::from(WindowFunction::new(
WindowFunctionDefinition::AggregateUDF(max_udaf()),
vec![col("column1")],
));
let (qualifier, name) = window.qualified_name();
let plan = values()
.window(vec![window.clone()])
.unwrap()
.build()
.unwrap();
TestCase {
desc: "a window over an input column resolves to the window output",
input: sort(window),
expected: sort(Expr::Column(Column::new(qualifier, name))),
}
.run(&plan);
let plan = values()
.distinct_on(
vec![col("column1")],
vec![col("column1"), (col("column1") +
col("column2")).alias("s")],
None,
)
.unwrap()
.build()
.unwrap();
TestCase {
desc: "column1 + column2 resolves to s",
input: sort(col("column1") + col("column2")),
expected: sort(col("s")),
}
.run(&plan);
}
/// An alias can reuse the name of an aggregate's argument; the argument
/// still means the input column.
#[test]
fn aggregate_argument_not_blocked_by_shadowed_name() {
let values = || LogicalPlanBuilder::values(vec![vec![lit(1),
lit(20)]]).unwrap();
let plan = values()
.aggregate(vec![col("column1")], vec![min(col("column2"))])
.unwrap()
.project(vec![col("column1"), min(col("column2")).alias("column2")])
.unwrap()
.build()
.unwrap();
TestCase {
desc: "min(column2) resolves to the projected column2",
input: sort(min(col("column2"))),
expected: sort(col("column2")),
}
.run(&plan);
let plan = values()
.aggregate(
vec![col("column1")],
vec![sum(col("column2")).alias("column2")],
)
.unwrap()
.build()
.unwrap();
TestCase {
desc: "sum(column2) resolves to the aggregate output column2",
input: sort(sum(col("column2"))),
expected: sort(col("column2")),
}
.run(&plan);
}
/// A `DISTINCT ON` item can alias an input column name too.
#[test]
fn distinct_on_alias_not_matched_against_unqualified_input() {
let plan = LogicalPlanBuilder::values(vec![vec![lit(1), lit(20)]])
.unwrap()
.distinct_on(
vec![col("column2")],
vec![
col("column1").alias("column2"),
col("column2").alias("column1"),
],
None,
)
.unwrap()
.build()
.unwrap();
TestCase {
desc: "column1 is the output column1, not the input column1 AS
column2",
input: sort(col("column1")),
expected: sort(col("column1")),
}
.run(&plan);
}
```
</details>
##########
datafusion/expr/src/expr_rewriter/order_by.rs:
##########
@@ -61,14 +86,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 `shadowed` output column is left as is:
the column already names an output column,
Review Comment:
Optional cleanup: this doc line is 118 characters wide (my earlier wording
suggestion caused it), and rustfmt doesn't wrap comments.
```suggestion
/// An expression that references a `shadowed` output column is left as is:
/// the column already names an output column,
```
##########
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:
The stray spaces are still in this string at 17b12c4 (line 361); the
suggestion above still applies.
--
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]