hcrosse opened a new issue, #27781:
URL: https://github.com/apache/datafusion/issues/27781

   ### Describe the bug
   
   Correlated subquery predicates in a `JOIN ... ON` clause fail to plan on 
unaliased tables with a missing field schema error. 
[`has_all_column_refs`](https://github.com/apache/datafusion/blob/main/datafusion/optimizer/src/utils.rs#L148)
 only inspects `expr.column_refs()` and ignores `Subquery::outer_ref_columns` 
inside `Expr::Exists`, `Expr::InSubquery`, `Expr::SetComparison`, and 
`Expr::ScalarSubquery`. When a predicate has no direct `Expr::Column` nodes, 
`ColumnChecker::is_left_only` and `ColumnChecker::is_right_only` in 
[`push_down_filter.rs`](https://github.com/apache/datafusion/blob/main/datafusion/optimizer/src/push_down_filter.rs#L230)
 return `true` vacuously and push the predicate onto the wrong side of the join.
   
   ### To Reproduce
   
   ```sql
   CREATE TABLE t1 (a INT) AS VALUES (1), (2);
   CREATE TABLE t2 (a INT) AS VALUES (1), (2);
   CREATE TABLE t3 (a INT) AS VALUES (1);
   
   SELECT t1.a, t2.a
   FROM t1
   INNER JOIN t2
     ON t1.a = t2.a AND EXISTS (SELECT 1 FROM t3 WHERE t3.a = t2.a);
   ```
   
   Output on `main`:
   
   ```text
   Schema error: No field named t2.a. Did you mean '__correlated_sq_1.a'?
   Valid fields are __correlated_sq_1.a.
   ```
   
   The same failure reproduces with `NOT EXISTS`, `= ANY`, `<> ALL`, and `> 
ALL`, as well as `LEFT JOIN` referencing `t1.a` and `RIGHT JOIN` referencing 
`t2.a` in `ON`.
   
   ### Expected behavior
   
   For the `INNER JOIN` above, `PushDownFilter` should push the `EXISTS` 
predicate onto `t2`, and the query should return `(1, 1)`. For `LEFT JOIN` 
referencing `t1.a` or `RIGHT JOIN` referencing `t2.a`, `PushDownFilter` should 
keep the predicate in the join filter rather than pushing it to the opposite 
child.
   
   ### Additional context
   
   This is distinct from #26573, which is about `SubqueryAlias` qualifier 
rewriting on aliased tables. Here the tables have no aliases and the failure 
comes from `has_all_column_refs` missing `Subquery::outer_ref_columns`, unlike 
[`for_each_referenced_index`](https://github.com/apache/datafusion/blob/main/datafusion/optimizer/src/utils.rs#L112)
 directly above it and 
[`references_any_column`](https://github.com/apache/datafusion/blob/main/datafusion/optimizer/src/push_down_filter.rs#L806).
   
   ### Willingness to contribute
   
   I plan to contribute a fix for this bug independently
   


-- 
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]

Reply via email to