rishvin commented on code in PR #1971:
URL: https://github.com/apache/datafusion-comet/pull/1971#discussion_r2178359783


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

Review Comment:
   Borrowed this code from 
https://github.com/apache/datafusion-comet/blob/2dd6ca23c80261b80db79d610dca3d4cf88a695f/native/core/src/execution/planner.rs#L885.
 We were doing these casting before creating modulo operation.



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

Reply via email to