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};
24use datafusion_common::cast::{
25    as_date32_array, as_int16_array, as_int32_array, as_int8_array,
26};
27use datafusion_common::{internal_err, Result};
28use datafusion_expr::{
29    ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl, Signature, TypeSignature,
30    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        Ok(DataType::Date32)
75    }
76
77    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
78        make_scalar_function(spark_date_sub, vec![])(&args.args)
79    }
80}
81
82fn spark_date_sub(args: &[ArrayRef]) -> Result<ArrayRef> {
83    let [date_arg, days_arg] = args else {
84        return internal_err!(
85            "Spark `date_sub` function requires 2 arguments, got {}",
86            args.len()
87        );
88    };
89    let date_array = as_date32_array(date_arg)?;
90    let result = match days_arg.data_type() {
91        DataType::Int8 => {
92            let days_array = as_int8_array(days_arg)?;
93            compute::binary::<_, _, _, Date32Type>(
94                date_array,
95                days_array,
96                |date, days| date - days as i32,
97            )?
98        }
99        DataType::Int16 => {
100            let days_array = as_int16_array(days_arg)?;
101            compute::binary::<_, _, _, Date32Type>(
102                date_array,
103                days_array,
104                |date, days| date - days as i32,
105            )?
106        }
107        DataType::Int32 => {
108            let days_array = as_int32_array(days_arg)?;
109            compute::binary::<_, _, _, Date32Type>(
110                date_array,
111                days_array,
112                |date, days| date - days,
113            )?
114        }
115        _ => {
116            return internal_err!(
117                "Spark `date_add` function: argument must be int8, int16, int32, got {:?}",
118                days_arg.data_type()
119            );
120        }
121    };
122    Ok(Arc::new(result))
123}