Skip to main content

datafusion_spark/function/datetime/
date_diff.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::datatypes::{DataType, Field, FieldRef};
22use datafusion_common::types::{NativeType, logical_date, logical_string};
23use datafusion_common::utils::take_function_args;
24use datafusion_common::{Result, internal_err};
25use datafusion_expr::simplify::{ExprSimplifyResult, SimplifyContext};
26use datafusion_expr::{
27    Coercion, ColumnarValue, Expr, ExprSchemable, Operator, ReturnFieldArgs,
28    ScalarFunctionArgs, ScalarUDFImpl, Signature, TypeSignatureClass, Volatility,
29    binary_expr,
30};
31
32/// <https://spark.apache.org/docs/latest/api/sql/index.html#date_diff>
33#[derive(Debug, PartialEq, Eq, Hash)]
34pub struct SparkDateDiff {
35    signature: Signature,
36    aliases: Vec<String>,
37}
38
39impl Default for SparkDateDiff {
40    fn default() -> Self {
41        Self::new()
42    }
43}
44
45impl SparkDateDiff {
46    pub fn new() -> Self {
47        Self {
48            signature: Signature::coercible(
49                vec![
50                    Coercion::new_implicit(
51                        TypeSignatureClass::Native(logical_date()),
52                        vec![
53                            TypeSignatureClass::Native(logical_string()),
54                            TypeSignatureClass::Timestamp,
55                        ],
56                        NativeType::Date,
57                    ),
58                    Coercion::new_implicit(
59                        TypeSignatureClass::Native(logical_date()),
60                        vec![
61                            TypeSignatureClass::Native(logical_string()),
62                            TypeSignatureClass::Timestamp,
63                        ],
64                        NativeType::Date,
65                    ),
66                ],
67                Volatility::Immutable,
68            ),
69            aliases: vec!["datediff".to_string()],
70        }
71    }
72}
73
74impl ScalarUDFImpl for SparkDateDiff {
75    fn as_any(&self) -> &dyn Any {
76        self
77    }
78
79    fn name(&self) -> &str {
80        "date_diff"
81    }
82
83    fn aliases(&self) -> &[String] {
84        &self.aliases
85    }
86
87    fn signature(&self) -> &Signature {
88        &self.signature
89    }
90
91    fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
92        internal_err!("return_field_from_args should be used instead")
93    }
94
95    fn return_field_from_args(&self, args: ReturnFieldArgs) -> Result<FieldRef> {
96        let nullable = args.arg_fields.iter().any(|f| f.is_nullable());
97        Ok(Arc::new(Field::new(self.name(), DataType::Int32, nullable)))
98    }
99
100    fn invoke_with_args(&self, _args: ScalarFunctionArgs) -> Result<ColumnarValue> {
101        internal_err!(
102            "Apache Spark `date_diff` should have been simplified to standard subtraction"
103        )
104    }
105
106    fn simplify(
107        &self,
108        args: Vec<Expr>,
109        info: &SimplifyContext,
110    ) -> Result<ExprSimplifyResult> {
111        let [end, start] = take_function_args(self.name(), args)?;
112        let end = end.cast_to(&DataType::Date32, info.schema())?;
113        let start = start.cast_to(&DataType::Date32, info.schema())?;
114        Ok(ExprSimplifyResult::Simplified(
115            binary_expr(end, Operator::Minus, start)
116                .cast_to(&DataType::Int32, info.schema())?,
117        ))
118    }
119}