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