Skip to main content

sql_values/datetime/
input.rs

1//! PostgreSQL 18's `date_in`, `time_in`, `timetz_in`, `timestamp_in` and `timestamptz_in` for the
2//! ISO spelling, and the readers of the text PostgreSQL, MySQL and SQLite print.
3
4use alloc::{string::String, vec::Vec};
5
6use super::{
7    DateTimeError, POSTGRES_EPOCH_JDATE, PgDate, PgTime, PgTimeTz, PgTimestamp, PgTimestampTz,
8    USECS_PER_DAY, USECS_PER_HOUR, USECS_PER_MINUTE, USECS_PER_SEC, abbreviation_offset, date2j,
9    days_in_month, is_valid_julian, local_offset, tm2timestamp,
10};
11use crate::{
12    PgTimeZone, TimeZoneAbbreviations,
13    cast::{is_pg_space, trim_pg_space},
14    float::{round_ties_even, truncate_to_i64},
15    interval::date_word_era,
16    zone::{DEFAULT_ABBREVIATIONS, Meaning},
17};
18
19/// `MAX_TZDISP_HOUR`, the largest hour of an offset a literal writes.
20const MAX_TZDISP_HOUR: i32 = 15;
21/// The longest literal the readers take, well inside PostgreSQL's `MAXDATELEN` of 128 bytes
22/// for the fields they read.
23const MAX_LITERAL_LEN: usize = 64;
24/// 1970-01-01 00:00:00, `epoch`, in microseconds from 2000-01-01.
25const EPOCH_MICROS: i64 = -946_684_800_000_000;
26/// 1970-01-01, `epoch`, in days from 2000-01-01.
27const EPOCH_DAYS: i32 = -10_957;
28
29/// The session state PostgreSQL's input functions read, which the caller supplies.
30///
31/// ```
32/// use sql_values::{DateTimeError, InputContext, PgTimeZone, PgTimestampTz, TimeZoneAbbreviations};
33///
34/// let rome = PgTimeZone::parse("Europe/Rome").unwrap();
35/// let local = "2026-07-01 12:00:00";
36/// assert_eq!(
37///     PgTimestampTz::parse(local, InputContext::new()),
38///     Err(DateTimeError::NeedsTimeZone),
39/// );
40/// let at = PgTimestampTz::parse(local, InputContext::new().with_time_zone(&rome)).unwrap();
41/// assert_eq!(at.to_string(), "2026-07-01 10:00:00+00");
42///
43/// // `EST` is New York's time in `Default` and Brisbane's in `Australia`.
44/// let australia = TimeZoneAbbreviations::bundled("Australia").unwrap();
45/// let context = InputContext::new().with_time_zone_abbreviations(australia);
46/// let est = PgTimestampTz::parse("2026-07-01 12:00 EST", context).unwrap();
47/// assert_eq!(est.to_string(), "2026-07-01 02:00:00+00");
48/// ```
49#[derive(Debug, Clone, Copy)]
50pub struct InputContext<'a> {
51    time_zone: Option<&'a PgTimeZone>,
52    abbreviations: &'a TimeZoneAbbreviations,
53}
54
55impl<'a> InputContext<'a> {
56    /// A context with no time zone and the `Default` abbreviations, as a stock installation's
57    /// `timezone_abbreviations` names them.
58    #[must_use]
59    pub const fn new() -> Self {
60        Self {
61            time_zone: None,
62            abbreviations: &DEFAULT_ABBREVIATIONS,
63        }
64    }
65
66    /// The context with `zone` as the session's `TimeZone`, which reads a `timestamptz` written
67    /// without an offset, and whose own abbreviations a literal may write before those of the
68    /// set.
69    #[must_use]
70    pub const fn with_time_zone(self, zone: &'a PgTimeZone) -> Self {
71        Self {
72            time_zone: Some(zone),
73            ..self
74        }
75    }
76
77    /// The context with `abbreviations` as the session's `timezone_abbreviations`.
78    #[must_use]
79    pub const fn with_time_zone_abbreviations(
80        self,
81        abbreviations: &'a TimeZoneAbbreviations,
82    ) -> Self {
83        Self {
84            abbreviations,
85            ..self
86        }
87    }
88}
89
90impl Default for InputContext<'_> {
91    fn default() -> Self {
92        Self::new()
93    }
94}
95
96/// The reserved words `date_in`, `timestamp_in` and `timestamptz_in` read without a clock.
97enum Special {
98    /// `infinity` or `+infinity`, `DTK_LATE`.
99    Late,
100    /// `-infinity`, `DTK_EARLY`.
101    Early,
102    /// `epoch`, `DTK_EPOCH`.
103    Epoch,
104}
105
106/// A literal's fields as `DecodeDateTime` leaves them, already checked.
107struct Fields {
108    /// The proleptic Gregorian year, where year `Y` BC is `1 - Y`.
109    year: i32,
110    month: i32,
111    day: i32,
112    /// The clock in microseconds, up to 24:00:00.
113    clock: i64,
114    /// The offset east of UTC in seconds, when the literal writes one.
115    offset: Option<i32>,
116    /// The zone the literal names, when it writes one.
117    zone: Option<LiteralZone>,
118}
119
120/// What a date and time literal reads as.
121enum Literal {
122    Special(Special),
123    Fields(Fields),
124}
125
126/// A numeric offset as written, its sign and the digits and colons after it, before
127/// `DecodeTimezone` checks it.
128struct RawOffset<'a> {
129    negative: bool,
130    digits: &'a [u8],
131}
132
133/// What a word of a literal reads as, by `DecodeTimezoneAbbrev`, `DecodeSpecial` and
134/// `pg_tzset` in that order.
135enum Word {
136    /// `ad`, `false`, or `bc`, `true`.
137    Era(bool),
138    /// A zone written after the clock.
139    Zone(LiteralZone),
140}
141
142/// A zone a literal writes, by abbreviation or by name.
143#[derive(Clone)]
144enum LiteralZone {
145    /// `TZ` or `DTZ`, a fixed offset east of UTC in seconds.
146    Fixed(i32),
147    /// `DYNTZ`, the uppercased abbreviation's meaning in a zone at the literal's date.
148    Dynamic {
149        zone: PgTimeZone,
150        abbreviation: String,
151    },
152    /// A full zone name, `pg_tzset`.
153    Named(PgTimeZone),
154}
155
156/// A clock as written, before `DecodeTime` checks it.
157struct RawClock<'a> {
158    hour: [u8; 2],
159    minute: [u8; 2],
160    second: Option<[u8; 2]>,
161    /// The fraction from its point, `.` alone included.
162    fraction: Option<&'a [u8]>,
163    offset: Option<RawOffset<'a>>,
164}
165
166/// A byte cursor over a literal.
167struct Scanner<'a> {
168    bytes: &'a [u8],
169    at: usize,
170}
171
172impl<'a> Scanner<'a> {
173    const fn new(bytes: &'a [u8]) -> Self {
174        Self { bytes, at: 0 }
175    }
176
177    fn peek(&self) -> Option<u8> {
178        self.bytes.get(self.at).copied()
179    }
180
181    fn peek_at(&self, ahead: usize) -> Option<u8> {
182        self.bytes.get(self.at + ahead).copied()
183    }
184
185    fn eat(&mut self, byte: u8) -> bool {
186        let found = self.peek() == Some(byte);
187        self.at += usize::from(found);
188        found
189    }
190
191    fn digits(&mut self) -> &'a [u8] {
192        let start = self.at;
193        while self.peek().is_some_and(|b| b.is_ascii_digit()) {
194            self.at += 1;
195        }
196        &self.bytes[start..self.at]
197    }
198
199    fn two_digits(&mut self) -> Option<[u8; 2]> {
200        match (self.peek(), self.peek_at(1)) {
201            (Some(a), Some(b)) if a.is_ascii_digit() && b.is_ascii_digit() => {
202                self.at += 2;
203                Some([a, b])
204            }
205            _ => None,
206        }
207    }
208
209    fn spaces(&mut self) -> usize {
210        let start = self.at;
211        while self.peek().is_some_and(is_pg_space) {
212            self.at += 1;
213        }
214        self.at - start
215    }
216
217    fn is_done(&self) -> bool {
218        self.at == self.bytes.len()
219    }
220
221    /// `HH:MM[:SS[.f]]` and an optional offset after blanks.
222    fn clock(&mut self) -> Option<RawClock<'a>> {
223        let hour = self.two_digits()?;
224        if !self.eat(b':') {
225            return None;
226        }
227        let minute = self.two_digits()?;
228        let mut second = None;
229        let mut fraction = None;
230        if self.eat(b':') {
231            second = Some(self.two_digits()?);
232            if self.peek() == Some(b'.') {
233                let start = self.at;
234                self.at += 1;
235                self.digits();
236                fraction = Some(&self.bytes[start..self.at]);
237            }
238        }
239        if self.peek().is_some_and(|b| b.is_ascii_digit() || b == b'.') {
240            return None;
241        }
242        let before_offset = self.at;
243        self.spaces();
244        let offset = match self.peek() {
245            Some(sign @ (b'+' | b'-')) if self.peek_at(1).is_some_and(|b| b.is_ascii_digit()) => {
246                self.at += 1;
247                let start = self.at;
248                while self.peek().is_some_and(|b| b.is_ascii_digit() || b == b':') {
249                    self.at += 1;
250                }
251                if matches!(self.peek(), Some(b'.' | b'-')) {
252                    return None;
253                }
254                Some(RawOffset {
255                    negative: sign == b'-',
256                    digits: &self.bytes[start..self.at],
257                })
258            }
259            _ => {
260                self.at = before_offset;
261                None
262            }
263        };
264        Some(RawClock {
265            hour,
266            minute,
267            second,
268            fraction,
269            offset,
270        })
271    }
272
273    /// The words that end a literal, each a run of letters `ParseDateTime` keeps as one token,
274    /// lowercased, or `None` when something else is left.
275    fn words(&mut self) -> Option<Vec<Vec<u8>>> {
276        let mut words = Vec::new();
277        loop {
278            self.spaces();
279            if self.is_done() {
280                return Some(words);
281            }
282            let start = self.at;
283            while self.peek().is_some_and(|b| b.is_ascii_alphabetic()) {
284                self.at += 1;
285            }
286            if self.at == start || !(self.is_done() || self.peek().is_some_and(is_pg_space)) {
287                return None;
288            }
289            words.push(self.bytes[start..self.at].to_ascii_lowercase());
290        }
291    }
292}
293
294/// `strtoint` of decimal digits, `None` on `ERANGE`.
295fn strtoint(digits: &[u8]) -> Option<i32> {
296    digits.iter().try_fold(0i32, |value, &digit| {
297        value.checked_mul(10)?.checked_add(i32::from(digit - b'0'))
298    })
299}
300
301/// The value of two ASCII digits.
302fn two(digits: [u8; 2]) -> i32 {
303    i32::from(digits[0] - b'0') * 10 + i32::from(digits[1] - b'0')
304}
305
306/// `ParseFractionalSecond`, a fraction from its point as whole microseconds, `rint` of the
307/// `double` times a million.
308fn fractional_second(fraction: &[u8]) -> i64 {
309    if fraction.len() == 1 {
310        return 0;
311    }
312    let value: f64 = core::str::from_utf8(fraction)
313        .ok()
314        .and_then(|text| text.parse().ok())
315        .expect("a point and digits read as a double");
316    truncate_to_i64(round_ties_even(value * 1_000_000.0))
317}
318
319impl RawClock<'_> {
320    /// `DecodeTime`'s sanity check, the clock in microseconds with the hour unchecked.
321    fn decode(&self) -> Result<i64, DateTimeError> {
322        let (hour, minute) = (two(self.hour), two(self.minute));
323        let second = self.second.map_or(0, two);
324        let fsec = self.fraction.map_or(0, fractional_second);
325        // A fraction below one rounds to at most a whole second, which PostgreSQL allows.
326        if minute > 59 || second > 60 {
327            return Err(DateTimeError::FieldValueOutOfRange);
328        }
329        Ok(i64::from(hour) * USECS_PER_HOUR
330            + i64::from(minute) * USECS_PER_MINUTE
331            + i64::from(second) * USECS_PER_SEC
332            + fsec)
333    }
334}
335
336/// `time_overflows` on a clock `DecodeTime` accepted, whose minute, second and fraction are each
337/// in range but whose total may pass 24:00:00, as any hour past 24 makes it.
338fn check_time_overflow(clock: i64) -> Result<i64, DateTimeError> {
339    if clock > USECS_PER_DAY {
340        Err(DateTimeError::FieldValueOutOfRange)
341    } else {
342        Ok(clock)
343    }
344}
345
346/// `DecodeTimezone`, the offset east of UTC in seconds.
347fn decode_timezone(offset: &RawOffset<'_>) -> Result<i32, DateTimeError> {
348    let RawOffset { negative, digits } = *offset;
349    // The token starts with a digit, so the hour is never empty.
350    let mut parts = digits.split(|&b| b == b':');
351    let mut field = || match parts.next() {
352        None => Ok(0),
353        Some([]) => Err(DateTimeError::Unsupported),
354        Some(part) => strtoint(part).ok_or(DateTimeError::TimeZoneDisplacementOutOfRange),
355    };
356    let mut hour = field()?;
357    let mut minute = field()?;
358    let second = field()?;
359    if parts.next().is_some() {
360        return Err(DateTimeError::Unsupported);
361    }
362    let colon = digits.contains(&b':');
363    // `strlen(str) > 3` counts the sign, so three or more digits run hours and minutes together.
364    if !colon && digits.len() > 2 {
365        minute = hour % 100;
366        hour /= 100;
367    }
368    if hour > MAX_TZDISP_HOUR || minute >= 60 || second >= 60 {
369        return Err(DateTimeError::TimeZoneDisplacementOutOfRange);
370    }
371    let seconds = (hour * 60 + minute) * 60 + second;
372    Ok(if negative { -seconds } else { seconds })
373}
374
375/// `DecodeTimezoneAbbrev`, then `DecodeSpecial`, then `pg_tzset`, for a lowercased word: an
376/// abbreviation the session's zone uses, then one of the context's set, then a word of
377/// `datetktbl`, then a zone name. Of `datetktbl`'s words only `ad` and `bc` are read here.
378fn classify(word: &[u8], context: InputContext<'_>) -> Result<Word, DateTimeError> {
379    let upper = String::from_utf8_lossy(word).to_ascii_uppercase();
380    if let Some(zone) = context.time_zone
381        && let Some((meaning, fixed)) = zone.abbreviation_is_known(&upper)
382    {
383        return Ok(Word::Zone(if fixed {
384            LiteralZone::Fixed(meaning.offset)
385        } else {
386            LiteralZone::Dynamic {
387                zone: zone.clone(),
388                abbreviation: upper,
389            }
390        }));
391    }
392    match context.abbreviations.lookup(word) {
393        Some(Meaning::Fixed { offset, .. }) => return Ok(Word::Zone(LiteralZone::Fixed(*offset))),
394        Some(Meaning::Zone(name)) => {
395            let zone = PgTimeZone::load(name).ok_or(DateTimeError::TimeZoneNotRecognized)?;
396            return Ok(Word::Zone(LiteralZone::Dynamic {
397                zone,
398                abbreviation: upper,
399            }));
400        }
401        None => {}
402    }
403    match date_word_era(word) {
404        Some(Some(bc)) => Ok(Word::Era(bc)),
405        Some(None) => Err(DateTimeError::Unsupported),
406        None => PgTimeZone::load(&upper)
407            .map(|zone| Word::Zone(LiteralZone::Named(zone)))
408            .ok_or(DateTimeError::Unsupported),
409    }
410}
411
412/// The era and zone a literal's words write, refusing a second of either, or a zone beside a
413/// numeric offset, which PostgreSQL reads as a syntax error.
414fn classify_words(
415    words: &[Vec<u8>],
416    numeric_offset: bool,
417    context: InputContext<'_>,
418) -> Result<(Option<bool>, Option<LiteralZone>), DateTimeError> {
419    let (mut era, mut zone) = (None, None);
420    for word in words {
421        match classify(word, context)? {
422            Word::Era(_) if era.is_some() => return Err(DateTimeError::Unsupported),
423            Word::Era(bc) => era = Some(bc),
424            Word::Zone(_) if zone.is_some() || numeric_offset => {
425                return Err(DateTimeError::Unsupported);
426            }
427            Word::Zone(written) => zone = Some(written),
428        }
429    }
430    Ok((era, zone))
431}
432
433/// `ParseDateTime` and `DecodeDateTime` for the spellings the readers take, the reserved words
434/// that need no clock and `YYYY-MM-DD[( |T)HH:MM[:SS[.f]][offset]]` between blanks, followed
435/// by a zone abbreviation or name and ` BC` or ` AD`, each at most once.
436fn read_date_time(text: &str, context: InputContext<'_>) -> Result<Literal, DateTimeError> {
437    let bytes = trim_pg_space(text.as_bytes());
438    if bytes.len() > MAX_LITERAL_LEN {
439        return Err(DateTimeError::Unsupported);
440    }
441    let special =
442        if bytes.eq_ignore_ascii_case(b"infinity") || bytes.eq_ignore_ascii_case(b"+infinity") {
443            Some(Special::Late)
444        } else if bytes.eq_ignore_ascii_case(b"-infinity") {
445            Some(Special::Early)
446        } else if bytes.eq_ignore_ascii_case(b"epoch") {
447            Some(Special::Epoch)
448        } else {
449            None
450        };
451    if let Some(special) = special {
452        return Ok(Literal::Special(special));
453    }
454
455    let unsupported = DateTimeError::Unsupported;
456    let mut scanner = Scanner::new(bytes);
457    let year = scanner.digits();
458    if year.len() < 4 || (year.len() > 4 && year[0] == b'0') || !scanner.eat(b'-') {
459        return Err(unsupported);
460    }
461    let month = scanner.two_digits().ok_or(unsupported)?;
462    if !scanner.eat(b'-') {
463        return Err(unsupported);
464    }
465    let day = scanner.two_digits().ok_or(unsupported)?;
466    if scanner.peek().is_some_and(|b| b.is_ascii_digit()) {
467        return Err(unsupported);
468    }
469    let after_date = scanner.at;
470    let separated = match scanner.peek() {
471        Some(b'T' | b't') => {
472            scanner.at += 1;
473            true
474        }
475        _ => scanner.spaces() > 0,
476    };
477    let clock = if separated && scanner.peek().is_some_and(|b| b.is_ascii_digit()) {
478        Some(scanner.clock().ok_or(unsupported)?)
479    } else {
480        scanner.at = after_date;
481        None
482    };
483    let words = scanner.words().ok_or(unsupported)?;
484
485    // The checks in `DecodeDateTime`'s order, the date token, the time token, the zone token,
486    // then `ValidateDate`.
487    let year = strtoint(year).ok_or(DateTimeError::FieldValueOutOfRange)?;
488    let (clock, offset) = match clock {
489        None => (0, None),
490        Some(raw) => {
491            let clock = check_time_overflow(raw.decode()?)?;
492            let offset = raw.offset.as_ref().map(decode_timezone).transpose()?;
493            (clock, offset)
494        }
495    };
496    let (era, zone) = classify_words(&words, offset.is_some(), context)?;
497    let bc = era.unwrap_or(false);
498    if year <= 0 {
499        return Err(DateTimeError::FieldValueOutOfRange);
500    }
501    let year = if bc { 1 - year } else { year };
502    let (month, day) = (two(month), two(day));
503    if !(1..=12).contains(&month) || !(1..=days_in_month(year, month)).contains(&day) {
504        return Err(DateTimeError::FieldValueOutOfRange);
505    }
506    Ok(Literal::Fields(Fields {
507        year,
508        month,
509        day,
510        clock,
511        offset,
512        zone,
513    }))
514}
515
516/// The offset a time literal writes, as `DecodeTimeOnly` settles it without a date.
517enum TimeOffset {
518    /// No offset, which the session's zone then gives.
519    Unwritten,
520    /// An offset east of UTC in seconds.
521    Known(i32),
522    /// A zone whose offset depends on the date, which the current date then decides.
523    NeedsDate,
524}
525
526/// `DecodeTimeOnly` for the spellings the readers take, `allballs` and `HH:MM[:SS[.f]]` with
527/// an optional offset, followed by a zone abbreviation or name, between blanks. `None` for
528/// `allballs`.
529fn read_time(
530    text: &str,
531    context: InputContext<'_>,
532) -> Result<Option<(i64, TimeOffset)>, DateTimeError> {
533    let bytes = trim_pg_space(text.as_bytes());
534    if bytes.len() > MAX_LITERAL_LEN {
535        return Err(DateTimeError::Unsupported);
536    }
537    if bytes.eq_ignore_ascii_case(b"allballs") {
538        return Ok(None);
539    }
540    let mut scanner = Scanner::new(bytes);
541    let raw = scanner.clock().ok_or(DateTimeError::Unsupported)?;
542    let words = scanner.words().ok_or(DateTimeError::Unsupported)?;
543    let clock = raw.decode()?;
544    let offset = raw.offset.as_ref().map(decode_timezone).transpose()?;
545    let (era, zone) = classify_words(&words, offset.is_some(), context)?;
546    if era.is_some() {
547        return Err(DateTimeError::Unsupported);
548    }
549    let offset = match (offset, zone) {
550        (Some(offset), _) | (None, Some(LiteralZone::Fixed(offset))) => TimeOffset::Known(offset),
551        (None, Some(LiteralZone::Named(zone))) => zone
552            .fixed_offset()
553            .map_or(TimeOffset::NeedsDate, TimeOffset::Known),
554        (None, Some(LiteralZone::Dynamic { .. })) => TimeOffset::NeedsDate,
555        (None, None) => TimeOffset::Unwritten,
556    };
557    Ok(Some((check_time_overflow(clock)?, offset)))
558}
559
560impl PgDate {
561    /// PostgreSQL's `date_in`, reading the ISO spelling and `infinity`, `-infinity` and `epoch`,
562    /// with a clock and offset read, checked and ignored.
563    ///
564    /// # Errors
565    ///
566    /// The [`DateTimeError`] PostgreSQL raises, or [`DateTimeError::Unsupported`] for another
567    /// spelling.
568    ///
569    /// ```
570    /// use sql_values::{DateTimeError, InputContext, PgDate};
571    ///
572    /// let read = |text| PgDate::parse(text, InputContext::new()).map(|d| d.to_string());
573    /// assert_eq!(read("5874897-12-31").unwrap(), "5874897-12-31");
574    /// assert_eq!(read(" -Infinity ").unwrap(), "-infinity");
575    /// assert_eq!(read("2024-02-30"), Err(DateTimeError::FieldValueOutOfRange));
576    /// assert_eq!(read("4714-11-23 BC"), Err(DateTimeError::DateOutOfRange));
577    /// ```
578    pub fn parse(text: &str, context: InputContext<'_>) -> Result<Self, DateTimeError> {
579        let fields = match read_date_time(text, context)? {
580            Literal::Special(Special::Late) => return Ok(Self::INFINITY),
581            Literal::Special(Special::Early) => return Ok(Self::NEG_INFINITY),
582            Literal::Special(Special::Epoch) => return Ok(Self(EPOCH_DAYS)),
583            Literal::Fields(fields) => fields,
584        };
585        if !is_valid_julian(fields.year, fields.month) {
586            return Err(DateTimeError::DateOutOfRange);
587        }
588        Self::from_pg_days(date2j(fields.year, fields.month, fields.day) - POSTGRES_EPOCH_JDATE)
589            .filter(|date| date.is_finite())
590            .ok_or(DateTimeError::DateOutOfRange)
591    }
592}
593
594impl PgTimestamp {
595    /// PostgreSQL's `timestamp_in`, reading the ISO spelling and `infinity`, `-infinity` and
596    /// `epoch`, with an offset read, checked and ignored.
597    ///
598    /// # Errors
599    ///
600    /// The [`DateTimeError`] PostgreSQL raises, or [`DateTimeError::Unsupported`] for another
601    /// spelling.
602    ///
603    /// ```
604    /// use sql_values::{DateTimeError, InputContext, PgTimestamp};
605    ///
606    /// let read = |text| PgTimestamp::parse(text, InputContext::new()).map(|t| t.to_string());
607    /// assert_eq!(read("2024-12-31 24:00:00").unwrap(), "2025-01-01 00:00:00");
608    /// assert_eq!(read("4714-11-24 00:00:00 BC").unwrap(), "4714-11-24 00:00:00 BC");
609    /// assert_eq!(read("294277-01-01"), Err(DateTimeError::TimestampOutOfRange));
610    /// ```
611    pub fn parse(text: &str, context: InputContext<'_>) -> Result<Self, DateTimeError> {
612        match read_date_time(text, context)? {
613            Literal::Special(Special::Late) => Ok(Self::INFINITY),
614            Literal::Special(Special::Early) => Ok(Self::NEG_INFINITY),
615            Literal::Special(Special::Epoch) => Ok(Self(EPOCH_MICROS)),
616            Literal::Fields(fields) => {
617                tm2timestamp(fields.year, fields.month, fields.day, fields.clock, 0)
618                    .map(Self)
619                    .ok_or(DateTimeError::TimestampOutOfRange)
620            }
621        }
622    }
623}
624
625impl PgTimestampTz {
626    /// PostgreSQL's `timestamptz_in`, reading the ISO spelling and `infinity`, `-infinity` and
627    /// `epoch`. A zone the literal names, or else the context's time zone, decides the offset of
628    /// a literal without a numeric one, its local clock resolved as
629    /// [`PgTimestamp::to_timestamptz`] resolves it, and an abbreviation whose meaning changed
630    /// takes the one it had at that clock.
631    ///
632    /// # Errors
633    ///
634    /// The [`DateTimeError`] PostgreSQL raises, [`DateTimeError::NeedsTimeZone`] for a literal
635    /// without an offset or zone and a context without a time zone,
636    /// [`DateTimeError::OutsideJiffRange`] where an IANA zone is asked about a clock outside
637    /// jiff's years, or [`DateTimeError::Unsupported`] for another spelling.
638    ///
639    /// ```
640    /// use sql_values::{DateTimeError, InputContext, PgTimestampTz};
641    ///
642    /// let read = |text| PgTimestampTz::parse(text, InputContext::new()).map(|t| t.to_string());
643    /// assert_eq!(read("2024-01-01 12:00+15:59:59").unwrap(), "2023-12-31 20:00:01+00");
644    /// assert_eq!(read("2024-01-01 12:00+16"), Err(DateTimeError::TimeZoneDisplacementOutOfRange));
645    /// // `MSK` follows Europe/Moscow, which kept +04 from 2011 to 2014.
646    /// assert_eq!(read("2012-01-01 12:00 MSK").unwrap(), "2012-01-01 08:00:00+00");
647    /// assert_eq!(read("2015-01-01 12:00 MSK").unwrap(), "2015-01-01 09:00:00+00");
648    /// ```
649    pub fn parse(text: &str, context: InputContext<'_>) -> Result<Self, DateTimeError> {
650        let fields = match read_date_time(text, context)? {
651            Literal::Special(Special::Late) => return Ok(Self::INFINITY),
652            Literal::Special(Special::Early) => return Ok(Self::NEG_INFINITY),
653            Literal::Special(Special::Epoch) => return Ok(Self(EPOCH_MICROS)),
654            Literal::Fields(fields) => fields,
655        };
656        let out_of_range = DateTimeError::TimestampOutOfRange;
657        // The local clock as microseconds from 2000-01-01, for a zone to resolve.
658        let local = || {
659            if !is_valid_julian(fields.year, fields.month) {
660                return Err(out_of_range);
661            }
662            let days = i64::from(date2j(fields.year, fields.month, fields.day))
663                - i64::from(POSTGRES_EPOCH_JDATE);
664            days.checked_mul(USECS_PER_DAY)
665                .and_then(|micros| micros.checked_add(fields.clock))
666                .ok_or(out_of_range)
667        };
668        let offset = match (fields.offset, &fields.zone, context.time_zone) {
669            (Some(offset), _, _) => offset,
670            (None, Some(LiteralZone::Fixed(offset)), _) => *offset,
671            (None, Some(LiteralZone::Dynamic { zone, abbreviation }), _) => {
672                abbreviation_offset(zone, abbreviation, local()?)?
673            }
674            (None, Some(LiteralZone::Named(zone)), _) | (None, None, Some(zone)) => {
675                local_offset(zone, local()?)?
676            }
677            (None, None, None) => return Err(DateTimeError::NeedsTimeZone),
678        };
679        tm2timestamp(fields.year, fields.month, fields.day, fields.clock, offset)
680            .map(Self)
681            .ok_or(out_of_range)
682    }
683}
684
685impl PgTime {
686    /// PostgreSQL's `time_in`, reading `HH:MM[:SS[.f]]` up to 24:00:00 and `allballs`, with an
687    /// offset read, checked and ignored, and the fraction rounded to the microsecond.
688    ///
689    /// # Errors
690    ///
691    /// The [`DateTimeError`] PostgreSQL raises, or [`DateTimeError::Unsupported`] for another
692    /// spelling.
693    ///
694    /// ```
695    /// use sql_values::{DateTimeError, InputContext, PgTime};
696    ///
697    /// let read = |text| PgTime::parse(text, InputContext::new()).map(|t| t.to_string());
698    /// assert_eq!(read("23:59:60").unwrap(), "24:00:00");
699    /// assert_eq!(read("12:00:00.1234565").unwrap(), "12:00:00.123456");
700    /// assert_eq!(read("24:00:00.000001"), Err(DateTimeError::FieldValueOutOfRange));
701    /// ```
702    pub fn parse(text: &str, context: InputContext<'_>) -> Result<Self, DateTimeError> {
703        Ok(Self(
704            read_time(text, context)?.map_or(0, |(clock, _)| clock),
705        ))
706    }
707}
708
709impl PgTimeTz {
710    /// PostgreSQL's `timetz_in`, reading `HH:MM[:SS[.f]]` up to 24:00:00 with an offset or a
711    /// zone of one fixed offset, and `allballs`. A time without an offset, or with a zone whose
712    /// offset changes, takes the offset of the current date, which this reader does not model.
713    ///
714    /// # Errors
715    ///
716    /// The [`DateTimeError`] PostgreSQL raises, or [`DateTimeError::Unsupported`] for another
717    /// spelling or a time whose offset the current date decides.
718    ///
719    /// ```
720    /// use sql_values::{InputContext, PgTimeTz};
721    ///
722    /// let read = |text| PgTimeTz::parse(text, InputContext::new()).map(|t| t.to_string());
723    /// assert_eq!(read("12:00:00-05:30").unwrap(), "12:00:00-05:30");
724    /// assert_eq!(read("allballs").unwrap(), "00:00:00+00");
725    /// ```
726    pub fn parse(text: &str, context: InputContext<'_>) -> Result<Self, DateTimeError> {
727        match read_time(text, context)? {
728            None => Ok(Self { time: 0, offset: 0 }),
729            Some((clock, TimeOffset::Known(offset))) => Ok(Self {
730                time: clock,
731                offset,
732            }),
733            Some((_, TimeOffset::Unwritten | TimeOffset::NeedsDate)) => {
734                Err(DateTimeError::Unsupported)
735            }
736        }
737    }
738}
739
740/// Parse `YYYY-MM-DD HH:MM:SS[.f]` with a space or `T` separator, a year of four or more digits,
741/// PostgreSQL's trailing ` BC`, and `infinity` and `-infinity`, the fraction rounded to the
742/// microsecond. Year `0000`, as MySQL and SQLite print 1 BC, is year 0.
743///
744/// ```
745/// let at = sql_values::parse_timestamp("2024-01-02 03:04:05.125").unwrap();
746/// assert_eq!(at.to_string(), "2024-01-02 03:04:05.125");
747/// ```
748#[must_use]
749pub fn parse_timestamp(text: &str) -> Option<PgTimestamp> {
750    match text {
751        "infinity" => return Some(PgTimestamp::INFINITY),
752        "-infinity" => return Some(PgTimestamp::NEG_INFINITY),
753        _ => {}
754    }
755    let (body, bc) = split_era(text.as_bytes());
756    match parse_datetime_prefix(body, bc)? {
757        (date, clock, []) => date.at(clock, 0).map(PgTimestamp),
758        _ => None,
759    }
760}
761
762/// Parse a [`parse_timestamp`] layout followed by a `Z`, `±HH`, `±HHMM`, `±HH:MM` or `±HH:MM:SS`
763/// offset, then PostgreSQL's optional ` BC`, or `infinity` and `-infinity`.
764///
765/// ```
766/// let at = sql_values::parse_timestamp_tz("2024-01-02T03:04:05+02:00").unwrap();
767/// assert_eq!(at.to_string(), "2024-01-02 01:04:05+00");
768/// ```
769#[must_use]
770pub fn parse_timestamp_tz(text: &str) -> Option<PgTimestampTz> {
771    match text {
772        "infinity" => return Some(PgTimestampTz::INFINITY),
773        "-infinity" => return Some(PgTimestampTz::NEG_INFINITY),
774        _ => {}
775    }
776    let (body, bc) = split_era(text.as_bytes());
777    let (date, clock, offset) = parse_datetime_prefix(body, bc)?;
778    date.at(clock, parse_offset(offset)?).map(PgTimestampTz)
779}
780
781/// Parse a `YYYY-MM-DD` date with a year of four or more digits and PostgreSQL's trailing ` BC`,
782/// or `infinity` and `-infinity`. Year `0000`, as MySQL and SQLite print 1 BC, is year 0.
783///
784/// ```
785/// let d = sql_values::parse_date("2024-01-02").unwrap();
786/// assert_eq!(d.to_string(), "2024-01-02");
787/// ```
788#[must_use]
789pub fn parse_date(text: &str) -> Option<PgDate> {
790    match text {
791        "infinity" => return Some(PgDate::INFINITY),
792        "-infinity" => return Some(PgDate::NEG_INFINITY),
793        _ => {}
794    }
795    let (body, bc) = split_era(text.as_bytes());
796    match parse_date_prefix(body, bc)? {
797        (date, []) => PgDate::from_ymd(date.year, date.month, date.day),
798        _ => None,
799    }
800}
801
802/// Parse `HH:MM:SS[.f]` with one to nine fraction digits, rounded to the microsecond, up to
803/// 24:00:00.
804///
805/// ```
806/// let t = sql_values::parse_time("03:04:05.125").unwrap();
807/// assert_eq!(t.to_string(), "03:04:05.125");
808/// ```
809#[must_use]
810pub fn parse_time(text: &str) -> Option<PgTime> {
811    match parse_time_prefix(text.as_bytes())? {
812        (micros, []) => Some(PgTime(micros)),
813        _ => None,
814    }
815}
816
817/// Split off PostgreSQL's ` BC`, which trails the whole value.
818fn split_era(bytes: &[u8]) -> (&[u8], bool) {
819    match bytes.strip_suffix(b" BC") {
820        Some(body) => (body, true),
821        None => (bytes, false),
822    }
823}
824
825/// A year, month and day as written, where year `Y` BC is year `1 - Y`.
826#[derive(Clone, Copy)]
827struct Ymd {
828    year: i32,
829    month: u8,
830    day: u8,
831}
832
833impl Ymd {
834    /// The timestamp of `clock` on this date with `offset` seconds east subtracted, or `None`
835    /// outside the calendar or PostgreSQL's range.
836    fn at(self, clock: i64, offset: i32) -> Option<i64> {
837        let (month, day) = (i32::from(self.month), i32::from(self.day));
838        if !(1..=12).contains(&month) || !(1..=days_in_month(self.year, month)).contains(&day) {
839            return None;
840        }
841        tm2timestamp(self.year, month, day, clock, offset)
842    }
843}
844
845/// Parse a leading `Y{4,}-MM-DD`, where year `Y` BC is year `1 - Y` and year `0000` is year 0.
846fn parse_date_prefix(bytes: &[u8], bc: bool) -> Option<(Ymd, &[u8])> {
847    let year_len = bytes.iter().take_while(|b| b.is_ascii_digit()).count();
848    if year_len < 4 || (year_len > 4 && bytes[0] == b'0') {
849        return None;
850    }
851    let (year_digits, rest) = bytes.split_at(year_len);
852    let year = strtoint(year_digits)?;
853    let year = match (year, bc) {
854        (0, true) => return None,
855        (_, true) => 1 - year,
856        (_, false) => year,
857    };
858    let Some((&[b'-', m1, m2, b'-', d1, d2], rest)) = rest.split_first_chunk() else {
859        return None;
860    };
861    let month = parse_two_digits([m1, m2])?;
862    let day = parse_two_digits([d1, d2])?;
863    Some((Ymd { year, month, day }, rest))
864}
865
866/// Parse a leading `HH:MM:SS[.f]` with one to nine fraction digits, as microseconds up to
867/// 24:00:00.
868fn parse_time_prefix(bytes: &[u8]) -> Option<(i64, &[u8])> {
869    let Some((&[h1, h2, b':', m1, m2, b':', s1, s2], rest)) = bytes.split_first_chunk() else {
870        return None;
871    };
872    let (fsec, rest) = match rest.split_first() {
873        Some((b'.', fraction)) => {
874            let len = fraction.iter().take_while(|b| b.is_ascii_digit()).count();
875            if !(1..=9).contains(&len) {
876                return None;
877            }
878            (fractional_second(&rest[..=len]), &fraction[len..])
879        }
880        _ => (0, rest),
881    };
882    let (hour, minute, second) = (
883        parse_two_digits([h1, h2])?,
884        parse_two_digits([m1, m2])?,
885        parse_two_digits([s1, s2])?,
886    );
887    if minute > 59 || second > 59 {
888        return None;
889    }
890    let micros = i64::from(hour) * USECS_PER_HOUR
891        + i64::from(minute) * USECS_PER_MINUTE
892        + i64::from(second) * USECS_PER_SEC
893        + fsec;
894    (micros <= USECS_PER_DAY).then_some((micros, rest))
895}
896
897/// Parse a leading date and time joined by a space or `T`, the clock in microseconds.
898fn parse_datetime_prefix(bytes: &[u8], bc: bool) -> Option<(Ymd, i64, &[u8])> {
899    let (date, rest) = parse_date_prefix(bytes, bc)?;
900    let (&(b' ' | b'T'), rest) = rest.split_first()? else {
901        return None;
902    };
903    let (clock, rest) = parse_time_prefix(rest)?;
904    Some((date, clock, rest))
905}
906
907/// Two ASCII digits as a number.
908fn parse_two_digits(digits: [u8; 2]) -> Option<u8> {
909    if digits.iter().all(u8::is_ascii_digit) {
910        Some((digits[0] - b'0') * 10 + (digits[1] - b'0'))
911    } else {
912        None
913    }
914}
915
916/// Parse a `Z`, `±HH`, `±HHMM`, `±HH:MM` or `±HH:MM:SS` offset as seconds east of UTC, with an
917/// hour up to 23.
918fn parse_offset(bytes: &[u8]) -> Option<i32> {
919    if bytes == b"Z" {
920        return Some(0);
921    }
922    let (&sign, digits) = bytes.split_first()?;
923    let negative = match sign {
924        b'+' => false,
925        b'-' => true,
926        _ => return None,
927    };
928    let pair = |at: usize| parse_two_digits(digits.get(at..at + 2)?.try_into().ok()?);
929    let hour = pair(0)?;
930    let (minute, second) = match digits.len() {
931        2 => (0, 0),
932        4 => (pair(2)?, 0),
933        5 if digits[2] == b':' => (pair(3)?, 0),
934        8 if digits[2] == b':' && digits[5] == b':' => (pair(3)?, pair(6)?),
935        _ => return None,
936    };
937    if hour > 23 || minute > 59 || second > 59 {
938        return None;
939    }
940    let seconds = (i32::from(hour) * 60 + i32::from(minute)) * 60 + i32::from(second);
941    Some(if negative { -seconds } else { seconds })
942}