datafusion_spark/function/datetime/
add_months.rs1use 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#[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}