wjones127 commented on code in PR #7467:
URL: https://github.com/apache/arrow-datafusion/pull/7467#discussion_r1323653945


##########
datafusion/optimizer/src/simplify_expressions/guarantees.rs:
##########
@@ -0,0 +1,514 @@
+// 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.
+
+//! Simplifier implementation for 
[ExprSimplifier::simplify_with_guarantees()][crate::simplify_expressions::expr_simplifier::ExprSimplifier::simplify_with_guarantees].
+use datafusion_common::{tree_node::TreeNodeRewriter, DataFusionError, Result};
+use datafusion_expr::{expr::InList, lit, Between, BinaryExpr, Expr, Operator};
+use std::collections::HashMap;
+
+use datafusion_physical_expr::intervals::{Interval, IntervalBound, 
NullableInterval};
+
+/// Rewrite expressions to incorporate guarantees.
+pub(crate) struct GuaranteeRewriter<'a> {
+    guarantees: HashMap<&'a Expr, &'a NullableInterval>,
+}
+
+impl<'a> GuaranteeRewriter<'a> {
+    pub fn new(
+        guarantees: impl IntoIterator<Item = &'a (Expr, NullableInterval)>,
+    ) -> Self {
+        Self {
+            guarantees: guarantees.into_iter().map(|(k, v)| (k, v)).collect(),
+        }
+    }
+}
+
+impl<'a> TreeNodeRewriter for GuaranteeRewriter<'a> {
+    type N = Expr;
+
+    fn mutate(&mut self, expr: Expr) -> Result<Expr> {
+        if self.guarantees.is_empty() {
+            return Ok(expr);
+        }
+
+        match &expr {
+            Expr::IsNull(inner) => match self.guarantees.get(inner.as_ref()) {
+                Some(NullableInterval::Null { .. }) => Ok(lit(true)),
+                Some(NullableInterval::NotNull { .. }) => Ok(lit(false)),
+                _ => Ok(expr),
+            },
+            Expr::IsNotNull(inner) => match 
self.guarantees.get(inner.as_ref()) {
+                Some(NullableInterval::Null { .. }) => Ok(lit(false)),
+                Some(NullableInterval::NotNull { .. }) => Ok(lit(true)),
+                _ => Ok(expr),
+            },
+            Expr::Between(Between {
+                expr: inner,
+                negated,
+                low,
+                high,
+            }) => {
+                if let (Some(interval), Expr::Literal(low), 
Expr::Literal(high)) = (
+                    self.guarantees.get(inner.as_ref()),
+                    low.as_ref(),
+                    high.as_ref(),
+                ) {
+                    let expr_interval = NullableInterval::NotNull {
+                        values: Interval::new(
+                            IntervalBound::new(low.clone(), false),
+                            IntervalBound::new(high.clone(), false),
+                        ),
+                    };
+
+                    let contains = expr_interval.contains(*interval)?;
+
+                    if contains.is_certainly_true() {
+                        Ok(lit(!negated))
+                    } else if contains.is_certainly_false() {
+                        Ok(lit(*negated))
+                    } else {
+                        Ok(expr)
+                    }
+                } else {
+                    Ok(expr)
+                }
+            }
+
+            Expr::BinaryExpr(BinaryExpr { left, op, right }) => {
+                // Check if this is a comparison
+                match op {
+                    Operator::Eq
+                    | Operator::NotEq
+                    | Operator::Lt
+                    | Operator::LtEq
+                    | Operator::Gt
+                    | Operator::GtEq
+                    | Operator::IsDistinctFrom
+                    | Operator::IsNotDistinctFrom => {}
+                    _ => return Ok(expr),
+                };
+
+                // Check if this is a comparison between a column and literal
+                let (col, op, value) = match (left.as_ref(), right.as_ref()) {
+                    (Expr::Column(_), Expr::Literal(value)) => (left, *op, 
value),
+                    (Expr::Literal(value), Expr::Column(_)) => {
+                        // If we can swap the op, we can simplify the 
expression
+                        if let Some(op) = op.swap() {
+                            (right, op, value)
+                        } else {
+                            return Ok(expr);
+                        }
+                    }
+                    _ => return Ok(expr),
+                };
+
+                if let Some(col_interval) = self.guarantees.get(col.as_ref()) {
+                    let result = col_interval.apply_operator(&op, 
&value.into())?;
+                    if result.is_certainly_true() {
+                        Ok(lit(true))
+                    } else if result.is_certainly_false() {
+                        Ok(lit(false))
+                    } else {
+                        Ok(expr)
+                    }
+                } else {
+                    Ok(expr)
+                }
+            }
+
+            // Columns (if interval is collapsed to a single value)
+            Expr::Column(_) => {
+                if let Some(col_interval) = self.guarantees.get(&expr) {
+                    if let Some(value) = col_interval.single_value() {
+                        Ok(lit(value))
+                    } else {
+                        Ok(expr)
+                    }
+                } else {
+                    Ok(expr)
+                }
+            }
+
+            Expr::InList(InList {
+                expr: inner,
+                list,
+                negated,
+            }) => {
+                if let Some(interval) = self.guarantees.get(inner.as_ref()) {
+                    // Can remove items from the list that don't match the 
guarantee
+                    let new_list: Vec<Expr> = list
+                        .iter()
+                        .filter_map(|expr| {
+                            if let Expr::Literal(item) = expr {
+                                match 
interval.contains(&NullableInterval::from(item)) {
+                                    // If we know for certain the value isn't 
in the column's interval,
+                                    // we can skip checking it.
+                                    Ok(NullableInterval::NotNull { values })
+                                        if values == Interval::CERTAINLY_FALSE 
=>
+                                    {
+                                        None
+                                    }
+                                    Err(err) => Some(Err(err)),
+                                    _ => Some(Ok(expr.clone())),
+                                }
+                            } else {
+                                Some(Ok(expr.clone()))
+                            }
+                        })
+                        .collect::<Result<_, DataFusionError>>()?;
+
+                    Ok(Expr::InList(InList {
+                        expr: inner.clone(),
+                        list: new_list,
+                        negated: *negated,
+                    }))
+                } else {
+                    Ok(expr)
+                }
+            }
+
+            _ => Ok(expr),
+        }
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    use arrow::datatypes::DataType;
+    use datafusion_common::{tree_node::TreeNode, ScalarValue};
+    use datafusion_expr::{col, lit};
+
+    #[test]
+    fn test_null_handling() {
+        // IsNull / IsNotNull can be rewritten to true / false
+        let guarantees = vec![
+            // Note: AlwaysNull case handled by test_column_single_value test,
+            // since it's a special case of a column with a single value.
+            (
+                col("x"),
+                NullableInterval::NotNull {
+                    values: Default::default(),
+                },
+            ),
+        ];
+        let mut rewriter = GuaranteeRewriter::new(guarantees.iter());
+
+        // x IS NULL => guaranteed false
+        let expr = col("x").is_null();
+        let output = expr.clone().rewrite(&mut rewriter).unwrap();
+        assert_eq!(output, lit(false));
+
+        // x IS NOT NULL => guaranteed true
+        let expr = col("x").is_not_null();
+        let output = expr.clone().rewrite(&mut rewriter).unwrap();
+        assert_eq!(output, lit(true));
+    }
+
+    fn validate_simplified_cases<T>(rewriter: &mut GuaranteeRewriter, cases: 
&[(Expr, T)])
+    where
+        ScalarValue: From<T>,
+        T: Clone,
+    {
+        for (expr, expected_value) in cases {
+            let output = expr.clone().rewrite(rewriter).unwrap();
+            let expected = lit(ScalarValue::from(expected_value.clone()));
+            assert_eq!(
+                output, expected,
+                "{} simplified to {}, but expected {}",
+                expr, output, expected
+            );
+        }
+    }
+
+    fn validate_unchanged_cases(rewriter: &mut GuaranteeRewriter, cases: 
&[Expr]) {
+        for expr in cases {
+            let output = expr.clone().rewrite(rewriter).unwrap();
+            assert_eq!(
+                &output, expr,
+                "{} was simplified to {}, but expected it to be unchanged",
+                expr, output
+            );
+        }
+    }
+
+    #[test]
+    fn test_inequalities_non_null_bounded() {
+        let guarantees = vec![
+            // x ∈ (1, 3] (not null)
+            (
+                col("x"),
+                NullableInterval::NotNull {
+                    values: Interval::make(Some(1_i32), Some(3_i32), (true, 
false)),
+                },
+            ),
+        ];
+
+        let mut rewriter = GuaranteeRewriter::new(guarantees.iter());
+
+        // (original_expr, expected_simplification)
+        let simplified_cases = &[
+            (col("x").lt_eq(lit(1)), false),
+            (col("x").lt_eq(lit(3)), true),
+            (col("x").gt(lit(3)), false),
+            (col("x").gt(lit(1)), true),
+            (col("x").eq(lit(0)), false),
+            (col("x").not_eq(lit(0)), true),
+            (col("x").between(lit(2), lit(5)), true),
+            (col("x").between(lit(5), lit(10)), false),

Review Comment:
   Good idea. Added.



-- 
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: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to