datafusion_spark/function/datetime/
date_add.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
18use std::any::Any;
19use std::sync::Arc;
20
21use arrow::array::ArrayRef;
22use arrow::compute;
23use arrow::datatypes::{DataType, Date32Type};
24use arrow::error::ArrowError;
25use datafusion_common::cast::{
26    as_date32_array, as_int16_array, as_int32_array, as_int8_array,
27};
28use datafusion_common::{internal_err, Result};
29use datafusion_expr::{
30    ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl, Signature, TypeSignature,
31    Volatility,
32};
33use datafusion_functions::utils::make_scalar_function;
34
35#[derive(Debug, PartialEq, Eq, Hash)]
36pub struct SparkDateAdd {
37    signature: Signature,
38    aliases: Vec<String>,
39}
40
41impl Default for SparkDateAdd {
42    fn default() -> Self {
43        Self::new()
44    }
45}
46
47impl SparkDateAdd {
48    pub fn new() -> Self {
49        Self {
50            signature: Signature::one_of(
51                vec![
52                    TypeSignature::Exact(vec![DataType::Date32, DataType::Int8]),
53                    TypeSignature::Exact(vec![DataType::Date32, DataType::Int16]),
54                    TypeSignature::Exact(vec![DataType::Date32, DataType::Int32]),
55                ],
56                Volatility::Immutable,
57            ),
58            aliases: vec!["dateadd".to_string()],
59        }
60    }
61}
62
63impl ScalarUDFImpl for SparkDateAdd {
64    fn as_any(&self) -> &dyn Any {
65        self
66    }
67
68    fn name(&self) -> &str {
69        "date_add"
70    }
71
72    fn aliases(&self) -> &[String] {
73        &self.aliases
74    }
75
76    fn signature(&self) -> &Signature {
77        &self.signature
78    }
79
80    fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
81        Ok(DataType::Date32)
82    }
83
84    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
85        make_scalar_function(spark_date_add, vec![])(&args.args)
86    }
87}
88
89fn spark_date_add(args: &[ArrayRef]) -> Result<ArrayRef> {
90    let [date_arg, days_arg] = args else {
91        return internal_err!(
92            "Spark `date_add` function requires 2 arguments, got {}",
93            args.len()
94        );
95    };
96    let date_array = as_date32_array(date_arg)?;
97    let result = match days_arg.data_type() {
98        DataType::Int8 => {
99            let days_array = as_int8_array(days_arg)?;
100            compute::try_binary::<_, _, _, Date32Type>(
101                date_array,
102                days_array,
103                |date, days| {
104                    date.checked_add(days as i32).ok_or_else(|| {
105                        ArrowError::ArithmeticOverflow("date_add".to_string())
106                    })
107                },
108            )?
109        }
110        DataType::Int16 => {
111            let days_array = as_int16_array(days_arg)?;
112            compute::try_binary::<_, _, _, Date32Type>(
113                date_array,
114                days_array,
115                |date, days| {
116                    date.checked_add(days as i32).ok_or_else(|| {
117                        ArrowError::ArithmeticOverflow("date_add".to_string())
118                    })
119                },
120            )?
121        }
122        DataType::Int32 => {
123            let days_array = as_int32_array(days_arg)?;
124            compute::try_binary::<_, _, _, Date32Type>(
125                date_array,
126                days_array,
127                |date, days| {
128                    date.checked_add(days).ok_or_else(|| {
129                        ArrowError::ArithmeticOverflow("date_add".to_string())
130                    })
131                },
132            )?
133        }
134        _ => {
135            return internal_err!(
136                "Spark `date_add` function: argument must be int8, int16, int32, got {:?}",
137                days_arg.data_type()
138            );
139        }
140    };
141    Ok(Arc::new(result))
142}