Skip to main content

datafusion_spark/function/datetime/
add_months.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::ops::Add;
20use std::sync::Arc;
21
22use arrow::datatypes::{DataType, Field, FieldRef, IntervalUnit};
23use datafusion_common::utils::take_function_args;
24use datafusion_common::{Result, internal_err};
25use datafusion_expr::simplify::{ExprSimplifyResult, SimplifyContext};
26use datafusion_expr::{
27    ColumnarValue, Expr, ExprSchemable, ReturnFieldArgs, ScalarFunctionArgs,
28    ScalarUDFImpl, Signature, Volatility,
29};
30
31/// <https://spark.apache.org/docs/latest/api/sql/index.html#add_months>
32#[derive(Debug, PartialEq, Eq, Hash)]
33pub struct SparkAddMonths {
34    signature: Signature,
35}
36
37impl Default for SparkAddMonths {
38    fn default() -> Self {
39        Self::new()
40    }
41}
42
43impl SparkAddMonths {
44    pub fn new() -> Self {
45        Self {
46            signature: Signature::exact(
47                vec![DataType::Date32, DataType::Int32],
48                Volatility::Immutable,
49            ),
50        }
51    }
52}
53
54impl ScalarUDFImpl for SparkAddMonths {
55    fn as_any(&self) -> &dyn Any {
56        self
57    }
58
59    fn name(&self) -> &str {
60        "add_months"
61    }
62
63    fn signature(&self) -> &Signature {
64        &self.signature
65    }
66
67    fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
68        internal_err!("return_field_from_args should be used instead")
69    }
70
71    fn return_field_from_args(&self, args: ReturnFieldArgs) -> Result<FieldRef> {
72        let nullable = args.arg_fields.iter().any(|f| f.is_nullable());
73
74        Ok(Arc::new(Field::new(
75            self.name(),
76            DataType::Date32,
77            nullable,
78        )))
79    }
80
81    fn simplify(
82        &self,
83        args: Vec<Expr>,
84        info: &SimplifyContext,
85    ) -> Result<ExprSimplifyResult> {
86        let [date_arg, months_arg] = take_function_args("add_months", args)?;
87        let interval = months_arg
88            .cast_to(&DataType::Interval(IntervalUnit::YearMonth), info.schema())?;
89        Ok(ExprSimplifyResult::Simplified(date_arg.add(interval)))
90    }
91
92    fn invoke_with_args(&self, _args: ScalarFunctionArgs) -> Result<ColumnarValue> {
93        internal_err!("invoke should not be called on a simplified add_months() function")
94    }
95}