datafusion_functions/datetime/
current_date.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;
19
20use arrow::array::timezone::Tz;
21use arrow::datatypes::DataType;
22use arrow::datatypes::DataType::Date32;
23use chrono::{Datelike, NaiveDate, TimeZone};
24
25use datafusion_common::{internal_err, Result, ScalarValue};
26use datafusion_expr::simplify::{ExprSimplifyResult, SimplifyInfo};
27use datafusion_expr::{
28    ColumnarValue, Documentation, Expr, ScalarUDFImpl, Signature, Volatility,
29};
30use datafusion_macros::user_doc;
31
32#[user_doc(
33    doc_section(label = "Time and Date Functions"),
34    description = r#"
35Returns the current date in the session time zone.
36
37The `current_date()` return value is determined at query time and will return the same date, no matter when in the query plan the function executes.
38"#,
39    syntax_example = r#"current_date()
40    (optional) SET datafusion.execution.time_zone = '+00:00';
41    SELECT current_date();"#
42)]
43#[derive(Debug, PartialEq, Eq, Hash)]
44pub struct CurrentDateFunc {
45    signature: Signature,
46    aliases: Vec<String>,
47}
48
49impl Default for CurrentDateFunc {
50    fn default() -> Self {
51        Self::new()
52    }
53}
54
55impl CurrentDateFunc {
56    pub fn new() -> Self {
57        Self {
58            signature: Signature::nullary(Volatility::Stable),
59            aliases: vec![String::from("today")],
60        }
61    }
62}
63
64/// Create an implementation of `current_date()` that always returns the
65/// specified current date.
66///
67/// The semantics of `current_date()` require it to return the same value
68/// wherever it appears within a single statement. This value is
69/// chosen during planning time.
70impl ScalarUDFImpl for CurrentDateFunc {
71    fn as_any(&self) -> &dyn Any {
72        self
73    }
74
75    fn name(&self) -> &str {
76        "current_date"
77    }
78
79    fn signature(&self) -> &Signature {
80        &self.signature
81    }
82
83    fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
84        Ok(Date32)
85    }
86
87    fn invoke_with_args(
88        &self,
89        _args: datafusion_expr::ScalarFunctionArgs,
90    ) -> Result<ColumnarValue> {
91        internal_err!(
92            "invoke should not be called on a simplified current_date() function"
93        )
94    }
95
96    fn aliases(&self) -> &[String] {
97        &self.aliases
98    }
99
100    fn simplify(
101        &self,
102        _args: Vec<Expr>,
103        info: &dyn SimplifyInfo,
104    ) -> Result<ExprSimplifyResult> {
105        let now_ts = info.execution_props().query_execution_start_time;
106
107        // Get timezone from config and convert to local time
108        let days = info
109            .execution_props()
110            .config_options()
111            .and_then(|config| {
112                config
113                    .execution
114                    .time_zone
115                    .as_ref()
116                    .map(|tz| tz.parse::<Tz>().ok())
117            })
118            .flatten()
119            .map_or_else(
120                || datetime_to_days(&now_ts),
121                |tz| {
122                    let local_now = tz.from_utc_datetime(&now_ts.naive_utc());
123                    datetime_to_days(&local_now)
124                },
125            );
126        Ok(ExprSimplifyResult::Simplified(Expr::Literal(
127            ScalarValue::Date32(Some(days)),
128            None,
129        )))
130    }
131
132    fn documentation(&self) -> Option<&Documentation> {
133        self.doc()
134    }
135}
136
137/// Converts a DateTime to the number of days since Unix epoch (1970-01-01)
138fn datetime_to_days<T: Datelike>(dt: &T) -> i32 {
139    dt.num_days_from_ce()
140        - NaiveDate::from_ymd_opt(1970, 1, 1)
141            .unwrap()
142            .num_days_from_ce()
143}