relate_core/temporal/mod.rs
1//! OpenCypher temporal values (ADR-0021).
2
3use std::cmp::Ordering;
4use std::fmt;
5
6use chrono::{NaiveDate, NaiveDateTime, NaiveTime, Timelike, Weekday};
7
8use crate::{Error, Value};
9
10mod arith;
11mod between;
12mod clock;
13mod component;
14mod construct;
15mod duration;
16mod duration_pattern;
17mod duration_tokens;
18mod exact;
19mod field;
20mod field_rules;
21mod format;
22mod parse;
23mod pattern;
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_clock;
34#[cfg(test)]
35mod tests_duration;
36#[cfg(test)]
37mod tests_fields;
38#[cfg(test)]
39mod tests_pattern;
40#[cfg(test)]
41mod tests_ranges;
42#[cfg(test)]
43mod tests_zone;
44mod truncate;
45mod zone;
46
47use format::format_zone_offset;
48use zone::add_offset;
49
50pub use arith::{
51 add_duration, civil_epoch_days, civil_from_days, negate_duration, scale_duration, sub_duration,
52};
53pub use between::{duration_between, duration_between_unit, BetweenUnit};
54pub use clock::{
55 clock_access, clock_spelling, clock_spelling_rows, clock_spellings, construct_clock,
56 now_epoch_millis, now_utc_dt, ClockKind, ClockMode, QueryClockGuard,
57};
58pub use construct::{
59 accepts_pattern, construct_date, construct_datetime, construct_duration,
60 construct_localdatetime, construct_localtime, construct_named, construct_time, is_constructor,
61 samples_clock,
62};
63pub use format::format_pattern;
64pub use parse::{
65 datetime_from_epoch, datetime_from_epoch_millis, padded_iso_date_value, parse_iso,
66 parse_pattern,
67};
68pub use truncate::{truncate, truncate_now};
69pub use zone::{zone_offset_at, zone_offset_at_utc, zone_region, ZoneError, MAX_OFFSET_SECONDS};
70
71#[derive(Debug, Clone, PartialEq, Eq)]
72pub enum Temporal {
73 Date(NaiveDate),
74 /// Out-of-range proleptic date (TCK ±999999999).
75 CivilDate {
76 year: i64,
77 month: u32,
78 day: u32,
79 },
80 LocalTime(NaiveTime),
81 Time {
82 time: NaiveTime,
83 offset: i32,
84 },
85 LocalDateTime(NaiveDateTime),
86 CivilDateTime {
87 year: i64,
88 month: u32,
89 day: u32,
90 time: NaiveTime,
91 },
92 DateTime {
93 utc: NaiveDateTime,
94 offset: i32,
95 zone: Option<String>,
96 },
97 Duration {
98 months: i64,
99 days: i64,
100 nanos: i128,
101 },
102}
103
104/// The six temporal type kinds, one per Cypher type name — the variant
105/// grouping the type-name spelling and the ORDER BY sub-ranks both key
106/// off, so it exists in one place. Declared in the ORDER BY rank order:
107/// ZONED DATETIME < LOCAL DATETIME < DATE < ZONED TIME < LOCAL TIME <
108/// DURATION (live Neo4j 2026.10.1, value-independent), so a kind's
109/// discriminant is that rank's offset.
110#[derive(Debug, Clone, Copy, PartialEq, Eq)]
111pub(crate) enum TemporalKind {
112 DateTime,
113 LocalDateTime,
114 Date,
115 Time,
116 LocalTime,
117 Duration,
118}
119
120impl TemporalKind {
121 /// The kind's lowercase wire name — the `Temporal::kind_name`
122 /// spelling, owned by the kind so the variant partition has one
123 /// owner.
124 pub(crate) fn name(self) -> &'static str {
125 match self {
126 TemporalKind::DateTime => "datetime",
127 TemporalKind::LocalDateTime => "localdatetime",
128 TemporalKind::Date => "date",
129 TemporalKind::Time => "time",
130 TemporalKind::LocalTime => "localtime",
131 TemporalKind::Duration => "duration",
132 }
133 }
134}
135
136impl Temporal {
137 /// This value's type kind — the one spelling of the variant grouping
138 /// (the civil out-of-range forms share their kind's name).
139 pub(crate) fn kind(&self) -> TemporalKind {
140 match self {
141 Temporal::DateTime { .. } => TemporalKind::DateTime,
142 Temporal::LocalDateTime(_) | Temporal::CivilDateTime { .. } => {
143 TemporalKind::LocalDateTime
144 }
145 Temporal::Date(_) | Temporal::CivilDate { .. } => TemporalKind::Date,
146 Temporal::Time { .. } => TemporalKind::Time,
147 Temporal::LocalTime(_) => TemporalKind::LocalTime,
148 Temporal::Duration { .. } => TemporalKind::Duration,
149 }
150 }
151}
152
153/// The zone half of a `DateTime`'s equality identity (TCK TemporalCompare):
154/// an IANA zone is identified by its name — so the two halves of a DST
155/// fall-back overlap stay equal — and every other spelling (`Z`, `+00:00`,
156/// `UTC`, …) by the UTC offset it denotes, so `Z` equals `+00:00` while a
157/// named zone never equals the offset it happens to denote.
158#[derive(Debug, Clone, PartialEq, Eq, Hash)]
159pub enum ZoneId {
160 Named(String),
161 Offset(i32),
162}
163
164impl ZoneId {
165 /// The identity of a `DateTime`'s `zone` at `offset`.
166 pub fn of(zone: Option<&str>, offset: i32) -> ZoneId {
167 match zone_region(zone) {
168 Some(name) => ZoneId::Named(name.to_string()),
169 None => ZoneId::Offset(offset),
170 }
171 }
172}
173
174impl Temporal {
175 /// The one place a duration's stored `(months, days, nanos)` triple is
176 /// assembled, and the one place its representability bound lives: the
177 /// sub-day part must fit Neo4j's `i64` seconds field (inclusive of
178 /// `2^63`, the `f64` image of `i64::MAX` that the scaling path still
179 /// casts back), and the duration's average length in seconds
180 /// (`months * AVG_SECONDS_PER_MONTH + days * 86400 + seconds`) must fit
181 /// an `i64` (`DurationValue.assertNoOverflow`). Every producer — the ISO
182 /// numeral parser, the pattern parser, the map constructor, scaling and
183 /// duration addition — builds through this seam, so one value is
184 /// accepted or rejected regardless of how it was spelled; a value past
185 /// the bound is Neo4j's interval-field overflow, never a silently larger
186 /// duration. Neo4j's constructor enforces the same bound (verified
187 /// against Neo4j 5: `duration({months: 4000000000000})` errors, while the
188 /// same value via `* 1.0` errors identically).
189 pub(crate) fn duration_checked(months: i64, days: i64, nanos: i128) -> Result<Temporal, Error> {
190 let seconds = nanos.div_euclid(NANOS_PER_SECOND);
191 if !(-MAX_DURATION_SECONDS..=MAX_DURATION_SECONDS).contains(&seconds) {
192 return Err(range_err());
193 }
194 // `seconds` can equal ±2^63, one past `i64`; the average-length sum
195 // stays in i128 and the final `i64::try_from` rejects an out-of-range
196 // total, so the clamp only keeps the sum's own arithmetic in range.
197 let seconds = seconds.clamp(i128::from(i64::MIN), i128::from(i64::MAX));
198 let average = i128::from(months) * AVG_SECONDS_PER_MONTH
199 + i128::from(days) * (NANOS_PER_DAY / NANOS_PER_SECOND)
200 + seconds;
201 i64::try_from(average).map_err(|_| range_err())?;
202 Ok(Temporal::Duration {
203 months,
204 days,
205 nanos,
206 })
207 }
208
209 /// [`Temporal::duration_checked`] with the strict stored-model bound for
210 /// producers whose arithmetic is exact (the ISO and pattern parsers, the
211 /// all-integer map constructor, negation and addition). Neo4j's duration
212 /// stores its sub-day part as an `i64` seconds field, so exactly `2^63`
213 /// seconds is not representable (`duration('PT9223372036854775808S')`
214 /// overflows); only the `f64` scaling path produces that image by
215 /// rounding `i64::MAX` and casts it back, which is why the shared seam
216 /// accepts it.
217 pub(crate) fn duration_checked_exact(
218 months: i64,
219 days: i64,
220 nanos: i128,
221 ) -> Result<Temporal, Error> {
222 if nanos.div_euclid(NANOS_PER_SECOND) > i128::from(i64::MAX) {
223 return Err(range_err());
224 }
225 Self::duration_checked(months, days, nanos)
226 }
227
228 pub fn kind_name(&self) -> &'static str {
229 self.kind().name()
230 }
231
232 /// Whether the value carries a calendar date — the one statement of the
233 /// capability partition, beside the type. The field policy
234 /// (`field_rules::check_sources`), the truncation granularity rule and
235 /// the part readers all read it, so no consumer keeps its own variant
236 /// list.
237 pub fn has_date(&self) -> bool {
238 matches!(
239 self,
240 Temporal::Date(_)
241 | Temporal::CivilDate { .. }
242 | Temporal::LocalDateTime(_)
243 | Temporal::CivilDateTime { .. }
244 | Temporal::DateTime { .. }
245 )
246 }
247
248 /// Whether the value carries a time of day (see [`Temporal::has_date`]).
249 pub fn has_time(&self) -> bool {
250 matches!(
251 self,
252 Temporal::LocalTime(_)
253 | Temporal::Time { .. }
254 | Temporal::LocalDateTime(_)
255 | Temporal::CivilDateTime { .. }
256 | Temporal::DateTime { .. }
257 )
258 }
259
260 /// Whether the value carries both halves (the `datetime` source field).
261 pub fn has_date_and_time(&self) -> bool {
262 self.has_date() && self.has_time()
263 }
264
265 pub fn iso_string(&self) -> String {
266 format::render(self, false)
267 }
268
269 /// The full-precision ISO rendering: [`Temporal::iso_string`] with
270 /// the time-of-day's seconds always present. The value layer's
271 /// temporal rendering policy for every string-producing surface —
272 /// `toString` (top-level, nested in a map or accepted list, or
273 /// through `toStringOrNull`) and the interpolated-string scalar
274 /// path — one rendering for one value, however it was built or
275 /// wherever it is embedded (ADR-0448).
276 pub fn full_seconds_string(&self) -> String {
277 format::render(self, true)
278 }
279
280 /// One component accessor (`d.year`, `t.offsetMinutes`, `dur.months`).
281 /// The reference engine rejects a component the value's kind does not
282 /// carry, so [`component::read`] is the whole policy: the reader answers
283 /// a component its kind carries or the read is a typed error.
284 pub fn component(&self, key: &str) -> Result<Value, Error> {
285 component::read(self, key)
286 }
287
288 /// Cypher `=` between two values of the same temporal kind (`false` for
289 /// unlike kinds). The relation is deliberately *not* the ordering one:
290 ///
291 /// * `Time` — local time **and** offset, so `12:00+01:00` and `11:00Z`
292 /// (the same instant) are different times, while `12:00Z` and
293 /// `12:00+00:00` are the same.
294 /// * `DateTime` — local date-time **and** zone identity, so the two
295 /// halves of a DST fall-back overlap (`02:30+02:00[Europe/Stockholm]`
296 /// and `02:30+01:00[Europe/Stockholm]`) are equal even though they are
297 /// different instants, while `[Europe/Stockholm]` never equals
298 /// `+01:00` (`ZoneId`).
299 pub fn equals(&self, other: &Temporal) -> bool {
300 match (self, other) {
301 (Temporal::Date(a), Temporal::Date(b)) => a == b,
302 (
303 Temporal::CivilDate {
304 year: ya,
305 month: ma,
306 day: da,
307 },
308 Temporal::CivilDate {
309 year: yb,
310 month: mb,
311 day: db,
312 },
313 ) => (ya, ma, da) == (yb, mb, db),
314 (Temporal::LocalTime(a), Temporal::LocalTime(b)) => a == b,
315 (
316 Temporal::Time {
317 time: a,
318 offset: oa,
319 },
320 Temporal::Time {
321 time: b,
322 offset: ob,
323 },
324 ) => a == b && oa == ob,
325 (Temporal::LocalDateTime(a), Temporal::LocalDateTime(b)) => a == b,
326 (
327 Temporal::CivilDateTime {
328 year: ya,
329 month: ma,
330 day: da,
331 time: ta,
332 },
333 Temporal::CivilDateTime {
334 year: yb,
335 month: mb,
336 day: db,
337 time: tb,
338 },
339 ) => (ya, ma, da, ta) == (yb, mb, db, tb),
340 (Temporal::DateTime { .. }, Temporal::DateTime { .. }) => {
341 self.datetime_eq_identity() == other.datetime_eq_identity()
342 }
343 (
344 Temporal::Duration {
345 months: am,
346 days: ad,
347 nanos: an,
348 },
349 Temporal::Duration {
350 months: bm,
351 days: bd,
352 nanos: bn,
353 },
354 ) => (am, ad, an) == (bm, bd, bn),
355 _ => false,
356 }
357 }
358
359 /// The two components [`Self::equals`] compares for a zoned `DateTime`:
360 /// its local wall clock and its [`ZoneId`]. `None` for every other
361 /// temporal kind. This is the `=` identity only; the property index,
362 /// uniqueness probe and `MERGE` key the finer equivalence identity
363 /// (UTC instant plus zone), so the two halves of a DST fall-back overlap
364 /// are equal yet separate index entries (LABS-785).
365 pub fn datetime_eq_identity(&self) -> Option<(NaiveDateTime, ZoneId)> {
366 match self {
367 Temporal::DateTime { utc, offset, zone } => Some((
368 local_of(*utc, *offset),
369 ZoneId::of(zone.as_deref(), *offset),
370 )),
371 _ => None,
372 }
373 }
374
375 /// Three-valued ordering for `<`, `>`, `<=`, `>=` (`None` is the null
376 /// result of comparing incomparable values):
377 ///
378 /// * `Time` — UTC nanos-of-day (not wrapped at midnight, so it can be
379 /// negative), then the offset, so two times at the same instant still
380 /// order.
381 /// * `DateTime` — instant (nanos included), then offset, then a plain
382 /// offset before a named zone, then the zone name.
383 /// * `Duration` — not orderable at all; only `=` is defined for it.
384 pub fn compare(&self, other: &Temporal) -> Option<Ordering> {
385 match (self, other) {
386 (Temporal::Date(a), Temporal::Date(b)) => Some(a.cmp(b)),
387 (
388 Temporal::CivilDate {
389 year: ya,
390 month: ma,
391 day: da,
392 },
393 Temporal::CivilDate {
394 year: yb,
395 month: mb,
396 day: db,
397 },
398 ) => Some((ya, ma, da).cmp(&(yb, mb, db))),
399 (Temporal::LocalTime(a), Temporal::LocalTime(b)) => Some(a.cmp(b)),
400 (Temporal::LocalDateTime(a), Temporal::LocalDateTime(b)) => Some(a.cmp(b)),
401 (
402 Temporal::Time {
403 time: a,
404 offset: oa,
405 },
406 Temporal::Time {
407 time: b,
408 offset: ob,
409 },
410 ) => Some(
411 utc_time_nanos(*a, *oa)
412 .cmp(&utc_time_nanos(*b, *ob))
413 .then(oa.cmp(ob)),
414 ),
415 (
416 Temporal::DateTime {
417 utc: ua,
418 offset: oa,
419 zone: za,
420 },
421 Temporal::DateTime {
422 utc: ub,
423 offset: ob,
424 zone: zb,
425 },
426 ) => Some(
427 ua.cmp(ub)
428 .then_with(|| oa.cmp(ob))
429 // A named (IANA) zone sorts after the plain offset it
430 // equals, by name: `None < Some(_)`.
431 .then_with(|| zone_region(za.as_deref()).cmp(&zone_region(zb.as_deref()))),
432 ),
433 (Temporal::Duration { .. }, Temporal::Duration { .. }) => None,
434 _ => None,
435 }
436 }
437
438 /// `IS SAME INSTANT` (Cypher 25 chronological comparison): the UTC
439 /// instant for the two zoned kinds — `DateTime` by its stored UTC half,
440 /// `Time` by [`utc_time_nanos`] — and [`Self::equals`] for the non-zoned
441 /// kinds, whose clock already *is* the instant. Unlike kinds are `false`
442 /// here too; the operator's mixed-kind null/false policy stays with the
443 /// caller, this relation only answers for a comparable pair.
444 pub fn same_instant(&self, other: &Temporal) -> bool {
445 match (self, other) {
446 (Temporal::DateTime { utc: a, .. }, Temporal::DateTime { utc: b, .. }) => a == b,
447 (
448 Temporal::Time {
449 time: a,
450 offset: oa,
451 },
452 Temporal::Time {
453 time: b,
454 offset: ob,
455 },
456 ) => utc_time_nanos(*a, *oa) == utc_time_nanos(*b, *ob),
457 _ => self.equals(other),
458 }
459 }
460
461 /// `IS BEFORE`/`IS AFTER` ordering (Cypher 25): the instant alone for
462 /// the zoned kinds — [`Self::compare`] also ranks equal instants by
463 /// offset and then zone, which a chronological operator must not — and
464 /// [`Self::compare`] for every other kind (durations stay unordered:
465 /// `None`).
466 pub fn instant_ordering(&self, other: &Temporal) -> Option<Ordering> {
467 match (self, other) {
468 (Temporal::DateTime { utc: a, .. }, Temporal::DateTime { utc: b, .. }) => {
469 Some(a.cmp(b))
470 }
471 (
472 Temporal::Time {
473 time: a,
474 offset: oa,
475 },
476 Temporal::Time {
477 time: b,
478 offset: ob,
479 },
480 ) => Some(utc_time_nanos(*a, *oa).cmp(&utc_time_nanos(*b, *ob))),
481 _ => self.compare(other),
482 }
483 }
484
485 /// Total order for `ORDER BY`, `min` and `max`: [`Self::compare`] where it
486 /// is defined, the `(months, days, nanos)` triple for durations (which
487 /// equality alone cannot rank), and `Equal` across unlike kinds — the
488 /// callers keep unlike temporals distinct by the value type rank.
489 pub(crate) fn total_cmp(&self, other: &Temporal) -> Ordering {
490 match (self, other) {
491 (
492 Temporal::Duration {
493 months: am,
494 days: ad,
495 nanos: an,
496 },
497 Temporal::Duration {
498 months: bm,
499 days: bd,
500 nanos: bn,
501 },
502 ) => (am, ad, an).cmp(&(bm, bd, bn)),
503 _ => self.compare(other).unwrap_or(Ordering::Equal),
504 }
505 }
506}
507
508impl fmt::Display for Temporal {
509 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
510 write!(f, "{}", self.iso_string())
511 }
512}
513
514fn time_to_nanos(t: NaiveTime) -> i64 {
515 t.num_seconds_from_midnight() as i64 * 1_000_000_000 + t.nanosecond() as i64
516}
517
518/// Nanoseconds of the UTC clock time a `Time` denotes. Deliberately *not*
519/// wrapped at midnight: an offset can push the wall clock out of the day, and
520/// the ordering contract is this signed value plus the offset.
521pub(super) fn utc_time_nanos(t: NaiveTime, offset: i32) -> i64 {
522 time_to_nanos(t) - i64::from(offset) * 1_000_000_000
523}
524
525/// The wall clock a zoned instant reads at (`utc + offset`). Constructors
526/// keep the sum inside chrono's range, but the Bolt parameter decoders
527/// accept any i32 offset (the render path's comment at the `DateTime` arm
528/// documents this input class), and equality bucketing has no error
529/// channel — so an out-of-range sum degrades to the UTC wall clock, the
530/// same stated fallback render uses, instead of panicking. Deterministic
531/// per payload, so `a = b` still implies one bucket.
532fn local_of(utc: NaiveDateTime, offset: i32) -> NaiveDateTime {
533 add_offset(utc, offset).unwrap_or(utc)
534}
535
536/// `n` is always a within-day nanosecond count (rem_euclid at the call sites),
537/// so the conversion is infallible in practice; fall back instead of unwrap.
538fn nanos_to_time(n: i64) -> NaiveTime {
539 let secs = (n / 1_000_000_000) as u32;
540 let nano = (n % 1_000_000_000) as u32;
541 NaiveTime::from_num_seconds_from_midnight_opt(secs, nano).unwrap_or(NaiveTime::MIN)
542}
543
544/// Error returned when a temporal computation overflows the representable
545/// range (chrono dates ±262143 years, i64 duration months/days, i128 nanos).
546/// The honest contract for out-of-range results is an error, never a panic.
547pub(super) fn range_err() -> Error {
548 Error::ty("temporal value out of range")
549}
550
551/// The one spelling of a duration arithmetic overflow: Neo4j's 22N28
552/// (`ArithmeticException`) text, naming the operation that overflowed
553/// (`duration()` for construction, the field for pattern formatting).
554pub(super) fn duration_overflow_err(operation: &str) -> Error {
555 Error::ty(format!(
556 "the result of the operation '{operation}' has caused an overflow"
557 ))
558}
559
560/// Narrow one i128 lane total to the i64 a duration component stores.
561/// Components that overflow individually but cancel stay representable because
562/// the lanes are summed before this check (Neo4j's exact wide arithmetic).
563pub(super) fn checked_lane(value: i128, operation: &str) -> crate::Result<i64> {
564 i64::try_from(value).map_err(|_| duration_overflow_err(operation))
565}
566
567/// The `Temporal` payload a field map holds under `k`, or `None` when the
568/// key is absent or non-temporal. Shared by the constructors and the zone
569/// resolution (`construct.rs`, `zone.rs`); the scalar extraction is the
570/// canonical [`Value::as_temporal`]. The field *policy* never reads a source
571/// field through this — a present non-temporal value is a typed rejection
572/// there (`field_rules`), not an absent field.
573pub(super) fn map_temporal<'a>(
574 map: &'a std::collections::BTreeMap<String, Value>,
575 k: &str,
576) -> Option<&'a Temporal> {
577 map.get(k).and_then(Value::as_temporal)
578}
579
580/// The value a `(spelling, value)` table names, or `None` — the one keyed
581/// table lookup behind every `from_name` ([`clock::ClockKind`],
582/// [`component::Component`], its duration sibling), so no table is walked by
583/// a hand-rolled copy.
584pub(super) fn lookup<T: Copy>(table: &[(&str, T)], name: &str) -> Option<T> {
585 table
586 .iter()
587 .find(|(spelling, _)| *spelling == name)
588 .map(|(_, value)| *value)
589}
590
591/// f64 → i128 with a range error; 1e38 is comfortably below i128::MAX ≈ 1.7e38.
592pub(super) fn f64_to_i128_range(v: f64) -> Result<i128, Error> {
593 if v.is_finite() && v.abs() < 1.0e38 {
594 Ok(v as i128)
595 } else {
596 Err(range_err())
597 }
598}
599
600/// f64 → i64 with a range error — Neo4j's `DurationValue.safeDoubleToLong`
601/// seam: the stored month and day fields are `i64`, so an out-of-range
602/// fraction fold is a typed range error, never a saturating cast.
603pub(super) fn f64_to_i64_range(v: f64) -> Result<i64, Error> {
604 i64::try_from(f64_to_i128_range(v)?).map_err(|_| range_err())
605}
606
607fn weekday_from_i(i: i64) -> Weekday {
608 // `i.rem_euclid(7)` is total (unlike `(i - 1).rem_euclid(7)`, which
609 // overflows at i64::MIN) and selects the same weekday for every input:
610 // 1..=6 -> Mon..Sat, 0 -> Sun.
611 match i.rem_euclid(7) {
612 1 => Weekday::Mon,
613 2 => Weekday::Tue,
614 3 => Weekday::Wed,
615 4 => Weekday::Thu,
616 5 => Weekday::Fri,
617 6 => Weekday::Sat,
618 _ => Weekday::Sun,
619 }
620}
621
622/// The duration field vocabulary — fields, tiers, unit scales and the
623/// average-month/overflow facts — lives in [`field`]; these names are the
624/// facade the sibling modules read through `super::`.
625use field::{
626 DurationField, AVG_NANOS_PER_MONTH, AVG_SECONDS_PER_MONTH, MAX_DURATION_SECONDS,
627 MONTHS_PER_QUARTER, MONTHS_PER_YEAR, NANOS_PER_DAY, NANOS_PER_HOUR, NANOS_PER_MICRO,
628 NANOS_PER_MILLI, NANOS_PER_MINUTE, NANOS_PER_SECOND, SECONDS_PER_HOUR, SECONDS_PER_MINUTE,
629};