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