datafusion_functions/math/
abs.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18//! math expressions
19
20use std::any::Any;
21use std::sync::Arc;
22
23use arrow::array::{
24    ArrayRef, Decimal128Array, Decimal256Array, Decimal32Array, Decimal64Array,
25    Float16Array, Float32Array, Float64Array, Int16Array, Int32Array, Int64Array,
26    Int8Array,
27};
28use arrow::datatypes::DataType;
29use arrow::error::ArrowError;
30use datafusion_common::{not_impl_err, utils::take_function_args, Result};
31use datafusion_expr::interval_arithmetic::Interval;
32use datafusion_expr::sort_properties::{ExprProperties, SortProperties};
33use datafusion_expr::{
34    ColumnarValue, Documentation, ScalarFunctionArgs, ScalarUDFImpl, Signature,
35    Volatility,
36};
37use datafusion_macros::user_doc;
38use num_traits::sign::Signed;
39
40type MathArrayFunction = fn(&ArrayRef) -> Result<ArrayRef>;
41
42macro_rules! make_abs_function {
43    ($ARRAY_TYPE:ident) => {{
44        |input: &ArrayRef| {
45            let array = downcast_named_arg!(&input, "abs arg", $ARRAY_TYPE);
46            let res: $ARRAY_TYPE = array.unary(|x| x.abs());
47            Ok(Arc::new(res) as ArrayRef)
48        }
49    }};
50}
51
52macro_rules! make_try_abs_function {
53    ($ARRAY_TYPE:ident) => {{
54        |input: &ArrayRef| {
55            let array = downcast_named_arg!(&input, "abs arg", $ARRAY_TYPE);
56            let res: $ARRAY_TYPE = array.try_unary(|x| {
57                x.checked_abs().ok_or_else(|| {
58                    ArrowError::ComputeError(format!(
59                        "{} overflow on abs({})",
60                        stringify!($ARRAY_TYPE),
61                        x
62                    ))
63                })
64            })?;
65            Ok(Arc::new(res) as ArrayRef)
66        }
67    }};
68}
69
70macro_rules! make_decimal_abs_function {
71    ($ARRAY_TYPE:ident) => {{
72        |input: &ArrayRef| {
73            let array = downcast_named_arg!(&input, "abs arg", $ARRAY_TYPE);
74            let res: $ARRAY_TYPE = array
75                .unary(|x| x.wrapping_abs())
76                .with_data_type(input.data_type().clone());
77            Ok(Arc::new(res) as ArrayRef)
78        }
79    }};
80}
81
82/// Abs SQL function
83/// Return different implementations based on input datatype to reduce branches during execution
84fn create_abs_function(input_data_type: &DataType) -> Result<MathArrayFunction> {
85    match input_data_type {
86        DataType::Float16 => Ok(make_abs_function!(Float16Array)),
87        DataType::Float32 => Ok(make_abs_function!(Float32Array)),
88        DataType::Float64 => Ok(make_abs_function!(Float64Array)),
89
90        // Types that may overflow, such as abs(-128_i8).
91        DataType::Int8 => Ok(make_try_abs_function!(Int8Array)),
92        DataType::Int16 => Ok(make_try_abs_function!(Int16Array)),
93        DataType::Int32 => Ok(make_try_abs_function!(Int32Array)),
94        DataType::Int64 => Ok(make_try_abs_function!(Int64Array)),
95
96        // Types of results are the same as the input.
97        DataType::Null
98        | DataType::UInt8
99        | DataType::UInt16
100        | DataType::UInt32
101        | DataType::UInt64 => Ok(|input: &ArrayRef| Ok(Arc::clone(input))),
102
103        // Decimal types
104        DataType::Decimal32(_, _) => Ok(make_decimal_abs_function!(Decimal32Array)),
105        DataType::Decimal64(_, _) => Ok(make_decimal_abs_function!(Decimal64Array)),
106        DataType::Decimal128(_, _) => Ok(make_decimal_abs_function!(Decimal128Array)),
107        DataType::Decimal256(_, _) => Ok(make_decimal_abs_function!(Decimal256Array)),
108
109        other => not_impl_err!("Unsupported data type {other:?} for function abs"),
110    }
111}
112#[user_doc(
113    doc_section(label = "Math Functions"),
114    description = "Returns the absolute value of a number.",
115    syntax_example = "abs(numeric_expression)",
116    sql_example = r#"```sql
117> SELECT abs(-5);
118+----------+
119| abs(-5)  |
120+----------+
121| 5        |
122+----------+
123```"#,
124    standard_argument(name = "numeric_expression", prefix = "Numeric")
125)]
126#[derive(Debug, PartialEq, Eq, Hash)]
127pub struct AbsFunc {
128    signature: Signature,
129}
130
131impl Default for AbsFunc {
132    fn default() -> Self {
133        Self::new()
134    }
135}
136
137impl AbsFunc {
138    pub fn new() -> Self {
139        Self {
140            signature: Signature::numeric(1, Volatility::Immutable),
141        }
142    }
143}
144
145impl ScalarUDFImpl for AbsFunc {
146    fn as_any(&self) -> &dyn Any {
147        self
148    }
149
150    fn name(&self) -> &str {
151        "abs"
152    }
153
154    fn signature(&self) -> &Signature {
155        &self.signature
156    }
157
158    fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
159        Ok(arg_types[0].clone())
160    }
161
162    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
163        let args = ColumnarValue::values_to_arrays(&args.args)?;
164        let [input] = take_function_args(self.name(), args)?;
165
166        let input_data_type = input.data_type();
167        let abs_fun = create_abs_function(input_data_type)?;
168
169        abs_fun(&input).map(ColumnarValue::Array)
170    }
171
172    fn output_ordering(&self, input: &[ExprProperties]) -> Result<SortProperties> {
173        // Non-decreasing for x ≥ 0 and symmetrically non-increasing for x ≤ 0.
174        let arg = &input[0];
175        let range = &arg.range;
176        let zero_point = Interval::make_zero(&range.lower().data_type())?;
177
178        if range.gt_eq(&zero_point)? == Interval::CERTAINLY_TRUE {
179            Ok(arg.sort_properties)
180        } else if range.lt_eq(&zero_point)? == Interval::CERTAINLY_TRUE {
181            Ok(-arg.sort_properties)
182        } else {
183            Ok(SortProperties::Unordered)
184        }
185    }
186
187    fn documentation(&self) -> Option<&Documentation> {
188        self.doc()
189    }
190}