Skip to main content

spg_engine/eval/
format.rs

1//! Canonical PG text representation of typed values + date/time literal
2//! parsing, split out of `eval.rs` (cut 31). The value→text formatters
3//! (`format_date` / `format_timestamp` / `format_timestamptz` /
4//! `format_time` / `format_timetz` / `format_money` / `format_interval`
5//! / `format_numeric` and the array formatters) plus the inverse
6//! `parse_date_literal` / `parse_timestamp_literal` text→value parsers
7//! with their TZ-suffix helpers. `civil_from_days` stays in `eval.rs`
8//! (shared with the date SQL functions there); the calendar-arithmetic
9//! helpers (`add_months_to_civil` / `days_in_month`) stay alongside
10//! `shift_date_by_months` in `eval.rs`.
11
12use alloc::format;
13use alloc::string::{String, ToString};
14use alloc::vec::Vec;
15
16use super::{MONTH_ABBR, MONTH_FULL, civil_from_days};
17
18// ---- v7.39 (GUC knife 3) — render styles ----
19//
20// PG's DateStyle / IntervalStyle / extra_float_digits GUCs change the
21// TEXT of date/timestamp/interval/float output everywhere the out-
22// functions run (wire cells, COPY, ::text casts). The engine caches a
23// parsed `RenderStyle` per session; formatters take it by reference.
24// Every shape below is verified against live PG18 (knife-3 probe).
25
26#[derive(Clone, Copy, PartialEq, Eq, Debug)]
27pub enum DateOrder {
28    Mdy,
29    Dmy,
30    Ymd,
31}
32
33#[derive(Clone, Copy, PartialEq, Eq, Debug)]
34pub enum DateStyleKind {
35    Iso,
36    German,
37    Sql,
38    Postgres,
39}
40
41#[derive(Clone, Copy, PartialEq, Eq, Debug)]
42pub enum IntervalStyleKind {
43    Postgres,
44    SqlStandard,
45    Iso8601,
46    PostgresVerbose,
47}
48
49#[derive(Clone, Copy, PartialEq, Eq, Debug)]
50pub struct RenderStyle {
51    pub date_style: DateStyleKind,
52    pub date_order: DateOrder,
53    pub interval_style: IntervalStyleKind,
54    /// PG default 1: >= 1 means shortest-round-trip output; 0 and
55    /// negative trim to 15+n (float8) / 6+n (float4) significant digits.
56    pub extra_float_digits: i32,
57    /// v7.39 (round 524) — the session asked for `bytea_output =
58    /// 'escape'`. PG's other bytea form: printable bytes as themselves, a
59    /// backslash doubled, everything else three-digit octal. SPG accepted
60    /// the SET and rendered hex regardless, so a client that asked for
61    /// escape got the form it had just said it did not want.
62    pub bytea_escape: bool,
63    /// v7.39 (round 368, M20 P3) — the session is on the MySQL dialect, so
64    /// a binary string (`Value::Bytes`, e.g. a `0x…` literal) renders as
65    /// its raw bytes read latin-1 (`0x41` → 'A', `CONCAT(0x41,'B')` →
66    /// 'AB'), not as PG's `\x…` hex form.
67    pub mysql: bool,
68}
69
70impl Default for RenderStyle {
71    fn default() -> Self {
72        Self {
73            date_style: DateStyleKind::Iso,
74            date_order: DateOrder::Mdy,
75            interval_style: IntervalStyleKind::Postgres,
76            extra_float_digits: 1,
77            bytea_escape: false,
78            mysql: false,
79        }
80    }
81}
82
83/// Day-of-week abbreviation. 1970-01-01 (day 0) was a Thursday.
84fn dow_abbr(days: i32) -> &'static str {
85    const DOW: [&str; 7] = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
86    DOW[((days.rem_euclid(7)) as usize + 3) % 7]
87}
88
89/// `HH:MM:SS[.frac]` with the 6-digit fraction's trailing zeros
90/// stripped — the intra-day part every timestamp style shares.
91fn hms_from_day_micros(day_micros: i64) -> String {
92    let secs = day_micros / 1_000_000;
93    let frac = day_micros % 1_000_000;
94    let hh = secs / 3600;
95    let mm = (secs / 60) % 60;
96    let ss = secs % 60;
97    if frac == 0 {
98        format!("{hh:02}:{mm:02}:{ss:02}")
99    } else {
100        let raw = format!("{frac:06}");
101        let trimmed = raw.trim_end_matches('0');
102        format!("{hh:02}:{mm:02}:{ss:02}.{trimmed}")
103    }
104}
105
106/// `format_date` under a DateStyle. PG18 shapes:
107/// ISO `2024-03-15` · German `15.03.2024` · SQL `03/15/2024` (DMY
108/// `15/03/2024`) · Postgres `03-15-2024` (DMY `15-03-2024`). YMD field
109/// order affects only ISO-irrelevant styles' INPUT; output falls back
110/// to the MDY arrangement (as PG does).
111pub fn format_date_styled(days: i32, style: &RenderStyle) -> String {
112    if days == i32::MAX {
113        return "infinity".into();
114    }
115    if days == i32::MIN {
116        return "-infinity".into();
117    }
118    let (y, m, d) = civil_from_days(days);
119    let (y, bc) = if y <= 0 { (1 - y, " BC") } else { (y, "") };
120    let dmy = style.date_order == DateOrder::Dmy;
121    match style.date_style {
122        DateStyleKind::Iso => format!("{y:04}-{m:02}-{d:02}{bc}"),
123        DateStyleKind::German => format!("{d:02}.{m:02}.{y:04}{bc}"),
124        DateStyleKind::Sql => {
125            if dmy {
126                format!("{d:02}/{m:02}/{y:04}{bc}")
127            } else {
128                format!("{m:02}/{d:02}/{y:04}{bc}")
129            }
130        }
131        DateStyleKind::Postgres => {
132            if dmy {
133                format!("{d:02}-{m:02}-{y:04}{bc}")
134            } else {
135                format!("{m:02}-{d:02}-{y:04}{bc}")
136            }
137        }
138    }
139}
140
141/// `format_timestamp` under a DateStyle. German/SQL prepend their date
142/// form; Postgres style is the asctime-like
143/// `Dow Mon DD HH:MM:SS[.f] YYYY` (DMY: `Dow DD Mon …`).
144pub fn format_timestamp_styled(micros: i64, style: &RenderStyle) -> String {
145    if micros == i64::MAX {
146        return "infinity".into();
147    }
148    if micros == i64::MIN {
149        return "-infinity".into();
150    }
151    if style.date_style == DateStyleKind::Iso {
152        return format_timestamp(micros);
153    }
154    const MICROS_PER_DAY: i64 = 86_400_000_000;
155    let days = micros.div_euclid(MICROS_PER_DAY);
156    let day_micros = micros.rem_euclid(MICROS_PER_DAY);
157    let day_i32 = i32::try_from(days).unwrap_or(i32::MAX);
158    let hms = hms_from_day_micros(day_micros);
159    match style.date_style {
160        DateStyleKind::Iso => unreachable!("handled above"),
161        DateStyleKind::German | DateStyleKind::Sql => {
162            // format_date_styled carries the BC suffix on the date part;
163            // move it after the time to match PG.
164            let d = format_date_styled(day_i32, style);
165            match d.strip_suffix(" BC") {
166                Some(base) => format!("{base} {hms} BC"),
167                None => format!("{d} {hms}"),
168            }
169        }
170        DateStyleKind::Postgres => {
171            let (y, m, d) = civil_from_days(day_i32);
172            let (y, bc) = if y <= 0 { (1 - y, " BC") } else { (y, "") };
173            let mon = MONTH_ABBR[(m as usize).saturating_sub(1).min(11)];
174            let dow = dow_abbr(day_i32);
175            if style.date_order == DateOrder::Dmy {
176                format!("{dow} {d} {mon} {hms} {y:04}{bc}")
177            } else {
178                format!("{dow} {mon} {d} {hms} {y:04}{bc}")
179            }
180        }
181    }
182}
183
184/// `format_timestamptz` under a DateStyle for the UTC session: ISO
185/// keeps the `+00` offset suffix; the other styles append the zone
186/// NAME (` UTC`), as PG does.
187pub fn format_timestamptz_styled(micros: i64, style: &RenderStyle) -> String {
188    format_timestamptz_tz(micros, style, 0, None)
189}
190
191/// v7.39 (tz epic) — the session-timezone-aware renderer: shift by the
192/// per-value offset; ISO appends the numeric offset (`+09`, `+05:45`),
193/// the other DateStyles append the zone designation — a named zone's
194/// abbreviation (`JST`, `EDT`), a fixed offset's numeric form, or
195/// `UTC` (all PG18-differential).
196pub fn format_timestamptz_tz(
197    micros: i64,
198    style: &RenderStyle,
199    offset_micros: i64,
200    abbr: Option<&str>,
201) -> String {
202    if style.date_style == DateStyleKind::Iso {
203        return format_timestamptz_at(micros, offset_micros);
204    }
205    if micros == i64::MAX || micros == i64::MIN {
206        return format_timestamp(micros);
207    }
208    let body = format_timestamp_styled(micros + offset_micros, style);
209    match abbr {
210        Some(a) => format!("{body} {a}"),
211        None if offset_micros == 0 => format!("{body} UTC"),
212        None => {
213            let total_min = (offset_micros / 60_000_000).abs();
214            let (h, m) = (total_min / 60, total_min % 60);
215            let sign = if offset_micros < 0 { '-' } else { '+' };
216            if m == 0 {
217                format!("{body} {sign}{h:02}")
218            } else {
219                format!("{body} {sign}{h:02}:{m:02}")
220            }
221        }
222    }
223}
224
225/// `H:MM:SS[.frac]` — the sql_standard time body (hour unpadded),
226/// over non-negative micros.
227fn sql_std_time(abs_us: i64) -> String {
228    let secs = abs_us / 1_000_000;
229    let frac = abs_us % 1_000_000;
230    let h = secs / 3600;
231    let mm = (secs / 60) % 60;
232    let ss = secs % 60;
233    if frac == 0 {
234        format!("{h}:{mm:02}:{ss:02}")
235    } else {
236        let raw = format!("{frac:06}");
237        let trimmed = raw.trim_end_matches('0');
238        format!("{h}:{mm:02}:{ss:02}.{trimmed}")
239    }
240}
241
242/// `SS[.frac]` seconds body for iso_8601 / verbose fields.
243fn secs_body(abs_us: i64) -> String {
244    let ss = abs_us / 1_000_000;
245    let frac = abs_us % 1_000_000;
246    if frac == 0 {
247        format!("{ss}")
248    } else {
249        let raw = format!("{frac:06}");
250        let trimmed = raw.trim_end_matches('0');
251        format!("{ss}.{trimmed}")
252    }
253}
254
255/// `format_interval` under an IntervalStyle (PG18 differential truth):
256///
257/// - sql_standard — pure year-month `1-2` / `-1-2`; pure day-time
258///   `1 0:00:00` (sign on the leading field, time fields absolute;
259///   time-only `2:00:00` / `-0:00:01`); a mix of year-month and
260///   day-time classes (or mixed signs) is non-conforming and prints
261///   every part explicitly signed: `+1-2 +3 +4:05:06`, `+0-1 -1
262///   +0:00:00`; zero → `0`.
263/// - iso_8601 — `P[nY][nM][nD][T[nH][nM][nS]]`, each field
264///   individually signed, zero → `PT0S`.
265/// - postgres_verbose — `@ ` + `years/mons/days/hours/mins/secs`
266///   fields; when the interval compares below zero every field is
267///   negated and ` ago` is appended; zero → `@ 0`.
268/// Render an interval that may be infinite.
269///
270/// v7.38.19 — PostgreSQL 18.4 renders the two infinities as the words
271/// `infinity` and `-infinity`, in every interval style, and reads them
272/// back (`'infinity'::text::interval` round-trips). `'inf'` is NOT
273/// accepted, which is the one place interval differs from float here.
274#[must_use]
275pub fn format_interval_kinded(
276    months: i32,
277    days: i32,
278    micros: i64,
279    kind: spg_storage::IntervalKind,
280) -> String {
281    match kind {
282        spg_storage::IntervalKind::PosInf => alloc::string::String::from("infinity"),
283        spg_storage::IntervalKind::NegInf => alloc::string::String::from("-infinity"),
284        spg_storage::IntervalKind::Finite => format_interval(months, days, micros),
285    }
286}
287
288pub fn format_interval_styled(months: i32, days: i32, micros: i64, style: &RenderStyle) -> String {
289    match style.interval_style {
290        IntervalStyleKind::Postgres => format_interval(months, days, micros),
291        IntervalStyleKind::SqlStandard => {
292            let has_ym = months != 0;
293            let has_dt = days != 0 || micros != 0;
294            if !has_ym && !has_dt {
295                return "0".into();
296            }
297            let y = months / 12;
298            let mo = (months % 12).abs();
299            // Sign coherence: every nonzero class must agree for the
300            // conforming shapes; a year-month + day-time mix is always
301            // the signed non-conforming shape.
302            let signs: Vec<i8> = [i64::from(months), i64::from(days), micros]
303                .iter()
304                .filter(|v| **v != 0)
305                .map(|v| if *v < 0 { -1i8 } else { 1 })
306                .collect();
307            let coherent = signs.windows(2).all(|w| w[0] == w[1]);
308            if has_ym && !has_dt && coherent {
309                return format!("{y}-{mo}");
310            }
311            if !has_ym && coherent {
312                let neg = days < 0 || micros < 0;
313                let time = sql_std_time(micros.abs());
314                if days == 0 {
315                    return format!("{}{time}", if neg { "-" } else { "" });
316                }
317                return format!("{days} {time}");
318            }
319            // Non-conforming: every part explicitly signed, absolute
320            // field bodies.
321            let sgn = |neg: bool| if neg { '-' } else { '+' };
322            format!(
323                "{}{}-{} {}{} {}{}",
324                sgn(months < 0),
325                y.abs(),
326                mo,
327                sgn(days < 0),
328                days.abs(),
329                sgn(micros < 0),
330                sql_std_time(micros.abs())
331            )
332        }
333        IntervalStyleKind::Iso8601 => {
334            if months == 0 && days == 0 && micros == 0 {
335                return "PT0S".into();
336            }
337            let y = months / 12;
338            let mo = months % 12;
339            let mut out = String::from("P");
340            if y != 0 {
341                out.push_str(&format!("{y}Y"));
342            }
343            if mo != 0 {
344                out.push_str(&format!("{mo}M"));
345            }
346            if days != 0 {
347                out.push_str(&format!("{days}D"));
348            }
349            if micros != 0 {
350                out.push('T');
351                let neg = micros < 0;
352                let abs = micros.abs();
353                let h = abs / 3_600_000_000;
354                let m = (abs / 60_000_000) % 60;
355                let s_us = abs % 60_000_000;
356                let sgn = if neg { "-" } else { "" };
357                if h != 0 {
358                    out.push_str(&format!("{sgn}{h}H"));
359                }
360                if m != 0 {
361                    out.push_str(&format!("{sgn}{m}M"));
362                }
363                if s_us != 0 {
364                    out.push_str(&format!("{sgn}{}S", secs_body(s_us)));
365                }
366            }
367            out
368        }
369        IntervalStyleKind::PostgresVerbose => {
370            if months == 0 && days == 0 && micros == 0 {
371                return "@ 0".into();
372            }
373            // PG's comparison convention (months at 30 days) decides
374            // the overall sign; a negative interval prints its fields
375            // negated with a trailing ` ago`.
376            let total = i128::from(months) * 30 * 86_400_000_000
377                + i128::from(days) * 86_400_000_000
378                + i128::from(micros);
379            let ago = total < 0;
380            let (months, days, micros) = if ago {
381                (-months, -days, -micros)
382            } else {
383                (months, days, micros)
384            };
385            let y = months / 12;
386            let mo = months % 12;
387            let neg_t = micros < 0;
388            let abs = micros.abs();
389            let h = abs / 3_600_000_000;
390            let m = (abs / 60_000_000) % 60;
391            let s_us = abs % 60_000_000;
392            let mut parts: Vec<String> = Vec::new();
393            let unit = |n: i64, singular: &'static str| -> String {
394                if n == 1 {
395                    singular.into()
396                } else {
397                    format!("{singular}s")
398                }
399            };
400            if y != 0 {
401                parts.push(format!("{y} {}", unit(i64::from(y), "year")));
402            }
403            if mo != 0 {
404                parts.push(format!("{mo} {}", unit(i64::from(mo), "mon")));
405            }
406            if days != 0 {
407                parts.push(format!("{days} {}", unit(i64::from(days), "day")));
408            }
409            let tsgn = if neg_t { "-" } else { "" };
410            if h != 0 {
411                parts.push(format!("{tsgn}{h} {}", unit(h, "hour")));
412            }
413            if m != 0 {
414                parts.push(format!("{tsgn}{m} {}", unit(m, "min")));
415            }
416            if s_us != 0 {
417                let body = secs_body(s_us);
418                let plural = body != "1";
419                parts.push(format!(
420                    "{tsgn}{body} {}",
421                    if plural { "secs" } else { "sec" }
422                ));
423            }
424            let mut out = String::from("@ ");
425            out.push_str(&parts.join(" "));
426            if ago {
427                out.push_str(" ago");
428            }
429            out
430        }
431    }
432}
433
434/// Styled array renderers — `{elem,…}` with per-element styled text.
435pub fn format_date_array_styled(items: &[Option<i32>], style: &RenderStyle) -> String {
436    array_styled(items, |d| format_date_styled(*d, style))
437}
438
439pub fn format_timestamp_array_styled(
440    items: &[Option<i64>],
441    with_tz: bool,
442    style: &RenderStyle,
443) -> String {
444    if with_tz {
445        array_styled(items, |t| format_timestamptz_styled(*t, style))
446    } else {
447        array_styled(items, |t| format_timestamp_styled(*t, style))
448    }
449}
450
451pub fn format_interval_array_styled(
452    items: &[Option<spg_storage::IntervalSpan>],
453    style: &RenderStyle,
454) -> String {
455    array_styled(items, |iv| {
456        if iv.kind.is_finite() {
457            format_interval_styled(iv.months, iv.days, iv.micros, style)
458        } else {
459            format_interval_kinded(0, 0, 0, iv.kind)
460        }
461    })
462}
463
464pub fn format_float_array_styled(items: &[Option<f64>], style: &RenderStyle) -> String {
465    array_styled(items, |f| format_float_styled(*f, style))
466}
467
468fn array_styled<T>(items: &[Option<T>], mut f: impl FnMut(&T) -> String) -> String {
469    let mut out = String::with_capacity(2 + items.len() * 12);
470    out.push('{');
471    for (i, item) in items.iter().enumerate() {
472        if i > 0 {
473            out.push(',');
474        }
475        match item {
476            None => out.push_str("NULL"),
477            Some(v) => push_array_element(&mut out, &f(v)),
478        }
479    }
480    out.push('}');
481    out
482}
483
484/// v7.39 (read01 round 73) — PG's array output QUOTES an element whose text
485/// contains a delimiter, a brace, a quote, a backslash or whitespace — so an
486/// interval array reads `{"1 day",02:00:00}`, not `{1 day,02:00:00}`. This lived
487/// only in the text-array renderer; every typed array shared `array_styled`,
488/// which never quoted, because none of the types it rendered had ever produced a
489/// space. `array_agg(interval)` does — and the differential caught it the moment
490/// round 73 gave that aggregate its real element type.
491fn push_array_element(out: &mut String, s: &str) {
492    let needs_quote = s.is_empty()
493        || s.eq_ignore_ascii_case("null")
494        || s.chars()
495            .any(|c| matches!(c, ',' | '{' | '}' | '"' | '\\') || c.is_whitespace());
496    if !needs_quote {
497        out.push_str(s);
498        return;
499    }
500    out.push('"');
501    for c in s.chars() {
502        if c == '"' || c == '\\' {
503            out.push('\\');
504        }
505        out.push(c);
506    }
507    out.push('"');
508}
509
510/// C `%.{prec}g` over an f64 — what PG's float8out/float4out emit when
511/// `extra_float_digits <= 0`: `prec` significant digits, fixed-point
512/// when the decimal exponent is in `-4..prec`, else scientific;
513/// trailing zeros trimmed in both shapes; exponent `e±NN`.
514fn format_g(x: f64, prec: usize) -> String {
515    let prec = prec.max(1);
516    // Round to `prec` significant digits via {:.*e} (exact decimal
517    // mantissa; handles the 9.99→10.0 exponent carry).
518    let sci = format!("{:.*e}", prec - 1, x);
519    let epos = sci.find('e').expect("{:e} always has an 'e'");
520    let exp_val: i32 = sci[epos + 1..].parse().unwrap_or(0);
521    let mant = &sci[..epos];
522    if exp_val >= -4 && (exp_val as i64) < prec as i64 {
523        // Fixed-point with prec-1-exp decimals, from the rounded value.
524        let decimals =
525            usize::try_from(i64::try_from(prec).unwrap_or(1) - 1 - i64::from(exp_val)).unwrap_or(0);
526        let rounded: f64 = sci.parse().unwrap_or(x);
527        let fixed = format!("{rounded:.decimals$}");
528        if fixed.contains('.') {
529            let t = fixed.trim_end_matches('0').trim_end_matches('.');
530            t.into()
531        } else {
532            fixed
533        }
534    } else {
535        let mant = if mant.contains('.') {
536            mant.trim_end_matches('0').trim_end_matches('.')
537        } else {
538            mant
539        };
540        let (sign, digits) = if exp_val < 0 {
541            ('-', format!("{}", -exp_val))
542        } else {
543            ('+', format!("{exp_val}"))
544        };
545        format!("{mant}e{sign}{digits:0>2}")
546    }
547}
548
549/// PG `float8out` under `extra_float_digits`: >= 1 → shortest
550/// round-trip (`format_float`); <= 0 → `%.{15+n}g`.
551pub fn format_float_styled(x: f64, style: &RenderStyle) -> String {
552    if style.extra_float_digits >= 1 {
553        return format_float(x);
554    }
555    if x.is_nan() {
556        return "NaN".into();
557    }
558    if x.is_infinite() {
559        return if x > 0.0 { "Infinity" } else { "-Infinity" }.into();
560    }
561    if x == 0.0 {
562        return if x.is_sign_negative() { "-0" } else { "0" }.into();
563    }
564    let prec = (15 + style.extra_float_digits).clamp(1, 17) as usize;
565    format_g(x, prec)
566}
567
568/// PG `float4out` under `extra_float_digits`: >= 1 → shortest
569/// round-trip (`format_real`); <= 0 → `%.{6+n}g`.
570pub fn format_real_styled(x: f32, style: &RenderStyle) -> String {
571    if style.extra_float_digits >= 1 {
572        return format_real(x);
573    }
574    if x.is_nan() {
575        return "NaN".into();
576    }
577    if x.is_infinite() {
578        return if x > 0.0 { "Infinity" } else { "-Infinity" }.into();
579    }
580    if x == 0.0 {
581        return if x.is_sign_negative() { "-0" } else { "0" }.into();
582    }
583    let prec = (6 + style.extra_float_digits).clamp(1, 9) as usize;
584    format_g(f64::from(x), prec)
585}
586
587/// Render a `Date` (days since epoch) as `YYYY-MM-DD`. Negative values
588/// for pre-1970 dates render with a leading `-` on the year.
589pub fn format_date(days: i32) -> String {
590    if days == i32::MAX {
591        return "infinity".into();
592    }
593    if days == i32::MIN {
594        return "-infinity".into();
595    }
596    let (y, m, d) = civil_from_days(days);
597    // v7.39 (GUC knife 6, BC) — PG renders astronomical year <= 0 as
598    // the positive year + " BC" (1 BC is astronomical year 0).
599    if y <= 0 {
600        return format!("{:04}-{m:02}-{d:02} BC", 1 - y);
601    }
602    format!("{y:04}-{m:02}-{d:02}")
603}
604
605/// Render a `Timestamp` (microseconds since epoch) as
606/// `YYYY-MM-DD HH:MM:SS[.fff...]`. Trailing-zero fractional digits are
607/// dropped; a whole-second value has no fractional part.
608/// v7.15.0 — PG-canonical TIMESTAMPTZ wire format. Storage is
609/// the same i64 microseconds UTC as TIMESTAMP, but the canonical
610/// PG text output appends the session's UTC-offset suffix (`+00`
611/// for the default UTC session, the form pg_dump emits). Mailrs
612/// round-8 acceptance criterion: `SELECT col FROM tstz` should
613/// round-trip to a literal that re-INSERTs without semantic
614/// drift.
615pub fn format_timestamptz(micros: i64) -> String {
616    format_timestamptz_at(micros, 0)
617}
618
619/// v7.38 (T-tstz Phase 2) — render a UTC instant in a fixed-offset zone: shift
620/// the wall clock by `offset_micros`, then append PG's offset suffix (`+09`,
621/// `-05`, `+05:30`, `+00`). Minutes are shown only when non-zero, matching PG.
622/// UTC (`offset_micros == 0`) reproduces the old `+00` output byte-for-byte.
623pub fn format_timestamptz_at(micros: i64, offset_micros: i64) -> String {
624    if micros == i64::MAX || micros == i64::MIN {
625        return format_timestamp(micros);
626    }
627    let base = format_timestamp(micros + offset_micros);
628    // v7.39 (GUC knife 6, BC) — the offset suffix goes before " BC"
629    // (PG: `0044-03-15 10:20:30+00 BC`).
630    let (base, bc) = match base.strip_suffix(" BC") {
631        Some(b) => (String::from(b), " BC"),
632        None => (base, ""),
633    };
634    let mut s = String::with_capacity(base.len() + 9);
635    s.push_str(&base);
636    let total_min = (offset_micros / 60_000_000).abs();
637    let (h, m) = (total_min / 60, total_min % 60);
638    s.push(if offset_micros < 0 { '-' } else { '+' });
639    s.push_str(&alloc::format!("{h:02}"));
640    if m != 0 {
641        s.push(':');
642        s.push_str(&alloc::format!("{m:02}"));
643    }
644    s.push_str(bc);
645    s
646}
647
648/// v7.17.0 Phase 3.P0-35 — PG `money` canonical text form, en_US
649/// PG `float8out` — the shortest round-trip decimal, rendered in
650/// scientific notation when the base-10 exponent is `< -4` or `> 14`
651/// (matching float.c's choice), otherwise fixed. Learned from read01
652/// float.c study: PG switches to `1e+15` / `1e-05` where SPG used to
653/// spell every digit (`1000000000000000000000000000000`). The exponent
654/// is read from Rust's `{:e}` (exact — avoids log10 rounding at powers
655/// of ten) and reformatted to PG's `e±NN` (sign always shown, ≥ 2
656/// digits). Infinities / NaN / signed zero match `float8out` too.
657pub fn format_float(x: f64) -> String {
658    if x.is_nan() {
659        return "NaN".into();
660    }
661    if x.is_infinite() {
662        return if x > 0.0 { "Infinity" } else { "-Infinity" }.into();
663    }
664    if x == 0.0 {
665        return if x.is_sign_negative() { "-0" } else { "0" }.into();
666    }
667    let sci = shortest_float_sci(x); // e.g. "1.234e15", "1e-5", "-2.5e-10"
668    let epos = sci.find('e').expect("{:e} always has an 'e'");
669    let exp_val: i32 = sci[epos + 1..].parse().unwrap_or(0);
670    if (-4..=14).contains(&exp_val) {
671        // Fixed-point rendering of the SAME digits the strict test
672        // chose — `{x}` would re-derive them under Rust's rule.
673        return fixed_from_sci(&sci, exp_val);
674    }
675    let mant = &sci[..epos];
676    let exp = &sci[epos + 1..];
677    let (sign, digits) = match exp.strip_prefix('-') {
678        Some(d) => ('-', d),
679        None => ('+', exp),
680    };
681    alloc::format!("{mant}e{sign}{digits:0>2}")
682}
683
684/// v7.39 (round 270) — the shortest decimal for an f32 in PG's sense,
685/// as `{:e}` style ("1.5000001e10").
686///
687/// Rust's `{:e}` gives the shortest decimal that ROUND-TRIPS. PG wants
688/// the shortest that lies STRICTLY INSIDE the value's rounding
689/// interval. The two differ exactly on the values whose short form sits
690/// on a half-ulp boundary: ties-to-even parses that boundary back to
691/// the same float, so Rust accepts it, while PG does not. Measured on
692/// PG 18.4: `15000000512::real` prints 1.5000001e+10, not 1.5e+10 —
693/// 1.5e10 is exactly half an ulp below the value. The same rule shows
694/// up in float8 (`1e23` prints 9.999999999999999e+22).
695///
696/// The boundary test is exact here because an f32 and its neighbour
697/// both widen losslessly into f64 and their midpoint needs only 25
698/// bits, so the midpoint is an f64 value that a <= 9-digit decimal
699/// parses to exactly when — and only when — it IS that midpoint.
700fn shortest_real_sci(x: f32) -> String {
701    let wide = f64::from(x);
702    let below = f64::from(next_f32(x, false));
703    let above = f64::from(next_f32(x, true));
704    // Midpoints to either neighbour; these are exact in f64.
705    let lo = (wide + below) / 2.0;
706    let hi = (wide + above) / 2.0;
707    for p in 1..=9u32 {
708        let cand = alloc::format!("{x:.*e}", (p - 1) as usize);
709        let Ok(v) = cand.parse::<f64>() else { continue };
710        // Round-trips as an f32 AND is not sitting on either boundary.
711        #[allow(clippy::cast_possible_truncation)]
712        if v as f32 == x && v != lo && v != hi {
713            return cand;
714        }
715    }
716    alloc::format!("{x:e}")
717}
718
719/// The adjacent f32 toward +inf (`up`) or -inf. Only ever called on a
720/// finite non-zero value.
721fn next_f32(x: f32, up: bool) -> f32 {
722    let bits = x.to_bits();
723    let stepped = if (x > 0.0) == up { bits + 1 } else { bits - 1 };
724    f32::from_bits(stepped)
725}
726
727/// Re-render a `{:e}`-style string in fixed-point notation.
728fn fixed_from_sci(sci: &str, exp: i32) -> String {
729    let epos = sci.find('e').expect("{:e} always has an 'e'");
730    let (mant, _) = sci.split_at(epos);
731    let (sign, mant) = match mant.strip_prefix('-') {
732        Some(m) => ("-", m),
733        None => ("", mant),
734    };
735    let digits: String = mant.chars().filter(char::is_ascii_digit).collect();
736    let point = exp + 1; // digits before the decimal point
737    let mut out = String::from(sign);
738    if point <= 0 {
739        out.push_str("0.");
740        for _ in 0..-point {
741            out.push('0');
742        }
743        out.push_str(&digits);
744    } else if (point as usize) >= digits.len() {
745        out.push_str(&digits);
746        for _ in 0..(point as usize - digits.len()) {
747            out.push('0');
748        }
749    } else {
750        out.push_str(&digits[..point as usize]);
751        out.push('.');
752        out.push_str(&digits[point as usize..]);
753    }
754    out
755}
756
757/// v7.38 (read01, T-float4) — PG `float4out`: the f32 shortest round-trip, in
758/// fixed-point for decimal exponents in `-4..=5` and scientific otherwise
759/// (a tighter window than float8's `-4..=14`, so `12345678::real` =
760/// `1.2345678e+07` while `12345678::float8` stays `12345678`).
761pub fn format_real(x: f32) -> String {
762    if x.is_nan() {
763        return "NaN".into();
764    }
765    if x.is_infinite() {
766        return if x > 0.0 { "Infinity" } else { "-Infinity" }.into();
767    }
768    if x == 0.0 {
769        return if x.is_sign_negative() { "-0" } else { "0" }.into();
770    }
771    let sci = shortest_real_sci(x);
772    let epos = sci.find('e').expect("{:e} always has an 'e'");
773    let exp_val: i32 = sci[epos + 1..].parse().unwrap_or(0);
774    if (-4..=5).contains(&exp_val) {
775        // Re-expand the (possibly longer than Rust's) mantissa in
776        // fixed-point rather than falling back to `{x}`, which would
777        // reintroduce Rust's choice of digits.
778        return fixed_from_sci(&sci, exp_val);
779    }
780    let mant = &sci[..epos];
781    let exp = &sci[epos + 1..];
782    let (sign, digits) = match exp.strip_prefix('-') {
783        Some(d) => ('-', d),
784        None => ('+', exp),
785    };
786    alloc::format!("{mant}e{sign}{digits:0>2}")
787}
788
789/// locale: `$N,NNN.CC`, negative → `-$1.23`. Mirrors PG's
790/// `cash_out` for `lc_monetary = 'en_US.UTF-8'`.
791pub fn format_money(cents: i64) -> String {
792    let neg = cents < 0;
793    let abs = cents.unsigned_abs();
794    let dollars = abs / 100;
795    let cc = abs % 100;
796    // Insert comma thousands separators in the integer portion.
797    let dollar_str = dollars.to_string();
798    let bytes = dollar_str.as_bytes();
799    let mut int_part = String::with_capacity(dollar_str.len() + dollar_str.len() / 3);
800    for (i, b) in bytes.iter().enumerate() {
801        // Position from the right: insert ',' before every 3rd
802        // digit (except the first).
803        let from_right = bytes.len() - i;
804        if i > 0 && from_right % 3 == 0 {
805            int_part.push(',');
806        }
807        int_part.push(*b as char);
808    }
809    let sign = if neg { "-" } else { "" };
810    format!("{sign}${int_part}.{cc:02}")
811}
812
813/// v7.17.0 Phase 3.P0-34 — PG `TIMETZ` canonical text form
814/// `HH:MM:SS[.ffffff]±HH[:MM]`. Mirrors PG `timetz_out`. The
815/// offset uses `±HH` for whole-hour offsets and `±HH:MM` for
816/// sub-hour offsets (matching PG's "minimal display" rule).
817pub fn format_timetz(us: i64, offset_secs: i32) -> String {
818    let time = format_time(us);
819    let sign = if offset_secs < 0 { '-' } else { '+' };
820    let abs = offset_secs.unsigned_abs();
821    let oh = abs / 3600;
822    let om = (abs % 3600) / 60;
823    if om == 0 {
824        format!("{time}{sign}{oh:02}")
825    } else {
826        format!("{time}{sign}{oh:02}:{om:02}")
827    }
828}
829
830/// v7.17.0 Phase 3.P0-32 — PG `TIME` canonical text form
831/// `HH:MM:SS[.ffffff]`. Mirrors PG `time_out`. Trailing zeros in
832/// the fractional component are stripped — `12:00:00.500000`
833/// renders as `12:00:00.5` to match PG's text output.
834pub fn format_time(us: i64) -> String {
835    let total_secs = us.div_euclid(1_000_000);
836    let frac = us.rem_euclid(1_000_000);
837    let hh = total_secs / 3600;
838    let mm = (total_secs / 60) % 60;
839    let ss = total_secs % 60;
840    if frac == 0 {
841        format!("{hh:02}:{mm:02}:{ss:02}")
842    } else {
843        let raw = format!("{frac:06}");
844        let trimmed = raw.trim_end_matches('0');
845        format!("{hh:02}:{mm:02}:{ss:02}.{trimmed}")
846    }
847}
848
849pub fn format_timestamp(micros: i64) -> String {
850    // PG infinity sentinels.
851    if micros == i64::MAX {
852        return "infinity".into();
853    }
854    if micros == i64::MIN {
855        return "-infinity".into();
856    }
857    const MICROS_PER_DAY: i64 = 86_400_000_000;
858    // Split into day + intra-day part with proper floor division so
859    // negative timestamps render right too.
860    let days = micros.div_euclid(MICROS_PER_DAY);
861    let day_micros = micros.rem_euclid(MICROS_PER_DAY);
862    let day_i32 = i32::try_from(days).unwrap_or(i32::MAX);
863    let (y, m, d) = civil_from_days(day_i32);
864    // v7.39 (GUC knife 6, BC) — " BC" trails the TIME part in PG.
865    let (y, bc) = if y <= 0 { (1 - y, " BC") } else { (y, "") };
866    let secs = day_micros / 1_000_000;
867    let frac = day_micros % 1_000_000;
868    let hh = secs / 3600;
869    let mm = (secs / 60) % 60;
870    let ss = secs % 60;
871    if frac == 0 {
872        format!("{y:04}-{m:02}-{d:02} {hh:02}:{mm:02}:{ss:02}{bc}")
873    } else {
874        // Strip trailing zeros from the 6-digit fractional component.
875        let raw = format!("{frac:06}");
876        let trimmed = raw.trim_end_matches('0');
877        format!("{y:04}-{m:02}-{d:02} {hh:02}:{mm:02}:{ss:02}.{trimmed}{bc}")
878    }
879}
880
881/// Inverse of `civil_from_days` — converts (year, month, day) to days
882/// since 1970-01-01. Out-of-range months / days saturate.
883#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
884pub fn days_from_civil(y: i32, m: u32, d: u32) -> i32 {
885    let y_adj = if m <= 2 {
886        i64::from(y) - 1
887    } else {
888        i64::from(y)
889    };
890    let era = y_adj.div_euclid(400);
891    let yoe = (y_adj - era * 400) as u32;
892    let doy = (153 * (if m > 2 { m - 3 } else { m + 9 }) + 2) / 5 + d.saturating_sub(1);
893    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
894    let total = era * 146_097 + i64::from(doe) - 719_468;
895    i32::try_from(total).unwrap_or(i32::MAX)
896}
897
898/// Parse `YYYY-MM-DD` into a `Date` (days since Unix epoch). Returns
899/// `None` on shape / numeric failure; the engine surfaces that as a
900/// `TypeMismatch` with the original text included.
901pub fn parse_date_literal(s: &str) -> Option<i32> {
902    parse_date_literal_ordered(s, DateOrder::Mdy)
903}
904
905/// v7.39 (GUC knife 5) — DateOrder-aware date input. PG disambiguates
906/// a three-field numeric date (`01/02/2024`, `02.01.2024`, `1/2/24`)
907/// by the DateStyle field order: MDY reads month first (the default —
908/// so `'01/02/2024'` is Jan 2 even with no SET), DMY day first, YMD
909/// year first (`'24/01/02'`, and `'1/2/24'` is 2001-02-24!). A
910/// two-digit year is < 70 → 20xx, >= 70 → 19xx. Field values that
911/// don't fit the order error (MDY `'13/02/2024'` is out of range —
912/// PG does NOT auto-swap). ISO year-first four-digit forms parse the
913/// same under every order.
914pub fn parse_date_literal_ordered(s: &str, order: DateOrder) -> Option<i32> {
915    let s = s.trim();
916    // v7.39 (GUC knife 6, BC) — a trailing era marker: `NNNN-MM-DD BC`
917    // maps year N to astronomical year 1-N (there is no year zero);
918    // an explicit AD is accepted and is the default.
919    if let Some(base) = s
920        .strip_suffix(" BC")
921        .or_else(|| s.strip_suffix(" bc"))
922        .or_else(|| s.strip_suffix(" Bc"))
923    {
924        let days = parse_date_literal_ordered(base, order)?;
925        let (y, m, d) = civil_from_days(days);
926        if y < 1 {
927            return None;
928        }
929        return Some(days_from_civil(1 - y, m, d));
930    }
931    if let Some(base) = s.strip_suffix(" AD").or_else(|| s.strip_suffix(" ad")) {
932        return parse_date_literal_ordered(base, order);
933    }
934    // PG special date values.
935    if s.eq_ignore_ascii_case("epoch") {
936        return Some(days_from_civil(1970, 1, 1));
937    }
938    if s.eq_ignore_ascii_case("infinity") || s.eq_ignore_ascii_case("+infinity") {
939        return Some(i32::MAX);
940    }
941    if s.eq_ignore_ascii_case("-infinity") {
942        return Some(i32::MIN);
943    }
944    let bytes = s.as_bytes();
945    // ISO 8601 basic (compact) form `YYYYMMDD` — no separators.
946    if bytes.len() == 8 && bytes.iter().all(u8::is_ascii_digit) {
947        let y: i32 = s[0..4].parse().ok()?;
948        let m: u32 = s[4..6].parse().ok()?;
949        let d: u32 = s[6..8].parse().ok()?;
950        if !(1..=12).contains(&m) || d < 1 || d > super::days_in_month(y, m) {
951            return None;
952        }
953        return Some(days_from_civil(y, m, d));
954    }
955    // v7.38 (read01) — month-name forms in any of PG's field orders
956    // (`Jan 5, 2020`, `5 Jan 2020`, `2020-Jan-05`, `5-Jan-2020`), case
957    // insensitive. Try this before the numeric split so a `Mon-D-Y` dashed
958    // form isn't mistaken for a numeric field.
959    if s.bytes().any(|b| b.is_ascii_alphabetic()) {
960        // v7.39 (read01 utils/adt, datetime.c) — 'J2451545' is a Julian
961        // day number (JD of the Unix epoch is 2440588).
962        if let Some(jd) = s.strip_prefix(['J', 'j'])
963            && !jd.is_empty()
964            && jd.bytes().all(|b| b.is_ascii_digit())
965        {
966            let jd: i64 = jd.parse().ok()?;
967            return i32::try_from(jd - 2_440_588).ok();
968        }
969        return parse_month_name_date(s, order);
970    }
971    // v7.38 (read01) — year-first numeric form with `-`, `/` or `.` separators
972    // and non-zero-padded month/day (`2020-1-5`, `2020/01/5`, `2020.1.05`), all
973    // of which PG accepts. Requires exactly three all-digit fields, the first
974    // being the 4-digit year, so it stays unambiguous (no MDY/DMY guessing).
975    // v7.39 (read01 utils/adt, datetime.c) — the day-of-year form:
976    // YEAR + exactly-three-digit ordinal ('2024-060' = Feb 29 2024).
977    {
978        let mut two = s.splitn(2, ['-', '/', '.']);
979        if let (Some(ya), Some(dd)) = (two.next(), two.next())
980            && ya.len() >= 3
981            && dd.len() == 3
982            && !dd.contains(['-', '/', '.', ' '])
983            && ya.bytes().all(|b| b.is_ascii_digit())
984            && dd.bytes().all(|b| b.is_ascii_digit())
985        {
986            let y: i32 = ya.parse().ok()?;
987            let doy: i64 = dd.parse().ok()?;
988            if y != 0 && (1..=366).contains(&doy) {
989                let jan1 = days_from_civil(y, 1, 1);
990                let days = jan1 + i32::try_from(doy).ok()? - 1;
991                let (yy, _, _) = civil_from_days(days);
992                if yy == y {
993                    return Some(days);
994                }
995                return None; // 366 in a non-leap year
996            }
997        }
998    }
999    let mut parts = s.splitn(3, ['-', '/', '.']);
1000    let (fa, fb, fc) = (parts.next()?, parts.next()?, parts.next()?);
1001    if fc.contains(['-', '/', '.', ' ']) {
1002        return None; // trailing separator / extra field / garbage
1003    }
1004    if [fa, fb, fc]
1005        .iter()
1006        .any(|p| p.is_empty() || !p.bytes().all(|b| b.is_ascii_digit()))
1007    {
1008        return None;
1009    }
1010    // Year-first: a 3-or-more-digit first field is unambiguously the
1011    // year regardless of DateOrder (PG DecodeNumber's flen >= 3 rule:
1012    // `2020-1-5`, `123-4-5` = 0123-04-05).
1013    if fa.len() >= 3 && fb.len() <= 2 && fc.len() <= 2 {
1014        let y: i32 = fa.parse().ok()?;
1015        // No year zero in the Gregorian era notation (PG: out of range).
1016        if y == 0 {
1017            return None;
1018        }
1019        // DOY form: exactly-three-digit second field after a year with
1020        // no third field is handled below (two-field split); with three
1021        // fields this is plain Y-M-D.
1022        let m: u32 = fb.parse().ok()?;
1023        let d: u32 = fc.parse().ok()?;
1024        // PG validates the day against the actual (leap-aware) month
1025        // length: `'2024-02-30'` raises "date/time field value out of
1026        // range" rather than rolling forward into March.
1027        if !(1..=12).contains(&m) || d < 1 || d > super::days_in_month(y, m) {
1028            return None;
1029        }
1030        return Some(days_from_civil(y, m, d));
1031    }
1032    // Order-disambiguated short forms.
1033    let expand_year = |t: &str| -> Option<i32> {
1034        match t.len() {
1035            4 => t.parse().ok(),
1036            // PG's two-digit-year window.
1037            1 | 2 => {
1038                let n: i32 = t.parse().ok()?;
1039                Some(if n < 70 { 2000 + n } else { 1900 + n })
1040            }
1041            _ => None,
1042        }
1043    };
1044    let (ys, ms, ds) = match order {
1045        DateOrder::Mdy => (fc, fa, fb),
1046        DateOrder::Dmy => (fc, fb, fa),
1047        DateOrder::Ymd => (fa, fb, fc),
1048    };
1049    if ms.len() > 2 || ds.len() > 2 {
1050        return None;
1051    }
1052    let y = expand_year(ys)?;
1053    let m: u32 = ms.parse().ok()?;
1054    let d: u32 = ds.parse().ok()?;
1055    if !(1..=12).contains(&m) || d < 1 || d > super::days_in_month(y, m) {
1056        return None;
1057    }
1058    Some(days_from_civil(y, m, d))
1059}
1060
1061/// v7.38 (read01) — resolve a month-name date in any of PG's field orders.
1062/// Tokenises on space / comma / dash, then classifies exactly one month name,
1063/// one 4-digit year, and one 1–2 digit day, in any order. Case insensitive;
1064/// both `Jan` and `January` spellings. Leap-aware day validation, like the
1065/// numeric path. Returns `None` for anything ambiguous or malformed so the
1066/// caller raises the same "invalid input" / "out of range" errors as PG.
1067fn parse_month_name_date(s: &str, order: DateOrder) -> Option<i32> {
1068    let tokens: alloc::vec::Vec<&str> =
1069        s.split([' ', ',', '-']).filter(|t| !t.is_empty()).collect();
1070    if tokens.len() != 3 {
1071        return None;
1072    }
1073    let month_of = |t: &str| -> Option<u32> {
1074        let up = t.to_ascii_uppercase();
1075        MONTH_ABBR
1076            .iter()
1077            .position(|a| a.eq_ignore_ascii_case(&up))
1078            .or_else(|| MONTH_FULL.iter().position(|f| f.eq_ignore_ascii_case(&up)))
1079            .map(|i| i as u32 + 1)
1080    };
1081    let mut month: Option<u32> = None;
1082    let mut nums: alloc::vec::Vec<&str> = alloc::vec::Vec::new();
1083    for t in tokens {
1084        if let Some(m) = month_of(t) {
1085            if month.replace(m).is_some() {
1086                return None; // two month names
1087            }
1088        } else if t.bytes().all(|b| b.is_ascii_digit()) {
1089            nums.push(t);
1090        } else {
1091            return None; // a non-month alphabetic token (`Foo`)
1092        }
1093    }
1094    let m = month?;
1095    if nums.len() != 2 {
1096        return None;
1097    }
1098    // v7.39 (read01 utils/adt, datetime.c DecodeNumber) — with a text
1099    // month, a 3+-digit numeric field is the YEAR; two short fields
1100    // disambiguate by DateOrder ('Jan-23-24' is day 23 / year 2024
1101    // under MDY/DMY, year 2023 / day 24 under YMD). Two-digit years
1102    // take PG's 1970-2069 window.
1103    let (ys, ds) = match (nums[0].len() >= 3, nums[1].len() >= 3) {
1104        (true, true) => return None,
1105        (true, false) => (nums[0], nums[1]),
1106        (false, true) => (nums[1], nums[0]),
1107        (false, false) => {
1108            if order == DateOrder::Ymd {
1109                (nums[0], nums[1])
1110            } else {
1111                (nums[1], nums[0])
1112            }
1113        }
1114    };
1115    let mut y: i32 = ys.parse().ok()?;
1116    if ys.len() <= 2 {
1117        y += if y < 70 { 2000 } else { 1900 };
1118    }
1119    let d: u32 = ds.parse().ok()?;
1120    if !(1..=12).contains(&m) || d < 1 || d > super::days_in_month(y, m) {
1121        return None;
1122    }
1123    Some(days_from_civil(y, m, d))
1124}
1125
1126/// Parse `YYYY-MM-DD[ HH:MM:SS[.ffffff]]` into a `Timestamp`
1127/// (microseconds since Unix epoch). The time portion is optional;
1128/// missing → midnight. The fractional portion accepts 1–6 digits and
1129/// pads with zeros to microseconds.
1130pub fn parse_timestamp_literal(s: &str) -> Option<i64> {
1131    parse_timestamp_literal_ordered(s, DateOrder::Mdy)
1132}
1133
1134/// v7.39 (GUC knife 5) — true when `s` tokenises as a numeric date shape
1135/// (three digit fields, or the 8-digit compact form) whose FIELDS parse but
1136/// whose values fail the calendar range checks — PG reports these as
1137/// `date/time field value out of range` (with a DateStyle hint), while
1138/// non-date-shaped text gets `invalid input syntax for type date`.
1139pub fn date_text_is_field_shaped(s: &str) -> bool {
1140    let s = s.trim();
1141    let date_part = match s.find([' ', 'T']) {
1142        Some(i) => &s[..i],
1143        None => s,
1144    };
1145    let b = date_part.as_bytes();
1146    if b.len() == 8 && b.iter().all(u8::is_ascii_digit) {
1147        return true;
1148    }
1149    let fields: alloc::vec::Vec<&str> = date_part.split(['-', '/', '.']).collect();
1150    fields.len() == 3
1151        && fields
1152            .iter()
1153            .all(|f| !f.is_empty() && f.len() <= 4 && f.bytes().all(|c| c.is_ascii_digit()))
1154}
1155
1156/// v7.39 (GUC knife 5) — DateOrder-aware timestamp input; the date
1157/// part follows `parse_date_literal_ordered`'s disambiguation.
1158pub fn parse_timestamp_literal_ordered(s: &str, order: DateOrder) -> Option<i64> {
1159    parse_timestamp_literal_tz_ordered(s, order).map(|(us, _)| us)
1160}
1161
1162/// v7.39 (tz epic) — like `parse_timestamp_literal_ordered` but also
1163/// reports whether the literal carried an explicit offset. A naive
1164/// literal's micros are the WALL clock (caller localises against the
1165/// session zone for a timestamptz); an offset-bearing literal's are
1166/// UTC already.
1167pub fn parse_timestamp_literal_tz_ordered(s: &str, order: DateOrder) -> Option<(i64, bool)> {
1168    if let Some(v) = timestamp_sentinel(s) {
1169        return Some((v, true));
1170    }
1171    let (days, day_micros, tz) = parse_timestamp_parts(s, order)?;
1172    let t = i64::from(days)
1173        .checked_mul(86_400_000_000)?
1174        .checked_add(day_micros)?
1175        .checked_sub(tz.unwrap_or(0))?;
1176    Some((t, tz.is_some()))
1177}
1178
1179/// v7.39 (round 289) — the pieces every timestamp-literal reader needs:
1180/// the day number, the LOCAL clock inside that day, and the zone offset
1181/// the literal carried (if any). Split out so the wall-clock reader and
1182/// the UTC reader cannot drift apart — the first attempt duplicated the
1183/// body and promptly lost the `BC` era handling.
1184fn parse_timestamp_parts(s: &str, order: DateOrder) -> Option<(i32, i64, Option<i64>)> {
1185    let trimmed = s.trim();
1186    // PG special timestamp values. `infinity` / `-infinity` use the i64
1187    // sentinels (they compare greater/less than every finite timestamp).
1188    if trimmed.eq_ignore_ascii_case("epoch") {
1189        return Some((0, 0, Some(0)));
1190    }
1191    // The infinity sentinels are whole i64 instants, not a day+offset
1192    // pair, so they cannot ride the parts shape — the two public
1193    // readers below special-case them before calling here.
1194    if trimmed.eq_ignore_ascii_case("infinity")
1195        || trimmed.eq_ignore_ascii_case("+infinity")
1196        || trimmed.eq_ignore_ascii_case("-infinity")
1197    {
1198        return None;
1199    }
1200    // v7.39 (GUC knife 6, BC) — the era marker trails the TIME part
1201    // (`0044-03-15 10:20:30 BC`); strip it and re-map the parsed date.
1202    let (trimmed, era_bc) = match trimmed
1203        .strip_suffix(" BC")
1204        .or_else(|| trimmed.strip_suffix(" bc"))
1205    {
1206        Some(b) => (b.trim_end(), true),
1207        None => (
1208            trimmed
1209                .strip_suffix(" AD")
1210                .or_else(|| trimmed.strip_suffix(" ad"))
1211                .map_or(trimmed, str::trim_end),
1212            false,
1213        ),
1214    };
1215    let (date_part, time_part) = match trimmed.find([' ', 'T']) {
1216        Some(i) => (&trimmed[..i], Some(&trimmed[i + 1..])),
1217        None => (trimmed, None),
1218    };
1219    // v7.39 (round 662) — a date may carry the zone directly, with no time
1220    // between them: PG reads `'2020-01-01+00'::timestamptz` as midnight in
1221    // that zone. SPG had no split point there — the scan above looks for a
1222    // space or a `T` — so the whole string went to the date parser and came
1223    // back `invalid input syntax`. The zone cannot simply be scanned for,
1224    // because an ISO date is full of hyphens; the split is accepted only
1225    // when the prefix parses as a date AND the suffix as a zone.
1226    if time_part.is_none() && parse_date_literal_ordered(date_part, order).is_none() {
1227        if let Some(rest) = date_part.strip_suffix(['Z', 'z']) {
1228            if let Some(d) = parse_date_literal_ordered(rest, order) {
1229                return Some((d, 0, Some(0)));
1230            }
1231        }
1232        // Only `+`. PG REFUSES `'2020-01-01-05'` — measured — because a
1233        // trailing `-05` cannot be told apart from the date's own hyphens,
1234        // and it would rather reject than guess. The first version here
1235        // accepted it and answered `2020-01-01 05:00:00+00`, i.e. invented
1236        // an instant PG declines to name.
1237        for (i, c) in date_part.char_indices().rev() {
1238            if c != '+' {
1239                continue;
1240            }
1241            let (head, tail) = date_part.split_at(i);
1242            let (Some(d), Some(off)) = (
1243                parse_date_literal_ordered(head, order),
1244                parse_tz_offset_suffix(tail, c == '+'),
1245            ) else {
1246                continue;
1247            };
1248            return Some((d, 0, Some(off)));
1249        }
1250    }
1251    let mut days = parse_date_literal_ordered(date_part, order)?;
1252    if era_bc {
1253        let (y, m, d) = civil_from_days(days);
1254        if y < 1 {
1255            return None;
1256        }
1257        days = days_from_civil(1 - y, m, d);
1258    }
1259    let (day_micros, tz_offset) = match time_part {
1260        None => (0, None),
1261        Some(t) => parse_time_of_day_micros_tz(t)?,
1262    };
1263    Some((days, day_micros, tz_offset))
1264}
1265
1266/// v7.39 (round 289) — the WALL-CLOCK value a literal spells, with any
1267/// zone designation ignored.
1268///
1269/// PG drops the zone when the target type has none: `'2020-01-01
1270/// 10:00:00+02'::timestamp` is `10:00:00`, not the `08:00:00` you get by
1271/// converting to UTC. SPG converted, so the cast returned a DIFFERENT
1272/// INSTANT with no error — the silent-wrong shape. It also refused a
1273/// named zone outright, where PG accepts and ignores it.
1274///
1275/// This is the same parse; it just does not apply the offset (the time
1276/// parser already reports the local clock separately) and strips a
1277/// trailing named zone the numeric-offset scanner cannot see.
1278/// A NAMED zone (`… America/New_York`) is not stripped here: PG
1279/// validates it — `'… Bogus/Zone'::timestamp` is `time zone
1280/// "bogus/zone" not recognized`, not a silent drop — and the zone
1281/// database lives on the host, not in this no_std crate. That case
1282/// still errors, which is wrong but LOUD; the numeric-offset case was
1283/// wrong and silent, which is why it is the one fixed here.
1284pub fn parse_timestamp_literal_wall_ordered(s: &str, order: DateOrder) -> Option<i64> {
1285    if let Some(v) = timestamp_sentinel(s) {
1286        return Some(v);
1287    }
1288    // Ignoring the offset is simply not applying it: the parts reader
1289    // already reports the LOCAL clock separately.
1290    let (days, day_micros, _tz) = parse_timestamp_parts(s, order)?;
1291    i64::from(days)
1292        .checked_mul(86_400_000_000)?
1293        .checked_add(day_micros)
1294}
1295
1296/// `epoch` / `±infinity`, which are whole instants rather than a
1297/// date-and-time to assemble.
1298fn timestamp_sentinel(s: &str) -> Option<i64> {
1299    let t = s.trim();
1300    if t.eq_ignore_ascii_case("epoch") {
1301        return Some(0);
1302    }
1303    if t.eq_ignore_ascii_case("infinity") || t.eq_ignore_ascii_case("+infinity") {
1304        return Some(i64::MAX);
1305    }
1306    if t.eq_ignore_ascii_case("-infinity") {
1307        return Some(i64::MIN);
1308    }
1309    None
1310}
1311
1312/// v7.15.0 — Parse `HH:MM:SS[.frac][<tz>]` and return
1313/// `(day_micros, tz_offset_micros)` where `day_micros` is the
1314/// local-clock seconds-of-day in microseconds and
1315/// `tz_offset_micros` is the UTC offset (positive = east of
1316/// UTC, negative = west). Caller subtracts the offset to
1317/// normalise to UTC. PG's recognised TZ shapes after the
1318/// seconds (or frac) part:
1319///   * `+OO[:MM]` / `-OO[:MM]` — numeric offset
1320///   * `+OOMM` / `-OOMM` (no colon, less common but legal)
1321///   * ` UTC` / `UTC` / `Z` — explicit zero offset
1322/// Anything else after the seconds = parse failure (the caller
1323/// v7.39 (round 324, V42) — PG's message for a text literal that will not
1324/// become a date/time value. Two shapes, measured on PG 18.4:
1325///
1326///   * `invalid input syntax for type <t>: "<text>"` — the text is not
1327///     date/time shaped at all (`not-a-date`, `2020`, `2020-01-01 abc`);
1328///   * `date/time field value out of range: "<text>"` — it IS shaped like
1329///     one but a field's value is impossible (`2020-13-01`, `2020-02-30`,
1330///     `2020-01-01 25:00:00`).
1331///
1332/// The second form carries `HINT: Perhaps you need a different "DateStyle"
1333/// setting.` only when the offending field is a month or day outside its
1334/// UNIVERSAL range — the case a different field order could have
1335/// explained. `2020-02-30` (a day that is fine for the field but not for
1336/// that month), a time-of-day overflow and an oversized year get no hint.
1337/// The wire splits the `\nHINT:  ` tail into the ErrorResponse `H` field.
1338#[must_use]
1339pub(crate) fn datetime_input_error_text(text: &str, type_name: &str) -> alloc::string::String {
1340    let (kind, hint) = classify_datetime_input(text);
1341    match kind {
1342        DatetimeInputProblem::Syntax => {
1343            alloc::format!("invalid input syntax for type {type_name}: \"{text}\"")
1344        }
1345        DatetimeInputProblem::OutOfRange => {
1346            let mut m = alloc::format!("date/time field value out of range: \"{text}\"");
1347            if hint {
1348                m.push_str("\nHINT:  Perhaps you need a different \"DateStyle\" setting.");
1349            }
1350            m
1351        }
1352    }
1353}
1354
1355enum DatetimeInputProblem {
1356    Syntax,
1357    OutOfRange,
1358}
1359
1360/// `(problem, wants_datestyle_hint)` for a literal that failed to parse.
1361fn classify_datetime_input(text: &str) -> (DatetimeInputProblem, bool) {
1362    let t = text.trim();
1363    // Any character outside the date/time alphabet means PG never got as
1364    // far as reading a field value.
1365    if t.is_empty()
1366        || !t
1367            .chars()
1368            .all(|c| c.is_ascii_digit() || matches!(c, '-' | ':' | '.' | ' ' | 'T' | '+' | 'Z'))
1369    {
1370        return (DatetimeInputProblem::Syntax, false);
1371    }
1372    // The date part is everything before the first space or `T`.
1373    let date_part = t.split([' ', 'T']).next().unwrap_or("");
1374    let fields: alloc::vec::Vec<&str> = date_part.split('-').collect();
1375    if fields.len() != 3
1376        || fields
1377            .iter()
1378            .any(|f| f.is_empty() || !f.chars().all(|c| c.is_ascii_digit()))
1379    {
1380        return (DatetimeInputProblem::Syntax, false);
1381    }
1382    // Shaped like a date; a month or day outside its universal range is
1383    // the case a different DateStyle could have explained.
1384    let month = fields[1].parse::<u32>().unwrap_or(0);
1385    let day = fields[2].parse::<u32>().unwrap_or(0);
1386    let field_out_of_range = !(1..=12).contains(&month) || !(1..=31).contains(&day);
1387    (DatetimeInputProblem::OutOfRange, field_out_of_range)
1388}
1389
1390/// surfaces as "cannot parse … as TIMESTAMP").
1391fn parse_time_of_day_micros(t: &str) -> Option<(i64, i64)> {
1392    parse_time_of_day_micros_tz(t).map(|(us, tz)| (us, tz.unwrap_or(0)))
1393}
1394
1395/// v7.39 (tz epic) — like `parse_time_of_day_micros` but reports
1396/// whether the literal carried an explicit offset (`None` = naive; a
1397/// timestamptz cast then interprets the wall clock in the session
1398/// zone, like PG).
1399fn parse_time_of_day_micros_tz(t: &str) -> Option<(i64, Option<i64>)> {
1400    let t = t.trim();
1401    // Detect & strip optional TZ suffix. Anchor on the first
1402    // `+` / `-` AFTER position 8 (so the leading sign on a
1403    // negative offset can't be mistaken for an `HH:MM:SS-OO`
1404    // boundary if the time itself is somehow malformed).
1405    // ` UTC` and trailing `Z` also count as zero-offset TZ tags.
1406    let (core, tz_micros) = if let Some(rest) = t.strip_suffix('Z') {
1407        (rest, Some(0i64))
1408    } else if let Some(rest) = t.strip_suffix(" UTC").or_else(|| t.strip_suffix("UTC")) {
1409        (rest, Some(0i64))
1410    } else if let Some((idx, sign_byte)) = find_offset_sign(t) {
1411        let suffix = &t[idx..];
1412        let micros = parse_tz_offset_suffix(suffix, sign_byte == b'+')?;
1413        (&t[..idx], Some(micros))
1414    } else {
1415        (t, None)
1416    };
1417    let (time, frac_str) = match core.split_once('.') {
1418        Some((a, b)) => (a, Some(b)),
1419        None => (core, None),
1420    };
1421    let bytes = time.as_bytes();
1422    // PG accepts both `HH:MM:SS` and the seconds-optional `HH:MM`
1423    // form in a TIMESTAMP literal (`'2024-01-15 10:30'::timestamp`
1424    // → `10:30:00`); hour-only (`'... 10'`) stays a parse error.
1425    let (hh, mm, ss): (i64, i64, i64) = if bytes.len() == 8 && bytes[2] == b':' && bytes[5] == b':'
1426    {
1427        (
1428            time[0..2].parse().ok()?,
1429            time[3..5].parse().ok()?,
1430            time[6..8].parse().ok()?,
1431        )
1432    } else if bytes.len() == 5 && bytes[2] == b':' {
1433        (time[0..2].parse().ok()?, time[3..5].parse().ok()?, 0)
1434    } else {
1435        return None;
1436    };
1437    if !(0..24).contains(&hh) || !(0..60).contains(&mm) || !(0..60).contains(&ss) {
1438        return None;
1439    }
1440    let frac_micros: i64 = match frac_str {
1441        None => 0,
1442        Some(f) => {
1443            // Pad right with zeros to 6 digits, then truncate extras.
1444            if f.is_empty() || f.len() > 9 {
1445                return None;
1446            }
1447            let mut padded = String::with_capacity(6);
1448            padded.push_str(&f[..f.len().min(6)]);
1449            while padded.len() < 6 {
1450                padded.push('0');
1451            }
1452            padded.parse().ok()?
1453        }
1454    };
1455    Some((
1456        ((hh * 3600 + mm * 60 + ss) * 1_000_000) + frac_micros,
1457        tz_micros,
1458    ))
1459}
1460
1461/// Find the index of the TZ-offset sign byte (`+` or `-`) that
1462/// terminates an `HH:MM:SS[.fff]` time string, or `None` when
1463/// the time carries no numeric TZ suffix. Anchors past the first
1464/// 8 bytes (`HH:MM:SS`) so the seconds/minutes colons don't
1465/// confuse the scan.
1466fn find_offset_sign(t: &str) -> Option<(usize, u8)> {
1467    let bytes = t.as_bytes();
1468    // Start past `HH:MM` (5 bytes) — the seconds-optional literal
1469    // (`'2024-07-15 12:00+00'`) carries its offset at index 5; a
1470    // time body itself never contains `+`/`-`.
1471    if bytes.len() < 6 {
1472        return None;
1473    }
1474    for i in 5..bytes.len() {
1475        match bytes[i] {
1476            b'+' | b'-' => return Some((i, bytes[i])),
1477            _ => {}
1478        }
1479    }
1480    None
1481}
1482
1483/// Parse `+OO`, `+OO:MM`, `+OOMM`, `-OO`, `-OO:MM`, `-OOMM` into
1484/// a UTC-offset microsecond delta. `is_positive` reflects the
1485/// already-stripped sign.
1486fn parse_tz_offset_suffix(suffix: &str, is_positive: bool) -> Option<i64> {
1487    // suffix starts with `+` or `-`; strip it.
1488    let body = &suffix[1..];
1489    let (hh, mm): (i64, i64) = if let Some((h, m)) = body.split_once(':') {
1490        (h.parse().ok()?, m.parse().ok()?)
1491    } else {
1492        match body.len() {
1493            2 => (body.parse().ok()?, 0),
1494            3 => {
1495                // PG's "+0530" form lacks the colon; but a 3-char
1496                // body is `OOM` which is ambiguous (`+053` ?). PG
1497                // doesn't emit that; reject.
1498                return None;
1499            }
1500            4 => {
1501                let h: i64 = body[0..2].parse().ok()?;
1502                let m: i64 = body[2..4].parse().ok()?;
1503                (h, m)
1504            }
1505            _ => return None,
1506        }
1507    };
1508    if !(0..=18).contains(&hh) || !(0..60).contains(&mm) {
1509        return None;
1510    }
1511    let abs = (hh * 3600 + mm * 60) * 1_000_000;
1512    Some(if is_positive { abs } else { -abs })
1513}
1514
1515/// Render an `Interval { months, days, micros }` in a PG-ish shape.
1516/// The output mirrors `psql`'s text format: years/months from the
1517/// months part, days from its own dimension (no carry from micros —
1518/// this is the PG-canonical separation so `'1 day'` ≠ `'24 hours'`),
1519/// HH:MM:SS[.frac] from micros. v7.37.5 β added the `days` parameter
1520/// for PG byte-equal; `micros` may still carry hours ≥ 24 (PG keeps
1521/// the unnormalised form on the wire).
1522pub fn format_interval(months: i32, days: i32, micros: i64) -> String {
1523    let mut parts: Vec<String> = Vec::new();
1524    let years = months / 12;
1525    let mons = months % 12;
1526    // PG renders the unit in the singular only for `+1`; `-1` and any
1527    // other value pluralise. Helper closes over that rule.
1528    let unit = |n: i64, singular: &'static str, plural: &'static str| -> &'static str {
1529        if n == 1 { singular } else { plural }
1530    };
1531    // PG shows an explicit `+` on a positive field that follows a
1532    // negative one (`-2 mons +3 days`), so mixed signs stay readable.
1533    let mut prev_negative = false;
1534    if years != 0 {
1535        parts.push(format!(
1536            "{years} {}",
1537            unit(i64::from(years), "year", "years")
1538        ));
1539        prev_negative = years < 0;
1540    }
1541    if mons != 0 {
1542        let plus = if prev_negative && mons > 0 { "+" } else { "" };
1543        parts.push(format!(
1544            "{plus}{mons} {}",
1545            unit(i64::from(mons), "mon", "mons")
1546        ));
1547        prev_negative = mons < 0;
1548    }
1549    if days != 0 {
1550        let plus = if prev_negative && days > 0 { "+" } else { "" };
1551        parts.push(format!(
1552            "{plus}{days} {}",
1553            unit(i64::from(days), "day", "days")
1554        ));
1555    }
1556    let mut rem = micros;
1557    if rem != 0 {
1558        let neg = rem < 0;
1559        if neg {
1560            rem = -rem;
1561        }
1562        let secs = rem / 1_000_000;
1563        let frac = rem % 1_000_000;
1564        let hh = secs / 3600;
1565        let mm = (secs / 60) % 60;
1566        let ss = secs % 60;
1567        // PG shows an explicit `+` on the time part when a preceding date
1568        // field was negative but the time itself is positive, e.g.
1569        // `-1 days +02:00:00`. `is_before` = the last-printed date field's
1570        // sign.
1571        let is_before = if days != 0 {
1572            days < 0
1573        } else if mons != 0 {
1574            mons < 0
1575        } else {
1576            years < 0
1577        };
1578        let sign = if neg {
1579            "-"
1580        } else if is_before {
1581            "+"
1582        } else {
1583            ""
1584        };
1585        if frac == 0 {
1586            parts.push(format!("{sign}{hh:02}:{mm:02}:{ss:02}"));
1587        } else {
1588            let raw = format!("{frac:06}");
1589            let trimmed = raw.trim_end_matches('0');
1590            parts.push(format!("{sign}{hh:02}:{mm:02}:{ss:02}.{trimmed}"));
1591        }
1592    }
1593    if parts.is_empty() {
1594        // PG renders a zero interval as `00:00:00`, not `0`.
1595        "00:00:00".into()
1596    } else {
1597        parts.join(" ")
1598    }
1599}
1600
1601/// v7.10.9 — render a TEXT[] in PG's external array form
1602/// (`{a,b,NULL}`). Elements containing whitespace, commas,
1603/// quotes, or braces get double-quoted with `\\` / `\"` escapes.
1604/// NULL elements use the literal token `NULL`. Public so the
1605/// wire layer can produce the canonical text-mode encoding.
1606pub fn format_text_array(items: &[Option<String>]) -> String {
1607    let mut out = String::with_capacity(2 + items.len() * 8);
1608    out.push('{');
1609    for (i, item) in items.iter().enumerate() {
1610        if i > 0 {
1611            out.push(',');
1612        }
1613        match item {
1614            None => out.push_str("NULL"),
1615            Some(s) => {
1616                // PG array_out quotes an element containing any structural
1617                // char or any whitespace `array_isspace` recognises — space,
1618                // tab, newline, carriage return, vertical tab, form feed —
1619                // not just space/tab.
1620                let needs_quote = s.is_empty()
1621                    || s.eq_ignore_ascii_case("NULL")
1622                    || s.chars().any(|c| {
1623                        matches!(
1624                            c,
1625                            ',' | '{'
1626                                | '}'
1627                                | '"'
1628                                | '\\'
1629                                | ' '
1630                                | '\t'
1631                                | '\n'
1632                                | '\r'
1633                                | '\x0b'
1634                                | '\x0c'
1635                        )
1636                    });
1637                if needs_quote {
1638                    out.push('"');
1639                    for c in s.chars() {
1640                        if c == '"' || c == '\\' {
1641                            out.push('\\');
1642                        }
1643                        out.push(c);
1644                    }
1645                    out.push('"');
1646                } else {
1647                    out.push_str(s);
1648                }
1649            }
1650        }
1651    }
1652    out.push('}');
1653    out
1654}
1655
1656/// v7.11.14 — render an INT[] in PG's external array form
1657/// (`{1,2,NULL}`). Integer payloads never need quoting. NULL
1658/// elements use the literal token `NULL`.
1659pub fn format_int_array(items: &[Option<i32>]) -> String {
1660    let mut out = String::with_capacity(2 + items.len() * 4);
1661    out.push('{');
1662    for (i, item) in items.iter().enumerate() {
1663        if i > 0 {
1664            out.push(',');
1665        }
1666        match item {
1667            None => out.push_str("NULL"),
1668            Some(n) => out.push_str(&n.to_string()),
1669        }
1670    }
1671    out.push('}');
1672    out
1673}
1674
1675/// v7.11.14 — render a BIGINT[] in PG's external array form
1676/// (`{1,2,NULL}`).
1677pub fn format_bigint_array(items: &[Option<i64>]) -> String {
1678    let mut out = String::with_capacity(2 + items.len() * 6);
1679    out.push('{');
1680    for (i, item) in items.iter().enumerate() {
1681        if i > 0 {
1682            out.push(',');
1683        }
1684        match item {
1685            None => out.push_str("NULL"),
1686            Some(n) => out.push_str(&n.to_string()),
1687        }
1688    }
1689    out.push('}');
1690    out
1691}
1692
1693/// v7.37.5 γ — render a BOOL[] in PG external form.
1694/// PG uses single-letter `t` / `f` for booleans (matching the
1695/// scalar wire convention).
1696pub fn format_bool_array(items: &[Option<bool>]) -> String {
1697    let mut out = String::with_capacity(2 + items.len() * 2);
1698    out.push('{');
1699    for (i, item) in items.iter().enumerate() {
1700        if i > 0 {
1701            out.push(',');
1702        }
1703        match item {
1704            None => out.push_str("NULL"),
1705            Some(b) => out.push(if *b { 't' } else { 'f' }),
1706        }
1707    }
1708    out.push('}');
1709    out
1710}
1711
1712/// v7.37.5 γ — render a SMALLINT[] in PG external form.
1713pub fn format_smallint_array(items: &[Option<i16>]) -> String {
1714    let mut out = String::with_capacity(2 + items.len() * 4);
1715    out.push('{');
1716    for (i, item) in items.iter().enumerate() {
1717        if i > 0 {
1718            out.push(',');
1719        }
1720        match item {
1721            None => out.push_str("NULL"),
1722            Some(n) => out.push_str(&n.to_string()),
1723        }
1724    }
1725    out.push('}');
1726    out
1727}
1728
1729/// v7.37.5 γ — render a FLOAT[] / DOUBLE PRECISION[] in PG
1730/// external form. PG renders floats via the engine's existing
1731/// f64 → text path so this just calls Rust's default Display.
1732pub fn format_float_array(items: &[Option<f64>]) -> String {
1733    let mut out = String::with_capacity(2 + items.len() * 8);
1734    out.push('{');
1735    for (i, item) in items.iter().enumerate() {
1736        if i > 0 {
1737            out.push(',');
1738        }
1739        match item {
1740            None => out.push_str("NULL"),
1741            // PG float8[] elements use float8out too — scientific past
1742            // the exponent thresholds (`{1e+30,2}`), not every digit.
1743            Some(x) => out.push_str(&format_float(*x)),
1744        }
1745    }
1746    out.push('}');
1747    out
1748}
1749
1750/// v7.37.5 γ — render a NUMERIC[] in PG external form.
1751pub fn format_numeric_array(items: &[Option<(i128, u16)>]) -> String {
1752    let mut out = String::with_capacity(2 + items.len() * 6);
1753    out.push('{');
1754    for (i, item) in items.iter().enumerate() {
1755        if i > 0 {
1756            out.push(',');
1757        }
1758        match item {
1759            None => out.push_str("NULL"),
1760            Some((scaled, scale)) => out.push_str(&format_numeric(*scaled, *scale)),
1761        }
1762    }
1763    out.push('}');
1764    out
1765}
1766
1767/// v7.37.5 γ — render a DATE[] in PG external form. Each
1768/// non-NULL element is rendered as `YYYY-MM-DD`.
1769pub fn format_date_array(items: &[Option<i32>]) -> String {
1770    let mut out = String::with_capacity(2 + items.len() * 12);
1771    out.push('{');
1772    for (i, item) in items.iter().enumerate() {
1773        if i > 0 {
1774            out.push(',');
1775        }
1776        match item {
1777            None => out.push_str("NULL"),
1778            Some(d) => out.push_str(&format_date(*d)),
1779        }
1780    }
1781    out.push('}');
1782    out
1783}
1784
1785/// v7.37.5 γ — render a TIMESTAMP[] (`with_tz=false`) or
1786/// TIMESTAMPTZ[] (`with_tz=true`) in PG external form. Each
1787/// non-NULL element is double-quoted because the canonical
1788/// timestamp text contains a space (`2024-06-01 12:00:00`)
1789/// that would otherwise split on commas wrong.
1790pub fn format_timestamp_array(items: &[Option<i64>], with_tz: bool) -> String {
1791    let mut out = String::with_capacity(2 + items.len() * 22);
1792    out.push('{');
1793    for (i, item) in items.iter().enumerate() {
1794        if i > 0 {
1795            out.push(',');
1796        }
1797        match item {
1798            None => out.push_str("NULL"),
1799            Some(t) => {
1800                out.push('"');
1801                if with_tz {
1802                    out.push_str(&format_timestamptz(*t));
1803                } else {
1804                    out.push_str(&format_timestamp(*t));
1805                }
1806                out.push('"');
1807            }
1808        }
1809    }
1810    out.push('}');
1811    out
1812}
1813
1814/// v7.37.5 γ — render a UUID[] in PG external form. UUID text is
1815/// the canonical lowercase 8-4-4-4-12 hyphenated form; no quoting
1816/// needed (hex + dashes, no spaces / commas).
1817pub fn format_uuid_array(items: &[Option<[u8; 16]>]) -> String {
1818    let mut out = String::with_capacity(2 + items.len() * 38);
1819    out.push('{');
1820    for (i, item) in items.iter().enumerate() {
1821        if i > 0 {
1822            out.push(',');
1823        }
1824        match item {
1825            None => out.push_str("NULL"),
1826            Some(b) => out.push_str(&spg_storage::format_uuid(b)),
1827        }
1828    }
1829    out.push('}');
1830    out
1831}
1832
1833/// v7.37.5 γ — render a BYTEA[] in PG external form. Each
1834/// non-NULL element is `\\x<hex>` (the PG hex output form) and
1835/// is double-quoted because the leading backslash is a PG array
1836/// escape character.
1837pub fn format_bytea_array(items: &[Option<Vec<u8>>]) -> String {
1838    let mut out = String::with_capacity(2 + items.len() * 8);
1839    out.push('{');
1840    for (i, item) in items.iter().enumerate() {
1841        if i > 0 {
1842            out.push(',');
1843        }
1844        match item {
1845            None => out.push_str("NULL"),
1846            Some(b) => {
1847                out.push('"');
1848                let hex = format_bytea_hex(b);
1849                // Escape leading backslash (`\` → `\\`) per PG
1850                // array-element quoting rules.
1851                for c in hex.chars() {
1852                    if c == '\\' {
1853                        out.push('\\');
1854                    }
1855                    out.push(c);
1856                }
1857                out.push('"');
1858            }
1859        }
1860    }
1861    out.push('}');
1862    out
1863}
1864
1865/// v7.37.5 β-P4 — render an INTERVAL[] in PG's external array form.
1866/// Each non-NULL element is double-quoted because interval text
1867/// contains spaces (`1 day`) and colons (`24:00:00`) that would
1868/// confuse the comma-separated parse: `{"1 day","24:00:00",NULL}`.
1869/// Inner `"` doesn't occur in interval text so no escaping is
1870/// needed; backslashes likewise can't appear.
1871pub fn format_interval_array(items: &[Option<spg_storage::IntervalSpan>]) -> String {
1872    let mut out = String::with_capacity(2 + items.len() * 12);
1873    out.push('{');
1874    for (i, item) in items.iter().enumerate() {
1875        if i > 0 {
1876            out.push(',');
1877        }
1878        match item {
1879            None => out.push_str("NULL"),
1880            Some(span) => {
1881                // v7.38.19 — an element can be infinite too, and the
1882                // word carries no comma or space, so PostgreSQL prints
1883                // it unquoted: `{infinity,"1 day"}`.
1884                if span.kind.is_finite() {
1885                    out.push('"');
1886                    out.push_str(&format_interval(span.months, span.days, span.micros));
1887                    out.push('"');
1888                } else {
1889                    out.push_str(&format_interval_kinded(0, 0, 0, span.kind));
1890                }
1891            }
1892        }
1893    }
1894    out.push('}');
1895    out
1896}
1897
1898/// v7.10.4 — render a BYTEA payload in PG's hex output format
1899/// (`\x` prefix, lowercase hex pairs). Public so the wire layer
1900/// can emit the canonical bytea-as-text representation.
1901/// v7.39 (round 524) — PG's `escape` bytea form: a printable byte as
1902/// itself, a backslash doubled, everything else `\ooo` octal.
1903#[must_use]
1904pub fn format_bytea_escape(b: &[u8]) -> String {
1905    let mut out = String::with_capacity(b.len());
1906    for &byte in b {
1907        match byte {
1908            b'\\' => out.push_str("\\\\"),
1909            0x20..=0x7e => out.push(byte as char),
1910            _ => out.push_str(&alloc::format!("\\{byte:03o}")),
1911        }
1912    }
1913    out
1914}
1915
1916pub fn format_bytea_hex(b: &[u8]) -> String {
1917    let mut out = String::with_capacity(2 + 2 * b.len());
1918    out.push_str("\\x");
1919    const HEX: &[u8; 16] = b"0123456789abcdef";
1920    for byte in b {
1921        out.push(HEX[(byte >> 4) as usize] as char);
1922        out.push(HEX[(byte & 0x0F) as usize] as char);
1923    }
1924    out
1925}
1926
1927/// Render a `Numeric { scaled, scale }` as its decimal text form.
1928/// Negative `scaled` prepends `-` to the absolute value's digits; the
1929/// integer / fractional split is by character count, padding the
1930/// fractional side with leading zeros to exactly `scale` chars.
1931/// v7.38 (read01, T6) — render a NUMERIC honoring its special kind. Finite uses
1932/// `format_numeric`; the specials render PG's full-word spellings.
1933pub fn format_numeric_kind(kind: spg_storage::NumericKind, scaled: i128, scale: u16) -> String {
1934    use spg_storage::NumericKind;
1935    match kind {
1936        NumericKind::Finite => format_numeric(scaled, scale),
1937        NumericKind::NaN => String::from("NaN"),
1938        NumericKind::PosInf => String::from("Infinity"),
1939        NumericKind::NegInf => String::from("-Infinity"),
1940    }
1941}
1942
1943pub fn format_numeric(scaled: i128, scale: u16) -> String {
1944    if scale == 0 {
1945        return format!("{scaled}");
1946    }
1947    let negative = scaled < 0;
1948    let mag_str = scaled.unsigned_abs().to_string();
1949    let mag_bytes = mag_str.as_bytes();
1950    let scale_u = scale as usize;
1951    let mut out = String::with_capacity(mag_str.len() + 3);
1952    if negative {
1953        out.push('-');
1954    }
1955    if mag_bytes.len() <= scale_u {
1956        out.push('0');
1957        out.push('.');
1958        for _ in mag_bytes.len()..scale_u {
1959            out.push('0');
1960        }
1961        out.push_str(&mag_str);
1962    } else {
1963        let split = mag_bytes.len() - scale_u;
1964        out.push_str(&mag_str[..split]);
1965        out.push('.');
1966        out.push_str(&mag_str[split..]);
1967    }
1968    out
1969}
1970
1971/// v7.39 (round 292) — the shortest decimal for an f64 in PG's sense,
1972/// as `{:e}` style. The f64 sibling of `shortest_real_sci`.
1973///
1974/// Rust's `{:e}` gives the shortest decimal that ROUND-TRIPS; PG wants
1975/// the shortest that lies STRICTLY INSIDE the rounding interval. The
1976/// two differ exactly on values whose short form sits on a half-ulp
1977/// boundary — measured on PG 18.4, `1e23::float8` prints
1978/// `9.999999999999999e+22`, because 1e23 IS the boundary and
1979/// ties-to-even parses it back to the same double, so Rust accepts it.
1980///
1981/// The f32 version can test the boundary by widening to f64. There is
1982/// no wider float here, so the test is done in exact INTEGER
1983/// arithmetic instead: a midpoint is `M · 2^E` with M odd, a candidate
1984/// is `D · 10^K`, and the two are equal only if their odd parts and
1985/// their powers of two both match. That forces `5^|K|` to divide a
1986/// 57-bit number, which bounds |K| — so the whole comparison fits in
1987/// u128 and needs no bignum at all.
1988fn shortest_float_sci(x: f64) -> String {
1989    let (m, e) = f64_mantissa_exp(x);
1990    // Midpoints to the neighbours, as odd·2^exp. The gap BELOW a power
1991    // of two is half the gap above it, so that side needs one more bit.
1992    let (hi_m, hi_e) = (2 * m + 1, e - 1);
1993    let (lo_m, lo_e) = if m == 1 << 52 && e > f64_min_exp() {
1994        (4 * m - 1, e - 2)
1995    } else {
1996        (2 * m - 1, e - 1)
1997    };
1998    for p in 1..=17u32 {
1999        let cand = alloc::format!("{x:.*e}", (p - 1) as usize);
2000        let Ok(v) = cand.parse::<f64>() else { continue };
2001        if v != x {
2002            continue;
2003        }
2004        let Some((d, k)) = sci_to_digits_exp(&cand) else {
2005            continue;
2006        };
2007        if !decimal_eq_binary(d, k, hi_m, hi_e) && !decimal_eq_binary(d, k, lo_m, lo_e) {
2008            return cand;
2009        }
2010    }
2011    alloc::format!("{x:e}")
2012}
2013
2014/// `x` as `mantissa · 2^exp` with the mantissa a positive integer.
2015/// Only called on finite non-zero values.
2016fn f64_mantissa_exp(x: f64) -> (u128, i32) {
2017    let bits = x.abs().to_bits();
2018    let biased = ((bits >> 52) & 0x7ff) as i32;
2019    let frac = u128::from(bits & 0x000f_ffff_ffff_ffff);
2020    if biased == 0 {
2021        (frac, -1074) // subnormal: no implicit leading bit
2022    } else {
2023        ((1u128 << 52) | frac, biased - 1075)
2024    }
2025}
2026
2027/// The exponent of the smallest normal f64, below which the
2028/// gap-below-a-power-of-two rule no longer applies.
2029const fn f64_min_exp() -> i32 {
2030    -1074
2031}
2032
2033/// Split a `{:e}` string into `(digits, exponent)` such that the value
2034/// is `digits · 10^exponent`. `None` when it does not fit u128 (which
2035/// cannot happen for the ≤ 17 digits generated here).
2036fn sci_to_digits_exp(sci: &str) -> Option<(u128, i32)> {
2037    let epos = sci.find('e')?;
2038    let (mant, rest) = sci.split_at(epos);
2039    let exp: i32 = rest[1..].parse().ok()?;
2040    let mant = mant.strip_prefix('-').unwrap_or(mant);
2041    let (int_part, frac_part) = match mant.split_once('.') {
2042        Some((a, b)) => (a, b),
2043        None => (mant, ""),
2044    };
2045    let mut digits: u128 = 0;
2046    for c in int_part.chars().chain(frac_part.chars()) {
2047        digits = digits
2048            .checked_mul(10)?
2049            .checked_add(u128::from(c as u8 - b'0'))?;
2050    }
2051    Some((digits, exp - i32::try_from(frac_part.len()).ok()?))
2052}
2053
2054/// Exactly: does `d · 10^k` equal `m · 2^e`, with `m` odd?
2055///
2056/// Both sides are split into an odd part and a power of two; they are
2057/// equal iff both halves match. `10^k = 2^k · 5^k`, so the 5s must
2058/// divide out exactly — which is what bounds the powers involved.
2059fn decimal_eq_binary(d: u128, k: i32, m: u128, e: i32) -> bool {
2060    if d == 0 {
2061        return false;
2062    }
2063    let a = i32::try_from(d.trailing_zeros()).unwrap_or(i32::MAX);
2064    let d_odd = d >> d.trailing_zeros();
2065    if k >= 0 {
2066        // odd part is d_odd · 5^k — bail as soon as it can only exceed m.
2067        let mut lhs = d_odd;
2068        for _ in 0..k {
2069            match lhs.checked_mul(5) {
2070                Some(v) if v <= m => lhs = v,
2071                _ => return false,
2072            }
2073        }
2074        lhs == m && a + k == e
2075    } else {
2076        // d_odd must be divisible by 5^|k|; the quotient is the odd part.
2077        let j = -k;
2078        let mut lhs = d_odd;
2079        for _ in 0..j {
2080            if lhs % 5 != 0 {
2081                return false;
2082            }
2083            lhs /= 5;
2084        }
2085        lhs == m && a - j == e
2086    }
2087}