Skip to main content

sql_values/postgres/datetime/
to_char.rs

1//! PostgreSQL 18's `to_char` of a date or time, `DCH_to_char` printing the fields of a value in
2//! the template `parse_format` reads, with the English names of the `C` locale.
3
4use alloc::string::String;
5use core::fmt::Write;
6
7use super::{
8    MONTHS_PER_YEAR, PgDate, PgTime, PgTimeZone, PgTimestamp, PgTimestampTz, USECS_PER_SEC, date2j,
9    local_time_type, split_clock, timestamp2tm,
10};
11use crate::postgres::PgInterval;
12
13/// Why PostgreSQL refuses to format a date or time with `to_char`, one variant per message it
14/// raises.
15#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, thiserror::Error)]
16pub enum TemporalFormatError {
17    /// A field of a calendar date or a zone in the template of an interval or a time, which
18    /// PostgreSQL hints are not tied to calendar dates.
19    #[error("invalid format specification for an interval value")]
20    InvalidForInterval,
21    /// `TZ` or `tz` of a zone abbreviation longer than 24 bytes.
22    #[error("time zone format value too long")]
23    TimeZoneFormatValueTooLong,
24    /// A date from 294277-01-01, or one whose midnight in the zone falls outside the
25    /// `timestamptz` range.
26    #[error("date out of range for timestamp")]
27    DateOutOfRangeForTimestamp,
28}
29
30const MONTHS: [&str; 12] = [
31    "January",
32    "February",
33    "March",
34    "April",
35    "May",
36    "June",
37    "July",
38    "August",
39    "September",
40    "October",
41    "November",
42    "December",
43];
44
45const DAYS: [&str; 7] = [
46    "Sunday",
47    "Monday",
48    "Tuesday",
49    "Wednesday",
50    "Thursday",
51    "Friday",
52    "Saturday",
53];
54
55/// `rm_months_upper`, December first, as `DCH_to_char` indexes it.
56const ROMAN_MONTHS: [&str; 12] = [
57    "XII", "XI", "X", "IX", "VIII", "VII", "VI", "V", "IV", "III", "II", "I",
58];
59
60/// `fmt_tm` and `TmToChar`, the fields of a value `DCH_to_char` prints.
61struct Fields<'a> {
62    year: i32,
63    month: i32,
64    day: i32,
65    hour: i64,
66    minute: i64,
67    second: i64,
68    microsecond: i64,
69    weekday: i32,
70    year_day: i32,
71    /// Seconds east of UTC.
72    offset: i32,
73    zone: Option<&'a str>,
74    /// Whether the fields are an interval's, counting years from zero and refusing the fields
75    /// of a calendar date or a zone.
76    interval: bool,
77}
78
79impl Fields<'_> {
80    /// The fields `timestamp2tm` gives a clock `micros` from 2000-01-01 without a zone, with the
81    /// weekday and day of the year `timestamp_to_char` adds.
82    fn civil(micros: i64) -> Self {
83        let (year, month, day, clock) = timestamp2tm(micros);
84        let (hour, minute, second, microsecond) = split_clock(clock);
85        let julian = date2j(year, month, day);
86        Self {
87            year,
88            month,
89            day,
90            hour,
91            minute,
92            second,
93            microsecond,
94            weekday: (julian + 1) % 7,
95            year_day: julian - date2j(year, 1, 1) + 1,
96            offset: 0,
97            zone: None,
98            interval: false,
99        }
100    }
101
102    /// The fields `interval_to_char` takes from `interval2itm`, each truncated toward zero, the
103    /// day of the year approximating the whole span in days.
104    fn interval(interval: PgInterval) -> Self {
105        let (hour, minute, second, microsecond) = split_clock(interval.microseconds);
106        Self {
107            year: interval.months / MONTHS_PER_YEAR,
108            month: interval.months % MONTHS_PER_YEAR,
109            day: interval.days,
110            hour,
111            minute,
112            second,
113            microsecond,
114            weekday: 0,
115            year_day: interval.months.wrapping_mul(30).wrapping_add(interval.days),
116            offset: 0,
117            zone: None,
118            interval: true,
119        }
120    }
121
122    /// `ADJUST_YEAR`, a date's year counted from 1 in its era, an interval's years as they are.
123    const fn era_year(&self, year: i32) -> i32 {
124        if self.interval || year > 0 {
125            year
126        } else {
127            1 - year
128        }
129    }
130}
131
132/// How a name keyword cases its name.
133#[derive(Debug, Clone, Copy)]
134enum Case {
135    Upper,
136    Capitalized,
137    Lower,
138}
139
140/// A keyword of `DCH_keywords`, the spellings that print alike sharing one.
141#[derive(Debug, Clone, Copy)]
142enum Keyword {
143    /// The morning and the afternoon marker.
144    Meridiem([&'static str; 2]),
145    /// The marker of the years from 1 AD and of those before.
146    Era([&'static str; 2]),
147    Hour12,
148    Hour24,
149    Minute,
150    Second,
151    /// The leading digits of the microseconds.
152    Fraction(u8),
153    SecondsOfDay,
154    ZoneAbbreviation {
155        lower: bool,
156    },
157    ZoneHours,
158    ZoneMinutes,
159    UtcOffset,
160    MonthName(Case),
161    MonthAbbreviation(Case),
162    Month,
163    DayName(Case),
164    DayAbbreviation(Case),
165    DayOfYear,
166    IsoDayOfYear,
167    DayOfMonth,
168    DayOfWeek,
169    IsoDayOfWeek,
170    WeekOfYear,
171    IsoWeek,
172    Quarter,
173    Century,
174    YearWithComma,
175    Year {
176        digits: usize,
177    },
178    IsoYear {
179        digits: usize,
180    },
181    RomanMonth {
182        upper: bool,
183    },
184    WeekOfMonth,
185    Julian,
186    FixedFormat,
187}
188
189/// `DCH_keywords` in its order, where the first that starts the template wins.
190const KEYWORDS: &[(&str, Keyword)] = {
191    use Case::{Capitalized, Lower, Upper};
192    use Keyword::*;
193    &[
194        ("A.D.", Era(["A.D.", "B.C."])),
195        ("A.M.", Meridiem(["A.M.", "P.M."])),
196        ("AD", Era(["AD", "BC"])),
197        ("AM", Meridiem(["AM", "PM"])),
198        ("B.C.", Era(["A.D.", "B.C."])),
199        ("BC", Era(["AD", "BC"])),
200        ("CC", Century),
201        ("DAY", DayName(Upper)),
202        ("DDD", DayOfYear),
203        ("DD", DayOfMonth),
204        ("DY", DayAbbreviation(Upper)),
205        ("Day", DayName(Capitalized)),
206        ("Dy", DayAbbreviation(Capitalized)),
207        ("D", DayOfWeek),
208        ("FF1", Fraction(1)),
209        ("FF2", Fraction(2)),
210        ("FF3", Fraction(3)),
211        ("FF4", Fraction(4)),
212        ("FF5", Fraction(5)),
213        ("FF6", Fraction(6)),
214        ("FX", FixedFormat),
215        ("HH24", Hour24),
216        ("HH12", Hour12),
217        ("HH", Hour12),
218        ("IDDD", IsoDayOfYear),
219        ("ID", IsoDayOfWeek),
220        ("IW", IsoWeek),
221        ("IYYY", IsoYear { digits: 4 }),
222        ("IYY", IsoYear { digits: 3 }),
223        ("IY", IsoYear { digits: 2 }),
224        ("I", IsoYear { digits: 1 }),
225        ("J", Julian),
226        ("MI", Minute),
227        ("MM", Month),
228        ("MONTH", MonthName(Upper)),
229        ("MON", MonthAbbreviation(Upper)),
230        ("MS", Fraction(3)),
231        ("Month", MonthName(Capitalized)),
232        ("Mon", MonthAbbreviation(Capitalized)),
233        ("OF", UtcOffset),
234        ("P.M.", Meridiem(["A.M.", "P.M."])),
235        ("PM", Meridiem(["AM", "PM"])),
236        ("Q", Quarter),
237        ("RM", RomanMonth { upper: true }),
238        ("SSSSS", SecondsOfDay),
239        ("SSSS", SecondsOfDay),
240        ("SS", Second),
241        ("TZH", ZoneHours),
242        ("TZM", ZoneMinutes),
243        ("TZ", ZoneAbbreviation { lower: false }),
244        ("US", Fraction(6)),
245        ("WW", WeekOfYear),
246        ("W", WeekOfMonth),
247        ("Y,YYY", YearWithComma),
248        ("YYYY", Year { digits: 4 }),
249        ("YYY", Year { digits: 3 }),
250        ("YY", Year { digits: 2 }),
251        ("Y", Year { digits: 1 }),
252        ("a.d.", Era(["a.d.", "b.c."])),
253        ("a.m.", Meridiem(["a.m.", "p.m."])),
254        ("ad", Era(["ad", "bc"])),
255        ("am", Meridiem(["am", "pm"])),
256        ("b.c.", Era(["a.d.", "b.c."])),
257        ("bc", Era(["ad", "bc"])),
258        ("cc", Century),
259        ("day", DayName(Lower)),
260        ("ddd", DayOfYear),
261        ("dd", DayOfMonth),
262        ("dy", DayAbbreviation(Lower)),
263        ("d", DayOfWeek),
264        ("ff1", Fraction(1)),
265        ("ff2", Fraction(2)),
266        ("ff3", Fraction(3)),
267        ("ff4", Fraction(4)),
268        ("ff5", Fraction(5)),
269        ("ff6", Fraction(6)),
270        ("fx", FixedFormat),
271        ("hh24", Hour24),
272        ("hh12", Hour12),
273        ("hh", Hour12),
274        ("iddd", IsoDayOfYear),
275        ("id", IsoDayOfWeek),
276        ("iw", IsoWeek),
277        ("iyyy", IsoYear { digits: 4 }),
278        ("iyy", IsoYear { digits: 3 }),
279        ("iy", IsoYear { digits: 2 }),
280        ("i", IsoYear { digits: 1 }),
281        ("j", Julian),
282        ("mi", Minute),
283        ("mm", Month),
284        ("month", MonthName(Lower)),
285        ("mon", MonthAbbreviation(Lower)),
286        ("ms", Fraction(3)),
287        ("of", UtcOffset),
288        ("p.m.", Meridiem(["a.m.", "p.m."])),
289        ("pm", Meridiem(["am", "pm"])),
290        ("q", Quarter),
291        ("rm", RomanMonth { upper: false }),
292        ("sssss", SecondsOfDay),
293        ("ssss", SecondsOfDay),
294        ("ss", Second),
295        ("tzh", ZoneHours),
296        ("tzm", ZoneMinutes),
297        ("tz", ZoneAbbreviation { lower: true }),
298        ("us", Fraction(6)),
299        ("ww", WeekOfYear),
300        ("w", WeekOfMonth),
301        ("y,yyy", YearWithComma),
302        ("yyyy", Year { digits: 4 }),
303        ("yyy", Year { digits: 3 }),
304        ("yy", Year { digits: 2 }),
305        ("y", Year { digits: 1 }),
306    ]
307};
308
309/// The suffix `TH` or `th` that appends a number's English ordinal ending.
310#[derive(Debug, Clone, Copy)]
311enum Ordinal {
312    Upper,
313    Lower,
314}
315
316/// A keyword and the modifiers `parse_format` read around it.
317#[derive(Debug, Clone, Copy)]
318struct Field {
319    keyword: Keyword,
320    /// `FM`, dropping the padding.
321    fill: bool,
322    /// `TM`, the locale's names without padding.
323    translate: bool,
324    ordinal: Option<Ordinal>,
325}
326
327/// One node of a template, text copied as it is or a field.
328#[derive(Debug, Clone, Copy)]
329enum Node<'a> {
330    Text(&'a str),
331    Field(Field),
332}
333
334/// `parse_format`'s reading of a template into nodes, as a cursor over the borrowed text.
335struct Nodes<'a> {
336    rest: &'a str,
337    quoted: bool,
338}
339
340impl<'a> Nodes<'a> {
341    const fn new(template: &'a str) -> Self {
342        Self {
343            rest: template,
344            quoted: false,
345        }
346    }
347
348    /// Moves past `prefix` when the text starts with it.
349    fn eat(&mut self, prefix: &str) -> bool {
350        match self.rest.strip_prefix(prefix) {
351            Some(rest) => {
352                self.rest = rest;
353                true
354            }
355            None => false,
356        }
357    }
358
359    /// The next character as text, past a backslash `parse_format` drops before it.
360    fn character(&mut self, escaped: bool) -> &'a str {
361        if escaped {
362            self.rest = &self.rest[1..];
363        }
364        let width = self.rest.chars().next().map_or(0, char::len_utf8);
365        let (character, rest) = self.rest.split_at(width);
366        self.rest = rest;
367        character
368    }
369}
370
371impl<'a> Iterator for Nodes<'a> {
372    type Item = Node<'a>;
373
374    fn next(&mut self) -> Option<Node<'a>> {
375        loop {
376            if self.rest.is_empty() {
377                return None;
378            }
379            if self.quoted {
380                if self.eat("\"") {
381                    self.quoted = false;
382                    continue;
383                }
384                // A backslash quotes the character after it, and a last one is itself.
385                let escaped = self.rest.starts_with('\\') && self.rest.len() > 1;
386                return Some(Node::Text(self.character(escaped)));
387            }
388            // A prefix is read, and lost, even where no keyword follows it.
389            let fill = self.eat("FM") || self.eat("fm");
390            let translate = !fill && (self.eat("TM") || self.eat("tm"));
391            if let Some(&(name, keyword)) = KEYWORDS
392                .iter()
393                .find(|(name, _)| self.rest.starts_with(name))
394            {
395                self.rest = &self.rest[name.len()..];
396                let ordinal = if self.eat("TH") {
397                    Some(Ordinal::Upper)
398                } else if self.eat("th") {
399                    Some(Ordinal::Lower)
400                } else {
401                    // `SP` is read and prints nothing.
402                    self.eat("SP");
403                    None
404                };
405                return Some(Node::Field(Field {
406                    keyword,
407                    fill,
408                    translate,
409                    ordinal,
410                }));
411            }
412            if self.rest.is_empty() {
413                return None;
414            }
415            if self.eat("\"") {
416                self.quoted = true;
417                continue;
418            }
419            // Outside quotes a backslash is special only before a double quote.
420            let escaped = self.rest.starts_with("\\\"");
421            return Some(Node::Text(self.character(escaped)));
422        }
423    }
424}
425
426/// `DCH_to_char`, the text of `fields` in `template`.
427fn format(template: &str, fields: &Fields<'_>) -> Result<String, TemporalFormatError> {
428    let mut out = String::with_capacity(template.len());
429    for node in Nodes::new(template) {
430        match node {
431            Node::Text(text) => out.push_str(text),
432            Node::Field(field) => field.write(fields, &mut out)?,
433        }
434    }
435    Ok(out)
436}
437
438/// `j2day`, the weekday of a Julian day from Sunday at 0.
439const fn j2day(julian: i32) -> i32 {
440    julian.wrapping_add(1).rem_euclid(7)
441}
442
443/// `isoweek2j(year, 1)`, the Julian day of the Monday that starts the first ISO week of `year`.
444const fn iso_week_start(year: i32) -> i32 {
445    let day4 = date2j(year, 1, 4);
446    day4.wrapping_sub(j2day(day4.wrapping_sub(1)))
447}
448
449/// `date2isoweek`, the ISO week of a date.
450const fn date2isoweek(year: i32, month: i32, day: i32) -> i32 {
451    let julian = date2j(year, month, day);
452    let mut start = iso_week_start(year);
453    if julian < start {
454        start = iso_week_start(year.wrapping_sub(1));
455    }
456    let mut week = julian.wrapping_sub(start) / 7 + 1;
457    if week >= 52 {
458        let next = iso_week_start(year.wrapping_add(1));
459        if julian >= next {
460            week = julian.wrapping_sub(next) / 7 + 1;
461        }
462    }
463    week
464}
465
466/// `date2isoyear`, the ISO year of a date, 0 being 1 BC.
467const fn date2isoyear(year: i32, month: i32, day: i32) -> i32 {
468    let julian = date2j(year, month, day);
469    let mut year = year;
470    let mut start = iso_week_start(year);
471    if julian < start {
472        year = year.wrapping_sub(1);
473        start = iso_week_start(year);
474    }
475    if julian.wrapping_sub(start) / 7 + 1 >= 52 && julian >= iso_week_start(year.wrapping_add(1)) {
476        year = year.wrapping_add(1);
477    }
478    year
479}
480
481/// The widest of `width` for a value from zero up, one more for a negative one.
482const fn signed_width(fill: bool, negative: bool, width: usize) -> usize {
483    if fill {
484        0
485    } else if negative {
486        width + 1
487    } else {
488        width
489    }
490}
491
492impl Field {
493    /// Appends the field's text for `fields` to `out`.
494    fn write(self, fields: &Fields<'_>, out: &mut String) -> Result<(), TemporalFormatError> {
495        let start = out.len();
496        let fill = self.fill;
497        let width = |width| if fill { 0 } else { width };
498        if fields.interval && self.keyword.needs_calendar_date() {
499            return Err(TemporalFormatError::InvalidForInterval);
500        }
501        match self.keyword {
502            Keyword::Meridiem([morning, afternoon]) => {
503                out.push_str(if fields.hour % 24 >= 12 {
504                    afternoon
505                } else {
506                    morning
507                });
508            }
509            Keyword::Era([common, before]) => {
510                out.push_str(if fields.year <= 0 { before } else { common });
511            }
512            Keyword::Hour12 => {
513                let hour = match fields.hour % 12 {
514                    0 => 12,
515                    hour => hour,
516                };
517                number(out, hour, signed_width(fill, fields.hour < 0, 2));
518            }
519            Keyword::Hour24 => number(out, fields.hour, signed_width(fill, fields.hour < 0, 2)),
520            Keyword::Minute => {
521                number(out, fields.minute, signed_width(fill, fields.minute < 0, 2));
522            }
523            Keyword::Second => {
524                number(out, fields.second, signed_width(fill, fields.second < 0, 2));
525            }
526            Keyword::Fraction(digits) => {
527                let divisor = 10_i64.pow(u32::from(6 - digits));
528                number(out, fields.microsecond / divisor, usize::from(digits));
529            }
530            Keyword::SecondsOfDay => {
531                number(
532                    out,
533                    fields.hour * 3_600 + fields.minute * 60 + fields.second,
534                    0,
535                );
536            }
537            Keyword::ZoneAbbreviation { lower } => {
538                if let Some(zone) = fields.zone {
539                    if zone.len() > 24 {
540                        return Err(TemporalFormatError::TimeZoneFormatValueTooLong);
541                    }
542                    if lower {
543                        out.extend(zone.chars().map(|c| c.to_ascii_lowercase()));
544                    } else {
545                        out.push_str(zone);
546                    }
547                }
548            }
549            Keyword::ZoneHours => {
550                out.push(offset_sign(fields.offset));
551                number(out, (fields.offset.unsigned_abs() / 3_600).into(), 2);
552            }
553            Keyword::ZoneMinutes => {
554                number(out, (fields.offset.unsigned_abs() % 3_600 / 60).into(), 2);
555            }
556            Keyword::UtcOffset => {
557                let magnitude = fields.offset.unsigned_abs();
558                out.push(offset_sign(fields.offset));
559                number(out, (magnitude / 3_600).into(), width(2));
560                if !magnitude.is_multiple_of(3_600) {
561                    out.push(':');
562                    number(out, (magnitude % 3_600 / 60).into(), 2);
563                }
564            }
565            Keyword::MonthName(case) => {
566                self.name(out, MONTHS[month_index(fields.month)], case, 9);
567            }
568            Keyword::MonthAbbreviation(case) => {
569                self.name(out, &MONTHS[month_index(fields.month)][..3], case, 0);
570            }
571            Keyword::Month => {
572                let month = fields.month.into();
573                number(out, month, signed_width(fill, month < 0, 2));
574            }
575            Keyword::DayName(case) => self.name(out, DAYS[day_index(fields.weekday)], case, 9),
576            Keyword::DayAbbreviation(case) => {
577                self.name(out, &DAYS[day_index(fields.weekday)][..3], case, 0);
578            }
579            Keyword::DayOfYear => number(out, fields.year_day.into(), width(3)),
580            Keyword::IsoDayOfYear => {
581                let year = date2isoyear(fields.year, fields.month, fields.day);
582                let julian = date2j(fields.year, fields.month, fields.day);
583                let day = julian.wrapping_sub(iso_week_start(year)).wrapping_add(1);
584                number(out, day.into(), width(3));
585            }
586            Keyword::DayOfMonth => number(out, fields.day.into(), width(2)),
587            Keyword::DayOfWeek => number(out, (fields.weekday + 1).into(), 0),
588            Keyword::IsoDayOfWeek => {
589                let day = if fields.weekday == 0 {
590                    7
591                } else {
592                    fields.weekday
593                };
594                number(out, day.into(), 0);
595            }
596            Keyword::WeekOfYear => {
597                let week = fields.year_day.wrapping_sub(1) / 7 + 1;
598                number(out, week.into(), width(2));
599            }
600            Keyword::IsoWeek => {
601                let week = date2isoweek(fields.year, fields.month, fields.day);
602                number(out, week.into(), width(2));
603            }
604            Keyword::Quarter => {
605                if fields.month == 0 {
606                    return Ok(());
607                }
608                number(out, ((fields.month - 1) / 3 + 1).into(), 0);
609            }
610            Keyword::Century => {
611                let century = if fields.interval {
612                    fields.year / 100
613                } else if fields.year > 0 {
614                    (fields.year - 1) / 100 + 1
615                } else {
616                    fields.year / 100 - 1
617                };
618                let width = if (-99..=99).contains(&century) {
619                    signed_width(fill, century < 0, 2)
620                } else {
621                    0
622                };
623                number(out, century.into(), width);
624            }
625            Keyword::YearWithComma => {
626                let year = fields.era_year(fields.year);
627                let thousands = year / 1_000;
628                number(out, thousands.into(), 0);
629                out.push(',');
630                number(out, (year - thousands * 1_000).into(), 3);
631            }
632            Keyword::Year { digits } => {
633                self.year(out, fields, fields.era_year(fields.year), digits);
634            }
635            Keyword::IsoYear { digits } => {
636                let year = date2isoyear(fields.year, fields.month, fields.day);
637                self.year(out, fields, fields.era_year(year), digits);
638            }
639            Keyword::RomanMonth { upper } => {
640                if fields.month == 0 && fields.year == 0 {
641                    return Ok(());
642                }
643                let index = match fields.month {
644                    0 if fields.year >= 0 => 0,
645                    0 => 11,
646                    month if month < 0 => -(month + 1),
647                    month => 12 - month,
648                };
649                let numeral = ROMAN_MONTHS[usize::try_from(index).expect("a month within a year")];
650                let padding = if fill { 0 } else { 4 };
651                let numeral_start = out.len();
652                if upper {
653                    out.push_str(numeral);
654                } else {
655                    out.extend(numeral.chars().map(|c| c.to_ascii_lowercase()));
656                }
657                pad(out, numeral_start, padding);
658                return Ok(());
659            }
660            Keyword::WeekOfMonth => {
661                number(out, (fields.day.wrapping_sub(1) / 7 + 1).into(), 0);
662            }
663            Keyword::Julian => {
664                number(out, date2j(fields.year, fields.month, fields.day).into(), 0);
665            }
666            Keyword::FixedFormat => return Ok(()),
667        }
668        if let Some(ordinal) = self.ordinal
669            && self.keyword.is_number()
670        {
671            append_ordinal(out, start, ordinal);
672        }
673        Ok(())
674    }
675
676    /// A day or month name in `case`, padded to `padding` unless `FM` or `TM` is given.
677    fn name(self, out: &mut String, name: &str, case: Case, padding: usize) {
678        let start = out.len();
679        match case {
680            Case::Upper => out.extend(name.chars().map(|c| c.to_ascii_uppercase())),
681            Case::Capitalized => out.push_str(name),
682            Case::Lower => out.extend(name.chars().map(|c| c.to_ascii_lowercase())),
683        }
684        if !self.fill && !self.translate {
685            pad(out, start, padding);
686        }
687    }
688
689    /// The last `digits` of `year`, widened by one when the era year of `fields` is negative.
690    fn year(self, out: &mut String, fields: &Fields<'_>, year: i32, digits: usize) {
691        let (value, width) = match digits {
692            4 => (year, 4),
693            3 => (year % 1_000, 3),
694            2 => (year % 100, 2),
695            _ => {
696                number(out, (year % 10).into(), 1);
697                return;
698            }
699        };
700        let negative = fields.era_year(fields.year) < 0;
701        number(out, value.into(), signed_width(self.fill, negative, width));
702    }
703}
704
705impl Keyword {
706    /// Whether the keyword prints a field of a calendar date or a zone, `INVALID_FOR_INTERVAL`.
707    const fn needs_calendar_date(self) -> bool {
708        matches!(
709            self,
710            Self::Era(_)
711                | Self::ZoneAbbreviation { .. }
712                | Self::ZoneHours
713                | Self::ZoneMinutes
714                | Self::UtcOffset
715                | Self::MonthName(_)
716                | Self::MonthAbbreviation(_)
717                | Self::DayName(_)
718                | Self::DayAbbreviation(_)
719                | Self::DayOfWeek
720                | Self::IsoDayOfWeek
721        )
722    }
723
724    /// Whether `TH` and `th` append an ordinal ending to the keyword's text.
725    const fn is_number(self) -> bool {
726        !matches!(
727            self,
728            Self::Meridiem { .. }
729                | Self::Era { .. }
730                | Self::ZoneAbbreviation { .. }
731                | Self::ZoneHours
732                | Self::ZoneMinutes
733                | Self::UtcOffset
734                | Self::MonthName(_)
735                | Self::MonthAbbreviation(_)
736                | Self::DayName(_)
737                | Self::DayAbbreviation(_)
738                | Self::RomanMonth { .. }
739                | Self::FixedFormat
740        )
741    }
742}
743
744/// The index of a calendar month in [`MONTHS`].
745fn month_index(month: i32) -> usize {
746    usize::try_from(month - 1).expect("a calendar month from 1 to 12")
747}
748
749/// The index in [`DAYS`] of a weekday, which C's `%` leaves negative for a local date before
750/// 4714-11-23 BC, where PostgreSQL reads the name from outside its table and this takes the
751/// date's own weekday.
752fn day_index(weekday: i32) -> usize {
753    usize::try_from(weekday.rem_euclid(7)).expect("a remainder of 7 fits usize")
754}
755
756const fn offset_sign(offset: i32) -> char {
757    if offset >= 0 { '+' } else { '-' }
758}
759
760/// C's `%0*d`, `value` zero-padded after its sign to `width` characters.
761fn number(out: &mut String, value: i64, width: usize) {
762    write!(out, "{value:0width$}").expect("a String takes any text");
763}
764
765/// C's `%-*s`, the text from `start` padded with blanks to `width` characters.
766fn pad(out: &mut String, start: usize, width: usize) {
767    let written = out[start..].chars().count();
768    out.extend(core::iter::repeat_n(' ', width.saturating_sub(written)));
769}
770
771/// `str_numth`, the English ordinal ending of the number from `start`, `TH` for each number
772/// ending in 11 to 13.
773fn append_ordinal(out: &mut String, start: usize, ordinal: Ordinal) {
774    let digits = &out.as_bytes()[start..];
775    let last = digits.last().copied();
776    let teen = digits.len() > 1 && digits[digits.len() - 2] == b'1';
777    let ending = match (last, teen) {
778        (Some(b'1'), false) => "st",
779        (Some(b'2'), false) => "nd",
780        (Some(b'3'), false) => "rd",
781        _ => "th",
782    };
783    match ordinal {
784        Ordinal::Upper => out.extend(ending.chars().map(|c| c.to_ascii_uppercase())),
785        Ordinal::Lower => out.push_str(ending),
786    }
787}
788
789impl PgTimestamp {
790    /// PostgreSQL's `to_char(timestamp, text)` under `lc_time` `C`, or `None`, PostgreSQL's SQL
791    /// `NULL`, for an empty template or an infinite timestamp.
792    ///
793    /// The template's keywords print the fields of the timestamp, `FM` before one drops its
794    /// padding, `TM` prints a name unpadded, and `TH` or `th` after a number its ordinal ending.
795    /// Every other character is copied, and a double-quoted run is copied whole.
796    ///
797    /// ```
798    /// use sql_values::postgres::{PgDate, PgTime, PgTimestamp};
799    ///
800    /// let date = PgDate::from_ymd(2024, 2, 29).unwrap();
801    /// let at = PgTimestamp::new(date, PgTime::from_hms_micro(13, 4, 5, 123_456).unwrap()).unwrap();
802    /// assert_eq!(
803    ///     at.to_char("FMDay|FMMonth|DDTH|J").as_deref(),
804    ///     Some("Thursday|February|29TH|2460370"),
805    /// );
806    /// assert_eq!(at.to_char("HH24:MI:SS.US").as_deref(), Some("13:04:05.123456"));
807    /// assert_eq!(at.to_char("Day|\"YYYY\"").as_deref(), Some("Thursday |YYYY"));
808    /// assert_eq!(at.to_char(""), None);
809    /// assert_eq!(PgTimestamp::INFINITY.to_char("YYYY"), None);
810    /// ```
811    #[must_use]
812    pub fn to_char(self, template: &str) -> Option<String> {
813        if template.is_empty() || !self.is_finite() {
814            return None;
815        }
816        let fields = Fields::civil(self.pg_micros());
817        let text = format(template, &fields);
818        Some(text.expect("only an interval's fields or a zone abbreviation refuse a template"))
819    }
820}
821
822impl PgTimestampTz {
823    /// PostgreSQL's `to_char(timestamptz, text)` with `zone` as the session's `TimeZone`, under
824    /// `lc_time` `C`, printing the local clock and `zone`'s offset and abbreviation at the
825    /// instant, or `None`, PostgreSQL's SQL `NULL`, for an empty template or an infinite instant.
826    ///
827    /// # Errors
828    ///
829    /// [`TemporalFormatError::TimeZoneFormatValueTooLong`] for `TZ` or `tz` of an abbreviation
830    /// longer than 24 bytes.
831    ///
832    /// ```
833    /// use sql_values::postgres::{InputContext, PgTimeZone, PgTimestampTz};
834    ///
835    /// #[cfg(feature = "tzdb")]
836    /// {
837    ///     let new_york = PgTimeZone::parse("America/New_York").unwrap();
838    ///     let at = PgTimestampTz::parse("2024-03-10 07:00:00+00", InputContext::new()).unwrap();
839    ///     assert_eq!(
840    ///         at.to_char("YYYY-MM-DD HH24:MI:SS TZ TZH TZM OF", &new_york).unwrap().as_deref(),
841    ///         Some("2024-03-10 03:00:00 EDT -04 00 -04"),
842    ///     );
843    /// }
844    /// let kathmandu = PgTimeZone::parse("<+0545>-05:45").unwrap();
845    /// let at = PgTimestampTz::parse("2024-02-29 00:00:00+00", InputContext::new()).unwrap();
846    /// assert_eq!(
847    ///     at.to_char("HH24:MI tz OF", &kathmandu).unwrap().as_deref(),
848    ///     Some("05:45 +0545 +05:45"),
849    /// );
850    /// assert_eq!(PgTimestampTz::INFINITY.to_char("YYYY", &kathmandu), Ok(None));
851    /// ```
852    pub fn to_char(
853        self,
854        template: &str,
855        zone: &PgTimeZone,
856    ) -> Result<Option<String>, TemporalFormatError> {
857        if template.is_empty() || !self.is_finite() {
858            return Ok(None);
859        }
860        let utc = self.pg_micros();
861        let (offset, abbreviation) = local_time_type(zone, utc);
862        let fields = Fields {
863            offset,
864            zone: Some(abbreviation.as_str()),
865            ..Fields::civil(utc + i64::from(offset) * USECS_PER_SEC)
866        };
867        format(template, &fields).map(Some)
868    }
869}
870
871impl PgDate {
872    /// PostgreSQL's `to_char(date, text)`, which formats the `timestamptz` of the date's first
873    /// moment in `zone`, the session's `TimeZone`, under `lc_time` `C`, or `None`, PostgreSQL's
874    /// SQL `NULL`, for an empty template or an infinite date.
875    ///
876    /// # Errors
877    ///
878    /// [`TemporalFormatError::DateOutOfRangeForTimestamp`] where the date's first moment lies
879    /// outside the `timestamptz` range, refused before the template is read, and the errors of
880    /// [`PgTimestampTz::to_char`].
881    ///
882    /// ```
883    /// use sql_values::postgres::{PgDate, PgTimeZone, TemporalFormatError};
884    ///
885    /// let utc = PgTimeZone::parse("UTC0").unwrap();
886    /// let leap = PgDate::from_ymd(2024, 2, 29).unwrap();
887    /// assert_eq!(
888    ///     leap.to_char("YYYY-MM-DD HH24:MI:SS TZ", &utc).unwrap().as_deref(),
889    ///     Some("2024-02-29 00:00:00 UTC"),
890    /// );
891    /// let late = PgDate::from_ymd(294_277, 1, 1).unwrap();
892    /// assert_eq!(late.to_char("", &utc), Err(TemporalFormatError::DateOutOfRangeForTimestamp));
893    ///
894    /// #[cfg(feature = "tzdb")]
895    /// {
896    ///     let rome = PgTimeZone::parse("Europe/Rome").unwrap();
897    ///     let far = PgDate::from_ymd(100_000, 7, 1).unwrap();
898    ///     assert_eq!(far.to_char("YYYY TZ", &rome).unwrap().as_deref(), Some("100000 CEST"));
899    /// }
900    /// ```
901    pub fn to_char(
902        self,
903        template: &str,
904        zone: &PgTimeZone,
905    ) -> Result<Option<String>, TemporalFormatError> {
906        // `date2timestamptz_opt_overflow` raises this error for either end of the range.
907        let out_of_range = TemporalFormatError::DateOutOfRangeForTimestamp;
908        let midnight = self.to_timestamp().map_err(|_| out_of_range)?;
909        let instant = midnight.to_timestamptz(zone).map_err(|_| out_of_range)?;
910        instant.to_char(template, zone)
911    }
912}
913
914impl PgInterval {
915    /// PostgreSQL's `to_char(interval, text)` under `lc_time` `C`, or `None`, PostgreSQL's SQL
916    /// `NULL`, for an empty template or an infinite interval.
917    ///
918    /// Years are the months over twelve and months the rest, days and the clock are printed as
919    /// they are held, each truncated toward zero with its sign, and `DDD` approximates the whole
920    /// span in days with a month as 30.
921    ///
922    /// # Errors
923    ///
924    /// [`TemporalFormatError::InvalidForInterval`] for a template naming a weekday, a month or
925    /// day name, an era or a zone field.
926    ///
927    /// ```
928    /// use sql_values::postgres::{TemporalFormatError, parse_interval};
929    ///
930    /// let span = parse_interval("1 year 2 months 3 days 25 hours 4 minutes 5.123456 seconds").unwrap();
931    /// assert_eq!(
932    ///     span.to_char("YYYY MM DD HH24 HH12 MI SS US").unwrap().as_deref(),
933    ///     Some("0001 02 03 25 01 04 05 123456"),
934    /// );
935    /// let negative = parse_interval("-1 year -2 months -3 days -25 hours").unwrap();
936    /// assert_eq!(
937    ///     negative.to_char("YYYY MM DD HH24 HH12").unwrap().as_deref(),
938    ///     Some("-0001 -02 -3 -25 -01"),
939    /// );
940    /// assert_eq!(span.to_char("IYYY IW ID"), Err(TemporalFormatError::InvalidForInterval));
941    /// ```
942    pub fn to_char(self, template: &str) -> Result<Option<String>, TemporalFormatError> {
943        if template.is_empty() || !self.is_finite() {
944            return Ok(None);
945        }
946        format(template, &Fields::interval(self)).map(Some)
947    }
948}
949
950impl PgTime {
951    /// PostgreSQL's `to_char(time, text)`, which formats the time cast to an `interval` of its
952    /// microseconds, as [`PgInterval::to_char`] does, or `None` for an empty template.
953    ///
954    /// # Errors
955    ///
956    /// [`TemporalFormatError::InvalidForInterval`] for a template naming a weekday, a month or
957    /// day name, an era or a zone field.
958    ///
959    /// ```
960    /// use sql_values::postgres::{PgTime, TemporalFormatError};
961    ///
962    /// let midnight = PgTime::from_hms_micro(24, 0, 0, 0).unwrap();
963    /// assert_eq!(
964    ///     midnight.to_char("HH24:MI:SS YYYY-MM-DD").unwrap().as_deref(),
965    ///     Some("24:00:00 0000-00-00"),
966    /// );
967    /// let noon = PgTime::from_hms_micro(12, 0, 0, 0).unwrap();
968    /// assert_eq!(noon.to_char("TZ"), Err(TemporalFormatError::InvalidForInterval));
969    /// ```
970    pub fn to_char(self, template: &str) -> Result<Option<String>, TemporalFormatError> {
971        let interval = PgInterval {
972            months: 0,
973            days: 0,
974            microseconds: self.micros(),
975        };
976        interval.to_char(template)
977    }
978}