andygrove commented on code in PR #2421:
URL: https://github.com/apache/arrow-datafusion/pull/2421#discussion_r863203543


##########
datafusion/core/src/optimizer/subquery_filter_to_join.rs:
##########
@@ -0,0 +1,312 @@
+// 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.
+
+//! Optimizer rule for rewriting subquery filters to joins
+//!
+//! It handles standalone parts of logical conjunction expressions, i.e.
+//! ```text
+//!   WHERE t1.f IN (SELECT f FROM t2) AND t2.f = 'x'
+//! ```
+//! will be rewritten, but
+//! ```text
+//!   WHERE t1.f IN (SELECT f FROM t2) OR t2.f = 'x'
+//! ```
+//! won't
+use std::sync::Arc;
+
+use crate::error::{DataFusionError, Result};
+use crate::execution::context::ExecutionProps;
+use crate::logical_plan::plan::{Filter, Join};
+use crate::logical_plan::{
+    build_join_schema, Expr, JoinConstraint, JoinType, LogicalPlan,
+};
+use crate::optimizer::optimizer::OptimizerRule;
+use crate::optimizer::utils;
+
+/// Optimizer rule for rewriting subquery filters to joins
+#[derive(Default)]
+pub struct SubqueryFilterToJoin {}
+
+impl SubqueryFilterToJoin {
+    #[allow(missing_docs)]
+    pub fn new() -> Self {
+        Self {}
+    }
+}
+
+impl OptimizerRule for SubqueryFilterToJoin {
+    fn optimize(
+        &self,
+        plan: &LogicalPlan,
+        execution_props: &ExecutionProps,
+    ) -> Result<LogicalPlan> {
+        match plan {
+            LogicalPlan::Filter(Filter { predicate, input }) => {
+                // Splitting filter expression into components by AND
+                let mut filters = vec![];
+                utils::split_conjunction(predicate, &mut filters);
+
+                // Searching for subquery-based filters
+                let (subquery_filters, regular_filters): (Vec<&Expr>, 
Vec<&Expr>) =
+                    filters
+                        .into_iter()
+                        .partition(|&e| matches!(e, Expr::InSubquery { .. }));
+
+                // Check all subquery filters could be rewritten
+                let mut subqueries_in_regular = vec![];
+                regular_filters.iter().try_for_each(|&e| {
+                    extract_subquery_filters(e, &mut subqueries_in_regular)
+                })?;
+
+                if !subqueries_in_regular.is_empty() {
+                    return Err(DataFusionError::NotImplemented(
+                        "InSubquery allowed only as part of AND 
conjunction".to_string(),
+                    ));
+                };
+
+                // Apply optimizer rule to current input
+                let mut new_input = self.optimize(input, execution_props)?;
+
+                // Add subquery joins to new_input
+                subquery_filters.iter().try_for_each(|&e| match e {
+                    Expr::InSubquery {
+                        expr,
+                        subquery,
+                        negated,
+                    } => {
+                        let right_input =
+                            self.optimize(&*subquery.subquery, 
execution_props)?;
+                        let right_schema = right_input.schema();
+                        if right_schema.fields().len() != 1 {
+                            return Err(DataFusionError::Plan(
+                                "Only single column allowed in 
InSubquery".to_string(),
+                            ));
+                        };
+
+                        let right_key = 
right_schema.field(0).qualified_column();
+                        let left_key = match *expr.clone() {
+                            Expr::Column(col) => col,
+                            _ => return Err(DataFusionError::NotImplemented(

Review Comment:
   Same comment here. Can we just abort the optimization attempt rather than 
fail.



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