sql-values 0.4.0

SQL values, with PostgreSQL's value rules beside readers of the text PostgreSQL, MySQL and SQLite emit
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
//! PostgreSQL 18's `date_in`, `time_in`, `timetz_in`, `timestamp_in` and `timestamptz_in` for the
//! ISO spelling, and the readers of the text PostgreSQL, MySQL and SQLite print.

use alloc::{string::String, vec::Vec};

use super::{
    DateTimeError, POSTGRES_EPOCH_JDATE, PgDate, PgTime, PgTimeTz, PgTimestamp, PgTimestampTz,
    USECS_PER_DAY, USECS_PER_HOUR, USECS_PER_MINUTE, USECS_PER_SEC, abbreviation_offset, date2j,
    days_in_month, is_valid_julian, local_offset, tm2timestamp,
};
use crate::{
    PgTimeZone, TimeZoneAbbreviations,
    cast::{is_pg_space, trim_pg_space},
    float::{round_ties_even, truncate_to_i64},
    interval::date_word_era,
    zone::{DEFAULT_ABBREVIATIONS, Meaning},
};

/// `MAX_TZDISP_HOUR`, the largest hour of an offset a literal writes.
const MAX_TZDISP_HOUR: i32 = 15;
/// The longest literal the readers take, well inside PostgreSQL's `MAXDATELEN` of 128 bytes
/// for the fields they read.
const MAX_LITERAL_LEN: usize = 64;
/// 1970-01-01 00:00:00, `epoch`, in microseconds from 2000-01-01.
const EPOCH_MICROS: i64 = -946_684_800_000_000;
/// 1970-01-01, `epoch`, in days from 2000-01-01.
const EPOCH_DAYS: i32 = -10_957;

/// The session state PostgreSQL's input functions read, which the caller supplies.
///
/// ```
/// use sql_values::{DateTimeError, InputContext, PgTimeZone, PgTimestampTz, TimeZoneAbbreviations};
///
/// let rome = PgTimeZone::parse("Europe/Rome").unwrap();
/// let local = "2026-07-01 12:00:00";
/// assert_eq!(
///     PgTimestampTz::parse(local, InputContext::new()),
///     Err(DateTimeError::NeedsTimeZone),
/// );
/// let at = PgTimestampTz::parse(local, InputContext::new().with_time_zone(&rome)).unwrap();
/// assert_eq!(at.to_string(), "2026-07-01 10:00:00+00");
///
/// // `EST` is New York's time in `Default` and Brisbane's in `Australia`.
/// let australia = TimeZoneAbbreviations::bundled("Australia").unwrap();
/// let context = InputContext::new().with_time_zone_abbreviations(australia);
/// let est = PgTimestampTz::parse("2026-07-01 12:00 EST", context).unwrap();
/// assert_eq!(est.to_string(), "2026-07-01 02:00:00+00");
/// ```
#[derive(Debug, Clone, Copy)]
pub struct InputContext<'a> {
    time_zone: Option<&'a PgTimeZone>,
    abbreviations: &'a TimeZoneAbbreviations,
}

impl<'a> InputContext<'a> {
    /// A context with no time zone and the `Default` abbreviations, as a stock installation's
    /// `timezone_abbreviations` names them.
    #[must_use]
    pub const fn new() -> Self {
        Self {
            time_zone: None,
            abbreviations: &DEFAULT_ABBREVIATIONS,
        }
    }

    /// The context with `zone` as the session's `TimeZone`, which reads a `timestamptz` written
    /// without an offset, and whose own abbreviations a literal may write before those of the
    /// set.
    #[must_use]
    pub const fn with_time_zone(self, zone: &'a PgTimeZone) -> Self {
        Self {
            time_zone: Some(zone),
            ..self
        }
    }

    /// The context with `abbreviations` as the session's `timezone_abbreviations`.
    #[must_use]
    pub const fn with_time_zone_abbreviations(
        self,
        abbreviations: &'a TimeZoneAbbreviations,
    ) -> Self {
        Self {
            abbreviations,
            ..self
        }
    }
}

impl Default for InputContext<'_> {
    fn default() -> Self {
        Self::new()
    }
}

/// The reserved words `date_in`, `timestamp_in` and `timestamptz_in` read without a clock.
enum Special {
    /// `infinity` or `+infinity`, `DTK_LATE`.
    Late,
    /// `-infinity`, `DTK_EARLY`.
    Early,
    /// `epoch`, `DTK_EPOCH`.
    Epoch,
}

/// A literal's fields as `DecodeDateTime` leaves them, already checked.
struct Fields {
    /// The proleptic Gregorian year, where year `Y` BC is `1 - Y`.
    year: i32,
    month: i32,
    day: i32,
    /// The clock in microseconds, up to 24:00:00.
    clock: i64,
    /// The offset east of UTC in seconds, when the literal writes one.
    offset: Option<i32>,
    /// The zone the literal names, when it writes one.
    zone: Option<LiteralZone>,
}

/// What a date and time literal reads as.
enum Literal {
    Special(Special),
    Fields(Fields),
}

/// A numeric offset as written, its sign and the digits and colons after it, before
/// `DecodeTimezone` checks it.
struct RawOffset<'a> {
    negative: bool,
    digits: &'a [u8],
}

/// What a word of a literal reads as, by `DecodeTimezoneAbbrev`, `DecodeSpecial` and
/// `pg_tzset` in that order.
enum Word {
    /// `ad`, `false`, or `bc`, `true`.
    Era(bool),
    /// A zone written after the clock.
    Zone(LiteralZone),
}

/// A zone a literal writes, by abbreviation or by name.
#[derive(Clone)]
enum LiteralZone {
    /// `TZ` or `DTZ`, a fixed offset east of UTC in seconds.
    Fixed(i32),
    /// `DYNTZ`, the uppercased abbreviation's meaning in a zone at the literal's date.
    Dynamic {
        zone: PgTimeZone,
        abbreviation: String,
    },
    /// A full zone name, `pg_tzset`.
    Named(PgTimeZone),
}

/// A clock as written, before `DecodeTime` checks it.
struct RawClock<'a> {
    hour: [u8; 2],
    minute: [u8; 2],
    second: Option<[u8; 2]>,
    /// The fraction from its point, `.` alone included.
    fraction: Option<&'a [u8]>,
    offset: Option<RawOffset<'a>>,
}

/// A byte cursor over a literal.
struct Scanner<'a> {
    bytes: &'a [u8],
    at: usize,
}

impl<'a> Scanner<'a> {
    const fn new(bytes: &'a [u8]) -> Self {
        Self { bytes, at: 0 }
    }

    fn peek(&self) -> Option<u8> {
        self.bytes.get(self.at).copied()
    }

    fn peek_at(&self, ahead: usize) -> Option<u8> {
        self.bytes.get(self.at + ahead).copied()
    }

    fn eat(&mut self, byte: u8) -> bool {
        let found = self.peek() == Some(byte);
        self.at += usize::from(found);
        found
    }

    fn digits(&mut self) -> &'a [u8] {
        let start = self.at;
        while self.peek().is_some_and(|b| b.is_ascii_digit()) {
            self.at += 1;
        }
        &self.bytes[start..self.at]
    }

    fn two_digits(&mut self) -> Option<[u8; 2]> {
        match (self.peek(), self.peek_at(1)) {
            (Some(a), Some(b)) if a.is_ascii_digit() && b.is_ascii_digit() => {
                self.at += 2;
                Some([a, b])
            }
            _ => None,
        }
    }

    fn spaces(&mut self) -> usize {
        let start = self.at;
        while self.peek().is_some_and(is_pg_space) {
            self.at += 1;
        }
        self.at - start
    }

    fn is_done(&self) -> bool {
        self.at == self.bytes.len()
    }

    /// `HH:MM[:SS[.f]]` and an optional offset after blanks.
    fn clock(&mut self) -> Option<RawClock<'a>> {
        let hour = self.two_digits()?;
        if !self.eat(b':') {
            return None;
        }
        let minute = self.two_digits()?;
        let mut second = None;
        let mut fraction = None;
        if self.eat(b':') {
            second = Some(self.two_digits()?);
            if self.peek() == Some(b'.') {
                let start = self.at;
                self.at += 1;
                self.digits();
                fraction = Some(&self.bytes[start..self.at]);
            }
        }
        if self.peek().is_some_and(|b| b.is_ascii_digit() || b == b'.') {
            return None;
        }
        let before_offset = self.at;
        self.spaces();
        let offset = match self.peek() {
            Some(sign @ (b'+' | b'-')) if self.peek_at(1).is_some_and(|b| b.is_ascii_digit()) => {
                self.at += 1;
                let start = self.at;
                while self.peek().is_some_and(|b| b.is_ascii_digit() || b == b':') {
                    self.at += 1;
                }
                if matches!(self.peek(), Some(b'.' | b'-')) {
                    return None;
                }
                Some(RawOffset {
                    negative: sign == b'-',
                    digits: &self.bytes[start..self.at],
                })
            }
            _ => {
                self.at = before_offset;
                None
            }
        };
        Some(RawClock {
            hour,
            minute,
            second,
            fraction,
            offset,
        })
    }

    /// The words that end a literal, each a run of letters `ParseDateTime` keeps as one token,
    /// lowercased, or `None` when something else is left.
    fn words(&mut self) -> Option<Vec<Vec<u8>>> {
        let mut words = Vec::new();
        loop {
            self.spaces();
            if self.is_done() {
                return Some(words);
            }
            let start = self.at;
            while self.peek().is_some_and(|b| b.is_ascii_alphabetic()) {
                self.at += 1;
            }
            if self.at == start || !(self.is_done() || self.peek().is_some_and(is_pg_space)) {
                return None;
            }
            words.push(self.bytes[start..self.at].to_ascii_lowercase());
        }
    }
}

/// `strtoint` of decimal digits, `None` on `ERANGE`.
fn strtoint(digits: &[u8]) -> Option<i32> {
    digits.iter().try_fold(0i32, |value, &digit| {
        value.checked_mul(10)?.checked_add(i32::from(digit - b'0'))
    })
}

/// The value of two ASCII digits.
fn two(digits: [u8; 2]) -> i32 {
    i32::from(digits[0] - b'0') * 10 + i32::from(digits[1] - b'0')
}

/// `ParseFractionalSecond`, a fraction from its point as whole microseconds, `rint` of the
/// `double` times a million.
fn fractional_second(fraction: &[u8]) -> i64 {
    if fraction.len() == 1 {
        return 0;
    }
    let value: f64 = core::str::from_utf8(fraction)
        .ok()
        .and_then(|text| text.parse().ok())
        .expect("a point and digits read as a double");
    truncate_to_i64(round_ties_even(value * 1_000_000.0))
}

impl RawClock<'_> {
    /// `DecodeTime`'s sanity check, the clock in microseconds with the hour unchecked.
    fn decode(&self) -> Result<i64, DateTimeError> {
        let (hour, minute) = (two(self.hour), two(self.minute));
        let second = self.second.map_or(0, two);
        let fsec = self.fraction.map_or(0, fractional_second);
        // A fraction below one rounds to at most a whole second, which PostgreSQL allows.
        if minute > 59 || second > 60 {
            return Err(DateTimeError::FieldValueOutOfRange);
        }
        Ok(i64::from(hour) * USECS_PER_HOUR
            + i64::from(minute) * USECS_PER_MINUTE
            + i64::from(second) * USECS_PER_SEC
            + fsec)
    }
}

/// `time_overflows` on a clock `DecodeTime` accepted, whose minute, second and fraction are each
/// in range but whose total may pass 24:00:00, as any hour past 24 makes it.
fn check_time_overflow(clock: i64) -> Result<i64, DateTimeError> {
    if clock > USECS_PER_DAY {
        Err(DateTimeError::FieldValueOutOfRange)
    } else {
        Ok(clock)
    }
}

/// `DecodeTimezone`, the offset east of UTC in seconds.
fn decode_timezone(offset: &RawOffset<'_>) -> Result<i32, DateTimeError> {
    let RawOffset { negative, digits } = *offset;
    // The token starts with a digit, so the hour is never empty.
    let mut parts = digits.split(|&b| b == b':');
    let mut field = || match parts.next() {
        None => Ok(0),
        Some([]) => Err(DateTimeError::Unsupported),
        Some(part) => strtoint(part).ok_or(DateTimeError::TimeZoneDisplacementOutOfRange),
    };
    let mut hour = field()?;
    let mut minute = field()?;
    let second = field()?;
    if parts.next().is_some() {
        return Err(DateTimeError::Unsupported);
    }
    let colon = digits.contains(&b':');
    // `strlen(str) > 3` counts the sign, so three or more digits run hours and minutes together.
    if !colon && digits.len() > 2 {
        minute = hour % 100;
        hour /= 100;
    }
    if hour > MAX_TZDISP_HOUR || minute >= 60 || second >= 60 {
        return Err(DateTimeError::TimeZoneDisplacementOutOfRange);
    }
    let seconds = (hour * 60 + minute) * 60 + second;
    Ok(if negative { -seconds } else { seconds })
}

/// `DecodeTimezoneAbbrev`, then `DecodeSpecial`, then `pg_tzset`, for a lowercased word: an
/// abbreviation the session's zone uses, then one of the context's set, then a word of
/// `datetktbl`, then a zone name. Of `datetktbl`'s words only `ad` and `bc` are read here.
fn classify(word: &[u8], context: InputContext<'_>) -> Result<Word, DateTimeError> {
    let upper = String::from_utf8_lossy(word).to_ascii_uppercase();
    if let Some(zone) = context.time_zone
        && let Some((meaning, fixed)) = zone.abbreviation_is_known(&upper)
    {
        return Ok(Word::Zone(if fixed {
            LiteralZone::Fixed(meaning.offset)
        } else {
            LiteralZone::Dynamic {
                zone: zone.clone(),
                abbreviation: upper,
            }
        }));
    }
    match context.abbreviations.lookup(word) {
        Some(Meaning::Fixed { offset, .. }) => return Ok(Word::Zone(LiteralZone::Fixed(*offset))),
        Some(Meaning::Zone(name)) => {
            let zone = PgTimeZone::load(name).ok_or(DateTimeError::TimeZoneNotRecognized)?;
            return Ok(Word::Zone(LiteralZone::Dynamic {
                zone,
                abbreviation: upper,
            }));
        }
        None => {}
    }
    match date_word_era(word) {
        Some(Some(bc)) => Ok(Word::Era(bc)),
        Some(None) => Err(DateTimeError::Unsupported),
        None => PgTimeZone::load(&upper)
            .map(|zone| Word::Zone(LiteralZone::Named(zone)))
            .ok_or(DateTimeError::Unsupported),
    }
}

/// The era and zone a literal's words write, refusing a second of either, or a zone beside a
/// numeric offset, which PostgreSQL reads as a syntax error.
fn classify_words(
    words: &[Vec<u8>],
    numeric_offset: bool,
    context: InputContext<'_>,
) -> Result<(Option<bool>, Option<LiteralZone>), DateTimeError> {
    let (mut era, mut zone) = (None, None);
    for word in words {
        match classify(word, context)? {
            Word::Era(_) if era.is_some() => return Err(DateTimeError::Unsupported),
            Word::Era(bc) => era = Some(bc),
            Word::Zone(_) if zone.is_some() || numeric_offset => {
                return Err(DateTimeError::Unsupported);
            }
            Word::Zone(written) => zone = Some(written),
        }
    }
    Ok((era, zone))
}

/// `ParseDateTime` and `DecodeDateTime` for the spellings the readers take, the reserved words
/// that need no clock and `YYYY-MM-DD[( |T)HH:MM[:SS[.f]][offset]]` between blanks, followed
/// by a zone abbreviation or name and ` BC` or ` AD`, each at most once.
fn read_date_time(text: &str, context: InputContext<'_>) -> Result<Literal, DateTimeError> {
    let bytes = trim_pg_space(text.as_bytes());
    if bytes.len() > MAX_LITERAL_LEN {
        return Err(DateTimeError::Unsupported);
    }
    let special =
        if bytes.eq_ignore_ascii_case(b"infinity") || bytes.eq_ignore_ascii_case(b"+infinity") {
            Some(Special::Late)
        } else if bytes.eq_ignore_ascii_case(b"-infinity") {
            Some(Special::Early)
        } else if bytes.eq_ignore_ascii_case(b"epoch") {
            Some(Special::Epoch)
        } else {
            None
        };
    if let Some(special) = special {
        return Ok(Literal::Special(special));
    }

    let unsupported = DateTimeError::Unsupported;
    let mut scanner = Scanner::new(bytes);
    let year = scanner.digits();
    if year.len() < 4 || (year.len() > 4 && year[0] == b'0') || !scanner.eat(b'-') {
        return Err(unsupported);
    }
    let month = scanner.two_digits().ok_or(unsupported)?;
    if !scanner.eat(b'-') {
        return Err(unsupported);
    }
    let day = scanner.two_digits().ok_or(unsupported)?;
    if scanner.peek().is_some_and(|b| b.is_ascii_digit()) {
        return Err(unsupported);
    }
    let after_date = scanner.at;
    let separated = match scanner.peek() {
        Some(b'T' | b't') => {
            scanner.at += 1;
            true
        }
        _ => scanner.spaces() > 0,
    };
    let clock = if separated && scanner.peek().is_some_and(|b| b.is_ascii_digit()) {
        Some(scanner.clock().ok_or(unsupported)?)
    } else {
        scanner.at = after_date;
        None
    };
    let words = scanner.words().ok_or(unsupported)?;

    // The checks in `DecodeDateTime`'s order, the date token, the time token, the zone token,
    // then `ValidateDate`.
    let year = strtoint(year).ok_or(DateTimeError::FieldValueOutOfRange)?;
    let (clock, offset) = match clock {
        None => (0, None),
        Some(raw) => {
            let clock = check_time_overflow(raw.decode()?)?;
            let offset = raw.offset.as_ref().map(decode_timezone).transpose()?;
            (clock, offset)
        }
    };
    let (era, zone) = classify_words(&words, offset.is_some(), context)?;
    let bc = era.unwrap_or(false);
    if year <= 0 {
        return Err(DateTimeError::FieldValueOutOfRange);
    }
    let year = if bc { 1 - year } else { year };
    let (month, day) = (two(month), two(day));
    if !(1..=12).contains(&month) || !(1..=days_in_month(year, month)).contains(&day) {
        return Err(DateTimeError::FieldValueOutOfRange);
    }
    Ok(Literal::Fields(Fields {
        year,
        month,
        day,
        clock,
        offset,
        zone,
    }))
}

/// The offset a time literal writes, as `DecodeTimeOnly` settles it without a date.
enum TimeOffset {
    /// No offset, which the session's zone then gives.
    Unwritten,
    /// An offset east of UTC in seconds.
    Known(i32),
    /// A zone whose offset depends on the date, which the current date then decides.
    NeedsDate,
}

/// `DecodeTimeOnly` for the spellings the readers take, `allballs` and `HH:MM[:SS[.f]]` with
/// an optional offset, followed by a zone abbreviation or name, between blanks. `None` for
/// `allballs`.
fn read_time(
    text: &str,
    context: InputContext<'_>,
) -> Result<Option<(i64, TimeOffset)>, DateTimeError> {
    let bytes = trim_pg_space(text.as_bytes());
    if bytes.len() > MAX_LITERAL_LEN {
        return Err(DateTimeError::Unsupported);
    }
    if bytes.eq_ignore_ascii_case(b"allballs") {
        return Ok(None);
    }
    let mut scanner = Scanner::new(bytes);
    let raw = scanner.clock().ok_or(DateTimeError::Unsupported)?;
    let words = scanner.words().ok_or(DateTimeError::Unsupported)?;
    let clock = raw.decode()?;
    let offset = raw.offset.as_ref().map(decode_timezone).transpose()?;
    let (era, zone) = classify_words(&words, offset.is_some(), context)?;
    if era.is_some() {
        return Err(DateTimeError::Unsupported);
    }
    let offset = match (offset, zone) {
        (Some(offset), _) | (None, Some(LiteralZone::Fixed(offset))) => TimeOffset::Known(offset),
        (None, Some(LiteralZone::Named(zone))) => zone
            .fixed_offset()
            .map_or(TimeOffset::NeedsDate, TimeOffset::Known),
        (None, Some(LiteralZone::Dynamic { .. })) => TimeOffset::NeedsDate,
        (None, None) => TimeOffset::Unwritten,
    };
    Ok(Some((check_time_overflow(clock)?, offset)))
}

impl PgDate {
    /// PostgreSQL's `date_in`, reading the ISO spelling and `infinity`, `-infinity` and `epoch`,
    /// with a clock and offset read, checked and ignored.
    ///
    /// # Errors
    ///
    /// The [`DateTimeError`] PostgreSQL raises, or [`DateTimeError::Unsupported`] for another
    /// spelling.
    ///
    /// ```
    /// use sql_values::{DateTimeError, InputContext, PgDate};
    ///
    /// let read = |text| PgDate::parse(text, InputContext::new()).map(|d| d.to_string());
    /// assert_eq!(read("5874897-12-31").unwrap(), "5874897-12-31");
    /// assert_eq!(read(" -Infinity ").unwrap(), "-infinity");
    /// assert_eq!(read("2024-02-30"), Err(DateTimeError::FieldValueOutOfRange));
    /// assert_eq!(read("4714-11-23 BC"), Err(DateTimeError::DateOutOfRange));
    /// ```
    pub fn parse(text: &str, context: InputContext<'_>) -> Result<Self, DateTimeError> {
        let fields = match read_date_time(text, context)? {
            Literal::Special(Special::Late) => return Ok(Self::INFINITY),
            Literal::Special(Special::Early) => return Ok(Self::NEG_INFINITY),
            Literal::Special(Special::Epoch) => return Ok(Self(EPOCH_DAYS)),
            Literal::Fields(fields) => fields,
        };
        if !is_valid_julian(fields.year, fields.month) {
            return Err(DateTimeError::DateOutOfRange);
        }
        Self::from_pg_days(date2j(fields.year, fields.month, fields.day) - POSTGRES_EPOCH_JDATE)
            .filter(|date| date.is_finite())
            .ok_or(DateTimeError::DateOutOfRange)
    }
}

impl PgTimestamp {
    /// PostgreSQL's `timestamp_in`, reading the ISO spelling and `infinity`, `-infinity` and
    /// `epoch`, with an offset read, checked and ignored.
    ///
    /// # Errors
    ///
    /// The [`DateTimeError`] PostgreSQL raises, or [`DateTimeError::Unsupported`] for another
    /// spelling.
    ///
    /// ```
    /// use sql_values::{DateTimeError, InputContext, PgTimestamp};
    ///
    /// let read = |text| PgTimestamp::parse(text, InputContext::new()).map(|t| t.to_string());
    /// assert_eq!(read("2024-12-31 24:00:00").unwrap(), "2025-01-01 00:00:00");
    /// assert_eq!(read("4714-11-24 00:00:00 BC").unwrap(), "4714-11-24 00:00:00 BC");
    /// assert_eq!(read("294277-01-01"), Err(DateTimeError::TimestampOutOfRange));
    /// ```
    pub fn parse(text: &str, context: InputContext<'_>) -> Result<Self, DateTimeError> {
        match read_date_time(text, context)? {
            Literal::Special(Special::Late) => Ok(Self::INFINITY),
            Literal::Special(Special::Early) => Ok(Self::NEG_INFINITY),
            Literal::Special(Special::Epoch) => Ok(Self(EPOCH_MICROS)),
            Literal::Fields(fields) => {
                tm2timestamp(fields.year, fields.month, fields.day, fields.clock, 0)
                    .map(Self)
                    .ok_or(DateTimeError::TimestampOutOfRange)
            }
        }
    }
}

impl PgTimestampTz {
    /// PostgreSQL's `timestamptz_in`, reading the ISO spelling and `infinity`, `-infinity` and
    /// `epoch`. A zone the literal names, or else the context's time zone, decides the offset of
    /// a literal without a numeric one, its local clock resolved as
    /// [`PgTimestamp::to_timestamptz`] resolves it, and an abbreviation whose meaning changed
    /// takes the one it had at that clock.
    ///
    /// # Errors
    ///
    /// The [`DateTimeError`] PostgreSQL raises, [`DateTimeError::NeedsTimeZone`] for a literal
    /// without an offset or zone and a context without a time zone,
    /// [`DateTimeError::OutsideJiffRange`] where an IANA zone is asked about a clock outside
    /// jiff's years, or [`DateTimeError::Unsupported`] for another spelling.
    ///
    /// ```
    /// use sql_values::{DateTimeError, InputContext, PgTimestampTz};
    ///
    /// let read = |text| PgTimestampTz::parse(text, InputContext::new()).map(|t| t.to_string());
    /// assert_eq!(read("2024-01-01 12:00+15:59:59").unwrap(), "2023-12-31 20:00:01+00");
    /// assert_eq!(read("2024-01-01 12:00+16"), Err(DateTimeError::TimeZoneDisplacementOutOfRange));
    /// // `MSK` follows Europe/Moscow, which kept +04 from 2011 to 2014.
    /// assert_eq!(read("2012-01-01 12:00 MSK").unwrap(), "2012-01-01 08:00:00+00");
    /// assert_eq!(read("2015-01-01 12:00 MSK").unwrap(), "2015-01-01 09:00:00+00");
    /// ```
    pub fn parse(text: &str, context: InputContext<'_>) -> Result<Self, DateTimeError> {
        let fields = match read_date_time(text, context)? {
            Literal::Special(Special::Late) => return Ok(Self::INFINITY),
            Literal::Special(Special::Early) => return Ok(Self::NEG_INFINITY),
            Literal::Special(Special::Epoch) => return Ok(Self(EPOCH_MICROS)),
            Literal::Fields(fields) => fields,
        };
        let out_of_range = DateTimeError::TimestampOutOfRange;
        // The local clock as microseconds from 2000-01-01, for a zone to resolve.
        let local = || {
            if !is_valid_julian(fields.year, fields.month) {
                return Err(out_of_range);
            }
            let days = i64::from(date2j(fields.year, fields.month, fields.day))
                - i64::from(POSTGRES_EPOCH_JDATE);
            days.checked_mul(USECS_PER_DAY)
                .and_then(|micros| micros.checked_add(fields.clock))
                .ok_or(out_of_range)
        };
        let offset = match (fields.offset, &fields.zone, context.time_zone) {
            (Some(offset), _, _) => offset,
            (None, Some(LiteralZone::Fixed(offset)), _) => *offset,
            (None, Some(LiteralZone::Dynamic { zone, abbreviation }), _) => {
                abbreviation_offset(zone, abbreviation, local()?)?
            }
            (None, Some(LiteralZone::Named(zone)), _) | (None, None, Some(zone)) => {
                local_offset(zone, local()?)?
            }
            (None, None, None) => return Err(DateTimeError::NeedsTimeZone),
        };
        tm2timestamp(fields.year, fields.month, fields.day, fields.clock, offset)
            .map(Self)
            .ok_or(out_of_range)
    }
}

impl PgTime {
    /// PostgreSQL's `time_in`, reading `HH:MM[:SS[.f]]` up to 24:00:00 and `allballs`, with an
    /// offset read, checked and ignored, and the fraction rounded to the microsecond.
    ///
    /// # Errors
    ///
    /// The [`DateTimeError`] PostgreSQL raises, or [`DateTimeError::Unsupported`] for another
    /// spelling.
    ///
    /// ```
    /// use sql_values::{DateTimeError, InputContext, PgTime};
    ///
    /// let read = |text| PgTime::parse(text, InputContext::new()).map(|t| t.to_string());
    /// assert_eq!(read("23:59:60").unwrap(), "24:00:00");
    /// assert_eq!(read("12:00:00.1234565").unwrap(), "12:00:00.123456");
    /// assert_eq!(read("24:00:00.000001"), Err(DateTimeError::FieldValueOutOfRange));
    /// ```
    pub fn parse(text: &str, context: InputContext<'_>) -> Result<Self, DateTimeError> {
        Ok(Self(
            read_time(text, context)?.map_or(0, |(clock, _)| clock),
        ))
    }
}

impl PgTimeTz {
    /// PostgreSQL's `timetz_in`, reading `HH:MM[:SS[.f]]` up to 24:00:00 with an offset or a
    /// zone of one fixed offset, and `allballs`. A time without an offset, or with a zone whose
    /// offset changes, takes the offset of the current date, which this reader does not model.
    ///
    /// # Errors
    ///
    /// The [`DateTimeError`] PostgreSQL raises, or [`DateTimeError::Unsupported`] for another
    /// spelling or a time whose offset the current date decides.
    ///
    /// ```
    /// use sql_values::{InputContext, PgTimeTz};
    ///
    /// let read = |text| PgTimeTz::parse(text, InputContext::new()).map(|t| t.to_string());
    /// assert_eq!(read("12:00:00-05:30").unwrap(), "12:00:00-05:30");
    /// assert_eq!(read("allballs").unwrap(), "00:00:00+00");
    /// ```
    pub fn parse(text: &str, context: InputContext<'_>) -> Result<Self, DateTimeError> {
        match read_time(text, context)? {
            None => Ok(Self { time: 0, offset: 0 }),
            Some((clock, TimeOffset::Known(offset))) => Ok(Self {
                time: clock,
                offset,
            }),
            Some((_, TimeOffset::Unwritten | TimeOffset::NeedsDate)) => {
                Err(DateTimeError::Unsupported)
            }
        }
    }
}

/// Parse `YYYY-MM-DD HH:MM:SS[.f]` with a space or `T` separator, a year of four or more digits,
/// PostgreSQL's trailing ` BC`, and `infinity` and `-infinity`, the fraction rounded to the
/// microsecond. Year `0000`, as MySQL and SQLite print 1 BC, is year 0.
///
/// ```
/// let at = sql_values::parse_timestamp("2024-01-02 03:04:05.125").unwrap();
/// assert_eq!(at.to_string(), "2024-01-02 03:04:05.125");
/// ```
#[must_use]
pub fn parse_timestamp(text: &str) -> Option<PgTimestamp> {
    match text {
        "infinity" => return Some(PgTimestamp::INFINITY),
        "-infinity" => return Some(PgTimestamp::NEG_INFINITY),
        _ => {}
    }
    let (body, bc) = split_era(text.as_bytes());
    match parse_datetime_prefix(body, bc)? {
        (date, clock, []) => date.at(clock, 0).map(PgTimestamp),
        _ => None,
    }
}

/// Parse a [`parse_timestamp`] layout followed by a `Z`, `±HH`, `±HHMM`, `±HH:MM` or `±HH:MM:SS`
/// offset, then PostgreSQL's optional ` BC`, or `infinity` and `-infinity`.
///
/// ```
/// let at = sql_values::parse_timestamp_tz("2024-01-02T03:04:05+02:00").unwrap();
/// assert_eq!(at.to_string(), "2024-01-02 01:04:05+00");
/// ```
#[must_use]
pub fn parse_timestamp_tz(text: &str) -> Option<PgTimestampTz> {
    match text {
        "infinity" => return Some(PgTimestampTz::INFINITY),
        "-infinity" => return Some(PgTimestampTz::NEG_INFINITY),
        _ => {}
    }
    let (body, bc) = split_era(text.as_bytes());
    let (date, clock, offset) = parse_datetime_prefix(body, bc)?;
    date.at(clock, parse_offset(offset)?).map(PgTimestampTz)
}

/// Parse a `YYYY-MM-DD` date with a year of four or more digits and PostgreSQL's trailing ` BC`,
/// or `infinity` and `-infinity`. Year `0000`, as MySQL and SQLite print 1 BC, is year 0.
///
/// ```
/// let d = sql_values::parse_date("2024-01-02").unwrap();
/// assert_eq!(d.to_string(), "2024-01-02");
/// ```
#[must_use]
pub fn parse_date(text: &str) -> Option<PgDate> {
    match text {
        "infinity" => return Some(PgDate::INFINITY),
        "-infinity" => return Some(PgDate::NEG_INFINITY),
        _ => {}
    }
    let (body, bc) = split_era(text.as_bytes());
    match parse_date_prefix(body, bc)? {
        (date, []) => PgDate::from_ymd(date.year, date.month, date.day),
        _ => None,
    }
}

/// Parse `HH:MM:SS[.f]` with one to nine fraction digits, rounded to the microsecond, up to
/// 24:00:00.
///
/// ```
/// let t = sql_values::parse_time("03:04:05.125").unwrap();
/// assert_eq!(t.to_string(), "03:04:05.125");
/// ```
#[must_use]
pub fn parse_time(text: &str) -> Option<PgTime> {
    match parse_time_prefix(text.as_bytes())? {
        (micros, []) => Some(PgTime(micros)),
        _ => None,
    }
}

/// Split off PostgreSQL's ` BC`, which trails the whole value.
fn split_era(bytes: &[u8]) -> (&[u8], bool) {
    match bytes.strip_suffix(b" BC") {
        Some(body) => (body, true),
        None => (bytes, false),
    }
}

/// A year, month and day as written, where year `Y` BC is year `1 - Y`.
#[derive(Clone, Copy)]
struct Ymd {
    year: i32,
    month: u8,
    day: u8,
}

impl Ymd {
    /// The timestamp of `clock` on this date with `offset` seconds east subtracted, or `None`
    /// outside the calendar or PostgreSQL's range.
    fn at(self, clock: i64, offset: i32) -> Option<i64> {
        let (month, day) = (i32::from(self.month), i32::from(self.day));
        if !(1..=12).contains(&month) || !(1..=days_in_month(self.year, month)).contains(&day) {
            return None;
        }
        tm2timestamp(self.year, month, day, clock, offset)
    }
}

/// Parse a leading `Y{4,}-MM-DD`, where year `Y` BC is year `1 - Y` and year `0000` is year 0.
fn parse_date_prefix(bytes: &[u8], bc: bool) -> Option<(Ymd, &[u8])> {
    let year_len = bytes.iter().take_while(|b| b.is_ascii_digit()).count();
    if year_len < 4 || (year_len > 4 && bytes[0] == b'0') {
        return None;
    }
    let (year_digits, rest) = bytes.split_at(year_len);
    let year = strtoint(year_digits)?;
    let year = match (year, bc) {
        (0, true) => return None,
        (_, true) => 1 - year,
        (_, false) => year,
    };
    let Some((&[b'-', m1, m2, b'-', d1, d2], rest)) = rest.split_first_chunk() else {
        return None;
    };
    let month = parse_two_digits([m1, m2])?;
    let day = parse_two_digits([d1, d2])?;
    Some((Ymd { year, month, day }, rest))
}

/// Parse a leading `HH:MM:SS[.f]` with one to nine fraction digits, as microseconds up to
/// 24:00:00.
fn parse_time_prefix(bytes: &[u8]) -> Option<(i64, &[u8])> {
    let Some((&[h1, h2, b':', m1, m2, b':', s1, s2], rest)) = bytes.split_first_chunk() else {
        return None;
    };
    let (fsec, rest) = match rest.split_first() {
        Some((b'.', fraction)) => {
            let len = fraction.iter().take_while(|b| b.is_ascii_digit()).count();
            if !(1..=9).contains(&len) {
                return None;
            }
            (fractional_second(&rest[..=len]), &fraction[len..])
        }
        _ => (0, rest),
    };
    let (hour, minute, second) = (
        parse_two_digits([h1, h2])?,
        parse_two_digits([m1, m2])?,
        parse_two_digits([s1, s2])?,
    );
    if minute > 59 || second > 59 {
        return None;
    }
    let micros = i64::from(hour) * USECS_PER_HOUR
        + i64::from(minute) * USECS_PER_MINUTE
        + i64::from(second) * USECS_PER_SEC
        + fsec;
    (micros <= USECS_PER_DAY).then_some((micros, rest))
}

/// Parse a leading date and time joined by a space or `T`, the clock in microseconds.
fn parse_datetime_prefix(bytes: &[u8], bc: bool) -> Option<(Ymd, i64, &[u8])> {
    let (date, rest) = parse_date_prefix(bytes, bc)?;
    let (&(b' ' | b'T'), rest) = rest.split_first()? else {
        return None;
    };
    let (clock, rest) = parse_time_prefix(rest)?;
    Some((date, clock, rest))
}

/// Two ASCII digits as a number.
fn parse_two_digits(digits: [u8; 2]) -> Option<u8> {
    if digits.iter().all(u8::is_ascii_digit) {
        Some((digits[0] - b'0') * 10 + (digits[1] - b'0'))
    } else {
        None
    }
}

/// Parse a `Z`, `±HH`, `±HHMM`, `±HH:MM` or `±HH:MM:SS` offset as seconds east of UTC, with an
/// hour up to 23.
fn parse_offset(bytes: &[u8]) -> Option<i32> {
    if bytes == b"Z" {
        return Some(0);
    }
    let (&sign, digits) = bytes.split_first()?;
    let negative = match sign {
        b'+' => false,
        b'-' => true,
        _ => return None,
    };
    let pair = |at: usize| parse_two_digits(digits.get(at..at + 2)?.try_into().ok()?);
    let hour = pair(0)?;
    let (minute, second) = match digits.len() {
        2 => (0, 0),
        4 => (pair(2)?, 0),
        5 if digits[2] == b':' => (pair(3)?, 0),
        8 if digits[2] == b':' && digits[5] == b':' => (pair(3)?, pair(6)?),
        _ => return None,
    };
    if hour > 23 || minute > 59 || second > 59 {
        return None;
    }
    let seconds = (i32::from(hour) * 60 + i32::from(minute)) * 60 + i32::from(second);
    Some(if negative { -seconds } else { seconds })
}