day-persistence 0.1.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
// 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, RelSql, SqlIndex, compile_count, compile_fallback, compile_fetch};

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 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,
}

/// 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.
        if let Some(from) = sql.split(" FROM ").nth(1) {
            let table = from.split_whitespace().next().unwrap_or("");
            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,
}

/// 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]] = &[];
    /// 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] = &[];
    /// 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;
    /// 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;
    }
}

/// 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);
        }
    };
    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 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 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, Copy, Debug)]
struct FkSpec {
    child_table: &'static str,
    child_field: &'static str,
    parent_table: &'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_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)>,
    /// 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>,
}

impl DirtyState {
    fn merge(&mut self, newer: Self) {
        for store in newer.full {
            if !self.full.contains(&store) {
                self.full.push(store);
            }
        }
        for id in newer.order {
            let next = newer.rows[&id].clone();
            if !self.rows.contains_key(&id) {
                self.order.push(id);
            }
            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);
            }
            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);
        }
        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,
    /// 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.
    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>,
    /// Same order as `columns`; what a change's label matches against.
    pub(crate) fields: Vec<String>,
    /// 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)>,
}

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>,
    /// 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>>,
    /// 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;

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),
                cache_limit: Cell::new(DEFAULT_CACHE_LIMIT),
                eviction_retry: RefCell::new(HashMap::new()),
                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);
        }
    }

    /// 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());
        }
        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 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();
                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()));
            }
        }
        result
    }

    // --- 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 keys = self.select_id_column_checked(&format!(
            "SELECT {} FROM {} ORDER BY {}",
            M::KEY,
            M::TABLE,
            M::KEY
        ))?;
        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 {}", M::TABLE),
            &[],
            &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(),
                hooks.columns.join(", "),
                hooks.table,
                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);
        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)> {
        self.inner
            .dirty
            .borrow()
            .rows
            .iter()
            .filter(|((s, _), _)| *s == store_id)
            .map(|((_, k), 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)
    }

    fn set_db_version(&self, v: u32) -> Result<(), DbError> {
        self.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(())
    }

    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
                    ),
                ));
            }
            let mut conn = self.conn();
            conn.begin()?;
            match (stage.run)(conn.as_mut()) {
                Ok(()) => {
                    conn.commit()?;
                    drop(conn);
                    current = stage.to;
                    self.set_db_version(current)?;
                }
                Err(e) => {
                    let _ = conn.rollback();
                    return Err(e);
                }
            }
        }
        if target > 0 {
            self.set_db_version(target)?;
        }
        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)>;

        self.inner.tables.borrow_mut().insert(
            store_id,
            TableHooks {
                table: M::TABLE,
                key_cols: vec![M::KEY.to_string()],
                key_where: Rc::new(|h| (format!("{} = ?", M::KEY), vec![key_param(h)])),
                columns,
                fields,
                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
        // (SQLite has no `ALTER ADD CONSTRAINT`); the in-memory rule still enforces, and a
        // staged rebuild adopts the clause when the app wants the engine's backstop too.
        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()) {
            return Ok(());
        }

        // DDL and backfill are one transaction: a failed migration leaves the old
        // index and fingerprint usable. Remove triggers before dropping indexed columns.
        self.conn().begin()?;
        let result = (|| {
            let t = M::TABLE;
            if self.table_exists(&format!("{t}_fts"))? {
                for suffix in ["ai", "ad", "au"] {
                    self.conn()
                        .execute(&format!("DROP TRIGGER IF EXISTS {t}_fts_{suffix}"), &[])?;
                }
                self.conn().execute(&format!("DROP TABLE {t}_fts"), &[])?;
                self.conn()
                    .execute(&format!("DROP TABLE IF EXISTS {t}_fts_keys"), &[])?;
            }
            if !self.table_exists(M::TABLE)? {
                self.create_table::<M>()?;
            } else {
                self.lightweight_migrate::<M>()?;
            }
            self.create_indexes::<M>()?;
            self.create_shadow_tables::<M>()?;
            self.store_fingerprint(M::TABLE, &fp)?;
            self.conn().commit()
        })();
        if result.is_err() {
            let _ = self.conn().rollback();
        }
        result
    }

    /// 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 t = M::TABLE;
        let key = M::KEY;
        if !M::FTS_COLUMNS.is_empty() {
            if !self.inner.caps.full_text_search {
                return Err(DbError::new(
                    DbErrorKind::Unsupported,
                    format!(
                        "`{t}` declares fts(…) but this driver's engine has no FTS5 — the \
                         bundled and cipher engines compile it in"
                    ),
                ));
            }
            let cols = M::FTS_COLUMNS.join(", ");
            let fresh = !self.table_exists(&format!("{t}_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 wide = M::COLUMNS
                .iter()
                .find(|c| c.name == 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 == key)
                    .expect("key column")
                    .sql
                    .ddl();
                // 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 {t}_fts_keys(day_rowid INTEGER PRIMARY KEY, day_key {key_type} NOT NULL UNIQUE)"), &[])?;
                self.conn().execute(&format!("CREATE VIRTUAL TABLE IF NOT EXISTS {t}_fts USING fts5(day_key UNINDEXED, {cols}{tokenize})"), &[])?;
                let new_cols = M::FTS_COLUMNS
                    .iter()
                    .map(|c| format!("new.{c}"))
                    .collect::<Vec<_>>()
                    .join(", ");
                let insert = format!(
                    "INSERT INTO {t}_fts_keys(day_key) VALUES (new.{key}); INSERT INTO {t}_fts(rowid, day_key, {cols}) VALUES ((SELECT day_rowid FROM {t}_fts_keys WHERE day_key = new.{key}), new.{key}, {new_cols});"
                );
                let delete = format!(
                    "DELETE FROM {t}_fts WHERE rowid = (SELECT day_rowid FROM {t}_fts_keys WHERE day_key = old.{key}); DELETE FROM {t}_fts_keys WHERE day_key = old.{key};"
                );
                for (suffix, event, body) in [
                    ("ai", "INSERT", insert.clone()),
                    ("ad", "DELETE", delete.clone()),
                    ("au", "UPDATE", format!("{delete} {insert}")),
                ] {
                    self.conn().execute(&format!("CREATE TRIGGER IF NOT EXISTS {t}_fts_{suffix} AFTER {event} ON {t} BEGIN {body} END"), &[])?;
                }
                if fresh {
                    self.conn().execute(
                        &format!("INSERT INTO {t}_fts_keys(day_key) SELECT {key} FROM {t}"),
                        &[],
                    )?;
                    let qualified = M::FTS_COLUMNS
                        .iter()
                        .map(|c| format!("b.{c}"))
                        .collect::<Vec<_>>()
                        .join(", ");
                    self.conn().execute(&format!("INSERT INTO {t}_fts(rowid, day_key, {cols}) SELECT k.day_rowid, b.{key}, {qualified} FROM {t} b JOIN {t}_fts_keys k ON k.day_key = b.{key}"), &[])?;
                }
            } else {
                self.conn().execute(
                    &format!(
                        "CREATE VIRTUAL TABLE IF NOT EXISTS {t}_fts USING fts5({cols}, \
                     content={t}, content_rowid={key}{tokenize})"
                    ),
                    &[],
                )?;
                let new_cols = M::FTS_COLUMNS
                    .iter()
                    .map(|c| format!("new.{c}"))
                    .collect::<Vec<_>>()
                    .join(", ");
                let old_cols = M::FTS_COLUMNS
                    .iter()
                    .map(|c| format!("old.{c}"))
                    .collect::<Vec<_>>()
                    .join(", ");
                self.conn().execute(
                    &format!(
                        "CREATE TRIGGER IF NOT EXISTS {t}_fts_ai AFTER INSERT ON {t} BEGIN \
                     INSERT INTO {t}_fts(rowid, {cols}) VALUES (new.{key}, {new_cols}); END"
                    ),
                    &[],
                )?;
                self.conn().execute(
                &format!(
                    "CREATE TRIGGER IF NOT EXISTS {t}_fts_ad AFTER DELETE ON {t} BEGIN \
                     INSERT INTO {t}_fts({t}_fts, rowid, {cols}) VALUES ('delete', old.{key}, {old_cols}); END"
                ),
                &[],
            )?;
                self.conn().execute(
                &format!(
                    "CREATE TRIGGER IF NOT EXISTS {t}_fts_au AFTER UPDATE ON {t} BEGIN \
                     INSERT INTO {t}_fts({t}_fts, rowid, {cols}) VALUES ('delete', old.{key}, {old_cols}); \
                     INSERT INTO {t}_fts(rowid, {cols}) VALUES (new.{key}, {new_cols}); END"
                ),
                &[],
            )?;
                if fresh {
                    // External-content rebuild: index whatever rows predate the declaration.
                    self.conn().execute(
                        &format!("INSERT INTO {t}_fts({t}_fts) VALUES ('rebuild')"),
                        &[],
                    )?;
                }
            }
        }
        if let Some(s) = M::SPATIAL {
            if !self.inner.caps.rtree {
                return Err(DbError::new(
                    DbErrorKind::Unsupported,
                    format!(
                        "`{t}` declares spatial(…) but this driver's engine has no R*Tree — \
                         the bundled and cipher engines compile it in"
                    ),
                ));
            }
            let (lat, lon) = (s.lat, s.lon);
            let fresh = !self.table_exists(&format!("{t}_geo"))?;
            self.conn().execute(
                &format!(
                    "CREATE VIRTUAL TABLE IF NOT EXISTS {t}_geo USING rtree({key}, \
                     min_lat, max_lat, min_lon, max_lon)"
                ),
                &[],
            )?;
            self.conn().execute(
                &format!(
                    "CREATE TRIGGER IF NOT EXISTS {t}_geo_ai AFTER INSERT ON {t} BEGIN \
                     INSERT OR REPLACE INTO {t}_geo VALUES (new.{key}, new.{lat}, new.{lat}, new.{lon}, new.{lon}); END"
                ),
                &[],
            )?;
            self.conn().execute(
                &format!(
                    "CREATE TRIGGER IF NOT EXISTS {t}_geo_au AFTER UPDATE OF {lat}, {lon} ON {t} BEGIN \
                     INSERT OR REPLACE INTO {t}_geo VALUES (new.{key}, new.{lat}, new.{lat}, new.{lon}, new.{lon}); END"
                ),
                &[],
            )?;
            self.conn().execute(
                &format!(
                    "CREATE TRIGGER IF NOT EXISTS {t}_geo_ad AFTER DELETE ON {t} BEGIN \
                     DELETE FROM {t}_geo WHERE {key} = old.{key}; END"
                ),
                &[],
            )?;
            if fresh {
                self.conn().execute(
                    &format!(
                        "INSERT OR REPLACE INTO {t}_geo \
                         SELECT {key}, {lat}, {lat}, {lon}, {lon} FROM {t}"
                    ),
                    &[],
                )?;
            }
        }
        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)
    }

    fn create_table<M: Model>(&self) -> Result<(), DbError> {
        let specs = self.inner.fk_specs.borrow();
        let cols: Vec<String> = M::COLUMNS
            .iter()
            .map(|c| {
                let mut s = format!("{} {}", c.name, c.sql.ddl());
                if c.name == M::KEY {
                    s.push_str(" PRIMARY KEY");
                } else if c.not_null {
                    s.push_str(" NOT NULL");
                }
                if c.unique && c.name != M::KEY {
                    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(spec) = specs
                    .iter()
                    .find(|f| f.child_table == M::TABLE && f.child_field == c.field)
                {
                    s.push_str(&format!(
                        " REFERENCES {}({}) ON DELETE {} DEFERRABLE INITIALLY DEFERRED",
                        spec.parent_table,
                        spec.parent_key,
                        spec.rule.sql()
                    ));
                }
                s
            })
            .collect();
        let body = format!("CREATE TABLE {} ({})", M::TABLE, 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(())
    }

    fn create_indexes<M: Model>(&self) -> Result<(), DbError> {
        // A declared relation's foreign-key column is indexed without being asked: it is what
        // `children_of` selects on, what relation predicates correlate on, and what the
        // engine scans to enforce `ON DELETE`. Unindexed, every one of those is a full scan
        // of the child table.
        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();
        for c in M::COLUMNS
            .iter()
            .filter(|c| c.indexed || (fk_cols.contains(&c.name) && c.name != M::KEY))
        {
            self.conn().execute(
                &format!(
                    "CREATE INDEX IF NOT EXISTS day_idx_{t}_{c} ON {t}({c})",
                    t = M::TABLE,
                    c = c.name
                ),
                &[],
            )?;
        }
        for idx in M::COMPOSITE_INDEXES {
            let cols = idx.join(", ");
            let name = idx.join("_");
            self.conn().execute(
                &format!(
                    "CREATE INDEX IF NOT EXISTS day_idx_{t}_{name} ON {t}({cols})",
                    t = M::TABLE
                ),
                &[],
            )?;
        }
        Ok(())
    }

    /// Close the gap between the file's columns and the declared ones: additions and drops
    /// only. A type change or a rename is refused with both names in the error; that is what
    /// staged migrations are for.
    fn lightweight_migrate<M: Model>(&self) -> Result<(), DbError> {
        let mut existing: Vec<String> = Vec::new();
        self.conn().query(
            &format!("PRAGMA table_info({})", M::TABLE),
            &[],
            &mut |row| {
                if let Ok(name) = row.get(1).as_text() {
                    existing.push(name.to_string());
                }
            },
        )?;

        let declared: Vec<&'static str> = M::COLUMNS.iter().map(|c| c.name).collect();
        let defaults = M::default_row();

        for (i, col) in M::COLUMNS.iter().enumerate() {
            if !existing.iter().any(|e| e == col.name) {
                // Add nullable, then backfill with the field's Rust default.
                self.conn().execute(
                    &format!(
                        "ALTER TABLE {} ADD COLUMN {} {}",
                        M::TABLE,
                        col.name,
                        col.sql.ddl()
                    ),
                    &[],
                )?;
                let default = Row::get(&defaults, i);
                if default != Value::Null {
                    self.conn().execute(
                        &format!("UPDATE {} SET {} = ?", M::TABLE, col.name),
                        &[default],
                    )?;
                }
            }
        }
        for gone in existing.iter().filter(|e| !declared.iter().any(|d| d == e)) {
            self.conn()
                .execute(&format!("ALTER TABLE {} DROP COLUMN {gone}", M::TABLE), &[])?;
        }
        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 stmts = self.fold(dirty)?;
        if stmts.is_empty() {
            return Ok(stmts);
        }
        let mut conn = self.conn();
        let outer = self.inner.worker_transaction.get();
        if !outer {
            conn.begin()?;
        }
        for (sql, params) in &stmts {
            if let Err(e) = conn.execute(sql, params) {
                if !outer {
                    let _ = conn.rollback();
                }
                return Err(e);
            }
        }
        if !outer && let Err(error) = conn.commit() {
            let _ = conn.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)();
        }
    }

    #[cfg(not(target_arch = "wasm32"))]
    fn worker_write<R>(
        &self,
        write: impl FnOnce(&Self) -> Result<R, DbError>,
    ) -> Result<R, DbError> {
        self.save()?;
        self.conn().begin()?;
        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.conn().commit()?;
            Ok(value)
        });
        self.inner.worker_transaction.set(false);
        if result.is_err() {
            self.conn().rollback().map_err(|error| {
                DbError::new(
                    DbErrorKind::Closed,
                    format!("transaction rollback failed: {error}"),
                )
            })?;
            self.worker_discard_changes()?;
        }
        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();
        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.
    fn fold(&self, dirty: &DirtyState) -> Result<Vec<(String, Vec<Value>)>, DbError> {
        let tables = self.inner.tables.borrow();
        let mut stmts: Vec<(String, Vec<Value>)> = Vec::new();

        // 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 (_, row) in (hooks.all_rows)() {
                stmts.push(upsert_stmt(hooks, &row));
            }
        }

        // 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();

        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;
            match state {
                DirtyRow::Delete => {
                    if !batchable {
                        let (clause, params) = (hooks.key_where)(key);
                        deletes.push(Batch::Single(
                            format!("DELETE FROM {} WHERE {clause}", hooks.table),
                            params,
                        ));
                        continue;
                    }
                    join_batch(&mut deletes, &mut open_deletes, store_id, None, key);
                }
                DirtyRow::Insert => {
                    if let Some(row) = (hooks.row_for)(key) {
                        let (sql, params) = upsert_stmt(hooks, &row);
                        batches.push(Batch::Single(sql, params));
                    }
                }
                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));
                        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
                        };
                        sets.push(format!("{} = ?", hooks.columns[i]));
                        set_params.push(row.get(i));
                    }
                    if set_params.is_empty() {
                        continue; // only transient fields changed
                    }
                    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.table),
                            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::Keyed { store, set, keys } => {
                    let Some(hooks) = tables.get(&store) else {
                        continue;
                    };
                    materialize(hooks, set, &keys, &mut stmts);
                }
            }
        }
        Ok(stmts)
    }

    // --- 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`, parsed: an empty list means the database is sound.
    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());
                }
            })?;
        Ok(findings)
    }

    /// Fold the WAL into the main file, before the OS copies it whole (device backup).
    pub fn checkpoint(&self) -> Result<(), DbError> {
        // The PRAGMA answers with a status row; a query with an ignored callback consumes it.
        self.conn()
            .query("PRAGMA wal_checkpoint(TRUNCATE)", &[], &mut |_| {})
    }

    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.
fn keys_where_of(hooks: &TableHooks) -> KeysWhere {
    if hooks.key_cols.len() == 1 {
        let col = hooks.key_cols[0].clone();
        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: an upsert (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>),
    /// 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.
    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 {} SET {clause} WHERE {where_clause}", hooks.table),
                    params,
                ));
            }
            None => out.push((
                format!("DELETE FROM {} WHERE {where_clause}", hooks.table),
                where_params,
            )),
        }
        return;
    }

    let key_col = &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 {} SET {clause} WHERE {key_col} IN ({marks})",
                hooks.table
            ),
            None => format!("DELETE FROM {} WHERE {key_col} IN ({marks})", hooks.table),
        };
        out.push((sql, params));
    }
}

fn upsert_stmt(hooks: &TableHooks, row: &[Value]) -> (String, Vec<Value>) {
    let cols = hooks.columns.join(", ");
    let marks = vec!["?"; hooks.columns.len()].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).
    let sets = hooks
        .columns
        .iter()
        .filter(|c| !hooks.key_cols.contains(c))
        .map(|c| format!("{c} = excluded.{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.table,
            hooks.key_cols.join(", ")
        ),
        row.to_vec(),
    )
}

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.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 {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()?;
        }
        let prefix = format!("{alias}.");
        type Doomed = Vec<(Rc<dyn Fn() -> Vec<u64>>, EvictFn)>;
        let doomed: Doomed = self
            .inner
            .tables
            .borrow()
            .values()
            .filter(|h| h.table.starts_with(&prefix))
            .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 {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> {
        struct RefreshJob {
            resident_keys: Rc<dyn Fn() -> Vec<u64>>,
            refresh: RefreshFn,
            columns: String,
            table: &'static str,
            keys_where: KeysWhere,
        }
        let jobs: Vec<RefreshJob> = {
            let tables = self.inner.tables.borrow();
            tables
                .values()
                .map(|h| RefreshJob {
                    resident_keys: h.resident_keys.clone(),
                    refresh: h.refresh.clone(),
                    columns: h.columns.join(", "),
                    table: h.table,
                    keys_where: keys_where_of(h),
                })
                .collect()
        };
        let mut changed = false;
        for RefreshJob {
            resident_keys,
            refresh,
            columns,
            table,
            keys_where,
        } in jobs
        {
            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);
        }
    }

    /// 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()
            }
        }
    }
    fn table_detached(&self, table: &str) -> bool {
        table.split_once('.').is_some_and(|(alias, _)| {
            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(),
                    key: h.key_cols[0].clone(),
                    fts: h.fts.clone(),
                    fts_key: h.fts_key,
                    spatial: h.spatial.clone(),
                })
                .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,
        }
    }
}

struct TableInfo {
    table: String,
    key: String,
    fts: Option<String>,
    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 fts_of(&self, table: &str) -> Option<String> {
        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 …`).
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 rest.split([' ', '(']).next() == Some(table);
        }
    }
    false
}

// ---------------------------------------------------------------------------
// 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;