graphitesql 0.1.0

A pure, safe, no_std Rust re-implementation of SQLite, compatible with the SQLite 3 file format.
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
//! Built-in scalar functions.
//!
//! Aggregate functions (`count`, `sum`, …) are handled by the executor, which
//! folds over rows; this module covers the per-row scalar functions. The set is
//! a useful core and grows toward SQLite's full library (`func.c`, `date.c`).

use super::eval::{self, EvalCtx};
use crate::error::{Error, Result};
use crate::sql::ast::{Expr, Literal};
use crate::value::Value;
use alloc::string::String;
use alloc::vec::Vec;

/// SQLite's default `SQLITE_MAX_LENGTH`: the largest string/blob a single value
/// may hold. `zeroblob`/`randomblob` error with "string or blob too big" past it
/// rather than attempting a multi-gigabyte allocation.
const MAX_BLOB_LEN: usize = 1_000_000_000;

/// Names that *can* be aggregates (used for catalog/name checks).
pub fn is_aggregate(name: &str) -> bool {
    matches!(
        name.to_ascii_lowercase().as_str(),
        "count" | "sum" | "total" | "avg" | "min" | "max" | "group_concat" | "geopoly_group_bbox"
    )
}

/// Whether a *specific call* is an aggregate. `min`/`max` are scalar with 2+
/// arguments and aggregate with exactly one (or `*`), matching SQLite.
pub fn is_aggregate_call(name: &str, nargs: usize, star: bool) -> bool {
    match name.to_ascii_lowercase().as_str() {
        "count" | "sum" | "total" | "avg" | "group_concat" | "string_agg" => true,
        // The JSON group aggregates have no scalar counterpart, so they are
        // aggregates at any argument count — a wrong count must reach the
        // aggregate arity guard ("wrong number of arguments"), not fall through
        // to scalar dispatch ("no such function").
        "json_group_array" | "jsonb_group_array" | "json_group_object" | "jsonb_group_object" => {
            true
        }
        // geopoly_group_bbox has no scalar counterpart, so it is an aggregate at
        // any argument count (the arity guard reports a wrong count).
        "geopoly_group_bbox" => true,
        "min" | "max" => star || nargs == 1,
        _ => false,
    }
}

/// The searchable `(column name, text)` pairs an FTS5 `MATCH` operand refers to,
/// or `None` if the operand is not a column or table-name reference (so `MATCH`
/// is not a full-text query in this context). A reference to an indexed column
/// yields just that column; an unqualified reference to the table's own name
/// yields every column (SQLite's table-wide `MATCH`, where `col:token` filters
/// pick out individual columns).
#[cfg(feature = "fts5")]
fn fts5_match_columns(
    operand: &Expr,
    ctx: &EvalCtx,
) -> Option<(Vec<(String, String)>, crate::vtab::Fts5Tok)> {
    let (table, column) = match operand {
        Expr::Column { table, column, .. } => (table.as_deref(), column.as_str()),
        Expr::Paren(e) => return fts5_match_columns(e, ctx),
        _ => return None,
    };
    // The table's tokenizer config (Porter stemming + `remove_diacritics` level),
    // so the query folds exactly like the indexed documents.
    let tok = |t: &str| {
        ctx.subqueries
            .map_or_else(crate::vtab::Fts5Tok::default, |s| s.fts5_tok(t))
    };
    // A reference to a specific indexed column searches only that column. An
    // `UNINDEXED` column matches nothing (it carries no full-text index).
    if let Some(i) = ctx.columns.iter().position(|c| {
        c.name.eq_ignore_ascii_case(column) && table.is_none_or(|t| c.table.eq_ignore_ascii_case(t))
    }) {
        let c = &ctx.columns[i];
        let unindexed = ctx
            .subqueries
            .and_then(|s| s.fts5_indexed_columns(&c.table))
            .is_some_and(|cols| !cols.iter().any(|n| n.eq_ignore_ascii_case(&c.name)));
        if unindexed {
            return Some((Vec::new(), crate::vtab::Fts5Tok::default()));
        }
        return Some((
            alloc::vec![(c.name.clone(), eval::to_text(&ctx.row[i]))],
            tok(&c.table),
        ));
    }
    // An unqualified reference to the table itself searches across every indexed
    // column (`UNINDEXED` columns are stored but excluded from the full-text index).
    if table.is_none() {
        let indexed = ctx.subqueries.and_then(|s| s.fts5_indexed_columns(column));
        let cols: Vec<(String, String)> = ctx
            .columns
            .iter()
            .enumerate()
            .filter(|(_, c)| c.table.eq_ignore_ascii_case(column))
            .filter(|(_, c)| {
                indexed
                    .as_ref()
                    .is_none_or(|cols| cols.iter().any(|n| n.eq_ignore_ascii_case(&c.name)))
            })
            .map(|(i, c)| (c.name.clone(), eval::to_text(&ctx.row[i])))
            .collect();
        if !cols.is_empty() {
            return Some((cols, tok(column)));
        }
    }
    None
}

/// The fts5 table a `MATCH` operand refers to: the operand `t` in `t MATCH q` (a
/// bare table reference) or the owning table of `t.col MATCH q`. Resolves the name
/// through the current row's column set (so an alias maps to the real table name),
/// falling back to the operand's own identifier. `None` when the operand is not a
/// column/table reference.
#[cfg(feature = "fts5")]
fn fts5_match_operand_table(operand: &Expr, ctx: &EvalCtx) -> Option<alloc::string::String> {
    let (table, column) = match operand {
        Expr::Column { table, column, .. } => (table.as_deref(), column.as_str()),
        Expr::Paren(e) => return fts5_match_operand_table(e, ctx),
        _ => return None,
    };
    // `t.col` → the table owning that column; bare `t` → the table named `t` in the
    // row's column set (its `table` field holds the resolved base-table name).
    if let Some(t) = table {
        return Some(alloc::string::String::from(t));
    }
    ctx.columns
        .iter()
        .find(|c| c.table.eq_ignore_ascii_case(column))
        .map(|c| c.table.clone())
        .or_else(|| Some(alloc::string::String::from(column)))
}

/// Whether a `highlight`/`snippet` first argument names a contentless fts5 table.
#[cfg(feature = "fts5")]
fn fts5_operand_is_contentless(operand: &Expr, ctx: &EvalCtx) -> bool {
    fts5_match_operand_table(operand, ctx)
        .zip(ctx.subqueries)
        .is_some_and(|(t, s)| s.fts5_is_contentless_table(&t))
}

/// Evaluate a scalar function call.
pub fn eval_scalar(name: &str, args: &[Expr], star: bool, ctx: &EvalCtx) -> Result<Value> {
    let lname = name.to_ascii_lowercase();
    if is_aggregate_call(&lname, args.len(), star) {
        // Reaching the scalar evaluator means this aggregate sits in a position
        // that forbids one — most commonly nested inside another aggregate's
        // argument or FILTER (`sum(count(a))`), where the inner call is evaluated
        // per row as a scalar. SQLite reports this as `misuse of aggregate
        // function NAME()`, naming the inner call. (Row-filtering positions —
        // WHERE, join ON, ORDER BY of a non-aggregate query, UPDATE/DELETE
        // expressions — are intercepted earlier at prepare time so they error even
        // over an empty table; see `reject_misused_aggregate`.)
        return Err(Error::Error(alloc::format!(
            "misuse of aggregate function {name}()"
        )));
    }
    if star {
        return Err(Error::Error(alloc::format!(
            "{name}(*) is not a scalar call"
        )));
    }

    // Connection-state functions: read counters off the subquery handler.
    match lname.as_str() {
        "last_insert_rowid" | "changes" | "total_changes" => {
            arity(&lname, args, 0)?;
            let n = ctx.subqueries.map_or(0, |s| match lname.as_str() {
                "last_insert_rowid" => s.last_insert_rowid(),
                "changes" => s.changes(),
                _ => s.total_changes(),
            });
            return Ok(Value::Integer(n));
        }
        "random" => {
            arity(&lname, args, 0)?;
            return Ok(Value::Integer(
                ctx.subqueries.map_or(0, |s| s.next_random()),
            ));
        }
        "randomblob" => {
            arity(&lname, args, 1)?;
            // SQLite coerces the argument to an integer (NULL/non-numeric text
            // become 0, reals truncate) and clamps N < 1 to a single byte — so
            // randomblob(NULL) is a 1-byte blob, not NULL.
            let n = eval::to_int_value(&eval::eval(&args[0], ctx)?);
            let len = if n < 1 { 1 } else { n as usize };
            if len > MAX_BLOB_LEN {
                return Err(Error::Error("string or blob too big".into()));
            }
            let mut bytes = Vec::new();
            if let Some(s) = ctx.subqueries {
                while bytes.len() < len {
                    bytes.extend_from_slice(&s.next_random().to_le_bytes());
                }
                bytes.truncate(len);
            } else {
                bytes.resize(len, 0);
            }
            return Ok(Value::Blob(bytes));
        }
        // FTS5 `MATCH`: `x MATCH 'query'` parsed to `match('query', x)`. When the
        // operand `x` references an indexed column (or the table itself), run the
        // full-text query against that document. When it is not a column/table
        // reference (e.g. a literal), fall through so a user-registered `match`
        // function — or the "no such function" error — applies, matching SQLite,
        // where a bare `MATCH` outside a virtual-table context is an error.
        #[cfg(feature = "fts5")]
        "match" if args.len() == 2 => {
            if let Some((cols, tok)) = fts5_match_columns(&args[1], ctx) {
                let pattern = eval::eval(&args[0], ctx)?;
                return Ok(match pattern {
                    Value::Null => Value::Null,
                    p => {
                        let q = eval::to_text(&p);
                        // A contentless table keeps no column text, so `MATCH` can't
                        // be re-checked from the (NULL) row — consult the index by
                        // rowid instead. `fts5_match_operand_table` names the table
                        // the operand refers to; the connection resolves whether it
                        // is contentless and, if so, evaluates against the index.
                        if let (Some(table), Some(rowid)) =
                            (fts5_match_operand_table(&args[1], ctx), ctx.rowid)
                        {
                            if let Some(m) = ctx
                                .subqueries
                                .and_then(|s| s.fts5_contentless_match(&table, &q, rowid))
                            {
                                return Ok(Value::Integer(m as i64));
                            }
                        }
                        Value::Integer(crate::vtab::fts5_query_matches(&q, &cols, tok) as i64)
                    }
                });
            }
        }
        // FTS5 `bm25(<table>[, w1, w2, …])`: the relevance score of the current row
        // (optionally with per-column weights), computed by `run_core` for a `MATCH`
        // query over an `fts5` table. Falls through when no such score is in scope
        // (so `bm25()` elsewhere is the usual unknown name).
        #[cfg(feature = "fts5")]
        "bm25" if !args.is_empty() && ctx.rowid.is_some() => {
            let weights: Vec<f64> = args[1..]
                .iter()
                .map(|a| Ok(eval::to_f64(&eval::eval(a, ctx)?)))
                .collect::<Result<_>>()?;
            if let Some(score) = ctx
                .rowid
                .and_then(|r| ctx.subqueries?.fts5_bm25(r, &weights))
            {
                return Ok(Value::Real(score));
            }
        }
        // FTS5 `highlight(<table>, col, open, close)`: column `col`'s text with the
        // matched tokens wrapped, in scope for a `MATCH` query over an `fts5` table.
        #[cfg(feature = "fts5")]
        "highlight" if args.len() == 4 => {
            // A contentless table stores no text, so there is nothing to render:
            // `highlight`/`snippet` return NULL (matching SQLite).
            if fts5_operand_is_contentless(&args[0], ctx) {
                return Ok(Value::Null);
            }
            let col = eval::to_int_value(&eval::eval(&args[1], ctx)?);
            let open = eval::to_text(&eval::eval(&args[2], ctx)?);
            let close = eval::to_text(&eval::eval(&args[3], ctx)?);
            // The column text is the current row's value for that column.
            if let Ok(col) = usize::try_from(col) {
                let text = ctx.row.get(col).map(eval::to_text).unwrap_or_default();
                if let Some(s) = ctx
                    .subqueries
                    .and_then(|s| s.fts5_highlight(col, &text, &open, &close))
                {
                    return Ok(Value::Text(s));
                }
            }
        }
        // FTS5 `snippet(<table>, col, open, close, ellipsis, n)`: a window of up
        // to `n` tokens from column `col`, matched tokens wrapped, ellipsis at any
        // trimmed end. In scope for a `MATCH` query over an `fts5` table.
        #[cfg(feature = "fts5")]
        "snippet" if args.len() == 6 => {
            if fts5_operand_is_contentless(&args[0], ctx) {
                return Ok(Value::Null);
            }
            let col = eval::to_int_value(&eval::eval(&args[1], ctx)?);
            let open = eval::to_text(&eval::eval(&args[2], ctx)?);
            let close = eval::to_text(&eval::eval(&args[3], ctx)?);
            let ellipsis = eval::to_text(&eval::eval(&args[4], ctx)?);
            let ntokens = eval::to_int_value(&eval::eval(&args[5], ctx)?);
            // A negative `col` auto-selects the best column, so pass every column's
            // text; the module bounds the slice by the table's declared columns.
            if let Ok(ntokens) = usize::try_from(ntokens) {
                let cols: Vec<alloc::string::String> = ctx.row.iter().map(eval::to_text).collect();
                if let Some(s) = ctx
                    .subqueries
                    .and_then(|s| s.fts5_snippet(col, &cols, &open, &close, &ellipsis, ntokens))
                {
                    return Ok(Value::Text(s));
                }
            }
        }
        _ => {}
    }

    // Functions whose NULL-handling is special are done before arg evaluation.
    match lname.as_str() {
        "coalesce" => {
            // SQLite requires at least two arguments.
            if args.len() < 2 {
                return Err(wrong_arg_count("coalesce"));
            }
            for a in args {
                let v = eval::eval(a, ctx)?;
                if !matches!(v, Value::Null) {
                    return Ok(v);
                }
            }
            return Ok(Value::Null);
        }
        "ifnull" => {
            arity(&lname, args, 2)?;
            let a = eval::eval(&args[0], ctx)?;
            return if matches!(a, Value::Null) {
                eval::eval(&args[1], ctx)
            } else {
                Ok(a)
            };
        }
        // `json_quote(X)` returns a JSON-subtyped argument as-is (it is already
        // JSON text), and only quotes a value that is *not* JSON. graphite has no
        // value subtypes, so it approximates the subtype syntactically: an arg
        // that is itself a JSON-producing call (`json`, `json_array`, …) carries
        // the subtype. Anything else falls through to the quoting arm below.
        "json_quote" if args.len() == 1 && produces_json(&args[0]) => {
            let val = eval::eval(&args[0], ctx)?;
            // A JSONB blob (e.g. `json_quote(jsonb('[1,2]'))`) renders as its JSON
            // text; any other blob is rejected.
            if let Value::Blob(b) = &val {
                let j = super::json::Json::from_jsonb(b)
                    .ok_or_else(|| Error::Error("JSON cannot hold BLOB values".into()))?;
                return Ok(Value::Text(j.quote()));
            }
            return Ok(val);
        }
        _ => {}
    }

    let v: Vec<Value> = args
        .iter()
        .map(|a| eval::eval(a, ctx))
        .collect::<Result<_>>()?;

    Ok(match lname.as_str() {
        "abs" => {
            arity(&lname, args, 1)?;
            match &v[0] {
                Value::Null => Value::Null,
                // `abs(-9223372036854775808)` has no i64 result — SQLite errors.
                Value::Integer(i) => match i.checked_abs() {
                    Some(a) => Value::Integer(a),
                    None => return Err(Error::Error("integer overflow".into())),
                },
                // `+ 0.0` normalises a negative-zero result to `0.0`, matching
                // SQLite (`abs(-0.0)` is `0.0`, not `-0.0`).
                Value::Real(r) => Value::Real(crate::util::float::abs(*r) + 0.0),
                // A text/blob argument is coerced to a real (SQLite gives
                // `abs('5')` = 5.0, not 5).
                other => Value::Real(crate::util::float::abs(eval::to_f64(other)) + 0.0),
            }
        }
        "length" => {
            arity(&lname, args, 1)?;
            match &v[0] {
                Value::Null => Value::Null,
                Value::Blob(b) => Value::Integer(b.len() as i64),
                // For a string, SQLite counts characters up to (not including)
                // the first NUL — `length('A'||char(0)||'B')` is 1, not 3.
                // Numbers stringify without NULs, so they are unaffected.
                other => {
                    let t = eval::to_text(other);
                    let n = match t.find('\0') {
                        Some(i) => t[..i].chars().count(),
                        None => t.chars().count(),
                    };
                    Value::Integer(n as i64)
                }
            }
        }
        "octet_length" => {
            arity(&lname, args, 1)?;
            // Number of bytes in the value's encoding: blobs as-is, everything
            // else as the UTF-8 length of its text representation.
            match &v[0] {
                Value::Null => Value::Null,
                Value::Blob(b) => Value::Integer(b.len() as i64),
                other => Value::Integer(eval::to_text(other).len() as i64),
            }
        }
        "glob" => {
            // glob(pattern, text) is the function form of `text GLOB pattern`.
            arity(&lname, args, 2)?;
            if v.iter().take(2).any(|x| matches!(x, Value::Null)) {
                Value::Null
            } else {
                let m = eval::glob_match(&eval::to_text(&v[0]), &eval::to_text(&v[1]));
                Value::Integer(m as i64)
            }
        }
        "lower" => {
            arity(&lname, args, 1)?;
            // Stock sqlite3's lower()/upper() fold ASCII A–Z/a–z only; the optional
            // `unicode` feature switches to full Unicode case-folding
            // (`CAFÉ` → `café`), like a sqlite3 built with the ICU extension.
            // `str::to_lowercase` provides it in core+alloc, so no dependency is
            // needed. Default (feature off) stays byte-for-byte stock-sqlite3.
            #[cfg(feature = "unicode")]
            {
                str_map(&v[0], |s| s.to_lowercase())
            }
            #[cfg(not(feature = "unicode"))]
            {
                str_map(&v[0], |s| s.to_ascii_lowercase())
            }
        }
        "upper" => {
            arity(&lname, args, 1)?;
            #[cfg(feature = "unicode")]
            {
                str_map(&v[0], |s| s.to_uppercase())
            }
            #[cfg(not(feature = "unicode"))]
            {
                str_map(&v[0], |s| s.to_ascii_uppercase())
            }
        }
        "trim" | "ltrim" | "rtrim" => {
            // SQLite's trim family takes 1 (string) or 2 (string, chars) arguments.
            if args.is_empty() || args.len() > 2 {
                return Err(wrong_arg_count(&lname));
            }
            let (left, right) = match lname.as_str() {
                "ltrim" => (true, false),
                "rtrim" => (false, true),
                _ => (true, true),
            };
            trim_fn(&v, left, right)
        }
        "soundex" => {
            arity(&lname, args, 1)?;
            // NULL/non-alpha input yields "?000" (SQLite does not propagate NULL).
            Value::Text(soundex(&c_text(&v[0])))
        }
        "typeof" => {
            arity(&lname, args, 1)?;
            Value::Text(String::from(type_name(&v[0])))
        }
        "nullif" => {
            arity(&lname, args, 2)?;
            // The comparison follows the standard binary-comparison collation
            // rule: an explicit `COLLATE` on either operand wins (left-preferred),
            // else a column's declared collation, else BINARY — so
            // `NULLIF('a','A' COLLATE NOCASE)` is NULL.
            let coll = eval::resolve_collation(&args[0], &args[1], ctx);
            if crate::value::cmp_values_coll(&v[0], &v[1], coll) == core::cmp::Ordering::Equal {
                Value::Null
            } else {
                v[0].clone()
            }
        }
        "n/a" => unreachable!(),
        "substr" | "substring" => substr(&v)?,
        "instr" => instr(&v)?,
        "replace" => replace(&v)?,
        "round" => round(&v)?,
        "min" => scalar_min_max(&v, true)?,
        "max" => scalar_min_max(&v, false)?,
        "hex" => {
            arity(&lname, args, 1)?;
            Value::Text(hex_encode(&v[0]))
        }
        "char" => char_fn(&v),
        "unicode" => {
            arity(&lname, args, 1)?;
            match &v[0] {
                Value::Null => Value::Null,
                other => eval::to_text(other)
                    .chars()
                    .next()
                    .map(|c| Value::Integer(c as i64))
                    .unwrap_or(Value::Null),
            }
        }
        // `if` is SQLite's alias for `iif`. The parser desugars the scalar form
        // (>= 2 args) into a CASE expression so it short-circuits, so this arm is
        // normally reached only for the <2-arg arity error; it still evaluates the
        // CASE-form semantics (`(when, then)` pairs with an optional trailing
        // ELSE) for any non-desugared call, for robustness.
        "iif" | "if" => {
            if args.len() < 2 {
                return Err(wrong_arg_count(&lname));
            }
            let n = v.len();
            let mut out = if n % 2 == 1 {
                v[n - 1].clone()
            } else {
                Value::Null
            };
            let mut i = 0;
            while i + 1 < n {
                if eval::truth(&v[i]) == Some(true) {
                    out = v[i + 1].clone();
                    break;
                }
                i += 2;
            }
            out
        }
        // The SQLite release graphitesql tracks and writes into new file headers
        // (`SQLITE_VERSION_NUMBER` 3_053_002 = 3.53.2).
        "sqlite_version" => {
            arity(&lname, args, 0)?;
            Value::Text(crate::TARGET_SQLITE_VERSION.into())
        }
        // Independent reimplementation: this is graphitesql's own identifier in
        // SQLite's `YYYY-MM-DD HH:MM:SS <hash>` shape, not a C build's id.
        "sqlite_source_id" => {
            arity(&lname, args, 0)?;
            Value::Text(crate::TARGET_SQLITE_SOURCE_ID.into())
        }
        "zeroblob" => {
            arity(&lname, args, 1)?;
            // SQLite reads the length via `sqlite3_value_int64`, which maps NULL to
            // 0 — so `zeroblob(NULL)` is an empty blob, not NULL.
            let n = eval::to_int_value(&v[0]).max(0) as usize;
            if n > MAX_BLOB_LEN {
                return Err(Error::Error("string or blob too big".into()));
            }
            Value::Blob(alloc::vec![0u8; n])
        }
        "quote" => {
            arity(&lname, args, 1)?;
            Value::Text(quote_value(&v[0]))
        }
        "unistr" => {
            // Decode `\uXXXX` / `\UXXXXXXXX` / `\\` escapes in the argument's
            // text. NULL passes through; any other escape errors, as in SQLite.
            arity(&lname, args, 1)?;
            match &v[0] {
                Value::Null => Value::Null,
                other => Value::Text(unistr_decode(&eval::to_text(other))?),
            }
        }
        "unistr_quote" => {
            // Like quote(), except a text value containing a control character
            // (< U+0020) is rendered as `unistr('…')` with those characters
            // escaped `\uXXXX`. Non-text values match quote() exactly.
            arity(&lname, args, 1)?;
            match &v[0] {
                Value::Text(s) if s.chars().any(|c| (c as u32) < 0x20) => {
                    Value::Text(unistr_quote_text(s))
                }
                other => Value::Text(quote_value(other)),
            }
        }
        "subtype" => {
            // The value's subtype. graphite tracks no subtypes, so this is
            // always 0 (SQLite also returns 0 for ordinary, non-JSON values).
            arity(&lname, args, 1)?;
            Value::Integer(0)
        }
        "sign" => {
            arity(&lname, args, 1)?;
            // Numeric (or losslessly-numeric text) only; otherwise NULL.
            let num = match &v[0] {
                Value::Integer(i) => Some(*i as f64),
                Value::Real(r) => Some(*r),
                Value::Text(s) => eval::parse_decimal_f64(s.trim()),
                _ => None,
            };
            match num {
                Some(r) if r > 0.0 => Value::Integer(1),
                Some(r) if r < 0.0 => Value::Integer(-1),
                Some(_) => Value::Integer(0),
                None => Value::Null,
            }
        }
        "concat" => {
            // SQLite 3.44+: concatenate all args, treating NULL as empty.
            // At least one argument is required.
            if v.is_empty() {
                return Err(wrong_arg_count("concat"));
            }
            let mut s = String::new();
            for x in &v {
                if !matches!(x, Value::Null) {
                    s.push_str(&eval::to_text(x));
                }
            }
            Value::Text(s)
        }
        "concat_ws" => {
            // A separator plus at least one value argument are required.
            if v.len() < 2 {
                return Err(wrong_arg_count("concat_ws"));
            }
            if matches!(v[0], Value::Null) {
                Value::Null
            } else {
                let sep = eval::to_text(&v[0]);
                let parts: alloc::vec::Vec<String> = v[1..]
                    .iter()
                    .filter(|x| !matches!(x, Value::Null))
                    .map(eval::to_text)
                    .collect();
                Value::Text(parts.join(&sep))
            }
        }
        "like" => {
            // like(pattern, text[, escape]) — the function form of `text LIKE
            // pattern`. NULL operand → NULL.
            if v.len() < 2 || v.len() > 3 {
                return Err(wrong_arg_count("like"));
            }
            // A NULL escape, like a NULL pattern/text, yields NULL.
            if v.iter().any(|x| matches!(x, Value::Null)) {
                Value::Null
            } else {
                // An explicit ESCAPE must be exactly one character (SQLite
                // raises "ESCAPE expression must be a single character" for
                // empty or multi-character escapes).
                let escape = match v.get(2) {
                    Some(e) => {
                        let s = eval::to_text(e);
                        let mut it = s.chars();
                        match (it.next(), it.next()) {
                            (Some(c), None) => Some(c),
                            _ => {
                                return Err(Error::Error(
                                    "ESCAPE expression must be a single character".into(),
                                ));
                            }
                        }
                    }
                    None => None,
                };
                let m = eval::like_match_escape(
                    &eval::to_text(&v[0]),
                    &eval::to_text(&v[1]),
                    escape,
                    ctx.subqueries.is_some_and(|s| s.case_sensitive_like()),
                );
                Value::Integer(m as i64)
            }
        }
        // Optimizer hints that are no-ops at the value level (return the operand).
        "likely" | "unlikely" => {
            arity(&lname, args, 1)?;
            v[0].clone()
        }
        "likelihood" => {
            arity(&lname, args, 2)?;
            // SQLite requires the second argument to be a floating-point *literal*
            // in the range 0.0..=1.0, checked against the parsed AST rather than
            // the runtime value: an integer literal (`0`, `1`, `2`), a negative,
            // a string, an expression (`0.5+0.1`), or a column reference are all
            // rejected, while `0.5`, `.5`, `1e0` and a parenthesized `(0.5)` are
            // accepted (`exprProbability` in SQLite's `expr.c`).
            if !likelihood_prob_is_valid(&args[1]) {
                return Err(Error::Error(
                    "second argument to likelihood() must be a constant between 0.0 and 1.0".into(),
                ));
            }
            v[0].clone()
        }
        "unhex" => {
            if v.is_empty() || v.len() > 2 {
                return Err(wrong_arg_count("unhex"));
            }
            // A NULL hex string or NULL ignore-set both yield NULL.
            let ignore = match v.get(1) {
                Some(Value::Null) => return Ok(Value::Null),
                // The ignore set is itself coerced as a C string (NUL-terminated).
                Some(set) => Some(c_text(set)),
                None => None,
            };
            match &v[0] {
                Value::Null => Value::Null,
                // The hex input is read as a NUL-terminated C string, matching
                // SQLite's `unhexFunc` (`sqlite3_value_text`).
                other => match unhex(&c_text(other), ignore.as_deref()) {
                    Some(b) => Value::Blob(b),
                    None => Value::Null,
                },
            }
        }
        // Math functions (SQLite's `-DSQLITE_ENABLE_MATH_FUNCTIONS` set; the CLI
        // ships with these enabled). Each coerces its argument(s) to a real and
        // returns NULL when an argument is NULL or the result is not finite,
        // matching SQLite.
        "pi" => {
            arity(&lname, args, 0)?;
            Value::Real(crate::util::float::PI)
        }
        "ceil" | "ceiling" => math_round_to_int(&lname, &v, crate::util::float::ceil)?,
        "floor" => math_round_to_int(&lname, &v, crate::util::float::floor)?,
        "trunc" => math_round_to_int(&lname, &v, crate::util::float::trunc)?,
        "sqrt" => math1(&lname, &v, crate::util::float::sqrt)?,
        "exp" => math1(&lname, &v, crate::util::float::exp)?,
        "ln" => math1(&lname, &v, crate::util::float::ln)?,
        "log2" => math1(&lname, &v, crate::util::float::log2)?,
        "sin" => math1(&lname, &v, crate::util::float::sin)?,
        "cos" => math1(&lname, &v, crate::util::float::cos)?,
        "tan" => math1(&lname, &v, crate::util::float::tan)?,
        "asin" => math1(&lname, &v, crate::util::float::asin)?,
        "acos" => math1(&lname, &v, crate::util::float::acos)?,
        "atan" => math1(&lname, &v, crate::util::float::atan)?,
        "sinh" => math1(&lname, &v, crate::util::float::sinh)?,
        "cosh" => math1(&lname, &v, crate::util::float::cosh)?,
        "tanh" => math1(&lname, &v, crate::util::float::tanh)?,
        "asinh" => math1(&lname, &v, crate::util::float::asinh)?,
        "acosh" => math1(&lname, &v, crate::util::float::acosh)?,
        "atanh" => math1(&lname, &v, crate::util::float::atanh)?,
        "degrees" => math1(&lname, &v, crate::util::float::degrees)?,
        "radians" => math1(&lname, &v, crate::util::float::radians)?,
        // `log(X)` is base-10; `log(B, X)` is base B. `log10` is base-10.
        "log10" => math1(&lname, &v, crate::util::float::log10)?,
        "log" => {
            if v.len() == 1 {
                math_finite(real_arg(&v[0]).map(crate::util::float::log10))
            } else {
                arity(&lname, args, 2)?;
                match (real_arg(&v[0]), real_arg(&v[1])) {
                    // `log(B, X)` is NULL unless `B > 0`, `B != 1`, and `X > 0`
                    // (SQLite). A base of 1 makes `ln(B) == 0`, which the bare
                    // division would turn into ±Inf instead of NULL, so guard it.
                    (Some(1.0), Some(_)) => Value::Null,
                    (Some(b), Some(x)) => {
                        math_finite(Some(crate::util::float::ln(x) / crate::util::float::ln(b)))
                    }
                    _ => Value::Null,
                }
            }
        }
        "pow" | "power" => {
            arity(&lname, args, 2)?;
            match (real_arg(&v[0]), real_arg(&v[1])) {
                (Some(b), Some(e)) => math_finite(Some(crate::util::float::pow(b, e))),
                _ => Value::Null,
            }
        }
        "atan2" => {
            arity(&lname, args, 2)?;
            match (real_arg(&v[0]), real_arg(&v[1])) {
                (Some(y), Some(x)) => math_finite(Some(crate::util::float::atan2(y, x))),
                _ => Value::Null,
            }
        }
        "mod" => {
            arity(&lname, args, 2)?;
            match (real_arg(&v[0]), real_arg(&v[1])) {
                (Some(x), Some(y)) => math_finite(Some(crate::util::float::fmod(x, y))),
                _ => Value::Null,
            }
        }
        // JSON functions (see `super::json`).
        "json" => {
            arity(&lname, args, 1)?;
            match json_root(&v[0])? {
                None => Value::Null,
                Some(j) => Value::Text(j.serialize()),
            }
        }
        // `jsonb(X)` — the JSONB (binary) form of `json(X)`: parse the JSON/JSON5
        // text (or pass a JSONB blob through) and return its JSONB encoding.
        "jsonb" => {
            arity(&lname, args, 1)?;
            match json_root(&v[0])? {
                None => Value::Null,
                Some(j) => Value::Blob(j.to_jsonb()),
            }
        }
        "json_valid" => {
            if v.is_empty() || v.len() > 2 {
                return Err(Error::Error(
                    "wrong number of arguments to function json_valid()".into(),
                ));
            }
            // The optional flags select which well-formedness checks count, and
            // must be 1..=15 (sqlite errors otherwise): 0x01 = strict RFC-8259
            // JSON text, 0x02 = JSON5 text, 0x04 = a BLOB that looks like JSONB,
            // 0x08 = a BLOB that is fully-valid JSONB. The 1-argument form is 0x01
            // (strict JSON only) — JSON5 acceptance needs the explicit flag.
            let flags = match v.get(1) {
                None => 1,
                Some(f) => {
                    let n = eval::to_int_value(f);
                    if !(1..=15).contains(&n) {
                        return Err(Error::Error(
                            "FLAGS parameter to json_valid() must be between 1 and 15".into(),
                        ));
                    }
                    n
                }
            };
            match &v[0] {
                Value::Null => Value::Null,
                // A BLOB is only ever judged against the JSONB flag bits; text bits
                // do not apply (and vice versa for a text value).
                Value::Blob(b) => {
                    let ok = flags & 0x0c != 0 && super::json::Json::from_jsonb(b).is_some();
                    Value::Integer(ok as i64)
                }
                other => {
                    let text = eval::to_text(other);
                    let ok = (flags & 0x01 != 0 && super::json::is_strict_json(&text))
                        || (flags & 0x02 != 0 && super::json::parse(&text).is_some());
                    Value::Integer(ok as i64)
                }
            }
        }
        // `json_error_position(X)` — the 1-based byte position of the first JSON
        // syntax error in X, or 0 when X is well-formed JSON. NULL yields NULL,
        // matching sqlite3.
        "json_error_position" => {
            arity(&lname, args, 1)?;
            match &v[0] {
                Value::Null => Value::Null,
                other => {
                    let pos = match super::json::parse_with_error_position(&eval::to_text(other)) {
                        Ok(_) => 0,
                        Err(off) => off as i64 + 1,
                    };
                    Value::Integer(pos)
                }
            }
        }
        // `json_pretty(X [, indent])` — reformat with indentation (default 4
        // spaces). Empty arrays/objects and scalars stay compact, like SQLite.
        "json_pretty" => {
            if v.is_empty() || v.len() > 2 {
                return Err(wrong_arg_count("json_pretty"));
            }
            match &v[0] {
                Value::Null => Value::Null,
                other => {
                    let indent = match v.get(1) {
                        Some(Value::Null) | None => alloc::string::String::from("    "),
                        Some(iv) => eval::to_text(iv),
                    };
                    let _ = other;
                    match json_root(&v[0])? {
                        None => Value::Null,
                        Some(j) => Value::Text(j.pretty(&indent)),
                    }
                }
            }
        }
        "json_quote" => {
            arity(&lname, args, 1)?;
            // A BLOB that decodes as JSONB renders as its JSON text (so
            // `json_quote(x'01')` → `true`, `json_quote(jsonb('[1,2]'))` →
            // `[1,2]`); any other BLOB is rejected. graphite has no value
            // subtypes, so it falls back to "does it parse as JSONB", matching
            // sqlite.
            let j = match &v[0] {
                Value::Blob(b) => super::json::Json::from_jsonb(b)
                    .ok_or_else(|| Error::Error("JSON cannot hold BLOB values".into()))?,
                other => super::json::value_to_json(other),
            };
            Value::Text(j.quote())
        }
        "json_type" => {
            if v.is_empty() || v.len() > 2 {
                return Err(wrong_arg_count("json_type"));
            }
            match json_root(&v[0])? {
                None => Value::Null,
                Some(root) => {
                    let target = if v.len() == 2 {
                        check_path(&v[1])?;
                        super::json::navigate(&root, &eval::to_text(&v[1]))
                    } else {
                        Some(&root)
                    };
                    match target {
                        Some(j) => Value::Text(String::from(j.type_name())),
                        None => Value::Null,
                    }
                }
            }
        }
        "json_array_length" => {
            if v.is_empty() || v.len() > 2 {
                return Err(wrong_arg_count("json_array_length"));
            }
            match json_root(&v[0])? {
                None => Value::Null,
                Some(root) => {
                    let target = if v.len() == 2 {
                        check_path(&v[1])?;
                        super::json::navigate(&root, &eval::to_text(&v[1]))
                    } else {
                        Some(&root)
                    };
                    match target {
                        Some(super::json::Json::Array(items)) => Value::Integer(items.len() as i64),
                        Some(_) => Value::Integer(0),
                        None => Value::Null,
                    }
                }
            }
        }
        "json_extract" | "jsonb_extract" => {
            // SQLite's json_extract is variadic: with fewer than two arguments
            // it returns NULL without even parsing the document (so an invalid
            // or absent first argument is NOT an error here).
            if v.len() < 2 {
                return Ok(Value::Null);
            }
            match json_root(&v[0])? {
                None => Value::Null,
                Some(root) => json_extract(&root, &v[1..], lname.starts_with("jsonb"))?,
            }
        }
        "json_array" | "jsonb_array" => {
            let mut items = Vec::with_capacity(v.len());
            for (i, val) in v.iter().enumerate() {
                items.push(json_value_arg(val, args.get(i))?);
            }
            json_doc_result(&lname, &super::json::Json::Array(items))
        }
        "json_object" | "jsonb_object" => {
            if !v.len().is_multiple_of(2) {
                return Err(Error::Error(
                    "json_object() requires an even number of arguments".into(),
                ));
            }
            let mut members = Vec::with_capacity(v.len() / 2);
            for pair in v.chunks(2).enumerate() {
                let (i, kv) = pair;
                // SQLite requires object labels to be TEXT (a NULL, numeric, or
                // BLOB key is an error), and rejects BLOB values.
                let Value::Text(key) = &kv[0] else {
                    return Err(Error::Error("json_object() labels must be TEXT".into()));
                };
                let val = json_value_arg(&kv[1], args.get(2 * i + 1))?;
                // A key built from a SQL TEXT arg carries no escape provenance.
                members.push((key.clone(), None, val));
            }
            json_doc_result(&lname, &super::json::Json::Object(members))
        }
        "json_set" | "json_insert" | "json_replace" | "jsonb_set" | "jsonb_insert"
        | "jsonb_replace" => {
            // sqlite: zero args → NULL; an even arg count is a hard error (the
            // message always names the text-output `json_*` form, even for the
            // `jsonb_*` blob variants); an odd count is the document followed by
            // zero or more (path, value) pairs (a bare document is a no-op).
            if v.is_empty() {
                return Ok(Value::Null);
            }
            if v.len().is_multiple_of(2) {
                let report = lname
                    .strip_prefix("jsonb_")
                    .map_or_else(|| lname.clone(), |rest| alloc::format!("json_{rest}"));
                return Err(Error::Error(alloc::format!(
                    "{report}() needs an odd number of arguments"
                )));
            }
            let mode = if lname.ends_with("set") {
                super::json::SetMode::Set
            } else if lname.ends_with("insert") {
                super::json::SetMode::Insert
            } else {
                super::json::SetMode::Replace
            };
            match json_root(&v[0])? {
                None => Value::Null,
                Some(mut root) => {
                    let mut i = 1;
                    while i + 1 < v.len() {
                        check_path(&v[i])?;
                        let path = eval::to_text(&v[i]);
                        let val = json_value_arg(&v[i + 1], args.get(i + 1))?;
                        super::json::set_path(&mut root, &path, val, mode);
                        i += 2;
                    }
                    json_doc_result(&lname, &root)
                }
            }
        }
        "json_remove" | "jsonb_remove" => {
            if v.is_empty() {
                return Err(Error::Error("json_remove() requires a document".into()));
            }
            match json_root(&v[0])? {
                None => Value::Null,
                Some(mut root) => {
                    let mut removed = Value::Text(String::new());
                    for p in &v[1..] {
                        // A NULL path collapses the whole call to NULL (scanning
                        // left to right, so a malformed path *before* it still
                        // errors via check_path first), discarding any removals
                        // already applied — matching sqlite's json_remove.
                        if matches!(p, Value::Null) {
                            removed = Value::Null;
                            break;
                        }
                        check_path(p)?;
                        // Removing the whole document (`$`) yields SQL NULL.
                        if matches!(p, Value::Text(s) if s == "$") {
                            removed = Value::Null;
                            continue;
                        }
                        super::json::remove_path(&mut root, &eval::to_text(p));
                    }
                    if matches!(removed, Value::Null) {
                        Value::Null
                    } else {
                        json_doc_result(&lname, &root)
                    }
                }
            }
        }
        "json_patch" | "jsonb_patch" => {
            arity(&lname, args, 2)?;
            match (json_root(&v[0])?, json_root(&v[1])?) {
                (Some(mut root), Some(patch)) => {
                    super::json::merge_patch(&mut root, &patch);
                    json_doc_result(&lname, &root)
                }
                _ => Value::Null,
            }
        }
        // Date/time functions (see `super::datetime`).
        "date" => super::datetime::date(&v),
        "time" => super::datetime::time(&v),
        "datetime" => super::datetime::datetime(&v),
        "julianday" => super::datetime::julianday(&v),
        "unixepoch" => super::datetime::unixepoch(&v),
        "strftime" => super::datetime::strftime(&v),
        "timediff" => {
            arity(&lname, args, 2)?;
            super::datetime::timediff(&v[0], &v[1])
        }
        "geopoly_json" => {
            arity(&lname, args, 1)?;
            match crate::geopoly::parse_value(&v[0]) {
                Some(p) => Value::Text(p.to_json()),
                None => Value::Null,
            }
        }
        "geopoly_blob" => {
            arity(&lname, args, 1)?;
            match crate::geopoly::parse_value(&v[0]) {
                Some(p) => Value::Blob(p.to_blob()),
                None => Value::Null,
            }
        }
        "geopoly_area" => {
            arity(&lname, args, 1)?;
            match crate::geopoly::parse_value(&v[0]) {
                Some(p) => Value::Real(p.area()),
                None => Value::Null,
            }
        }
        "geopoly_bbox" => {
            arity(&lname, args, 1)?;
            match crate::geopoly::parse_value(&v[0]) {
                Some(p) => Value::Blob(p.bbox().to_blob()),
                None => Value::Null,
            }
        }
        "geopoly_ccw" => {
            arity(&lname, args, 1)?;
            match crate::geopoly::parse_value(&v[0]) {
                Some(p) => Value::Blob(p.ccw().to_blob()),
                None => Value::Null,
            }
        }
        "geopoly_regular" => {
            arity(&lname, args, 4)?;
            // A NULL argument yields NULL (SQLite's `sqlite3_value_double`/`int`
            // treat NULL as 0, but n<3 or r<=0 then returns NULL anyway; an
            // explicit NULL check keeps the common cases NULL-clean).
            if v.iter().any(|x| matches!(x, Value::Null)) {
                Value::Null
            } else {
                let cx = eval::to_f64(&v[0]);
                let cy = eval::to_f64(&v[1]);
                let r = eval::to_f64(&v[2]);
                let n = eval::to_int_value(&v[3]);
                match crate::geopoly::regular(cx, cy, r, n) {
                    Some(p) => Value::Blob(p.to_blob()),
                    None => Value::Null,
                }
            }
        }
        "geopoly_contains_point" => {
            arity(&lname, args, 3)?;
            match crate::geopoly::parse_value(&v[0]) {
                Some(p) => {
                    Value::Integer(p.contains_point(eval::to_f64(&v[1]), eval::to_f64(&v[2])))
                }
                None => Value::Null,
            }
        }
        "geopoly_overlap" => {
            arity(&lname, args, 2)?;
            match (
                crate::geopoly::parse_value(&v[0]),
                crate::geopoly::parse_value(&v[1]),
            ) {
                (Some(p1), Some(p2)) => Value::Integer(crate::geopoly::overlap(&p1, &p2)),
                _ => Value::Null,
            }
        }
        "geopoly_within" => {
            arity(&lname, args, 2)?;
            match (
                crate::geopoly::parse_value(&v[0]),
                crate::geopoly::parse_value(&v[1]),
            ) {
                (Some(p1), Some(p2)) => Value::Integer(crate::geopoly::within(&p1, &p2)),
                _ => Value::Null,
            }
        }
        "geopoly_svg" => {
            // geopoly_svg(X, ...) is variadic. With no arguments SQLite's
            // implementation simply returns NULL (`if(argc<1) return;`) rather
            // than raising an arity error.
            if args.is_empty() {
                return Ok(Value::Null);
            }
            match crate::geopoly::parse_value(&v[0]) {
                Some(p) => {
                    let extra: Vec<Option<String>> = v[1..]
                        .iter()
                        .map(|x| match x {
                            Value::Null => None,
                            other => Some(eval::to_text(other)),
                        })
                        .collect();
                    Value::Text(p.to_svg(&extra))
                }
                None => Value::Null,
            }
        }
        "geopoly_xform" => {
            arity(&lname, args, 7)?;
            match crate::geopoly::parse_value(&v[0]) {
                Some(p) => Value::Blob(
                    p.xform(
                        eval::to_f64(&v[1]),
                        eval::to_f64(&v[2]),
                        eval::to_f64(&v[3]),
                        eval::to_f64(&v[4]),
                        eval::to_f64(&v[5]),
                        eval::to_f64(&v[6]),
                    )
                    .to_blob(),
                ),
                None => Value::Null,
            }
        }
        "printf" | "format" => super::datetime::printf(&v),
        _ => {
            // A user-defined function registered via `register_function`. Builtins
            // above take precedence; this fires only for an otherwise-unknown name.
            if let Some(result) = ctx.subqueries.and_then(|s| s.call_udf(&lname, &v)) {
                return result;
            }
            // A built-in window/ranking function used outside an `OVER` clause is
            // "misuse of window function NAME()" in SQLite, not "no such function".
            if is_window_function_name(&lname) {
                return Err(Error::Error(alloc::format!(
                    "misuse of window function {lname}()"
                )));
            }
            // `RAISE(...)` parses into a canonical `raise(...)` call. A real
            // trigger program intercepts it before evaluation (see `fire_raise`);
            // reaching scalar dispatch means it was used outside a trigger, which
            // SQLite rejects with this dedicated message rather than "no such
            // function".
            if lname == "raise" {
                return Err(Error::Error(alloc::string::String::from(
                    "RAISE() may only be used within a trigger-program",
                )));
            }
            return Err(Error::Error(alloc::format!("no such function: {name}")));
        }
    })
}

/// Render a value as a SQL literal, like SQLite's `quote()`.
fn quote_value(v: &Value) -> String {
    match v {
        Value::Null => String::from("NULL"),
        Value::Integer(i) => alloc::format!("{i}"),
        // `quote()` renders an infinity as `±9.0e+999` (unlike plain text output,
        // which prints `Inf`).
        Value::Real(r) if !r.is_finite() => {
            String::from(if *r < 0.0 { "-9.0e+999" } else { "9.0e+999" })
        }
        // `quote()` renders a finite real at round-trip precision (`%!0.15g`,
        // falling back to `%!0.20e`), unlike the 15-significant-digit column
        // rendering `format_real` produces — so a dumped real reparses exactly.
        Value::Real(r) => crate::util::fpdecode::quote_real(*r),
        Value::Text(s) => {
            // SQLite's `quote()` reads the text through `sqlite3_value_text`, a
            // NUL-terminated C string, so an embedded NUL truncates the rendered
            // literal (the stored value keeps its full bytes). Match that.
            let s = s.split('\0').next().unwrap_or("");
            alloc::format!("'{}'", s.replace('\'', "''"))
        }
        Value::Blob(b) => {
            // SQLite renders blob literals as `X'ABCD'` — uppercase `X` and
            // uppercase hex digits.
            let mut s = String::from("X'");
            for byte in b {
                s.push_str(&alloc::format!("{byte:02X}"));
            }
            s.push('\'');
            s
        }
    }
}

/// Decode SQLite `unistr()` escapes: `\uXXXX` (4 hex), `\UXXXXXXXX` (8 hex), and
/// `\\` (a literal backslash). Any other backslash sequence — including a `\u`/
/// `\U` with too few hex digits or a trailing `\` — is an error, matching
/// SQLite's "invalid Unicode escape". A code point Rust cannot represent (a lone
/// surrogate or one past U+10FFFF) becomes the replacement char `U+FFFD`; SQLite
/// emits raw WTF-8 there, an extreme edge graphite cannot store in a `String`.
fn unistr_decode(s: &str) -> Result<String> {
    let cs: alloc::vec::Vec<char> = s.chars().collect();
    let mut out = String::with_capacity(s.len());
    let invalid = || Error::Error(String::from("invalid Unicode escape"));
    let hex_char = |cs: &[char], at: usize, n: usize| -> Option<u32> {
        let slice = cs.get(at..at + n)?;
        if !slice.iter().all(|c| c.is_ascii_hexdigit()) {
            return None;
        }
        let s: String = slice.iter().collect();
        u32::from_str_radix(&s, 16).ok()
    };
    let mut i = 0;
    while i < cs.len() {
        if cs[i] != '\\' {
            out.push(cs[i]);
            i += 1;
            continue;
        }
        match cs.get(i + 1) {
            Some('\\') => {
                out.push('\\');
                i += 2;
            }
            Some('u') => {
                let cp = hex_char(&cs, i + 2, 4).ok_or_else(invalid)?;
                out.push(char::from_u32(cp).unwrap_or('\u{FFFD}'));
                i += 6;
            }
            Some('U') => {
                let cp = hex_char(&cs, i + 2, 8).ok_or_else(invalid)?;
                out.push(char::from_u32(cp).unwrap_or('\u{FFFD}'));
                i += 10;
            }
            _ => return Err(invalid()),
        }
    }
    Ok(out)
}

/// Render a control-character-bearing text value as SQLite's `unistr('…')`: each
/// character below U+0020 becomes `\uXXXX`, a backslash doubles, a single quote
/// doubles, everything else (including non-ASCII) is kept literal.
fn unistr_quote_text(s: &str) -> String {
    let mut out = String::from("unistr('");
    for c in s.chars() {
        let cp = c as u32;
        if cp < 0x20 {
            out.push_str(&alloc::format!("\\u{cp:04x}"));
        } else if c == '\\' {
            out.push_str("\\\\");
        } else if c == '\'' {
            out.push_str("''");
        } else {
            out.push(c);
        }
    }
    out.push_str("')");
    out
}

/// Decode a hex string to bytes, returning `None` on malformed input. A faithful
/// port of SQLite's `unhexFunc`:
///
/// - with no ignore set (`ignore` is `None`), the input must be an even number of
///   hex digits and nothing else;
/// - with an ignore set (the 2-argument form), characters from `ignore` may
///   appear *before*, *between*, and *after* complete byte pairs, but never
///   *within* a pair — so `unhex('AB CD', ' ')` is `X'ABCD'` while
///   `unhex('A BCD', ' ')` is `NULL`. Any character that is neither a hex digit
///   nor in the ignore set fails the whole decode.
fn unhex(s: &str, ignore: Option<&str>) -> Option<alloc::vec::Vec<u8>> {
    let hexval = |c: char| -> Option<u8> {
        match c {
            '0'..='9' => Some(c as u8 - b'0'),
            'a'..='f' => Some(c as u8 - b'a' + 10),
            'A'..='F' => Some(c as u8 - b'A' + 10),
            _ => None,
        }
    };
    let ignored = |c: char| -> bool { ignore.is_some_and(|set| set.contains(c)) };
    let mut out = alloc::vec::Vec::new();
    let mut it = s.chars();
    loop {
        // Skip any leading/inter-pair ignore characters. A non-ignored,
        // non-hex-digit character (or running out of input) ends this phase.
        let hi = loop {
            match it.next() {
                None => return Some(out),
                Some(c) if hexval(c).is_some() => break c,
                Some(c) if ignored(c) => continue,
                Some(_) => return None,
            }
        };
        // The second nibble must immediately follow the first.
        let lo = it.next()?;
        out.push((hexval(hi)? << 4) | hexval(lo)?);
    }
}

/// Whether `e` is an acceptable `likelihood()` probability: a floating-point
/// literal in `0.0..=1.0`, after peeling any redundant parentheses. SQLite's
/// `exprProbability` only accepts a bare `TK_FLOAT` token in range, so an
/// integer literal, a negated float, or any compound expression is rejected.
pub(crate) fn likelihood_prob_is_valid(e: &Expr) -> bool {
    match e {
        Expr::Paren(inner) => likelihood_prob_is_valid(inner),
        Expr::Literal(Literal::Real(r)) => (0.0..=1.0).contains(r),
        _ => false,
    }
}

fn arity(name: &str, args: &[Expr], n: usize) -> Result<()> {
    if args.len() == n {
        Ok(())
    } else {
        Err(wrong_arg_count(name))
    }
}

/// SQLite's universal arity-error message: `wrong number of arguments to
/// function NAME()` — no "(want N, got M)" suffix, for every built-in.
fn wrong_arg_count(name: &str) -> Error {
    Error::Error(alloc::format!(
        "wrong number of arguments to function {name}()"
    ))
}

/// The built-in ranking/value window functions, which are only valid inside an
/// `OVER` clause. Called as a plain scalar, SQLite reports "misuse of window
/// function NAME()". `name` must already be lowercased.
fn is_window_function_name(name: &str) -> bool {
    matches!(
        name,
        "row_number"
            | "rank"
            | "dense_rank"
            | "percent_rank"
            | "cume_dist"
            | "ntile"
            | "first_value"
            | "last_value"
            | "nth_value"
            | "lag"
            | "lead"
    )
}

/// SQLite's `soundex(X)`: the phonetic code of the first word in `X` — the first
/// letter followed by up to three digits, padded with `0`. Input with no letters
/// (including NULL, which `to_text` maps to "") yields `"?000"`. Faithful port of
/// `soundexFunc`: each letter maps to a digit; a digit is emitted only when it is
/// nonzero and differs from the previous letter's code; a zero-code character
/// (vowel, `H`/`W`/`Y`, or non-letter) resets the running code.
fn soundex(s: &str) -> String {
    // Code for a-z (index `c.to_ascii_lowercase() - b'a'`); 0 = not coded.
    const CODE: [u8; 26] = [
        0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0, 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2,
    ];
    let code_of = |c: u8| -> u8 {
        if c.is_ascii_alphabetic() {
            CODE[(c.to_ascii_lowercase() - b'a') as usize]
        } else {
            0
        }
    };
    let b = s.as_bytes();
    let mut i = 0;
    while i < b.len() && !b[i].is_ascii_alphabetic() {
        i += 1;
    }
    if i >= b.len() {
        return String::from("?000");
    }
    let mut out = String::with_capacity(4);
    out.push(b[i].to_ascii_uppercase() as char);
    let mut prev = code_of(b[i]);
    let mut j = 1;
    while j < 4 && i < b.len() {
        let code = code_of(b[i]);
        if code > 0 {
            if code != prev {
                prev = code;
                out.push((b'0' + code) as char);
                j += 1;
            }
        } else {
            prev = 0;
        }
        i += 1;
    }
    while j < 4 {
        out.push('0');
        j += 1;
    }
    out
}

/// Coerce a value to text for the string functions (`trim`/`upper`/`lower`/
/// `replace`/`substr`/`soundex`).
///
/// When the value is a BLOB, SQLite reads it as a NUL-terminated C string
/// (`sqlite3_value_text`), so an embedded `NUL` byte truncates the coerced
/// text: `trim(X'00200041…')` is `''`, not `'   A   '`. We reproduce that for
/// the blob path. A genuine TEXT value keeps its embedded NULs: this engine's
/// TEXT model is NUL-preserving (e.g. the JSON5 `\0` escape stores a real NUL
/// character — see `tests/json5.rs`), and `length`/`unicode` count through it,
/// so truncating TEXT here would be inconsistent with the rest of the engine.
fn c_text(v: &Value) -> String {
    match v {
        Value::Blob(b) => {
            let end = b.iter().position(|&x| x == 0).unwrap_or(b.len());
            String::from_utf8_lossy(&b[..end]).into_owned()
        }
        other => eval::to_text(other),
    }
}

fn str_map(v: &Value, f: impl Fn(&str) -> String) -> Value {
    match v {
        Value::Null => Value::Null,
        other => Value::Text(f(&c_text(other))),
    }
}

/// A numeric argument to a math function: `None` for SQL `NULL`, else the value
/// coerced to `f64` (SQLite applies REAL affinity to math-function arguments).
/// Coerce a math-function argument to `f64` using SQLite's
/// `sqlite3_value_numeric_type` rule: an INTEGER / REAL — or a text that is wholly
/// numeric (`'4'`, `'  9  '`, `'2e2'`) — yields its numeric value, while a
/// non-numeric text, a blob, or NULL yields `None` (so the caller returns SQL
/// NULL). This is *not* the lax `to_f64`, which would turn `'abc'` or a blob into
/// `0.0` and silently feed it to `sqrt`/`log`/`pow`/…
fn real_arg(v: &Value) -> Option<f64> {
    eval::to_number_strict(v).map(|n| eval::to_f64(&n))
}

/// Wrap a computed math result, matching SQLite's split between a *domain error*
/// and an *overflow*:
///
/// - a missing argument or a `NaN` result (`sqrt(-1)`, `ln(0)`, `acos(2)`, …)
///   becomes SQL `NULL`;
/// - a `±∞` result is kept as a `REAL` — both genuine overflow (`exp(710)`,
///   `pow(2,2000)`) and poles (`pow(0,-1)`, `atanh(1)`) render as `Inf`/`-Inf`,
///   exactly as SQLite reports them.
///
/// Each underlying `float` routine is responsible for returning `NaN` (not `±∞`)
/// on a domain error, so that the NULL-vs-Inf decision is made consistently here.
fn math_finite(r: Option<f64>) -> Value {
    match r {
        Some(x) if x.is_nan() => Value::Null,
        Some(x) => Value::Real(x),
        None => Value::Null,
    }
}

/// A one-argument math function: arity-check, coerce, apply, finiteness-guard.
fn math1(name: &str, v: &[Value], f: impl Fn(f64) -> f64) -> Result<Value> {
    if v.len() != 1 {
        return Err(Error::Error(alloc::format!(
            "wrong number of arguments to function {name}()"
        )));
    }
    Ok(math_finite(real_arg(&v[0]).map(f)))
}

/// `ceil`/`ceiling`/`floor`/`trunc`: SQLite dispatches on `sqlite3_value_numeric_type`
/// — an INTEGER argument is returned UNCHANGED (so its exact value, incl. i64
/// extremes, survives), a REAL is rounded to a REAL, and a non-numeric text / blob
/// / NULL argument yields NULL. This differs from the other `math1` functions,
/// which always coerce to a real (and read a blob's bytes as a number).
fn math_round_to_int(name: &str, v: &[Value], f: impl Fn(f64) -> f64) -> Result<Value> {
    if v.len() != 1 {
        return Err(Error::Error(alloc::format!(
            "wrong number of arguments to function {name}()"
        )));
    }
    Ok(match eval::to_number_strict(&v[0]) {
        Some(Value::Integer(i)) => Value::Integer(i),
        Some(Value::Real(r)) => math_finite(Some(f(r))),
        _ => Value::Null,
    })
}

/// Parse the first argument of a JSON function as a document: `NULL` → `None`;
/// malformed JSON is an error (matching SQLite).
/// Render a JSON document result as text (`json_*`) or as a JSONB blob
/// (`jsonb_*`), chosen by the function name.
fn json_doc_result(lname: &str, j: &super::json::Json) -> Value {
    if lname.starts_with("jsonb") {
        Value::Blob(j.to_jsonb())
    } else {
        Value::Text(j.serialize())
    }
}

fn json_root(v: &Value) -> Result<Option<super::json::Json>> {
    match v {
        Value::Null => Ok(None),
        // A BLOB document is JSONB (SQLite's binary JSON); text is JSON/JSON5.
        Value::Blob(b) => match super::json::Json::from_jsonb(b) {
            Some(j) => Ok(Some(j)),
            None => Err(Error::Error("malformed JSON".into())),
        },
        other => match super::json::parse(&eval::to_text(other)) {
            Some(j) => Ok(Some(j)),
            None => Err(Error::Error("malformed JSON".into())),
        },
    }
}

/// Validate a JSON path argument, raising SQLite's `bad JSON path: '<path>'`
/// error if it is malformed. A `NULL` path is left for the caller to treat as a
/// missing lookup (SQLite returns NULL rather than erroring on a NULL path).
fn check_path(p: &Value) -> Result<()> {
    // A NULL path is not validated — callers treat it as a missing lookup
    // (SQLite returns NULL rather than erroring). Every other type is coerced to
    // text first (SQLite applies its usual text conversion before parsing the
    // path), so an integer/real/blob argument is validated as the path it spells
    // — e.g. `json_extract(j, 1)` raises `bad JSON path: '1'`, just like sqlite.
    if matches!(p, Value::Null) {
        return Ok(());
    }
    let s = eval::to_text(p);
    if !super::json::path_is_valid(&s) {
        return Err(Error::Error(alloc::format!("bad JSON path: '{s}'")));
    }
    Ok(())
}

/// Convert a *value* argument of a JSON/JSONB constructor or mutator to JSON. A
/// BLOB is embedded as its JSON when it decodes as JSONB (so `jsonb_*` results
/// compose, e.g. `jsonb_object('a', jsonb_array(1,2))`) and otherwise rejected —
/// graphite has no value subtypes, so it falls back to "does it parse as JSONB".
fn json_value_arg(val: &Value, expr: Option<&Expr>) -> Result<super::json::Json> {
    if let Value::Blob(b) = val {
        return super::json::Json::from_jsonb(b)
            .ok_or_else(|| Error::Error("JSON cannot hold BLOB values".into()));
    }
    Ok(arg_to_json(val, expr))
}

/// `json_extract`: one path returns the SQL value at that path (objects/arrays as
/// minified JSON text); multiple paths return a JSON array of the extracted
/// elements (missing paths become JSON `null`). `jsonb_extract` is the same but
/// returns object/array results (and the multi-path array) as JSONB blobs.
fn json_extract(root: &super::json::Json, paths: &[Value], jsonb: bool) -> Result<Value> {
    // SQLite scans the paths left to right: a NULL path collapses the whole
    // result to NULL (even when a *later* path is malformed), but a malformed
    // non-NULL path that comes *first* still errors before the NULL is reached.
    for p in paths {
        if matches!(p, Value::Null) {
            return Ok(Value::Null);
        }
        check_path(p)?;
    }
    // A non-scalar single-path result is JSONB under jsonb_extract; scalars are
    // returned as their SQL value either way.
    let scalar_or_doc = |j: &super::json::Json| -> Value {
        match j {
            super::json::Json::Array(_) | super::json::Json::Object(_) if jsonb => {
                Value::Blob(j.to_jsonb())
            }
            _ => j.to_sql(),
        }
    };
    if paths.len() == 1 {
        return Ok(
            match super::json::navigate(root, &eval::to_text(&paths[0])) {
                Some(j) => scalar_or_doc(j),
                None => Value::Null,
            },
        );
    }
    let items = paths
        .iter()
        .map(|p| match super::json::navigate(root, &eval::to_text(p)) {
            Some(j) => j.clone(),
            None => super::json::Json::Null,
        })
        .collect();
    let arr = super::json::Json::Array(items);
    Ok(if jsonb {
        Value::Blob(arr.to_jsonb())
    } else {
        Value::Text(arr.serialize())
    })
}

/// Convert a constructor argument to JSON. If the source expression is itself a
/// JSON-producing call (`json`, `json_array`, `json_object`), its text value is
/// embedded as parsed JSON — mirroring SQLite's JSON subtype propagation — rather
/// than quoted as a string.
pub(crate) fn arg_to_json(val: &Value, expr: Option<&Expr>) -> super::json::Json {
    if let (Value::Text(s), Some(e)) = (val, expr) {
        if produces_json(e) {
            if let Some(j) = super::json::parse(s) {
                return j;
            }
        }
    }
    super::json::value_to_json(val)
}

/// Whether an expression *statically* yields a value carrying SQLite's JSON
/// subtype. Functions that always emit a JSON structure (including the
/// `json_group_array`/`json_group_object` aggregates) qualify; `json_extract`
/// only with two or more paths (then its result is always a JSON array — a
/// single path's subtype is value-dependent and needs the runtime subtype, not
/// modelled here); the `->` operator always carries the subtype (`->>` does not).
fn produces_json(e: &Expr) -> bool {
    match e {
        Expr::Function { name, args, .. } => {
            let lname = name.to_ascii_lowercase();
            match lname.as_str() {
                "json" | "json_array" | "json_object" | "json_insert" | "json_replace"
                | "json_set" | "json_patch" | "json_remove" | "json_group_array"
                | "json_group_object" => true,
                // Multiple paths → a JSON array (subtype). One path's subtype is
                // value-dependent (structure vs scalar), so don't claim it here.
                "json_extract" => args.len() >= 3,
                _ => false,
            }
        }
        // `->` (JsonExtract) carries the JSON subtype; `->>` (JsonExtractText) does not.
        Expr::Binary {
            op: crate::sql::ast::BinaryOp::JsonExtract,
            ..
        } => true,
        Expr::Paren(inner) => produces_json(inner),
        _ => false,
    }
}

fn type_name(v: &Value) -> &'static str {
    match v {
        Value::Null => "null",
        Value::Integer(_) => "integer",
        Value::Real(_) => "real",
        Value::Text(_) => "text",
        Value::Blob(_) => "blob",
    }
}

fn trim_fn(v: &[Value], left: bool, right: bool) -> Value {
    if v.is_empty() || matches!(v[0], Value::Null) {
        return Value::Null;
    }
    // A NULL trim-set yields NULL, like any other NULL argument (sqlite:
    // `trim(X, NULL)` / `ltrim` / `rtrim` are all NULL).
    if v.len() >= 2 && matches!(v[1], Value::Null) {
        return Value::Null;
    }
    let s = c_text(&v[0]);
    let trim_chars: Vec<char> = if v.len() >= 2 {
        c_text(&v[1]).chars().collect()
    } else {
        alloc::vec![' ']
    };
    let is_trim = |c: char| trim_chars.contains(&c);
    let chars: Vec<char> = s.chars().collect();
    let mut start = 0;
    let mut end = chars.len();
    if left {
        while start < end && is_trim(chars[start]) {
            start += 1;
        }
    }
    if right {
        while end > start && is_trim(chars[end - 1]) {
            end -= 1;
        }
    }
    Value::Text(chars[start..end].iter().collect())
}

fn substr(v: &[Value]) -> Result<Value> {
    if v.len() < 2 || v.len() > 3 {
        return Err(wrong_arg_count("substr"));
    }
    if matches!(v[0], Value::Null) {
        return Ok(Value::Null);
    }
    // `substr` of a blob slices bytes and returns a blob; otherwise it slices
    // characters of the text form and returns text.
    let blob = matches!(v[0], Value::Blob(_));
    let units: alloc::vec::Vec<char> = if blob {
        match &v[0] {
            Value::Blob(b) => b.iter().map(|&x| x as char).collect(),
            _ => unreachable!(),
        }
    } else {
        eval::to_text(&v[0]).chars().collect()
    };
    // `substr(x, NULL [, …])` returns NULL — a NULL start position propagates
    // like any other NULL argument (the length already does, below).
    if matches!(v[1], Value::Null) {
        return Ok(Value::Null);
    }
    let len = units.len() as i64;
    // Faithful port of SQLite's `substrFunc` (src/func.c): `p1` is a 1-based
    // start (negative counts from the end), `p2` a signed length (negative
    // means "the |p2| units ending at p1"). The default `p2` for the 2-arg form
    // is the LENGTH limit (1e9), which we clamp to `len` below. All arithmetic
    // saturates so pathological i64 inputs (e.g. i64::MIN) cannot overflow,
    // matching SQLite's behaviour where the window collapses to empty or the
    // whole string.
    let mut p1 = eval::to_int_value(&v[1]);
    let mut p2 = if v.len() == 3 {
        // `substr(x, p1, NULL)` returns NULL (the length argument is required
        // to be non-NULL to produce a value).
        if matches!(v[2], Value::Null) {
            return Ok(Value::Null);
        }
        eval::to_int_value(&v[2])
    } else {
        1_000_000_000
    };
    if p1 < 0 {
        p1 = p1.saturating_add(len);
        if p1 < 0 {
            if p2 < 0 {
                p2 = 0;
            } else {
                p2 = p2.saturating_add(p1);
            }
            p1 = 0;
        }
    } else if p1 > 0 {
        p1 -= 1;
    } else if p2 > 0 {
        p2 -= 1;
    }
    if p2 < 0 {
        if p2 < -p1 {
            p2 = p1;
        } else {
            p2 = -p2;
        }
        p1 = p1.saturating_sub(p2);
    }
    // `p1 >= 0 && p2 >= 0` now holds. Clamp the window to the available units.
    let start = (p1.max(0) as usize).min(units.len());
    let take = (p2.max(0) as usize).min(units.len() - start);
    let slice = &units[start..start + take];
    if blob {
        Ok(Value::Blob(slice.iter().map(|&c| c as u8).collect()))
    } else {
        Ok(Value::Text(slice.iter().collect()))
    }
}

fn instr(v: &[Value]) -> Result<Value> {
    if v.len() != 2 {
        return Err(wrong_arg_count("instr"));
    }
    if matches!(v[0], Value::Null) || matches!(v[1], Value::Null) {
        return Ok(Value::Null);
    }
    let hay = eval::to_text(&v[0]);
    let needle = eval::to_text(&v[1]);
    // SQLite returns a 1-based character index, 0 if not found.
    match hay.find(&needle) {
        None => Ok(Value::Integer(0)),
        Some(byte_idx) => {
            let char_idx = hay[..byte_idx].chars().count();
            Ok(Value::Integer(char_idx as i64 + 1))
        }
    }
}

fn replace(v: &[Value]) -> Result<Value> {
    if v.len() != 3 {
        return Err(wrong_arg_count("replace"));
    }
    // SQLite short-circuits in a specific order: a NULL subject or a NULL pattern
    // yields NULL, but an EMPTY pattern returns the subject (converted to text)
    // *before* the replacement argument is examined — so `replace('ab','',NULL)`
    // is `'ab'`, not NULL. Checking all three for NULL up front got this wrong.
    if matches!(v[0], Value::Null) || matches!(v[1], Value::Null) {
        return Ok(Value::Null);
    }
    let s = c_text(&v[0]);
    let from = c_text(&v[1]);
    if from.is_empty() {
        return Ok(Value::Text(s));
    }
    if matches!(v[2], Value::Null) {
        return Ok(Value::Null);
    }
    let to = c_text(&v[2]);
    Ok(Value::Text(s.replace(&from, &to)))
}

fn round(v: &[Value]) -> Result<Value> {
    if v.is_empty() || v.len() > 2 {
        return Err(wrong_arg_count("round"));
    }
    // A NULL value or NULL precision both yield NULL.
    if matches!(v[0], Value::Null) || matches!(v.get(1), Some(Value::Null)) {
        return Ok(Value::Null);
    }
    let x = eval::to_f64(&v[0]);
    let digits = if v.len() == 2 {
        eval::to_int_value(&v[1]).clamp(0, 30) as u32
    } else {
        0
    };
    let r = round_half_away(x, digits);
    // SQLite normalises a negative-zero result to positive zero
    // (`round(-0.4)` is `0.0`, not `-0.0`).
    Ok(Value::Real(if r == 0.0 { 0.0 } else { r }))
}

/// Round `x` to `n` decimal places, half away from zero, matching SQLite. Instead
/// of `round(x * 10^n) / 10^n` — which loses precision (e.g. `2.675 * 100` rounds
/// *up* to exactly `267.5` in f64, giving 2.68 where SQLite gives 2.67) — this
/// formats `x` to high fixed precision (exposing the true decimal digits) and
/// rounds the digit string, so it sees that `2.675` is really `2.67499…`.
pub(crate) fn round_half_away(x: f64, n: u32) -> f64 {
    if !x.is_finite() || x == 0.0 {
        return x;
    }
    // Values at or beyond 2^52 have no fractional part in f64; return unchanged
    // (this also bounds the formatted string length).
    if crate::util::float::abs(x) >= 4_503_599_627_370_496.0 {
        return x;
    }
    let neg = x < 0.0;
    let ax = crate::util::float::abs(x);
    let prec = n as usize + 25;
    let s = alloc::format!("{ax:.prec$}");
    let dot = s.find('.').unwrap_or(s.len());
    let frac = if dot < s.len() { &s[dot + 1..] } else { "" };
    // Round up when the first dropped digit (position `n`) is >= 5.
    let round_up = frac.as_bytes().get(n as usize).is_some_and(|&d| d >= b'5');
    // Kept digits: the integer part followed by the first `n` fractional digits.
    let mut digits: alloc::vec::Vec<u8> = alloc::vec::Vec::new();
    digits.extend_from_slice(&s.as_bytes()[..dot]);
    if n > 0 {
        let take = (n as usize).min(frac.len());
        digits.extend_from_slice(&frac.as_bytes()[..take]);
        // Pad with zeros if the formatting produced fewer than n fraction digits.
        digits.resize(dot + n as usize, b'0');
    }
    if round_up {
        let mut i = digits.len();
        loop {
            if i == 0 {
                digits.insert(0, b'1');
                break;
            }
            i -= 1;
            if digits[i] == b'9' {
                digits[i] = b'0';
            } else {
                digits[i] += 1;
                break;
            }
        }
    }
    // Reassemble with the decimal point `n` digits from the right and parse back.
    let nn = n as usize;
    let s2 = if nn == 0 {
        alloc::string::String::from_utf8(digits).unwrap_or_default()
    } else {
        let point = digits.len() - nn;
        let mut out = alloc::string::String::new();
        out.push_str(core::str::from_utf8(&digits[..point]).unwrap_or("0"));
        out.push('.');
        out.push_str(core::str::from_utf8(&digits[point..]).unwrap_or("0"));
        out
    };
    let mag: f64 = s2.parse().unwrap_or(ax);
    if neg {
        -mag
    } else {
        mag
    }
}

fn scalar_min_max(v: &[Value], want_min: bool) -> Result<Value> {
    // Scalar min()/max() take 2+ args (the 1-arg/`*` forms are aggregates,
    // routed elsewhere); 0 args is an error in SQLite.
    if v.is_empty() {
        let name = if want_min { "min" } else { "max" };
        return Err(Error::Error(alloc::format!(
            "wrong number of arguments to function {name}()"
        )));
    }
    // NULL if any arg is NULL.
    if v.iter().any(|x| matches!(x, Value::Null)) {
        return Ok(Value::Null);
    }
    // Mirror SQLite's `minmaxFunc`: scan left-to-right keeping the best so far.
    // For `min`, replace whenever `best >= candidate` (so on a tie the *later*
    // argument wins — `min(1.0,1)` is the integer `1`); for `max`, replace only
    // when `best < candidate` (so on a tie the *earlier* argument wins —
    // `max(1.0,1)` is the real `1.0`). This preserves the storage class of the
    // exact argument SQLite would return.
    let mut best = v[0].clone();
    for x in &v[1..] {
        let ord = eval::compare(&best, x);
        let take = if want_min {
            ord != core::cmp::Ordering::Less
        } else {
            ord == core::cmp::Ordering::Less
        };
        if take {
            best = x.clone();
        }
    }
    Ok(best)
}

fn hex_encode(v: &Value) -> String {
    let bytes = match v {
        Value::Blob(b) => b.clone(),
        other => eval::to_text(other).into_bytes(),
    };
    let mut s = String::with_capacity(bytes.len() * 2);
    for b in bytes {
        s.push(nibble(b >> 4));
        s.push(nibble(b & 0xf));
    }
    s
}

fn nibble(n: u8) -> char {
    match n {
        0..=9 => (b'0' + n) as char,
        _ => (b'A' + n - 10) as char,
    }
}

fn char_fn(v: &[Value]) -> Value {
    let mut s = String::new();
    for x in v {
        // SQLite's `charFunc` reads each argument as a code point and substitutes
        // U+FFFD for an out-of-range value (negative or > U+10FFFF) rather than
        // dropping the character. Surrogates (U+D800..=U+DFFF) cannot be held in
        // Rust's UTF-8 `String`, so they too fall back to U+FFFD (SQLite emits
        // their raw 3-byte encoding — a faithful match would need invalid UTF-8,
        // which this engine's TEXT representation forbids).
        let cp = eval::to_int_value(x);
        let c = u32::try_from(cp)
            .ok()
            .and_then(char::from_u32)
            .unwrap_or('\u{FFFD}');
        s.push(c);
    }
    Value::Text(s)
}