wjones127 commented on code in PR #7467: URL: https://github.com/apache/arrow-datafusion/pull/7467#discussion_r1323600203
########## 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())), + } Review Comment: This is one of those awkward closures where we are returning `Option<Result<_>>`, so early returning result doesn't quite work. But you are right it can be simplified. 👍 ########## 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())), + } Review Comment: This is one of those awkward closures where we are returning `Option<Result<_>>`, so early returning result doesn't quite work. But you are right it can be simplified. 👍 -- 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]
