Skip to main content

sql_values/datetime/
decode.rs

1//! PostgreSQL 18's `DecodeDateTime` and `DecodeTimeOnly`, with `DecodeDate`, `DecodeNumber`,
2//! `DecodeNumberField`, `DecodeTime`, `DecodeTimezone` and `ValidateDate`, ported from
3//! `datetime.c` with PostgreSQL's names and order of checks. The session state the C reads from globals, `DateOrder`, the
4//! session's `TimeZone` and the transaction's start, comes from the [`InputContext`].
5
6use alloc::{borrow::Cow, string::String};
7
8use super::{
9    DateTimeError, InputContext, PgTimestampTz, USECS_PER_DAY, USECS_PER_HOUR, USECS_PER_MINUTE,
10    USECS_PER_SEC, date2j, days_in_month, j2date, timestamp2tm,
11    tokens::{
12        ADBC, AMPM, BadFormat, DATE_TOKENS, DAY, DOW, DOY, DTK_DATE_M, DTK_EPOCH, DTK_JULIAN,
13        DTK_LATE, DTK_NOW, DTK_TIME, DTK_TIME_M, DTK_TODAY, DTK_TOMORROW, DTK_YESTERDAY, DTK_ZULU,
14        DTZ, DTZMOD, DYNTZ, FieldType, IGNORE_DTF, ISOTIME, MONTH, RESERV, TZ, Tokens, UNITS,
15        UNKNOWN_FIELD, YEAR, dtk_m, lookup, parse_fraction, parse_fractional_second, strtoint,
16        strtoll,
17    },
18    utc_offset,
19};
20use crate::{PgTimeZone, zone::Meaning};
21
22/// `HOURS_PER_DAY`.
23const HOURS_PER_DAY: i32 = 24;
24const AM: i32 = 0;
25const PM: i32 = 1;
26const HR24: i32 = 2;
27
28/// `DateOrder`, the field order of `DateStyle` for a date written in numbers alone.
29#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
30pub enum DateOrder {
31    /// `MDY`, month, day, year, PostgreSQL's stock order.
32    Mdy,
33    /// `DMY`, day, month, year.
34    Dmy,
35    /// `YMD`, year, month, day.
36    Ymd,
37}
38
39/// A `DTERR` code, or session state the context lacks.
40#[derive(Debug, Clone, Copy, PartialEq, Eq)]
41pub(crate) enum Dterr {
42    /// `DTERR_BAD_FORMAT`.
43    BadFormat,
44    /// `DTERR_FIELD_OVERFLOW` or `DTERR_MD_FIELD_OVERFLOW`.
45    FieldOverflow,
46    /// `DTERR_TZDISP_OVERFLOW`.
47    TzDispOverflow,
48    /// `DTERR_BAD_TIMEZONE` or `DTERR_BAD_ZONE_ABBREV`.
49    BadTimezone,
50    /// An answer the readers give besides PostgreSQL's codes.
51    Other(DateTimeError),
52}
53
54impl From<BadFormat> for Dterr {
55    fn from(_: BadFormat) -> Self {
56        Self::BadFormat
57    }
58}
59
60impl Dterr {
61    /// `DateTimeParseError`'s error for a literal of `pg_type`.
62    pub(crate) const fn for_type(self, pg_type: crate::PgType) -> DateTimeError {
63        match self {
64            Self::BadFormat => DateTimeError::InvalidInputSyntax(pg_type),
65            Self::FieldOverflow => DateTimeError::FieldValueOutOfRange,
66            Self::TzDispOverflow => DateTimeError::TimeZoneDisplacementOutOfRange,
67            Self::BadTimezone => DateTimeError::TimeZoneNotRecognized,
68            Self::Other(error) => error,
69        }
70    }
71}
72
73/// `struct pg_tm` as the decoders fill it, with `fsec` beside it.
74#[derive(Debug, Clone, Copy, Default)]
75pub(crate) struct Tm {
76    pub(crate) year: i32,
77    pub(crate) mon: i32,
78    pub(crate) mday: i32,
79    pub(crate) hour: i32,
80    pub(crate) min: i32,
81    pub(crate) sec: i32,
82    pub(crate) yday: i32,
83    /// Microseconds of the second, `fsec`.
84    pub(crate) fsec: i64,
85}
86
87impl Tm {
88    /// `time2t`, the clock in microseconds.
89    pub(crate) fn clock(&self) -> i64 {
90        ((i64::from(self.hour) * 60 + i64::from(self.min)) * 60 + i64::from(self.sec))
91            * USECS_PER_SEC
92            + self.fsec
93    }
94}
95
96/// `dtype`, what a literal reads as.
97#[derive(Debug, Clone, Copy, PartialEq, Eq)]
98pub(crate) enum DateType {
99    /// `DTK_DATE`, the fields of a date and time.
100    Date,
101    /// `DTK_EPOCH`.
102    Epoch,
103    /// `DTK_LATE`, `infinity`.
104    Late,
105    /// `DTK_EARLY`, `-infinity`.
106    Early,
107}
108
109/// Where the offset of a `DTK_DATE` literal comes from, which `DecodeDateTime` resolves last.
110#[derive(Debug, Clone)]
111pub(crate) enum ZoneSource<'a> {
112    /// `*tzp` set by the literal, seconds west of UTC.
113    West(i32),
114    /// `namedTz`, `DetermineTimeZoneOffset` in a zone the literal names.
115    Named(PgTimeZone),
116    /// `abbrevTz`, `DetermineTimeZoneAbbrevOffset` of the uppercased abbreviation.
117    Abbreviation {
118        zone: Cow<'a, PgTimeZone>,
119        upper: String,
120    },
121    /// The session's `TimeZone`, when the literal writes none.
122    Session,
123}
124
125/// What `DecodeTimeOnly` leaves its caller.
126#[derive(Debug)]
127pub(crate) struct DecodedTime<'a> {
128    pub(crate) tm: Tm,
129    /// Whether the literal writes a full date, which dates the zone's offset in place of the
130    /// current date.
131    pub(crate) dated: bool,
132    /// [`ZoneSource::Named`] only for a dated literal.
133    pub(crate) zone: ZoneSource<'a>,
134}
135
136/// What `DecodeDateTime` leaves its caller.
137#[derive(Debug)]
138pub(crate) struct Decoded<'a> {
139    pub(crate) dtype: DateType,
140    pub(crate) tm: Tm,
141    pub(crate) zone: ZoneSource<'a>,
142}
143
144/// A `DecodeTimezoneAbbrev` and `DecodeSpecial` answer, the token type and its value.
145pub(crate) enum WordType<'a> {
146    /// A `datetktbl` token type and value.
147    Table(i32, i32),
148    /// `TZ` or `DTZ`, an offset west of UTC in seconds.
149    Fixed { west: i32, dst: bool },
150    /// `DYNTZ`, the uppercased abbreviation and the zone that gives its meaning.
151    Dynamic {
152        zone: Cow<'a, PgTimeZone>,
153        upper: String,
154    },
155    /// `UNKNOWN_FIELD`.
156    Unknown,
157}
158
159/// `DecodeTimezoneAbbrev` falling back to `DecodeSpecial`: an abbreviation the session's zone
160/// uses, then one of the context's set, then a `datetktbl` word.
161pub(crate) fn decode_word<'a>(
162    word: &[u8],
163    context: InputContext<'a>,
164) -> Result<WordType<'a>, Dterr> {
165    let upper = String::from_utf8_lossy(word).to_ascii_uppercase();
166    if let Some(zone) = context.time_zone
167        && let Some((meaning, fixed)) = zone.abbreviation_is_known(&upper)
168    {
169        return Ok(if fixed {
170            WordType::Fixed {
171                west: -meaning.offset,
172                dst: meaning.dst,
173            }
174        } else {
175            WordType::Dynamic {
176                zone: Cow::Borrowed(zone),
177                upper,
178            }
179        });
180    }
181    match context.abbreviations.lookup(word) {
182        Some(Meaning::Fixed { offset, dst }) => {
183            return Ok(WordType::Fixed {
184                west: -*offset,
185                dst: *dst,
186            });
187        }
188        Some(Meaning::Zone(name)) => {
189            let zone = PgTimeZone::load(name).ok_or(Dterr::BadTimezone)?;
190            return Ok(WordType::Dynamic {
191                zone: Cow::Owned(zone),
192                upper,
193            });
194        }
195        None => {}
196    }
197    Ok(match lookup(DATE_TOKENS, word) {
198        Some((kind, value)) => WordType::Table(kind, value),
199        None => WordType::Unknown,
200    })
201}
202
203/// `DecodeTimezone`, the offset west of UTC in seconds a numeric zone writes, `*tzp`.
204pub(crate) fn decode_timezone(text: &[u8]) -> Result<i32, Dterr> {
205    let negative = match text.first() {
206        Some(b'+') => false,
207        Some(b'-') => true,
208        _ => return Err(Dterr::BadFormat),
209    };
210    let (mut hour, mut at, erange) = strtoint(text, 1);
211    if erange {
212        return Err(Dterr::TzDispOverflow);
213    }
214    let mut minute = 0;
215    let mut second = 0;
216    if text.get(at) == Some(&b':') {
217        let (value, end, erange) = strtoint(text, at + 1);
218        if erange {
219            return Err(Dterr::TzDispOverflow);
220        }
221        (minute, at) = (value, end);
222        if text.get(at) == Some(&b':') {
223            let (value, end, erange) = strtoint(text, at + 1);
224            if erange {
225                return Err(Dterr::TzDispOverflow);
226            }
227            (second, at) = (value, end);
228        }
229    } else if at == text.len() && text.len() > 3 {
230        minute = hour % 100;
231        hour /= 100;
232    }
233    if !(0..=15).contains(&hour) || !(0..60).contains(&minute) || !(0..60).contains(&second) {
234        return Err(Dterr::TzDispOverflow);
235    }
236    let east = (hour * 60 + minute) * 60 + second;
237    if at != text.len() {
238        return Err(Dterr::BadFormat);
239    }
240    Ok(if negative { east } else { -east })
241}
242
243/// `DecodeTimeCommon` with `INTERVAL_FULL_RANGE` and `DecodeTime`, a time field into `tm`.
244pub(crate) fn decode_time(text: &[u8], tm: &mut Tm) -> Result<(), Dterr> {
245    // A time field starts with digits and a colon.
246    let (hour, mut at, erange) = strtoll(text, 0);
247    if erange {
248        return Err(Dterr::FieldOverflow);
249    }
250    let (mut minute, end, erange) = strtoint(text, at + 1);
251    if erange {
252        return Err(Dterr::FieldOverflow);
253    }
254    at = end;
255    let (mut hour, mut second, mut fsec) = (hour, 0, 0);
256    match text.get(at) {
257        None => {}
258        Some(b'.') => {
259            // `mm:ss.sss`, minutes and seconds.
260            fsec = parse_fractional_second(&text[at..])?;
261            second = minute;
262            minute = i32::try_from(hour).map_err(|_| Dterr::FieldOverflow)?;
263            hour = 0;
264        }
265        // The field holds digits, colons and points alone, so this is a colon.
266        Some(_) => {
267            let (value, end, erange) = strtoint(text, at + 1);
268            if erange {
269                return Err(Dterr::FieldOverflow);
270            }
271            second = value;
272            match text.get(end) {
273                Some(b'.') => fsec = parse_fractional_second(&text[end..])?,
274                None => {}
275                Some(_) => return Err(Dterr::BadFormat),
276            }
277        }
278    }
279    // The digits make the hour positive and the fraction is within a second.
280    if !(0..60).contains(&minute) || !(0..=60).contains(&second) {
281        return Err(Dterr::FieldOverflow);
282    }
283    tm.hour = i32::try_from(hour).map_err(|_| Dterr::FieldOverflow)?;
284    tm.min = minute;
285    tm.sec = second;
286    tm.fsec = i64::from(fsec);
287    Ok(())
288}
289
290/// `time_overflows` on a clock whose fields are not negative and whose fraction is within a
291/// second, as the decoders leave every clock.
292pub(crate) fn time_overflows(tm: &Tm) -> bool {
293    !(0..=HOURS_PER_DAY).contains(&tm.hour)
294        || !(0..60).contains(&tm.min)
295        || !(0..=60).contains(&tm.sec)
296        || tm.clock() > USECS_PER_DAY
297}
298
299/// C's `atoi` of digits, `strtol` saturating and then narrowed to `int`.
300fn atoi(digits: &[u8]) -> i32 {
301    let (value, _, _) = strtoll(digits, 0);
302    // Intended loss, as C's conversion of the `long` to `int` keeps its low 32 bits.
303    value as i32
304}
305
306/// `DecodeNumberField`, a run of digits as a date or a time, answering `DTK_DATE` or
307/// `DTK_TIME` with the fields it sets in `tmask`.
308pub(crate) fn decode_number_field(
309    text: &[u8],
310    fmask: u32,
311    tmask: &mut u32,
312    tm: &mut Tm,
313    is2digits: &mut bool,
314) -> Result<i32, Dterr> {
315    if !text.iter().all(|b| b.is_ascii_digit() || *b == b'.') {
316        return Err(Dterr::BadFormat);
317    }
318    let mut digits = text;
319    if let Some(point) = text.iter().position(|&b| b == b'.') {
320        tm.fsec = i64::from(parse_fractional_second(&text[point..])?);
321        digits = &text[..point];
322    } else if fmask & DTK_DATE_M != DTK_DATE_M && digits.len() >= 6 {
323        *tmask = DTK_DATE_M;
324        let len = digits.len();
325        tm.mday = atoi(&digits[len - 2..]);
326        tm.mon = atoi(&digits[len - 4..len - 2]);
327        tm.year = atoi(&digits[..len - 4]);
328        if len - 4 == 2 {
329            *is2digits = true;
330        }
331        return Ok(super::tokens::DTK_DATE);
332    }
333    if fmask & DTK_TIME_M != DTK_TIME_M {
334        match digits.len() {
335            6 => {
336                *tmask = DTK_TIME_M;
337                tm.sec = atoi(&digits[4..]);
338                tm.min = atoi(&digits[2..4]);
339                tm.hour = atoi(&digits[..2]);
340                return Ok(DTK_TIME);
341            }
342            4 => {
343                *tmask = DTK_TIME_M;
344                tm.sec = 0;
345                tm.min = atoi(&digits[2..]);
346                tm.hour = atoi(&digits[..2]);
347                return Ok(DTK_TIME);
348            }
349            _ => {}
350        }
351    }
352    Err(Dterr::BadFormat)
353}
354
355/// `DecodeNumber`, one number of a date, placed by what the literal has so far and the
356/// context's `DateOrder`.
357pub(crate) fn decode_number(
358    text: &[u8],
359    have_text_month: bool,
360    fmask: u32,
361    tmask: &mut u32,
362    tm: &mut Tm,
363    is2digits: &mut bool,
364    order: Option<DateOrder>,
365) -> Result<(), Dterr> {
366    *tmask = 0;
367    let flen = text.len();
368    let (value, end, erange) = strtoint(text, 0);
369    if erange {
370        return Err(Dterr::FieldOverflow);
371    }
372    if end == 0 {
373        return Err(Dterr::BadFormat);
374    }
375    // The callers pass digits, with a fraction only after one or two of them.
376    if end < flen {
377        tm.fsec = i64::from(parse_fractional_second(&text[end..])?);
378    }
379    if flen == 3 && fmask & DTK_DATE_M == dtk_m(YEAR) && (1..=366).contains(&value) {
380        *tmask = dtk_m(DOY) | dtk_m(MONTH) | dtk_m(DAY);
381        tm.yday = value;
382        return Ok(());
383    }
384    let needs_order = || order.ok_or(Dterr::Other(DateTimeError::NeedsDateOrder));
385    match fmask & DTK_DATE_M {
386        0 => {
387            if flen >= 3 || needs_order()? == DateOrder::Ymd {
388                *tmask = dtk_m(YEAR);
389                tm.year = value;
390            } else if needs_order()? == DateOrder::Dmy {
391                *tmask = dtk_m(DAY);
392                tm.mday = value;
393            } else {
394                *tmask = dtk_m(MONTH);
395                tm.mon = value;
396            }
397        }
398        mask if mask == dtk_m(YEAR) => {
399            *tmask = dtk_m(MONTH);
400            tm.mon = value;
401        }
402        mask if mask == dtk_m(MONTH) => {
403            if have_text_month && (flen >= 3 || needs_order()? == DateOrder::Ymd) {
404                *tmask = dtk_m(YEAR);
405                tm.year = value;
406            } else {
407                *tmask = dtk_m(DAY);
408                tm.mday = value;
409            }
410        }
411        mask if mask == dtk_m(YEAR) | dtk_m(MONTH) => {
412            if have_text_month && flen >= 3 && *is2digits {
413                *tmask = dtk_m(DAY);
414                tm.mday = tm.year;
415                tm.year = value;
416                *is2digits = false;
417            } else {
418                *tmask = dtk_m(DAY);
419                tm.mday = value;
420            }
421        }
422        mask if mask == dtk_m(DAY) => {
423            *tmask = dtk_m(MONTH);
424            tm.mon = value;
425        }
426        mask if mask == dtk_m(MONTH) | dtk_m(DAY) => {
427            *tmask = dtk_m(YEAR);
428            tm.year = value;
429        }
430        // The full date. A day without a month comes first and only under `DMY`, so a year
431        // and a day never stand alone.
432        _ => {
433            decode_number_field(text, fmask, tmask, tm, is2digits)?;
434            return Ok(());
435        }
436    }
437    if *tmask == dtk_m(YEAR) {
438        *is2digits = flen <= 2;
439    }
440    Ok(())
441}
442
443/// `DecodeDate`, a date of delimited fields, text months first.
444pub(crate) fn decode_date(
445    text: &[u8],
446    mut fmask: u32,
447    tmask: &mut u32,
448    is2digits: &mut bool,
449    tm: &mut Tm,
450    order: Option<DateOrder>,
451) -> Result<(), Dterr> {
452    *tmask = 0;
453    let mut fields: [&[u8]; super::tokens::MAX_DATE_FIELDS] = [&[]; super::tokens::MAX_DATE_FIELDS];
454    let mut count = 0;
455    let mut at = 0;
456    while at < text.len() && count < fields.len() {
457        while at < text.len() && !text[at].is_ascii_alphanumeric() {
458            at += 1;
459        }
460        if at == text.len() {
461            return Err(Dterr::BadFormat);
462        }
463        let start = at;
464        if text[at].is_ascii_digit() {
465            while at < text.len() && text[at].is_ascii_digit() {
466                at += 1;
467            }
468        } else {
469            while at < text.len() && text[at].is_ascii_alphabetic() {
470                at += 1;
471            }
472        }
473        fields[count] = &text[start..at];
474        count += 1;
475        // The C overwrites the character after the field with its terminator.
476        at += usize::from(at < text.len());
477    }
478    let fields = &fields[..count];
479    let mut have_text_month = false;
480    let mut done = [false; super::tokens::MAX_DATE_FIELDS];
481    for (field, done) in fields.iter().zip(&mut done) {
482        if field.first().is_some_and(u8::is_ascii_alphabetic) {
483            let (kind, value) = lookup(DATE_TOKENS, field).unwrap_or((UNKNOWN_FIELD, 0));
484            if kind == IGNORE_DTF {
485                continue;
486            }
487            let dmask = dtk_m(kind);
488            if kind != MONTH {
489                return Err(Dterr::BadFormat);
490            }
491            tm.mon = value;
492            have_text_month = true;
493            if fmask & dmask != 0 {
494                return Err(Dterr::BadFormat);
495            }
496            fmask |= dmask;
497            *tmask |= dmask;
498            *done = true;
499        }
500    }
501    for (field, done) in fields.iter().zip(done) {
502        if done {
503            continue;
504        }
505        let mut dmask = 0;
506        decode_number(
507            field,
508            have_text_month,
509            fmask,
510            &mut dmask,
511            tm,
512            is2digits,
513            order,
514        )?;
515        // `DecodeNumber` sets only fields not yet set.
516        fmask |= dmask;
517        *tmask |= dmask;
518    }
519    if fmask & !(dtk_m(DOY) | dtk_m(TZ)) != DTK_DATE_M {
520        return Err(Dterr::BadFormat);
521    }
522    Ok(())
523}
524
525/// `ValidateDate`, the year by era and digits, the day of year, and the month and day.
526pub(crate) fn validate_date(
527    fmask: u32,
528    isjulian: bool,
529    is2digits: bool,
530    bc: bool,
531    tm: &mut Tm,
532) -> Result<(), Dterr> {
533    if fmask & dtk_m(YEAR) != 0 {
534        // A Julian day's year is already right.
535        if isjulian {
536            // Nothing to adjust.
537        } else if bc {
538            if tm.year <= 0 {
539                return Err(Dterr::FieldOverflow);
540            }
541            tm.year = -(tm.year - 1);
542        } else if is2digits {
543            // Two digits make a year from 0 to 99.
544            tm.year += if tm.year < 70 { 2000 } else { 1900 };
545        } else if tm.year <= 0 {
546            return Err(Dterr::FieldOverflow);
547        }
548    }
549    if fmask & dtk_m(DOY) != 0 {
550        (tm.year, tm.mon, tm.mday) = j2date(date2j(tm.year, 1, 1).wrapping_add(tm.yday - 1));
551    }
552    if fmask & dtk_m(MONTH) != 0 && !(1..=12).contains(&tm.mon) {
553        return Err(Dterr::FieldOverflow);
554    }
555    if fmask & dtk_m(DAY) != 0 && !(1..=31).contains(&tm.mday) {
556        return Err(Dterr::FieldOverflow);
557    }
558    if fmask & DTK_DATE_M == DTK_DATE_M && tm.mday > days_in_month(tm.year, tm.mon) {
559        return Err(Dterr::FieldOverflow);
560    }
561    Ok(())
562}
563
564/// `GetCurrentTimeUsec`, the local fields of the transaction's start in the session's zone and
565/// its offset west of UTC.
566pub(crate) fn current_time(context: InputContext<'_>) -> Result<(Tm, i32), Dterr> {
567    let now = context
568        .now
569        .ok_or(Dterr::Other(DateTimeError::NeedsCurrentTime))?;
570    let zone = context
571        .time_zone
572        .ok_or(Dterr::Other(DateTimeError::NeedsTimeZone))?;
573    local_fields(now, zone).map_err(Dterr::Other)
574}
575
576/// `timestamp2tm` in `zone`, the local fields of an instant and its offset west of UTC, which
577/// refuses an infinity as out of range.
578pub(crate) fn local_fields(
579    at: PgTimestampTz,
580    zone: &PgTimeZone,
581) -> Result<(Tm, i32), DateTimeError> {
582    if !at.is_finite() {
583        return Err(DateTimeError::TimestampOutOfRange);
584    }
585    let offset = utc_offset(zone, at.pg_micros())?;
586    let (year, mon, mday, clock) = timestamp2tm(at.pg_micros() + i64::from(offset) * USECS_PER_SEC);
587    let tm = Tm {
588        year,
589        mon,
590        mday,
591        hour: i32::try_from(clock / USECS_PER_HOUR).expect("an hour of the day fits int"),
592        min: i32::try_from(clock % USECS_PER_HOUR / USECS_PER_MINUTE).expect("a minute fits int"),
593        sec: i32::try_from(clock % USECS_PER_MINUTE / USECS_PER_SEC).expect("a second fits int"),
594        yday: 0,
595        fsec: clock % USECS_PER_SEC,
596    };
597    Ok((tm, -offset))
598}
599
600/// A Julian day number after `j` or `julian`, with the fraction of the day after it, into `tm`,
601/// answering the fields it sets.
602fn julian_day(value: i32, fraction: &[u8], tm: &mut Tm) -> Result<u32, Dterr> {
603    let mut tmask = DTK_DATE_M;
604    (tm.year, tm.mon, tm.mday) = j2date(value);
605    if !fraction.is_empty() {
606        let fraction = parse_fraction(fraction)?;
607        // C's conversion of the `double` to `int64` truncates.
608        let time =
609            crate::float::truncate_to_i64(fraction * crate::float::int_to_f64(USECS_PER_DAY));
610        dt2time(time, tm);
611        tmask |= DTK_TIME_M;
612    }
613    Ok(tmask)
614}
615
616/// The `AM` or `PM` a literal writes, applied to its hour.
617fn apply_meridian(mer: i32, tm: &mut Tm) -> Result<(), Dterr> {
618    if mer != HR24 && tm.hour > HOURS_PER_DAY / 2 {
619        return Err(Dterr::FieldOverflow);
620    }
621    if mer == AM && tm.hour == HOURS_PER_DAY / 2 {
622        tm.hour = 0;
623    } else if mer == PM && tm.hour != HOURS_PER_DAY / 2 {
624        tm.hour += HOURS_PER_DAY / 2;
625    }
626    Ok(())
627}
628
629/// `dt2time`, a clock in microseconds as hours, minutes, seconds and the fraction.
630fn dt2time(time: i64, tm: &mut Tm) {
631    let narrow = |value: i64| i32::try_from(value).expect("a Julian day's clock fits int");
632    tm.hour = narrow(time / USECS_PER_HOUR);
633    let time = time - i64::from(tm.hour) * USECS_PER_HOUR;
634    tm.min = narrow(time / USECS_PER_MINUTE);
635    let time = time - i64::from(tm.min) * USECS_PER_MINUTE;
636    tm.sec = narrow(time / USECS_PER_SEC);
637    tm.fsec = time - i64::from(tm.sec) * USECS_PER_SEC;
638}
639
640/// `DecodeDateTime` over the tokens of a date or timestamp literal.
641#[expect(
642    clippy::too_many_lines,
643    reason = "the port keeps `DecodeDateTime` whole, one arm per token type, as PostgreSQL does"
644)]
645pub(crate) fn decode_date_time<'a>(
646    tokens: &Tokens,
647    context: InputContext<'a>,
648) -> Result<Decoded<'a>, Dterr> {
649    let mut fmask: u32 = 0;
650    let mut ptype = 0;
651    let mut mer = HR24;
652    let mut have_text_month = false;
653    let mut isjulian = false;
654    let mut is2digits = false;
655    let mut bc = false;
656    let mut dtype = DateType::Date;
657    let mut tm = Tm::default();
658    let mut tz: i32 = 0;
659    let mut named: Option<PgTimeZone> = None;
660    let mut abbreviated: Option<(Cow<'a, PgTimeZone>, String)> = None;
661    let order = context.date_order;
662
663    for index in 0..tokens.len() {
664        let (field, kind) = tokens.field(index);
665        let mut tmask: u32;
666        match kind {
667            FieldType::Date => {
668                if ptype == DTK_JULIAN {
669                    let (jday, end, erange) = strtoint(field, 0);
670                    if erange {
671                        return Err(Dterr::FieldOverflow);
672                    }
673                    (tm.year, tm.mon, tm.mday) = j2date(jday);
674                    isjulian = true;
675                    tz = decode_timezone(&field[end..])?;
676                    tmask = DTK_DATE_M | DTK_TIME_M | dtk_m(TZ);
677                    ptype = 0;
678                } else if ptype != 0
679                    || fmask & (dtk_m(MONTH) | dtk_m(DAY)) == dtk_m(MONTH) | dtk_m(DAY)
680                {
681                    if field[0].is_ascii_digit() || ptype != 0 {
682                        if ptype != 0 {
683                            if ptype != DTK_TIME {
684                                return Err(Dterr::BadFormat);
685                            }
686                            ptype = 0;
687                        }
688                        if fmask & DTK_TIME_M == DTK_TIME_M {
689                            return Err(Dterr::BadFormat);
690                        }
691                        let dash = field
692                            .iter()
693                            .position(|&b| b == b'-')
694                            .ok_or(Dterr::BadFormat)?;
695                        tz = decode_timezone(&field[dash..])?;
696                        tmask = 0;
697                        decode_number_field(
698                            &field[..dash],
699                            fmask,
700                            &mut tmask,
701                            &mut tm,
702                            &mut is2digits,
703                        )?;
704                        tmask |= dtk_m(TZ);
705                    } else {
706                        let name = String::from_utf8_lossy(field);
707                        named = Some(PgTimeZone::load(&name).ok_or(Dterr::BadTimezone)?);
708                        tmask = dtk_m(TZ);
709                    }
710                } else {
711                    tmask = 0;
712                    decode_date(field, fmask, &mut tmask, &mut is2digits, &mut tm, order)?;
713                }
714            }
715            FieldType::Time => {
716                if ptype != 0 {
717                    if ptype != DTK_TIME {
718                        return Err(Dterr::BadFormat);
719                    }
720                    ptype = 0;
721                }
722                decode_time(field, &mut tm)?;
723                tmask = DTK_TIME_M;
724                if time_overflows(&tm) {
725                    return Err(Dterr::FieldOverflow);
726                }
727            }
728            FieldType::Tz => {
729                tz = decode_timezone(field)?;
730                tmask = dtk_m(TZ);
731            }
732            FieldType::Number => {
733                if ptype != 0 {
734                    // A number field is digits with an optional fraction.
735                    let (value, end, erange) = strtoint(field, 0);
736                    if erange {
737                        return Err(Dterr::FieldOverflow);
738                    }
739                    match ptype {
740                        DTK_JULIAN => {
741                            tmask = julian_day(value, &field[end..], &mut tm)?;
742                            isjulian = true;
743                        }
744                        DTK_TIME => {
745                            tmask = 0;
746                            // With the date marked set, a success reads a time.
747                            decode_number_field(
748                                field,
749                                fmask | DTK_DATE_M,
750                                &mut tmask,
751                                &mut tm,
752                                &mut is2digits,
753                            )?;
754                        }
755                        _ => return Err(Dterr::BadFormat),
756                    }
757                    ptype = 0;
758                    dtype = DateType::Date;
759                } else {
760                    let point = field.iter().position(|&b| b == b'.');
761                    tmask = 0;
762                    if point.is_some() && fmask & DTK_DATE_M == 0 {
763                        decode_date(field, fmask, &mut tmask, &mut is2digits, &mut tm, order)?;
764                    } else if point.is_some_and(|point| point > 2)
765                        || (field.len() >= 6
766                            && (fmask & DTK_DATE_M == 0 || fmask & DTK_TIME_M == 0))
767                    {
768                        // A run-together date or time, with or without a fraction.
769                        decode_number_field(field, fmask, &mut tmask, &mut tm, &mut is2digits)?;
770                    } else {
771                        decode_number(
772                            field,
773                            have_text_month,
774                            fmask,
775                            &mut tmask,
776                            &mut tm,
777                            &mut is2digits,
778                            order,
779                        )?;
780                    }
781                }
782            }
783            FieldType::String | FieldType::Special => {
784                let word = decode_word(field, context)?;
785                let (kind, value) = match word {
786                    WordType::Fixed { west, dst } => {
787                        tz = west;
788                        (if dst { DTZ } else { TZ }, 0)
789                    }
790                    WordType::Dynamic { zone, upper } => {
791                        abbreviated = Some((zone, upper));
792                        (DYNTZ, 0)
793                    }
794                    WordType::Table(kind, value) => (kind, value),
795                    WordType::Unknown => (UNKNOWN_FIELD, 0),
796                };
797                if kind == IGNORE_DTF {
798                    continue;
799                }
800                tmask = dtk_m(kind);
801                match kind {
802                    RESERV => match value {
803                        DTK_NOW => {
804                            tmask = DTK_DATE_M | DTK_TIME_M | dtk_m(TZ);
805                            dtype = DateType::Date;
806                            (tm, tz) = current_time(context)?;
807                        }
808                        DTK_YESTERDAY | DTK_TODAY | DTK_TOMORROW => {
809                            tmask = DTK_DATE_M;
810                            dtype = DateType::Date;
811                            let (now, _) = current_time(context)?;
812                            let shift = match value {
813                                DTK_YESTERDAY => -1,
814                                DTK_TOMORROW => 1,
815                                _ => 0,
816                            };
817                            (tm.year, tm.mon, tm.mday) =
818                                j2date(date2j(now.year, now.mon, now.mday) + shift);
819                        }
820                        DTK_ZULU => {
821                            tmask = DTK_TIME_M | dtk_m(TZ);
822                            dtype = DateType::Date;
823                            (tm.hour, tm.min, tm.sec) = (0, 0, 0);
824                            tz = 0;
825                        }
826                        // `epoch`, `infinity` and `-infinity`.
827                        _ => {
828                            tmask = DTK_DATE_M | DTK_TIME_M | dtk_m(TZ);
829                            dtype = match value {
830                                DTK_EPOCH => DateType::Epoch,
831                                DTK_LATE => DateType::Late,
832                                _ => DateType::Early,
833                            };
834                        }
835                    },
836                    MONTH => {
837                        if fmask & dtk_m(MONTH) != 0
838                            && !have_text_month
839                            && fmask & dtk_m(DAY) == 0
840                            && (1..=31).contains(&tm.mon)
841                        {
842                            tm.mday = tm.mon;
843                            tmask = dtk_m(DAY);
844                        }
845                        have_text_month = true;
846                        tm.mon = value;
847                    }
848                    DTZMOD => {
849                        tmask |= dtk_m(DTZ);
850                        tz -= value;
851                    }
852                    DTZ => tmask |= dtk_m(TZ),
853                    TZ => {}
854                    DYNTZ => tmask |= dtk_m(TZ),
855                    AMPM => mer = value,
856                    ADBC => bc = value == 1,
857                    DOW => {}
858                    UNITS => {
859                        tmask = 0;
860                        if ptype != 0 {
861                            return Err(Dterr::BadFormat);
862                        }
863                        ptype = value;
864                    }
865                    ISOTIME => {
866                        tmask = 0;
867                        if fmask & DTK_DATE_M != DTK_DATE_M || ptype != 0 {
868                            return Err(Dterr::BadFormat);
869                        }
870                        ptype = value;
871                    }
872                    // `UNKNOWN_FIELD`, the one kind left.
873                    _ => {
874                        let name = String::from_utf8_lossy(field);
875                        named = Some(PgTimeZone::load(&name).ok_or(Dterr::BadFormat)?);
876                        tmask = dtk_m(TZ);
877                    }
878                }
879            }
880        }
881        if tmask & fmask != 0 {
882            return Err(Dterr::BadFormat);
883        }
884        fmask |= tmask;
885    }
886    if ptype != 0 {
887        return Err(Dterr::BadFormat);
888    }
889
890    let mut zone = ZoneSource::West(tz);
891    if dtype == DateType::Date {
892        validate_date(fmask, isjulian, is2digits, bc, &mut tm)?;
893        apply_meridian(mer, &mut tm)?;
894        if fmask & DTK_DATE_M != DTK_DATE_M {
895            return Err(Dterr::BadFormat);
896        }
897        let modified = fmask & dtk_m(DTZMOD) != 0;
898        if let Some(named) = named {
899            if modified {
900                return Err(Dterr::BadFormat);
901            }
902            zone = ZoneSource::Named(named);
903        }
904        if let Some((abbreviation_zone, upper)) = abbreviated {
905            if modified {
906                return Err(Dterr::BadFormat);
907            }
908            zone = ZoneSource::Abbreviation {
909                zone: abbreviation_zone,
910                upper,
911            };
912        }
913        if fmask & dtk_m(TZ) == 0 {
914            if modified {
915                return Err(Dterr::BadFormat);
916            }
917            zone = ZoneSource::Session;
918        }
919    }
920    Ok(Decoded { dtype, tm, zone })
921}
922
923/// `DecodeTimeOnly` over the tokens of a `time` or `timetz` literal, with `tzp` given as
924/// `time_in` and `timetz_in` give it.
925#[expect(
926    clippy::too_many_lines,
927    reason = "the port keeps `DecodeTimeOnly` whole, one arm per token type, as PostgreSQL does"
928)]
929pub(crate) fn decode_time_only<'a>(
930    tokens: &Tokens,
931    context: InputContext<'a>,
932) -> Result<DecodedTime<'a>, Dterr> {
933    let mut fmask: u32 = 0;
934    let mut ptype = 0;
935    let mut mer = HR24;
936    let mut isjulian = false;
937    let mut is2digits = false;
938    let mut bc = false;
939    let mut tm = Tm::default();
940    let mut tz: i32 = 0;
941    let mut named: Option<PgTimeZone> = None;
942    let mut abbreviated: Option<(Cow<'a, PgTimeZone>, String)> = None;
943    let order = context.date_order;
944    let count = tokens.len();
945    // A date is read only as the first field, before a time or with a date last.
946    let last_is_date = count >= 2 && tokens.field(count - 1).1 == FieldType::Date;
947    let second_is_time = count >= 2 && tokens.field(1).1 == FieldType::Time;
948
949    for index in 0..count {
950        let (field, kind) = tokens.field(index);
951        let mut tmask: u32;
952        match kind {
953            FieldType::Date => {
954                if index == 0 && (last_is_date || second_is_time) {
955                    tmask = 0;
956                    decode_date(field, fmask, &mut tmask, &mut is2digits, &mut tm, order)?;
957                } else if field[0].is_ascii_digit() {
958                    if fmask & DTK_TIME_M == DTK_TIME_M {
959                        return Err(Dterr::BadFormat);
960                    }
961                    let dash = field
962                        .iter()
963                        .position(|&b| b == b'-')
964                        .ok_or(Dterr::BadFormat)?;
965                    tz = decode_timezone(&field[dash..])?;
966                    tmask = 0;
967                    decode_number_field(
968                        &field[..dash],
969                        fmask | DTK_DATE_M,
970                        &mut tmask,
971                        &mut tm,
972                        &mut is2digits,
973                    )?;
974                    tmask |= dtk_m(TZ);
975                } else {
976                    let name = String::from_utf8_lossy(field);
977                    named = Some(PgTimeZone::load(&name).ok_or(Dterr::BadTimezone)?);
978                    tmask = dtk_m(TZ);
979                }
980            }
981            FieldType::Time => {
982                if ptype != 0 {
983                    if ptype != DTK_TIME {
984                        return Err(Dterr::BadFormat);
985                    }
986                    ptype = 0;
987                }
988                decode_time(field, &mut tm)?;
989                tmask = DTK_TIME_M;
990            }
991            FieldType::Tz => {
992                tz = decode_timezone(field)?;
993                tmask = dtk_m(TZ);
994            }
995            FieldType::Number => {
996                if ptype != 0 {
997                    // A number field is digits with an optional fraction.
998                    let (value, end, erange) = strtoint(field, 0);
999                    if erange {
1000                        return Err(Dterr::FieldOverflow);
1001                    }
1002                    match ptype {
1003                        DTK_JULIAN => {
1004                            tmask = julian_day(value, &field[end..], &mut tm)?;
1005                            isjulian = true;
1006                        }
1007                        DTK_TIME => {
1008                            tmask = 0;
1009                            // With the date marked set, a success reads a time.
1010                            decode_number_field(
1011                                field,
1012                                fmask | DTK_DATE_M,
1013                                &mut tmask,
1014                                &mut tm,
1015                                &mut is2digits,
1016                            )?;
1017                        }
1018                        _ => return Err(Dterr::BadFormat),
1019                    }
1020                    ptype = 0;
1021                } else {
1022                    tmask = 0;
1023                    match field.iter().position(|&b| b == b'.') {
1024                        Some(_) if index == 0 && last_is_date => {
1025                            decode_date(field, fmask, &mut tmask, &mut is2digits, &mut tm, order)?;
1026                        }
1027                        Some(point) if point <= 2 => return Err(Dterr::BadFormat),
1028                        Some(_) => {
1029                            decode_number_field(
1030                                field,
1031                                fmask | DTK_DATE_M,
1032                                &mut tmask,
1033                                &mut tm,
1034                                &mut is2digits,
1035                            )?;
1036                        }
1037                        None if field.len() > 4 => {
1038                            decode_number_field(
1039                                field,
1040                                fmask | DTK_DATE_M,
1041                                &mut tmask,
1042                                &mut tm,
1043                                &mut is2digits,
1044                            )?;
1045                        }
1046                        None => decode_number(
1047                            field,
1048                            false,
1049                            fmask | DTK_DATE_M,
1050                            &mut tmask,
1051                            &mut tm,
1052                            &mut is2digits,
1053                            order,
1054                        )?,
1055                    }
1056                }
1057            }
1058            FieldType::String | FieldType::Special => {
1059                let (kind, value) = match decode_word(field, context)? {
1060                    WordType::Fixed { west, dst } => {
1061                        tz = west;
1062                        (if dst { DTZ } else { TZ }, 0)
1063                    }
1064                    WordType::Dynamic { zone, upper } => {
1065                        abbreviated = Some((zone, upper));
1066                        (DYNTZ, 0)
1067                    }
1068                    WordType::Table(kind, value) => (kind, value),
1069                    WordType::Unknown => (UNKNOWN_FIELD, 0),
1070                };
1071                if kind == IGNORE_DTF {
1072                    continue;
1073                }
1074                tmask = dtk_m(kind);
1075                match kind {
1076                    RESERV => match value {
1077                        DTK_NOW => {
1078                            tmask = DTK_TIME_M;
1079                            (tm, _) = current_time(context)?;
1080                        }
1081                        DTK_ZULU => {
1082                            tmask = DTK_TIME_M | dtk_m(TZ);
1083                            (tm.hour, tm.min, tm.sec) = (0, 0, 0);
1084                        }
1085                        _ => return Err(Dterr::BadFormat),
1086                    },
1087                    DTZMOD => {
1088                        tmask |= dtk_m(DTZ);
1089                        tz -= value;
1090                    }
1091                    DTZ | DYNTZ => tmask |= dtk_m(TZ),
1092                    TZ => {}
1093                    AMPM => mer = value,
1094                    ADBC => bc = value == 1,
1095                    UNITS | ISOTIME => {
1096                        tmask = 0;
1097                        if ptype != 0 {
1098                            return Err(Dterr::BadFormat);
1099                        }
1100                        ptype = value;
1101                    }
1102                    UNKNOWN_FIELD => {
1103                        let name = String::from_utf8_lossy(field);
1104                        named = Some(PgTimeZone::load(&name).ok_or(Dterr::BadFormat)?);
1105                        tmask = dtk_m(TZ);
1106                    }
1107                    // `MONTH` and `DOW`.
1108                    _ => return Err(Dterr::BadFormat),
1109                }
1110            }
1111        }
1112        if tmask & fmask != 0 {
1113            return Err(Dterr::BadFormat);
1114        }
1115        fmask |= tmask;
1116    }
1117    if ptype != 0 {
1118        return Err(Dterr::BadFormat);
1119    }
1120
1121    validate_date(fmask, isjulian, is2digits, bc, &mut tm)?;
1122    apply_meridian(mer, &mut tm)?;
1123    if time_overflows(&tm) {
1124        return Err(Dterr::FieldOverflow);
1125    }
1126    if fmask & DTK_TIME_M != DTK_TIME_M {
1127        return Err(Dterr::BadFormat);
1128    }
1129    let modified = fmask & dtk_m(DTZMOD) != 0;
1130    // `DecodeDate` and a Julian day set the date whole, so a literal has all of it or none.
1131    let dated = fmask & DTK_DATE_M == DTK_DATE_M;
1132    let mut zone = ZoneSource::West(tz);
1133    if let Some(named) = named {
1134        if modified {
1135            return Err(Dterr::BadFormat);
1136        }
1137        zone = match named.fixed_offset() {
1138            Some(east) => ZoneSource::West(-east),
1139            None if dated => ZoneSource::Named(named),
1140            None => return Err(Dterr::BadFormat),
1141        };
1142    }
1143    if let Some((abbreviation_zone, upper)) = abbreviated {
1144        if modified {
1145            return Err(Dterr::BadFormat);
1146        }
1147        zone = ZoneSource::Abbreviation {
1148            zone: abbreviation_zone,
1149            upper,
1150        };
1151    }
1152    if fmask & dtk_m(TZ) == 0 {
1153        if modified {
1154            return Err(Dterr::BadFormat);
1155        }
1156        zone = ZoneSource::Session;
1157    }
1158    Ok(DecodedTime { tm, dated, zone })
1159}