Skip to main content

datafusion_spark/function/datetime/
date_sub.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, Field, FieldRef};
24use datafusion_common::cast::{
25    as_date32_array, as_int8_array, as_int16_array, as_int32_array,
26};
27use datafusion_common::{Result, internal_err};
28use datafusion_expr::{
29    ColumnarValue, ReturnFieldArgs, ScalarFunctionArgs, ScalarUDFImpl, Signature,
30    TypeSignature, Volatility,
31};
32use datafusion_functions::utils::make_scalar_function;
33
34#[derive(Debug, PartialEq, Eq, Hash)]
35pub struct SparkDateSub {
36    signature: Signature,
37}
38
39impl Default for SparkDateSub {
40    fn default() -> Self {
41        Self::new()
42    }
43}
44
45impl SparkDateSub {
46    pub fn new() -> Self {
47        Self {
48            signature: Signature::one_of(
49                vec![
50                    TypeSignature::Exact(vec![DataType::Date32, DataType::Int8]),
51                    TypeSignature::Exact(vec![DataType::Date32, DataType::Int16]),
52                    TypeSignature::Exact(vec![DataType::Date32, DataType::Int32]),
53                ],
54                Volatility::Immutable,
55            ),
56        }
57    }
58}
59
60impl ScalarUDFImpl for SparkDateSub {
61    fn as_any(&self) -> &dyn Any {
62        self
63    }
64
65    fn name(&self) -> &str {
66        "date_sub"
67    }
68
69    fn signature(&self) -> &Signature {
70        &self.signature
71    }
72
73    fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
74        internal_err!("return_field_from_args should be used instead")
75    }
76
77    fn return_field_from_args(&self, args: ReturnFieldArgs) -> Result<FieldRef> {
78        let nullable = args.arg_fields.iter().any(|f| f.is_nullable());
79        Ok(Arc::new(Field::new(
80            self.name(),
81            DataType::Date32,
82            nullable,
83        )))
84    }
85
86    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
87        make_scalar_function(spark_date_sub, vec![])(&args.args)
88    }
89}
90
91fn spark_date_sub(args: &[ArrayRef]) -> Result<ArrayRef> {
92    let [date_arg, days_arg] = args else {
93        return internal_err!(
94            "Spark `date_sub` function requires 2 arguments, got {}",
95            args.len()
96        );
97    };
98    let date_array = as_date32_array(date_arg)?;
99    let result = match days_arg.data_type() {
100        DataType::Int8 => {
101            let days_array = as_int8_array(days_arg)?;
102            compute::binary::<_, _, _, Date32Type>(
103                date_array,
104                days_array,
105                |date, days| date.wrapping_sub(days as i32),
106            )?
107        }
108        DataType::Int16 => {
109            let days_array = as_int16_array(days_arg)?;
110            compute::binary::<_, _, _, Date32Type>(
111                date_array,
112                days_array,
113                |date, days| date.wrapping_sub(days as i32),
114            )?
115        }
116        DataType::Int32 => {
117            let days_array = as_int32_array(days_arg)?;
118            compute::binary::<_, _, _, Date32Type>(
119                date_array,
120                days_array,
121                |date, days| date.wrapping_sub(days),
122            )?
123        }
124        _ => {
125            return internal_err!(
126                "Spark `date_sub` function: argument must be int8, int16, int32, got {:?}",
127                days_arg.data_type()
128            );
129        }
130    };
131    Ok(Arc::new(result))
132}
133
134#[cfg(test)]
135mod tests {
136    use super::*;
137
138    #[test]
139    fn test_date_sub_nullability_non_nullable_args() {
140        let udf = SparkDateSub::new();
141        let date_field = Arc::new(Field::new("d", DataType::Date32, false));
142        let days_field = Arc::new(Field::new("n", DataType::Int32, false));
143
144        let result = udf
145            .return_field_from_args(ReturnFieldArgs {
146                arg_fields: &[date_field, days_field],
147                scalar_arguments: &[None, None],
148            })
149            .unwrap();
150
151        assert!(!result.is_nullable());
152        assert_eq!(result.data_type(), &DataType::Date32);
153    }
154
155    #[test]
156    fn test_date_sub_nullability_nullable_arg() {
157        let udf = SparkDateSub::new();
158        let date_field = Arc::new(Field::new("d", DataType::Date32, false));
159        let nullable_days_field = Arc::new(Field::new("n", DataType::Int32, true));
160
161        let result = udf
162            .return_field_from_args(ReturnFieldArgs {
163                arg_fields: &[date_field, nullable_days_field],
164                scalar_arguments: &[None, None],
165            })
166            .unwrap();
167
168        assert!(result.is_nullable());
169        assert_eq!(result.data_type(), &DataType::Date32);
170    }
171}