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/04 07:10:57 UTC

[GitHub] [arrow-datafusion] korowa commented on a diff in pull request #2421: Basic support for `IN` and `NOT IN` Subqueries by rewriting them to `SEMI` / `ANTI`

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


##########
datafusion/core/src/optimizer/subquery_filter_to_join.rs:
##########
@@ -0,0 +1,334 @@
+// 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 opt_result = subquery_filters.iter().try_fold(
+                    optimized_input.clone(),
+                    |input, &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 = if *negated {
+                                JoinType::Anti
+                            } else {
+                                JoinType::Semi
+                            };
+
+                            let schema = build_join_schema(
+                                optimized_input.schema(),
+                                right_schema,
+                                &join_type,
+                            )?;
+
+                            Ok(LogicalPlan::Join(Join {
+                                left: Arc::new(input),
+                                right: Arc::new(right_input),
+                                on: vec![(left_key, right_key)],
+                                join_type,
+                                join_constraint: JoinConstraint::On,
+                                schema: Arc::new(schema),
+                                null_equals_null: false,
+                            }))
+                        }
+                        _ => Err(DataFusionError::Plan(
+                            "Unknown expression while rewriting subquery to joins"
+                                .to_string(),
+                        )),
+                    }
+                );
+
+                // In case of expressions which could not be rewritten
+                // return original filter with optimized input
+                let new_input = match opt_result {
+                    Ok(plan) => plan,
+                    Err(_) => {
+                        return Ok(LogicalPlan::Filter(Filter {
+                            predicate: predicate.clone(),
+                            input: Arc::new(optimized_input),
+                        }))
+                    }
+                };
+
+                // Apply regular filters to join output if some or just return join
+                if regular_filters.is_empty() {
+                    Ok(new_input)
+                } else {
+                    Ok(utils::add_filter(new_input, &regular_filters))
+                }
+            }
+            _ => {
+                // Apply the optimization to all inputs of the plan
+                utils::optimize_children(self, plan, execution_props)
+            }
+        }
+    }
+
+    fn name(&self) -> &str {
+        "subquery_filter_to_join"
+    }
+}
+
+fn extract_subquery_filters(expression: &Expr, extracted: &mut Vec<Expr>) -> Result<()> {
+    utils::expr_sub_expressions(expression)?
+        .into_iter()
+        .try_for_each(|se| match se {
+            Expr::InSubquery { .. } => {
+                extracted.push(se);
+                Ok(())
+            }
+            _ => extract_subquery_filters(&se, extracted),
+        })
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use crate::logical_plan::{
+        and, binary_expr, col, in_subquery, lit, not_in_subquery, LogicalPlanBuilder,
+        Operator,
+    };
+    use crate::test::*;
+
+    fn assert_optimized_plan_eq(plan: &LogicalPlan, expected: &str) {
+        let rule = SubqueryFilterToJoin::new();
+        let optimized_plan = rule
+            .optimize(plan, &ExecutionProps::new())
+            .expect("failed to optimize plan");
+        let formatted_plan = format!("{}", optimized_plan.display_indent_schema());
+        assert_eq!(formatted_plan, expected);
+    }
+
+    fn test_subquery() -> Result<Arc<LogicalPlan>> {
+        let table_scan = test_table_scan()?;
+        Ok(Arc::new(
+            LogicalPlanBuilder::from(table_scan)
+                .project(vec![col("c")])?
+                .build()?,
+        ))
+    }
+
+    /// Test for single IN subquery filter
+    #[test]
+    fn in_subquery_simple() -> Result<()> {
+        let table_scan = test_table_scan()?;
+        let plan = LogicalPlanBuilder::from(table_scan)
+            .filter(in_subquery(col("c"), test_subquery()?))?
+            .project(vec![col("test.b")])?
+            .build()?;
+
+        let expected = "Projection: #test.b [b:UInt32]\
+        \n  Semi Join: #test.c = #test.c [a:UInt32, b:UInt32, c:UInt32]\
+        \n    TableScan: test projection=None [a:UInt32, b:UInt32, c:UInt32]\
+        \n    Projection: #test.c [c:UInt32]\
+        \n      TableScan: test projection=None [a:UInt32, b:UInt32, c:UInt32]";
+
+        assert_optimized_plan_eq(&plan, expected);
+        Ok(())
+    }
+
+    /// Test for single NOT IN subquery filter
+    #[test]
+    fn not_in_subquery_simple() -> Result<()> {
+        let table_scan = test_table_scan()?;
+        let plan = LogicalPlanBuilder::from(table_scan)
+            .filter(not_in_subquery(col("c"), test_subquery()?))?
+            .project(vec![col("test.b")])?
+            .build()?;
+
+        let expected = "Projection: #test.b [b:UInt32]\
+        \n  Anti Join: #test.c = #test.c [a:UInt32, b:UInt32, c:UInt32]\

Review Comment:
   Done - now table names in tests are different, so it should by much easier to read



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