hsiang-c commented on code in PR #18205:
URL: https://github.com/apache/datafusion/pull/18205#discussion_r2507640412


##########
datafusion/spark/src/function/math/abs.rs:
##########
@@ -0,0 +1,1136 @@
+// 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::function::error_utils::{
+    invalid_arg_count_exec_err, unsupported_data_type_exec_err,
+};
+use arrow::array::*;
+use arrow::datatypes::DataType;
+use arrow::datatypes::*;
+use datafusion_common::DataFusionError::ArrowError;
+use datafusion_common::{internal_err, DataFusionError, Result, ScalarValue};
+use datafusion_expr::{
+    ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl, Signature, Volatility,
+};
+use std::any::Any;
+use std::sync::Arc;
+
+/// Spark-compatible `abs` expression
+/// <https://spark.apache.org/docs/latest/api/sql/index.html#abs>
+///
+/// Returns the absolute value of input
+/// Returns NULL if input is NULL, returns NaN if input is NaN.
+///
+/// Differences with DataFusion abs:
+///  - Spark's ANSI-compliant dialect, when off (i.e. 
`spark.sql.ansi.enabled=false`), taking absolute values on minimal values of 
signed integers returns the value as is. DataFusion's abs throws "DataFusion 
error: Arrow error: Compute error" on arithmetic overflow
+///  - Spark's abs also supports ANSI interval types: YearMonthIntervalType 
and DayTimeIntervalType. DataFusion's abs doesn't.
+///
+#[derive(Debug, PartialEq, Eq, Hash)]
+pub struct SparkAbs {
+    signature: Signature,
+}
+
+impl Default for SparkAbs {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
+impl SparkAbs {
+    pub fn new() -> Self {
+        Self {
+            signature: Signature::user_defined(Volatility::Immutable),
+        }
+    }
+}
+
+impl ScalarUDFImpl for SparkAbs {
+    fn as_any(&self) -> &dyn Any {
+        self
+    }
+
+    fn name(&self) -> &str {
+        "abs"
+    }
+
+    fn signature(&self) -> &Signature {
+        &self.signature
+    }
+
+    fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
+        Ok(arg_types[0].clone())
+    }
+
+    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> 
Result<ColumnarValue> {
+        spark_abs(&args.args)
+    }
+
+    fn coerce_types(&self, arg_types: &[DataType]) -> Result<Vec<DataType>> {
+        if arg_types.len() > 2 {
+            return Err(invalid_arg_count_exec_err("abs", (1, 2), 
arg_types.len()));
+        }
+        match &arg_types[0] {
+            DataType::Null
+            | DataType::UInt8
+            | DataType::UInt16
+            | DataType::UInt32
+            | DataType::UInt64
+            | DataType::Int8
+            | DataType::Int16
+            | DataType::Int32
+            | DataType::Int64
+            | DataType::Float32
+            | DataType::Float64
+            | DataType::Decimal128(_, _)
+            | DataType::Decimal256(_, _)
+            | DataType::Interval(IntervalUnit::YearMonth)
+            | DataType::Interval(IntervalUnit::DayTime) => 
Ok(vec![arg_types[0].clone()]),
+            other => {
+                if other.is_numeric() {
+                    Ok(vec![DataType::Float64])
+                } else {
+                    Err(unsupported_data_type_exec_err(
+                        "abs",
+                        "Numeric Type or Interval Type",
+                        &arg_types[0],
+                    ))
+                }
+            }
+        }
+    }
+}
+
+macro_rules! legacy_compute_op {
+    ($ARRAY:expr, $FUNC:ident, $TYPE:ident, $RESULT:ident) => {{
+        let n = $ARRAY.as_any().downcast_ref::<$TYPE>();
+        match n {
+            Some(array) => {
+                let res: $RESULT =
+                    arrow::compute::kernels::arity::unary(array, |x| 
x.$FUNC());
+                Ok(res)
+            }
+            _ => Err(DataFusionError::Internal(format!(
+                "Invalid data type for abs"
+            ))),
+        }
+    }};
+}
+
+macro_rules! ansi_compute_op {
+    ($ARRAY:expr, $FUNC:ident, $TYPE:ident, $RESULT:ident, $NATIVE:ident, 
$FROM_TYPE:expr) => {{
+        let n = $ARRAY.as_any().downcast_ref::<$TYPE>();
+        match n {
+            Some(array) => {
+                match arrow::compute::kernels::arity::try_unary(array, |x| {
+                    if x == $NATIVE::MIN {
+                        Err(arrow::error::ArrowError::ArithmeticOverflow(
+                            $FROM_TYPE.to_string(),
+                        ))
+                    } else {
+                        Ok(x.$FUNC())
+                    }
+                }) {
+                    Ok(res) => Ok(ColumnarValue::Array(
+                        Arc::<PrimitiveArray<$RESULT>>::new(res),
+                    )),
+                    Err(_) => Err(arithmetic_overflow_error($FROM_TYPE)),
+                }
+            }
+            _ => Err(DataFusionError::Internal("Invalid data 
type".to_string())),
+        }
+    }};
+}
+
+fn arithmetic_overflow_error(from_type: &str) -> DataFusionError {
+    ArrowError(
+        Box::from(arrow::error::ArrowError::ComputeError(format!(
+            "arithmetic overflow from {from_type}",
+        ))),
+        None,
+    )
+}
+
+pub fn spark_abs(args: &[ColumnarValue]) -> Result<ColumnarValue, 
DataFusionError> {
+    if args.len() > 2 {
+        return internal_err!("abs takes at most 2 arguments, but got: {}", 
args.len());
+    }
+
+    let fail_on_error = if args.len() == 2 {
+        match &args[1] {
+            ColumnarValue::Scalar(ScalarValue::Boolean(Some(fail_on_error))) 
=> {
+                *fail_on_error
+            }

Review Comment:
   @Jefffrey It is tested by `test_abs_incorrect_arg` now.



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


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to