houqp commented on a change in pull request #9309:
URL: https://github.com/apache/arrow/pull/9309#discussion_r571687423



##########
File path: rust/datafusion/src/optimizer/constant_folding.rs
##########
@@ -0,0 +1,620 @@
+// 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.
+
+//! Boolean comparision rule rewrites redudant comparison expression involing 
boolean literal into
+//! unary expression.
+
+use std::sync::Arc;
+
+use arrow::datatypes::DataType;
+
+use crate::error::Result;
+use crate::logical_plan::{DFSchemaRef, Expr, LogicalPlan, Operator};
+use crate::optimizer::optimizer::OptimizerRule;
+use crate::optimizer::utils;
+use crate::scalar::ScalarValue;
+
+/// Optimizer that simplifies comparison expressions involving boolean 
literals.
+///
+/// Recursively go through all expressionss and simplify the following cases:
+/// * `expr = ture` and `expr != false` to `expr` when `expr` is of boolean 
type
+/// * `expr = false` and `expr != true` to `!expr` when `expr` is of boolean 
type
+/// * `true = true` and `false = false` to `true`
+/// * `false = true` and `true = false` to `false`
+pub struct ConstantFolding {}
+
+impl ConstantFolding {
+    #[allow(missing_docs)]
+    pub fn new() -> Self {
+        Self {}
+    }
+}
+
+impl OptimizerRule for ConstantFolding {
+    fn optimize(&self, plan: &LogicalPlan) -> Result<LogicalPlan> {
+        match plan {
+            LogicalPlan::Filter { predicate, input } => Ok(LogicalPlan::Filter 
{
+                predicate: optimize_expr(predicate, plan.schema())?,
+                input: Arc::new(self.optimize(input)?),
+            }),
+            // Rest: recurse into plan, apply optimization where possible
+            LogicalPlan::Projection { .. }
+            | LogicalPlan::Aggregate { .. }
+            | LogicalPlan::Limit { .. }
+            | LogicalPlan::Repartition { .. }
+            | LogicalPlan::CreateExternalTable { .. }
+            | LogicalPlan::Extension { .. }
+            | LogicalPlan::Sort { .. }
+            | LogicalPlan::Explain { .. }
+            | LogicalPlan::Join { .. } => {
+                let expr = utils::expressions(plan);
+
+                // apply the optimization to all inputs of the plan
+                let inputs = utils::inputs(plan);
+                let new_inputs = inputs
+                    .iter()
+                    .map(|plan| self.optimize(plan))
+                    .collect::<Result<Vec<_>>>()?;
+
+                utils::from_plan(plan, &expr, &new_inputs)
+            }
+            LogicalPlan::TableScan { .. } | LogicalPlan::EmptyRelation { .. } 
=> {
+                Ok(plan.clone())
+            }
+        }
+    }
+
+    fn name(&self) -> &str {
+        "constant_folding"
+    }
+}
+
+/// Recursively transverses the logical plan.
+fn optimize_expr(e: &Expr, schema: &DFSchemaRef) -> Result<Expr> {
+    Ok(match e {
+        Expr::BinaryExpr { left, op, right } => {
+            let left = optimize_expr(left, schema)?;
+            let right = optimize_expr(right, schema)?;
+            match op {
+                Operator::Eq => match (&left, &right) {
+                    (
+                        Expr::Literal(ScalarValue::Boolean(l)),
+                        Expr::Literal(ScalarValue::Boolean(r)),
+                    ) => Expr::Literal(ScalarValue::Boolean(Some(
+                        l.unwrap_or(false) == r.unwrap_or(false),
+                    ))),
+                    (Expr::Literal(ScalarValue::Boolean(b)), _)
+                        if right.get_type(schema)? == DataType::Boolean =>
+                    {
+                        match b {
+                            Some(true) => right,
+                            Some(false) | None => Expr::Not(Box::new(right)),
+                        }
+                    }
+                    (_, Expr::Literal(ScalarValue::Boolean(b)))
+                        if left.get_type(schema)? == DataType::Boolean =>
+                    {
+                        match b {
+                            Some(true) => left,
+                            Some(false) | None => Expr::Not(Box::new(left)),
+                        }
+                    }
+                    _ => Expr::BinaryExpr {
+                        left: Box::new(left),
+                        op: Operator::Eq,
+                        right: Box::new(right),
+                    },
+                },
+                Operator::NotEq => match (&left, &right) {
+                    (
+                        Expr::Literal(ScalarValue::Boolean(l)),
+                        Expr::Literal(ScalarValue::Boolean(r)),
+                    ) => Expr::Literal(ScalarValue::Boolean(Some(
+                        l.unwrap_or(false) != r.unwrap_or(false),

Review comment:
       yeah, any binary operation, other than null safe equality, that involves 
null should return null, i will updated the other non-literal branches to 
return null literal as well.




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

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


Reply via email to