rishvin commented on code in PR #1971: URL: https://github.com/apache/datafusion-comet/pull/1971#discussion_r2178356222
########## native/spark-expr/src/math_funcs/modulo_expr.rs: ########## @@ -0,0 +1,513 @@ +// 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 crate::IfExpr; +use crate::{divide_by_zero_error, Cast, EvalMode, SparkCastOptions}; +use arrow::array::*; +use arrow::datatypes::*; +use datafusion::common::{internal_err, DataFusionError, Result, ScalarValue}; +use datafusion::logical_expr::binary::BinaryTypeCoercer; +use datafusion::logical_expr::sort_properties::ExprProperties; +use datafusion::logical_expr::statistics::Distribution::Gaussian; +use datafusion::logical_expr::statistics::{ + combine_gaussians, new_generic_from_binary_op, Distribution, +}; +use datafusion::logical_expr_common::interval_arithmetic::apply_operator; +use datafusion::physical_expr::expressions::{lit, BinaryExpr}; +use datafusion::physical_expr::intervals::cp_solver::propagate_arithmetic; +use datafusion::physical_expr_common::datum::{apply, apply_cmp_for_nested}; +use datafusion::{ + logical_expr::{interval_arithmetic::Interval, ColumnarValue, Operator}, + physical_expr::PhysicalExpr, +}; +use std::cmp::max; +use std::hash::Hash; +use std::{any::Any, sync::Arc}; + +#[derive(Debug, Eq)] +pub struct ModuloExpr { + left: Arc<dyn PhysicalExpr>, + right: Arc<dyn PhysicalExpr>, + + // Specifies whether the modulo expression should fail on error. If true, the modulo expression + // will be ANSI-compliant. + fail_on_error: bool, +} + +impl PartialEq for ModuloExpr { + fn eq(&self, other: &Self) -> bool { + self.left.eq(&other.left) + && self.right.eq(&other.right) + && self.fail_on_error.eq(&other.fail_on_error) + } +} +impl Hash for ModuloExpr { + fn hash<H: std::hash::Hasher>(&self, state: &mut H) { + self.left.hash(state); + self.right.hash(state); + self.fail_on_error.hash(state); + } +} + +fn is_primitive_datatype(dt: &DataType) -> bool { + matches!( + dt, + DataType::Int8 + | DataType::Int16 + | DataType::Int32 + | DataType::Int64 + | DataType::UInt8 + | DataType::UInt16 + | DataType::UInt32 + | DataType::UInt64 + | DataType::Float32 + | DataType::Float64 + | DataType::Decimal128(_, _) + | DataType::Decimal256(_, _) + ) +} + +fn null_if_zero_primitive( + expression: Arc<dyn PhysicalExpr>, + input_schema: &Schema, +) -> Result<Arc<dyn PhysicalExpr>, DataFusionError> { + let expr_data_type = expression.data_type(input_schema)?; + + if is_primitive_datatype(&expr_data_type) { + let zero = match expr_data_type { + DataType::Int8 => ScalarValue::Int8(Some(0)), + DataType::Int16 => ScalarValue::Int16(Some(0)), + DataType::Int32 => ScalarValue::Int32(Some(0)), + DataType::Int64 => ScalarValue::Int64(Some(0)), + DataType::UInt8 => ScalarValue::UInt8(Some(0)), + DataType::UInt16 => ScalarValue::UInt16(Some(0)), + DataType::UInt32 => ScalarValue::UInt32(Some(0)), + DataType::UInt64 => ScalarValue::UInt64(Some(0)), + DataType::Float32 => ScalarValue::Float32(Some(0.0)), + DataType::Float64 => ScalarValue::Float64(Some(0.0)), + DataType::Decimal128(s, p) => ScalarValue::Decimal128(Some(0), s, p), + DataType::Decimal256(s, p) => ScalarValue::Decimal256(Some(i256::from(0)), s, p), + _ => return Ok(expression), + }; + + // Create an expression: if (expression == 0) then null else expression. + // This expression evaluates to null for rows with zero values to prevent divide by zero + // error. + let eq_expr = Arc::new(BinaryExpr::new(Arc::<dyn PhysicalExpr>::clone(&expression), Operator::Eq, lit(zero))); + let null_literal = lit(ScalarValue::try_new_null(&expr_data_type)?); + let exp = Arc::new(IfExpr::new(eq_expr, null_literal, expression)); + Ok(exp) + } else { + Ok(expression) + } +} + +pub fn create_modulo_expr( + left: Arc<dyn PhysicalExpr>, + right: Arc<dyn PhysicalExpr>, + data_type: DataType, + input_schema: SchemaRef, + fail_on_error: bool, +) -> Result<Arc<dyn PhysicalExpr>, DataFusionError> { + // For non-ANSI mode, wrap the right expression with null-if-zero logic + let wrapped_right = if !fail_on_error { + null_if_zero_primitive(right, &input_schema)? + } else { + right + }; + + // If the data type is Decimal128 and the precision/scale exceeds the maximum allowed for + // Decimal256, then cast both operands to Decimal256 before creating the modulo expression, + // otherwise, create the modulo expression directly. + match ( + left.data_type(&input_schema), + wrapped_right.data_type(&input_schema), + ) { + (Ok(DataType::Decimal128(p1, s1)), Ok(DataType::Decimal128(p2, s2))) + if max(s1, s2) as u8 + max(p1 - s1 as u8, p2 - s2 as u8) > DECIMAL128_MAX_PRECISION => + { + let left = Arc::new(Cast::new( + left, + DataType::Decimal256(p1, s1), + SparkCastOptions::new_without_timezone(EvalMode::Legacy, false), + )); + let right = Arc::new(Cast::new( + wrapped_right, + DataType::Decimal256(p2, s2), + SparkCastOptions::new_without_timezone(EvalMode::Legacy, false), + )); + let child = Arc::new(ModuloExpr::new(left, right, fail_on_error)); + Ok(Arc::new(Cast::new( + child, + data_type, + SparkCastOptions::new_without_timezone(EvalMode::Legacy, false), + ))) + } + _ => Ok(Arc::new(ModuloExpr::new( + left, + wrapped_right, + fail_on_error, + ))), + } +} + +impl ModuloExpr { + pub fn new( + left: Arc<dyn PhysicalExpr>, + right: Arc<dyn PhysicalExpr>, + fail_on_error: bool, + ) -> Self { + Self { + left, + right, + fail_on_error, + } + } +} + +impl std::fmt::Display for ModuloExpr { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + write!(f, "({})", self.left.as_ref())?; + write!(f, " {} ", &Operator::Modulo)?; + write!(f, "({})", self.right.as_ref())?; + Ok(()) + } +} + +impl PhysicalExpr for ModuloExpr { + fn as_any(&self) -> &dyn Any { + self + } + + fn data_type(&self, input_schema: &Schema) -> Result<DataType> { + BinaryTypeCoercer::new( + &self.left.data_type(input_schema)?, + &Operator::Modulo, + &self.right.data_type(input_schema)?, + ) + .get_result_type() + } + + fn nullable(&self, input_schema: &Schema) -> Result<bool> { + Ok(self.left.nullable(input_schema)? || self.right.nullable(input_schema)?) + } + + fn evaluate(&self, batch: &RecordBatch) -> Result<ColumnarValue> { + use arrow::compute::kernels::numeric::*; + + let lhs = self.left.evaluate(batch)?; + let rhs = self.right.evaluate(batch)?; + + let left_data_type = lhs.data_type(); + let right_data_type = rhs.data_type(); + + if left_data_type.is_nested() { + if right_data_type != left_data_type { + return internal_err!("type mismatch for modulo operation"); + } + return apply_cmp_for_nested(Operator::Modulo, &lhs, &rhs); + } + + match apply(&lhs, &rhs, rem) { + Ok(result) => Ok(result), + Err(e) if e.to_string().contains("Divide by zero") && self.fail_on_error => { + // Return Spark-compliant divide by zero error. + Err(divide_by_zero_error().into()) + } + Err(e) => Err(e), + } + } + + fn children(&self) -> Vec<&Arc<dyn PhysicalExpr>> { + vec![&self.left, &self.right] + } + + fn with_new_children( + self: Arc<Self>, + children: Vec<Arc<dyn PhysicalExpr>>, + ) -> Result<Arc<dyn PhysicalExpr>> { + Ok(Arc::new(ModuloExpr::new( + Arc::clone(&children[0]), + Arc::clone(&children[1]), + self.fail_on_error, + ))) + } + + fn evaluate_bounds(&self, children: &[&Interval]) -> Result<Interval> { + let left_interval = children[0]; + let right_interval = children[1]; + apply_operator(&Operator::Modulo, left_interval, right_interval) + } + + fn propagate_constraints( + &self, + interval: &Interval, + children: &[&Interval], + ) -> Result<Option<Vec<Interval>>> { + let left_interval = children[0]; + let right_interval = children[1]; + Ok( + propagate_arithmetic(&Operator::Modulo, interval, left_interval, right_interval)? + .map(|(left, right)| vec![left, right]), + ) + } + + fn evaluate_statistics(&self, children: &[&Distribution]) -> Result<Distribution> { + let (left, right) = (children[0], children[1]); + + if let (Gaussian(left), Gaussian(right)) = (left, right) { Review Comment: Borrowed these changes from `BinaryExpr` expression. -- 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-unsubscr...@datafusion.apache.org For queries about this service, please contact Infrastructure at: us...@infra.apache.org --------------------------------------------------------------------- To unsubscribe, e-mail: github-unsubscr...@datafusion.apache.org For additional commands, e-mail: github-h...@datafusion.apache.org