Skip to main content

relate_core/temporal/
mod.rs

1//! OpenCypher temporal values (ADR-0021).
2
3use std::fmt;
4
5use chrono::{NaiveDate, NaiveDateTime, NaiveTime, Timelike, Weekday};
6
7use crate::{Error, Value};
8
9mod arith;
10mod between;
11mod clock;
12mod component;
13mod construct;
14mod duration;
15mod duration_pattern;
16mod duration_tokens;
17mod exact;
18mod field;
19mod field_rules;
20mod format;
21mod parse;
22mod pattern;
23mod relations;
24#[cfg(test)]
25mod test_support;
26#[cfg(test)]
27mod tests;
28#[cfg(test)]
29mod tests_arith;
30#[cfg(test)]
31mod tests_between;
32#[cfg(test)]
33mod tests_civil_zoned;
34#[cfg(test)]
35mod tests_clock;
36#[cfg(test)]
37mod tests_construct;
38#[cfg(test)]
39mod tests_duration;
40#[cfg(test)]
41mod tests_fields;
42#[cfg(test)]
43mod tests_pattern;
44#[cfg(test)]
45mod tests_ranges;
46#[cfg(test)]
47mod tests_zone;
48mod truncate;
49mod zone;
50
51use format::format_zone_offset;
52
53pub use arith::{
54    add_duration, civil_epoch_days, civil_epoch_seconds, civil_from_days, negate_duration,
55    scale_duration, sub_duration,
56};
57pub use between::{duration_between, duration_between_unit, BetweenUnit};
58pub use clock::{
59    clock_access, clock_spelling, clock_spelling_rows, clock_spellings, construct_clock,
60    now_epoch_millis, now_utc_dt, ClockKind, ClockMode, QueryClockGuard, TransactionClock,
61};
62pub use construct::{
63    accepts_pattern, clock_kind, construct_date, construct_datetime, construct_duration,
64    construct_localdatetime, construct_localtime, construct_named, construct_time, is_constructor,
65    samples_clock,
66};
67pub use format::format_pattern;
68pub use parse::{
69    datetime_from_epoch, datetime_from_epoch_millis, padded_iso_date_value, parse_iso,
70    parse_pattern,
71};
72pub use truncate::{truncate, truncate_now};
73pub use zone::{zone_offset_at, zone_offset_at_utc, zone_region, ZoneError, MAX_OFFSET_SECONDS};
74
75#[derive(Debug, Clone, PartialEq, Eq)]
76pub enum Temporal {
77    Date(NaiveDate),
78    /// Out-of-range proleptic date (TCK ±999999999).
79    CivilDate {
80        year: i64,
81        month: u32,
82        day: u32,
83    },
84    LocalTime(NaiveTime),
85    Time {
86        time: NaiveTime,
87        offset: i32,
88    },
89    LocalDateTime(NaiveDateTime),
90    CivilDateTime {
91        year: i64,
92        month: u32,
93        day: u32,
94        time: NaiveTime,
95    },
96    DateTime {
97        utc: NaiveDateTime,
98        offset: i32,
99        zone: Option<String>,
100    },
101    /// Out-of-range zoned datetime (TCK ±999999999): the wall clock as
102    /// proleptic civil fields — [`CivilZonedFields`], [`Temporal::CivilDateTime`]'s
103    /// payload plus the offset and optional zone spelling
104    /// [`Temporal::DateTime`] carries. Only an offset or `Z` zone spec
105    /// constructs one (ADR-0683); the instant is the wall clock minus the
106    /// offset, computed over the wide day arithmetic and never a chrono
107    /// conversion. The payload is boxed: unboxed it is 56 bytes against
108    /// the chrono `DateTime` variant's 48, and `Temporal` growing past 48
109    /// grows every row's `Value` with it — the far-year form is rare
110    /// enough to pay one allocation instead.
111    CivilZoned(Box<CivilZonedFields>),
112    Duration {
113        months: i64,
114        days: i64,
115        nanos: i128,
116    },
117}
118
119/// The boxed payload of [`Temporal::CivilZoned`] (ADR-0683): the wall
120/// clock's proleptic civil fields plus the offset and optional zone
121/// spelling — the fields a `parse_zoned_dt` far-year fallback fills and
122/// every zoned relation reads.
123#[derive(Debug, Clone, PartialEq, Eq)]
124pub struct CivilZonedFields {
125    /// The wall clock's proleptic year, ±999999999.
126    pub year: i64,
127    pub month: u32,
128    pub day: u32,
129    pub time: NaiveTime,
130    pub offset: i32,
131    pub zone: Option<String>,
132}
133
134impl CivilZonedFields {
135    /// The UTC instant in epoch nanoseconds — the wall clock minus the
136    /// offset over the wide day arithmetic (the one civil derivation the
137    /// relations' zoned view and the executor's group/index key read:
138    /// `relations::ZonedView`). Never a chrono conversion.
139    pub fn epoch_nanos(&self) -> i128 {
140        civil_epoch_days(self.year, self.month, self.day) * NANOS_PER_DAY
141            + i128::from(time_to_nanos(self.time))
142            - i128::from(self.offset) * 1_000_000_000
143    }
144}
145
146/// The six temporal type kinds, one per Cypher type name — the variant
147/// grouping the type-name spelling and the ORDER BY sub-ranks both key
148/// off, so it exists in one place. Declared in the ORDER BY rank order:
149/// ZONED DATETIME < LOCAL DATETIME < DATE < ZONED TIME < LOCAL TIME <
150/// DURATION (live Neo4j 2026.10.1, value-independent), so a kind's
151/// discriminant is that rank's offset.
152#[derive(Debug, Clone, Copy, PartialEq, Eq)]
153pub enum TemporalKind {
154    DateTime,
155    LocalDateTime,
156    Date,
157    Time,
158    LocalTime,
159    Duration,
160}
161
162impl TemporalKind {
163    /// The kind's lowercase wire name — the `Temporal::kind_name`
164    /// spelling, owned by the kind so the variant partition has one
165    /// owner.
166    pub(crate) fn name(self) -> &'static str {
167        match self {
168            TemporalKind::DateTime => "datetime",
169            TemporalKind::LocalDateTime => "localdatetime",
170            TemporalKind::Date => "date",
171            TemporalKind::Time => "time",
172            TemporalKind::LocalTime => "localtime",
173            TemporalKind::Duration => "duration",
174        }
175    }
176}
177
178impl Temporal {
179    /// This value's type kind — the one spelling of the variant grouping
180    /// (the civil out-of-range forms share their kind's name).
181    pub fn kind(&self) -> TemporalKind {
182        match self {
183            Temporal::DateTime { .. } | Temporal::CivilZoned(_) => TemporalKind::DateTime,
184            Temporal::LocalDateTime(_) | Temporal::CivilDateTime { .. } => {
185                TemporalKind::LocalDateTime
186            }
187            Temporal::Date(_) | Temporal::CivilDate { .. } => TemporalKind::Date,
188            Temporal::Time { .. } => TemporalKind::Time,
189            Temporal::LocalTime(_) => TemporalKind::LocalTime,
190            Temporal::Duration { .. } => TemporalKind::Duration,
191        }
192    }
193}
194
195/// The zoned facts of a `DateTime` in either representation (ADR-0683) —
196/// the shape [`Temporal::zoned_parts`] publishes and the one the temporal
197/// relations and the Bolt encoder read: the wide UTC instant in epoch
198/// nanoseconds, the offset, and the already-classified IANA region (`None`
199/// for a plain offset spelling). Named fields, so a consumer never has to
200/// know a positional order to read the three facts.
201#[derive(Debug, Clone, Copy, PartialEq, Eq)]
202pub struct ZonedParts<'a> {
203    /// The UTC instant in epoch nanoseconds — the value the ordering
204    /// relations rank by and the executor's group/index key keys on. Wide
205    /// `i128` throughout (never `timestamp_nanos`, an `i64` that
206    /// overflows far inside chrono's range).
207    pub instant: i128,
208    pub offset: i32,
209    /// The IANA region name, `None` for a plain offset spelling.
210    pub region: Option<&'a str>,
211}
212
213/// The zone half of a `DateTime`'s equality identity (TCK TemporalCompare):
214/// an IANA zone is identified by its name — so the two halves of a DST
215/// fall-back overlap stay equal — and every other spelling (`Z`, `+00:00`,
216/// `UTC`, …) by the UTC offset it denotes, so `Z` equals `+00:00` while a
217/// named zone never equals the offset it happens to denote.
218#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
219pub enum ZoneId {
220    Named(String),
221    Offset(i32),
222}
223
224impl ZoneId {
225    /// The identity of a `DateTime`'s `zone` at `offset`.
226    pub fn of(zone: Option<&str>, offset: i32) -> ZoneId {
227        Self::of_region(zone_region(zone), offset)
228    }
229
230    /// The identity of an **already-classified** region at `offset` — the
231    /// shape the zoned view yields (`relations::zoned_parts`), so a
232    /// consumer holding the resolved region never re-runs the spelling
233    /// classification. Crate-internal: [`ZoneId::of`] is the one public
234    /// entry, so a caller holding a raw zone spelling cannot reach this
235    /// form and mistake a spelling for a region.
236    pub(crate) fn of_region(region: Option<&str>, offset: i32) -> ZoneId {
237        match region {
238            Some(name) => ZoneId::Named(name.to_string()),
239            None => ZoneId::Offset(offset),
240        }
241    }
242}
243
244impl Temporal {
245    /// The one place a duration's stored `(months, days, nanos)` triple is
246    /// assembled, and the one place its representability bound lives: the
247    /// sub-day part must fit Neo4j's `i64` seconds field (inclusive of
248    /// `2^63`, the `f64` image of `i64::MAX` that the scaling path still
249    /// casts back), and the duration's average length in seconds
250    /// (`months * AVG_SECONDS_PER_MONTH + days * 86400 + seconds`) must fit
251    /// an `i64` (`DurationValue.assertNoOverflow`). Every producer — the ISO
252    /// numeral parser, the pattern parser, the map constructor, scaling and
253    /// duration addition — builds through this seam, so one value is
254    /// accepted or rejected regardless of how it was spelled; a value past
255    /// the bound is Neo4j's interval-field overflow, never a silently larger
256    /// duration. Neo4j's constructor enforces the same bound (verified
257    /// against Neo4j 5: `duration({months: 4000000000000})` errors, while the
258    /// same value via `* 1.0` errors identically).
259    pub(crate) fn duration_checked(months: i64, days: i64, nanos: i128) -> Result<Temporal, Error> {
260        let (seconds, _) = split_seconds(nanos);
261        if !(-MAX_DURATION_SECONDS..=MAX_DURATION_SECONDS).contains(&seconds) {
262            return Err(range_err());
263        }
264        // `seconds` can equal ±2^63, one past `i64`; the average-length sum
265        // stays in i128 and the final `i64::try_from` rejects an out-of-range
266        // total, so the clamp only keeps the sum's own arithmetic in range.
267        let seconds = seconds.clamp(i128::from(i64::MIN), i128::from(i64::MAX));
268        let average = i128::from(months) * AVG_SECONDS_PER_MONTH
269            + i128::from(days) * (NANOS_PER_DAY / NANOS_PER_SECOND)
270            + seconds;
271        i64::try_from(average).map_err(|_| range_err())?;
272        Ok(Temporal::Duration {
273            months,
274            days,
275            nanos,
276        })
277    }
278
279    /// [`Temporal::duration_checked`] with the strict stored-model bound for
280    /// producers whose arithmetic is exact (the ISO and pattern parsers, the
281    /// all-integer map constructor, negation and addition). Neo4j's duration
282    /// stores its sub-day part as an `i64` seconds field, so exactly `2^63`
283    /// seconds is not representable (`duration('PT9223372036854775808S')`
284    /// overflows); only the `f64` scaling path produces that image by
285    /// rounding `i64::MAX` and casts it back, which is why the shared seam
286    /// accepts it.
287    pub(crate) fn duration_checked_exact(
288        months: i64,
289        days: i64,
290        nanos: i128,
291    ) -> Result<Temporal, Error> {
292        if nanos.div_euclid(NANOS_PER_SECOND) > i128::from(i64::MAX) {
293            return Err(range_err());
294        }
295        Self::duration_checked(months, days, nanos)
296    }
297
298    pub fn kind_name(&self) -> &'static str {
299        self.kind().name()
300    }
301
302    /// Whether the value carries a calendar date — the one statement of the
303    /// capability partition, beside the type. The field policy
304    /// (`field_rules::check_sources`), the truncation granularity rule and
305    /// the part readers all read it, so no consumer keeps its own variant
306    /// list.
307    pub fn has_date(&self) -> bool {
308        matches!(
309            self.kind(),
310            TemporalKind::Date | TemporalKind::LocalDateTime | TemporalKind::DateTime
311        )
312    }
313
314    /// Whether the value carries a time of day (see [`Temporal::has_date`]).
315    pub fn has_time(&self) -> bool {
316        matches!(
317            self.kind(),
318            TemporalKind::LocalTime
319                | TemporalKind::Time
320                | TemporalKind::LocalDateTime
321                | TemporalKind::DateTime
322        )
323    }
324
325    /// Whether the value carries both halves (the `datetime` source field).
326    pub fn has_date_and_time(&self) -> bool {
327        self.has_date() && self.has_time()
328    }
329
330    pub fn iso_string(&self) -> String {
331        format::render(self, false)
332    }
333
334    /// The full-precision ISO rendering: [`Temporal::iso_string`] with
335    /// the time-of-day's seconds always present. The value layer's
336    /// temporal rendering policy for every string-producing surface —
337    /// `toString` (top-level, nested in a map or accepted list, or
338    /// through `toStringOrNull`) and the interpolated-string scalar
339    /// path — one rendering for one value, however it was built or
340    /// wherever it is embedded (ADR-0448).
341    pub fn full_seconds_string(&self) -> String {
342        format::render(self, true)
343    }
344
345    /// One component accessor (`d.year`, `t.offsetMinutes`, `dur.months`).
346    /// The reference engine rejects a component the value's kind does not
347    /// carry, so [`component::read`] is the whole policy: the reader answers
348    /// a component its kind carries or the read is a typed error.
349    pub fn component(&self, key: &str) -> Result<Value, Error> {
350        component::read(self, key)
351    }
352}
353
354impl fmt::Display for Temporal {
355    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
356        write!(f, "{}", self.iso_string())
357    }
358}
359
360fn time_to_nanos(t: NaiveTime) -> i64 {
361    t.num_seconds_from_midnight() as i64 * 1_000_000_000 + t.nanosecond() as i64
362}
363
364/// The ISO decimal separator policy for temporal literals: a `,` is
365/// accepted wherever a `.` fraction goes (live 2026.10.1), and no temporal
366/// literal grammar has another comma — so the one normalization, borrowed
367/// when no comma is present, serves the time-of-day and duration parsers
368/// alike.
369pub(super) fn decimal_comma_as_dot(s: &str) -> std::borrow::Cow<'_, str> {
370    if s.contains(',') {
371        std::borrow::Cow::Owned(s.replace(',', "."))
372    } else {
373        std::borrow::Cow::Borrowed(s)
374    }
375}
376
377/// Nanoseconds of the UTC clock time a `Time` denotes. Deliberately *not*
378/// wrapped at midnight: an offset can push the wall clock out of the day, and
379/// the ordering contract is this signed value plus the offset. The lowest
380/// shared home for its two consumers — the relations (`temporal/relations.rs`)
381/// and `between`'s unit arithmetic, which shares the signed-nanos convention.
382pub(super) fn utc_time_nanos(t: NaiveTime, offset: i32) -> i64 {
383    time_to_nanos(t) - i64::from(offset) * 1_000_000_000
384}
385
386/// The wall clock of a zoned datetime as its normalized `(year, month,
387/// day, time)` parts (ADR-0683): the relations construct it from either
388/// representation — a chrono wall clock through its calendar fields, a
389/// civil one from its own — so equality is the tuple's (see
390/// `relations::ZonedView`). The type lives here, at the crate's temporal
391/// root, because it is the public signature type of
392/// [`Temporal::datetime_eq_identity`]. Named for its shape:
393/// `zone::WallClock` owns the resolver concept.
394pub type WallClockParts = (i64, u32, u32, NaiveTime);
395
396/// The one floored decomposition of a stored nanosecond count: whole
397/// seconds and the non-negative sub-second remainder. The split floors, so
398/// a negative sub-second duration lands on seconds = -1 with a
399/// non-negative remainder — Neo4j's own stored model — and every reader of
400/// the seconds/sub-second pair shares the one rounding convention.
401fn split_seconds(nanos: i128) -> (i128, i128) {
402    (
403        nanos.div_euclid(NANOS_PER_SECOND),
404        nanos.rem_euclid(NANOS_PER_SECOND),
405    )
406}
407
408/// `n` is always a within-day nanosecond count (rem_euclid at the call sites),
409/// so the conversion is infallible in practice; fall back instead of unwrap.
410fn nanos_to_time(n: i64) -> NaiveTime {
411    let secs = (n / 1_000_000_000) as u32;
412    let nano = (n % 1_000_000_000) as u32;
413    NaiveTime::from_num_seconds_from_midnight_opt(secs, nano).unwrap_or(NaiveTime::MIN)
414}
415
416/// Error returned when a temporal computation overflows the representable
417/// range (chrono dates ±262143 years, i64 duration months/days, i128 nanos).
418/// The honest contract for out-of-range results is an error, never a panic.
419pub(super) fn range_err() -> Error {
420    Error::ty("temporal value out of range")
421}
422
423/// The one spelling of a duration arithmetic overflow: Neo4j's 22N28
424/// (`ArithmeticException`) text, naming the operation that overflowed
425/// (`duration()` for construction, the field for pattern formatting).
426pub(super) fn duration_overflow_err(operation: &str) -> Error {
427    Error::ty(format!(
428        "the result of the operation '{operation}' has caused an overflow"
429    ))
430}
431
432/// Narrow one i128 lane total to the i64 a duration component stores.
433/// Components that overflow individually but cancel stay representable because
434/// the lanes are summed before this check (Neo4j's exact wide arithmetic).
435pub(super) fn checked_lane(value: i128, operation: &str) -> crate::Result<i64> {
436    i64::try_from(value).map_err(|_| duration_overflow_err(operation))
437}
438
439/// The `Temporal` payload a field map holds under `k`, or `None` when the
440/// key is absent or non-temporal. Shared by the constructors and the zone
441/// resolution (`construct.rs`, `zone.rs`); the scalar extraction is the
442/// canonical [`Value::as_temporal`]. The field *policy* never reads a source
443/// field through this — a present non-temporal value is a typed rejection
444/// there (`field_rules`), not an absent field.
445pub(super) fn map_temporal<'a>(
446    map: &'a std::collections::BTreeMap<String, Value>,
447    k: &str,
448) -> Option<&'a Temporal> {
449    map.get(k).and_then(Value::as_temporal)
450}
451
452/// The value a `(spelling, value)` table names, or `None` — the one keyed
453/// table lookup behind every `from_name` ([`clock::ClockKind`],
454/// [`component::Component`], its duration sibling), so no table is walked by
455/// a hand-rolled copy.
456pub(super) fn lookup<T: Copy>(table: &[(&str, T)], name: &str) -> Option<T> {
457    table
458        .iter()
459        .find(|(spelling, _)| *spelling == name)
460        .map(|(_, value)| *value)
461}
462
463/// f64 → i128 with a range error; 1e38 is comfortably below i128::MAX ≈ 1.7e38.
464pub(super) fn f64_to_i128_range(v: f64) -> Result<i128, Error> {
465    if v.is_finite() && v.abs() < 1.0e38 {
466        Ok(v as i128)
467    } else {
468        Err(range_err())
469    }
470}
471
472/// f64 → i64 with a range error — Neo4j's `DurationValue.safeDoubleToLong`
473/// seam: the stored month and day fields are `i64`, so an out-of-range
474/// fraction fold is a typed range error, never a saturating cast.
475pub(super) fn f64_to_i64_range(v: f64) -> Result<i64, Error> {
476    i64::try_from(f64_to_i128_range(v)?).map_err(|_| range_err())
477}
478
479fn weekday_from_i(i: i64) -> Weekday {
480    // `i.rem_euclid(7)` is total (unlike `(i - 1).rem_euclid(7)`, which
481    // overflows at i64::MIN) and selects the same weekday for every input:
482    // 1..=6 -> Mon..Sat, 0 -> Sun.
483    match i.rem_euclid(7) {
484        1 => Weekday::Mon,
485        2 => Weekday::Tue,
486        3 => Weekday::Wed,
487        4 => Weekday::Thu,
488        5 => Weekday::Fri,
489        6 => Weekday::Sat,
490        _ => Weekday::Sun,
491    }
492}
493
494/// The duration field vocabulary — fields, tiers, unit scales and the
495/// average-month/overflow facts — lives in [`field`]; these names are the
496/// facade the sibling modules read through `super::`.
497use field::{
498    DurationField, AVG_NANOS_PER_MONTH, AVG_SECONDS_PER_MONTH, MAX_DURATION_SECONDS,
499    MONTHS_PER_QUARTER, MONTHS_PER_YEAR, NANOS_PER_DAY, NANOS_PER_HOUR, NANOS_PER_MICRO,
500    NANOS_PER_MILLI, NANOS_PER_MINUTE, NANOS_PER_SECOND, SECONDS_PER_HOUR, SECONDS_PER_MINUTE,
501};