You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@arrow.apache.org by GitBox <gi...@apache.org> on 2022/05/03 12:01:09 UTC

[GitHub] [arrow-datafusion] Dandandan commented on a diff in pull request #2421: naive InSubquery implementation

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


##########
datafusion/core/src/optimizer/subquery_filter_to_join.rs:
##########
@@ -0,0 +1,327 @@
+// 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 }) => {
+                // Apply optimizer rule to current input
+                let optimized_input = self.optimize(input, execution_props)?;
+
+                // 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
+                //
+                // In case of expressions which could not be rewritten
+                // return original filter with optimized input
+                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 Ok(LogicalPlan::Filter(Filter {
+                        predicate: predicate.clone(),
+                        input: Arc::new(optimized_input),
+                    }));
+                };
+
+                // Add subquery joins to new_input
+                // optimized_input value should retain for possible optimization rollback
+                let mut new_input = optimized_input.clone();
+                let opt_result = 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(
+                                "Filtering by expression not implemented for InSubquery"
+                                    .to_string(),
+                            )),
+                        };
+
+                        let join_type = match negated {

Review Comment:
   can we use if/else here?



-- 
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-unsubscribe@arrow.apache.org

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