Skip to main content

datafusion_functions/math/
nans.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 function: `isnan()`.
19
20use arrow::array::{ArrayRef, AsArray, BooleanArray};
21use arrow::datatypes::DataType::{
22    Decimal32, Decimal64, Decimal128, Decimal256, Float16, Float32, Float64, Int8, Int16,
23    Int32, Int64, Null, UInt8, UInt16, UInt32, UInt64,
24};
25use arrow::datatypes::{
26    DataType, Decimal32Type, Decimal64Type, Decimal128Type, Decimal256Type, Float16Type,
27    Float32Type, Float64Type, Int8Type, Int16Type, Int32Type, Int64Type, UInt8Type,
28    UInt16Type, UInt32Type, UInt64Type,
29};
30use datafusion_common::{Result, ScalarValue, exec_err, utils::take_function_args};
31use datafusion_expr::{
32    Coercion, ColumnarValue, Documentation, ScalarFunctionArgs, ScalarUDFImpl, Signature,
33    TypeSignatureClass, Volatility,
34};
35use datafusion_macros::user_doc;
36use std::any::Any;
37use std::sync::Arc;
38
39#[user_doc(
40    doc_section(label = "Math Functions"),
41    description = "Returns true if a given number is +NaN or -NaN otherwise returns false.",
42    syntax_example = "isnan(numeric_expression)",
43    sql_example = r#"```sql
44> SELECT isnan(1);
45+----------+
46| isnan(1) |
47+----------+
48| false    |
49+----------+
50```"#,
51    standard_argument(name = "numeric_expression", prefix = "Numeric")
52)]
53#[derive(Debug, PartialEq, Eq, Hash)]
54pub struct IsNanFunc {
55    signature: Signature,
56}
57
58impl Default for IsNanFunc {
59    fn default() -> Self {
60        Self::new()
61    }
62}
63
64impl IsNanFunc {
65    pub fn new() -> Self {
66        // Accept any numeric type (ints, uints, floats, decimals) without implicit casts.
67        let numeric = Coercion::new_exact(TypeSignatureClass::Numeric);
68        Self {
69            signature: Signature::coercible(vec![numeric], Volatility::Immutable),
70        }
71    }
72}
73
74impl ScalarUDFImpl for IsNanFunc {
75    fn as_any(&self) -> &dyn Any {
76        self
77    }
78    fn name(&self) -> &str {
79        "isnan"
80    }
81
82    fn signature(&self) -> &Signature {
83        &self.signature
84    }
85
86    fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
87        Ok(DataType::Boolean)
88    }
89
90    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
91        let [arg] = take_function_args(self.name(), args.args)?;
92
93        match arg {
94            ColumnarValue::Scalar(scalar) => {
95                if scalar.is_null() {
96                    return Ok(ColumnarValue::Scalar(ScalarValue::Boolean(None)));
97                }
98
99                let result = match scalar {
100                    ScalarValue::Float64(Some(v)) => Some(v.is_nan()),
101                    ScalarValue::Float32(Some(v)) => Some(v.is_nan()),
102                    ScalarValue::Float16(Some(v)) => Some(v.is_nan()),
103
104                    // Non-float numeric inputs are never NaN
105                    ScalarValue::Int8(_)
106                    | ScalarValue::Int16(_)
107                    | ScalarValue::Int32(_)
108                    | ScalarValue::Int64(_)
109                    | ScalarValue::UInt8(_)
110                    | ScalarValue::UInt16(_)
111                    | ScalarValue::UInt32(_)
112                    | ScalarValue::UInt64(_)
113                    | ScalarValue::Decimal32(_, _, _)
114                    | ScalarValue::Decimal64(_, _, _)
115                    | ScalarValue::Decimal128(_, _, _)
116                    | ScalarValue::Decimal256(_, _, _) => Some(false),
117
118                    other => {
119                        return exec_err!(
120                            "Unsupported data type {other:?} for function {}",
121                            self.name()
122                        );
123                    }
124                };
125
126                Ok(ColumnarValue::Scalar(ScalarValue::Boolean(result)))
127            }
128            ColumnarValue::Array(array) => {
129                // NOTE: BooleanArray::from_unary preserves nulls.
130                let arr: ArrayRef = match array.data_type() {
131                    Null => Arc::new(BooleanArray::new_null(array.len())) as ArrayRef,
132
133                    Float64 => Arc::new(BooleanArray::from_unary(
134                        array.as_primitive::<Float64Type>(),
135                        f64::is_nan,
136                    )) as ArrayRef,
137                    Float32 => Arc::new(BooleanArray::from_unary(
138                        array.as_primitive::<Float32Type>(),
139                        f32::is_nan,
140                    )) as ArrayRef,
141                    Float16 => Arc::new(BooleanArray::from_unary(
142                        array.as_primitive::<Float16Type>(),
143                        |x| x.is_nan(),
144                    )) as ArrayRef,
145
146                    // Non-float numeric arrays are never NaN
147                    Decimal32(_, _) => Arc::new(BooleanArray::from_unary(
148                        array.as_primitive::<Decimal32Type>(),
149                        |_| false,
150                    )) as ArrayRef,
151                    Decimal64(_, _) => Arc::new(BooleanArray::from_unary(
152                        array.as_primitive::<Decimal64Type>(),
153                        |_| false,
154                    )) as ArrayRef,
155                    Decimal128(_, _) => Arc::new(BooleanArray::from_unary(
156                        array.as_primitive::<Decimal128Type>(),
157                        |_| false,
158                    )) as ArrayRef,
159                    Decimal256(_, _) => Arc::new(BooleanArray::from_unary(
160                        array.as_primitive::<Decimal256Type>(),
161                        |_| false,
162                    )) as ArrayRef,
163
164                    Int8 => Arc::new(BooleanArray::from_unary(
165                        array.as_primitive::<Int8Type>(),
166                        |_| false,
167                    )) as ArrayRef,
168                    Int16 => Arc::new(BooleanArray::from_unary(
169                        array.as_primitive::<Int16Type>(),
170                        |_| false,
171                    )) as ArrayRef,
172                    Int32 => Arc::new(BooleanArray::from_unary(
173                        array.as_primitive::<Int32Type>(),
174                        |_| false,
175                    )) as ArrayRef,
176                    Int64 => Arc::new(BooleanArray::from_unary(
177                        array.as_primitive::<Int64Type>(),
178                        |_| false,
179                    )) as ArrayRef,
180                    UInt8 => Arc::new(BooleanArray::from_unary(
181                        array.as_primitive::<UInt8Type>(),
182                        |_| false,
183                    )) as ArrayRef,
184                    UInt16 => Arc::new(BooleanArray::from_unary(
185                        array.as_primitive::<UInt16Type>(),
186                        |_| false,
187                    )) as ArrayRef,
188                    UInt32 => Arc::new(BooleanArray::from_unary(
189                        array.as_primitive::<UInt32Type>(),
190                        |_| false,
191                    )) as ArrayRef,
192                    UInt64 => Arc::new(BooleanArray::from_unary(
193                        array.as_primitive::<UInt64Type>(),
194                        |_| false,
195                    )) as ArrayRef,
196
197                    other => {
198                        return exec_err!(
199                            "Unsupported data type {other:?} for function {}",
200                            self.name()
201                        );
202                    }
203                };
204
205                Ok(ColumnarValue::Array(arr))
206            }
207        }
208    }
209
210    fn documentation(&self) -> Option<&Documentation> {
211        self.doc()
212    }
213}