Skip to main content

relate_core/temporal/
clock.rs

1//! The clock-reading temporal constructors: the `.transaction` /
2//! `.statement` / `.realtime` spellings, their timezone argument, the
3//! `{timezone: …}` map reading, and the per-statement clock pin every
4//! `date()` / `time()` / `now()` reading shares.
5//!
6//! The engine pins one instant per statement ([`QueryClockGuard`]) and keeps
7//! no longer-lived transaction clock, so [`ClockMode::Transaction`] reads
8//! that same pinned instant while [`ClockMode::Realtime`] reads the wall
9//! clock at each call.
10
11use 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/// One of the five temporal kinds whose constructor has clock-access
21/// spellings. The typed vocabulary behind [`clock_access`], so no reader
22/// keeps a second list of base names.
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub enum ClockKind {
25    Date,
26    Time,
27    LocalTime,
28    DateTime,
29    LocalDateTime,
30}
31
32impl ClockKind {
33    /// The canonical kind table: every variant with its constructor
34    /// spelling. [`ClockKind::name`] and [`ClockKind::from_name`] both read
35    /// it, so a variant cannot render without parsing.
36    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    /// The constructor spelling of the kind (`localdatetime`, …).
45    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    /// The inverse of [`ClockKind::name`].
54    pub(super) fn from_name(name: &str) -> Option<Self> {
55        super::lookup(Self::TABLE, name)
56    }
57
58    /// Whether the kind carries a calendar date. The capability model the
59    /// field policy (`accepts` and its guards) and the component readers both
60    /// read, so a kind's parts are stated once.
61    pub(super) fn has_date(self) -> bool {
62        matches!(
63            self,
64            ClockKind::Date | ClockKind::LocalDateTime | ClockKind::DateTime
65        )
66    }
67
68    /// Whether the kind carries a time of day.
69    pub(super) fn has_time(self) -> bool {
70        !matches!(self, ClockKind::Date)
71    }
72
73    /// Whether the kind carries a UTC offset / time zone.
74    pub(super) fn has_zone(self) -> bool {
75        matches!(self, ClockKind::Time | ClockKind::DateTime)
76    }
77
78    /// Whether the kind has an epoch-map form. Only `datetime` does: the
79    /// reference engine rejects `epochSeconds`/`epochMillis` on every other
80    /// constructor, so an epoch map of a zoneless kind is a typed rejection
81    /// rather than a silently different reading.
82    pub(super) fn has_epoch(self) -> bool {
83        matches!(self, ClockKind::DateTime)
84    }
85
86    /// Whether the kind carries both halves (the `datetime` source field).
87    pub(super) fn has_date_and_time(self) -> bool {
88        self.has_date() && self.has_time()
89    }
90}
91
92/// The clock a temporal accessor reads.
93#[derive(Debug, Clone, Copy, PartialEq, Eq)]
94pub enum ClockMode {
95    Transaction,
96    Statement,
97    Realtime,
98}
99
100impl ClockMode {
101    /// The canonical mode table: every variant with its `.suffix` spelling.
102    /// [`ClockMode::suffix`] and the private parser both read it.
103    const TABLE: &'static [(&'static str, ClockMode)] = &[
104        ("transaction", ClockMode::Transaction),
105        ("statement", ClockMode::Statement),
106        ("realtime", ClockMode::Realtime),
107    ];
108
109    /// The `.suffix` spelling of the mode — parse and render share it.
110    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
119/// Every clock-access spelling with its typed meaning — the one registry the
120/// parser ([`clock_access`]), the advertised catalog ([`clock_spellings`])
121/// and the executor's builtin table all read. A row cannot carry a kind and
122/// mode its spelling does not name.
123pub 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
177/// The kind and mode a `<kind>.<mode>` spelling names, or `None` for every
178/// other name. Case insensitive, like every Cypher function name.
179pub 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
187/// The `<kind>.<mode>` spelling of a clock accessor, for messages — the
188/// inverse of [`clock_access`].
189pub fn clock_spelling(kind: ClockKind, mode: ClockMode) -> String {
190    format!("{}.{}", kind.name(), mode.suffix())
191}
192
193/// The typed spelling registry: every `<kind>.<mode>` spelling with the kind
194/// and mode it names — the row source for the executor's builtin table, so
195/// the table never re-parses a spelling to recover its own payload.
196pub fn clock_spelling_rows() -> impl Iterator<Item = (&'static str, ClockKind, ClockMode)> {
197    CLOCK_SPELLINGS.iter().copied()
198}
199
200/// Every `<kind>.<mode>` spelling — the advertised set.
201pub fn clock_spellings() -> impl Iterator<Item = &'static str> {
202    clock_spelling_rows().map(|(spelling, _, _)| spelling)
203}
204
205/// One clock observation: the instant as a UTC wall clock and the host's
206/// local offset at that instant. The local wall clock is derived
207/// ([`clock_temporal`]), never stored, so the two readings cannot name
208/// different instants.
209#[derive(Debug, Clone, Copy, PartialEq, Eq)]
210struct ClockReading {
211    utc: NaiveDateTime,
212    local_offset: i32,
213}
214
215impl ClockReading {
216    /// The wall-clock observation: sample the instant once, then read the
217    /// host's offset at that same instant.
218    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    /// Test seam: the observation of an explicit instant at an explicit host
231    /// offset, so a test can pin a non-UTC host instead of hiding the offset
232    /// behind a zero.
233    #[cfg(test)]
234    fn pinned(utc: NaiveDateTime, local_offset: i32) -> Self {
235        Self { utc, local_offset }
236    }
237}
238
239/// The zone a clock kind reads in when the caller names none: the host's
240/// local reading for the zoneless kinds, UTC (`Z`) for the zoned `datetime`
241/// — the engine's documented default zone.
242fn 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
254/// One zoned `DateTime` from a UTC instant and the zone it is read in — the
255/// one zoned-construction seam.
256pub(super) fn zoned(utc: NaiveDateTime, resolved: ResolvedZone) -> Temporal {
257    Temporal::DateTime {
258        utc,
259        offset: resolved.offset,
260        zone: resolved.zone,
261    }
262}
263
264/// The temporal value `kind` reads at the UTC instant `utc` in `resolved` —
265/// the one construction seam every clock reading goes through (the accessor
266/// argument, the clock-reading map, the epoch map, and the `now_*` readers).
267pub(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
285/// The clock-reading map form: the current instant (transaction clock) read
286/// in the map's `timezone`. A present but non-string timezone is
287/// [`offset_from_map`]'s typed rejection, never a silent UTC reading.
288pub(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
294/// The clock-access form (`date.transaction('Europe/Paris')`, …): its one
295/// argument is a timezone, never a value, so it resolves through the zone
296/// table at the accessor's own instant. Arity is the dispatcher's contract;
297/// the one argument here is either a null, a timezone, or the invalid call
298/// signature (syntax class).
299pub 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
328/// Pins `date()` / `datetime()` / `time()` to one instant for a statement,
329/// restoring the previous pin when it drops.
330pub 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    /// Installs `reading` for the guard's lifetime, keeping the previous pin
346    /// so a nested guard restores the outer statement's instant.
347    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    /// Test seam: pins the statement clock to `utc` with host local offset
356    /// `local_offset`.
357    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
368/// The reading an unpinned clock read uses: the host's wall clock, sampled
369/// at the call. Every statement entry installs a [`QueryClockGuard`] (the
370/// executor's statement runner), so this is reachable only from a direct
371/// core embedder that calls a constructor outside a statement — a named,
372/// documented contract rather than a silent fallback inside the pin.
373fn 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
381/// The observation `mode` names: the pinned statement instant for
382/// [`ClockMode::Transaction`] and [`ClockMode::Statement`], the live wall
383/// clock for [`ClockMode::Realtime`].
384fn clock_reading(mode: ClockMode) -> ClockReading {
385    match mode {
386        ClockMode::Transaction | ClockMode::Statement => pinned(),
387        ClockMode::Realtime => ClockReading::wall_clock(),
388    }
389}
390
391/// The pinned clock's value of a kind — the production paths' shared body
392/// (`construct` reads it directly; the per-kind `now_*` readers below are
393/// test-only façades over it).
394pub(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
415/// The pinned statement instant as milliseconds since 1970-01-01T00:00:00Z,
416/// the same instant `now_dt()` reads (so `timestamp()` equals
417/// `datetime().epochMillis` for the whole statement).
418pub 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
432/// The pinned statement instant's UTC wall clock — the `now_*` family's
433/// naive-UTC member, for callers that resolve a zone at "now" without
434/// constructing a `Temporal` (the `time` truncate boundary).
435pub fn now_utc_dt() -> NaiveDateTime {
436    pinned().utc
437}