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/11/13 06:01:36 UTC

[GitHub] [arrow-datafusion] jackwener opened a new pull request, #4192: add propagate_empty_relation

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

   # Which issue does this PR close?
   Closes #3864.
   
   We can propagate `empty_relation` to eliminate useless plan.
   ```sql
   | logical_plan after eliminate_filter                        | Projection: t1.column1                        |
   |                                                            |   Inner Join: t1.column1 = ta1.column1        |
   |                                                            |     TableScan: t1                             |
   |                                                            |     Projection: ta1.column1, alias=ta1        |
   |                                                            |       Projection: t2.column1, alias=ta1       |
   |                                                            |         Inner Join: t2.column1 = ta2.column1  |
   |                                                            |           TableScan: t2                       |
   |                                                            |           Projection: ta2.column1, alias=ta2  |
   |                                                            |             Projection: t3.column1, alias=ta2 |
   |                                                            |               EmptyRelation                   |
   | logical_plan after eliminate_limit                         | EmptyRelation                                 |
   ```
   
   # Rationale for this change
   
   # What changes are included in this PR?
   
   
   # Are these changes tested?
   
   
   # Are there any user-facing changes?
   
   <!--
   If there are user-facing changes then we may require documentation to be updated before approving the PR.
   -->
   
   <!--
   If there are any breaking changes to public APIs, please add the `api change` label.
   -->


-- 
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] mingmwang commented on a diff in pull request #4192: add `propagate_empty_relation` optimizer rule

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


##########
datafusion/optimizer/src/propagate_empty_relation.rs:
##########
@@ -0,0 +1,331 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use datafusion_common::{DataFusionError, Result};
+use datafusion_expr::logical_plan::LogicalPlan;
+use datafusion_expr::{EmptyRelation, JoinType, Projection};
+use std::sync::Arc;
+
+use crate::{utils, OptimizerConfig, OptimizerRule};
+
+/// Optimization rule that bottom-up to eliminate plan by propagating empty_relation.
+#[derive(Default)]
+pub struct PropagateEmptyRelation;
+
+impl PropagateEmptyRelation {
+    #[allow(missing_docs)]
+    pub fn new() -> Self {
+        Self {}
+    }
+}
+
+impl OptimizerRule for PropagateEmptyRelation {
+    fn optimize(
+        &self,
+        plan: &LogicalPlan,
+        optimizer_config: &mut OptimizerConfig,
+    ) -> Result<LogicalPlan> {
+        // optimize child plans first
+        let optimized_children_plan =
+            utils::optimize_children(self, plan, optimizer_config)?;
+        match &optimized_children_plan {
+            LogicalPlan::EmptyRelation(_) => Ok(optimized_children_plan),
+            LogicalPlan::Projection(_)
+            | LogicalPlan::Filter(_)
+            | LogicalPlan::Window(_)
+            | LogicalPlan::Sort(_)
+            | LogicalPlan::SubqueryAlias(_)
+            | LogicalPlan::Repartition(_)
+            | LogicalPlan::Limit(_) => match empty_child(&optimized_children_plan)? {
+                Some(empty) => Ok(empty),
+                None => Ok(optimized_children_plan),
+            },
+            LogicalPlan::CrossJoin(_) => {
+                let (left_empty, right_empty) = binary_plan_children_is_empty(plan)?;
+                if left_empty || right_empty {
+                    Ok(LogicalPlan::EmptyRelation(EmptyRelation {
+                        produce_one_row: false,
+                        schema: plan.schema().clone(),
+                    }))
+                } else {
+                    Ok(optimized_children_plan)
+                }
+            }
+            LogicalPlan::Join(join) => {
+                // TODO: For Join, more join type need to be careful:
+                // For LeftOuter/LeftSemi/LeftAnti Join, only the left side is empty, the Join result is empty.
+                // For LeftSemi Join, if the right side is empty, the Join result is empty.
+                // For LeftAnti Join, if the right side is empty, the Join result is left side(should exclude null ??).
+                // For RightOuter/RightSemi/RightAnti Join, only the right side is empty, the Join result is empty.
+                // For RightSemi Join, if the left side is empty, the Join result is empty.
+                // For RightAnti Join, if the left side is empty, the Join result is right side(should exclude null ??).
+                // For Full Join, only both sides are empty, the Join result is empty.
+                // For LeftOut/Full Join, if the right side is empty, the Join can be eliminated with a Projection with left side
+                // columns + right side columns replaced with null values.
+                // For RightOut/Full Join, if the left side is empty, the Join can be eliminated with a Projection with right side
+                // columns + left side columns replaced with null values.
+                if join.join_type == JoinType::Inner {
+                    let (left_empty, right_empty) = binary_plan_children_is_empty(plan)?;
+                    if left_empty || right_empty {
+                        Ok(LogicalPlan::EmptyRelation(EmptyRelation {
+                            produce_one_row: false,
+                            schema: plan.schema().clone(),
+                        }))
+                    } else {
+                        Ok(optimized_children_plan)
+                    }
+                } else {
+                    Ok(optimized_children_plan)
+                }
+            }
+            LogicalPlan::Union(union) => {
+                let (left_empty, right_empty) = binary_plan_children_is_empty(plan)?;
+                if left_empty && right_empty {

Review Comment:
   I'm not sure whether DataFusion's Union is binary or can have more than 2 inputs.



-- 
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] mingmwang commented on a diff in pull request #4192: add `propagate_empty_relation` optimizer rule

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


##########
datafusion/expr/src/logical_plan/plan.rs:
##########
@@ -1145,6 +1145,22 @@ impl Projection {
         })
     }
 
+    /// Create a new Projection using the specified output schema
+    pub fn new_from_schema(input: Arc<LogicalPlan>, schema: DFSchemaRef) -> Self {
+        let expr: Vec<Expr> = schema
+            .fields()
+            .iter()
+            .map(|field| field.qualified_column())
+            .map(Expr::Column)
+            .collect();
+        Self {
+            expr,
+            input,
+            schema,
+            alias: None,
+        }
+    }

Review Comment:
   > Your concerns are justified, fix it.
   > 
   > I noticed it before, but I forgot when I was writing the code
   > 
   > BTW, I think we should add alias in Union, how do you think it? We should remove union alias, and replace with projection. @mingmwang
   
   I think the Alias in Datafusion Union/Projection is more like the SubqueryAlias in SparkSQL, it is not the Column level Alias Expr. If the original Union has the alias, you can keep the alias in the Union and no need to move alias from Union to Projection.  But if the Union is eliminated(only 1 input), we should keep the Alias in Projection.  
   I think besides checking the Union Alias, you also need to check whether we should add additional Alias in new projection exprs.
   
   ````
   let new_plan = {
   new children len ==  1  and there is alias in original Union: 
       Projection(child, alias)
   new children  len ==  1 input and no alias in original Union
       child
   new children len > 1
      let new_union_schema = from_new_children(new_children)
       Union(new_children, new_union_schema, union.alias);
   }
   
   if new_plan.schema != union.schema {
     // Add new projection for column level Alias maybe
   }
   ````
   



-- 
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] jackwener commented on a diff in pull request #4192: add `propagate_empty_relation` optimizer rule

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


##########
datafusion/optimizer/src/propagate_empty_relation.rs:
##########
@@ -0,0 +1,331 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use datafusion_common::{DataFusionError, Result};
+use datafusion_expr::logical_plan::LogicalPlan;
+use datafusion_expr::{EmptyRelation, JoinType, Projection};
+use std::sync::Arc;
+
+use crate::{utils, OptimizerConfig, OptimizerRule};
+
+/// Optimization rule that bottom-up to eliminate plan by propagating empty_relation.
+#[derive(Default)]
+pub struct PropagateEmptyRelation;
+
+impl PropagateEmptyRelation {
+    #[allow(missing_docs)]
+    pub fn new() -> Self {
+        Self {}
+    }
+}
+
+impl OptimizerRule for PropagateEmptyRelation {
+    fn optimize(
+        &self,
+        plan: &LogicalPlan,
+        optimizer_config: &mut OptimizerConfig,
+    ) -> Result<LogicalPlan> {
+        // optimize child plans first
+        let optimized_children_plan =
+            utils::optimize_children(self, plan, optimizer_config)?;
+        match &optimized_children_plan {
+            LogicalPlan::EmptyRelation(_) => Ok(optimized_children_plan),
+            LogicalPlan::Projection(_)
+            | LogicalPlan::Filter(_)
+            | LogicalPlan::Window(_)
+            | LogicalPlan::Sort(_)
+            | LogicalPlan::SubqueryAlias(_)
+            | LogicalPlan::Repartition(_)
+            | LogicalPlan::Limit(_) => match empty_child(&optimized_children_plan)? {
+                Some(empty) => Ok(empty),
+                None => Ok(optimized_children_plan),
+            },
+            LogicalPlan::CrossJoin(_) => {
+                let (left_empty, right_empty) = binary_plan_children_is_empty(plan)?;
+                if left_empty || right_empty {
+                    Ok(LogicalPlan::EmptyRelation(EmptyRelation {
+                        produce_one_row: false,
+                        schema: plan.schema().clone(),
+                    }))
+                } else {
+                    Ok(optimized_children_plan)
+                }
+            }
+            LogicalPlan::Join(join) => {
+                // TODO: For Join, more join type need to be careful:
+                // For LeftOuter/LeftSemi/LeftAnti Join, only the left side is empty, the Join result is empty.
+                // For LeftSemi Join, if the right side is empty, the Join result is empty.
+                // For LeftAnti Join, if the right side is empty, the Join result is left side(should exclude null ??).
+                // For RightOuter/RightSemi/RightAnti Join, only the right side is empty, the Join result is empty.
+                // For RightSemi Join, if the left side is empty, the Join result is empty.
+                // For RightAnti Join, if the left side is empty, the Join result is right side(should exclude null ??).
+                // For Full Join, only both sides are empty, the Join result is empty.
+                // For LeftOut/Full Join, if the right side is empty, the Join can be eliminated with a Projection with left side
+                // columns + right side columns replaced with null values.
+                // For RightOut/Full Join, if the left side is empty, the Join can be eliminated with a Projection with right side
+                // columns + left side columns replaced with null values.
+                if join.join_type == JoinType::Inner {
+                    let (left_empty, right_empty) = binary_plan_children_is_empty(plan)?;
+                    if left_empty || right_empty {
+                        Ok(LogicalPlan::EmptyRelation(EmptyRelation {
+                            produce_one_row: false,
+                            schema: plan.schema().clone(),
+                        }))
+                    } else {
+                        Ok(optimized_children_plan)
+                    }
+                } else {
+                    Ok(optimized_children_plan)
+                }
+            }
+            LogicalPlan::Union(union) => {
+                let (left_empty, right_empty) = binary_plan_children_is_empty(plan)?;
+                if left_empty && right_empty {
+                    Ok(LogicalPlan::EmptyRelation(EmptyRelation {
+                        produce_one_row: false,
+                        schema: plan.schema().clone(),
+                    }))
+                } else if !left_empty && right_empty {
+                    Ok(LogicalPlan::Projection(Projection::new_from_schema(
+                        Arc::new((**(union.inputs.get(0).unwrap())).clone()),
+                        plan.schema().clone(),
+                    )))
+                } else if left_empty && !right_empty {
+                    Ok(LogicalPlan::Projection(Projection::new_from_schema(
+                        Arc::new((**(union.inputs.get(1).unwrap())).clone()),
+                        plan.schema().clone(),
+                    )))
+                } else {
+                    Ok(optimized_children_plan)
+                }
+            }
+            LogicalPlan::Aggregate(agg) => {
+                if !agg.group_expr.is_empty() {
+                    match empty_child(&optimized_children_plan)? {
+                        Some(empty) => Ok(empty),
+                        None => Ok(optimized_children_plan),
+                    }
+                } else {
+                    Ok(optimized_children_plan)
+                }
+            }
+            _ => Ok(optimized_children_plan),
+        }
+    }
+
+    fn name(&self) -> &str {
+        "propagate_empty_relation"
+    }
+}
+
+fn binary_plan_children_is_empty(plan: &LogicalPlan) -> Result<(bool, bool)> {
+    let inputs = plan.inputs();
+
+    // all binary-plan need to deal with separately.
+    match inputs.len() {
+        2 => {
+            let left = inputs.get(0).unwrap();
+            let right = inputs.get(1).unwrap();
+
+            let left_empty = match left {
+                LogicalPlan::EmptyRelation(empty) => !empty.produce_one_row,
+                _ => false,
+            };
+            let right_empty = match right {
+                LogicalPlan::EmptyRelation(empty) => !empty.produce_one_row,
+                _ => false,
+            };
+            Ok((left_empty, right_empty))
+        }
+        _ => Err(DataFusionError::Plan(
+            "plan just can have two child".to_string(),
+        )),
+    }
+}
+
+fn empty_child(plan: &LogicalPlan) -> Result<Option<LogicalPlan>> {
+    let inputs = plan.inputs();
+
+    // all binary-plan need to deal with separately.
+    match inputs.len() {
+        1 => {
+            let input = inputs.get(0).unwrap();
+            match input {
+                LogicalPlan::EmptyRelation(empty) => {
+                    if !empty.produce_one_row {
+                        Ok(Some(LogicalPlan::EmptyRelation(EmptyRelation {
+                            produce_one_row: false,
+                            schema: plan.schema().clone(),
+                        })))
+                    } else {
+                        Ok(None)
+                    }
+                }
+                _ => Ok(None),
+            }
+        }
+        _ => Err(DataFusionError::Plan(
+            "plan just can have one child".to_string(),
+        )),
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use crate::eliminate_filter::EliminateFilter;
+    use crate::test::{test_table_scan, test_table_scan_with_name};
+    use datafusion_common::{Column, ScalarValue};
+    use datafusion_expr::{
+        binary_expr, col, lit, logical_plan::builder::LogicalPlanBuilder, Expr, JoinType,
+        Operator,
+    };
+
+    use super::*;
+
+    fn assert_optimized_plan_eq(plan: &LogicalPlan, expected: &str) {
+        let rule = PropagateEmptyRelation::new();
+        let optimized_plan = rule
+            .optimize(plan, &mut OptimizerConfig::new())
+            .expect("failed to optimize plan");
+        let formatted_plan = format!("{:?}", optimized_plan);
+        assert_eq!(formatted_plan, expected);
+        assert_eq!(plan.schema(), optimized_plan.schema());
+    }
+
+    fn assert_together_optimized_plan_eq(plan: &LogicalPlan, expected: &str) {
+        let optimize_one = EliminateFilter::new()
+            .optimize(plan, &mut OptimizerConfig::new())
+            .expect("failed to optimize plan");
+        let optimize_two = PropagateEmptyRelation::new()
+            .optimize(&optimize_one, &mut OptimizerConfig::new())
+            .expect("failed to optimize plan");
+        let formatted_plan = format!("{:?}", optimize_two);
+        assert_eq!(formatted_plan, expected);
+        assert_eq!(plan.schema(), optimize_two.schema());
+    }
+
+    #[test]
+    fn propagate_empty() -> Result<()> {
+        let plan = LogicalPlanBuilder::empty(false)
+            .filter(Expr::Literal(ScalarValue::Boolean(Some(true))))?
+            .limit(10, None)?
+            .project(vec![binary_expr(lit(1), Operator::Plus, lit(1))])?
+            .build()?;
+
+        let expected = "EmptyRelation";
+        assert_optimized_plan_eq(&plan, expected);
+
+        Ok(())
+    }
+
+    #[test]
+    fn propagate_union_right_empty() -> Result<()> {
+        let table_scan = test_table_scan()?;
+        let left = LogicalPlanBuilder::from(table_scan).build()?;
+        let right_table_scan = test_table_scan_with_name("test2")?;
+        let right = LogicalPlanBuilder::from(right_table_scan)
+            .filter(Expr::Literal(ScalarValue::Boolean(Some(false))))?
+            .build()?;
+
+        let plan = LogicalPlanBuilder::from(left).union(right)?.build()?;
+
+        let expected = "Projection: a, b, c\
+            \n  TableScan: test";
+        assert_together_optimized_plan_eq(&plan, expected);
+
+        Ok(())
+    }
+
+    #[test]
+    fn propagate_union_left_empty() -> Result<()> {
+        let table_scan = test_table_scan()?;
+        let left = LogicalPlanBuilder::from(table_scan)
+            .filter(Expr::Literal(ScalarValue::Boolean(Some(false))))?
+            .build()?;
+        let right_table_scan = test_table_scan_with_name("test2")?;
+        let right = LogicalPlanBuilder::from(right_table_scan).build()?;
+
+        let plan = LogicalPlanBuilder::from(left).union(right)?.build()?;
+
+        let expected = "Projection: a, b, c\
+            \n  TableScan: test2";
+        assert_together_optimized_plan_eq(&plan, expected);
+
+        Ok(())
+    }
+

Review Comment:
   have added it.



-- 
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] mingmwang commented on pull request #4192: add `propagate_empty_relation` optimizer rule

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

   Thank you so much @jackwener. Overall, the PR LGTM. 


-- 
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] mingmwang commented on a diff in pull request #4192: add `propagate_empty_relation` optimizer rule

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


##########
datafusion/optimizer/src/propagate_empty_relation.rs:
##########
@@ -0,0 +1,178 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use datafusion_common::Result;
+use datafusion_expr::logical_plan::LogicalPlan;
+use datafusion_expr::EmptyRelation;
+
+use crate::{utils, OptimizerConfig, OptimizerRule};
+
+/// Optimization rule that bottom-up to eliminate plan by propagating empty_relation.
+#[derive(Default)]
+pub struct PropagateEmptyRelation;
+
+impl PropagateEmptyRelation {
+    #[allow(missing_docs)]
+    pub fn new() -> Self {
+        Self {}
+    }
+}
+
+impl OptimizerRule for PropagateEmptyRelation {
+    fn optimize(
+        &self,
+        plan: &LogicalPlan,
+        optimizer_config: &mut OptimizerConfig,
+    ) -> Result<LogicalPlan> {
+        // optimize child plans first
+        let optimized_children_plan =
+            utils::optimize_children(self, plan, optimizer_config)?;
+        let optimized_plan_opt = match &optimized_children_plan {
+            LogicalPlan::Projection(_)
+            | LogicalPlan::Filter(_)
+            | LogicalPlan::Window(_)
+            | LogicalPlan::Sort(_)
+            | LogicalPlan::Join(_)
+            | LogicalPlan::CrossJoin(_)
+            | LogicalPlan::EmptyRelation(_)
+            | LogicalPlan::SubqueryAlias(_)
+            | LogicalPlan::Limit(_) => empty_child(&optimized_children_plan),
+            _ => None,
+        };
+

Review Comment:
   For Aggregation, if there are group by exprs and the input is empty, we can also propagate the empty relation. 



-- 
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] jackwener commented on a diff in pull request #4192: add `propagate_empty_relation` optimizer rule

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


##########
datafusion/expr/src/logical_plan/plan.rs:
##########
@@ -1145,6 +1145,22 @@ impl Projection {
         })
     }
 
+    /// Create a new Projection using the specified output schema
+    pub fn new_from_schema(input: Arc<LogicalPlan>, schema: DFSchemaRef) -> Self {
+        let expr: Vec<Expr> = schema
+            .fields()
+            .iter()
+            .map(|field| field.qualified_column())
+            .map(Expr::Column)
+            .collect();
+        Self {
+            expr,
+            input,
+            schema,
+            alias: None,
+        }
+    }

Review Comment:
   Your concerns are justified. I have fixed it and added UT
   
   I noticed it before, but I forgot when I was writing the code
   
   BTW, I think we shouldn't add alias in Union, how do you think it? We should remove union alias, and replace with projection. @mingmwang 



-- 
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] jackwener commented on a diff in pull request #4192: add `propagate_empty_relation` optimizer rule

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


##########
datafusion/expr/src/logical_plan/plan.rs:
##########
@@ -1145,6 +1145,22 @@ impl Projection {
         })
     }
 
+    /// Create a new Projection using the specified output schema
+    pub fn new_from_schema(input: Arc<LogicalPlan>, schema: DFSchemaRef) -> Self {
+        let expr: Vec<Expr> = schema
+            .fields()
+            .iter()
+            .map(|field| field.qualified_column())
+            .map(Expr::Column)
+            .collect();
+        Self {
+            expr,
+            input,
+            schema,
+            alias: None,
+        }
+    }

Review Comment:
   ```scala
   spark Union
   
   case class Union(
       children: Seq[LogicalPlan],
       byName: Boolean = false,
       allowMissingCol: Boolean = false) extends LogicalPlan {
   }
   ```



-- 
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] mingmwang commented on a diff in pull request #4192: add `propagate_empty_relation` optimizer rule

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


##########
datafusion/optimizer/src/propagate_empty_relation.rs:
##########
@@ -0,0 +1,178 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use datafusion_common::Result;
+use datafusion_expr::logical_plan::LogicalPlan;
+use datafusion_expr::EmptyRelation;
+
+use crate::{utils, OptimizerConfig, OptimizerRule};
+
+/// Optimization rule that bottom-up to eliminate plan by propagating empty_relation.
+#[derive(Default)]
+pub struct PropagateEmptyRelation;
+
+impl PropagateEmptyRelation {
+    #[allow(missing_docs)]
+    pub fn new() -> Self {
+        Self {}
+    }
+}
+
+impl OptimizerRule for PropagateEmptyRelation {
+    fn optimize(
+        &self,
+        plan: &LogicalPlan,
+        optimizer_config: &mut OptimizerConfig,
+    ) -> Result<LogicalPlan> {
+        // optimize child plans first
+        let optimized_children_plan =
+            utils::optimize_children(self, plan, optimizer_config)?;
+        let optimized_plan_opt = match &optimized_children_plan {
+            LogicalPlan::Projection(_)
+            | LogicalPlan::Filter(_)
+            | LogicalPlan::Window(_)
+            | LogicalPlan::Sort(_)
+            | LogicalPlan::Join(_)

Review Comment:
   For Join, we need to be careful:
   For Inner join, if either side is empty, the Join is empty.
   For LeftOuter/LeftSemi/LeftAnti Join, only the left side is empty, the Join result is empty.
   For RightOuter/RightSemi/RightAnti Join, only the right side is empty, the Join result is empty.
   For Full Join, only both sides are empty, the Join result is empty.
   



-- 
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] jackwener commented on a diff in pull request #4192: add `propagate_empty_relation` optimizer rule

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


##########
datafusion/expr/src/logical_plan/plan.rs:
##########
@@ -1145,6 +1145,22 @@ impl Projection {
         })
     }
 
+    /// Create a new Projection using the specified output schema
+    pub fn new_from_schema(input: Arc<LogicalPlan>, schema: DFSchemaRef) -> Self {
+        let expr: Vec<Expr> = schema
+            .fields()
+            .iter()
+            .map(|field| field.qualified_column())
+            .map(Expr::Column)
+            .collect();
+        Self {
+            expr,
+            input,
+            schema,
+            alias: None,
+        }
+    }

Review Comment:
   Your concerns are justified. I have fixed it and added UT
   
   I noticed it before, but I forgot when I was writing the code
   
   BTW, I think we should add alias in Union, how do you think it? We should remove union alias, and replace with projection. @mingmwang 



-- 
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] jackwener commented on a diff in pull request #4192: add `propagate_empty_relation` optimizer rule

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


##########
datafusion/expr/src/logical_plan/plan.rs:
##########
@@ -1145,6 +1145,22 @@ impl Projection {
         })
     }
 
+    /// Create a new Projection using the specified output schema
+    pub fn new_from_schema(input: Arc<LogicalPlan>, schema: DFSchemaRef) -> Self {
+        let expr: Vec<Expr> = schema
+            .fields()
+            .iter()
+            .map(|field| field.qualified_column())
+            .map(Expr::Column)
+            .collect();
+        Self {
+            expr,
+            input,
+            schema,
+            alias: None,
+        }
+    }

Review Comment:
   Yes, your concerns are justified
   
   



-- 
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] mingmwang commented on a diff in pull request #4192: add `propagate_empty_relation` optimizer rule

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


##########
datafusion/optimizer/src/propagate_empty_relation.rs:
##########
@@ -0,0 +1,178 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use datafusion_common::Result;
+use datafusion_expr::logical_plan::LogicalPlan;
+use datafusion_expr::EmptyRelation;
+
+use crate::{utils, OptimizerConfig, OptimizerRule};
+
+/// Optimization rule that bottom-up to eliminate plan by propagating empty_relation.
+#[derive(Default)]
+pub struct PropagateEmptyRelation;
+
+impl PropagateEmptyRelation {
+    #[allow(missing_docs)]
+    pub fn new() -> Self {
+        Self {}
+    }
+}
+
+impl OptimizerRule for PropagateEmptyRelation {
+    fn optimize(
+        &self,
+        plan: &LogicalPlan,
+        optimizer_config: &mut OptimizerConfig,
+    ) -> Result<LogicalPlan> {
+        // optimize child plans first
+        let optimized_children_plan =
+            utils::optimize_children(self, plan, optimizer_config)?;
+        let optimized_plan_opt = match &optimized_children_plan {
+            LogicalPlan::Projection(_)
+            | LogicalPlan::Filter(_)
+            | LogicalPlan::Window(_)
+            | LogicalPlan::Sort(_)
+            | LogicalPlan::Join(_)
+            | LogicalPlan::CrossJoin(_)
+            | LogicalPlan::EmptyRelation(_)
+            | LogicalPlan::SubqueryAlias(_)
+            | LogicalPlan::Limit(_) => empty_child(&optimized_children_plan),
+            _ => None,
+        };
+

Review Comment:
   For Repartition, if the input is empty, we can also propagate the empty relation.



-- 
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] mingmwang commented on a diff in pull request #4192: add `propagate_empty_relation` optimizer rule

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


##########
datafusion/expr/src/logical_plan/plan.rs:
##########
@@ -1145,6 +1145,22 @@ impl Projection {
         })
     }
 
+    /// Create a new Projection using the specified output schema
+    pub fn new_from_schema(input: Arc<LogicalPlan>, schema: DFSchemaRef) -> Self {
+        let expr: Vec<Expr> = schema
+            .fields()
+            .iter()
+            .map(|field| field.qualified_column())
+            .map(Expr::Column)
+            .collect();
+        Self {
+            expr,
+            input,
+            schema,
+            alias: None,
+        }
+    }

Review Comment:
   I'm not sure, if the schema here has different names with the input plan's schema, do we need to create an Alias Expr or a normal Column Expr?



-- 
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] mingmwang commented on a diff in pull request #4192: add `propagate_empty_relation` optimizer rule

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


##########
datafusion/optimizer/src/propagate_empty_relation.rs:
##########
@@ -0,0 +1,178 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use datafusion_common::Result;
+use datafusion_expr::logical_plan::LogicalPlan;
+use datafusion_expr::EmptyRelation;
+
+use crate::{utils, OptimizerConfig, OptimizerRule};
+
+/// Optimization rule that bottom-up to eliminate plan by propagating empty_relation.
+#[derive(Default)]
+pub struct PropagateEmptyRelation;
+
+impl PropagateEmptyRelation {
+    #[allow(missing_docs)]
+    pub fn new() -> Self {
+        Self {}
+    }
+}
+
+impl OptimizerRule for PropagateEmptyRelation {
+    fn optimize(
+        &self,
+        plan: &LogicalPlan,
+        optimizer_config: &mut OptimizerConfig,
+    ) -> Result<LogicalPlan> {
+        // optimize child plans first
+        let optimized_children_plan =
+            utils::optimize_children(self, plan, optimizer_config)?;
+        let optimized_plan_opt = match &optimized_children_plan {
+            LogicalPlan::Projection(_)
+            | LogicalPlan::Filter(_)
+            | LogicalPlan::Window(_)
+            | LogicalPlan::Sort(_)
+            | LogicalPlan::Join(_)

Review Comment:
   For Join, we need to be careful:
   For Inner Join, if either side is empty, the Join is empty.
   For LeftOuter/LeftSemi/LeftAnti Join, only the left side is empty, the Join result is empty.
   For LeftSemi Join, if the right side is empty, the Join result is empty.
   For LeftAnti Join,  if the right side is empty, the Join result is left side(should exclude null ??).
   For RightOuter/RightSemi/RightAnti Join, only the right side is empty, the Join result is empty.
   For RightSemi Join, if the left side is empty, the Join result is empty.
   For RightAnti Join,  if the left side is empty, the Join result is right side(should exclude null ??).
   For Full Join, only both sides are empty, the Join result is empty.
   For LeftOut/Full Join, if the right side is empty, the Join can be eliminated with a Projection with left side 
   columns +  right side columns replaced with null  values.
   For RightOut/Full Join, if the left side is empty, the Join can be eliminated with a Projection with right side columns + left side columns replaced with null  values.
   



-- 
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] mingmwang commented on a diff in pull request #4192: add `propagate_empty_relation` optimizer rule

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


##########
datafusion/optimizer/src/propagate_empty_relation.rs:
##########
@@ -0,0 +1,331 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use datafusion_common::{DataFusionError, Result};
+use datafusion_expr::logical_plan::LogicalPlan;
+use datafusion_expr::{EmptyRelation, JoinType, Projection};
+use std::sync::Arc;
+
+use crate::{utils, OptimizerConfig, OptimizerRule};
+
+/// Optimization rule that bottom-up to eliminate plan by propagating empty_relation.
+#[derive(Default)]
+pub struct PropagateEmptyRelation;
+
+impl PropagateEmptyRelation {
+    #[allow(missing_docs)]
+    pub fn new() -> Self {
+        Self {}
+    }
+}
+
+impl OptimizerRule for PropagateEmptyRelation {
+    fn optimize(
+        &self,
+        plan: &LogicalPlan,
+        optimizer_config: &mut OptimizerConfig,
+    ) -> Result<LogicalPlan> {
+        // optimize child plans first
+        let optimized_children_plan =
+            utils::optimize_children(self, plan, optimizer_config)?;
+        match &optimized_children_plan {
+            LogicalPlan::EmptyRelation(_) => Ok(optimized_children_plan),
+            LogicalPlan::Projection(_)
+            | LogicalPlan::Filter(_)
+            | LogicalPlan::Window(_)
+            | LogicalPlan::Sort(_)
+            | LogicalPlan::SubqueryAlias(_)
+            | LogicalPlan::Repartition(_)
+            | LogicalPlan::Limit(_) => match empty_child(&optimized_children_plan)? {
+                Some(empty) => Ok(empty),
+                None => Ok(optimized_children_plan),
+            },
+            LogicalPlan::CrossJoin(_) => {
+                let (left_empty, right_empty) = binary_plan_children_is_empty(plan)?;
+                if left_empty || right_empty {
+                    Ok(LogicalPlan::EmptyRelation(EmptyRelation {
+                        produce_one_row: false,
+                        schema: plan.schema().clone(),
+                    }))
+                } else {
+                    Ok(optimized_children_plan)
+                }
+            }
+            LogicalPlan::Join(join) => {
+                // TODO: For Join, more join type need to be careful:
+                // For LeftOuter/LeftSemi/LeftAnti Join, only the left side is empty, the Join result is empty.
+                // For LeftSemi Join, if the right side is empty, the Join result is empty.
+                // For LeftAnti Join, if the right side is empty, the Join result is left side(should exclude null ??).
+                // For RightOuter/RightSemi/RightAnti Join, only the right side is empty, the Join result is empty.
+                // For RightSemi Join, if the left side is empty, the Join result is empty.
+                // For RightAnti Join, if the left side is empty, the Join result is right side(should exclude null ??).
+                // For Full Join, only both sides are empty, the Join result is empty.
+                // For LeftOut/Full Join, if the right side is empty, the Join can be eliminated with a Projection with left side
+                // columns + right side columns replaced with null values.
+                // For RightOut/Full Join, if the left side is empty, the Join can be eliminated with a Projection with right side
+                // columns + left side columns replaced with null values.
+                if join.join_type == JoinType::Inner {
+                    let (left_empty, right_empty) = binary_plan_children_is_empty(plan)?;
+                    if left_empty || right_empty {
+                        Ok(LogicalPlan::EmptyRelation(EmptyRelation {
+                            produce_one_row: false,
+                            schema: plan.schema().clone(),
+                        }))
+                    } else {
+                        Ok(optimized_children_plan)
+                    }
+                } else {
+                    Ok(optimized_children_plan)
+                }
+            }
+            LogicalPlan::Union(union) => {
+                let (left_empty, right_empty) = binary_plan_children_is_empty(plan)?;
+                if left_empty && right_empty {

Review Comment:
   I'm not sure whether DataFusion's Union is binary or can have more than 2 inputs.
   Based on the doc, looks like it can accept multiple inputs.
   
   ``
       /// Union multiple inputs
       Union(Union),
   
   ``



-- 
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] jackwener commented on a diff in pull request #4192: add `propagate_empty_relation` optimizer rule

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


##########
datafusion/expr/src/logical_plan/plan.rs:
##########
@@ -1145,6 +1145,22 @@ impl Projection {
         })
     }
 
+    /// Create a new Projection using the specified output schema
+    pub fn new_from_schema(input: Arc<LogicalPlan>, schema: DFSchemaRef) -> Self {
+        let expr: Vec<Expr> = schema
+            .fields()
+            .iter()
+            .map(|field| field.qualified_column())
+            .map(Expr::Column)
+            .collect();
+        Self {
+            expr,
+            input,
+            schema,
+            alias: None,
+        }
+    }

Review Comment:
   Make sense to me.
   But I think add projection directly when  `new children  len ==  1` also is valid, and it's simple.



-- 
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] mingmwang commented on a diff in pull request #4192: add `propagate_empty_relation` optimizer rule

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


##########
datafusion/optimizer/src/propagate_empty_relation.rs:
##########
@@ -0,0 +1,178 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use datafusion_common::Result;
+use datafusion_expr::logical_plan::LogicalPlan;
+use datafusion_expr::EmptyRelation;
+
+use crate::{utils, OptimizerConfig, OptimizerRule};
+
+/// Optimization rule that bottom-up to eliminate plan by propagating empty_relation.
+#[derive(Default)]
+pub struct PropagateEmptyRelation;
+
+impl PropagateEmptyRelation {
+    #[allow(missing_docs)]
+    pub fn new() -> Self {
+        Self {}
+    }
+}
+
+impl OptimizerRule for PropagateEmptyRelation {
+    fn optimize(
+        &self,
+        plan: &LogicalPlan,
+        optimizer_config: &mut OptimizerConfig,
+    ) -> Result<LogicalPlan> {
+        // optimize child plans first
+        let optimized_children_plan =
+            utils::optimize_children(self, plan, optimizer_config)?;
+        let optimized_plan_opt = match &optimized_children_plan {
+            LogicalPlan::Projection(_)
+            | LogicalPlan::Filter(_)
+            | LogicalPlan::Window(_)
+            | LogicalPlan::Sort(_)
+            | LogicalPlan::Join(_)
+            | LogicalPlan::CrossJoin(_)
+            | LogicalPlan::EmptyRelation(_)
+            | LogicalPlan::SubqueryAlias(_)
+            | LogicalPlan::Limit(_) => empty_child(&optimized_children_plan),
+            _ => None,
+        };
+

Review Comment:
   For Union, if all the inputs are empty, we can also propagate the empty relation.
   And if not all the inputs are empty but just some of them are empty, we can eliminate the empty inputs I think.



-- 
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 #4192: add `propagate_empty_relation` optimizer rule

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


##########
datafusion/optimizer/src/propagate_empty_relation.rs:
##########
@@ -0,0 +1,178 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use datafusion_common::Result;
+use datafusion_expr::logical_plan::LogicalPlan;
+use datafusion_expr::EmptyRelation;
+
+use crate::{utils, OptimizerConfig, OptimizerRule};
+
+/// Optimization rule that bottom-up to eliminate plan by propagating empty_relation.
+#[derive(Default)]
+pub struct PropagateEmptyRelation;
+
+impl PropagateEmptyRelation {
+    #[allow(missing_docs)]
+    pub fn new() -> Self {
+        Self {}
+    }
+}
+
+impl OptimizerRule for PropagateEmptyRelation {
+    fn optimize(
+        &self,
+        plan: &LogicalPlan,
+        optimizer_config: &mut OptimizerConfig,
+    ) -> Result<LogicalPlan> {
+        // optimize child plans first
+        let optimized_children_plan =
+            utils::optimize_children(self, plan, optimizer_config)?;
+        let optimized_plan_opt = match &optimized_children_plan {
+            LogicalPlan::Projection(_)
+            | LogicalPlan::Filter(_)
+            | LogicalPlan::Window(_)
+            | LogicalPlan::Sort(_)
+            | LogicalPlan::Join(_)
+            | LogicalPlan::CrossJoin(_)
+            | LogicalPlan::EmptyRelation(_)
+            | LogicalPlan::SubqueryAlias(_)
+            | LogicalPlan::Limit(_) => empty_child(&optimized_children_plan),
+            _ => None,
+        };
+
+        match optimized_plan_opt {
+            Some(optimized_plan) => Ok(optimized_plan),
+            None => Ok(optimized_children_plan),
+        }
+    }
+
+    fn name(&self) -> &str {
+        "eliminate_limit"

Review Comment:
   ```suggestion
           "propagate_empty_relation"
   ```



-- 
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] mingmwang commented on a diff in pull request #4192: add `propagate_empty_relation` optimizer rule

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


##########
datafusion/expr/src/logical_plan/plan.rs:
##########
@@ -1145,6 +1145,22 @@ impl Projection {
         })
     }
 
+    /// Create a new Projection using the specified output schema
+    pub fn new_from_schema(input: Arc<LogicalPlan>, schema: DFSchemaRef) -> Self {
+        let expr: Vec<Expr> = schema
+            .fields()
+            .iter()
+            .map(|field| field.qualified_column())
+            .map(Expr::Column)
+            .collect();
+        Self {
+            expr,
+            input,
+            schema,
+            alias: None,
+        }
+    }

Review Comment:
   But this might introduce unnecessary Projection. I would suggest to add Projection only when it is really unnecessary.



-- 
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] mingmwang commented on a diff in pull request #4192: add `propagate_empty_relation` optimizer rule

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


##########
datafusion/optimizer/src/propagate_empty_relation.rs:
##########
@@ -0,0 +1,331 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use datafusion_common::{DataFusionError, Result};
+use datafusion_expr::logical_plan::LogicalPlan;
+use datafusion_expr::{EmptyRelation, JoinType, Projection};
+use std::sync::Arc;
+
+use crate::{utils, OptimizerConfig, OptimizerRule};
+
+/// Optimization rule that bottom-up to eliminate plan by propagating empty_relation.
+#[derive(Default)]
+pub struct PropagateEmptyRelation;
+
+impl PropagateEmptyRelation {
+    #[allow(missing_docs)]
+    pub fn new() -> Self {
+        Self {}
+    }
+}
+
+impl OptimizerRule for PropagateEmptyRelation {
+    fn optimize(
+        &self,
+        plan: &LogicalPlan,
+        optimizer_config: &mut OptimizerConfig,
+    ) -> Result<LogicalPlan> {
+        // optimize child plans first
+        let optimized_children_plan =
+            utils::optimize_children(self, plan, optimizer_config)?;
+        match &optimized_children_plan {
+            LogicalPlan::EmptyRelation(_) => Ok(optimized_children_plan),
+            LogicalPlan::Projection(_)
+            | LogicalPlan::Filter(_)
+            | LogicalPlan::Window(_)
+            | LogicalPlan::Sort(_)
+            | LogicalPlan::SubqueryAlias(_)
+            | LogicalPlan::Repartition(_)
+            | LogicalPlan::Limit(_) => match empty_child(&optimized_children_plan)? {
+                Some(empty) => Ok(empty),
+                None => Ok(optimized_children_plan),
+            },
+            LogicalPlan::CrossJoin(_) => {
+                let (left_empty, right_empty) = binary_plan_children_is_empty(plan)?;
+                if left_empty || right_empty {
+                    Ok(LogicalPlan::EmptyRelation(EmptyRelation {
+                        produce_one_row: false,
+                        schema: plan.schema().clone(),
+                    }))
+                } else {
+                    Ok(optimized_children_plan)
+                }
+            }
+            LogicalPlan::Join(join) => {
+                // TODO: For Join, more join type need to be careful:
+                // For LeftOuter/LeftSemi/LeftAnti Join, only the left side is empty, the Join result is empty.
+                // For LeftSemi Join, if the right side is empty, the Join result is empty.
+                // For LeftAnti Join, if the right side is empty, the Join result is left side(should exclude null ??).
+                // For RightOuter/RightSemi/RightAnti Join, only the right side is empty, the Join result is empty.
+                // For RightSemi Join, if the left side is empty, the Join result is empty.
+                // For RightAnti Join, if the left side is empty, the Join result is right side(should exclude null ??).
+                // For Full Join, only both sides are empty, the Join result is empty.
+                // For LeftOut/Full Join, if the right side is empty, the Join can be eliminated with a Projection with left side
+                // columns + right side columns replaced with null values.
+                // For RightOut/Full Join, if the left side is empty, the Join can be eliminated with a Projection with right side
+                // columns + left side columns replaced with null values.
+                if join.join_type == JoinType::Inner {
+                    let (left_empty, right_empty) = binary_plan_children_is_empty(plan)?;
+                    if left_empty || right_empty {
+                        Ok(LogicalPlan::EmptyRelation(EmptyRelation {
+                            produce_one_row: false,
+                            schema: plan.schema().clone(),
+                        }))
+                    } else {
+                        Ok(optimized_children_plan)
+                    }
+                } else {
+                    Ok(optimized_children_plan)
+                }
+            }
+            LogicalPlan::Union(union) => {
+                let (left_empty, right_empty) = binary_plan_children_is_empty(plan)?;
+                if left_empty && right_empty {

Review Comment:
   I'm not sure whether DataFusion's Union is binary or can have more than 2 inputs.
   Based on the doc, looks like it can accept multiple inputs.
   
   ````
       /// Union multiple inputs
       Union(Union),
   
   ````



-- 
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] jackwener commented on a diff in pull request #4192: add `propagate_empty_relation` optimizer rule

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


##########
datafusion/expr/src/logical_plan/plan.rs:
##########
@@ -1145,6 +1145,22 @@ impl Projection {
         })
     }
 
+    /// Create a new Projection using the specified output schema
+    pub fn new_from_schema(input: Arc<LogicalPlan>, schema: DFSchemaRef) -> Self {
+        let expr: Vec<Expr> = schema
+            .fields()
+            .iter()
+            .map(|field| field.qualified_column())
+            .map(Expr::Column)
+            .collect();
+        Self {
+            expr,
+            input,
+            schema,
+            alias: None,
+        }
+    }

Review Comment:
   Your concerns are justified, fix it. 
   
   I noticed it before, but I forgot when I was writing the code
   
   BTW, I think we should add alias in Union, how do you think it? We should remove union alias, and replace with projection. @mingmwang 



-- 
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] jackwener commented on a diff in pull request #4192: add `propagate_empty_relation` optimizer rule

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


##########
datafusion/expr/src/logical_plan/plan.rs:
##########
@@ -1145,6 +1145,22 @@ impl Projection {
         })
     }
 
+    /// Create a new Projection using the specified output schema
+    pub fn new_from_schema(input: Arc<LogicalPlan>, schema: DFSchemaRef) -> Self {
+        let expr: Vec<Expr> = schema
+            .fields()
+            .iter()
+            .map(|field| field.qualified_column())
+            .map(Expr::Column)
+            .collect();
+        Self {
+            expr,
+            input,
+            schema,
+            alias: None,
+        }
+    }

Review Comment:
   Make sense👍



-- 
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] jackwener commented on a diff in pull request #4192: add `propagate_empty_relation` optimizer rule

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


##########
datafusion/expr/src/logical_plan/plan.rs:
##########
@@ -1145,6 +1145,22 @@ impl Projection {
         })
     }
 
+    /// Create a new Projection using the specified output schema
+    pub fn new_from_schema(input: Arc<LogicalPlan>, schema: DFSchemaRef) -> Self {
+        let expr: Vec<Expr> = schema
+            .fields()
+            .iter()
+            .map(|field| field.qualified_column())
+            .map(Expr::Column)
+            .collect();
+        Self {
+            expr,
+            input,
+            schema,
+            alias: None,
+        }
+    }

Review Comment:
   Yes, your concerns are justified
   
   



-- 
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] jackwener commented on a diff in pull request #4192: add `propagate_empty_relation` optimizer rule

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


##########
datafusion/expr/src/logical_plan/plan.rs:
##########
@@ -1145,6 +1145,22 @@ impl Projection {
         })
     }
 
+    /// Create a new Projection using the specified output schema
+    pub fn new_from_schema(input: Arc<LogicalPlan>, schema: DFSchemaRef) -> Self {
+        let expr: Vec<Expr> = schema
+            .fields()
+            .iter()
+            .map(|field| field.qualified_column())
+            .map(Expr::Column)
+            .collect();
+        Self {
+            expr,
+            input,
+            schema,
+            alias: None,
+        }
+    }

Review Comment:
   when `new children  len ==  1`, we must add projection, because union schema != child schema.



-- 
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] jackwener commented on a diff in pull request #4192: add `propagate_empty_relation` optimizer rule

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


##########
datafusion/expr/src/logical_plan/plan.rs:
##########
@@ -1145,6 +1145,22 @@ impl Projection {
         })
     }
 
+    /// Create a new Projection using the specified output schema
+    pub fn new_from_schema(input: Arc<LogicalPlan>, schema: DFSchemaRef) -> Self {
+        let expr: Vec<Expr> = schema
+            .fields()
+            .iter()
+            .map(|field| field.qualified_column())
+            .map(Expr::Column)
+            .collect();
+        Self {
+            expr,
+            input,
+            schema,
+            alias: None,
+        }
+    }

Review Comment:
   Make sense to me.
   But I think add projection directly also is valid. 



-- 
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 pull request #4192: add `propagate_empty_relation` optimizer rule

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

   Thank you @jackwener 


-- 
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 #4192: add `propagate_empty_relation` optimizer rule

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


##########
datafusion/optimizer/tests/integration-test.rs:
##########
@@ -258,6 +258,15 @@ fn timestamp_nano_ts_utc_predicates() {
     assert_eq!(expected, format!("{:?}", plan));
 }
 
+#[test]
+fn propagate_empty_relation() {
+    let sql = "SELECT col_int32 FROM test JOIN ( SELECT col_int32 FROM test WHERE false ) AS ta1 ON test.col_int32 = ta1.col_int32;";
+    let plan = test_sql(sql).unwrap();
+    // when children exist EmptyRelation, it will bottom-up propagate.

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] ursabot commented on pull request #4192: add `propagate_empty_relation` optimizer rule

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

   Benchmark runs are scheduled for baseline = f0359a797d73c05d72d02a17dc398a924ced2742 and contender = 5de9709fadf1344baca1ed3e1f9a44e06dfa9a63. 5de9709fadf1344baca1ed3e1f9a44e06dfa9a63 is a master commit associated with this PR. Results will be available as each benchmark for each run completes.
   Conbench compare runs links:
   [Skipped :warning: Benchmarking of arrow-datafusion-commits is not supported on ec2-t3-xlarge-us-east-2] [ec2-t3-xlarge-us-east-2](https://conbench.ursa.dev/compare/runs/eb947d3c13954ed986dac3ac2aeb6982...9a0133e6383741d98a0cb4e19945f77f/)
   [Skipped :warning: Benchmarking of arrow-datafusion-commits is not supported on test-mac-arm] [test-mac-arm](https://conbench.ursa.dev/compare/runs/6022899f434640e2b817459aea4c99ff...ad2b34eb160b4a5dad8215adc0ec7792/)
   [Skipped :warning: Benchmarking of arrow-datafusion-commits is not supported on ursa-i9-9960x] [ursa-i9-9960x](https://conbench.ursa.dev/compare/runs/086eb58022bd45d9a74e9525532a69a6...e403d31c1ae14a9cb9d7cd40ad3a3161/)
   [Skipped :warning: Benchmarking of arrow-datafusion-commits is not supported on ursa-thinkcentre-m75q] [ursa-thinkcentre-m75q](https://conbench.ursa.dev/compare/runs/b28879cf8e4d454980b765465b5762a3...dedd3850b59349158d1d1247c9b0cfb1/)
   Buildkite builds:
   Supported benchmarks:
   ec2-t3-xlarge-us-east-2: Supported benchmark langs: Python, R. Runs only benchmarks with cloud = True
   test-mac-arm: Supported benchmark langs: C++, Python, R
   ursa-i9-9960x: Supported benchmark langs: Python, R, JavaScript
   ursa-thinkcentre-m75q: Supported benchmark langs: C++, Java
   


-- 
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 pull request #4192: add `propagate_empty_relation` optimizer rule

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

   Thanks again @jackwener 


-- 
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 #4192: add `propagate_empty_relation` optimizer rule

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


-- 
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] jackwener commented on pull request #4192: add `propagate_empty_relation` optimizer rule

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

   Thanks @mingmwang.
   Condition for `Join` is complex😂, I leave a TODO for it.


-- 
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] jackwener commented on a diff in pull request #4192: add `propagate_empty_relation` optimizer rule

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


##########
datafusion/expr/src/logical_plan/plan.rs:
##########
@@ -1145,6 +1145,22 @@ impl Projection {
         })
     }
 
+    /// Create a new Projection using the specified output schema
+    pub fn new_from_schema(input: Arc<LogicalPlan>, schema: DFSchemaRef) -> Self {
+        let expr: Vec<Expr> = schema
+            .fields()
+            .iter()
+            .map(|field| field.qualified_column())
+            .map(Expr::Column)
+            .collect();
+        Self {
+            expr,
+            input,
+            schema,
+            alias: None,
+        }
+    }

Review Comment:
   Make sense to me.
   But I think add projection directly also is valid, and it's simple.



-- 
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] jackwener commented on pull request #4192: add `propagate_empty_relation` optimizer rule

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

   Thanks @mingmwang @alamb @Dandandan review❤️


-- 
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] jackwener commented on a diff in pull request #4192: add `propagate_empty_relation` optimizer rule

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


##########
datafusion/expr/src/logical_plan/plan.rs:
##########
@@ -1145,6 +1145,22 @@ impl Projection {
         })
     }
 
+    /// Create a new Projection using the specified output schema
+    pub fn new_from_schema(input: Arc<LogicalPlan>, schema: DFSchemaRef) -> Self {
+        let expr: Vec<Expr> = schema
+            .fields()
+            .iter()
+            .map(|field| field.qualified_column())
+            .map(Expr::Column)
+            .collect();
+        Self {
+            expr,
+            input,
+            schema,
+            alias: None,
+        }
+    }

Review Comment:
   Your concerns are justified. I have fixed it. 
   
   I noticed it before, but I forgot when I was writing the code
   
   BTW, I think we should add alias in Union, how do you think it? We should remove union alias, and replace with projection. @mingmwang 



-- 
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] jackwener commented on a diff in pull request #4192: add `propagate_empty_relation` optimizer rule

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


##########
datafusion/expr/src/logical_plan/plan.rs:
##########
@@ -1145,6 +1145,22 @@ impl Projection {
         })
     }
 
+    /// Create a new Projection using the specified output schema
+    pub fn new_from_schema(input: Arc<LogicalPlan>, schema: DFSchemaRef) -> Self {
+        let expr: Vec<Expr> = schema
+            .fields()
+            .iter()
+            .map(|field| field.qualified_column())
+            .map(Expr::Column)
+            .collect();
+        Self {
+            expr,
+            input,
+            schema,
+            alias: None,
+        }
+    }

Review Comment:
   ```scala
   spark Union don't include alias
   
   case class Union(
       children: Seq[LogicalPlan],
       byName: Boolean = false,
       allowMissingCol: Boolean = false) extends LogicalPlan {
   }
   ```



-- 
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] mingmwang commented on a diff in pull request #4192: add `propagate_empty_relation` optimizer rule

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


##########
datafusion/optimizer/src/propagate_empty_relation.rs:
##########
@@ -0,0 +1,331 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use datafusion_common::{DataFusionError, Result};
+use datafusion_expr::logical_plan::LogicalPlan;
+use datafusion_expr::{EmptyRelation, JoinType, Projection};
+use std::sync::Arc;
+
+use crate::{utils, OptimizerConfig, OptimizerRule};
+
+/// Optimization rule that bottom-up to eliminate plan by propagating empty_relation.
+#[derive(Default)]
+pub struct PropagateEmptyRelation;
+
+impl PropagateEmptyRelation {
+    #[allow(missing_docs)]
+    pub fn new() -> Self {
+        Self {}
+    }
+}
+
+impl OptimizerRule for PropagateEmptyRelation {
+    fn optimize(
+        &self,
+        plan: &LogicalPlan,
+        optimizer_config: &mut OptimizerConfig,
+    ) -> Result<LogicalPlan> {
+        // optimize child plans first
+        let optimized_children_plan =
+            utils::optimize_children(self, plan, optimizer_config)?;
+        match &optimized_children_plan {
+            LogicalPlan::EmptyRelation(_) => Ok(optimized_children_plan),
+            LogicalPlan::Projection(_)
+            | LogicalPlan::Filter(_)
+            | LogicalPlan::Window(_)
+            | LogicalPlan::Sort(_)
+            | LogicalPlan::SubqueryAlias(_)
+            | LogicalPlan::Repartition(_)
+            | LogicalPlan::Limit(_) => match empty_child(&optimized_children_plan)? {
+                Some(empty) => Ok(empty),
+                None => Ok(optimized_children_plan),
+            },
+            LogicalPlan::CrossJoin(_) => {
+                let (left_empty, right_empty) = binary_plan_children_is_empty(plan)?;
+                if left_empty || right_empty {
+                    Ok(LogicalPlan::EmptyRelation(EmptyRelation {
+                        produce_one_row: false,
+                        schema: plan.schema().clone(),
+                    }))
+                } else {
+                    Ok(optimized_children_plan)
+                }
+            }
+            LogicalPlan::Join(join) => {
+                // TODO: For Join, more join type need to be careful:
+                // For LeftOuter/LeftSemi/LeftAnti Join, only the left side is empty, the Join result is empty.
+                // For LeftSemi Join, if the right side is empty, the Join result is empty.
+                // For LeftAnti Join, if the right side is empty, the Join result is left side(should exclude null ??).
+                // For RightOuter/RightSemi/RightAnti Join, only the right side is empty, the Join result is empty.
+                // For RightSemi Join, if the left side is empty, the Join result is empty.
+                // For RightAnti Join, if the left side is empty, the Join result is right side(should exclude null ??).
+                // For Full Join, only both sides are empty, the Join result is empty.
+                // For LeftOut/Full Join, if the right side is empty, the Join can be eliminated with a Projection with left side
+                // columns + right side columns replaced with null values.
+                // For RightOut/Full Join, if the left side is empty, the Join can be eliminated with a Projection with right side
+                // columns + left side columns replaced with null values.
+                if join.join_type == JoinType::Inner {
+                    let (left_empty, right_empty) = binary_plan_children_is_empty(plan)?;
+                    if left_empty || right_empty {
+                        Ok(LogicalPlan::EmptyRelation(EmptyRelation {
+                            produce_one_row: false,
+                            schema: plan.schema().clone(),
+                        }))
+                    } else {
+                        Ok(optimized_children_plan)
+                    }
+                } else {
+                    Ok(optimized_children_plan)
+                }
+            }
+            LogicalPlan::Union(union) => {
+                let (left_empty, right_empty) = binary_plan_children_is_empty(plan)?;
+                if left_empty && right_empty {
+                    Ok(LogicalPlan::EmptyRelation(EmptyRelation {
+                        produce_one_row: false,
+                        schema: plan.schema().clone(),
+                    }))
+                } else if !left_empty && right_empty {
+                    Ok(LogicalPlan::Projection(Projection::new_from_schema(
+                        Arc::new((**(union.inputs.get(0).unwrap())).clone()),
+                        plan.schema().clone(),
+                    )))
+                } else if left_empty && !right_empty {
+                    Ok(LogicalPlan::Projection(Projection::new_from_schema(
+                        Arc::new((**(union.inputs.get(1).unwrap())).clone()),
+                        plan.schema().clone(),
+                    )))
+                } else {
+                    Ok(optimized_children_plan)
+                }
+            }
+            LogicalPlan::Aggregate(agg) => {
+                if !agg.group_expr.is_empty() {
+                    match empty_child(&optimized_children_plan)? {
+                        Some(empty) => Ok(empty),
+                        None => Ok(optimized_children_plan),
+                    }
+                } else {
+                    Ok(optimized_children_plan)
+                }
+            }
+            _ => Ok(optimized_children_plan),
+        }
+    }
+
+    fn name(&self) -> &str {
+        "propagate_empty_relation"
+    }
+}
+
+fn binary_plan_children_is_empty(plan: &LogicalPlan) -> Result<(bool, bool)> {
+    let inputs = plan.inputs();
+
+    // all binary-plan need to deal with separately.
+    match inputs.len() {
+        2 => {
+            let left = inputs.get(0).unwrap();
+            let right = inputs.get(1).unwrap();
+
+            let left_empty = match left {
+                LogicalPlan::EmptyRelation(empty) => !empty.produce_one_row,
+                _ => false,
+            };
+            let right_empty = match right {
+                LogicalPlan::EmptyRelation(empty) => !empty.produce_one_row,
+                _ => false,
+            };
+            Ok((left_empty, right_empty))
+        }
+        _ => Err(DataFusionError::Plan(
+            "plan just can have two child".to_string(),
+        )),
+    }
+}
+
+fn empty_child(plan: &LogicalPlan) -> Result<Option<LogicalPlan>> {
+    let inputs = plan.inputs();
+
+    // all binary-plan need to deal with separately.
+    match inputs.len() {
+        1 => {
+            let input = inputs.get(0).unwrap();
+            match input {
+                LogicalPlan::EmptyRelation(empty) => {
+                    if !empty.produce_one_row {
+                        Ok(Some(LogicalPlan::EmptyRelation(EmptyRelation {
+                            produce_one_row: false,
+                            schema: plan.schema().clone(),
+                        })))
+                    } else {
+                        Ok(None)
+                    }
+                }
+                _ => Ok(None),
+            }
+        }
+        _ => Err(DataFusionError::Plan(
+            "plan just can have one child".to_string(),
+        )),
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use crate::eliminate_filter::EliminateFilter;
+    use crate::test::{test_table_scan, test_table_scan_with_name};
+    use datafusion_common::{Column, ScalarValue};
+    use datafusion_expr::{
+        binary_expr, col, lit, logical_plan::builder::LogicalPlanBuilder, Expr, JoinType,
+        Operator,
+    };
+
+    use super::*;
+
+    fn assert_optimized_plan_eq(plan: &LogicalPlan, expected: &str) {
+        let rule = PropagateEmptyRelation::new();
+        let optimized_plan = rule
+            .optimize(plan, &mut OptimizerConfig::new())
+            .expect("failed to optimize plan");
+        let formatted_plan = format!("{:?}", optimized_plan);
+        assert_eq!(formatted_plan, expected);
+        assert_eq!(plan.schema(), optimized_plan.schema());
+    }
+
+    fn assert_together_optimized_plan_eq(plan: &LogicalPlan, expected: &str) {
+        let optimize_one = EliminateFilter::new()
+            .optimize(plan, &mut OptimizerConfig::new())
+            .expect("failed to optimize plan");
+        let optimize_two = PropagateEmptyRelation::new()
+            .optimize(&optimize_one, &mut OptimizerConfig::new())
+            .expect("failed to optimize plan");
+        let formatted_plan = format!("{:?}", optimize_two);
+        assert_eq!(formatted_plan, expected);
+        assert_eq!(plan.schema(), optimize_two.schema());
+    }
+
+    #[test]
+    fn propagate_empty() -> Result<()> {
+        let plan = LogicalPlanBuilder::empty(false)
+            .filter(Expr::Literal(ScalarValue::Boolean(Some(true))))?
+            .limit(10, None)?
+            .project(vec![binary_expr(lit(1), Operator::Plus, lit(1))])?
+            .build()?;
+
+        let expected = "EmptyRelation";
+        assert_optimized_plan_eq(&plan, expected);
+
+        Ok(())
+    }
+
+    #[test]
+    fn propagate_union_right_empty() -> Result<()> {
+        let table_scan = test_table_scan()?;
+        let left = LogicalPlanBuilder::from(table_scan).build()?;
+        let right_table_scan = test_table_scan_with_name("test2")?;
+        let right = LogicalPlanBuilder::from(right_table_scan)
+            .filter(Expr::Literal(ScalarValue::Boolean(Some(false))))?
+            .build()?;
+
+        let plan = LogicalPlanBuilder::from(left).union(right)?.build()?;
+
+        let expected = "Projection: a, b, c\
+            \n  TableScan: test";
+        assert_together_optimized_plan_eq(&plan, expected);
+
+        Ok(())
+    }
+
+    #[test]
+    fn propagate_union_left_empty() -> Result<()> {
+        let table_scan = test_table_scan()?;
+        let left = LogicalPlanBuilder::from(table_scan)
+            .filter(Expr::Literal(ScalarValue::Boolean(Some(false))))?
+            .build()?;
+        let right_table_scan = test_table_scan_with_name("test2")?;
+        let right = LogicalPlanBuilder::from(right_table_scan).build()?;
+
+        let plan = LogicalPlanBuilder::from(left).union(right)?.build()?;
+
+        let expected = "Projection: a, b, c\
+            \n  TableScan: test2";
+        assert_together_optimized_plan_eq(&plan, expected);
+
+        Ok(())
+    }
+

Review Comment:
   Could you please add one more UT to cover the case that the union inputs have slightly different schema ?



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