Skip to content

Commit cc97b61

Browse files
committed
fix(optimizer): check column position under derived table alias in correlated subqueries
Fail fast with an explicit error when a correlated subquery contains a derived table referencing multiple inner relations with identical column names, preventing silent wrong results caused by duplicate column collapse into the derived table alias. Closes apache#26234
1 parent 8f7690a commit cc97b61

2 files changed

Lines changed: 24 additions & 0 deletions

File tree

‎datafusion/optimizer/src/decorrelate.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -709,6 +709,7 @@ impl TreeNodeRewriter for PullUpCorrelatedExpr {
709709
);
710710
let mut new_correlated_cols = BTreeSet::new();
711711
for col in local_correlated_cols.iter() {
712+
check_alias_keeps_column_name(alias.input.schema(), col)?;
712713
new_correlated_cols
713714
.insert(Column::new(Some(alias.alias.clone()), col.name.clone()));
714715
}

‎datafusion/sqllogictest/test_files/subquery.slt‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4810,6 +4810,29 @@ SELECT t_outer.k FROM t26234 t_outer WHERE EXISTS (
48104810
1
48114811
2
48124812

4813+
# Same-named columns of a derived table inside the subquery
4814+
statement error Unsupported correlated subquery: correlated column two.k has the same name as an earlier column of the subquery output
4815+
SELECT t_outer.k FROM t26234 t_outer WHERE EXISTS (
4816+
SELECT 1 FROM (
4817+
SELECT * FROM t26234 one, t26234 two WHERE one.k = t_outer.k AND two.k = t_outer.k + 1
4818+
) d
4819+
);
4820+
4821+
statement error Unsupported correlated subquery: correlated column two.k has the same name as an earlier column of the subquery output
4822+
SELECT t_outer.k FROM t26234 t_outer WHERE NOT EXISTS (
4823+
SELECT 1 FROM (
4824+
SELECT * FROM t26234 one, t26234 two WHERE one.k = t_outer.k AND two.k = t_outer.k + 1
4825+
) d
4826+
);
4827+
4828+
# A derived table with one relation still works
4829+
query I
4830+
SELECT t_outer.k FROM t26234 t_outer WHERE EXISTS (
4831+
SELECT 1 FROM (SELECT * FROM t26234 one WHERE one.k = t_outer.k + 1) d
4832+
) ORDER BY t_outer.k;
4833+
----
4834+
1
4835+
48134836
statement ok
48144837
DROP TABLE t26234;
48154838

0 commit comments

Comments
 (0)