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)]
351struct Pins {
352 statement: ClockReading,
353 transaction: ClockReading,
354}
355
356thread_local! {
357 static PINS: std::cell::Cell<Option<Pins>> = const { std::cell::Cell::new(None) };
358}
359
360#[derive(Debug, Clone, Copy, PartialEq, Eq)]
365pub struct TransactionClock(ClockReading);
366
367impl TransactionClock {
368 pub fn begin() -> Self {
370 Self(ClockReading::wall_clock())
371 }
372}
373
374pub struct QueryClockGuard {
377 previous: Option<Pins>,
378}
379
380impl Default for QueryClockGuard {
381 fn default() -> Self {
382 Self::new()
383 }
384}
385
386impl QueryClockGuard {
387 pub fn new() -> Self {
389 Self::within(None)
390 }
391
392 pub fn within(transaction: Option<TransactionClock>) -> Self {
395 Self::install(ClockReading::wall_clock(), transaction.map(|t| t.0))
396 }
397
398 fn install(reading: ClockReading, transaction: Option<ClockReading>) -> Self {
401 let previous = PINS.with(|c| {
402 c.replace(Some(Pins {
403 statement: reading,
404 transaction: transaction.unwrap_or(reading),
405 }))
406 });
407 Self { previous }
408 }
409}
410
411#[cfg(test)]
412impl QueryClockGuard {
413 pub fn pinned_at(utc: NaiveDateTime, local_offset: i32) -> Self {
416 Self::install(ClockReading::pinned(utc, local_offset), None)
417 }
418
419 pub fn pinned_in_transaction(statement: NaiveDateTime, transaction: NaiveDateTime) -> Self {
422 Self::install(
423 ClockReading::pinned(statement, 0),
424 Some(ClockReading::pinned(transaction, 0)),
425 )
426 }
427}
428
429impl Drop for QueryClockGuard {
430 fn drop(&mut self) {
431 PINS.with(|c| c.set(self.previous));
432 }
433}
434
435fn unpinned_reading() -> ClockReading {
441 ClockReading::wall_clock()
442}
443
444fn pinned_with(select: impl FnOnce(Pins) -> ClockReading) -> ClockReading {
448 PINS.with(|c| c.get()).map_or_else(unpinned_reading, select)
449}
450
451fn pinned() -> ClockReading {
452 pinned_with(|pins| pins.statement)
453}
454
455fn clock_reading(mode: ClockMode) -> ClockReading {
460 match mode {
461 ClockMode::Transaction => pinned_with(|pins| pins.transaction),
462 ClockMode::Statement => pinned(),
463 ClockMode::Realtime => ClockReading::wall_clock(),
464 }
465}
466
467pub(super) fn now_value(kind: ClockKind) -> Temporal {
471 let reading = pinned();
472 clock_temporal(kind, reading.utc, default_zone(kind, reading))
473 .expect("the host clock is representable")
474}
475
476#[cfg(test)]
477pub(super) fn now_date() -> Temporal {
478 now_value(ClockKind::Date)
479}
480
481#[cfg(test)]
482pub(super) fn now_local_dt() -> Temporal {
483 now_value(ClockKind::LocalDateTime)
484}
485
486#[cfg(test)]
487pub(super) fn now_dt() -> Temporal {
488 now_value(ClockKind::DateTime)
489}
490
491pub fn now_epoch_millis() -> i64 {
495 pinned().utc.and_utc().timestamp_millis()
496}
497
498#[cfg(test)]
499pub(super) fn now_local_time() -> Temporal {
500 now_value(ClockKind::LocalTime)
501}
502
503#[cfg(test)]
504pub(super) fn now_time() -> Temporal {
505 now_value(ClockKind::Time)
506}
507
508pub fn now_utc_dt() -> NaiveDateTime {
512 pinned().utc
513}