day-persistence 0.4.0

SQLite persistence for the Day observable model.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
// Copyright © The Daybrite Project
// SPDX-License-Identifier: MPL-2.0

//! SQLite persistence for the observable model (docs/persistence.md).
//!
//! An app depends on this crate directly, beside the `day` facade with its `model` feature on,
//! and starts a model module with `use day_persistence::prelude::*`. The crate is built on the
//! framework's public API and nothing in the framework depends on it; `#[derive(Model)]` comes
//! from day-persistence-macros and the web engine from day-sqlite-worker.
//!
//! The engine owns the data; memory holds a working set. A [`ModelContainer`] opens a
//! database through a pluggable [`SqliteDriver`], creates or migrates each model's table,
//! and stops: no rows are read at open, so opening a million-row store costs the same as
//! opening an empty one. Rows enter memory by faulting: a typed [`ModelContainer::get`], a
//! batch [`ModelContainer::ensure_resident`], or a list binding materializing the rows it is
//! about to show. Each model's [`Store`] is that working set (an ordinary day-model store,
//! so every binding and accessor works on it unchanged), bounded by a per-table cache limit;
//! clean rows nothing observes leave silently and fault back on the next read.
//!
//! The write half is day-model's change log, folded. Any write requires its row resident
//! (editing is what faulted it in); at the end of any turn that touched a store (autosave,
//! the default) the accumulated changes fold into the smallest statement list that expresses
//! them: twenty keystrokes into one field is one `UPDATE`; a row inserted and then filled is
//! one `INSERT`; a thousand-child cascade is a handful of chunked `DELETE`s.
//!
//! Typed live queries ([`ModelContainer::query`]) compile entirely to SQL: predicate to
//! `WHERE` (relation crossings as correlated `EXISTS`, full-text as an FTS5 subquery, spatial
//! boxes through the R*Tree shadow), sort to `ORDER BY` with the key as tie-break, window to
//! `LIMIT`, so the engine's indexes answer them at any table size. Live maintenance is
//! dependency-gated: a change to a column no query mentions costs nothing; a change a query
//! does depend on marks it stale, and one requery after the turn's flush re-derives its id
//! set, diffed against the previous answer so a list animates the difference instead of
//! reloading. Rows behind the ids stay lazy: the query holds ids, and the list faults the
//! window it shows.
//!
//! The driver is a trait so the engine is the app's choice: the built-in [`Sqlite`] driver
//! (feature `driver-rusqlite`, on by default) compiles a bundled SQLite, links the system one
//! (`system`), or builds SQLCipher (`cipher`); the [`Recorder`] answers from fixtures and
//! records every statement, which is what keeps persistence assertable headlessly: a test
//! can check the SQL a UI action produced without a database on disk.
//!
//! Another connection's committed writes arrive through [`ModelContainer::check_external`],
//! which re-reads only the resident rows and re-runs the live queries: O(working set), never
//! O(table). Row identity is the model's `#[model(id)]` key; display order is a projection
//! concern and is not persisted.

use std::any::{Any, TypeId};
use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::fmt;
use std::path::{Path, PathBuf};
use std::rc::Rc;

use day_model::Source;
use day_model::{Identified, Key, Keyed, ModelId, Op, Store};

#[cfg(not(target_arch = "wasm32"))]
mod worker;
#[cfg(not(target_arch = "wasm32"))]
pub use worker::{
    DatabaseWorker, WorkerOptions, WorkerRequest, WorkerSnapshot, WorkerSubscription,
};

mod queries;
pub use queries::{
    Col, Delta, Deps, Fetch, FtsRef, GeoRect, GeoRef, Pred, Quant, RelatedDep, RelationCol,
    ResultSet, RowView, SetChange, Sort, compare_values, encode_column, rank,
};
use queries::{
    CompileErr, FtsSql, RelSql, SqlIndex, compile_count, compile_fallback, compile_fetch,
};

mod blob;
pub use blob::{Blob, BlobField, BlobReader};
mod relations;
pub use relations::{
    DeleteRule, Many, One, Registrar, RelationDef, RelationRef, wire_join, wire_to_many,
};

#[cfg(feature = "driver-rusqlite")]
mod rusqlite_driver;
#[cfg(feature = "driver-rusqlite")]
pub use rusqlite_driver::Sqlite;
#[cfg(all(
    feature = "driver-rusqlite",
    target_family = "wasm",
    target_os = "unknown"
))]
pub use rusqlite_driver::WebStorage;

/// The derive for the [`Model`] trait (the two share a name, so `use day_persistence::Model`
/// brings both): everything `#[derive(Observable)]` generates plus the schema half.
/// `#[model(id)]` marks the key; docs/persistence.md lists the field and struct options.
pub use day_persistence_macros::Model;

// `#[derive(Model)]` expands its observable half to this (day-macros' `observable_impls!`),
// reached by this crate's name so a model crate needs no day-macros dependency of its own.
#[doc(hidden)]
pub use day_macros::observable_impls as __observable_impls;

/// What a model module starts from: `use day_persistence::prelude::*;` beside the app's `use
/// day::prelude::*;`. The container, the `Model` trait and its derive, the relation markers,
/// the drivers and `schema!`.
pub mod prelude {
    #[cfg(feature = "driver-rusqlite")]
    pub use crate::Sqlite;
    pub use crate::{DeleteRule, Many, Model, ModelContainer, One, Recorder, Secret, schema};
}

// ---------------------------------------------------------------------------
// Errors
// ---------------------------------------------------------------------------

/// Why a persistence operation failed. `message` is for the log; `kind` is for the code path
/// that can do something about it.
#[derive(Clone, Debug)]
pub struct DbError {
    pub kind: DbErrorKind,
    pub message: String,
}

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum DbErrorKind {
    /// An asynchronous request was rejected because its worker has closed.
    Closed,
    /// The bounded worker queue has no room; the request was not accepted.
    Busy,
    /// A queued read was cancelled before it began.
    Cancelled,
    /// A worker operation panicked. The worker is closed and must be reopened.
    Panicked,
    /// The transaction committed, but refreshing resident models failed. Do not replay the
    /// write. Recover the cache with `rescan` before editing; workers retry before their next job.
    CommittedRefreshFailed,
    /// The engine said no: SQL error, I/O, constraint.
    Driver,
    /// The stored schema and the declared one disagree in a way lightweight migration cannot
    /// close (a type change, a rename); the file is refused, never silently rewritten.
    Schema,
    /// The database would not open with the key it was given.
    BadKey,
    /// A stored value would not decode as the field's type.
    Decode,
    /// The driver cannot do this (encryption on a non-cipher build, …).
    Unsupported,
    /// A `DeleteRule::Deny` relation refused the delete: children still reference the row.
    Deny,
}

impl DbError {
    pub fn new(kind: DbErrorKind, message: impl Into<String>) -> Self {
        DbError {
            kind,
            message: message.into(),
        }
    }
    /// Engine-error shorthand for driver implementations (public: external drivers use it too).
    pub fn driver(message: impl Into<String>) -> Self {
        Self::new(DbErrorKind::Driver, message)
    }
}

impl fmt::Display for DbError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:?}: {}", self.kind, self.message)
    }
}

impl std::error::Error for DbError {}

// ---------------------------------------------------------------------------
// Values and rows
// ---------------------------------------------------------------------------

/// SQLite's five storage classes, and nothing else; no driver type reaches the layer above.
#[derive(Clone, Debug, PartialEq)]
pub enum Value {
    Null,
    Int(i64),
    Real(f64),
    Text(String),
    Blob(Vec<u8>),
}

impl Value {
    pub fn as_int(&self) -> Result<i64, DbError> {
        match self {
            Value::Int(i) => Ok(*i),
            other => Err(DbError::new(
                DbErrorKind::Decode,
                format!("expected INTEGER, found {other:?}"),
            )),
        }
    }
    pub fn as_real(&self) -> Result<f64, DbError> {
        match self {
            Value::Real(r) => Ok(*r),
            Value::Int(i) => Ok(*i as f64),
            other => Err(DbError::new(
                DbErrorKind::Decode,
                format!("expected REAL, found {other:?}"),
            )),
        }
    }
    pub fn as_text(&self) -> Result<&str, DbError> {
        match self {
            Value::Text(t) => Ok(t),
            other => Err(DbError::new(
                DbErrorKind::Decode,
                format!("expected TEXT, found {other:?}"),
            )),
        }
    }
    pub fn as_blob(&self) -> Result<&[u8], DbError> {
        match self {
            Value::Blob(b) => Ok(b),
            other => Err(DbError::new(
                DbErrorKind::Decode,
                format!("expected BLOB, found {other:?}"),
            )),
        }
    }
}

/// A column's declared type. Part of the schema fingerprint, so changing one is a migration.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum SqlType {
    Integer,
    Real,
    Text,
    Blob,
}

impl SqlType {
    pub fn ddl(self) -> &'static str {
        match self {
            SqlType::Integer => "INTEGER",
            SqlType::Real => "REAL",
            SqlType::Text => "TEXT",
            SqlType::Blob => "BLOB",
        }
    }
}

/// One result row, by position.
pub trait Row {
    fn len(&self) -> usize;
    fn get(&self, i: usize) -> Value;
    fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

impl Row for Vec<Value> {
    fn len(&self) -> usize {
        Vec::len(self)
    }
    fn get(&self, i: usize) -> Value {
        self.as_slice().get(i).cloned().unwrap_or(Value::Null)
    }
}

// ---------------------------------------------------------------------------
// The driver interface
// ---------------------------------------------------------------------------

/// Where the database lives.
#[derive(Clone, Debug)]
pub enum Location {
    Memory,
    File(PathBuf),
}

/// A key for an encrypted database. Redacted in Debug and zeroed on drop; where it lives
/// between launches is the app's business, never this crate's.
#[derive(Clone)]
pub struct Secret(String);

impl Secret {
    pub fn new(key: impl Into<String>) -> Self {
        Secret(key.into())
    }
    #[cfg(feature = "cipher")]
    pub(crate) fn reveal(&self) -> &str {
        &self.0
    }
}

impl fmt::Debug for Secret {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("Secret(…)")
    }
}

impl Drop for Secret {
    fn drop(&mut self) {
        // Best-effort scrub; the allocation may have been moved by earlier clones.
        unsafe {
            // SAFETY: we own the String and overwrite only its initialized bytes in place.
            for b in self.0.as_bytes_mut() {
                *b = 0;
            }
        }
    }
}

/// How to open the database. Built by the driver's own constructors ([`Sqlite::at`] etc.);
/// public so alternative drivers speak the same vocabulary.
#[derive(Clone, Debug)]
pub struct OpenOptions {
    pub location: Location,
    /// SQLCipher key; drivers without encryption reject it loudly.
    pub key: Option<Secret>,
    /// Journal in WAL mode (files only; ignored in memory). Default true.
    pub wal: bool,
    /// Enforce foreign keys. Default true.
    pub foreign_keys: bool,
    pub busy_timeout_ms: u32,
    /// Upgrade a file written by an older SQLCipher generation (PRAGMA cipher_migrate).
    pub cipher_migrate: bool,
}

impl OpenOptions {
    pub fn new(location: Location) -> Self {
        OpenOptions {
            location,
            key: None,
            wal: true,
            foreign_keys: true,
            busy_timeout_ms: 5_000,
            cipher_migrate: false,
        }
    }
}

/// What a driver can and cannot do, so the container degrades visibly instead of silently.
#[derive(Clone, Copy, Debug, Default)]
pub struct Capabilities {
    /// Survives a relaunch (false for memory stores and the Recorder).
    pub durable: bool,
    pub encryption: bool,
    pub wal: bool,
    pub full_text_search: bool,
    pub rtree: bool,
    /// Another connection's committed writes are detectable (SQLite's `PRAGMA data_version`
    /// counter), so [`ModelContainer::check_external`] can merge them. The built-in driver
    /// claims it for file databases on native targets; memory databases (no second connection
    /// can reach one), the Recorder, and the web engine (its OPFS access is exclusive) do not.
    pub external_changes: bool,
    /// The connection has `day_fold` registered (Rust's full-Unicode `to_lowercase` as a
    /// scalar SQL function), so case-insensitive text predicates compile to exact SQL. The
    /// built-in native driver registers it at open; without it those predicates take the
    /// fallback path (SQL for everything else, the folding test re-checked in memory).
    pub unicode_fold: bool,
}

/// What `PRAGMA wal_checkpoint(TRUNCATE)` answered ([`ModelContainer::checkpoint`]): the
/// three columns of its status row. The engine reads the counts after the checkpoint, so a
/// completed one answers `0` and `0` (the log was emptied); a busy one describes the log it
/// had to leave behind. Both counts are `-1` when the database is not in WAL mode (a memory
/// database, or `wal: false`).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Checkpoint {
    /// A reader or writer kept the checkpoint from completing within the busy timeout; the
    /// WAL was folded as far as it could be and the rest waits for the next call.
    pub busy: bool,
    /// Frames in the WAL when the checkpoint finished.
    pub log_frames: i64,
    /// Frames of that log already carried into the main file.
    pub checkpointed_frames: i64,
}

impl Checkpoint {
    /// The whole log was folded and truncated.
    pub fn is_complete(&self) -> bool {
        !self.busy
    }
}

/// One row of `PRAGMA foreign_key_check` ([`ModelContainer::foreign_key_check`]): a child
/// row whose reference names no parent.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ForeignKeyViolation {
    /// The child table.
    pub table: String,
    /// The child row's rowid; `None` for a `WITHOUT ROWID` table.
    pub rowid: Option<i64>,
    /// The parent table the reference names.
    pub parent: String,
    /// The constraint's index in the child's `PRAGMA foreign_key_list`.
    pub constraint: i64,
}

impl fmt::Display for ForeignKeyViolation {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.rowid {
            Some(rowid) => write!(
                f,
                "foreign key: {} row {rowid} references missing {}",
                self.table, self.parent
            ),
            None => write!(
                f,
                "foreign key: {} row references missing {}",
                self.table, self.parent
            ),
        }
    }
}

/// The engine trait. Object-safe on the connection side, so the container stores
/// `Box<dyn SqliteConnection>` and never names an engine type.
pub trait SqliteDriver {
    type Connection: SqliteConnection;
    fn open(self) -> Result<Self::Connection, DbError>;
    fn capabilities(&self) -> Capabilities;
}

impl SqliteConnection for Box<dyn SqliteConnection> {
    fn execute(&mut self, sql: &str, params: &[Value]) -> Result<u64, DbError> {
        (**self).execute(sql, params)
    }
    fn query(
        &mut self,
        sql: &str,
        params: &[Value],
        row: &mut dyn FnMut(&dyn Row),
    ) -> Result<(), DbError> {
        (**self).query(sql, params, row)
    }
    fn execute_batch(&mut self, sql: &str) -> Result<(), DbError> {
        (**self).execute_batch(sql)
    }
    fn query_named(
        &mut self,
        sql: &str,
        params: &[Value],
        row: &mut dyn FnMut(&[String], &dyn Row),
    ) -> Result<(), DbError> {
        (**self).query_named(sql, params, row)
    }
}

/// One open connection. Everything above speaks plain SQL and [`Value`]s through it.
pub trait SqliteConnection: 'static {
    fn execute(&mut self, sql: &str, params: &[Value]) -> Result<u64, DbError>;
    fn query(
        &mut self,
        sql: &str,
        params: &[Value],
        row: &mut dyn FnMut(&dyn Row),
    ) -> Result<(), DbError>;
    fn begin(&mut self) -> Result<(), DbError> {
        self.execute("BEGIN", &[]).map(|_| ())
    }
    fn commit(&mut self) -> Result<(), DbError> {
        self.execute("COMMIT", &[]).map(|_| ())
    }
    fn rollback(&mut self) -> Result<(), DbError> {
        self.execute("ROLLBACK", &[]).map(|_| ())
    }
    /// Several statements in one string, no parameters: a DDL script, a migration step
    /// (day-lite's storage speaks this). The default runs the string as one statement;
    /// drivers whose engine executes scripts override it (the built-in native driver does).
    fn execute_batch(&mut self, sql: &str) -> Result<(), DbError> {
        self.execute(sql, &[]).map(|_| ())
    }
    /// [`SqliteConnection::query`], with the result's column names alongside each row, for
    /// callers that surface rows as named objects (day-lite's JS bridge). A driver that
    /// cannot name columns refuses rather than guessing.
    fn query_named(
        &mut self,
        sql: &str,
        params: &[Value],
        row: &mut dyn FnMut(&[String], &dyn Row),
    ) -> Result<(), DbError> {
        let _ = (sql, params, row);
        Err(DbError::new(
            DbErrorKind::Unsupported,
            "this driver does not report column names",
        ))
    }
}

// ---------------------------------------------------------------------------
// The Recorder: the headless fake
// ---------------------------------------------------------------------------

/// A driver that answers from fixtures and records every statement: the piece that keeps
/// persistence assertable with no database on disk. `let (driver, log) = Recorder::new();`
///
/// Fixtures answer by table, not by statement: any `SELECT … FROM <table>` serves every
/// fixture row registered for it, whatever the `WHERE` clause says. Faulting paths keep only
/// the keys they asked for, so `get` and `ensure_resident` behave; a query against the
/// Recorder answers with all fixture keys, so assert the SQL it recorded, and use
/// `Sqlite::memory()` where predicate results themselves are under test.
pub struct Recorder {
    state: Rc<RecorderState>,
}

struct RecorderState {
    log: RefCell<Vec<(String, Vec<Value>)>>,
    /// table name → rows served for a `SELECT … FROM <table>`.
    fixtures: RefCell<HashMap<String, Vec<Vec<Value>>>>,
}

/// The recorded statement log, shared with the test that holds it.
#[derive(Clone)]
pub struct RecorderLog {
    state: Rc<RecorderState>,
}

impl RecorderLog {
    /// Every statement so far, SQL text only.
    pub fn sql(&self) -> Vec<String> {
        self.state
            .log
            .borrow()
            .iter()
            .map(|(s, _)| s.clone())
            .collect()
    }
    /// Statements with their bound parameters.
    pub fn entries(&self) -> Vec<(String, Vec<Value>)> {
        self.state.log.borrow().clone()
    }
    pub fn clear(&self) {
        self.state.log.borrow_mut().clear();
    }
}

impl Recorder {
    pub fn new() -> (Recorder, RecorderLog) {
        let state = Rc::new(RecorderState {
            log: RefCell::new(Vec::new()),
            fixtures: RefCell::new(HashMap::new()),
        });
        (
            Recorder {
                state: state.clone(),
            },
            RecorderLog { state },
        )
    }

    /// Rows a table's `SELECT` will answer with.
    pub fn with_table(self, table: &str, rows: Vec<Vec<Value>>) -> Self {
        self.state.fixtures.borrow_mut().insert(table.into(), rows);
        self
    }
}

pub struct RecorderConn {
    state: Rc<RecorderState>,
}

impl SqliteDriver for Recorder {
    type Connection = RecorderConn;
    fn open(self) -> Result<RecorderConn, DbError> {
        Ok(RecorderConn { state: self.state })
    }
    fn capabilities(&self) -> Capabilities {
        Capabilities {
            durable: false,
            wal: false,
            // The fake answers everything: an FTS/spatial model must open against fixtures
            // (its reads just come back empty unless a fixture answers them), and folded
            // predicates compile as if day_fold existed; the SQL is recorded, never run.
            full_text_search: true,
            rtree: true,
            unicode_fold: true,
            ..Default::default()
        }
    }
}

impl SqliteConnection for RecorderConn {
    fn execute(&mut self, sql: &str, params: &[Value]) -> Result<u64, DbError> {
        self.state
            .log
            .borrow_mut()
            .push((sql.to_string(), params.to_vec()));
        Ok(0)
    }
    fn query(
        &mut self,
        sql: &str,
        params: &[Value],
        row: &mut dyn FnMut(&dyn Row),
    ) -> Result<(), DbError> {
        self.state
            .log
            .borrow_mut()
            .push((sql.to_string(), params.to_vec()));
        // Serve a fixture when the statement reads `FROM` a table one was registered for:
        // quoted, as the container writes it, or plain, as a raw query might.
        if let Some(from) = sql.split(" FROM ").nth(1) {
            let table = quoted_name(from)
                .unwrap_or_else(|| from.split_whitespace().next().unwrap_or("").to_string());
            if let Some(rows) = self.state.fixtures.borrow().get(&table) {
                for r in rows {
                    row(r);
                }
            }
        }
        Ok(())
    }
}

// ---------------------------------------------------------------------------
// Column values and codecs (docs/persistence.md)
// ---------------------------------------------------------------------------

/// A Rust type that knows how to be a column. One impl per type: its canonical form.
pub trait ColumnValue: Sized + 'static {
    /// The declared column type. Part of the schema fingerprint, so changing it is a
    /// migration, never a surprise.
    const SQL_TYPE: SqlType;
    fn to_sqlite_value(&self) -> Value;
    fn from_sqlite_value(v: Value) -> Result<Self, DbError>;
}

/// A named alternative representation for `T`, serde's `#[serde(with = …)]` idiom.
/// Implement on a unit struct; select it per field with `#[model(with = …)]`.
pub trait ValueCodec<T>: 'static {
    const SQL_TYPE: SqlType;
    fn to_sqlite_value(v: &T) -> Value;
    fn from_sqlite_value(v: Value) -> Result<T, DbError>;
}

macro_rules! int_column {
    ($($t:ty),*) => {$(
        impl ColumnValue for $t {
            const SQL_TYPE: SqlType = SqlType::Integer;
            fn to_sqlite_value(&self) -> Value {
                Value::Int(*self as i64)
            }
            fn from_sqlite_value(v: Value) -> Result<Self, DbError> {
                Ok(v.as_int()? as $t)
            }
        }
    )*};
}
int_column!(i8, i16, i32, i64, u8, u16, u32, u64, usize, isize);

impl ColumnValue for bool {
    const SQL_TYPE: SqlType = SqlType::Integer;
    fn to_sqlite_value(&self) -> Value {
        Value::Int(*self as i64)
    }
    fn from_sqlite_value(v: Value) -> Result<Self, DbError> {
        Ok(v.as_int()? != 0)
    }
}

impl ColumnValue for f64 {
    const SQL_TYPE: SqlType = SqlType::Real;
    fn to_sqlite_value(&self) -> Value {
        Value::Real(*self)
    }
    fn from_sqlite_value(v: Value) -> Result<Self, DbError> {
        v.as_real()
    }
}

impl ColumnValue for f32 {
    const SQL_TYPE: SqlType = SqlType::Real;
    fn to_sqlite_value(&self) -> Value {
        Value::Real(*self as f64)
    }
    fn from_sqlite_value(v: Value) -> Result<Self, DbError> {
        Ok(v.as_real()? as f32)
    }
}

impl ColumnValue for String {
    const SQL_TYPE: SqlType = SqlType::Text;
    fn to_sqlite_value(&self) -> Value {
        Value::Text(self.clone())
    }
    fn from_sqlite_value(v: Value) -> Result<Self, DbError> {
        Ok(v.as_text()?.to_string())
    }
}

impl ColumnValue for Vec<u8> {
    const SQL_TYPE: SqlType = SqlType::Blob;
    fn to_sqlite_value(&self) -> Value {
        Value::Blob(self.clone())
    }
    fn from_sqlite_value(v: Value) -> Result<Self, DbError> {
        Ok(v.as_blob()?.to_vec())
    }
}

/// A Uuid is a 16-byte `BLOB`: compact, indexable, and readable by any tool that knows the
/// convention. (`day_model::Uuid` is `uuid::Uuid`, so no second dependency edge exists.)
impl ColumnValue for day_model::Uuid {
    const SQL_TYPE: SqlType = SqlType::Blob;
    fn to_sqlite_value(&self) -> Value {
        Value::Blob(self.as_bytes().to_vec())
    }
    fn from_sqlite_value(v: Value) -> Result<Self, DbError> {
        day_model::Uuid::from_slice(v.as_blob()?)
            .map_err(|e| DbError::new(DbErrorKind::Decode, format!("uuid: {e}")))
    }
}

/// A key handle, as the bound parameter its stored form takes: `INTEGER` for integer keys,
/// a 16-byte `BLOB` for Uuid keys, `TEXT` for string keys. `Pair` keys (join rows) bind
/// through their own two-column clause, never through this.
fn key_param(handle: u64) -> Value {
    match Key::of_handle(handle) {
        Some(Key::U64(k)) => Value::Int(k as i64),
        Some(Key::Uuid(u)) => Value::Blob(day_model::Uuid::from_u128(u).as_bytes().to_vec()),
        Some(Key::Str(s)) => Value::Text(s.to_string()),
        Some(Key::Pair(..)) | None => Value::Null,
    }
}

/// A stored key value, back as its path handle. `None` for shapes no key takes (a negative
/// integer, a blob that is not 16 bytes); the caller treats those rows as unaddressable.
fn value_to_handle(v: &Value) -> Option<u64> {
    match v {
        Value::Int(i) if *i >= 0 => Some(Key::U64(*i as u64).handle()),
        Value::Blob(b) if b.len() == 16 => day_model::Uuid::from_slice(b)
            .ok()
            .map(|u| Key::Uuid(u.as_u128()).handle()),
        Value::Text(t) => Some(Key::Str(t.as_str().into()).handle()),
        _ => None,
    }
}

/// `NULL` belongs to the framework: `Option` wraps any column type, encoding is called only on
/// present values, and a NULL decodes to `None`, so an impl never sees `Null` and cannot
/// disagree about it.
impl<T: ColumnValue> ColumnValue for Option<T> {
    const SQL_TYPE: SqlType = T::SQL_TYPE;
    fn to_sqlite_value(&self) -> Value {
        match self {
            Some(v) => v.to_sqlite_value(),
            None => Value::Null,
        }
    }
    fn from_sqlite_value(v: Value) -> Result<Self, DbError> {
        match v {
            Value::Null => Ok(None),
            v => Ok(Some(T::from_sqlite_value(v)?)),
        }
    }
}

/// The serde codec: any `Serialize + Deserialize` type as a `TEXT` column SQLite's own
/// `json_*` functions can reach. `#[model(json)]` is sugar for `#[model(with = Json)]`.
pub struct Json;

impl<T> ValueCodec<T> for Json
where
    T: serde::Serialize + serde::de::DeserializeOwned + 'static,
{
    const SQL_TYPE: SqlType = SqlType::Text;
    fn to_sqlite_value(v: &T) -> Value {
        match serde_json::to_string(v) {
            Ok(s) => Value::Text(s),
            // Serialization of an in-memory value failing is a bug in the type's serde impl;
            // surface it as a NULL rather than a panic, and the decode side will report it.
            Err(_) => Value::Null,
        }
    }
    fn from_sqlite_value(v: Value) -> Result<T, DbError> {
        serde_json::from_str(v.as_text()?)
            .map_err(|e| DbError::new(DbErrorKind::Decode, format!("json: {e}")))
    }
}

// ---------------------------------------------------------------------------
// The Model trait: what #[derive(Model)] implements
// ---------------------------------------------------------------------------

/// One column of a model's table, as the derive declares it. `field` is the struct field the
/// column stores: the change log speaks field names, the SQL speaks column names, and this is
/// where the two meet (they differ only under `#[model(column = "…")]`).
#[derive(Clone, Copy, Debug)]
pub struct ColumnDef {
    pub name: &'static str,
    pub field: &'static str,
    pub sql: SqlType,
    pub not_null: bool,
    pub unique: bool,
    pub indexed: bool,
    /// A [`Blob`] column: never read by a row fault, written only when it carries pending
    /// bytes, served on demand through the field's accessor.
    pub lazy: bool,
}

/// The column pair a `#[model(spatial(lat = …, lon = …))]` declaration names.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct SpatialCols {
    pub lat: &'static str,
    pub lon: &'static str,
}

/// One `#[model(link(…))]` as the derive emits it: `owner.local = target.remote` is the join.
#[derive(Clone, Copy, Debug)]
pub struct LinkDef {
    /// The marker field the link was declared on: the name `Owner::field()` answers to.
    pub field: &'static str,
    /// The owner's column holding the value.
    pub local: &'static str,
    /// The target's (qualified) table.
    pub target_table: &'static str,
    /// The target's column the value names.
    pub remote: &'static str,
}

/// The marker a `#[model(link(…))]` field carries. It has neither a column nor state; the
/// type is what names the far model for the derive.
pub struct Linked<M: ?Sized> {
    _m: std::marker::PhantomData<fn() -> M>,
}

impl<M: ?Sized> Clone for Linked<M> {
    fn clone(&self) -> Self {
        *self
    }
}
impl<M: ?Sized> Copy for Linked<M> {}
impl<M: ?Sized> Default for Linked<M> {
    fn default() -> Self {
        Linked {
            _m: std::marker::PhantomData,
        }
    }
}
impl<M: ?Sized> PartialEq for Linked<M> {
    fn eq(&self, _: &Self) -> bool {
        true
    }
}
impl<M: ?Sized> std::fmt::Debug for Linked<M> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("Linked")
    }
}

/// A wired link, as the SQL compiler and the query watcher see it.
#[derive(Clone, Copy, Debug)]
pub(crate) struct LinkInfo {
    pub(crate) owner_table: &'static str,
    pub(crate) field: &'static str,
    pub(crate) local: &'static str,
    pub(crate) target_table: &'static str,
    pub(crate) remote: &'static str,
}

/// A persistable model: an [`Identified`] observable struct with a schema half. Implemented by
/// `#[derive(Model)]`; the container consumes it.
pub trait Model: Identified + day_model::ApplyField + Clone + 'static {
    const TABLE: &'static str;
    /// The key column's name (the `#[model(id)]` field). Also the first entry of `COLUMNS`.
    const KEY: &'static str;
    const COLUMNS: &'static [ColumnDef];
    /// Composite indexes from struct-level `#[model(index("a", "b"))]`.
    const COMPOSITE_INDEXES: &'static [&'static [&'static str]] = &[];
    /// `#[model(unique("a", "b"))]` on the struct: multi-column UNIQUE constraints, kept as
    /// unique indexes (`day_uidx_{table}_{a}_{b}`), part of the fingerprint and of the
    /// lightweight migration.
    const UNIQUE_INDEXES: &'static [&'static [&'static str]] = &[];
    /// Full-text-indexed columns from struct-level `#[model(fts("a", "b"))]`: an
    /// external-content FTS5 shadow table plus sync triggers, generated at open.
    const FTS_COLUMNS: &'static [&'static str] = &[];
    /// The FTS5 tokenizer, from `#[model(fts(…, tokenize = "…"))]`, e.g.
    /// `"unicode61 remove_diacritics 2"` for diacritics-insensitive search. `None` keeps
    /// FTS5's default. Part of the schema fingerprint, so changing it rebuilds the shadow.
    const FTS_TOKENIZE: Option<&'static str> = None;
    /// The R*Tree pair from struct-level `#[model(spatial(lat = "…", lon = "…"))]`.
    const SPATIAL: Option<SpatialCols> = None;
    /// The key column's SQL shape: what a `One<Self>` foreign-key column stores.
    const KEY_SQL: SqlType = SqlType::Integer;
    /// Relations declared on this model's `Many` fields (`#[model(relation(…))]`).
    const RELATIONS: &'static [RelationDef] = &[];
    /// Relations by value (`#[model(link(…))]`): rows of another model whose `remote` column
    /// equals this row's `local` column, with no foreign key: the shape that reaches across an
    /// attached database (see [`ModelContainer::attach_database`]).
    const LINKS: &'static [LinkDef] = &[];
    /// The fields declared as [`Blob`]: the columns a fault names as `NULL` and the fold
    /// writes only when they carry pending bytes.
    const LAZY_FIELDS: &'static [&'static str] = &[];
    /// After a flush wrote this row: hand over every lazy field's pending bytes and mark
    /// them stored. The derive generates it for models with [`Blob`] fields.
    fn settle_lazy(&mut self) -> Vec<(&'static str, std::sync::Arc<Vec<u8>>)> {
        Vec::new()
    }
    /// Declared `external = "alias"`: the table belongs to a database attached under that alias
    /// and managed elsewhere. The container creates, migrates, and fingerprints nothing for
    /// it, and treats it as read-only.
    const EXTERNAL: bool = false;
    /// The alias an `EXTERNAL` table's database is attached under, the part `TABLE` is
    /// qualified with (`catalog` in `catalog.stations`). Kept apart so SQL can quote each
    /// half; `None` for a table in the container's own file.
    const SCHEMA: Option<&'static str> = None;
    /// One [`Value`] per column, in `COLUMNS` order.
    fn to_row(&self) -> Vec<Value>;
    fn from_row(row: &dyn Row) -> Result<Self, DbError>;
    /// Each column's Rust-default value: what an added column backfills with.
    fn default_row() -> Vec<Value>;
    /// Wire this model's declared relations. Generated; the default declares none.
    fn wire(reg: &mut Registrar<'_>) {
        let _ = reg;
    }
}

/// `name` as a SQL identifier: double-quoted, an embedded `"` doubled. Quoted, any name
/// reaches the engine as itself: a keyword (`order`, `group`), a space, a quote, an emoji.
/// Every statement the container writes names its tables and columns this way, and raw SQL
/// written against them should too.
pub fn ident(name: &str) -> String {
    let mut out = String::with_capacity(name.len() + 2);
    out.push('"');
    for ch in name.chars() {
        if ch == '"' {
            out.push('"');
        }
        out.push(ch);
    }
    out.push('"');
    out
}

/// A table's name in the two halves SQL quotes separately: the attached database's alias,
/// if any, and the table's own name. [`Model::TABLE`] (`notes`, `catalog.stations`) stays the
/// plain key every lookup, fingerprint and `_day_schema` row uses; this is what a statement
/// gets.
#[derive(Clone, Copy)]
pub(crate) struct TableName {
    pub(crate) schema: Option<&'static str>,
    pub(crate) bare: &'static str,
}

impl TableName {
    pub(crate) fn of<M: Model>() -> Self {
        let bare = match M::SCHEMA {
            Some(schema) => M::TABLE
                .strip_prefix(schema)
                .and_then(|rest| rest.strip_prefix('.'))
                .unwrap_or(M::TABLE),
            None => M::TABLE,
        };
        TableName {
            schema: M::SCHEMA,
            bare,
        }
    }

    /// A table in the container's own file, named directly (a join table).
    pub(crate) fn plain(bare: &'static str) -> Self {
        TableName { schema: None, bare }
    }

    /// The quoted SQL that names the table in a statement: `"notes"`, `"catalog"."stations"`.
    pub(crate) fn sql(&self) -> String {
        table_sql(self.schema, self.bare)
    }

    /// The quoted SQL naming a shadow beside the table (`_fts`, `_geo`), in the same schema.
    pub(crate) fn shadow(&self, suffix: &str) -> String {
        table_sql(self.schema, &format!("{}{suffix}", self.bare))
    }
}

pub(crate) fn table_sql(schema: Option<&str>, bare: &str) -> String {
    match schema {
        Some(schema) => format!("{}.{}", ident(schema), ident(bare)),
        None => ident(bare),
    }
}

/// The declared schema's fingerprint: table, columns, types, flags, indexes. Equal fingerprints
/// open instantly; a difference migrates or refuses, never silently.
pub fn model_fingerprint<M: Model>() -> u64 {
    let mut h: u64 = 0xcbf2_9ce4_8422_2325;
    let mut eat = |bytes: &[u8]| {
        for b in bytes {
            h ^= *b as u64;
            h = h.wrapping_mul(0x1000_0000_01b3);
        }
    };
    // The DDL generation this fingerprint vouches for. Bumped when what the file must look
    // like changes (constrained column additions, unique indexes), so a fingerprint an older
    // build recorded no longer matches and the file gets one comparison pass, which rebuilds
    // what the older path left unconstrained and records the new fingerprint.
    eat(b"ddl-v2|");
    eat(M::TABLE.as_bytes());
    eat(M::KEY.as_bytes());
    for c in M::COLUMNS {
        eat(c.name.as_bytes());
        eat(c.sql.ddl().as_bytes());
        eat(&[c.not_null as u8, c.unique as u8, c.indexed as u8]);
    }
    for idx in M::COMPOSITE_INDEXES {
        for c in *idx {
            eat(c.as_bytes());
        }
        eat(b"|");
    }
    for idx in M::UNIQUE_INDEXES {
        eat(b"uniq:");
        for c in *idx {
            eat(c.as_bytes());
        }
        eat(b"|");
    }
    for c in M::FTS_COLUMNS {
        eat(b"fts:");
        eat(c.as_bytes());
    }
    if !M::FTS_COLUMNS.is_empty()
        && M::COLUMNS
            .iter()
            .any(|c| c.name == M::KEY && c.sql != SqlType::Integer)
    {
        eat(b"wide-fts-key-map-v1");
    }
    if let Some(t) = M::FTS_TOKENIZE {
        eat(b"tok:");
        eat(t.as_bytes());
    }
    if let Some(s) = M::SPATIAL {
        eat(b"geo:");
        eat(s.lat.as_bytes());
        eat(s.lon.as_bytes());
    }
    h
}

// ---------------------------------------------------------------------------
// Schema sets and migrations
// ---------------------------------------------------------------------------

/// The set of models a container manages; build with [`schema!`].
#[derive(Default)]
pub struct Schema {
    installers: Vec<Installer>,
    /// Run after every table is attached, because relation wiring needs both ends present.
    wirers: Vec<Installer>,
    /// Foreign-key clauses each declared relation contributes to its target's table.
    fk_specs: Vec<FkSpec>,
}

type Installer = Box<dyn FnOnce(&ModelContainer) -> Result<(), DbError>>;
/// Decode raw rows into the cache silently, answering their handles.
type SettleFn = Rc<dyn Fn(&[u64]) -> Vec<(u64, &'static str, std::sync::Arc<Vec<u8>>)>>;
type AbsorbFn = Rc<dyn Fn(Vec<Vec<Value>>) -> Result<Vec<u64>, DbError>>;
/// Diff raw rows (selected by the resident keys) against the cache: per-field announcements
/// authored [`ModelContainer::EXTERNAL_AUTHOR`], resident rows missing from the input deleted
/// the same way. Returns whether anything differed.
type RefreshFn = Rc<dyn Fn(Vec<Vec<Value>>) -> Result<bool, DbError>>;
/// A `WHERE` clause plus its parameters, addressing one row by handle.
type KeyWhere = Rc<dyn Fn(u64) -> (String, Vec<Value>)>;
/// A `WHERE` clause plus its parameters, addressing a set of rows by handle.
type KeysWhere = Rc<dyn Fn(&[u64]) -> (String, Vec<Value>)>;
/// Evict up to N clean rows from an ordered candidate list, answering how many left.
type EvictFn = Rc<dyn Fn(&[u64], usize) -> usize>;

/// One foreign-key clause, resolved from a `RelationDef` at `Schema::with` time: the child's
/// column carries `REFERENCES parent(key) ON DELETE …` in its generated DDL.
#[derive(Clone, Debug)]
struct FkSpec {
    child_table: &'static str,
    child_field: &'static str,
    parent_table: &'static str,
    /// `parent_table` as the `REFERENCES` clause names it.
    parent_sql: String,
    /// `parent_table` as `PRAGMA foreign_key_list` reports it: the bare, unquoted name.
    parent_bare: &'static str,
    parent_key: &'static str,
    rule: DeleteRule,
}

impl Schema {
    pub fn new() -> Self {
        Self::default()
    }
    pub fn with<M: Model>(mut self) -> Self {
        for def in M::RELATIONS {
            if def.join.is_none() {
                self.fk_specs.push(FkSpec {
                    child_table: def.target_table,
                    child_field: def.inverse,
                    parent_table: M::TABLE,
                    parent_sql: TableName::of::<M>().sql(),
                    parent_bare: TableName::of::<M>().bare,
                    parent_key: M::KEY,
                    rule: def.delete,
                });
            }
        }
        self.installers.push(Box::new(|c| c.attach::<M>()));
        self.wirers.push(Box::new(|c| {
            let mut reg = Registrar {
                container: c,
                error: None,
            };
            M::wire(&mut reg);
            match reg.error {
                Some(e) => Err(e),
                None => Ok(()),
            }
        }));
        self
    }
}

/// `schema![Trip, Lodging]`: the models a container manages.
#[macro_export]
macro_rules! schema {
    ($($m:ty),+ $(,)?) => {{
        let s = $crate::Schema::new();
        $(let s = s.with::<$m>();)+
        s
    }};
}

/// Staged migrations: anything with intent behind it (a rename, a split) gets a stage the app
/// writes; each stage runs in its own transaction against the raw connection, and versions only
/// go up. Lightweight migration (added/dropped columns and indexes) runs afterward, inferred
/// from the schema fingerprint.
#[derive(Default)]
pub struct MigrationPlan {
    stages: Vec<Stage>,
}

type StageFn = Box<dyn FnOnce(&mut dyn SqliteConnection) -> Result<(), DbError>>;

struct Stage {
    from: u32,
    to: u32,
    run: StageFn,
}

impl MigrationPlan {
    pub fn new() -> Self {
        Self::default()
    }
    /// A hand-written stage taking the database from `from` to `to`. Stages run in ascending
    /// order from the file's current version; a gap is an error at open.
    pub fn custom(
        mut self,
        from: u32,
        to: u32,
        f: impl FnOnce(&mut dyn SqliteConnection) -> Result<(), DbError> + 'static,
    ) -> Self {
        self.stages.push(Stage {
            from,
            to,
            run: Box::new(f),
        });
        self
    }
    fn target_version(&self) -> u32 {
        self.stages.iter().map(|s| s.to).max().unwrap_or(0)
    }
}

// ---------------------------------------------------------------------------
// Dirty tracking: the fold, applied live
// ---------------------------------------------------------------------------

/// What one row needs at the next flush. The merge rules are the change-log fold: same-row
/// changes coalesce, an INSERT absorbs later field writes, a DELETE absorbs everything.
#[derive(Clone, Debug, PartialEq)]
pub(crate) enum DirtyRow {
    Insert,
    Update(Vec<&'static str>),
    Delete,
}

#[derive(Clone, Default)]
struct DirtyState {
    /// (store, key) → pending statement kind, in first-touch order.
    rows: HashMap<(u64, u64), DirtyRow>,
    order: Vec<(u64, u64)>,
    /// store → its dirty keys, so a relation's mid-turn overlay reads one store's rows
    /// instead of scanning every store's.
    by_store: HashMap<u64, Vec<u64>>,
    /// Stores whose whole value was rewritten (a wholesale `Store::update`), flushed by
    /// upserting every resident row. With a lazy cache no "delete the rest" is possible (the
    /// rest was never loaded), so wholesale rewrites are a resync of the working set only.
    full: Vec<u64>,
    /// (store, key) → the distinct author tags of the changes folded into that row, in
    /// first-seen order; the unauthored user edit (`None`) leaves no tag.
    authors: HashMap<(u64, u64), Vec<&'static str>>,
    /// store → the author tags of its wholesale rewrites.
    store_authors: HashMap<u64, Vec<&'static str>>,
}

/// Record one author tag once, in first-seen order; `None` (the user) is not a tag.
fn add_author(tags: &mut Vec<&'static str>, author: Option<&'static str>) {
    if let Some(author) = author
        && !tags.contains(&author)
    {
        tags.push(author);
    }
}

impl DirtyState {
    fn merge(&mut self, newer: Self) {
        for store in newer.full {
            if !self.full.contains(&store) {
                self.full.push(store);
            }
        }
        for (store, tags) in newer.store_authors {
            let mine = self.store_authors.entry(store).or_default();
            for tag in tags {
                add_author(mine, Some(tag));
            }
        }
        for (id, tags) in newer.authors {
            let mine = self.authors.entry(id).or_default();
            for tag in tags {
                add_author(mine, Some(tag));
            }
        }
        for id in newer.order {
            let next = newer.rows[&id].clone();
            if !self.rows.contains_key(&id) {
                self.order.push(id);
                self.by_store.entry(id.0).or_default().push(id.1);
            }
            match (self.rows.get_mut(&id), next) {
                (Some(DirtyRow::Update(old)), DirtyRow::Update(cols)) => {
                    for col in cols {
                        if !old.contains(&col) {
                            old.push(col);
                        }
                    }
                }
                (Some(DirtyRow::Insert | DirtyRow::Delete), DirtyRow::Update(_)) => {}
                (_, next) => {
                    self.rows.insert(id, next);
                }
            }
        }
    }

    fn is_empty(&self) -> bool {
        self.rows.is_empty() && self.full.is_empty()
    }

    fn note(&mut self, change: &day_model::Change, known_store: impl Fn(u64) -> bool) {
        let Some(&store) = change.components.first() else {
            return;
        };
        if !known_store(store) {
            return;
        }
        let Some(&key) = change.components.get(1) else {
            // A store-level change: the whole value may have been replaced.
            if !self.full.contains(&store) {
                self.full.push(store);
            }
            add_author(self.store_authors.entry(store).or_default(), change.author);
            return;
        };
        if key == day_model::STRUCTURE {
            return; // the shape path is for the UI; the row paths carry the work
        }
        let id = (store, key);
        if !self.rows.contains_key(&id) {
            self.order.push(id);
            self.by_store.entry(store).or_default().push(key);
        }
        add_author(self.authors.entry(id).or_default(), change.author);
        let slot = self.rows.entry(id).or_insert(DirtyRow::Update(Vec::new()));
        match (change.op, &mut *slot) {
            (Op::Delete, _) => *slot = DirtyRow::Delete,
            (Op::Insert, _) => *slot = DirtyRow::Insert,
            (Op::Set, DirtyRow::Insert) | (Op::Set, DirtyRow::Delete) => {}
            (Op::Set, DirtyRow::Update(columns)) => {
                if change.components.len() >= 3 && !columns.contains(&change.label) {
                    columns.push(change.label);
                }
            }
            (Op::Move, _) => {}
        }
    }
}

// ---------------------------------------------------------------------------
// The container
// ---------------------------------------------------------------------------

/// Everything the container knows how to do for one attached model type, monomorphized at
/// [`Schema::with`] and stored type-erased. Join tables (relations.rs) hand-build one over
/// their pair-keyed membership cache, which is why keys are plural and clause-shaped here.
pub(crate) struct TableHooks {
    pub(crate) table: &'static str,
    /// `table` split for SQL: the statements below name it through `name.sql()`.
    pub(crate) name: TableName,
    /// The key column(s), in order: the key SELECT list, the upsert's conflict target, and
    /// what its DO UPDATE leaves alone. One entry everywhere but join tables. Plain names,
    /// like `columns`; [`ident`] quotes them where a statement is written.
    pub(crate) key_cols: Vec<String>,
    /// `WHERE` clause + params addressing one row by its key handle.
    pub(crate) key_where: KeyWhere,
    pub(crate) columns: Vec<String>,
    /// `columns` again, as the model's static names: what a [`RowChange`] reports.
    pub(crate) column_names: Vec<&'static str>,
    /// Same order as `columns`; what a change's label matches against.
    pub(crate) fields: Vec<String>,
    /// Per column, whether it is a [`Blob`]: named as `NULL` in a row select, protected by
    /// `COALESCE` in the upsert, skipped by an update that carries no bytes for it.
    pub(crate) lazy: Vec<bool>,
    /// After a flush wrote these rows: settle their lazy fields to stored and return the
    /// pending bytes they carried, for the blob memo.
    pub(crate) settle: SettleFn,
    /// The FTS5 shadow's table name, when the model declares `fts(…)`.
    pub(crate) fts: Option<String>,
    pub(crate) fts_key: &'static str,
    /// The R*Tree shadow: (lat column, lon column, shadow table name).
    pub(crate) spatial: Option<(String, String, String)>,
    /// Current row values by key, read from the cache at flush time; the change log carries
    /// which rows and columns moved, never their contents.
    pub(crate) row_for: Rc<dyn Fn(u64) -> Option<Vec<Value>>>,
    /// Every (key, row) currently resident, for wholesale resyncs.
    pub(crate) all_rows: Rc<dyn Fn() -> Vec<(u64, Vec<Value>)>>,
    /// The resident keys, in cache (≈ fault) order: what eviction walks.
    pub(crate) resident_keys: Rc<dyn Fn() -> Vec<u64>>,
    /// The resident count, O(1): the fault path's eviction gate.
    pub(crate) resident_len: Rc<dyn Fn() -> usize>,
    pub(crate) is_resident: Rc<dyn Fn(u64) -> bool>,
    /// Decode raw rows into the cache silently (a fault landing).
    pub(crate) absorb: AbsorbFn,
    /// Diff raw rows against the resident set, announcing as the external author.
    pub(crate) refresh: RefreshFn,
    /// Silently drop up to `want` clean rows from the cache, taking candidates in order and
    /// skipping anything observed; answers how many left. One retain over the store, so an
    /// eviction pass costs O(cache), not O(cache × evicted). (Dirtiness is the container's
    /// knowledge, checked before this is called.)
    pub(crate) evict: EvictFn,
    #[cfg(not(target_arch = "wasm32"))]
    pub(crate) dispose_cache: Rc<dyn Fn()>,
    /// Bring this store under an undo history; captured here because the model type is known
    /// only at attach time.
    pub(crate) watch_undo: Rc<dyn Fn(&day_model::UndoStack)>,
}

/// Why a durable transaction is being performed. Cache refreshes use EXTERNAL_AUTHOR and
/// do not constitute a write transaction. Remote imports persist but must not echo outbound.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum WriteOrigin {
    #[default]
    Local,
    RemoteImport,
    Maintenance,
}

/// One row of a transaction's folded change set, as [`TransactionParticipant::before_commit`]
/// receives it: every row the ORM's pipeline wrote in the transaction (model edits, relation
/// upkeep, in-process cascades), one entry per (table, key). Rows the engine's own `ON
/// DELETE` clause removed without the process faulting them are not in the set.
#[derive(Clone, Debug, PartialEq)]
pub struct RowChange {
    /// The model's table, as [`Model::TABLE`] names it (a join table by its generated name).
    pub table: &'static str,
    /// The key as stored: one value, or the (parent, child) pair of a join row.
    pub key: Vec<Value>,
    pub kind: RowChangeKind,
    /// The distinct author tags ([`day_model::with_author`]) of the changes folded into
    /// the row, first seen first. The user's own edits carry no tag; the container's
    /// external-merge author never reaches the set.
    pub authors: Vec<&'static str>,
}

/// What happened to a [`RowChange`]'s row over the transaction. Same-row changes coalesce
/// the way the autosave fold does: an insert absorbs later updates, a delete absorbs
/// everything before it, updates union their columns, and a wholesale write supersedes a
/// column list.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum RowChangeKind {
    Inserted,
    /// The changed columns' names, in first-touch order; transient fields never appear.
    Updated(Vec<&'static str>),
    /// The key only; the removed row's values are not retained.
    Deleted,
    /// Every column was written: a row-level replacement, or a row of a store rewritten
    /// wholesale (`Store::update`), which resyncs the resident rows.
    Rewritten,
}

impl RowChange {
    /// Fold a later change to the same row into this one, by the autosave fold's rules.
    fn absorb(&mut self, later: RowChange) {
        for author in later.authors {
            add_author(&mut self.authors, Some(author));
        }
        self.kind = match (
            std::mem::replace(&mut self.kind, RowChangeKind::Deleted),
            later.kind,
        ) {
            (RowChangeKind::Updated(mut cols), RowChangeKind::Updated(more)) => {
                for col in more {
                    if !cols.contains(&col) {
                        cols.push(col);
                    }
                }
                RowChangeKind::Updated(cols)
            }
            (RowChangeKind::Updated(_), RowChangeKind::Rewritten)
            | (RowChangeKind::Rewritten, RowChangeKind::Updated(_) | RowChangeKind::Rewritten) => {
                RowChangeKind::Rewritten
            }
            (
                kept @ (RowChangeKind::Inserted | RowChangeKind::Deleted),
                RowChangeKind::Updated(_) | RowChangeKind::Rewritten,
            ) => kept,
            (_, next @ (RowChangeKind::Inserted | RowChangeKind::Deleted)) => next,
        };
    }
}

/// The cache refresh a participant asks for after its own SQL may have changed model rows
/// that were already flushed from the caches.
#[derive(Clone, Debug, PartialEq, Eq, Default)]
pub enum Refresh {
    /// The participant wrote nothing the caches hold.
    #[default]
    None,
    /// Re-read and diff the resident rows of these tables only, drop the relation memos
    /// that involve them, and re-run the live queries that read them.
    Tables(Vec<&'static str>),
    /// Every resident row, every relation memo, every live query.
    All,
}

/// Queue-confined extension participating in the SAME SQL transaction as model changes.
/// Callbacks must use only the supplied connection, never re-enter the container, commit,
/// roll back, perform network I/O, or mutate reactive models. Returning an error aborts the
/// transaction. `before_commit` runs after worker reactions and intermediate saves settle.
/// Persist extension state transactionally; callbacks may run again following a rollback.
pub trait TransactionParticipant: 'static {
    fn begin(
        &self,
        connection: &mut dyn SqliteConnection,
        origin: WriteOrigin,
    ) -> Result<(), DbError>;
    /// The transaction's folded change set is `changes`: accumulated across every flush in
    /// the transaction (a worker job's intermediate saves included), empty again after a
    /// rollback. The answer names the cache refresh to run after a successful COMMIT, before
    /// the work is acknowledged; a refresh failure surfaces as
    /// [`DbErrorKind::CommittedRefreshFailed`] (the data is durable, it cannot roll back).
    fn before_commit(
        &self,
        connection: &mut dyn SqliteConnection,
        origin: WriteOrigin,
        changes: &[RowChange],
    ) -> Result<Refresh, DbError>;
}

pub(crate) struct ContainerInner {
    conn: RefCell<Box<dyn SqliteConnection>>,
    caps: Capabilities,
    /// store root id → hooks.
    tables: RefCell<HashMap<u64, TableHooks>>,
    /// model TypeId → the `Store<Keyed<M>>` handle, boxed.
    stores: RefCell<HashMap<TypeId, Box<dyn Any>>>,
    dirty: RefCell<DirtyState>,
    /// Live query result sets, marked stale from the change sink. Weak: the app's `Query`
    /// handles own the state; dead entries are pruned on dispatch.
    queries: RefCell<Vec<std::rc::Weak<QueryState>>>,
    /// The engine's cross-connection change counter as of the last look (`PRAGMA
    /// data_version`; it moves only when another connection commits to the file). `None`
    /// where the driver reports no external-change detection.
    data_version: Cell<Option<i64>>,
    /// Foreign-key clauses relations contribute to their targets' tables, set before attach.
    fk_specs: RefCell<Vec<FkSpec>>,
    /// The wired relations, maintained from the change sink and read by `RelationRef`s.
    pub(crate) relations: RefCell<Vec<Rc<relations::ToOneRel>>>,
    /// The wired many-to-manys, each over its own membership cache.
    pub(crate) joins: RefCell<Vec<Rc<relations::JoinRel>>>,
    /// The declared value links (`#[model(link(…))]`), from every attached model.
    pub(crate) links: RefCell<Vec<LinkInfo>>,
    /// The databases `attach_database` holds open, by alias.
    attached: RefCell<Vec<String>>,
    sink: Cell<Option<day_model::ChangeSinkId>>,
    autosave: Cell<bool>,
    /// An outer worker transaction owns commit/rollback; inner model saves only execute SQL.
    worker_transaction: Cell<bool>,
    participant: RefCell<Option<Rc<dyn TransactionParticipant>>>,
    /// The open transaction's folded change set, kept only while a participant is installed:
    /// appended per flush, handed to `before_commit`, cleared at begin, commit and rollback.
    transaction_changes: RefCell<Vec<RowChange>>,
    /// What `before_commit` asked for, acted on once the COMMIT has succeeded.
    refresh_scope: RefCell<Refresh>,
    refresh_pending: Cell<bool>,
    /// Soft per-table bound on resident rows. Dirty and observed rows never evict, so the
    /// working set can exceed it; everything else does not.
    cache_limit: Cell<usize>,
    /// Retry eviction after growth when dirty/observed rows prevent reaching the limit.
    eviction_retry: RefCell<HashMap<u64, usize>>,
    /// Bytes of lazy blob columns read or written recently, bounded by `blob_cache_limit`.
    blob_memo: RefCell<blob::BlobMemo>,
    blob_cache_limit: Cell<usize>,
    /// Child tables whose rows the engine's `ON DELETE` clauses are taking or nullifying in
    /// the flush under way, with no undo stack to serve: their resident rows are re-read
    /// after the commit (relations.rs, `parent_deleted`).
    engine_cascades: RefCell<Vec<&'static str>>,
    /// Set while `reconcile_engine_cascades` re-reads the child tables. Every row it finds
    /// gone or re-pointed got that way because its parent was deleted, so relation upkeep
    /// skips the point lookups that would ask the file for a parent that no longer exists.
    pub(crate) reconciling: Cell<bool>,
    /// The last autosave failure, observable by the UI (`when(container.last_error()…)`).
    pub(crate) error: day_reactive::Signal<Option<String>>,
    /// Guards re-entrant flushes (a turn-end firing during an explicit save).
    flushing: Cell<bool>,
}

/// An open database and the working-set caches over it. Clone is shallow: clones share the
/// connection and the dirty state.
#[derive(Clone)]
pub struct ModelContainer {
    pub(crate) inner: Rc<ContainerInner>,
}

/// The default per-table bound on resident rows ([`ModelContainer::set_cache_limit`]).
pub const DEFAULT_CACHE_LIMIT: usize = 8_192;

/// How many bytes of lazy [`Blob`] values a container keeps in memory by default (32 MiB):
/// the memo behind [`BlobField::bytes`], bounded in bytes rather than rows.
pub const DEFAULT_BLOB_CACHE_LIMIT: usize = 32 * 1024 * 1024;

impl ModelContainer {
    /// Open through `driver`, migrate, and attach every model in `schema`. Attaching creates
    /// or migrates the table and nothing more: no rows load, so open cost does not grow with
    /// the file. Autosave is on: any turn that touched a store flushes at its end.
    pub fn open<D: SqliteDriver>(driver: D, schema: Schema) -> Result<ModelContainer, DbError>
    where
        D::Connection: 'static,
    {
        Self::open_with(driver, schema, MigrationPlan::new())
    }

    /// [`ModelContainer::open`], with hand-written migration stages that run first.
    pub fn open_with<D: SqliteDriver>(
        driver: D,
        schema: Schema,
        plan: MigrationPlan,
    ) -> Result<ModelContainer, DbError>
    where
        D::Connection: 'static,
    {
        let caps = driver.capabilities();
        let conn: Box<dyn SqliteConnection> = Box::new(driver.open()?);
        let error = day_reactive::Scope::detached().enter(|| day_reactive::Signal::new(None));
        let container = ModelContainer {
            inner: Rc::new(ContainerInner {
                conn: RefCell::new(conn),
                caps,
                tables: RefCell::new(HashMap::new()),
                stores: RefCell::new(HashMap::new()),
                dirty: RefCell::new(DirtyState::default()),
                queries: RefCell::new(Vec::new()),
                data_version: Cell::new(None),
                fk_specs: RefCell::new(Vec::new()),
                relations: RefCell::new(Vec::new()),
                joins: RefCell::new(Vec::new()),
                links: RefCell::new(Vec::new()),
                attached: RefCell::new(Vec::new()),
                sink: Cell::new(None),
                autosave: Cell::new(true),
                worker_transaction: Cell::new(false),
                refresh_pending: Cell::new(false),
                participant: RefCell::new(None),
                transaction_changes: RefCell::new(Vec::new()),
                refresh_scope: RefCell::new(Refresh::None),
                cache_limit: Cell::new(DEFAULT_CACHE_LIMIT),
                eviction_retry: RefCell::new(HashMap::new()),
                blob_memo: RefCell::new(blob::BlobMemo::default()),
                blob_cache_limit: Cell::new(DEFAULT_BLOB_CACHE_LIMIT),
                engine_cascades: RefCell::new(Vec::new()),
                reconciling: Cell::new(false),
                error,
                flushing: Cell::new(false),
            }),
        };

        container.ensure_schema_table()?;
        container.run_stages(plan)?;
        let Schema {
            installers,
            wirers,
            fk_specs,
        } = schema;
        *container.inner.fk_specs.borrow_mut() = fk_specs;
        for install in installers {
            install(&container)?;
        }
        // Relations wire once every table is attached (both ends exist), and only then does
        // the sink go live.
        for wire in wirers {
            wire(&container)?;
        }
        relations::register_container(&container.inner);
        container.install_sink();
        container.install_autosave();
        if caps.external_changes {
            container
                .inner
                .data_version
                .set(container.file_data_version()?);
        }
        Ok(container)
    }

    /// The author tag on changes [`ModelContainer::check_external`] merges in: the database's
    /// own contents arriving, distinguishable by every change consumer and never persisted
    /// back. Reserved: an app writing stores under this tag would have its writes dropped by
    /// the autosave fold.
    pub const EXTERNAL_AUTHOR: &'static str = "database";

    /// The working-set cache for `M`, an ordinary day-model store holding the rows currently
    /// resident and not the table: its `keys()` are whatever happens to be faulted in. Bindings
    /// and accessors work on it unchanged; enumerate rows through a [`ModelContainer::query`],
    /// never through the cache. Panics only if `M` was not in the container's `schema!`,
    /// which is a wiring bug worth stopping on.
    pub fn cache<M: Model>(&self) -> Store<Keyed<M>> {
        let stores = self.inner.stores.borrow();
        let any = stores
            .get(&TypeId::of::<M>())
            .unwrap_or_else(|| panic!("model `{}` is not in this container's schema!", M::TABLE));
        *any.downcast_ref::<Store<Keyed<M>>>()
            .expect("store map holds the exact type it was keyed by")
    }

    /// What the driver can and cannot do.
    pub fn capabilities(&self) -> Capabilities {
        self.inner.caps
    }

    /// Autosave on/off (default on). Off, changes accumulate until [`ModelContainer::save`],
    /// and live queries answer from the last save, since only the file can answer them.
    pub fn set_autosave(&self, on: bool) {
        self.inner.autosave.set(on);
    }

    /// The soft per-table bound on resident rows (default [`DEFAULT_CACHE_LIMIT`]). Dirty
    /// rows and rows something observes never evict; beyond that, faulting past the limit
    /// releases the oldest resident rows. `usize::MAX` disables eviction. Lowering the limit
    /// enforces it immediately.
    pub fn set_cache_limit(&self, rows: usize) {
        self.inner.cache_limit.set(rows.max(1));
        let store_ids: Vec<u64> = self.inner.tables.borrow().keys().copied().collect();
        for id in store_ids {
            self.enforce_cache_limit(id, &[], true);
        }
    }

    // --- lazy blobs (blob.rs) ------------------------------------------------------------

    /// Bound, in bytes, on the lazy [`Blob`] values kept in memory after a read or a flush
    /// (default [`DEFAULT_BLOB_CACHE_LIMIT`]). Lowering it releases the oldest entries now;
    /// a value larger than the limit is served but never kept.
    pub fn set_blob_cache_limit(&self, bytes: usize) {
        self.inner.blob_cache_limit.set(bytes);
        let mut memo = self.inner.blob_memo.borrow_mut();
        if bytes == 0 {
            memo.clear();
        } else {
            // Re-inserting nothing: the memo trims itself on the next insert, so trim here by
            // inserting an empty value under a key no row has, then forgetting it.
            memo.insert(
                (u64::MAX, u64::MAX, ""),
                std::sync::Arc::new(Vec::new()),
                bytes,
            );
            memo.forget_row(u64::MAX, u64::MAX);
        }
    }

    /// Bytes the blob memo currently holds.
    pub fn blob_cache_bytes(&self) -> usize {
        self.inner.blob_memo.borrow().bytes()
    }

    /// Values the blob memo currently holds.
    pub fn blob_cache_len(&self) -> usize {
        self.inner.blob_memo.borrow().len()
    }

    /// Whether a delete may leave its rule to the engine's `ON DELETE` clause: no undo stack
    /// is capturing (it needs the removed rows to restore them) and no transaction
    /// participant is installed (its change set would miss the rows the engine removed).
    pub(crate) fn engine_cascade_allowed(&self) -> bool {
        !day_model::record_capture_active() && self.inner.participant.borrow().is_none()
    }

    /// A relation whose parent row is being deleted this turn, with no undo stack to serve:
    /// the engine's `ON DELETE` clause will take or nullify the children in the flush, and
    /// the resident ones are re-read afterwards.
    pub(crate) fn note_engine_cascade(&self, child_table: &'static str) {
        let mut tables = self.inner.engine_cascades.borrow_mut();
        if !tables.contains(&child_table) {
            tables.push(child_table);
        }
    }

    /// After a flush whose parent deletes the engine cascaded: re-read the resident rows of
    /// the child tables (vanished rows announce as deletes, nullified keys as field changes,
    /// both under the database's own author), drop their relation memos and re-run the live
    /// queries that read them. A vanished child is itself a parent whose children the engine
    /// took too, so the pass repeats while the announcements name new tables.
    fn reconcile_engine_cascades(&self) {
        for _ in 0..16 {
            let tables: Vec<&'static str> =
                std::mem::take(&mut *self.inner.engine_cascades.borrow_mut());
            if tables.is_empty() {
                return;
            }
            self.inner.reconciling.set(true);
            let refreshed = self.refresh_resident_in(Some(&tables));
            self.inner.reconciling.set(false);
            if let Err(error) = refreshed {
                self.inner.error.set(Some(error.to_string()));
                return;
            }
            self.invalidate_relation_memos_of(&tables);
            self.requery_tables(&tables);
        }
    }

    /// After a successful flush: settle every written row's lazy fields (pending → stored),
    /// keep the bytes they carried in the memo, and drop the memo of every deleted row.
    fn settle_blobs(&self, dirty: &DirtyState) {
        let mut written: HashMap<u64, Vec<u64>> = HashMap::new();
        let mut deleted: Vec<(u64, u64)> = Vec::new();
        for id in &dirty.order {
            match dirty.rows.get(id) {
                Some(DirtyRow::Delete) => deleted.push(*id),
                Some(_) => written.entry(id.0).or_default().push(id.1),
                None => {}
            }
        }
        for store in &dirty.full {
            let keys = {
                let tables = self.inner.tables.borrow();
                tables
                    .get(store)
                    .map(|h| (h.resident_keys)())
                    .unwrap_or_default()
            };
            written.entry(*store).or_default().extend(keys);
        }
        let limit = self.inner.blob_cache_limit.get();
        for (store, keys) in written {
            let settle = {
                let tables = self.inner.tables.borrow();
                match tables.get(&store) {
                    Some(h) if h.lazy.iter().any(|l| *l) => h.settle.clone(),
                    _ => continue,
                }
            };
            for (key, field, bytes) in settle(&keys) {
                self.inner
                    .blob_memo
                    .borrow_mut()
                    .insert((store, key, field), bytes, limit);
            }
        }
        if !deleted.is_empty() {
            let mut memo = self.inner.blob_memo.borrow_mut();
            for (store, key) in deleted {
                memo.forget_row(store, key);
            }
        }
    }

    /// The SQL half of a lazy read: the table, the key clause and the stored column name.
    fn blob_target(
        &self,
        store: u64,
        key: u64,
        column: &str,
    ) -> Option<(String, String, Vec<Value>)> {
        let tables = self.inner.tables.borrow();
        let hooks = tables.get(&store)?;
        let (clause, params) = (hooks.key_where)(key);
        Some((
            hooks.name.sql(),
            format!("{} FROM {} WHERE {clause}", ident(column), hooks.name.sql()),
            params,
        ))
    }

    /// The whole value of a lazy column, from the memo or one point `SELECT`. Pending writes
    /// flush first with autosave, like every other read.
    pub(crate) fn blob_bytes(
        &self,
        store: u64,
        key: u64,
        column: &'static str,
    ) -> Result<std::sync::Arc<Vec<u8>>, DbError> {
        if self.inner.autosave.get() && !self.inner.dirty.borrow().is_empty() {
            self.save()?;
        }
        if let Some(hit) = self.inner.blob_memo.borrow_mut().get((store, key, column)) {
            return Ok(hit);
        }
        let Some((_, tail, params)) = self.blob_target(store, key, column) else {
            return Ok(std::sync::Arc::new(Vec::new()));
        };
        let mut bytes = Vec::new();
        self.conn()
            .query(&format!("SELECT {tail}"), &params, &mut |row| {
                bytes = row.get(0).as_blob().map(|b| b.to_vec()).unwrap_or_default();
            })?;
        let bytes = std::sync::Arc::new(bytes);
        let limit = self.inner.blob_cache_limit.get();
        self.inner
            .blob_memo
            .borrow_mut()
            .insert((store, key, column), bytes.clone(), limit);
        Ok(bytes)
    }

    /// `length(col)`: the value's size without reading it (the memo answers when it can).
    pub(crate) fn blob_len(
        &self,
        store: u64,
        key: u64,
        column: &'static str,
    ) -> Result<usize, DbError> {
        if self.inner.autosave.get() && !self.inner.dirty.borrow().is_empty() {
            self.save()?;
        }
        if let Some(hit) = self.inner.blob_memo.borrow_mut().get((store, key, column)) {
            return Ok(hit.len());
        }
        let Some((table, _, params)) = self.blob_target(store, key, column) else {
            return Ok(0);
        };
        let clause = {
            let tables = self.inner.tables.borrow();
            tables
                .get(&store)
                .map(|h| (h.key_where)(key).0)
                .unwrap_or_default()
        };
        let mut len = 0usize;
        self.conn().query(
            &format!(
                "SELECT length({}) FROM {table} WHERE {clause}",
                ident(column)
            ),
            &params,
            &mut |row| len = row.get(0).as_int().unwrap_or(0).max(0) as usize,
        )?;
        Ok(len)
    }

    /// `substr(col, start + 1, len)`: one range of the value, clamped to its length, so only
    /// the asked-for bytes cross from the engine.
    pub(crate) fn blob_range(
        &self,
        store: u64,
        key: u64,
        column: &'static str,
        range: std::ops::Range<usize>,
    ) -> Result<Vec<u8>, DbError> {
        if self.inner.autosave.get() && !self.inner.dirty.borrow().is_empty() {
            self.save()?;
        }
        if let Some(hit) = self.inner.blob_memo.borrow_mut().get((store, key, column)) {
            let start = range.start.min(hit.len());
            let end = range.end.clamp(start, hit.len());
            return Ok(hit[start..end].to_vec());
        }
        if range.end <= range.start {
            return Ok(Vec::new());
        }
        let Some((table, _, mut params)) = self.blob_target(store, key, column) else {
            return Ok(Vec::new());
        };
        let clause = {
            let tables = self.inner.tables.borrow();
            tables
                .get(&store)
                .map(|h| (h.key_where)(key).0)
                .unwrap_or_default()
        };
        let mut all = vec![
            Value::Int(range.start as i64 + 1),
            Value::Int((range.end - range.start) as i64),
        ];
        all.append(&mut params);
        let mut bytes = Vec::new();
        self.conn().query(
            &format!(
                "SELECT substr({}, ?, ?) FROM {table} WHERE {clause}",
                ident(column)
            ),
            &all,
            &mut |row| bytes = row.get(0).as_blob().map(|b| b.to_vec()).unwrap_or_default(),
        )?;
        Ok(bytes)
    }

    /// Drop the memo of one row's lazy values (the row left).
    #[allow(dead_code)]
    pub(crate) fn blob_forget(&self, store: u64, key: u64) {
        self.inner.blob_memo.borrow_mut().forget_row(store, key);
    }

    /// Drop the memo of one lazy value (a write replaced it).
    pub(crate) fn blob_forget_field(&self, store: u64, key: u64, column: &'static str) {
        self.inner
            .blob_memo
            .borrow_mut()
            .forget_one((store, key, column));
    }

    /// Install one transaction extension before exposing the container to writers. Registration
    /// does not initialize its schema; do that in the worker factory first. No replacement or
    /// removal is supported, preventing a sync-enabled connection silently losing journaling.
    pub fn install_transaction_participant(
        &self,
        participant: impl TransactionParticipant,
    ) -> Result<(), DbError> {
        if self.inner.worker_transaction.get()
            || !self.inner.dirty.borrow().is_empty()
            || self.inner.participant.borrow().is_some()
        {
            return Err(DbError::new(
                DbErrorKind::Deny,
                "transaction participant must be installed on an idle, clean container",
            ));
        }
        *self.inner.participant.borrow_mut() = Some(Rc::new(participant));
        Ok(())
    }

    fn participant_begin(
        &self,
        conn: &mut dyn SqliteConnection,
        origin: WriteOrigin,
    ) -> Result<(), DbError> {
        let participant = self.inner.participant.borrow().clone();
        if let Some(p) = participant {
            self.inner.transaction_changes.borrow_mut().clear();
            *self.inner.refresh_scope.borrow_mut() = Refresh::None;
            p.begin(conn, origin)?;
        }
        Ok(())
    }

    /// Hand the participant the transaction's change set and keep its refresh request for
    /// [`ModelContainer::participant_refresh`], which runs once the COMMIT has succeeded.
    fn participant_commit(
        &self,
        conn: &mut dyn SqliteConnection,
        origin: WriteOrigin,
    ) -> Result<(), DbError> {
        let participant = self.inner.participant.borrow().clone();
        if let Some(p) = participant {
            let changes = std::mem::take(&mut *self.inner.transaction_changes.borrow_mut());
            let scope = p.before_commit(conn, origin, &changes)?;
            *self.inner.refresh_scope.borrow_mut() = scope;
        }
        Ok(())
    }

    /// A transaction is ending without a COMMIT: its change set is not anyone's to see.
    fn participant_rollback(&self) {
        self.inner.transaction_changes.borrow_mut().clear();
        *self.inner.refresh_scope.borrow_mut() = Refresh::None;
    }

    /// Append one flush's folded rows to the open transaction's change set, coalescing with
    /// the rows earlier flushes of the same transaction already recorded.
    fn record_changes(&self, changes: Vec<RowChange>) {
        if changes.is_empty() {
            return;
        }
        let mut set = self.inner.transaction_changes.borrow_mut();
        for change in changes {
            match set
                .iter_mut()
                .find(|c| c.table == change.table && c.key == change.key)
            {
                None => set.push(change),
                Some(prior) => prior.absorb(change),
            }
        }
    }

    /// The last autosave failure, if any, as a tracked signal the UI can watch.
    pub fn last_error(&self) -> day_reactive::Signal<Option<String>> {
        self.inner.error
    }

    /// Flush every pending change now, in one transaction. Autosave calls this at turn end;
    /// call it directly where the error matters at a known point.
    pub fn save(&self) -> Result<(), DbError> {
        self.save_now().map(|_| ())
    }

    /// Run `f` and return the SQL one flush of everything it changed issues: the headless
    /// persistence assert (autosave is suspended for the duration so the statements land
    /// here). Twenty keystrokes into one field come back as one `UPDATE`.
    pub fn record_sql(&self, f: impl FnOnce()) -> Result<Vec<String>, DbError> {
        let prior = self.inner.autosave.replace(false);
        f();
        let result = self.save_now();
        self.inner.autosave.set(prior);
        result.map(|stmts| stmts.into_iter().map(|(sql, _)| sql).collect())
    }

    fn save_now(&self) -> Result<Vec<(String, Vec<Value>)>, DbError> {
        if self.inner.flushing.get() {
            return Ok(Vec::new());
        }
        if self.inner.refresh_pending.get() {
            self.refresh_committed()?;
        }
        let dirty = {
            let mut d = self.inner.dirty.borrow_mut();
            if d.is_empty() {
                drop(d);
                // Nothing to flush, but a stale query may still be waiting on its deferred
                // requery (a fetch swap on a clean container lands here).
                self.run_deferred_requeries(&[]);
                return Ok(Vec::new());
            }
            std::mem::take(&mut *d)
        };
        self.inner.flushing.set(true);
        let had_writes = !dirty.is_empty();
        let result = self.flush(&dirty);
        self.inner.flushing.set(false);
        match &result {
            Ok(stmts) => {
                // Previously dirty rows can now be evicted on the next fault.
                self.inner.eviction_retry.borrow_mut().clear();
                // And a pass runs now for every store the flush touched: an import that only
                // inserts never faults, so without this every row it wrote would stay
                // resident, however far past the limit (a ten-million-row seed sat at 3 GB).
                let mut touched: Vec<u64> = dirty.order.iter().map(|(store, _)| *store).collect();
                touched.extend(dirty.full.iter().copied());
                touched.sort_unstable();
                touched.dedup();
                for store in touched {
                    self.enforce_cache_limit(store, &[], false);
                }
                self.settle_blobs(&dirty);
                self.reconcile_engine_cascades();
                self.inner.error.set_if_changed(None);
                self.run_deferred_requeries(stmts);
            }
            Err(e) => {
                // Keep the optimistic cache and its pending writes together. A retry must
                // persist the same edits, including any edits made after the failed save.
                {
                    let mut pending = self.inner.dirty.borrow_mut();
                    let newer = std::mem::take(&mut *pending);
                    *pending = dirty;
                    pending.merge(newer);
                }
                self.inner.error.set(Some(e.to_string()));
            }
        }
        if result.is_ok() && !self.inner.worker_transaction.get() && had_writes {
            self.participant_refresh()?;
        }
        result
    }

    /// After a successful COMMIT: the refresh `before_commit` asked for. A failure here is
    /// [`DbErrorKind::CommittedRefreshFailed`]; the refresh stays pending (as a full one) for
    /// the next save to retry, since the file already holds the participant's writes.
    fn participant_refresh(&self) -> Result<(), DbError> {
        let scope = std::mem::take(&mut *self.inner.refresh_scope.borrow_mut());
        let tables = match scope {
            Refresh::None => return Ok(()),
            Refresh::Tables(tables) => Some(tables),
            Refresh::All => None,
        };
        self.inner.refresh_pending.set(true);
        self.refresh_committed_in(tables.as_deref()).map_err(|e| {
            let error = DbError::new(DbErrorKind::CommittedRefreshFailed, e.to_string());
            self.inner.error.set(Some(error.to_string()));
            error
        })
    }

    fn refresh_committed(&self) -> Result<(), DbError> {
        self.refresh_committed_in(None)
    }

    /// Re-read the resident rows of `tables` (every table when `None`) and bring the memos
    /// and live queries that depend on them up to date.
    fn refresh_committed_in(&self, tables: Option<&[&'static str]>) -> Result<(), DbError> {
        if !self.inner.dirty.borrow().is_empty() {
            return Err(DbError::new(
                DbErrorKind::Deny,
                "refresh committed state before making further model edits",
            ));
        }
        self.refresh_resident_in(tables)?;
        match tables {
            None => {
                self.invalidate_relation_memos();
                self.requery_all();
            }
            Some(tables) => {
                self.invalidate_relation_memos_of(tables);
                self.requery_tables(tables);
            }
        }
        if self.inner.caps.external_changes {
            self.inner.data_version.set(self.file_data_version()?);
        }
        self.inner.refresh_pending.set(false);
        self.inner.error.set_if_changed(None);
        Ok(())
    }

    // --- faulting ----------------------------------------------------------------------------

    /// One row, made resident (faulted from the file if it was not). `None` when no such row
    /// exists (or a driver error surfaced, observable through [`ModelContainer::last_error`]).
    pub fn get<M: Model>(&self, id: impl Into<ModelId<M>>) -> Option<day_model::Elem<M>> {
        match self.try_get::<M>(id) {
            Ok(row) => row,
            Err(error) => {
                self.inner.error.set(Some(error.to_string()));
                None
            }
        }
    }

    /// Read a row, distinguishing an absent key from a storage or decoding failure.
    pub fn try_get<M: Model>(
        &self,
        id: impl Into<ModelId<M>>,
    ) -> Result<Option<day_model::Elem<M>>, DbError> {
        let store = self.cache::<M>();
        let h = id.into().handle();
        if !store.with_untracked(|k| k.get(h).is_some()) {
            self.ensure_resident::<M>(&[h])?;
        }
        Ok(store
            .with_untracked(|k| k.get(h).is_some())
            .then(|| store.elem(h)))
    }

    /// Make these rows resident, faulting the missing ones in one chunked `SELECT`. Rows the
    /// file does not have are not resident afterwards; rows deleted this turn are not
    /// resurrected.
    pub fn ensure_resident<M: Model>(&self, keys: &[u64]) -> Result<(), DbError> {
        let store = self.cache::<M>();
        self.fault_into(store.store_id(), keys)
    }

    /// [`ModelContainer::ensure_resident`], typed ids in.
    pub fn ensure<M: Model>(
        &self,
        ids: impl IntoIterator<Item = impl Into<ModelId<M>>>,
    ) -> Result<(), DbError> {
        let keys: Vec<u64> = ids.into_iter().map(|i| i.into().handle()).collect();
        self.ensure_resident::<M>(&keys)
    }

    /// Fault every row of `M`'s table in: the document pattern, said explicitly. A sketch's
    /// scene or a settings table is the working set, and the app that draws all of it warms
    /// it once at open. Raise the cache limit first (`set_cache_limit(usize::MAX)` for a
    /// document container) so the warmed rows are not immediately eligible to leave; rows
    /// deleted this turn stay deleted. Returns how many rows are resident afterward.
    pub fn warm<M: Model>(&self) -> Result<usize, DbError> {
        let store = self.cache::<M>();
        let key = ident(M::KEY);
        let keys = self.select_id_column_checked(&format!(
            "SELECT {key} FROM {} ORDER BY {key}",
            TableName::of::<M>().sql()
        ))?;
        self.fault_into(store.store_id(), &keys)?;
        Ok(store.with_untracked(|k| k.len()))
    }

    /// Insert one row through the front door: it becomes resident and dirty, announces, and
    /// folds to one `INSERT` at the next flush.
    pub fn insert<M: Model>(&self, row: M) {
        let store = self.cache::<M>();
        let h = row.handle();
        store.restructure("create", Op::Insert, h, move |k| k.push(row));
    }

    /// `SELECT COUNT(*)`: the table's true size, which the cache cannot know. Settles
    /// pending writes first (with autosave), like every other read.
    pub fn table_count<M: Model>(&self) -> Result<u64, DbError> {
        if self.inner.autosave.get() && !self.inner.dirty.borrow().is_empty() {
            self.save()?;
        }
        let mut n = 0i64;
        self.conn().query(
            &format!("SELECT COUNT(*) FROM {}", TableName::of::<M>().sql()),
            &[],
            &mut |row| {
                n = row.get(0).as_int().unwrap_or(0);
            },
        )?;
        Ok(n.max(0) as u64)
    }

    /// The untyped fault: bring `keys` into `store_id`'s cache.
    pub(crate) fn fault_into(&self, store_id: u64, keys: &[u64]) -> Result<(), DbError> {
        let (is_resident, absorb, columns, table, keys_where) = {
            let tables = self.inner.tables.borrow();
            let Some(hooks) = tables.get(&store_id) else {
                return Ok(());
            };
            (
                hooks.is_resident.clone(),
                hooks.absorb.clone(),
                select_list(hooks),
                hooks.name.sql(),
                keys_where_of(hooks),
            )
        };
        let missing: Vec<u64> = {
            let dirty = self.inner.dirty.borrow();
            keys.iter()
                .copied()
                .filter(|k| !is_resident(*k))
                // A row deleted this turn still exists in the file until the flush; faulting
                // it back would resurrect it.
                .filter(|k| dirty.rows.get(&(store_id, *k)) != Some(&DirtyRow::Delete))
                .collect()
        };
        if missing.is_empty() {
            return Ok(());
        }
        let mut faulted: Vec<u64> = Vec::with_capacity(missing.len());
        for chunk in missing.chunks(MAX_BOUND_PARAMS / 2) {
            let (clause, params) = keys_where(chunk);
            let mut rows: Vec<Vec<Value>> = Vec::new();
            self.conn().query(
                &format!("SELECT {columns} FROM {table} WHERE {clause}"),
                &params,
                &mut |row| {
                    let n = Row::len(row);
                    rows.push((0..n).map(|i| row.get(i)).collect());
                },
            )?;
            faulted.extend(absorb(rows)?);
        }
        // The Recorder serves whole fixture tables whatever the `WHERE` says; keep only what
        // was asked for so faulting stays precise there too. (Through a `HashSet`; a linear
        // scan here made warming half a million rows quadratic.)
        let wanted: std::collections::HashSet<u64> = missing.iter().copied().collect();
        faulted.retain(|k| wanted.contains(k));
        self.enforce_cache_limit(store_id, &faulted, false);
        Ok(())
    }

    /// Release resident rows beyond the cache limit: oldest first, never a dirty row, never
    /// an observed one, never one just faulted for the caller still holding it.
    ///
    /// The pass walks every resident key, so it runs with hysteresis on the fault path:
    /// nothing happens until the cache overshoots the limit by a slack margin, and one pass
    /// then brings it back to the limit, amortizing the walk over the faults that filled the
    /// slack, instead of paying O(resident) per fault batch. (Measured: a 50k-row relation
    /// traversal over a 500k-row table spent 99% of its time in the un-amortized walk.)
    /// `strict` skips the slack, so `set_cache_limit` enforces its new bound immediately.
    fn enforce_cache_limit(&self, store_id: u64, protect: &[u64], strict: bool) {
        let limit = self.inner.cache_limit.get();
        if limit == usize::MAX {
            return;
        }
        let (resident_len, evict) = {
            let tables = self.inner.tables.borrow();
            let Some(hooks) = tables.get(&store_id) else {
                return;
            };
            ((hooks.resident_len)(), hooks.evict.clone())
        };
        let slack = if strict {
            0
        } else {
            (limit / 8).clamp(64, 4096)
        };
        let threshold = if strict {
            limit
        } else {
            self.inner
                .eviction_retry
                .borrow()
                .get(&store_id)
                .copied()
                .unwrap_or_else(|| limit.saturating_add(slack))
        };
        if resident_len <= threshold {
            return;
        }
        // Back off even when every row is pinned. A fixed limit gate otherwise scans an
        // ever-growing dirty transaction on EVERY single-row fault (quadratic work).
        self.inner.eviction_retry.borrow_mut().insert(
            store_id,
            resident_len.saturating_add(slack.max(resident_len / 8).max(1)),
        );
        let resident = {
            let tables = self.inner.tables.borrow();
            match tables.get(&store_id) {
                Some(hooks) => (hooks.resident_keys)(),
                None => return,
            }
        };
        let excess = resident.len().saturating_sub(limit);
        let candidates: Vec<u64> = {
            let dirty = self.inner.dirty.borrow();
            if dirty.full.contains(&store_id) {
                return; // a wholesale rewrite is pending; every row is implicitly dirty
            }
            let protect: std::collections::HashSet<u64> = protect.iter().copied().collect();
            resident
                .into_iter()
                .filter(|key| !protect.contains(key) && !dirty.rows.contains_key(&(store_id, *key)))
                .collect()
        };
        let evicted = evict(&candidates, excess);
        if evicted > 0 {
            let is_resident = {
                let tables = self.inner.tables.borrow();
                tables.get(&store_id).map(|h| h.is_resident.clone())
            };
            if let Some(is_resident) = is_resident {
                let mut memo = self.inner.blob_memo.borrow_mut();
                for key in candidates.iter().filter(|k| !is_resident(**k)) {
                    memo.forget_row(store_id, *key);
                }
            }
        }
        let remaining = resident_len.saturating_sub(evicted);
        self.inner.eviction_retry.borrow_mut().insert(
            store_id,
            remaining
                .max(limit)
                .saturating_add(slack.max(remaining / 8).max(1)),
        );
    }

    // --- internals ---------------------------------------------------------------------------

    pub(crate) fn conn(&self) -> std::cell::RefMut<'_, Box<dyn SqliteConnection>> {
        self.inner.conn.borrow_mut()
    }

    /// Run a one-column SELECT and hand back the values as key handles. Errors surface on the
    /// error signal (these run on read paths with no caller to give a `Result` to).
    /// One-column key SELECT with the error returned, for callers that have a `Result` to
    /// give it to (the read paths use [`ModelContainer::select_id_column`] instead).
    fn select_id_column_checked(&self, sql: &str) -> Result<Vec<u64>, DbError> {
        let mut ids = Vec::new();
        self.conn().query(sql, &[], &mut |row| {
            if let Some(h) = value_to_handle(&row.get(0)) {
                ids.push(h);
            }
        })?;
        Ok(ids)
    }

    fn select_ids_checked(&self, sql: &str, params: &[Value]) -> Result<Vec<u64>, DbError> {
        let mut ids = Vec::new();
        self.conn().query(sql, params, &mut |row| {
            if let Some(h) = value_to_handle(&row.get(0)) {
                ids.push(h);
            }
        })?;
        Ok(ids)
    }
    pub(crate) fn select_id_column(&self, sql: &str, params: &[Value]) -> Vec<u64> {
        match self.select_ids_checked(sql, params) {
            Ok(ids) => ids,
            Err(e) => {
                self.inner.error.set(Some(e.to_string()));
                Vec::new()
            }
        }
    }

    /// Run a one-column SELECT for a single REAL.
    pub(crate) fn select_real(&self, sql: &str, params: &[Value]) -> Option<f64> {
        let mut v = None;
        if let Err(e) = self.conn().query(sql, params, &mut |row| {
            v = row.get(0).as_real().ok();
        }) {
            self.inner.error.set(Some(e.to_string()));
        }
        v
    }

    /// This turn's unflushed rows of one store: what relation reads overlay.
    pub(crate) fn dirty_rows_of(&self, store_id: u64) -> Vec<(u64, DirtyRow)> {
        let dirty = self.inner.dirty.borrow();
        let Some(keys) = dirty.by_store.get(&store_id) else {
            return Vec::new();
        };
        keys.iter()
            .filter_map(|k| {
                dirty
                    .rows
                    .get(&(store_id, *k))
                    .map(|state| (*k, state.clone()))
            })
            .collect()
    }

    /// One row's pending state, if any.
    pub(crate) fn dirty_state_of(&self, store_id: u64, key: u64) -> Option<DirtyRow> {
        self.inner
            .dirty
            .borrow()
            .rows
            .get(&(store_id, key))
            .cloned()
    }

    fn ensure_schema_table(&self) -> Result<(), DbError> {
        self.conn().execute(
            "CREATE TABLE IF NOT EXISTS _day_schema (\
             table_name TEXT PRIMARY KEY, fingerprint TEXT NOT NULL, version INTEGER NOT NULL)",
            &[],
        )?;
        Ok(())
    }

    fn db_version(&self) -> Result<u32, DbError> {
        let mut version = 0u32;
        self.conn().query(
            "SELECT version FROM _day_schema WHERE table_name = '_db'",
            &[],
            &mut |row| {
                version = row.get(0).as_int().unwrap_or(0) as u32;
            },
        )?;
        Ok(version)
    }

    /// The `_db` version row, written on the caller's connection so it can ride inside the
    /// transaction whose effects it labels.
    fn write_db_version(conn: &mut dyn SqliteConnection, v: u32) -> Result<(), DbError> {
        conn.execute(
            "INSERT INTO _day_schema (table_name, fingerprint, version) VALUES ('_db', '', ?) \
             ON CONFLICT(table_name) DO UPDATE SET version = excluded.version",
            &[Value::Int(v as i64)],
        )?;
        Ok(())
    }

    /// `f` and the version row it leads to, in one transaction: the stage's effects and its
    /// label commit together or not at all. A failure in the stage, in the version write, or
    /// in the commit itself takes the one rollback path.
    fn versioned_transaction(
        &self,
        version: u32,
        f: impl FnOnce(&mut dyn SqliteConnection) -> Result<(), DbError>,
    ) -> Result<(), DbError> {
        let mut conn = self.conn();
        conn.begin()?;
        let result = f(conn.as_mut())
            .and_then(|()| Self::write_db_version(conn.as_mut(), version))
            .and_then(|()| conn.commit());
        if result.is_err() {
            let _ = conn.rollback();
        }
        result
    }

    fn run_stages(&self, plan: MigrationPlan) -> Result<(), DbError> {
        let target = plan.target_version();
        let mut current = self.db_version()?;
        if current > target && target > 0 {
            return Err(DbError::new(
                DbErrorKind::Schema,
                format!(
                    "database is at version {current}, newer than this build's {target} — \
                     refusing to open (an old app writing a new schema is how data rots)"
                ),
            ));
        }
        let mut stages = plan.stages;
        stages.sort_by_key(|s| s.from);
        for stage in stages {
            if stage.from != current {
                if stage.to <= current {
                    continue; // already applied
                }
                return Err(DbError::new(
                    DbErrorKind::Schema,
                    format!(
                        "migration stage {}→{} does not start at the database's version {current}",
                        stage.from, stage.to
                    ),
                ));
            }
            self.versioned_transaction(stage.to, stage.run)?;
            current = stage.to;
        }
        if target > 0 && current != target {
            self.versioned_transaction(target, |_| Ok(()))?;
        }
        Ok(())
    }

    /// Create (or lightweight-migrate) `M`'s table and register its hooks. The cache starts
    /// empty: this is the line where the old engine read the whole table, and the lazy one
    /// exists so that nothing does.
    fn attach<M: Model>(&self) -> Result<(), DbError> {
        // FTS5's external-content table and the R*Tree address rows by ROWID (an i64), so
        // both need the key column to be the integer rowid. A wide-keyed model declaring one
        // is refused at open, naming the constraint, rather than silently mis-indexing.
        let key_sql = M::COLUMNS
            .iter()
            .find(|c| c.name == M::KEY)
            .map(|c| c.sql)
            .unwrap_or(SqlType::Integer);
        if key_sql != SqlType::Integer && M::SPATIAL.is_some() {
            return Err(DbError::new(
                DbErrorKind::Unsupported,
                format!(
                    "`{}` declares spatial(…), which addresses rows by ROWID — those \
                     need an integer `#[model(id)]`, not a Uuid or String key",
                    M::TABLE
                ),
            ));
        }
        // A second attach of the same model (a re-attached database after a catalog swap)
        // keeps its store and hooks; only the resident rows are stale, and they are dropped
        // so the next fault reads the new file.
        if self.inner.stores.borrow().contains_key(&TypeId::of::<M>()) {
            let store = self.cache::<M>();
            let keys: Vec<u64> = store.with_untracked(|k| k.keys());
            store.depopulate_many(&keys);
            return Ok(());
        }
        if !M::EXTERNAL {
            self.ensure_table::<M>()?;
        }
        for l in M::LINKS {
            self.inner.links.borrow_mut().push(LinkInfo {
                owner_table: M::TABLE,
                field: l.field,
                local: l.local,
                target_table: l.target_table,
                remote: l.remote,
            });
        }

        let store: Store<Keyed<M>> = Store::new(Keyed::new(Vec::new()));
        let store_id = store.store_id();

        let columns: Vec<String> = M::COLUMNS.iter().map(|c| c.name.to_string()).collect();
        let fields: Vec<String> = M::COLUMNS.iter().map(|c| c.field.to_string()).collect();
        let row_for = {
            Rc::new(move |key: u64| store.with_untracked(|k| k.get(key).map(|m| m.to_row())))
                as Rc<dyn Fn(u64) -> Option<Vec<Value>>>
        };
        let all_rows = {
            Rc::new(move || {
                store.with_untracked(|k| {
                    k.items().iter().map(|m| (m.handle(), m.to_row())).collect()
                })
            }) as Rc<dyn Fn() -> Vec<(u64, Vec<Value>)>>
        };
        let resident_keys =
            Rc::new(move || store.with_untracked(|k| k.keys())) as Rc<dyn Fn() -> Vec<u64>>;
        let resident_len =
            Rc::new(move || store.with_untracked(|k| k.len())) as Rc<dyn Fn() -> usize>;
        let is_resident = Rc::new(move |h: u64| store.with_untracked(|k| k.get(h).is_some()))
            as Rc<dyn Fn(u64) -> bool>;

        let absorb = {
            Rc::new(
                move |raw_rows: Vec<Vec<Value>>| -> Result<Vec<u64>, DbError> {
                    let mut decoded: Vec<M> = Vec::with_capacity(raw_rows.len());
                    for r in raw_rows {
                        decoded.push(M::from_row(&r)?);
                    }
                    let keys: Vec<u64> = decoded.iter().map(|m| m.handle()).collect();
                    store.populate(decoded);
                    Ok(keys)
                },
            ) as AbsorbFn
        };
        let refresh = {
            Rc::new(move |raw_rows: Vec<Vec<Value>>| -> Result<bool, DbError> {
                let mut fresh: Vec<M> = Vec::with_capacity(raw_rows.len());
                for r in raw_rows {
                    fresh.push(M::from_row(&r)?);
                }
                let existing: Vec<u64> = store.with_untracked(|k| k.keys());
                let fresh_keys: std::collections::HashSet<u64> =
                    fresh.iter().map(|m| m.handle()).collect();
                let mut changed = false;
                day_model::with_author(ModelContainer::EXTERNAL_AUTHOR, || {
                    for m in fresh {
                        let key = m.handle();
                        match store.with_untracked(|k| k.get(key).map(|old| old.to_row())) {
                            // Selected by resident keys, so an unknown row means the cache
                            // moved underneath us; treat it as an arrival.
                            None => {
                                changed = true;
                                store.restructure("external", Op::Insert, key, |k| k.push(m));
                            }
                            Some(old) => {
                                let new_row = m.to_row();
                                let labels: Vec<&'static str> = M::COLUMNS
                                    .iter()
                                    .enumerate()
                                    .filter(|(i, _)| Row::get(&old, *i) != Row::get(&new_row, *i))
                                    .map(|(_, c)| c.field)
                                    .collect();
                                if !labels.is_empty() {
                                    changed = true;
                                    store.merge_row(key, m, &labels);
                                }
                            }
                        }
                    }
                    for gone in existing.into_iter().filter(|k| !fresh_keys.contains(k)) {
                        changed = true;
                        store.restructure("external", Op::Delete, gone, |k| {
                            k.remove(gone);
                        });
                    }
                });
                Ok(changed)
            }) as RefreshFn
        };
        let evict = Rc::new(move |candidates: &[u64], want: usize| {
            let doomed: Vec<u64> = candidates
                .iter()
                .copied()
                .filter(|h| !store.is_observed(*h))
                .take(want)
                .collect();
            store.depopulate_many(&doomed)
        }) as EvictFn;
        let watch_undo = Rc::new(move |stack: &day_model::UndoStack| stack.watch(store))
            as Rc<dyn Fn(&day_model::UndoStack)>;
        // After a flush: the pending bytes of these rows' lazy fields are in the file, so the
        // fields settle to stored, under the database's own author so nothing re-dirties.
        let settle = Rc::new(move |keys: &[u64]| {
            let mut out = Vec::new();
            if M::LAZY_FIELDS.is_empty() {
                return out;
            }
            day_model::with_author(ModelContainer::EXTERNAL_AUTHOR, || {
                for &key in keys {
                    let Some(mut row) = store.with_untracked(|k| k.get(key).cloned()) else {
                        continue;
                    };
                    let taken = row.settle_lazy();
                    if taken.is_empty() {
                        continue;
                    }
                    store.merge_row(key, row, M::LAZY_FIELDS);
                    out.extend(taken.into_iter().map(|(f, b)| (key, f, b)));
                }
            });
            out
        }) as SettleFn;

        self.inner.tables.borrow_mut().insert(
            store_id,
            TableHooks {
                table: M::TABLE,
                name: TableName::of::<M>(),
                key_cols: vec![M::KEY.to_string()],
                key_where: Rc::new(|h| (format!("{} = ?", ident(M::KEY)), vec![key_param(h)])),
                columns,
                column_names: M::COLUMNS.iter().map(|c| c.name).collect(),
                fields,
                lazy: M::COLUMNS.iter().map(|c| c.lazy).collect(),
                settle,
                resident_len,
                fts: (!M::FTS_COLUMNS.is_empty()).then(|| format!("{}_fts", M::TABLE)),
                fts_key: if key_sql == SqlType::Integer {
                    "rowid"
                } else {
                    "day_key"
                },
                spatial: M::SPATIAL.map(|s| {
                    (
                        s.lat.to_string(),
                        s.lon.to_string(),
                        format!("{}_geo", M::TABLE),
                    )
                }),
                row_for,
                all_rows,
                resident_keys,
                is_resident,
                absorb,
                refresh,
                evict,
                #[cfg(not(target_arch = "wasm32"))]
                dispose_cache: Rc::new(move || store.dispose_contents()),
                watch_undo,
            },
        );
        self.inner
            .stores
            .borrow_mut()
            .insert(TypeId::of::<M>(), Box::new(store));
        Ok(())
    }

    fn ensure_table<M: Model>(&self) -> Result<(), DbError> {
        // Relation-contributed clauses fold into the fingerprint: adopting or changing a
        // delete rule re-runs this path. An existing table cannot gain the SQL-level clause
        // in place (SQLite has no `ALTER ADD CONSTRAINT`), so the comparison below routes
        // that difference through the table rebuild, which writes the declared DDL whole.
        let mut fp_val = model_fingerprint::<M>();
        for s in self
            .inner
            .fk_specs
            .borrow()
            .iter()
            .filter(|s| s.child_table == M::TABLE)
        {
            for b in s
                .child_field
                .bytes()
                .chain(s.parent_table.bytes())
                .chain(s.rule.sql().bytes())
            {
                fp_val ^= b as u64;
                fp_val = fp_val.wrapping_mul(0x1000_0000_01b3);
            }
        }
        let fp = format!("{fp_val:016x}");
        let stored = self.stored_fingerprint(M::TABLE)?;
        if stored.as_deref() == Some(fp.as_str()) {
            // The layout is known to match; the generated triggers are still reconciled, so
            // updated trigger logic reaches an existing file (an unchanged trigger is a read
            // and no write).
            self.conn().begin()?;
            let result = self
                .create_shadow_tables::<M>()
                .and_then(|()| self.conn().commit());
            if result.is_err() {
                let _ = self.conn().rollback();
            }
            return result;
        }

        let name = TableName::of::<M>();
        // A missing table is created whole; an existing one is compared column by column,
        // index by index, and the comparison decides between in-place DDL and a rebuild,
        // or refuses before anything is touched.
        let delta = if self.table_exists(M::TABLE)? {
            let file = self.file_schema(name)?;
            Some((self.compare_schema::<M>(&file)?, file))
        } else {
            None
        };
        // A rebuild drops and recreates the table, which `PRAGMA foreign_keys` would treat
        // as a delete of every row (cascading into children). The pragma is a no-op inside
        // a transaction, so it toggles around one, and the rebuild's own
        // `foreign_key_check` is what guarantees nothing dangles afterwards.
        let rebuild = matches!(delta, Some((SchemaDelta::Rebuild, _)));
        let fk_was_on = rebuild && self.foreign_keys_enabled()?;
        if fk_was_on {
            self.conn().execute("PRAGMA foreign_keys = OFF", &[])?;
        }

        // DDL, copy and backfill are one transaction: a failed migration leaves the old
        // table, index and fingerprint usable. Remove triggers before dropping indexed
        // columns.
        // Bound first: the `RefMut` the `begin` call holds must be gone before the closure
        // borrows the connection again.
        let began = self.conn().begin();
        let result = began.and_then(|()| {
            let result = (|| {
                let t = name.bare;
                if self.table_exists(&format!("{t}_fts"))? {
                    for suffix in ["ai", "ad", "au"] {
                        self.conn().execute(
                            &format!(
                                "DROP TRIGGER IF EXISTS {}",
                                ident(&format!("{t}_fts_{suffix}"))
                            ),
                            &[],
                        )?;
                    }
                    self.conn()
                        .execute(&format!("DROP TABLE {}", name.shadow("_fts")), &[])?;
                    self.conn().execute(
                        &format!("DROP TABLE IF EXISTS {}", name.shadow("_fts_keys")),
                        &[],
                    )?;
                }
                let mut unique_indexes: Vec<&'static str> = Vec::new();
                match delta {
                    None => self.create_table_named::<M>(name.sql())?,
                    Some((SchemaDelta::Lightweight(plan), _)) => {
                        unique_indexes = plan.unique_indexes.clone();
                        self.lightweight_migrate::<M>(&plan)?;
                    }
                    Some((SchemaDelta::Rebuild, file)) => {
                        self.rebuild_table::<M>(&file)?;
                    }
                }
                self.create_indexes::<M>(&unique_indexes)?;
                if rebuild {
                    let dangling = Self::foreign_key_check_on(self.conn().as_mut())?;
                    if let Some(first) = dangling.first() {
                        return Err(DbError::new(
                            DbErrorKind::Schema,
                            format!(
                                "rebuilding `{}` leaves {} row(s) with a dangling foreign \
                                 key ({first}); the file is unchanged",
                                M::TABLE,
                                dangling.len()
                            ),
                        ));
                    }
                }
                self.create_shadow_tables::<M>()?;
                // The fingerprint is the last write: it records a layout that has been
                // brought to the declaration and verified, never one still in flight.
                self.store_fingerprint(M::TABLE, &fp)?;
                self.conn().commit()
            })();
            if result.is_err() {
                let _ = self.conn().rollback();
            }
            result
        });
        if fk_was_on {
            let restored = self
                .conn()
                .execute("PRAGMA foreign_keys = ON", &[])
                .map(|_| ());
            return result.and(restored);
        }
        result
    }

    /// Whether this connection enforces foreign keys right now (`PRAGMA foreign_keys`). A
    /// driver that answers nothing (the Recorder) counts as not enforcing.
    fn foreign_keys_enabled(&self) -> Result<bool, DbError> {
        let mut on = false;
        self.conn().query("PRAGMA foreign_keys", &[], &mut |row| {
            on = row.get(0).as_int().unwrap_or(0) != 0;
        })?;
        Ok(on)
    }

    /// The FTS5 and R*Tree shadows a model declares: virtual tables plus `AFTER` triggers, so
    /// the indexes stay true inside the same transaction as every write, even a write made by
    /// another tool straight into the file. Backfilled when first created.
    fn create_shadow_tables<M: Model>(&self) -> Result<(), DbError> {
        let name = TableName::of::<M>();
        // The plain names, for messages and `sqlite_master` lookups; the quoted ones, for
        // every statement. A shadow's trigger is named after the shadow, quoted as one name.
        let bare = name.bare;
        let t = name.sql();
        let key = ident(M::KEY);
        let trigger = |suffix: &str| ident(&format!("{bare}{suffix}"));
        if !M::FTS_COLUMNS.is_empty() {
            if !self.inner.caps.full_text_search {
                return Err(DbError::new(
                    DbErrorKind::Unsupported,
                    format!(
                        "`{bare}` declares fts(…) but this driver's engine has no FTS5 — the \
                         bundled and cipher engines compile it in"
                    ),
                ));
            }
            let fts = name.shadow("_fts");
            // The hidden column FTS5 takes its commands through carries the index's own name.
            let fts_command = ident(&format!("{bare}_fts"));
            let cols = column_list(M::FTS_COLUMNS);
            let fresh = !self.table_exists(&format!("{bare}_fts"))?;
            // The tokenizer rides in the DDL; its value is a compile-time literal, quoted
            // through SQL's own escape so an apostrophe cannot break the statement.
            let tokenize = match M::FTS_TOKENIZE {
                Some(tok) => format!(", tokenize='{}'", tok.replace('\'', "''")),
                None => String::new(),
            };
            let new_cols = prefixed_list("new", M::FTS_COLUMNS);
            let wide = M::COLUMNS
                .iter()
                .find(|c| c.name == M::KEY)
                .is_some_and(|c| c.sql != SqlType::Integer);
            if wide {
                if M::FTS_COLUMNS.contains(&"day_key") {
                    return Err(DbError::new(
                        DbErrorKind::Unsupported,
                        "day_key is reserved in a non-integer-key FTS index",
                    ));
                }
                let key_type = M::COLUMNS
                    .iter()
                    .find(|c| c.name == M::KEY)
                    .expect("key column")
                    .sql
                    .ddl();
                let fts_keys = name.shadow("_fts_keys");
                // FTS rowids stay private. An indexed mapping makes update/delete O(log n)
                // rather than scanning the unindexed public key in every FTS row.
                self.conn().execute(&format!("CREATE TABLE IF NOT EXISTS {fts_keys}(day_rowid INTEGER PRIMARY KEY, day_key {key_type} NOT NULL UNIQUE)"), &[])?;
                self.conn().execute(&format!("CREATE VIRTUAL TABLE IF NOT EXISTS {fts} USING fts5(day_key UNINDEXED, {cols}{tokenize})"), &[])?;
                let insert = format!(
                    "INSERT INTO {fts_keys}(day_key) VALUES (new.{key}); INSERT INTO {fts}(rowid, day_key, {cols}) VALUES ((SELECT day_rowid FROM {fts_keys} WHERE day_key = new.{key}), new.{key}, {new_cols});"
                );
                let delete = format!(
                    "DELETE FROM {fts} WHERE rowid = (SELECT day_rowid FROM {fts_keys} WHERE day_key = old.{key}); DELETE FROM {fts_keys} WHERE day_key = old.{key};"
                );
                let (update_of, changed) = fts_update_guard(M::KEY, M::FTS_COLUMNS);
                for (suffix, event, body) in [
                    ("_fts_ai", "INSERT".to_string(), insert.clone()),
                    ("_fts_ad", "DELETE".to_string(), delete.clone()),
                    (
                        "_fts_au",
                        format!("UPDATE OF {update_of}"),
                        format!("{delete} {insert}"),
                    ),
                ] {
                    let when = if suffix == "_fts_au" {
                        format!(" WHEN {changed}")
                    } else {
                        String::new()
                    };
                    self.ensure_trigger(
                        &format!("{bare}{suffix}"),
                        name.schema,
                        &format!(
                            "CREATE TRIGGER {} AFTER {event} ON {t}{when} BEGIN {body} END",
                            trigger(suffix)
                        ),
                    )?;
                }
                if fresh {
                    self.conn().execute(
                        &format!("INSERT INTO {fts_keys}(day_key) SELECT {key} FROM {t}"),
                        &[],
                    )?;
                    let qualified = prefixed_list("b", M::FTS_COLUMNS);
                    self.conn().execute(&format!("INSERT INTO {fts}(rowid, day_key, {cols}) SELECT k.day_rowid, b.{key}, {qualified} FROM {t} b JOIN {fts_keys} k ON k.day_key = b.{key}"), &[])?;
                }
            } else {
                // FTS5 reads its options as SQL string literals; the content table and its
                // rowid column are plain names inside them.
                self.conn().execute(
                    &format!(
                        "CREATE VIRTUAL TABLE IF NOT EXISTS {fts} USING fts5({cols}, \
                     content='{}', content_rowid='{}'{tokenize})",
                        bare.replace('\'', "''"),
                        M::KEY.replace('\'', "''")
                    ),
                    &[],
                )?;
                let old_cols = prefixed_list("old", M::FTS_COLUMNS);
                self.ensure_trigger(
                    &format!("{bare}_fts_ai"),
                    name.schema,
                    &format!(
                        "CREATE TRIGGER {} AFTER INSERT ON {t} BEGIN \
                     INSERT INTO {fts}(rowid, {cols}) VALUES (new.{key}, {new_cols}); END",
                        trigger("_fts_ai")
                    ),
                )?;
                self.ensure_trigger(
                    &format!("{bare}_fts_ad"),
                    name.schema,
                    &format!(
                        "CREATE TRIGGER {} AFTER DELETE ON {t} BEGIN \
                     INSERT INTO {fts}({fts_command}, rowid, {cols}) VALUES ('delete', old.{key}, {old_cols}); END",
                        trigger("_fts_ad")
                    ),
                )?;
                // Only a change to indexed content or to the row's identity re-indexes it: an
                // update that touches other columns, or assigns an indexed column its own
                // value, leaves the index alone.
                let (update_of, changed) = fts_update_guard(M::KEY, M::FTS_COLUMNS);
                self.ensure_trigger(
                    &format!("{bare}_fts_au"),
                    name.schema,
                    &format!(
                        "CREATE TRIGGER {} AFTER UPDATE OF {update_of} ON {t} WHEN {changed} BEGIN \
                     INSERT INTO {fts}({fts_command}, rowid, {cols}) VALUES ('delete', old.{key}, {old_cols}); \
                     INSERT INTO {fts}(rowid, {cols}) VALUES (new.{key}, {new_cols}); END",
                        trigger("_fts_au")
                    ),
                )?;
                if fresh {
                    // External-content rebuild: index whatever rows predate the declaration.
                    self.conn().execute(
                        &format!("INSERT INTO {fts}({fts_command}) VALUES ('rebuild')"),
                        &[],
                    )?;
                }
            }
        }
        if let Some(s) = M::SPATIAL {
            if !self.inner.caps.rtree {
                return Err(DbError::new(
                    DbErrorKind::Unsupported,
                    format!(
                        "`{bare}` declares spatial(…) but this driver's engine has no R*Tree — \
                         the bundled and cipher engines compile it in"
                    ),
                ));
            }
            let (lat, lon) = (ident(s.lat), ident(s.lon));
            let geo = name.shadow("_geo");
            let fresh = !self.table_exists(&format!("{bare}_geo"))?;
            self.conn().execute(
                &format!(
                    "CREATE VIRTUAL TABLE IF NOT EXISTS {geo} USING rtree({key}, \
                     min_lat, max_lat, min_lon, max_lon)"
                ),
                &[],
            )?;
            self.ensure_trigger(
                &format!("{bare}_geo_ai"),
                name.schema,
                &format!(
                    "CREATE TRIGGER {} AFTER INSERT ON {t} BEGIN \
                     INSERT OR REPLACE INTO {geo} VALUES (new.{key}, new.{lat}, new.{lat}, new.{lon}, new.{lon}); END",
                    trigger("_geo_ai")
                ),
            )?;
            self.ensure_trigger(
                &format!("{bare}_geo_au"),
                name.schema,
                &format!(
                    "CREATE TRIGGER {} AFTER UPDATE OF {lat}, {lon} ON {t} BEGIN \
                     INSERT OR REPLACE INTO {geo} VALUES (new.{key}, new.{lat}, new.{lat}, new.{lon}, new.{lon}); END",
                    trigger("_geo_au")
                ),
            )?;
            self.ensure_trigger(
                &format!("{bare}_geo_ad"),
                name.schema,
                &format!(
                    "CREATE TRIGGER {} AFTER DELETE ON {t} BEGIN \
                     DELETE FROM {geo} WHERE {key} = old.{key}; END",
                    trigger("_geo_ad")
                ),
            )?;
            if fresh {
                self.conn().execute(
                    &format!(
                        "INSERT OR REPLACE INTO {geo} \
                         SELECT {key}, {lat}, {lat}, {lon}, {lon} FROM {t}"
                    ),
                    &[],
                )?;
            }
        }
        Ok(())
    }

    /// Install a generated trigger, replacing one whose stored text differs: updated trigger
    /// logic reaches an existing file on the open that carries it, and a trigger that is
    /// already right costs one `sqlite_master` read and no write. `create_sql` is the plain
    /// `CREATE TRIGGER` statement; the engine stores that text verbatim, which is what the
    /// comparison reads back.
    fn ensure_trigger(
        &self,
        bare_name: &str,
        schema: Option<&str>,
        create_sql: &str,
    ) -> Result<(), DbError> {
        let master = table_sql(schema, "sqlite_master");
        let mut stored: Option<String> = None;
        self.conn().query(
            &format!("SELECT sql FROM {master} WHERE type = 'trigger' AND name = ?"),
            &[Value::Text(bare_name.into())],
            &mut |row| {
                if let Ok(sql) = row.get(0).as_text() {
                    stored = Some(sql.to_string());
                }
            },
        )?;
        match stored {
            Some(sql) if sql == create_sql => return Ok(()),
            Some(_) => {
                self.conn().execute(
                    &format!("DROP TRIGGER IF EXISTS {}", table_sql(schema, bare_name)),
                    &[],
                )?;
            }
            None => {}
        }
        self.conn().execute(create_sql, &[])?;
        Ok(())
    }

    fn table_exists(&self, table: &str) -> Result<bool, DbError> {
        let mut found = false;
        self.conn().query(
            "SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?",
            &[Value::Text(table.into())],
            &mut |_| found = true,
        )?;
        Ok(found)
    }

    /// `M`'s declared DDL under `table_sql` (its own quoted name, or the `_new` name a
    /// rebuild copies into). The fresh form carries every constraint inline; the upgrade
    /// paths produce the same enforced constraints by other means (a `NOT NULL DEFAULT`
    /// addition, a `day_uidx_` unique index), and the comparison treats them as equal.
    fn create_table_named<M: Model>(&self, table_sql: String) -> Result<(), DbError> {
        let cols: Vec<String> = self
            .declared_columns::<M>()
            .iter()
            .map(|d| {
                let c = &d.def;
                let mut s = format!("{} {}", ident(c.name), c.sql.ddl());
                if d.pk {
                    s.push_str(" PRIMARY KEY");
                } else if c.not_null {
                    s.push_str(" NOT NULL");
                }
                if c.unique && !d.pk {
                    s.push_str(" UNIQUE");
                }
                // A declared relation's foreign key: enforced by the engine too, so another
                // process honors the same delete rule, and so a cascade's reach into rows
                // this process never faulted still lands in the file. Deferred, so
                // within-transaction statement order (a cascade's children, an undo's
                // re-inserts) never trips it.
                if let Some(fk) = &d.fk {
                    s.push_str(&fk.clause());
                }
                s
            })
            .collect();
        let body = format!("CREATE TABLE {table_sql} ({})", cols.join(", "));
        // `STRICT` where the engine allows it (always, for the bundled build); older system
        // SQLites reject the keyword, and the plain form is the fallback.
        if self.conn().execute(&format!("{body} STRICT"), &[]).is_err() {
            self.conn().execute(&body, &[])?;
        }
        Ok(())
    }

    /// The indexes `M` owns in the file, by name: one per `indexed` column, one per declared
    /// relation's foreign-key column (what `children_of` selects on, what relation predicates
    /// correlate on, and what the engine scans to enforce `ON DELETE`; unindexed, each is a
    /// full scan of the child table), one per composite declaration, and a unique index for
    /// each column in `unique_indexes`, the declared-unique columns whose table carries no
    /// inline `UNIQUE` because they arrived through `ADD COLUMN`.
    fn declared_indexes<M: Model>(&self, unique_indexes: &[&'static str]) -> Vec<DeclaredIndex> {
        let fk_cols: Vec<&str> = self
            .inner
            .fk_specs
            .borrow()
            .iter()
            .filter(|s| s.child_table == M::TABLE)
            .filter_map(|s| {
                M::COLUMNS
                    .iter()
                    .find(|c| c.field == s.child_field)
                    .map(|c| c.name)
            })
            .collect();
        let bare = TableName::of::<M>().bare;
        let mut out: Vec<DeclaredIndex> = M::COLUMNS
            .iter()
            .filter(|c| c.indexed || (fk_cols.contains(&c.name) && c.name != M::KEY))
            .map(|c| DeclaredIndex {
                name: format!("day_idx_{bare}_{}", c.name),
                columns: vec![c.name.to_string()],
                unique: false,
            })
            .collect();
        out.extend(M::COMPOSITE_INDEXES.iter().map(|idx| DeclaredIndex {
            name: format!("day_idx_{bare}_{}", idx.join("_")),
            columns: idx.iter().map(|c| c.to_string()).collect(),
            unique: false,
        }));
        out.extend(unique_indexes.iter().map(|c| DeclaredIndex {
            name: format!("day_uidx_{bare}_{c}"),
            columns: vec![c.to_string()],
            unique: true,
        }));
        out.extend(M::UNIQUE_INDEXES.iter().map(|idx| DeclaredIndex {
            name: format!("day_uidx_{bare}_{}", idx.join("_")),
            columns: idx.iter().map(|c| c.to_string()).collect(),
            unique: true,
        }));
        out
    }

    fn create_indexes<M: Model>(&self, unique_indexes: &[&'static str]) -> Result<(), DbError> {
        let name = TableName::of::<M>();
        let t = name.sql();
        for idx in self.declared_indexes::<M>(unique_indexes) {
            self.conn().execute(
                &format!(
                    "CREATE {}INDEX IF NOT EXISTS {} ON {t}({})",
                    if idx.unique { "UNIQUE " } else { "" },
                    table_sql(name.schema, &idx.name),
                    column_list(&idx.columns)
                ),
                &[],
            )?;
        }
        Ok(())
    }

    /// `M`'s columns as declared, with the relation-contributed foreign key resolved: the
    /// declared side of [`ModelContainer::compare_schema`], and what the DDL is written from.
    fn declared_columns<M: Model>(&self) -> Vec<DeclaredColumn> {
        let specs = self.inner.fk_specs.borrow();
        M::COLUMNS
            .iter()
            .enumerate()
            .map(|(index, c)| DeclaredColumn {
                def: *c,
                index,
                pk: c.name == M::KEY,
                fk: specs
                    .iter()
                    .find(|f| f.child_table == M::TABLE && f.child_field == c.field)
                    .map(|s| DeclaredFk {
                        parent_sql: s.parent_sql.clone(),
                        parent_bare: s.parent_bare,
                        parent_key: s.parent_key,
                        rule: s.rule,
                    }),
            })
            .collect()
    }

    /// The table as the file has it: `PRAGMA table_info`, `foreign_key_list`, `index_list`
    /// and `index_info`, read into one value the comparison and the rebuild both consume.
    fn file_schema(&self, name: TableName) -> Result<FileSchema, DbError> {
        let mut columns: Vec<FileColumn> = Vec::new();
        self.conn().query(
            &pragma_sql(name.schema, "table_info", name.bare),
            &[],
            &mut |row| {
                columns.push(FileColumn {
                    name: row.get(1).as_text().unwrap_or("").to_string(),
                    decl_type: row.get(2).as_text().unwrap_or("").to_ascii_uppercase(),
                    not_null: row.get(3).as_int().unwrap_or(0) != 0,
                    pk: row.get(5).as_int().unwrap_or(0) != 0,
                    fk: None,
                });
            },
        )?;
        self.conn().query(
            &pragma_sql(name.schema, "foreign_key_list", name.bare),
            &[],
            &mut |row| {
                let from = row.get(3).as_text().unwrap_or("").to_string();
                if let Some(col) = columns.iter_mut().find(|c| c.name == from) {
                    col.fk = Some(FileFk {
                        parent: row.get(2).as_text().unwrap_or("").to_string(),
                        parent_key: row.get(4).as_text().unwrap_or("").to_string(),
                        on_delete: row.get(6).as_text().unwrap_or("").to_ascii_uppercase(),
                    });
                }
            },
        )?;
        let mut indexes: Vec<FileIndex> = Vec::new();
        self.conn().query(
            &pragma_sql(name.schema, "index_list", name.bare),
            &[],
            &mut |row| {
                indexes.push(FileIndex {
                    name: row.get(1).as_text().unwrap_or("").to_string(),
                    unique: row.get(2).as_int().unwrap_or(0) != 0,
                    origin: row.get(3).as_text().unwrap_or("").to_string(),
                    columns: Vec::new(),
                });
            },
        )?;
        for idx in &mut indexes {
            let mut cols: Vec<(i64, String)> = Vec::new();
            self.conn().query(
                &pragma_sql(name.schema, "index_info", &idx.name),
                &[],
                &mut |row| {
                    cols.push((
                        row.get(0).as_int().unwrap_or(0),
                        row.get(2).as_text().unwrap_or("").to_string(),
                    ));
                },
            )?;
            cols.sort_by_key(|(seq, _)| *seq);
            idx.columns = cols.into_iter().map(|(_, c)| c).collect();
        }
        Ok(FileSchema { columns, indexes })
    }

    /// Decide how the file's table reaches the declaration. Column and index additions and
    /// drops are closed in place; any other difference (a type, a nullability, a unique
    /// constraint, a foreign key or its delete action) is a rebuild; a change the rebuild
    /// could not fill truthfully (the key column, a required column with no usable default)
    /// is refused here, before anything is touched.
    fn compare_schema<M: Model>(&self, file: &FileSchema) -> Result<SchemaDelta, DbError> {
        let declared = self.declared_columns::<M>();
        let defaults = M::default_row();
        let bare = TableName::of::<M>().bare;
        let refuse = |column: &str, what: String| {
            Err(DbError::new(
                DbErrorKind::Schema,
                format!(
                    "`{}`.`{column}`: {what}; this is not a change the container can make to \
                     an existing table, and it refuses to open rather than guess (a staged \
                     migration can make it)",
                    M::TABLE
                ),
            ))
        };
        let mut plan = LightweightPlan::default();
        // Any one of these differences needs the copy; which one is immaterial to the work.
        let mut rebuild = false;
        let mut note = |_why: String| rebuild = true;
        let inline_unique = |col: &str| {
            file.indexes
                .iter()
                .any(|i| i.origin == "u" && i.columns.len() == 1 && i.columns[0] == col)
        };
        let unique_index_name = |col: &str| format!("day_uidx_{bare}_{col}");
        let has_unique_index = |col: &str| {
            let name = unique_index_name(col);
            file.indexes
                .iter()
                .any(|i| i.name == name && i.unique && i.columns.len() == 1 && i.columns[0] == col)
        };

        for d in &declared {
            let c = &d.def;
            let default = Row::get(&defaults, d.index);
            let required = c.not_null || d.pk;
            match file.columns.iter().find(|f| f.name == c.name) {
                None => {
                    if d.pk {
                        return refuse(c.name, "the declared key column is not in the file".into());
                    }
                    if required && default == Value::Null {
                        return refuse(
                            c.name,
                            "a required column whose Rust default stores NULL cannot be \
                             added to existing rows"
                                .into(),
                        );
                    }
                    if d.fk.is_some() && required {
                        // `ADD COLUMN … REFERENCES` must default to NULL while foreign keys
                        // are enforced; a required reference needs the copy.
                        note(format!("required foreign-key column `{}` added", c.name));
                    } else {
                        plan.add.push(d.index);
                        if c.unique {
                            plan.unique_indexes.push(c.name);
                        }
                    }
                }
                Some(f) => {
                    if f.decl_type != c.sql.ddl() {
                        if d.pk {
                            return refuse(
                                c.name,
                                format!(
                                    "the key column is {} in the file and {} in the declaration",
                                    f.decl_type,
                                    c.sql.ddl()
                                ),
                            );
                        }
                        note(format!(
                            "`{}` is {} in the file and {} in the declaration",
                            c.name,
                            f.decl_type,
                            c.sql.ddl()
                        ));
                    }
                    if f.pk != d.pk {
                        return refuse(
                            c.name,
                            if d.pk {
                                "declared as the key but not the file's primary key".into()
                            } else {
                                "the file's primary key but not the declared key".into()
                            },
                        );
                    }
                    // The key's NOT NULL is implied by PRIMARY KEY (and reported either way
                    // by the engine, depending on its type), so only the other columns compare.
                    if !d.pk && f.not_null != c.not_null {
                        if c.not_null && default == Value::Null {
                            return refuse(
                                c.name,
                                "becomes required, but its Rust default stores NULL, so \
                                 existing NULLs cannot be filled"
                                    .into(),
                            );
                        }
                        note(format!(
                            "`{}` is {} in the file and {} in the declaration",
                            c.name,
                            if f.not_null { "NOT NULL" } else { "nullable" },
                            if c.not_null { "NOT NULL" } else { "nullable" }
                        ));
                    }
                    let want_unique = c.unique && !d.pk;
                    // A declared unique without the inline constraint owns its index,
                    // whether that index exists yet or not (`IF NOT EXISTS` keeps one).
                    match (want_unique, inline_unique(c.name), has_unique_index(c.name)) {
                        (true, false, _) => plan.unique_indexes.push(c.name),
                        (false, true, _) => note(format!(
                            "`{}` carries UNIQUE but is not declared unique",
                            c.name
                        )),
                        (false, false, true) => plan.drop_indexes.push(unique_index_name(c.name)),
                        _ => {}
                    }
                    let fk_matches = match (&d.fk, &f.fk) {
                        (None, None) => true,
                        (Some(want), Some(have)) => {
                            have.parent == want.parent_bare
                                && have.parent_key == want.parent_key
                                && have.on_delete == want.rule.sql()
                        }
                        _ => false,
                    };
                    if !fk_matches {
                        note(format!("`{}`'s foreign key differs", c.name));
                    }
                }
            }
        }
        for f in file
            .columns
            .iter()
            .filter(|f| !declared.iter().any(|d| d.def.name == f.name))
        {
            if f.pk {
                return refuse(&f.name, "the file's primary key is not declared".into());
            }
            // `DROP COLUMN` refuses a column under a constraint or a foreign index; those go
            // through the copy, which simply leaves them out.
            let covered_by_foreign_index = file.indexes.iter().any(|i| {
                i.origin == "c" && !is_day_index(&i.name, bare) && i.columns.contains(&f.name)
            });
            if f.fk.is_some() || inline_unique(&f.name) || covered_by_foreign_index {
                note(format!("constrained column `{}` dropped", f.name));
            } else {
                plan.drop.push(f.name.clone());
            }
        }
        if let Some(extra) = file
            .indexes
            .iter()
            .find(|i| i.origin == "u" && i.columns.len() > 1)
        {
            note(format!(
                "undeclared multi-column UNIQUE constraint over ({})",
                extra.columns.join(", ")
            ));
        }
        // Day's own indexes: one that no longer matches a declaration is dropped in place;
        // a missing one is created after the column work.
        let want = self.declared_indexes::<M>(&plan.unique_indexes);
        for i in file
            .indexes
            .iter()
            .filter(|i| i.origin == "c" && is_day_index(&i.name, bare))
        {
            let matches = want
                .iter()
                .any(|w| w.name == i.name && w.columns == i.columns && w.unique == i.unique);
            if !matches && !plan.drop_indexes.contains(&i.name) {
                plan.drop_indexes.push(i.name.clone());
            }
        }
        Ok(if rebuild {
            SchemaDelta::Rebuild
        } else {
            SchemaDelta::Lightweight(plan)
        })
    }

    /// Close the gap in place: indexes that no longer match are dropped, missing columns are
    /// added with their declared constraints (`NOT NULL DEFAULT <Rust default>`; a nullable
    /// foreign key with its `REFERENCES`), and columns the declaration lost are dropped.
    /// Declared-unique additions get their unique index from `create_indexes`, since
    /// `ADD COLUMN` cannot carry `UNIQUE`.
    fn lightweight_migrate<M: Model>(&self, plan: &LightweightPlan) -> Result<(), DbError> {
        let name = TableName::of::<M>();
        let t = name.sql();
        let declared = self.declared_columns::<M>();
        let defaults = M::default_row();
        for idx in &plan.drop_indexes {
            self.conn().execute(
                &format!("DROP INDEX IF EXISTS {}", table_sql(name.schema, idx)),
                &[],
            )?;
        }
        for &i in &plan.add {
            let d = &declared[i];
            let c = &d.def;
            let default = Row::get(&defaults, i);
            let mut ddl = format!(
                "ALTER TABLE {t} ADD COLUMN {} {}",
                ident(c.name),
                c.sql.ddl()
            );
            if c.not_null {
                ddl.push_str(&format!(" NOT NULL DEFAULT {}", sql_literal(&default)?));
            }
            if let Some(fk) = &d.fk {
                ddl.push_str(&fk.clause());
            }
            self.conn().execute(&ddl, &[])?;
            // A nullable column whose Rust default is a value still backfills, as before.
            if !c.not_null && default != Value::Null {
                self.conn()
                    .execute(&format!("UPDATE {t} SET {} = ?", ident(c.name)), &[default])?;
            }
        }
        for gone in &plan.drop {
            self.conn()
                .execute(&format!("ALTER TABLE {t} DROP COLUMN {}", ident(gone)), &[])?;
        }
        Ok(())
    }

    /// SQLite's documented procedure for every other change
    /// (<https://www.sqlite.org/lang_altertable.html#otheralter>): the declared table is
    /// created under a temporary name, the rows copied across (shared columns as they are,
    /// a required column that was nullable through `COALESCE` with its Rust default, a
    /// missing one from that default), the old table dropped, the new one renamed into
    /// place, and the application's own indexes that still apply re-created. The caller
    /// holds the transaction, has foreign keys off, and runs `foreign_key_check` after.
    /// Application-owned triggers on the table go with it; their owner re-creates them.
    fn rebuild_table<M: Model>(&self, file: &FileSchema) -> Result<(), DbError> {
        let name = TableName::of::<M>();
        let t = name.sql();
        let bare = name.bare;
        let tmp_bare = format!("{bare}_new");
        let tmp = table_sql(name.schema, &tmp_bare);
        let declared = self.declared_columns::<M>();
        let defaults = M::default_row();
        let master = table_sql(name.schema, "sqlite_master");

        // The application's own indexes, to re-create when every column they name survives.
        let mut foreign_indexes: Vec<String> = Vec::new();
        self.conn().query(
            &format!(
                "SELECT name, sql FROM {master} WHERE type = 'index' AND tbl_name = ? \
                 AND sql IS NOT NULL"
            ),
            &[Value::Text(bare.into())],
            &mut |row| {
                let idx_name = row.get(0).as_text().unwrap_or("").to_string();
                if is_day_index(&idx_name, bare) {
                    return;
                }
                let survives = file
                    .indexes
                    .iter()
                    .find(|i| i.name == idx_name)
                    .is_some_and(|i| {
                        i.columns
                            .iter()
                            .all(|c| declared.iter().any(|d| d.def.name == c))
                    });
                if survives && let Ok(sql) = row.get(1).as_text() {
                    foreign_indexes.push(sql.to_string());
                }
            },
        )?;

        // Triggers on the table go with `DROP TABLE`; the application's come back verbatim
        // after the rename when every column they name survives (Day's generated ones are
        // reconciled afterwards anyway). Checked by a dry parse against the new table.
        let mut triggers: Vec<String> = Vec::new();
        self.conn().query(
            &format!(
                "SELECT sql FROM {master} WHERE type = 'trigger' AND tbl_name = ? \
                 AND sql IS NOT NULL ORDER BY rowid"
            ),
            &[Value::Text(bare.into())],
            &mut |row| {
                if let Ok(sql) = row.get(0).as_text() {
                    triggers.push(sql.to_string());
                }
            },
        )?;

        let wrap =
            |e: DbError| DbError::new(e.kind, format!("rebuilding `{}`: {}", M::TABLE, e.message));
        self.conn()
            .execute(&format!("DROP TABLE IF EXISTS {tmp}"), &[])
            .map_err(wrap)?;
        self.create_table_named::<M>(tmp.clone()).map_err(wrap)?;
        let targets = column_list(&declared.iter().map(|d| d.def.name).collect::<Vec<_>>());
        let mut sources: Vec<String> = Vec::with_capacity(declared.len());
        for d in &declared {
            let c = &d.def;
            let default = Row::get(&defaults, d.index);
            let required = c.not_null || d.pk;
            let shared = file.columns.iter().find(|f| f.name == c.name);
            sources.push(match shared {
                Some(f) if !required || f.not_null => ident(c.name),
                Some(_) => format!(
                    "COALESCE({}, {})",
                    ident(c.name),
                    sql_literal(&default).map_err(wrap)?
                ),
                None => sql_literal(&default).map_err(wrap)?,
            });
        }
        self.conn()
            .execute(
                &format!(
                    "INSERT INTO {tmp} ({targets}) SELECT {} FROM {t}",
                    sources.join(", ")
                ),
                &[],
            )
            .map_err(wrap)?;
        self.conn()
            .execute(&format!("DROP TABLE {t}"), &[])
            .map_err(wrap)?;
        // Other tables' triggers and views may name this table (an adapter's capture trigger
        // on a child table reads the parent), and a rename checks every such reference
        // against a schema the table is momentarily absent from. The legacy rename leaves
        // those references as written, which is what a rebuild under the same name wants.
        self.conn()
            .execute_batch("PRAGMA legacy_alter_table = ON")
            .map_err(wrap)?;
        let renamed = self
            .conn()
            .execute(&format!("ALTER TABLE {tmp} RENAME TO {}", ident(bare)), &[]);
        self.conn()
            .execute_batch("PRAGMA legacy_alter_table = OFF")
            .map_err(wrap)?;
        renamed.map_err(wrap)?;
        for sql in foreign_indexes {
            self.conn().execute(&sql, &[]).map_err(wrap)?;
        }
        for sql in triggers {
            // A trigger naming a dropped column cannot come back; its owner recreates it.
            let _ = self.conn().execute(&sql, &[]);
        }
        Ok(())
    }

    fn stored_fingerprint(&self, table: &str) -> Result<Option<String>, DbError> {
        let mut fp = None;
        self.conn().query(
            "SELECT fingerprint FROM _day_schema WHERE table_name = ?",
            &[Value::Text(table.into())],
            &mut |row| {
                if let Ok(t) = row.get(0).as_text() {
                    fp = Some(t.to_string());
                }
            },
        )?;
        Ok(fp)
    }

    fn store_fingerprint(&self, table: &str, fp: &str) -> Result<(), DbError> {
        self.conn().execute(
            "INSERT INTO _day_schema (table_name, fingerprint, version) VALUES (?, ?, 0) \
             ON CONFLICT(table_name) DO UPDATE SET fingerprint = excluded.fingerprint",
            &[Value::Text(table.into()), Value::Text(fp.into())],
        )?;
        Ok(())
    }

    fn install_sink(&self) {
        let inner = Rc::downgrade(&self.inner);
        let sink = day_model::install_change_sink(move |change| {
            if let Some(inner) = inner.upgrade() {
                // An external merge's changes are the database's own contents arriving:
                // queries go stale on them like any edit, but nothing goes back to the file.
                if change.author != Some(ModelContainer::EXTERNAL_AUTHOR) {
                    let tables = inner.tables.borrow();
                    inner
                        .dirty
                        .borrow_mut()
                        .note(change, |store| tables.contains_key(&store));
                }
                let container = ModelContainer { inner };
                container.mark_queries_stale(change);
                container.relations_on_change(change);
            }
        });
        self.inner.sink.set(Some(sink));
    }

    fn install_autosave(&self) {
        // Weak: `on_turn_end` registrations live for the process, and a strong clone here
        // would keep the container (and its connection) alive forever.
        let inner = Rc::downgrade(&self.inner);
        day_reactive::on_turn_end(move || {
            let Some(inner) = inner.upgrade() else { return };
            let this = ModelContainer { inner };
            if this.inner.autosave.get() && !this.inner.dirty.borrow().is_empty() {
                // The error lands in the signal; a turn end has no caller to give a Result to.
                let _ = this.save();
            }
        });
    }

    fn flush(&self, dirty: &DirtyState) -> Result<Vec<(String, Vec<Value>)>, DbError> {
        let capture = self.inner.participant.borrow().is_some();
        let (stmts, changes) = self.fold(dirty, capture)?;
        if stmts.is_empty() {
            return Ok(stmts);
        }
        let mut conn = self.conn();
        let outer = self.inner.worker_transaction.get();
        if !outer {
            conn.begin()?;
            if let Err(error) = self.participant_begin(conn.as_mut(), WriteOrigin::Local) {
                let _ = conn.rollback();
                return Err(error);
            }
        }
        // After begin (which clears the set) and before the statements: an outer worker
        // transaction accumulates every inner flush, and rolls the set back with the rest.
        self.record_changes(changes);
        for (sql, params) in &stmts {
            if let Err(e) = conn.execute(sql, params) {
                if !outer {
                    let _ = conn.rollback();
                    self.participant_rollback();
                }
                return Err(e);
            }
        }
        if !outer
            && let Err(error) = self
                .participant_commit(conn.as_mut(), WriteOrigin::Local)
                .and_then(|_| conn.commit())
        {
            let _ = conn.rollback();
            self.participant_rollback();
            return Err(error);
        }
        Ok(stmts)
    }

    #[cfg(not(target_arch = "wasm32"))]
    fn worker_dispose_caches(&self) {
        for hooks in self.inner.tables.borrow().values() {
            (hooks.dispose_cache)();
        }
        // Reactive callbacks can retain a container until thread teardown. Release transaction
        // resources (including replication's writer lease) before acknowledging worker close.
        self.inner.participant.borrow_mut().take();
    }

    #[cfg(not(target_arch = "wasm32"))]
    fn worker_write<R>(
        &self,
        write: impl FnOnce(&Self) -> Result<R, DbError>,
    ) -> Result<R, DbError> {
        self.worker_write_origin(WriteOrigin::Local, write)
    }

    #[cfg(not(target_arch = "wasm32"))]
    fn worker_write_origin<R>(
        &self,
        origin: WriteOrigin,
        write: impl FnOnce(&Self) -> Result<R, DbError>,
    ) -> Result<R, DbError> {
        self.save()?;
        self.conn().begin()?;
        let admission = self.participant_begin(self.conn().as_mut(), origin);
        if let Err(error) = admission {
            self.conn().rollback().map_err(|rollback| {
                DbError::new(
                    DbErrorKind::Closed,
                    format!("transaction admission rollback failed: {rollback}"),
                )
            })?;
            return Err(error);
        }
        self.inner.worker_transaction.set(true);
        let result = day_reactive::batch(|| {
            let value = write(self)?;
            self.save()?;
            Ok(value)
        })
        .and_then(|value| {
            // Reactions may have made additional writes while the batch drained. Commit only
            // after those writes settle, never before turn-end autosave has run.
            self.save()?;
            self.participant_commit(self.conn().as_mut(), origin)?;
            self.conn().commit()?;
            Ok(value)
        });
        self.inner.worker_transaction.set(false);
        if result.is_err() {
            self.participant_rollback();
            self.conn().rollback().map_err(|error| {
                DbError::new(
                    DbErrorKind::Closed,
                    format!("transaction rollback failed: {error}"),
                )
            })?;
            self.worker_discard_changes()?;
        }
        if result.is_ok() {
            self.participant_refresh()?;
        }
        result
    }

    #[cfg(not(target_arch = "wasm32"))]
    fn worker_read<R>(&self, read: impl FnOnce(&Self) -> Result<R, DbError>) -> Result<R, DbError> {
        self.save()?;
        self.conn().execute_batch("PRAGMA query_only = ON")?;
        self.conn().begin().map_err(|error| {
            DbError::new(
                DbErrorKind::Closed,
                format!("could not begin read snapshot: {error}"),
            )
        })?;
        let autosave = self.inner.autosave.replace(false);
        let mut result =
            day_model::with_author("worker-read", || day_reactive::batch(|| read(self)));
        let mutated = !self.inner.dirty.borrow().is_empty();
        self.conn().rollback().map_err(|error| {
            DbError::new(
                DbErrorKind::Closed,
                format!("could not end read snapshot: {error}"),
            )
        })?;
        self.conn()
            .execute_batch("PRAGMA query_only = OFF")
            .map_err(|error| {
                DbError::new(
                    DbErrorKind::Closed,
                    format!("could not restore write mode: {error}"),
                )
            })?;
        if mutated {
            self.worker_discard_changes()?;
            result = Err(DbError::driver(
                "a worker read attempted to mutate model state",
            ));
        }
        self.inner.autosave.set(autosave);
        result
    }

    #[cfg(not(target_arch = "wasm32"))]
    fn worker_discard_changes(&self) -> Result<(), DbError> {
        let autosave = self.inner.autosave.replace(false);
        *self.inner.dirty.borrow_mut() = DirtyState::default();
        self.participant_rollback();
        let result = self.refresh_resident();
        self.invalidate_relation_memos();
        if result.is_ok() {
            self.requery_all();
        }
        self.inner.autosave.set(autosave);
        result.map(|_| ()).map_err(|error| {
            DbError::new(
                DbErrorKind::Closed,
                format!("transaction cache recovery failed: {error}"),
            )
        })
    }

    /// The fold, materialized: the smallest statement list that expresses `dirty`, in
    /// first-touch order. Row values come from the caches now; the change log carried which
    /// rows and columns moved, never their contents. Reads only; [`ModelContainer::flush`]
    /// executes the list in one transaction.
    ///
    /// With `capture`, the second answer is the same work as a change set, one entry per row
    /// a statement writes (the participant's view of the flush); without it, empty.
    #[allow(clippy::type_complexity)]
    fn fold(
        &self,
        dirty: &DirtyState,
        capture: bool,
    ) -> Result<(Vec<(String, Vec<Value>)>, Vec<RowChange>), DbError> {
        let tables = self.inner.tables.borrow();
        let mut stmts: Vec<(String, Vec<Value>)> = Vec::new();
        let mut changes: Vec<RowChange> = Vec::new();
        let authors_of = |store_id: u64, key: u64| -> Vec<&'static str> {
            dirty
                .authors
                .get(&(store_id, key))
                .cloned()
                .unwrap_or_default()
        };

        // Wholesale rewrites first: upsert every resident row. (The cache is a working set;
        // rows outside it were never part of the rewrite, and deleting "the rest" would
        // delete data the rewrite never saw.)
        for store_id in &dirty.full {
            let Some(hooks) = tables.get(store_id) else {
                continue;
            };
            for (key, row) in (hooks.all_rows)() {
                stmts.push(upsert_stmt(hooks, &row));
                if capture {
                    let mut authors = dirty
                        .store_authors
                        .get(store_id)
                        .cloned()
                        .unwrap_or_default();
                    for tag in authors_of(*store_id, key) {
                        add_author(&mut authors, Some(tag));
                    }
                    changes.push(RowChange {
                        table: hooks.table,
                        key: (hooks.key_where)(key).1,
                        kind: RowChangeKind::Rewritten,
                        authors,
                    });
                }
            }
        }

        // Per-row work, into batches that can merge. Deletes of one table merge into one
        // `IN`; updates merge when they write the same columns to the same values, which is
        // what a multi-selection edit produces ("set fill on twelve shapes").
        //
        // Deletes are held apart and emitted last. Dirty order interleaves rows by when each
        // first changed, which can put a parent row's delete between its children's detach
        // updates (the first detach dirties the parent through relation upkeep), and a
        // relation column's `ON DELETE CASCADE` fires per statement, `DEFERRABLE` or not, so
        // the mid-batch delete would take every still-attached child with it (found by Day
        // Sketch's ungroup: two members detached, one row left). With inserts and updates
        // first, a row still referencing a deleted parent at delete time is one the batch
        // never detached: an orphan the cascade rule is meant to take.
        let mut batches: Vec<Batch> = Vec::new();
        let mut deletes: Vec<Batch> = Vec::new();
        // (store, statement shape, a fingerprint of the `SET` values) → the batch it joins.
        let mut open: HashMap<(u64, String, u64), usize> = HashMap::new();
        let mut open_deletes: HashMap<(u64, String, u64), usize> = HashMap::new();
        // store → the insert batch collecting its new rows.
        let mut open_inserts: HashMap<u64, usize> = HashMap::new();

        for id in &dirty.order {
            let Some(state) = dirty.rows.get(id) else {
                continue;
            };
            let (store_id, key) = *id;
            if dirty.full.contains(&store_id) {
                continue; // the resync above already covered it
            }
            let Some(hooks) = tables.get(&store_id) else {
                continue;
            };
            // A join row is addressed by a pair of columns, which no single-column `IN` can
            // express, so those keep one statement each.
            let batchable = hooks.key_cols.len() == 1;
            let mut capture_as = |kind: RowChangeKind| {
                if capture {
                    changes.push(RowChange {
                        table: hooks.table,
                        key: (hooks.key_where)(key).1,
                        kind,
                        authors: authors_of(store_id, key),
                    });
                }
            };
            match state {
                DirtyRow::Delete => {
                    capture_as(RowChangeKind::Deleted);
                    if !batchable {
                        let (clause, params) = (hooks.key_where)(key);
                        deletes.push(Batch::Single(
                            format!("DELETE FROM {} WHERE {clause}", hooks.name.sql()),
                            params,
                        ));
                        continue;
                    }
                    join_batch(&mut deletes, &mut open_deletes, store_id, None, key);
                }
                DirtyRow::Insert => {
                    if let Some(row) = (hooks.row_for)(key) {
                        capture_as(RowChangeKind::Inserted);
                        match open_inserts.get(&store_id) {
                            Some(&i) => {
                                if let Batch::Inserts { rows, .. } = &mut batches[i] {
                                    rows.push(row);
                                }
                            }
                            None => {
                                open_inserts.insert(store_id, batches.len());
                                batches.push(Batch::Inserts {
                                    store: store_id,
                                    rows: vec![row],
                                });
                            }
                        }
                    }
                }
                DirtyRow::Update(cols) => {
                    let Some(row) = (hooks.row_for)(key) else {
                        continue; // deleted since; its Delete entry handles it
                    };
                    if cols.is_empty() {
                        // A row-level replacement named no columns; write them all.
                        let (sql, params) = upsert_stmt(hooks, &row);
                        batches.push(Batch::Single(sql, params));
                        capture_as(RowChangeKind::Rewritten);
                        continue;
                    }
                    let mut sets: Vec<String> = Vec::with_capacity(cols.len());
                    let mut set_params: Vec<Value> = Vec::with_capacity(cols.len());
                    for c in cols {
                        let Some(i) = hooks.fields.iter().position(|n| n == c) else {
                            continue; // a transient field's label, never a column
                        };
                        let value = row.get(i);
                        if hooks.lazy.get(i).copied().unwrap_or(false) && value == Value::Null {
                            continue; // a stored blob the row did not rewrite: leave the bytes
                        }
                        sets.push(format!("{} = ?", ident(&hooks.columns[i])));
                        set_params.push(value);
                    }
                    if set_params.is_empty() {
                        continue; // only transient fields changed
                    }
                    if capture {
                        let written: Vec<&'static str> = cols
                            .iter()
                            .filter_map(|c| hooks.fields.iter().position(|n| n == c))
                            .map(|i| hooks.column_names[i])
                            .collect();
                        capture_as(RowChangeKind::Updated(written));
                    }
                    let clause = sets.join(", ");
                    if !batchable {
                        let (where_clause, mut where_params) = (hooks.key_where)(key);
                        let mut params = set_params;
                        params.append(&mut where_params);
                        batches.push(Batch::Single(
                            format!(
                                "UPDATE {} SET {clause} WHERE {where_clause}",
                                hooks.name.sql()
                            ),
                            params,
                        ));
                        continue;
                    }
                    join_batch(
                        &mut batches,
                        &mut open,
                        store_id,
                        Some((clause, set_params)),
                        key,
                    );
                }
            }
        }

        for batch in batches.into_iter().chain(deletes) {
            match batch {
                Batch::Single(sql, params) => stmts.push((sql, params)),
                Batch::Inserts { store, rows } => {
                    let Some(hooks) = tables.get(&store) else {
                        continue;
                    };
                    insert_stmts(hooks, rows, &mut stmts);
                }
                Batch::Keyed { store, set, keys } => {
                    let Some(hooks) = tables.get(&store) else {
                        continue;
                    };
                    materialize(hooks, set, &keys, &mut stmts);
                }
            }
        }
        Ok((stmts, changes))
    }

    // --- maintenance (docs/persistence.md) ---------------------------------------------------

    /// `VACUUM INTO`: a transactionally consistent, already-compacted snapshot, taken while
    /// the app keeps writing. Restore is an open, not a verb.
    pub fn backup_to(&self, path: &Path) -> Result<(), DbError> {
        self.save()?;
        self.conn().execute(
            "VACUUM INTO ?",
            &[Value::Text(path.to_string_lossy().into_owned())],
        )?;
        Ok(())
    }

    /// `PRAGMA integrity_check` and `PRAGMA foreign_key_check`, parsed: an empty list means
    /// the database is sound. A foreign-key violation reads
    /// `foreign key: <child> row <rowid> references missing <parent>`; the structured form is
    /// [`ModelContainer::foreign_key_check`].
    pub fn integrity_check(&self) -> Result<Vec<String>, DbError> {
        let mut findings = Vec::new();
        self.conn()
            .query("PRAGMA integrity_check", &[], &mut |row| {
                if let Ok(t) = row.get(0).as_text()
                    && t != "ok"
                {
                    findings.push(t.to_string());
                }
            })?;
        for v in self.foreign_key_check()? {
            findings.push(v.to_string());
        }
        Ok(findings)
    }

    /// `PRAGMA foreign_key_check`, parsed: every row whose foreign key names a parent that
    /// does not exist. Empty when every reference resolves. Runs on the whole file, which is
    /// what a migration's post-check and a settings-page validation both want.
    pub fn foreign_key_check(&self) -> Result<Vec<ForeignKeyViolation>, DbError> {
        Self::foreign_key_check_on(self.conn().as_mut())
    }

    fn foreign_key_check_on(
        conn: &mut dyn SqliteConnection,
    ) -> Result<Vec<ForeignKeyViolation>, DbError> {
        let mut violations = Vec::new();
        conn.query("PRAGMA foreign_key_check", &[], &mut |row| {
            violations.push(ForeignKeyViolation {
                table: row.get(0).as_text().unwrap_or("").to_string(),
                rowid: row.get(1).as_int().ok(),
                parent: row.get(2).as_text().unwrap_or("").to_string(),
                constraint: row.get(3).as_int().unwrap_or(0),
            });
        })?;
        Ok(violations)
    }

    /// Fold the WAL into the main file (`PRAGMA wal_checkpoint(TRUNCATE)`), before the OS
    /// copies it whole (device backup). The engine's own answer comes back: whether a reader
    /// kept the checkpoint from completing, and how much of the log it folded.
    pub fn checkpoint(&self) -> Result<Checkpoint, DbError> {
        let mut result = Checkpoint::default();
        self.conn()
            .query("PRAGMA wal_checkpoint(TRUNCATE)", &[], &mut |row| {
                result = Checkpoint {
                    busy: row.get(0).as_int().unwrap_or(0) != 0,
                    log_frames: row.get(1).as_int().unwrap_or(-1),
                    checkpointed_frames: row.get(2).as_int().unwrap_or(-1),
                };
            })?;
        Ok(result)
    }

    pub fn vacuum(&self) -> Result<(), DbError> {
        self.save()?;
        self.conn().execute("VACUUM", &[]).map(|_| ())
    }

    /// Re-encrypt in place under a new key (`PRAGMA rekey`; feature `cipher`).
    #[cfg(feature = "cipher")]
    pub fn rekey(&self, new: Secret) -> Result<(), DbError> {
        self.save()?;
        let quoted = new.reveal().replace('\'', "''");
        // The PRAGMA answers with a status row; consume it as a query.
        self.conn()
            .query(&format!("PRAGMA rekey = '{quoted}'"), &[], &mut |_| {})
    }

    /// Write an encrypted copy at `path` through SQLCipher's conversion path (`ATTACH` +
    /// `sqlcipher_export`); plaintext↔encrypted cannot happen in place.
    #[cfg(feature = "cipher")]
    pub fn encrypt_to(&self, path: &Path, key: Secret) -> Result<(), DbError> {
        self.export_to(path, Some(key))
    }

    /// Write a plaintext copy at `path`, same mechanism with an empty key.
    #[cfg(feature = "cipher")]
    pub fn decrypt_to(&self, path: &Path) -> Result<(), DbError> {
        self.export_to(path, None)
    }

    #[cfg(feature = "cipher")]
    fn export_to(&self, path: &Path, key: Option<Secret>) -> Result<(), DbError> {
        self.save()?;
        let quoted_path = path.to_string_lossy().replace('\'', "''");
        let quoted_key = key
            .as_ref()
            .map(|k| k.reveal().replace('\'', "''"))
            .unwrap_or_default();
        let mut conn = self.conn();
        conn.execute(
            &format!("ATTACH DATABASE '{quoted_path}' AS day_export KEY '{quoted_key}'"),
            &[],
        )?;
        conn.query("SELECT sqlcipher_export('day_export')", &[], &mut |_| {})
            .and_then(|_| conn.execute("DETACH DATABASE day_export", &[]).map(|_| ()))
    }

    /// Total size in bytes (page_count × page_size).
    pub fn size_bytes(&self) -> Result<u64, DbError> {
        let mut pages = 0i64;
        let mut page_size = 0i64;
        self.conn().query("PRAGMA page_count", &[], &mut |row| {
            pages = row.get(0).as_int().unwrap_or(0);
        })?;
        self.conn().query("PRAGMA page_size", &[], &mut |row| {
            page_size = row.get(0).as_int().unwrap_or(0);
        })?;
        Ok((pages * page_size).max(0) as u64)
    }
}

/// The multi-key `WHERE` builder for a hooks entry: `key IN (…)` for single-column keys, an OR
/// list of pair clauses for join tables.
/// `a, b, c` as a quoted SELECT list or insert column list.
pub(crate) fn column_list<S: AsRef<str>>(columns: &[S]) -> String {
    columns
        .iter()
        .map(|c| ident(c.as_ref()))
        .collect::<Vec<_>>()
        .join(", ")
}

/// `prefix.a, prefix.b`: the same list through a table alias or a trigger's `new`/`old`.
pub(crate) fn prefixed_list<S: AsRef<str>>(prefix: &str, columns: &[S]) -> String {
    columns
        .iter()
        .map(|c| format!("{prefix}.{}", ident(c.as_ref())))
        .collect::<Vec<_>>()
        .join(", ")
}

/// The two halves of an FTS update trigger's gate: the `UPDATE OF` column list (the key and
/// every indexed column, once each) and the `WHEN` expression that is true only if one of
/// them actually changed (`IS NOT`, so a NULL on either side compares like any value).
fn fts_update_guard(key: &str, fts_columns: &[&str]) -> (String, String) {
    let mut cols: Vec<&str> = vec![key];
    cols.extend(fts_columns.iter().copied().filter(|c| *c != key));
    let update_of = column_list(&cols);
    let changed = cols
        .iter()
        .map(|c| {
            let c = ident(c);
            format!("new.{c} IS NOT old.{c}")
        })
        .collect::<Vec<_>>()
        .join(" OR ");
    (update_of, changed)
}

// ---------------------------------------------------------------------------
// Schema comparison: the declaration against the file
// ---------------------------------------------------------------------------

/// One column as the model declares it, with the relation-contributed foreign key resolved.
struct DeclaredColumn {
    def: ColumnDef,
    /// Position in `Model::COLUMNS`, which is also the position in `Model::default_row()`.
    index: usize,
    pk: bool,
    fk: Option<DeclaredFk>,
}

/// A declared relation's foreign key on a child column.
struct DeclaredFk {
    parent_sql: String,
    parent_bare: &'static str,
    parent_key: &'static str,
    rule: DeleteRule,
}

impl DeclaredFk {
    /// The column constraint, deferred so within-transaction statement order (a cascade's
    /// children, an undo's re-inserts) never trips it.
    fn clause(&self) -> String {
        format!(
            " REFERENCES {}({}) ON DELETE {} DEFERRABLE INITIALLY DEFERRED",
            self.parent_sql,
            ident(self.parent_key),
            self.rule.sql()
        )
    }
}

/// An index the container owns, as it is declared.
struct DeclaredIndex {
    name: String,
    columns: Vec<String>,
    unique: bool,
}

/// A column as `PRAGMA table_info` and `PRAGMA foreign_key_list` report it.
struct FileColumn {
    name: String,
    /// Upper-cased declared type (`INTEGER`, `TEXT`, …).
    decl_type: String,
    not_null: bool,
    pk: bool,
    fk: Option<FileFk>,
}

struct FileFk {
    parent: String,
    parent_key: String,
    on_delete: String,
}

/// An index as `PRAGMA index_list` and `index_info` report it. `origin` is `c` for a
/// `CREATE INDEX`, `u` for an inline `UNIQUE`, `pk` for the primary key's.
struct FileIndex {
    name: String,
    unique: bool,
    origin: String,
    columns: Vec<String>,
}

struct FileSchema {
    columns: Vec<FileColumn>,
    indexes: Vec<FileIndex>,
}

/// What `lightweight_migrate` does in place: positions in `COLUMNS` to add, file columns to
/// drop, Day-owned index names to drop, and declared-unique columns that need a unique index.
#[derive(Default, Clone)]
struct LightweightPlan {
    add: Vec<usize>,
    drop: Vec<String>,
    drop_indexes: Vec<String>,
    unique_indexes: Vec<&'static str>,
}

/// The comparison's verdict for an existing table.
enum SchemaDelta {
    Lightweight(LightweightPlan),
    Rebuild,
}

/// Whether an index name is one the container writes for `table` (`day_idx_`, `day_uidx_`).
fn is_day_index(name: &str, table: &str) -> bool {
    name.starts_with(&format!("day_idx_{table}_"))
        || name.starts_with(&format!("day_uidx_{table}_"))
}

/// `PRAGMA [schema.]name("arg")`.
fn pragma_sql(schema: Option<&str>, name: &str, arg: &str) -> String {
    match schema {
        Some(s) => format!("PRAGMA {}.{name}({})", ident(s), ident(arg)),
        None => format!("PRAGMA {name}({})", ident(arg)),
    }
}

/// A [`Value`] as an SQL literal, for the places a bound parameter cannot go (a column's
/// `DEFAULT`, a copy's `SELECT` list): text single-quoted with `'` doubled, a blob as
/// `X'…'`, numbers as themselves. A non-finite real has no literal and is refused.
fn sql_literal(v: &Value) -> Result<String, DbError> {
    Ok(match v {
        Value::Null => "NULL".into(),
        Value::Int(i) => i.to_string(),
        Value::Real(r) if r.is_finite() => format!("{r:?}"),
        Value::Real(r) => {
            return Err(DbError::new(
                DbErrorKind::Schema,
                format!("{r} has no SQL literal to use as a column default"),
            ));
        }
        Value::Text(t) => format!("'{}'", t.replace('\'', "''")),
        Value::Blob(b) => {
            let mut s = String::with_capacity(b.len() * 2 + 3);
            s.push_str("X'");
            for byte in b {
                s.push_str(&format!("{byte:02x}"));
            }
            s.push('\'');
            s
        }
    })
}

fn keys_where_of(hooks: &TableHooks) -> KeysWhere {
    if hooks.key_cols.len() == 1 {
        let col = ident(&hooks.key_cols[0]);
        Rc::new(move |keys: &[u64]| {
            let marks = vec!["?"; keys.len()].join(", ");
            (
                format!("{col} IN ({marks})"),
                keys.iter().map(|k| key_param(*k)).collect(),
            )
        })
    } else {
        let key_where = hooks.key_where.clone();
        Rc::new(move |keys: &[u64]| {
            let mut clauses = Vec::with_capacity(keys.len());
            let mut params = Vec::with_capacity(keys.len() * 2);
            for k in keys {
                let (c, mut p) = key_where(*k);
                clauses.push(format!("({c})"));
                params.append(&mut p);
            }
            (clauses.join(" OR "), params)
        })
    }
}

/// One statement the fold will write, before the mergeable ones have merged.
enum Batch {
    /// Stands alone: a row-level rewrite (its values are the row's own), or a row addressed
    /// by a composite key, which no single-column `IN` can express.
    Single(String, Vec<Value>),
    /// One table's inserted rows: a multi-row upsert, chunked by the parameter ceiling.
    Inserts { store: u64, rows: Vec<Vec<Value>> },
    /// Same table, same operation, same values: one statement per chunk of keys.
    Keyed {
        store: u64,
        /// The `SET` clause and its parameters for an update; `None` for a delete.
        set: Option<(String, Vec<Value>)>,
        keys: Vec<u64>,
    },
}

/// SQLite's conservative bound-parameter ceiling. Modern builds allow far more, but a
/// `system` engine may be an older one, and chunking costs nothing to write.
const MAX_BOUND_PARAMS: usize = 900;

/// Add `key` to the batch sharing this table, clause and values, or open a new one.
///
/// The slot key separates a delete from an update (their clauses differ), and separates
/// updates writing different values, which must stay different statements. Grouping is by
/// hash so a large flush stays linear; the values are compared before merging, so a hash
/// collision costs a second statement rather than a wrong one.
fn join_batch(
    batches: &mut Vec<Batch>,
    open: &mut HashMap<(u64, String, u64), usize>,
    store: u64,
    set: Option<(String, Vec<Value>)>,
    key: u64,
) {
    let clause = set.as_ref().map(|(c, _)| c.clone()).unwrap_or_default();
    let print = set.as_ref().map(|(_, p)| fingerprint(p)).unwrap_or(0);
    let slot = (store, clause, print);
    if let Some(&i) = open.get(&slot)
        && let Batch::Keyed {
            set: existing,
            keys,
            ..
        } = &mut batches[i]
        && existing.as_ref().map(|(_, p)| p.as_slice()) == set.as_ref().map(|(_, p)| p.as_slice())
    {
        keys.push(key);
        return;
    }
    open.insert(slot, batches.len());
    batches.push(Batch::Keyed {
        store,
        set,
        keys: vec![key],
    });
}

/// A cheap order-sensitive hash of bound values, for grouping identical updates. Equality is
/// still checked before two rows share a statement; this only decides who to compare with.
fn fingerprint(values: &[Value]) -> u64 {
    let mut h: u64 = 0xcbf2_9ce4_8422_2325;
    let mut eat = |bytes: &[u8]| {
        for b in bytes {
            h ^= *b as u64;
            h = h.wrapping_mul(0x1000_0000_01b3);
        }
    };
    for v in values {
        match v {
            Value::Null => eat(&[0]),
            Value::Int(i) => {
                eat(&[1]);
                eat(&i.to_le_bytes());
            }
            // Bit pattern, not numeric value: two values that hash apart are only compared
            // separately, never merged wrongly.
            Value::Real(r) => {
                eat(&[2]);
                eat(&r.to_bits().to_le_bytes());
            }
            Value::Text(t) => {
                eat(&[3]);
                eat(t.as_bytes());
            }
            Value::Blob(b) => {
                eat(&[4]);
                eat(b);
            }
        }
    }
    h
}

/// Write a batch out: the familiar `= ?` form for one key, chunked `IN` statements for more.
fn materialize(
    hooks: &TableHooks,
    set: Option<(String, Vec<Value>)>,
    keys: &[u64],
    out: &mut Vec<(String, Vec<Value>)>,
) {
    // One key keeps the `= ?` form: it is the common case by far, it reads plainly in a
    // trace, and it is one more statement shape the cache can hold.
    let table = hooks.name.sql();
    if keys.len() == 1 {
        let (where_clause, where_params) = (hooks.key_where)(keys[0]);
        match set {
            Some((clause, mut params)) => {
                params.extend(where_params);
                out.push((
                    format!("UPDATE {table} SET {clause} WHERE {where_clause}"),
                    params,
                ));
            }
            None => out.push((
                format!("DELETE FROM {table} WHERE {where_clause}"),
                where_params,
            )),
        }
        return;
    }

    let key_col = ident(&hooks.key_cols[0]);
    let set_len = set.as_ref().map(|(_, p)| p.len()).unwrap_or(0);
    let cap = MAX_BOUND_PARAMS.saturating_sub(set_len).max(1);
    for chunk in keys.chunks(cap) {
        let mut params: Vec<Value> = Vec::with_capacity(set_len + chunk.len());
        if let Some((_, set_params)) = &set {
            params.extend(set_params.iter().cloned());
        }
        params.extend(chunk.iter().map(|k| key_param(*k)));
        let marks = vec!["?"; chunk.len()].join(", ");
        let sql = match &set {
            Some((clause, _)) => {
                format!("UPDATE {table} SET {clause} WHERE {key_col} IN ({marks})")
            }
            None => format!("DELETE FROM {table} WHERE {key_col} IN ({marks})"),
        };
        out.push((sql, params));
    }
}

/// The row select list: every column, with a lazy one named as a literal `NULL` so the
/// row's shape stays the same while the bytes stay in the file.
fn select_list(hooks: &TableHooks) -> String {
    hooks
        .columns
        .iter()
        .enumerate()
        .map(|(i, c)| {
            if hooks.lazy.get(i).copied().unwrap_or(false) {
                "NULL".to_string()
            } else {
                ident(c)
            }
        })
        .collect::<Vec<_>>()
        .join(", ")
}

/// One table's inserted rows as multi-row upserts: as many rows per statement as the
/// parameter ceiling allows, so a thousand new rows are a few statements rather than a
/// thousand.
fn insert_stmts(hooks: &TableHooks, rows: Vec<Vec<Value>>, out: &mut Vec<(String, Vec<Value>)>) {
    let per_row = hooks.columns.len().max(1);
    let per_stmt = (MAX_BOUND_PARAMS / per_row).max(1);
    for chunk in rows.chunks(per_stmt) {
        let sql = upsert_sql(hooks, chunk.len());
        let params: Vec<Value> = chunk.iter().flatten().cloned().collect();
        out.push((sql, params));
    }
}

fn upsert_stmt(hooks: &TableHooks, row: &[Value]) -> (String, Vec<Value>) {
    (upsert_sql(hooks, 1), row.to_vec())
}

/// `INSERT … VALUES (…), (…) ON CONFLICT(key) DO UPDATE SET …` for `rows` rows.
fn upsert_sql(hooks: &TableHooks, rows: usize) -> String {
    let cols = column_list(&hooks.columns);
    let one = format!("({})", vec!["?"; hooks.columns.len()].join(", "));
    let marks = vec![one.as_str(); rows.max(1)].join(", ");
    // A true upsert, not `INSERT OR REPLACE`: the conflict path fires `UPDATE` triggers, which
    // is what keeps the generated FTS/R*Tree shadows in sync (`OR REPLACE`'s implicit delete
    // skips `AFTER DELETE` triggers unless recursive_triggers is on). A lazy column keeps its
    // stored bytes when the row arrives without new ones (`NULL`).
    let sets = hooks
        .columns
        .iter()
        .enumerate()
        .filter(|(_, c)| !hooks.key_cols.contains(c))
        .map(|(i, c)| {
            if hooks.lazy.get(i).copied().unwrap_or(false) {
                format!("{0} = COALESCE(excluded.{0}, {0})", ident(c))
            } else {
                format!("{0} = excluded.{0}", ident(c))
            }
        })
        .collect::<Vec<_>>()
        .join(", ");
    let conflict = if sets.is_empty() {
        "DO NOTHING".to_string()
    } else {
        format!("DO UPDATE SET {sets}")
    };
    format!(
        "INSERT INTO {} ({cols}) VALUES {marks} ON CONFLICT({}) {conflict}",
        hooks.name.sql(),
        column_list(&hooks.key_cols)
    )
}

impl Drop for ContainerInner {
    fn drop(&mut self) {
        if let Some(sink) = self.sink.take() {
            day_model::remove_change_sink(sink);
        }
    }
}

// ---------------------------------------------------------------------------
// Live queries (docs/persistence.md; queries.rs holds the compiler and the diff)
// ---------------------------------------------------------------------------

/// What a query's consumers have not yet seen. `Deltas` can animate a list row by row;
/// `Reload` means the whole set moved (a fetch swap, a tangled requery) and a reload is
/// the accurate answer.
#[derive(Clone, Debug, PartialEq)]
pub enum QueryEvents {
    None,
    Deltas(Vec<Delta>),
    Reload,
}

impl QueryEvents {
    fn push(&mut self, deltas: &[Delta]) {
        match self {
            QueryEvents::None => *self = QueryEvents::Deltas(deltas.to_vec()),
            QueryEvents::Deltas(d) => d.extend_from_slice(deltas),
            QueryEvents::Reload => {}
        }
    }
    fn reload(&mut self) {
        *self = QueryEvents::Reload;
    }
}

/// What one relation crossing subscribes a query to, precomputed at install (and at every
/// fetch swap) so the change sink's staleness check is a few comparisons.
struct RelWatch {
    /// The store on the far side of the crossing (the related table's cache).
    store: u64,
    /// The join membership store, when the crossing is a many-to-many; every link, unlink
    /// and reposition there is a membership change.
    join_store: Option<u64>,
    /// Field names on the far store whose write is a membership change (the foreign key, the
    /// order field) even though no predicate reads them.
    fields: Vec<&'static str>,
    /// Column names of the far table the inner predicate reads.
    columns: Vec<&'static str>,
}

struct QueryState {
    store_id: u64,
    table: &'static str,
    /// The relation subscriptions, recomputed when the fetch is swapped.
    watches: RefCell<Vec<RelWatch>>,
    /// Extra local columns whose write is a membership change (a `One` column crossed by the
    /// query's own table).
    local_extra: RefCell<Vec<&'static str>>,
    set: RefCell<ResultSet>,
    /// Bumped whenever the result set changes; `ids()`/`count()` track it.
    version: day_reactive::Signal<u64>,
    pending: RefCell<QueryEvents>,
    /// A dependency-touching change arrived; the answer re-derives after the flush.
    needs_sql: Cell<bool>,
    // Reading the last committed result must not consume the post-commit invalidation.
    pending_commit: Cell<bool>,
    error: day_reactive::Signal<Option<DbError>>,
    /// `query_raw` only: the statement and the tables whose flush re-runs it.
    raw: Option<RawQuery>,
    /// A count-shaped query: `count` is the answer, the id set stays empty, and requeries
    /// run `SELECT COUNT(*)`, the badge query, O(1) memory at any result size.
    count_only: bool,
    count: Cell<usize>,
}

struct RawQuery {
    sql: String,
    params: Vec<Value>,
    tables: Vec<String>,
}

/// A live, typed result set over one model's table: ids only, answered by the engine and
/// kept current by dependency-gated requeries. Rows stay lazy: fault the ones you show
/// ([`Query::materialize`], or a list source doing it for you). Clone shares the same set.
pub struct Query<M: Model> {
    state: Rc<QueryState>,
    container: ModelContainer,
    _p: std::marker::PhantomData<fn() -> M>,
}

impl<M: Model> Clone for Query<M> {
    fn clone(&self) -> Self {
        Query {
            state: self.state.clone(),
            container: self.container.clone(),
            _p: std::marker::PhantomData,
        }
    }
}

impl<M: Model> Query<M> {
    /// This query's last read failure. A failed read preserves its previous result set.
    pub fn error(&self) -> day_reactive::Signal<Option<DbError>> {
        self.state.error
    }

    /// Explicitly retry a query after a transient read failure (also useful after external SQL).
    pub fn refresh(&self) {
        self.state.needs_sql.set(true);
        self.refresh_if_stale();
    }

    /// Checked form of `ids`, for imports and commands that must not mistake failure for absence.
    pub fn try_ids(&self) -> Result<Vec<ModelId<M>>, DbError> {
        let ids = self.ids();
        match self.state.error.get() {
            Some(e) => Err(e),
            None => Ok(ids),
        }
    }

    /// A checked snapshot for non-UI work, fetched in batches. UI lists should use the query
    /// itself as their row source so they only materialize the visible working set.
    pub fn try_collect(&self) -> Result<Vec<M>, DbError> {
        let ids = self.try_ids()?;
        let mut rows = Vec::with_capacity(ids.len());
        for chunk in ids.chunks(64) {
            self.container
                .ensure_resident::<M>(&chunk.iter().map(|id| id.handle()).collect::<Vec<_>>())?;
            for id in chunk {
                if let Some(row) = self.container.try_get::<M>(*id)?
                    && let Some(value) = row.with_value_untracked(|v| v.cloned())
                {
                    rows.push(value);
                }
            }
        }
        Ok(rows)
    }

    /// The result ids, typed and in query order, as a tracked read: the caller re-runs when
    /// the set changes, and only then.
    pub fn ids(&self) -> Vec<ModelId<M>> {
        self.refresh_if_stale();
        let _ = self.state.version.get();
        self.state
            .set
            .borrow()
            .ids()
            .iter()
            .map(|h| ModelId::from_handle(*h))
            .collect()
    }

    /// The result count, tracked like [`Query::ids`].
    pub fn count(&self) -> usize {
        self.refresh_if_stale();
        let _ = self.state.version.get();
        self.state.set.borrow().ids().len()
    }

    /// The first result, tracked.
    pub fn first(&self) -> Option<ModelId<M>> {
        self.refresh_if_stale();
        let _ = self.state.version.get();
        self.state
            .set
            .borrow()
            .ids()
            .first()
            .map(|h| ModelId::from_handle(*h))
    }

    /// Tracked membership test.
    pub fn contains(&self, id: impl Into<ModelId<M>>) -> bool {
        self.refresh_if_stale();
        let _ = self.state.version.get();
        self.state.set.borrow().ids().contains(&id.into().handle())
    }

    /// Untracked snapshot: reactively silent, but still current (pending staleness settles
    /// first, like every other read).
    pub fn ids_untracked(&self) -> Vec<ModelId<M>> {
        self.refresh_if_stale();
        self.state
            .set
            .borrow()
            .ids()
            .iter()
            .map(|h| ModelId::from_handle(*h))
            .collect()
    }

    /// Bring this window of the result into the cache: what a list binding calls for the
    /// rows it is about to show, batched into one `SELECT`.
    pub fn materialize(&self, range: std::ops::Range<usize>) {
        let keys: Vec<u64> = {
            let set = self.state.set.borrow();
            let ids = set.ids();
            let end = range.end.min(ids.len());
            let start = range.start.min(end);
            ids[start..end].to_vec()
        };
        if let Err(e) = self.container.ensure_resident::<M>(&keys) {
            self.container.inner.error.set(Some(e.to_string()));
        }
    }

    /// Swap the fetch (a changed filter or sort): requeries and reloads consumers. No-op when
    /// equal to the current one, so a `query_fn` closure can re-run cheaply.
    pub fn set_fetch(&self, fetch: Fetch) {
        if *self.state.set.borrow().fetch() == fetch {
            return;
        }
        self.container.rewire_watches(&self.state, &fetch);
        {
            let mut set = self.state.set.borrow_mut();
            *set = ResultSet::new(fetch);
        }
        // Resolve once pending statements land; mid-turn the flush has not run yet.
        self.state.needs_sql.set(true);
        self.state
            .pending_commit
            .set(!self.container.inner.dirty.borrow().is_empty());
        self.refresh_if_stale();
        self.state.pending.borrow_mut().reload();
        self.bump();
    }

    /// Drain what changed since the last call: the list source's feed. Pending staleness
    /// settles first, so a drain right after an edit already narrates it.
    pub fn take_events(&self) -> QueryEvents {
        self.refresh_if_stale();
        std::mem::replace(&mut *self.state.pending.borrow_mut(), QueryEvents::None)
    }

    /// A dependency-touching change arrived this turn and the flush has not run yet: settle
    /// it now. With autosave the pending statements flush (which requeries everything stale);
    /// with autosave off the query re-derives against the last save; the file is the only
    /// thing that can answer it.
    fn refresh_if_stale(&self) {
        if !self.state.needs_sql.get() {
            return;
        }
        if self.container.inner.autosave.get() {
            let _ = self.container.save();
        }
        if self.state.needs_sql.replace(false) {
            self.container.requery(&self.state);
        }
    }

    fn bump(&self) {
        self.state
            .version
            .set(self.state.version.get_untracked().wrapping_add(1));
    }
}

/// Builder for a [`Query`]: `container.query::<Trip>().filter(…).sort(…).live()`.
pub struct QueryBuilder<'c, M: Model> {
    container: &'c ModelContainer,
    fetch: Fetch,
    _p: std::marker::PhantomData<fn() -> M>,
}

impl<M: Model> QueryBuilder<'_, M> {
    pub fn filter(mut self, p: Pred) -> Self {
        self.fetch = self.fetch.filter(p);
        self
    }
    pub fn sort(mut self, s: Sort) -> Self {
        self.fetch = self.fetch.sort(s);
        self
    }
    pub fn limit(mut self, n: usize) -> Self {
        self.fetch = self.fetch.limit(n);
        self
    }
    /// Run the fetch and keep it live against the change log.
    pub fn live(self) -> Query<M> {
        self.container.install_query::<M>(self.fetch, None)
    }

    /// Keep only the count live, the badge form: no id vector, one `SELECT COUNT(*)` per
    /// requery, the same dependency gating.
    pub fn live_count(self) -> CountQuery<M> {
        CountQuery {
            state: self.container.install_state::<M>(self.fetch, None, true),
            container: self.container.clone(),
            _p: std::marker::PhantomData,
        }
    }
}

/// A live count over one model's table, the badge query: `SELECT COUNT(*)` behind the same
/// dependency-gated staleness as [`Query`], holding no id vector, so a count over a
/// million-row result costs O(1) memory. Clone shares the same state.
pub struct CountQuery<M: Model> {
    state: Rc<QueryState>,
    container: ModelContainer,
    _p: std::marker::PhantomData<fn() -> M>,
}

impl<M: Model> Clone for CountQuery<M> {
    fn clone(&self) -> Self {
        CountQuery {
            state: self.state.clone(),
            container: self.container.clone(),
            _p: std::marker::PhantomData,
        }
    }
}

impl<M: Model> CountQuery<M> {
    /// The last read error, independently of the last successful count.
    pub fn error(&self) -> day_reactive::Signal<Option<DbError>> {
        self.state.error
    }
    /// Checked count for operations that require a successful read.
    pub fn try_get(&self) -> Result<usize, DbError> {
        let n = self.get();
        match self.state.error.get() {
            Some(e) => Err(e),
            None => Ok(n),
        }
    }
    /// Retry after a transient read error.
    pub fn refresh(&self) {
        self.state.needs_sql.set(true);
        self.refresh_if_stale();
    }

    /// The count, as a tracked read: the caller re-runs when it changes, and only then.
    pub fn get(&self) -> usize {
        self.refresh_if_stale();
        let _ = self.state.version.get();
        self.state.count.get()
    }

    /// Untracked snapshot: reactively silent, still current.
    pub fn get_untracked(&self) -> usize {
        self.refresh_if_stale();
        self.state.count.get()
    }

    /// Swap the fetch (a changed filter): re-counts. No-op when equal, so a `count_fn`
    /// closure can re-run cheaply.
    pub fn set_fetch(&self, fetch: Fetch) {
        if *self.state.set.borrow().fetch() == fetch {
            return;
        }
        self.container.rewire_watches(&self.state, &fetch);
        *self.state.set.borrow_mut() = ResultSet::new(fetch);
        self.state.needs_sql.set(true);
        self.state
            .pending_commit
            .set(!self.container.inner.dirty.borrow().is_empty());
        self.refresh_if_stale();
    }

    fn refresh_if_stale(&self) {
        if !self.state.needs_sql.get() {
            return;
        }
        if self.container.inner.autosave.get() {
            let _ = self.container.save();
        }
        if self.state.needs_sql.replace(false) {
            self.container.requery(&self.state);
        }
    }
}

/// A fallback row: the key plus the dependency columns the fallback `SELECT` carried.
struct FallbackRow<'a> {
    cols: &'a [&'static str],
    /// values[0] is the key; values[1..] align with `cols`.
    values: &'a [Value],
}

impl RowView for FallbackRow<'_> {
    fn col(&self, c: &str) -> Option<Value> {
        self.cols
            .iter()
            .position(|n| *n == c)
            .and_then(|i| self.values.get(i + 1).cloned())
    }
}

impl ModelContainer {
    /// Start a typed query over `M`'s rows. Panics (like [`ModelContainer::cache`]) if `M` is
    /// not in this container's `schema!`, a wiring bug worth stopping on.
    pub fn query<M: Model>(&self) -> QueryBuilder<'_, M> {
        let _ = self.cache::<M>();
        QueryBuilder {
            container: self,
            fetch: Fetch::new(),
            _p: std::marker::PhantomData,
        }
    }

    /// The reactive-fetch form: `f` is a computation, so a query whose fetch depends on signals
    /// (a search term, a filter toggle) re-derives itself when they change.
    pub fn query_fn<M: Model>(&self, f: impl Fn() -> Fetch + 'static) -> Query<M> {
        let q = self.install_query::<M>(f(), None);
        let q2 = q.clone();
        day_reactive::bind(f, move |fetch| q2.set_fetch(fetch.clone()));
        q
    }

    /// The reactive-fetch count: a badge whose fetch depends on signals (the "Today" cutoff,
    /// a filter toggle) re-counts itself when they change.
    pub fn count_fn<M: Model>(&self, f: impl Fn() -> Fetch + 'static) -> CountQuery<M> {
        let q = CountQuery::<M> {
            state: self.install_state::<M>(f(), None, true),
            container: self.clone(),
            _p: std::marker::PhantomData,
        };
        let q2 = q.clone();
        day_reactive::bind(f, move |fetch| q2.set_fetch(fetch.clone()));
        q
    }

    /// Raw SQL, declared: a read-only SELECT returning ids, re-run whenever a flush touches
    /// one of the named tables. The price of the escape hatch is whole-query invalidation.
    pub fn query_raw<M: Model>(
        &self,
        sql: impl Into<String>,
        params: Vec<Value>,
        tables: &[&str],
    ) -> Query<M> {
        self.install_query::<M>(
            Fetch::new().filter(Pred::Raw(String::new(), Vec::new())),
            Some(RawQuery {
                sql: sql.into(),
                params,
                tables: tables.iter().map(|s| s.to_string()).collect(),
            }),
        )
    }

    /// Opt into undo: One history over every store this container manages, `levels` deep.
    /// Undo/redo replay flows through the same change pipeline as the user's edits, so
    /// autosave writes the inverse statements and live queries hear rows come back. Call it
    /// once, after open; clear it on migration (`UndoStack::clear`). While a stack is
    /// installed, deletes materialize the rows they remove (a cascade included) so the
    /// history can restore them.
    pub fn undo(&self, levels: usize) -> day_model::UndoStack {
        let stack = day_model::UndoStack::new(levels);
        for hooks in self.inner.tables.borrow().values() {
            (hooks.watch_undo)(&stack);
        }
        stack
    }

    /// The driver's connection, directly, for maintenance, imports, or an extension's
    /// statements. Pending changes flush first; writes made here bypass the change log, so
    /// call [`ModelContainer::rescan`] afterward if they touched Day's tables.
    ///
    /// # Panics
    /// Panics if the pending save fails. Use [`ModelContainer::try_with_connection`] when
    /// the caller needs to handle storage errors.
    pub fn with_connection<R>(&self, f: impl FnOnce(&mut dyn SqliteConnection) -> R) -> R {
        self.save().expect(
            "pending persistence save failed; use try_with_connection to handle storage errors",
        );
        f(self.conn().as_mut())
    }

    /// Flush pending edits before accessing the connection. The closure is never run if
    /// that save fails; its own error is returned unchanged.
    pub fn try_with_connection<R>(
        &self,
        f: impl FnOnce(&mut dyn SqliteConnection) -> Result<R, DbError>,
    ) -> Result<R, DbError> {
        self.save()?;
        f(self.conn().as_mut())
    }

    /// Re-read the resident rows from the file and re-run every query: the recovery from
    /// writes that bypassed the change log ([`ModelContainer::with_connection`], another
    /// process). O(working set + query results), never O(table).
    pub fn rescan(&self) -> Result<(), DbError> {
        self.save()?;
        self.inner.blob_memo.borrow_mut().clear();
        self.refresh_resident()?;
        self.invalidate_relation_memos();
        self.requery_all();
        // The cache now equals the file; a later check_external should not re-merge for
        // whatever external commits this refresh already picked up.
        if self.inner.caps.external_changes {
            self.inner.data_version.set(self.file_data_version()?);
        }
        Ok(())
    }

    /// Attach another SQLite file under `alias` and bring `schema`'s models (every one
    /// declared `external = "alias"`) into this container: their tables are read as they
    /// are, with no DDL, migration, or fingerprint, through the same caches, queries, and
    /// lists as the container's own. Writes to them fail at flush (the file is attached
    /// read-only where the engine honors `mode=ro`), which is the contract: the other
    /// database has its own owner.
    ///
    /// Calling it again with the same alias swaps the file: the old one is detached, every
    /// resident row of its models dropped, and every live query re-run: the shape a
    /// downloaded catalog update takes.
    pub fn attach_database(&self, alias: &str, path: &str, schema: Schema) -> Result<(), DbError> {
        if alias.is_empty() || !alias.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
            return Err(DbError::new(
                DbErrorKind::Unsupported,
                format!("attach_database: {alias:?} is not a plain SQL schema name"),
            ));
        }
        let held = self.inner.attached.borrow().iter().any(|a| a == alias);
        if held {
            self.detach_database(alias)?;
        }
        // Flush first: a DETACH/ATTACH pair inside an open write transaction is refused.
        if !self.inner.dirty.borrow().is_empty() {
            self.save()?;
        }
        // `file:` URIs carry the read-only mode; a driver without URI filenames (the web
        // worker) takes the bare path and relies on nobody writing.
        let uri = if path.starts_with("file:") || path.contains("://") {
            path.to_string()
        } else {
            format!("file:{}?mode=ro", path.replace('?', "%3F"))
        };
        let attach = |target: &str| -> Result<(), DbError> {
            self.conn().execute(
                &format!("ATTACH DATABASE ? AS {}", ident(alias)),
                &[Value::Text(target.to_string())],
            )?;
            Ok(())
        };
        if let Err(uri_err) = attach(&uri) {
            attach(path).map_err(|_| uri_err)?;
        }
        self.inner.attached.borrow_mut().push(alias.to_string());
        let Schema {
            installers, wirers, ..
        } = schema;
        for install in installers {
            install(self)?;
        }
        for wire in wirers {
            wire(self)?;
        }
        self.rescan()
    }

    /// Detach a database [`ModelContainer::attach_database`] holds, dropping every resident
    /// row of its models. Their stores stay registered (empty), so a query over them answers
    /// nothing until the alias is attached again.
    pub fn detach_database(&self, alias: &str) -> Result<(), DbError> {
        let position = self.inner.attached.borrow().iter().position(|a| a == alias);
        let Some(position) = position else {
            return Ok(());
        };
        if !self.inner.dirty.borrow().is_empty() {
            self.save()?;
        }
        self.inner.blob_memo.borrow_mut().clear();
        type Doomed = Vec<(Rc<dyn Fn() -> Vec<u64>>, EvictFn)>;
        let doomed: Doomed = self
            .inner
            .tables
            .borrow()
            .values()
            .filter(|h| h.name.schema == Some(alias))
            .map(|h| (h.resident_keys.clone(), h.evict.clone()))
            .collect();
        for (keys, evict) in &doomed {
            let resident = keys();
            let _ = evict(&resident, resident.len());
        }
        self.conn()
            .execute(&format!("DETACH DATABASE {}", ident(alias)), &[])?;
        self.inner.attached.borrow_mut().remove(position);
        self.rescan()
    }

    /// Look for other connections' committed writes (another process, a sync engine, a CLI)
    /// and merge what changed. Detection is one `PRAGMA data_version` (the counter moves only
    /// when another connection commits, never for this one's own writes), so this is cheap
    /// enough to wire to app foreground, window focus, or a timer.
    ///
    /// When the counter moved, pending local edits flush first; then the resident rows are
    /// re-read and diffed: changed fields announce per column, disappearances take the
    /// structural path, every live query re-derives, all authored
    /// [`ModelContainer::EXTERNAL_AUTHOR`], so the autosave fold declines the echo and an
    /// installed undo stack skips them (another author's writes are not the user's history).
    /// Rows that arrived elsewhere become visible through the re-run queries and fault in
    /// like any other row. A row another connection rewrote arrives whole, so its
    /// `#[model(transient)]` fields reset to their defaults, exactly as at fault.
    ///
    /// Returns whether anything arrived. On a driver without detection
    /// ([`Capabilities::external_changes`]) this is `Ok(false)`; writes made
    /// through [`ModelContainer::with_connection`] are this connection's own and stay
    /// [`ModelContainer::rescan`]'s job.
    pub fn check_external(&self) -> Result<bool, DbError> {
        if !self.inner.caps.external_changes {
            return Ok(false);
        }
        let Some(current) = self.file_data_version()? else {
            return Ok(false);
        };
        if self.inner.data_version.get() == Some(current) {
            return Ok(false);
        }
        // Local edits flush first, so the diff compares the file against a cache with nothing
        // pending: an unflushed local edit must not read as the other side's deletion.
        self.save()?;
        self.refresh_resident()?;
        self.invalidate_relation_memos();
        self.requery_all();
        // A commit matters even when it inserted only nonresident rows: count/projection
        // observers still need invalidation. Advance only after a successful merge so errors
        // remain retryable.
        self.inner.data_version.set(Some(current));
        Ok(true)
    }

    /// `PRAGMA data_version`, or `None` where the engine did not answer (the Recorder).
    fn file_data_version(&self) -> Result<Option<i64>, DbError> {
        let mut v = None;
        self.conn().query("PRAGMA data_version", &[], &mut |row| {
            if let Ok(i) = row.get(0).as_int() {
                v = Some(i);
            }
        })?;
        Ok(v)
    }

    /// Re-select every resident row and feed the differences through the caches: per-field
    /// announcements, external deletions, all authored [`ModelContainer::EXTERNAL_AUTHOR`].
    fn refresh_resident(&self) -> Result<bool, DbError> {
        self.refresh_resident_in(None)
    }

    /// [`ModelContainer::refresh_resident`] over the tables named (all of them for `None`).
    fn refresh_resident_in(&self, only: Option<&[&'static str]>) -> Result<bool, DbError> {
        struct RefreshJob {
            store: u64,
            resident_keys: Rc<dyn Fn() -> Vec<u64>>,
            refresh: RefreshFn,
            columns: String,
            table: String,
            keys_where: KeysWhere,
        }
        let jobs: Vec<RefreshJob> = {
            let tables = self.inner.tables.borrow();
            tables
                .iter()
                .filter(|(_, h)| only.is_none_or(|t| t.contains(&h.table)))
                .map(|(store, h)| RefreshJob {
                    store: *store,
                    resident_keys: h.resident_keys.clone(),
                    refresh: h.refresh.clone(),
                    columns: select_list(h),
                    table: h.name.sql(),
                    keys_where: keys_where_of(h),
                })
                .collect()
        };
        let mut changed = false;
        for RefreshJob {
            store,
            resident_keys,
            refresh,
            columns,
            table,
            keys_where,
        } in jobs
        {
            // Another writer may have replaced the bytes; the memo answers from the file next.
            self.inner.blob_memo.borrow_mut().forget_store(store);
            let resident = resident_keys();
            if resident.is_empty() {
                continue;
            }
            let mut rows: Vec<Vec<Value>> = Vec::new();
            for chunk in resident.chunks(MAX_BOUND_PARAMS / 2) {
                let (clause, params) = keys_where(chunk);
                self.conn().query(
                    &format!("SELECT {columns} FROM {table} WHERE {clause}"),
                    &params,
                    &mut |row| {
                        let n = Row::len(row);
                        rows.push((0..n).map(|i| row.get(i)).collect());
                    },
                )?;
            }
            // The connection borrow is released before refresh announces; a sink hearing
            // these changes may read back through SQL.
            if refresh(rows)? {
                changed = true;
            }
        }
        Ok(changed)
    }

    fn install_state<M: Model>(
        &self,
        fetch: Fetch,
        raw: Option<RawQuery>,
        count_only: bool,
    ) -> Rc<QueryState> {
        let store = self.cache::<M>();
        let state = Rc::new(QueryState {
            store_id: store.store_id(),
            table: M::TABLE,
            watches: RefCell::new(Vec::new()),
            local_extra: RefCell::new(Vec::new()),
            set: RefCell::new(ResultSet::new(fetch.clone())),
            version: day_reactive::Scope::detached().enter(|| day_reactive::Signal::new(0)),
            pending: RefCell::new(QueryEvents::None),
            needs_sql: Cell::new(false),
            pending_commit: Cell::new(!self.inner.dirty.borrow().is_empty()),
            error: day_reactive::Scope::detached().enter(|| day_reactive::Signal::new(None)),
            raw,
            count_only,
            count: Cell::new(0),
        });
        self.rewire_watches(&state, &fetch);
        self.inner.queries.borrow_mut().push(Rc::downgrade(&state));
        // The seed: flush anything pending (with autosave; without it the query answers from
        // the last save, documented), then one SQL round trip.
        if self.inner.autosave.get() && !self.inner.dirty.borrow().is_empty() {
            let _ = self.save();
        }
        if count_only {
            state.count.set(self.answer_count(&state));
        } else {
            let ids = self.answer(&state);
            state.set.borrow_mut().reset(ids);
        }
        // The seed is the list's starting snapshot, not a stream of inserts to replay.
        *state.pending.borrow_mut() = QueryEvents::None;
        state
    }

    fn install_query<M: Model>(&self, fetch: Fetch, raw: Option<RawQuery>) -> Query<M> {
        Query {
            state: self.install_state::<M>(fetch, raw, false),
            container: self.clone(),
            _p: std::marker::PhantomData,
        }
    }

    /// (Re)compute a query's relation subscriptions from its fetch.
    fn rewire_watches(&self, state: &Rc<QueryState>, fetch: &Fetch) {
        let deps = fetch.dependencies();
        let mut watches: Vec<RelWatch> = Vec::new();
        let mut local_extra: Vec<&'static str> = Vec::new();
        let relations = self.inner.relations.borrow();
        let joins = self.inner.joins.borrow();
        for dep in &deps.related {
            let mut resolved = false;
            for r in relations.iter() {
                if r.parent_table == dep.owner && r.parent_field == dep.field {
                    watches.push(RelWatch {
                        store: r.child_store,
                        join_store: None,
                        fields: {
                            let mut f = vec![r.fk_field];
                            if let Some(o) = r.ordered {
                                f.push(o);
                            }
                            f
                        },
                        columns: dep.columns.clone(),
                    });
                    resolved = true;
                    break;
                }
                if r.child_table == dep.owner && r.fk_field == dep.field {
                    // The membership column lives on the query's table: a rewrite of the
                    // reference must mark it stale even though no predicate reads it.
                    if dep.owner == state.table && !local_extra.contains(&r.fk_col) {
                        local_extra.push(r.fk_col);
                    }
                    watches.push(RelWatch {
                        store: r.parent_store,
                        join_store: None,
                        fields: Vec::new(),
                        columns: dep.columns.clone(),
                    });
                    resolved = true;
                    break;
                }
            }
            if resolved {
                continue;
            }
            // A link: the far store's read columns matter, and so does the owner's value
            // column; rewriting it is what moves the row across the link.
            if let Some(l) = self
                .inner
                .links
                .borrow()
                .iter()
                .find(|l| l.owner_table == dep.owner && l.field == dep.field)
                .copied()
            {
                if dep.owner == state.table && !local_extra.contains(&l.local) {
                    local_extra.push(l.local);
                }
                let far = self
                    .inner
                    .tables
                    .borrow()
                    .iter()
                    .find(|(_, h)| h.table == l.target_table)
                    .map(|(id, _)| *id);
                if let Some(store) = far {
                    let mut columns = dep.columns.clone();
                    if !columns.contains(&l.remote) {
                        columns.push(l.remote);
                    }
                    watches.push(RelWatch {
                        store,
                        join_store: None,
                        fields: Vec::new(),
                        columns,
                    });
                }
                continue;
            }
            for j in joins.iter() {
                let side = if j.a_table == dep.owner && j.a_field == dep.field {
                    Some(j.b_store)
                } else if j.b_table == dep.owner && j.b_field.get() == Some(dep.field) {
                    Some(j.a_store)
                } else {
                    None
                };
                if let Some(other) = side {
                    watches.push(RelWatch {
                        store: other,
                        join_store: Some(j.join_store),
                        fields: Vec::new(),
                        columns: dep.columns.clone(),
                    });
                    break;
                }
            }
        }
        *state.watches.borrow_mut() = watches;
        *state.local_extra.borrow_mut() = local_extra;
    }

    /// One announced change: decide, per live query, whether it can move the result, and
    /// mark stale where it can. No SQL runs here; the requery happens once, after the flush.
    fn mark_queries_stale(&self, change: &day_model::Change) {
        let Some(&store) = change.components.first() else {
            return;
        };
        let states: Vec<Rc<QueryState>> = {
            let mut queries = self.inner.queries.borrow_mut();
            queries.retain(|w| w.strong_count() > 0);
            queries.iter().filter_map(|w| w.upgrade()).collect()
        };
        if states.is_empty() {
            return;
        }
        let key = change.components.get(1).copied();
        if key == Some(day_model::STRUCTURE) {
            return; // the shape path duplicates the row paths
        }
        // The change log speaks field names; predicates speak column names.
        let (column, changed_table): (Option<String>, Option<&'static str>) = {
            let tables = self.inner.tables.borrow();
            let hooks = tables.get(&store);
            let column = if change.components.len() >= 3 {
                hooks.map(|h| {
                    h.fields
                        .iter()
                        .position(|f| f == change.label)
                        .map(|i| h.columns[i].clone())
                        // A transient field: never a dependency column.
                        .unwrap_or_else(|| "\u{0}".to_string())
                })
            } else {
                None
            };
            (column, hooks.map(|h| h.table))
        };
        let column = column.as_deref();

        for state in &states {
            if state.needs_sql.get() {
                continue; // already stale; nothing to learn
            }
            if let Some(raw) = &state.raw {
                if changed_table.is_some_and(|t| raw.tables.iter().any(|r| r == t)) {
                    state.needs_sql.set(true);
                }
                continue;
            }
            // Both gates apply: a self-referential relation makes the query's own store a
            // related store too, so the own-table check must not shadow the watch check.
            let own_stale = state.store_id == store
                && match (key, change.op) {
                    (None, _) => true, // a wholesale rewrite: anything may have moved
                    (Some(_), Op::Insert) | (Some(_), Op::Delete) => true,
                    (Some(_), Op::Set) => match column {
                        // A row-level merge without a field name: assume the worst.
                        None => true,
                        Some(c) => {
                            let set = state.set.borrow();
                            set.deps().touches_local(c) || state.local_extra.borrow().contains(&c)
                        }
                    },
                    (Some(_), Op::Move) => false, // user order is not a query's business
                };
            let stale = own_stale || {
                let watches = state.watches.borrow();
                watches.iter().any(|w| {
                    if w.join_store == Some(store) {
                        return true; // every link/unlink/reposition is a membership change
                    }
                    if w.store != store {
                        return false;
                    }
                    match (key, change.op) {
                        (None, _) => true,
                        (Some(_), Op::Insert) | (Some(_), Op::Delete) => true,
                        (Some(_), Op::Set) => {
                            w.fields.contains(&change.label)
                                || column.is_some_and(|c| w.columns.contains(&c))
                        }
                        (Some(_), Op::Move) => false,
                    }
                })
            };
            if stale {
                state.needs_sql.set(true);
                state.pending_commit.set(true);
            }
        }
    }

    /// After a flush: every stale query re-derives (plus raw queries whose tables the flush
    /// touched), each answer diffed into list deltas.
    fn run_deferred_requeries(&self, stmts: &[(String, Vec<Value>)]) {
        let states: Vec<Rc<QueryState>> = self
            .inner
            .queries
            .borrow()
            .iter()
            .filter_map(|w| w.upgrade())
            .collect();
        for state in states {
            let mut due = state.needs_sql.replace(false) | state.pending_commit.replace(false);
            if let Some(raw) = &state.raw
                && !due
            {
                due = stmts
                    .iter()
                    .any(|(sql, _)| raw.tables.iter().any(|t| statement_touches(sql, t)));
            }
            if due {
                self.requery(&state);
            }
        }
    }

    /// Mark every query stale and requery now: the external-change and rescan path.
    fn requery_all(&self) {
        let states: Vec<Rc<QueryState>> = self
            .inner
            .queries
            .borrow()
            .iter()
            .filter_map(|w| w.upgrade())
            .collect();
        for state in states {
            state.needs_sql.set(false);
            self.requery(&state);
        }
    }

    /// [`ModelContainer::requery_all`] for the live queries that read `tables`: a query over
    /// one of them, one crossing into one through a relation (or that relation's join
    /// table), or a raw query naming one.
    fn requery_tables(&self, tables: &[&'static str]) {
        let stores: Vec<u64> = self
            .inner
            .tables
            .borrow()
            .iter()
            .filter(|(_, h)| tables.contains(&h.table))
            .map(|(id, _)| *id)
            .collect();
        let states: Vec<Rc<QueryState>> = self
            .inner
            .queries
            .borrow()
            .iter()
            .filter_map(|w| w.upgrade())
            .collect();
        for state in states {
            let reads = match &state.raw {
                Some(raw) => raw.tables.iter().any(|t| tables.contains(&t.as_str())),
                None => {
                    stores.contains(&state.store_id)
                        || state.watches.borrow().iter().any(|w| {
                            stores.contains(&w.store)
                                || w.join_store.is_some_and(|j| stores.contains(&j))
                        })
                }
            };
            if reads {
                state.needs_sql.set(false);
                self.requery(&state);
            }
        }
    }

    /// One requery: answer through the engine, adopt, narrate.
    fn requery(&self, state: &Rc<QueryState>) {
        if state.count_only {
            let n = self.answer_count(state);
            if n != state.count.get() {
                state.count.set(n);
                state
                    .version
                    .set(state.version.get_untracked().wrapping_add(1));
            }
            return;
        }
        let ids = self.answer(state);
        let change = state.set.borrow_mut().adopt(ids);
        match change {
            SetChange::Same => {}
            SetChange::Deltas(d) => {
                state.pending.borrow_mut().push(&d);
                state
                    .version
                    .set(state.version.get_untracked().wrapping_add(1));
            }
            SetChange::Reload => {
                state.pending.borrow_mut().reload();
                state
                    .version
                    .set(state.version.get_untracked().wrapping_add(1));
            }
        }
    }

    /// Answer a COUNT-shaped fetch: one `SELECT COUNT(*)`, capped by the fetch's limit
    /// (a limited set's length is `min(count, limit)`). The fallback form counts its
    /// re-checked rows the same way.
    fn answer_count(&self, state: &Rc<QueryState>) -> usize {
        let result = (|| {
            if self.table_detached(state.table) {
                return Ok(0);
            }
            if let Some(raw) = &state.raw {
                return self
                    .select_ids_checked(&raw.sql, &raw.params)
                    .map(|ids| ids.len());
            }
            let fetch = state.set.borrow().fetch().clone();
            let cap = fetch.limit.unwrap_or(usize::MAX);
            let snapshot = self.sql_snapshot();
            match compile_count(state.table, &fetch, &snapshot) {
                Ok(q) => {
                    let mut n = Ok(0_i64);
                    self.conn().query(&q.sql, &q.params, &mut |row| {
                        n = row.get(0).as_int();
                    })?;
                    Ok((n?.max(0) as usize).min(cap))
                }
                Err(CompileErr::NeedsFold) => {
                    let (q, cols) = compile_fallback(state.table, &fetch, &snapshot)
                        .map_err(|e| DbError::new(DbErrorKind::Unsupported, e.message()))?;
                    let mut n = 0;
                    self.conn().query(&q.sql, &q.params, &mut |row| {
                        let values = (0..row.len()).map(|i| row.get(i)).collect::<Vec<_>>();
                        if let Some(h) = value_to_handle(&values[0])
                            && fetch.pred.eval(
                                h,
                                &FallbackRow {
                                    cols: &cols,
                                    values: &values,
                                },
                            )
                        {
                            n += 1;
                        }
                    })?;
                    Ok(n.min(cap))
                }
                Err(e) => Err(DbError::new(DbErrorKind::Unsupported, e.message())),
            }
        })();
        match result {
            Ok(n) => {
                state.error.set(None);
                n
            }
            Err(error) => {
                self.inner.error.set(Some(error.to_string()));
                state.error.set(Some(error));
                state.count.get()
            }
        }
    }

    /// Answer a query's fetch through the engine: the compiled form, the fallback form for
    /// drivers without `day_fold`, or the raw statement.
    fn answer(&self, state: &Rc<QueryState>) -> Vec<u64> {
        match self.answer_checked(state) {
            Ok(ids) => {
                state.error.set(None);
                ids
            }
            Err(error) => {
                self.inner.error.set(Some(error.to_string()));
                state.error.set(Some(error));
                // A failed read is not an empty result. Retain the last successful set.
                state.set.borrow().ids().to_vec()
            }
        }
    }
    /// Whether `table` belongs to an attached database that is not attached right now. The
    /// alias is the model's declared one, not a prefix of the name: a table of the
    /// container's own may be called `dot.ted`.
    fn table_detached(&self, table: &str) -> bool {
        let tables = self.inner.tables.borrow();
        let Some(alias) = tables
            .values()
            .find(|h| h.table == table)
            .and_then(|h| h.name.schema)
        else {
            return false;
        };
        alias != "main"
            && alias != "temp"
            && !self.inner.attached.borrow().iter().any(|a| a == alias)
    }
    fn answer_checked(&self, state: &Rc<QueryState>) -> Result<Vec<u64>, DbError> {
        // Explicit detachment is a successful transition to an empty catalog, not an I/O error.
        if self.table_detached(state.table) {
            return Ok(Vec::new());
        }
        if let Some(raw) = &state.raw {
            return self.select_ids_checked(&raw.sql, &raw.params);
        }
        let fetch = state.set.borrow().fetch().clone();
        let snapshot = self.sql_snapshot();
        match compile_fetch(state.table, &fetch, &snapshot) {
            Ok(q) => self.select_ids_checked(&q.sql, &q.params),
            Err(CompileErr::NeedsFold) => {
                let (q, cols) = compile_fallback(state.table, &fetch, &snapshot)
                    .map_err(|e| DbError::new(DbErrorKind::Unsupported, e.message()))?;
                let mut ids = Vec::new();
                self.conn().query(&q.sql, &q.params, &mut |row| {
                    let values = (0..row.len()).map(|i| row.get(i)).collect::<Vec<_>>();
                    if let Some(h) = value_to_handle(&values[0])
                        && fetch.pred.eval(
                            h,
                            &FallbackRow {
                                cols: &cols,
                                values: &values,
                            },
                        )
                    {
                        ids.push(h);
                    }
                })?;
                if let Some(limit) = fetch.limit {
                    ids.truncate(limit);
                }
                Ok(ids)
            }
            Err(e) => Err(DbError::new(DbErrorKind::Unsupported, e.message())),
        }
    }

    /// A point-in-time view of names for the SQL compiler: tables, keys, shadows, wired
    /// relations, and whether the driver folds case.
    fn sql_snapshot(&self) -> SqlSnapshot {
        let tables = self.inner.tables.borrow();
        let relations = self.inner.relations.borrow();
        let joins = self.inner.joins.borrow();
        SqlSnapshot {
            tables: tables
                .values()
                .map(|h| TableInfo {
                    table: h.table.to_string(),
                    sql: h.name.sql(),
                    key: h.key_cols[0].clone(),
                    fts: h.fts.as_ref().map(|_| FtsSql {
                        from: h.name.shadow("_fts"),
                        match_col: ident(&format!("{}_fts", h.name.bare)),
                    }),
                    fts_key: h.fts_key,
                    spatial: h
                        .spatial
                        .as_ref()
                        .map(|(lat, lon, _)| (lat.clone(), lon.clone(), h.name.shadow("_geo"))),
                })
                .collect(),
            rels: relations
                .iter()
                .map(|r| RelInfo {
                    parent_table: r.parent_table,
                    parent_field: r.parent_field,
                    parent_key: r.parent_key_col,
                    child_table: r.child_table,
                    child_key: r.child_key_col,
                    fk_field: r.fk_field,
                    fk_col: r.fk_col,
                })
                .collect(),
            joins: joins
                .iter()
                .map(|j| JoinInfo {
                    join_table: j.join_table,
                    a_table: j.a_table,
                    a_field: j.a_field,
                    a_key: j.a_key_col,
                    b_table: j.b_table,
                    b_field: j.b_field.get(),
                    b_key: j.b_key_col,
                    parent_col: j.parent_col,
                    child_col: j.child_col,
                })
                .collect(),
            links: self.inner.links.borrow().clone(),
            fold: self.inner.caps.unicode_fold,
        }
    }
}

/// One table as the SQL compiler sees it: `table` is the plain name it is asked about,
/// `sql` the quoted form it writes; the shadows come already quoted, the columns plain.
struct TableInfo {
    table: String,
    sql: String,
    key: String,
    fts: Option<FtsSql>,
    fts_key: &'static str,
    spatial: Option<(String, String, String)>,
}

struct RelInfo {
    parent_table: &'static str,
    parent_field: &'static str,
    parent_key: &'static str,
    child_table: &'static str,
    child_key: &'static str,
    fk_field: &'static str,
    fk_col: &'static str,
}

struct JoinInfo {
    join_table: &'static str,
    a_table: &'static str,
    a_field: &'static str,
    a_key: &'static str,
    b_table: &'static str,
    b_field: Option<&'static str>,
    b_key: &'static str,
    parent_col: &'static str,
    child_col: &'static str,
}

struct SqlSnapshot {
    tables: Vec<TableInfo>,
    rels: Vec<RelInfo>,
    joins: Vec<JoinInfo>,
    links: Vec<LinkInfo>,
    fold: bool,
}

impl SqlIndex for SqlSnapshot {
    fn relation(&self, owner: &str, field: &str) -> Option<RelSql> {
        for r in &self.rels {
            if r.parent_table == owner && r.parent_field == field {
                return Some(RelSql::Children {
                    target_key: r.child_key.to_string(),
                    fk_col: r.fk_col.to_string(),
                    owner_key: r.parent_key.to_string(),
                });
            }
            if r.child_table == owner && r.fk_field == field {
                return Some(RelSql::Referent {
                    target_key: r.parent_key.to_string(),
                    fk_col: r.fk_col.to_string(),
                });
            }
        }
        for j in &self.joins {
            if j.a_table == owner && j.a_field == field {
                return Some(RelSql::Join {
                    join_table: j.join_table.to_string(),
                    owner_col: j.parent_col.to_string(),
                    target_col: j.child_col.to_string(),
                    owner_key: j.a_key.to_string(),
                    target_key: j.b_key.to_string(),
                });
            }
            if j.b_table == owner && j.b_field == Some(field) {
                return Some(RelSql::Join {
                    join_table: j.join_table.to_string(),
                    owner_col: j.child_col.to_string(),
                    target_col: j.parent_col.to_string(),
                    owner_key: j.b_key.to_string(),
                    target_key: j.a_key.to_string(),
                });
            }
        }
        for l in &self.links {
            if l.owner_table == owner && l.field == field {
                return Some(RelSql::Linked {
                    local_col: l.local.to_string(),
                    remote_col: l.remote.to_string(),
                    target_key: self.key_of(l.target_table)?,
                });
            }
        }
        None
    }

    fn key_of(&self, table: &str) -> Option<String> {
        self.tables
            .iter()
            .find(|t| t.table == table)
            .map(|t| t.key.clone())
    }

    fn table_sql(&self, table: &str) -> String {
        self.tables
            .iter()
            .find(|t| t.table == table)
            .map(|t| t.sql.clone())
            .unwrap_or_else(|| ident(table))
    }

    fn fts_of(&self, table: &str) -> Option<FtsSql> {
        self.tables
            .iter()
            .find(|t| t.table == table)
            .and_then(|t| t.fts.clone())
    }

    fn fts_key_of(&self, table: &str) -> &str {
        self.tables
            .iter()
            .find(|t| t.table == table)
            .map(|t| t.fts_key)
            .unwrap_or("rowid")
    }

    fn geo_of(&self, table: &str, lat: &str, lon: &str) -> Option<String> {
        self.tables
            .iter()
            .find(|t| t.table == table)
            .and_then(|t| t.spatial.as_ref())
            .filter(|(a, o, _)| a == lat && o == lon)
            .map(|(_, _, g)| g.clone())
    }

    fn unicode_fold(&self) -> bool {
        self.fold
    }
}

/// Whether a statement's target table is `table`, a plain-text check over the SQL the fold
/// itself produced (`INSERT INTO "t" … ON CONFLICT`, `UPDATE "t" SET …`, `DELETE FROM "t" …`).
/// The fold quotes its table names, so the name is read back through the quotes; `table` is
/// the plain name a raw query declared.
fn statement_touches(sql: &str, table: &str) -> bool {
    for prefix in [
        "INSERT INTO ",
        "INSERT OR REPLACE INTO ",
        "UPDATE ",
        "DELETE FROM ",
    ] {
        if let Some(rest) = sql.strip_prefix(prefix) {
            return quoted_name(rest).as_deref() == Some(table);
        }
    }
    false
}

/// The identifier a quoted name at the start of `sql` spells (a doubled `"` is one quote),
/// `None` when `sql` does not start with one.
fn quoted_name(sql: &str) -> Option<String> {
    let mut chars = sql.strip_prefix('"')?.chars();
    let mut name = String::new();
    loop {
        match chars.next()? {
            '"' => match chars.next() {
                Some('"') => name.push('"'),
                _ => return Some(name),
            },
            ch => name.push(ch),
        }
    }
}

// ---------------------------------------------------------------------------
// Query as a list row source (feature `pieces`)
// ---------------------------------------------------------------------------

#[cfg(feature = "pieces")]
mod pieces_glue {
    use std::cell::RefCell;

    use day_model::{Elem, Keyed, Store};
    use day_pieces::{ModelSlot, RowConn, RowSource};

    use crate::{Delta, Model, Query, QueryEvents};

    /// How far around a bound row the list source faults in one batch: the price of showing
    /// row N is one `SELECT` that also covers the rows about to scroll in.
    const FAULT_BEHIND: usize = 16;
    const FAULT_AHEAD: usize = 64;

    /// `list(query, row)`: the query's ids are the display order, rows fault in as the list
    /// binds them (a window at a time), and set changes arrive as row deltas the native list
    /// can animate.
    impl<M: Model> RowSource for Query<M> {
        type Slot = ModelSlot<M>;
        type Ref = Elem<M>;
        type Conn = QueryConn<M>;
        fn connect(self) -> QueryConn<M> {
            let store = self.container.cache::<M>();
            QueryConn {
                query: self,
                store,
                keys: RefCell::new(Vec::new()),
            }
        }
    }

    pub struct QueryConn<M: Model> {
        query: Query<M>,
        store: Store<Keyed<M>>,
        keys: RefCell<Vec<u64>>,
    }

    impl<M: Model> QueryConn<M> {
        /// Make the row at `index` (and its neighborhood) resident before anything binds it.
        fn fault_window(&self, index: usize) {
            let len = self.keys.borrow().len();
            let start = index.saturating_sub(FAULT_BEHIND);
            let end = (index + FAULT_AHEAD).min(len);
            self.query.materialize(start..end);
        }
    }

    impl<M: Model> RowConn for QueryConn<M> {
        type Slot = ModelSlot<M>;
        type Ref = Elem<M>;

        fn refresh(&self) -> Vec<u64> {
            let keys: Vec<u64> = self.query.ids().iter().map(|id| id.handle()).collect();
            *self.keys.borrow_mut() = keys.clone();
            keys
        }
        fn len(&self) -> usize {
            self.keys.borrow().len()
        }
        fn token_at(&self, index: usize) -> u64 {
            self.keys.borrow().get(index).copied().unwrap_or(0)
        }
        fn tokens_now(&self) -> Vec<u64> {
            self.keys.borrow().clone()
        }
        fn slot_at(&self, index: usize) -> Option<ModelSlot<M>> {
            let key = self.keys.borrow().get(index).copied()?;
            if !self.store.with_untracked(|k| k.get(key).is_some()) {
                self.fault_window(index);
            }
            Some(ModelSlot::for_key(self.store, key))
        }
        fn rebind(&self, slot: &ModelSlot<M>, index: usize) {
            if let Some(key) = self.keys.borrow().get(index).copied() {
                if !self.store.with_untracked(|k| k.get(key).is_some()) {
                    self.fault_window(index);
                }
                slot.rebind_key(key);
            }
        }
        fn select_ref(&self, index: usize) -> Option<Elem<M>> {
            let key = self.keys.borrow().get(index).copied()?;
            if !self.store.with_untracked(|k| k.get(key).is_some()) {
                self.fault_window(index);
            }
            Some(self.store.elem(key))
        }
        fn values_flow_by_reload(&self) -> bool {
            false // row values flow through the store's own per-field notifications
        }
        fn take_row_events(&self) -> Option<Vec<day_spec::props::RowDelta>> {
            match self.query.take_events() {
                QueryEvents::Deltas(d) => Some(
                    d.into_iter()
                        .map(|d| match d {
                            Delta::Insert(i, _) => day_spec::props::RowDelta::Insert(i),
                            Delta::Remove(i, _) => day_spec::props::RowDelta::Remove(i),
                            Delta::Move(from, to, _) => day_spec::props::RowDelta::Move(from, to),
                        })
                        .collect(),
                ),
                // Reload means "the whole set moved"; None here means the same to the list.
                QueryEvents::Reload | QueryEvents::None => None,
            }
        }
        fn commit_move(&self, from: usize, to: usize) {
            // The native drag already moved the row: serve that order until the app's write
            // (its on_reorder, typically a rank column the query sorts by) requeries. The list
            // expects exactly this order back as the echo of its own move; left unrotated, the
            // echo never matched, and the query's own move was replayed on rows already moved.
            let mut keys = self.keys.borrow_mut();
            if from < keys.len() && to < keys.len() {
                let key = keys.remove(from);
                keys.insert(to, key);
            }
        }
        fn commit_delete(&self, index: usize) {
            // The native delete affordance: drop from the local snapshot; the app's on_delete
            // writes the store, and the query's own delta follows as the echo.
            let mut keys = self.keys.borrow_mut();
            if index < keys.len() {
                keys.remove(index);
            }
        }
    }
}

#[cfg(feature = "pieces")]
pub use pieces_glue::QueryConn;

// ---------------------------------------------------------------------------
// Date and time codecs (feature `datetime`; docs/persistence.md)
// ---------------------------------------------------------------------------

/// Column codecs for day::datetime's [`DayDate`](day_spec::controls::datetime::DayDate) and
/// [`DayTime`](day_spec::controls::datetime::DayTime), for `#[derive(Model)]` fields.
///
/// Canonical, what a bare field of the type stores: `DayDate` → `INTEGER` epoch days,
/// `DayTime` → `INTEGER` seconds-of-day: the same numeric interchange forms the pickers
/// already speak across native boundaries, and both sort chronologically as plain integers.
///
/// Named, picked per field with `#[model(with = …)]`: [`Iso8601`](datetime::Iso8601) stores
/// `TEXT` in the form `Display` writes (readable in any sqlite tool, and lexicographic order
/// is chronological order, ISO-8601's design goal); [`EpochSeconds`](datetime::EpochSeconds)
/// and [`EpochMillis`](datetime::EpochMillis) store the `INTEGER` a server that speaks Unix
/// time expects, midnight-of-day for a `DayDate`.
///
/// The impls live here rather than in the piece because one of the two crates has to own
/// them, and this is the one that depends on the other.
#[cfg(feature = "datetime")]
pub mod datetime {
    use crate::{ColumnValue, DbError, DbErrorKind, SqlType, Value, ValueCodec};
    use day_spec::controls::datetime::{DayDate, DayTime};

    impl ColumnValue for DayDate {
        const SQL_TYPE: SqlType = SqlType::Integer;
        fn to_sqlite_value(&self) -> Value {
            Value::Int(self.to_epoch_days())
        }
        fn from_sqlite_value(v: Value) -> Result<Self, DbError> {
            Ok(DayDate::from_epoch_days(v.as_int()?))
        }
    }

    impl ColumnValue for DayTime {
        const SQL_TYPE: SqlType = SqlType::Integer;
        fn to_sqlite_value(&self) -> Value {
            Value::Int(self.seconds_of_day())
        }
        fn from_sqlite_value(v: Value) -> Result<Self, DbError> {
            Ok(DayTime::from_seconds_of_day(v.as_int()?))
        }
    }

    /// `TEXT` in the `Display` form: `YYYY-MM-DD` for a date, `HH:MM[:SS]` for a time.
    pub struct Iso8601;

    impl ValueCodec<DayDate> for Iso8601 {
        const SQL_TYPE: SqlType = SqlType::Text;
        fn to_sqlite_value(v: &DayDate) -> Value {
            Value::Text(v.to_string())
        }
        fn from_sqlite_value(v: Value) -> Result<DayDate, DbError> {
            let s = v.as_text()?;
            DayDate::parse_iso(s).ok_or_else(|| {
                DbError::new(DbErrorKind::Decode, format!("not an ISO-8601 date: {s:?}"))
            })
        }
    }

    impl ValueCodec<DayTime> for Iso8601 {
        const SQL_TYPE: SqlType = SqlType::Text;
        fn to_sqlite_value(v: &DayTime) -> Value {
            Value::Text(v.to_string())
        }
        fn from_sqlite_value(v: Value) -> Result<DayTime, DbError> {
            let s = v.as_text()?;
            DayTime::parse_iso(s).ok_or_else(|| {
                DbError::new(DbErrorKind::Decode, format!("not an ISO-8601 time: {s:?}"))
            })
        }
    }

    /// `INTEGER` seconds since 1970-01-01T00:00Z; midnight of the day, for a [`DayDate`].
    pub struct EpochSeconds;

    impl ValueCodec<DayDate> for EpochSeconds {
        const SQL_TYPE: SqlType = SqlType::Integer;
        fn to_sqlite_value(v: &DayDate) -> Value {
            Value::Int(v.to_epoch_days() * 86_400)
        }
        fn from_sqlite_value(v: Value) -> Result<DayDate, DbError> {
            Ok(DayDate::from_epoch_days(v.as_int()?.div_euclid(86_400)))
        }
    }

    /// `INTEGER` milliseconds since the same epoch, for interop that expects it.
    pub struct EpochMillis;

    impl ValueCodec<DayDate> for EpochMillis {
        const SQL_TYPE: SqlType = SqlType::Integer;
        fn to_sqlite_value(v: &DayDate) -> Value {
            Value::Int(v.to_epoch_days() * 86_400_000)
        }
        fn from_sqlite_value(v: Value) -> Result<DayDate, DbError> {
            Ok(DayDate::from_epoch_days(v.as_int()?.div_euclid(86_400_000)))
        }
    }
}

#[cfg(all(test, feature = "driver-rusqlite"))]
mod eviction_tests;