alamb commented on code in PR #14595:
URL: https://github.com/apache/datafusion/pull/14595#discussion_r1953460041


##########
datafusion/optimizer/src/decorrelate_lateral_join.rs:
##########
@@ -0,0 +1,106 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! [`DecorrelateLateralJoin`] decorrelates logical plans produced by lateral 
joins.
+
+use crate::optimizer::ApplyOrder;
+use crate::{decorrelate_predicate_subquery, OptimizerConfig, OptimizerRule};
+
+use datafusion_common::tree_node::{Transformed, TreeNodeRecursion, 
TreeNodeVisitor};
+use datafusion_common::Result;
+use datafusion_expr::logical_plan::JoinType;
+use datafusion_expr::LogicalPlan;
+
+/// Optimizer rule for rewriting lateral joins to joins
+#[derive(Default, Debug)]
+pub struct DecorrelateLateralJoin {}
+
+impl DecorrelateLateralJoin {
+    #[allow(missing_docs)]
+    pub fn new() -> Self {
+        Self::default()
+    }
+}
+
+impl OptimizerRule for DecorrelateLateralJoin {
+    fn supports_rewrite(&self) -> bool {
+        true
+    }
+
+    fn rewrite(
+        &self,
+        plan: LogicalPlan,
+        config: &dyn OptimizerConfig,
+    ) -> Result<Transformed<LogicalPlan>> {
+        // Find cross joins with outer column references on the right side 
(i.e., the apply operator).
+        let LogicalPlan::Join(join) = &plan else {
+            return Ok(Transformed::no(plan));
+        };
+        if join.join_type != JoinType::Inner {
+            return Ok(Transformed::no(plan));
+        }
+        // TODO: this makes the rule to be quadratic to the number of nodes, 
in theory, we can build this property

Review Comment:
   I believe you can cause `rewrite` to be called in a bottom up fashion by 
using:
   
https://docs.rs/datafusion/latest/datafusion/optimizer/trait.OptimizerRule.html#method.apply_order
   
   Then you could maybe add a `contains_outer_reference` type flag to 
`DecorrelateLateralJoin`
   



##########
datafusion/optimizer/src/decorrelate_lateral_join.rs:
##########
@@ -0,0 +1,106 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! [`DecorrelateLateralJoin`] decorrelates logical plans produced by lateral 
joins.
+
+use crate::optimizer::ApplyOrder;
+use crate::{decorrelate_predicate_subquery, OptimizerConfig, OptimizerRule};
+
+use datafusion_common::tree_node::{Transformed, TreeNodeRecursion, 
TreeNodeVisitor};
+use datafusion_common::Result;
+use datafusion_expr::logical_plan::JoinType;
+use datafusion_expr::LogicalPlan;
+
+/// Optimizer rule for rewriting lateral joins to joins
+#[derive(Default, Debug)]
+pub struct DecorrelateLateralJoin {}
+
+impl DecorrelateLateralJoin {
+    #[allow(missing_docs)]
+    pub fn new() -> Self {
+        Self::default()
+    }
+}
+
+impl OptimizerRule for DecorrelateLateralJoin {
+    fn supports_rewrite(&self) -> bool {
+        true
+    }
+
+    fn rewrite(
+        &self,
+        plan: LogicalPlan,
+        config: &dyn OptimizerConfig,
+    ) -> Result<Transformed<LogicalPlan>> {
+        // Find cross joins with outer column references on the right side 
(i.e., the apply operator).
+        let LogicalPlan::Join(join) = &plan else {
+            return Ok(Transformed::no(plan));
+        };
+        if join.join_type != JoinType::Inner {
+            return Ok(Transformed::no(plan));
+        }
+        // TODO: this makes the rule to be quadratic to the number of nodes, 
in theory, we can build this property
+        // bottom-up.
+        if !plan_contains_outer_reference(&join.right) {
+            return Ok(Transformed::no(plan));
+        }
+        // The right side contains outer references, we need to decorrelate it.
+        let LogicalPlan::Subquery(subquery) = &*join.right else {
+            return Ok(Transformed::no(plan));
+        };
+        let alias = config.alias_generator();
+        let Some(new_plan) = decorrelate_predicate_subquery::build_join(
+            &join.left,
+            subquery.subquery.as_ref(),
+            None,
+            join.join_type,
+            alias.next("__lateral_sq"),
+        )?
+        else {
+            return Ok(Transformed::no(plan));
+        };
+        Ok(Transformed::new(new_plan, true, TreeNodeRecursion::Jump))
+    }
+
+    fn name(&self) -> &str {
+        "decorrelate_lateral_join"
+    }
+
+    fn apply_order(&self) -> Option<ApplyOrder> {
+        Some(ApplyOrder::TopDown)
+    }
+}
+
+fn plan_contains_outer_reference(plan: &LogicalPlan) -> bool {
+    struct Visitor {
+        contains: bool,
+    }
+    impl<'n> TreeNodeVisitor<'n> for Visitor {
+        type Node = LogicalPlan;
+        fn f_down(&mut self, plan: &'n LogicalPlan) -> 
Result<TreeNodeRecursion> {
+            if plan.contains_outer_reference() {
+                self.contains = true;
+                Ok(TreeNodeRecursion::Stop)
+            } else {
+                Ok(TreeNodeRecursion::Continue)
+            }
+        }
+    }
+    let mut visitor = Visitor { contains: false };
+    plan.visit_with_subqueries(&mut visitor).unwrap();
+    visitor.contains

Review Comment:
   I think you can do this more simply using `apply_subqueries` as described 
here: 
https://datafusion.apache.org/library-user-guide/query-optimizer.html#recursively-walk-an-expression-tree
   
   Something like (untested):
   
   ```rust
   fn plan_contains_outer_reference(plan: &LogicalPlan) -> bool {
     let mut contains = false;
     plan.apply_subqueries(|plan| {
               if plan.contains_outer_reference() {
                   self.contains = true;
                   Ok(TreeNodeRecursion::Stop)
               } else {
                   Ok(TreeNodeRecursion::Continue)
               }
     }).unwrap();
     contains
   }
   ```



##########
datafusion/sqllogictest/test_files/join.slt.part:
##########
@@ -1312,3 +1312,85 @@ SELECT a+b*2,
 
 statement ok
 drop table t1;
+
+
+statement ok
+CREATE TABLE t1(v0 BIGINT, v1 BIGINT);
+
+statement ok
+CREATE TABLE t0(v0 BIGINT, v1 BIGINT);
+
+statement ok

Review Comment:
   Thanks!
   
   Could we please add some negative cases to these tests too such as:
   1. When there are two subqueries
   2. When the subqueries have no correlation



##########
datafusion/sqllogictest/test_files/join.slt.part:
##########
@@ -1312,3 +1312,85 @@ SELECT a+b*2,
 
 statement ok
 drop table t1;
+
+
+statement ok
+CREATE TABLE t1(v0 BIGINT, v1 BIGINT);
+
+statement ok
+CREATE TABLE t0(v0 BIGINT, v1 BIGINT);
+
+statement ok
+INSERT INTO t0(v0, v1) VALUES (1, 1), (1, 2), (3, 3);
+
+statement ok
+INSERT INTO t1(v0, v1) VALUES (1, 1), (3, 2), (3, 5);
+
+query TT
+explain SELECT *
+FROM t0,
+LATERAL (SELECT sum(v1) FROM t1 WHERE t0.v0 = t1.v0);
+----
+logical_plan
+01)Projection: t0.v0, t0.v1, sum(t1.v1)
+02)--Inner Join: t0.v0 = __lateral_sq_1.v0
+03)----TableScan: t0 projection=[v0, v1]
+04)----SubqueryAlias: __lateral_sq_1
+05)------Projection: sum(t1.v1), t1.v0
+06)--------Aggregate: groupBy=[[t1.v0]], aggr=[[sum(t1.v1)]]
+07)----------TableScan: t1 projection=[v0, v1]
+physical_plan
+01)ProjectionExec: expr=[v0@1 as v0, v1@2 as v1, sum(t1.v1)@0 as sum(t1.v1)]

Review Comment:
   So the DuckDB plan has 2 joins in it (I don't know what a `RIGHT_DELIM_JOIN` 
is)  but this plan has only one
   
   ```
   D explain SELECT *
     FROM t0,
     LATERAL (SELECT sum(v1) FROM t1 WHERE t0.v0 = t1.v0);
   
   ┌─────────────────────────────┐
   │┌───────────────────────────┐│
   ││       Physical Plan       ││
   │└───────────────────────────┘│
   └─────────────────────────────┘
   ┌───────────────────────────┐
   │         PROJECTION        │
   │    ────────────────────   │
   │             v0            │
   │             v1            │
   │          sum(v1)          │
   │                           │
   │          ~3 Rows          │
   └─────────────┬─────────────┘
   ┌─────────────┴─────────────┐
   │      RIGHT_DELIM_JOIN     │
   │    ────────────────────   │
   │      Join Type: INNER     │
   │                           │
   │        Conditions:        ├──────────────┐
   │ v0 IS NOT DISTINCT FROM v0│              │
   │                           │              │
   │          ~3 Rows          │              │
   └─────────────┬─────────────┘              │
   ┌─────────────┴─────────────┐┌─────────────┴─────────────┐
   │         SEQ_SCAN          ││         HASH_JOIN         │
   │    ────────────────────   ││    ────────────────────   │
   │             t0            ││      Join Type: INNER     │
   │                           ││                           │
   │        Projections:       ││        Conditions:        
├───────────────────────────────────────────┐
   │             v0            ││ v0 IS NOT DISTINCT FROM v0│                   
                        │
   │             v1            ││                           │                   
                        │
   │                           ││                           │                   
                        │
   │          ~3 Rows          ││          ~3 Rows          │                   
                        │
   └───────────────────────────┘└─────────────┬─────────────┘                   
                        │
                                ┌─────────────┴─────────────┐                   
          ┌─────────────┴─────────────┐
                                │         PROJECTION        │                   
          │         DUMMY_SCAN        │
                                │    ────────────────────   │                   
          │                           │
                                │          sum(v1)          │                   
          │                           │
                                │             v0            │                   
          │                           │
                                │                           │                   
          │                           │
                                │          ~1 Rows          │                   
          │                           │
                                └─────────────┬─────────────┘                   
          └───────────────────────────┘
                                ┌─────────────┴─────────────┐
                                │         HASH_JOIN         │
                                │    ────────────────────   │
                                │      Join Type: LEFT      │
                                │                           │
                                │        Conditions:        ├──────────────┐
                                │ v0 IS NOT DISTINCT FROM #0│              │
                                │                           │              │
                                │          ~1 Rows          │              │
                                └─────────────┬─────────────┘              │
                                
┌─────────────┴─────────────┐┌─────────────┴─────────────┐
                                │         DELIM_SCAN        ││         
PROJECTION        │
                                │    ────────────────────   ││    
────────────────────   │
                                │       Delim Index: 1      
││__internal_decompress_integ│
                                │                           ││     
ral_bigint(#0, 1)     │
                                │                           ││             #1   
         │
                                │                           ││                  
         │
                                │          ~1 Rows          ││          ~0 Rows 
         │
                                
└───────────────────────────┘└─────────────┬─────────────┘
                                                             
┌─────────────┴─────────────┐
                                                             │   
PERFECT_HASH_GROUP_BY   │
                                                             │    
────────────────────   │
                                                             │         Groups: 
#0        │
                                                             │                  
         │
                                                             │        
Aggregates:        │
                                                             │    
sum_no_overflow(#1)    │
                                                             
└─────────────┬─────────────┘
                                                             
┌─────────────┴─────────────┐
                                                             │         
PROJECTION        │
                                                             │    
────────────────────   │
                                                             │             v0   
         │
                                                             │             v1   
         │
                                                             │                  
         │
                                                             │          ~3 Rows 
         │
                                                             
└─────────────┬─────────────┘
                                                             
┌─────────────┴─────────────┐
                                                             │         
PROJECTION        │
                                                             │    
────────────────────   │
                                                             
│__internal_compress_integra│
                                                             │     
l_utinyint(#0, 1)     │
                                                             │             #1   
         │
                                                             │                  
         │
                                                             │          ~3 Rows 
         │
                                                             
└─────────────┬─────────────┘
                                                             
┌─────────────┴─────────────┐
                                                             │         SEQ_SCAN 
         │
                                                             │    
────────────────────   │
                                                             │             t1   
         │
                                                             │                  
         │
                                                             │        
Projections:       │
                                                             │             v0   
         │
                                                             │             v1   
         │
                                                             │                  
         │
                                                             │          ~3 Rows 
         │
                                                             
└───────────────────────────┘
   ```



-- 
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: github-unsubscr...@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscr...@datafusion.apache.org
For additional commands, e-mail: github-h...@datafusion.apache.org

Reply via email to