Skip to main content

datafusion_spark/function/datetime/
time_trunc.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::logical_string;
22use datafusion_common::{Result, ScalarValue, internal_err, plan_err};
23use datafusion_expr::expr::ScalarFunction;
24use datafusion_expr::simplify::{ExprSimplifyResult, SimplifyContext};
25use datafusion_expr::{
26    Coercion, ColumnarValue, Expr, ReturnFieldArgs, ScalarFunctionArgs, ScalarUDFImpl,
27    Signature, TypeSignatureClass, Volatility,
28};
29
30/// Spark time_trunc function only handles time inputs.
31/// <https://spark.apache.org/docs/latest/api/sql/index.html#time_trunc>
32#[derive(Debug, PartialEq, Eq, Hash)]
33pub struct SparkTimeTrunc {
34    signature: Signature,
35}
36
37impl Default for SparkTimeTrunc {
38    fn default() -> Self {
39        Self::new()
40    }
41}
42
43impl SparkTimeTrunc {
44    pub fn new() -> Self {
45        Self {
46            signature: Signature::coercible(
47                vec![
48                    Coercion::new_exact(TypeSignatureClass::Native(logical_string())),
49                    Coercion::new_exact(TypeSignatureClass::Time),
50                ],
51                Volatility::Immutable,
52            ),
53        }
54    }
55}
56
57impl ScalarUDFImpl for SparkTimeTrunc {
58    fn name(&self) -> &str {
59        "time_trunc"
60    }
61
62    fn signature(&self) -> &Signature {
63        &self.signature
64    }
65
66    fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
67        internal_err!("return_field_from_args should be used instead")
68    }
69
70    fn return_field_from_args(&self, args: ReturnFieldArgs) -> Result<FieldRef> {
71        let nullable = args.arg_fields.iter().any(|f| f.is_nullable());
72
73        Ok(Arc::new(Field::new(
74            self.name(),
75            args.arg_fields[1].data_type().clone(),
76            nullable,
77        )))
78    }
79
80    fn invoke_with_args(&self, _args: ScalarFunctionArgs) -> Result<ColumnarValue> {
81        internal_err!(
82            "spark time_trunc should have been simplified to standard date_trunc"
83        )
84    }
85
86    fn simplify(
87        &self,
88        args: Vec<Expr>,
89        _info: &SimplifyContext,
90    ) -> Result<ExprSimplifyResult> {
91        let fmt_expr = &args[0];
92
93        let fmt = match fmt_expr.as_literal() {
94            Some(ScalarValue::Utf8(Some(v)))
95            | Some(ScalarValue::Utf8View(Some(v)))
96            | Some(ScalarValue::LargeUtf8(Some(v))) => v.to_lowercase(),
97            _ => {
98                return plan_err!(
99                    "First argument of `TIME_TRUNC` must be non-null scalar Utf8"
100                );
101            }
102        };
103
104        if !matches!(
105            fmt.as_str(),
106            "hour" | "minute" | "second" | "millisecond" | "microsecond"
107        ) {
108            return plan_err!(
109                "The format argument of `TIME_TRUNC` must be one of: hour, minute, second, millisecond, microsecond"
110            );
111        }
112
113        Ok(ExprSimplifyResult::Simplified(Expr::ScalarFunction(
114            ScalarFunction::new_udf(datafusion_functions::datetime::date_trunc(), args),
115        )))
116    }
117}