Skip to main content

sql_values/postgres/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::postgres::{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::postgres::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 = crate::postgres::float::truncate_to_i64(
609            fraction * crate::postgres::float::int_to_f64(USECS_PER_DAY),
610        );
611        dt2time(time, tm);
612        tmask |= DTK_TIME_M;
613    }
614    Ok(tmask)
615}
616
617/// The `AM` or `PM` a literal writes, applied to its hour.
618fn apply_meridian(mer: i32, tm: &mut Tm) -> Result<(), Dterr> {
619    if mer != HR24 && tm.hour > HOURS_PER_DAY / 2 {
620        return Err(Dterr::FieldOverflow);
621    }
622    if mer == AM && tm.hour == HOURS_PER_DAY / 2 {
623        tm.hour = 0;
624    } else if mer == PM && tm.hour != HOURS_PER_DAY / 2 {
625        tm.hour += HOURS_PER_DAY / 2;
626    }
627    Ok(())
628}
629
630/// `dt2time`, a clock in microseconds as hours, minutes, seconds and the fraction.
631fn dt2time(time: i64, tm: &mut Tm) {
632    let narrow = |value: i64| i32::try_from(value).expect("a Julian day's clock fits int");
633    tm.hour = narrow(time / USECS_PER_HOUR);
634    let time = time - i64::from(tm.hour) * USECS_PER_HOUR;
635    tm.min = narrow(time / USECS_PER_MINUTE);
636    let time = time - i64::from(tm.min) * USECS_PER_MINUTE;
637    tm.sec = narrow(time / USECS_PER_SEC);
638    tm.fsec = time - i64::from(tm.sec) * USECS_PER_SEC;
639}
640
641/// `DecodeDateTime` over the tokens of a date or timestamp literal.
642#[expect(
643    clippy::too_many_lines,
644    reason = "the port keeps `DecodeDateTime` whole, one arm per token type, as PostgreSQL does"
645)]
646pub(crate) fn decode_date_time<'a>(
647    tokens: &Tokens,
648    context: InputContext<'a>,
649) -> Result<Decoded<'a>, Dterr> {
650    let mut fmask: u32 = 0;
651    let mut ptype = 0;
652    let mut mer = HR24;
653    let mut have_text_month = false;
654    let mut isjulian = false;
655    let mut is2digits = false;
656    let mut bc = false;
657    let mut dtype = DateType::Date;
658    let mut tm = Tm::default();
659    let mut tz: i32 = 0;
660    let mut named: Option<PgTimeZone> = None;
661    let mut abbreviated: Option<(Cow<'a, PgTimeZone>, String)> = None;
662    let order = context.date_order;
663
664    for index in 0..tokens.len() {
665        let (field, kind) = tokens.field(index);
666        let mut tmask: u32;
667        match kind {
668            FieldType::Date => {
669                if ptype == DTK_JULIAN {
670                    let (jday, end, erange) = strtoint(field, 0);
671                    if erange {
672                        return Err(Dterr::FieldOverflow);
673                    }
674                    (tm.year, tm.mon, tm.mday) = j2date(jday);
675                    isjulian = true;
676                    tz = decode_timezone(&field[end..])?;
677                    tmask = DTK_DATE_M | DTK_TIME_M | dtk_m(TZ);
678                    ptype = 0;
679                } else if ptype != 0
680                    || fmask & (dtk_m(MONTH) | dtk_m(DAY)) == dtk_m(MONTH) | dtk_m(DAY)
681                {
682                    if field[0].is_ascii_digit() || ptype != 0 {
683                        if ptype != 0 {
684                            if ptype != DTK_TIME {
685                                return Err(Dterr::BadFormat);
686                            }
687                            ptype = 0;
688                        }
689                        if fmask & DTK_TIME_M == DTK_TIME_M {
690                            return Err(Dterr::BadFormat);
691                        }
692                        let dash = field
693                            .iter()
694                            .position(|&b| b == b'-')
695                            .ok_or(Dterr::BadFormat)?;
696                        tz = decode_timezone(&field[dash..])?;
697                        tmask = 0;
698                        decode_number_field(
699                            &field[..dash],
700                            fmask,
701                            &mut tmask,
702                            &mut tm,
703                            &mut is2digits,
704                        )?;
705                        tmask |= dtk_m(TZ);
706                    } else {
707                        let name = String::from_utf8_lossy(field);
708                        named = Some(PgTimeZone::load(&name).ok_or(Dterr::BadTimezone)?);
709                        tmask = dtk_m(TZ);
710                    }
711                } else {
712                    tmask = 0;
713                    decode_date(field, fmask, &mut tmask, &mut is2digits, &mut tm, order)?;
714                }
715            }
716            FieldType::Time => {
717                if ptype != 0 {
718                    if ptype != DTK_TIME {
719                        return Err(Dterr::BadFormat);
720                    }
721                    ptype = 0;
722                }
723                decode_time(field, &mut tm)?;
724                tmask = DTK_TIME_M;
725                if time_overflows(&tm) {
726                    return Err(Dterr::FieldOverflow);
727                }
728            }
729            FieldType::Tz => {
730                tz = decode_timezone(field)?;
731                tmask = dtk_m(TZ);
732            }
733            FieldType::Number => {
734                if ptype != 0 {
735                    // A number field is digits with an optional fraction.
736                    let (value, end, erange) = strtoint(field, 0);
737                    if erange {
738                        return Err(Dterr::FieldOverflow);
739                    }
740                    match ptype {
741                        DTK_JULIAN => {
742                            tmask = julian_day(value, &field[end..], &mut tm)?;
743                            isjulian = true;
744                        }
745                        DTK_TIME => {
746                            tmask = 0;
747                            // With the date marked set, a success reads a time.
748                            decode_number_field(
749                                field,
750                                fmask | DTK_DATE_M,
751                                &mut tmask,
752                                &mut tm,
753                                &mut is2digits,
754                            )?;
755                        }
756                        _ => return Err(Dterr::BadFormat),
757                    }
758                    ptype = 0;
759                    dtype = DateType::Date;
760                } else {
761                    let point = field.iter().position(|&b| b == b'.');
762                    tmask = 0;
763                    if point.is_some() && fmask & DTK_DATE_M == 0 {
764                        decode_date(field, fmask, &mut tmask, &mut is2digits, &mut tm, order)?;
765                    } else if point.is_some_and(|point| point > 2)
766                        || (field.len() >= 6
767                            && (fmask & DTK_DATE_M == 0 || fmask & DTK_TIME_M == 0))
768                    {
769                        // A run-together date or time, with or without a fraction.
770                        decode_number_field(field, fmask, &mut tmask, &mut tm, &mut is2digits)?;
771                    } else {
772                        decode_number(
773                            field,
774                            have_text_month,
775                            fmask,
776                            &mut tmask,
777                            &mut tm,
778                            &mut is2digits,
779                            order,
780                        )?;
781                    }
782                }
783            }
784            FieldType::String | FieldType::Special => {
785                let word = decode_word(field, context)?;
786                let (kind, value) = match word {
787                    WordType::Fixed { west, dst } => {
788                        tz = west;
789                        (if dst { DTZ } else { TZ }, 0)
790                    }
791                    WordType::Dynamic { zone, upper } => {
792                        abbreviated = Some((zone, upper));
793                        (DYNTZ, 0)
794                    }
795                    WordType::Table(kind, value) => (kind, value),
796                    WordType::Unknown => (UNKNOWN_FIELD, 0),
797                };
798                if kind == IGNORE_DTF {
799                    continue;
800                }
801                tmask = dtk_m(kind);
802                match kind {
803                    RESERV => match value {
804                        DTK_NOW => {
805                            tmask = DTK_DATE_M | DTK_TIME_M | dtk_m(TZ);
806                            dtype = DateType::Date;
807                            (tm, tz) = current_time(context)?;
808                        }
809                        DTK_YESTERDAY | DTK_TODAY | DTK_TOMORROW => {
810                            tmask = DTK_DATE_M;
811                            dtype = DateType::Date;
812                            let (now, _) = current_time(context)?;
813                            let shift = match value {
814                                DTK_YESTERDAY => -1,
815                                DTK_TOMORROW => 1,
816                                _ => 0,
817                            };
818                            (tm.year, tm.mon, tm.mday) =
819                                j2date(date2j(now.year, now.mon, now.mday) + shift);
820                        }
821                        DTK_ZULU => {
822                            tmask = DTK_TIME_M | dtk_m(TZ);
823                            dtype = DateType::Date;
824                            (tm.hour, tm.min, tm.sec) = (0, 0, 0);
825                            tz = 0;
826                        }
827                        // `epoch`, `infinity` and `-infinity`.
828                        _ => {
829                            tmask = DTK_DATE_M | DTK_TIME_M | dtk_m(TZ);
830                            dtype = match value {
831                                DTK_EPOCH => DateType::Epoch,
832                                DTK_LATE => DateType::Late,
833                                _ => DateType::Early,
834                            };
835                        }
836                    },
837                    MONTH => {
838                        if fmask & dtk_m(MONTH) != 0
839                            && !have_text_month
840                            && fmask & dtk_m(DAY) == 0
841                            && (1..=31).contains(&tm.mon)
842                        {
843                            tm.mday = tm.mon;
844                            tmask = dtk_m(DAY);
845                        }
846                        have_text_month = true;
847                        tm.mon = value;
848                    }
849                    DTZMOD => {
850                        tmask |= dtk_m(DTZ);
851                        tz -= value;
852                    }
853                    DTZ => tmask |= dtk_m(TZ),
854                    TZ => {}
855                    DYNTZ => tmask |= dtk_m(TZ),
856                    AMPM => mer = value,
857                    ADBC => bc = value == 1,
858                    DOW => {}
859                    UNITS => {
860                        tmask = 0;
861                        if ptype != 0 {
862                            return Err(Dterr::BadFormat);
863                        }
864                        ptype = value;
865                    }
866                    ISOTIME => {
867                        tmask = 0;
868                        if fmask & DTK_DATE_M != DTK_DATE_M || ptype != 0 {
869                            return Err(Dterr::BadFormat);
870                        }
871                        ptype = value;
872                    }
873                    // `UNKNOWN_FIELD`, the one kind left.
874                    _ => {
875                        let name = String::from_utf8_lossy(field);
876                        named = Some(PgTimeZone::load(&name).ok_or(Dterr::BadFormat)?);
877                        tmask = dtk_m(TZ);
878                    }
879                }
880            }
881        }
882        if tmask & fmask != 0 {
883            return Err(Dterr::BadFormat);
884        }
885        fmask |= tmask;
886    }
887    if ptype != 0 {
888        return Err(Dterr::BadFormat);
889    }
890
891    let mut zone = ZoneSource::West(tz);
892    if dtype == DateType::Date {
893        validate_date(fmask, isjulian, is2digits, bc, &mut tm)?;
894        apply_meridian(mer, &mut tm)?;
895        if fmask & DTK_DATE_M != DTK_DATE_M {
896            return Err(Dterr::BadFormat);
897        }
898        let modified = fmask & dtk_m(DTZMOD) != 0;
899        if let Some(named) = named {
900            if modified {
901                return Err(Dterr::BadFormat);
902            }
903            zone = ZoneSource::Named(named);
904        }
905        if let Some((abbreviation_zone, upper)) = abbreviated {
906            if modified {
907                return Err(Dterr::BadFormat);
908            }
909            zone = ZoneSource::Abbreviation {
910                zone: abbreviation_zone,
911                upper,
912            };
913        }
914        if fmask & dtk_m(TZ) == 0 {
915            if modified {
916                return Err(Dterr::BadFormat);
917            }
918            zone = ZoneSource::Session;
919        }
920    }
921    Ok(Decoded { dtype, tm, zone })
922}
923
924/// `DecodeTimeOnly` over the tokens of a `time` or `timetz` literal, with `tzp` given as
925/// `time_in` and `timetz_in` give it.
926#[expect(
927    clippy::too_many_lines,
928    reason = "the port keeps `DecodeTimeOnly` whole, one arm per token type, as PostgreSQL does"
929)]
930pub(crate) fn decode_time_only<'a>(
931    tokens: &Tokens,
932    context: InputContext<'a>,
933) -> Result<DecodedTime<'a>, Dterr> {
934    let mut fmask: u32 = 0;
935    let mut ptype = 0;
936    let mut mer = HR24;
937    let mut isjulian = false;
938    let mut is2digits = false;
939    let mut bc = false;
940    let mut tm = Tm::default();
941    let mut tz: i32 = 0;
942    let mut named: Option<PgTimeZone> = None;
943    let mut abbreviated: Option<(Cow<'a, PgTimeZone>, String)> = None;
944    let order = context.date_order;
945    let count = tokens.len();
946    // A date is read only as the first field, before a time or with a date last.
947    let last_is_date = count >= 2 && tokens.field(count - 1).1 == FieldType::Date;
948    let second_is_time = count >= 2 && tokens.field(1).1 == FieldType::Time;
949
950    for index in 0..count {
951        let (field, kind) = tokens.field(index);
952        let mut tmask: u32;
953        match kind {
954            FieldType::Date => {
955                if index == 0 && (last_is_date || second_is_time) {
956                    tmask = 0;
957                    decode_date(field, fmask, &mut tmask, &mut is2digits, &mut tm, order)?;
958                } else if field[0].is_ascii_digit() {
959                    if fmask & DTK_TIME_M == DTK_TIME_M {
960                        return Err(Dterr::BadFormat);
961                    }
962                    let dash = field
963                        .iter()
964                        .position(|&b| b == b'-')
965                        .ok_or(Dterr::BadFormat)?;
966                    tz = decode_timezone(&field[dash..])?;
967                    tmask = 0;
968                    decode_number_field(
969                        &field[..dash],
970                        fmask | DTK_DATE_M,
971                        &mut tmask,
972                        &mut tm,
973                        &mut is2digits,
974                    )?;
975                    tmask |= dtk_m(TZ);
976                } else {
977                    let name = String::from_utf8_lossy(field);
978                    named = Some(PgTimeZone::load(&name).ok_or(Dterr::BadTimezone)?);
979                    tmask = dtk_m(TZ);
980                }
981            }
982            FieldType::Time => {
983                if ptype != 0 {
984                    if ptype != DTK_TIME {
985                        return Err(Dterr::BadFormat);
986                    }
987                    ptype = 0;
988                }
989                decode_time(field, &mut tm)?;
990                tmask = DTK_TIME_M;
991            }
992            FieldType::Tz => {
993                tz = decode_timezone(field)?;
994                tmask = dtk_m(TZ);
995            }
996            FieldType::Number => {
997                if ptype != 0 {
998                    // A number field is digits with an optional fraction.
999                    let (value, end, erange) = strtoint(field, 0);
1000                    if erange {
1001                        return Err(Dterr::FieldOverflow);
1002                    }
1003                    match ptype {
1004                        DTK_JULIAN => {
1005                            tmask = julian_day(value, &field[end..], &mut tm)?;
1006                            isjulian = true;
1007                        }
1008                        DTK_TIME => {
1009                            tmask = 0;
1010                            // With the date marked set, a success reads a time.
1011                            decode_number_field(
1012                                field,
1013                                fmask | DTK_DATE_M,
1014                                &mut tmask,
1015                                &mut tm,
1016                                &mut is2digits,
1017                            )?;
1018                        }
1019                        _ => return Err(Dterr::BadFormat),
1020                    }
1021                    ptype = 0;
1022                } else {
1023                    tmask = 0;
1024                    match field.iter().position(|&b| b == b'.') {
1025                        Some(_) if index == 0 && last_is_date => {
1026                            decode_date(field, fmask, &mut tmask, &mut is2digits, &mut tm, order)?;
1027                        }
1028                        Some(point) if point <= 2 => return Err(Dterr::BadFormat),
1029                        Some(_) => {
1030                            decode_number_field(
1031                                field,
1032                                fmask | DTK_DATE_M,
1033                                &mut tmask,
1034                                &mut tm,
1035                                &mut is2digits,
1036                            )?;
1037                        }
1038                        None if field.len() > 4 => {
1039                            decode_number_field(
1040                                field,
1041                                fmask | DTK_DATE_M,
1042                                &mut tmask,
1043                                &mut tm,
1044                                &mut is2digits,
1045                            )?;
1046                        }
1047                        None => decode_number(
1048                            field,
1049                            false,
1050                            fmask | DTK_DATE_M,
1051                            &mut tmask,
1052                            &mut tm,
1053                            &mut is2digits,
1054                            order,
1055                        )?,
1056                    }
1057                }
1058            }
1059            FieldType::String | FieldType::Special => {
1060                let (kind, value) = match decode_word(field, context)? {
1061                    WordType::Fixed { west, dst } => {
1062                        tz = west;
1063                        (if dst { DTZ } else { TZ }, 0)
1064                    }
1065                    WordType::Dynamic { zone, upper } => {
1066                        abbreviated = Some((zone, upper));
1067                        (DYNTZ, 0)
1068                    }
1069                    WordType::Table(kind, value) => (kind, value),
1070                    WordType::Unknown => (UNKNOWN_FIELD, 0),
1071                };
1072                if kind == IGNORE_DTF {
1073                    continue;
1074                }
1075                tmask = dtk_m(kind);
1076                match kind {
1077                    RESERV => match value {
1078                        DTK_NOW => {
1079                            tmask = DTK_TIME_M;
1080                            (tm, _) = current_time(context)?;
1081                        }
1082                        DTK_ZULU => {
1083                            tmask = DTK_TIME_M | dtk_m(TZ);
1084                            (tm.hour, tm.min, tm.sec) = (0, 0, 0);
1085                        }
1086                        _ => return Err(Dterr::BadFormat),
1087                    },
1088                    DTZMOD => {
1089                        tmask |= dtk_m(DTZ);
1090                        tz -= value;
1091                    }
1092                    DTZ | DYNTZ => tmask |= dtk_m(TZ),
1093                    TZ => {}
1094                    AMPM => mer = value,
1095                    ADBC => bc = value == 1,
1096                    UNITS | ISOTIME => {
1097                        tmask = 0;
1098                        if ptype != 0 {
1099                            return Err(Dterr::BadFormat);
1100                        }
1101                        ptype = value;
1102                    }
1103                    UNKNOWN_FIELD => {
1104                        let name = String::from_utf8_lossy(field);
1105                        named = Some(PgTimeZone::load(&name).ok_or(Dterr::BadFormat)?);
1106                        tmask = dtk_m(TZ);
1107                    }
1108                    // `MONTH` and `DOW`.
1109                    _ => return Err(Dterr::BadFormat),
1110                }
1111            }
1112        }
1113        if tmask & fmask != 0 {
1114            return Err(Dterr::BadFormat);
1115        }
1116        fmask |= tmask;
1117    }
1118    if ptype != 0 {
1119        return Err(Dterr::BadFormat);
1120    }
1121
1122    validate_date(fmask, isjulian, is2digits, bc, &mut tm)?;
1123    apply_meridian(mer, &mut tm)?;
1124    if time_overflows(&tm) {
1125        return Err(Dterr::FieldOverflow);
1126    }
1127    if fmask & DTK_TIME_M != DTK_TIME_M {
1128        return Err(Dterr::BadFormat);
1129    }
1130    let modified = fmask & dtk_m(DTZMOD) != 0;
1131    // `DecodeDate` and a Julian day set the date whole, so a literal has all of it or none.
1132    let dated = fmask & DTK_DATE_M == DTK_DATE_M;
1133    let mut zone = ZoneSource::West(tz);
1134    if let Some(named) = named {
1135        if modified {
1136            return Err(Dterr::BadFormat);
1137        }
1138        zone = match named.fixed_offset() {
1139            Some(east) => ZoneSource::West(-east),
1140            None if dated => ZoneSource::Named(named),
1141            None => return Err(Dterr::BadFormat),
1142        };
1143    }
1144    if let Some((abbreviation_zone, upper)) = abbreviated {
1145        if modified {
1146            return Err(Dterr::BadFormat);
1147        }
1148        zone = ZoneSource::Abbreviation {
1149            zone: abbreviation_zone,
1150            upper,
1151        };
1152    }
1153    if fmask & dtk_m(TZ) == 0 {
1154        if modified {
1155            return Err(Dterr::BadFormat);
1156        }
1157        zone = ZoneSource::Session;
1158    }
1159    Ok(DecodedTime { tm, dated, zone })
1160}