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, for an
7//! explicit transaction, one instant at `BEGIN` ([`TransactionClock`]) that
8//! every statement of the transaction carries. [`ClockMode::Transaction`]
9//! reads the transaction instant, [`ClockMode::Statement`] the statement's
10//! own, and [`ClockMode::Realtime`] the wall clock at each call. An
11//! autocommit statement is its own transaction, so both read the one pin.
12
13use 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/// One of the five temporal kinds whose constructor has clock-access
23/// spellings. The typed vocabulary behind [`clock_access`], so no reader
24/// keeps a second list of base names.
25#[derive(Debug, Clone, Copy, PartialEq, Eq)]
26pub enum ClockKind {
27    Date,
28    Time,
29    LocalTime,
30    DateTime,
31    LocalDateTime,
32}
33
34impl ClockKind {
35    /// The canonical kind table: every variant with its constructor
36    /// spelling. [`ClockKind::name`] and [`ClockKind::from_name`] both read
37    /// it, so a variant cannot render without parsing.
38    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    /// The constructor spelling of the kind (`localdatetime`, …).
47    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    /// The inverse of [`ClockKind::name`].
56    pub(super) fn from_name(name: &str) -> Option<Self> {
57        super::lookup(Self::TABLE, name)
58    }
59
60    /// [`ClockKind::from_name`] over any ASCII casing, without allocating.
61    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    /// Whether the kind carries a calendar date. The capability model the
69    /// field policy (`accepts` and its guards) and the component readers both
70    /// read, so a kind's parts are stated once.
71    pub(super) fn has_date(self) -> bool {
72        matches!(
73            self,
74            ClockKind::Date | ClockKind::LocalDateTime | ClockKind::DateTime
75        )
76    }
77
78    /// Whether the kind carries a time of day.
79    pub(super) fn has_time(self) -> bool {
80        !matches!(self, ClockKind::Date)
81    }
82
83    /// Whether the kind carries a UTC offset / time zone.
84    pub(super) fn has_zone(self) -> bool {
85        matches!(self, ClockKind::Time | ClockKind::DateTime)
86    }
87
88    /// Whether the kind has an epoch-map form. Only `datetime` does: the
89    /// reference engine rejects `epochSeconds`/`epochMillis` on every other
90    /// constructor, so an epoch map of a zoneless kind is a typed rejection
91    /// rather than a silently different reading.
92    pub(super) fn has_epoch(self) -> bool {
93        matches!(self, ClockKind::DateTime)
94    }
95
96    /// Whether the kind carries both halves (the `datetime` source field).
97    pub(super) fn has_date_and_time(self) -> bool {
98        self.has_date() && self.has_time()
99    }
100
101    /// Every clock kind, in table order — the enumeration the tests iterate
102    /// over the kind vocabulary; a kind's spelling always comes from
103    /// [`ClockKind::name`], never a second copy.
104    #[cfg(test)]
105    pub(super) fn all() -> impl Iterator<Item = ClockKind> {
106        Self::TABLE.iter().map(|(_, kind)| *kind)
107    }
108}
109
110/// The clock a temporal accessor reads.
111#[derive(Debug, Clone, Copy, PartialEq, Eq)]
112pub enum ClockMode {
113    Transaction,
114    Statement,
115    Realtime,
116}
117
118impl ClockMode {
119    /// The canonical mode table: every variant with its `.suffix` spelling.
120    /// [`ClockMode::suffix`] and the private parser both read it.
121    const TABLE: &'static [(&'static str, ClockMode)] = &[
122        ("transaction", ClockMode::Transaction),
123        ("statement", ClockMode::Statement),
124        ("realtime", ClockMode::Realtime),
125    ];
126
127    /// The `.suffix` spelling of the mode — parse and render share it.
128    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
137/// Every clock-access spelling with its typed meaning — the one registry the
138/// parser ([`clock_access`]), the advertised catalog ([`clock_spellings`])
139/// and the executor's builtin table all read. A row cannot carry a kind and
140/// mode its spelling does not name.
141pub 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
195/// The kind and mode a `<kind>.<mode>` spelling names, or `None` for every
196/// other name. Case insensitive, like every Cypher function name.
197pub 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
205/// The `<kind>.<mode>` spelling of a clock accessor, for messages — the
206/// inverse of [`clock_access`].
207pub fn clock_spelling(kind: ClockKind, mode: ClockMode) -> String {
208    format!("{}.{}", kind.name(), mode.suffix())
209}
210
211/// The typed spelling registry: every `<kind>.<mode>` spelling with the kind
212/// and mode it names — the row source for the executor's builtin table, so
213/// the table never re-parses a spelling to recover its own payload.
214pub fn clock_spelling_rows() -> impl Iterator<Item = (&'static str, ClockKind, ClockMode)> {
215    CLOCK_SPELLINGS.iter().copied()
216}
217
218/// Every `<kind>.<mode>` spelling — the advertised set.
219pub fn clock_spellings() -> impl Iterator<Item = &'static str> {
220    clock_spelling_rows().map(|(spelling, _, _)| spelling)
221}
222
223/// One clock observation: the instant as a UTC wall clock and the host's
224/// local offset at that instant. The local wall clock is derived
225/// ([`clock_temporal`]), never stored, so the two readings cannot name
226/// different instants.
227#[derive(Debug, Clone, Copy, PartialEq, Eq)]
228struct ClockReading {
229    utc: NaiveDateTime,
230    local_offset: i32,
231}
232
233impl ClockReading {
234    /// The wall-clock observation: sample the instant once, then read the
235    /// host's offset at that same instant.
236    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    /// Test seam: the observation of an explicit instant at an explicit host
249    /// offset, so a test can pin a non-UTC host instead of hiding the offset
250    /// behind a zero.
251    #[cfg(test)]
252    fn pinned(utc: NaiveDateTime, local_offset: i32) -> Self {
253        Self { utc, local_offset }
254    }
255}
256
257/// The zone a clock kind reads in when the caller names none: the host's
258/// local reading for the zoneless kinds, UTC (`Z`) for the zoned `datetime`
259/// — the engine's documented default zone.
260fn 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
272/// One zoned `DateTime` from a UTC instant and the zone it is read in — the
273/// one zoned-construction seam.
274pub(super) fn zoned(utc: NaiveDateTime, resolved: ResolvedZone) -> Temporal {
275    Temporal::DateTime {
276        utc,
277        offset: resolved.offset,
278        zone: resolved.zone,
279    }
280}
281
282/// The temporal value `kind` reads at the UTC instant `utc` in `resolved` —
283/// the one construction seam every clock reading goes through (the accessor
284/// argument, the clock-reading map, the epoch map, and the `now_*` readers).
285pub(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
303/// The clock-reading map form: the current instant (statement clock) read
304/// in the map's `timezone`. A present but non-string timezone is
305/// [`offset_from_map`]'s typed rejection, never a silent UTC reading.
306pub(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
312/// The clock-access form (`date.transaction('Europe/Paris')`, …): its one
313/// argument is a timezone, never a value, so it resolves through the zone
314/// table at the accessor's own instant. Arity is the dispatcher's contract;
315/// the one argument here is either a null, a timezone, or the call's own
316/// failure — the ProcedureCallFailed class, 42001.
317pub 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        // Live reports the non-string timezone argument as the call's own
335        // failure — ProcedureCallFailed under 42001 (probed 2026-11-20 on
336        // 2026.10.1: date.realtime(123)).
337        Some(_) => Err(Error::procedure_call(format!(
338            "Invalid call signature: {}() takes a timezone STRING",
339            clock_spelling(kind, mode)
340        ))),
341    }
342}
343
344/// The instants the running statement reads: its own pin, and the pin of the
345/// transaction it belongs to — the explicit transaction's begin instant, or
346/// (autocommit) the statement's own, settled once at guard installation.
347/// The two travel as one value — both present inside a guard, both absent
348/// outside any — so "one pinned, the other not" is unrepresentable. One cell,
349/// so the pair is installed and restored in lockstep.
350#[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/// The instant an explicit transaction began at, captured once at `BEGIN`
361/// and handed to every statement run in it ([`QueryClockGuard::within`]),
362/// so `<kind>.transaction()` reads one instant for the whole transaction
363/// while `<kind>.statement()` still moves with each statement.
364#[derive(Debug, Clone, Copy, PartialEq, Eq)]
365pub struct TransactionClock(ClockReading);
366
367impl TransactionClock {
368    /// Samples the wall clock as the transaction's instant.
369    pub fn begin() -> Self {
370        Self(ClockReading::wall_clock())
371    }
372}
373
374/// Pins `date()` / `datetime()` / `time()` to one instant for a statement,
375/// restoring the previous pins when it drops.
376pub 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    /// An autocommit statement: its own instant is also its transaction's.
388    pub fn new() -> Self {
389        Self::within(None)
390    }
391
392    /// A statement of `transaction` (`None` = autocommit): a fresh statement
393    /// instant, and the transaction's instant when it has one.
394    pub fn within(transaction: Option<TransactionClock>) -> Self {
395        Self::install(ClockReading::wall_clock(), transaction.map(|t| t.0))
396    }
397
398    /// Installs the pins for the guard's lifetime, keeping the previous ones
399    /// so a nested guard restores the outer statement's instants.
400    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    /// Test seam: pins the statement clock to `utc` with host local offset
414    /// `local_offset`.
415    pub fn pinned_at(utc: NaiveDateTime, local_offset: i32) -> Self {
416        Self::install(ClockReading::pinned(utc, local_offset), None)
417    }
418
419    /// Test seam: a statement pinned at `statement` inside a transaction
420    /// that began at `transaction`, both at host local offset 0.
421    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
435/// The reading an unpinned clock read uses: the host's wall clock, sampled
436/// at the call. Every statement entry installs a [`QueryClockGuard`] (the
437/// executor's statement runner), so this is reachable only from a direct
438/// core embedder that calls a constructor outside a statement — a named,
439/// documented contract rather than a silent fallback inside the pin.
440fn unpinned_reading() -> ClockReading {
441    ClockReading::wall_clock()
442}
443
444/// The one accessor over the installed pins: `select` names the statement's
445/// or the transaction's instant; outside any guard it is the documented
446/// [`unpinned_reading`].
447fn 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
455/// The observation `mode` names: the transaction's instant for
456/// [`ClockMode::Transaction`] (the statement's own pin outside an explicit
457/// transaction), the pinned statement instant for [`ClockMode::Statement`],
458/// the live wall clock for [`ClockMode::Realtime`].
459fn 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
467/// The pinned clock's value of a kind — the production paths' shared body
468/// (`construct` reads it directly; the per-kind `now_*` readers below are
469/// test-only façades over it).
470pub(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
491/// The pinned statement instant as milliseconds since 1970-01-01T00:00:00Z,
492/// the same instant `now_dt()` reads (so `timestamp()` equals
493/// `datetime().epochMillis` for the whole statement).
494pub 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
508/// The pinned statement instant's UTC wall clock — the `now_*` family's
509/// naive-UTC member, for callers that resolve a zone at "now" without
510/// constructing a `Temporal` (the `time` truncate boundary).
511pub fn now_utc_dt() -> NaiveDateTime {
512    pinned().utc
513}