alamb commented on code in PR #2885:
URL: https://github.com/apache/arrow-datafusion/pull/2885#discussion_r925980997


##########
datafusion/optimizer/src/decorrelate_scalar_subquery.rs:
##########
@@ -0,0 +1,704 @@
+// 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.
+
+use crate::utils::{
+    exprs_to_join_cols, find_join_exprs, has_disjunction, only_or_err, 
split_conjunction,
+};
+use crate::{utils, OptimizerConfig, OptimizerRule};
+use datafusion_common::{context, plan_err, Column, Result};
+use datafusion_expr::logical_plan::{Aggregate, Filter, JoinType, Projection, 
Subquery};
+use datafusion_expr::{combine_filters, Expr, LogicalPlan, LogicalPlanBuilder, 
Operator};
+use log::debug;
+use std::sync::Arc;
+
+/// Optimizer rule for rewriting subquery filters to joins
+#[derive(Default)]
+pub struct DecorrelateScalarSubquery {}
+
+impl DecorrelateScalarSubquery {
+    #[allow(missing_docs)]
+    pub fn new() -> Self {
+        Self {}
+    }
+
+    /// Finds expressions that have a scalar subquery in them (and recurses 
when found)
+    ///
+    /// # Arguments
+    /// * `predicate` - A conjunction to split and search
+    /// * `optimizer_config` - For generating unique subquery aliases
+    ///
+    /// Returns a tuple (subqueries, non-subquery expressions)
+    fn extract_subquery_exprs(
+        &self,
+        predicate: &Expr,
+        optimizer_config: &mut OptimizerConfig,
+    ) -> Result<(Vec<SubqueryInfo>, Vec<Expr>)> {
+        let mut filters = vec![];
+        split_conjunction(predicate, &mut filters); // TODO: disjunctions
+
+        let mut subqueries = vec![];
+        let mut others = vec![];
+        for it in filters.iter() {
+            match it {
+                Expr::BinaryExpr { left, op, right } => {
+                    let l_query = Subquery::try_from_expr(left);
+                    let r_query = Subquery::try_from_expr(right);
+                    if l_query.is_err() && r_query.is_err() {
+                        others.push((*it).clone());
+                        continue;
+                    }
+                    let mut recurse =
+                        |q: Result<&Subquery>, expr: Expr, lhs: bool| -> 
Result<()> {
+                            let subquery = match q {
+                                Ok(subquery) => subquery,
+                                _ => return Ok(()),
+                            };
+                            let subquery =
+                                self.optimize(&*subquery.subquery, 
optimizer_config)?;
+                            let subquery = Arc::new(subquery);
+                            let subquery = Subquery { subquery };
+                            let res = SubqueryInfo::new(subquery, expr, *op, 
lhs);
+                            subqueries.push(res);
+                            Ok(())
+                        };
+                    recurse(l_query, (**right).clone(), false)?;
+                    recurse(r_query, (**left).clone(), true)?;
+                    // TODO: if subquery doesn't get optimized, optimized 
children are lost
+                }
+                _ => others.push((*it).clone()),
+            }
+        }
+
+        Ok((subqueries, others))
+    }
+}
+
+impl OptimizerRule for DecorrelateScalarSubquery {
+    fn optimize(
+        &self,
+        plan: &LogicalPlan,
+        optimizer_config: &mut OptimizerConfig,
+    ) -> Result<LogicalPlan> {
+        match plan {
+            LogicalPlan::Filter(Filter { predicate, input }) => {
+                // Apply optimizer rule to current input
+                let optimized_input = self.optimize(input, optimizer_config)?;
+
+                let (subqueries, other_exprs) =
+                    self.extract_subquery_exprs(predicate, optimizer_config)?;
+                let optimized_plan = LogicalPlan::Filter(Filter {
+                    predicate: predicate.clone(),
+                    input: Arc::new(optimized_input),
+                });
+                if subqueries.is_empty() {
+                    // regular filter, no subquery exists clause here
+                    return Ok(optimized_plan);
+                }
+
+                // iterate through all exists clauses in predicate, turning 
each into a join
+                let mut cur_input = (**input).clone();
+                for subquery in subqueries {
+                    cur_input = optimize_scalar(
+                        &subquery,
+                        &cur_input,
+                        &other_exprs,
+                        optimizer_config,
+                    )?;
+                }
+                Ok(cur_input)
+            }
+            _ => {
+                // Apply the optimization to all inputs of the plan
+                utils::optimize_children(self, plan, optimizer_config)
+            }
+        }
+    }
+
+    fn name(&self) -> &str {
+        "decorrelate_scalar_subquery"
+    }
+}
+
+/// Takes a query like:
+///
+/// ```select id from customers where balance > (select avg(total) from 
orders)```

Review Comment:
   I was just pointing out that the comment seemed incorrect. The code looked 
great



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

Reply via email to