datumesh-store 0.5.2

Store for Datumesh on PostgreSQL or SQLite: descriptors, receipts, blobs, versions over transaction time, lineage, namespaces and names; a datumesh-core Resolver.
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
//! `SqliteStore`: the store in one SQLite file (since 0.4.0).

use std::borrow::Cow;
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use std::time::{Duration, Instant};

use rusqlite::types::Value as SqlValue;
use rusqlite::{Connection, OpenFlags, OptionalExtension};

use crate::catalogue::{
    aliases_json, args_json, as_i64, canonical_examples, check_catalog_entry, check_key_values, entry_fields,
    entry_from_columns, invalid, miss_text, parse_aliases, rank, Words, SUMMARY_VALUES,
};
use crate::error::{Db, Error, Result};
use crate::slices::{check_entry, cmp_keys, is_hash, is_instant, version_slice, Constraint, Kind, Pattern};
use crate::sqlite_sql::L;
use crate::{
    not_canonical_class, Binding, CatalogEntry, CatalogKind, ClassBinding, Dictionary, DictionaryValue, Embedding,
    FunctionTest, Hit, KeyValue, Namespace, PendingEmbedding, SliceMember, SliceValue, Store, Summary, SummaryEntry,
    TestSummary, Version, FIND_MISSES_CAP,
};
use datumesh_core::json::{self, Value};
use datumesh_core::lexical::{check_dns_name, check_function_name, check_hex, check_instant};
use datumesh_core::{
    keys_from_response, sha256_hex, verify, Arg, Args, Cell, ClassDescriptor, ErrorCode, FunctionDescriptor, Keys,
    Manifest, Receipt, Resolver, Scalar, Slice, Type,
};

/// How a [`SqliteStore`] opens and uses its connections.
///
/// Builder style: `SqliteOptions::new().busy_timeout(Duration::from_secs(5))`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SqliteOptions {
    max_size: usize,
    busy_timeout: Duration,
    durable: bool,
}

impl Default for SqliteOptions {
    fn default() -> SqliteOptions {
        SqliteOptions::new()
    }
}

impl SqliteOptions {
    /// At most 8 idle connections kept; a writer waits at most 30 seconds for the
    /// database's write lock (and a reader for a lock held in exclusive mode); every commit
    /// durable (`synchronous = FULL`).
    pub fn new() -> SqliteOptions {
        SqliteOptions { max_size: 8, busy_timeout: Duration::from_secs(30), durable: true }
    }

    /// The most idle connections kept open for reuse (at least 1). More may be open at
    /// once, one per concurrent call; SQLite connections are cheap, and readers do not
    /// wait for each other or for the writer (WAL).
    pub fn max_size(mut self, n: usize) -> SqliteOptions {
        self.max_size = n.max(1);
        self
    }

    /// How long a call waits for a lock another connection (of this process or another)
    /// holds before failing with [`Error::Database`] (`SQLITE_BUSY`; reads through the
    /// [`Resolver`]: `None`). Writers take the database's one write lock for the duration
    /// of a `put_*`, so this is the longest a writer waits behind the others.
    pub fn busy_timeout(mut self, d: Duration) -> SqliteOptions {
        self.busy_timeout = d;
        self
    }

    /// Whether each commit is flushed to disk before it returns (`synchronous = FULL`, the
    /// default), or only at checkpoints (`synchronous = NORMAL`: a power loss can lose the
    /// latest commits, never consistency; much faster for bulk loads, like PostgreSQL's
    /// `synchronous_commit = off`). Either way an application crash loses nothing
    /// committed.
    pub fn durable(mut self, yes: bool) -> SqliteOptions {
        self.durable = yes;
        self
    }
}

/// The store in one SQLite file (bundled SQLite, no server), with the same behaviour as
/// [`PgStore`](crate::PgStore): every method, error and rule of [`Store`] and
/// [`Resolver`]. `Send + Sync`: share one per process (behind an `Arc`); each call takes a
/// connection for its duration. Since 0.4.0.
///
/// The file is in WAL mode (readers never wait for the writer), with a busy timeout
/// ([`SqliteOptions::busy_timeout`]). Every `put_*` is one transaction begun with `BEGIN
/// IMMEDIATE`: it takes the database's write lock first, so its checks (a version later
/// than the latest, a key not yet taken) and its inserts are one atomic step against every
/// other writer, threads of this process or other processes on the same machine. The
/// append-only rules are also triggers in the file, so they hold for any connection. (A
/// SQLite file on a network file system is not supported: its locks are not reliable.)
///
/// Every `put_*` is one transaction. [`Store`] methods return errors: a malformed argument
/// is [`Error::Invalid`] (no query is made), a database failure [`Error::Database`]. The
/// [`Resolver`] methods answer both with `None`; a database failure is logged with
/// `tracing` (target `datumesh_store`, level `error`).
pub struct SqliteStore {
    path: PathBuf,
    options: SqliteOptions,
    idle: Mutex<Vec<Connection>>,
    /// The store's own writers queue here before taking the database's write lock: SQLite's
    /// busy handler polls with sleeps of up to 100 ms, so threads contending for the lock
    /// would mostly sleep. Other stores and processes still meet at the database's lock.
    writer: Mutex<()>,
    /// Opened with `open_existing`: never creates the file, never changes its journal mode.
    existing: bool,
}

impl std::fmt::Debug for SqliteStore {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("SqliteStore").field("path", &self.path).finish_non_exhaustive()
    }
}

/// A connection taken from the store, returned to it when dropped.
struct Pooled<'a> {
    store: &'a SqliteStore,
    conn: Option<Connection>,
}

impl std::ops::Deref for Pooled<'_> {
    type Target = Connection;
    fn deref(&self) -> &Connection {
        self.conn.as_ref().expect("a pooled connection")
    }
}

impl Drop for Pooled<'_> {
    fn drop(&mut self) {
        if let Some(c) = self.conn.take() {
            // A connection left inside a transaction (a failed rollback) is not reused.
            if c.is_autocommit() {
                if let Ok(mut idle) = self.store.idle.lock() {
                    if idle.len() < self.store.options.max_size {
                        idle.push(c);
                    }
                }
            }
        }
    }
}

impl SqliteStore {
    /// Opens the SQLite file at `path` with the default [`SqliteOptions`]; a missing file
    /// is created (empty: apply [`migrate::sqlite::apply`](crate::migrate::sqlite::apply)
    /// next), as a missing directory is not. [`open_existing`](Self::open_existing) creates
    /// nothing.
    pub fn open(path: impl AsRef<Path>) -> Result<SqliteStore> {
        SqliteStore::open_with(path, SqliteOptions::new())
    }

    /// Opens the SQLite file at `path`, creating it when it is missing (its directory must
    /// exist). One connection is opened at once (and
    /// the file put in WAL mode), so a path that cannot be opened fails here
    /// (`SQLITE_CANTOPEN`); the schema is not looked at, so a new or empty file is fine
    /// (create the schema with [`migrate::sqlite::apply`](crate::migrate::sqlite::apply)).
    pub fn open_with(path: impl AsRef<Path>, options: SqliteOptions) -> Result<SqliteStore> {
        let store = SqliteStore {
            path: path.as_ref().to_path_buf(),
            options,
            idle: Mutex::new(Vec::new()),
            writer: Mutex::new(()),
            existing: false,
        };
        let c = store.open_connection()?;
        if let Ok(mut idle) = store.idle.lock() {
            idle.push(c);
        }
        Ok(store)
    }

    /// Opens an existing SQLite file without changing anything: a path with no file is
    /// [`Error::Database`] (`no such database file: <path>`, code `SQLITE_CANTOPEN`) and
    /// nothing is created; the file's journal mode is left as it is. For checking a
    /// database ([`migrate::sqlite::check`](crate::migrate::sqlite::check), the command's
    /// `migrate --check`), which has no side effects. Writes through such a store work
    /// as through any other. Since 0.4.0.
    pub fn open_existing(path: impl AsRef<Path>) -> Result<SqliteStore> {
        let path = path.as_ref();
        if !path.is_file() {
            return Err(Error::Database(crate::error::DatabaseError::no_such_file(path)));
        }
        let store = SqliteStore {
            path: path.to_path_buf(),
            options: SqliteOptions::new(),
            idle: Mutex::new(Vec::new()),
            writer: Mutex::new(()),
            existing: true,
        };
        let c = store.open_connection()?;
        if let Ok(mut idle) = store.idle.lock() {
            idle.push(c);
        }
        Ok(store)
    }

    /// Opens a store named by a URL: `sqlite:<path>` or `sqlite://<path>` (so
    /// `sqlite:///var/lib/datumesh/store.db` is an absolute path), or a plain file path.
    /// Query parameters are not taken: the path is everything after the scheme.
    pub fn connect(url: &str) -> Result<SqliteStore> {
        SqliteStore::open(sqlite_path(url))
    }

    /// The database file's path.
    pub fn path(&self) -> &Path {
        &self.path
    }

    fn open_connection(&self) -> Result<Connection> {
        let mut flags = OpenFlags::SQLITE_OPEN_READ_WRITE | OpenFlags::SQLITE_OPEN_NO_MUTEX;
        if !self.existing {
            flags |= OpenFlags::SQLITE_OPEN_CREATE;
        }
        let c = Connection::open_with_flags(&self.path, flags).db()?;
        c.busy_timeout(self.options.busy_timeout).db()?;
        c.set_prepared_statement_cache_capacity(L::ALL.len() + 16);
        if self.existing {
            // Nothing about the file changes: no journal mode, no synchronous setting.
            c.execute_batch("PRAGMA foreign_keys = ON").db()?;
            return Ok(c);
        }
        // WAL: readers and the writer do not block each other, and a commit appends to the
        // log. Changing the mode needs a lock the busy handler does not always wait for (a
        // new file opened by several processes at once), so it is retried here.
        let start = Instant::now();
        loop {
            match c.query_row("PRAGMA journal_mode = WAL", [], |r| r.get::<_, String>(0)) {
                Ok(mode) if mode.eq_ignore_ascii_case("wal") => break,
                Ok(mode) => return Err(Error::Config(format!("SQLite: journal mode WAL refused (it is {mode})"))),
                Err(e) if is_busy(&e) && start.elapsed() < self.options.busy_timeout => {
                    std::thread::sleep(Duration::from_millis(5));
                }
                Err(e) => return Err(e).db(),
            }
        }
        let sync = if self.options.durable { "FULL" } else { "NORMAL" };
        c.execute_batch(&format!("PRAGMA foreign_keys = ON; PRAGMA synchronous = {sync};")).db()?;
        Ok(c)
    }

    /// A connection: an idle one, or a new one.
    fn conn(&self) -> Result<Pooled<'_>> {
        let idle = self.idle.lock().ok().and_then(|mut v| v.pop());
        let conn = match idle {
            Some(c) => c,
            None => self.open_connection()?,
        };
        Ok(Pooled { store: self, conn: Some(conn) })
    }

    /// Prepares every SQL statement the store uses against the live schema, on a new
    /// connection, and returns how many there are. Fails with the first statement the
    /// schema cannot serve.
    pub fn check_statements(&self) -> Result<usize> {
        let c = self.open_connection()?;
        for q in L::ALL {
            c.prepare(q.sql()).db()?;
        }
        Ok(L::ALL.len())
    }

    /// A connection held for a migration (one transaction on it), or a catalog read.
    pub(crate) fn raw(&self) -> Result<impl std::ops::Deref<Target = Connection> + '_> {
        self.conn()
    }

    /// A [`Resolver`] lookup: a failure (logged by `run`) becomes `None`.
    fn resolve<T>(&self, op: &'static str, f: impl FnOnce(&Connection) -> Result<Option<T>>) -> Option<T> {
        self.run(op, f).ok().flatten()
    }

    /// Runs `f` on a connection; a database failure is logged.
    fn run<T>(&self, op: &'static str, f: impl FnOnce(&Connection) -> Result<T>) -> Result<T> {
        let result = self.conn().and_then(|c| f(&c));
        if let Err(e @ Error::Database(_)) = &result {
            tracing::error!(target: "datumesh_store", op, error = %e, "database failure");
        }
        result
    }

    /// Runs `f` in a write transaction (`BEGIN IMMEDIATE`: the write lock first), committed
    /// when `f` succeeds and rolled back otherwise; a database failure is logged.
    fn write<T>(&self, op: &'static str, f: impl FnOnce(&Connection) -> Result<T>) -> Result<T> {
        self.run(op, |c| {
            let v = self.locked_write(c, f)?;
            self.bound_wal(c);
            Ok(v)
        })
    }

    /// `write`, after the store's other writers.
    fn locked_write<T>(&self, c: &Connection, f: impl FnOnce(&Connection) -> Result<T>) -> Result<T> {
        let _queue = self.writer.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
        write(c, f)
    }

    /// Keeps the write-ahead log bounded. SQLite's automatic checkpoints copy the log into
    /// the database but restart the log only when no reader is using it, which under a
    /// steady load of concurrent readers may be never: the log then grows with every
    /// commit. After a commit, when the log has outgrown `WAL_LIMIT`, this connection runs
    /// a TRUNCATE checkpoint, which waits (the busy timeout) for the readers to move to the
    /// latest snapshot, copies everything and empties the log. A failure (still busy) is
    /// left to the next commit.
    fn bound_wal(&self, c: &Connection) {
        let mut wal = self.path.clone().into_os_string();
        wal.push("-wal");
        if std::fs::metadata(&wal).is_ok_and(|m| m.len() > WAL_LIMIT) {
            if let Err(e) = c.query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |_| Ok(())) {
                tracing::debug!(target: "datumesh_store", error = %e, "checkpoint deferred");
            }
        }
    }

    /// A version from a query answering (tx, receipt_hash, asof) for (cell_id, asof).
    fn asof_version(&self, op: &'static str, q: L, cell_id: &str, asof: &str) -> Result<Option<Version>> {
        check_hex(cell_id, 64, "cell_id")?;
        check_instant(asof, "asof")?;
        self.run(op, |c| {
            c.prepare_cached(q.sql())
                .db()?
                .query_row(rusqlite::params![cell_id, asof], |r| version_row(r, cell_id))
                .optional()
                .db()
        })
    }

    /// A version and its receipt's bytes from a query answering (tx, receipt_hash, asof,
    /// bytes) for (cell_id, asof).
    fn asof_with_receipt(
        &self,
        op: &'static str,
        q: L,
        cell_id: &str,
        asof: &str,
    ) -> Result<Option<(Version, Vec<u8>)>> {
        check_hex(cell_id, 64, "cell_id")?;
        check_instant(asof, "asof")?;
        self.run(op, |c| {
            c.prepare_cached(q.sql())
                .db()?
                .query_row(rusqlite::params![cell_id, asof], |r| Ok((version_row(r, cell_id)?, r.get(3)?)))
                .optional()
                .db()
        })
    }
}

/// The size of the write-ahead log beyond which a commit checkpoints it and truncates it.
const WAL_LIMIT: u64 = 64 << 20;

/// Runs `f` in a `BEGIN IMMEDIATE` transaction on `c`.
pub(crate) fn write<T>(c: &Connection, f: impl FnOnce(&Connection) -> Result<T>) -> Result<T> {
    c.execute_batch("BEGIN IMMEDIATE").db()?;
    let result = f(c).and_then(|v| c.execute_batch("COMMIT").db().map(|()| v));
    if result.is_err() && !c.is_autocommit() {
        let _ = c.execute_batch("ROLLBACK");
    }
    result
}

fn is_busy(e: &rusqlite::Error) -> bool {
    matches!(e, rusqlite::Error::SqliteFailure(f, _) if f.code == rusqlite::ErrorCode::DatabaseBusy)
}

/// The path of a `sqlite:` URL (`sqlite:<path>`, `sqlite://<path>`), or `url` itself.
pub(crate) fn sqlite_path(url: &str) -> &str {
    match url.strip_prefix("sqlite:") {
        Some(rest) => rest.strip_prefix("//").unwrap_or(rest),
        None => url,
    }
}

/// The name of a SQLite (extended) result code.
pub(crate) fn result_code_name(code: std::os::raw::c_int) -> String {
    let name = match code {
        1 => "SQLITE_ERROR",
        2 => "SQLITE_INTERNAL",
        3 => "SQLITE_PERM",
        4 => "SQLITE_ABORT",
        5 => "SQLITE_BUSY",
        6 => "SQLITE_LOCKED",
        7 => "SQLITE_NOMEM",
        8 => "SQLITE_READONLY",
        9 => "SQLITE_INTERRUPT",
        10 => "SQLITE_IOERR",
        11 => "SQLITE_CORRUPT",
        12 => "SQLITE_NOTFOUND",
        13 => "SQLITE_FULL",
        14 => "SQLITE_CANTOPEN",
        15 => "SQLITE_PROTOCOL",
        16 => "SQLITE_EMPTY",
        17 => "SQLITE_SCHEMA",
        18 => "SQLITE_TOOBIG",
        19 => "SQLITE_CONSTRAINT",
        20 => "SQLITE_MISMATCH",
        21 => "SQLITE_MISUSE",
        22 => "SQLITE_NOLFS",
        23 => "SQLITE_AUTH",
        24 => "SQLITE_FORMAT",
        25 => "SQLITE_RANGE",
        26 => "SQLITE_NOTADB",
        261 => "SQLITE_BUSY_RECOVERY",
        517 => "SQLITE_BUSY_SNAPSHOT",
        773 => "SQLITE_BUSY_TIMEOUT",
        262 => "SQLITE_LOCKED_SHAREDCACHE",
        264 => "SQLITE_READONLY_RECOVERY",
        520 => "SQLITE_READONLY_CANTLOCK",
        270 => "SQLITE_CANTOPEN_NOTEMPDIR",
        526 => "SQLITE_CANTOPEN_ISDIR",
        782 => "SQLITE_CANTOPEN_FULLPATH",
        267 => "SQLITE_CORRUPT_VTAB",
        275 => "SQLITE_CONSTRAINT_CHECK",
        531 => "SQLITE_CONSTRAINT_COMMITHOOK",
        787 => "SQLITE_CONSTRAINT_FOREIGNKEY",
        1043 => "SQLITE_CONSTRAINT_FUNCTION",
        1299 => "SQLITE_CONSTRAINT_NOTNULL",
        1555 => "SQLITE_CONSTRAINT_PRIMARYKEY",
        1811 => "SQLITE_CONSTRAINT_TRIGGER",
        2067 => "SQLITE_CONSTRAINT_UNIQUE",
        2323 => "SQLITE_CONSTRAINT_VTAB",
        2579 => "SQLITE_CONSTRAINT_ROWID",
        3091 => "SQLITE_CONSTRAINT_DATATYPE",
        _ => {
            // Another extended code: its primary code's name and the number.
            let primary = code & 0xff;
            return if primary != code && primary != 0 {
                format!("{}({code})", result_code_name(primary))
            } else {
                format!("SQLITE({code})")
            };
        }
    };
    name.to_string()
}

fn version_row(r: &rusqlite::Row<'_>, cell_id: &str) -> rusqlite::Result<Version> {
    Ok(Version { cell_id: cell_id.to_string(), tx: r.get(0)?, receipt_hash: r.get(1)?, asof: r.get(2)? })
}

/// The host of a fully qualified function name (`host/name`): what precedes the last `/`.
fn name_host(fn_name: &str) -> &str {
    fn_name.rsplit_once('/').map_or("", |(h, _)| h)
}

fn read_namespace(c: &Connection, host: &str) -> Result<Option<Namespace>> {
    c.prepare_cached(L::NamespaceGet.sql())
        .db()?
        .query_row([host], |r| {
            Ok(Namespace {
                host: host.to_string(),
                keydoc: r.get(0)?,
                validated_at: r.get(1)?,
                suspended_at: r.get(2)?,
                consecutive_failures: r.get(3)?,
                last_checked_at: r.get(4)?,
            })
        })
        .optional()
        .db()
}

fn get_bytes(c: &Connection, q: L, key: &str) -> Result<Option<Vec<u8>>> {
    c.prepare_cached(q.sql()).db()?.query_row([key], |r| r.get(0)).optional().db()
}

fn get_strings(c: &Connection, q: L, key: &str) -> Result<Vec<String>> {
    let mut st = c.prepare_cached(q.sql()).db()?;
    let rows = st.query_map([key], |r| r.get(0)).db()?;
    rows.collect::<rusqlite::Result<Vec<String>>>().db()
}

fn exists(c: &Connection, q: L, key: &str) -> Result<bool> {
    c.prepare_cached(q.sql()).db()?.query_row([key], |r| r.get(0)).db()
}

fn exec(c: &Connection, q: L, params: impl rusqlite::Params) -> Result<usize> {
    c.prepare_cached(q.sql()).db()?.execute(params).db()
}

/// A stored value that does not parse back (a corrupt row).
fn bad(what: &str) -> Error {
    Error::Invalid(datumesh_core::Error::new(ErrorCode::CanonType, "$", format!("a stored {what}")))
}

/// A cell's arguments from the typed-argument index: a JSON array of `[name, type, value]`.
fn args_of(text: &str) -> Result<Args> {
    let Ok(Value::Array(list)) = json::parse(text.as_bytes()) else { return Err(bad("argument list")) };
    let mut args = Args::new();
    for a in &list {
        let item = |i: usize| match a {
            Value::Array(x) => x.get(i).and_then(Value::as_str).ok_or_else(|| bad("argument")),
            _ => Err(bad("argument")),
        };
        let ty = Type::from_name(item(1)?).ok_or_else(|| bad("type"))?;
        args.insert(item(0)?.to_string(), Arg::Value(Scalar::from_lexical(ty, item(2)?)?));
    }
    Ok(args)
}

/// The sort key of a typed value in the typed-argument index: for a number, a text that
/// sorts (as bytes) as the decimal does; for every other type, its lexical form, which
/// already sorts in the type's order.
pub(crate) fn sort_key(ty: &str, lexical: &str) -> String {
    if ty == "number" {
        decimal_key(lexical)
    } else {
        lexical.to_string()
    }
}

/// A decimal (SPEC 3.1 form: optional `-`, digits, optional `.` and digits) as a text that
/// sorts as the number does: `0` for a negative number, `1` for zero, `2` for a positive
/// one; then the decimal exponent `e` (the number is `0.d1d2... x 10^e`) plus 500, in three
/// digits; then the significant digits `d1d2...`. Longer digit strings after a shared
/// prefix are larger, as text and as numbers. For a negative number the exponent and the
/// digits are complemented (`999 - x`, `9 - d`) and `~` appended, which reverses the order,
/// prefixes included (`~` sorts after every digit). The specification's numbers have at
/// most 128 characters, so `e` lies in -127..=128.
pub(crate) fn decimal_key(lexical: &str) -> String {
    let (negative, magnitude) = match lexical.strip_prefix('-') {
        Some(m) => (true, m),
        None => (false, lexical),
    };
    let (int, frac) = magnitude.split_once('.').unwrap_or((magnitude, ""));
    let int = int.trim_start_matches('0');
    let frac = frac.trim_end_matches('0');
    let (exponent, digits): (i64, String) = if !int.is_empty() {
        (int.len() as i64, format!("{int}{frac}").trim_end_matches('0').to_string())
    } else {
        let zeros = frac.len() - frac.trim_start_matches('0').len();
        (-(zeros as i64), frac[zeros..].to_string())
    };
    if digits.is_empty() {
        return "1".to_string();
    }
    let e = (exponent + 500).clamp(0, 999);
    if negative {
        let complement: String = digits.bytes().map(|d| char::from(b'9' - (d - b'0'))).collect();
        format!("0{:03}{complement}~", 999 - e)
    } else {
        format!("2{e:03}{digits}")
    }
}

impl Resolver for SqliteStore {
    fn descriptor(&self, fn_hash: &str) -> Option<Cow<'_, [u8]>> {
        if !is_hash(fn_hash) {
            return None;
        }
        self.resolve("descriptor", |c| get_bytes(c, L::DescriptorGet, fn_hash)).map(Cow::Owned)
    }

    fn receipt(&self, hash: &str) -> Option<Cow<'_, [u8]>> {
        if !is_hash(hash) {
            return None;
        }
        self.resolve("receipt", |c| get_bytes(c, L::ReceiptGet, hash)).map(Cow::Owned)
    }

    /// The stored manifest of slice entry `entry` ([`Store::put_manifest`]), its canonical
    /// form; `None` when there is none, or `entry` is not an entry.
    fn manifest(&self, entry: &str) -> Option<Cow<'_, [u8]>> {
        if check_entry(entry, "$").is_err() {
            return None;
        }
        self.resolve("manifest", |c| get_bytes(c, L::ManifestGet, entry)).map(Cow::Owned)
    }

    /// `Some` only for a `stored` function, as [`PgStore`](crate::PgStore)'s: the value of
    /// the receipt of [`stored_asof`](Store::stored_asof)'s version.
    fn evaluate(&self, cell: &Cell, asof: &str) -> Option<Scalar> {
        if !is_instant(asof) {
            return None;
        }
        self.resolve("evaluate", |c| {
            let Some(desc) = get_bytes(c, L::DescriptorGet, &cell.fn_hash)? else { return Ok(None) };
            match FunctionDescriptor::from_json(&desc) {
                Ok(d) if d.lang == "stored" => {}
                Ok(_) => return Ok(None),
                Err(e) => {
                    tracing::error!(target: "datumesh_store", fn_hash = %cell.fn_hash, error = %e, "stored descriptor does not parse");
                    return Ok(None);
                }
            }
            let bytes: Option<Vec<u8>> = c
                .prepare_cached(L::ValueAsof.sql())
                .db()?
                .query_row(rusqlite::params![cell.id(), asof], |r| r.get(0))
                .optional()
                .db()?;
            let Some(bytes) = bytes else { return Ok(None) };
            match Receipt::from_json(&bytes) {
                Ok(r) => Ok(Some(r.value().clone())),
                Err(e) => {
                    tracing::error!(target: "datumesh_store", cell_id = %cell.id(), error = %e, "stored receipt does not parse");
                    Ok(None)
                }
            }
        })
    }
}

impl SqliteStore {
    /// A failed check (`threshold` is `Some`) or a successful one (`None`) at `checked_at`.
    fn record_check(
        &self,
        op: &'static str,
        host: &str,
        checked_at: &str,
        threshold: Option<u32>,
    ) -> Result<Option<Namespace>> {
        check_dns_name(host, "host")?;
        check_instant(checked_at, "checked_at")?;
        let out = self.write(op, |c| {
            let Some(mut ns) = read_namespace(c, host)? else { return Ok(None) };
            if let Some(at) = &ns.last_checked_at {
                if checked_at < at.as_str() {
                    return Err(Error::NotLater {
                        what: "namespace",
                        key: host.to_string(),
                        given: checked_at.to_string(),
                        latest: at.clone(),
                    });
                }
            }
            crate::apply_check(&mut ns, checked_at, threshold);
            exec(c, L::NamespaceCheck, rusqlite::params![host, ns.consecutive_failures, checked_at, ns.suspended_at])?;
            Ok(Some(ns))
        })?;
        tracing::debug!(target: "datumesh_store", host, checked_at, ok = threshold.is_none(), "namespace check");
        Ok(out)
    }
}

impl Store for SqliteStore {
    fn put_descriptor(&self, bytes: &[u8]) -> Result<String> {
        let d = FunctionDescriptor::from_json(bytes)?;
        let hash = d.hash();
        let canonical = d.canonical();
        // The descriptor (once) and its inputs' index (0.5.1), in one write transaction.
        self.run("put_descriptor", |c| {
            let fresh = !exists(c, L::DescriptorExists, &hash)?;
            if fresh || !d.inputs.is_empty() {
                self.locked_write(c, |c| {
                    exec(c, L::DescriptorPut, rusqlite::params![hash, canonical])?;
                    for input in &d.inputs {
                        exec(c, L::DescriptorInputPut, rusqlite::params![hash, input])?;
                    }
                    Ok(())
                })?;
                self.bound_wal(c);
            }
            Ok(())
        })?;
        tracing::debug!(target: "datumesh_store", fn_hash = %hash, "put_descriptor");
        Ok(hash)
    }

    fn put_receipt(&self, bytes: &[u8]) -> Result<String> {
        // Steps 1-4 first: a receipt that is not one is refused without a query.
        let r = Receipt::from_json(bytes)?;
        let canonical = json::parse(bytes)?.to_jcs();
        let hash = r.hash().to_string();
        let cell = r.cell();
        let cell_id = cell.id();
        let host = r.signer_host().to_string();
        let (mut entries, mut inputs): (Vec<String>, Vec<String>) =
            r.inputs().iter().cloned().partition(|e| e.starts_with("slice:"));
        entries.sort();
        entries.dedup();
        inputs.sort();
        inputs.dedup();
        let mut args = Vec::with_capacity(cell.args.len());
        for (name, a) in &cell.args {
            let Some(s) = a.scalar() else {
                return Err(Error::Invalid(datumesh_core::Error::new(
                    ErrorCode::Schema,
                    "$.cell.args",
                    "a receipt's cell has no open argument",
                )));
            };
            let ty = s.ty().as_str();
            args.push((name.clone(), ty, s.lexical().to_string(), sort_key(ty, s.lexical())));
        }
        self.run("put_receipt", |c| {
            // Idempotent: the very receipt already stored verified when it was stored.
            if let Some(stored) = get_bytes(c, L::ReceiptGet, &hash)? {
                if stored == canonical {
                    return Ok(());
                }
            }
            // Steps 5-6 against the stored key document of the signer host (outside the
            // write lock: verifying is the slow part).
            let mut keys = Keys::new();
            if let Some(ns) = read_namespace(c, &host)? {
                // No new writes under a suspended namespace.
                if let Some(since) = ns.suspended_at {
                    return Err(Error::NamespaceSuspended { host: host.clone(), suspended_at: since });
                }
                keys.insert_response(&host, 200, Some(&ns.keydoc));
            }
            let out = verify(bytes, &keys, None, None);
            if !out.ok {
                return Err(Error::Invalid(out.error().unwrap_or_else(|| {
                    datumesh_core::Error::new(ErrorCode::Signature, "$", "the receipt did not verify")
                })));
            }
            self.locked_write(c, |c| {
                // Under the write lock: another writer may have stored it meanwhile.
                if let Some(stored) = get_bytes(c, L::ReceiptGet, &hash)? {
                    return if stored == canonical { Ok(()) } else { Err(Error::Conflict { hash: hash.clone() }) };
                }
                let value = r.value();
                exec(
                    c,
                    L::ReceiptPut,
                    rusqlite::params![
                        hash,
                        canonical,
                        cell_id,
                        r.tx(),
                        cell.fn_hash,
                        r.publisher(),
                        r.asof(),
                        value.ty().as_str(),
                        value.lexical()
                    ],
                )?;
                for i in &inputs {
                    exec(c, L::EdgePut, rusqlite::params![hash, i])?;
                }
                for e in &entries {
                    exec(c, L::SliceEdgePut, rusqlite::params![hash, e])?;
                }
                if !exists(c, L::CellExists, &cell_id)? {
                    exec(
                        c,
                        L::CellPut,
                        rusqlite::params![cell_id, cell.fn_hash, cell.ns, cell.fn_name, args.len() as i64],
                    )?;
                    for (name, ty, value, key) in &args {
                        exec(c, L::CellArgPut, rusqlite::params![cell_id, name, ty, value, key, cell.fn_hash])?;
                    }
                }
                Ok(())
            })?;
            self.bound_wal(c);
            Ok(())
        })?;
        tracing::debug!(target: "datumesh_store", hash = %hash, cell_id = %cell_id, "put_receipt");
        Ok(hash)
    }

    fn put_blob(&self, bytes: &[u8]) -> Result<String> {
        let sha = sha256_hex(bytes);
        let length = i64::try_from(bytes.len()).unwrap_or(i64::MAX);
        self.run("put_blob", |c| {
            if exists(c, L::BlobExists, &sha)? {
                return Ok(());
            }
            self.locked_write(c, |c| exec(c, L::BlobPut, rusqlite::params![sha, bytes, length]).map(|_| ()))?;
            self.bound_wal(c);
            Ok(())
        })?;
        tracing::debug!(target: "datumesh_store", sha256 = %sha, length, "put_blob");
        Ok(sha)
    }

    fn blob(&self, sha256: &str) -> Result<Option<Cow<'_, [u8]>>> {
        check_hex(sha256, 64, "sha256")?;
        Ok(self.run("blob", |c| get_bytes(c, L::BlobGet, sha256))?.map(Cow::Owned))
    }

    fn put_version(&self, cell_id: &str, tx: &str, receipt_hash: &str) -> Result<()> {
        check_hex(cell_id, 64, "cell_id")?;
        check_instant(tx, "tx")?;
        check_hex(receipt_hash, 64, "receipt_hash")?;
        self.write("put_version", |c| {
            let meta: Option<(String, String)> = c
                .prepare_cached(L::ReceiptMeta.sql())
                .db()?
                .query_row([receipt_hash], |r| Ok((r.get(0)?, r.get(1)?)))
                .optional()
                .db()?;
            let Some((r_cell, r_tx)) = meta else {
                return Err(Error::NotFound { what: "receipt", key: receipt_hash.to_string() });
            };
            // No new versions of a receipt signed by a suspended namespace.
            let stored = get_bytes(c, L::ReceiptGet, receipt_hash)?
                .ok_or_else(|| Error::NotFound { what: "receipt", key: receipt_hash.to_string() })?;
            let signer = Receipt::from_json(&stored)?.signer_host().to_string();
            if let Some(since) = read_namespace(c, &signer)?.and_then(|n| n.suspended_at) {
                return Err(Error::NamespaceSuspended { host: signer, suspended_at: since });
            }
            if r_cell != cell_id {
                return Err(Error::Mismatch { what: "cell_id", expected: cell_id.to_string(), found: r_cell });
            }
            if r_tx != tx {
                return Err(Error::Mismatch { what: "tx", expected: tx.to_string(), found: r_tx });
            }
            if let Some(l) = get_strings(c, L::VersionLatestTx, cell_id)?.pop() {
                if tx <= l.as_str() {
                    return Err(Error::NotLater {
                        what: "version",
                        key: cell_id.to_string(),
                        given: tx.to_string(),
                        latest: l,
                    });
                }
            }
            exec(c, L::VersionPut, rusqlite::params![cell_id, tx, receipt_hash])?;
            Ok(())
        })?;
        tracing::debug!(target: "datumesh_store", cell_id, tx, receipt_hash, "put_version");
        Ok(())
    }

    fn version_asof(&self, cell_id: &str, asof: &str) -> Result<Option<Version>> {
        self.asof_version("version_asof", L::VersionAsof, cell_id, asof)
    }

    fn versions(&self, cell_id: &str, from: &str, to: &str) -> Result<Vec<Version>> {
        check_hex(cell_id, 64, "cell_id")?;
        check_instant(from, "from")?;
        check_instant(to, "to")?;
        self.run("versions", |c| {
            let mut st = c.prepare_cached(L::VersionRange.sql()).db()?;
            let rows = st.query_map(rusqlite::params![cell_id, from, to], |r| version_row(r, cell_id)).db()?;
            rows.collect::<rusqlite::Result<Vec<Version>>>().db()
        })
    }

    fn latest(&self, cell_id: &str) -> Result<Option<Version>> {
        check_hex(cell_id, 64, "cell_id")?;
        self.run("latest", |c| {
            c.prepare_cached(L::VersionLatest.sql())
                .db()?
                .query_row([cell_id], |r| version_row(r, cell_id))
                .optional()
                .db()
        })
    }

    fn dependents(&self, receipt_hash: &str) -> Result<Vec<String>> {
        check_hex(receipt_hash, 64, "receipt_hash")?;
        self.run("dependents", |c| get_strings(c, L::Dependents, receipt_hash))
    }

    fn inputs(&self, receipt_hash: &str) -> Result<Vec<String>> {
        check_hex(receipt_hash, 64, "receipt_hash")?;
        self.run("inputs", |c| get_strings(c, L::Inputs, receipt_hash))
    }

    fn put_namespace(&self, host: &str, keydoc_bytes: &[u8], validated_at: &str) -> Result<()> {
        keys_from_response(host, 200, Some(keydoc_bytes))?;
        check_instant(validated_at, "validated_at")?;
        let canonical = json::parse(keydoc_bytes)?.to_jcs();
        self.write("put_namespace", |c| {
            let at: Option<String> =
                c.prepare_cached(L::NamespaceGet.sql()).db()?.query_row([host], |r| r.get(1)).optional().db()?;
            if let Some(at) = at {
                if validated_at < at.as_str() {
                    return Err(Error::NotLater {
                        what: "namespace",
                        key: host.to_string(),
                        given: validated_at.to_string(),
                        latest: at,
                    });
                }
            }
            exec(c, L::NamespacePut, rusqlite::params![host, canonical, validated_at])?;
            Ok(())
        })?;
        tracing::debug!(target: "datumesh_store", host, validated_at, "put_namespace");
        Ok(())
    }

    fn namespace(&self, host: &str) -> Result<Option<Namespace>> {
        check_dns_name(host, "host")?;
        self.run("namespace", |c| read_namespace(c, host))
    }

    fn namespaces(&self) -> Result<Vec<Namespace>> {
        self.run("namespaces", |c| {
            let mut st = c.prepare_cached(L::NamespaceList.sql()).db()?;
            let rows = st
                .query_map([], |r| {
                    Ok(Namespace {
                        host: r.get(0)?,
                        keydoc: r.get(1)?,
                        validated_at: r.get(2)?,
                        suspended_at: r.get(3)?,
                        consecutive_failures: r.get(4)?,
                        last_checked_at: r.get(5)?,
                    })
                })
                .db()?;
            rows.collect::<rusqlite::Result<Vec<Namespace>>>().db()
        })
    }

    fn record_namespace_failure(&self, host: &str, checked_at: &str, threshold: u32) -> Result<Option<Namespace>> {
        self.record_check("record_namespace_failure", host, checked_at, Some(threshold))
    }

    fn record_namespace_success(&self, host: &str, checked_at: &str) -> Result<Option<Namespace>> {
        self.record_check("record_namespace_success", host, checked_at, None)
    }

    fn bind_name(&self, fn_name: &str, fn_hash: &str, tx: &str) -> Result<()> {
        check_function_name(fn_name, "fn_name")?;
        check_hex(fn_hash, 64, "fn_hash")?;
        check_instant(tx, "tx")?;
        self.write("bind_name", |c| {
            // No new bindings under a suspended namespace.
            let host = name_host(fn_name);
            if let Some(since) = read_namespace(c, host)?.and_then(|n| n.suspended_at) {
                return Err(Error::NamespaceSuspended { host: host.to_string(), suspended_at: since });
            }
            // One namespace of names: a class name is not a function name.
            if exists(c, L::ClassNameBound, fn_name)? {
                return Err(Error::NameTaken { name: fn_name.to_string(), bound_as: "class" });
            }
            if !exists(c, L::DescriptorExists, fn_hash)? {
                return Err(Error::NotFound { what: "descriptor", key: fn_hash.to_string() });
            }
            if let Some(l) = get_strings(c, L::NameLatest, fn_name)?.pop() {
                if tx <= l.as_str() {
                    return Err(Error::NotLater {
                        what: "name",
                        key: fn_name.to_string(),
                        given: tx.to_string(),
                        latest: l,
                    });
                }
            }
            exec(c, L::NamePut, rusqlite::params![fn_name, tx, fn_hash])?;
            Ok(())
        })?;
        tracing::debug!(target: "datumesh_store", fn_name, fn_hash, tx, "bind_name");
        Ok(())
    }

    fn resolve_name(&self, fn_name: &str, asof: &str) -> Result<Option<String>> {
        check_function_name(fn_name, "fn_name")?;
        check_instant(asof, "asof")?;
        self.run("resolve_name", |c| {
            c.prepare_cached(L::NameAsof.sql()).db()?.query_row([fn_name, asof], |r| r.get(0)).optional().db()
        })
    }

    fn put_class(&self, bytes: &[u8]) -> Result<String> {
        // The core checks the descriptor (strict JSON, then 16.1); the bytes must be its
        // canonical form, since the class hash is the hash of the bytes stored.
        let d = ClassDescriptor::from_json(bytes)?;
        let canonical = d.canonical();
        if canonical != bytes {
            return Err(not_canonical_class());
        }
        let hash = d.hash();
        let host = d.steward.namespace.clone();
        self.write("put_class", |c| {
            // No new writes under a suspended namespace: the steward's (16.2).
            if let Some(since) = read_namespace(c, &host)?.and_then(|n| n.suspended_at) {
                return Err(Error::NamespaceSuspended { host: host.clone(), suspended_at: since });
            }
            exec(c, L::ClassPut, rusqlite::params![hash, canonical])?;
            Ok(())
        })?;
        tracing::debug!(target: "datumesh_store", class_hash = %hash, "put_class");
        Ok(hash)
    }

    fn class(&self, class_hash: &str) -> Result<Option<Vec<u8>>> {
        check_hex(class_hash, 64, "class_hash")?;
        self.run("class", |c| get_bytes(c, L::ClassGet, class_hash))
    }

    fn bind_class(&self, class_name: &str, class_hash: &str, tx: &str) -> Result<()> {
        check_function_name(class_name, "class_name")?;
        check_hex(class_hash, 64, "class_hash")?;
        check_instant(tx, "tx")?;
        self.write("bind_class", |c| {
            // No new bindings under a suspended namespace: the host of the class name.
            let host = name_host(class_name);
            if let Some(since) = read_namespace(c, host)?.and_then(|n| n.suspended_at) {
                return Err(Error::NamespaceSuspended { host: host.to_string(), suspended_at: since });
            }
            let Some(bytes) = get_bytes(c, L::ClassGet, class_hash)? else {
                return Err(Error::NotFound { what: "class", key: class_hash.to_string() });
            };
            let flat = ClassDescriptor::from_json(&bytes)?;
            let methods: Vec<(String, String)> = flat.methods.into_iter().collect();
            let method_names: Vec<String> = methods.iter().map(|(m, _)| format!("{class_name}/{m}")).collect();
            // Every method's function descriptor is stored.
            for (_, h) in &methods {
                if !exists(c, L::DescriptorExists, h)? {
                    return Err(Error::NotFound { what: "descriptor", key: h.clone() });
                }
            }
            // One namespace of names: the class name is not a function name, and no method
            // name is a class name.
            if exists(c, L::NameBound, class_name)? {
                return Err(Error::NameTaken { name: class_name.to_string(), bound_as: "function" });
            }
            for name in &method_names {
                if exists(c, L::ClassNameBound, name)? {
                    return Err(Error::NameTaken { name: name.clone(), bound_as: "class" });
                }
            }
            // Later than the latest binding of the class name and of each method name.
            if let Some(l) = get_strings(c, L::ClassBindingLatest, class_name)?.pop() {
                if tx <= l.as_str() {
                    return Err(Error::NotLater {
                        what: "name",
                        key: class_name.to_string(),
                        given: tx.to_string(),
                        latest: l,
                    });
                }
            }
            for name in &method_names {
                if let Some(l) = get_strings(c, L::NameLatest, name)?.pop() {
                    if tx <= l.as_str() {
                        return Err(Error::NotLater {
                            what: "name",
                            key: name.clone(),
                            given: tx.to_string(),
                            latest: l,
                        });
                    }
                }
            }
            exec(c, L::ClassBindingPut, rusqlite::params![class_name, tx, class_hash])?;
            for ((_, h), name) in methods.iter().zip(&method_names) {
                exec(c, L::NamePut, rusqlite::params![name.as_str(), tx, h.as_str()])?;
            }
            Ok(())
        })?;
        tracing::debug!(target: "datumesh_store", class_name, class_hash, tx, "bind_class");
        Ok(())
    }

    fn resolve_class(&self, class_name: &str, asof: &str) -> Result<Option<String>> {
        Ok(self.resolve_class_binding(class_name, asof)?.map(|b| b.class_hash))
    }

    fn resolve_class_binding(&self, class_name: &str, asof: &str) -> Result<Option<ClassBinding>> {
        check_function_name(class_name, "class_name")?;
        check_instant(asof, "asof")?;
        self.run("resolve_class_binding", |c| {
            c.prepare_cached(L::ClassBindingAsof.sql())
                .db()?
                .query_row([class_name, asof], |r| Ok(ClassBinding { class_hash: r.get(0)?, tx: r.get(1)? }))
                .optional()
                .db()
        })
    }

    fn resolve_binding(&self, fn_name: &str, asof: &str) -> Result<Option<Binding>> {
        check_function_name(fn_name, "fn_name")?;
        check_instant(asof, "asof")?;
        self.run("resolve_binding", |c| {
            c.prepare_cached(L::BindingAsof.sql())
                .db()?
                .query_row([fn_name, asof], |r| Ok(Binding { fn_hash: r.get(0)?, tx: r.get(1)? }))
                .optional()
                .db()
        })
    }

    fn put_computed(&self, cell_id: &str, tx: &str, receipt_hash: &str) -> Result<()> {
        check_hex(cell_id, 64, "cell_id")?;
        check_instant(tx, "tx")?;
        check_hex(receipt_hash, 64, "receipt_hash")?;
        let asof = self.write("put_computed", |c| {
            let meta: Option<(String, String, String)> = c
                .prepare_cached(L::ReceiptMeta.sql())
                .db()?
                .query_row([receipt_hash], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)))
                .optional()
                .db()?;
            let Some((r_cell, r_tx, asof)) = meta else {
                return Err(Error::NotFound { what: "receipt", key: receipt_hash.to_string() });
            };
            if r_cell != cell_id {
                return Err(Error::Mismatch { what: "cell_id", expected: cell_id.to_string(), found: r_cell });
            }
            if r_tx != tx {
                return Err(Error::Mismatch { what: "tx", expected: tx.to_string(), found: r_tx });
            }
            let stored: Option<String> = c
                .prepare_cached(L::ComputedGet.sql())
                .db()?
                .query_row([cell_id, tx, asof.as_str()], |r| r.get(0))
                .optional()
                .db()?;
            match stored {
                Some(h) if h == receipt_hash => {}
                Some(_) => return Err(Error::Conflict { hash: receipt_hash.to_string() }),
                None => {
                    exec(c, L::ComputedPut, rusqlite::params![cell_id, tx, asof, receipt_hash])?;
                }
            }
            Ok(asof)
        })?;
        tracing::debug!(target: "datumesh_store", cell_id, tx, asof, receipt_hash, "put_computed");
        Ok(())
    }

    fn computed_asof(&self, cell_id: &str, asof: &str) -> Result<Option<Version>> {
        self.asof_version("computed_asof", L::ComputedAsof, cell_id, asof)
    }

    fn stored_asof(&self, cell_id: &str, asof: &str) -> Result<Option<Version>> {
        self.asof_version("stored_asof", L::StoredAsof, cell_id, asof)
    }

    fn cell_dependents(&self, cell_id: &str) -> Result<Vec<String>> {
        check_hex(cell_id, 64, "cell_id")?;
        self.run("cell_dependents", |c| get_strings(c, L::CellDependents, cell_id))
    }

    /// One query: the version and its receipt's bytes.
    fn computed_asof_with_receipt(&self, cell_id: &str, asof: &str) -> Result<Option<(Version, Cow<'_, [u8]>)>> {
        Ok(self
            .asof_with_receipt("computed_asof_with_receipt", L::ComputedAsofReceipt, cell_id, asof)?
            .map(|(v, b)| (v, Cow::Owned(b))))
    }

    /// One query: the version and its receipt's bytes.
    fn stored_asof_with_receipt(&self, cell_id: &str, asof: &str) -> Result<Option<(Version, Cow<'_, [u8]>)>> {
        Ok(self
            .asof_with_receipt("stored_asof_with_receipt", L::StoredAsofReceipt, cell_id, asof)?
            .map(|(v, b)| (v, Cow::Owned(b))))
    }

    fn put_manifest(&self, bytes: &[u8]) -> Result<String> {
        let m = Manifest::from_json(bytes)?;
        let entry = m.entry();
        let canonical = m.canonical();
        let members = m.members();
        let n = i64::try_from(members.len()).unwrap_or(i64::MAX);
        self.run("put_manifest", |c| {
            // The entry hashes the content: a stored entry has these very bytes.
            if exists(c, L::ManifestExists, &entry)? {
                return Ok(());
            }
            self.locked_write(c, |c| {
                if exists(c, L::ManifestExists, &entry)? {
                    return Ok(());
                }
                exec(
                    c,
                    L::ManifestPut,
                    rusqlite::params![entry, m.slice().id(), m.members_hash(), m.slice().fn_hash(), n, canonical],
                )?;
                let mut st = c.prepare_cached(L::ManifestMemberPut.sql()).db()?;
                for h in members {
                    st.execute([entry.as_str(), h.as_str()]).db()?;
                }
                Ok(())
            })?;
            self.bound_wal(c);
            Ok(())
        })?;
        tracing::debug!(target: "datumesh_store", entry = %entry, members = n, "put_manifest");
        Ok(entry)
    }

    fn member_manifests(&self, receipt_hash: &str) -> Result<Vec<String>> {
        check_hex(receipt_hash, 64, "receipt_hash")?;
        self.run("member_manifests", |c| get_strings(c, L::MemberManifests, receipt_hash))
    }

    fn slice_entries(&self, receipt_hash: &str) -> Result<Vec<String>> {
        check_hex(receipt_hash, 64, "receipt_hash")?;
        self.run("slice_entries", |c| get_strings(c, L::SliceEntries, receipt_hash))
    }

    fn slice_dependents(&self, entry: &str) -> Result<Vec<String>> {
        check_entry(entry, "entry")?;
        self.run("slice_dependents", |c| get_strings(c, L::SliceDependents, entry))
    }

    fn slice_members(&self, slice: &Slice, asof: &str) -> Result<Vec<SliceMember>> {
        check_instant(asof, "asof")?;
        let v = slice.to_value();
        if let Some((cell_id, from, to)) = version_slice(slice, &v)? {
            return self.versions_between(&cell_id, &from, &to, asof);
        }
        let p = Pattern::of(&v)?;
        self.run("slice_members", |c| {
            let rows = rows(&p, c, asof, [L::SliceMembersAll, L::SliceMembersDrive], |r| {
                let cell_id: String = r.get(4)?;
                Ok((
                    SliceMember {
                        version: Version { cell_id, tx: r.get(0)?, receipt_hash: r.get(1)?, asof: r.get(2)? },
                        receipt: r.get(3)?,
                    },
                    r.get::<_, String>(5)?,
                ))
            })?;
            in_key_order(&p, rows, |m| &m.version.cell_id)
        })
    }

    fn versions_between(&self, cell_id: &str, from: &str, to: &str, asof: &str) -> Result<Vec<SliceMember>> {
        check_hex(cell_id, 64, "cell_id")?;
        check_instant(from, "from")?;
        check_instant(to, "to")?;
        check_instant(asof, "asof")?;
        self.run("versions_between", |c| {
            let mut st = c.prepare_cached(L::VersionsBetween.sql()).db()?;
            let rows = st
                .query_map(rusqlite::params![cell_id, from, to, asof], |r| {
                    Ok(SliceMember { version: version_row(r, cell_id)?, receipt: r.get(3)? })
                })
                .db()?;
            rows.collect::<rusqlite::Result<Vec<SliceMember>>>().db()
        })
    }

    fn slice_values(&self, slice: &Slice, asof: &str) -> Result<Vec<SliceValue>> {
        check_instant(asof, "asof")?;
        let v = slice.to_value();
        if let Some((cell_id, from, to)) = version_slice(slice, &v)? {
            return self.run("slice_values", |c| {
                let mut st = c.prepare_cached(L::VersionsBetweenValues.sql()).db()?;
                let rows = st.query_map(rusqlite::params![cell_id, from, to, asof], value_columns).db()?;
                let mut out = Vec::new();
                for r in rows {
                    out.push(value_of(r.db()?)?.0);
                }
                Ok(out)
            });
        }
        let p = Pattern::of(&v)?;
        self.run("slice_values", |c| {
            let rows = rows(&p, c, asof, [L::SliceValuesAll, L::SliceValuesDrive], value_columns)?;
            let mut values = Vec::with_capacity(rows.len());
            for row in rows {
                values.push(value_of(row)?);
            }
            in_key_order_parsed(&p, values, |m| &m.version.cell_id)
        })
    }

    fn slice_changed_after(&self, slice: &Slice, asof: &str) -> Result<bool> {
        check_instant(asof, "asof")?;
        let v = slice.to_value();
        if let Some((cell_id, from, to)) = version_slice(slice, &v)? {
            return self.run("slice_changed_after", |c| {
                c.prepare_cached(L::VersionsChangedAfter.sql())
                    .db()?
                    .query_row(rusqlite::params![cell_id, from, to, asof], |r| r.get(0))
                    .db()
            });
        }
        let p = Pattern::of(&v)?;
        self.run("slice_changed_after", |c| changed_after(&p, c, asof))
    }

    fn computed_cells(&self, slice: &Slice, asof: &str, limit: usize) -> Result<Vec<Cell>> {
        check_instant(asof, "asof")?;
        let p = Pattern::of(&slice.to_value())?;
        let limit = i64::try_from(limit).unwrap_or(i64::MAX);
        self.run("computed_cells", |c| {
            let (d, _) = drive(&p, c, false)?;
            let q = if d.is_some() { L::ComputedCellsDrive } else { L::ComputedCellsAll };
            let mut binds = params(&p, asof, d);
            binds.push((":limit", SqlValue::Integer(limit)));
            let mut st = c.prepare_cached(q.sql()).db()?;
            bind(&mut st, &binds)?;
            let mut rows = st.raw_query();
            let mut out = Vec::new();
            while let Some(r) = rows.next().db()? {
                let args = args_of(&r.get::<_, String>(3).db()?)?;
                out.push(Cell {
                    args,
                    fn_hash: r.get::<_, String>(2).db()?,
                    fn_name: r.get::<_, String>(1).db()?,
                    ns: r.get::<_, String>(0).db()?,
                });
            }
            Ok(out)
        })
    }

    fn has_bindings_under(&self, namespace: &str) -> Result<bool> {
        let prefix = format!("{namespace}/");
        self.run("has_bindings_under", |c| {
            c.prepare_cached(L::HasBindingsUnder.sql()).db()?.query_row([&prefix], |r| r.get(0)).db()
        })
    }

    fn upsert_catalog(&self, entries: &[CatalogEntry]) -> Result<Vec<i64>> {
        for e in entries {
            check_catalog_entry(e)?;
        }
        if entries.is_empty() {
            return Ok(Vec::new());
        }
        self.write("upsert_catalog", |c| {
            let mut ids = Vec::with_capacity(entries.len());
            for e in entries {
                let args = args_json(&e.args);
                let examples = canonical_examples(&e.examples)?;
                let updated: Option<i64> = c
                    .prepare_cached(
                        "INSERT INTO catalog_entries (kind, name, hash, label, description, args, examples, source, signed_by, updated_at)
                         VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))
                         ON CONFLICT (kind, name) DO UPDATE SET hash = excluded.hash, label = excluded.label,
                             description = excluded.description, args = excluded.args, examples = excluded.examples,
                             source = excluded.source, signed_by = excluded.signed_by, updated_at = excluded.updated_at
                         WHERE catalog_entries.source = 'operator' OR excluded.source = 'publisher'
                         RETURNING id",
                    )
                    .db()?
                    .query_row(
                        rusqlite::params![e.kind.as_str(), e.name, e.hash, e.label, e.description, args, examples, e.source.as_str(), e.signed_by],
                        |r| r.get(0),
                    )
                    .optional()
                    .db()?;
                let id = match updated {
                    Some(id) => id,
                    // An operator's entry over a publisher's: kept as it is.
                    None => c
                        .prepare_cached("SELECT id FROM catalog_entries WHERE kind = ?1 AND name = ?2")
                        .db()?
                        .query_row([e.kind.as_str(), e.name.as_str()], |r| r.get(0))
                        .db()?,
                };
                ids.push(id);
            }
            Ok(ids)
        })
    }

    fn upsert_key_values(&self, owner: &str, key: &str, values: &[KeyValue]) -> Result<Vec<i64>> {
        check_key_values(owner, key, values)?;
        if values.is_empty() {
            return Ok(Vec::new());
        }
        self.write("upsert_key_values", |c| {
            let mut ids = Vec::with_capacity(values.len());
            for v in values {
                let aliases = aliases_json(&v.aliases);
                let id: i64 = c
                    .prepare_cached(
                        "INSERT INTO key_values (owner, key, value, label, aliases) VALUES (?1, ?2, ?3, ?4, ?5)
                         ON CONFLICT (owner, key, value) DO UPDATE SET label = excluded.label, aliases = excluded.aliases
                         RETURNING id",
                    )
                    .db()?
                    .query_row(rusqlite::params![owner, key, v.value, v.label, aliases], |r| r.get(0))
                    .db()?;
                ids.push(id);
            }
            Ok(ids)
        })
    }

    fn refresh_value_counts(&self) -> Result<u64> {
        self.write("refresh_value_counts", |c| {
            let n = c
                .prepare_cached(
                    "UPDATE key_values SET n_cells = COALESCE((
                         SELECT count(*) FROM catalog_entries e JOIN cell_args a
                           ON a.fn_hash = e.hash AND a.name = key_values.key AND a.value = key_values.value
                          WHERE e.kind = 'function' AND e.name = key_values.owner), 0)",
                )
                .db()?
                .execute([])
                .db()?;
            Ok(n as u64)
        })
    }

    fn text_find(&self, query: &str, limit: usize) -> Result<Vec<Hit>> {
        let Some(words) = Words::new(query) else { return Ok(Vec::new()) };
        if limit == 0 {
            return Ok(Vec::new());
        }
        let entry_where = like_where_sqlite(&words, &["name", "label", "description", "args"]);
        let value_where = like_where_sqlite(&words, &["value", "label", "aliases"]);
        self.run("text_find", |c| {
            let mut hits = Vec::new();
            let sql = format!(
                "SELECT id, kind, name, hash, label, description, args, examples, source, signed_by FROM catalog_entries WHERE 1 = 1{}",
                entry_where.0
            );
            let rows: Vec<EntryRow> = {
                let mut st = c.prepare(&sql).db()?;
                let mapped = st.query_map(rusqlite::params_from_iter(entry_where.1.iter()), entry_columns).db()?;
                mapped.collect::<rusqlite::Result<Vec<_>>>().db()?
            };
            for (id, kind, name, hash, label, description, args, examples, source, signed_by) in rows {
                let entry = entry_from_columns(&kind, name, hash, label, description, &args, &examples, &source, signed_by)?;
                let score = words.score(&entry_fields(&entry));
                if let Some(score) = score {
                    hits.push(Hit::Entry { id, entry, score });
                }
            }
            let sql = format!("SELECT id, owner, key, value, label, aliases FROM key_values WHERE 1 = 1{}", value_where.0);
            let rows: Vec<ValueRow> = {
                let mut st = c.prepare(&sql).db()?;
                let mapped = st.query_map(rusqlite::params_from_iter(value_where.1.iter()), value_columns_of).db()?;
                mapped.collect::<rusqlite::Result<Vec<_>>>().db()?
            };
            for (id, owner, key, value, label, aliases_text) in rows {
                let aliases = parse_aliases(&aliases_text)?;
                let score = {
                    let mut fields: Vec<&str> = vec![&value, &label];
                    fields.extend(aliases.iter().map(String::as_str));
                    words.score(&fields)
                };
                if let Some(score) = score {
                    hits.push(Hit::Value { id, owner, key, value, label, aliases, score });
                }
            }
            Ok(rank(hits, limit))
        })
    }

    fn vector_find(&self, _model: &str, _vec: &[f32], _limit: usize) -> Result<Vec<Hit>> {
        Err(unsupported_vectors())
    }

    fn put_embeddings(&self, _model: &str, _items: &[Embedding]) -> Result<()> {
        Err(unsupported_vectors())
    }

    fn pending_embeddings(&self, _model: &str, _limit: usize) -> Result<Vec<PendingEmbedding>> {
        Ok(Vec::new())
    }

    fn vector_available(&self) -> bool {
        false
    }

    fn log_miss(&self, query: &str) -> Result<()> {
        let Some(q) = miss_text(query) else { return Ok(()) };
        self.write("log_miss", |c| {
            c.prepare_cached("INSERT INTO find_misses (query) VALUES (?1)").db()?.execute([q]).db()?;
            // Keep the newest FIND_MISSES_CAP rows: prune the oldest beyond that.
            c.prepare_cached(
                "DELETE FROM find_misses WHERE rowid IN (SELECT rowid FROM find_misses ORDER BY at
                     LIMIT max((SELECT count(*) FROM find_misses) - ?1, 0))",
            )
            .db()?
            .execute([as_i64(FIND_MISSES_CAP)])
            .db()?;
            Ok(())
        })
    }

    fn put_function_test(&self, test: &FunctionTest) -> Result<bool> {
        let (total, covered) = crate::functions::check_test(test)?;
        self.write("put_function_test", |c| {
            let n = exec(
                c,
                L::FunctionTestPut,
                rusqlite::params![
                    &test.fn_hash,
                    &test.case,
                    &test.test_json,
                    &test.signed_by,
                    &test.last_run_at,
                    &test.last_result,
                    &test.last_detail,
                    total,
                    covered
                ],
            )?;
            Ok(n == 1)
        })
    }

    fn function_tests(&self, fn_hash: &str) -> Result<Vec<FunctionTest>> {
        check_hex(fn_hash, 64, "fn_hash")?;
        self.run("function_tests", |c| {
            let mut st = c.prepare_cached(L::FunctionTestsOf.sql()).db()?;
            let rows = st.query_map([fn_hash], function_test_row).db()?;
            rows.collect::<rusqlite::Result<Vec<FunctionTest>>>().db()
        })
    }

    fn record_function_test(
        &self,
        fn_hash: &str,
        case: &str,
        run_at: &str,
        result: &str,
        detail: &str,
    ) -> Result<bool> {
        check_hex(fn_hash, 64, "fn_hash")?;
        crate::functions::check_case(case)?;
        check_instant(run_at, "run_at")?;
        crate::functions::check_result(result)?;
        self.write("record_function_test", |c| {
            let n = exec(c, L::FunctionTestRecord, rusqlite::params![run_at, result, detail, fn_hash, case])?;
            Ok(n == 1)
        })
    }

    fn set_function_branches(&self, fn_hash: &str, total: u32, covered: u32) -> Result<()> {
        check_hex(fn_hash, 64, "fn_hash")?;
        let (total, covered) = crate::functions::branch_counts(total, covered)?;
        self.write("set_function_branches", |c| {
            exec(c, L::FunctionBranches, rusqlite::params![fn_hash, total, covered]).map(|_| ())
        })
    }

    fn function_readers(&self, name: &str) -> Result<Vec<String>> {
        check_function_name(name, "name")?;
        self.run("function_readers", |c| get_strings(c, L::FunctionReaders, name))
    }

    fn bound_names(&self, fn_hash: &str) -> Result<Vec<String>> {
        check_hex(fn_hash, 64, "fn_hash")?;
        self.run("bound_names", |c| get_strings(c, L::BoundNames, fn_hash))
    }

    fn name_function_tests(&self, fn_hash: &str, names: &[(String, String)]) -> Result<u64> {
        check_hex(fn_hash, 64, "fn_hash")?;
        for (case, name) in names {
            crate::functions::check_case(case)?;
            check_function_name(name, "name")?;
        }
        if names.is_empty() {
            return Ok(0);
        }
        self.write("name_function_tests", |c| {
            let mut st = c.prepare_cached(L::FunctionTestName.sql()).db()?;
            let mut named = 0u64;
            for (case, name) in names {
                named += st.execute(rusqlite::params![fn_hash, case, name]).db()? as u64;
            }
            Ok(named)
        })
    }

    fn unnamed_function_tests(&self, limit: usize) -> Result<Vec<FunctionTest>> {
        let limit = i64::try_from(limit).unwrap_or(i64::MAX);
        self.run("unnamed_function_tests", |c| {
            let mut st = c.prepare_cached(L::FunctionTestsUnnamed.sql()).db()?;
            let rows = st.query_map([limit], function_test_row).db()?;
            rows.collect::<rusqlite::Result<Vec<FunctionTest>>>().db()
        })
    }

    fn function_test_summary(&self, fn_hash: &str, fn_name: Option<&str>) -> Result<TestSummary> {
        check_hex(fn_hash, 64, "fn_hash")?;
        self.run("function_test_summary", |c| {
            let mut st = c.prepare_cached(L::FunctionTestSummary.sql()).db()?;
            let (count, pass, fail, error, not_run, last_run_at, total, covered) = st
                .query_row(rusqlite::params![fn_hash, fn_name], |r| {
                    Ok((
                        r.get::<_, i64>(0)?,
                        r.get::<_, i64>(1)?,
                        r.get::<_, i64>(2)?,
                        r.get::<_, i64>(3)?,
                        r.get::<_, i64>(4)?,
                        r.get::<_, Option<String>>(5)?,
                        r.get::<_, i64>(6)?,
                        r.get::<_, i64>(7)?,
                    ))
                })
                .db()?;
            // The branch counts are integer with a check of at least zero: an `as` is exact.
            Ok(TestSummary {
                count: count as u64,
                pass: pass as u64,
                fail: fail as u64,
                error: error as u64,
                not_run: not_run as u64,
                last_run_at,
                branches_total: total as u32,
                branches_covered: covered as u32,
            })
        })
    }

    fn function_tests_page(
        &self,
        fn_hash: &str,
        fn_name: Option<&str>,
        after_case: Option<&str>,
        limit: usize,
    ) -> Result<Vec<FunctionTest>> {
        check_hex(fn_hash, 64, "fn_hash")?;
        let limit = i64::try_from(limit).unwrap_or(i64::MAX);
        self.run("function_tests_page", |c| {
            let rows: Vec<FunctionTest> = match fn_name {
                None => {
                    let mut st = c.prepare_cached(L::FunctionTestsPage.sql()).db()?;
                    let mapped = st.query_map(rusqlite::params![fn_hash, after_case, limit], function_test_row).db()?;
                    mapped.collect::<rusqlite::Result<Vec<_>>>().db()?
                }
                Some(name) => {
                    let mut st = c.prepare_cached(L::FunctionTestsPageNamed.sql()).db()?;
                    let mapped =
                        st.query_map(rusqlite::params![fn_hash, name, after_case, limit], function_test_row).db()?;
                    mapped.collect::<rusqlite::Result<Vec<_>>>().db()?
                }
            };
            Ok(rows)
        })
    }

    fn stored_receipts_of(&self, ns: &str, fn_name: &str, fn_hash: &str, limit: usize) -> Result<Vec<Vec<u8>>> {
        check_hex(fn_hash, 64, "fn_hash")?;
        let limit = i64::try_from(limit).unwrap_or(i64::MAX);
        self.run("stored_receipts_of", |c| {
            let mut st = c.prepare_cached(L::StoredReceiptsOf.sql()).db()?;
            let rows = st.query_map(rusqlite::params![fn_hash, ns, fn_name, limit], |r| r.get::<_, Vec<u8>>(0)).db()?;
            rows.collect::<rusqlite::Result<Vec<Vec<u8>>>>().db()
        })
    }

    fn slice_values_limit(&self, slice: &Slice, asof: &str, limit: usize) -> Result<Vec<SliceValue>> {
        check_instant(asof, "asof")?;
        let limit = i64::try_from(limit).unwrap_or(i64::MAX);
        let v = slice.to_value();
        if let Some((cell_id, from, to)) = version_slice(slice, &v)? {
            return self.run("slice_values_limit", |c| {
                // The statement of slice_values, with its LIMIT: the same order (tx).
                let sql = format!("{} LIMIT ?5", L::VersionsBetweenValues.sql());
                let mut st = c.prepare(&sql).db()?;
                let mut rows = st.query(rusqlite::params![cell_id, from, to, asof, limit]).db()?;
                let mut out = Vec::new();
                while let Some(r) = rows.next().db()? {
                    out.push(value_of(value_columns(r).db()?)?.0);
                }
                Ok(out)
            });
        }
        let p = Pattern::of(&v)?;
        self.run("slice_values_limit", |c| values_limited(&p, c, asof, limit))
    }

    fn versions_limit(&self, cell_id: &str, from: &str, to: &str, limit: usize) -> Result<Vec<Version>> {
        check_hex(cell_id, 64, "cell_id")?;
        check_instant(from, "from")?;
        check_instant(to, "to")?;
        let limit = i64::try_from(limit).unwrap_or(i64::MAX);
        self.run("versions_limit", |c| {
            let mut st = c.prepare_cached(L::VersionRangeLimit.sql()).db()?;
            let rows = st.query_map(rusqlite::params![cell_id, from, to, limit], |r| version_row(r, cell_id)).db()?;
            rows.collect::<rusqlite::Result<Vec<Version>>>().db()
        })
    }

    fn stored_cell_count(&self, ns: &str, fn_name: &str, fn_hash: &str) -> Result<u64> {
        check_hex(fn_hash, 64, "fn_hash")?;
        self.run("stored_cell_count", |c| {
            let n: i64 = c
                .prepare_cached(L::StoredCellCount.sql())
                .db()?
                .query_row(rusqlite::params![fn_hash, ns, fn_name], |r| r.get(0))
                .db()?;
            Ok(n as u64)
        })
    }

    fn has_key_value(&self, owner: &str, key: &str, value: &str) -> Result<bool> {
        self.run("has_key_value", |c| {
            c.prepare_cached(L::DictionaryHas.sql())
                .db()?
                .query_row(rusqlite::params![owner, key, value], |r| r.get(0))
                .db()
        })
    }

    fn key_value_count(&self, owner: &str, key: &str) -> Result<u64> {
        self.run("key_value_count", |c| {
            let n: i64 = c
                .prepare_cached(L::DictionaryCount.sql())
                .db()?
                .query_row(rusqlite::params![owner, key], |r| r.get(0))
                .db()?;
            Ok(n as u64)
        })
    }

    fn mark_key_open(&self, owner: &str, key: &str) -> Result<()> {
        if owner.is_empty() || owner.len() > 512 || key.is_empty() || key.len() > 128 {
            return Err(invalid("key", "an owner of 1 to 512 bytes and a key of 1 to 128 bytes"));
        }
        self.write("mark_key_open", |c| exec(c, L::KeyOpenPut, rusqlite::params![owner, key]).map(|_| ()))
    }

    fn open_key_count(&self) -> Result<u64> {
        self.run("open_key_count", |c| {
            let n: i64 = c.prepare_cached(L::OpenKeyCount.sql()).db()?.query_row([], |r| r.get(0)).db()?;
            Ok(n as u64)
        })
    }

    fn key_is_open(&self, owner: &str, key: &str) -> Result<bool> {
        self.run("key_is_open", |c| {
            c.prepare_cached(L::KeyIsOpen.sql()).db()?.query_row(rusqlite::params![owner, key], |r| r.get(0)).db()
        })
    }

    fn catalog_entry(&self, name: &str) -> Result<Option<CatalogEntry>> {
        self.run("catalog_entry", |c| {
            let mut st = c.prepare_cached(L::CatalogEntryNamed.sql()).db()?;
            let row = st
                .query_row([name], |r| {
                    Ok((
                        r.get::<_, String>(0)?,
                        r.get::<_, String>(1)?,
                        r.get::<_, Option<String>>(2)?,
                        r.get::<_, String>(3)?,
                        r.get::<_, String>(4)?,
                        r.get::<_, String>(5)?,
                        r.get::<_, String>(6)?,
                        r.get::<_, String>(7)?,
                        r.get::<_, Option<String>>(8)?,
                    ))
                })
                .optional()
                .db()?;
            let Some((kind, name, hash, label, description, args, examples, source, signed_by)) = row else {
                return Ok(None);
            };
            entry_from_columns(&kind, name, hash, label, description, &args, &examples, &source, signed_by).map(Some)
        })
    }

    fn catalog_summary(&self) -> Result<Summary> {
        self.run("catalog_summary", |c| {
            let rows: Vec<(String, String, String, i64)> = {
                let mut st = c
                    .prepare(
                        "SELECT kind, name, label, CASE WHEN kind = 'function'
                             THEN (SELECT count(*) FROM cells x WHERE x.fn_hash = e.hash) ELSE 0 END
                           FROM catalog_entries e ORDER BY kind, name",
                    )
                    .db()?;
                let mapped = st.query_map([], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?))).db()?;
                mapped.collect::<rusqlite::Result<Vec<_>>>().db()?
            };
            let mut entries = Vec::with_capacity(rows.len());
            for (kind, name, label, n_cells) in rows {
                let kind = CatalogKind::parse(&kind).ok_or_else(|| invalid("catalog", "a stored entry has a bad kind"))?;
                entries.push(SummaryEntry { kind, name, label, n_cells });
            }
            let groups: Vec<(String, String, i64)> = {
                let mut st = c.prepare("SELECT owner, key, count(*) FROM key_values GROUP BY owner, key ORDER BY owner, key").db()?;
                let mapped = st.query_map([], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?))).db()?;
                mapped.collect::<rusqlite::Result<Vec<_>>>().db()?
            };
            let mut dictionaries = Vec::with_capacity(groups.len());
            for (owner, key, n_values) in groups {
                let values: Vec<DictionaryValue> = {
                    let mut st = c
                        .prepare("SELECT value, label, n_cells FROM key_values WHERE owner = ?1 AND key = ?2 ORDER BY value LIMIT ?3")
                        .db()?;
                    let mapped = st
                        .query_map(rusqlite::params![owner, key, as_i64(SUMMARY_VALUES)], |r| {
                            Ok(DictionaryValue { value: r.get(0)?, label: r.get(1)?, n_cells: r.get(2)? })
                        })
                        .db()?;
                    mapped.collect::<rusqlite::Result<Vec<_>>>().db()?
                };
                dictionaries.push(Dictionary { owner, key, n_values, values });
            }
            Ok(Summary { entries, dictionaries })
        })
    }
}

/// The columns of a value row: (tx, receipt_hash, asof, value_type, value, cell_id,
/// arguments, ns, fn, fn_hash).
type ValueColumns = (String, String, String, String, String, String, String, String, String, String);

fn value_columns(r: &rusqlite::Row<'_>) -> rusqlite::Result<ValueColumns> {
    Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?, r.get(5)?, r.get(6)?, r.get(7)?, r.get(8)?, r.get(9)?))
}

/// A member's value and cell, rebuilt from the typed-argument index (with its arguments).
fn value_of(c: ValueColumns) -> Result<(SliceValue, Args)> {
    let (tx, receipt_hash, asof, ty, value, cell_id, args, ns, fn_name, fn_hash) = c;
    let ty = Type::from_name(&ty).ok_or_else(|| bad("type"))?;
    let args = args_of(&args)?;
    let cell = Cell { args: args.clone(), fn_hash, fn_name, ns };
    Ok((
        SliceValue {
            version: Version { cell_id, tx, receipt_hash, asof },
            value: Scalar::from_lexical(ty, &value)?,
            cell,
        },
        args,
    ))
}

/// The constraints of a slice as the queries take them (`:cons`): `[name, kind, type, lo,
/// hi]`, a number range's ends as sort keys, a bound value's lexical form as `lo`.
fn constraints(p: &Pattern) -> String {
    let items: Vec<Value> = p
        .args
        .iter()
        .map(|a| {
            let (lo, hi) = match a.kind {
                Kind::Range => (sort_key(&a.ty, &a.lo), sort_key(&a.ty, &a.hi)),
                _ => (a.lo.clone(), a.hi.clone()),
            };
            Value::Array(
                [a.name.clone(), a.kind.as_str().to_string(), a.ty.clone(), lo, hi]
                    .into_iter()
                    .map(Value::String)
                    .collect(),
            )
        })
        .collect();
    String::from_utf8(Value::Array(items).to_jcs()).unwrap_or_default()
}

/// Binds the named parameters a statement has, from `params` (skipping the others).
fn bind(st: &mut rusqlite::CachedStatement<'_>, params: &[(&str, SqlValue)]) -> Result<()> {
    for (name, value) in params {
        if let Some(i) = st.parameter_index(name).db()? {
            st.raw_bind_parameter(i, value).db()?;
        }
    }
    Ok(())
}

/// The bound or ranged argument holding the fewest cells (probed, up to 10,001, when there
/// are several, or when `count` asks), else none (every cell of the function); and the
/// number of candidates when probed.
fn drive<'p>(p: &'p Pattern, c: &Connection, count: bool) -> Result<(Option<&'p Constraint>, Option<i64>)> {
    let probe = |a: Option<&Constraint>| -> Result<i64> {
        match a {
            None => c.prepare_cached(L::ProbeCells.sql()).db()?.query_row([&p.fn_hash], |r| r.get(0)).db(),
            Some(a) => {
                let (lo, hi) = (sort_key(&a.ty, &a.lo), sort_key(&a.ty, &a.hi));
                c.prepare_cached(L::SliceProbe.sql())
                    .db()?
                    .query_row(rusqlite::params![p.fn_hash, a.name, a.ty, lo, hi], |r| r.get(0))
                    .db()
            }
        }
    };
    let constrained: Vec<&Constraint> = p.args.iter().filter(|a| a.kind != Kind::Open).collect();
    Ok(match constrained.as_slice() {
        [] => (None, if count { Some(probe(None)?) } else { None }),
        [one] => (Some(*one), if count { Some(probe(Some(one))?) } else { None }),
        several => {
            let mut best: Option<(i64, &Constraint)> = None;
            for a in several {
                let n = probe(Some(a))?;
                if best.is_none_or(|(m, _)| n < m) {
                    best = Some((n, a));
                }
            }
            (best.map(|(_, a)| a), best.map(|(n, _)| n))
        }
    })
}

/// The parameters of a slice query: the slice's, and the driving argument's range.
fn params(p: &Pattern, asof: &str, drive: Option<&Constraint>) -> Vec<(&'static str, SqlValue)> {
    let text = |s: &str| SqlValue::Text(s.to_string());
    let mut out = vec![
        (":fn_hash", text(&p.fn_hash)),
        (":ns", text(&p.ns)),
        (":fn", text(&p.fn_name)),
        (":nargs", SqlValue::Integer(p.args.len() as i64)),
        (":asof", text(asof)),
        (":cons", SqlValue::Text(constraints(p))),
    ];
    if let Some(a) = drive {
        out.push((":d_name", text(&a.name)));
        out.push((":d_type", text(&a.ty)));
        out.push((":d_lo", SqlValue::Text(sort_key(&a.ty, &a.lo))));
        out.push((":d_hi", SqlValue::Text(sort_key(&a.ty, &a.hi))));
    }
    out
}

/// The rows of one of the member queries `qs` (all cells, driven), each made by `make`.
fn rows<T>(
    p: &Pattern,
    c: &Connection,
    asof: &str,
    qs: [L; 2],
    make: impl Fn(&rusqlite::Row<'_>) -> rusqlite::Result<T>,
) -> Result<Vec<T>> {
    let (d, _) = drive(p, c, false)?;
    let q = if d.is_some() { qs[1] } else { qs[0] };
    let mut st = c.prepare_cached(q.sql()).db()?;
    bind(&mut st, &params(p, asof, d))?;
    let mut rows = st.raw_query();
    let mut out = Vec::new();
    while let Some(r) = rows.next().db()? {
        out.push(make(r).db()?);
    }
    Ok(out)
}

/// The key of a member: the "type:value" of its open and ranged arguments, by name.
fn key_of(p: &Pattern, args: &Args) -> Vec<String> {
    p.args
        .iter()
        .filter(|a| a.kind != Kind::Value)
        .filter_map(|a| args.get(&a.name).and_then(Arg::scalar))
        .map(|s| format!("{}:{}", s.ty().as_str(), s.lexical()))
        .collect()
}

/// Members with their argument lists (JSON), in key order (then by cell id).
fn in_key_order<T>(p: &Pattern, rows: Vec<(T, String)>, cell_of: impl Fn(&T) -> &String) -> Result<Vec<T>> {
    let mut keyed = Vec::with_capacity(rows.len());
    for (m, args) in rows {
        keyed.push((key_of(p, &args_of(&args)?), m));
    }
    keyed.sort_by(|(a, ma), (b, mb)| cmp_keys(a, b).then_with(|| cell_of(ma).cmp(cell_of(mb))));
    Ok(keyed.into_iter().map(|(_, m)| m).collect())
}

/// Members with their parsed arguments, in key order (then by cell id).
fn in_key_order_parsed<T>(p: &Pattern, rows: Vec<(T, Args)>, cell_of: impl Fn(&T) -> &String) -> Result<Vec<T>> {
    let mut keyed: Vec<(Vec<String>, T)> = rows.into_iter().map(|(m, args)| (key_of(p, &args), m)).collect();
    keyed.sort_by(|(a, ma), (b, mb)| cmp_keys(a, b).then_with(|| cell_of(ma).cmp(cell_of(mb))));
    Ok(keyed.into_iter().map(|(_, m)| m).collect())
}

/// The members' values of a slice of cells as of `asof`, in key order, at most `limit`: the
/// statement of `slice_values` with the key order and the LIMIT in SQL. The order of `cmp_keys`
/// is, per key argument by name, the type's name, then the sort key (which sorts as the value
/// does, a number's as the decimal does).
fn values_limited(p: &Pattern, c: &Connection, asof: &str, limit: i64) -> Result<Vec<SliceValue>> {
    let (d, _) = drive(p, c, false)?;
    let base = if d.is_some() { L::SliceValuesDrive } else { L::SliceValuesAll };
    let keys: Vec<&Constraint> = p.args.iter().filter(|a| a.kind != Kind::Value).collect();
    let mut order = Vec::with_capacity(keys.len() * 2 + 1);
    for i in 0..keys.len() {
        let of =
            |col: &str| format!("(SELECT x.{col} FROM cell_args x WHERE x.cell_id = c.cell_id AND x.name = :k{i})");
        order.push(of("type"));
        order.push(of("sort_key"));
    }
    order.push("c.cell_id".to_string());
    let sql = format!("{} ORDER BY {} LIMIT :limit", base.sql(), order.join(", "));
    let mut binds: Vec<(String, SqlValue)> = params(p, asof, d).into_iter().map(|(k, v)| (k.to_string(), v)).collect();
    for (i, a) in keys.iter().enumerate() {
        binds.push((format!(":k{i}"), SqlValue::Text(a.name.clone())));
    }
    binds.push((":limit".to_string(), SqlValue::Integer(limit)));
    let mut st = c.prepare(&sql).db()?;
    for (name, value) in &binds {
        if let Some(i) = st.parameter_index(name).db()? {
            st.raw_bind_parameter(i, value).db()?;
        }
    }
    let mut rows = st.raw_query();
    let mut out = Vec::new();
    while let Some(r) = rows.next().db()? {
        out.push(value_of(value_columns(r).db()?)?.0);
    }
    Ok(out)
}

/// Whether a matching cell has a stored version answering from after `asof`: from
/// whichever side is smaller (both probed, up to 10,001), the function's receipts with an
/// asof after `asof`, or the slice's candidate cells.
fn changed_after(p: &Pattern, c: &Connection, asof: &str) -> Result<bool> {
    let (d, candidates) = drive(p, c, true)?;
    let recent: i64 = c
        .prepare_cached(L::ProbeRecent.sql())
        .db()?
        .query_row(rusqlite::params![p.fn_hash, asof], |r| r.get(0))
        .db()?;
    let q = if recent <= candidates.unwrap_or(i64::MAX) {
        L::ChangedRecent
    } else if d.is_some() {
        L::ChangedCandDrive
    } else {
        L::ChangedCandAll
    };
    let d = if q == L::ChangedCandDrive { d } else { None };
    let mut st = c.prepare_cached(q.sql()).db()?;
    bind(&mut st, &params(p, asof, d))?;
    let mut rows = st.raw_query();
    Ok(rows.next().db()?.is_some())
}

/// The columns of an entry row, as `entry_from_columns` takes them, with the id first.
type EntryRow = (i64, String, String, Option<String>, String, String, String, String, String, Option<String>);

fn entry_columns(r: &rusqlite::Row<'_>) -> rusqlite::Result<EntryRow> {
    Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?, r.get(5)?, r.get(6)?, r.get(7)?, r.get(8)?, r.get(9)?))
}

/// A dictionary value's row: id, owner, key, value, label, aliases (JSON).
type ValueRow = (i64, String, String, String, String, String);

fn value_columns_of(r: &rusqlite::Row<'_>) -> rusqlite::Result<ValueRow> {
    Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?, r.get(5)?))
}

/// The `AND (...)` prefilter of a text search over `fields` (SQL expressions): one clause per
/// word the SQL can match exactly (ASCII, no `"`, `\` or control characters: SQLite's LIKE
/// folds ASCII only, and JSON text escapes those), with its parameters numbered from ?1.
fn like_where_sqlite(words: &Words, fields: &[&str]) -> (String, Vec<String>) {
    let mut sql = String::new();
    let mut params = Vec::new();
    for i in 0..words.len() {
        if let Some(p) = words.pattern(i, sqlite_safe) {
            params.push(p);
            let n = params.len();
            let ors: Vec<String> = fields.iter().map(|f| format!("{f} LIKE ?{n} ESCAPE '!'")).collect();
            sql.push_str(&format!(" AND ({})", ors.join(" OR ")));
        }
    }
    (sql, params)
}

fn sqlite_safe(word: &str) -> bool {
    word.is_ascii() && !word.chars().any(|c| c == '"' || c == '\\' || c.is_control())
}

fn unsupported_vectors() -> Error {
    Error::Unsupported("vectors need PostgreSQL with the vector extension; SQLite has none".into())
}

/// A function test row of `function_tests`, in the column order of `FunctionTestsOf`.
fn function_test_row(r: &rusqlite::Row<'_>) -> rusqlite::Result<FunctionTest> {
    Ok(FunctionTest {
        fn_hash: r.get(0)?,
        case: r.get(1)?,
        test_json: r.get(2)?,
        signed_by: r.get(3)?,
        last_run_at: r.get(4)?,
        last_result: r.get(5)?,
        last_detail: r.get(6)?,
        branches_total: r.get(7)?,
        branches_covered: r.get(8)?,
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::slices::cmp_decimal;

    #[test]
    fn decimal_keys_sort_as_the_numbers() {
        let mut numbers: Vec<String> = [
            "0", "9", "10", "-1.5", "-1", "-1.25", "-1.11", "-1.1", "-0.1", "-0.099", "0.099", "0.1", "0.109", "0.11",
            "1", "1.1", "1.109", "1.11", "9.5", "99.999", "100", "-100", "-10", "-9", "123", "-123", "0.0001",
            "-0.0001", "1000000", "-1000000", "12.5", "12.05", "-12.5", "-12.05", "120", "-120", "1.2", "-1.2",
        ]
        .iter()
        .map(|s| s.to_string())
        .collect();
        numbers.push("9".repeat(128));
        numbers.push(format!("-{}", "9".repeat(127)));
        numbers.push(format!("1{}", "0".repeat(127)));
        numbers.push(format!("-1{}", "0".repeat(126)));
        numbers.push(format!("0.{}1", "0".repeat(125)));
        numbers.push(format!("-0.{}1", "0".repeat(124)));
        numbers.push(format!("{}.{}", "1".repeat(64), "1".repeat(63)));
        numbers.push(format!("-{}.{}", "1".repeat(63), "1".repeat(63)));
        for a in &numbers {
            assert!(a.len() <= 128, "{a}");
            for b in &numbers {
                assert_eq!(decimal_key(a).cmp(&decimal_key(b)), cmp_decimal(a, b), "{a} vs {b}");
            }
        }
        // Equal numbers, equal keys; the forms.
        assert_eq!(decimal_key("0"), "1");
        assert_eq!(decimal_key("100"), "25031");
        assert_eq!(decimal_key("0.0012"), "249812");
        assert_eq!(decimal_key("-1.5"), "049884~");
        assert_eq!(decimal_key(&"9".repeat(128)), format!("2628{}", "9".repeat(128)));
    }

    #[test]
    fn result_codes_have_names() {
        assert_eq!(result_code_name(5), "SQLITE_BUSY");
        assert_eq!(result_code_name(1811), "SQLITE_CONSTRAINT_TRIGGER");
        assert_eq!(result_code_name(14), "SQLITE_CANTOPEN");
        assert_eq!(result_code_name(10 | (99 << 8)), "SQLITE_IOERR(25354)");
    }

    #[test]
    fn sqlite_urls_name_paths() {
        assert_eq!(sqlite_path("sqlite:store.db"), "store.db");
        assert_eq!(sqlite_path("sqlite://store.db"), "store.db");
        assert_eq!(sqlite_path("sqlite:///var/lib/x.db"), "/var/lib/x.db");
        assert_eq!(sqlite_path("/var/lib/x.db"), "/var/lib/x.db");
        assert_eq!(sqlite_path("x.db"), "x.db");
    }

    /// The plan of a statement, one line per step (`EXPLAIN QUERY PLAN`).
    fn plan(c: &Connection, sql: &str) -> Vec<String> {
        let mut st = c.prepare(&format!("EXPLAIN QUERY PLAN {sql}")).unwrap();
        let n = st.parameter_count();
        for i in 1..=n {
            st.raw_bind_parameter(i, "x").unwrap();
        }
        let mut rows = st.raw_query();
        let mut out = Vec::new();
        while let Some(r) = rows.next().unwrap() {
            out.push(r.get::<_, String>(3).unwrap());
        }
        out
    }

    /// The statements of bounded slices and of the probes look tables up by index only: no
    /// step scans a table or a whole index (SQLite's counterpart of the PostgreSQL tests'
    /// sequential-scan counters). Planned on the migrated schema with statistics of a
    /// loaded store's shape (100,000 cells of one function).
    #[test]
    fn bounded_slices_use_indexes() {
        let c = Connection::open_in_memory().unwrap();
        for m in crate::migrate::sqlite::MIGRATIONS {
            c.execute_batch(m.sql).unwrap();
        }
        // Statistics as ANALYZE leaves them for 100,000 cells, 2 arguments each.
        c.execute_batch(
            "ANALYZE sqlite_schema;
             INSERT INTO sqlite_stat1 (tbl, idx, stat) VALUES
               ('cells', 'cells_fn_hash', '100000 100000 1'),
               ('cells', 'sqlite_autoindex_cells_1', '100000 1'),
               ('cell_args', 'cell_args_key', '200000 200000 100000 100000 1 1'),
               ('cell_args', 'sqlite_autoindex_cell_args_1', '200000 2 1'),
               ('versions', 'sqlite_autoindex_versions_1', '100000 1 1'),
               ('versions', 'versions_receipt_hash', '100000 1'),
               ('receipts', 'sqlite_autoindex_receipts_1', '100000 1'),
               ('receipts', 'receipts_cell_tx', '100000 1 1'),
               ('receipts', 'receipts_fn_hash_asof', '100000 100000 1'),
               ('receipts', 'receipts_cell_asof', '100000 1 1');
             ANALYZE sqlite_schema;",
        )
        .unwrap();
        // A scan of the constraints (json_each) or of a subquery's rows is fine; of a table
        // or an index, not.
        let scans = |s: &str| s.starts_with("SCAN ") && !s.starts_with("SCAN k") && !s.starts_with("SCAN (subquery");
        for q in [
            L::SliceMembersDrive,
            L::SliceValuesDrive,
            L::ChangedCandDrive,
            L::ChangedRecent,
            L::SliceProbe,
            L::ProbeRecent,
            L::ProbeCells,
            L::VersionsBetween,
            L::VersionsBetweenValues,
            L::StoredAsof,
            L::ComputedAsof,
            L::CellDependents,
        ] {
            let steps = plan(&c, q.sql());
            assert!(!steps.iter().any(|s| scans(s)), "{q:?} scans:\n{steps:#?}");
        }
        // The unbounded ones walk the function's cells by index, and nothing else.
        for q in [L::SliceMembersAll, L::SliceValuesAll, L::ChangedCandAll] {
            let steps = plan(&c, q.sql());
            assert!(
                steps.iter().any(|s| s.contains("SEARCH c USING") && s.contains("cells_fn_hash")),
                "{q:?}: {steps:#?}"
            );
            assert!(!steps.iter().any(|s| scans(s)), "{q:?} scans:\n{steps:#?}");
        }
    }
}