1use std::collections::BTreeMap;
14
15use chrono::{Local, NaiveDateTime, Offset, TimeZone, Utc};
16
17use crate::{Error, Result, Value};
18
19use super::zone::{add_offset, offset_for_zone, offset_from_map, IanaAt, ResolvedZone};
20use super::Temporal;
21
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
26pub enum ClockKind {
27 Date,
28 Time,
29 LocalTime,
30 DateTime,
31 LocalDateTime,
32}
33
34impl ClockKind {
35 const TABLE: &'static [(&'static str, ClockKind)] = &[
39 ("date", ClockKind::Date),
40 ("time", ClockKind::Time),
41 ("localtime", ClockKind::LocalTime),
42 ("datetime", ClockKind::DateTime),
43 ("localdatetime", ClockKind::LocalDateTime),
44 ];
45
46 pub fn name(self) -> &'static str {
48 Self::TABLE
49 .iter()
50 .find(|(_, kind)| *kind == self)
51 .map(|(name, _)| *name)
52 .expect("every ClockKind is in the table")
53 }
54
55 pub(super) fn from_name(name: &str) -> Option<Self> {
57 super::lookup(Self::TABLE, name)
58 }
59
60 pub(super) fn from_name_ignore_case(name: &str) -> Option<Self> {
62 Self::TABLE
63 .iter()
64 .find(|(spelling, _)| spelling.eq_ignore_ascii_case(name))
65 .map(|(_, kind)| *kind)
66 }
67
68 pub(super) fn has_date(self) -> bool {
72 matches!(
73 self,
74 ClockKind::Date | ClockKind::LocalDateTime | ClockKind::DateTime
75 )
76 }
77
78 pub(super) fn has_time(self) -> bool {
80 !matches!(self, ClockKind::Date)
81 }
82
83 pub(super) fn has_zone(self) -> bool {
85 matches!(self, ClockKind::Time | ClockKind::DateTime)
86 }
87
88 pub(super) fn has_epoch(self) -> bool {
93 matches!(self, ClockKind::DateTime)
94 }
95
96 pub(super) fn has_date_and_time(self) -> bool {
98 self.has_date() && self.has_time()
99 }
100
101 #[cfg(test)]
105 pub(super) fn all() -> impl Iterator<Item = ClockKind> {
106 Self::TABLE.iter().map(|(_, kind)| *kind)
107 }
108}
109
110#[derive(Debug, Clone, Copy, PartialEq, Eq)]
112pub enum ClockMode {
113 Transaction,
114 Statement,
115 Realtime,
116}
117
118impl ClockMode {
119 const TABLE: &'static [(&'static str, ClockMode)] = &[
122 ("transaction", ClockMode::Transaction),
123 ("statement", ClockMode::Statement),
124 ("realtime", ClockMode::Realtime),
125 ];
126
127 pub fn suffix(self) -> &'static str {
129 Self::TABLE
130 .iter()
131 .find(|(_, mode)| *mode == self)
132 .map(|(suffix, _)| *suffix)
133 .expect("every ClockMode is in the table")
134 }
135}
136
137pub const CLOCK_SPELLINGS: &[(&str, ClockKind, ClockMode)] = &[
142 ("date.realtime", ClockKind::Date, ClockMode::Realtime),
143 ("date.statement", ClockKind::Date, ClockMode::Statement),
144 ("date.transaction", ClockKind::Date, ClockMode::Transaction),
145 (
146 "datetime.realtime",
147 ClockKind::DateTime,
148 ClockMode::Realtime,
149 ),
150 (
151 "datetime.statement",
152 ClockKind::DateTime,
153 ClockMode::Statement,
154 ),
155 (
156 "datetime.transaction",
157 ClockKind::DateTime,
158 ClockMode::Transaction,
159 ),
160 (
161 "localdatetime.realtime",
162 ClockKind::LocalDateTime,
163 ClockMode::Realtime,
164 ),
165 (
166 "localdatetime.statement",
167 ClockKind::LocalDateTime,
168 ClockMode::Statement,
169 ),
170 (
171 "localdatetime.transaction",
172 ClockKind::LocalDateTime,
173 ClockMode::Transaction,
174 ),
175 (
176 "localtime.realtime",
177 ClockKind::LocalTime,
178 ClockMode::Realtime,
179 ),
180 (
181 "localtime.statement",
182 ClockKind::LocalTime,
183 ClockMode::Statement,
184 ),
185 (
186 "localtime.transaction",
187 ClockKind::LocalTime,
188 ClockMode::Transaction,
189 ),
190 ("time.realtime", ClockKind::Time, ClockMode::Realtime),
191 ("time.statement", ClockKind::Time, ClockMode::Statement),
192 ("time.transaction", ClockKind::Time, ClockMode::Transaction),
193];
194
195pub fn clock_access(name: &str) -> Option<(ClockKind, ClockMode)> {
198 let lower = name.to_ascii_lowercase();
199 CLOCK_SPELLINGS
200 .iter()
201 .find(|(spelling, _, _)| *spelling == lower)
202 .map(|(_, kind, mode)| (*kind, *mode))
203}
204
205pub fn clock_spelling(kind: ClockKind, mode: ClockMode) -> String {
208 format!("{}.{}", kind.name(), mode.suffix())
209}
210
211pub fn clock_spelling_rows() -> impl Iterator<Item = (&'static str, ClockKind, ClockMode)> {
215 CLOCK_SPELLINGS.iter().copied()
216}
217
218pub fn clock_spellings() -> impl Iterator<Item = &'static str> {
220 clock_spelling_rows().map(|(spelling, _, _)| spelling)
221}
222
223#[derive(Debug, Clone, Copy, PartialEq, Eq)]
228struct ClockReading {
229 utc: NaiveDateTime,
230 local_offset: i32,
231}
232
233impl ClockReading {
234 fn wall_clock() -> Self {
237 let utc = Utc::now();
238 let naive = utc.naive_utc();
239 Self {
240 utc: naive,
241 local_offset: Local
242 .offset_from_utc_datetime(&naive)
243 .fix()
244 .local_minus_utc(),
245 }
246 }
247
248 #[cfg(test)]
252 fn pinned(utc: NaiveDateTime, local_offset: i32) -> Self {
253 Self { utc, local_offset }
254 }
255}
256
257fn default_zone(kind: ClockKind, reading: ClockReading) -> ResolvedZone {
261 match kind {
262 ClockKind::DateTime => ResolvedZone::utc(),
263 ClockKind::Date | ClockKind::Time | ClockKind::LocalTime | ClockKind::LocalDateTime => {
264 ResolvedZone {
265 offset: reading.local_offset,
266 zone: None,
267 }
268 }
269 }
270}
271
272pub(super) fn zoned(utc: NaiveDateTime, resolved: ResolvedZone) -> Temporal {
275 Temporal::DateTime {
276 utc,
277 offset: resolved.offset,
278 zone: resolved.zone,
279 }
280}
281
282pub(super) fn clock_temporal(
286 kind: ClockKind,
287 utc: NaiveDateTime,
288 resolved: ResolvedZone,
289) -> Result<Temporal> {
290 let wall = add_offset(utc, resolved.offset)?;
291 Ok(match kind {
292 ClockKind::Date => Temporal::Date(wall.date()),
293 ClockKind::Time => Temporal::Time {
294 time: wall.time(),
295 offset: resolved.offset,
296 },
297 ClockKind::LocalTime => Temporal::LocalTime(wall.time()),
298 ClockKind::DateTime => zoned(utc, resolved),
299 ClockKind::LocalDateTime => Temporal::LocalDateTime(wall),
300 })
301}
302
303pub(super) fn clock_from_map(kind: ClockKind, m: &BTreeMap<String, Value>) -> Result<Temporal> {
307 let reading = clock_reading(ClockMode::Statement);
308 let resolved = offset_from_map(m, IanaAt::Utc(reading.utc))?;
309 clock_temporal(kind, reading.utc, resolved)
310}
311
312pub fn construct_clock(kind: ClockKind, mode: ClockMode, arg: Option<&Value>) -> Result<Value> {
318 let reading = clock_reading(mode);
319 match arg {
320 None => Ok(Value::Temporal(clock_temporal(
321 kind,
322 reading.utc,
323 default_zone(kind, reading),
324 )?)),
325 Some(Value::Null) => Ok(Value::Null),
326 Some(Value::String(zone)) => {
327 let resolved = offset_for_zone(zone, IanaAt::Utc(reading.utc))?;
328 Ok(Value::Temporal(clock_temporal(
329 kind,
330 reading.utc,
331 resolved,
332 )?))
333 }
334 Some(_) => Err(Error::procedure_call(format!(
338 "Invalid call signature: {}() takes a timezone STRING",
339 clock_spelling(kind, mode)
340 ))),
341 }
342}
343
344#[derive(Clone, Copy)]
350struct Pins {
351 statement: Option<ClockReading>,
352 transaction: Option<ClockReading>,
353}
354
355thread_local! {
356 static PINS: std::cell::Cell<Pins> = const {
357 std::cell::Cell::new(Pins { statement: None, transaction: None })
358 };
359}
360
361#[derive(Debug, Clone, Copy, PartialEq, Eq)]
366pub struct TransactionClock(ClockReading);
367
368impl TransactionClock {
369 pub fn begin() -> Self {
371 Self(ClockReading::wall_clock())
372 }
373}
374
375pub struct QueryClockGuard {
378 previous: Pins,
379}
380
381impl Default for QueryClockGuard {
382 fn default() -> Self {
383 Self::new()
384 }
385}
386
387impl QueryClockGuard {
388 pub fn new() -> Self {
390 Self::within(None)
391 }
392
393 pub fn within(transaction: Option<TransactionClock>) -> Self {
396 Self::install(ClockReading::wall_clock(), transaction.map(|t| t.0))
397 }
398
399 fn install(reading: ClockReading, transaction: Option<ClockReading>) -> Self {
402 let previous = PINS.with(|c| {
403 c.replace(Pins {
404 statement: Some(reading),
405 transaction: Some(transaction.unwrap_or(reading)),
406 })
407 });
408 Self { previous }
409 }
410}
411
412#[cfg(test)]
413impl QueryClockGuard {
414 pub fn pinned_at(utc: NaiveDateTime, local_offset: i32) -> Self {
417 Self::install(ClockReading::pinned(utc, local_offset), None)
418 }
419
420 pub fn pinned_in_transaction(statement: NaiveDateTime, transaction: NaiveDateTime) -> Self {
423 Self::install(
424 ClockReading::pinned(statement, 0),
425 Some(ClockReading::pinned(transaction, 0)),
426 )
427 }
428}
429
430impl Drop for QueryClockGuard {
431 fn drop(&mut self) {
432 PINS.with(|c| c.set(self.previous));
433 }
434}
435
436fn unpinned_reading() -> ClockReading {
442 ClockReading::wall_clock()
443}
444
445fn pinned() -> ClockReading {
446 PINS.with(|c| c.get())
447 .statement
448 .unwrap_or_else(unpinned_reading)
449}
450
451fn clock_reading(mode: ClockMode) -> ClockReading {
456 match mode {
457 ClockMode::Transaction => PINS
458 .with(|c| c.get())
459 .transaction
460 .unwrap_or_else(unpinned_reading),
461 ClockMode::Statement => pinned(),
462 ClockMode::Realtime => ClockReading::wall_clock(),
463 }
464}
465
466pub(super) fn now_value(kind: ClockKind) -> Temporal {
470 let reading = pinned();
471 clock_temporal(kind, reading.utc, default_zone(kind, reading))
472 .expect("the host clock is representable")
473}
474
475#[cfg(test)]
476pub(super) fn now_date() -> Temporal {
477 now_value(ClockKind::Date)
478}
479
480#[cfg(test)]
481pub(super) fn now_local_dt() -> Temporal {
482 now_value(ClockKind::LocalDateTime)
483}
484
485#[cfg(test)]
486pub(super) fn now_dt() -> Temporal {
487 now_value(ClockKind::DateTime)
488}
489
490pub fn now_epoch_millis() -> i64 {
494 pinned().utc.and_utc().timestamp_millis()
495}
496
497#[cfg(test)]
498pub(super) fn now_local_time() -> Temporal {
499 now_value(ClockKind::LocalTime)
500}
501
502#[cfg(test)]
503pub(super) fn now_time() -> Temporal {
504 now_value(ClockKind::Time)
505}
506
507pub fn now_utc_dt() -> NaiveDateTime {
511 pinned().utc
512}