spg-engine 7.37.23

Execution engine for SPG: glues spg-sql parsing to spg-storage. Foreign keys, joins, vectors, cold tier.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
//! String / text SQL functions split out of `eval.rs` (cut 28):
//! `left` / `right` (string_left_right), `lpad` / `rpad` (string_pad),
//! `trim` / `ltrim` / `rtrim` (string_trim + TrimSide), `format`
//! (format_string), `to_char`, plus the `pg_typeof` name lookup and
//! the `value_to_format_text` coercion shared by concat / replace /
//! split_part / position dispatch in eval.rs. The date helpers
//! (`civil_from_days`, `MONTH_FULL` / `MONTH_ABBR`) stay in eval.rs
//! since `date_format_mysql` and the timestamp paths share them.

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

use spg_storage::Value;

use super::{EvalError, MONTH_ABBR, MONTH_FULL, civil_from_days, days_from_civil};

/// Full weekday names, indexed Monday = 0 .. Sunday = 6 (matching
/// `(days + 3).rem_euclid(7)` since 1970-01-01 was a Thursday).
const DAY_FULL: [&str; 7] = [
    "Monday",
    "Tuesday",
    "Wednesday",
    "Thursday",
    "Friday",
    "Saturday",
    "Sunday",
];
/// Abbreviated weekday names, same Monday = 0 indexing.
const DAY_ABBR: [&str; 7] = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
/// Roman numeral months (PG `RM` / `rm`), index month-1.
const MONTH_ROMAN: [&str; 12] = [
    "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X", "XI", "XII",
];

/// Apply a PG `to_char` case template to a mixed-case canonical name:
/// `"Tuesday"` → itself for `Xx`, uppercase for `XX`, lowercase for
/// `xx`. `blank_to` (when `Some`) right-pads with spaces to the fixed
/// PG field width (9 for full day/month names, 4 for roman months).
fn cased_name(canonical: &str, upper: bool, lower: bool, blank_to: Option<usize>) -> String {
    let mut s = if upper {
        canonical.to_ascii_uppercase()
    } else if lower {
        canonical.to_ascii_lowercase()
    } else {
        canonical.to_string()
    };
    if let Some(width) = blank_to {
        while s.len() < width {
            s.push(' ');
        }
    }
    s
}

// PG trim family: which side to strip.
#[derive(Debug, Clone, Copy)]
pub(super) enum TrimSide {
    Left,
    Right,
    Both,
}

/// PG `left(s, n)` / `right(s, n)` shared implementation. Both
/// support negative n which means "all but |n| chars from the
/// opposite side". n=0 → ''. Codepoint-counted. NULL → NULL.
pub(super) fn string_left_right(
    args: &[Value<'_>],
    is_left: bool,
    fn_name: &str,
    mysql: bool,
) -> Result<Value<'static>, EvalError> {
    if args.len() != 2 {
        return Err(EvalError::TypeMismatch {
            detail: alloc::format!("{fn_name}() takes 2 args, got {}", args.len()),
        });
    }
    if args.iter().any(|v| matches!(v, Value::Null)) {
        return Ok(Value::Null);
    }
    // v7.39 (round 610) — `left(s, 5)` allocated 5.5 times a row over 200k
    // rows to hand back five characters: a copy of the operand, a `Vec<char>`
    // of it (four bytes a character), and then the result collected out of
    // that vector. The operand is borrowed now and the answer is one slice.
    let s = value_to_format_text_ref(&args[0]);
    let n = match &args[1] {
        Value::SmallInt(x) => i64::from(*x),
        Value::Int(x) => i64::from(*x),
        Value::BigInt(x) => *x,
        other => {
            return Err(EvalError::TypeMismatch {
                detail: alloc::format!(
                    "{fn_name}(): n must be integer, got {}",
                    crate::conversions::pg_type_name_for_error_opt(other.data_type())
                ),
            });
        }
    };
    // The character count is still needed for every case except a positive
    // `left`, which stops at the nth character without knowing the total.
    let len = if is_left && n > 0 {
        i64::MAX
    } else {
        s.chars().count() as i64
    };
    // v7.39 (round 395) — MySQL LEFT/RIGHT with a negative length is the
    // empty string (`LEFT('abc', -1)` is ''), where PG drops the last /
    // first |k| chars (`left('abc', -1)` is 'ab').
    if n == 0 || (mysql && n < 0) {
        return Ok(Value::text(String::new()));
    }
    let (start, end) = if is_left {
        if n > 0 {
            (0usize, (n.min(len)) as usize)
        } else {
            // left(s, -k) → drop last |k| chars; keep [0..len - k]
            let drop = (-n).min(len);
            (0usize, (len - drop) as usize)
        }
    } else if n > 0 {
        // right(s, k) → keep last k chars; start = max(0, len-k)
        let start = (len - n).max(0);
        (start as usize, len as usize)
    } else {
        // right(s, -k) → drop first |k| chars; keep [k..len]
        let drop = (-n).min(len);
        (drop as usize, len as usize)
    };
    if start >= end {
        return Ok(Value::text(String::new()));
    }
    // Character indices to byte offsets, in one walk.
    let mut byte_start = s.len();
    let mut byte_end = s.len();
    for (nth, (byte, _)) in s.char_indices().enumerate() {
        if nth == start {
            byte_start = byte;
        }
        if nth == end {
            byte_end = byte;
            break;
        }
    }
    if byte_start >= byte_end {
        return Ok(Value::text(String::new()));
    }
    Ok(Value::text(alloc::string::String::from(
        &s[byte_start..byte_end],
    )))
}

/// PG `lpad` / `rpad` shared implementation. Length is the
/// target codepoint count. When the input is longer than `length`,
/// truncate keeping the LEFT side (both lpad and rpad agree with
/// PG here). When shorter, pad with `fill` (default SPACE) cycling
/// for multi-char fills, on the appropriate side. Empty fill +
/// needs padding → returns input verbatim (potentially
/// truncated). NULL on any arg → NULL.
pub(super) fn string_pad(
    args: &[Value<'_>],
    is_left: bool,
    fn_name: &str,
) -> Result<Value<'static>, EvalError> {
    if args.len() != 2 && args.len() != 3 {
        return Err(EvalError::TypeMismatch {
            detail: alloc::format!("{fn_name}() takes 2 or 3 args, got {}", args.len()),
        });
    }
    if args.iter().any(|v| matches!(v, Value::Null)) {
        return Ok(Value::Null);
    }
    // v7.39 (round 608) — `lpad(s, 12, '0')` allocated 7.5 times a row over
    // 200k rows: a copy of each text operand, a `Vec<char>` of each (four
    // bytes a character), a padding string, and then the concatenation
    // growing into it. The result is the only string this has to build.
    let s = value_to_format_text_ref(&args[0]);
    let target = match &args[1] {
        Value::SmallInt(x) => i64::from(*x),
        Value::Int(x) => i64::from(*x),
        Value::BigInt(x) => *x,
        other => {
            return Err(EvalError::TypeMismatch {
                detail: alloc::format!(
                    "{fn_name}(): length must be integer, got {}",
                    crate::conversions::pg_type_name_for_error_opt(other.data_type())
                ),
            });
        }
    };
    let fill: alloc::borrow::Cow<'_, str> = if args.len() == 3 {
        value_to_format_text_ref(&args[2])
    } else {
        alloc::borrow::Cow::Borrowed(" ")
    };
    if target <= 0 {
        return Ok(Value::text(String::new()));
    }
    let target = target as usize;
    let s_len = s.chars().count();
    if s_len >= target {
        // Truncate from the right (PG keeps LEFT side for both
        // lpad and rpad).
        let end = s.char_indices().nth(target).map_or(s.len(), |(i, _)| i);
        return Ok(Value::text(alloc::string::String::from(&s[..end])));
    }
    if fill.is_empty() {
        return Ok(Value::text(s.into_owned()));
    }
    let pad_needed = target - s_len;
    // The fill cycles, exactly as indexing it modulo its length did.
    let mut out = String::with_capacity(s.len() + pad_needed * 4);
    if is_left {
        out.extend(fill.chars().cycle().take(pad_needed));
        out.push_str(&s);
    } else {
        out.push_str(&s);
        out.extend(fill.chars().cycle().take(pad_needed));
    }
    Ok(Value::text(out))
}

/// PG `trim` / `ltrim` / `rtrim` / `btrim` shared implementation.
/// Accepts 1 or 2 args; coerces both to text via the standard
/// `value_to_format_text` helper; treats the chars arg as a SET
/// of UTF-8 codepoints (not a substring). NULL on either arg
/// poisons the result.
pub(super) fn string_trim(
    args: &[Value<'_>],
    side: TrimSide,
    fn_name: &str,
) -> Result<Value<'static>, EvalError> {
    // v7.39 (read01 oracle_compat.c) — bytea trim variants work on BYTES
    // (byteatrim/ltrim/rtrim): trim any byte present in the set argument,
    // returning bytea — the text path would eat the \x prefix.
    if let [Value::Bytes(b), Value::Bytes(set)] = args {
        let setb: alloc::collections::BTreeSet<u8> = set.iter().copied().collect();
        let mut lo = 0usize;
        let mut hi = b.len();
        if matches!(side, TrimSide::Left | TrimSide::Both) {
            while lo < hi && setb.contains(&b[lo]) {
                lo += 1;
            }
        }
        if matches!(side, TrimSide::Right | TrimSide::Both) {
            while hi > lo && setb.contains(&b[hi - 1]) {
                hi -= 1;
            }
        }
        return Ok(Value::Bytes(alloc::borrow::Cow::Owned(b[lo..hi].to_vec())));
    }
    let (input, chars_str) = match args {
        [v] => (v.clone(), String::from(" ")),
        [v, c] => (v.clone(), {
            // NULL chars poisons.
            if matches!(c, Value::Null) {
                return Ok(Value::Null);
            }
            value_to_format_text(c)
        }),
        _ => {
            return Err(EvalError::TypeMismatch {
                detail: alloc::format!("{fn_name}() takes 1 or 2 args, got {}", args.len()),
            });
        }
    };
    if matches!(input, Value::Null) {
        return Ok(Value::Null);
    }
    let s = value_to_format_text(&input);
    let charset: alloc::collections::BTreeSet<char> = chars_str.chars().collect();
    let chars: Vec<char> = s.chars().collect();
    let mut start = 0usize;
    let mut end = chars.len();
    if matches!(side, TrimSide::Left | TrimSide::Both) {
        while start < end && charset.contains(&chars[start]) {
            start += 1;
        }
    }
    if matches!(side, TrimSide::Right | TrimSide::Both) {
        while end > start && charset.contains(&chars[end - 1]) {
            end -= 1;
        }
    }
    Ok(Value::text(chars[start..end].iter().collect::<String>()))
}

/// v7.17.0 Phase 3.8 — PG `format(fmtstr, args…)` with
/// sprintf-style conversion specifiers. Subset covered:
///   * `%s` — text rendering of the arg
///   * `%I` — quoted SQL identifier (always double-quoted; embedded
///     `"` doubled per SQL grammar)
///   * `%L` — quoted SQL literal (single-quoted; embedded `'`
///     doubled; NULL → literal `NULL`)
///   * `%%` — literal `%`
///   * `%n$X` — argument position (1-based) before the specifier
///     character (e.g. `%2$s` picks the 2nd arg)
/// PostgreSQL keywords whose `pg_get_keywords().catcode <> 'U'`
/// (reserved / type-func-name / col-name categories). `quote_ident`
/// / `quote_identifier` quote any of these even when the character
/// class is otherwise identifier-safe. Sorted ascending for
/// `binary_search`. Captured live from PG 18.4.
const PG_QUOTE_KEYWORDS: &[&str] = &[
    "all",
    "analyse",
    "analyze",
    "and",
    "any",
    "array",
    "as",
    "asc",
    "asymmetric",
    "authorization",
    "between",
    "bigint",
    "binary",
    "bit",
    "boolean",
    "both",
    "case",
    "cast",
    "char",
    "character",
    "check",
    "coalesce",
    "collate",
    "collation",
    "column",
    "concurrently",
    "constraint",
    "create",
    "cross",
    "current_catalog",
    "current_date",
    "current_role",
    "current_schema",
    "current_time",
    "current_timestamp",
    "current_user",
    "dec",
    "decimal",
    "default",
    "deferrable",
    "desc",
    "distinct",
    "do",
    "else",
    "end",
    "except",
    "exists",
    "extract",
    "false",
    "fetch",
    "float",
    "for",
    "foreign",
    "freeze",
    "from",
    "full",
    "grant",
    "greatest",
    "group",
    "grouping",
    "having",
    "ilike",
    "in",
    "initially",
    "inner",
    "inout",
    "int",
    "integer",
    "intersect",
    "interval",
    "into",
    "is",
    "isnull",
    "join",
    "json",
    "json_array",
    "json_arrayagg",
    "json_exists",
    "json_object",
    "json_objectagg",
    "json_query",
    "json_scalar",
    "json_serialize",
    "json_table",
    "json_value",
    "lateral",
    "leading",
    "least",
    "left",
    "like",
    "limit",
    "localtime",
    "localtimestamp",
    "merge_action",
    "national",
    "natural",
    "nchar",
    "none",
    "normalize",
    "not",
    "notnull",
    "null",
    "nullif",
    "numeric",
    "offset",
    "on",
    "only",
    "or",
    "order",
    "out",
    "outer",
    "overlaps",
    "overlay",
    "placing",
    "position",
    "precision",
    "primary",
    "real",
    "references",
    "returning",
    "right",
    "row",
    "select",
    "session_user",
    "setof",
    "similar",
    "smallint",
    "some",
    "substring",
    "symmetric",
    "system_user",
    "table",
    "tablesample",
    "then",
    "time",
    "timestamp",
    "to",
    "trailing",
    "treat",
    "trim",
    "true",
    "union",
    "unique",
    "user",
    "using",
    "values",
    "varchar",
    "variadic",
    "verbose",
    "when",
    "where",
    "window",
    "with",
    "xmlattributes",
    "xmlconcat",
    "xmlelement",
    "xmlexists",
    "xmlforest",
    "xmlnamespaces",
    "xmlparse",
    "xmlpi",
    "xmlroot",
    "xmlserialize",
    "xmltable",
];

/// True when `s` must be double-quoted to survive as a SQL
/// identifier, mirroring PG's `quote_identifier`: an unquoted
/// identifier must be non-empty, start with `[a-z_]`, contain only
/// `[a-z0-9_]`, and not collide with a non-unreserved keyword.
fn ident_needs_quotes(s: &str) -> bool {
    let mut chars = s.chars();
    let Some(first) = chars.next() else {
        return true; // empty → always quote ("")
    };
    if !(first.is_ascii_lowercase() || first == '_') {
        return true;
    }
    if s.chars()
        .any(|c| !(c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_'))
    {
        return true;
    }
    // All-lowercase identifier-safe text: quote iff it is a keyword
    // PG would otherwise reinterpret.
    PG_QUOTE_KEYWORDS.binary_search(&s).is_ok()
}

/// PG `quote_ident` / `quote_identifier`: return `s` unchanged when
/// it is a safe unquoted identifier, otherwise wrap it in double
/// quotes with embedded `"` doubled.
pub(super) fn pg_quote_ident(s: &str) -> String {
    if !ident_needs_quotes(s) {
        return s.to_string();
    }
    let mut out = String::with_capacity(s.len() + 2);
    out.push('"');
    for ch in s.chars() {
        if ch == '"' {
            out.push('"');
        }
        out.push(ch);
    }
    out.push('"');
    out
}

/// PG `quote_literal(text)`: wrap `s` in single quotes, doubling any
/// embedded single quote. When the string contains a backslash, PG
/// emits the `E'…'` escape-string form with backslashes doubled, so
/// the result stays a valid literal regardless of the reader's
/// `standard_conforming_strings` setting — e.g. `quote_literal('c:\p')`
/// → `E'c:\\p'`. This is the shared body for both `quote_literal` and
/// the non-null branch of `quote_nullable`.
pub(super) fn pg_quote_literal(s: &str) -> String {
    let has_backslash = s.contains('\\');
    let mut out = String::with_capacity(s.len() + 4);
    if has_backslash {
        out.push('E');
    }
    out.push('\'');
    for ch in s.chars() {
        match ch {
            '\'' => out.push_str("''"),
            '\\' => out.push_str("\\\\"),
            _ => out.push(ch),
        }
    }
    out.push('\'');
    out
}

pub(super) fn format_string(
    args: &[Value<'_>],
    style: &super::format::RenderStyle,
) -> Result<Value<'static>, EvalError> {
    if args.is_empty() {
        return Err(EvalError::TypeMismatch {
            detail: "format() takes at least 1 arg (format string)".into(),
        });
    }
    // v7.39 (round 611) — `format('%s/%s', s, id)` allocated TEN times a row
    // over 200k rows to build one string: the format string was cloned, each
    // conversion spec built two `String`s just to hold its digits, each
    // argument was cloned out of the slice, and each was then rendered into
    // another owned `String`. Only the result has to be built.
    let fmt: &str = match &args[0] {
        Value::Text(s) => s.as_ref(),
        Value::Null => return Ok(Value::Null),
        other => {
            return Err(EvalError::TypeMismatch {
                detail: format!(
                    "format(): first arg must be text, got {}",
                    crate::conversions::pg_type_name_for_error_opt(other.data_type())
                ),
            });
        }
    };
    let arg_values = &args[1..];
    // Sized from the format string plus a little for the substitutions: an
    // empty `String` reallocated its way up through 8 / 16 / 32 bytes for
    // every row.
    let mut out = String::with_capacity(fmt.len() + 16 * arg_values.len().max(1));
    let mut chars = fmt.chars().peekable();
    // Position cursor — next implicit arg picked when no `n$`
    // prefix is given. PG's format uses a 1-based cursor that
    // advances on each implicit-position spec.
    let mut implicit_cursor: usize = 0;
    while let Some(c) = chars.next() {
        if c != '%' {
            out.push(c);
            continue;
        }
        // Parse optional `n$` position prefix. Accumulated as a number
        // rather than buffered as text: the digits are either the position or
        // the width, and both are read back as one.
        let mut explicit_pos: Option<usize> = None;
        let mut digits: usize = 0;
        let mut ndigits = 0usize;
        let mut digits_overflowed = false;
        while let Some(&d) = chars.peek() {
            if d.is_ascii_digit() {
                match digits
                    .checked_mul(10)
                    .and_then(|n| n.checked_add(d as usize - '0' as usize))
                {
                    Some(n) => digits = n,
                    None => digits_overflowed = true,
                }
                ndigits += 1;
                chars.next();
            } else {
                break;
            }
        }
        // PG conversion spec: `% [n$] [-] [width] type`. The pre-`$` digits are
        // the arg position; otherwise they are the field width.
        let mut have_width = false;
        let mut width_digits: usize = 0;
        if ndigits > 0 && matches!(chars.peek(), Some(&'$')) {
            chars.next(); // consume `$`
            if digits_overflowed {
                return Err(EvalError::TypeMismatch {
                    detail: String::from("format(): invalid arg position"),
                });
            }
            explicit_pos = Some(digits);
        } else if ndigits > 0 {
            have_width = true;
            width_digits = if digits_overflowed { 0 } else { digits };
        }
        // `-` flag (left-justify) then width — but only when the width wasn't
        // already captured as the pre-`$` digits above. The width may be a
        // literal number or `*`, which pulls it from the next argument (PG:
        // `format('%*s', 5, 'x')` right-pads 'x' to width 5).
        let mut left_justify = false;
        let mut width_from_arg = false;
        if !have_width {
            if matches!(chars.peek(), Some(&'-')) {
                chars.next();
                left_justify = true;
            }
            if matches!(chars.peek(), Some(&'*')) {
                chars.next();
                width_from_arg = true;
            } else {
                while let Some(&d) = chars.peek() {
                    if d.is_ascii_digit() {
                        width_digits = width_digits
                            .saturating_mul(10)
                            .saturating_add(d as usize - '0' as usize);
                        chars.next();
                    } else {
                        break;
                    }
                }
            }
        }
        let width: usize = if width_from_arg {
            // The `*` consumes one implicit argument as the width. PG: a
            // negative width means left-justify with the absolute width.
            let w_arg = arg_values.get(implicit_cursor);
            implicit_cursor += 1;
            let w = match w_arg {
                Some(Value::SmallInt(n)) => i64::from(*n),
                Some(Value::Int(n)) => i64::from(*n),
                Some(Value::BigInt(n)) => *n,
                _ => 0,
            };
            if w < 0 {
                left_justify = true;
            }
            #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
            let uw = w.unsigned_abs() as usize;
            uw
        } else {
            width_digits
        };
        // Specifier character.
        let spec = match chars.next() {
            Some(c) => c,
            None => {
                return Err(EvalError::TypeMismatch {
                    detail: "format(): trailing `%` with no specifier".into(),
                });
            }
        };
        if spec == '%' {
            out.push('%');
            continue;
        }
        let arg_index = match explicit_pos {
            Some(p) => p.saturating_sub(1),
            None => {
                let i = implicit_cursor;
                implicit_cursor += 1;
                i
            }
        };
        let arg = arg_values.get(arg_index);
        // Build the converted text for this conversion, then apply the field
        // width (minimum width; PG never truncates, pads with spaces).
        let converted: alloc::borrow::Cow<'_, str> = match spec {
            's' => match arg {
                // PG: NULL renders as empty for %s.
                None | Some(Value::Null) => alloc::borrow::Cow::Borrowed(""),
                // Already the text it renders as, so no copy is needed.
                Some(Value::Text(s)) => alloc::borrow::Cow::Borrowed(s.as_ref()),
                Some(v) => alloc::borrow::Cow::Owned(value_to_format_text_styled(v, style)),
            },
            'I' => match arg {
                None | Some(Value::Null) => {
                    return Err(EvalError::TypeMismatch {
                        detail: "format(): NULL is not a valid identifier (%I)".into(),
                    });
                }
                Some(v) => alloc::borrow::Cow::Owned(pg_quote_ident(&value_to_format_text_styled(
                    v, style,
                ))),
            },
            'L' => match arg {
                None | Some(Value::Null) => alloc::borrow::Cow::Borrowed("NULL"),
                Some(v) => {
                    let s = value_to_format_text_styled(v, style);
                    let mut q = String::with_capacity(s.len() + 2);
                    q.push('\'');
                    for ch in s.chars() {
                        if ch == '\'' {
                            q.push('\'');
                        }
                        q.push(ch);
                    }
                    q.push('\'');
                    alloc::borrow::Cow::Owned(q)
                }
            },
            other => {
                return Err(EvalError::TypeMismatch {
                    detail: format!(
                        "format(): unknown specifier '%{other}' \
                         (supports %s %I %L %%)"
                    ),
                });
            }
        };
        let vis_len = converted.chars().count();
        if vis_len < width {
            let pad = " ".repeat(width - vis_len);
            if left_justify {
                out.push_str(&converted);
                out.push_str(&pad);
            } else {
                out.push_str(&pad);
                out.push_str(&converted);
            }
        } else {
            out.push_str(&converted);
        }
    }
    Ok(Value::text(out))
}

/// Helper: render a Value as text for format()'s %s / %I / %L
/// payload. Reuses the regular text-coercion table.
/// v7.17.0 Phase 3.P0-31 — map a `Value` to the canonical PG
/// type-name string returned by `pg_typeof`. Lowercase, matches
/// what real PostgreSQL emits (NOT SPG's UPPERCASE Display shape).
pub(super) fn pg_typeof_name(v: &Value) -> &'static str {
    match v {
        Value::SmallInt(_) => "smallint",
        Value::Int(_) => "integer",
        Value::BigInt(_) => "bigint",
        Value::Float(_) => "double precision",
        Value::Real(_) => "real",
        Value::Text(_) => "text",
        Value::Bool(_) => "boolean",
        Value::Vector(_) | Value::Sq8Vector(_) | Value::HalfVector(_) => "vector",
        Value::Numeric { .. } | Value::NumericBig(_) => "numeric",
        Value::Date(_) => "date",
        Value::Time(_) => "time without time zone",
        // v7.39 (round 755, F31-B6) — fell to the "unknown" arm, so
        // `pg_typeof(current_time)` had no name even once the keyword
        // produced a real TIMETZ.
        Value::TimeTz { .. } => "time with time zone",
        Value::Timestamp(_) => "timestamp without time zone",
        Value::Interval { .. } => "interval",
        Value::Json(_) => {
            // SPG carries JSON and JSONB in the same Value::Json
            // variant; without a column ty hint we cannot tell
            // them apart at value level. Return "json" as the
            // conservative answer (PG's pg_typeof on a literal
            // `'{}'::json` returns "json"; the jsonb case is
            // covered when an explicit ::jsonb cast lands as
            // Value::Json too — see below override at call site).
            //
            // The eval-arm above for pg_typeof handles the
            // disambiguation via Expr-shape probing.
            "json"
        }
        Value::Bytes(_) => "bytea",
        Value::TextArray(_) => "text[]",
        Value::IntArray(_) => "integer[]",
        Value::BigIntArray(_) => "bigint[]",
        // v7.38 (read01) — the constructor now unifies numeric-ladder element
        // types (`ARRAY[1, 2.5]` → numeric[], `ARRAY[1, 2.5::float8]` →
        // double precision[]); report them instead of falling to "unknown".
        Value::SmallIntArray(_) => "smallint[]",
        Value::NumericArray(_) => "numeric[]",
        Value::FloatArray(_) => "double precision[]",
        // v7.39 (read01 round 73) — the 2-D forms. Every 1-D element type already
        // had a name (below); the multidimensional ones read as "unknown", which
        // drivers take for "no type". PG reports the same name however many
        // dimensions an array has — `integer[]`, not `integer[][]`.
        Value::IntArray2D(_) => "integer[]",
        Value::BigIntArray2D(_) => "bigint[]",
        Value::TextArray2D(_) => "text[]",
        Value::BoolArray2D(_) => "boolean[]",
        Value::TsVector(_) => "tsvector",
        Value::TsQuery(_) => "tsquery",
        Value::Uuid(_) => "uuid",
        // SPG carries both `bit` and `bit varying` in one BitString
        // variant (no fixed-vs-varying tag), so it reports the varying
        // spelling — the same as its data_type() — rather than "unknown".
        // A `bit` literal reads as "bit varying" here vs PG's "bit"; that
        // needs a bit-vs-varbit value tag SPG doesn't yet keep.
        Value::BitString { .. } => "bit varying",
        // v7.38 (read01) — the rest of SPG's scalar value types. These all
        // reported "unknown" before, which drivers and ORMs read as "no type".
        Value::Money(_) => "money",
        Value::Inet { .. } => "inet",
        Value::Cidr { .. } => "cidr",
        Value::Macaddr(_) => "macaddr",
        Value::Macaddr8(_) => "macaddr8",
        Value::PgLsn(_) => "pg_lsn",
        Value::RegClass(..) => "regclass",
        Value::Tid(..) => "tid",
        Value::Xid(_) => "xid",
        Value::Cid(_) => "cid",
        // v7.39 (round 342, V65) — one carrier, two PG types: a
        // `regprocedure` renders WITH its argument list (`f(integer)`),
        // a `regproc` never does. PG reports them apart, so SPG does.
        // v7.39 (round 648) — `pg_typeof('text'::regtype)` said `text`
        // while the value was a plain Text; PG says `regtype`.
        Value::RegType(..) => "regtype",
        Value::RegProc(_, name) => {
            if name.contains('(') {
                "regprocedure"
            } else {
                "regproc"
            }
        }
        Value::Xml(_) => "xml",
        Value::Hstore(_) => "hstore",
        Value::BpChar(_) => "character",
        // An anonymous `row(...)` / whole-row reference is PG's `record`.
        Value::Composite(_) => "record",
        Value::Point(_) => "point",
        Value::Lseg(..) => "lseg",
        Value::Path { .. } => "path",
        Value::PgBox(..) => "box",
        Value::Polygon(_) => "polygon",
        Value::Line { .. } => "line",
        Value::Circle { .. } => "circle",
        // v7.39 (round 256) — the multirange types reported "unknown".
        Value::Multirange { kind, .. } => match kind {
            spg_storage::RangeKind::Int4 => "int4multirange",
            spg_storage::RangeKind::Int8 => "int8multirange",
            spg_storage::RangeKind::Num => "nummultirange",
            spg_storage::RangeKind::Ts => "tsmultirange",
            spg_storage::RangeKind::TsTz => "tstzmultirange",
            spg_storage::RangeKind::Date => "datemultirange",
        },
        Value::Range { kind, .. } => match kind {
            spg_storage::RangeKind::Int4 => "int4range",
            spg_storage::RangeKind::Int8 => "int8range",
            spg_storage::RangeKind::Num => "numrange",
            spg_storage::RangeKind::Ts => "tsrange",
            spg_storage::RangeKind::TsTz => "tstzrange",
            spg_storage::RangeKind::Date => "daterange",
        },
        Value::BoolArray(_) => "boolean[]",
        Value::DateArray(_) => "date[]",
        Value::TimestampArray(_) => "timestamp without time zone[]",
        Value::TimestamptzArray(_) => "timestamp with time zone[]",
        Value::IntervalArray(_) => "interval[]",
        Value::UuidArray(_) => "uuid[]",
        Value::JsonArray(_) => "json[]",
        Value::JsonbArray(_) => "jsonb[]",
        Value::BytesArray(_) => "bytea[]",
        Value::VarcharArray(_) => "character varying[]",
        Value::CharArray(_) => "character[]",
        Value::MoneyArray(_) => "money[]",
        Value::Null => "unknown",
        // Value is #[non_exhaustive]; future variants land here
        // until the table is updated.
        _ => "unknown",
    }
}

pub(super) fn value_to_format_text(v: &Value) -> String {
    value_to_format_text_styled(v, &super::format::RenderStyle::default())
}

/// v7.39 (round 608) — the same rendering, BORROWING when the value already
/// is the text it renders as.
///
/// Every string function reached its operands through the owning form, so a
/// `TEXT` column was copied into a fresh `String` before anything read it —
/// `strpos(s, '234')` returns an INTEGER and still allocated 5.5 times a row
/// over 200k rows, against 1 for `upper(s)` (which allocates only its
/// result) and none for `length(s)`. Two of those were the operand copies.
/// v7.39 (round 612) — the styled render, borrowing when the value already
/// is the text it renders as. `concat` / `concat_ws` rendered every argument
/// into an owned `String` only to push it into the answer and drop it.
pub(super) fn value_to_format_text_styled_ref<'a>(
    v: &'a Value<'a>,
    style: &super::format::RenderStyle,
) -> alloc::borrow::Cow<'a, str> {
    match v {
        Value::Text(s) | Value::Json(s) => alloc::borrow::Cow::Borrowed(s.as_ref()),
        other => alloc::borrow::Cow::Owned(value_to_format_text_styled(other, style)),
    }
}

pub(super) fn value_to_format_text_ref<'a>(v: &'a Value<'a>) -> alloc::borrow::Cow<'a, str> {
    match v {
        Value::Text(s) | Value::Json(s) => alloc::borrow::Cow::Borrowed(s.as_ref()),
        // BpChar renders with its declared padding here, as it did before.
        other => alloc::borrow::Cow::Owned(value_to_format_text(other)),
    }
}

/// v7.39 (GUC knife 4) — the styled variant: concat / concat_ws /
/// format(%s) textify via PG's out-functions, which honour DateStyle /
/// IntervalStyle / extra_float_digits.
pub(super) fn value_to_format_text_styled(v: &Value, style: &super::format::RenderStyle) -> String {
    match v {
        Value::Text(s) | Value::Json(s) => s.to_string(),
        Value::SmallInt(n) => n.to_string(),
        Value::Int(n) => n.to_string(),
        Value::BigInt(n) => n.to_string(),
        Value::Float(x) => super::format::format_float_styled(*x, style),
        // PG renders numeric in concat/format/text-coercion as its exact
        // decimal (`x || 2.5::numeric` → `x2.5`), not a debug dump.
        Value::Numeric {
            scaled,
            scale,
            kind,
        } => super::format::format_numeric_kind(*kind, *scaled, *scale),
        Value::Bool(b) => {
            if *b {
                "t".into()
            } else {
                "f".into()
            }
        }
        Value::Null => String::new(),
        // v7.39 (round 368, M20 P3) — a binary string in the MySQL dialect
        // reads as its raw bytes (latin-1): `CONCAT(0x41,'B')` is 'AB', not
        // PG's `\x41B`. The PG dialect keeps the `\x…` hex form below.
        Value::Bytes(b) if style.mysql => b.iter().map(|&x| x as char).collect(),
        // Every other type (Date / Timestamp / Interval / arrays / Bytea /
        // UUID / Time / Money / Range / Hstore / 2D arrays / …) renders via
        // the canonical value→text renderer — the same PG-faithful form SELECT
        // and the wire layer emit — rather than leaking a Rust debug dump.
        other => super::values::value_to_text_styled(other, style),
    }
}

/// Coerce a numeric operand to f64 for the `to_char(number, fmt)`
/// form. Returns `None` for non-numeric values so the date/timestamp
/// path takes over.
fn numeric_value_for_to_char(v: &Value) -> Option<f64> {
    match v {
        Value::SmallInt(n) => Some(f64::from(*n)),
        Value::Int(n) => Some(f64::from(*n)),
        #[allow(clippy::cast_precision_loss)]
        Value::BigInt(n) => Some(*n as f64),
        Value::Float(x) => Some(*x),
        // v7.39 (round 662) — `real` (float4). `float8` was here and its
        // single-precision sibling was not, so `to_char(1.5::real, '9.9')`
        // answered "needs a number, DATE or TIMESTAMP, got real" where PG
        // renders ` 1.5`. C09 measured it as a missing overload; it is one
        // arm of one match.
        //
        // The route matters, and PG's is `real -> numeric`, NOT
        // `real -> float8`: asked directly, `12345.678::real::numeric` is
        // `12345.7` while `12345.678::real::float8` is `12345.677734375`,
        // so the two paths format as `12345.7` and `12345.68`. Going
        // through `f64::from` — the obvious spelling — takes the wrong one.
        // Six significant digits — PG's `FLT_DIG`, the same rule the
        // `real -> numeric` cast follows (round 662 fixed that too; this
        // overload is what exposed it).
        Value::Real(x) => alloc::format!("{x:.5e}").parse::<f64>().ok(),
        #[allow(clippy::cast_precision_loss)]
        Value::Numeric { scaled, scale, .. } => Some(
            crate::eval::format_numeric(*scaled, *scale)
                .parse()
                .unwrap_or(f64::NAN),
        ),
        _ => None,
    }
}

/// A PG-faithful subset of the numeric `to_char` format. Supported
/// tokens: digit slots `9` (leading-zero-blanked) and `0`
/// (zero-forced); the decimal separators `.` / `D`; the group
/// separators `,` / `G`; the explicit sign `S`; and the `FM`
/// fill-mode prefix that drops padding and trims trailing fraction
/// zeros. Matches PG on sign placement (spaces pad to the far left,
/// the sign sits immediately left of the first digit), leading-zero
/// suppression for values < 1, and `#` field-overflow.
///
/// Unsupported (rendered as literals / ignored, documented as
/// known-limitations): `MI` / `PR` / `SG` alternate signs, `RN`
/// roman numerals, `EEEE` scientific, `V` scale, `TH` / `th`
/// ordinals, currency `L` / `$`, and a trailing (rather than
/// leading) `S`.
/// `to_char(interval, fmt)`. Unlike the timestamp form, interval fields carry
/// their own sign and don't wrap: `HH24` of `interval '25 hours'` is `25`, not
/// `01`. `MM`/`YYYY` come straight from the months component (14 months →
/// `0001-02`); the time part decomposes into `HH24:MI:SS`. Calendar-only codes
/// (day/month names, DOW, week, Julian) are meaningless for an interval and
/// pass through as literals rather than erroring. Known cosmetic divergence:
/// PG renders a negative `DD` field unpadded (`-1`, not `-01`); we zero-pad
/// every numeric field consistently after the sign.
fn to_char_interval(months: i64, days: i64, micros: i128, fmt: &str) -> String {
    use core::fmt::Write as _;
    let yyyy = months / 12;
    let mm = months % 12;
    let hh24 = i64::try_from(micros / 3_600_000_000).unwrap_or(0);
    let mi = i64::try_from((micros / 60_000_000) % 60).unwrap_or(0);
    let ss = i64::try_from((micros / 1_000_000) % 60).unwrap_or(0);
    let ms = i64::try_from((micros / 1_000) % 1_000).unwrap_or(0);
    let us = i64::try_from(micros % 1_000_000).unwrap_or(0);
    let hh12 = match hh24.rem_euclid(12) {
        0 => 12,
        x => x,
    };
    let ampm = if hh24.rem_euclid(24) < 12 { "AM" } else { "PM" };
    // Sign-aware zero pad: PG renders `-2` hours as `-02`.
    let pad = |v: i64, w: usize, fm: bool| -> String {
        if fm {
            alloc::format!("{v}")
        } else if v < 0 {
            alloc::format!("-{:0width$}", -v, width = w)
        } else {
            alloc::format!("{:0width$}", v, width = w)
        }
    };
    let mut out = String::with_capacity(fmt.len() + 8);
    let bytes = fmt.as_bytes();
    let mut i = 0;
    let mut fm = false;
    while i < bytes.len() {
        let rest = &bytes[i..];
        if rest.starts_with(b"FM") {
            fm = true;
            i += 2;
            continue;
        }
        if bytes[i] == b'"' {
            i += 1;
            let start = i;
            while i < bytes.len() && bytes[i] != b'"' {
                i += 1;
            }
            out.push_str(&fmt[start..i]);
            if i < bytes.len() {
                i += 1;
            }
            continue;
        }
        let (frag, consumed): (String, usize) = if rest.starts_with(b"YYYY") {
            (pad(yyyy, 4, fm), 4)
        } else if rest.starts_with(b"YYY") {
            // v — trailing-N-digit year forms (PG: interval '1 year' →
            // YYY '001', YY '01', Y '1'; YY of 123 years → '23').
            (pad(yyyy % 1000, 3, fm), 3)
        } else if rest.starts_with(b"YY") {
            (pad(yyyy % 100, 2, fm), 2)
        } else if rest.starts_with(b"Y") {
            (pad(yyyy % 10, 1, fm), 1)
        } else if rest.starts_with(b"HH24") {
            (pad(hh24, 2, fm), 4)
        } else if rest.starts_with(b"HH12") {
            (pad(hh12, 2, fm), 4)
        } else if rest.starts_with(b"US") {
            (pad(us, 6, fm), 2)
        } else if rest.starts_with(b"MS") {
            (pad(ms, 3, fm), 2)
        } else if rest.starts_with(b"HH") {
            (pad(hh12, 2, fm), 2)
        } else if rest.starts_with(b"MI") {
            (pad(mi, 2, fm), 2)
        } else if rest.starts_with(b"SSSS") {
            // v7.37 — seconds of the time-of-day part; must precede `SS`.
            (alloc::format!("{}", hh24 * 3600 + mi * 60 + ss), 4)
        } else if rest.starts_with(b"FF") && rest.get(2).is_some_and(u8::is_ascii_digit) {
            // v7.37 — `FF1`..`FF6`: first N digits of the fractional second.
            let n = usize::from(rest[2] - b'0');
            let frac = alloc::format!("{us:06}");
            (frac[..n.min(6)].to_string(), 3)
        } else if rest.starts_with(b"SS") {
            (pad(ss, 2, fm), 2)
        } else if rest.starts_with(b"DD") {
            (pad(days, 2, fm), 2)
        } else if rest.starts_with(b"MM") {
            (pad(mm, 2, fm), 2)
        } else if rest.starts_with(b"AM") || rest.starts_with(b"PM") {
            (ampm.to_string(), 2)
        } else {
            // Any other byte (punctuation, spaces, calendar-name letters)
            // passes through literally.
            let mut buf = String::new();
            let _ = write!(buf, "{}", bytes[i] as char);
            (buf, 1)
        };
        out.push_str(&frag);
        fm = false;
        i += consumed;
    }
    out
}

/// PG `to_char(n, 'RN')` — Roman numerals. Valid for 1..=3999; anything else
/// (including 0 and negatives) renders as 15 `#`. Without `FM` the result is
/// right-justified in a 15-character field; `FM` trims it.
/// Format `x` with exactly `d` fractional digits (round-half-away-from-zero),
/// no sign. `d == 0` yields no decimal point.
fn format_fixed_abs(x: f64, d: usize) -> String {
    #[allow(clippy::cast_possible_truncation, clippy::cast_precision_loss)]
    let pow = libm::pow(10.0, d as f64);
    #[allow(clippy::cast_possible_truncation)]
    let scaled = libm::round(x.abs() * pow) as i128;
    if d == 0 {
        return alloc::format!("{scaled}");
    }
    let unit = 10_i128.pow(d as u32);
    let ip = scaled / unit;
    let fp = (scaled % unit).abs();
    alloc::format!("{ip}.{fp:0width$}", width = d)
}

/// PG `V` scale: multiply by 10^(digit count after `V`) and render as an
/// integer (the `V` drops the decimal point). Field width = all digit slots
/// (before + after V) plus a sign column; non-FM left-pads with blanks.
fn to_char_v_scale(n: f64, before: &str, after: &str, fill_mode: bool) -> String {
    let count_slots = |s: &str| s.chars().filter(|c| matches!(c, '9' | '0')).count();
    let vdigits = count_slots(after);
    let total_slots = count_slots(before) + vdigits;
    #[allow(clippy::cast_possible_truncation, clippy::cast_precision_loss)]
    let scaled = libm::round(n.abs() * libm::pow(10.0, vdigits as f64)) as i128;
    let neg = n < 0.0 && scaled != 0;
    // v7.39 (round 243) — a value wider than the slots OVERFLOWS: every
    // digit slot renders `#` and the pattern's literal characters (spaces
    // in `V99 999`) stay put, exactly as the plain path already did. SPG
    // used to print the scaled number full-width.
    // v7.39 (round 632, F33) — no digit slots on either side of the `V`
    // means no number and no sign column, the same rule the main path
    // learned in round 631. A lone `V` answered a space; PG answers
    // nothing. Whatever literals the picture carries still come through.
    if total_slots == 0 {
        return alloc::format!("{before}{after}");
    }
    let digits = alloc::format!("{scaled}").len();
    if digits > total_slots {
        let mut out = String::new();
        if !fill_mode {
            out.push(' ');
        }
        for c in before.chars().chain(after.chars()) {
            out.push(if matches!(c, '9' | '0') { '#' } else { c });
        }
        return out;
    }
    let core = if neg {
        alloc::format!("-{scaled}")
    } else {
        alloc::format!("{scaled}")
    };
    if fill_mode {
        core
    } else {
        left_pad_spaces(&core, total_slots + 1)
    }
}

/// PG `EEEE` scientific notation. `mant_fmt` is the format preceding `EEEE`
/// (e.g. `9.9`); its post-decimal digit count sets the mantissa precision.
/// Mantissa is normalised to one leading digit; rounding is not
/// re-normalised (PG: `9.99` with `9.9EEEE` → `10.0e+00`). Exponent is a
/// signed two-digit field. Non-FM keeps a leading blank for the sign.
fn to_char_scientific(n: f64, mant_fmt: &str, fill_mode: bool) -> String {
    let neg = n < 0.0 && n != 0.0;
    let a = n.abs();
    let exp: i32 = if a == 0.0 {
        0
    } else {
        #[allow(clippy::cast_possible_truncation)]
        {
            libm::floor(libm::log10(a)) as i32
        }
    };
    let frac_digits = mant_fmt.find(['.', 'D', 'd']).map_or(0, |dot| {
        mant_fmt[dot + 1..]
            .chars()
            .filter(|c| matches!(c, '9' | '0'))
            .count()
    });
    let mantissa = if a == 0.0 {
        0.0
    } else {
        a / libm::pow(10.0, f64::from(exp))
    };
    let mant_str = format_fixed_abs(mantissa, frac_digits);
    let sign = if neg {
        "-"
    } else if fill_mode {
        ""
    } else {
        " "
    };
    let esign = if exp < 0 { '-' } else { '+' };
    alloc::format!("{sign}{mant_str}e{esign}{:02}", exp.abs())
}

fn to_char_roman(n: f64, fill_mode: bool) -> String {
    #[allow(clippy::cast_possible_truncation)]
    let v = libm::round(n) as i64;
    if !(1..=3999).contains(&v) {
        return core::iter::repeat_n('#', 15).collect();
    }
    const VALS: [(i64, &str); 13] = [
        (1000, "M"),
        (900, "CM"),
        (500, "D"),
        (400, "CD"),
        (100, "C"),
        (90, "XC"),
        (50, "L"),
        (40, "XL"),
        (10, "X"),
        (9, "IX"),
        (5, "V"),
        (4, "IV"),
        (1, "I"),
    ];
    let mut out = String::new();
    let mut rem = v;
    for (val, sym) in VALS {
        while rem >= val {
            out.push_str(sym);
            rem -= val;
        }
    }
    if fill_mode {
        out
    } else {
        alloc::format!("{out:>15}")
    }
}

/// v7.38 (read01, T23) — the numeric `EEEE` scientific marker has two PG
/// placement rules, both rejected at parse time (before any output):
///   * combining `EEEE` with a sign/fill/scale/roman flag
///     (`FM`,`S`,`MI`,`PL`,`SG`,`PR`,`RN`,`V`,`B`) → "incompatible with
///     other formats";
///   * any further *format token* after `EEEE` (a digit `9`/`0`, a
///     decimal/group `.`/`,`/`D`/`G`, a currency `L`, a scale `V`, a sign
///     flag, or a second `EEEE`) → "EEEE must be the last pattern used".
/// Plain literals after it — spaces, `$`, or `"…"`-quoted text — are fine.
/// Quoted spans and `\`-escaped characters are literals, so we scan a
/// de-quoted copy of the mask; the incompatible check wins when a flag
/// precedes `EEEE` and a token also follows it (PG's left-to-right pass).
fn check_eeee_format(fmt: &str) -> Result<(), EvalError> {
    // Build the significant (non-literal) characters, uppercased, dropping
    // `"…"` quoted spans and `\`-escaped characters the way PG's lexer does.
    let mut sig = String::with_capacity(fmt.len());
    let mut chars = fmt.chars();
    while let Some(c) = chars.next() {
        match c {
            '\\' => {
                chars.next();
            }
            '"' => {
                for q in chars.by_ref() {
                    if q == '"' {
                        break;
                    }
                }
            }
            _ => sig.push(c.to_ascii_uppercase()),
        }
    }
    let Some(epos) = sig.find("EEEE") else {
        return Ok(());
    };
    let before = &sig[..epos];
    if ["FM", "MI", "PL", "SG", "PR", "RN"]
        .iter()
        .any(|f| before.contains(f))
        || before.contains(['S', 'V', 'B'])
    {
        return Err(EvalError::TypeMismatch {
            detail: String::from(
                "\"EEEE\" is incompatible with other formats: \"EEEE\" may \
                 only be used together with digit and decimal point patterns",
            ),
        });
    }
    let after = &sig[epos + 4..];
    if after.contains([
        '9', '0', '.', ',', 'D', 'G', 'L', 'V', 'S', 'M', 'I', 'P', 'R', 'N', 'B', 'F', 'H', 'E',
    ]) {
        return Err(EvalError::TypeMismatch {
            detail: String::from("\"EEEE\" must be the last pattern used"),
        });
    }
    Ok(())
}

// v7.38 (read01 P6.01) — `exact` carries the input's exact (scaled, scale)
// when it came in as `numeric`, so the digit-slot path can build the value
// from integer arithmetic instead of the lossy f64 `n`. `n` is still used by
// the RN / EEEE / V paths (roman / scientific / V-scale), which are inherently
// float-shaped, and as the fallback when the exact form overflows i128.
/// v7.39 (round 669, F33) — returns `Result` because PG REFUSES two
/// degenerate pictures that SPG used to answer, and refusing needs a
/// channel this function did not have.
///
/// Measured against PG18: `to_char(1234, 'th')` is `"." is not a number`
/// (an ordinal suffix with no digit position before it), and
/// `to_char(1234.5, 'SS9999')` — or any picture with two `S` — is
/// `cannot use "S" twice`. Both answered here.
///
/// The rest of F33's ledger entry did not survive re-measurement. It
/// recorded 56 of 104 single-letter shapes and 13 of 24 keyword shapes as
/// divergent; today it is 2 and 4, and three of those six are the `L`
/// currency symbol, which is not a defect at all — the oracle container
/// runs `lc_monetary = en_US.utf8` while SPG advertises `C`, and PG under
/// `SET lc_monetary='C'` answers byte-for-byte what SPG does.
fn to_char_numeric(n: f64, exact: Option<(i128, u16)>, fmt: &str) -> Result<String, EvalError> {
    let fill_mode = fmt.len() >= 2 && fmt[..2].eq_ignore_ascii_case("FM");
    let pat = if fill_mode { &fmt[2..] } else { fmt };

    // Two shapes PG rejects outright, checked before anything is rendered.
    let upper = pat.to_ascii_uppercase();
    if upper.matches('S').count() > 1 {
        return Err(EvalError::TypeMismatch {
            detail: "cannot use \"S\" twice".into(),
        });
    }
    // An ordinal suffix needs a digit position ahead of it. `9TH` is fine;
    // a bare `TH` has nothing to be the ordinal OF, and PG reports that as
    // the decimal point failing to be a number.
    if (upper == "TH" || upper == "RD" || upper == "ND" || upper == "ST")
        && !pat.chars().any(|c| c.is_ascii_digit())
    {
        return Err(EvalError::TypeMismatch {
            detail: "\".\" is not a number".into(),
        });
    }
    // v7.39 (round 243) — characters with no meaning in a number picture
    // print AS THEMSELVES in PG (`XYZ999` → `XYZ 123`); SPG dropped them.
    // Peel a leading / trailing run of letters outside the template
    // alphabet and re-attach it around the rendered body. (Literals in the
    // MIDDLE of the picture remain a recorded residual.)
    // v7.39 (round 627/628, F33) — whether a letter is part of the picture
    // is a question about the POSITION, not the character.
    //
    // The predicate this replaces asked it per character, with `E R N T H P
    // M I F` in the template alphabet because they appear inside `EEEE`
    // `RN` `TH` `PL`/`PR` `MI` `FM`. But PG matches keywords left to right,
    // longest first: a lone `M` is a literal and `MI` is the minus column,
    // a lone `P` is a literal and `PL` is the plus column. Asking per
    // character cannot tell them apart, so every one of those letters was
    // swallowed on its own — `to_char(1,'MON')` answered a single space
    // where PG answers `MON`, and `to_char(1,'HH')` likewise. Measured over
    // the alphabet in both placements, 56 of 104 shapes differed.
    //
    // Recorded and still open: `B` and `C` are picture elements in PG
    // (consumed, producing nothing) and are literals here, so
    // `to_char(1,'abc')` is `abc` where PG says `a`. Adding them to the
    // scanner without teaching the body renderer what they mean would move
    // the wrong answer rather than remove it.
    let keyword_len_at = |rest: &str| -> Option<usize> {
        const KW4: [&str; 1] = ["EEEE"];
        const KW2: [&str; 7] = ["FM", "PL", "PR", "RN", "TH", "SG", "MI"];
        if rest.len() >= 4 && KW4.iter().any(|k| rest[..4].eq_ignore_ascii_case(k)) {
            return Some(4);
        }
        if rest.len() >= 2 && KW2.iter().any(|k| rest[..2].eq_ignore_ascii_case(k)) {
            return Some(2);
        }
        match rest.chars().next() {
            // v7.39 (round 629, F33) — `B` and `C` are picture elements, not
            // literals. PG consumes both: `C` is the ISO currency code,
            // empty in the C locale, and `B` blanks the integer digits when
            // the value is zero. SPG's blanking already agreed with PG —
            // `to_char(0,'B9999.99')` produced the right five spaces — it
            // simply echoed the `B` in front of them, because the literal
            // peel claimed it. Measured: `[B    0]` vs PG `[    0]`,
            // `[C 1234]` and `[ 1234C]` vs PG `[ 1234]` for both.
            Some(c)
                if matches!(
                    c.to_ascii_uppercase(),
                    'S' | 'L' | 'D' | 'G' | 'V' | 'B' | 'C'
                ) =>
            {
                Some(1)
            }
            Some(c) if c.is_ascii_digit() || matches!(c, '.' | ',' | '$' | '%') => Some(1),
            _ => None,
        }
    };
    // One left-to-right pass, longest match first, recording where the
    // picture's first element begins and where its last one ends. Asking
    // "does a keyword START here" while walking BACKWARDS is not the same
    // question and gets `MI` wrong (the `I` looks like a literal), which is
    // how the first cut of this scanner turned `MI` `RN` and `EEEE` into
    // echoed text.
    let mut first_kw: Option<usize> = None;
    let mut last_kw_end = 0usize;
    let mut scan = 0usize;
    while scan < pat.len() {
        if let Some(len) = keyword_len_at(&pat[scan..]) {
            if first_kw.is_none() {
                first_kw = Some(scan);
            }
            last_kw_end = scan + len;
            scan += len;
        } else {
            scan += pat[scan..].chars().next().map_or(1, char::len_utf8);
        }
    }
    let Some(first_kw) = first_kw else {
        // No picture element at all: PG echoes the pattern.
        return Ok(String::from(pat));
    };
    let mut lit_prefix_len = 0usize;
    while lit_prefix_len < first_kw {
        let Some(c) = pat[lit_prefix_len..].chars().next() else {
            break;
        };
        if !c.is_ascii_alphabetic() {
            break;
        }
        lit_prefix_len += c.len_utf8();
    }
    let mut lit_suffix_start = pat.len();
    while lit_suffix_start > last_kw_end {
        let prev = pat[..lit_suffix_start]
            .chars()
            .next_back()
            .expect("non-empty");
        if !prev.is_ascii_alphabetic() {
            break;
        }
        lit_suffix_start -= prev.len_utf8();
    }
    let lit_suffix_len = pat.len() - lit_suffix_start;
    // v7.39 (round 626, S05b/F29) — a pattern that is ALL literal.
    //
    // `to_char(1, 'YYYY')` panicked: every letter of `YYYY` is a literal in
    // the NUMERIC templates, so the prefix scan claimed all four bytes and
    // the suffix scan claimed all four too, leaving `&pat[4..0]` — "byte
    // range starts at 4 but ends at 0". It killed the connection, which is
    // what a client sending a date template to a number would have got.
    //
    // PG echoes such a pattern verbatim: `to_char(1,'YYYY')` is `YYYY`,
    // `to_char(1.5,'xyz')` is `xyz`, `to_char(1,'MON')` is `MON`. There is
    // no numeric body to render between a prefix and a suffix that are the
    // same four characters.
    if lit_prefix_len >= pat.len() {
        return Ok(String::from(pat));
    }
    if lit_prefix_len > 0 || lit_suffix_len > 0 {
        let prefix = &pat[..lit_prefix_len];
        let suffix = &pat[pat.len() - lit_suffix_len..];
        let inner = &pat[lit_prefix_len..pat.len() - lit_suffix_len];
        let inner_fmt = if fill_mode {
            alloc::format!("FM{inner}")
        } else {
            String::from(inner)
        };
        return Ok(alloc::format!(
            "{prefix}{}{suffix}",
            to_char_numeric(n, exact, &inner_fmt)?
        ));
    }
    // v7.39 (round 243) — a LEADING `PL` is its own column: `+` for a
    // non-negative value, a space otherwise, ahead of the normally
    // rendered body (PG: `PL9999.9` → `+ 1234.5` / ` -1234.5`).
    if pat.len() >= 2 && pat[..2].eq_ignore_ascii_case("PL") && !pat[2..].is_empty() {
        let rest = &pat[2..];
        let rest_fmt = if fill_mode {
            alloc::format!("FM{rest}")
        } else {
            String::from(rest)
        };
        let col = if n < 0.0 { " " } else { "+" };
        return Ok(alloc::format!(
            "{col}{}",
            to_char_numeric(n, exact, &rest_fmt)?
        ));
    }
    // `RN` / `rn`: Roman numerals (handled before the digit-slot machinery).
    if pat.eq_ignore_ascii_case("RN") {
        return Ok(to_char_roman(n, fill_mode));
    }
    // `EEEE`: scientific notation. The mantissa format is whatever precedes
    // `EEEE`; the digit count after its decimal sets the mantissa precision.
    if let Some(epos) = pat.to_ascii_uppercase().find("EEEE") {
        return Ok(to_char_scientific(n, &pat[..epos], fill_mode));
    }
    // `V`: scale — multiply by 10^(digits after V) and drop the decimal.
    if let Some(vpos) = pat.find(['V', 'v']) {
        return Ok(to_char_v_scale(
            n,
            &pat[..vpos],
            &pat[vpos + 1..],
            fill_mode,
        ));
    }
    // `PR` suffix: PG's accounting-negative notation — a negative value is
    // wrapped in angle brackets with no minus sign (`<1234.50>`), a
    // non-negative one gets a trailing space where the `>` would sit.
    let has_pr = pat.len() >= 2 && pat[pat.len() - 2..].eq_ignore_ascii_case("PR");
    let mut pat = if has_pr { &pat[..pat.len() - 2] } else { pat };
    // v7.37 — `TH` / `th` ordinal suffix and a trailing `%` literal. Both are
    // stripped here and re-applied post-pass (like PR), so the slot machinery
    // never sees them. `TH` (upper) → uppercase suffix; `th` → lowercase.
    let th_suffix: Option<bool> =
        if pat.len() >= 2 && pat[pat.len() - 2..].eq_ignore_ascii_case("TH") {
            let upper = pat.ends_with("TH");
            pat = &pat[..pat.len() - 2];
            Some(upper)
        } else {
            None
        };
    let has_pct = pat.ends_with('%');
    if has_pct {
        pat = &pat[..pat.len() - 1];
    }
    // v7.37 — leading `L` currency locale symbol (C locale → `$`). Stripped
    // here; the rest formats normally and `$` is prepended post-pass.
    // v7.38 (read01) — a leading literal `$` (`FM$9,999.00`) anchors the dollar
    // sign at the front too, matching PG (`$1,234.50`).
    // v7.39 (read01 formatting.c) — the currency symbol comes from the
    // locale: in the C locale PG's L is a single SPACE, while a literal
    // `$` in the picture stays a dollar sign.
    // v7.39 (round 628) — VERIFIED, after a round that changed it and had
    // to change it back. The bench oracle runs `lc_monetary = en_US.utf8`
    // and answers `$ 1` for `to_char(1,'L9')`; the SAME PG with
    // `SET lc_monetary = 'C'` answers `  1`. SPG reports `lc_monetary = C`,
    // so the space is what agrees with the locale it advertises. Measuring
    // the oracle without reading the GUC the feature depends on is how the
    // wrong conclusion got drawn.
    let has_locale_currency = pat.starts_with(['L', 'l']);
    let has_lit_currency = !has_locale_currency && pat.starts_with('$');
    if has_locale_currency || has_lit_currency {
        pat = &pat[1..];
    }
    // v7.39 (read01 formatting.c) — leading `SG` writes the sign itself
    // (always + or -, no blank column), like PG's NUM_SG action.
    let has_leading_sg = pat.len() >= 2 && pat[..2].eq_ignore_ascii_case("SG");
    if has_leading_sg {
        pat = &pat[2..];
    }
    // v7.37 — trailing sign / literal suffixes (stripped here, applied
    // post-pass; the sign moves out of the leading column). Mutually
    // exclusive by construction. `MI` = minus-if-negative, `PL` =
    // plus-if-positive, `SG` = always-signed, a lone trailing `S` = trailing
    // sign, `$` = literal currency.
    let ends_kw = |p: &str, kw: &str| p.len() >= 2 && p[p.len() - 2..].eq_ignore_ascii_case(kw);
    let has_mi = ends_kw(pat, "MI");
    if has_mi {
        pat = &pat[..pat.len() - 2];
    }
    let has_pl = !has_mi && ends_kw(pat, "PL");
    if has_pl {
        pat = &pat[..pat.len() - 2];
    }
    let has_sg = !has_mi && !has_pl && ends_kw(pat, "SG");
    if has_sg {
        pat = &pat[..pat.len() - 2];
    }
    let has_trailing_s = !has_sg
        && (pat.ends_with('S') || pat.ends_with('s'))
        && !pat.ends_with("SS")
        && !pat.ends_with("ss");
    if has_trailing_s {
        pat = &pat[..pat.len() - 1];
    }
    let has_dollar = pat.ends_with('$');
    if has_dollar {
        pat = &pat[..pat.len() - 1];
    }
    let trailing_sign = has_mi || has_pl || has_sg || has_trailing_s;
    let has_sign_tok = !trailing_sign && pat.chars().any(|c| c == 'S' || c == 's');

    // Split around the decimal separator ('.', 'D', or 'd').
    let dec_pos = pat
        .char_indices()
        .find(|(_, c)| *c == '.' || *c == 'D' || *c == 'd')
        .map(|(i, c)| (i, c.len_utf8()));
    let (int_pat, frac_pat, has_decimal) = match dec_pos {
        Some((i, w)) => (&pat[..i], &pat[i + w..], true),
        None => (pat, "", false),
    };

    let is_slot = |c: char| matches!(c, '9' | '0');
    let is_group = |c: char| matches!(c, ',' | 'G' | 'g');
    let int_slots = int_pat.chars().filter(|c| is_slot(*c)).count();
    let frac_digits = frac_pat.chars().filter(|c| is_slot(*c)).count();
    let has_group = int_pat.chars().any(is_group);
    // The field width reserved for the integer side plus one sign
    // column (PG keeps a slot for the sign in fixed width). MI / SG and a
    // trailing `S` position the sign at the end, so PG drops the reserved
    // leading column (`PL` and `$` keep it).
    // v7.39 (round 629, F33) — a picture with NO digit slots gets no sign
    // column either. PG answers `to_char(1,'L')` with a single space (the
    // `L` itself in the C locale) and `to_char(1,'B')` with nothing; SPG
    // answered two spaces and one, the extra being a column reserved for a
    // sign that has no number to sit beside. All twenty of the
    // single-letter shapes still differing came from this one place.
    //
    // A decimal separator counts as a numeric field even with no slots
    // around it: PG answers `to_char(1,'D')` with ` .`, so dropping the
    // column on `int_slots == 0 && frac_digits == 0` alone took that with
    // it (and `DAY`, whose `D` is the separator).
    // v7.39 (round 631, F33) — does this picture ask for a number at all?
    //
    // Digit slots, or a decimal separator, which is a numeric field even
    // with no slots around it. A picture that asks for none — `MI`, `PL`,
    // `L`, `B` on their own — prints no digits, reserves no sign column,
    // and is not an overflow when the value has digits that will not fit.
    let has_numeric_field = int_slots > 0 || frac_digits > 0 || has_decimal;
    let sign_col = usize::from(!(has_mi || has_sg || has_trailing_s) && has_numeric_field);
    let int_field_width = int_pat
        .chars()
        .filter(|c| is_slot(*c) || is_group(*c))
        .count()
        + sign_col;
    // Right-most integer slot char (units position) and left-most
    // `0` slot position from the right (units = 0).
    let int_slot_chars: alloc::vec::Vec<char> = int_pat.chars().filter(|c| is_slot(*c)).collect();
    let units_slot = int_slot_chars.last().copied().unwrap_or('9');
    // Force leading zeros up to (and including) the left-most `0`
    // slot: its distance from the units position sets the minimum
    // integer width. `009` → width 3, `990` → width 1.
    let zero_pad = int_slot_chars
        .iter()
        .position(|c| *c == '0')
        .map_or(0, |i| int_slot_chars.len() - i);

    // Round to the requested scale, split into integer / fraction. When the
    // input is exact numeric (P6.01), rescale it to `frac_digits` decimals in
    // pure i128 arithmetic so high-precision values keep every digit; only
    // fall back to the lossy f64 path for floats or on i128 overflow.
    let pow = 10_i128.pow(frac_digits as u32);
    #[allow(clippy::cast_possible_truncation)]
    let f64_scaled = || libm::round(n.abs() * pow as f64) as i128;
    let exact_scaled = exact.and_then(|(in_scaled, in_scale)| {
        let abs = in_scaled.unsigned_abs();
        let fd = u32::try_from(frac_digits).ok()?;
        let insc = u32::from(in_scale);
        let rescaled: u128 = if fd >= insc {
            10_u128
                .checked_pow(fd - insc)
                .and_then(|m| abs.checked_mul(m))?
        } else {
            // Drop excess fraction digits, rounding half away from zero.
            let divisor = 10_u128.checked_pow(insc - fd)?;
            (abs / divisor) + u128::from(abs % divisor >= divisor.div_ceil(2))
        };
        i128::try_from(rescaled).ok()
    });
    let (scaled, neg) = match exact_scaled {
        Some(s) => (s, exact.is_some_and(|(v, _)| v < 0) && s != 0),
        None => {
            let s = f64_scaled();
            (s, n < 0.0 && s != 0)
        }
    };
    let int_part = scaled / pow;
    let frac_part = scaled % pow;
    let value_is_zero = scaled == 0;
    let sign_str: &str = if has_pl && neg && has_numeric_field {
        // v7.39 (round 631, F33) — `PL` is a PLUS column, not a sign
        // column: it shows `+` for a non-negative value and a blank for a
        // negative one, and the minus goes to the leading position. PG
        // answers `-1 ` for `to_char(-1,'9PL')`; SPG answered ` 1-`,
        // treating PL like `SG`. Measured with and without digit slots.
        "-"
    } else if has_pr || trailing_sign {
        // PR and the trailing sign modes render the sign as a post-pass below.
        ""
    } else if neg {
        "-"
    } else if has_sign_tok {
        "+"
    } else {
        ""
    };

    // --- Field overflow: integer digits exceed the digit slots. ---
    let int_digit_len = if int_part == 0 {
        0
    } else {
        alloc::format!("{int_part}").len()
    };
    // v7.39 (round 630 diagnosed, 631 fixed) — a picture with no numeric
    // field is not an overflow, it is a picture that prints no number.
    //
    // `to_char(1,'MI')` used to take this branch — one integer digit
    // against zero slots — and return from inside it, before the sign
    // columns are applied at the end of the function, so the sign was
    // lost: PG answers ` ` and `-` for the two signs and SPG answered
    // nothing for either. Exempting the branch alone is NOT the fix and
    // was measured to be worse; the body has to go empty at the same time.
    if has_numeric_field && int_digit_len > int_slots {
        let mut core = String::new();
        core.push_str(sign_str);
        if has_group {
            // v7.39 (round 632) — the separators keep their places in an
            // overflowed field too: PG answers ` #,#` for
            // `to_char(1234.5,'9G9')`, not `  ##`.
            let mut seen_slot = false;
            for c in int_pat.chars() {
                match c {
                    '9' | '0' => {
                        core.push('#');
                        seen_slot = true;
                    }
                    // A separator with no slot to its LEFT is not between
                    // two groups: PG answers `  #` for `to_char(x,'G9')`,
                    // not ` ,#`.
                    ',' | 'G' | 'g' => core.push(if seen_slot { ',' } else { ' ' }),
                    _ => {}
                }
            }
        } else {
            for _ in 0..int_slots {
                core.push('#');
            }
        }
        let mut out = if fill_mode {
            core
        } else {
            left_pad_spaces(&core, int_field_width)
        };
        if has_decimal {
            out.push('.');
            for _ in 0..frac_digits {
                out.push('#');
            }
        }
        // v7.39 (round 628, F33) — the currency column belongs to the
        // picture, not to the value, so an overflowed body still carries
        // it: PG answers `$ #` for `to_char(1234.5,'L9')` under en_US and
        // `  #` under C. This return skipped the insertion at the end of
        // the function entirely, dropping the column either way.
        if has_locale_currency {
            out.insert(0, ' ');
        } else if has_lit_currency {
            out.insert(0, '$');
        }
        return Ok(out);
    }

    // --- Integer body (significant digits, no leading blanks). ---
    //
    // v7.39 (round 631) — with no numeric field there are no digits to
    // render. Round 630 exempted the overflow branch WITHOUT this and the
    // digits came out with nothing to sit in: `to_char(1,'B')` answered
    // `1`. Both halves are needed, which is why they land together.
    let mut body = if !has_numeric_field {
        String::new()
    } else if int_part == 0 {
        // Show a "0" unless it is a leading zero being blanked: a
        // '9' units slot with a decimal point (PG shows `.50`), and
        // in fixed width a whole-zero value is likewise blanked.
        let show_zero = if fill_mode {
            value_is_zero || units_slot == '0'
        } else {
            units_slot == '0' || !has_decimal
        };
        if show_zero {
            "0".to_string()
        } else {
            String::new()
        }
    } else {
        alloc::format!("{int_part}")
    };
    // Force leading zeros up to the left-most '0' slot.
    while !body.is_empty() && body.chars().count() < zero_pad {
        body.insert(0, '0');
    }
    // --- Assemble sign + body, then pad / trim per mode. ---
    let mut out = if has_group {
        let field = render_positional_groups(int_pat, &body);
        if fill_mode {
            alloc::format!("{sign_str}{}", field.trim_start())
        } else {
            left_pad_spaces(&alloc::format!("{sign_str}{field}"), int_field_width)
        }
    } else if fill_mode {
        alloc::format!("{sign_str}{body}")
    } else {
        left_pad_spaces(&alloc::format!("{sign_str}{body}"), int_field_width)
    };

    if has_decimal {
        let mut fs = alloc::format!("{frac_part:0width$}", width = frac_digits);
        if fill_mode {
            // FM trims trailing zeros down to the `0` slots but keeps
            // the decimal point (PG renders `5.` for to_char(5,'FM9.99')).
            let keep = frac_pat.chars().filter(|c| *c == '0').count();
            while fs.chars().count() > keep && fs.ends_with('0') {
                fs.pop();
            }
            out.push('.');
            out.push_str(&fs);
        } else if frac_digits > 0 {
            out.push('.');
            out.push_str(&fs);
        }
    }
    // v7.39 (round 631) — `PR` on a picture with no numeric field prints
    // nothing: PG answers the empty string for `to_char(1,'PR')` and for
    // the negative too, where SPG produced ` ` and `<>`.
    if has_pr && has_numeric_field {
        if neg {
            // Consume the reserved sign column with `<` and append `>`.
            let trimmed = out.trim_start();
            let lead = out.chars().count() - trimmed.chars().count();
            out = alloc::format!("{}<{trimmed}>", " ".repeat(lead.saturating_sub(1)));
        } else if !fill_mode {
            out.push(' ');
        }
    }
    // v7.37 — trailing sign / currency suffixes (see the strip block above).
    if has_mi {
        if neg {
            out.push('-');
        } else if !fill_mode {
            out.push(' ');
        }
    } else if has_pl {
        // The plus column: `+` when non-negative, blank when the minus
        // already went to the leading position.
        out.push(if neg { ' ' } else { '+' });
    } else if has_sg || (has_trailing_s && has_numeric_field) {
        // v7.39 (round 631) — a lone trailing `S` prints nothing: PG
        // answers the empty string for `to_char(1,'S')`, while `SG` alone
        // does print its sign (`+` / `-`). Measured both ways.
        out.push(if neg { '-' } else { '+' });
    }
    if has_dollar {
        out.push('$');
    }
    // v7.37 — ordinal suffix (`TH`/`th`) based on the integer value, then a
    // trailing `%` literal.
    if let Some(upper) = th_suffix {
        let suf = ordinal_suffix(int_part);
        if upper {
            out.push_str(&suf.to_ascii_uppercase());
        } else {
            out.push_str(suf);
        }
    }
    if has_pct {
        out.push('%');
    }
    if has_leading_sg {
        // SG owns the sign COLUMN: replace the single leading blank or
        // minus the slot machinery wrote (later pre-decimal blanks stay,
        // PG: SG9.9 of .5 = "+ .5"), or prepend when there is none.
        let sign = if neg { '-' } else { '+' };
        if out.starts_with(' ') || out.starts_with('-') {
            out.replace_range(..1, &sign.to_string());
        } else {
            out.insert(0, sign);
        }
    }
    if has_locale_currency {
        out.insert(0, ' ');
    } else if has_lit_currency {
        out.insert(0, '$');
    }
    Ok(out)
}

/// The English ordinal suffix (`st`/`nd`/`rd`/`th`) for `n`, matching PG's
/// `TH` / `th` numeric-format modifier. 11/12/13 are always `th`.
fn ordinal_suffix(n: i128) -> &'static str {
    let n = n.unsigned_abs();
    if (11..=13).contains(&(n % 100)) {
        return "th";
    }
    match n % 10 {
        1 => "st",
        2 => "nd",
        3 => "rd",
        _ => "th",
    }
}

/// Left-pad `s` with spaces so its char count reaches `width`
/// (right-alignment); returns `s` unchanged when already wide enough.
fn left_pad_spaces(s: &str, width: usize) -> String {
    let len = s.chars().count();
    if len >= width {
        return s.to_string();
    }
    let mut out = String::with_capacity(width);
    for _ in 0..width - len {
        out.push(' ');
    }
    out.push_str(s);
    out
}

/// Insert commas every three digits from the right of a pure-digit
/// integer string.
/// v7.39 (round 523) — the `TZH` / `OF` spelling of a zone offset.
fn zone_hours(zone: Option<(&str, i64)>) -> String {
    let secs = zone.map_or(0, |(_, off)| off / 1_000_000);
    let h = secs / 3600;
    alloc::format!("{}{:02}", if h < 0 { '-' } else { '+' }, h.abs())
}

/// v7.39 (round 523) — the `TZM` spelling: whole minutes past the hour.
fn zone_minutes(zone: Option<(&str, i64)>) -> String {
    let secs = zone.map_or(0, |(_, off)| off / 1_000_000);
    alloc::format!("{:02}", (secs.abs() / 60) % 60)
}

/// v7.39 (round 632, F33) — a group separator goes where the PICTURE puts
/// it, not every three digits.
///
/// PG fills the digit slots from the right and emits each separator in the
/// picture as `,` when digits are still to be placed to its left, and as a
/// blank when they are not. Grouping every three digits agrees only when
/// the separator happens to sit on a thousands boundary, which is why
/// `9G999` matched and `9G9` did not: PG answers ` 1,2` for
/// `to_char(12,'9G9')` and SPG answered `  12`. Measured across
/// `9G9` `9G99` `9G999` `99G99` and their FM forms.
fn render_positional_groups(int_pat: &str, digits: &str) -> String {
    let mut rev: alloc::vec::Vec<char> = alloc::vec::Vec::new();
    let mut left = digits.chars().rev();
    let mut pending: Option<char> = left.next();
    for c in int_pat.chars().rev() {
        match c {
            '9' | '0' => {
                rev.push(pending.unwrap_or(' '));
                if pending.is_some() {
                    pending = left.next();
                }
            }
            ',' | 'G' | 'g' => rev.push(if pending.is_some() { ',' } else { ' ' }),
            other => rev.push(other),
        }
    }
    rev.iter().rev().collect()
}

fn group_thousands(int_str: &str) -> String {
    let bytes: alloc::vec::Vec<char> = int_str.chars().collect();
    let mut out = String::new();
    let len = bytes.len();
    for (idx, c) in bytes.iter().enumerate() {
        if idx > 0 && (len - idx) % 3 == 0 {
            out.push(',');
        }
        out.push(*c);
    }
    out
}

pub(super) fn to_char(args: &[Value<'_>]) -> Result<Value<'static>, EvalError> {
    to_char_in_zone(args, None)
}

/// v7.39 (round 523) — `to_char` with the SESSION zone's designation and
/// offset, for a timestamptz source. The zone tokens answered a fixed
/// `UTC` / `+00` whatever the session was set to, so a formatted stamp
/// named a zone the value was not being read in.
pub(super) fn to_char_in_zone(
    args: &[Value<'_>],
    zone: Option<(&str, i64)>,
) -> Result<Value<'static>, EvalError> {
    use core::fmt::Write as _;
    if args.len() != 2 {
        return Err(EvalError::TypeMismatch {
            detail: format!("to_char() takes 2 args, got {}", args.len()),
        });
    }
    if matches!(&args[0], Value::Null) || matches!(&args[1], Value::Null) {
        return Ok(Value::Null);
    }
    let Value::Text(fmt) = &args[1] else {
        return Err(EvalError::TypeMismatch {
            detail: format!(
                "to_char() needs a text format, got {}",
                crate::conversions::pg_type_name_for_error_opt(args[1].data_type())
            ),
        });
    };
    // Interval form: to_char(interval, 'HH24:MI:SS' / 'DD' / 'YYYY-MM' / …).
    if let Value::Interval {
        months,
        days,
        micros,
    } = &args[0]
    {
        return Ok(Value::text(to_char_interval(
            i64::from(*months),
            i64::from(*days),
            i128::from(*micros),
            fmt,
        )));
    }
    // Numeric form: to_char(number, 'FM9999.00' / '999,990.9' / …).
    if let Some(n) = numeric_value_for_to_char(&args[0]) {
        check_eeee_format(fmt)?;
        // v7.38 (read01 P6.01) — thread the exact (scaled, scale) for numeric
        // inputs so to_char never rounds a high-precision value through f64.
        let exact = match &args[0] {
            Value::Numeric { scaled, scale, .. } => Some((*scaled, *scale)),
            _ => None,
        };
        return Ok(Value::text(to_char_numeric(n, exact, fmt)?));
    }
    let (days, day_micros) = match &args[0] {
        Value::Date(d) => (*d, 0_i64),
        // v7.39 (round 246) — to_char(TIME, 'HH24:MI:SS'): the time tokens
        // render from the time-of-day; date tokens read the epoch date, as
        // PG's zeroed date fields do.
        Value::Time(us) => (0_i32, *us),
        Value::Timestamp(t) => {
            let days = t.div_euclid(86_400_000_000);
            (
                i32::try_from(days).unwrap_or(i32::MAX),
                t.rem_euclid(86_400_000_000),
            )
        }
        other => {
            return Err(EvalError::TypeMismatch {
                detail: format!(
                    "to_char() needs a number, DATE or TIMESTAMP, got {}",
                    crate::conversions::pg_type_name_for_error_opt(other.data_type())
                ),
            });
        }
    };
    let (y, mo, d) = civil_from_days(days);
    let secs = day_micros / 1_000_000;
    let frac = day_micros % 1_000_000;
    // div_euclid keeps every value non-negative — the casts below are
    // sign-safe by construction. `secs ∈ [0, 86400)`, `frac ∈ [0,
    // 1_000_000)`, so all three quantities fit in u32.
    let hh24 = u32::try_from(secs / 3600).unwrap_or(0);
    let mi = u32::try_from((secs / 60) % 60).unwrap_or(0);
    let ss = u32::try_from(secs % 60).unwrap_or(0);
    let hh12 = match hh24 % 12 {
        0 => 12,
        x => x,
    };
    let ampm = if hh24 < 12 { "AM" } else { "PM" };
    let ms = u32::try_from(frac / 1_000).unwrap_or(0); // millisecond
    let us = u32::try_from(frac).unwrap_or(0); // microsecond (0..1_000_000)

    // Calendar-derived fields (PG doc semantics). 1970-01-01 was a
    // Thursday (index 3 in a Monday=0 week).
    let dow_mon0 = usize::try_from((i64::from(days) + 3).rem_euclid(7)).unwrap_or(0);
    let day_of_year = i64::from(days - days_from_civil(y, 1, 1)) + 1; // DDD
    let (iso_week, iso_year) = super::datetime::iso_week_and_year(days, y); // IW / IYYY
    let quarter = i64::from((mo - 1) / 3) + 1; // Q
    let week_of_year = (day_of_year - 1) / 7 + 1; // WW
    let week_of_month = i64::from((d - 1) / 7) + 1; // W
    let dow_sun1 = (i64::from(days) + 4).rem_euclid(7) + 1; // D: Sunday = 1
    let iso_dow = (dow_mon0 as i64) + 1; // ID: Monday = 1
    let julian = i64::from(days) + 2_440_588; // J
    let century: i64 = if y > 0 {
        i64::from((y - 1) / 100) + 1
    } else {
        i64::from(y / 100) - 1
    }; // CC
    // v7.39 (read01 formatting.c) — year fields render the ERA year (PG's
    // ADJUST_YEAR): there is no year 0, so astronomical year <= 0 displays
    // as 1 - y (44 BC is stored as -43 and prints 0044; the era tokens
    // still read the raw sign).
    let disp_y: i64 = if y <= 0 {
        1 - i64::from(y)
    } else {
        i64::from(y)
    };

    let mut out = String::with_capacity(fmt.len() + 8);
    let bytes = fmt.as_bytes();
    let mut i = 0;
    // `FM` prefix suppresses the leading zeros / blank padding of the
    // one field it precedes.
    let mut fm = false;
    // v7.39 (read01 round 101) — `TM` prefix = translation mode: emit the
    // localized day/month name at its natural width (no blank padding). SPG's
    // locale is C, where the localized names ARE the English ones this
    // formatter already uses, so TM's only observable effect here is the
    // trim — the same trim FM applies to a name field. Affects the one field
    // it precedes; numeric fields ignore it (PG does too).
    let mut tm = false;
    // v7.37 — the numeric value emitted by the immediately preceding field,
    // so a following `TH`/`th` renders its ordinal suffix (e.g. `DDth` → 21st).
    let mut last_num: Option<i128> = None;
    // write! against a String never fails — discard the Result.
    while i < bytes.len() {
        // Try the longest prefixes first so "YYYY" wins over "YY".
        let rest = &bytes[i..];
        // FM toggles fill-mode for the *next* field only; consume and
        // loop without emitting so it applies to whatever follows.
        if rest.starts_with(b"FM") {
            fm = true;
            i += 2;
            continue;
        }
        // v7.39 (read01 round 101) — `TM` (translation-mode) prefix. Case-
        // insensitive like PG's other modifiers. Sets the natural-width flag
        // for the next name field; without it `TMDay` emitted a literal "TM".
        if rest.len() >= 2 && rest[..2].eq_ignore_ascii_case(b"TM") {
            tm = true;
            i += 2;
            continue;
        }
        // Double-quoted text is a literal — PG strips the quotes and emits the
        // content verbatim (e.g. `HH24"h"MI"m"` → `14h30m`, `YYYY"年"` → `2024年`).
        if bytes[i] == b'"' {
            i += 1;
            let start = i;
            while i < bytes.len() && bytes[i] != b'"' {
                i += 1;
            }
            out.push_str(&fmt[start..i]);
            if i < bytes.len() {
                i += 1; // consume the closing quote
            }
            continue;
        }
        // Blank-padded name fields (Day / Month / RM): FM strips the
        // trailing blanks; the width is the longest member (9 for
        // day/month names, 4 for roman months).
        let pad = |width: usize| if fm || tm { None } else { Some(width) };
        // Ordinal pending from the previous field (see `last_num`); `take`
        // clears it so a non-`TH` field drops the pending suffix.
        let pending_ord = last_num.take();
        let mut next_num: Option<i128> = None;
        // Numeric fields honour FM by dropping the zero pad.
        macro_rules! num {
            ($val:expr, $width:literal) => {{
                if fm {
                    let _ = write!(out, "{}", $val);
                } else {
                    let _ = write!(out, "{:0width$}", $val, width = $width);
                }
                next_num = Some(i128::from($val));
            }};
        }
        let mut consumed = 2usize;
        if rest.starts_with(b"Y,YYY") {
            // v7.37 — special comma-grouped year token (2026 → "2,026").
            out.push_str(&group_thousands(&alloc::format!("{disp_y}")));
            consumed = 5;
        } else if rest.starts_with(b"YYYY") {
            num!(disp_y, 4);
            consumed = 4;
        } else if rest.starts_with(b"IYYY") {
            num!(iso_year, 4);
            consumed = 4;
        } else if rest.starts_with(b"HH24") {
            num!(hh24, 2);
            consumed = 4;
        } else if rest.starts_with(b"HH12") {
            num!(hh12, 2);
            consumed = 4;
        } else if rest.starts_with(b"IYY") {
            let _ = write!(out, "{:03}", iso_year.rem_euclid(1000));
            consumed = 3;
        } else if rest.starts_with(b"YYY") {
            let _ = write!(out, "{:03}", disp_y.rem_euclid(1000));
            consumed = 3;
        } else if rest.starts_with(b"DDD") {
            num!(day_of_year, 3);
            consumed = 3;
        } else if rest.starts_with(b"Month") {
            out.push_str(&cased_name(
                MONTH_FULL[(mo - 1) as usize],
                false,
                false,
                pad(9),
            ));
            consumed = 5;
        } else if rest.starts_with(b"MONTH") {
            out.push_str(&cased_name(
                MONTH_FULL[(mo - 1) as usize],
                true,
                false,
                pad(9),
            ));
            consumed = 5;
        } else if rest.starts_with(b"month") {
            out.push_str(&cased_name(
                MONTH_FULL[(mo - 1) as usize],
                false,
                true,
                pad(9),
            ));
            consumed = 5;
        } else if rest.starts_with(b"Mon") {
            out.push_str(&cased_name(
                MONTH_ABBR[(mo - 1) as usize],
                false,
                false,
                None,
            ));
            consumed = 3;
        } else if rest.starts_with(b"MON") {
            out.push_str(&cased_name(
                MONTH_ABBR[(mo - 1) as usize],
                true,
                false,
                None,
            ));
            consumed = 3;
        } else if rest.starts_with(b"mon") {
            out.push_str(&cased_name(
                MONTH_ABBR[(mo - 1) as usize],
                false,
                true,
                None,
            ));
            consumed = 3;
        } else if rest.starts_with(b"Day") {
            out.push_str(&cased_name(DAY_FULL[dow_mon0], false, false, pad(9)));
            consumed = 3;
        } else if rest.starts_with(b"DAY") {
            out.push_str(&cased_name(DAY_FULL[dow_mon0], true, false, pad(9)));
            consumed = 3;
        } else if rest.starts_with(b"day") {
            out.push_str(&cased_name(DAY_FULL[dow_mon0], false, true, pad(9)));
            consumed = 3;
        } else if rest.starts_with(b"Dy") {
            out.push_str(&cased_name(DAY_ABBR[dow_mon0], false, false, None));
        } else if rest.starts_with(b"DY") {
            out.push_str(&cased_name(DAY_ABBR[dow_mon0], true, false, None));
        } else if rest.starts_with(b"dy") {
            out.push_str(&cased_name(DAY_ABBR[dow_mon0], false, true, None));
        } else if rest.starts_with(b"YY") {
            let _ = write!(out, "{:02}", disp_y.rem_euclid(100));
        } else if rest.starts_with(b"IW") {
            num!(iso_week, 2);
        } else if rest.starts_with(b"IY") {
            let _ = write!(out, "{:02}", iso_year.rem_euclid(100));
        } else if rest.starts_with(b"IDDD") {
            // v7.37 — ISO day of year (day within the ISO 8601 week-year),
            // = (iso_week - 1) * 7 + iso_dow. Must precede the `ID` arm.
            let _ = write!(out, "{:03}", (iso_week - 1) * 7 + iso_dow);
            consumed = 4;
        } else if rest.starts_with(b"ID") {
            let _ = write!(out, "{iso_dow}");
        } else if rest.starts_with(b"MM") {
            num!(mo, 2);
        } else if rest.starts_with(b"DD") {
            num!(d, 2);
        } else if rest.starts_with(b"MI") {
            num!(mi, 2);
        } else if rest.starts_with(b"SSSSS") {
            // v7.39 (round 246) — `SSSSS` is PG's alias for `SSSS`; without
            // its own arm the four-letter match left a stray literal `S`.
            let _ = write!(out, "{}", hh24 * 3600 + mi * 60 + ss);
            consumed = 5;
        } else if rest.starts_with(b"SSSS") {
            // v7.37 — seconds past midnight (0..86399), no zero padding.
            // Must precede the `SS` arm (which `SSSS` also prefix-matches).
            let _ = write!(out, "{}", hh24 * 3600 + mi * 60 + ss);
            consumed = 4;
        } else if rest.starts_with(b"TZH") {
            // v7.39 (round 246) — the zone tokens.
            // v7.39 (round 523) — they answer for the SESSION zone now,
            // which is the one the value beside them is being read in.
            // A fixed `UTC` / `+00` here named a zone the rest of the
            // string did not agree with.
            out.push_str(&zone_hours(zone));
            consumed = 3;
        } else if rest.starts_with(b"TZM") {
            out.push_str(&zone_minutes(zone));
            consumed = 3;
        } else if rest.starts_with(b"TZ") || rest.starts_with(b"tz") {
            let name = zone.map_or_else(|| String::from("UTC"), |(n, _)| String::from(n));
            out.push_str(&if rest.starts_with(b"TZ") {
                name.to_uppercase()
            } else {
                name.to_lowercase()
            });
            consumed = 2;
        } else if rest.starts_with(b"OF") {
            out.push_str(&zone_hours(zone));
            consumed = 2;
        } else if rest.starts_with(b"FF") && rest.get(2).is_some_and(u8::is_ascii_digit) {
            // v7.37 — `FF1`..`FF6`: the first N digits of the fractional
            // second (from the 6-digit microsecond field). Previously the
            // `FFn` pattern was emitted verbatim.
            let n = usize::from(rest[2] - b'0');
            let frac = alloc::format!("{us:06}");
            out.push_str(&frac[..n.min(6)]);
            consumed = 3;
        } else if rest.starts_with(b"SS") {
            num!(ss, 2);
        } else if rest.starts_with(b"MS") {
            let _ = write!(out, "{ms:03}");
        } else if rest.starts_with(b"US") {
            let _ = write!(out, "{us:06}");
        } else if rest.starts_with(b"WW") {
            num!(week_of_year, 2);
        } else if rest.starts_with(b"CC") {
            num!(century, 2);
        } else if rest.starts_with(b"RM") {
            out.push_str(&cased_name(
                MONTH_ROMAN[(mo - 1) as usize],
                true,
                false,
                pad(4),
            ));
        } else if rest.starts_with(b"rm") {
            out.push_str(&cased_name(
                MONTH_ROMAN[(mo - 1) as usize],
                false,
                true,
                pad(4),
            ));
        } else if rest.starts_with(b"HH") {
            num!(hh12, 2);
        } else if rest.starts_with(b"A.M.") || rest.starts_with(b"P.M.") {
            // v7.37 — dotted meridiem (uppercase). PG renders the actual
            // half-day regardless of which spelling was requested.
            out.push_str(if hh24 < 12 { "A.M." } else { "P.M." });
            consumed = 4;
        } else if rest.starts_with(b"a.m.") || rest.starts_with(b"p.m.") {
            out.push_str(if hh24 < 12 { "a.m." } else { "p.m." });
            consumed = 4;
        } else if rest.starts_with(b"B.C.") || rest.starts_with(b"A.D.") {
            // v7.37 — dotted era. Proleptic year <= 0 is BC; PG shows the
            // actual era regardless of the requested spelling.
            out.push_str(if i64::from(y) <= 0 { "B.C." } else { "A.D." });
            consumed = 4;
        } else if rest.starts_with(b"b.c.") || rest.starts_with(b"a.d.") {
            out.push_str(if i64::from(y) <= 0 { "b.c." } else { "a.d." });
            consumed = 4;
        } else if rest.starts_with(b"AM") || rest.starts_with(b"PM") {
            out.push_str(ampm);
        } else if rest.starts_with(b"am") || rest.starts_with(b"pm") {
            out.push_str(if hh24 < 12 { "am" } else { "pm" });
        } else if rest.starts_with(b"BC") || rest.starts_with(b"AD") {
            // v7.37 — era indicator (uppercase, no dots).
            out.push_str(if i64::from(y) <= 0 { "BC" } else { "AD" });
        } else if rest.starts_with(b"bc") || rest.starts_with(b"ad") {
            out.push_str(if i64::from(y) <= 0 { "bc" } else { "ad" });
        } else if (rest.starts_with(b"TH") || rest.starts_with(b"th")) && pending_ord.is_some() {
            // v7.37 — ordinal suffix for the preceding numeric field
            // (`DDth` → 21st, `HH12th` → 02nd). Only fires right after a
            // number; a bare `th`/`TH` still passes through as a literal.
            let suf = ordinal_suffix(pending_ord.unwrap_or(0));
            if rest.starts_with(b"TH") {
                out.push_str(&suf.to_ascii_uppercase());
            } else {
                out.push_str(suf);
            }
        } else if rest.starts_with(b"Y") || rest.starts_with(b"I") {
            // Single-digit year / ISO-year (last digit).
            let base = if rest[0] == b'I' { iso_year } else { disp_y };
            let _ = write!(out, "{}", base.rem_euclid(10));
            consumed = 1;
        } else if rest.starts_with(b"Q") {
            let _ = write!(out, "{quarter}");
            consumed = 1;
        } else if rest.starts_with(b"W") {
            let _ = write!(out, "{week_of_month}");
            consumed = 1;
        } else if rest.starts_with(b"D") {
            let _ = write!(out, "{dow_sun1}");
            next_num = Some(i128::from(dow_sun1));
            consumed = 1;
        } else if rest.starts_with(b"J") {
            let _ = write!(out, "{julian}");
            consumed = 1;
        } else {
            // Pass any non-placeholder byte through verbatim.
            out.push(bytes[i] as char);
            consumed = 1;
            i += consumed;
            // A literal byte doesn't consume the pending FM.
            continue;
        }
        last_num = next_num;
        fm = false;
        tm = false;
        i += consumed;
    }
    Ok(Value::text(out))
}