## Coverage Report

#### Created: 2025-11-22 06:00

next uncovered line (L), next uncovered region (R), next uncovered branch (B)

    /Users/andrewlamb/Software/datafusion/datafusion/functions/src/math/signum.rs

    Line
    Count
    Source
    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
    use std::any::Any;
    19
    use std::sync::Arc;
    20
    21
    use arrow::array::{ArrayRef, AsArray};
    22
    use arrow::datatypes::DataType::{Float32, Float64};
    23
    use arrow::datatypes::{DataType, Float32Type, Float64Type};
    24
    25
    use datafusion_common::{exec_err, Result};
    26
    use datafusion_expr::sort_properties::{ExprProperties, SortProperties};
    27
    use datafusion_expr::{
    28
        ColumnarValue, Documentation, ScalarFunctionArgs, ScalarUDFImpl, Signature,
    29
        Volatility,
    30
    };
    31
    use datafusion_macros::user_doc;
    32
    33
    use crate::utils::make_scalar_function;
    34
    35
    #[user_doc(
    36
        doc_section(label = "Math Functions"),
    37
        description = r#"Returns the sign of a number.
    38
    Negative numbers return `-1`.
    39
    Zero and positive numbers return `1`."#,
    40
        syntax_example = "signum(numeric_expression)",
    41
        standard_argument(name = "numeric_expression", prefix = "Numeric"),
    42
        sql_example = r#"```sql
    43
    > SELECT signum(-42);
    44
    +-------------+
    45
    | signum(-42) |
    46
    +-------------+
    47
    | -1          |
    48
    +-------------+
    49
    ```"#
    50
    )]
    51
    #[derive(Debug, PartialEq, Eq, Hash)]
    52
    pub struct SignumFunc {
    53
        signature: Signature,
    54
    }
    55
    56
    impl Default for SignumFunc {
    57
    0
        fn default() -> Self {
    58
    0
            SignumFunc::new()
    59
    0
        }
    60
    }
    61
    62
    impl SignumFunc {
    63
    0
        pub fn new() -> Self {
    64
            use DataType::*;
    65
    0
            Self {
    66
    0
                signature: Signature::uniform(
    67
    0
                    1,
    68
    0
                    vec![Float64, Float32],
    69
    0
                    Volatility::Immutable,
    70
    0
                ),
    71
    0
            }
    72
    0
        }
    73
    }
    74
    75
    impl ScalarUDFImpl for SignumFunc {
    76
    0
        fn as_any(&self) -> &dyn Any {
    77
    0
            self
    78
    0
        }
    79
    80
    0
        fn name(&self) -> &str {
    81
    0
            "signum"
    82
    0
        }
    83
    84
    0
        fn signature(&self) -> &Signature {
    85
    0
            &self.signature
    86
    0
        }
    87
    88
    0
        fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
    89
    0
            match &arg_types[0] {
    90
    0
                Float32 => Ok(Float32),
    91
    0
                _ => Ok(Float64),
    92
            }
    93
    0
        }
    94
    95
    0
        fn output_ordering(&self, input: &[ExprProperties]) -> Result<SortProperties> {
    96
            // Non-decreasing for all real numbers x.
    97
    0
            Ok(input[0].sort_properties)
    98
    0
        }
    99
    100
    0
        fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
    101
    0
            make_scalar_function(signum, vec![])(&args.args)
    102
    0
        }
    103
    104
    0
        fn documentation(&self) -> Option<&Documentation> {
    105
    0
            self.doc()
    106
    0
        }
    107
    }
    108
    109
    /// signum SQL function
    110
    0
    pub fn signum(args: &[ArrayRef]) -> Result<ArrayRef> {
    111
    0
        match args[0].data_type() {
    112
    0
            Float64 => Ok(Arc::new(
    113
    0
                args[0]
    114
    0
                    .as_primitive::<Float64Type>()
    115
    0
                    .unary::<_, Float64Type>(
    116
    0
                        |x: f64| {
    117
    0
                            if x == 0_f64 {
    118
    0
                                0_f64
    119
                            } else {
    120
    0
                                x.signum()
    121
                            }
    122
    0
                        },
    123
                    ),
    124
    0
            ) as ArrayRef),
    125
    126
    0
            Float32 => Ok(Arc::new(
    127
    0
                args[0]
    128
    0
                    .as_primitive::<Float32Type>()
    129
    0
                    .unary::<_, Float32Type>(
    130
    0
                        |x: f32| {
    131
    0
                            if x == 0_f32 {
    132
    0
                                0_f32
    133
                            } else {
    134
    0
                                x.signum()
    135
                            }
    136
    0
                        },
    137
                    ),
    138
    0
            ) as ArrayRef),
    139
    140
    0
            other => exec_err!("Unsupported data type {other:?} for function signum"),
    141
        }
    142
    0
    }
    143
    144
    #[cfg(test)]
    145
    mod test {
    146
        use std::sync::Arc;
    147
    148
        use arrow::array::{ArrayRef, Float32Array, Float64Array};
    149
        use arrow::datatypes::{DataType, Field};
    150
        use datafusion_common::cast::{as_float32_array, as_float64_array};
    151
        use datafusion_common::config::ConfigOptions;
    152
        use datafusion_expr::{ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl};
    153
    154
        use crate::math::signum::SignumFunc;
    155
    156
        #[test]
    157
        fn test_signum_f32() {
    158
            let array = Arc::new(Float32Array::from(vec![
    159
                -1.0,
    160
                -0.0,
    161
                0.0,
    162
                1.0,
    163
                -0.01,
    164
                0.01,
    165
                f32::NAN,
    166
                f32::INFINITY,
    167
                f32::NEG_INFINITY,
    168
            ]));
    169
            let arg_fields = vec![Field::new("a", DataType::Float32, false).into()];
    170
            let args = ScalarFunctionArgs {
    171
                args: vec![ColumnarValue::Array(Arc::clone(&array) as ArrayRef)],
    172
                arg_fields,
    173
                number_rows: array.len(),
    174
                return_field: Field::new("f", DataType::Float32, true).into(),
    175
                config_options: Arc::new(ConfigOptions::default()),
    176
            };
    177
            let result = SignumFunc::new()
    178
                .invoke_with_args(args)
    179
                .expect("failed to initialize function signum");
    180
    181
            match result {
    182
                ColumnarValue::Array(arr) => {
    183
                    let floats = as_float32_array(&arr)
    184
                        .expect("failed to convert result to a Float32Array");
    185
    186
                    assert_eq!(floats.len(), 9);
    187
                    assert_eq!(floats.value(0), -1.0);
    188
                    assert_eq!(floats.value(1), 0.0);
    189
                    assert_eq!(floats.value(2), 0.0);
    190
                    assert_eq!(floats.value(3), 1.0);
    191
                    assert_eq!(floats.value(4), -1.0);
    192
                    assert_eq!(floats.value(5), 1.0);
    193
                    assert!(floats.value(6).is_nan());
    194
                    assert_eq!(floats.value(7), 1.0);
    195
                    assert_eq!(floats.value(8), -1.0);
    196
                }
    197
                ColumnarValue::Scalar(_) => {
    198
                    panic!("Expected an array value")
    199
                }
    200
            }
    201
        }
    202
    203
        #[test]
    204
        fn test_signum_f64() {
    205
            let array = Arc::new(Float64Array::from(vec![
    206
                -1.0,
    207
                -0.0,
    208
                0.0,
    209
                1.0,
    210
                -0.01,
    211
                0.01,
    212
                f64::NAN,
    213
                f64::INFINITY,
    214
                f64::NEG_INFINITY,
    215
            ]));
    216
            let arg_fields = vec![Field::new("a", DataType::Float64, false).into()];
    217
            let args = ScalarFunctionArgs {
    218
                args: vec![ColumnarValue::Array(Arc::clone(&array) as ArrayRef)],
    219
                arg_fields,
    220
                number_rows: array.len(),
    221
                return_field: Field::new("f", DataType::Float64, true).into(),
    222
                config_options: Arc::new(ConfigOptions::default()),
    223
            };
    224
            let result = SignumFunc::new()
    225
                .invoke_with_args(args)
    226
                .expect("failed to initialize function signum");
    227
    228
            match result {
    229
                ColumnarValue::Array(arr) => {
    230
                    let floats = as_float64_array(&arr)
    231
                        .expect("failed to convert result to a Float32Array");
    232
    233
                    assert_eq!(floats.len(), 9);
    234
                    assert_eq!(floats.value(0), -1.0);
    235
                    assert_eq!(floats.value(1), 0.0);
    236
                    assert_eq!(floats.value(2), 0.0);
    237
                    assert_eq!(floats.value(3), 1.0);
    238
                    assert_eq!(floats.value(4), -1.0);
    239
                    assert_eq!(floats.value(5), 1.0);
    240
                    assert!(floats.value(6).is_nan());
    241
                    assert_eq!(floats.value(7), 1.0);
    242
                    assert_eq!(floats.value(8), -1.0);
    243
                }
    244
                ColumnarValue::Scalar(_) => {
    245
                    panic!("Expected an array value")
    246
                }
    247
            }
    248
        }
    249
    }