## 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/factorial.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 arrow::{
    19
        array::{ArrayRef, Int64Array},
    20
        error::ArrowError,
    21
    };
    22
    use std::any::Any;
    23
    use std::sync::Arc;
    24
    25
    use arrow::datatypes::DataType;
    26
    use arrow::datatypes::DataType::Int64;
    27
    28
    use crate::utils::make_scalar_function;
    29
    use datafusion_common::{arrow_datafusion_err, exec_err, DataFusionError, Result};
    30
    use datafusion_expr::{
    31
        ColumnarValue, Documentation, ScalarFunctionArgs, ScalarUDFImpl, Signature,
    32
        Volatility,
    33
    };
    34
    use datafusion_macros::user_doc;
    35
    36
    #[user_doc(
    37
        doc_section(label = "Math Functions"),
    38
        description = "Factorial. Returns 1 if value is less than 2.",
    39
        syntax_example = "factorial(numeric_expression)",
    40
        sql_example = r#"```sql
    41
    > SELECT factorial(5);
    42
    +---------------+
    43
    | factorial(5)  |
    44
    +---------------+
    45
    | 120           |
    46
    +---------------+
    47
    ```"#,
    48
        standard_argument(name = "numeric_expression", prefix = "Numeric")
    49
    )]
    50
    #[derive(Debug, PartialEq, Eq, Hash)]
    51
    pub struct FactorialFunc {
    52
        signature: Signature,
    53
    }
    54
    55
    impl Default for FactorialFunc {
    56
    0
        fn default() -> Self {
    57
    0
            FactorialFunc::new()
    58
    0
        }
    59
    }
    60
    61
    impl FactorialFunc {
    62
    0
        pub fn new() -> Self {
    63
    0
            Self {
    64
    0
                signature: Signature::uniform(1, vec![Int64], Volatility::Immutable),
    65
    0
            }
    66
    0
        }
    67
    }
    68
    69
    impl ScalarUDFImpl for FactorialFunc {
    70
    0
        fn as_any(&self) -> &dyn Any {
    71
    0
            self
    72
    0
        }
    73
    74
    0
        fn name(&self) -> &str {
    75
    0
            "factorial"
    76
    0
        }
    77
    78
    0
        fn signature(&self) -> &Signature {
    79
    0
            &self.signature
    80
    0
        }
    81
    82
    0
        fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
    83
    0
            Ok(Int64)
    84
    0
        }
    85
    86
    0
        fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
    87
    0
            make_scalar_function(factorial, vec![])(&args.args)
    88
    0
        }
    89
    90
    0
        fn documentation(&self) -> Option<&Documentation> {
    91
    0
            self.doc()
    92
    0
        }
    93
    }
    94
    95
    /// Factorial SQL function
    96
    0
    fn factorial(args: &[ArrayRef]) -> Result<ArrayRef> {
    97
    0
        match args[0].data_type() {
    98
            Int64 => {
    99
    0
                let arg = downcast_named_arg!((&args[0]), "value", Int64Array);
    100
    0
                Ok(arg
    101
    0
                    .iter()
    102
    0
                    .map(|a| match a {
    103
    0
                        Some(a) => (2..=a)
    104
    0
                            .try_fold(1i64, i64::checked_mul)
    105
    0
                            .ok_or_else(|| {
    106
    0
                                arrow_datafusion_err!(ArrowError::ComputeError(format!(
    107
    0
                                    "Overflow happened on FACTORIAL({a})"
    108
    0
                                )))
    109
    0
                            })
    110
    0
                            .map(Some),
    111
    0
                        _ => Ok(None),
    112
    0
                    })
    113
    0
                    .collect::<Result<Int64Array>>()
    114
    0
                    .map(Arc::new)? as ArrayRef)
    115
            }
    116
    0
            other => exec_err!("Unsupported data type {other:?} for function factorial."),
    117
        }
    118
    0
    }
    119
    120
    #[cfg(test)]
    121
    mod test {
    122
    123
        use datafusion_common::cast::as_int64_array;
    124
    125
        use super::*;
    126
    127
        #[test]
    128
        fn test_factorial_i64() {
    129
            let args: Vec<ArrayRef> = vec![
    130
                Arc::new(Int64Array::from(vec![0, 1, 2, 4])), // input
    131
            ];
    132
    133
            let result = factorial(&args).expect("failed to initialize function factorial");
    134
            let ints =
    135
                as_int64_array(&result).expect("failed to initialize function factorial");
    136
    137
            let expected = Int64Array::from(vec![1, 1, 2, 24]);
    138
    139
            assert_eq!(ints, &expected);
    140
        }
    141
    }