You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@datafusion.apache.org by "hsiang-c (via GitHub)" <gi...@apache.org> on 2025/10/21 17:05:16 UTC
[PR] feat: support Spark-compatible `abs` math function [datafusion]
hsiang-c opened a new pull request, #18205:
URL: https://github.com/apache/datafusion/pull/18205
## Which issue does this PR close?
<!--
We generally require a GitHub issue to be filed for all bug fixes and enhancements and this helps us generate change logs for our releases. You can link an issue to this PR using the GitHub syntax. For example `Closes #123` indicates that this PR will close issue #123.
-->
- Partially Closes #15914
## Rationale for this change
<!--
Why are you proposing this change? If this is already explained clearly in the issue then this section is not needed.
Explaining clearly why changes are proposed helps reviewers understand your changes and offer better suggestions for fixes.
-->
- Apache Spark's `abs()` behaves differently than DataFusion.
- Apache Spark's [ANSI-compliant](https://spark.apache.org/docs/latest/sql-ref-ansi-compliance.html#ansi-compliance) dialect can be toggled by SparkConf `spark.sql.ansi.enabled`. When it is off, arithmetic overflow doesn't throw exception like DataFusion does.
- Apache Spark's abs also supports ANSI interval types: `YearMonthIntervalType` and `DayTimeIntervalType`
- DataFusion Comet can leverage it at https://github.com/apache/datafusion-comet/pull/2595
## What changes are included in this PR?
<!--
There is no need to duplicate the description in the issue here but it is sometimes worth providing a summary of the individual changes in this PR.
-->
- Mimics Apache Spark `v4.0.1` [abs expression](https://github.com/apache/spark/blob/v4.0.1/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/arithmetic.scala#L148)
- DataFusion Spark's `abs()` API takes an additional flag `fail_on_error` if `spark.sql.ansi.enabled=true` at caller's side.
## Are these changes tested?
<!--
We typically require tests for all PRs in order to:
1. Prevent the code from being accidentally broken by subsequent changes
2. Serve as another way to document the expected behavior of the code
If tests are not included in your PR, please explain why (for example, are they covered by existing tests)?
-->
- unit tests
- sqllogictest: `test_files/spark/math/abs.slt`
## Are there any user-facing changes?
<!--
If there are user-facing changes then we may require documentation to be updated before approving the PR.
-->
Yes, the abs function can be specified in the SQL.
- Arithmetic overflow will be thrown when `spark.sql.ansi.enabled=true`
- Support ANSI interval types: `YearMonthIntervalType` and `DayTimeIntervalType`
<!--
If there are any breaking changes to public APIs, please add the `api change` label.
-->
--
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-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat: support Spark-compatible `abs` math function part 1 - non-ANSI mode [datafusion]
Posted by "comphead (via GitHub)" <gi...@apache.org>.
comphead commented on code in PR #18205:
URL: https://github.com/apache/datafusion/pull/18205#discussion_r2540101773
##########
datafusion/sqllogictest/test_files/spark/math/abs.slt:
##########
@@ -23,10 +23,75 @@
## Original Query: SELECT abs(-1);
## PySpark 3.5.5 Result: {'abs(-1)': 1, 'typeof(abs(-1))': 'int', 'typeof(-1)': 'int'}
-#query
-#SELECT abs(-1::int);
+
+# abs: signed int and NULL
+query IIIIR
+SELECT abs(-127::TINYINT), abs(-32767::SMALLINT), abs(-2147483647::INT), abs(-9223372036854775807::BIGINT), abs(NULL);
+----
+127 32767 2147483647 9223372036854775807 NULL
+
+
+# See https://github.com/apache/datafusion/issues/18794 for operator precedence
+# abs: signed int minimal values
+query IIII
+select abs((-128)::TINYINT), abs((-32768)::SMALLINT), abs((-2147483648)::INT), abs((-9223372036854775808)::BIGINT)
+----
+-128 -32768 -2147483648 -9223372036854775808
+
+# abs: floats, NULL and NaN
Review Comment:
Thanks @hsiang-c can we also add -Inf, Inf for float/double and -0.0
--
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-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat: support Spark-compatible `abs` math function [datafusion]
Posted by "hsiang-c (via GitHub)" <gi...@apache.org>.
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat: support Spark-compatible `abs` math function part 1 - non-ANSI mode [datafusion]
Posted by "hsiang-c (via GitHub)" <gi...@apache.org>.
hsiang-c commented on code in PR #18205:
URL: https://github.com/apache/datafusion/pull/18205#discussion_r2540649863
##########
datafusion/sqllogictest/test_files/spark/math/abs.slt:
##########
@@ -23,10 +23,75 @@
## Original Query: SELECT abs(-1);
## PySpark 3.5.5 Result: {'abs(-1)': 1, 'typeof(abs(-1))': 'int', 'typeof(-1)': 'int'}
-#query
-#SELECT abs(-1::int);
+
+# abs: signed int and NULL
+query IIIIR
+SELECT abs(-127::TINYINT), abs(-32767::SMALLINT), abs(-2147483647::INT), abs(-9223372036854775807::BIGINT), abs(NULL);
+----
+127 32767 2147483647 9223372036854775807 NULL
+
+
+# See https://github.com/apache/datafusion/issues/18794 for operator precedence
+# abs: signed int minimal values
+query IIII
+select abs((-128)::TINYINT), abs((-32768)::SMALLINT), abs((-2147483648)::INT), abs((-9223372036854775808)::BIGINT)
+----
+-128 -32768 -2147483648 -9223372036854775808
+
+# abs: floats, NULL and NaN
Review Comment:
Good catch, added.
--
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-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat: support Spark-compatible `abs` math function [datafusion]
Posted by "Jefffrey (via GitHub)" <gi...@apache.org>.
Jefffrey commented on code in PR #18205:
URL: https://github.com/apache/datafusion/pull/18205#discussion_r2450070803
##########
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,
+ )
+}
Review Comment:
I feel we should return a `DataFusionError::Execution` here instead of creating an arrow error and wrapping it in datafusion error, given the error occurs in our datafusion code
##########
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) => {
Review Comment:
I would prefer if we unwrap `n` directly instead of matching on it, as we are guaranteed it would be of the correct array type; same goes for `ansi_compute_op` below
##########
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:
Is this branch actually being tested?
##########
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
+ }
+ _ => {
+ return internal_err!(
+ "The second argument must be boolean scalar, but got: {:?}",
+ args[1]
+ );
+ }
+ }
+ } else {
+ false
+ };
+
+ 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 => {
+ if !fail_on_error {
+ let result =
+ legacy_compute_op!(array, wrapping_abs, Int8Array, Int8Array);
+ Ok(ColumnarValue::Array(Arc::new(result?)))
+ } else {
+ ansi_compute_op!(array, abs, Int8Array, Int8Type, i8, "Int8")
+ }
+ }
+ DataType::Int16 => {
+ if !fail_on_error {
+ let result =
+ legacy_compute_op!(array, wrapping_abs, Int16Array, Int16Array);
+ Ok(ColumnarValue::Array(Arc::new(result?)))
+ } else {
+ ansi_compute_op!(array, abs, Int16Array, Int16Type, i16, "Int16")
+ }
+ }
+ DataType::Int32 => {
+ if !fail_on_error {
+ let result =
+ legacy_compute_op!(array, wrapping_abs, Int32Array, Int32Array);
+ Ok(ColumnarValue::Array(Arc::new(result?)))
+ } else {
+ ansi_compute_op!(array, abs, Int32Array, Int32Type, i32, "Int32")
+ }
+ }
+ DataType::Int64 => {
+ if !fail_on_error {
+ let result =
+ legacy_compute_op!(array, wrapping_abs, Int64Array, Int64Array);
+ Ok(ColumnarValue::Array(Arc::new(result?)))
+ } else {
+ ansi_compute_op!(array, abs, Int64Array, Int64Type, i64, "Int64")
+ }
+ }
+ DataType::Float32 => {
+ let result = legacy_compute_op!(array, abs, Float32Array, Float32Array);
+ Ok(ColumnarValue::Array(Arc::new(result?)))
+ }
+ DataType::Float64 => {
+ let result = legacy_compute_op!(array, abs, Float64Array, Float64Array);
+ Ok(ColumnarValue::Array(Arc::new(result?)))
+ }
+ DataType::Decimal128(precision, scale) => {
+ if !fail_on_error {
+ let result = legacy_compute_op!(
+ array,
+ wrapping_abs,
+ Decimal128Array,
+ Decimal128Array
+ )?;
+ let result =
+ result.with_data_type(DataType::Decimal128(*precision, *scale));
+ Ok(ColumnarValue::Array(Arc::new(result)))
+ } else {
+ // Need to pass precision and scale from input, so not using ansi_compute_op
+ let input = array.as_any().downcast_ref::<Decimal128Array>();
+ match input {
+ Some(i) => {
+ match arrow::compute::kernels::arity::try_unary(i, |x| {
+ if x == i128::MIN {
+ Err(arrow::error::ArrowError::ArithmeticOverflow(
+ "Decimal128".to_string(),
+ ))
+ } else {
+ Ok(x.abs())
+ }
+ }) {
+ Ok(res) => Ok(ColumnarValue::Array(Arc::<
+ PrimitiveArray<Decimal128Type>,
+ >::new(
+ res.with_data_type(DataType::Decimal128(
+ *precision, *scale,
+ )),
+ ))),
+ Err(_) => Err(arithmetic_overflow_error("Decimal128")),
+ }
+ }
+ _ => Err(DataFusionError::Internal(
+ "Invalid data type".to_string(),
+ )),
+ }
+ }
+ }
+ DataType::Decimal256(precision, scale) => {
+ if !fail_on_error {
+ let result = legacy_compute_op!(
+ array,
+ wrapping_abs,
+ Decimal256Array,
+ Decimal256Array
+ )?;
+ let result =
+ result.with_data_type(DataType::Decimal256(*precision, *scale));
+ Ok(ColumnarValue::Array(Arc::new(result)))
+ } else {
+ // Need to pass precision and scale from input, so not using ansi_compute_op
+ let input = array.as_any().downcast_ref::<Decimal256Array>();
+ match input {
+ Some(i) => {
+ match arrow::compute::kernels::arity::try_unary(i, |x| {
+ if x == i256::MIN {
+ Err(arrow::error::ArrowError::ArithmeticOverflow(
+ "Decimal256".to_string(),
+ ))
+ } else {
+ Ok(x.wrapping_abs()) // i256 doesn't define abs() method
+ }
+ }) {
+ Ok(res) => Ok(ColumnarValue::Array(Arc::<
+ PrimitiveArray<Decimal256Type>,
+ >::new(
+ res.with_data_type(DataType::Decimal256(
+ *precision, *scale,
+ )),
+ ))),
+ Err(_) => Err(arithmetic_overflow_error("Decimal256")),
+ }
+ }
+ _ => Err(DataFusionError::Internal(
+ "Invalid data type".to_string(),
+ )),
+ }
+ }
+ }
+ DataType::Interval(unit) => match unit {
+ IntervalUnit::YearMonth => {
+ let result = legacy_compute_op!(
+ array,
+ wrapping_abs,
+ IntervalYearMonthArray,
+ IntervalYearMonthArray
+ )?;
+ let result = result.with_data_type(DataType::Interval(*unit));
+ Ok(ColumnarValue::Array(Arc::new(result)))
+ }
+ IntervalUnit::DayTime => {
+ let result = legacy_compute_op!(
+ array,
+ wrapping_abs,
+ IntervalDayTimeArray,
+ IntervalDayTimeArray
+ )?;
+ let result = result.with_data_type(DataType::Interval(*unit));
+ Ok(ColumnarValue::Array(Arc::new(result)))
+ }
+ IntervalUnit::MonthDayNano => internal_err!(
+ "MonthDayNano is not a supported Interval unit for Spark ABS"
+ ),
+ },
+ 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) => a
+ .map(|v| match v.checked_abs() {
+ Some(abs_val) => {
+ Ok(ColumnarValue::Scalar(ScalarValue::Int8(Some(abs_val))))
+ }
+ None => {
+ if !fail_on_error {
+ // return the original value
+ Ok(ColumnarValue::Scalar(ScalarValue::Int8(Some(v))))
+ } else {
+ Err(arithmetic_overflow_error("Int8"))
+ }
+ }
+ })
+ .unwrap(),
+ ScalarValue::Int16(a) => a
+ .map(|v| match v.checked_abs() {
+ Some(abs_val) => {
+ Ok(ColumnarValue::Scalar(ScalarValue::Int16(Some(abs_val))))
+ }
+ None => {
+ if !fail_on_error {
+ // return the original value
+ Ok(ColumnarValue::Scalar(ScalarValue::Int16(Some(v))))
+ } else {
+ Err(arithmetic_overflow_error("Int16"))
+ }
+ }
+ })
+ .unwrap(),
+ ScalarValue::Int32(a) => a
+ .map(|v| match v.checked_abs() {
+ Some(abs_val) => {
+ Ok(ColumnarValue::Scalar(ScalarValue::Int32(Some(abs_val))))
+ }
+ None => {
+ if !fail_on_error {
+ // return the original value
+ Ok(ColumnarValue::Scalar(ScalarValue::Int32(Some(v))))
+ } else {
+ Err(arithmetic_overflow_error("Int32"))
+ }
+ }
+ })
+ .unwrap(),
+ ScalarValue::Int64(a) => a
+ .map(|v| match v.checked_abs() {
+ Some(abs_val) => {
+ Ok(ColumnarValue::Scalar(ScalarValue::Int64(Some(abs_val))))
+ }
+ None => {
+ if !fail_on_error {
+ // return the original value
+ Ok(ColumnarValue::Scalar(ScalarValue::Int64(Some(v))))
+ } else {
+ Err(arithmetic_overflow_error("Int64"))
+ }
+ }
+ })
+ .unwrap(),
+ ScalarValue::Float32(a) => Ok(ColumnarValue::Scalar(
+ ScalarValue::Float32(a.map(|x| x.abs())),
+ )),
+ ScalarValue::Float64(a) => Ok(ColumnarValue::Scalar(
+ ScalarValue::Float64(a.map(|x| x.abs())),
+ )),
+ ScalarValue::Decimal128(a, precision, scale) => a
+ .map(|v| match v.checked_abs() {
+ Some(abs_val) => Ok(ColumnarValue::Scalar(
+ ScalarValue::Decimal128(Some(abs_val), *precision, *scale),
+ )),
+ None => {
+ if !fail_on_error {
+ // return the original value
+ Ok(ColumnarValue::Scalar(ScalarValue::Decimal128(
+ Some(v),
+ *precision,
+ *scale,
+ )))
+ } else {
+ Err(arithmetic_overflow_error("Decimal128"))
+ }
+ }
+ })
+ .unwrap(),
+ ScalarValue::Decimal256(a, precision, scale) => a
+ .map(|v| match v.checked_abs() {
+ Some(abs_val) => Ok(ColumnarValue::Scalar(
+ ScalarValue::Decimal256(Some(abs_val), *precision, *scale),
+ )),
+ None => {
+ if !fail_on_error {
+ // return the original value
+ Ok(ColumnarValue::Scalar(ScalarValue::Decimal256(
+ Some(v),
+ *precision,
+ *scale,
+ )))
+ } else {
+ Err(arithmetic_overflow_error("Decimal256"))
+ }
+ }
+ })
+ .unwrap(),
+ ScalarValue::IntervalYearMonth(a) => {
+ let result = a.map(|v| v.wrapping_abs());
+ Ok(ColumnarValue::Scalar(ScalarValue::IntervalYearMonth(
+ result,
+ )))
+ }
+ ScalarValue::IntervalDayTime(a) => {
+ let result = a.map(|v| v.wrapping_abs());
+ Ok(ColumnarValue::Scalar(ScalarValue::IntervalDayTime(result)))
+ }
+
+ dt => internal_err!("Not supported datatype for Spark ABS: {dt}"),
+ }
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use datafusion_common::cast::{
+ as_decimal128_array, as_decimal256_array, as_float32_array, as_float64_array,
+ as_int16_array, as_int32_array, as_int64_array, as_int8_array,
+ as_interval_dt_array, as_interval_ym_array, as_uint64_array,
+ };
+
+ fn with_fail_on_error<F: Fn(bool) -> Result<()>>(test_fn: F) {
+ for fail_on_error in [true, false] {
+ let _ = test_fn(fail_on_error);
+ }
+ }
+
+ // Unsigned types, return as is
+ #[test]
+ fn test_abs_u8_scalar() {
+ with_fail_on_error(|fail_on_error| {
+ let args = ColumnarValue::Scalar(ScalarValue::UInt8(Some(u8::MAX)));
+ let fail_on_error_arg =
+ ColumnarValue::Scalar(ScalarValue::Boolean(Some(fail_on_error)));
+ match spark_abs(&[args, fail_on_error_arg]) {
+ Ok(ColumnarValue::Scalar(ScalarValue::UInt8(Some(result)))) => {
+ assert_eq!(result, u8::MAX);
+ Ok(())
+ }
+ Err(e) => {
+ if fail_on_error {
+ assert!(
+ e.to_string().contains("ARITHMETIC_OVERFLOW"),
+ "Error message did not match. Actual message: {e}"
+ );
+ Ok(())
+ } else {
+ panic!("Didn't expect error, but got: {e:?}")
+ }
+ }
+ _ => unreachable!(),
+ }
+ });
+ }
Review Comment:
This test design is very confusing; we can't tell if a test case is meant to return Ok or Err as it automatically does the "correct" verification for each case. This automatic way of passing the test on Err should be switched so if we have a test case that is meant to return Err, that is the only thing we check for.
--
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-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat: support Spark-compatible `abs` math function [datafusion]
Posted by "hsiang-c (via GitHub)" <gi...@apache.org>.
hsiang-c commented on code in PR #18205:
URL: https://github.com/apache/datafusion/pull/18205#discussion_r2462593989
##########
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:
The `if` branch is tested by flipping the `fail_or_error` flag in the `with_fail_on_error` helper function. However, you're right, I didn't test the `else` branch. I'll cover it when I refactor the unit tests.
--
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-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat: support Spark-compatible `abs` math function [datafusion]
Posted by "hsiang-c (via GitHub)" <gi...@apache.org>.
hsiang-c commented on code in PR #18205:
URL: https://github.com/apache/datafusion/pull/18205#discussion_r2507640830
##########
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
+ }
+ _ => {
+ return internal_err!(
+ "The second argument must be boolean scalar, but got: {:?}",
+ args[1]
+ );
+ }
+ }
+ } else {
+ false
+ };
+
+ 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 => {
+ if !fail_on_error {
+ let result =
+ legacy_compute_op!(array, wrapping_abs, Int8Array, Int8Array);
+ Ok(ColumnarValue::Array(Arc::new(result?)))
+ } else {
+ ansi_compute_op!(array, abs, Int8Array, Int8Type, i8, "Int8")
+ }
+ }
+ DataType::Int16 => {
+ if !fail_on_error {
+ let result =
+ legacy_compute_op!(array, wrapping_abs, Int16Array, Int16Array);
+ Ok(ColumnarValue::Array(Arc::new(result?)))
+ } else {
+ ansi_compute_op!(array, abs, Int16Array, Int16Type, i16, "Int16")
+ }
+ }
+ DataType::Int32 => {
+ if !fail_on_error {
+ let result =
+ legacy_compute_op!(array, wrapping_abs, Int32Array, Int32Array);
+ Ok(ColumnarValue::Array(Arc::new(result?)))
+ } else {
+ ansi_compute_op!(array, abs, Int32Array, Int32Type, i32, "Int32")
+ }
+ }
+ DataType::Int64 => {
+ if !fail_on_error {
+ let result =
+ legacy_compute_op!(array, wrapping_abs, Int64Array, Int64Array);
+ Ok(ColumnarValue::Array(Arc::new(result?)))
+ } else {
+ ansi_compute_op!(array, abs, Int64Array, Int64Type, i64, "Int64")
+ }
+ }
+ DataType::Float32 => {
+ let result = legacy_compute_op!(array, abs, Float32Array, Float32Array);
+ Ok(ColumnarValue::Array(Arc::new(result?)))
+ }
+ DataType::Float64 => {
+ let result = legacy_compute_op!(array, abs, Float64Array, Float64Array);
+ Ok(ColumnarValue::Array(Arc::new(result?)))
+ }
+ DataType::Decimal128(precision, scale) => {
+ if !fail_on_error {
+ let result = legacy_compute_op!(
+ array,
+ wrapping_abs,
+ Decimal128Array,
+ Decimal128Array
+ )?;
+ let result =
+ result.with_data_type(DataType::Decimal128(*precision, *scale));
+ Ok(ColumnarValue::Array(Arc::new(result)))
+ } else {
+ // Need to pass precision and scale from input, so not using ansi_compute_op
+ let input = array.as_any().downcast_ref::<Decimal128Array>();
+ match input {
+ Some(i) => {
+ match arrow::compute::kernels::arity::try_unary(i, |x| {
+ if x == i128::MIN {
+ Err(arrow::error::ArrowError::ArithmeticOverflow(
+ "Decimal128".to_string(),
+ ))
+ } else {
+ Ok(x.abs())
+ }
+ }) {
+ Ok(res) => Ok(ColumnarValue::Array(Arc::<
+ PrimitiveArray<Decimal128Type>,
+ >::new(
+ res.with_data_type(DataType::Decimal128(
+ *precision, *scale,
+ )),
+ ))),
+ Err(_) => Err(arithmetic_overflow_error("Decimal128")),
+ }
+ }
+ _ => Err(DataFusionError::Internal(
+ "Invalid data type".to_string(),
+ )),
+ }
+ }
+ }
+ DataType::Decimal256(precision, scale) => {
+ if !fail_on_error {
+ let result = legacy_compute_op!(
+ array,
+ wrapping_abs,
+ Decimal256Array,
+ Decimal256Array
+ )?;
+ let result =
+ result.with_data_type(DataType::Decimal256(*precision, *scale));
+ Ok(ColumnarValue::Array(Arc::new(result)))
+ } else {
+ // Need to pass precision and scale from input, so not using ansi_compute_op
+ let input = array.as_any().downcast_ref::<Decimal256Array>();
+ match input {
+ Some(i) => {
+ match arrow::compute::kernels::arity::try_unary(i, |x| {
+ if x == i256::MIN {
+ Err(arrow::error::ArrowError::ArithmeticOverflow(
+ "Decimal256".to_string(),
+ ))
+ } else {
+ Ok(x.wrapping_abs()) // i256 doesn't define abs() method
+ }
+ }) {
+ Ok(res) => Ok(ColumnarValue::Array(Arc::<
+ PrimitiveArray<Decimal256Type>,
+ >::new(
+ res.with_data_type(DataType::Decimal256(
+ *precision, *scale,
+ )),
+ ))),
+ Err(_) => Err(arithmetic_overflow_error("Decimal256")),
+ }
+ }
+ _ => Err(DataFusionError::Internal(
+ "Invalid data type".to_string(),
+ )),
+ }
+ }
+ }
+ DataType::Interval(unit) => match unit {
+ IntervalUnit::YearMonth => {
+ let result = legacy_compute_op!(
+ array,
+ wrapping_abs,
+ IntervalYearMonthArray,
+ IntervalYearMonthArray
+ )?;
+ let result = result.with_data_type(DataType::Interval(*unit));
+ Ok(ColumnarValue::Array(Arc::new(result)))
+ }
+ IntervalUnit::DayTime => {
+ let result = legacy_compute_op!(
+ array,
+ wrapping_abs,
+ IntervalDayTimeArray,
+ IntervalDayTimeArray
+ )?;
+ let result = result.with_data_type(DataType::Interval(*unit));
+ Ok(ColumnarValue::Array(Arc::new(result)))
+ }
+ IntervalUnit::MonthDayNano => internal_err!(
+ "MonthDayNano is not a supported Interval unit for Spark ABS"
+ ),
+ },
+ 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) => a
+ .map(|v| match v.checked_abs() {
+ Some(abs_val) => {
+ Ok(ColumnarValue::Scalar(ScalarValue::Int8(Some(abs_val))))
+ }
+ None => {
+ if !fail_on_error {
+ // return the original value
+ Ok(ColumnarValue::Scalar(ScalarValue::Int8(Some(v))))
+ } else {
+ Err(arithmetic_overflow_error("Int8"))
+ }
+ }
+ })
+ .unwrap(),
+ ScalarValue::Int16(a) => a
+ .map(|v| match v.checked_abs() {
+ Some(abs_val) => {
+ Ok(ColumnarValue::Scalar(ScalarValue::Int16(Some(abs_val))))
+ }
+ None => {
+ if !fail_on_error {
+ // return the original value
+ Ok(ColumnarValue::Scalar(ScalarValue::Int16(Some(v))))
+ } else {
+ Err(arithmetic_overflow_error("Int16"))
+ }
+ }
+ })
+ .unwrap(),
+ ScalarValue::Int32(a) => a
+ .map(|v| match v.checked_abs() {
+ Some(abs_val) => {
+ Ok(ColumnarValue::Scalar(ScalarValue::Int32(Some(abs_val))))
+ }
+ None => {
+ if !fail_on_error {
+ // return the original value
+ Ok(ColumnarValue::Scalar(ScalarValue::Int32(Some(v))))
+ } else {
+ Err(arithmetic_overflow_error("Int32"))
+ }
+ }
+ })
+ .unwrap(),
+ ScalarValue::Int64(a) => a
+ .map(|v| match v.checked_abs() {
+ Some(abs_val) => {
+ Ok(ColumnarValue::Scalar(ScalarValue::Int64(Some(abs_val))))
+ }
+ None => {
+ if !fail_on_error {
+ // return the original value
+ Ok(ColumnarValue::Scalar(ScalarValue::Int64(Some(v))))
+ } else {
+ Err(arithmetic_overflow_error("Int64"))
+ }
+ }
+ })
+ .unwrap(),
+ ScalarValue::Float32(a) => Ok(ColumnarValue::Scalar(
+ ScalarValue::Float32(a.map(|x| x.abs())),
+ )),
+ ScalarValue::Float64(a) => Ok(ColumnarValue::Scalar(
+ ScalarValue::Float64(a.map(|x| x.abs())),
+ )),
+ ScalarValue::Decimal128(a, precision, scale) => a
+ .map(|v| match v.checked_abs() {
+ Some(abs_val) => Ok(ColumnarValue::Scalar(
+ ScalarValue::Decimal128(Some(abs_val), *precision, *scale),
+ )),
+ None => {
+ if !fail_on_error {
+ // return the original value
+ Ok(ColumnarValue::Scalar(ScalarValue::Decimal128(
+ Some(v),
+ *precision,
+ *scale,
+ )))
+ } else {
+ Err(arithmetic_overflow_error("Decimal128"))
+ }
+ }
+ })
+ .unwrap(),
+ ScalarValue::Decimal256(a, precision, scale) => a
+ .map(|v| match v.checked_abs() {
+ Some(abs_val) => Ok(ColumnarValue::Scalar(
+ ScalarValue::Decimal256(Some(abs_val), *precision, *scale),
+ )),
+ None => {
+ if !fail_on_error {
+ // return the original value
+ Ok(ColumnarValue::Scalar(ScalarValue::Decimal256(
+ Some(v),
+ *precision,
+ *scale,
+ )))
+ } else {
+ Err(arithmetic_overflow_error("Decimal256"))
+ }
+ }
+ })
+ .unwrap(),
+ ScalarValue::IntervalYearMonth(a) => {
+ let result = a.map(|v| v.wrapping_abs());
+ Ok(ColumnarValue::Scalar(ScalarValue::IntervalYearMonth(
+ result,
+ )))
+ }
+ ScalarValue::IntervalDayTime(a) => {
+ let result = a.map(|v| v.wrapping_abs());
+ Ok(ColumnarValue::Scalar(ScalarValue::IntervalDayTime(result)))
+ }
+
+ dt => internal_err!("Not supported datatype for Spark ABS: {dt}"),
+ }
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use datafusion_common::cast::{
+ as_decimal128_array, as_decimal256_array, as_float32_array, as_float64_array,
+ as_int16_array, as_int32_array, as_int64_array, as_int8_array,
+ as_interval_dt_array, as_interval_ym_array, as_uint64_array,
+ };
+
+ fn with_fail_on_error<F: Fn(bool) -> Result<()>>(test_fn: F) {
+ for fail_on_error in [true, false] {
+ let _ = test_fn(fail_on_error);
+ }
+ }
+
+ // Unsigned types, return as is
+ #[test]
+ fn test_abs_u8_scalar() {
+ with_fail_on_error(|fail_on_error| {
+ let args = ColumnarValue::Scalar(ScalarValue::UInt8(Some(u8::MAX)));
+ let fail_on_error_arg =
+ ColumnarValue::Scalar(ScalarValue::Boolean(Some(fail_on_error)));
+ match spark_abs(&[args, fail_on_error_arg]) {
+ Ok(ColumnarValue::Scalar(ScalarValue::UInt8(Some(result)))) => {
+ assert_eq!(result, u8::MAX);
+ Ok(())
+ }
+ Err(e) => {
+ if fail_on_error {
+ assert!(
+ e.to_string().contains("ARITHMETIC_OVERFLOW"),
+ "Error message did not match. Actual message: {e}"
+ );
+ Ok(())
+ } else {
+ panic!("Didn't expect error, but got: {e:?}")
+ }
+ }
+ _ => unreachable!(),
+ }
+ });
+ }
Review Comment:
I've refactored the test cases, please take a look for me, thank you.
--
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-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat: support Spark-compatible `abs` math function part 1 - non-ANSI mode [datafusion]
Posted by "Jefffrey (via GitHub)" <gi...@apache.org>.
Jefffrey commented on code in PR #18205:
URL: https://github.com/apache/datafusion/pull/18205#discussion_r2536552731
##########
datafusion/sqllogictest/test_files/spark/math/abs.slt:
##########
@@ -23,10 +23,75 @@
## Original Query: SELECT abs(-1);
## PySpark 3.5.5 Result: {'abs(-1)': 1, 'typeof(abs(-1))': 'int', 'typeof(-1)': 'int'}
-#query
-#SELECT abs(-1::int);
+
+# abs: signed int and NULL
+query IIIIR
+SELECT abs(-127::TINYINT), abs(-32767::SMALLINT), abs(-2147483647::INT), abs(-9223372036854775807::BIGINT), abs(NULL);
+----
+127 32767 2147483647 9223372036854775807 NULL
+
+
+# See https://github.com/apache/datafusion/issues/18794 for operator precedence
+# abs: signed int minimal values
+query IIII
+select abs((-128)::TINYINT), abs((-32768)::SMALLINT), abs((-2147483648)::INT), abs((-9223372036854775808)::BIGINT)
+----
+-128 -32768 -2147483648 -9223372036854775808
+
+# abs: floats, NULL and NaN
+query RRRR
+SELECT abs(-1.0::FLOAT), abs(0.::FLOAT), abs(NULL::FLOAT), abs('NaN'::FLOAT)
+----
+1 0 NULL NaN
+
+# abs: doubles, NULL and NaN
+query RRRR
+SELECT abs(-1.0::DOUBLE), abs(0.::DOUBLE), abs(NULL::DOUBLE), abs('NaN'::DOUBLE)
+----
+1 0 NULL NaN
+
+# abs: decimal128 and decimal256
+statement ok
+CREATE TABLE test_nullable_decimal(
+ c1 DECIMAL(10, 2), /* Decimal128 */
+ c2 DECIMAL(38, 10), /* Decimal128 with max precision */
+ c3 DECIMAL(40, 2), /* Decimal256 */
+ c4 DECIMAL(76, 10) /* Decimal256 with max precision */
+ ) AS VALUES
+ (0, 0, 0, 0),
+ (NULL, NULL, NULL, NULL);
+
+query I
+INSERT into test_nullable_decimal values
+ (
+ -99999999.99,
+ '-9999999999999999999999999999.9999999999',
+ '-99999999999999999999999999999999999999.99',
+ '-999999999999999999999999999999999999999999999999999999999999999999.9999999999'
+ ),
+ (
+ 99999999.99,
+ '9999999999999999999999999999.9999999999',
+ '99999999999999999999999999999999999999.99',
+ '999999999999999999999999999999999999999999999999999999999999999999.9999999999'
+ )
+----
+2
+
+query RRRR rowsort
+SELECT abs(c1), abs(c2), abs(c3), abs(c4) FROM test_nullable_decimal
+----
+0 0 0 0
+99999999.99 9999999999999999999999999999.9999999999 99999999999999999999999999999999999999.99 999999999999999999999999999999999999999999999999999999999999999999.9999999999
+99999999.99 9999999999999999999999999999.9999999999 99999999999999999999999999999999999999.99 999999999999999999999999999999999999999999999999999999999999999999.9999999999
+NULL NULL NULL NULL
+
+
+statement ok
+drop table test_nullable_decimal
## Original Query: SELECT abs(INTERVAL -'1-1' YEAR TO MONTH);
## PySpark 3.5.5 Result: {"abs(INTERVAL '-1-1' YEAR TO MONTH)": 13, "typeof(abs(INTERVAL '-1-1' YEAR TO MONTH))": 'interval year to month', "typeof(INTERVAL '-1-1' YEAR TO MONTH)": 'interval year to month'}
#query
#SELECT abs(INTERVAL '-1-1' YEAR TO MONTH::interval year to month);
+# See GitHub issue for ANSI interval support: https://github.com/apache/datafusion/issues/18793
Review Comment:
Fyi can cast to specific interval type like so:
https://github.com/apache/datafusion/issues/18793
##########
datafusion/sqllogictest/test_files/spark/math/abs.slt:
##########
@@ -23,10 +23,75 @@
## Original Query: SELECT abs(-1);
## PySpark 3.5.5 Result: {'abs(-1)': 1, 'typeof(abs(-1))': 'int', 'typeof(-1)': 'int'}
-#query
-#SELECT abs(-1::int);
+
+# abs: signed int and NULL
+query IIIIR
+SELECT abs(-127::TINYINT), abs(-32767::SMALLINT), abs(-2147483647::INT), abs(-9223372036854775807::BIGINT), abs(NULL);
+----
+127 32767 2147483647 9223372036854775807 NULL
+
+
+# See https://github.com/apache/datafusion/issues/18794 for operator precedence
+# abs: signed int minimal values
+query IIII
+select abs((-128)::TINYINT), abs((-32768)::SMALLINT), abs((-2147483648)::INT), abs((-9223372036854775808)::BIGINT)
+----
+-128 -32768 -2147483648 -9223372036854775808
+
+# abs: floats, NULL and NaN
+query RRRR
+SELECT abs(-1.0::FLOAT), abs(0.::FLOAT), abs(NULL::FLOAT), abs('NaN'::FLOAT)
+----
+1 0 NULL NaN
+
+# abs: doubles, NULL and NaN
+query RRRR
+SELECT abs(-1.0::DOUBLE), abs(0.::DOUBLE), abs(NULL::DOUBLE), abs('NaN'::DOUBLE)
+----
+1 0 NULL NaN
+
+# abs: decimal128 and decimal256
+statement ok
+CREATE TABLE test_nullable_decimal(
+ c1 DECIMAL(10, 2), /* Decimal128 */
+ c2 DECIMAL(38, 10), /* Decimal128 with max precision */
+ c3 DECIMAL(40, 2), /* Decimal256 */
+ c4 DECIMAL(76, 10) /* Decimal256 with max precision */
+ ) AS VALUES
+ (0, 0, 0, 0),
+ (NULL, NULL, NULL, NULL);
+
+query I
+INSERT into test_nullable_decimal values
+ (
+ -99999999.99,
+ '-9999999999999999999999999999.9999999999',
+ '-99999999999999999999999999999999999999.99',
+ '-999999999999999999999999999999999999999999999999999999999999999999.9999999999'
+ ),
+ (
+ 99999999.99,
+ '9999999999999999999999999999.9999999999',
+ '99999999999999999999999999999999999999.99',
+ '999999999999999999999999999999999999999999999999999999999999999999.9999999999'
+ )
+----
+2
+
+query RRRR rowsort
+SELECT abs(c1), abs(c2), abs(c3), abs(c4) FROM test_nullable_decimal
+----
+0 0 0 0
+99999999.99 9999999999999999999999999999.9999999999 99999999999999999999999999999999999999.99 999999999999999999999999999999999999999999999999999999999999999999.9999999999
+99999999.99 9999999999999999999999999999.9999999999 99999999999999999999999999999999999999.99 999999999999999999999999999999999999999999999999999999999999999999.9999999999
+NULL NULL NULL NULL
+
+
+statement ok
+drop table test_nullable_decimal
## Original Query: SELECT abs(INTERVAL -'1-1' YEAR TO MONTH);
## PySpark 3.5.5 Result: {"abs(INTERVAL '-1-1' YEAR TO MONTH)": 13, "typeof(abs(INTERVAL '-1-1' YEAR TO MONTH))": 'interval year to month', "typeof(INTERVAL '-1-1' YEAR TO MONTH)": 'interval year to month'}
#query
#SELECT abs(INTERVAL '-1-1' YEAR TO MONTH::interval year to month);
+# See GitHub issue for ANSI interval support: https://github.com/apache/datafusion/issues/18793
Review Comment:
Fyi can cast to specific interval type like so:
https://github.com/apache/datafusion/blob/0304cda4fb18fd0555f5499a07a34f53b3cdf613/datafusion/sqllogictest/test_files/aggregate.slt#L2345-L2347
--
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-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat: support Spark-compatible `abs` math function [datafusion]
Posted by "Jefffrey (via GitHub)" <gi...@apache.org>.
Jefffrey commented on code in PR #18205:
URL: https://github.com/apache/datafusion/pull/18205#discussion_r2462921847
##########
datafusion/sqllogictest/test_files/spark/math/abs.slt:
##########
@@ -23,10 +23,103 @@
## Original Query: SELECT abs(-1);
## PySpark 3.5.5 Result: {'abs(-1)': 1, 'typeof(abs(-1))': 'int', 'typeof(-1)': 'int'}
-#query
-#SELECT abs(-1::int);
+query I
+SELECT abs(-1::int);
+----
+1
+
+statement ok
+CREATE TABLE test_nullable_integer(
+ c1 TINYINT,
+ c2 SMALLINT,
+ c3 INT,
+ c4 BIGINT,
+ dataset TEXT
+ )
+ AS VALUES
+ (NULL, NULL, NULL, NULL, 'nulls'),
+ (0, 0, 0, 0, 'zeros'),
+ (1, 1, 1, 1, 'ones');
+
+query I
+INSERT into test_nullable_integer values(-128, -32768, -2147483648, -9223372036854775808, 'mins');
+----
+1
+
+# abs: signed int minimal values
+query IIII
+select abs(c1), abs(c2), abs(c3), abs(c4) from test_nullable_integer where dataset = 'mins'
Review Comment:
I think this is a bug in SQL parsing:
```sql
> select -128::tinyint;
Arrow error: Cast error: Can't cast value 128 to type Int8
> select (-128)::tinyint;
+-------------+
| Int64(-128) |
+-------------+
| -128 |
+-------------+
1 row(s) fetched.
Elapsed 0.003 seconds.
```
- Might need to raise an issue for this?
So can wrap it in parentheses to ensure the correct precedence, or alternatively use `arrow_cast`:
```sql
> select arrow_cast(-128, 'Int8');
+--------------------------------------+
| arrow_cast(Int64(-128),Utf8("Int8")) |
+--------------------------------------+
| -128 |
+--------------------------------------+
1 row(s) fetched.
Elapsed 0.007 seconds.
```
--
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-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat: support Spark-compatible `abs` math function [datafusion]
Posted by "hsiang-c (via GitHub)" <gi...@apache.org>.
hsiang-c commented on code in PR #18205:
URL: https://github.com/apache/datafusion/pull/18205#discussion_r2462587584
##########
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
+ }
+ _ => {
+ return internal_err!(
+ "The second argument must be boolean scalar, but got: {:?}",
+ args[1]
+ );
+ }
+ }
+ } else {
+ false
+ };
+
+ 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 => {
+ if !fail_on_error {
+ let result =
+ legacy_compute_op!(array, wrapping_abs, Int8Array, Int8Array);
+ Ok(ColumnarValue::Array(Arc::new(result?)))
+ } else {
+ ansi_compute_op!(array, abs, Int8Array, Int8Type, i8, "Int8")
+ }
+ }
+ DataType::Int16 => {
+ if !fail_on_error {
+ let result =
+ legacy_compute_op!(array, wrapping_abs, Int16Array, Int16Array);
+ Ok(ColumnarValue::Array(Arc::new(result?)))
+ } else {
+ ansi_compute_op!(array, abs, Int16Array, Int16Type, i16, "Int16")
+ }
+ }
+ DataType::Int32 => {
+ if !fail_on_error {
+ let result =
+ legacy_compute_op!(array, wrapping_abs, Int32Array, Int32Array);
+ Ok(ColumnarValue::Array(Arc::new(result?)))
+ } else {
+ ansi_compute_op!(array, abs, Int32Array, Int32Type, i32, "Int32")
+ }
+ }
+ DataType::Int64 => {
+ if !fail_on_error {
+ let result =
+ legacy_compute_op!(array, wrapping_abs, Int64Array, Int64Array);
+ Ok(ColumnarValue::Array(Arc::new(result?)))
+ } else {
+ ansi_compute_op!(array, abs, Int64Array, Int64Type, i64, "Int64")
+ }
+ }
+ DataType::Float32 => {
+ let result = legacy_compute_op!(array, abs, Float32Array, Float32Array);
+ Ok(ColumnarValue::Array(Arc::new(result?)))
+ }
+ DataType::Float64 => {
+ let result = legacy_compute_op!(array, abs, Float64Array, Float64Array);
+ Ok(ColumnarValue::Array(Arc::new(result?)))
+ }
+ DataType::Decimal128(precision, scale) => {
+ if !fail_on_error {
+ let result = legacy_compute_op!(
+ array,
+ wrapping_abs,
+ Decimal128Array,
+ Decimal128Array
+ )?;
+ let result =
+ result.with_data_type(DataType::Decimal128(*precision, *scale));
+ Ok(ColumnarValue::Array(Arc::new(result)))
+ } else {
+ // Need to pass precision and scale from input, so not using ansi_compute_op
+ let input = array.as_any().downcast_ref::<Decimal128Array>();
+ match input {
+ Some(i) => {
+ match arrow::compute::kernels::arity::try_unary(i, |x| {
+ if x == i128::MIN {
+ Err(arrow::error::ArrowError::ArithmeticOverflow(
+ "Decimal128".to_string(),
+ ))
+ } else {
+ Ok(x.abs())
+ }
+ }) {
+ Ok(res) => Ok(ColumnarValue::Array(Arc::<
+ PrimitiveArray<Decimal128Type>,
+ >::new(
+ res.with_data_type(DataType::Decimal128(
+ *precision, *scale,
+ )),
+ ))),
+ Err(_) => Err(arithmetic_overflow_error("Decimal128")),
+ }
+ }
+ _ => Err(DataFusionError::Internal(
+ "Invalid data type".to_string(),
+ )),
+ }
+ }
+ }
+ DataType::Decimal256(precision, scale) => {
+ if !fail_on_error {
+ let result = legacy_compute_op!(
+ array,
+ wrapping_abs,
+ Decimal256Array,
+ Decimal256Array
+ )?;
+ let result =
+ result.with_data_type(DataType::Decimal256(*precision, *scale));
+ Ok(ColumnarValue::Array(Arc::new(result)))
+ } else {
+ // Need to pass precision and scale from input, so not using ansi_compute_op
+ let input = array.as_any().downcast_ref::<Decimal256Array>();
+ match input {
+ Some(i) => {
+ match arrow::compute::kernels::arity::try_unary(i, |x| {
+ if x == i256::MIN {
+ Err(arrow::error::ArrowError::ArithmeticOverflow(
+ "Decimal256".to_string(),
+ ))
+ } else {
+ Ok(x.wrapping_abs()) // i256 doesn't define abs() method
+ }
+ }) {
+ Ok(res) => Ok(ColumnarValue::Array(Arc::<
+ PrimitiveArray<Decimal256Type>,
+ >::new(
+ res.with_data_type(DataType::Decimal256(
+ *precision, *scale,
+ )),
+ ))),
+ Err(_) => Err(arithmetic_overflow_error("Decimal256")),
+ }
+ }
+ _ => Err(DataFusionError::Internal(
+ "Invalid data type".to_string(),
+ )),
+ }
+ }
+ }
+ DataType::Interval(unit) => match unit {
+ IntervalUnit::YearMonth => {
+ let result = legacy_compute_op!(
+ array,
+ wrapping_abs,
+ IntervalYearMonthArray,
+ IntervalYearMonthArray
+ )?;
+ let result = result.with_data_type(DataType::Interval(*unit));
+ Ok(ColumnarValue::Array(Arc::new(result)))
+ }
+ IntervalUnit::DayTime => {
+ let result = legacy_compute_op!(
+ array,
+ wrapping_abs,
+ IntervalDayTimeArray,
+ IntervalDayTimeArray
+ )?;
+ let result = result.with_data_type(DataType::Interval(*unit));
+ Ok(ColumnarValue::Array(Arc::new(result)))
+ }
+ IntervalUnit::MonthDayNano => internal_err!(
+ "MonthDayNano is not a supported Interval unit for Spark ABS"
+ ),
+ },
+ 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) => a
+ .map(|v| match v.checked_abs() {
+ Some(abs_val) => {
+ Ok(ColumnarValue::Scalar(ScalarValue::Int8(Some(abs_val))))
+ }
+ None => {
+ if !fail_on_error {
+ // return the original value
+ Ok(ColumnarValue::Scalar(ScalarValue::Int8(Some(v))))
+ } else {
+ Err(arithmetic_overflow_error("Int8"))
+ }
+ }
+ })
+ .unwrap(),
+ ScalarValue::Int16(a) => a
+ .map(|v| match v.checked_abs() {
+ Some(abs_val) => {
+ Ok(ColumnarValue::Scalar(ScalarValue::Int16(Some(abs_val))))
+ }
+ None => {
+ if !fail_on_error {
+ // return the original value
+ Ok(ColumnarValue::Scalar(ScalarValue::Int16(Some(v))))
+ } else {
+ Err(arithmetic_overflow_error("Int16"))
+ }
+ }
+ })
+ .unwrap(),
+ ScalarValue::Int32(a) => a
+ .map(|v| match v.checked_abs() {
+ Some(abs_val) => {
+ Ok(ColumnarValue::Scalar(ScalarValue::Int32(Some(abs_val))))
+ }
+ None => {
+ if !fail_on_error {
+ // return the original value
+ Ok(ColumnarValue::Scalar(ScalarValue::Int32(Some(v))))
+ } else {
+ Err(arithmetic_overflow_error("Int32"))
+ }
+ }
+ })
+ .unwrap(),
+ ScalarValue::Int64(a) => a
+ .map(|v| match v.checked_abs() {
+ Some(abs_val) => {
+ Ok(ColumnarValue::Scalar(ScalarValue::Int64(Some(abs_val))))
+ }
+ None => {
+ if !fail_on_error {
+ // return the original value
+ Ok(ColumnarValue::Scalar(ScalarValue::Int64(Some(v))))
+ } else {
+ Err(arithmetic_overflow_error("Int64"))
+ }
+ }
+ })
+ .unwrap(),
+ ScalarValue::Float32(a) => Ok(ColumnarValue::Scalar(
+ ScalarValue::Float32(a.map(|x| x.abs())),
+ )),
+ ScalarValue::Float64(a) => Ok(ColumnarValue::Scalar(
+ ScalarValue::Float64(a.map(|x| x.abs())),
+ )),
+ ScalarValue::Decimal128(a, precision, scale) => a
+ .map(|v| match v.checked_abs() {
+ Some(abs_val) => Ok(ColumnarValue::Scalar(
+ ScalarValue::Decimal128(Some(abs_val), *precision, *scale),
+ )),
+ None => {
+ if !fail_on_error {
+ // return the original value
+ Ok(ColumnarValue::Scalar(ScalarValue::Decimal128(
+ Some(v),
+ *precision,
+ *scale,
+ )))
+ } else {
+ Err(arithmetic_overflow_error("Decimal128"))
+ }
+ }
+ })
+ .unwrap(),
+ ScalarValue::Decimal256(a, precision, scale) => a
+ .map(|v| match v.checked_abs() {
+ Some(abs_val) => Ok(ColumnarValue::Scalar(
+ ScalarValue::Decimal256(Some(abs_val), *precision, *scale),
+ )),
+ None => {
+ if !fail_on_error {
+ // return the original value
+ Ok(ColumnarValue::Scalar(ScalarValue::Decimal256(
+ Some(v),
+ *precision,
+ *scale,
+ )))
+ } else {
+ Err(arithmetic_overflow_error("Decimal256"))
+ }
+ }
+ })
+ .unwrap(),
+ ScalarValue::IntervalYearMonth(a) => {
+ let result = a.map(|v| v.wrapping_abs());
+ Ok(ColumnarValue::Scalar(ScalarValue::IntervalYearMonth(
+ result,
+ )))
+ }
+ ScalarValue::IntervalDayTime(a) => {
+ let result = a.map(|v| v.wrapping_abs());
+ Ok(ColumnarValue::Scalar(ScalarValue::IntervalDayTime(result)))
+ }
+
+ dt => internal_err!("Not supported datatype for Spark ABS: {dt}"),
+ }
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use datafusion_common::cast::{
+ as_decimal128_array, as_decimal256_array, as_float32_array, as_float64_array,
+ as_int16_array, as_int32_array, as_int64_array, as_int8_array,
+ as_interval_dt_array, as_interval_ym_array, as_uint64_array,
+ };
+
+ fn with_fail_on_error<F: Fn(bool) -> Result<()>>(test_fn: F) {
+ for fail_on_error in [true, false] {
+ let _ = test_fn(fail_on_error);
+ }
+ }
+
+ // Unsigned types, return as is
+ #[test]
+ fn test_abs_u8_scalar() {
+ with_fail_on_error(|fail_on_error| {
+ let args = ColumnarValue::Scalar(ScalarValue::UInt8(Some(u8::MAX)));
+ let fail_on_error_arg =
+ ColumnarValue::Scalar(ScalarValue::Boolean(Some(fail_on_error)));
+ match spark_abs(&[args, fail_on_error_arg]) {
+ Ok(ColumnarValue::Scalar(ScalarValue::UInt8(Some(result)))) => {
+ assert_eq!(result, u8::MAX);
+ Ok(())
+ }
+ Err(e) => {
+ if fail_on_error {
+ assert!(
+ e.to_string().contains("ARITHMETIC_OVERFLOW"),
+ "Error message did not match. Actual message: {e}"
+ );
+ Ok(())
+ } else {
+ panic!("Didn't expect error, but got: {e:?}")
+ }
+ }
+ _ => unreachable!(),
+ }
+ });
+ }
Review Comment:
@Jefffrey You're right, thanks for the feedback.
--
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-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat: support Spark-compatible `abs` math function part 1 - non-ANSI mode [datafusion]
Posted by "comphead (via GitHub)" <gi...@apache.org>.
comphead merged PR #18205:
URL: https://github.com/apache/datafusion/pull/18205
--
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-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat: support Spark-compatible `abs` math function [datafusion]
Posted by "comphead (via GitHub)" <gi...@apache.org>.
comphead commented on code in PR #18205:
URL: https://github.com/apache/datafusion/pull/18205#discussion_r2450020140
##########
datafusion/sqllogictest/test_files/spark/math/abs.slt:
##########
@@ -23,10 +23,103 @@
## Original Query: SELECT abs(-1);
## PySpark 3.5.5 Result: {'abs(-1)': 1, 'typeof(abs(-1))': 'int', 'typeof(-1)': 'int'}
-#query
-#SELECT abs(-1::int);
+query I
+SELECT abs(-1::int);
+----
+1
+
+statement ok
+CREATE TABLE test_nullable_integer(
+ c1 TINYINT,
+ c2 SMALLINT,
+ c3 INT,
+ c4 BIGINT,
+ dataset TEXT
+ )
+ AS VALUES
+ (NULL, NULL, NULL, NULL, 'nulls'),
+ (0, 0, 0, 0, 'zeros'),
+ (1, 1, 1, 1, 'ones');
+
+query I
+INSERT into test_nullable_integer values(-128, -32768, -2147483648, -9223372036854775808, 'mins');
+----
+1
+
+# abs: signed int minimal values
+query IIII
+select abs(c1), abs(c2), abs(c3), abs(c4) from test_nullable_integer where dataset = 'mins'
+----
+-128 -32768 -2147483648 -9223372036854775808
+
+statement ok
+drop table test_nullable_integer
+
+statement ok
+CREATE TABLE test_nullable_float(
+ c1 float,
+ c2 double
+ ) AS VALUES
+ (-1.0, -1.0),
+ (1.0, 1.0),
+ (NULL, NULL),
+ (0., 0.),
+ ('NaN'::double, 'NaN'::double);
+
+# abs: floats
+query RR rowsort
+SELECT abs(c1), abs(c2) from test_nullable_float
+----
+0 0
+1 1
+1 1
+NULL NULL
Review Comment:
its better to use inline query, in this example the answers and input data are out of order and it might be more difficult to read
--
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-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat: support Spark-compatible `abs` math function [datafusion]
Posted by "hsiang-c (via GitHub)" <gi...@apache.org>.
hsiang-c commented on code in PR #18205:
URL: https://github.com/apache/datafusion/pull/18205#discussion_r2507649061
##########
datafusion/spark/src/function/math/abs.rs:
##########
@@ -0,0 +1,792 @@
+// 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 arrow::error::ArrowError;
+use datafusion_common::{internal_err, DataFusionError, Result, ScalarValue};
+use datafusion_expr::{
+ ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl, Signature, Volatility,
+};
+use datafusion_functions::{
Review Comment:
Reuse existing marcos from DF's abs function.
--
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-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat: support Spark-compatible `abs` math function part 1 - non-ANSI mode [datafusion]
Posted by "comphead (via GitHub)" <gi...@apache.org>.
comphead commented on code in PR #18205:
URL: https://github.com/apache/datafusion/pull/18205#discussion_r2534877821
##########
parquet-testing:
##########
Review Comment:
both parquet-testing and testing comes some time from vscode, but it needs to be removed
--
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-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat: support Spark-compatible `abs` math function [datafusion]
Posted by "comphead (via GitHub)" <gi...@apache.org>.
comphead commented on code in PR #18205:
URL: https://github.com/apache/datafusion/pull/18205#discussion_r2450031697
##########
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),
Review Comment:
```suggestion
signature: Signature::numeric(1, Volatility::Immutable),
```
Lets keep it this way for now since the PR doesn't support Intervals
--
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-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat: support Spark-compatible `abs` math function [datafusion]
Posted by "Jefffrey (via GitHub)" <gi...@apache.org>.
Jefffrey commented on code in PR #18205:
URL: https://github.com/apache/datafusion/pull/18205#discussion_r2462921847
##########
datafusion/sqllogictest/test_files/spark/math/abs.slt:
##########
@@ -23,10 +23,103 @@
## Original Query: SELECT abs(-1);
## PySpark 3.5.5 Result: {'abs(-1)': 1, 'typeof(abs(-1))': 'int', 'typeof(-1)': 'int'}
-#query
-#SELECT abs(-1::int);
+query I
+SELECT abs(-1::int);
+----
+1
+
+statement ok
+CREATE TABLE test_nullable_integer(
+ c1 TINYINT,
+ c2 SMALLINT,
+ c3 INT,
+ c4 BIGINT,
+ dataset TEXT
+ )
+ AS VALUES
+ (NULL, NULL, NULL, NULL, 'nulls'),
+ (0, 0, 0, 0, 'zeros'),
+ (1, 1, 1, 1, 'ones');
+
+query I
+INSERT into test_nullable_integer values(-128, -32768, -2147483648, -9223372036854775808, 'mins');
+----
+1
+
+# abs: signed int minimal values
+query IIII
+select abs(c1), abs(c2), abs(c3), abs(c4) from test_nullable_integer where dataset = 'mins'
Review Comment:
I think this is a bug in SQL parsing:
```sql
> select -128::tinyint;
Arrow error: Cast error: Can't cast value 128 to type Int8
> select (-128)::tinyint;
+-------------+
| Int64(-128) |
+-------------+
| -128 |
+-------------+
1 row(s) fetched.
Elapsed 0.003 seconds.
```
- It casts the 128 value without accounting for the negative; might need to raise an issue for this? Not sure if this is intended behaviour or not
So can wrap it in parentheses to ensure the correct precedence, or alternatively use `arrow_cast`:
```sql
> select arrow_cast(-128, 'Int8');
+--------------------------------------+
| arrow_cast(Int64(-128),Utf8("Int8")) |
+--------------------------------------+
| -128 |
+--------------------------------------+
1 row(s) fetched.
Elapsed 0.007 seconds.
```
--
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-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat: support Spark-compatible `abs` math function [datafusion]
Posted by "Jefffrey (via GitHub)" <gi...@apache.org>.
Jefffrey commented on code in PR #18205:
URL: https://github.com/apache/datafusion/pull/18205#discussion_r2462921847
##########
datafusion/sqllogictest/test_files/spark/math/abs.slt:
##########
@@ -23,10 +23,103 @@
## Original Query: SELECT abs(-1);
## PySpark 3.5.5 Result: {'abs(-1)': 1, 'typeof(abs(-1))': 'int', 'typeof(-1)': 'int'}
-#query
-#SELECT abs(-1::int);
+query I
+SELECT abs(-1::int);
+----
+1
+
+statement ok
+CREATE TABLE test_nullable_integer(
+ c1 TINYINT,
+ c2 SMALLINT,
+ c3 INT,
+ c4 BIGINT,
+ dataset TEXT
+ )
+ AS VALUES
+ (NULL, NULL, NULL, NULL, 'nulls'),
+ (0, 0, 0, 0, 'zeros'),
+ (1, 1, 1, 1, 'ones');
+
+query I
+INSERT into test_nullable_integer values(-128, -32768, -2147483648, -9223372036854775808, 'mins');
+----
+1
+
+# abs: signed int minimal values
+query IIII
+select abs(c1), abs(c2), abs(c3), abs(c4) from test_nullable_integer where dataset = 'mins'
Review Comment:
I think this is a bug in SQL parsing:
```sql
> select -128::tinyint;
Arrow error: Cast error: Can't cast value 128 to type Int8
> select (-128)::tinyint;
+-------------+
| Int64(-128) |
+-------------+
| -128 |
+-------------+
1 row(s) fetched.
Elapsed 0.003 seconds.
```
- It casts the 128 value without accounting for the negative; might need to raise an issue for this?
So can wrap it in parentheses to ensure the correct precedence, or alternatively use `arrow_cast`:
```sql
> select arrow_cast(-128, 'Int8');
+--------------------------------------+
| arrow_cast(Int64(-128),Utf8("Int8")) |
+--------------------------------------+
| -128 |
+--------------------------------------+
1 row(s) fetched.
Elapsed 0.007 seconds.
```
--
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-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat: support Spark-compatible `abs` math function [datafusion]
Posted by "comphead (via GitHub)" <gi...@apache.org>.
comphead commented on code in PR #18205:
URL: https://github.com/apache/datafusion/pull/18205#discussion_r2450018311
##########
datafusion/sqllogictest/test_files/spark/math/abs.slt:
##########
@@ -23,10 +23,103 @@
## Original Query: SELECT abs(-1);
## PySpark 3.5.5 Result: {'abs(-1)': 1, 'typeof(abs(-1))': 'int', 'typeof(-1)': 'int'}
-#query
-#SELECT abs(-1::int);
+query I
+SELECT abs(-1::int);
+----
+1
+
+statement ok
+CREATE TABLE test_nullable_integer(
+ c1 TINYINT,
+ c2 SMALLINT,
+ c3 INT,
+ c4 BIGINT,
+ dataset TEXT
+ )
+ AS VALUES
+ (NULL, NULL, NULL, NULL, 'nulls'),
+ (0, 0, 0, 0, 'zeros'),
+ (1, 1, 1, 1, 'ones');
+
+query I
+INSERT into test_nullable_integer values(-128, -32768, -2147483648, -9223372036854775808, 'mins');
+----
+1
+
+# abs: signed int minimal values
+query IIII
+select abs(c1), abs(c2), abs(c3), abs(c4) from test_nullable_integer where dataset = 'mins'
Review Comment:
wondering would be that easier to test like
```
query II
select abs(1), abs(-1)
----
1 1
```
?
instead of creating/dropping tables
--
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-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat: support Spark-compatible `abs` math function [datafusion]
Posted by "hsiang-c (via GitHub)" <gi...@apache.org>.
hsiang-c commented on code in PR #18205:
URL: https://github.com/apache/datafusion/pull/18205#discussion_r2462627669
##########
datafusion/sqllogictest/test_files/spark/math/abs.slt:
##########
@@ -23,10 +23,103 @@
## Original Query: SELECT abs(-1);
## PySpark 3.5.5 Result: {'abs(-1)': 1, 'typeof(abs(-1))': 'int', 'typeof(-1)': 'int'}
-#query
-#SELECT abs(-1::int);
+query I
+SELECT abs(-1::int);
+----
+1
+
+statement ok
+CREATE TABLE test_nullable_integer(
+ c1 TINYINT,
+ c2 SMALLINT,
+ c3 INT,
+ c4 BIGINT,
+ dataset TEXT
+ )
+ AS VALUES
+ (NULL, NULL, NULL, NULL, 'nulls'),
+ (0, 0, 0, 0, 'zeros'),
+ (1, 1, 1, 1, 'ones');
+
+query I
+INSERT into test_nullable_integer values(-128, -32768, -2147483648, -9223372036854775808, 'mins');
+----
+1
+
+# abs: signed int minimal values
+query IIII
+select abs(c1), abs(c2), abs(c3), abs(c4) from test_nullable_integer where dataset = 'mins'
Review Comment:
Doing `abs(-128)`, `abs(-32768)` and `abs(-2147483648)` doesn't work b/c type widening.
Doing `abs(-128::SMALLINT), abs(-32768::SMALLINT), abs(-2147483648::INT), abs(-9223372036854775808::BIGINT)` throws casting error. For example, `DataFusion error: Arrow error: Cast error: Can't cast value 128 to type Int8`
--
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-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat: support Spark-compatible `abs` math function [datafusion]
Posted by "hsiang-c (via GitHub)" <gi...@apache.org>.
hsiang-c commented on code in PR #18205:
URL: https://github.com/apache/datafusion/pull/18205#discussion_r2507641626
##########
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,
+ )
+}
Review Comment:
This method is removed. I reused marcos from DF's own abs implementation and arithmetic overflow is thrown from the marcos.
--
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-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat: support Spark-compatible `abs` math function part 1 - non-ANSI mode [datafusion]
Posted by "Jefffrey (via GitHub)" <gi...@apache.org>.
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat: support Spark-compatible `abs` math function [datafusion]
Posted by "hsiang-c (via GitHub)" <gi...@apache.org>.
hsiang-c commented on PR #18205:
URL: https://github.com/apache/datafusion/pull/18205#issuecomment-3429980831
cc @comphead for code review, thank you.
--
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-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat: support Spark-compatible `abs` math function [datafusion]
Posted by "hsiang-c (via GitHub)" <gi...@apache.org>.
hsiang-c commented on code in PR #18205:
URL: https://github.com/apache/datafusion/pull/18205#discussion_r2507648767
##########
datafusion/functions/src/math/abs.rs:
##########
@@ -49,14 +50,15 @@ macro_rules! make_abs_function {
}};
}
+#[macro_export]
macro_rules! make_try_abs_function {
($ARRAY_TYPE:ident) => {{
|input: &ArrayRef| {
let array = downcast_named_arg!(&input, "abs arg", $ARRAY_TYPE);
let res: $ARRAY_TYPE = array.try_unary(|x| {
x.checked_abs().ok_or_else(|| {
ArrowError::ComputeError(format!(
- "{} overflow on abs({})",
+ "{} overflow on abs({:?})",
Review Comment:
Need to use `:?` formatting specifier b/c `IntervalDayTimeArray` and `IntervalYearMonthArray` only support it. Otherwise, I got
```shell
let abs_fun = make_try_abs_function!(IntervalDayTimeArray);
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
`arrow::datatypes::IntervalDayTime` cannot be formatted with the default formatter
required by this formatting parameter
```
--
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-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat: support Spark-compatible `abs` math function [datafusion]
Posted by "hsiang-c (via GitHub)" <gi...@apache.org>.
hsiang-c commented on code in PR #18205:
URL: https://github.com/apache/datafusion/pull/18205#discussion_r2462627669
##########
datafusion/sqllogictest/test_files/spark/math/abs.slt:
##########
@@ -23,10 +23,103 @@
## Original Query: SELECT abs(-1);
## PySpark 3.5.5 Result: {'abs(-1)': 1, 'typeof(abs(-1))': 'int', 'typeof(-1)': 'int'}
-#query
-#SELECT abs(-1::int);
+query I
+SELECT abs(-1::int);
+----
+1
+
+statement ok
+CREATE TABLE test_nullable_integer(
+ c1 TINYINT,
+ c2 SMALLINT,
+ c3 INT,
+ c4 BIGINT,
+ dataset TEXT
+ )
+ AS VALUES
+ (NULL, NULL, NULL, NULL, 'nulls'),
+ (0, 0, 0, 0, 'zeros'),
+ (1, 1, 1, 1, 'ones');
+
+query I
+INSERT into test_nullable_integer values(-128, -32768, -2147483648, -9223372036854775808, 'mins');
+----
+1
+
+# abs: signed int minimal values
+query IIII
+select abs(c1), abs(c2), abs(c3), abs(c4) from test_nullable_integer where dataset = 'mins'
Review Comment:
Doing `abs(-128)`, `abs(-32768)` and `abs(-2147483648)` doesn't work b/c type widening.
Doing `abs(-128::TINYLINT), abs(-32768::SMALLINT), abs(-2147483648::INT), abs(-9223372036854775808::BIGINT)` throws casting error. For example, `DataFusion error: Arrow error: Cast error: Can't cast value 128 to type Int8`
--
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-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat: support Spark-compatible `abs` math function part 1 - non-ANSI mode [datafusion]
Posted by "hsiang-c (via GitHub)" <gi...@apache.org>.
hsiang-c commented on code in PR #18205:
URL: https://github.com/apache/datafusion/pull/18205#discussion_r2536469554
##########
parquet-testing:
##########
Review Comment:
Reverted the changes now, sorry about that.
--
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-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat: support Spark-compatible `abs` math function part 1 - non-ANSI mode [datafusion]
Posted by "hsiang-c (via GitHub)" <gi...@apache.org>.
hsiang-c commented on PR #18205:
URL: https://github.com/apache/datafusion/pull/18205#issuecomment-3545702114
Thanks @Jefffrey
--
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-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat: support Spark-compatible `abs` math function [datafusion]
Posted by "comphead (via GitHub)" <gi...@apache.org>.
comphead commented on code in PR #18205:
URL: https://github.com/apache/datafusion/pull/18205#discussion_r2450024930
##########
datafusion/sqllogictest/test_files/spark/math/abs.slt:
##########
@@ -23,10 +23,103 @@
## Original Query: SELECT abs(-1);
## PySpark 3.5.5 Result: {'abs(-1)': 1, 'typeof(abs(-1))': 'int', 'typeof(-1)': 'int'}
-#query
-#SELECT abs(-1::int);
+query I
+SELECT abs(-1::int);
+----
+1
+
+statement ok
+CREATE TABLE test_nullable_integer(
+ c1 TINYINT,
+ c2 SMALLINT,
+ c3 INT,
+ c4 BIGINT,
+ dataset TEXT
+ )
+ AS VALUES
+ (NULL, NULL, NULL, NULL, 'nulls'),
+ (0, 0, 0, 0, 'zeros'),
+ (1, 1, 1, 1, 'ones');
+
+query I
+INSERT into test_nullable_integer values(-128, -32768, -2147483648, -9223372036854775808, 'mins');
+----
+1
+
+# abs: signed int minimal values
+query IIII
+select abs(c1), abs(c2), abs(c3), abs(c4) from test_nullable_integer where dataset = 'mins'
+----
+-128 -32768 -2147483648 -9223372036854775808
+
+statement ok
+drop table test_nullable_integer
+
+statement ok
+CREATE TABLE test_nullable_float(
+ c1 float,
+ c2 double
+ ) AS VALUES
+ (-1.0, -1.0),
+ (1.0, 1.0),
+ (NULL, NULL),
+ (0., 0.),
+ ('NaN'::double, 'NaN'::double);
+
+# abs: floats
+query RR rowsort
+SELECT abs(c1), abs(c2) from test_nullable_float
+----
+0 0
+1 1
+1 1
+NULL NULL
+NaN NaN
+
+statement ok
+drop table test_nullable_float
+
+statement ok
+CREATE TABLE test_nullable_decimal(
+ c1 DECIMAL(10, 2), /* Decimal128 */
+ c2 DECIMAL(38, 10), /* Decimal128 with max precision */
+ c3 DECIMAL(40, 2), /* Decimal256 */
+ c4 DECIMAL(76, 10) /* Decimal256 with max precision */
+ ) AS VALUES
+ (0, 0, 0, 0),
+ (NULL, NULL, NULL, NULL);
+
+query I
+INSERT into test_nullable_decimal values
+ (
+ -99999999.99,
+ '-9999999999999999999999999999.9999999999',
+ '-99999999999999999999999999999999999999.99',
+ '-999999999999999999999999999999999999999999999999999999999999999999.9999999999'
+ ),
+ (
+ 99999999.99,
+ '9999999999999999999999999999.9999999999',
+ '99999999999999999999999999999999999999.99',
+ '999999999999999999999999999999999999999999999999999999999999999999.9999999999'
+ )
+----
+2
+
+# abs: decimals
+query RRRR rowsort
+SELECT abs(c1), abs(c2), abs(c3), abs(c4) FROM test_nullable_decimal
+----
+0 0 0 0
+99999999.99 9999999999999999999999999999.9999999999 99999999999999999999999999999999999999.99 999999999999999999999999999999999999999999999999999999999999999999.9999999999
+99999999.99 9999999999999999999999999999.9999999999 99999999999999999999999999999999999999.99 999999999999999999999999999999999999999999999999999999999999999999.9999999999
+NULL NULL NULL NULL
+
+
+statement ok
+drop table test_nullable_decimal
## Original Query: SELECT abs(INTERVAL -'1-1' YEAR TO MONTH);
## PySpark 3.5.5 Result: {"abs(INTERVAL '-1-1' YEAR TO MONTH)": 13, "typeof(abs(INTERVAL '-1-1' YEAR TO MONTH))": 'interval year to month', "typeof(INTERVAL '-1-1' YEAR TO MONTH)": 'interval year to month'}
-#query
-#SELECT abs(INTERVAL '-1-1' YEAR TO MONTH::interval year to month);
+query error DataFusion error: This feature is not implemented: Unsupported SQL type INTERVAL YEAR TO MONTH
Review Comment:
Lets create a github ticket to fix this and refer to it in the comments in addition to the error.
Looks like abs works with intervals for Spark only
--
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-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org