Skip to main content

relate_core/temporal/
relations.rs

1//! The temporal relations: `=` ([`Temporal::equals`]), the three-valued
2//! [`Temporal::compare`], the chronological [`Temporal::same_instant`] /
3//! [`Temporal::instant_ordering`], the zoned identities
4//! ([`Temporal::datetime_eq_identity`], [`Temporal::zoned_instant_identity`])
5//! and the total order `ORDER BY` reads ([`Temporal::total_cmp`]) —
6//! extracted from `mod.rs` with the helpers only they use.
7//!
8//! Every kind-partitioned relation reads its key from [`kind_key`], the
9//! **one exhaustive match** from a value to its kind's key: each Cypher
10//! kind's two internal representations (a chrono date and a proleptic
11//! civil one, and the zoned pair of ADR-0683) share one key, and the
12//! zoned key carries the whole [`ZonedView`] the ordering, the `=`
13//! identity and the executor's group key all derive from — so a
14//! representation added to any kind is a compile error at that one match,
15//! never a silently unkeyed value. The kind-level predicates
16//! ([`Temporal::same_instant`]) ask [`Temporal::kind`] instead, the one
17//! vocabulary for "same Cypher kind".
18
19use std::cmp::Ordering;
20
21use chrono::{Datelike, NaiveDate, NaiveDateTime, NaiveTime};
22
23use super::zone::{add_offset, zone_region};
24use super::{
25    utc_time_nanos, CivilZonedFields, Temporal, TemporalKind, WallClockParts, ZoneId, ZonedParts,
26};
27
28/// The one view over the zoned partition (ADR-0683) — the facts the
29/// zoned relations read, matched out of either representation by
30/// [`kind_key`]: the UTC instant (wide `i128` epoch nanoseconds), the
31/// offset, the IANA region (`None` for a plain offset spelling) and the
32/// matched-out source, from which the local wall clock
33/// ([`ZonedView::wall`]) is derived on demand — the ordering relations
34/// and the group key never read it, so their comparisons skip the offset
35/// add and the calendar decomposition the `=` identity alone needs.
36struct ZonedView<'a> {
37    /// The published three facts — instant, offset, region — in their one
38    /// definition ([`ZonedParts`]); the ordering reads them directly and
39    /// [`Temporal::zoned_parts`] hands them to the Bolt encoder.
40    parts: ZonedParts<'a>,
41    /// The matched-out representation — the memo of the one partition
42    /// match, so [`ZonedView::wall`] reads the matched representation's
43    /// own fields, never a re-derived policy.
44    source: ZonedSource<'a>,
45}
46
47/// The representation a [`ZonedView`] was matched out of.
48enum ZonedSource<'a> {
49    /// A chrono-range `DateTime`'s stored UTC half (the view carries its
50    /// offset).
51    Chrono { utc: NaiveDateTime },
52    /// The far-year civil form's own fields.
53    Civil(&'a CivilZonedFields),
54}
55
56impl ZonedView<'_> {
57    /// The local wall clock as its normalized `(year, month, day, time)`
58    /// parts — the `=` identity's clock half ([`WallClockParts`]),
59    /// derived on demand from the matched source: only the `=` identity
60    /// reads it.
61    fn wall(&self) -> WallClockParts {
62        match self.source {
63            ZonedSource::Chrono { utc } => local_datetime_parts(local_of(utc, self.parts.offset)),
64            ZonedSource::Civil(fields) => (fields.year, fields.month, fields.day, fields.time),
65        }
66    }
67
68    /// The two components [`Temporal::equals`] compares for a zoned
69    /// datetime: its local wall clock and its [`ZoneId`] — the `=`
70    /// identity only, finer than the instant so the two halves of a DST
71    /// fall-back overlap stay equal (LABS-785 keys the index and `MERGE`
72    /// on [`ZonedView::instant`] plus the zone instead).
73    fn eq_identity(&self) -> (WallClockParts, ZoneId) {
74        (
75            self.wall(),
76            ZoneId::of_region(self.parts.region, self.parts.offset),
77        )
78    }
79}
80
81/// The zoned pair's `=` relation, and the one its [`KindKey`] variant
82/// compares with: the view's own identity — wall clock plus [`ZoneId`] —
83/// never a derived field-by-field comparison, so the two halves of a DST
84/// fall-back overlap are `=`-equal though their instants differ.
85impl PartialEq for ZonedView<'_> {
86    fn eq(&self, other: &Self) -> bool {
87        self.eq_identity() == other.eq_identity()
88    }
89}
90
91/// One representation's ordering/equality key, per kind — the payloads
92/// [`kind_key`] produces and every key-level relation matches on. Each
93/// kind's two internal representations share one variant, so DATE's
94/// chrono and civil forms order and compare alike.
95#[derive(PartialEq)]
96enum KindKey<'a> {
97    /// The DATE kind: the proleptic calendar triple.
98    Date((i64, u32, u32)),
99    /// The LOCAL TIME kind.
100    LocalTime(NaiveTime),
101    /// The LOCAL DATETIME kind: the wall clock parts ([`WallClockParts`]).
102    LocalDateTime(WallClockParts),
103    /// The TIME kind: the signed UTC nanos-of-day and the offset — named,
104    /// so the arm that reads only the instant
105    /// ([`Temporal::instant_ordering`]) says which half it means.
106    Time { utc_nanos: i64, offset: i32 },
107    /// The DATETIME kind: the one zoned view.
108    Zoned(ZonedView<'a>),
109    /// The DURATION kind: the stored `(months, days, nanos)` triple,
110    /// which `=` compares as-is and [`Temporal::total_cmp`] ranks.
111    Duration((i64, i64, i128)),
112}
113
114/// The one exhaustive match from a value to its kind's key — the
115/// relations' dispatch and their single extension point: a new
116/// representation of any kind fails to compile here, never silently
117/// answering an unkeyed value.
118fn kind_key(t: &Temporal) -> KindKey<'_> {
119    match t {
120        Temporal::Date(d) => KindKey::Date(date_parts(*d)),
121        Temporal::CivilDate { year, month, day } => KindKey::Date((*year, *month, *day)),
122        Temporal::LocalTime(time) => KindKey::LocalTime(*time),
123        Temporal::LocalDateTime(dt) => KindKey::LocalDateTime(local_datetime_parts(*dt)),
124        Temporal::CivilDateTime {
125            year,
126            month,
127            day,
128            time,
129        } => KindKey::LocalDateTime((*year, *month, *day, *time)),
130        Temporal::Time { time, offset } => KindKey::Time {
131            utc_nanos: utc_time_nanos(*time, *offset),
132            offset: *offset,
133        },
134        // The zoned pair (ADR-0683): one view, from either
135        // representation — the chrono instant through its seconds pair,
136        // the civil one through the wide day arithmetic.
137        Temporal::DateTime { utc, offset, zone } => KindKey::Zoned(ZonedView {
138            parts: ZonedParts {
139                instant: utc_epoch_nanos(*utc),
140                offset: *offset,
141                region: zone_region(zone.as_deref()),
142            },
143            source: ZonedSource::Chrono { utc: *utc },
144        }),
145        Temporal::CivilZoned(fields) => KindKey::Zoned(ZonedView {
146            parts: ZonedParts {
147                instant: fields.epoch_nanos(),
148                offset: fields.offset,
149                region: zone_region(fields.zone.as_deref()),
150            },
151            source: ZonedSource::Civil(fields),
152        }),
153        Temporal::Duration {
154            months,
155            days,
156            nanos,
157        } => KindKey::Duration((*months, *days, *nanos)),
158    }
159}
160
161/// The three-valued ordering of two **already-derived** kind keys — the
162/// one key-level comparison sink, so a relation that has built its keys
163/// ([`Temporal::instant_ordering`], [`Temporal::total_cmp`]) never derives
164/// them a second time through [`Temporal::compare`].
165fn compare_keys(a: KindKey<'_>, b: KindKey<'_>) -> Option<Ordering> {
166    match (a, b) {
167        (KindKey::Date(a), KindKey::Date(b)) => Some(a.cmp(&b)),
168        (KindKey::LocalTime(a), KindKey::LocalTime(b)) => Some(a.cmp(&b)),
169        (KindKey::LocalDateTime(a), KindKey::LocalDateTime(b)) => Some(a.cmp(&b)),
170        // The UTC nanos first, then the offset.
171        (
172            KindKey::Time {
173                utc_nanos: a,
174                offset: oa,
175            },
176            KindKey::Time {
177                utc_nanos: b,
178                offset: ob,
179            },
180        ) => Some(a.cmp(&b).then_with(|| oa.cmp(&ob))),
181        // A zoned pair — both representations — orders by the one instant
182        // both representations share (ADR-0683), then offset, then zone.
183        (KindKey::Zoned(a), KindKey::Zoned(b)) => Some(
184            a.parts
185                .instant
186                .cmp(&b.parts.instant)
187                .then_with(|| a.parts.offset.cmp(&b.parts.offset))
188                // A named (IANA) zone sorts after the plain offset it
189                // equals, by name: `None < Some(_)`.
190                .then_with(|| a.parts.region.cmp(&b.parts.region)),
191        ),
192        // Unlike kinds, and durations (not orderable at all — only `=`
193        // is defined for them), answer the null result.
194        _ => None,
195    }
196}
197
198/// The wide epoch nanoseconds of a chrono UTC datetime: through the
199/// seconds pair, never `timestamp_nanos` (an `i64` that overflows far
200/// inside chrono's range). The chrono half of the one instant derivation
201/// — [`CivilZonedFields::epoch_nanos`] is the civil half.
202fn utc_epoch_nanos(utc: NaiveDateTime) -> i128 {
203    let instant = utc.and_utc();
204    i128::from(instant.timestamp()) * 1_000_000_000 + i128::from(instant.timestamp_subsec_nanos())
205}
206
207impl Temporal {
208    /// Cypher `=` between two values of the same temporal kind (`false` for
209    /// unlike kinds). The relation is deliberately *not* the ordering one:
210    ///
211    /// * `Time` — local time **and** offset, so `12:00+01:00` and `11:00Z`
212    ///   (the same instant) are different times, while `12:00Z` and
213    ///   `12:00+00:00` are the same.
214    /// * `DateTime` — local date-time **and** zone identity, so the two
215    ///   halves of a DST fall-back overlap (`02:30+02:00[Europe/Stockholm]`
216    ///   and `02:30+01:00[Europe/Stockholm]`) are equal even though they are
217    ///   different instants, while `[Europe/Stockholm]` never equals
218    ///   `+01:00` (`ZoneId`).
219    pub fn equals(&self, other: &Temporal) -> bool {
220        // The key's own `=` — per kind the key *is* the `=` identity, and
221        // the zoned variant's [`PartialEq`] reads the wall clock plus zone
222        // (so the two halves of a DST fall-back overlap stay equal across
223        // the representations they parse into, ADR-0683). Unlike kinds are
224        // different variants, hence unequal.
225        kind_key(self) == kind_key(other)
226    }
227
228    /// The two components [`Self::equals`] compares for a zoned datetime —
229    /// either representation, the civil far-year form included (ADR-0683):
230    /// its local wall clock and its [`ZoneId`]. `None` for every other
231    /// temporal kind. This is the `=` identity only; the property index,
232    /// uniqueness probe and `MERGE` key the finer equivalence identity
233    /// (UTC instant plus zone, [`Self::zoned_instant_identity`]), so the
234    /// two halves of a DST fall-back overlap are equal yet separate index
235    /// entries (LABS-785).
236    pub fn datetime_eq_identity(&self) -> Option<(WallClockParts, ZoneId)> {
237        self.zoned_view().map(|view| view.eq_identity())
238    }
239
240    /// The zoned datetime's identity for the property index, uniqueness
241    /// probe and `MERGE` key (LABS-785): the UTC instant plus [`ZoneId`] —
242    /// finer than [`Self::datetime_eq_identity`]'s wall clock and zone, so
243    /// the two halves of a DST fall-back overlap are `=`-equal yet separate
244    /// entries. `None` for every non-zoned kind. The executor's group key
245    /// reads this one derivation, so a representation added to the zoned
246    /// partition can never fork the equivalence.
247    pub fn zoned_instant_identity(&self) -> Option<(i128, ZoneId)> {
248        self.zoned_parts()
249            .map(|parts| (parts.instant, ZoneId::of_region(parts.region, parts.offset)))
250    }
251
252    /// The zoned facts every consumer reads (ADR-0683): the wide UTC
253    /// instant in epoch nanoseconds, the offset, and the already-classified
254    /// IANA region (`None` for a plain offset spelling). `None` for every
255    /// non-zoned kind. The relations derive from the one [`kind_key`], and
256    /// so does the Bolt encoder, which needs exactly these three — one
257    /// derivation, never a per-consumer reassembly of the instant.
258    pub fn zoned_parts(&self) -> Option<ZonedParts<'_>> {
259        self.zoned_view().map(|view| view.parts)
260    }
261
262    /// The one "is this zoned — hand me its view" extraction the three
263    /// zoned accessors project from, so the `Some` set and its `None`
264    /// contract have one home (the same `KindKey::Zoned` arm every
265    /// relation reads).
266    fn zoned_view(&self) -> Option<ZonedView<'_>> {
267        match kind_key(self) {
268            KindKey::Zoned(view) => Some(view),
269            _ => None,
270        }
271    }
272
273    /// Three-valued ordering for `<`, `>`, `<=`, `>=` (`None` is the null
274    /// result of comparing incomparable values). The dispatch is the
275    /// [`kind_key`] pair — the one key-level spelling of the variant
276    /// grouping (`Temporal::kind` stays the kind-level discriminant) — so
277    /// each kind's two representations compare through one key:
278    ///
279    /// * `Date` — the proleptic calendar triple, so DATE's chrono and
280    ///   civil forms share one order.
281    /// * `LocalDateTime` — the wall clock parts, likewise.
282    /// * `Time` — UTC nanos-of-day (not wrapped at midnight, so it can be
283    ///   negative), then the offset, so two times at the same instant
284    ///   still order.
285    /// * `DateTime` — the [`ZonedView`]'s instant (nanos included), then
286    ///   offset, then a plain offset before a named zone, then the zone
287    ///   name.
288    /// * `Duration` — not orderable at all; only `=` is defined for it.
289    ///
290    /// Unlike kinds answer `None` (the null result).
291    pub fn compare(&self, other: &Temporal) -> Option<Ordering> {
292        compare_keys(kind_key(self), kind_key(other))
293    }
294
295    /// `IS SAME INSTANT` (Cypher 25 chronological comparison): the instant
296    /// for the two instant-bearing kinds — `DateTime` (either
297    /// representation) and `Time` — is [`Self::instant_ordering`]'s
298    /// equality, one derivation for both; [`Self::equals`] for the
299    /// non-zoned kinds, whose clock already *is* the instant. Unlike kinds
300    /// are `false` here too; the operator's mixed-kind null/false policy
301    /// stays with the caller, this relation only answers for a comparable
302    /// pair.
303    pub fn same_instant(&self, other: &Temporal) -> bool {
304        match (self.kind(), other.kind()) {
305            (TemporalKind::DateTime, TemporalKind::DateTime)
306            | (TemporalKind::Time, TemporalKind::Time) => {
307                self.instant_ordering(other) == Some(Ordering::Equal)
308            }
309            _ => self.equals(other),
310        }
311    }
312
313    /// `IS BEFORE`/`IS AFTER` ordering (Cypher 25): the instant alone for
314    /// the two instant-bearing kinds — [`Self::compare`] also ranks equal
315    /// instants by offset and then zone, which a chronological operator
316    /// must not — and [`Self::compare`] for every other kind (durations
317    /// stay unordered: `None`).
318    pub fn instant_ordering(&self, other: &Temporal) -> Option<Ordering> {
319        match (kind_key(self), kind_key(other)) {
320            // A zoned pair — both representations — orders by the wide
321            // instant (ADR-0683).
322            (KindKey::Zoned(a), KindKey::Zoned(b)) => Some(a.parts.instant.cmp(&b.parts.instant)),
323            // The UTC nanos alone: the offset must not break a tie.
324            (KindKey::Time { utc_nanos: a, .. }, KindKey::Time { utc_nanos: b, .. }) => {
325                Some(a.cmp(&b))
326            }
327            // The keys are already built — the one comparison sink reads
328            // them, never a second derivation through `compare`.
329            (a, b) => compare_keys(a, b),
330        }
331    }
332
333    /// Total order for `ORDER BY`, `min` and `max`: [`Self::compare`] where it
334    /// is defined, the duration triple for durations (which equality alone
335    /// cannot rank), and `Equal` across unlike kinds — the callers keep
336    /// unlike temporals distinct by the value type rank.
337    pub(crate) fn total_cmp(&self, other: &Temporal) -> Ordering {
338        match (kind_key(self), kind_key(other)) {
339            (KindKey::Duration(a), KindKey::Duration(b)) => a.cmp(&b),
340            (a, b) => compare_keys(a, b).unwrap_or(Ordering::Equal),
341        }
342    }
343}
344
345/// The calendar ordering key of a representable date — the same triple a
346/// [`Temporal::CivilDate`] carries, so DATE's two representations share one
347/// order.
348fn date_parts(d: NaiveDate) -> (i64, u32, u32) {
349    (i64::from(d.year()), d.month(), d.day())
350}
351
352/// The ordering key of a representable local date-time, in the shape a
353/// [`Temporal::CivilDateTime`] carries.
354fn local_datetime_parts(dt: NaiveDateTime) -> WallClockParts {
355    let (year, month, day) = date_parts(dt.date());
356    (year, month, day, dt.time())
357}
358
359/// The wall clock a zoned instant reads at (`utc + offset`). Constructors
360/// keep the sum inside chrono's range, but the Bolt parameter decoders
361/// accept any i32 offset (the render path's comment at the `DateTime` arm
362/// documents this input class), and equality bucketing has no error
363/// channel — so an out-of-range sum degrades to the UTC wall clock, the
364/// same stated fallback render uses, instead of panicking. Deterministic
365/// per payload, so `a = b` still implies one bucket.
366fn local_of(utc: NaiveDateTime, offset: i32) -> NaiveDateTime {
367    add_offset(utc, offset).unwrap_or(utc)
368}