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