Jefffrey commented on code in PR #18205: URL: https://github.com/apache/datafusion/pull/18205#discussion_r2532919978
########## parquet-testing: ########## Review Comment: These submodule changes are intended? ########## datafusion/spark/src/function/math/abs.rs: ########## @@ -0,0 +1,432 @@ +// 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 datafusion_common::{internal_err, DataFusionError, Result, ScalarValue}; +use datafusion_expr::{ + ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl, Signature, Volatility, +}; +use datafusion_functions::{ + downcast_named_arg, make_abs_function, make_wrapping_abs_function, +}; +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. +/// +/// TODOs: +/// - Spark's ANSI-compliant dialect, when off (i.e. `spark.sql.ansi.enabled=false`), taking absolute value on the minimal value of a signed integer 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::numeric(1, 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>> { Review Comment: Remove `coerce_types`, only relevant if signature is user defined ########## datafusion/spark/src/function/math/abs.rs: ########## @@ -0,0 +1,432 @@ +// 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 datafusion_common::{internal_err, DataFusionError, Result, ScalarValue}; +use datafusion_expr::{ + ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl, Signature, Volatility, +}; +use datafusion_functions::{ + downcast_named_arg, make_abs_function, make_wrapping_abs_function, +}; +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. +/// +/// TODOs: +/// - Spark's ANSI-compliant dialect, when off (i.e. `spark.sql.ansi.enabled=false`), taking absolute value on the minimal value of a signed integer 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::numeric(1, 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() != 1 { + return Err(invalid_arg_count_exec_err("abs", (1, 1), 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(_, _) => 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", + &arg_types[0], + )) + } + } + } + } +} + +macro_rules! scalar_compute_op { + ($INPUT:ident, $SCALAR_TYPE:ident) => {{ + let result = $INPUT.wrapping_abs(); + Ok(ColumnarValue::Scalar(ScalarValue::$SCALAR_TYPE(Some( + result, + )))) + }}; + ($INPUT:ident, $PRECISION:expr, $SCALE:expr, $SCALAR_TYPE:ident) => {{ + let result = $INPUT.wrapping_abs(); + Ok(ColumnarValue::Scalar(ScalarValue::$SCALAR_TYPE( + Some(result), + $PRECISION, + $SCALE, + ))) + }}; +} + +pub fn spark_abs(args: &[ColumnarValue]) -> Result<ColumnarValue, DataFusionError> { + if args.len() != 1 { + return internal_err!("abs takes exactly 1 argument, but got: {}", args.len()); + } + + match &args[0] { + ColumnarValue::Array(array) => match array.data_type() { + DataType::Null + | DataType::UInt8 + | DataType::UInt16 + | DataType::UInt32 + | DataType::UInt64 => Ok(args[0].clone()), + DataType::Int8 => { + let abs_fun = make_wrapping_abs_function!(Int8Array); + abs_fun(array).map(ColumnarValue::Array) + } + DataType::Int16 => { + let abs_fun = make_wrapping_abs_function!(Int16Array); + abs_fun(array).map(ColumnarValue::Array) + } + DataType::Int32 => { + let abs_fun = make_wrapping_abs_function!(Int32Array); + abs_fun(array).map(ColumnarValue::Array) + } + DataType::Int64 => { + let abs_fun = make_wrapping_abs_function!(Int64Array); + abs_fun(array).map(ColumnarValue::Array) + } + DataType::Float32 => { + let abs_fun = make_abs_function!(Float32Array); + abs_fun(array).map(ColumnarValue::Array) + } + DataType::Float64 => { + let abs_fun = make_abs_function!(Float64Array); + abs_fun(array).map(ColumnarValue::Array) + } + DataType::Decimal128(_, _) => { + let abs_fun = make_wrapping_abs_function!(Decimal128Array); + abs_fun(array).map(ColumnarValue::Array) + } + DataType::Decimal256(_, _) => { + let abs_fun = make_wrapping_abs_function!(Decimal256Array); + abs_fun(array).map(ColumnarValue::Array) + } + dt => internal_err!("Not supported datatype for Spark ABS: {dt}"), + }, + ColumnarValue::Scalar(sv) => match sv { + ScalarValue::Null + | ScalarValue::UInt8(_) + | ScalarValue::UInt16(_) + | ScalarValue::UInt32(_) + | ScalarValue::UInt64(_) => Ok(args[0].clone()), + ScalarValue::Int8(a) => match a { + None => Ok(args[0].clone()), + Some(v) => scalar_compute_op!(v, Int8), + }, + ScalarValue::Int16(a) => match a { + None => Ok(args[0].clone()), + Some(v) => scalar_compute_op!(v, Int16), + }, Review Comment: ```suggestion | ScalarValue::UInt64(_) => Ok(args[0].clone()), sv if sv.is_null() => Ok(args[0].clone()), ScalarValue::Int8(Some(v)) => scalar_compute_op!(v, Int8), ScalarValue::Int16(Some(v)) => scalar_compute_op!(v, Int16), ``` Slight more compact way of doing this -- 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]
