Skip to main content

zu_common/
temporal.rs

1//! Temporal values: the six types of GV39, GV40 and GV41.
2//!
3//! A temporal value is a number and a meaning, never a struct of named
4//! parts. A date is a day count, a time is a nanosecond count, and a
5//! duration is a month count or a nanosecond count depending on which
6//! of the two kinds it is. The calendar arithmetic happens at the edges
7//! where text is read and written, so a comparison is an integer
8//! comparison and a column of dates is a column of `i32`.
9//!
10//! Three decisions are worth writing down because they are the ones a
11//! reader will want to argue with.
12//!
13//! A zone is an offset in minutes and never an IANA name. A name is a
14//! rule that changes under a database's feet when the zone database is
15//! updated, and a value that means something different tomorrow is not
16//! a value. `2024-01-15T10:00+07:00` is what the standard asks for and
17//! is what zu stores; the name that produced the offset belongs to the
18//! session that wrote it, not to the row.
19//!
20//! The two duration kinds do not mix. A year-month duration counts
21//! months and a day-time duration counts nanoseconds, and no number of
22//! days is a month. An engine that stores both in one value has to
23//! invent an answer for one month after 31 January, and the standard
24//! does not ask for the invention, so zu refuses the arithmetic instead
25//! of guessing.
26//!
27//! Adding months to a date does clamp, and that is a different case
28//! from mixing kinds. One month after 31 January is 28 February, which
29//! is not an invention but the answer every calendar gives, because the
30//! month is named and the day is the largest that month has.
31
32use std::fmt;
33
34use crate::types::{DurationKind, LogicalType};
35
36/// Nanoseconds in one second, minute, hour and day. The minute and the
37/// day are public because an offset and a calendar day are the two
38/// units a conversion between temporal types is stated in.
39const NANOS_PER_SEC: i64 = 1_000_000_000;
40pub const NANOS_PER_MINUTE: i64 = 60 * NANOS_PER_SEC;
41const NANOS_PER_HOUR: i64 = 60 * NANOS_PER_MINUTE;
42pub const NANOS_PER_DAY: i64 = 24 * NANOS_PER_HOUR;
43
44/// The first and last day the standard's calendar has, as day counts
45/// from 1970-01-01.
46///
47/// ISO dates run from year 1 to year 9999, so an addition that lands
48/// outside that is 22008 and not a wider date. An engine with a roomier
49/// internal calendar still owes the overflow, because the value it
50/// would return has no spelling in the type.
51pub const MIN_DAY: i32 = -719_162;
52pub const MAX_DAY: i32 = 2_932_896;
53
54/// The instant `days` days after the epoch and `nanos` into that day,
55/// or `None` where it does not fit.
56///
57/// A datetime is nanoseconds since the epoch in one signed word, and
58/// that word runs out long before the calendar does: the last instant
59/// it spells is in 2262 and the first is in 1677, while a date runs
60/// from year 1 to year 9999. So there are dates that are perfectly
61/// good dates and name no datetime at all, and every place that builds
62/// a datetime out of a day has to say so rather than wrap into a year
63/// on the other side of the epoch.
64///
65/// This is the one place that multiplication is written. It was
66/// written in five places before, none of them checked, and each one
67/// was a panic in a debug build and a wrong answer in a release one.
68pub fn instant_at(days: i32, nanos: i64) -> Option<i64> {
69    i64::from(days)
70        .checked_mul(NANOS_PER_DAY)?
71        .checked_add(nanos)
72}
73
74/// What a statement answers the datetime value functions with: the
75/// instant it is running at and the displacement its session keeps.
76///
77/// It is one reading and not a call to the operating system per row,
78/// because ISO 20.27 asks that every datetime value function in one
79/// statement answer the same instant. A statement that read the clock
80/// twice could have `CURRENT_DATE` and `CURRENT_TIMESTAMP` land on two
81/// days, and a scan of ten million rows would spend ten million system
82/// calls finding that out.
83///
84/// The displacement is minutes east of UTC and never a zone name, for
85/// the reason the zoned types carry an offset: a name is a rule that
86/// changes when the zone database is updated, and a value that means
87/// something different tomorrow is not a value.
88#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
89pub struct Clock {
90    /// Nanoseconds since 1970-01-01T00:00:00Z.
91    pub nanos: i64,
92    /// Minutes east of UTC.
93    pub offset: i16,
94}
95
96impl Clock {
97    /// The clock read now, in UTC, which is what a statement does once
98    /// before its first row.
99    ///
100    /// The displacement is nought because a session opens in UTC, which
101    /// is one of the implementation-defined choices the standard leaves
102    /// open and is written down as such. A session that has moved its
103    /// zone stamps this reading with what it moved to (GS15), so the
104    /// zone rides in beside the instant rather than being read here. A
105    /// clock before
106    /// the epoch on a machine whose time is set wrong reads as the
107    /// epoch rather than refusing, since a statement asking what time
108    /// it is has no better answer to give and no condition to raise.
109    pub fn read() -> Clock {
110        let nanos = std::time::SystemTime::now()
111            .duration_since(std::time::UNIX_EPOCH)
112            .map(|since| i64::try_from(since.as_nanos()).unwrap_or(i64::MAX))
113            .unwrap_or(0);
114        Clock { nanos, offset: 0 }
115    }
116
117    /// The instant as a zoned datetime, which is the one value the five
118    /// datetime value functions are cut out of.
119    pub fn instant(self) -> Temporal {
120        Temporal::ZonedDatetime {
121            nanos: self.nanos,
122            offset: self.offset,
123        }
124    }
125}
126
127/// One temporal value.
128///
129/// The variants carry counts and not fields. A zoned value carries the
130/// instant and the offset separately, so two zoned values compare by
131/// instant while each still prints in the zone it was written in.
132#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
133pub enum Temporal {
134    /// Days since 1970-01-01.
135    Date(i32),
136    /// Nanoseconds since midnight.
137    LocalTime(i64),
138    /// Nanoseconds since midnight in the offset's own day, and the
139    /// offset from UTC in minutes.
140    ZonedTime { nanos: i64, offset: i16 },
141    /// Nanoseconds since 1970-01-01T00:00:00.
142    LocalDatetime(i64),
143    /// Nanoseconds since the epoch in UTC, and the offset from UTC in
144    /// minutes that the value was written with.
145    ZonedDatetime { nanos: i64, offset: i16 },
146    /// Months for a year-month duration, nanoseconds for a day-time
147    /// one. The kind is carried because the number means nothing on
148    /// its own.
149    Duration(DurationKind, i64),
150}
151
152impl Temporal {
153    /// The lattice type of this value.
154    pub fn logical_type(&self) -> LogicalType {
155        match self {
156            Temporal::Date(_) => LogicalType::Date,
157            Temporal::LocalTime(_) => LogicalType::LocalTime,
158            Temporal::ZonedTime { .. } => LogicalType::ZonedTime,
159            Temporal::LocalDatetime(_) => LogicalType::LocalDatetime,
160            Temporal::ZonedDatetime { .. } => LogicalType::ZonedDatetime,
161            Temporal::Duration(kind, _) => LogicalType::Duration(*kind),
162        }
163    }
164
165    /// The value `text` spells as a value of type `ty`, or `None` when
166    /// it spells none.
167    ///
168    /// A datetime type accepts a date on its own, at midnight, because
169    /// the standard's datetime literal does. Nothing else is widened:
170    /// a date is not a datetime and reading one as the other silently
171    /// would answer a question nobody asked.
172    pub fn parse(ty: &LogicalType, text: &str) -> Option<Temporal> {
173        let text = text.trim();
174        Some(match ty {
175            LogicalType::Date => Temporal::Date(parse_date(text)?),
176            LogicalType::LocalTime => {
177                let (nanos, offset) = parse_time(text)?;
178                if offset.is_some() {
179                    return None;
180                }
181                Temporal::LocalTime(nanos)
182            }
183            LogicalType::ZonedTime => {
184                let (nanos, offset) = parse_time(text)?;
185                Temporal::ZonedTime {
186                    nanos,
187                    offset: offset.unwrap_or(0),
188                }
189            }
190            LogicalType::LocalDatetime => {
191                let (nanos, offset) = parse_datetime(text)?;
192                if offset.is_some() {
193                    return None;
194                }
195                Temporal::LocalDatetime(nanos)
196            }
197            LogicalType::ZonedDatetime => {
198                let (nanos, offset) = parse_datetime(text)?;
199                // The stored instant is UTC, so a written offset is
200                // subtracted rather than kept alongside a local time.
201                // Two values written in two zones for one instant are
202                // then one number and compare equal, which is the
203                // whole reason to store the instant.
204                let offset = offset.unwrap_or(0);
205                Temporal::ZonedDatetime {
206                    nanos: nanos.checked_sub(i64::from(offset) * NANOS_PER_MINUTE)?,
207                    offset,
208                }
209            }
210            LogicalType::Duration(_) => parse_duration(text)?,
211            _ => return None,
212        })
213    }
214
215    /// The value `text` spells when the type is not written out, which
216    /// is what a property in a fixture and a value read back from a
217    /// column both need.
218    ///
219    /// The shape decides: a leading `P` is a duration, a `T` or a space
220    /// in the middle is a datetime, a colon is a time, and a dash is a
221    /// date.
222    pub fn parse_any(text: &str) -> Option<Temporal> {
223        let text = text.trim();
224        let ty = if text.starts_with('P') || text.starts_with("-P") {
225            LogicalType::Duration(DurationKind::DayTime)
226        } else if text.contains('T') || text.contains(' ') {
227            if has_offset(text) {
228                LogicalType::ZonedDatetime
229            } else {
230                LogicalType::LocalDatetime
231            }
232        } else if text.contains(':') {
233            if has_offset(text) {
234                LogicalType::ZonedTime
235            } else {
236                LogicalType::LocalTime
237            }
238        } else {
239            LogicalType::Date
240        };
241        Temporal::parse(&ty, text)
242    }
243
244    /// The duration `text` spells when it is written the way SQL
245    /// writes one, `INTERVAL '3 04:05:06' DAY TO SECOND`, with the
246    /// qualifier already read.
247    ///
248    /// The qualifier is not decoration. It is the whole of what says
249    /// how to read the string, because `'1-2'` is a year and two
250    /// months under `YEAR TO MONTH` and is nothing at all under `DAY`,
251    /// and `'3'` is three of whichever single field was named. So this
252    /// reads the fields the qualifier lists, in order, and refuses
253    /// anything the qualifier did not ask for.
254    ///
255    /// The leading field is unbounded and the ones behind it are not:
256    /// `'25' HOUR` is twenty five hours, and `'1 25:00:00' DAY TO
257    /// SECOND` is not a day and an hour, because a written hour that
258    /// follows a written day has 24 of its own and the standard says
259    /// so. A number that runs over its field is refused rather than
260    /// carried, since carrying it would answer a question the
261    /// statement did not ask.
262    pub fn parse_sql_interval(text: &str, qualifier: &IntervalQualifier) -> Option<Temporal> {
263        if qualifier.start.kind() != qualifier.end.kind()
264            || qualifier.start.rank() > qualifier.end.rank()
265        {
266            return None;
267        }
268        let (negative, body) = match text.strip_prefix('-') {
269            Some(rest) => (true, rest),
270            None => (false, text.strip_prefix('+').unwrap_or(text)),
271        };
272        let fields = &FIELD_ORDER[qualifier.start.rank()..=qualifier.end.rank()];
273        // The written value is one part a field, and which character
274        // stands between two of them depends on the pair: a year and a
275        // month are written with a minus sign, a day and the time
276        // behind it with a space, and the rest with a colon. That is
277        // `'1-2'`, `'3 04:05:06'` and `'04:05'`.
278        let mut parts = Vec::with_capacity(fields.len());
279        let mut rest = body;
280        for (ix, field) in fields.iter().enumerate() {
281            if ix + 1 == fields.len() {
282                parts.push(rest);
283                break;
284            }
285            let separator = match field {
286                IntervalField::Year => '-',
287                IntervalField::Day => ' ',
288                _ => ':',
289            };
290            let (head, tail) = rest.split_once(separator)?;
291            parts.push(head);
292            rest = tail;
293        }
294        // A written precision is a statement about the leading field
295        // alone, and it is the only meaning zu can give it, since the
296        // duration types carry one precision each and it is not this
297        // one.
298        let whole = parts[0].split('.').next()?;
299        if qualifier
300            .leading
301            .is_some_and(|limit| whole.len() > limit as usize)
302        {
303            return None;
304        }
305        let mut months = 0i64;
306        let mut nanos = 0i64;
307        for (ix, (field, text)) in fields.iter().zip(&parts).enumerate() {
308            let leading = ix == 0;
309            match field {
310                IntervalField::Year => {
311                    months = months.checked_add(uint(text)?.checked_mul(12)?)?;
312                }
313                IntervalField::Month => {
314                    months = months.checked_add(bounded(text, leading, 11)?)?;
315                }
316                IntervalField::Day => {
317                    nanos = nanos.checked_add(uint(text)?.checked_mul(NANOS_PER_DAY)?)?;
318                }
319                IntervalField::Hour => {
320                    nanos = nanos
321                        .checked_add(bounded(text, leading, 23)?.checked_mul(NANOS_PER_HOUR)?)?;
322                }
323                IntervalField::Minute => {
324                    nanos = nanos
325                        .checked_add(bounded(text, leading, 59)?.checked_mul(NANOS_PER_MINUTE)?)?;
326                }
327                IntervalField::Second => {
328                    nanos =
329                        nanos.checked_add(interval_seconds(text, leading, qualifier.fraction)?)?;
330                }
331            }
332        }
333        let sign = if negative { -1 } else { 1 };
334        Some(match qualifier.start.kind() {
335            DurationKind::YearMonth => Temporal::Duration(DurationKind::YearMonth, sign * months),
336            DurationKind::DayTime => Temporal::Duration(DurationKind::DayTime, sign * nanos),
337        })
338    }
339
340    /// The value a record constructor spells, or `None` where it
341    /// spells none.
342    ///
343    /// This is the second way ISO 20.27 and 20.29 write a temporal
344    /// value: `DATE({year: 2024, month: 1, day: 1})` beside
345    /// `DATE('2024-01-01')`. A field the record left out takes the
346    /// least value it has, so `DATE({year: 2024})` is the first of
347    /// January, which is what the standard's default for an omitted
348    /// `<field>` comes to.
349    ///
350    /// `None` is the calendar refusing, not the record being malformed:
351    /// the names were checked before anything got here and what is
352    /// left is a thirteenth month or a thirty-first of February, which
353    /// the caller reports as 22G06.
354    pub fn from_parts(ty: &LogicalType, parts: &Parts) -> Option<Temporal> {
355        if let LogicalType::Duration(_) = ty {
356            return parts.duration();
357        }
358        let days = match ty {
359            LogicalType::LocalTime | LogicalType::ZonedTime => 0,
360            _ => parts.days()?,
361        };
362        let nanos = parts.nanos()?;
363        let offset = parts.timezone.unwrap_or(0);
364        if !(-1080..=1080).contains(&offset) {
365            return None;
366        }
367        Some(match ty {
368            LogicalType::Date => Temporal::Date(days),
369            LogicalType::LocalTime => Temporal::LocalTime(nanos),
370            LogicalType::ZonedTime => Temporal::ZonedTime { nanos, offset },
371            LogicalType::LocalDatetime => Temporal::LocalDatetime(instant_at(days, nanos)?),
372            LogicalType::ZonedDatetime => Temporal::ZonedDatetime {
373                nanos: instant_at(days, nanos)?
374                    .checked_sub(i64::from(offset).checked_mul(NANOS_PER_MINUTE)?)?,
375                offset,
376            },
377            _ => return None,
378        })
379    }
380
381    /// The duration from `from` to `to`, of the kind asked for, or
382    /// `None` when the two are not two instants of one shape or the
383    /// answer leaves the calendar.
384    ///
385    /// This is what `DURATION_BETWEEN` answers and what a minus
386    /// between two instants answers, so the operator and the function
387    /// cannot drift apart.
388    ///
389    /// The two operands have to be the same shape. A date and a time
390    /// have no length between them, and a local datetime and a zoned
391    /// one have none either, because a local value names a wall clock
392    /// and not an instant, so the length would depend on a zone nobody
393    /// wrote.
394    ///
395    /// A day-time answer is a count of nanoseconds and needs no
396    /// calendar. A year-month answer is the largest count of whole
397    /// months that does not carry `from` past `to`, which is stated
398    /// against zu's own month addition rather than against a
399    /// comparison of day numbers. The two readings differ: 31 March to
400    /// 30 April is one month here, because 31 March plus one month is
401    /// 30 April and lands exactly on it, and is nought under a rule
402    /// that compares the days of the month first. Stating it against
403    /// the addition is what makes `from + DURATION_BETWEEN(from, to)`
404    /// land at or before `to` and one month more overshoot, and a law
405    /// that holds is worth more than agreement with a rule that does
406    /// not.
407    ///
408    /// A backwards answer truncates toward nought the same way, so the
409    /// two directions are not mirror images when a month is clipped.
410    pub fn between(from: Temporal, to: Temporal, kind: DurationKind) -> Option<Temporal> {
411        if std::mem::discriminant(&from) != std::mem::discriminant(&to) {
412            return None;
413        }
414        let count = match kind {
415            DurationKind::DayTime => to.elapsed()?.checked_sub(from.elapsed()?)?,
416            DurationKind::YearMonth => {
417                let ((day_a, time_a), (day_b, time_b)) = (from.civil()?, to.civil()?);
418                let (year_a, month_a, _) = civil_from_days(day_a);
419                let (year_b, month_b, _) = civil_from_days(day_b);
420                let mut months = (i64::from(year_b) * 12 + i64::from(month_b))
421                    - (i64::from(year_a) * 12 + i64::from(month_a));
422                // The count read off the year and the month alone is
423                // out by at most one, in whichever direction the day
424                // and the time of day fall, so one step settles it.
425                if months != 0 {
426                    let landed = (add_months(day_a, months)?, time_a);
427                    let past = if months > 0 {
428                        landed > (day_b, time_b)
429                    } else {
430                        landed < (day_b, time_b)
431                    };
432                    if past {
433                        months -= months.signum();
434                    }
435                }
436                months
437            }
438        };
439        Some(Temporal::Duration(kind, count))
440    }
441
442    /// The instant this value names, as one number in a frame the same
443    /// shape shares: nanoseconds since the epoch for a datetime, since
444    /// midnight for a time, and since the epoch for a date. `None` for
445    /// a duration, which names no instant.
446    fn elapsed(self) -> Option<i64> {
447        Some(match self {
448            Temporal::Date(days) => i64::from(days).checked_mul(NANOS_PER_DAY)?,
449            Temporal::LocalTime(nanos) | Temporal::LocalDatetime(nanos) => nanos,
450            Temporal::ZonedTime { nanos, offset } => {
451                nanos.checked_sub(i64::from(offset) * NANOS_PER_MINUTE)?
452            }
453            Temporal::ZonedDatetime { nanos, .. } => nanos,
454            Temporal::Duration(_, _) => return None,
455        })
456    }
457
458    /// The calendar day this value falls on and the nanoseconds into
459    /// that day, read on the value's own wall clock. `None` for the
460    /// values that have no calendar: the two times and a duration.
461    fn civil(self) -> Option<(i32, i64)> {
462        let local = match self {
463            Temporal::Date(days) => return Some((days, 0)),
464            Temporal::LocalDatetime(nanos) => nanos,
465            Temporal::ZonedDatetime { nanos, offset } => {
466                nanos.checked_add(i64::from(offset) * NANOS_PER_MINUTE)?
467            }
468            Temporal::LocalTime(_) | Temporal::ZonedTime { .. } | Temporal::Duration(_, _) => {
469                return None;
470            }
471        };
472        let days = i32::try_from(local.div_euclid(NANOS_PER_DAY)).ok()?;
473        Some((days, local.rem_euclid(NANOS_PER_DAY)))
474    }
475}
476
477/// The six primary datetime fields, smallest last, which is the order
478/// a qualifier names them in and the order they are written in.
479#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
480pub enum IntervalField {
481    Year,
482    Month,
483    Day,
484    Hour,
485    Minute,
486    Second,
487}
488
489/// The fields in the order the standard writes them, so a qualifier is
490/// a slice of this and never a list built by hand.
491const FIELD_ORDER: [IntervalField; 6] = [
492    IntervalField::Year,
493    IntervalField::Month,
494    IntervalField::Day,
495    IntervalField::Hour,
496    IntervalField::Minute,
497    IntervalField::Second,
498];
499
500impl IntervalField {
501    /// The field this word names, or `None` when it names none.
502    pub fn spelled(word: &str) -> Option<IntervalField> {
503        FIELD_ORDER
504            .into_iter()
505            .find(|field| word.eq_ignore_ascii_case(field.word()))
506    }
507
508    /// The word the standard writes this field with.
509    pub fn word(self) -> &'static str {
510        match self {
511            IntervalField::Year => "YEAR",
512            IntervalField::Month => "MONTH",
513            IntervalField::Day => "DAY",
514            IntervalField::Hour => "HOUR",
515            IntervalField::Minute => "MINUTE",
516            IntervalField::Second => "SECOND",
517        }
518    }
519
520    /// Where this field stands among the six, which is what says
521    /// whether one field may follow another.
522    pub fn rank(self) -> usize {
523        FIELD_ORDER
524            .iter()
525            .position(|field| *field == self)
526            .unwrap_or(0)
527    }
528
529    /// Which of the two duration kinds this field counts in. The kinds
530    /// do not mix, so a qualifier naming one field from each is not a
531    /// qualifier at all.
532    pub fn kind(self) -> DurationKind {
533        match self {
534            IntervalField::Year | IntervalField::Month => DurationKind::YearMonth,
535            _ => DurationKind::DayTime,
536        }
537    }
538}
539
540/// The qualifier of a SQL interval literal: the run of fields the
541/// value is written in, and the precisions it was written with.
542///
543/// A single field is `start` and `end` the same, since one field is
544/// the run of length one and nothing about the reading changes.
545#[derive(Clone, Copy, PartialEq, Eq, Debug)]
546pub struct IntervalQualifier {
547    pub start: IntervalField,
548    pub end: IntervalField,
549    /// Digits the leading field may have, when a precision was
550    /// written.
551    pub leading: Option<u32>,
552    /// Digits after the point in the seconds, when one was written.
553    pub fraction: Option<u32>,
554}
555
556impl fmt::Display for IntervalQualifier {
557    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
558        match self.start == self.end {
559            true => write!(f, "{}", self.start.word()),
560            false => write!(f, "{} TO {}", self.start.word(), self.end.word()),
561        }
562    }
563}
564
565/// A run of digits and nothing else, which is what every field of a
566/// SQL interval string is: the sign is written once, in front of them
567/// all, and a field carries no sign of its own.
568fn uint(text: &str) -> Option<i64> {
569    if text.is_empty() || !text.bytes().all(|b| b.is_ascii_digit()) {
570        return None;
571    }
572    text.parse().ok()
573}
574
575/// The same, with the bound a field carries when something is written
576/// in front of it.
577fn bounded(text: &str, leading: bool, most: i64) -> Option<i64> {
578    let value = uint(text)?;
579    match leading || value <= most {
580        true => Some(value),
581        false => None,
582    }
583}
584
585/// The seconds of an interval string, which is the one field that may
586/// carry a fraction.
587fn interval_seconds(text: &str, leading: bool, digits: Option<u32>) -> Option<i64> {
588    let (whole, frac) = match text.split_once('.') {
589        Some((whole, frac)) => (whole, Some(frac)),
590        None => (text, None),
591    };
592    let mut nanos = bounded(whole, leading, 59)?.checked_mul(NANOS_PER_SEC)?;
593    if let Some(frac) = frac {
594        if frac.is_empty() || frac.len() > 9 || !frac.bytes().all(|b| b.is_ascii_digit()) {
595            return None;
596        }
597        if digits.is_some_and(|limit| frac.len() > limit as usize) {
598            return None;
599        }
600        let scale = 10i64.pow(9 - frac.len() as u32);
601        nanos = nanos.checked_add(frac.parse::<i64>().ok()? * scale)?;
602    }
603    Some(nanos)
604}
605
606/// Whether a written time or datetime carries a zone.
607///
608/// The date is dropped first, because a date's own dashes are not
609/// offsets and are the only other sign a written value has.
610fn has_offset(text: &str) -> bool {
611    let time = match text.split_once(['T', 't', ' ']) {
612        Some((_, time)) => time,
613        None => text,
614    };
615    time.ends_with('Z') || time.ends_with('z') || time.contains('+') || time.contains('-')
616}
617
618/// `yyyy-mm-dd` as a day count.
619fn parse_date(text: &str) -> Option<i32> {
620    let bytes = text.as_bytes();
621    if bytes.len() != 10 || bytes[4] != b'-' || bytes[7] != b'-' {
622        return None;
623    }
624    let year: i32 = text[0..4].parse().ok()?;
625    let month: u32 = text[5..7].parse().ok()?;
626    let day: u32 = text[8..10].parse().ok()?;
627    if !(1..=9999).contains(&year)
628        || !(1..=12).contains(&month)
629        || day < 1
630        || day > days_in(year, month)
631    {
632        return None;
633    }
634    Some(days_from_civil(year, month, day))
635}
636
637/// `hh:mm[:ss[.fffffffff]][offset]` as nanoseconds since midnight and
638/// the offset in minutes when one is written.
639fn parse_time(text: &str) -> Option<(i64, Option<i16>)> {
640    let (time, offset) = split_offset(text)?;
641    let mut parts = time.split(':');
642    let hour: i64 = parts.next()?.parse().ok()?;
643    let minute: i64 = parts.next()?.parse().ok()?;
644    let (second, nanos) = match parts.next() {
645        Some(rest) => parse_seconds(rest)?,
646        None => (0, 0),
647    };
648    if parts.next().is_some() || hour > 23 || minute > 59 || second > 59 {
649        return None;
650    }
651    let total = hour * NANOS_PER_HOUR + minute * NANOS_PER_MINUTE + second * NANOS_PER_SEC + nanos;
652    Some((total, offset))
653}
654
655/// `ss` or `ss.fff` as whole seconds and nanoseconds.
656fn parse_seconds(text: &str) -> Option<(i64, i64)> {
657    match text.split_once('.') {
658        None => Some((text.parse().ok()?, 0)),
659        Some((whole, frac)) => {
660            if frac.is_empty() || frac.len() > 9 || !frac.bytes().all(|b| b.is_ascii_digit()) {
661                return None;
662            }
663            let scale = 10i64.pow(9 - frac.len() as u32);
664            Some((whole.parse().ok()?, frac.parse::<i64>().ok()? * scale))
665        }
666    }
667}
668
669/// A time zone displacement on its own, as minutes east of UTC, or
670/// `None` for a string that is not one (GS15, ISO 7.1).
671///
672/// `SESSION SET TIME ZONE` is where a displacement is written with no
673/// time in front of it, so the reader below, which takes the zone off
674/// the end of a time, has nothing to take it off. What it accepts is
675/// what a zoned literal accepts, `Z` and `+hh`, `+hhmm` and `+hh:mm`
676/// either way of nought, and an empty body is the whole of the
677/// difference: a string that reads as a zone and leaves anything in
678/// front of it is a time and not a displacement.
679///
680/// A name is not a displacement and is refused as one. A zone name is
681/// a rule that changes when the zone database is updated, so a session
682/// set to `Europe/Dublin` would mean one thing today and another after
683/// an upgrade, and `02 §3.4` writes zu's answer to that down: an offset
684/// or nothing.
685pub fn zone_offset(text: &str) -> Option<i16> {
686    match split_offset(text.trim())? {
687        ("", Some(minutes)) => Some(minutes),
688        _ => None,
689    }
690}
691
692/// A written time split into the part before the zone and the zone in
693/// minutes, `None` in the second place when no zone is written.
694///
695/// The caller has already taken the date off, so a sign here can only
696/// be an offset: a time of day has no other use for one.
697fn split_offset(text: &str) -> Option<(&str, Option<i16>)> {
698    if let Some(rest) = text.strip_suffix('Z').or_else(|| text.strip_suffix('z')) {
699        return Some((rest, Some(0)));
700    }
701    let Some(sign) = text.find(['+', '-']) else {
702        return Some((text, None));
703    };
704    let (body, zone) = text.split_at(sign);
705    let negative = zone.starts_with('-');
706    let digits = &zone[1..];
707    let (hours, minutes) = match digits.split_once(':') {
708        Some((h, m)) => (h, m),
709        // `+0700` and `+07` are both written in the wild and both mean
710        // the same offset.
711        None if digits.len() == 4 => (&digits[0..2], &digits[2..4]),
712        None => (digits, "0"),
713    };
714    let hours: i16 = hours.parse().ok()?;
715    let minutes: i16 = minutes.parse().ok()?;
716    if hours > 18 || minutes > 59 {
717        return None;
718    }
719    let total = hours * 60 + minutes;
720    Some((body, Some(if negative { -total } else { total })))
721}
722
723/// `yyyy-mm-ddThh:mm:ss` as nanoseconds since the epoch, plus the
724/// offset when one is written.
725///
726/// A date the calendar has and the word does not reads as no datetime,
727/// which the caller reports as a string that is not a value of the
728/// type. That is the truth about it: `9999-12-31T00:00:00` names an
729/// instant this build cannot hold, so there is nothing to hand back.
730fn parse_datetime(text: &str) -> Option<(i64, Option<i16>)> {
731    let Some((date, time)) = text
732        .split_once('T')
733        .or_else(|| text.split_once('t'))
734        .or_else(|| text.split_once(' '))
735    else {
736        // A date on its own is midnight, which is what the standard's
737        // datetime literal says and what the cast matrix expects of
738        // `CAST('2024-01-15' AS DATETIME)`. There is no offset to read
739        // out of a date, so the value is local until a zoned type asks
740        // for one and gets UTC.
741        return Some((instant_at(parse_date(text)?, 0)?, None));
742    };
743    let days = parse_date(date)?;
744    let (nanos, offset) = parse_time(time)?;
745    Some((instant_at(days, nanos)?, offset))
746}
747
748/// An ISO 8601 duration, `PnYnMnDTnHnMnS`.
749///
750/// The two kinds are decided by which fields are written, and a
751/// duration that writes both is refused rather than split, because a
752/// value that is half months and half nanoseconds is exactly the thing
753/// the two kinds exist to prevent.
754fn parse_duration(text: &str) -> Option<Temporal> {
755    let (negative, rest) = match text.strip_prefix('-') {
756        Some(rest) => (true, rest),
757        None => (false, text.strip_prefix('+').unwrap_or(text)),
758    };
759    let rest = rest.strip_prefix('P').or_else(|| rest.strip_prefix('p'))?;
760    let (date_part, time_part) = match rest.split_once(['T', 't']) {
761        Some((d, t)) => (d, Some(t)),
762        None => (rest, None),
763    };
764    if date_part.is_empty() && time_part.is_none_or(str::is_empty) {
765        return None;
766    }
767    let mut months = 0i64;
768    let mut nanos = 0i64;
769    for (value, unit) in fields(date_part)? {
770        match unit {
771            'Y' | 'y' => months = months.checked_add(whole(value)?.checked_mul(12)?)?,
772            'M' | 'm' => months = months.checked_add(whole(value)?)?,
773            'W' | 'w' => nanos = nanos.checked_add(scaled(value, 7 * NANOS_PER_DAY)?)?,
774            'D' | 'd' => nanos = nanos.checked_add(scaled(value, NANOS_PER_DAY)?)?,
775            _ => return None,
776        }
777    }
778    for (value, unit) in fields(time_part.unwrap_or(""))? {
779        match unit {
780            'H' | 'h' => nanos = nanos.checked_add(scaled(value, NANOS_PER_HOUR)?)?,
781            'M' | 'm' => nanos = nanos.checked_add(scaled(value, NANOS_PER_MINUTE)?)?,
782            'S' | 's' => nanos = nanos.checked_add(scaled(value, NANOS_PER_SEC)?)?,
783            _ => return None,
784        }
785    }
786    if months != 0 && nanos != 0 {
787        return None;
788    }
789    let sign = if negative { -1 } else { 1 };
790    Some(if nanos != 0 || months == 0 {
791        Temporal::Duration(DurationKind::DayTime, sign * nanos)
792    } else {
793        Temporal::Duration(DurationKind::YearMonth, sign * months)
794    })
795}
796
797/// A duration part split into its number and unit pairs.
798fn fields(text: &str) -> Option<Vec<(&str, char)>> {
799    let mut out = Vec::new();
800    let mut start = 0;
801    for (ix, ch) in text.char_indices() {
802        if ch.is_ascii_digit() || ch == '.' || ch == ',' {
803            continue;
804        }
805        // ISO 21.2 writes every field of a duration string as an
806        // `<iso8601 sint>`, a sign and then digits, so a sign at the
807        // head of a field opens it rather than ending the one before:
808        // `P-1D` is minus a day and there is no form with the sign in
809        // front of the `P`.
810        if (ch == '-' || ch == '+') && ix == start {
811            continue;
812        }
813        if ix == start {
814            return None;
815        }
816        out.push((&text[start..ix], ch));
817        start = ix + ch.len_utf8();
818    }
819    if start != text.len() {
820        return None;
821    }
822    Some(out)
823}
824
825/// A field written without a fraction, which is what the month fields
826/// need: a third of a month is not a number of anything.
827fn whole(text: &str) -> Option<i64> {
828    text.parse().ok()
829}
830
831/// A field times the size of its unit, with a fraction allowed because
832/// `PT0.5S` is half a second and half a second is nanoseconds.
833fn scaled(text: &str, unit: i64) -> Option<i64> {
834    let text = text.replace(',', ".");
835    // The sign comes off in front, because the fraction carries it as
836    // well: minus half a second is half a second the other way and not
837    // minus one plus a positive half.
838    let (sign, text) = match text.strip_prefix('-') {
839        Some(rest) => (-1, rest.to_string()),
840        None => (1, text.strip_prefix('+').unwrap_or(&text).to_string()),
841    };
842    let size = match text.split_once('.') {
843        None => text.parse::<i64>().ok()?.checked_mul(unit),
844        Some((whole, frac)) => {
845            if frac.len() > 9 || !frac.bytes().all(|b| b.is_ascii_digit()) {
846                return None;
847            }
848            let whole: i64 = if whole.is_empty() {
849                0
850            } else {
851                whole.parse().ok()?
852            };
853            let digits = frac.len() as u32;
854            let numerator: i64 = frac.parse().ok()?;
855            let part = unit.checked_mul(numerator)? / 10i64.pow(digits);
856            whole.checked_mul(unit)?.checked_add(part)
857        }
858    };
859    size?.checked_mul(sign)
860}
861
862/// Days in `month` of `year`, which is where the leap rule lives.
863/// The fields ISO 20.27 and 20.29 name for a record written in front of
864/// a temporal value function, in the order the standard writes them.
865///
866/// The names belong to the type and not to the record, which is what
867/// separates the two conditions this feeds: a name that is not on this
868/// list is 22G05 for a datetime and 22G07 for a duration, whatever the
869/// value beside it was, and a name that is on it and holds a
870/// thirteenth month is 22G06.
871///
872/// A time has no calendar part and a local value has no zone, so each
873/// type gets its own list rather than one list and a check afterwards.
874/// `DATE({hour: 1})` is not a date with an hour it will ignore.
875pub fn fields_of(ty: &LogicalType) -> &'static [&'static str] {
876    match ty {
877        LogicalType::Date => &["year", "month", "day"],
878        LogicalType::LocalTime => &["hour", "minute", "second"],
879        LogicalType::ZonedTime => &["hour", "minute", "second", "timezone"],
880        LogicalType::LocalDatetime => &["year", "month", "day", "hour", "minute", "second"],
881        LogicalType::ZonedDatetime => &[
882            "year", "month", "day", "hour", "minute", "second", "timezone",
883        ],
884        LogicalType::Duration(_) => &["year", "month", "day", "hour", "minute", "second"],
885        _ => &[],
886    }
887}
888
889/// The named parts a record constructor gave, before they are a value.
890///
891/// Every part is optional because the standard's fields are, and the
892/// meaning of an absent one differs by type: an absent month is
893/// January and an absent month in a duration is nought months. The
894/// seconds are a float because ISO's `<seconds value>` carries a
895/// fraction and the other five do not.
896#[derive(Clone, Copy, Debug, Default, PartialEq)]
897pub struct Parts {
898    pub year: Option<i64>,
899    pub month: Option<i64>,
900    pub day: Option<i64>,
901    pub hour: Option<i64>,
902    pub minute: Option<i64>,
903    pub second: Option<f64>,
904    /// The zone as an offset from UTC in minutes, which is the only
905    /// form zu holds one in; see the module note.
906    pub timezone: Option<i16>,
907}
908
909impl Parts {
910    /// The day count the calendar parts name, or `None` where they
911    /// name no day.
912    ///
913    /// The range checks are the calendar's own and not a clamp. A
914    /// thirteenth month has no day and a thirty-first of February has
915    /// none either, and answering with the nearest real day would turn
916    /// a statement that is wrong into a row that is wrong.
917    fn days(&self) -> Option<i32> {
918        let year = i32::try_from(self.year.unwrap_or(1)).ok()?;
919        let month = u32::try_from(self.month.unwrap_or(1)).ok()?;
920        let day = u32::try_from(self.day.unwrap_or(1)).ok()?;
921        if !(1..=9999).contains(&year) || !(1..=12).contains(&month) {
922            return None;
923        }
924        if day < 1 || day > days_in(year, month) {
925            return None;
926        }
927        Some(days_from_civil(year, month, day))
928    }
929
930    /// The nanoseconds into the day the clock parts name.
931    ///
932    /// Twenty-four hours is not a time and neither is sixty seconds:
933    /// the standard's `<hours value>` runs to 23 and its `<seconds
934    /// value>` stops short of 60, so a leap second is not spellable
935    /// here any more than it is in the string form.
936    fn nanos(&self) -> Option<i64> {
937        let hour = self.hour.unwrap_or(0);
938        let minute = self.minute.unwrap_or(0);
939        let second = self.second.unwrap_or(0.0);
940        if !(0..=23).contains(&hour) || !(0..=59).contains(&minute) {
941            return None;
942        }
943        if !(second.is_finite() && (0.0..60.0).contains(&second)) {
944            return None;
945        }
946        let whole = second.trunc() as i64;
947        let fraction = ((second - second.trunc()) * NANOS_PER_SEC as f64).round() as i64;
948        Some(hour * NANOS_PER_HOUR + minute * NANOS_PER_MINUTE + whole * NANOS_PER_SEC + fraction)
949    }
950
951    /// The duration the parts name, of whichever kind they name.
952    ///
953    /// The two kinds do not mix, for the reason the module note gives,
954    /// so a record naming a year and a day names no duration. The
955    /// parts are counts here rather than positions on a calendar, so
956    /// nothing is range checked: `DURATION({hour: 100})` is a hundred
957    /// hours and is a perfectly good length of time.
958    fn duration(&self) -> Option<Temporal> {
959        let months = self.year.unwrap_or(0).checked_mul(12)? + self.month.unwrap_or(0);
960        let has_months = self.year.is_some() || self.month.is_some();
961        let has_nanos = self.day.is_some()
962            || self.hour.is_some()
963            || self.minute.is_some()
964            || self.second.is_some();
965        if has_months && has_nanos {
966            return None;
967        }
968        if has_months {
969            return Some(Temporal::Duration(DurationKind::YearMonth, months));
970        }
971        let second = self.second.unwrap_or(0.0);
972        if !second.is_finite() {
973            return None;
974        }
975        let nanos = self
976            .day
977            .unwrap_or(0)
978            .checked_mul(NANOS_PER_DAY)?
979            .checked_add(self.hour.unwrap_or(0).checked_mul(NANOS_PER_HOUR)?)?
980            .checked_add(self.minute.unwrap_or(0).checked_mul(NANOS_PER_MINUTE)?)?
981            .checked_add((second * NANOS_PER_SEC as f64).round() as i64)?;
982        Some(Temporal::Duration(DurationKind::DayTime, nanos))
983    }
984}
985
986fn days_in(year: i32, month: u32) -> u32 {
987    match month {
988        1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
989        4 | 6 | 9 | 11 => 30,
990        _ if leap(year) => 29,
991        _ => 28,
992    }
993}
994
995fn leap(year: i32) -> bool {
996    year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)
997}
998
999/// Days from 1970-01-01 to a proleptic Gregorian date, and back.
1000///
1001/// This is Howard Hinnant's shift to a calendar whose year starts in
1002/// March, which makes the leap day the last day of the year and the
1003/// month lengths a repeating pattern with no table.
1004pub fn days_from_civil(year: i32, month: u32, day: u32) -> i32 {
1005    let y = if month <= 2 { year - 1 } else { year };
1006    let era = if y >= 0 { y } else { y - 399 } / 400;
1007    let yoe = y - era * 400;
1008    let m = month as i32;
1009    let doy = (153 * (if m > 2 { m - 3 } else { m + 9 }) + 2) / 5 + day as i32 - 1;
1010    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
1011    era * 146_097 + doe - 719_468
1012}
1013
1014/// The year, month and day a day count spells.
1015pub fn civil_from_days(days: i32) -> (i32, u32, u32) {
1016    let z = days + 719_468;
1017    let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
1018    let doe = z - era * 146_097;
1019    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
1020    let y = yoe + era * 400;
1021    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
1022    let mp = (5 * doy + 2) / 153;
1023    let day = (doy - (153 * mp + 2) / 5 + 1) as u32;
1024    let month = (if mp < 10 { mp + 3 } else { mp - 9 }) as u32;
1025    (if month <= 2 { y + 1 } else { y }, month, day)
1026}
1027
1028/// A date shifted by whole months, with the day clamped to the length
1029/// of the month it lands in. `None` when the result leaves the
1030/// calendar.
1031pub fn add_months(days: i32, months: i64) -> Option<i32> {
1032    let (year, month, day) = civil_from_days(days);
1033    let total = i64::from(year) * 12 + i64::from(month) - 1 + months;
1034    let new_year = i32::try_from(total.div_euclid(12)).ok()?;
1035    let new_month = (total.rem_euclid(12) + 1) as u32;
1036    if !(1..=9999).contains(&new_year) {
1037        return None;
1038    }
1039    let clamped = day.min(days_in(new_year, new_month));
1040    let out = days_from_civil(new_year, new_month, clamped);
1041    (MIN_DAY..=MAX_DAY).contains(&out).then_some(out)
1042}
1043
1044impl fmt::Display for Temporal {
1045    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1046        match *self {
1047            Temporal::Date(days) => {
1048                let (y, m, d) = civil_from_days(days);
1049                write!(f, "{y:04}-{m:02}-{d:02}")
1050            }
1051            Temporal::LocalTime(nanos) => write_time(f, nanos),
1052            Temporal::ZonedTime { nanos, offset } => {
1053                write_time(f, nanos)?;
1054                write_offset(f, offset)
1055            }
1056            Temporal::LocalDatetime(nanos) => write_datetime(f, nanos),
1057            Temporal::ZonedDatetime { nanos, offset } => {
1058                write_datetime(f, nanos + i64::from(offset) * NANOS_PER_MINUTE)?;
1059                write_offset(f, offset)
1060            }
1061            Temporal::Duration(kind, count) => write_duration(f, kind, count),
1062        }
1063    }
1064}
1065
1066fn write_time(f: &mut fmt::Formatter<'_>, nanos: i64) -> fmt::Result {
1067    let nanos = nanos.rem_euclid(NANOS_PER_DAY);
1068    let (h, m) = (nanos / NANOS_PER_HOUR, nanos / NANOS_PER_MINUTE % 60);
1069    let (s, frac) = (nanos / NANOS_PER_SEC % 60, nanos % NANOS_PER_SEC);
1070    write!(f, "{h:02}:{m:02}:{s:02}")?;
1071    if frac != 0 {
1072        write!(f, ".{:09}", frac)?;
1073    }
1074    Ok(())
1075}
1076
1077fn write_datetime(f: &mut fmt::Formatter<'_>, nanos: i64) -> fmt::Result {
1078    let days = nanos.div_euclid(NANOS_PER_DAY) as i32;
1079    let (y, m, d) = civil_from_days(days);
1080    write!(f, "{y:04}-{m:02}-{d:02}T")?;
1081    write_time(f, nanos.rem_euclid(NANOS_PER_DAY))
1082}
1083
1084fn write_offset(f: &mut fmt::Formatter<'_>, offset: i16) -> fmt::Result {
1085    if offset == 0 {
1086        return write!(f, "Z");
1087    }
1088    let sign = if offset < 0 { '-' } else { '+' };
1089    let (h, m) = (offset.abs() / 60, offset.abs() % 60);
1090    write!(f, "{sign}{h:02}:{m:02}")
1091}
1092
1093/// A duration written the way ISO writes it, which is the way it parses
1094/// back. A zero duration is `PT0S`, because `P` alone is not a value.
1095fn write_duration(f: &mut fmt::Formatter<'_>, kind: DurationKind, count: i64) -> fmt::Result {
1096    if count < 0 {
1097        write!(f, "-")?;
1098    }
1099    let count = count.unsigned_abs();
1100    write!(f, "P")?;
1101    if kind == DurationKind::YearMonth {
1102        let (years, months) = (count / 12, count % 12);
1103        if years != 0 {
1104            write!(f, "{years}Y")?;
1105        }
1106        if months != 0 || years == 0 {
1107            write!(f, "{months}M")?;
1108        }
1109        return Ok(());
1110    }
1111    let nanos = count as i128;
1112    let day = NANOS_PER_DAY as i128;
1113    let days = nanos / day;
1114    let rest = (nanos % day) as i64;
1115    if days != 0 {
1116        write!(f, "{days}D")?;
1117    }
1118    if rest == 0 && days != 0 {
1119        return Ok(());
1120    }
1121    write!(f, "T")?;
1122    let (h, m) = (rest / NANOS_PER_HOUR, rest / NANOS_PER_MINUTE % 60);
1123    let (s, frac) = (rest / NANOS_PER_SEC % 60, rest % NANOS_PER_SEC);
1124    if h != 0 {
1125        write!(f, "{h}H")?;
1126    }
1127    if m != 0 {
1128        write!(f, "{m}M")?;
1129    }
1130    if s != 0 || frac != 0 || (h == 0 && m == 0) {
1131        write!(f, "{s}")?;
1132        if frac != 0 {
1133            write!(f, ".{:09}", frac)?;
1134        }
1135        write!(f, "S")?;
1136    }
1137    Ok(())
1138}
1139
1140#[cfg(test)]
1141mod tests {
1142    use super::*;
1143
1144    fn date(text: &str) -> Temporal {
1145        Temporal::parse(&LogicalType::Date, text).expect(text)
1146    }
1147
1148    fn duration(text: &str) -> Temporal {
1149        Temporal::parse(&LogicalType::Duration(DurationKind::DayTime), text).expect(text)
1150    }
1151
1152    #[test]
1153    fn a_date_is_a_day_count_and_prints_back_as_it_was_written() {
1154        assert_eq!(date("1970-01-01"), Temporal::Date(0));
1155        assert_eq!(date("2024-01-15").to_string(), "2024-01-15");
1156        assert_eq!(date("0001-01-01"), Temporal::Date(MIN_DAY));
1157        assert_eq!(date("9999-12-31"), Temporal::Date(MAX_DAY));
1158        // A day the month does not have is not a date, which a day
1159        // count cannot say on its own and the parser has to.
1160        assert_eq!(Temporal::parse(&LogicalType::Date, "2023-02-29"), None);
1161        assert_eq!(date("2024-02-29").to_string(), "2024-02-29");
1162        assert_eq!(Temporal::parse(&LogicalType::Date, "2024-13-01"), None);
1163    }
1164
1165    #[test]
1166    fn a_round_trip_holds_across_the_whole_calendar() {
1167        let mut day = MIN_DAY;
1168        while day <= MAX_DAY {
1169            let (y, m, d) = civil_from_days(day);
1170            assert_eq!(days_from_civil(y, m, d), day, "{y:04}-{m:02}-{d:02}");
1171            day += 97;
1172        }
1173    }
1174
1175    #[test]
1176    fn a_time_takes_its_seconds_and_its_fraction_or_leaves_them_out() {
1177        let time = |t: &str| Temporal::parse(&LogicalType::LocalTime, t);
1178        assert_eq!(
1179            time("10:30"),
1180            Some(Temporal::LocalTime(37_800 * NANOS_PER_SEC))
1181        );
1182        assert_eq!(
1183            time("10:30:15.5").map(|t| t.to_string()),
1184            Some("10:30:15.500000000".into())
1185        );
1186        assert_eq!(time("24:00"), None);
1187        // A local type refuses a written zone rather than dropping it.
1188        assert_eq!(time("10:30+07:00"), None);
1189    }
1190
1191    /// Two spellings of one instant are one number, which is the reason
1192    /// a zoned value stores UTC and the offset apart.
1193    #[test]
1194    fn a_zoned_datetime_stores_the_instant_and_remembers_the_offset() {
1195        let a = Temporal::parse(&LogicalType::ZonedDatetime, "2024-01-15T10:00:00+07:00").unwrap();
1196        let b = Temporal::parse(&LogicalType::ZonedDatetime, "2024-01-15T03:00:00Z").unwrap();
1197        let (Temporal::ZonedDatetime { nanos: x, .. }, Temporal::ZonedDatetime { nanos: y, .. }) =
1198            (a, b)
1199        else {
1200            panic!("both are zoned datetimes")
1201        };
1202        assert_eq!(x, y);
1203        assert_eq!(a.to_string(), "2024-01-15T10:00:00+07:00");
1204        assert_eq!(b.to_string(), "2024-01-15T03:00:00Z");
1205    }
1206
1207    #[test]
1208    fn a_duration_is_one_kind_or_the_other_and_never_both() {
1209        assert_eq!(
1210            duration("P2D"),
1211            Temporal::Duration(DurationKind::DayTime, 2 * NANOS_PER_DAY)
1212        );
1213        assert_eq!(
1214            duration("P1Y2M"),
1215            Temporal::Duration(DurationKind::YearMonth, 14)
1216        );
1217        assert_eq!(
1218            duration("PT1H30M"),
1219            Temporal::Duration(DurationKind::DayTime, 90 * NANOS_PER_MINUTE)
1220        );
1221        assert_eq!(
1222            duration("PT0.5S"),
1223            Temporal::Duration(DurationKind::DayTime, NANOS_PER_SEC / 2)
1224        );
1225        assert_eq!(duration("P2D").to_string(), "P2D");
1226        assert_eq!(duration("P1Y2M").to_string(), "P1Y2M");
1227        assert_eq!(duration("PT1H30M").to_string(), "PT1H30M");
1228        // A month and a day in one value is the thing the two kinds
1229        // exist to prevent.
1230        assert!(Temporal::parse(&LogicalType::Duration(DurationKind::DayTime), "P1M1D").is_none());
1231        assert!(Temporal::parse(&LogicalType::Duration(DurationKind::DayTime), "P").is_none());
1232    }
1233
1234    /// ISO 21.2 writes each field of a duration string as an
1235    /// `<iso8601 sint>`, so the minus belongs to the field and there is
1236    /// no form with one in front of the `P`.
1237    #[test]
1238    fn a_field_of_a_duration_carries_its_own_sign() {
1239        assert_eq!(
1240            duration("P-1D"),
1241            Temporal::Duration(DurationKind::DayTime, -NANOS_PER_DAY)
1242        );
1243        assert_eq!(
1244            duration("P-1Y-2M"),
1245            Temporal::Duration(DurationKind::YearMonth, -14)
1246        );
1247        assert_eq!(
1248            duration("PT-0.5S"),
1249            Temporal::Duration(DurationKind::DayTime, -NANOS_PER_SEC / 2)
1250        );
1251        // Two signs of opposite kinds is a sum like any other: nine
1252        // hours less than a day.
1253        assert_eq!(
1254            duration("P1DT-3H"),
1255            Temporal::Duration(DurationKind::DayTime, NANOS_PER_DAY - 3 * NANOS_PER_HOUR)
1256        );
1257        // A sign with nothing behind it is not a field, and the sign
1258        // in front of the P was never a spelling of anything.
1259        assert!(Temporal::parse(&LogicalType::Duration(DurationKind::DayTime), "P-D").is_none());
1260        assert!(Temporal::parse(&LogicalType::Duration(DurationKind::DayTime), "P1-D").is_none());
1261    }
1262
1263    #[test]
1264    fn adding_months_clamps_to_the_length_of_the_month_it_lands_in() {
1265        let jan31 = days_from_civil(2024, 1, 31);
1266        assert_eq!(
1267            add_months(jan31, 1).map(civil_from_days),
1268            Some((2024, 2, 29))
1269        );
1270        assert_eq!(
1271            add_months(jan31, 13).map(civil_from_days),
1272            Some((2025, 2, 28))
1273        );
1274        assert_eq!(add_months(MAX_DAY, 1), None);
1275    }
1276
1277    #[test]
1278    fn a_written_value_reads_back_without_being_told_its_type() {
1279        assert_eq!(Temporal::parse_any("2024-01-15"), Some(date("2024-01-15")));
1280        assert_eq!(Temporal::parse_any("P2D"), Some(duration("P2D")));
1281        assert!(matches!(
1282            Temporal::parse_any("2024-01-15T10:00:00Z"),
1283            Some(Temporal::ZonedDatetime { .. })
1284        ));
1285        assert!(matches!(
1286            Temporal::parse_any("2024-01-15T10:00:00"),
1287            Some(Temporal::LocalDatetime(_))
1288        ));
1289        assert!(matches!(
1290            Temporal::parse_any("10:00:00"),
1291            Some(Temporal::LocalTime(_))
1292        ));
1293        assert_eq!(Temporal::parse_any("nonsense"), None);
1294    }
1295
1296    fn interval(text: &str, start: IntervalField, end: IntervalField) -> Option<Temporal> {
1297        Temporal::parse_sql_interval(
1298            text,
1299            &IntervalQualifier {
1300                start,
1301                end,
1302                leading: None,
1303                fraction: None,
1304            },
1305        )
1306    }
1307
1308    #[test]
1309    fn a_sql_interval_is_read_by_the_fields_its_qualifier_names() {
1310        use IntervalField::{Day, Hour, Minute, Month, Second, Year};
1311        assert_eq!(
1312            interval("1-2", Year, Month),
1313            Some(Temporal::Duration(DurationKind::YearMonth, 14))
1314        );
1315        assert_eq!(
1316            interval("2", Month, Month),
1317            Some(Temporal::Duration(DurationKind::YearMonth, 2))
1318        );
1319        assert_eq!(
1320            interval("3 04:05:06", Day, Second),
1321            duration("P3DT4H5M6S").into()
1322        );
1323        assert_eq!(interval("10:30", Hour, Minute), duration("PT10H30M").into());
1324        assert_eq!(interval("1.5", Second, Second), duration("PT1.5S").into());
1325        // The same string under two qualifiers is two values, which is
1326        // the whole reason the qualifier is not optional.
1327        assert_eq!(interval("1", Day, Day), duration("P1D").into());
1328        assert_eq!(interval("1", Hour, Hour), duration("PT1H").into());
1329        // And a string the qualifier did not describe is nothing.
1330        assert_eq!(interval("1-2", Day, Day), None);
1331        assert_eq!(interval("3 04:05:06", Hour, Minute), None);
1332        assert_eq!(interval("", Day, Day), None);
1333        assert_eq!(interval("1x", Day, Day), None);
1334    }
1335
1336    #[test]
1337    fn only_the_leading_field_of_an_interval_runs_past_its_own_size() {
1338        use IntervalField::{Day, Hour, Minute, Month, Second, Year};
1339        assert_eq!(interval("25", Hour, Hour), duration("PT25H").into());
1340        assert_eq!(interval("90", Minute, Minute), duration("PT1H30M").into());
1341        assert_eq!(
1342            interval("13", Month, Month),
1343            Some(Temporal::Duration(DurationKind::YearMonth, 13))
1344        );
1345        // A field with something written in front of it has the size
1346        // the calendar gives it, so these carry nothing and fail.
1347        assert_eq!(interval("1 25:00:00", Day, Second), None);
1348        assert_eq!(interval("1:60", Hour, Minute), None);
1349        assert_eq!(interval("1:60", Minute, Second), None);
1350        assert_eq!(interval("1-12", Year, Month), None);
1351    }
1352
1353    #[test]
1354    fn an_interval_precision_bounds_the_digits_that_were_written() {
1355        use IntervalField::{Day, Second};
1356        let bound = |text: &str, leading, fraction| {
1357            Temporal::parse_sql_interval(
1358                text,
1359                &IntervalQualifier {
1360                    start: Day,
1361                    end: Day,
1362                    leading,
1363                    fraction,
1364                },
1365            )
1366            .is_some()
1367        };
1368        assert!(bound("100", Some(3), None));
1369        assert!(!bound("1000", Some(3), None));
1370        assert!(bound("1000", None, None));
1371        let seconds = |text: &str, fraction| {
1372            Temporal::parse_sql_interval(
1373                text,
1374                &IntervalQualifier {
1375                    start: Second,
1376                    end: Second,
1377                    leading: Some(2),
1378                    fraction,
1379                },
1380            )
1381            .is_some()
1382        };
1383        // The leading precision counts the digits in front of the
1384        // point and the fraction counts the ones behind it, so a
1385        // second written to three places fits `SECOND(2, 3)`.
1386        assert!(seconds("1.123", Some(3)));
1387        assert!(!seconds("1.1234", Some(3)));
1388        assert!(!seconds("100.1", Some(3)));
1389    }
1390
1391    /// The word a datetime rides in runs out long before the calendar
1392    /// does, and every place that builds a datetime out of a day has to
1393    /// say so. These are the ends of it: the last instant the count
1394    /// reaches is in 2262 and the first is in 1677, and a day on either
1395    /// side of that has no datetime however good a date it is.
1396    #[test]
1397    fn a_datetime_stops_where_the_word_does_and_not_where_the_calendar_does() {
1398        let datetime = |text: &str| Temporal::parse(&LogicalType::LocalDatetime, text);
1399
1400        assert!(datetime("2262-04-11T00:00:00").is_some());
1401        assert!(datetime("1677-09-22T00:00:00").is_some());
1402        assert_eq!(datetime("9999-12-31T00:00:00"), None);
1403        assert_eq!(datetime("1677-09-21T00:00:00"), None);
1404        // A date on its own is midnight and takes the same bound, which
1405        // is the other arm of the same parse and was the other unchecked
1406        // multiplication.
1407        assert_eq!(datetime("9999-12-31"), None);
1408        assert!(datetime("2262-04-11").is_some());
1409
1410        // The last day is not whole. The count stops partway through it,
1411        // so an instant late enough on 2262-04-11 has nowhere to go
1412        // either, and that is the boundary rather than the day boundary.
1413        assert!(datetime("2262-04-11T23:47:16").is_some());
1414        assert_eq!(datetime("2262-04-11T23:47:17"), None);
1415
1416        assert_eq!(instant_at(0, 0), Some(0));
1417        assert_eq!(instant_at(1, 5), Some(NANOS_PER_DAY + 5));
1418        assert_eq!(instant_at(MAX_DAY, 0), None);
1419        assert_eq!(instant_at(MIN_DAY, 0), None);
1420    }
1421
1422    /// GS15. A displacement on its own, which is what a session takes,
1423    /// and never a name.
1424    #[test]
1425    fn a_session_zone_is_a_displacement_and_not_a_name() {
1426        assert_eq!(zone_offset("+07:00"), Some(420));
1427        assert_eq!(zone_offset("-05:30"), Some(-330));
1428        assert_eq!(zone_offset("+0700"), Some(420));
1429        assert_eq!(zone_offset("+07"), Some(420));
1430        assert_eq!(zone_offset(" Z "), Some(0));
1431        assert_eq!(zone_offset("-00:00"), Some(0));
1432        assert_eq!(zone_offset("+00:00"), Some(0));
1433
1434        assert_eq!(zone_offset("UTC"), None);
1435        assert_eq!(zone_offset("Europe/Dublin"), None);
1436        assert_eq!(zone_offset(""), None);
1437        // Eighteen hours is the widest displacement there is, and a
1438        // time in front of the sign is a time and not a zone.
1439        assert_eq!(zone_offset("+19:00"), None);
1440        assert_eq!(zone_offset("12:00:00+07:00"), None);
1441    }
1442}