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