datafusion_functions/datetime/
current_date.rs1use 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
64impl 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 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
137fn 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}