Skip to main content

hawdb_core/
temporal.rs

1// Copyright 2026 Nowledge
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! openCypher temporal values: dates, local times, local and zoned datetimes,
16//! and durations.
17//!
18//! Instants use time types with the large-dates feature. Zoned datetimes carry
19//! a fixed UTC offset; named time-zone regions are not supported. A [`Duration`]
20//! keeps calendar months and days separate from its exact time part, as
21//! openCypher requires: one month or one day has no fixed length.
22
23mod arithmetic;
24pub mod codec;
25mod component;
26mod construct;
27mod format;
28mod parse;
29mod text;
30pub use text::{parse_metadata_millis, parse_rfc3339_millis};
31
32use crate::temporal::types::*;
33
34use std::cell::Cell;
35use std::cmp::Ordering;
36use std::fmt::{Display, Formatter};
37
38// Keep facade names stable across the minimum and current time releases.
39pub use ::time::{
40    Date, Duration as SignedDuration, Month, OffsetDateTime, PrimitiveDateTime as PlainDateTime,
41    Time, UtcOffset, Weekday,
42};
43pub(crate) mod types;
44
45use crate::Value;
46
47use arithmetic::between;
48pub use arithmetic::{arithmetic, truncate, TemporalArithmeticOp};
49pub use component::component;
50pub use construct::{construct, from_epoch, from_epoch_millis};
51pub use format::{format_date, format_datetime, format_local_datetime, format_local_time};
52pub use parse::{
53    parse_date, parse_datetime, parse_duration, parse_local_datetime, parse_local_time,
54};
55
56pub(crate) const NANOS_PER_SECOND: i128 = 1_000_000_000;
57pub(crate) const SECONDS_PER_DAY: i128 = 86_400;
58pub(crate) const NANOS_PER_DAY: i128 = NANOS_PER_SECOND * SECONDS_PER_DAY;
59/// The openCypher (and ISO 8601 Gregorian) average month length: 30.436875
60/// days, used only to cascade fractional months into days.
61pub(crate) const AVERAGE_DAYS_PER_MONTH: f64 = 30.436_875;
62
63/// A temporal evaluation error. Callers map it to the error class of the
64/// evaluating layer (semantic during planning, execution at run time).
65#[derive(Debug, Clone, PartialEq, Eq)]
66pub struct TemporalError(String);
67
68impl TemporalError {
69    pub(crate) fn new(message: impl Into<String>) -> Self {
70        Self(message.into())
71    }
72
73    pub fn message(&self) -> &str {
74        &self.0
75    }
76}
77
78impl Display for TemporalError {
79    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
80        f.write_str(&self.0)
81    }
82}
83
84impl std::error::Error for TemporalError {}
85
86impl From<TemporalError> for crate::HawDBError {
87    fn from(error: TemporalError) -> Self {
88        crate::HawDBError::Execution(error.0)
89    }
90}
91
92pub type TemporalResult<T> = std::result::Result<T, TemporalError>;
93
94/// An openCypher duration.
95///
96/// `months` and `days` are calendar quantities whose length depends on the
97/// instant they are applied to; `time` is an exact length. The derived order
98/// (months, days, time) is a total internal order used for sorting, grouping
99/// and indexes. Cypher `<`/`>` between durations is undefined (NULL).
100#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
101pub struct Duration {
102    pub months: i64,
103    pub days: i64,
104    time: SignedDuration,
105}
106
107impl Duration {
108    /// Rejects exact time parts outside the established i64-millisecond domain.
109    pub fn new(months: i64, days: i64, time: SignedDuration) -> Option<Self> {
110        delta_from_nanos(time.whole_nanoseconds())?;
111        Some(Self { months, days, time })
112    }
113
114    pub const fn time(&self) -> SignedDuration {
115        self.time
116    }
117
118    /// Builds a duration from a nanosecond time part.
119    pub fn from_parts(months: i64, days: i64, nanos: i128) -> Option<Self> {
120        Self::new(months, days, delta_from_nanos(nanos)?)
121    }
122
123    /// The time part in nanoseconds.
124    pub fn time_nanos(&self) -> i128 {
125        delta_nanos(self.time)
126    }
127
128    /// Whole seconds of the time part, rounded toward negative infinity so
129    /// that [`Self::nanos_of_second`] is always non-negative.
130    pub fn seconds(&self) -> i64 {
131        self.time_nanos().div_euclid(NANOS_PER_SECOND) as i64
132    }
133
134    /// Nanoseconds of the time part within its second, in `0..1_000_000_000`.
135    pub fn nanos_of_second(&self) -> i64 {
136        self.time_nanos().rem_euclid(NANOS_PER_SECOND) as i64
137    }
138
139    pub fn checked_add(self, other: Self) -> Option<Self> {
140        Self::new(
141            self.months.checked_add(other.months)?,
142            self.days.checked_add(other.days)?,
143            delta_from_nanos(self.time_nanos().checked_add(other.time_nanos())?)?,
144        )
145    }
146
147    pub fn checked_neg(self) -> Option<Self> {
148        Self::new(
149            self.months.checked_neg()?,
150            self.days.checked_neg()?,
151            delta_from_nanos(-self.time_nanos())?,
152        )
153    }
154
155    pub fn checked_sub(self, other: Self) -> Option<Self> {
156        self.checked_add(other.checked_neg()?)
157    }
158}
159
160impl Display for Duration {
161    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
162        format::write_duration(f, self)
163    }
164}
165
166pub(crate) fn delta_nanos(delta: SignedDuration) -> i128 {
167    delta.whole_nanoseconds()
168}
169
170pub(crate) fn delta_from_nanos(nanos: i128) -> Option<SignedDuration> {
171    // Preserve the existing duration payload domain (signed i64 milliseconds).
172    let limit = i128::from(i64::MAX) * 1_000_000;
173    (-limit..=limit)
174        .contains(&nanos)
175        .then(|| SignedDuration::nanoseconds_i128(nanos))
176}
177
178/// The four instant kinds that openCypher constructors and truncation produce.
179#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
180pub enum TemporalKind {
181    Date,
182    LocalTime,
183    LocalDateTime,
184    DateTime,
185}
186
187impl TemporalKind {
188    pub const fn function_name(self) -> &'static str {
189        match self {
190            Self::Date => "date",
191            Self::LocalTime => "localtime",
192            Self::LocalDateTime => "localdatetime",
193            Self::DateTime => "datetime",
194        }
195    }
196
197    pub const fn has_date(self) -> bool {
198        !matches!(self, Self::LocalTime)
199    }
200
201    pub const fn has_time(self) -> bool {
202        !matches!(self, Self::Date)
203    }
204}
205
206/// The openCypher temporal functions HawDB evaluates.
207#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
208pub enum TemporalFunction {
209    /// `date()`, `localtime()`, `localdatetime()` or `datetime()`: the
210    /// statement clock without an argument, otherwise a string, map or
211    /// temporal conversion.
212    Construct(TemporalKind),
213    /// `duration(string|map)`.
214    Duration,
215    /// `duration.between(a, b)`.
216    DurationBetween,
217    /// `duration.inMonths(a, b)`.
218    DurationInMonths,
219    /// `duration.inDays(a, b)`.
220    DurationInDays,
221    /// `duration.inSeconds(a, b)`.
222    DurationInSeconds,
223    /// `date.truncate(unit, value)` and its siblings.
224    Truncate(TemporalKind),
225    /// `datetime.fromepoch(seconds, nanoseconds)`.
226    DateTimeFromEpoch,
227    /// `datetime.fromepochmillis(milliseconds)`.
228    DateTimeFromEpochMillis,
229}
230
231const KINDS: [TemporalKind; 4] = [
232    TemporalKind::Date,
233    TemporalKind::LocalTime,
234    TemporalKind::LocalDateTime,
235    TemporalKind::DateTime,
236];
237
238impl TemporalFunction {
239    /// Every function, for parser dispatch and exhaustive tests.
240    pub const ALL: [Self; 15] = [
241        Self::Construct(TemporalKind::Date),
242        Self::Construct(TemporalKind::LocalTime),
243        Self::Construct(TemporalKind::LocalDateTime),
244        Self::Construct(TemporalKind::DateTime),
245        Self::Duration,
246        Self::DurationBetween,
247        Self::DurationInMonths,
248        Self::DurationInDays,
249        Self::DurationInSeconds,
250        Self::Truncate(TemporalKind::Date),
251        Self::Truncate(TemporalKind::LocalTime),
252        Self::Truncate(TemporalKind::LocalDateTime),
253        Self::Truncate(TemporalKind::DateTime),
254        Self::DateTimeFromEpoch,
255        Self::DateTimeFromEpochMillis,
256    ];
257
258    /// Returns whether `name` (case-insensitive) is a temporal namespace that
259    /// may start a function call: `date`, `localtime`, `localdatetime`,
260    /// `datetime` or `duration`.
261    pub fn is_namespace(name: &str) -> bool {
262        KINDS
263            .iter()
264            .any(|kind| name.eq_ignore_ascii_case(kind.function_name()))
265            || name.eq_ignore_ascii_case("duration")
266    }
267
268    /// Resolves `namespace` or `namespace.member` case-insensitively.
269    pub fn from_name(namespace: &str, member: Option<&str>) -> Option<Self> {
270        Self::ALL.into_iter().find(|function| {
271            let (expected_namespace, expected_member) = function.name_parts();
272            namespace.eq_ignore_ascii_case(expected_namespace)
273                && match (member, expected_member) {
274                    (None, None) => true,
275                    (Some(member), Some(expected)) => member.eq_ignore_ascii_case(expected),
276                    _ => false,
277                }
278        })
279    }
280
281    const fn name_parts(self) -> (&'static str, Option<&'static str>) {
282        match self {
283            Self::Construct(kind) => (kind.function_name(), None),
284            Self::Duration => ("duration", None),
285            Self::DurationBetween => ("duration", Some("between")),
286            Self::DurationInMonths => ("duration", Some("inMonths")),
287            Self::DurationInDays => ("duration", Some("inDays")),
288            Self::DurationInSeconds => ("duration", Some("inSeconds")),
289            Self::Truncate(kind) => (kind.function_name(), Some("truncate")),
290            Self::DateTimeFromEpoch => ("datetime", Some("fromepoch")),
291            Self::DateTimeFromEpochMillis => ("datetime", Some("fromepochmillis")),
292        }
293    }
294
295    /// The canonical Cypher spelling, such as `duration.between`.
296    pub fn function_name(self) -> String {
297        match self.name_parts() {
298            (namespace, None) => namespace.to_string(),
299            (namespace, Some(member)) => format!("{namespace}.{member}"),
300        }
301    }
302
303    /// Inclusive minimum and maximum argument counts.
304    pub const fn arity(self) -> (usize, usize) {
305        match self {
306            Self::Construct(_) => (0, 1),
307            Self::Duration | Self::DateTimeFromEpochMillis => (1, 1),
308            Self::DurationBetween
309            | Self::DurationInMonths
310            | Self::DurationInDays
311            | Self::DurationInSeconds
312            | Self::Truncate(_)
313            | Self::DateTimeFromEpoch => (2, 2),
314        }
315    }
316
317    /// Whether a call with `argument_count` arguments reads the statement
318    /// clock (and therefore must not be cached or folded across statements).
319    pub const fn reads_clock(self, argument_count: usize) -> bool {
320        matches!(self, Self::Construct(_)) && argument_count == 0
321    }
322}
323
324/// Evaluates a temporal function. NULL arguments produce NULL, except that
325/// a missing argument to a constructor reads `now`.
326pub fn evaluate(
327    function: TemporalFunction,
328    arguments: &[Value],
329    now: OffsetDateTime,
330) -> TemporalResult<Value> {
331    let (min, max) = function.arity();
332    if !(min..=max).contains(&arguments.len()) {
333        return Err(TemporalError::new(format!(
334            "{}() expects {} argument(s), got {}",
335            function.function_name(),
336            if min == max {
337                min.to_string()
338            } else {
339                format!("{min} or {max}")
340            },
341            arguments.len()
342        )));
343    }
344    if arguments.iter().any(|value| matches!(value, Value::Null)) {
345        return Ok(Value::Null);
346    }
347    match function {
348        TemporalFunction::Construct(kind) => {
349            let now = now.checked_to_offset(UtcOffset::UTC).ok_or_else(|| {
350                TemporalError::new("statement clock UTC datetime is out of range")
351            })?;
352            construct(kind, arguments.first(), now)
353        }
354        TemporalFunction::Duration => construct::duration(&arguments[0]),
355        TemporalFunction::DurationBetween => {
356            between(&arguments[0], &arguments[1], arithmetic::BetweenMode::Full)
357        }
358        TemporalFunction::DurationInMonths => between(
359            &arguments[0],
360            &arguments[1],
361            arithmetic::BetweenMode::Months,
362        ),
363        TemporalFunction::DurationInDays => {
364            between(&arguments[0], &arguments[1], arithmetic::BetweenMode::Days)
365        }
366        TemporalFunction::DurationInSeconds => between(
367            &arguments[0],
368            &arguments[1],
369            arithmetic::BetweenMode::Seconds,
370        ),
371        TemporalFunction::Truncate(kind) => {
372            let Value::String(unit) = &arguments[0] else {
373                return Err(TemporalError::new(format!(
374                    "{}() unit must be a string",
375                    function.function_name()
376                )));
377            };
378            truncate(kind, unit, &arguments[1])
379        }
380        TemporalFunction::DateTimeFromEpoch => match (&arguments[0], &arguments[1]) {
381            (Value::Int(seconds), Value::Int(nanos)) => from_epoch(*seconds, *nanos),
382            _ => Err(TemporalError::new(
383                "datetime.fromepoch() expects integer seconds and nanoseconds",
384            )),
385        },
386        TemporalFunction::DateTimeFromEpochMillis => match &arguments[0] {
387            Value::Int(millis) => from_epoch_millis(*millis),
388            _ => Err(TemporalError::new(
389                "datetime.fromepochmillis() expects integer milliseconds",
390            )),
391        },
392    }
393}
394
395/// Returns whether `value` is a temporal instant or a duration.
396pub const fn is_temporal(value: &Value) -> bool {
397    matches!(
398        value,
399        Value::Date(_)
400            | Value::LocalTime(_)
401            | Value::LocalDateTime(_)
402            | Value::DateTime(_)
403            | Value::Duration(_)
404    )
405}
406
407/// The Cypher comparison order of two temporal values: `Some` for two
408/// instants of the same kind, `None` otherwise (including two durations,
409/// which openCypher leaves incomparable).
410///
411/// The result agrees with [`Value`]'s total order, so index range seeks and
412/// predicate evaluation select the same rows. Zoned datetimes compare by
413/// instant and then by offset.
414pub fn comparable_ordering(left: &Value, right: &Value) -> Option<Ordering> {
415    match (left, right) {
416        (Value::Date(left), Value::Date(right)) => Some(left.cmp(right)),
417        (Value::LocalTime(left), Value::LocalTime(right)) => Some(left.cmp(right)),
418        (Value::LocalDateTime(left), Value::LocalDateTime(right)) => Some(left.cmp(right)),
419        (Value::DateTime(left), Value::DateTime(right)) => Some(datetime_cmp(left, right)),
420        _ => None,
421    }
422}
423
424/// Whether `value`, as the argument of a temporal constructor, reads the
425/// statement clock: a map without keys other than `timezone`
426/// (`datetime({timezone: '+01:00'})`).
427pub fn is_clock_reading_map(value: &Value) -> bool {
428    matches!(value, Value::Map(map)
429        if map.keys().all(|key| key.eq_ignore_ascii_case("timezone")))
430}
431
432/// Whether `<`, `<=`, `>` and `>=` are undefined (NULL) for this pair:
433/// openCypher durations have no order because months and days have no
434/// fixed length. Other incomparable pairs keep HawDB's `false` result.
435pub const fn ordering_is_null(left: &Value, right: &Value) -> bool {
436    matches!((left, right), (Value::Duration(_), Value::Duration(_)))
437}
438
439/// Orders zoned datetimes by UTC instant, then by offset (east of UTC last),
440/// so that equal instants in different offsets remain distinct values.
441pub fn datetime_cmp(left: &OffsetDateTime, right: &OffsetDateTime) -> Ordering {
442    left.cmp(right).then_with(|| {
443        left.offset()
444            .whole_seconds()
445            .cmp(&right.offset().whole_seconds())
446    })
447}
448
449/// The tagged-JSON object keys used by bindings and developer JSON:
450/// `{"$date": "2026-10-30"}`, `{"$localtime": "12:00:00"}`,
451/// `{"$localdatetime": "2026-10-30T12:00:00"}`,
452/// `{"$datetime": "2026-10-30T12:00:00+02:00"}` and
453/// `{"$duration": "P1M2DT3.5S"}`. Payloads are ISO 8601 strings.
454pub const JSON_TAGS: [&str; 5] = [
455    "$date",
456    "$localtime",
457    "$localdatetime",
458    "$datetime",
459    "$duration",
460];
461
462/// The tagged-JSON key of a temporal value; its payload is `value.to_string()`.
463pub const fn json_tag(value: &Value) -> Option<&'static str> {
464    Some(match value {
465        Value::Date(_) => JSON_TAGS[0],
466        Value::LocalTime(_) => JSON_TAGS[1],
467        Value::LocalDateTime(_) => JSON_TAGS[2],
468        Value::DateTime(_) => JSON_TAGS[3],
469        Value::Duration(_) => JSON_TAGS[4],
470        _ => return None,
471    })
472}
473
474/// Parses the payload of a tagged-JSON temporal value, or returns `None`
475/// when `tag` is not a temporal tag.
476pub fn from_json_tag(tag: &str, text: &str) -> Option<TemporalResult<Value>> {
477    Some(match tag {
478        "$date" => parse_date(text).map(Value::Date),
479        "$localtime" => parse_local_time(text).map(Value::LocalTime),
480        "$localdatetime" => parse_local_datetime(text).map(Value::LocalDateTime),
481        "$datetime" => parse_datetime(text).map(Value::DateTime),
482        "$duration" => parse_duration(text).map(Value::duration),
483        _ => return None,
484    })
485}
486
487thread_local! {
488    static STATEMENT_CLOCK: Cell<Option<OffsetDateTime>> = const { Cell::new(None) };
489}
490
491/// The instant that clock-reading temporal functions observe: the pinned
492/// statement clock, or the system clock when none is pinned.
493pub fn statement_now() -> OffsetDateTime {
494    STATEMENT_CLOCK.with(Cell::get).unwrap_or_else(system_now)
495}
496
497fn system_now() -> OffsetDateTime {
498    let nanos = crate::time::SystemTime::now()
499        .duration_since(crate::time::UNIX_EPOCH)
500        .map(|duration| duration.as_nanos().min(i64::MAX as u128) as i64)
501        .unwrap_or(0);
502    datetime_from_nanos(nanos)
503}
504
505/// Runs `f` with the statement clock pinned to `instant` on this thread.
506/// The previous pin is restored afterwards, also on unwind.
507///
508/// # Panics
509/// Panics if `instant` has no representable UTC calendar value.
510pub fn with_statement_clock<R>(instant: OffsetDateTime, f: impl FnOnce() -> R) -> R {
511    struct Restore(Option<OffsetDateTime>);
512    impl Drop for Restore {
513        fn drop(&mut self) {
514            STATEMENT_CLOCK.with(|clock| clock.set(self.0));
515        }
516    }
517    let _restore = Restore(
518        STATEMENT_CLOCK.with(|clock| clock.replace(Some(instant.to_offset(UtcOffset::UTC)))),
519    );
520    f()
521}
522
523/// Runs `f` with one stable statement clock: an existing pin (for example a
524/// test clock) is kept, otherwise the system clock is read once and pinned.
525pub fn with_stable_statement_clock<R>(f: impl FnOnce() -> R) -> R {
526    if STATEMENT_CLOCK.with(Cell::get).is_some() {
527        return f();
528    }
529    with_statement_clock(system_now(), f)
530}
531
532/// The statement clock pinned on this thread, if any. Work handed to another
533/// thread re-pins it there with [`with_optional_statement_clock`], so that
534/// parallel workers observe the statement's instant too.
535pub fn pinned_statement_clock() -> Option<OffsetDateTime> {
536    STATEMENT_CLOCK.with(Cell::get)
537}
538
539/// Runs `f` with the statement clock pinned to `instant` when it is `Some`,
540/// and with this thread's current clock otherwise.
541pub fn with_optional_statement_clock<R>(
542    instant: Option<OffsetDateTime>,
543    f: impl FnOnce() -> R,
544) -> R {
545    match instant {
546        Some(instant) => with_statement_clock(instant, f),
547        None => f(),
548    }
549}
550
551#[cfg(test)]
552mod tests;