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/02 20:08:35 UTC

[GitHub] [arrow-datafusion] korowa opened a new pull request, #2421: naive InSubquery implementation

korowa opened a new pull request, #2421:
URL: https://github.com/apache/arrow-datafusion/pull/2421

   # Which issue does this PR close?
   
   <!--
   We generally require a GitHub issue to be filed for all bug fixes and enhancements and this helps us generate change logs for our releases. You can link an issue to this PR using the GitHub syntax. For example `Closes #123` indicates that this PR will close issue #123.
   -->
   
   Partially #488.
   
    # Rationale for this change
   <!--
    Why are you proposing this change? If this is already explained clearly in the issue then this section is not needed.
    Explaining clearly why changes are proposed helps reviewers understand your changes and offer better suggestions for fixes.  
   -->
   
   Naive implementation of optimizer rule for replacing InSubquery with join, which allows to execute queries with IN (subquery) in case of proper WHERE condition.
   
   # What changes are included in this PR?
   <!--
   There is no need to duplicate the description in the issue here but it is sometimes worth providing a summary of the individual changes in this PR.
   -->
   
   SubqueryFilterToJoin rule is able to replace Filter input in logical plan with Sem/AntiJoin in case InSubquery is a part of logical conjunction - this precondition allows to pushdown IN predicate before other predicates in Filter.
   
   Cases when IN (subquery) result cannot be pushed to Filters input and its result required for predicate evaluation, are handled by returning NotImplemented error for now.
   
   # Are there any user-facing changes?
   <!--
   If there are user-facing changes then we may require documentation to be updated before approving the PR.
   -->
   
   Queries with IN (subquery) predicates start executing for described above filter combinations
   
   <!--
   If there are any breaking changes to public APIs, please add the `api change` label.
   -->
   
   No


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


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

Posted by GitBox <gi...@apache.org>.
andygrove commented on code in PR #2421:
URL: https://github.com/apache/arrow-datafusion/pull/2421#discussion_r863203136


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

Review Comment:
   Can we just revert to the original query here 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: github-unsubscribe@arrow.apache.org

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


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

Posted by GitBox <gi...@apache.org>.
korowa commented on code in PR #2421:
URL: https://github.com/apache/arrow-datafusion/pull/2421#discussion_r863818456


##########
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:
   Sure, done



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


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

Posted by GitBox <gi...@apache.org>.
korowa commented on code in PR #2421:
URL: https://github.com/apache/arrow-datafusion/pull/2421#discussion_r863500101


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

Review Comment:
   All fixed. My idea was to give user some explanation about why query is "incorrect" by throwing errors.
   
   Now I see that if DF is able to produce this kind of logical plan, then it's valid (at least for some purposes maybe), even if we don't have physical implementation for some of its parts yet.



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


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

Posted by GitBox <gi...@apache.org>.
korowa commented on code in PR #2421:
URL: https://github.com/apache/arrow-datafusion/pull/2421#discussion_r863819830


##########
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 {
+                            true => JoinType::Anti,
+                            false => JoinType::Semi,
+                        };
+
+                        let schema = build_join_schema(
+                            new_input.schema(),

Review Comment:
   Switched to try_fold, no mutable variables required now



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


[GitHub] [arrow-datafusion] alamb merged pull request #2421: Basic support for `IN` and `NOT IN` Subqueries by rewriting them to `SEMI` / `ANTI`

Posted by GitBox <gi...@apache.org>.
alamb merged PR #2421:
URL: https://github.com/apache/arrow-datafusion/pull/2421


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


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

Posted by GitBox <gi...@apache.org>.
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


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

Posted by GitBox <gi...@apache.org>.
korowa commented on code in PR #2421:
URL: https://github.com/apache/arrow-datafusion/pull/2421#discussion_r864518240


##########
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]\
+        \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 several IN subquery expressions
+    #[test]
+    fn in_subquery_multiple() -> Result<()> {
+        let table_scan = test_table_scan()?;
+        let plan = LogicalPlanBuilder::from(table_scan)
+            .filter(and(
+                in_subquery(col("c"), test_subquery()?),
+                in_subquery(col("b"), test_subquery()?),
+            ))?
+            .project(vec![col("test.b")])?
+            .build()?;
+
+        let expected = "Projection: #test.b [b:UInt32]\
+        \n  Semi Join: #test.b = #test.c [a:UInt32, b:UInt32, c: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]\
+        \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 IN subquery with additional filters
+    #[test]
+    fn in_subquery_with_filters() -> Result<()> {
+        let table_scan = test_table_scan()?;
+        let plan = LogicalPlanBuilder::from(table_scan)
+            .filter(and(
+                in_subquery(col("c"), test_subquery()?),
+                and(
+                    binary_expr(col("a"), Operator::Eq, lit(1_u32)),
+                    binary_expr(col("b"), Operator::Lt, lit(30_u32)),
+                ),
+            ))?
+            .project(vec![col("test.b")])?
+            .build()?;
+
+        let expected = "Projection: #test.b [b:UInt32]\
+        \n  Filter: #test.a = UInt32(1) AND #test.b < UInt32(30) [a:UInt32, b:UInt32, c: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 nested IN subqueries
+    #[test]
+    fn in_subquery_nested() -> Result<()> {
+        let table_scan = test_table_scan()?;
+
+        let subquery = LogicalPlanBuilder::from(table_scan.clone())
+            .filter(in_subquery(col("a"), test_subquery()?))?
+            .project(vec![col("a")])?
+            .build()?;
+
+        let plan = LogicalPlanBuilder::from(table_scan)
+            .filter(in_subquery(col("b"), Arc::new(subquery)))?
+            .project(vec![col("test.b")])?
+            .build()?;
+
+        let expected = "Projection: #test.b [b:UInt32]\
+        \n  Semi Join: #test.b = #test.a [a:UInt32, b:UInt32, c:UInt32]\
+        \n    TableScan: test projection=None [a:UInt32, b:UInt32, c:UInt32]\
+        \n    Projection: #test.a [a:UInt32]\
+        \n      Semi Join: #test.a = #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(())
+    }
+}

Review Comment:
   Added cases for most complex expression and for filter input being rewritten while filter remains untouched (checks that falling back to original query doesn't affect its recursive call results)



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


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

Posted by GitBox <gi...@apache.org>.
korowa commented on code in PR #2421:
URL: https://github.com/apache/arrow-datafusion/pull/2421#discussion_r864518240


##########
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]\
+        \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 several IN subquery expressions
+    #[test]
+    fn in_subquery_multiple() -> Result<()> {
+        let table_scan = test_table_scan()?;
+        let plan = LogicalPlanBuilder::from(table_scan)
+            .filter(and(
+                in_subquery(col("c"), test_subquery()?),
+                in_subquery(col("b"), test_subquery()?),
+            ))?
+            .project(vec![col("test.b")])?
+            .build()?;
+
+        let expected = "Projection: #test.b [b:UInt32]\
+        \n  Semi Join: #test.b = #test.c [a:UInt32, b:UInt32, c: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]\
+        \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 IN subquery with additional filters
+    #[test]
+    fn in_subquery_with_filters() -> Result<()> {
+        let table_scan = test_table_scan()?;
+        let plan = LogicalPlanBuilder::from(table_scan)
+            .filter(and(
+                in_subquery(col("c"), test_subquery()?),
+                and(
+                    binary_expr(col("a"), Operator::Eq, lit(1_u32)),
+                    binary_expr(col("b"), Operator::Lt, lit(30_u32)),
+                ),
+            ))?
+            .project(vec![col("test.b")])?
+            .build()?;
+
+        let expected = "Projection: #test.b [b:UInt32]\
+        \n  Filter: #test.a = UInt32(1) AND #test.b < UInt32(30) [a:UInt32, b:UInt32, c: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 nested IN subqueries
+    #[test]
+    fn in_subquery_nested() -> Result<()> {
+        let table_scan = test_table_scan()?;
+
+        let subquery = LogicalPlanBuilder::from(table_scan.clone())
+            .filter(in_subquery(col("a"), test_subquery()?))?
+            .project(vec![col("a")])?
+            .build()?;
+
+        let plan = LogicalPlanBuilder::from(table_scan)
+            .filter(in_subquery(col("b"), Arc::new(subquery)))?
+            .project(vec![col("test.b")])?
+            .build()?;
+
+        let expected = "Projection: #test.b [b:UInt32]\
+        \n  Semi Join: #test.b = #test.a [a:UInt32, b:UInt32, c:UInt32]\
+        \n    TableScan: test projection=None [a:UInt32, b:UInt32, c:UInt32]\
+        \n    Projection: #test.a [a:UInt32]\
+        \n      Semi Join: #test.a = #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(())
+    }
+}

Review Comment:
   Added cases for unsupported filter expression and for filters input being rewritten while filter remains untouched (checks that falling back to original query doesn't affect its recursive call results)



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


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

Posted by GitBox <gi...@apache.org>.
Dandandan commented on code in PR #2421:
URL: https://github.com/apache/arrow-datafusion/pull/2421#discussion_r863703647


##########
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 {
+                            true => JoinType::Anti,
+                            false => JoinType::Semi,
+                        };
+
+                        let schema = build_join_schema(
+                            new_input.schema(),

Review Comment:
   Better to use `optimized_input.schema()` and avoid creating a `mut`



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


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

Posted by GitBox <gi...@apache.org>.
alamb commented on code in PR #2421:
URL: https://github.com/apache/arrow-datafusion/pull/2421#discussion_r864852539


##########
datafusion/core/src/optimizer/subquery_filter_to_join.rs:
##########
@@ -220,15 +220,15 @@ mod tests {
     fn in_subquery_simple() -> Result<()> {
         let table_scan = test_table_scan()?;
         let plan = LogicalPlanBuilder::from(table_scan)
-            .filter(in_subquery(col("c"), test_subquery()?))?
+            .filter(in_subquery(col("c"), test_subquery_with_name("sq")?))?
             .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  Semi Join: #test.c = #sq.c [a:UInt32, b:UInt32, c:UInt32]\

Review Comment:
   much easier to read -- thank you



##########
datafusion/core/src/optimizer/subquery_filter_to_join.rs:
##########
@@ -320,13 +346,42 @@ mod tests {
             .build()?;
 
         let expected = "Projection: #test.b [b:UInt32]\
-        \n  Semi Join: #test.b = #test.a [a:UInt32, b:UInt32, c:UInt32]\
+        \n  Semi Join: #test.b = #sq.a [a:UInt32, b:UInt32, c:UInt32]\
         \n    TableScan: test projection=None [a:UInt32, b:UInt32, c:UInt32]\
-        \n    Projection: #test.a [a:UInt32]\
-        \n      Semi Join: #test.a = #test.c [a:UInt32, b:UInt32, c:UInt32]\
+        \n    Projection: #sq.a [a:UInt32]\
+        \n      Semi Join: #sq.a = #sq_nested.c [a:UInt32, b:UInt32, c:UInt32]\
+        \n        TableScan: sq projection=None [a:UInt32, b:UInt32, c:UInt32]\
+        \n        Projection: #sq_nested.c [c:UInt32]\
+        \n          TableScan: sq_nested projection=None [a:UInt32, b:UInt32, c:UInt32]";
+
+        assert_optimized_plan_eq(&plan, expected);
+        Ok(())
+    }
+
+    /// Test for filter input modification in case filter not supported
+    /// Outer filter expression not modified while inner converted to join

Review Comment:
   👍 



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


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

Posted by GitBox <gi...@apache.org>.
andygrove commented on code in PR #2421:
URL: https://github.com/apache/arrow-datafusion/pull/2421#discussion_r863203672


##########
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(
+                                "Filtering by expression not implemented for InSubquery"
+                                    .to_string(),
+                            )),
+                        };
+
+                        let join_type = match negated {
+                            true => JoinType::Anti,
+                            false => JoinType::Semi,
+                        };
+
+                        let schema = build_join_schema(
+                            new_input.schema(),
+                            right_schema,
+                            &join_type,
+                        )?;
+
+                        new_input = LogicalPlan::Join(Join {
+                            left: Arc::new(new_input.clone()),
+                            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,
+                        });
+
+                        Ok(())
+                    }
+                    _ => Err(DataFusionError::Plan(
+                        "Unknown expression while rewriting subquery to joins"

Review Comment:
   Same comment 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


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

Posted by GitBox <gi...@apache.org>.
korowa commented on code in PR #2421:
URL: https://github.com/apache/arrow-datafusion/pull/2421#discussion_r864518240


##########
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]\
+        \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 several IN subquery expressions
+    #[test]
+    fn in_subquery_multiple() -> Result<()> {
+        let table_scan = test_table_scan()?;
+        let plan = LogicalPlanBuilder::from(table_scan)
+            .filter(and(
+                in_subquery(col("c"), test_subquery()?),
+                in_subquery(col("b"), test_subquery()?),
+            ))?
+            .project(vec![col("test.b")])?
+            .build()?;
+
+        let expected = "Projection: #test.b [b:UInt32]\
+        \n  Semi Join: #test.b = #test.c [a:UInt32, b:UInt32, c: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]\
+        \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 IN subquery with additional filters
+    #[test]
+    fn in_subquery_with_filters() -> Result<()> {
+        let table_scan = test_table_scan()?;
+        let plan = LogicalPlanBuilder::from(table_scan)
+            .filter(and(
+                in_subquery(col("c"), test_subquery()?),
+                and(
+                    binary_expr(col("a"), Operator::Eq, lit(1_u32)),
+                    binary_expr(col("b"), Operator::Lt, lit(30_u32)),
+                ),
+            ))?
+            .project(vec![col("test.b")])?
+            .build()?;
+
+        let expected = "Projection: #test.b [b:UInt32]\
+        \n  Filter: #test.a = UInt32(1) AND #test.b < UInt32(30) [a:UInt32, b:UInt32, c: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 nested IN subqueries
+    #[test]
+    fn in_subquery_nested() -> Result<()> {
+        let table_scan = test_table_scan()?;
+
+        let subquery = LogicalPlanBuilder::from(table_scan.clone())
+            .filter(in_subquery(col("a"), test_subquery()?))?
+            .project(vec![col("a")])?
+            .build()?;
+
+        let plan = LogicalPlanBuilder::from(table_scan)
+            .filter(in_subquery(col("b"), Arc::new(subquery)))?
+            .project(vec![col("test.b")])?
+            .build()?;
+
+        let expected = "Projection: #test.b [b:UInt32]\
+        \n  Semi Join: #test.b = #test.a [a:UInt32, b:UInt32, c:UInt32]\
+        \n    TableScan: test projection=None [a:UInt32, b:UInt32, c:UInt32]\
+        \n    Projection: #test.a [a:UInt32]\
+        \n      Semi Join: #test.a = #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(())
+    }
+}

Review Comment:
   Added cases for most complex expression and for filter input being rewritten while filter remains untouched (check if falling back to original query doesn't affect its recursive call results)



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


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

Posted by GitBox <gi...@apache.org>.
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


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

Posted by GitBox <gi...@apache.org>.
korowa commented on code in PR #2421:
URL: https://github.com/apache/arrow-datafusion/pull/2421#discussion_r863500183


##########
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:
   Also fixed



##########
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(
+                                "Filtering by expression not implemented for InSubquery"
+                                    .to_string(),
+                            )),
+                        };
+
+                        let join_type = match negated {
+                            true => JoinType::Anti,
+                            false => JoinType::Semi,
+                        };
+
+                        let schema = build_join_schema(
+                            new_input.schema(),
+                            right_schema,
+                            &join_type,
+                        )?;
+
+                        new_input = LogicalPlan::Join(Join {
+                            left: Arc::new(new_input.clone()),
+                            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,
+                        });
+
+                        Ok(())
+                    }
+                    _ => Err(DataFusionError::Plan(
+                        "Unknown expression while rewriting subquery to joins"

Review Comment:
   Also fixed



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


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

Posted by GitBox <gi...@apache.org>.
korowa commented on code in PR #2421:
URL: https://github.com/apache/arrow-datafusion/pull/2421#discussion_r863836243


##########
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 {
+                            true => JoinType::Anti,
+                            false => JoinType::Semi,
+                        };
+
+                        let schema = build_join_schema(
+                            new_input.schema(),
+                            right_schema,
+                            &join_type,
+                        )?;
+
+                        new_input = LogicalPlan::Join(Join {
+                            left: Arc::new(new_input.clone()),
+                            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,
+                        });
+
+                        Ok(())

Review Comment:
   Now folding



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


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

Posted by GitBox <gi...@apache.org>.
korowa commented on code in PR #2421:
URL: https://github.com/apache/arrow-datafusion/pull/2421#discussion_r864518240


##########
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]\
+        \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 several IN subquery expressions
+    #[test]
+    fn in_subquery_multiple() -> Result<()> {
+        let table_scan = test_table_scan()?;
+        let plan = LogicalPlanBuilder::from(table_scan)
+            .filter(and(
+                in_subquery(col("c"), test_subquery()?),
+                in_subquery(col("b"), test_subquery()?),
+            ))?
+            .project(vec![col("test.b")])?
+            .build()?;
+
+        let expected = "Projection: #test.b [b:UInt32]\
+        \n  Semi Join: #test.b = #test.c [a:UInt32, b:UInt32, c: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]\
+        \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 IN subquery with additional filters
+    #[test]
+    fn in_subquery_with_filters() -> Result<()> {
+        let table_scan = test_table_scan()?;
+        let plan = LogicalPlanBuilder::from(table_scan)
+            .filter(and(
+                in_subquery(col("c"), test_subquery()?),
+                and(
+                    binary_expr(col("a"), Operator::Eq, lit(1_u32)),
+                    binary_expr(col("b"), Operator::Lt, lit(30_u32)),
+                ),
+            ))?
+            .project(vec![col("test.b")])?
+            .build()?;
+
+        let expected = "Projection: #test.b [b:UInt32]\
+        \n  Filter: #test.a = UInt32(1) AND #test.b < UInt32(30) [a:UInt32, b:UInt32, c: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 nested IN subqueries
+    #[test]
+    fn in_subquery_nested() -> Result<()> {
+        let table_scan = test_table_scan()?;
+
+        let subquery = LogicalPlanBuilder::from(table_scan.clone())
+            .filter(in_subquery(col("a"), test_subquery()?))?
+            .project(vec![col("a")])?
+            .build()?;
+
+        let plan = LogicalPlanBuilder::from(table_scan)
+            .filter(in_subquery(col("b"), Arc::new(subquery)))?
+            .project(vec![col("test.b")])?
+            .build()?;
+
+        let expected = "Projection: #test.b [b:UInt32]\
+        \n  Semi Join: #test.b = #test.a [a:UInt32, b:UInt32, c:UInt32]\
+        \n    TableScan: test projection=None [a:UInt32, b:UInt32, c:UInt32]\
+        \n    Projection: #test.a [a:UInt32]\
+        \n      Semi Join: #test.a = #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(())
+    }
+}

Review Comment:
   Added cases for most complex expression and for filter input being rewritten while filter remains untouched (checks if falling back to original query doesn't affect its recursive call results)



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


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

Posted by GitBox <gi...@apache.org>.
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: github-unsubscribe@arrow.apache.org

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


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

Posted by GitBox <gi...@apache.org>.
Dandandan commented on code in PR #2421:
URL: https://github.com/apache/arrow-datafusion/pull/2421#discussion_r863703877


##########
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 {
+                            true => JoinType::Anti,
+                            false => JoinType::Semi,
+                        };
+
+                        let schema = build_join_schema(
+                            new_input.schema(),
+                            right_schema,
+                            &join_type,
+                        )?;
+
+                        new_input = LogicalPlan::Join(Join {
+                            left: Arc::new(new_input.clone()),
+                            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,
+                        });
+
+                        Ok(())

Review Comment:
   and return result here to use below



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


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

Posted by GitBox <gi...@apache.org>.
alamb commented on code in PR #2421:
URL: https://github.com/apache/arrow-datafusion/pull/2421#discussion_r864404088


##########
benchmarks/src/bin/tpch.rs:
##########
@@ -1074,6 +1074,16 @@ mod tests {
         run_query(14).await
     }
 
+    #[tokio::test]

Review Comment:
   🎉 



##########
datafusion/core/src/optimizer/filter_push_down.rs:
##########
@@ -305,7 +267,7 @@ fn optimize(plan: &LogicalPlan, mut state: State) -> Result<LogicalPlan> {
         LogicalPlan::Analyze { .. } => push_down(&state, plan),
         LogicalPlan::Filter(Filter { input, predicate }) => {
             let mut predicates = vec![];
-            split_members(predicate, &mut predicates);
+            utils::split_conjunction(predicate, &mut predicates);

Review Comment:
   👍 



##########
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:
   I can't tell from this plan if the predicate is correct (because `#test` is used as the relation name in both the inner and outer query. 
   
   It might make these tests more readable if the relation name in the subquery was something different (like `test_sq`) so that this join predicate appears as `#test.c = #sq_ test.c`



##########
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]\
+        \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 several IN subquery expressions
+    #[test]
+    fn in_subquery_multiple() -> Result<()> {
+        let table_scan = test_table_scan()?;
+        let plan = LogicalPlanBuilder::from(table_scan)
+            .filter(and(
+                in_subquery(col("c"), test_subquery()?),
+                in_subquery(col("b"), test_subquery()?),
+            ))?
+            .project(vec![col("test.b")])?
+            .build()?;
+
+        let expected = "Projection: #test.b [b:UInt32]\
+        \n  Semi Join: #test.b = #test.c [a:UInt32, b:UInt32, c: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]\
+        \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 IN subquery with additional filters
+    #[test]
+    fn in_subquery_with_filters() -> Result<()> {
+        let table_scan = test_table_scan()?;
+        let plan = LogicalPlanBuilder::from(table_scan)
+            .filter(and(
+                in_subquery(col("c"), test_subquery()?),
+                and(
+                    binary_expr(col("a"), Operator::Eq, lit(1_u32)),
+                    binary_expr(col("b"), Operator::Lt, lit(30_u32)),
+                ),
+            ))?
+            .project(vec![col("test.b")])?
+            .build()?;
+
+        let expected = "Projection: #test.b [b:UInt32]\
+        \n  Filter: #test.a = UInt32(1) AND #test.b < UInt32(30) [a:UInt32, b:UInt32, c: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 nested IN subqueries
+    #[test]
+    fn in_subquery_nested() -> Result<()> {
+        let table_scan = test_table_scan()?;
+
+        let subquery = LogicalPlanBuilder::from(table_scan.clone())
+            .filter(in_subquery(col("a"), test_subquery()?))?
+            .project(vec![col("a")])?
+            .build()?;
+
+        let plan = LogicalPlanBuilder::from(table_scan)
+            .filter(in_subquery(col("b"), Arc::new(subquery)))?
+            .project(vec![col("test.b")])?
+            .build()?;
+
+        let expected = "Projection: #test.b [b:UInt32]\
+        \n  Semi Join: #test.b = #test.a [a:UInt32, b:UInt32, c:UInt32]\

Review Comment:
   👍 



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

Review Comment:
   👍 



##########
datafusion/core/src/optimizer/utils.rs:
##########
@@ -556,6 +556,41 @@ pub fn rewrite_expression(expr: &Expr, expressions: &[Expr]) -> Result<Expr> {
     }
 }
 
+/// converts "A AND B AND C" => [A, B, C]

Review Comment:
   👍  for moving these functions into `utils`



##########
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]\
+        \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 several IN subquery expressions
+    #[test]
+    fn in_subquery_multiple() -> Result<()> {
+        let table_scan = test_table_scan()?;
+        let plan = LogicalPlanBuilder::from(table_scan)
+            .filter(and(
+                in_subquery(col("c"), test_subquery()?),
+                in_subquery(col("b"), test_subquery()?),
+            ))?
+            .project(vec![col("test.b")])?
+            .build()?;
+
+        let expected = "Projection: #test.b [b:UInt32]\
+        \n  Semi Join: #test.b = #test.c [a:UInt32, b:UInt32, c: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]\
+        \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 IN subquery with additional filters
+    #[test]
+    fn in_subquery_with_filters() -> Result<()> {
+        let table_scan = test_table_scan()?;
+        let plan = LogicalPlanBuilder::from(table_scan)
+            .filter(and(
+                in_subquery(col("c"), test_subquery()?),
+                and(
+                    binary_expr(col("a"), Operator::Eq, lit(1_u32)),
+                    binary_expr(col("b"), Operator::Lt, lit(30_u32)),
+                ),
+            ))?
+            .project(vec![col("test.b")])?
+            .build()?;
+
+        let expected = "Projection: #test.b [b:UInt32]\
+        \n  Filter: #test.a = UInt32(1) AND #test.b < UInt32(30) [a:UInt32, b:UInt32, c: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 nested IN subqueries
+    #[test]
+    fn in_subquery_nested() -> Result<()> {
+        let table_scan = test_table_scan()?;
+
+        let subquery = LogicalPlanBuilder::from(table_scan.clone())
+            .filter(in_subquery(col("a"), test_subquery()?))?
+            .project(vec![col("a")])?
+            .build()?;
+
+        let plan = LogicalPlanBuilder::from(table_scan)
+            .filter(in_subquery(col("b"), Arc::new(subquery)))?
+            .project(vec![col("test.b")])?
+            .build()?;
+
+        let expected = "Projection: #test.b [b:UInt32]\
+        \n  Semi Join: #test.b = #test.a [a:UInt32, b:UInt32, c:UInt32]\
+        \n    TableScan: test projection=None [a:UInt32, b:UInt32, c:UInt32]\
+        \n    Projection: #test.a [a:UInt32]\
+        \n      Semi Join: #test.a = #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(())
+    }
+}

Review Comment:
   I think it would also be helpful to coverage of the negative cases (aka cases that can't be rewritten like `x IN (select ...) OR y = 5`?



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


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

Posted by GitBox <gi...@apache.org>.
korowa commented on PR #2421:
URL: https://github.com/apache/arrow-datafusion/pull/2421#issuecomment-1117352763

   Thanks for reviews! I hope I'll follow up with PR(s?) for currently unsupported cases soon.


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