datafusion_functions/datetime/
current_date.rs1use arrow::array::timezone::Tz;
19use arrow::datatypes::DataType;
20use arrow::datatypes::DataType::Date32;
21use chrono::{Datelike, NaiveDate, TimeZone};
22
23use datafusion_common::{Result, ScalarValue, internal_err};
24use datafusion_expr::simplify::{ExprSimplifyResult, SimplifyContext};
25use datafusion_expr::{
26 ColumnarValue, Documentation, Expr, ScalarFunctionArgs, ScalarUDFImpl, Signature,
27 Volatility,
28};
29use datafusion_macros::user_doc;
30
31#[user_doc(
32 doc_section(label = "Time and Date Functions"),
33 description = r#"
34Returns the current date in the session time zone.
35
36The `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.
37"#,
38 syntax_example = r#"current_date()
39 (optional) SET datafusion.execution.time_zone = '+00:00';
40 SELECT current_date();"#,
41 sql_example = r#"```sql
42> SELECT current_date();
43+----------------+
44| current_date() |
45+----------------+
46| 2024-12-23 |
47+----------------+
48
49-- The current date is based on the session time zone (UTC by default)
50> SET datafusion.execution.time_zone = 'Asia/Tokyo';
51> SELECT current_date();
52+----------------+
53| current_date() |
54+----------------+
55| 2024-12-24 |
56+----------------+
57```"#
58)]
59#[derive(Debug, PartialEq, Eq, Hash)]
60pub struct CurrentDateFunc {
61 signature: Signature,
62 aliases: Vec<String>,
63}
64
65impl Default for CurrentDateFunc {
66 fn default() -> Self {
67 Self::new()
68 }
69}
70
71impl CurrentDateFunc {
72 pub fn new() -> Self {
73 Self {
74 signature: Signature::nullary(Volatility::Stable),
75 aliases: vec![String::from("today")],
76 }
77 }
78}
79
80impl ScalarUDFImpl for CurrentDateFunc {
87 fn name(&self) -> &str {
88 "current_date"
89 }
90
91 fn signature(&self) -> &Signature {
92 &self.signature
93 }
94
95 fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
96 Ok(Date32)
97 }
98
99 fn invoke_with_args(&self, _args: ScalarFunctionArgs) -> Result<ColumnarValue> {
100 internal_err!(
101 "invoke should not be called on a simplified current_date() function"
102 )
103 }
104
105 fn aliases(&self) -> &[String] {
106 &self.aliases
107 }
108
109 fn simplify(
110 &self,
111 args: Vec<Expr>,
112 info: &SimplifyContext,
113 ) -> Result<ExprSimplifyResult> {
114 let Some(now_ts) = info.query_execution_start_time() else {
115 return Ok(ExprSimplifyResult::Original(args));
116 };
117
118 let days = info
120 .config_options()
121 .execution
122 .time_zone
123 .as_ref()
124 .and_then(|tz| tz.parse::<Tz>().ok())
125 .map_or_else(
126 || datetime_to_days(&now_ts),
127 |tz| {
128 let local_now = tz.from_utc_datetime(&now_ts.naive_utc());
129 datetime_to_days(&local_now)
130 },
131 );
132 Ok(ExprSimplifyResult::Simplified(Expr::Literal(
133 ScalarValue::Date32(Some(days)),
134 None,
135 )))
136 }
137
138 fn documentation(&self) -> Option<&Documentation> {
139 self.doc()
140 }
141}
142
143fn datetime_to_days<T: Datelike>(dt: &T) -> i32 {
145 dt.num_days_from_ce()
146 - NaiveDate::from_ymd_opt(1970, 1, 1)
147 .unwrap()
148 .num_days_from_ce()
149}