relate-core 1.5.0

Core values, errors, and IDs for Relate
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
//! The temporal component-accessor vocabulary and the one reader per
//! component.
//!
//! Neo4j rejects a component read on a kind that has no such component
//! (`date().hour`, `duration({days: 1}).year`, `date().epochSeconds`) with a
//! typed `TypeError`; the engine answered null. The readers below are the one
//! exposure source: a component is answered when the kind's part readers
//! produce it and rejected otherwise ([`read`]), so no second table can
//! admit a component a reader cannot produce.

use chrono::{Datelike, NaiveDate, NaiveTime, Timelike};

use crate::{Error, Result, Value};

use super::civil_epoch_days;
use super::field::{quarter_of_month, quarter_start_month};
use super::zone::{add_offset, zone_kind, ZoneSpec};
use super::{
    format_zone_offset, lookup, split_seconds, Temporal, NANOS_PER_MICRO, NANOS_PER_MILLI,
    SECONDS_PER_HOUR, SECONDS_PER_MINUTE,
};

/// One calendar/time component an accessor can read. The variants are the
/// accessor vocabulary, not per-kind: [`component_value`] answers only the
/// kinds that carry the part, and its `None` is the typed rejection's cue.
/// Private to this module: the name table's inverse and the reader are its
/// only users.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Component {
    Year,
    Month,
    Day,
    OrdinalDay,
    Quarter,
    Week,
    WeekYear,
    DayOfWeek,
    DayOfQuarter,
    Hour,
    Minute,
    Second,
    Millisecond,
    Microsecond,
    Nanosecond,
    Timezone,
    Offset,
    OffsetSeconds,
    OffsetMinutes,
    EpochSeconds,
    EpochMillis,
}

impl Component {
    /// The accessor spellings, lower-case. `weekDay` is Neo4j's alias for
    /// `dayOfWeek`, so both names map to one variant. This is the only name
    /// table; [`Component::from_name`] is its inverse.
    const TABLE: &'static [(&'static str, Component)] = &[
        ("year", Component::Year),
        ("month", Component::Month),
        ("day", Component::Day),
        ("ordinalday", Component::OrdinalDay),
        ("quarter", Component::Quarter),
        ("week", Component::Week),
        ("weekyear", Component::WeekYear),
        ("dayofweek", Component::DayOfWeek),
        ("weekday", Component::DayOfWeek),
        ("dayofquarter", Component::DayOfQuarter),
        ("hour", Component::Hour),
        ("minute", Component::Minute),
        ("second", Component::Second),
        ("millisecond", Component::Millisecond),
        ("microsecond", Component::Microsecond),
        ("nanosecond", Component::Nanosecond),
        ("timezone", Component::Timezone),
        ("offset", Component::Offset),
        ("offsetseconds", Component::OffsetSeconds),
        ("offsetminutes", Component::OffsetMinutes),
        ("epochseconds", Component::EpochSeconds),
        ("epochmillis", Component::EpochMillis),
    ];

    fn from_name(name: &str) -> Option<Self> {
        lookup(Self::TABLE, name)
    }
}

/// One duration component. Neo4j exposes only the plural aggregate
/// spellings (`years`, not `year`); the singular calendar names are not
/// duration components at all.
#[derive(Clone, Copy)]
enum DurationComponent {
    Years,
    Quarters,
    Months,
    Weeks,
    Days,
    Hours,
    Minutes,
    Seconds,
    Millis,
    Micros,
    Nanos,
    MonthsOfYear,
    QuartersOfYear,
    MonthsOfQuarter,
    DaysOfWeek,
    MinutesOfHour,
    SecondsOfMinute,
    MillisOfSecond,
    MicrosOfSecond,
    NanosOfSecond,
}

impl DurationComponent {
    /// The duration accessor spellings, lower-case; the inverse is
    /// [`DurationComponent::from_name`].
    const TABLE: &'static [(&'static str, DurationComponent)] = &[
        ("years", DurationComponent::Years),
        ("quarters", DurationComponent::Quarters),
        ("months", DurationComponent::Months),
        ("weeks", DurationComponent::Weeks),
        ("days", DurationComponent::Days),
        ("hours", DurationComponent::Hours),
        ("minutes", DurationComponent::Minutes),
        ("seconds", DurationComponent::Seconds),
        ("milliseconds", DurationComponent::Millis),
        ("microseconds", DurationComponent::Micros),
        ("nanoseconds", DurationComponent::Nanos),
        ("monthsofyear", DurationComponent::MonthsOfYear),
        ("quartersofyear", DurationComponent::QuartersOfYear),
        ("monthsofquarter", DurationComponent::MonthsOfQuarter),
        ("daysofweek", DurationComponent::DaysOfWeek),
        ("minutesofhour", DurationComponent::MinutesOfHour),
        ("secondsofminute", DurationComponent::SecondsOfMinute),
        ("millisecondsofsecond", DurationComponent::MillisOfSecond),
        ("microsecondsofsecond", DurationComponent::MicrosOfSecond),
        ("nanosecondsofsecond", DurationComponent::NanosOfSecond),
    ];

    fn from_name(name: &str) -> Option<Self> {
        lookup(Self::TABLE, name)
    }
}

/// The component `key` of `t`, or the typed rejection the reference engine
/// raises for a component the value's kind does not carry. The reader's own
/// `None` *is* the exposure policy: there is no second table to disagree
/// with, and an unreadable stored value is the reader's typed range failure
/// rather than an internal error.
pub(super) fn read(t: &Temporal, key: &str) -> Result<Value> {
    let name = key.to_ascii_lowercase();
    if let Temporal::Duration {
        months,
        days,
        nanos,
    } = t
    {
        let component =
            DurationComponent::from_name(&name).ok_or_else(|| no_component("duration", key))?;
        return duration_component(*months, *days, *nanos, component);
    }
    // A proleptic civil form reads as the kind it extends (`kind_name`).
    let kind = t.kind_name();
    let component = Component::from_name(&name).ok_or_else(|| no_component(kind, key))?;
    component_value(t, component)?.ok_or_else(|| no_component(kind, key))
}

/// The one rejection spelling for an accessor a kind does not carry.
fn no_component(kind: &str, key: &str) -> Error {
    Error::ty(format!("no such component '{key}' on a {kind} value"))
}

/// A local calendar date with an unbounded year: the shape both the chrono
/// kinds and the proleptic civil forms (±999999999) read through.
#[derive(Clone, Copy)]
struct Ymd {
    year: i64,
    month: u32,
    day: u32,
}

impl From<NaiveDate> for Ymd {
    fn from(d: NaiveDate) -> Self {
        Ymd {
            year: i64::from(d.year()),
            month: d.month(),
            day: d.day(),
        }
    }
}

/// An ISO-8601 week and the week-year that owns it.
struct IsoWeek {
    week_year: i64,
    week: i64,
}

impl Ymd {
    fn epoch_days(self) -> i128 {
        civil_epoch_days(self.year, self.month, self.day)
    }

    /// ISO weekday, Monday = 1 .. Sunday = 7 (1970-01-01 was a Thursday).
    fn day_of_week(self) -> i64 {
        // The remainder is 0..=6, so the narrowing is exact.
        (self.epoch_days() + 3).rem_euclid(7) as i64 + 1
    }

    fn ordinal_day(self) -> i64 {
        let jan_first = civil_epoch_days(self.year, 1, 1);
        // Within 0..=365 by construction.
        (self.epoch_days() - jan_first) as i64 + 1
    }

    fn quarter(self) -> u32 {
        quarter_of_month(self.month)
    }

    fn day_of_quarter(self) -> i64 {
        let quarter_start = civil_epoch_days(self.year, quarter_start_month(self.month), 1);
        // Within a quarter, 0..=91 by construction.
        (self.epoch_days() - quarter_start) as i64 + 1
    }

    /// The ISO-8601 week and week-year over the wide day arithmetic, so a
    /// ±999999999 year reads exactly as an in-range one. The `year ± 1`
    /// below cannot overflow: a civil year is range-checked to ±999999999
    /// at construction (`construct.rs`).
    fn iso_week(self) -> IsoWeek {
        let week = (self.ordinal_day() - self.day_of_week() + 10) / 7;
        if week < 1 {
            IsoWeek {
                week_year: self.year - 1,
                week: iso_weeks_in_year(self.year - 1),
            }
        } else if week > iso_weeks_in_year(self.year) {
            IsoWeek {
                week_year: self.year + 1,
                week: 1,
            }
        } else {
            IsoWeek {
                week_year: self.year,
                week,
            }
        }
    }
}

/// 53 for a year whose first or last day is a Thursday (a leap year's last
/// day is one weekday past its first, so leapness needs no separate test);
/// 52 otherwise.
fn iso_weeks_in_year(year: i64) -> i64 {
    const THURSDAY: i64 = 4;
    let day_of_week = |month, day| Ymd { year, month, day }.day_of_week();
    if day_of_week(1, 1) == THURSDAY || day_of_week(12, 31) == THURSDAY {
        53
    } else {
        52
    }
}

/// The date part of a clock value: its local calendar date. `None` for a
/// kind without a date; an out-of-range `utc + offset` (reachable from a
/// decoded parameter) is the typed range failure, never a silent UTC
/// reading.
fn date_part(t: &Temporal) -> Result<Option<Ymd>> {
    Ok(match t {
        Temporal::Date(d) => Some((*d).into()),
        Temporal::LocalDateTime(dt) => Some(dt.date().into()),
        Temporal::DateTime { utc, offset, .. } => Some(add_offset(*utc, *offset)?.date().into()),
        Temporal::CivilDate { year, month, day }
        | Temporal::CivilDateTime {
            year, month, day, ..
        } => Some(Ymd {
            year: *year,
            month: *month,
            day: *day,
        }),
        Temporal::CivilZoned(f) => Some(Ymd {
            year: f.year,
            month: f.month,
            day: f.day,
        }),
        _ => None,
    })
}

/// The time-of-day part of a clock value. The error contract is
/// [`date_part`]'s.
fn time_part(t: &Temporal) -> Result<Option<NaiveTime>> {
    Ok(match t {
        Temporal::LocalTime(tm) | Temporal::Time { time: tm, .. } => Some(*tm),
        Temporal::LocalDateTime(dt) => Some(dt.time()),
        Temporal::DateTime { utc, offset, .. } => Some(add_offset(*utc, *offset)?.time()),
        Temporal::CivilDateTime { time, .. } => Some(*time),
        Temporal::CivilZoned(f) => Some(f.time),
        _ => None,
    })
}

/// The UTC offset a zoned clock value carries; `None` for the zoneless
/// kinds.
fn offset_part(t: &Temporal) -> Option<i32> {
    match t {
        Temporal::Time { offset, .. } | Temporal::DateTime { offset, .. } => Some(*offset),
        Temporal::CivilZoned(f) => Some(f.offset),
        _ => None,
    }
}

/// The `timezone` rendering: the stored zone spelling when the value names
/// one (an IANA region or a fixed `+HH:MM`/`GMT+HH:MM` spelling), `Z` for
/// UTC, and the offset-only spelling otherwise — the same zero-offset rule
/// the ISO suffix uses.
fn timezone_part(t: &Temporal) -> Option<String> {
    let offset = offset_part(t)?;
    let named_zone = match t {
        Temporal::DateTime { zone, .. } => zone.as_deref(),
        Temporal::CivilZoned(f) => f.zone.as_deref(),
        _ => None,
    };
    if let Some(zone) = named_zone {
        return Some(match zone_kind(zone) {
            ZoneSpec::Iana(name) => name.into(),
            // A numeric offset spelling renders through the one zero-offset
            // rule, so `.timezone` and `.offset` agree on `Z`; a
            // `GMT`/`UTC` prefixed spelling keeps its own text
            // (Neo4j-verified: `timezone: 'GMT'` answers `GMT` while
            // `.offset` answers `Z`).
            ZoneSpec::Fixed(_) | ZoneSpec::Other(_) => format_zone_offset(offset),
            ZoneSpec::Prefixed(name) => name.into(),
            ZoneSpec::Utc => "Z".into(),
        });
    }
    Some(format_zone_offset(offset))
}

/// The one reader: the component's value for `t`, or `None` when the value's
/// kind carries no such part (the caller answers the typed rejection). An
/// unreadable stored value is the part reader's typed range failure.
fn component_value(t: &Temporal, component: Component) -> Result<Option<Value>> {
    // The calendar and clock components read one half each; a kind without
    // that half answers `None`.
    let ymd_int = |f: fn(Ymd) -> i64| -> Result<Option<Value>> {
        Ok(date_part(t)?.map(|d| Value::Int(f(d))))
    };
    let time_int = |f: fn(NaiveTime) -> i64| -> Result<Option<Value>> {
        Ok(time_part(t)?.map(|tm| Value::Int(f(tm))))
    };
    match component {
        Component::Year => ymd_int(|d| d.year),
        Component::Month => ymd_int(|d| i64::from(d.month)),
        Component::Day => ymd_int(|d| i64::from(d.day)),
        Component::OrdinalDay => ymd_int(Ymd::ordinal_day),
        Component::Quarter => ymd_int(|d| i64::from(d.quarter())),
        Component::Week => ymd_int(|d| d.iso_week().week),
        Component::WeekYear => ymd_int(|d| d.iso_week().week_year),
        Component::DayOfWeek => ymd_int(Ymd::day_of_week),
        Component::DayOfQuarter => ymd_int(Ymd::day_of_quarter),
        Component::Hour => time_int(|tm| i64::from(tm.hour())),
        Component::Minute => time_int(|tm| i64::from(tm.minute())),
        Component::Second => time_int(|tm| i64::from(tm.second())),
        Component::Millisecond => time_int(|tm| i64::from(tm.nanosecond() / 1_000_000)),
        Component::Microsecond => time_int(|tm| i64::from(tm.nanosecond() / 1_000)),
        Component::Nanosecond => time_int(|tm| i64::from(tm.nanosecond())),
        Component::Timezone => Ok(timezone_part(t).map(|z| Value::String(z.into()))),
        Component::Offset => {
            Ok(offset_part(t).map(|o| Value::String(format_zone_offset(o).into())))
        }
        Component::OffsetSeconds => Ok(offset_part(t).map(|o| Value::Int(i64::from(o)))),
        Component::OffsetMinutes => Ok(offset_part(t).map(|o| Value::Int(i64::from(o / 60)))),
        Component::EpochSeconds => Ok(epoch_millis(t)?.map(|ms| Value::Int(ms.div_euclid(1000)))),
        Component::EpochMillis => Ok(epoch_millis(t)?.map(Value::Int)),
    }
}

/// The zoned datetime's epoch milliseconds — the one epoch reading both
/// units derive from, as the reference engine does: a count that does not fit
/// i64 fails *both* `epochSeconds` and `epochMillis` (live: a year-500000000
/// datetime overflows its long on either accessor, while one at year
/// 285200616 reads exactly). The epoch components exist only on the zoned
/// datetime kinds; every other kind answers `None`.
fn epoch_millis(t: &Temporal) -> Result<Option<i64>> {
    // The one zoned-instant derivation (`Temporal::zoned_parts`, both
    // representations), never a per-consumer reassembly.
    let Some(parts) = t.zoned_parts() else {
        return Ok(None);
    };
    i64::try_from(parts.instant.div_euclid(NANOS_PER_MILLI))
        .map(Some)
        .map_err(|_| super::range_err())
}

fn duration_component(
    months: i64,
    days: i64,
    nanos: i128,
    component: DurationComponent,
) -> Result<Value> {
    // One decomposition, not two: the floored split of the stored i128
    // nanos into whole seconds and the sub-second remainder the
    // `…OfSecond` accessors read. Every arm below is expressed over it, so
    // the two rounding conventions cannot disagree again (the truncating
    // fields divide the whole-second count, exactly Neo4j's accessors).
    let (total_seconds, sub_nanos) = split_seconds(nanos);
    let total_minutes = total_seconds / SECONDS_PER_MINUTE;
    let hours = total_seconds / SECONDS_PER_HOUR;
    // Totals derived from the i128 nanosecond count can exceed i64 for
    // extreme durations; error honestly instead of truncating through `as`.
    let total = |v: i128| i64::try_from(v).map_err(|_| super::range_err());
    Ok(Value::Int(match component {
        DurationComponent::Years => months / 12,
        DurationComponent::Months => months,
        DurationComponent::MonthsOfYear => months.rem_euclid(12),
        DurationComponent::Quarters => months / 3,
        DurationComponent::QuartersOfYear => months.rem_euclid(12) / 3,
        DurationComponent::MonthsOfQuarter => months.rem_euclid(3),
        DurationComponent::Weeks => days / 7,
        DurationComponent::Days => days,
        DurationComponent::DaysOfWeek => days.rem_euclid(7),
        DurationComponent::Hours => total(hours)?,
        DurationComponent::Minutes => total(total_minutes)?,
        DurationComponent::MinutesOfHour => total(total_minutes % 60)?,
        DurationComponent::Seconds => total(total_seconds)?,
        DurationComponent::SecondsOfMinute => total(total_seconds % 60)?,
        DurationComponent::Nanos => total(nanos)?,
        // Neo4j's accessors floor a negative nanosecond count
        // (`DurationValue.milliseconds`), so the i64::MIN edge is reachable
        // only through `div_euclid`; truncating division lands one unit
        // short (-9223372036854775807 instead of i64::MIN).
        DurationComponent::Millis => total(nanos.div_euclid(NANOS_PER_MILLI))?,
        DurationComponent::Micros => total(nanos.div_euclid(NANOS_PER_MICRO))?,
        DurationComponent::MillisOfSecond => total(sub_nanos / NANOS_PER_MILLI)?,
        DurationComponent::MicrosOfSecond => total(sub_nanos / NANOS_PER_MICRO)?,
        DurationComponent::NanosOfSecond => total(sub_nanos)?,
    }))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::temporal::clock::ClockKind;
    use crate::temporal::{
        construct_date, construct_datetime, construct_localdatetime, construct_localtime,
        construct_time,
    };

    fn sample(kind: ClockKind) -> Temporal {
        match kind {
            ClockKind::Date => construct_date(None).unwrap(),
            ClockKind::LocalTime => construct_localtime(None).unwrap(),
            ClockKind::Time => construct_time(None).unwrap(),
            ClockKind::LocalDateTime => construct_localdatetime(None).unwrap(),
            ClockKind::DateTime => construct_datetime(None).unwrap(),
        }
    }

    /// The readers are the one exposure table: each kind answers exactly the
    /// components it carries and rejects the rest with the typed `no such
    /// component` text — pinned by example, because the readers themselves
    /// now are the policy.
    #[test]
    fn accessors_read_exactly_the_parts_the_kind_carries() {
        let date = sample(ClockKind::Date);
        assert!(read(&date, "year").is_ok());
        assert!(read(&date, "dayOfQuarter").is_ok());
        assert!(read(&date, "epochSeconds").is_err());
        assert!(read(&date, "hour").is_err());
        assert!(read(&date, "offset").is_err());

        let localtime = sample(ClockKind::LocalTime);
        assert!(read(&localtime, "hour").is_ok());
        assert!(read(&localtime, "timezone").is_err());
        assert!(read(&localtime, "year").is_err());

        let time = sample(ClockKind::Time);
        assert!(read(&time, "hour").is_ok());
        assert!(read(&time, "offsetMinutes").is_ok());
        assert!(read(&time, "timezone").is_ok());
        assert!(read(&time, "year").is_err());
        assert!(read(&time, "epochMillis").is_err());

        let localdatetime = sample(ClockKind::LocalDateTime);
        assert!(read(&localdatetime, "year").is_ok());
        assert!(read(&localdatetime, "hour").is_ok());
        assert!(read(&localdatetime, "timezone").is_err());
        assert!(read(&localdatetime, "epochSeconds").is_err());

        let datetime = sample(ClockKind::DateTime);
        assert!(read(&datetime, "year").is_ok());
        assert!(read(&datetime, "timezone").is_ok());
        assert!(read(&datetime, "epochMillis").is_ok());

        let err = read(&date, "hour").unwrap_err();
        assert!(err.to_string().contains("no such component"), "{err}");
    }

    /// B8: one zero-offset rule — a stored zero offset renders `Z` through
    /// both the `timezone` and the `offset` accessor, the same spelling the
    /// ISO suffix uses, while a non-zero offset keeps its numeric form.
    #[test]
    fn a_zero_offset_renders_z_through_both_accessors() {
        let utc = crate::temporal::parse_iso("time", "12:00Z").unwrap();
        assert_eq!(read(&utc, "timezone").unwrap(), Value::String("Z".into()));
        assert_eq!(read(&utc, "offset").unwrap(), Value::String("Z".into()));
        let plus_one = crate::temporal::parse_iso("time", "12:00+01:00").unwrap();
        assert_eq!(
            read(&plus_one, "timezone").unwrap(),
            Value::String("+01:00".into())
        );
        assert_eq!(
            read(&plus_one, "offset").unwrap(),
            Value::String("+01:00".into())
        );
    }

    /// B7: a stored offset that pushes the wall clock past chrono's range is
    /// the typed range failure of the part reader — not an internal "no
    /// reader" error far from the cause.
    #[test]
    fn an_out_of_range_offset_is_a_typed_range_error() {
        let t = Temporal::DateTime {
            utc: NaiveDate::MAX.and_hms_opt(23, 59, 59).unwrap(),
            offset: 3600,
            zone: None,
        };
        let err = read(&t, "year").unwrap_err();
        assert!(err.to_string().contains("out of range"), "{err}");
    }

    /// A far-year `Date` reads the calendar accessors of its kind (live
    /// Neo4j values at both edges); a part the kind lacks stays rejected.
    #[test]
    fn a_far_year_date_reads_the_calendar_accessors() {
        let date = crate::temporal::parse_iso("date", "-999999999-01-01").unwrap();
        assert!(matches!(date, Temporal::CivilDate { .. }));
        assert_eq!(read(&date, "year").unwrap(), Value::Int(-999_999_999));
        assert_eq!(read(&date, "month").unwrap(), Value::Int(1));
        assert_eq!(read(&date, "day").unwrap(), Value::Int(1));
        assert_eq!(read(&date, "quarter").unwrap(), Value::Int(1));
        // Live Neo4j: week 1 of week-year -999999999, a Monday, ordinal 1.
        assert_eq!(read(&date, "week").unwrap(), Value::Int(1));
        assert_eq!(read(&date, "weekYear").unwrap(), Value::Int(-999_999_999));
        assert_eq!(read(&date, "dayOfWeek").unwrap(), Value::Int(1));
        assert_eq!(read(&date, "ordinalDay").unwrap(), Value::Int(1));
        assert_eq!(read(&date, "dayOfQuarter").unwrap(), Value::Int(1));
        // Live Neo4j: +999999999-01-01 is a Friday in week 53 of 999999998.
        let top = crate::temporal::parse_iso("date", "+999999999-01-01").unwrap();
        assert_eq!(read(&top, "week").unwrap(), Value::Int(53));
        assert_eq!(read(&top, "weekYear").unwrap(), Value::Int(999_999_998));
        assert_eq!(read(&top, "dayOfWeek").unwrap(), Value::Int(5));
        let err = read(&date, "hour").unwrap_err();
        assert!(err.to_string().contains("no such component"), "{err}");
    }

    /// A far-year `LocalDateTime` reads the calendar and clock halves and
    /// rejects the zone parts it lacks.
    #[test]
    fn a_far_year_localdatetime_reads_calendar_and_clock() {
        let local =
            crate::temporal::parse_iso("localdatetime", "999999999-12-31T23:59:58.5").unwrap();
        assert!(matches!(local, Temporal::CivilDateTime { .. }));
        assert_eq!(read(&local, "year").unwrap(), Value::Int(999_999_999));
        assert_eq!(read(&local, "month").unwrap(), Value::Int(12));
        assert_eq!(read(&local, "second").unwrap(), Value::Int(58));
        assert_eq!(read(&local, "millisecond").unwrap(), Value::Int(500));
        assert!(read(&local, "offset").is_err());
    }

    /// A far-year `DateTime` reads calendar, clock and zone parts; the epoch
    /// units derive from epoch millis, so both fail past i64 and both read
    /// exactly within it (live: year 285200616 reads, year 500000000 fails).
    #[test]
    fn a_far_year_datetime_reads_zone_parts_and_bounded_epochs() {
        let zoned =
            crate::temporal::parse_iso("datetime", "+999999999-12-31T23:59:58+01:00").unwrap();
        assert!(matches!(zoned, Temporal::CivilZoned(_)));
        assert_eq!(read(&zoned, "day").unwrap(), Value::Int(31));
        assert_eq!(read(&zoned, "hour").unwrap(), Value::Int(23));
        assert_eq!(read(&zoned, "offsetMinutes").unwrap(), Value::Int(60));
        assert_eq!(
            read(&zoned, "offset").unwrap(),
            Value::String("+01:00".into())
        );
        assert_eq!(read(&zoned, "week").unwrap(), Value::Int(52));
        assert_eq!(read(&zoned, "ordinalDay").unwrap(), Value::Int(365));
        for unit in ["epochSeconds", "epochMillis"] {
            let err = read(&zoned, unit).unwrap_err();
            assert!(err.to_string().contains("out of range"), "{err}");
        }
        let edge = crate::temporal::parse_iso("datetime", "+285200616-06-01T00:00Z").unwrap();
        assert!(matches!(edge, Temporal::CivilZoned(_)));
        assert_eq!(
            read(&edge, "epochSeconds").unwrap(),
            Value::Int(8_999_999_995_363_200)
        );
        assert_eq!(
            read(&edge, "epochMillis").unwrap(),
            Value::Int(8_999_999_995_363_200_000)
        );
    }

    /// The duration vocabulary is its own table: the singular calendar names
    /// are not duration components, the plural aggregate names are.
    #[test]
    fn duration_reads_only_its_own_spellings() {
        let d =
            crate::temporal::construct_duration(Some(&Value::String("P1Y2M3D".into()))).unwrap();
        assert_eq!(read(&d, "years").unwrap(), Value::Int(1));
        assert_eq!(read(&d, "months").unwrap(), Value::Int(14));
        assert!(read(&d, "year").is_err());
        assert!(read(&d, "weekOfMonth").is_err());
        assert!(read(&d, "epochSeconds").is_err());
    }
}