Repository navigation
Conversation
…input column's alias When a SELECT alias reused the name of an unqualified input column read by another SELECT item, `rewrite_in_terms_of_projection` matched the sort key against that input column inside the other item's alias and sorted by the wrong output column, e.g. SELECT price AS old_price, 10 - price AS price FROM (SELECT 1 AS price UNION ALL SELECT 5) ORDER BY price sorted by `old_price`. Leave a sort-key column as is when it already resolves in the projection's output schema. Closes apache#27795
tlfua
left a comment
There was a problem hiding this comment.
This review was prepared with AI assistance; I checked each point below against 69e0b4a.
Thanks @czhang06 for tracking this down, and for the clear write-up of the cause! The fix works for the reported queries: with the new check disabled, output_column_not_matched_against_unqualified_input fails (column1 is rewritten to column2), and the unaliased ORDER BY price returns (1, 9), (5, 5) on main and (5, 5), (1, 9) here.
One change is needed before I'd consider this ready: decide how a colliding name inside an expression should resolve, and pin it with tests (inline comment below). Right now ORDER BY -price and ORDER BY 10 - price resolve price differently.
Not blocking, possibly for a follow-up: the GROUP BY form of the issue is still wrong on both main and this PR:
SELECT price AS old_price, 10 - price AS price
FROM (SELECT 1 AS price UNION ALL SELECT 5)
GROUP BY price
ORDER BY price;
-- main: (1, 9), (5, 5) this PR: (1, 9), (5, 5) expected: (5, 5), (1, 9)That path doesn't reach rewrite_in_terms_of_projection for this. In datafusion/sql/src/select.rs around line 1483 (outside the diff), the ORDER BY key is rebased and then matched against aliased SELECT items, so price matches price AS old_price. If you'd rather keep this PR focused, could you file a follow-up issue and change Closes #27795 to Part of #27795?
| // available as an output column named "b + c" | ||
| expr.transform(|expr| { | ||
| if let Expr::Column(col) = &expr | ||
| && output_schema.has_column(col) |
There was a problem hiding this 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:
Repro (Codespace, main vs this PR)
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) |
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 andnormalize_colmatching for any expression that contains a column resolving inoutput_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(_))beforetransform). 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.
| 1 | ||
|
|
||
| query TT | ||
| EXPLAIN SELECT price AS old_price, 10 - price AS price |
There was a problem hiding this 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.
…xpressions Review feedback: the previous commit protected only a sort key that was a bare output column, so a colliding name inside an expression could still resolve to the input column (`ORDER BY 10 - price`, `ORDER BY CAST(price AS BIGINT)`) while others used the output column (`ORDER BY -price`). Leave any sort sub-expression that references an output column as is, so the name always means the output column, matching the behavior when the subquery is aliased. Sub-expressions over input-only columns are still rewritten. Add order.slt cases for expressions with and without a subquery alias, and show only the logical plan in the EXPLAIN test.
jayzhan211
left a comment
There was a problem hiding this comment.
@czhang06 thanks for the fix! Two small follow-ups to @tlfua's review that are still open at 31c434c:
- Since 31c434c,
ORDER BY 10 - priceandORDER BY CAST(price AS BIGINT)return different results from main ((5,5),(1,9) → (1,9),(5,5), and the reverse). The description still says10 - priceresolves "as before". Could you update that line and mention the change under "Are there any user-facing changes?" - +1 on the GROUP BY form:
… GROUP BY price ORDER BY pricestill returns (1,9),(5,5) here. Could you changeCloses #27795toPart of #27795, so the issue stays open for that path?
| if expr | ||
| .column_refs() | ||
| .iter() | ||
| .any(|col| output_schema.has_column(col)) | ||
| { | ||
| return Ok(Transformed::no(expr)); | ||
| } |
There was a problem hiding this 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:
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 orderFor 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.
@@ 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".)
Tests for each condition (each one fails when its condition is removed)
/// 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);
}| expected: sort(col("column2")), | ||
| }, | ||
| TestCase { | ||
| desc: "column1 inside an expression is the output column too, so the expression is not matched to diff", |
There was a problem hiding this comment.
Optional cleanup: the line break inside this string literal leaves about 24 spaces in the message. A trailing \ drops them:
| desc: "column1 inside an expression is the output column too, so the expression is not matched to diff", | |
| desc: "column1 inside an expression is the output column too, \ | |
| so the expression is not matched to diff", |
…BY rewrite Pass-through columns mean the same above and below the projection, so expressions over them still match a SELECT item again (e.g. ORDER BY a + b sorts by s, and a volatile key reuses the SELECT item). Non-projection plans (Aggregate, DistinctOn) still treat all output columns as shadowed.
|
Thanks, good catch on pass-through columns. Applied your patch + tests in 17b12c4, and added an EXPLAIN in order.slt showing |
Which issue does this PR close?
ORDER BYcase. TheGROUP BYform goes through a different path inselect.rsand is tracked in GROUP BY + ORDER BY on a SELECT alias sorts by the wrong column when the alias reuses an input column name #27814.Rationale for this change
ORDER BYon 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:The same happens with
ORDER BY 2and with swappedVALUEScolumn names. Adding an alias to the subquery (... AS s) hid the bug.What changes are included in this PR?
The SQL planner resolves names in
ORDER BYagainst the SELECT list first, sopriceabove is the output column.LogicalPlanBuilder::sortthen callsrewrite_in_terms_of_projection, which matches sort expressions against the projection's expressions so it can reuse the computed columns. Those expressions are written over the input, and the matching looks inside aliases. So the inputpriceinsideprice AS old_pricecompared equal to the outputprice.rewrite_in_terms_of_projectionnow receives the projection's output schema. It leaves any sort sub-expression that references an output column as is, because that expression is evaluated over the output. A colliding name therefore always means the output column, whether it stands alone or sits inside an expression. That matches the behavior with an aliased subquery. Sub-expressions that reference only input columns are still rewritten as before, for examplemin(c2)inc1 + min(c2), orpriceinSELECT price AS old_price ... ORDER BY price.What is the testing strategy for this PR?
datafusion/expr/src/expr_rewriter/order_by.rs:output_column_not_matched_against_unqualified_input: bare columns, an expression, and a cast that use an output column stay as is.input_only_columns_still_resolve_to_aliases: input-only expressions and columns are still rewritten.datafusion/sqllogictest/test_files/order.slt:ORDER BY 10 - price,-price,price + 0andCAST(price AS BIGINT), each with and withoutAS s, which must agreeEXPLAINshowingSort: price ASC NULLS LASTdatafusion-expr/datafusion-sqltests pass, as docargo fmtandcargo clippy -D warnings.Are there any user-facing changes?
Yes, results change for queries where a SELECT alias reuses the name of an unqualified input column read by another SELECT item, and
ORDER BYrefers to that name. They now sort by the output column, the same as when the subquery has an alias:ORDER BY priceandORDER BY 2(the reported bug)ORDER BY 10 - price,-price,price + 0orCAST(price AS BIGINT), which previously used the inputpriceThere are no public API changes, since the touched functions are private.