Skip to main content

relate_core/temporal/
construct.rs

1//! Construction of temporal values from components and maps. The
2//! zone-resolution cluster lives in [`super::zone`] (ADR-0340), the
3//! truncation cluster in [`super::truncate`], and the CIP-223 pattern
4//! formatter in [`super::format`].
5
6use chrono::{
7    Datelike, Days, Duration as ChronoDur, NaiveDate, NaiveDateTime, NaiveTime, Timelike, Weekday,
8};
9
10use crate::{bare_type_name, Error, Result, Value};
11
12use super::clock::now_value;
13use super::clock::{self, ClockKind};
14use super::exact::{exact_number, DurationTiers, ExactNumber};
15use super::field::DurationLane;
16use super::field_rules::{
17    self, DateForm, EpochField, Fields, Sources, DAY_OF_QUARTER_KEYS, DAY_OF_WEEK_KEYS,
18    EPOCH_MILLIS_KEYS, EPOCH_SECONDS_KEYS, ORDINAL_DAY_KEYS,
19};
20use super::parse::{parse_iso, parse_pattern};
21use super::zone::{add_offset, apply_timezone, offset_from_map, IanaAt, ResolvedZone};
22use super::{
23    checked_lane, weekday_from_i, DurationField, Temporal, MONTHS_PER_QUARTER, NANOS_PER_SECOND,
24};
25
26/// The integer a temporal component map holds under `k`, or `None` when the
27/// field is absent or null. A present non-integer is Neo4j's 22G06
28/// non-assignable component (an `ArgumentError`): an integer-typed component
29/// map never reads a float/string/bool/list value as an absent field. Null is
30/// ignored, as Neo4j filters null-valued fields before constructing.
31pub(super) fn map_int(map: &Fields, k: &str) -> Result<Option<i64>> {
32    match map.get(k) {
33        None | Some(Value::Null) => Ok(None),
34        Some(Value::Int(v)) => Ok(Some(*v)),
35        Some(other) => Err(Error::argument_error(format!(
36            "cannot assign '{k}' of a {}",
37            bare_type_name(other)
38        ))),
39    }
40}
41
42/// [`map_int`] narrowed to the bounded integer a component stores (`u32` for
43/// a date/time field, `i32` for a calendar year). The one home of the
44/// conversion and its typed out-of-range error.
45pub(super) fn map_int_bounded<T>(map: &Fields, k: &str, msg: &str) -> Result<Option<T>>
46where
47    T: TryFrom<i64>,
48{
49    map_int(map, k)?
50        .map(|value| T::try_from(value).map_err(|_| Error::argument_error(msg)))
51        .transpose()
52}
53
54/// The first present spelling of a multi-spelling field (`dayOfWeek`/
55/// `dayofweek`), validated through [`map_int`]. The first spelling keeps the
56/// documented precedence when both are present.
57pub(super) fn map_int_alias(map: &Fields, keys: &[&str]) -> Result<Option<i64>> {
58    for key in keys {
59        if let Some(value) = map_int(map, key)? {
60            return Ok(Some(value));
61        }
62    }
63    Ok(None)
64}
65
66/// `(epoch seconds, subsecond nanos)` named by the epoch field `field` —
67/// the field [`field_rules::validate_epoch`] selected, read through its own
68/// key family, so the validator and the reader cannot disagree about which
69/// field names the instant.
70fn epoch_from_map(m: &Fields, field: EpochField) -> Result<(i64, u32)> {
71    // The validator proved one spelling carries a non-null value; the alias
72    // reader keeps the first-spelling precedence and the 22G06 rejection for
73    // a non-integer.
74    let value = map_int_alias(m, field.keys())?
75        .ok_or_else(|| Error::argument_error(format!("{} must be an integer", field.name())))?;
76    Ok(field.split(value))
77}
78
79/// The UTC naive datetime the selected epoch field names. Epoch fields are
80/// instants on the UTC timeline by definition, so the conversion itself
81/// needs no zone.
82fn epoch_utc_dt(m: &Fields, field: EpochField) -> Result<NaiveDateTime> {
83    let (secs, nanos) = epoch_from_map(m, field)?;
84    // `split` answers nanos already in `0..=999_999_999`, so no clamp or
85    // unchecked cast is needed here.
86    chrono::DateTime::from_timestamp(secs, nanos)
87        .map(|d| d.naive_utc())
88        .ok_or_else(|| Error::argument_error("epoch out of range"))
89}
90
91pub(super) fn date_from_parts(year: i32, month: u32, day: u32) -> Result<NaiveDate> {
92    NaiveDate::from_ymd_opt(year, month, day).ok_or_else(|| Error::argument_error("invalid date"))
93}
94
95pub(super) fn date_from_week(year: i32, week: u32, dow: Weekday) -> Result<NaiveDate> {
96    // chrono's `from_isoywd_opt` computes `year ± 1` internally *before* its
97    // range guard, so i32-extreme years (reachable here from week-date
98    // strings, e.g. '2147483647W526') panic inside chrono. Restrict to
99    // chrono's range ±1: the internal `year ± 1` then stays within i32 and
100    // any genuinely out-of-range result still returns `None`.
101    if !(-262_144..=262_144).contains(&year) {
102        return Err(Error::argument_error("invalid week date"));
103    }
104    NaiveDate::from_isoywd_opt(year, week, dow)
105        .ok_or_else(|| Error::argument_error("invalid week date"))
106}
107
108/// Whether `name` is a temporal constructor spelling [`construct_named`]
109/// builds values from — a clock kind ([`ClockKind::from_name`], which reads
110/// the canonical kind table) or `duration`, the one non-clock constructor.
111/// The one predicate the front-end's dialect gate and literal folding and
112/// the executor's scan-predicate specialization consult, so none can
113/// recognize a name the shared policy would not construct. The alias
114/// spellings (`local_time`, …) canonicalize inside; the clock-access
115/// spellings are not constructors of arguments at all.
116pub fn is_constructor(name: &str) -> bool {
117    let canon = canonical(name);
118    canon == "duration" || ClockKind::from_name(&canon).is_some()
119}
120
121/// The one name canonicalization both readers share: every spelling is
122/// case-folded and mapped to the base constructor it stands for.
123/// [`is_constructor`] recognizes only the base and alias spellings, so every name
124/// comparison goes through here first — [`accepts_pattern`] and
125/// [`construct_named`] cannot disagree on a spelling.
126fn canonical(name: &str) -> String {
127    match name.to_ascii_lowercase().as_str() {
128        "local_time" => "localtime".to_string(),
129        "local_datetime" | "local_date_time" => "localdatetime".to_string(),
130        "zoned_time" => "time".to_string(),
131        "zoned_datetime" | "zoned_date_time" => "datetime".to_string(),
132        other => other.to_string(),
133    }
134}
135
136/// Whether `name` accepts the CIP-228 `(value, pattern)` form — every
137/// constructor does, so this is [`is_constructor`], the one vocabulary
138/// predicate.
139pub fn accepts_pattern(name: &str) -> bool {
140    is_constructor(name)
141}
142
143/// The three shapes a temporal constructor's map argument can take.
144enum MapForm {
145    /// An epoch field (`epochMillis`/`epochSeconds`) names an instant on the
146    /// UTC timeline.
147    Epoch,
148    /// The map's only constructor-relevant entry is a `timezone`: the
149    /// clock-reading form.
150    Clock,
151    /// Component fields — the field constructors' map.
152    Fields,
153}
154
155/// The one map-shape classifier, consulted once per constructor call. Its
156/// positive rules are the readers' own vocabulary — the epoch fields, the
157/// `timezone` selector, and (by exclusion) the component fields — so no
158/// second field list can drift from them. A map carrying an epoch field
159/// alongside `timezone` stays the epoch form; null-valued entries are
160/// ignored, as every field reader ignores them, so a null epoch spelling
161/// neither selects the epoch form nor hides the component fields beside it.
162/// A null `timezone` keeps the clock form so it is rejected as a timezone
163/// rather than read as an absent field.
164fn map_form(m: &Fields) -> MapForm {
165    if field_rules::present_alias(m, EPOCH_MILLIS_KEYS)
166        || field_rules::present_alias(m, EPOCH_SECONDS_KEYS)
167    {
168        return MapForm::Epoch;
169    }
170    if m.contains_key("timezone")
171        && m.iter()
172            .all(|(key, value)| key == "timezone" || value.is_null())
173    {
174        return MapForm::Clock;
175    }
176    MapForm::Fields
177}
178
179/// Whether a constructor argument is the clock-reading map form. The
180/// literal fold consults this: a clock reading samples the clock, so folding
181/// it would bake a lowering-time instant into the plan.
182pub fn samples_clock(arg: &Value) -> bool {
183    matches!(arg, Value::Map(m) if matches!(map_form(m), MapForm::Clock))
184}
185
186/// The map-argument policy for a clock-capable kind: an epoch field names
187/// an instant, a timezone-only map is the clock reading, every other map is
188/// the component-field map.
189fn construct_map(kind: ClockKind, m: &Fields) -> Result<Temporal> {
190    match map_form(m) {
191        MapForm::Epoch => epoch_map(kind, m),
192        MapForm::Clock => clock::clock_from_map(kind, m),
193        MapForm::Fields => {
194            let validated = field_rules::validate(kind, m)?;
195            field_map(kind, m, &validated)
196        }
197    }
198}
199
200/// The epoch map form: the instant the epoch field names, then every other
201/// component field applied over its wall clock in the resolved zone. The
202/// component-field policy is the one that reads those overrides, so the
203/// validator's "component fields and `timezone` stay legal overrides"
204/// contract and the reader cannot diverge (Neo4j-verified:
205/// `datetime({epochSeconds: 0, year: 2020})` is `2020-01-01T00:00Z`, and
206/// `{epochMillis: 0, minute: 5, timezone: '+02:00'}` is
207/// `1970-01-01T02:05+02:00`).
208fn epoch_map(kind: ClockKind, m: &Fields) -> Result<Temporal> {
209    let field = field_rules::validate_epoch(kind, m)?;
210    let utc = epoch_utc_dt(m, field)?;
211    let resolved = offset_from_map(m, IanaAt::Utc(utc))?;
212    // The instant's wall clock in the resolved zone is this map's source
213    // date/time; the epoch spellings are replaced by it and every other key
214    // (component fields, `timezone`) is carried through unchanged.
215    let mut component_map: Fields = m
216        .iter()
217        .filter(|(key, _)| !field_rules::is_epoch_field(key))
218        .map(|(key, value)| (key.clone(), value.clone()))
219        .collect();
220    component_map.insert(
221        "datetime".into(),
222        Value::Temporal(clock::zoned(utc, resolved)),
223    );
224    let validated = field_rules::validate(kind, &component_map)?;
225    field_map(kind, &component_map, &validated)
226}
227
228/// The component-field map constructor for `kind` — the map path for maps
229/// [`map_form`] classified as [`MapForm::Fields`] (and the epoch form, once
230/// its instant is the map's source), after [`field_rules::validate`] admitted
231/// the field set and resolved its form and sources.
232fn field_map(
233    kind: ClockKind,
234    m: &Fields,
235    validated: &field_rules::Validated<'_>,
236) -> Result<Temporal> {
237    let form = validated.form;
238    let sources = &validated.sources;
239    Ok(match kind {
240        ClockKind::Date => Temporal::Date(date_from_map(m, form, sources.date)?),
241        ClockKind::LocalTime => Temporal::LocalTime(time_from_map(m, sources)?),
242        ClockKind::Time => {
243            let time = time_from_map(m, sources)?;
244            // A `time` map has no date fields (`accepts` rejects them), so
245            // the date comes from a zoned `time` source or the epoch default.
246            let date = match sources.time {
247                Some(Temporal::DateTime { utc, offset, .. }) => add_offset(*utc, *offset)?.date(),
248                _ => date_from_parts(1970, 1, 1)?,
249            };
250            let (utc, resolved) = apply_timezone(date.and_time(time), m)?;
251            time_wall_clock(utc, resolved.offset)?
252        }
253        ClockKind::LocalDateTime => Temporal::LocalDateTime(
254            date_from_map(m, form, sources.date)?.and_time(time_from_map(m, sources)?),
255        ),
256        ClockKind::DateTime => {
257            let local = date_from_map(m, form, sources.date)?.and_time(time_from_map(m, sources)?);
258            let (utc, resolved) = apply_timezone(local, m)?;
259            clock::zoned(utc, resolved)
260        }
261    })
262}
263
264/// The one constructor entry: the clock reading (`None`), the value
265/// construction (`Some`), or the map policy — the five kinds differ only in
266/// the vocabulary the kind supplies.
267fn construct(kind: ClockKind, arg: Option<&Value>) -> Result<Temporal> {
268    match arg {
269        None => Ok(now_value(kind)),
270        Some(Value::String(value)) => parse_iso(kind.name(), value),
271        // A duration is not a temporal source any clock constructor accepts:
272        // Neo4j reports it as an invalid call signature (42001), not as a
273        // value-conversion failure.
274        Some(Value::Temporal(Temporal::Duration { .. })) => Err(Error::syntax(format!(
275            "Invalid call signature: {}() does not accept a duration",
276            kind.name()
277        ))),
278        Some(Value::Temporal(value)) => temporal_of(kind, value),
279        Some(Value::Map(m)) => construct_map(kind, m),
280        Some(_) => Err(Error::syntax(format!(
281            "Invalid call signature: {}()",
282            kind.name()
283        ))),
284    }
285}
286
287/// The value conversion each kind applies to an existing temporal (`date(x)`,
288/// `time(x)`, …). `datetime` keeps a zoned source verbatim; `time` keeps the
289/// source's offset where it carries one. A source without the part a kind
290/// needs is a typed rejection (`datetime(date(…))`, `date(localtime(…))`).
291fn temporal_of(kind: ClockKind, value: &Temporal) -> Result<Temporal> {
292    Ok(match kind {
293        ClockKind::Date => Temporal::Date(date_of(value)?),
294        ClockKind::Time => {
295            let time = time_of(value).ok_or_else(|| Error::ty("cannot convert to time"))?;
296            let offset = match value {
297                Temporal::Time { offset, .. } | Temporal::DateTime { offset, .. } => *offset,
298                _ => 0,
299            };
300            Temporal::Time { time, offset }
301        }
302        ClockKind::LocalTime => time_of(value)
303            .map(Temporal::LocalTime)
304            .ok_or_else(|| Error::ty("cannot convert to localtime"))?,
305        // Every dated-and-timed source reads as its local wall clock; a
306        // source without both halves is the typed rejection.
307        ClockKind::LocalDateTime => match value {
308            Temporal::LocalDateTime(_)
309            | Temporal::CivilDateTime { .. }
310            | Temporal::DateTime { .. } => Temporal::LocalDateTime(local_dt_of(value)?),
311            _ => return Err(Error::ty("cannot convert to localdatetime")),
312        },
313        ClockKind::DateTime => match value {
314            Temporal::DateTime { .. } => value.clone(),
315            Temporal::LocalDateTime(_) | Temporal::CivilDateTime { .. } => {
316                clock::zoned(local_dt_of(value)?, ResolvedZone::utc())
317            }
318            _ => return Err(Error::ty("cannot convert to datetime")),
319        },
320    })
321}
322
323/// A constructor call with more than the two arguments the grammar
324/// defines. The message follows the executor's `invalid_arity` shape
325/// (`InvalidNumberOfArguments: <name>() requires <range>`); it is spelled
326/// here because core cannot call that helper (the dependency points the
327/// other way).
328fn too_many_arguments(name: &str, got: usize) -> Error {
329    Error::syntax(format!(
330        "InvalidNumberOfArguments: {name}() requires zero to two arguments, got {got}"
331    ))
332}
333
334/// The one name-keyed temporal construction policy: the spelling
335/// canonicalization (`local_time` → `localtime`, …), the two-argument
336/// `value, pattern` form, and the base constructors — shared by the
337/// executor's builtin dispatch, the scan-predicate specialization, and
338/// the front-end's literal folding, so no two of them can disagree on
339/// what `date("…")` means. Callers passing zero arguments get the clock
340/// reading (`QueryClockGuard` pins it per statement).
341pub fn construct_named(name: &str, vals: &[Value]) -> Result<Value> {
342    let canon = canonical(name);
343    match vals {
344        // The clock reading: the base constructor with no argument.
345        [] => base_value(&canon, None),
346        [Value::Null] => Ok(Value::Null),
347        [value] => base_value(&canon, Some(value)),
348        // CIP-228 `(value, pattern)`: a null on either side constructs null.
349        [value, pattern] => match (value, pattern) {
350            (Value::Null, _) | (_, Value::Null) => Ok(Value::Null),
351            (Value::String(value), Value::String(pattern)) => {
352                Ok(Value::Temporal(parse_pattern(&canon, value, pattern)?))
353            }
354            (Value::String(_), _) => Err(Error::invalid_argument_type("temporal pattern")),
355            _ => Err(Error::invalid_argument_type("temporal value")),
356        },
357        // Every other arity is the typed arity rejection, never a silent
358        // construction from the first argument.
359        _ => Err(too_many_arguments(name, vals.len())),
360    }
361}
362
363/// The zero/one-argument construction: a clock kind through the one
364/// [`construct`] entry, `duration` through its own ISO/map constructor.
365fn base_value(canon: &str, arg: Option<&Value>) -> Result<Value> {
366    match ClockKind::from_name(canon) {
367        Some(kind) => construct(kind, arg).map(Value::Temporal),
368        None if canon == "duration" => construct_duration(arg).map(Value::Temporal),
369        None => Err(Error::ty("unknown temporal constructor")),
370    }
371}
372
373pub fn construct_date(arg: Option<&Value>) -> Result<Temporal> {
374    construct(ClockKind::Date, arg)
375}
376
377/// The calendar date a value reads as. A civil datetime's date is outside
378/// chrono's range by construction (that is why it is civil), so the reader
379/// answers the authored unreadable-source rejection rather than a generic
380/// conversion failure.
381pub(super) fn date_of(t: &Temporal) -> Result<NaiveDate> {
382    match t {
383        Temporal::Date(d) => Ok(*d),
384        Temporal::CivilDate { year, month, day } => {
385            // `as i32` would wrap extreme civil years into chrono range;
386            // convert honestly so only representable years can succeed.
387            let year =
388                i32::try_from(*year).map_err(|_| Error::ty("civil date out of chrono range"))?;
389            NaiveDate::from_ymd_opt(year, *month, *day)
390                .ok_or_else(|| Error::ty("civil date out of chrono range"))
391        }
392        Temporal::LocalDateTime(dt) => Ok(dt.date()),
393        Temporal::CivilDateTime { .. } => Err(field_rules::cannot_get_temporal("date", t)),
394        Temporal::DateTime { utc, offset, .. } => Ok(add_offset(*utc, *offset)?.date()),
395        _ => Err(Error::ty("cannot convert to date")),
396    }
397}
398
399/// The date a component map names, reading the fields of the form
400/// [`field_rules::validate`] resolved — so presence is decided once, and a
401/// null-valued form field cannot select a form here that the validator
402/// ignored (or vice versa). `source` is the validated `date`/`datetime`
403/// source temporal, supplying every form's defaults.
404fn date_from_map(
405    m: &Fields,
406    form: Option<DateForm>,
407    source: Option<&Temporal>,
408) -> Result<NaiveDate> {
409    let source = source.map(date_of).transpose()?;
410    match form {
411        Some(DateForm::Week) => week_from_map(m, source),
412        Some(DateForm::Ordinal) => ordinal_from_map(m, source),
413        Some(DateForm::Quarter) => quarter_from_map(m, source),
414        Some(DateForm::Calendar) | None => calendar_from_map(m, source),
415    }
416}
417
418/// The `year` field, else the source date's calendar year, else zero (the
419/// documented default of an unset year).
420fn year_from_map(m: &Fields, source: Option<NaiveDate>) -> Result<i32> {
421    Ok(map_int_bounded(m, "year", "invalid date")?
422        .or_else(|| source.map(|d| d.year()))
423        .unwrap_or(0))
424}
425
426/// The calendar form (`month`/`day` over the source date).
427fn calendar_from_map(m: &Fields, source: Option<NaiveDate>) -> Result<NaiveDate> {
428    let year = year_from_map(m, source)?;
429    let month = map_int_bounded(m, "month", "invalid date")?
430        .or_else(|| source.map(|d| d.month()))
431        .unwrap_or(1);
432    let day = map_int_bounded(m, "day", "invalid date")?
433        .or_else(|| source.map(|d| d.day()))
434        .unwrap_or(1);
435    date_from_parts(year, month, day)
436}
437
438/// The week form: the ISO week-year and weekday the source date falls in,
439/// overridden by the map's own `year`/`week`/`dayOfWeek`.
440fn week_from_map(m: &Fields, source: Option<NaiveDate>) -> Result<NaiveDate> {
441    let (default_year, default_week, default_dow) = match source {
442        Some(d) => (
443            d.iso_week().year(),
444            d.iso_week().week(),
445            i64::from(d.weekday().number_from_monday()),
446        ),
447        None => (0, 1, 1),
448    };
449    let year = map_int_bounded(m, "year", "invalid date")?.unwrap_or(default_year);
450    let week = map_int_bounded(m, "week", "invalid date")?.unwrap_or(default_week);
451    let dow = map_int_alias(m, DAY_OF_WEEK_KEYS)?.unwrap_or(default_dow);
452    date_from_week(year, week, weekday_from_i(dow))
453}
454
455/// The ordinal form: `year` plus `ordinalDay`.
456fn ordinal_from_map(m: &Fields, source: Option<NaiveDate>) -> Result<NaiveDate> {
457    let year = year_from_map(m, source)?;
458    // The ordinal form is selected by `ordinalDay` itself, so the non-null
459    // integer the validator admitted is what is read here.
460    let ordinal = map_int_alias(m, ORDINAL_DAY_KEYS)?
461        .expect("the ordinal form implies a non-null ordinalDay");
462    let ordinal = u32::try_from(ordinal).map_err(|_| Error::argument_error("invalid date"))?;
463    NaiveDate::from_yo_opt(year, ordinal).ok_or_else(|| Error::argument_error("invalid date"))
464}
465
466/// The quarter form: an optional `quarter` (defaulting to the source date's
467/// month, or January) and an optional `dayOfQuarter`.
468fn quarter_from_map(m: &Fields, source: Option<NaiveDate>) -> Result<NaiveDate> {
469    let year = year_from_map(m, source)?;
470    let default_month = source.map(|d| d.month()).unwrap_or(1);
471    let quarter = map_int(m, "quarter")?.unwrap_or_else(|| i64::from((default_month - 1) / 3 + 1));
472    // Quarter-of-year math on a user-controlled i64: compute in i128 and
473    // error on anything out of range instead of wrapping a u32. A quarter
474    // outside 1..=4, or `quarter: 0` (whose first month is not a month),
475    // reaches the typed `invalid date` error — never a silent clamp.
476    let quarter_month = |moq: u32| -> Result<u32> {
477        let month = (i128::from(quarter) - 1) * MONTHS_PER_QUARTER + i128::from(moq);
478        u32::try_from(month).map_err(|_| Error::argument_error("invalid date"))
479    };
480    let Some(day_of_quarter) = map_int_alias(m, DAY_OF_QUARTER_KEYS)? else {
481        // The month within the quarter keeps the source date's position, and
482        // its day of month carries over unchanged.
483        let moq = (default_month.saturating_sub(1) % 3) + 1;
484        let day = source.map(|d| d.day()).unwrap_or(1);
485        return date_from_parts(year, quarter_month(moq)?, day);
486    };
487    let dq = u32::try_from(day_of_quarter)
488        .ok()
489        .filter(|dq| *dq >= 1)
490        .ok_or_else(|| Error::argument_error("invalid date"))?;
491    let start = date_from_parts(year, quarter_month(1)?, 1)?;
492    start
493        .checked_add_days(Days::new(u64::from(dq - 1)))
494        .ok_or_else(|| Error::argument_error("invalid date"))
495}
496
497fn time_from_map(m: &Fields, sources: &Sources<'_>) -> Result<NaiveTime> {
498    // An embedded `time`/`datetime` value supplies the base clock; a map
499    // without one starts at midnight.
500    let base = sources.time.and_then(time_of).unwrap_or(NaiveTime::MIN);
501    time_from_map_with_base(base, m)
502}
503
504/// The time of day a component map names, overridden field by field on top
505/// of `base`. One override block shared by construction (base midnight or an
506/// embedded temporal) and truncation (base the truncated input's time).
507pub(super) fn time_from_map_with_base(base: NaiveTime, m: &Fields) -> Result<NaiveTime> {
508    let hour = map_int_bounded(m, "hour", "invalid time")?.unwrap_or(base.hour());
509    let minute = map_int_bounded(m, "minute", "invalid time")?.unwrap_or(base.minute());
510    let second = map_int_bounded(m, "second", "invalid time")?.unwrap_or(base.second());
511    let nano = nano_with_subsecond_fields(base.nanosecond(), m)?;
512    NaiveTime::from_hms_nano_opt(hour, minute, second, nano)
513        .ok_or_else(|| Error::argument_error("invalid time"))
514}
515
516/// The upper bound (exclusive) each sub-second field accepts in the map
517/// constructors. The finer fields' bounds narrow when a coarser sibling is
518/// present: `millisecond` always stops at 1000, `microsecond` at 1000 when
519/// milliseconds are supplied (else 1_000_000), and `nanosecond` at 1000 when
520/// microseconds are supplied, else 1_000_000 when milliseconds are, else
521/// 1_000_000_000. That is Neo4j's `validNano` rule, and the one place it is
522/// stated.
523fn subsecond_bound(coarser_present: bool, when_coarser: i64, otherwise: i64) -> i64 {
524    if coarser_present {
525        when_coarser
526    } else {
527        otherwise
528    }
529}
530
531/// Sum the subsecond map fields (`millisecond`/`microsecond`/`nanosecond`)
532/// into a nanosecond count, validating each field against its own range
533/// ([`subsecond_bound`]). A negative or over-range field is Neo4j's 22N03
534/// numeric-out-of-range error, never a wrapped contribution. The accumulation
535/// stays in i128 because the three i64 fields are user-controlled.
536fn nano_with_subsecond_fields(base: u32, m: &Fields) -> Result<u32> {
537    let millisecond = map_int(m, "millisecond")?;
538    let microsecond = map_int(m, "microsecond")?;
539    let nanosecond = map_int(m, "nanosecond")?;
540    let check = |field: &str, value: i64, bound: i64| -> Result<i64> {
541        if (0..bound).contains(&value) {
542            Ok(value)
543        } else {
544            Err(Error::argument_error(format!(
545                "specified numeric value out of range: expected {field} in the range 0 to {} but found {value}",
546                bound - 1
547            )))
548        }
549    };
550    let mut total = i128::from(base);
551    if let Some(ms) = millisecond {
552        total += i128::from(check("millisecond", ms, 1_000)?) * 1_000_000;
553    }
554    if let Some(us) = microsecond {
555        let bound = subsecond_bound(millisecond.is_some(), 1_000, 1_000_000);
556        total += i128::from(check("microsecond", us, bound)?) * 1_000;
557    }
558    if let Some(ns) = nanosecond {
559        let millis_bound = subsecond_bound(millisecond.is_some(), 1_000_000, 1_000_000_000);
560        let bound = subsecond_bound(microsecond.is_some(), 1_000, millis_bound);
561        total += i128::from(check("nanosecond", ns, bound)?);
562    }
563    let nanos = u32::try_from(total).map_err(|_| Error::argument_error("invalid time"))?;
564    // Chrono encodes a leap second as second 59 with a fraction >= 1e9 (up
565    // to 1_999_999_999) — the encoding `truncate_time` and its test
566    // deliberately preserve. The base can carry that encoding (an embedded
567    // time or an extras map reading an existing value); the user fields
568    // cannot reach 1e9 on their own (each component check bounds them and
569    // the bounds tighten when a coarser field is present), so the full
570    // representable range round-trips and only a genuinely over-range sum
571    // errors.
572    if nanos >= 2_000_000_000 {
573        return Err(Error::argument_error("invalid time"));
574    }
575    Ok(nanos)
576}
577
578/// The time of day a value reads as, or `None` when it carries none. The
579/// proleptic civil datetime answers its own wall clock, the same value
580/// [`Temporal::has_time`] admits.
581pub(super) fn time_of(t: &Temporal) -> Option<NaiveTime> {
582    match t {
583        Temporal::LocalTime(t) | Temporal::Time { time: t, .. } => Some(*t),
584        Temporal::LocalDateTime(dt) => Some(dt.time()),
585        Temporal::CivilDateTime { time, .. } => Some(*time),
586        Temporal::DateTime { utc, offset, .. } => utc
587            .checked_add_signed(ChronoDur::seconds(i64::from(*offset)))
588            .map(|local| local.time()),
589        _ => None,
590    }
591}
592
593pub fn construct_localtime(arg: Option<&Value>) -> Result<Temporal> {
594    construct(ClockKind::LocalTime, arg)
595}
596
597pub fn construct_time(arg: Option<&Value>) -> Result<Temporal> {
598    construct(ClockKind::Time, arg)
599}
600
601/// The wall-clock `Temporal::Time` of the UTC instant `utc` read at
602/// `offset` — the shared tail of `construct_time`'s epoch and field-map
603/// paths (F-1-20).
604fn time_wall_clock(utc: NaiveDateTime, offset: i32) -> Result<Temporal> {
605    let wall = add_offset(utc, offset)?;
606    Ok(Temporal::Time {
607        time: wall.time(),
608        offset,
609    })
610}
611
612pub fn construct_localdatetime(arg: Option<&Value>) -> Result<Temporal> {
613    construct(ClockKind::LocalDateTime, arg)
614}
615
616pub(super) fn local_dt_of(t: &Temporal) -> Result<NaiveDateTime> {
617    match t {
618        Temporal::LocalDateTime(dt) => Ok(*dt),
619        Temporal::Date(d) => Ok(d.and_time(NaiveTime::MIN)),
620        Temporal::DateTime { utc, offset, .. } => add_offset(*utc, *offset),
621        _ => Err(Error::ty("cannot convert to localdatetime")),
622    }
623}
624
625pub fn construct_datetime(arg: Option<&Value>) -> Result<Temporal> {
626    construct(ClockKind::DateTime, arg)
627}
628
629pub fn construct_duration(arg: Option<&Value>) -> Result<Temporal> {
630    match arg {
631        Some(Value::String(s)) => parse_iso("duration", s),
632        Some(Value::Temporal(t @ Temporal::Duration { .. })) => Ok(t.clone()),
633        Some(Value::Map(m)) => duration_from_map(m),
634        _ => Err(Error::syntax("Invalid call signature: duration()")),
635    }
636}
637
638/// The duration a component map names. Every map key that names a duration
639/// field contributes through the one field table (`DurationField::from_map_key`);
640/// null fields are ignored, as Neo4j filters them before constructing, and a
641/// map with no non-null field names no unit (22N30). Integer-only maps take
642/// the exact i64 lane arithmetic; any float sends the whole map through the
643/// approximate f64 cascade, matching Neo4j's all-integral-values split.
644fn duration_from_map(m: &Fields) -> Result<Temporal> {
645    let mut values: std::collections::BTreeMap<DurationField, ExactNumber> =
646        std::collections::BTreeMap::new();
647    for (key, value) in m.iter().filter(|(_, value)| !value.is_null()) {
648        // A non-null field no duration unit names is Neo4j's
649        // `Unknown field: foo`; a null one was filtered above, like every
650        // other null field.
651        let field = DurationField::from_map_key(key)
652            .ok_or_else(|| Error::ty(format!("Unknown field: {key}")))?;
653        values.insert(field, exact_number(key, value)?);
654    }
655    if values.is_empty() {
656        return Err(field_rules::at_least_one_unit());
657    }
658    // Integer-only maps take the lane arithmetic; the all-integral split is
659    // taken once, here, so the lane sum never re-checks it.
660    let integers: Option<std::collections::BTreeMap<DurationField, i128>> = values
661        .iter()
662        .map(|(field, number)| number.as_int().map(|n| (*field, n)))
663        .collect();
664    if let Some(integers) = integers {
665        return integral_duration(&integers);
666    }
667    let mut tiers = DurationTiers::default();
668    for (field, number) in &values {
669        let slot = field.slot(&mut tiers);
670        slot.accumulator.add(*number, slot.scale)?;
671    }
672    let (months, days, nanos) = tiers.finish()?;
673    Temporal::duration_checked(months, days, nanos)
674}
675
676/// Build a duration from integer map fields through Neo4j's lane arithmetic:
677/// years/months, weeks/days, hours/minutes/seconds and the three sub-second
678/// fields each sum in one lane, then each lane is narrowed to i64 (22N28 on
679/// overflow) and the assembled value goes through [`Temporal::duration_checked`],
680/// the one representability seam every producer shares. Sub-second nanos fold
681/// into the seconds lane for that bound; the stored value keeps the exact i128
682/// nanosecond total.
683fn integral_duration(values: &std::collections::BTreeMap<DurationField, i128>) -> Result<Temporal> {
684    // Every lane is summed from the one field table
685    // ([`DurationField::lane_and_unit`], walked in cascade order), so a
686    // field added to the vocabulary cannot be dropped from a lane. An absent
687    // field contributes zero. The nanosecond tier splits at whole seconds: its
688    // seconds lane counts in seconds, its sub-second lane in nanoseconds.
689    let mut lanes = [0i128; DurationLane::COUNT];
690    for field in DurationField::CASCADE {
691        let Some(n) = values.get(&field) else {
692            continue;
693        };
694        let (lane, unit) = field.lane_and_unit();
695        lanes[lane as usize] += n * unit;
696    }
697    let lane = |lane: DurationLane| checked_lane(lanes[lane as usize], "duration()");
698    let months = lane(DurationLane::Months)?;
699    let days = lane(DurationLane::Days)?;
700    let seconds = lane(DurationLane::Seconds)?;
701    let subsecond = lane(DurationLane::SubSecond)?;
702    Temporal::duration_checked_exact(
703        months,
704        days,
705        i128::from(seconds) * NANOS_PER_SECOND + i128::from(subsecond),
706    )
707}