1use std::collections::BTreeMap;
12
13use chrono::{Local, NaiveDateTime, Offset, TimeZone, Utc};
14
15use crate::{Error, Result, Value};
16
17use super::zone::{add_offset, offset_for_zone, offset_from_map, IanaAt, ResolvedZone};
18use super::Temporal;
19
20#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub enum ClockKind {
25 Date,
26 Time,
27 LocalTime,
28 DateTime,
29 LocalDateTime,
30}
31
32impl ClockKind {
33 const TABLE: &'static [(&'static str, ClockKind)] = &[
37 ("date", ClockKind::Date),
38 ("time", ClockKind::Time),
39 ("localtime", ClockKind::LocalTime),
40 ("datetime", ClockKind::DateTime),
41 ("localdatetime", ClockKind::LocalDateTime),
42 ];
43
44 pub fn name(self) -> &'static str {
46 Self::TABLE
47 .iter()
48 .find(|(_, kind)| *kind == self)
49 .map(|(name, _)| *name)
50 .expect("every ClockKind is in the table")
51 }
52
53 pub(super) fn from_name(name: &str) -> Option<Self> {
55 super::lookup(Self::TABLE, name)
56 }
57
58 pub(super) fn has_date(self) -> bool {
62 matches!(
63 self,
64 ClockKind::Date | ClockKind::LocalDateTime | ClockKind::DateTime
65 )
66 }
67
68 pub(super) fn has_time(self) -> bool {
70 !matches!(self, ClockKind::Date)
71 }
72
73 pub(super) fn has_zone(self) -> bool {
75 matches!(self, ClockKind::Time | ClockKind::DateTime)
76 }
77
78 pub(super) fn has_epoch(self) -> bool {
83 matches!(self, ClockKind::DateTime)
84 }
85
86 pub(super) fn has_date_and_time(self) -> bool {
88 self.has_date() && self.has_time()
89 }
90}
91
92#[derive(Debug, Clone, Copy, PartialEq, Eq)]
94pub enum ClockMode {
95 Transaction,
96 Statement,
97 Realtime,
98}
99
100impl ClockMode {
101 const TABLE: &'static [(&'static str, ClockMode)] = &[
104 ("transaction", ClockMode::Transaction),
105 ("statement", ClockMode::Statement),
106 ("realtime", ClockMode::Realtime),
107 ];
108
109 pub fn suffix(self) -> &'static str {
111 Self::TABLE
112 .iter()
113 .find(|(_, mode)| *mode == self)
114 .map(|(suffix, _)| *suffix)
115 .expect("every ClockMode is in the table")
116 }
117}
118
119pub const CLOCK_SPELLINGS: &[(&str, ClockKind, ClockMode)] = &[
124 ("date.realtime", ClockKind::Date, ClockMode::Realtime),
125 ("date.statement", ClockKind::Date, ClockMode::Statement),
126 ("date.transaction", ClockKind::Date, ClockMode::Transaction),
127 (
128 "datetime.realtime",
129 ClockKind::DateTime,
130 ClockMode::Realtime,
131 ),
132 (
133 "datetime.statement",
134 ClockKind::DateTime,
135 ClockMode::Statement,
136 ),
137 (
138 "datetime.transaction",
139 ClockKind::DateTime,
140 ClockMode::Transaction,
141 ),
142 (
143 "localdatetime.realtime",
144 ClockKind::LocalDateTime,
145 ClockMode::Realtime,
146 ),
147 (
148 "localdatetime.statement",
149 ClockKind::LocalDateTime,
150 ClockMode::Statement,
151 ),
152 (
153 "localdatetime.transaction",
154 ClockKind::LocalDateTime,
155 ClockMode::Transaction,
156 ),
157 (
158 "localtime.realtime",
159 ClockKind::LocalTime,
160 ClockMode::Realtime,
161 ),
162 (
163 "localtime.statement",
164 ClockKind::LocalTime,
165 ClockMode::Statement,
166 ),
167 (
168 "localtime.transaction",
169 ClockKind::LocalTime,
170 ClockMode::Transaction,
171 ),
172 ("time.realtime", ClockKind::Time, ClockMode::Realtime),
173 ("time.statement", ClockKind::Time, ClockMode::Statement),
174 ("time.transaction", ClockKind::Time, ClockMode::Transaction),
175];
176
177pub fn clock_access(name: &str) -> Option<(ClockKind, ClockMode)> {
180 let lower = name.to_ascii_lowercase();
181 CLOCK_SPELLINGS
182 .iter()
183 .find(|(spelling, _, _)| *spelling == lower)
184 .map(|(_, kind, mode)| (*kind, *mode))
185}
186
187pub fn clock_spelling(kind: ClockKind, mode: ClockMode) -> String {
190 format!("{}.{}", kind.name(), mode.suffix())
191}
192
193pub fn clock_spelling_rows() -> impl Iterator<Item = (&'static str, ClockKind, ClockMode)> {
197 CLOCK_SPELLINGS.iter().copied()
198}
199
200pub fn clock_spellings() -> impl Iterator<Item = &'static str> {
202 clock_spelling_rows().map(|(spelling, _, _)| spelling)
203}
204
205#[derive(Debug, Clone, Copy, PartialEq, Eq)]
210struct ClockReading {
211 utc: NaiveDateTime,
212 local_offset: i32,
213}
214
215impl ClockReading {
216 fn wall_clock() -> Self {
219 let utc = Utc::now();
220 let naive = utc.naive_utc();
221 Self {
222 utc: naive,
223 local_offset: Local
224 .offset_from_utc_datetime(&naive)
225 .fix()
226 .local_minus_utc(),
227 }
228 }
229
230 #[cfg(test)]
234 fn pinned(utc: NaiveDateTime, local_offset: i32) -> Self {
235 Self { utc, local_offset }
236 }
237}
238
239fn default_zone(kind: ClockKind, reading: ClockReading) -> ResolvedZone {
243 match kind {
244 ClockKind::DateTime => ResolvedZone::utc(),
245 ClockKind::Date | ClockKind::Time | ClockKind::LocalTime | ClockKind::LocalDateTime => {
246 ResolvedZone {
247 offset: reading.local_offset,
248 zone: None,
249 }
250 }
251 }
252}
253
254pub(super) fn zoned(utc: NaiveDateTime, resolved: ResolvedZone) -> Temporal {
257 Temporal::DateTime {
258 utc,
259 offset: resolved.offset,
260 zone: resolved.zone,
261 }
262}
263
264pub(super) fn clock_temporal(
268 kind: ClockKind,
269 utc: NaiveDateTime,
270 resolved: ResolvedZone,
271) -> Result<Temporal> {
272 let wall = add_offset(utc, resolved.offset)?;
273 Ok(match kind {
274 ClockKind::Date => Temporal::Date(wall.date()),
275 ClockKind::Time => Temporal::Time {
276 time: wall.time(),
277 offset: resolved.offset,
278 },
279 ClockKind::LocalTime => Temporal::LocalTime(wall.time()),
280 ClockKind::DateTime => zoned(utc, resolved),
281 ClockKind::LocalDateTime => Temporal::LocalDateTime(wall),
282 })
283}
284
285pub(super) fn clock_from_map(kind: ClockKind, m: &BTreeMap<String, Value>) -> Result<Temporal> {
289 let reading = clock_reading(ClockMode::Transaction);
290 let resolved = offset_from_map(m, IanaAt::Utc(reading.utc))?;
291 clock_temporal(kind, reading.utc, resolved)
292}
293
294pub fn construct_clock(kind: ClockKind, mode: ClockMode, arg: Option<&Value>) -> Result<Value> {
300 let reading = clock_reading(mode);
301 match arg {
302 None => Ok(Value::Temporal(clock_temporal(
303 kind,
304 reading.utc,
305 default_zone(kind, reading),
306 )?)),
307 Some(Value::Null) => Ok(Value::Null),
308 Some(Value::String(zone)) => {
309 let resolved = offset_for_zone(zone, IanaAt::Utc(reading.utc))?;
310 Ok(Value::Temporal(clock_temporal(
311 kind,
312 reading.utc,
313 resolved,
314 )?))
315 }
316 Some(_) => Err(Error::syntax(format!(
317 "Invalid call signature: {}() takes a timezone STRING",
318 clock_spelling(kind, mode)
319 ))),
320 }
321}
322
323thread_local! {
324 static PINNED: std::cell::Cell<Option<ClockReading>> =
325 const { std::cell::Cell::new(None) };
326}
327
328pub struct QueryClockGuard {
331 previous: Option<ClockReading>,
332}
333
334impl Default for QueryClockGuard {
335 fn default() -> Self {
336 Self::new()
337 }
338}
339
340impl QueryClockGuard {
341 pub fn new() -> Self {
342 Self::install(ClockReading::wall_clock())
343 }
344
345 fn install(reading: ClockReading) -> Self {
348 let previous = PINNED.with(|c| c.replace(Some(reading)));
349 Self { previous }
350 }
351}
352
353#[cfg(test)]
354impl QueryClockGuard {
355 pub fn pinned_at(utc: NaiveDateTime, local_offset: i32) -> Self {
358 Self::install(ClockReading::pinned(utc, local_offset))
359 }
360}
361
362impl Drop for QueryClockGuard {
363 fn drop(&mut self) {
364 PINNED.with(|c| c.set(self.previous));
365 }
366}
367
368fn unpinned_reading() -> ClockReading {
374 ClockReading::wall_clock()
375}
376
377fn pinned() -> ClockReading {
378 PINNED.with(|c| c.get()).unwrap_or_else(unpinned_reading)
379}
380
381fn clock_reading(mode: ClockMode) -> ClockReading {
385 match mode {
386 ClockMode::Transaction | ClockMode::Statement => pinned(),
387 ClockMode::Realtime => ClockReading::wall_clock(),
388 }
389}
390
391pub(super) fn now_value(kind: ClockKind) -> Temporal {
395 let reading = pinned();
396 clock_temporal(kind, reading.utc, default_zone(kind, reading))
397 .expect("the host clock is representable")
398}
399
400#[cfg(test)]
401pub(super) fn now_date() -> Temporal {
402 now_value(ClockKind::Date)
403}
404
405#[cfg(test)]
406pub(super) fn now_local_dt() -> Temporal {
407 now_value(ClockKind::LocalDateTime)
408}
409
410#[cfg(test)]
411pub(super) fn now_dt() -> Temporal {
412 now_value(ClockKind::DateTime)
413}
414
415pub fn now_epoch_millis() -> i64 {
419 pinned().utc.and_utc().timestamp_millis()
420}
421
422#[cfg(test)]
423pub(super) fn now_local_time() -> Temporal {
424 now_value(ClockKind::LocalTime)
425}
426
427#[cfg(test)]
428pub(super) fn now_time() -> Temporal {
429 now_value(ClockKind::Time)
430}
431
432pub fn now_utc_dt() -> NaiveDateTime {
436 pinned().utc
437}