graphitesql 0.0.10

A pure, safe, no_std Rust re-implementation of SQLite, compatible with the SQLite 3 file format.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908
13909
13910
13911
13912
13913
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924
13925
13926
13927
13928
13929
13930
13931
13932
13933
13934
13935
13936
13937
13938
13939
13940
13941
13942
13943
13944
13945
13946
13947
13948
13949
13950
13951
13952
13953
13954
13955
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983
13984
13985
13986
13987
13988
13989
13990
13991
13992
13993
13994
13995
13996
13997
13998
13999
14000
14001
14002
14003
14004
14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022
14023
14024
14025
14026
14027
14028
14029
14030
14031
14032
14033
14034
14035
14036
14037
14038
14039
14040
14041
14042
14043
14044
14045
14046
14047
14048
14049
14050
14051
14052
14053
14054
14055
14056
14057
14058
14059
14060
14061
14062
14063
14064
14065
14066
14067
14068
14069
14070
14071
14072
14073
14074
14075
14076
14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098
14099
14100
14101
14102
14103
14104
14105
14106
14107
14108
14109
14110
14111
14112
14113
14114
14115
14116
14117
14118
14119
14120
14121
14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135
14136
14137
14138
14139
14140
14141
14142
14143
14144
14145
14146
14147
14148
14149
14150
14151
14152
14153
14154
14155
14156
14157
14158
14159
14160
14161
14162
14163
14164
14165
14166
14167
14168
14169
14170
14171
14172
14173
14174
14175
14176
14177
14178
14179
14180
14181
14182
14183
14184
14185
14186
14187
14188
14189
14190
14191
14192
14193
14194
14195
14196
14197
14198
14199
14200
14201
14202
14203
14204
14205
14206
14207
14208
14209
14210
14211
14212
14213
14214
14215
14216
14217
14218
14219
14220
14221
14222
14223
14224
14225
14226
14227
14228
14229
14230
14231
14232
14233
14234
14235
14236
14237
14238
14239
14240
14241
14242
14243
14244
14245
14246
14247
14248
14249
14250
14251
14252
14253
14254
14255
14256
14257
14258
14259
14260
14261
14262
14263
14264
14265
14266
14267
14268
14269
14270
14271
14272
14273
14274
14275
14276
14277
14278
14279
14280
14281
14282
14283
14284
14285
14286
14287
14288
14289
14290
14291
14292
14293
14294
14295
14296
14297
14298
14299
14300
14301
14302
14303
14304
14305
14306
14307
14308
14309
14310
14311
14312
14313
14314
14315
14316
14317
14318
14319
14320
14321
14322
14323
14324
14325
14326
14327
14328
14329
14330
14331
14332
14333
14334
14335
14336
14337
14338
14339
14340
14341
14342
14343
14344
14345
14346
14347
14348
14349
14350
14351
14352
14353
14354
14355
14356
14357
14358
14359
14360
14361
14362
14363
14364
14365
14366
14367
14368
14369
14370
14371
14372
14373
14374
14375
14376
14377
14378
14379
14380
14381
14382
14383
14384
14385
14386
14387
14388
14389
14390
14391
14392
14393
14394
14395
14396
14397
14398
14399
14400
14401
14402
14403
14404
14405
14406
14407
14408
14409
14410
14411
14412
14413
14414
14415
14416
14417
14418
14419
14420
14421
14422
14423
14424
14425
14426
14427
14428
14429
14430
14431
14432
14433
14434
14435
14436
14437
14438
14439
14440
14441
14442
14443
14444
14445
14446
14447
14448
14449
14450
14451
14452
14453
14454
14455
14456
14457
14458
14459
14460
14461
14462
14463
14464
14465
14466
14467
14468
14469
14470
14471
14472
14473
14474
14475
14476
14477
14478
14479
14480
14481
14482
14483
14484
14485
14486
14487
14488
14489
14490
14491
14492
14493
14494
14495
14496
14497
14498
14499
14500
14501
14502
14503
14504
14505
14506
14507
14508
14509
14510
14511
14512
14513
14514
14515
14516
14517
14518
14519
14520
14521
14522
14523
14524
14525
14526
14527
14528
14529
14530
14531
14532
14533
14534
14535
14536
14537
14538
14539
14540
14541
14542
14543
14544
14545
14546
14547
14548
14549
14550
14551
14552
14553
14554
14555
14556
14557
14558
14559
14560
14561
14562
14563
14564
14565
14566
14567
14568
14569
14570
14571
14572
14573
14574
14575
14576
14577
14578
14579
14580
14581
14582
14583
14584
14585
14586
14587
14588
14589
14590
14591
14592
14593
14594
14595
14596
14597
14598
14599
14600
14601
14602
14603
14604
14605
14606
14607
14608
14609
14610
14611
14612
14613
14614
14615
14616
14617
14618
14619
14620
14621
14622
14623
14624
14625
14626
14627
14628
14629
14630
14631
14632
14633
14634
14635
14636
14637
14638
14639
14640
14641
14642
14643
14644
14645
14646
14647
14648
14649
14650
14651
14652
14653
14654
14655
14656
14657
14658
14659
14660
14661
14662
14663
14664
14665
14666
14667
14668
14669
14670
14671
14672
14673
14674
14675
14676
14677
14678
14679
14680
14681
14682
14683
14684
14685
14686
14687
14688
14689
14690
14691
14692
14693
14694
14695
14696
14697
14698
14699
14700
14701
14702
14703
14704
14705
14706
14707
14708
14709
14710
14711
14712
14713
14714
14715
14716
14717
14718
14719
14720
14721
14722
14723
14724
14725
14726
14727
14728
14729
14730
14731
14732
14733
14734
14735
14736
14737
14738
14739
14740
14741
14742
14743
14744
14745
14746
14747
14748
14749
14750
14751
14752
14753
14754
14755
14756
14757
14758
14759
14760
14761
14762
14763
14764
14765
14766
14767
14768
14769
14770
14771
14772
14773
14774
14775
14776
14777
14778
14779
14780
14781
14782
14783
14784
14785
14786
14787
14788
14789
14790
14791
14792
14793
14794
14795
14796
14797
14798
14799
14800
14801
14802
14803
14804
14805
14806
14807
14808
14809
14810
14811
14812
14813
14814
14815
14816
14817
14818
14819
14820
14821
14822
14823
14824
14825
14826
14827
14828
14829
14830
14831
14832
14833
14834
14835
14836
14837
14838
14839
14840
14841
14842
14843
14844
14845
14846
14847
14848
14849
14850
14851
14852
14853
14854
14855
14856
14857
14858
14859
14860
14861
14862
14863
14864
14865
14866
14867
14868
14869
14870
14871
14872
14873
14874
14875
14876
14877
14878
14879
14880
14881
14882
14883
14884
14885
14886
14887
14888
14889
14890
14891
14892
14893
14894
14895
14896
14897
14898
14899
14900
14901
14902
14903
14904
14905
14906
14907
14908
14909
14910
14911
14912
14913
14914
14915
14916
14917
14918
14919
14920
14921
14922
14923
14924
14925
14926
14927
14928
14929
14930
14931
14932
14933
14934
14935
14936
14937
14938
14939
14940
14941
14942
14943
14944
14945
14946
14947
14948
14949
14950
14951
14952
14953
14954
14955
14956
14957
14958
14959
14960
14961
14962
14963
14964
14965
14966
14967
14968
14969
14970
14971
14972
14973
14974
14975
14976
14977
14978
14979
14980
14981
14982
14983
14984
14985
14986
14987
14988
14989
14990
14991
14992
14993
14994
14995
14996
14997
14998
14999
15000
15001
15002
15003
15004
15005
15006
15007
15008
15009
15010
15011
15012
15013
15014
15015
15016
15017
15018
15019
15020
15021
15022
15023
15024
15025
15026
15027
15028
15029
15030
15031
15032
15033
15034
15035
15036
15037
15038
15039
15040
15041
15042
15043
15044
15045
15046
15047
15048
15049
15050
15051
15052
15053
15054
15055
15056
15057
15058
15059
15060
15061
15062
15063
15064
15065
15066
15067
15068
15069
15070
15071
15072
15073
15074
15075
15076
15077
15078
15079
15080
15081
15082
15083
15084
15085
15086
15087
15088
15089
15090
15091
15092
15093
15094
15095
15096
15097
15098
15099
15100
15101
15102
15103
15104
15105
15106
15107
15108
15109
15110
15111
15112
15113
15114
15115
15116
15117
15118
15119
15120
15121
15122
15123
15124
15125
15126
15127
15128
15129
15130
15131
15132
15133
15134
15135
15136
15137
15138
15139
15140
15141
15142
15143
15144
15145
15146
15147
15148
15149
15150
15151
15152
15153
15154
15155
15156
15157
15158
15159
15160
15161
15162
15163
15164
15165
15166
15167
15168
15169
15170
15171
15172
15173
15174
15175
15176
15177
15178
15179
15180
15181
15182
15183
15184
15185
15186
15187
15188
15189
15190
15191
15192
15193
15194
15195
15196
15197
15198
15199
15200
15201
15202
15203
15204
15205
15206
15207
15208
15209
15210
15211
15212
15213
15214
15215
15216
15217
15218
15219
15220
15221
15222
15223
15224
15225
15226
15227
15228
15229
15230
15231
15232
15233
15234
15235
15236
15237
15238
15239
15240
15241
15242
15243
15244
15245
15246
15247
15248
15249
15250
15251
15252
15253
15254
15255
15256
15257
15258
15259
15260
15261
15262
15263
15264
15265
15266
15267
15268
15269
15270
15271
15272
15273
15274
15275
15276
15277
15278
15279
15280
15281
15282
15283
15284
15285
15286
15287
15288
15289
15290
15291
15292
15293
15294
15295
15296
15297
15298
15299
15300
15301
15302
15303
15304
15305
15306
15307
15308
15309
15310
15311
15312
15313
15314
15315
15316
15317
15318
15319
15320
15321
15322
15323
15324
15325
15326
15327
15328
15329
15330
15331
15332
15333
15334
15335
15336
15337
15338
15339
15340
15341
15342
15343
15344
15345
15346
15347
15348
15349
15350
15351
15352
15353
15354
15355
15356
15357
15358
15359
15360
15361
15362
15363
15364
15365
15366
15367
15368
15369
15370
15371
15372
15373
15374
15375
15376
15377
15378
15379
15380
15381
15382
15383
15384
15385
15386
15387
15388
15389
15390
15391
15392
15393
15394
15395
15396
15397
15398
15399
15400
15401
15402
15403
15404
15405
15406
15407
15408
15409
15410
15411
15412
15413
15414
15415
15416
15417
15418
15419
15420
15421
15422
15423
15424
15425
15426
15427
15428
15429
15430
15431
15432
15433
15434
15435
15436
15437
15438
15439
15440
15441
15442
15443
15444
15445
15446
15447
15448
15449
15450
15451
15452
15453
15454
15455
15456
15457
15458
15459
15460
15461
15462
15463
15464
15465
15466
15467
15468
15469
15470
15471
15472
15473
15474
15475
15476
15477
15478
15479
15480
15481
15482
15483
15484
15485
15486
15487
15488
15489
15490
15491
15492
15493
15494
15495
15496
15497
15498
15499
15500
15501
15502
15503
15504
15505
15506
15507
15508
15509
15510
15511
15512
15513
15514
15515
15516
15517
15518
15519
15520
15521
15522
15523
15524
15525
15526
15527
15528
15529
15530
15531
15532
15533
15534
15535
15536
15537
15538
15539
15540
15541
15542
15543
15544
15545
15546
15547
15548
15549
15550
15551
15552
15553
15554
15555
15556
15557
15558
15559
15560
15561
15562
15563
15564
15565
15566
15567
15568
15569
15570
15571
15572
15573
15574
15575
15576
15577
15578
15579
15580
15581
15582
15583
15584
15585
15586
15587
15588
15589
15590
15591
15592
15593
15594
15595
15596
15597
15598
15599
15600
15601
15602
15603
15604
15605
15606
15607
15608
15609
15610
15611
15612
15613
15614
15615
15616
15617
15618
15619
15620
15621
15622
15623
15624
15625
15626
15627
15628
15629
15630
15631
15632
15633
15634
15635
15636
15637
15638
15639
15640
15641
15642
15643
15644
15645
15646
15647
15648
15649
15650
15651
15652
15653
15654
15655
15656
15657
15658
15659
15660
15661
15662
15663
15664
15665
15666
15667
15668
15669
15670
15671
15672
15673
15674
15675
15676
15677
15678
15679
15680
15681
15682
15683
15684
15685
15686
15687
15688
15689
15690
15691
15692
15693
15694
15695
15696
15697
15698
15699
15700
15701
15702
15703
15704
15705
15706
15707
15708
15709
15710
15711
15712
15713
15714
15715
15716
15717
15718
15719
15720
15721
15722
15723
15724
15725
15726
15727
15728
15729
15730
15731
15732
15733
15734
15735
15736
15737
15738
15739
15740
15741
15742
15743
15744
15745
15746
15747
15748
15749
15750
15751
15752
15753
15754
15755
15756
15757
15758
15759
15760
15761
15762
15763
15764
15765
15766
15767
15768
15769
15770
15771
15772
15773
15774
15775
15776
15777
15778
15779
15780
15781
15782
15783
15784
15785
15786
15787
15788
15789
15790
15791
15792
15793
15794
15795
15796
15797
15798
15799
15800
15801
15802
15803
15804
15805
15806
15807
15808
15809
15810
15811
15812
15813
15814
15815
15816
15817
15818
15819
15820
15821
15822
15823
15824
15825
15826
15827
15828
15829
15830
15831
15832
15833
15834
15835
15836
15837
15838
15839
15840
15841
15842
15843
15844
15845
15846
15847
15848
15849
15850
15851
15852
15853
15854
15855
15856
15857
15858
15859
15860
15861
15862
15863
15864
15865
15866
15867
15868
15869
15870
15871
15872
15873
15874
15875
15876
15877
15878
15879
15880
15881
15882
15883
15884
15885
15886
15887
15888
15889
15890
15891
15892
15893
15894
15895
15896
15897
15898
15899
15900
15901
15902
15903
15904
15905
15906
15907
15908
15909
15910
15911
15912
15913
15914
15915
15916
15917
15918
15919
15920
15921
15922
15923
15924
15925
15926
15927
15928
15929
15930
15931
15932
15933
15934
15935
15936
15937
15938
15939
15940
15941
15942
15943
15944
15945
15946
15947
15948
15949
15950
15951
15952
15953
15954
15955
15956
15957
15958
15959
15960
15961
15962
15963
15964
15965
15966
15967
15968
15969
15970
15971
15972
15973
15974
15975
15976
15977
15978
15979
15980
15981
15982
15983
15984
15985
15986
15987
15988
15989
15990
15991
15992
15993
15994
15995
15996
15997
15998
15999
16000
16001
16002
16003
16004
16005
16006
16007
16008
16009
16010
16011
16012
16013
16014
16015
16016
16017
16018
16019
16020
16021
16022
16023
16024
16025
16026
16027
16028
16029
16030
16031
16032
16033
16034
16035
16036
16037
16038
16039
16040
16041
16042
16043
16044
16045
16046
16047
16048
16049
16050
16051
16052
16053
16054
16055
16056
16057
16058
16059
16060
16061
16062
16063
16064
16065
16066
16067
16068
16069
16070
16071
16072
16073
16074
16075
16076
16077
16078
16079
16080
16081
16082
16083
16084
16085
16086
16087
16088
16089
16090
16091
16092
16093
16094
16095
16096
16097
16098
16099
16100
16101
16102
16103
16104
16105
16106
16107
16108
16109
16110
16111
16112
16113
16114
16115
16116
16117
16118
16119
16120
16121
16122
16123
16124
16125
16126
16127
16128
16129
16130
16131
16132
16133
16134
16135
16136
16137
16138
16139
16140
16141
16142
16143
16144
16145
16146
16147
16148
16149
16150
16151
16152
16153
16154
16155
16156
16157
16158
16159
16160
16161
16162
16163
16164
16165
16166
16167
16168
16169
16170
16171
16172
16173
16174
16175
16176
16177
16178
16179
16180
16181
16182
16183
16184
16185
16186
16187
16188
16189
16190
16191
16192
16193
16194
16195
16196
16197
16198
16199
16200
16201
16202
16203
16204
16205
16206
16207
16208
16209
16210
16211
16212
16213
16214
16215
16216
16217
16218
16219
16220
16221
16222
16223
16224
16225
16226
16227
16228
16229
16230
16231
16232
16233
16234
16235
16236
16237
16238
16239
16240
16241
16242
16243
16244
16245
16246
16247
16248
16249
16250
16251
16252
16253
16254
16255
16256
16257
16258
16259
16260
16261
16262
16263
16264
16265
16266
16267
16268
16269
16270
16271
16272
16273
16274
16275
16276
16277
16278
16279
16280
16281
16282
16283
16284
16285
16286
16287
16288
16289
16290
16291
16292
16293
16294
16295
16296
16297
16298
16299
16300
16301
16302
16303
16304
16305
16306
16307
16308
16309
16310
16311
16312
16313
16314
16315
16316
16317
16318
16319
16320
16321
16322
16323
16324
16325
16326
16327
16328
16329
16330
16331
16332
16333
16334
16335
16336
16337
16338
16339
16340
16341
16342
16343
16344
16345
16346
16347
16348
16349
16350
16351
16352
16353
16354
16355
16356
16357
16358
16359
16360
16361
16362
16363
16364
16365
16366
16367
16368
16369
16370
16371
16372
16373
16374
16375
16376
16377
16378
16379
16380
16381
16382
16383
16384
16385
16386
16387
16388
16389
16390
16391
16392
16393
16394
16395
16396
16397
16398
16399
16400
16401
16402
16403
16404
16405
16406
16407
16408
16409
16410
16411
16412
16413
16414
16415
16416
16417
16418
16419
16420
16421
16422
16423
16424
16425
16426
16427
16428
16429
16430
16431
16432
16433
16434
16435
16436
16437
16438
16439
16440
16441
16442
16443
16444
16445
16446
16447
16448
16449
16450
16451
16452
16453
16454
16455
16456
16457
16458
16459
16460
16461
16462
16463
16464
16465
16466
16467
16468
16469
16470
16471
16472
16473
16474
16475
16476
16477
16478
16479
16480
16481
16482
16483
16484
16485
16486
16487
16488
16489
16490
16491
16492
16493
16494
16495
16496
16497
16498
16499
16500
16501
16502
16503
16504
16505
16506
16507
16508
16509
16510
16511
16512
16513
16514
16515
16516
16517
16518
16519
16520
16521
16522
16523
16524
16525
16526
16527
16528
16529
16530
16531
16532
16533
16534
16535
16536
16537
16538
16539
16540
16541
16542
16543
16544
16545
16546
16547
16548
16549
16550
16551
16552
16553
16554
16555
16556
16557
16558
16559
16560
16561
16562
16563
16564
16565
16566
16567
16568
16569
16570
16571
16572
16573
16574
16575
16576
16577
16578
16579
16580
16581
16582
16583
16584
16585
16586
16587
16588
16589
16590
16591
16592
16593
16594
16595
16596
16597
16598
16599
16600
16601
16602
16603
16604
16605
16606
16607
16608
16609
16610
16611
16612
16613
16614
16615
16616
16617
16618
16619
16620
16621
16622
16623
16624
16625
16626
16627
16628
16629
16630
16631
16632
16633
16634
16635
16636
16637
16638
16639
16640
16641
16642
16643
16644
16645
16646
16647
16648
16649
16650
16651
16652
16653
16654
16655
16656
16657
16658
16659
16660
16661
16662
16663
16664
16665
16666
16667
16668
16669
16670
16671
16672
16673
16674
16675
16676
16677
16678
16679
16680
16681
16682
16683
16684
16685
16686
16687
16688
16689
16690
16691
16692
16693
16694
16695
16696
16697
16698
16699
16700
16701
16702
16703
16704
16705
16706
16707
16708
16709
16710
16711
16712
16713
16714
16715
16716
16717
16718
16719
16720
16721
16722
16723
16724
16725
16726
16727
16728
16729
16730
16731
16732
16733
16734
16735
16736
16737
16738
16739
16740
16741
16742
16743
16744
16745
16746
16747
16748
16749
16750
16751
16752
16753
16754
16755
16756
16757
16758
16759
16760
16761
16762
16763
16764
16765
16766
16767
16768
16769
16770
16771
16772
16773
16774
16775
16776
16777
16778
16779
16780
16781
16782
16783
16784
16785
16786
16787
16788
16789
16790
16791
16792
16793
16794
16795
16796
16797
16798
16799
16800
16801
16802
16803
16804
16805
16806
16807
16808
16809
16810
16811
16812
16813
16814
16815
16816
16817
16818
16819
16820
16821
16822
16823
16824
16825
16826
16827
16828
16829
16830
16831
16832
16833
16834
16835
16836
16837
16838
16839
16840
16841
16842
16843
16844
16845
16846
16847
16848
16849
16850
16851
16852
16853
16854
16855
16856
16857
16858
16859
16860
16861
16862
16863
16864
16865
16866
16867
16868
16869
16870
16871
16872
16873
16874
16875
16876
16877
16878
16879
16880
16881
16882
16883
16884
16885
16886
16887
16888
16889
16890
16891
16892
16893
16894
16895
16896
16897
16898
16899
16900
16901
16902
16903
16904
16905
16906
16907
16908
16909
16910
16911
16912
16913
16914
16915
16916
16917
16918
16919
16920
16921
16922
16923
16924
16925
16926
16927
16928
16929
16930
16931
16932
16933
16934
16935
16936
16937
16938
16939
16940
16941
16942
16943
16944
16945
16946
16947
16948
16949
16950
16951
16952
16953
16954
16955
16956
16957
16958
16959
16960
16961
16962
16963
16964
16965
16966
16967
16968
16969
16970
16971
16972
16973
16974
16975
16976
16977
16978
16979
16980
16981
16982
16983
16984
16985
16986
16987
16988
16989
16990
16991
16992
16993
16994
16995
16996
16997
16998
16999
17000
17001
17002
17003
17004
17005
17006
17007
17008
17009
17010
17011
17012
17013
17014
17015
17016
17017
17018
17019
17020
17021
17022
17023
17024
17025
17026
17027
17028
17029
17030
17031
17032
17033
17034
17035
17036
17037
17038
17039
17040
17041
17042
17043
17044
17045
17046
17047
17048
17049
17050
17051
17052
17053
17054
17055
17056
17057
17058
17059
17060
17061
17062
17063
17064
17065
17066
17067
17068
17069
17070
17071
17072
17073
17074
17075
17076
17077
17078
17079
17080
17081
17082
17083
17084
17085
17086
17087
17088
17089
17090
17091
17092
17093
17094
17095
17096
17097
17098
17099
17100
17101
17102
17103
17104
17105
17106
17107
17108
17109
17110
17111
17112
17113
17114
17115
17116
17117
17118
17119
17120
17121
17122
17123
17124
17125
17126
17127
17128
17129
17130
17131
17132
17133
17134
17135
17136
17137
17138
17139
17140
17141
17142
17143
17144
17145
17146
17147
17148
17149
17150
17151
17152
17153
17154
17155
17156
17157
17158
17159
17160
17161
17162
17163
17164
17165
17166
17167
17168
17169
17170
17171
17172
17173
17174
17175
17176
17177
17178
17179
17180
17181
17182
17183
17184
17185
17186
17187
17188
17189
17190
17191
17192
17193
17194
17195
17196
17197
17198
17199
17200
17201
17202
17203
17204
17205
17206
17207
17208
17209
17210
17211
17212
17213
17214
17215
17216
17217
17218
17219
17220
17221
17222
17223
17224
17225
17226
17227
17228
17229
17230
17231
17232
17233
17234
17235
17236
17237
17238
17239
17240
17241
17242
17243
17244
17245
17246
17247
17248
17249
17250
17251
17252
17253
17254
17255
17256
17257
17258
17259
17260
17261
17262
17263
17264
17265
17266
17267
17268
17269
17270
17271
17272
17273
17274
17275
17276
17277
17278
17279
17280
17281
17282
17283
17284
17285
17286
17287
17288
17289
17290
17291
17292
17293
17294
17295
17296
17297
17298
17299
17300
17301
17302
17303
17304
17305
17306
17307
17308
17309
17310
17311
17312
17313
17314
17315
17316
17317
17318
17319
17320
17321
17322
17323
17324
17325
17326
17327
17328
17329
17330
17331
17332
17333
17334
17335
17336
17337
17338
17339
17340
17341
17342
17343
17344
17345
17346
17347
17348
17349
17350
17351
17352
17353
17354
17355
17356
17357
17358
17359
17360
17361
17362
17363
17364
17365
17366
17367
17368
17369
17370
17371
17372
17373
17374
17375
17376
17377
17378
17379
17380
17381
17382
17383
17384
17385
17386
17387
17388
17389
17390
17391
17392
17393
17394
17395
17396
17397
17398
17399
17400
17401
17402
17403
17404
17405
17406
17407
17408
17409
17410
17411
17412
17413
17414
17415
17416
17417
17418
17419
17420
17421
17422
17423
17424
17425
17426
17427
17428
17429
17430
17431
17432
17433
17434
17435
17436
17437
17438
17439
17440
17441
17442
17443
17444
17445
17446
17447
17448
17449
17450
17451
17452
17453
17454
17455
17456
17457
17458
17459
17460
17461
17462
17463
17464
17465
17466
17467
17468
17469
17470
17471
17472
17473
17474
17475
17476
17477
17478
17479
17480
17481
17482
17483
17484
17485
17486
17487
17488
17489
17490
17491
17492
17493
17494
17495
17496
17497
17498
17499
17500
17501
17502
17503
17504
17505
17506
17507
17508
17509
17510
17511
17512
17513
17514
17515
17516
17517
17518
17519
17520
17521
17522
17523
17524
17525
17526
17527
17528
17529
17530
17531
17532
17533
17534
17535
17536
17537
17538
17539
17540
17541
17542
17543
17544
17545
17546
17547
17548
17549
17550
17551
17552
17553
17554
17555
17556
17557
17558
17559
17560
17561
17562
17563
17564
17565
17566
17567
17568
17569
17570
17571
17572
17573
17574
17575
17576
17577
17578
17579
17580
17581
17582
17583
17584
17585
17586
17587
17588
17589
17590
17591
17592
17593
17594
17595
17596
17597
17598
17599
17600
17601
17602
17603
17604
17605
17606
17607
17608
17609
17610
17611
17612
17613
17614
17615
17616
17617
17618
17619
17620
17621
17622
17623
17624
17625
17626
17627
17628
17629
17630
17631
17632
17633
17634
17635
17636
17637
17638
17639
17640
17641
17642
17643
17644
17645
17646
17647
17648
17649
17650
17651
17652
17653
17654
17655
17656
17657
17658
17659
17660
17661
17662
17663
17664
17665
17666
17667
17668
17669
17670
17671
17672
17673
17674
17675
17676
17677
17678
17679
17680
17681
17682
17683
17684
17685
17686
17687
17688
17689
17690
17691
17692
17693
17694
17695
17696
17697
17698
17699
17700
17701
17702
17703
17704
17705
17706
17707
17708
17709
17710
17711
17712
17713
17714
17715
17716
17717
17718
17719
17720
17721
17722
17723
17724
17725
17726
17727
17728
17729
17730
17731
17732
17733
17734
17735
17736
17737
17738
17739
17740
17741
17742
17743
17744
17745
17746
17747
17748
17749
17750
17751
17752
17753
17754
17755
17756
17757
17758
17759
17760
17761
17762
17763
17764
17765
17766
17767
17768
17769
17770
17771
17772
17773
17774
17775
17776
17777
17778
17779
17780
17781
17782
17783
17784
17785
17786
17787
17788
17789
17790
17791
17792
17793
17794
17795
17796
17797
17798
17799
17800
17801
17802
17803
17804
17805
17806
17807
17808
17809
17810
17811
17812
17813
17814
17815
17816
17817
17818
17819
17820
17821
17822
17823
17824
17825
17826
17827
17828
17829
17830
17831
17832
17833
17834
17835
17836
17837
17838
17839
17840
17841
17842
17843
17844
17845
17846
17847
17848
17849
17850
17851
17852
17853
17854
17855
17856
17857
17858
17859
17860
17861
17862
17863
17864
17865
17866
17867
17868
17869
17870
17871
17872
17873
17874
17875
17876
17877
17878
17879
17880
17881
17882
17883
17884
17885
17886
17887
17888
17889
17890
17891
17892
17893
17894
17895
17896
17897
17898
17899
17900
17901
17902
17903
17904
17905
17906
17907
17908
17909
17910
17911
17912
17913
17914
17915
17916
17917
17918
17919
17920
17921
17922
17923
17924
17925
17926
17927
17928
17929
17930
17931
17932
17933
17934
17935
17936
17937
17938
17939
17940
17941
17942
17943
17944
17945
17946
17947
17948
17949
17950
17951
17952
17953
17954
17955
17956
17957
17958
17959
17960
17961
17962
17963
17964
17965
17966
17967
17968
17969
17970
17971
17972
17973
17974
17975
17976
17977
17978
17979
17980
17981
17982
17983
17984
17985
17986
17987
17988
17989
17990
17991
17992
17993
17994
17995
17996
17997
17998
17999
18000
18001
18002
18003
18004
18005
18006
18007
18008
18009
18010
18011
18012
18013
18014
18015
18016
18017
18018
18019
18020
18021
18022
18023
18024
18025
18026
18027
18028
18029
18030
18031
18032
18033
18034
18035
18036
18037
18038
18039
18040
18041
18042
18043
18044
18045
18046
18047
18048
18049
18050
18051
18052
18053
18054
18055
18056
18057
18058
18059
18060
18061
18062
18063
18064
18065
18066
18067
18068
18069
18070
18071
18072
18073
18074
18075
18076
18077
18078
18079
18080
18081
18082
18083
18084
18085
18086
18087
18088
18089
18090
18091
18092
18093
18094
18095
18096
18097
18098
18099
18100
18101
18102
18103
18104
18105
18106
18107
18108
18109
18110
18111
18112
18113
18114
18115
18116
18117
18118
18119
18120
18121
18122
18123
18124
18125
18126
18127
18128
18129
18130
18131
18132
18133
18134
18135
18136
18137
18138
18139
18140
18141
18142
18143
18144
18145
18146
18147
18148
18149
18150
18151
18152
18153
18154
18155
18156
18157
18158
18159
18160
18161
18162
18163
18164
18165
18166
18167
18168
18169
18170
18171
18172
18173
18174
18175
18176
18177
18178
18179
18180
18181
18182
18183
18184
18185
18186
18187
18188
18189
18190
18191
18192
18193
18194
18195
18196
18197
18198
18199
18200
18201
18202
18203
18204
18205
18206
18207
18208
18209
18210
18211
18212
18213
18214
18215
18216
18217
18218
18219
18220
18221
18222
18223
18224
18225
18226
18227
18228
18229
18230
18231
18232
18233
18234
18235
18236
18237
18238
18239
18240
18241
18242
18243
18244
18245
18246
18247
18248
18249
18250
18251
18252
18253
18254
18255
18256
18257
18258
18259
18260
18261
18262
18263
18264
18265
18266
18267
18268
18269
18270
18271
18272
18273
18274
18275
18276
18277
18278
18279
18280
18281
18282
18283
18284
18285
18286
18287
18288
18289
18290
18291
18292
18293
18294
18295
18296
18297
18298
18299
18300
18301
18302
18303
18304
18305
18306
18307
18308
18309
18310
18311
18312
18313
18314
18315
18316
18317
18318
18319
18320
18321
18322
18323
18324
18325
18326
18327
18328
18329
18330
18331
18332
18333
18334
18335
18336
18337
18338
18339
18340
18341
18342
18343
18344
18345
18346
18347
18348
18349
18350
18351
18352
18353
18354
18355
18356
18357
18358
18359
18360
18361
18362
18363
18364
18365
18366
18367
18368
18369
18370
18371
18372
18373
18374
18375
18376
18377
18378
18379
18380
18381
18382
18383
18384
18385
18386
18387
18388
18389
18390
18391
18392
18393
18394
18395
18396
18397
18398
18399
18400
18401
18402
18403
18404
18405
18406
18407
18408
18409
18410
18411
18412
18413
18414
18415
18416
18417
18418
18419
18420
18421
18422
18423
18424
18425
18426
18427
18428
18429
18430
18431
18432
18433
18434
18435
18436
18437
18438
18439
18440
18441
18442
18443
18444
18445
18446
18447
18448
18449
18450
18451
18452
18453
18454
18455
18456
18457
18458
18459
18460
18461
18462
18463
18464
18465
18466
18467
18468
18469
18470
18471
18472
18473
18474
18475
18476
18477
18478
18479
18480
18481
18482
18483
18484
18485
18486
18487
18488
18489
18490
18491
18492
18493
18494
18495
18496
18497
18498
18499
18500
18501
18502
18503
18504
18505
18506
18507
18508
18509
18510
18511
18512
18513
18514
18515
18516
18517
18518
18519
18520
18521
18522
18523
18524
18525
18526
18527
18528
18529
18530
18531
18532
18533
18534
18535
18536
18537
18538
18539
18540
18541
18542
18543
18544
18545
18546
18547
18548
18549
18550
18551
18552
18553
18554
18555
18556
18557
18558
18559
18560
18561
18562
18563
18564
18565
18566
18567
18568
18569
18570
18571
18572
18573
18574
18575
18576
18577
18578
18579
18580
18581
18582
18583
18584
18585
18586
18587
18588
18589
18590
18591
18592
18593
18594
18595
18596
18597
18598
18599
18600
18601
18602
18603
18604
18605
18606
18607
18608
18609
18610
18611
18612
18613
18614
18615
18616
18617
18618
18619
18620
18621
18622
18623
18624
18625
18626
18627
18628
18629
18630
18631
18632
18633
18634
18635
18636
18637
18638
18639
18640
18641
18642
18643
18644
18645
18646
18647
18648
18649
18650
18651
18652
18653
18654
18655
18656
18657
18658
18659
18660
18661
18662
18663
18664
18665
18666
18667
18668
18669
18670
18671
18672
18673
18674
18675
18676
18677
18678
18679
18680
18681
18682
18683
18684
18685
18686
18687
18688
18689
18690
18691
18692
18693
18694
18695
18696
18697
18698
18699
18700
18701
18702
18703
18704
18705
18706
18707
18708
18709
18710
18711
18712
18713
18714
18715
18716
18717
18718
18719
18720
18721
18722
18723
18724
18725
18726
18727
18728
18729
18730
18731
18732
18733
18734
18735
18736
18737
18738
18739
18740
18741
18742
18743
18744
18745
18746
18747
18748
18749
18750
18751
18752
18753
18754
18755
18756
18757
18758
18759
18760
18761
18762
18763
18764
18765
18766
18767
18768
18769
18770
18771
18772
18773
18774
18775
18776
18777
18778
18779
18780
18781
18782
18783
18784
18785
18786
18787
18788
18789
18790
18791
18792
18793
18794
18795
18796
18797
18798
18799
18800
18801
18802
18803
18804
18805
18806
18807
18808
18809
18810
18811
18812
18813
18814
18815
18816
18817
18818
18819
18820
18821
18822
18823
18824
18825
18826
18827
18828
18829
18830
18831
18832
18833
18834
18835
18836
18837
18838
18839
18840
18841
18842
18843
18844
18845
18846
18847
18848
18849
18850
18851
18852
18853
18854
18855
18856
18857
18858
18859
18860
18861
18862
18863
18864
18865
18866
18867
18868
18869
18870
18871
18872
18873
18874
18875
18876
18877
18878
18879
18880
18881
18882
18883
18884
18885
18886
18887
18888
18889
18890
18891
18892
18893
18894
18895
18896
18897
18898
18899
18900
18901
18902
18903
18904
18905
18906
18907
18908
18909
18910
18911
18912
18913
18914
18915
18916
18917
18918
18919
18920
18921
18922
18923
18924
18925
18926
18927
18928
18929
18930
18931
18932
18933
18934
18935
18936
18937
18938
18939
18940
18941
18942
18943
18944
18945
18946
18947
18948
18949
18950
18951
18952
18953
18954
18955
18956
18957
18958
18959
18960
18961
18962
18963
18964
18965
18966
18967
18968
18969
18970
18971
18972
18973
18974
18975
18976
18977
18978
18979
18980
18981
18982
18983
18984
18985
18986
18987
18988
18989
18990
18991
18992
18993
18994
18995
18996
18997
18998
18999
19000
19001
19002
19003
19004
19005
19006
19007
19008
19009
19010
19011
19012
19013
19014
19015
19016
19017
19018
19019
19020
19021
19022
19023
19024
19025
19026
19027
19028
19029
19030
19031
19032
19033
19034
19035
19036
19037
19038
19039
19040
19041
19042
19043
19044
19045
19046
19047
19048
19049
19050
19051
19052
19053
19054
19055
19056
19057
19058
19059
19060
19061
19062
19063
19064
19065
19066
19067
19068
19069
19070
19071
19072
19073
19074
19075
19076
19077
19078
19079
19080
19081
19082
19083
19084
19085
19086
19087
19088
19089
19090
19091
19092
19093
19094
19095
19096
19097
19098
19099
19100
19101
19102
19103
19104
19105
19106
19107
19108
19109
19110
19111
19112
19113
19114
19115
19116
19117
19118
19119
19120
19121
19122
19123
19124
19125
19126
19127
19128
19129
19130
19131
19132
19133
19134
19135
19136
19137
19138
19139
19140
19141
19142
19143
19144
19145
19146
19147
19148
19149
19150
19151
19152
19153
19154
19155
19156
19157
19158
19159
19160
19161
19162
19163
19164
19165
19166
19167
19168
19169
19170
19171
19172
19173
19174
19175
19176
19177
19178
19179
19180
19181
19182
19183
19184
19185
19186
19187
19188
19189
19190
19191
19192
19193
19194
19195
19196
19197
19198
19199
19200
19201
19202
19203
19204
19205
19206
19207
19208
19209
19210
19211
19212
19213
19214
19215
19216
19217
19218
19219
19220
19221
19222
19223
19224
19225
19226
19227
19228
19229
19230
19231
19232
19233
19234
19235
19236
19237
19238
19239
19240
19241
19242
19243
19244
19245
19246
19247
19248
19249
19250
19251
19252
19253
19254
19255
19256
19257
19258
19259
19260
19261
19262
19263
19264
19265
19266
19267
19268
19269
19270
19271
19272
19273
19274
19275
19276
19277
19278
19279
19280
19281
19282
19283
19284
19285
19286
19287
19288
19289
19290
19291
19292
19293
19294
19295
19296
19297
19298
19299
19300
19301
19302
19303
19304
19305
19306
19307
19308
19309
19310
19311
19312
19313
19314
19315
19316
19317
19318
19319
19320
19321
19322
19323
19324
19325
19326
19327
19328
19329
19330
19331
19332
19333
19334
19335
19336
19337
19338
19339
19340
19341
19342
19343
19344
19345
19346
19347
19348
19349
19350
19351
19352
19353
19354
19355
19356
19357
19358
19359
19360
19361
19362
19363
19364
19365
19366
19367
19368
19369
19370
19371
19372
19373
19374
19375
19376
19377
19378
19379
19380
19381
19382
19383
19384
19385
19386
19387
19388
19389
19390
19391
19392
19393
19394
19395
19396
19397
19398
19399
19400
19401
19402
19403
19404
19405
19406
19407
19408
19409
19410
19411
19412
19413
19414
19415
19416
19417
19418
19419
19420
19421
19422
19423
19424
19425
19426
19427
19428
19429
19430
19431
19432
19433
19434
19435
19436
19437
19438
19439
19440
19441
19442
19443
19444
19445
19446
19447
19448
19449
19450
19451
19452
19453
19454
19455
19456
19457
19458
19459
19460
19461
19462
19463
19464
19465
19466
19467
19468
19469
19470
19471
19472
19473
19474
19475
19476
19477
19478
19479
19480
19481
19482
19483
19484
19485
19486
19487
19488
19489
19490
19491
19492
19493
19494
19495
19496
19497
19498
19499
19500
19501
19502
19503
19504
19505
19506
19507
19508
19509
19510
19511
19512
19513
19514
19515
19516
19517
19518
19519
19520
19521
19522
19523
19524
19525
19526
19527
19528
19529
19530
19531
19532
19533
19534
19535
19536
19537
19538
19539
19540
19541
19542
19543
19544
19545
19546
19547
19548
19549
19550
19551
19552
19553
19554
19555
19556
19557
19558
19559
19560
19561
19562
19563
19564
19565
19566
19567
19568
19569
19570
19571
19572
19573
19574
19575
19576
19577
19578
19579
19580
19581
19582
19583
19584
19585
19586
19587
19588
19589
19590
19591
19592
19593
19594
19595
19596
19597
19598
19599
19600
19601
19602
19603
19604
19605
19606
19607
19608
19609
19610
19611
19612
19613
19614
19615
19616
19617
19618
19619
19620
19621
19622
19623
19624
19625
19626
19627
19628
19629
19630
19631
19632
19633
19634
19635
19636
19637
19638
19639
19640
19641
19642
19643
19644
19645
19646
19647
19648
19649
19650
19651
19652
19653
19654
19655
19656
19657
19658
19659
19660
19661
19662
19663
19664
19665
19666
19667
19668
19669
19670
19671
19672
19673
19674
19675
19676
19677
19678
19679
19680
19681
19682
19683
19684
19685
19686
19687
19688
19689
19690
19691
19692
19693
19694
19695
19696
19697
19698
19699
19700
19701
19702
19703
19704
19705
19706
19707
19708
19709
19710
19711
19712
19713
19714
19715
19716
19717
19718
19719
19720
19721
19722
19723
19724
19725
19726
19727
19728
19729
19730
19731
19732
19733
19734
19735
19736
19737
19738
19739
19740
19741
19742
19743
19744
19745
19746
19747
19748
19749
19750
19751
19752
19753
19754
19755
19756
19757
19758
19759
19760
19761
19762
19763
19764
19765
19766
19767
19768
19769
19770
19771
19772
19773
19774
19775
19776
19777
19778
19779
19780
19781
19782
19783
19784
19785
19786
19787
19788
19789
19790
19791
19792
19793
19794
19795
19796
19797
19798
19799
19800
19801
19802
19803
19804
19805
19806
19807
19808
19809
19810
19811
19812
19813
19814
19815
19816
19817
19818
19819
19820
19821
19822
19823
19824
19825
19826
19827
19828
19829
19830
19831
19832
19833
19834
19835
19836
19837
19838
19839
19840
19841
19842
19843
19844
19845
19846
19847
19848
19849
19850
19851
19852
19853
19854
19855
19856
19857
19858
19859
19860
19861
19862
19863
19864
19865
19866
19867
19868
19869
19870
19871
19872
19873
19874
19875
19876
19877
19878
19879
19880
19881
19882
19883
19884
19885
19886
19887
19888
19889
19890
19891
19892
19893
19894
19895
19896
19897
19898
19899
19900
19901
19902
19903
19904
19905
19906
19907
19908
19909
19910
19911
19912
19913
19914
19915
19916
19917
19918
19919
19920
19921
19922
19923
19924
19925
19926
19927
19928
19929
19930
19931
19932
19933
19934
19935
19936
19937
19938
19939
19940
19941
19942
19943
19944
19945
19946
19947
19948
19949
19950
19951
19952
19953
19954
19955
19956
19957
19958
19959
19960
19961
19962
19963
19964
19965
19966
19967
19968
19969
19970
19971
19972
19973
19974
19975
19976
19977
19978
19979
19980
19981
19982
19983
19984
19985
19986
19987
19988
19989
19990
19991
19992
19993
19994
19995
19996
19997
19998
19999
20000
20001
20002
20003
20004
20005
20006
20007
20008
20009
20010
20011
20012
20013
20014
20015
20016
20017
20018
20019
20020
20021
20022
20023
20024
20025
20026
20027
20028
20029
20030
20031
20032
20033
20034
20035
20036
20037
20038
20039
20040
20041
20042
20043
20044
20045
20046
20047
20048
20049
20050
20051
20052
20053
20054
20055
20056
20057
20058
20059
20060
20061
20062
20063
20064
20065
20066
20067
20068
20069
20070
20071
20072
20073
20074
20075
20076
20077
20078
20079
20080
20081
20082
20083
20084
20085
20086
20087
20088
20089
20090
20091
20092
20093
20094
20095
20096
20097
20098
20099
20100
20101
20102
20103
20104
20105
20106
20107
20108
20109
20110
20111
20112
20113
20114
20115
20116
20117
20118
20119
20120
20121
20122
20123
20124
20125
20126
20127
20128
20129
20130
20131
20132
20133
20134
20135
20136
20137
20138
20139
20140
20141
20142
20143
20144
20145
20146
20147
20148
20149
20150
20151
20152
20153
20154
20155
20156
20157
20158
20159
20160
20161
20162
20163
20164
20165
20166
20167
20168
20169
20170
20171
20172
20173
20174
20175
20176
20177
20178
20179
20180
20181
20182
20183
20184
20185
20186
20187
20188
20189
20190
20191
20192
20193
20194
20195
20196
20197
20198
20199
20200
20201
20202
20203
20204
20205
20206
20207
20208
20209
20210
20211
20212
20213
20214
20215
20216
20217
20218
20219
20220
20221
20222
20223
20224
20225
20226
20227
20228
20229
20230
20231
20232
20233
20234
20235
20236
20237
20238
20239
20240
20241
20242
20243
20244
20245
20246
20247
20248
20249
20250
20251
20252
20253
20254
20255
20256
20257
20258
20259
20260
20261
20262
20263
20264
20265
20266
20267
20268
20269
20270
20271
20272
20273
20274
20275
20276
20277
20278
20279
20280
20281
20282
20283
20284
20285
20286
20287
20288
20289
20290
20291
20292
20293
20294
20295
20296
20297
20298
20299
20300
20301
20302
20303
20304
20305
20306
20307
20308
20309
20310
20311
20312
20313
20314
20315
20316
20317
20318
20319
20320
20321
20322
20323
20324
20325
20326
20327
20328
20329
20330
20331
20332
20333
20334
20335
20336
20337
20338
20339
20340
20341
20342
20343
20344
20345
20346
20347
20348
20349
20350
20351
20352
20353
20354
20355
20356
20357
20358
20359
20360
20361
20362
20363
20364
20365
20366
20367
20368
20369
20370
20371
20372
20373
20374
20375
20376
20377
20378
20379
20380
20381
20382
20383
20384
20385
20386
20387
20388
20389
20390
20391
20392
20393
20394
20395
20396
20397
20398
20399
20400
20401
20402
20403
20404
20405
20406
20407
20408
20409
20410
20411
20412
20413
20414
20415
20416
20417
20418
20419
20420
20421
20422
20423
20424
20425
20426
20427
20428
20429
20430
20431
20432
20433
20434
20435
20436
20437
20438
20439
20440
20441
20442
20443
20444
20445
20446
20447
20448
20449
20450
20451
20452
20453
20454
20455
20456
20457
20458
20459
20460
20461
20462
20463
20464
20465
20466
20467
20468
20469
20470
20471
20472
20473
20474
20475
20476
20477
20478
20479
20480
20481
20482
20483
20484
20485
20486
20487
20488
20489
20490
20491
20492
20493
20494
20495
20496
20497
20498
20499
20500
20501
20502
20503
20504
20505
20506
20507
20508
20509
20510
20511
20512
20513
20514
20515
20516
20517
20518
20519
20520
20521
20522
20523
20524
20525
20526
20527
20528
20529
20530
20531
20532
20533
20534
20535
20536
20537
20538
20539
20540
20541
20542
20543
20544
20545
20546
20547
20548
20549
20550
20551
20552
20553
20554
20555
20556
20557
20558
20559
20560
20561
20562
20563
20564
20565
20566
20567
20568
20569
20570
20571
20572
20573
20574
20575
20576
20577
20578
20579
20580
20581
20582
20583
20584
20585
20586
20587
20588
20589
20590
20591
20592
20593
20594
20595
20596
20597
20598
20599
20600
20601
20602
20603
20604
20605
20606
20607
20608
20609
20610
20611
20612
20613
20614
20615
20616
20617
20618
20619
20620
20621
20622
20623
20624
20625
20626
20627
20628
20629
20630
20631
20632
20633
20634
20635
20636
20637
20638
20639
20640
20641
20642
20643
20644
20645
20646
20647
20648
20649
20650
20651
20652
20653
20654
20655
20656
20657
20658
20659
20660
20661
20662
20663
20664
20665
20666
20667
20668
20669
20670
20671
20672
20673
20674
20675
20676
20677
20678
20679
20680
20681
20682
20683
20684
20685
20686
20687
20688
20689
20690
20691
20692
20693
20694
20695
20696
20697
20698
20699
20700
20701
20702
20703
20704
20705
20706
20707
20708
20709
20710
20711
20712
20713
20714
20715
20716
20717
20718
20719
20720
20721
20722
20723
20724
20725
20726
20727
20728
20729
20730
20731
20732
20733
20734
20735
20736
20737
20738
20739
20740
20741
20742
20743
20744
20745
20746
20747
20748
20749
20750
20751
20752
20753
20754
20755
20756
20757
20758
20759
20760
20761
20762
20763
20764
20765
20766
20767
20768
20769
20770
20771
20772
20773
20774
20775
20776
20777
20778
20779
20780
20781
20782
20783
20784
20785
20786
20787
20788
20789
20790
20791
20792
20793
20794
20795
20796
20797
20798
20799
20800
20801
20802
20803
20804
20805
20806
20807
20808
20809
20810
20811
20812
20813
20814
20815
20816
20817
20818
20819
20820
20821
20822
20823
20824
20825
20826
20827
20828
20829
20830
20831
20832
20833
20834
20835
20836
20837
20838
20839
20840
20841
20842
20843
20844
20845
20846
20847
20848
20849
20850
20851
20852
20853
20854
20855
20856
20857
20858
20859
20860
20861
20862
20863
20864
20865
20866
20867
20868
20869
20870
20871
20872
20873
20874
20875
20876
20877
20878
20879
20880
20881
20882
20883
20884
20885
20886
20887
20888
20889
20890
20891
20892
20893
20894
20895
20896
20897
20898
20899
20900
20901
20902
20903
20904
20905
20906
20907
20908
20909
20910
20911
20912
20913
20914
20915
20916
20917
20918
20919
20920
20921
20922
20923
20924
20925
20926
20927
20928
20929
20930
20931
20932
20933
20934
20935
20936
20937
20938
20939
20940
20941
20942
20943
20944
20945
20946
20947
20948
20949
20950
20951
20952
20953
20954
20955
20956
20957
20958
20959
20960
20961
20962
20963
20964
20965
20966
20967
20968
20969
20970
20971
20972
20973
20974
20975
20976
20977
20978
20979
20980
20981
20982
20983
20984
20985
20986
20987
20988
20989
20990
20991
20992
20993
20994
20995
20996
20997
20998
20999
21000
21001
21002
21003
21004
21005
21006
21007
21008
21009
21010
21011
21012
21013
21014
21015
21016
21017
21018
21019
21020
21021
21022
21023
21024
21025
21026
21027
21028
21029
21030
21031
21032
21033
21034
21035
21036
21037
21038
21039
21040
21041
21042
21043
21044
21045
21046
21047
21048
21049
21050
21051
21052
21053
21054
21055
21056
21057
21058
21059
21060
21061
21062
21063
21064
21065
21066
21067
21068
21069
21070
21071
21072
21073
21074
21075
21076
21077
21078
21079
21080
21081
21082
21083
21084
21085
21086
21087
21088
21089
21090
21091
21092
21093
21094
21095
21096
21097
21098
21099
21100
21101
21102
21103
21104
21105
21106
21107
21108
21109
21110
21111
21112
21113
21114
21115
21116
21117
21118
21119
21120
21121
21122
21123
21124
21125
21126
21127
21128
21129
21130
21131
21132
21133
21134
21135
21136
21137
21138
21139
21140
21141
21142
21143
21144
21145
21146
21147
21148
21149
21150
21151
21152
21153
21154
21155
21156
21157
21158
21159
21160
21161
21162
21163
21164
21165
21166
21167
21168
21169
21170
21171
21172
21173
21174
21175
21176
21177
21178
21179
21180
21181
21182
21183
21184
21185
21186
21187
21188
21189
21190
21191
21192
21193
21194
21195
21196
21197
21198
21199
21200
21201
21202
21203
21204
21205
21206
21207
21208
21209
21210
21211
21212
21213
21214
21215
21216
21217
21218
21219
21220
21221
21222
21223
21224
21225
21226
21227
21228
21229
21230
21231
21232
21233
21234
21235
21236
21237
21238
21239
21240
21241
21242
21243
21244
21245
21246
21247
21248
21249
21250
21251
21252
21253
21254
21255
21256
21257
21258
21259
21260
21261
21262
21263
21264
21265
21266
21267
21268
21269
21270
21271
21272
21273
21274
21275
21276
21277
21278
21279
21280
21281
21282
21283
21284
21285
21286
21287
21288
21289
21290
21291
21292
21293
21294
21295
21296
21297
21298
21299
21300
21301
21302
21303
21304
21305
21306
21307
21308
21309
21310
21311
21312
21313
21314
21315
21316
21317
21318
21319
21320
21321
21322
21323
21324
21325
21326
21327
21328
21329
21330
21331
21332
21333
21334
21335
21336
21337
21338
21339
21340
21341
21342
21343
21344
21345
21346
21347
21348
21349
21350
21351
21352
21353
21354
21355
21356
21357
21358
21359
21360
21361
21362
21363
21364
21365
21366
21367
21368
21369
21370
21371
21372
21373
21374
21375
21376
21377
21378
21379
21380
21381
21382
21383
21384
21385
21386
21387
21388
21389
21390
21391
21392
21393
21394
21395
21396
21397
21398
21399
21400
21401
21402
21403
21404
21405
21406
21407
21408
21409
21410
21411
21412
21413
21414
21415
21416
21417
21418
21419
21420
21421
21422
21423
21424
21425
21426
21427
21428
21429
21430
21431
21432
21433
21434
21435
21436
21437
21438
21439
21440
21441
21442
21443
21444
21445
21446
21447
21448
21449
21450
21451
21452
21453
21454
21455
21456
21457
21458
21459
21460
21461
21462
21463
21464
21465
21466
21467
21468
21469
21470
21471
21472
21473
21474
21475
21476
21477
21478
21479
21480
21481
21482
21483
21484
21485
21486
21487
21488
21489
21490
21491
21492
21493
21494
21495
21496
21497
21498
21499
21500
21501
21502
21503
21504
21505
21506
21507
21508
21509
21510
21511
21512
21513
21514
21515
21516
21517
21518
21519
21520
21521
21522
21523
21524
21525
21526
21527
21528
21529
21530
21531
21532
21533
21534
21535
21536
21537
21538
21539
21540
21541
21542
21543
21544
21545
21546
21547
21548
21549
21550
21551
21552
21553
21554
21555
21556
21557
21558
21559
21560
21561
21562
21563
21564
21565
21566
21567
21568
21569
21570
21571
21572
21573
21574
21575
21576
21577
21578
21579
21580
21581
21582
21583
21584
21585
21586
21587
21588
21589
21590
21591
21592
21593
21594
21595
21596
21597
21598
21599
21600
21601
21602
21603
21604
21605
21606
21607
21608
21609
21610
21611
21612
21613
21614
21615
21616
21617
21618
21619
21620
21621
21622
21623
21624
21625
21626
21627
21628
21629
21630
21631
21632
21633
21634
21635
21636
21637
21638
21639
21640
21641
21642
21643
21644
21645
21646
21647
21648
21649
21650
21651
21652
21653
21654
21655
21656
21657
21658
21659
21660
21661
21662
21663
21664
21665
21666
21667
21668
21669
21670
21671
21672
21673
21674
21675
21676
21677
21678
21679
21680
21681
21682
21683
21684
21685
21686
21687
21688
21689
21690
21691
21692
21693
21694
21695
21696
21697
21698
21699
21700
21701
21702
21703
21704
21705
21706
21707
21708
21709
21710
21711
21712
21713
21714
21715
21716
21717
21718
21719
21720
21721
21722
21723
21724
21725
21726
21727
21728
21729
21730
21731
21732
21733
21734
21735
21736
21737
21738
21739
21740
21741
21742
21743
21744
21745
21746
21747
21748
21749
21750
21751
21752
21753
21754
21755
21756
21757
21758
21759
21760
21761
21762
21763
21764
21765
21766
21767
21768
21769
21770
21771
21772
21773
21774
21775
21776
21777
21778
21779
21780
21781
21782
21783
21784
21785
21786
21787
21788
21789
21790
21791
21792
21793
21794
21795
21796
21797
21798
21799
21800
21801
21802
21803
21804
21805
21806
21807
21808
21809
21810
21811
21812
21813
21814
21815
21816
21817
21818
21819
21820
21821
21822
21823
21824
21825
21826
21827
21828
21829
21830
21831
21832
21833
21834
21835
21836
21837
21838
21839
21840
21841
21842
21843
21844
21845
21846
21847
21848
21849
21850
21851
21852
21853
21854
21855
21856
21857
21858
21859
21860
21861
21862
21863
21864
21865
21866
21867
21868
21869
21870
21871
21872
21873
21874
21875
21876
21877
21878
21879
21880
21881
21882
21883
21884
21885
21886
21887
21888
21889
21890
21891
21892
21893
21894
21895
21896
21897
21898
21899
21900
21901
21902
21903
21904
21905
21906
21907
21908
21909
21910
21911
21912
21913
21914
21915
21916
21917
21918
21919
21920
21921
21922
21923
21924
21925
21926
21927
21928
21929
21930
21931
21932
21933
21934
21935
21936
21937
21938
21939
21940
21941
21942
21943
21944
21945
21946
21947
21948
21949
21950
21951
21952
21953
21954
21955
21956
21957
21958
21959
21960
21961
21962
21963
21964
21965
21966
21967
21968
21969
21970
21971
21972
21973
21974
21975
21976
21977
21978
21979
21980
21981
21982
21983
21984
21985
21986
21987
21988
21989
21990
21991
21992
21993
21994
21995
21996
21997
21998
21999
22000
22001
22002
22003
22004
22005
22006
22007
22008
22009
22010
22011
22012
22013
22014
22015
22016
22017
22018
22019
22020
22021
22022
22023
22024
22025
22026
22027
22028
22029
22030
22031
22032
22033
22034
22035
22036
22037
22038
22039
22040
22041
22042
22043
22044
22045
22046
22047
22048
22049
22050
22051
22052
22053
22054
22055
22056
22057
22058
22059
22060
22061
22062
22063
22064
22065
22066
22067
22068
22069
22070
22071
22072
22073
22074
22075
22076
22077
22078
22079
22080
22081
22082
22083
22084
22085
22086
22087
22088
22089
22090
22091
22092
22093
22094
22095
22096
22097
22098
22099
22100
22101
22102
22103
22104
22105
22106
22107
22108
22109
22110
22111
22112
22113
22114
22115
22116
22117
22118
22119
22120
22121
22122
22123
22124
22125
22126
22127
22128
22129
22130
22131
22132
22133
22134
22135
22136
22137
22138
22139
22140
22141
22142
22143
22144
22145
22146
22147
22148
22149
22150
22151
22152
22153
22154
22155
22156
22157
22158
22159
22160
22161
22162
22163
22164
22165
22166
22167
22168
22169
22170
22171
22172
22173
22174
22175
22176
22177
22178
22179
22180
22181
22182
22183
22184
22185
22186
22187
22188
22189
22190
22191
22192
22193
22194
22195
22196
22197
22198
22199
22200
22201
22202
22203
22204
22205
22206
22207
22208
22209
22210
22211
22212
22213
22214
22215
22216
22217
22218
22219
22220
22221
22222
22223
22224
22225
22226
22227
22228
22229
22230
22231
22232
22233
22234
22235
22236
22237
22238
22239
22240
22241
22242
22243
22244
22245
22246
22247
22248
22249
22250
22251
22252
22253
22254
22255
22256
22257
22258
22259
22260
22261
22262
22263
22264
22265
22266
22267
22268
22269
22270
22271
22272
22273
22274
22275
22276
22277
22278
22279
22280
22281
22282
22283
22284
22285
22286
22287
22288
22289
22290
22291
22292
22293
22294
22295
22296
22297
22298
22299
22300
22301
22302
22303
22304
22305
22306
22307
22308
22309
22310
22311
22312
22313
22314
22315
22316
22317
22318
22319
22320
22321
22322
22323
22324
22325
22326
22327
22328
22329
22330
22331
22332
22333
22334
22335
22336
22337
22338
22339
22340
22341
22342
22343
22344
22345
22346
22347
22348
22349
22350
22351
22352
22353
22354
22355
22356
22357
22358
22359
22360
22361
22362
22363
22364
22365
22366
22367
22368
22369
22370
22371
22372
22373
22374
22375
22376
22377
22378
22379
22380
22381
22382
22383
22384
22385
22386
22387
22388
22389
22390
22391
22392
22393
22394
22395
22396
22397
22398
22399
22400
22401
22402
22403
22404
22405
22406
22407
22408
22409
22410
22411
22412
22413
22414
22415
22416
22417
22418
22419
22420
22421
22422
22423
22424
22425
22426
22427
22428
22429
22430
22431
22432
22433
22434
22435
22436
22437
22438
22439
22440
22441
22442
22443
22444
22445
22446
22447
22448
22449
22450
//! Query execution: the `Connection` API and the read-query executor.
//!
//! This layer ties the pieces together: parse SQL ([`crate::sql`]), resolve
//! names against the schema catalog ([`crate::schema`]), scan b-trees
//! ([`crate::btree`]), decode records ([`crate::format::record`]), and evaluate
//! expressions ([`eval`]) to produce result rows.
//!
//! It implements an *operational, iterator-style* executor rather than emitting
//! VDBE bytecode. The observable semantics (row order, type coercion, NULL
//! handling) follow SQLite; the bytecode representation the roadmap describes is
//! an internal-representation refactor we can layer in later without changing
//! results. The [`Connection`] reads (`query`) and writes (`execute`) over a
//! writable pager, an in-memory database, or — read-only — a WAL-mode database
//! (the `-wal` overlay is detected automatically).

pub mod datetime;
pub mod eval;
pub mod func;
pub mod json;
pub mod vdbe;
mod window;

use crate::btree::{
    clear_index, clear_table, create_index_root, create_table_root, delete_table, free_tree,
    insert_index, insert_table, table_has_empty_leaf, IndexCursor, TableCursor,
};
use crate::error::{Error, Result};
use crate::format::record::{decode_record, encode_record};
use crate::pager::{AutoVacuum, PageSource, WritePager};
use crate::schema::Schema;
use crate::sql::ast::*;
use crate::sql::{self};
use crate::value::Value;
use crate::vfs::{OpenFlags, Vfs};
use crate::vtab::{
    ConstraintOp, DynVTabModule, IndexConstraint, IndexPlan, VTabChange, VTabRegistry, VTabStore,
};
use alloc::boxed::Box;
use alloc::format;
use alloc::string::{String, ToString};
use alloc::vec::Vec;
use eval::{ColumnInfo, EvalCtx, Params};

/// The result of a query: column labels and the materialized rows.
#[derive(Debug, Clone, PartialEq)]
pub struct QueryResult {
    /// Result column labels, in order.
    pub columns: Vec<String>,
    /// Result rows, each with one value per column.
    pub rows: Vec<Vec<Value>>,
}

/// The storage backing a connection: a writable pager, or a read-only page
/// source (e.g. a WAL-mode database opened read-only).
enum Backend {
    Write(Box<WritePager>),
    Read(Box<dyn PageSource>),
}

impl Backend {
    fn source(&self) -> &dyn PageSource {
        match self {
            Backend::Write(w) => w.as_ref(),
            Backend::Read(r) => r.as_ref(),
        }
    }
    fn writer(&mut self) -> Result<&mut WritePager> {
        match self {
            Backend::Write(w) => Ok(w),
            Backend::Read(_) => Err(Error::Error("database is read-only".into())),
        }
    }
    fn wal_mode(&self) -> bool {
        matches!(self, Backend::Write(w) if w.wal_mode())
    }
}

/// A database connection. Supports reading (`query`) and writing (`execute`),
/// over a file or in memory.
pub struct Connection {
    backend: Backend,
    schema: Schema,
    /// The `main` database's file path (empty for an in-memory database), as
    /// reported by `PRAGMA database_list`.
    main_file: String,
    /// Attached databases (`ATTACH … AS name`), in attachment order, each with
    /// its own backend and schema. The `main` database is the fields above; this
    /// list holds everything attached after it.
    attached: Vec<AttachedDb>,
    /// The `temp` database (`CREATE TEMP …`), created lazily on first use and
    /// invisible to other connections. Reported at seq 1 by `database_list`.
    temp_db: Option<AttachedDb>,
    /// True between `BEGIN` and `COMMIT`/`ROLLBACK`; suppresses autocommit.
    in_tx: bool,
    /// A stack of materialized `WITH` common table expressions in scope, innermost
    /// last. Resolved by name during `FROM` scanning before the schema is
    /// consulted; this is also how a recursive CTE sees its own working table.
    cte_env: core::cell::RefCell<Vec<CteBinding>>,
    /// A stack of enclosing query rows, innermost last. A correlated subquery
    /// pushes its evaluation row here so its body can resolve outer columns.
    outer_scope: core::cell::RefCell<Vec<OuterFrame>>,
    /// Whether foreign-key constraints are enforced (`PRAGMA foreign_keys`).
    /// Off by default, matching SQLite.
    foreign_keys: bool,
    /// Re-entrancy depth of trigger firing.
    trigger_depth: core::cell::Cell<usize>,
    /// Set by an `OR FAIL` conflict before it raises: tells the statement-level
    /// atomicity wrapper to keep the rows changed before the failure (rather than
    /// rolling the statement back, which is the `OR ABORT` default).
    stmt_keep_partial: core::cell::Cell<bool>,
    /// Set by an `OR ROLLBACK` conflict before it raises: the surrounding
    /// transaction must be unwound, not just the current statement.
    stmt_rollback_tx: core::cell::Cell<bool>,
    /// Set when a `BEFORE` trigger runs `SELECT RAISE(IGNORE)`: the row operation
    /// that fired the trigger is silently abandoned (no error). The firing caller
    /// reads and clears it.
    raise_ignore: core::cell::Cell<bool>,
    /// Whether triggers may fire other triggers (`PRAGMA recursive_triggers`).
    /// Off by default, matching SQLite: triggers then fire only at the top level.
    recursive_triggers: bool,
    /// Rows projected by the most recent `RETURNING` clause, drained by
    /// [`execute_returning`](Self::execute_returning). Populated as a side effect
    /// of `INSERT`/`UPDATE`/`DELETE` execution when the statement has a
    /// `RETURNING` list.
    returning_rows: core::cell::RefCell<Vec<Vec<Value>>>,
    /// Count of open savepoints. Like `in_tx`, a non-zero count suppresses
    /// autocommit so changes accumulate until the outermost savepoint is released.
    open_savepoints: usize,
    /// The rowid of the most recently inserted row (`last_insert_rowid()`).
    last_insert_rowid: core::cell::Cell<i64>,
    /// Rows modified by the most recent INSERT/UPDATE/DELETE (`changes()`).
    changes: core::cell::Cell<i64>,
    /// Rows modified since the connection opened (`total_changes()`).
    total_changes: core::cell::Cell<i64>,
    /// During a cross-database view read, the database whose catalog unqualified
    /// table names resolve against (so a view's body reads its own database's
    /// tables). `Main` at all other times; nested subqueries inherit it. Set and
    /// restored around [`scan_db_view`](Self::scan_db_view).
    read_default: core::cell::Cell<DbRef>,
    /// Virtual-table modules registered on this connection, keyed by the name
    /// that follows `USING` in `CREATE VIRTUAL TABLE`. Seeded with the built-in
    /// `series` module; a public registration API is roadmap D4.
    vtab_registry: VTabRegistry,
    /// State for `random()`/`randomblob()`, advanced one SplitMix64 step per
    /// value. Seeded from the system clock under `std` (so each process run
    /// differs, like SQLite reseeding from the OS) and from a fixed constant in
    /// `no_std` builds (which have no entropy source) — non-determinism that no
    /// differential test can observe either way.
    rng_state: core::cell::Cell<u64>,
    /// `PRAGMA cache_size` setting, round-tripped verbatim (a positive value is a
    /// page count, a negative value is KiB; default −2000). graphite keeps every
    /// page resident, so this is reported back but does not bound a real cache.
    cache_size: core::cell::Cell<i64>,
    /// `PRAGMA analysis_limit` — the row sample cap `ANALYZE` would use (0 =
    /// unlimited). graphite always analyzes fully, so this is advisory; it is
    /// stored and reported back like sqlite (which clamps a negative value to 0).
    analysis_limit: core::cell::Cell<i64>,
    /// `PRAGMA busy_timeout` — the lock-wait timeout in ms (0 = no wait). graphite
    /// has no cross-process lock manager, so this never blocks; it is stored and
    /// reported back like sqlite (which clamps a negative value to 0).
    busy_timeout: core::cell::Cell<i64>,
    /// `PRAGMA secure_delete` (0=off, 1=on, 2=fast), round-tripped like sqlite.
    /// When non-zero, freed pages are zeroed (the pager honors it); a
    /// per-connection runtime setting, not persisted in the file.
    secure_delete: core::cell::Cell<i64>,
    /// User-defined scalar functions registered via
    /// [`register_function`](Self::register_function), keyed by lowercased name.
    /// Built-in functions take precedence; these fill otherwise-unknown names.
    functions: alloc::collections::BTreeMap<String, ScalarFunction>,
    /// User-defined aggregate functions registered via
    /// [`register_aggregate_function`](Self::register_aggregate_function), keyed by
    /// lowercased name. Built-in aggregates take precedence.
    aggregates: alloc::collections::BTreeMap<String, AggregateFactory>,
    /// Per-query FTS5 state ([`Fts5QueryCtx`]: the MATCH query plus, when ranking
    /// is referenced, the bm25 corpus), set by `run_core` while executing a
    /// `SELECT … MATCH …` over an `fts5` table and read by the `rank`/`bm25()`/
    /// `highlight()` special forms. `None` outside such a query.
    #[cfg(feature = "fts5")]
    fts5_rank: core::cell::RefCell<Option<Fts5QueryCtx>>,
    /// Whether `SELECT` execution tries the VDBE engine first, falling back
    /// transparently to the tree-walker for any query shape it does not support.
    /// **On by default** (Track B, B7b): the VDBE is the primary engine, parity-
    /// validated across the full test suite and the differential corpus. Toggled
    /// by [`set_use_vdbe`](Self::set_use_vdbe) — turn it off to force the
    /// tree-walker. The result is identical either way; this only chooses which
    /// engine produces it.
    use_vdbe: core::cell::Cell<bool>,
}

/// A user-defined scalar function: it receives its evaluated argument values and
/// returns a result [`Value`] (or an error). Registered with
/// [`Connection::register_function`].
pub type ScalarFunction = Box<dyn Fn(&[Value]) -> Result<Value>>;

/// A user-defined aggregate's accumulator: `step` is called once per group row
/// with the evaluated argument values, then `finalize` produces the result.
/// A fresh accumulator is created (by the registered factory) for each group.
pub trait AggregateFunction {
    /// Fold one row's argument values into the accumulator.
    fn step(&mut self, args: &[Value]) -> Result<()>;
    /// Produce the aggregate's value for the group.
    fn finalize(&mut self) -> Result<Value>;
}

/// Builds a fresh [`AggregateFunction`] accumulator per group. Registered with
/// [`Connection::register_aggregate_function`].
pub type AggregateFactory = Box<dyn Fn() -> Box<dyn AggregateFunction>>;

/// Initial seed for a connection's `random()` generator. Under `std` it mixes
/// the wall clock so repeated invocations of the binary produce different
/// sequences; `no_std` builds, lacking any entropy source, fall back to a fixed
/// constant (the SplitMix64 golden-ratio increment).
fn initial_rng_seed() -> u64 {
    #[cfg(feature = "std")]
    {
        let nanos = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_nanos() as u64)
            .unwrap_or(0);
        nanos ^ 0x9E37_79B9_7F4A_7C15
    }
    #[cfg(not(feature = "std"))]
    {
        0x9E37_79B9_7F4A_7C15
    }
}

/// Which database an operation targets: `main`, the lazily-created `temp`
/// database, or an attached database by index.
#[derive(Clone, Copy, PartialEq, Eq)]
enum DbRef {
    Main,
    Temp,
    Attached(usize),
}

/// An attached database (`ATTACH 'file' AS name`): its own storage and catalog.
struct AttachedDb {
    /// The schema name given in `ATTACH … AS name`.
    name: String,
    /// The file path it was attached from (empty for an in-memory attachment).
    file: String,
    backend: Backend,
    schema: Schema,
}

/// A materialized common table expression: a named, in-memory relation.
struct CteBinding {
    name: String,
    columns: Vec<ColumnInfo>,
    rows: Vec<InputRow>,
}

/// A snapshot of an enclosing query's current row, for correlated subqueries.
struct OuterFrame {
    columns: Vec<ColumnInfo>,
    row: Vec<Value>,
    rowid: Option<i64>,
}

/// The kind of data-change event, for trigger matching.
#[derive(Clone, Copy, PartialEq, Eq)]
enum TrigEvent {
    Insert,
    Update,
    Delete,
}

impl Connection {
    fn from_pager(db: WritePager) -> Result<Connection> {
        let backend = Backend::Write(Box::new(db));
        let schema = Schema::read(backend.source())?;
        Ok(Connection {
            backend,
            schema,
            main_file: String::new(),
            attached: Vec::new(),
            temp_db: None,
            in_tx: false,
            cte_env: core::cell::RefCell::new(Vec::new()),
            outer_scope: core::cell::RefCell::new(Vec::new()),
            foreign_keys: false,
            trigger_depth: core::cell::Cell::new(0),
            stmt_keep_partial: core::cell::Cell::new(false),
            stmt_rollback_tx: core::cell::Cell::new(false),
            raise_ignore: core::cell::Cell::new(false),
            recursive_triggers: false,
            returning_rows: core::cell::RefCell::new(Vec::new()),
            open_savepoints: 0,
            last_insert_rowid: core::cell::Cell::new(0),
            changes: core::cell::Cell::new(0),
            total_changes: core::cell::Cell::new(0),
            read_default: core::cell::Cell::new(DbRef::Main),
            vtab_registry: VTabRegistry::with_builtins(),
            rng_state: core::cell::Cell::new(initial_rng_seed()),
            cache_size: core::cell::Cell::new(-2000),
            analysis_limit: core::cell::Cell::new(0),
            busy_timeout: core::cell::Cell::new(0),
            secure_delete: core::cell::Cell::new(0),
            functions: alloc::collections::BTreeMap::new(),
            aggregates: alloc::collections::BTreeMap::new(),
            #[cfg(feature = "fts5")]
            fts5_rank: core::cell::RefCell::new(None),
            use_vdbe: core::cell::Cell::new(true),
        })
    }

    fn from_read_backend(backend: Box<dyn PageSource>) -> Result<Connection> {
        let backend = Backend::Read(backend);
        let schema = Schema::read(backend.source())?;
        Ok(Connection {
            backend,
            schema,
            main_file: String::new(),
            attached: Vec::new(),
            temp_db: None,
            in_tx: false,
            cte_env: core::cell::RefCell::new(Vec::new()),
            outer_scope: core::cell::RefCell::new(Vec::new()),
            foreign_keys: false,
            trigger_depth: core::cell::Cell::new(0),
            stmt_keep_partial: core::cell::Cell::new(false),
            stmt_rollback_tx: core::cell::Cell::new(false),
            raise_ignore: core::cell::Cell::new(false),
            recursive_triggers: false,
            returning_rows: core::cell::RefCell::new(Vec::new()),
            open_savepoints: 0,
            last_insert_rowid: core::cell::Cell::new(0),
            changes: core::cell::Cell::new(0),
            total_changes: core::cell::Cell::new(0),
            read_default: core::cell::Cell::new(DbRef::Main),
            vtab_registry: VTabRegistry::with_builtins(),
            rng_state: core::cell::Cell::new(initial_rng_seed()),
            cache_size: core::cell::Cell::new(-2000),
            analysis_limit: core::cell::Cell::new(0),
            busy_timeout: core::cell::Cell::new(0),
            secure_delete: core::cell::Cell::new(0),
            functions: alloc::collections::BTreeMap::new(),
            aggregates: alloc::collections::BTreeMap::new(),
            #[cfg(feature = "fts5")]
            fts5_rank: core::cell::RefCell::new(None),
            use_vdbe: core::cell::Cell::new(true),
        })
    }

    /// Open an existing database for reading and writing through `vfs`. Creates
    /// (and recovers from) a `<path>-journal` companion file.
    pub fn open_vfs(vfs: &dyn Vfs, path: &str) -> Result<Connection> {
        let main = vfs.open(path, OpenFlags::READ_WRITE)?;
        let journal = vfs.open(&journal_path(path), OpenFlags::READ_WRITE_CREATE)?;
        let wal = vfs.open(&wal_path(path), OpenFlags::READ_WRITE_CREATE)?;
        let mut c = Connection::from_pager(WritePager::open_wal(main, Some(journal), Some(wal))?)?;
        c.main_file = path.to_string();
        Ok(c)
    }

    /// Open an existing database read-only through `vfs`. If a `<path>-wal` file
    /// is present, its committed frames are overlaid so WAL-mode databases read
    /// correctly.
    pub fn open_readonly_vfs(vfs: &dyn Vfs, path: &str) -> Result<Connection> {
        let main = vfs.open(path, OpenFlags::READ_ONLY)?;
        let wal_path = wal_path(path);
        if vfs.exists(&wal_path)? {
            let mut wal = vfs.open(&wal_path, OpenFlags::READ_ONLY)?;
            let reader = crate::pager::WalReader::open(main, wal.as_mut())?;
            let mut c = Connection::from_read_backend(Box::new(reader))?;
            c.main_file = path.to_string();
            return Ok(c);
        }
        let mut c = Connection::from_read_backend(Box::new(WritePager::open(main, None)?))?;
        c.main_file = path.to_string();
        Ok(c)
    }

    /// Create a new, empty database through `vfs`.
    pub fn create_vfs(vfs: &dyn Vfs, path: &str, page_size: u32) -> Result<Connection> {
        let main = vfs.open(path, OpenFlags::READ_WRITE_CREATE)?;
        let journal = vfs.open(&journal_path(path), OpenFlags::READ_WRITE_CREATE)?;
        let wal = vfs.open(&wal_path(path), OpenFlags::READ_WRITE_CREATE)?;
        let mut db = WritePager::create_wal(main, Some(journal), Some(wal), page_size)?;
        db.commit()?;
        let mut c = Connection::from_pager(db)?;
        c.main_file = path.to_string();
        Ok(c)
    }

    /// Open an existing database file for reading and writing (requires `std`).
    #[cfg(feature = "std")]
    #[cfg_attr(docsrs, doc(cfg(feature = "std")))]
    pub fn open(path: &str) -> Result<Connection> {
        Connection::open_vfs(&crate::vfs::std_file::StdVfs::new(), path)
    }

    /// Open an existing database file read-only (requires `std`).
    #[cfg(feature = "std")]
    #[cfg_attr(docsrs, doc(cfg(feature = "std")))]
    pub fn open_readonly(path: &str) -> Result<Connection> {
        Connection::open_readonly_vfs(&crate::vfs::std_file::StdVfs::new(), path)
    }

    /// Create a new database file with the default 4096-byte page size (`std`).
    #[cfg(feature = "std")]
    #[cfg_attr(docsrs, doc(cfg(feature = "std")))]
    pub fn create(path: &str) -> Result<Connection> {
        Connection::create_vfs(&crate::vfs::std_file::StdVfs::new(), path, 4096)
    }

    /// Create a fresh in-memory database (`:memory:`), always available.
    pub fn open_memory() -> Result<Connection> {
        let vfs = crate::vfs::memory::MemoryVfs::new();
        let main = vfs.open("main", OpenFlags::READ_WRITE_CREATE)?;
        let mut db = WritePager::create(main, None, 4096)?;
        db.commit()?;
        Connection::from_pager(db)
    }

    /// The schema catalog.
    pub fn schema(&self) -> &Schema {
        &self.schema
    }

    /// Run a single `SELECT` and return all rows.
    pub fn query(&self, sql: &str) -> Result<QueryResult> {
        self.query_params(sql, &Params::default())
    }

    /// Run `sql` through the experimental VDBE engine instead of the tree-walker.
    /// Supports constant projections and plain single-table scans
    /// (`SELECT <exprs> FROM <table>` with no `WHERE`/joins/aggregates/`ORDER BY`);
    /// returns `Unsupported` otherwise so callers can fall back to
    /// [`query`](Self::query).
    pub fn query_vdbe(&self, sql: &str) -> Result<QueryResult> {
        let Statement::Select(sel) = sql::parse_one(sql)? else {
            return Err(Error::Unsupported("query_vdbe expects SELECT"));
        };
        self.run_select_vdbe(&sel)
    }

    /// Enable or disable the VDBE engine for `SELECT` (Track B). When on (the
    /// default), [`query`](Self::query) runs through the VDBE and falls back
    /// transparently to the tree-walker for any query shape it does not handle;
    /// turning it off forces the tree-walker. The result is identical either way.
    pub fn set_use_vdbe(&self, on: bool) {
        self.use_vdbe.set(on);
    }

    /// Compile a `SELECT` to a VDBE program *without running it*, gathering only
    /// the schema (column names / qualifiers / affinities) it needs — no row
    /// scan. Used by plain `EXPLAIN`. Covers the constant and single-table cases;
    /// joins and other shapes return `Unsupported`.
    fn compile_select_program(&self, sel: &Select) -> Result<vdbe::Program> {
        let Some(from) = &sel.from else {
            return vdbe::compile_const_select(sel);
        };
        if !from.joins.is_empty() {
            return Err(Error::Unsupported(
                "EXPLAIN: VDBE join programs not yet listed",
            ));
        }
        if from.first.subquery.is_some() || from.first.tvf_args.is_some() {
            return Err(Error::Unsupported("EXPLAIN: only plain table sources"));
        }
        let meta = self.table_meta(&from.first.name, from.first.alias.as_deref())?;
        let cols: Vec<String> = meta.columns.iter().map(|c| c.name.clone()).collect();
        let qualifier = from
            .first
            .alias
            .clone()
            .unwrap_or_else(|| from.first.name.clone());
        let tables: Vec<String> = meta.columns.iter().map(|_| qualifier.clone()).collect();
        let affinities: Vec<eval::Affinity> = meta.columns.iter().map(|c| c.affinity).collect();
        let collations: Vec<crate::value::Collation> =
            meta.columns.iter().map(|c| c.collation).collect();
        // A rowid table can carry `rowid`/`_rowid_`/`oid` references; expose the
        // hidden rowid slot so EXPLAIN compiles the same program execution uses.
        vdbe::compile_table_select(
            sel,
            &cols,
            &tables,
            &affinities,
            &collations,
            !meta.without_rowid,
        )
    }

    /// Plain `EXPLAIN <select>` (Track B, B8): compile the query to graphite's
    /// VDBE bytecode and return the program listing as `(addr, opcode, detail)`
    /// rows. Returns `Unsupported` for a query shape the VDBE cannot compile.
    fn explain_bytecode(&self, stmt: &Statement) -> Result<QueryResult> {
        let Statement::Select(sel) = stmt else {
            return Err(Error::Unsupported(
                "EXPLAIN: only SELECT is compiled to bytecode",
            ));
        };
        let prog = self.compile_select_program(sel)?;
        let rows = prog
            .explain_rows()
            .into_iter()
            .map(|(addr, opcode, detail)| {
                alloc::vec![
                    Value::Integer(addr as i64),
                    Value::Text(opcode),
                    Value::Text(detail),
                ]
            })
            .collect();
        Ok(QueryResult {
            columns: alloc::vec!["addr".into(), "opcode".into(), "detail".into()],
            rows,
        })
    }

    /// Rewrite `sel`'s top-level expressions, replacing every provably
    /// non-correlated scalar or `EXISTS` subquery with the constant it evaluates
    /// to. Returns `Some(rewritten)` when at least one subquery was folded, or
    /// `None` when there was nothing to fold (the caller keeps the original).
    ///
    /// Only the *top-level* expression positions are touched — a subquery that is
    /// itself a `FROM` source is its own scope and is materialized separately. A
    /// subquery is folded only when [`Self::vdbe_subquery_foldable`] proves it is
    /// self-contained; everything else is left untouched, so the result is never
    /// affected (the compiler simply falls back when an unfoldable subquery
    /// remains).
    fn fold_vdbe_subqueries(&self, sel: &Select) -> Option<Select> {
        let mut changed = false;
        let mut out = sel.clone();
        for rc in &mut out.columns {
            if let sql::ast::ResultColumn::Expr { expr, .. } = rc {
                *expr = self.fold_subquery_expr(expr, &mut changed);
            }
        }
        if let Some(w) = out.where_clause.take() {
            out.where_clause = Some(self.fold_subquery_expr(&w, &mut changed));
        }
        if let Some(h) = out.having.take() {
            out.having = Some(self.fold_subquery_expr(&h, &mut changed));
        }
        for g in &mut out.group_by {
            *g = self.fold_subquery_expr(g, &mut changed);
        }
        for o in &mut out.order_by {
            o.expr = self.fold_subquery_expr(&o.expr, &mut changed);
        }
        // A non-correlated scalar subquery in `LIMIT`/`OFFSET` folds to its
        // constant, which the VDBE's `fold_const_int` then accepts (it otherwise
        // bails on any non-constant LIMIT/OFFSET). Parity-safe: the value comes
        // from running the subquery, and a non-integer fold still falls back.
        if let Some(l) = out.limit.take() {
            out.limit = Some(self.fold_subquery_expr(&l, &mut changed));
        }
        if let Some(o) = out.offset.take() {
            out.offset = Some(self.fold_subquery_expr(&o, &mut changed));
        }
        if let Some(from) = &mut out.from {
            for j in &mut from.joins {
                if let Some(on) = j.on.take() {
                    j.on = Some(self.fold_subquery_expr(&on, &mut changed));
                }
            }
        }
        if changed {
            Some(out)
        } else {
            None
        }
    }

    /// Recursively rebuild `e`, folding any foldable scalar/`EXISTS` subquery into
    /// a literal and otherwise descending into sub-expressions. A subquery that is
    /// not foldable is left in place (so the VDBE compiler still falls back).
    fn fold_subquery_expr(&self, e: &Expr, changed: &mut bool) -> Expr {
        use sql::ast::Expr as E;
        match e {
            E::Subquery(sel2) => match self.eval_foldable_scalar(sel2) {
                Some(v) => {
                    *changed = true;
                    E::Literal(value_to_literal(v))
                }
                None => e.clone(),
            },
            E::Exists { select, negated } => match self.eval_foldable_exists(select) {
                Some(found) => {
                    *changed = true;
                    E::Literal(Literal::Integer((found ^ *negated) as i64))
                }
                None => e.clone(),
            },
            E::Unary { op, expr } => E::Unary {
                op: *op,
                expr: alloc::boxed::Box::new(self.fold_subquery_expr(expr, changed)),
            },
            E::Binary { op, left, right } => E::Binary {
                op: *op,
                left: alloc::boxed::Box::new(self.fold_subquery_expr(left, changed)),
                right: alloc::boxed::Box::new(self.fold_subquery_expr(right, changed)),
            },
            E::IsNull { expr, negated } => E::IsNull {
                expr: alloc::boxed::Box::new(self.fold_subquery_expr(expr, changed)),
                negated: *negated,
            },
            E::InList {
                expr,
                list,
                negated,
                candidate_affinity,
            } => E::InList {
                expr: alloc::boxed::Box::new(self.fold_subquery_expr(expr, changed)),
                list: list
                    .iter()
                    .map(|x| self.fold_subquery_expr(x, changed))
                    .collect(),
                negated: *negated,
                candidate_affinity: candidate_affinity.clone(),
            },
            E::Between {
                expr,
                low,
                high,
                negated,
            } => E::Between {
                expr: alloc::boxed::Box::new(self.fold_subquery_expr(expr, changed)),
                low: alloc::boxed::Box::new(self.fold_subquery_expr(low, changed)),
                high: alloc::boxed::Box::new(self.fold_subquery_expr(high, changed)),
                negated: *negated,
            },
            E::Case {
                operand,
                when_then,
                else_result,
            } => E::Case {
                operand: operand
                    .as_ref()
                    .map(|o| alloc::boxed::Box::new(self.fold_subquery_expr(o, changed))),
                when_then: when_then
                    .iter()
                    .map(|(w, t)| {
                        (
                            self.fold_subquery_expr(w, changed),
                            self.fold_subquery_expr(t, changed),
                        )
                    })
                    .collect(),
                else_result: else_result
                    .as_ref()
                    .map(|x| alloc::boxed::Box::new(self.fold_subquery_expr(x, changed))),
            },
            E::Cast { expr, type_name } => E::Cast {
                expr: alloc::boxed::Box::new(self.fold_subquery_expr(expr, changed)),
                type_name: type_name.clone(),
            },
            E::Paren(inner) => E::Paren(alloc::boxed::Box::new(
                self.fold_subquery_expr(inner, changed),
            )),
            E::Collate { expr, collation } => E::Collate {
                expr: alloc::boxed::Box::new(self.fold_subquery_expr(expr, changed)),
                collation: collation.clone(),
            },
            E::RowValue(items) => E::RowValue(
                items
                    .iter()
                    .map(|x| self.fold_subquery_expr(x, changed))
                    .collect(),
            ),
            // A function call: fold within ordinary arguments and the `FILTER`
            // predicate. A windowed call (`OVER (…)`) is left untouched (its frame
            // exprs are not in the VDBE's grammar anyway).
            E::Function {
                name,
                distinct,
                args,
                star,
                filter,
                order_by,
                over,
            } if over.is_none() => E::Function {
                name: name.clone(),
                distinct: *distinct,
                args: args
                    .iter()
                    .map(|a| self.fold_subquery_expr(a, changed))
                    .collect(),
                star: *star,
                filter: filter
                    .as_ref()
                    .map(|f| alloc::boxed::Box::new(self.fold_subquery_expr(f, changed))),
                order_by: order_by.clone(),
                over: None,
            },
            // `IN (SELECT …)`: fold to an `IN (list)` of the materialized candidate
            // values when the subquery is self-contained (non-correlated). A
            // *computed* candidate column carries NONE affinity / BINARY collation,
            // so the list compares exactly like the original (no candidate affinity).
            // A *bare-column* candidate instead contributes its column's affinity:
            // SQLite compares under `combine(left_aff, col_aff)`, which a plain
            // `IN (list)` would not reproduce — so the fold records that affinity in
            // `candidate_affinity`, and the VDBE/eval feed it as the right-operand
            // comparison affinity. (The candidate column's collation is irrelevant
            // — `IN (SELECT)` uses the left operand's collation.) `None` leaves the
            // `IN (SELECT)` in place.
            E::InSelect {
                expr,
                select,
                negated,
            } => match self.eval_foldable_in_select(select) {
                Some((values, candidate_affinity)) => {
                    *changed = true;
                    E::InList {
                        expr: alloc::boxed::Box::new(self.fold_subquery_expr(expr, changed)),
                        list: values
                            .into_iter()
                            .map(|v| E::Literal(value_to_literal(v)))
                            .collect(),
                        negated: *negated,
                        candidate_affinity,
                    }
                }
                None => e.clone(),
            },
            // Literals, parameters, columns, windowed calls: nothing to fold.
            _ => e.clone(),
        }
    }

    /// Evaluate a scalar subquery to its constant value when it is foldable, else
    /// `None`. Foldable means [`Self::vdbe_subquery_foldable`] (self-contained) AND
    /// the single result column is a *computed* expression, not a bare column
    /// reference — so the resulting literal has the same NONE affinity / BINARY
    /// collation the subquery operand would have had, making the substitution
    /// exact for the enclosing comparison.
    fn eval_foldable_scalar(&self, sel2: &Select) -> Option<Value> {
        if !self.vdbe_subquery_foldable(sel2) {
            return None;
        }
        if sel2.columns.len() != 1 {
            return None;
        }
        let sql::ast::ResultColumn::Expr { expr, .. } = &sel2.columns[0] else {
            return None;
        };
        if is_bare_column_expr(expr) {
            return None;
        }
        let r = self.run_select(sel2, &Params::default()).ok()?;
        Some(
            r.rows
                .first()
                .and_then(|row| row.first())
                .cloned()
                .unwrap_or(Value::Null),
        )
    }

    /// Materialize an `IN (SELECT …)` candidate set to its values, with the
    /// candidate side's comparison affinity, when the subquery is self-contained
    /// (non-correlated). Returns `(values, candidate_affinity)`:
    ///
    /// - A *computed* candidate column carries NONE affinity / BINARY collation,
    ///   so `L IN (SELECT …)` compares exactly like `L IN (v1, v2, …)` (the
    ///   comparison takes `L`'s affinity in both forms — verified vs sqlite); the
    ///   returned affinity is `None`.
    /// - A *bare-column* candidate contributes its column's affinity: SQLite uses
    ///   `combine(left_aff, col_aff)`, which a plain literal list lacks. The
    ///   column's affinity is returned as a canonical type name so the VDBE/eval
    ///   feed it as the element comparison's right-operand affinity.
    ///
    /// **Collation:** the candidate column's collation is NOT consulted — SQLite
    /// resolves `x IN (SELECT col)` under the LEFT operand's collation (the
    /// candidate's collation never affects the result, verified vs sqlite), and
    /// the folded `IN (list)` comparison already applies the left's collation.
    /// `None` when not foldable, so the VDBE compiler simply falls back as before.
    fn eval_foldable_in_select(&self, sel2: &Select) -> Option<(Vec<Value>, Option<String>)> {
        if !self.vdbe_subquery_foldable(sel2) {
            return None;
        }
        if sel2.columns.len() != 1 {
            return None;
        }
        let sql::ast::ResultColumn::Expr { expr, .. } = &sel2.columns[0] else {
            return None;
        };
        // A bare-column candidate must carry its column's affinity into the
        // comparison; resolve the single output column's origin affinity (bail
        // only when the origin is unresolvable). The candidate column's COLLATION
        // is irrelevant: `x IN (SELECT col)` always uses the LEFT operand's
        // collation — the candidate column's collation never affects the result
        // (verified vs sqlite) — and the folded IN-list comparison already applies
        // the left's collation.
        let candidate_affinity = if is_bare_column_expr(expr) {
            let origins = self.subquery_column_origins(sel2)?;
            let (aff, _coll) = origins.first().copied()?;
            Some(affinity_type_name(aff))
        } else {
            None
        };
        let r = self.run_select(sel2, &Params::default()).ok()?;
        Some((
            r.rows
                .into_iter()
                .map(|row| row.into_iter().next().unwrap_or(Value::Null))
                .collect(),
            candidate_affinity,
        ))
    }

    /// Evaluate `EXISTS (sel2)` to a constant truth value when `sel2` is
    /// self-contained (non-correlated), else `None`.
    fn eval_foldable_exists(&self, sel2: &Select) -> Option<bool> {
        if !self.vdbe_subquery_foldable(sel2) {
            return None;
        }
        let r = self.run_select(sel2, &Params::default()).ok()?;
        Some(!r.rows.is_empty())
    }

    /// Conservatively decide whether `sel2` is self-contained — i.e. references no
    /// column outside its own `FROM` sources (non-correlated), takes no bound
    /// parameter, and contains no further nested subquery. Such a query yields the
    /// same value evaluated in isolation as it would in any outer row, so its
    /// result can be folded to a constant. Bails (returns `false`) on anything it
    /// cannot prove: compound/CTE bodies, non-base-table sources, etc.
    fn vdbe_subquery_foldable(&self, sel2: &Select) -> bool {
        if !sel2.compound.is_empty() || !sel2.ctes.is_empty() {
            return false;
        }
        let Some(from) = &sel2.from else {
            // A `FROM`-less scalar (`(SELECT 1)`) is trivially constant, but only
            // if it carries no column reference at all.
            return self.expr_positions_internal(sel2, &[], &[]);
        };
        // Collect the source qualifiers and the union of their columns; every
        // source must be a plain base table so the column set is known.
        let mut quals: Vec<String> = Vec::new();
        let mut cols: Vec<String> = Vec::new();
        let mut collect = |tr: &sql::ast::TableRef| -> bool {
            if tr.subquery.is_some()
                || tr.tvf_args.is_some()
                || tr.schema.is_some()
                || tr.name.is_empty()
            {
                return false;
            }
            let Ok(meta) = self.table_meta(&tr.name, None) else {
                return false;
            };
            quals.push(tr.name.clone());
            if let Some(a) = &tr.alias {
                quals.push(a.clone());
            }
            for c in &meta.columns {
                cols.push(c.name.clone());
            }
            true
        };
        if !collect(&from.first) {
            return false;
        }
        for j in &from.joins {
            if !collect(&j.table) {
                return false;
            }
        }
        self.expr_positions_internal(sel2, &quals, &cols)
    }

    /// True when every column reference in every top-level expression of `sel2`
    /// resolves to one of `quals`/`cols` (its own sources) and no expression
    /// contains a parameter or a nested subquery — see [`expr_is_internal`].
    fn expr_positions_internal(&self, sel2: &Select, quals: &[String], cols: &[String]) -> bool {
        let ok = |e: &Expr| expr_is_internal(e, quals, cols);
        for rc in &sel2.columns {
            if let sql::ast::ResultColumn::Expr { expr, .. } = rc {
                if !ok(expr) {
                    return false;
                }
            }
        }
        if let Some(w) = &sel2.where_clause {
            if !ok(w) {
                return false;
            }
        }
        if let Some(h) = &sel2.having {
            if !ok(h) {
                return false;
            }
        }
        if !sel2.group_by.iter().all(&ok) {
            return false;
        }
        if !sel2.order_by.iter().all(|t| ok(&t.expr)) {
            return false;
        }
        if let Some(from) = &sel2.from {
            for j in &from.joins {
                if let Some(on) = &j.on {
                    if !ok(on) {
                        return false;
                    }
                }
            }
        }
        if let Some(l) = &sel2.limit {
            if !ok(l) {
                return false;
            }
        }
        if let Some(o) = &sel2.offset {
            if !ok(o) {
                return false;
            }
        }
        true
    }

    /// Compile and run a parsed `SELECT` through the VDBE engine, or `Unsupported`
    /// when its shape is outside the spike's grammar (so callers fall back).
    fn run_select_vdbe(&self, sel: &Select) -> Result<QueryResult> {
        // The VDBE resolves table names in the `main` schema only
        // (`table_meta`). Whenever an attached or `temp` database is in scope, or
        // a non-main database is the current resolution default, or a source is
        // schema-qualified, defer to the tree-walker so the right schema is used.
        if self.temp_db.is_some()
            || !self.attached.is_empty()
            || self.read_default.get() != DbRef::Main
        {
            return Err(Error::Unsupported("VDBE: non-main schema in scope"));
        }
        if let Some(f) = &sel.from {
            if f.first.schema.is_some() || f.joins.iter().any(|j| j.table.schema.is_some()) {
                return Err(Error::Unsupported("VDBE: schema-qualified source"));
            }
        }
        // A compound query (UNION / UNION ALL / INTERSECT / EXCEPT) runs each
        // constituent SELECT on the VDBE and combines the row-sets with the same
        // set semantics the tree-walker uses (Track B, B5c-3).
        if !sel.compound.is_empty() {
            return self.run_compound_vdbe(sel);
        }
        // When the tree-walker satisfies `ORDER BY` via an index/rowid/seek scan,
        // its tie/NULL order follows that (possibly reversed) scan; the VDBE
        // sorter would emit a different — valid, but SQL-unspecified — tie order.
        // Defer such queries to the tree-walker so the observable order matches.
        if sel.from.is_some()
            && !sel.order_by.is_empty()
            && self
                .order_satisfied_by_scan(sel, &eval::Params::default())
                .is_some()
        {
            return Err(Error::Unsupported("VDBE: ORDER BY satisfied by a scan"));
        }
        // A window-function query (Track B5c-4): scan the single base table on the
        // VDBE (with `WHERE` applied and the rowid appended), then evaluate the
        // windows, projection, DISTINCT, `ORDER BY` and `LIMIT`/`OFFSET` through the
        // shared `finish_from_rows` tail — the same code the tree-walker runs.
        if window::has_window(sel) {
            return self.run_window_vdbe(sel);
        }
        // Fold provably non-correlated scalar / `EXISTS` subqueries that appear in
        // the top-level expressions to the constant they evaluate to, so the VDBE
        // (which cannot open a cursor for a nested query) can run the rest. Only
        // self-contained subqueries are folded; anything correlated, parameterized,
        // or itself containing a nested subquery is left in place and the compiler
        // falls back as before — so this only widens what the VDBE accepts, never
        // changes a result.
        let folded;
        let sel = match self.fold_vdbe_subqueries(sel) {
            Some(s) => {
                folded = s;
                &folded
            }
            None => sel,
        };
        // Resolve a positional `GROUP BY N` (a bare integer literal) to the N-th
        // output column's expression — `GROUP BY 1` groups by the first result
        // column, not the constant `1` (SQLite). The VDBE group compiler bails on
        // an integer group key, so without this rewrite the query would always
        // fall back. Only a clean, wildcard-free projection is resolved here: a
        // leading `*`/`t.*` would make the ordinal count post-expansion columns
        // (which the bare projection list cannot index), and an out-of-range
        // ordinal must be *rejected* — both defer to the tree-walker, which
        // validates and errors them exactly like SQLite.
        let regrouped;
        let sel = if sel
            .group_by
            .iter()
            .any(|g| matches!(g, Expr::Literal(Literal::Integer(_))))
        {
            if sel
                .columns
                .iter()
                .any(|c| matches!(c, ResultColumn::Wildcard | ResultColumn::TableWildcard(_)))
            {
                return Err(Error::Unsupported(
                    "VDBE: positional GROUP BY with wildcard projection",
                ));
            }
            let mut s = sel.clone();
            for g in &mut s.group_by {
                if let Expr::Literal(Literal::Integer(n)) = g {
                    match usize::try_from(*n)
                        .ok()
                        .filter(|&n| n >= 1)
                        .and_then(|n| sel.columns.get(n - 1))
                    {
                        Some(ResultColumn::Expr { expr, .. }) => *g = expr.clone(),
                        // Out of range (or names a wildcard): the tree-walker
                        // rejects/handles it.
                        _ => {
                            return Err(Error::Unsupported(
                                "VDBE: positional GROUP BY out of range",
                            ))
                        }
                    }
                }
            }
            regrouped = s;
            &regrouped
        } else {
            sel
        };
        // Constant SELECT (no FROM): compile and run directly.
        let Some(from) = &sel.from else {
            let prog = vdbe::compile_const_select(sel)?;
            let rows = vdbe::run(&prog)?;
            return Ok(QueryResult {
                columns: prog.columns,
                rows,
            });
        };
        // Materialize a plain table source's column names and rows. Subqueries
        // and table-valued functions are out of the spike's scope.
        // (column names, owning-table qualifier, affinities, collations, rows, and
        // the per-row rowids — `None` for a `WITHOUT ROWID` table, which has none).
        type ScanOut = (
            Vec<String>,
            Vec<String>,
            Vec<eval::Affinity>,
            Vec<crate::value::Collation>,
            Vec<Vec<Value>>,
            Option<Vec<i64>>,
        );
        let scan_one = |tr: &sql::ast::TableRef| -> Result<ScanOut> {
            // A derived table (FROM subquery), conservatively: a single-block
            // subquery over a single all-BINARY base table. Then every output
            // column has BINARY collation and its affinity comes from the resolved
            // output type — so the materialized rows compare in the outer query
            // exactly like the tree-walker. Anything else defers.
            if let Some(sub) = &tr.subquery {
                if tr.tvf_args.is_some() || !sub.compound.is_empty() {
                    return Err(Error::Unsupported("VDBE: complex subquery source"));
                }
                let sfrom = sub
                    .from
                    .as_ref()
                    .ok_or(Error::Unsupported("VDBE: subquery source without FROM"))?;
                if !sfrom.joins.is_empty()
                    || sfrom.first.subquery.is_some()
                    || sfrom.first.tvf_args.is_some()
                    || sfrom.first.index_hint.is_some()
                    || sfrom.first.schema.is_some()
                    || self.schema.table(&sfrom.first.name).is_none()
                {
                    return Err(Error::Unsupported("VDBE: complex subquery source"));
                }
                let base = self.table_meta(&sfrom.first.name, None)?;
                if base
                    .columns
                    .iter()
                    .any(|c| c.collation != crate::value::Collation::default())
                {
                    return Err(Error::Unsupported(
                        "VDBE: subquery over a non-BINARY column",
                    ));
                }
                let named = self
                    .resolved_view_columns(sub)
                    .ok_or(Error::Unsupported("VDBE: subquery columns unresolved"))?;
                let result = self.run_select(sub, &eval::Params::default())?;
                if result.columns.len() != named.len() {
                    return Err(Error::Unsupported("VDBE: subquery column count mismatch"));
                }
                let qualifier = tr.alias.clone().unwrap_or_default();
                let tables = result.columns.iter().map(|_| qualifier.clone()).collect();
                let affinities = named
                    .iter()
                    .map(|(_, t)| eval::Affinity::from_type(t.as_deref()))
                    .collect();
                let collations = result
                    .columns
                    .iter()
                    .map(|_| crate::value::Collation::default())
                    .collect();
                return Ok((
                    result.columns,
                    tables,
                    affinities,
                    collations,
                    result.rows,
                    None,
                ));
            }
            if tr.tvf_args.is_some() {
                return Err(Error::Unsupported("VDBE: only plain table sources"));
            }
            // The VDBE always full-scans and does not model `INDEXED BY`/`NOT
            // INDEXED` (and an invalid `INDEXED BY` must error); defer to the
            // tree-walker so the hint is honoured or rejected.
            if tr.index_hint.is_some() {
                return Err(Error::Unsupported("VDBE: index hint"));
            }
            let meta = self.table_meta(&tr.name, tr.alias.as_deref())?;
            let cols = meta.columns.iter().map(|c| c.name.clone()).collect();
            let collations = meta.columns.iter().map(|c| c.collation).collect();
            // The qualifier a `t.col` reference must use: the alias if present,
            // else the table name.
            let qualifier = tr.alias.clone().unwrap_or_else(|| tr.name.clone());
            let tables = meta.columns.iter().map(|_| qualifier.clone()).collect();
            let affinities = meta.columns.iter().map(|c| c.affinity).collect();
            let (rows, rowids): (Vec<Vec<Value>>, Option<Vec<i64>>) = if meta.without_rowid {
                (self.scan_without_rowid(&meta)?, None)
            } else {
                let scanned = self.scan_table(&meta)?;
                let ids = scanned.iter().map(|(r, _)| *r).collect();
                (scanned.into_iter().map(|(_, v)| v).collect(), Some(ids))
            };
            Ok((cols, tables, affinities, collations, rows, rowids))
        };

        // Outer / NATURAL / USING join(s) — anything beyond a plain INNER chain. A
        // filtered cross-product can't model the NULL-extension of unmatched rows
        // or the column coalescing, so build the joined rows by a real nested loop,
        // processing each join left-to-right exactly like the tree-walker: for each
        // accumulated left row emit a row per right match — matching on equality of
        // the NATURAL/USING coalesce columns (each under the left column's
        // collation) when present, else the `ON` predicate. A LEFT/FULL step also
        // null-extends an unmatched left row; a RIGHT/FULL step appends each
        // unmatched right row with a null left. Each NATURAL/USING column is then
        // coalesced into its left position and the right duplicate dropped. Only the
        // final WHERE is handed to the VDBE. Pure plain-INNER chains keep the
        // cross-product path below.
        if from.joins.iter().any(|j| {
            matches!(
                j.kind,
                sql::ast::JoinKind::Left | sql::ast::JoinKind::Right | sql::ast::JoinKind::Full
            ) || j.natural
                || !j.using.is_empty()
        }) {
            // `t.*` over a coalesced (NATURAL/USING) join would need qualifier-aware
            // expansion of the reduced column set; defer it. A plain outer join's
            // `t.*` is fine (compile_table_select expands it by qualifier).
            let has_coalesce = from.joins.iter().any(|j| j.natural || !j.using.is_empty());
            if has_coalesce
                && sel
                    .columns
                    .iter()
                    .any(|rc| matches!(rc, sql::ast::ResultColumn::TableWildcard(_)))
            {
                return Err(Error::Unsupported("VDBE: table.* over NATURAL/USING join"));
            }
            // The VDBE path is param-less (explicit params were substituted
            // upstream); evaluate each ON against an empty parameter set.
            let on_params = eval::Params::default();
            let first = scan_one(&from.first)?;
            let mut names = first.0;
            let mut tabs = first.1;
            let mut affs = first.2;
            let mut colls = first.3;
            let mut rows: Vec<Vec<Value>> = first.4;
            for j in &from.joins {
                let src = scan_one(&j.table)?;
                let lw = names.len();
                let rw = src.0.len();
                // Combined schema after adding this source (for ON resolution).
                let mut n_names = names.clone();
                n_names.extend(src.0.iter().cloned());
                let mut n_tabs = tabs.clone();
                n_tabs.extend(src.1.iter().cloned());
                let mut n_affs = affs.clone();
                n_affs.extend(src.2.iter().copied());
                let mut n_colls = colls.clone();
                n_colls.extend(src.3.iter().copied());
                let cinfos: Vec<ColumnInfo> = (0..n_names.len())
                    .map(|i| ColumnInfo {
                        name: n_names[i].clone(),
                        table: n_tabs[i].clone(),
                        affinity: n_affs[i],
                        collation: n_colls[i],
                    })
                    .collect();
                // NATURAL/USING coalesce pairs (left index, right local index): the
                // join matches on equality of these instead of an `ON`.
                let pairs: Vec<(usize, usize)> = if j.natural {
                    src.0
                        .iter()
                        .enumerate()
                        .filter_map(|(rl, rn)| {
                            names
                                .iter()
                                .position(|n| n.eq_ignore_ascii_case(rn))
                                .map(|li| (li, rl))
                        })
                        .collect()
                } else if !j.using.is_empty() {
                    let mut v = Vec::with_capacity(j.using.len());
                    for name in &j.using {
                        let li = names.iter().position(|n| n.eq_ignore_ascii_case(name));
                        let rl = src.0.iter().position(|n| n.eq_ignore_ascii_case(name));
                        match (li, rl) {
                            (Some(li), Some(rl)) => v.push((li, rl)),
                            _ => {
                                return Err(Error::Error(format!(
                                "cannot join using column {name} - column not present in both tables"
                            )))
                            }
                        }
                    }
                    v
                } else {
                    Vec::new()
                };
                let keep_unmatched_left =
                    matches!(j.kind, sql::ast::JoinKind::Left | sql::ast::JoinKind::Full);
                let keep_unmatched_right =
                    matches!(j.kind, sql::ast::JoinKind::Right | sql::ast::JoinKind::Full);
                let mut matched_right = alloc::vec![false; src.4.len()];
                let mut next: Vec<Vec<Value>> = Vec::new();
                for a in &rows {
                    let mut any = false;
                    for (rj, b) in src.4.iter().enumerate() {
                        let mut row = a.clone();
                        row.extend(b.iter().cloned());
                        let keep = if !pairs.is_empty() {
                            pairs.iter().all(|&(li, rl)| {
                                // Apply each side's affinity (cross-type USING/
                                // NATURAL key: INTEGER 1 = TEXT '1'), as the
                                // tree-walker join does.
                                let (lv, rv) = eval::apply_comparison_affinity(
                                    row[li].clone(),
                                    Some(n_affs[li]),
                                    row[lw + rl].clone(),
                                    Some(n_affs[lw + rl]),
                                );
                                eval::truth(&eval::compare_op(
                                    sql::ast::BinaryOp::Eq,
                                    &lv,
                                    &rv,
                                    n_colls[li],
                                )) == Some(true)
                            })
                        } else {
                            match &j.on {
                                Some(p) => {
                                    let ir = InputRow {
                                        values: row.clone(),
                                        rowid: None,
                                    };
                                    let ctx = ir.ctx(&cinfos, &on_params).with_subqueries(self);
                                    eval::truth(&eval::eval(p, &ctx)?) == Some(true)
                                }
                                None => true,
                            }
                        };
                        if keep {
                            next.push(row);
                            matched_right[rj] = true;
                            any = true;
                        }
                    }
                    // LEFT/FULL: emit the left row with NULLs when nothing matched.
                    if keep_unmatched_left && !any {
                        let mut row = a.clone();
                        row.extend(core::iter::repeat_n(Value::Null, rw));
                        next.push(row);
                    }
                }
                // RIGHT/FULL: append each unmatched right row with a null left.
                if keep_unmatched_right {
                    for (rj, b) in src.4.iter().enumerate() {
                        if !matched_right[rj] {
                            let mut row = alloc::vec![Value::Null; lw];
                            row.extend(b.iter().cloned());
                            next.push(row);
                        }
                    }
                }
                // Coalesce each NATURAL/USING column into its left position (taking
                // the right value when the left is NULL, i.e. an outer-join row),
                // then drop the right duplicates so it appears once.
                if !pairs.is_empty() {
                    let mut drop: Vec<usize> = pairs.iter().map(|&(_, rl)| lw + rl).collect();
                    drop.sort_unstable();
                    drop.dedup();
                    for row in &mut next {
                        for &(li, rl) in &pairs {
                            if matches!(row[li], Value::Null) {
                                row[li] = row[lw + rl].clone();
                            }
                        }
                        for &d in drop.iter().rev() {
                            row.remove(d);
                        }
                    }
                    for &d in drop.iter().rev() {
                        n_names.remove(d);
                        n_tabs.remove(d);
                        n_affs.remove(d);
                        n_colls.remove(d);
                    }
                }
                rows = next;
                names = n_names;
                tabs = n_tabs;
                affs = n_affs;
                colls = n_colls;
            }
            // The VDBE resolves a bare column by name and would silently pick one
            // side of an ambiguous reference; defer such a query to the tree-walker,
            // which rejects it with "ambiguous column name" (reusing the exact same
            // check over this join's resolved column list).
            let join_cols: Vec<ColumnInfo> = (0..names.len())
                .map(|i| ColumnInfo {
                    name: names[i].clone(),
                    table: tabs[i].clone(),
                    affinity: affs[i],
                    collation: colls[i],
                })
                .collect();
            if validate_unambiguous_columns(sel, &join_cols).is_err() {
                return Err(Error::Unsupported("VDBE: ambiguous column name"));
            }
            let prog = vdbe::compile_table_select(sel, &names, &tabs, &affs, &colls, false)?;
            let result = vdbe::run_rows(&prog, &rows)?;
            return Ok(QueryResult {
                columns: prog.columns,
                rows: result,
            });
        }

        // Inner join(s) (B5a): an inner join is a filtered cross-product, so
        // materialize `t1 × t2 × … × tN` (leftmost source outermost, matching the
        // tree-walker's and sqlite's nested-loop row order), fold every `ON` into
        // the `WHERE`, and reuse the single-cursor scan compiler. Every join must
        // be a plain `INNER`/`CROSS`/comma join (no `NATURAL`/`USING`/outer).
        if !from.joins.is_empty() {
            // A single two-table LEFT/RIGHT/FULL JOIN routes to the null-padding
            // nested loop below; otherwise only plain INNER joins are handled here
            // (NATURAL/USING fall back to the tree-walker).
            let single =
                from.joins.len() == 1 && !from.joins[0].natural && from.joins[0].using.is_empty();
            let is_left_2 = single && from.joins[0].kind == sql::ast::JoinKind::Left;
            let is_right_2 = single && from.joins[0].kind == sql::ast::JoinKind::Right;
            let is_full_2 = single && from.joins[0].kind == sql::ast::JoinKind::Full;
            if !is_left_2
                && !is_right_2
                && !is_full_2
                && from.joins.iter().any(|j| {
                    j.kind != sql::ast::JoinKind::Inner || j.natural || !j.using.is_empty()
                })
            {
                return Err(Error::Unsupported("VDBE: only plain inner joins"));
            }
            // `t.*` over a join expands by qualifier inside `compile_table_select`.
            // Scan every source (the first table, then each joined table) in
            // declaration order.
            let mut sources = alloc::vec![scan_one(&from.first)?];
            for j in &from.joins {
                sources.push(scan_one(&j.table)?);
            }
            // Combined schema = each source's columns concatenated in order. Shared
            // bare names are allowed: a qualified `t.col` disambiguates them, and an
            // ambiguous *bare* reference makes the compiler bail (→ tree-walker).
            let mut combined: Vec<String> = Vec::new();
            let mut combined_tables: Vec<String> = Vec::new();
            let mut combined_aff: Vec<eval::Affinity> = Vec::new();
            let mut combined_coll: Vec<crate::value::Collation> = Vec::new();
            for (c, t, a, l, _, _) in &sources {
                combined.extend(c.iter().cloned());
                combined_tables.extend(t.iter().cloned());
                combined_aff.extend(a.iter().copied());
                combined_coll.extend(l.iter().copied());
            }
            // A two-table LEFT/RIGHT JOIN: the ON predicate gates which inner rows
            // match (an unmatched preserved-side row gets one null-padded output
            // row), so it is NOT merged into WHERE — compile it via the
            // null-padding nested loop. `compile_left_join2` always preserves
            // cursor 0 and null-pads cursor 1, so order the cursors by which side
            // is preserved: LEFT keeps the left table (declaration order [a, b]),
            // RIGHT keeps the right table (so cursor 0 = b, cursor 1 = a). Column
            // refs resolve by name regardless of cursor order. Any unsupported
            // shape (or an ambiguous column) returns `Unsupported`, so the router
            // falls back to the tree-walker (never the inner-join path, whose
            // ON-into-WHERE merge would change outer-join semantics).
            if is_left_2 || is_right_2 || is_full_2 {
                // RIGHT preserves the right table, so it swaps the cursor order
                // (cursor 0 = the preserved side); LEFT and FULL keep declaration
                // order [a, b].
                let (outer, inner) = if is_right_2 {
                    (1usize, 0usize)
                } else {
                    (0usize, 1usize)
                };
                let mut oj_cols: Vec<String> = Vec::new();
                let mut oj_tables: Vec<String> = Vec::new();
                let mut oj_aff: Vec<eval::Affinity> = Vec::new();
                let mut oj_coll: Vec<crate::value::Collation> = Vec::new();
                for &si in &[outer, inner] {
                    let (c, t, a, l, _, _) = &sources[si];
                    oj_cols.extend(c.iter().cloned());
                    oj_tables.extend(t.iter().cloned());
                    oj_aff.extend(a.iter().copied());
                    oj_coll.extend(l.iter().copied());
                }
                let join_cols: Vec<ColumnInfo> = (0..oj_cols.len())
                    .map(|i| ColumnInfo {
                        name: oj_cols[i].clone(),
                        table: oj_tables[i].clone(),
                        affinity: oj_aff[i],
                        collation: oj_coll[i],
                    })
                    .collect();
                if validate_unambiguous_columns(sel, &join_cols).is_err() {
                    return Err(Error::Unsupported("VDBE: ambiguous column name"));
                }
                let n_outer = sources[outer].0.len();
                let on = &from.joins[0].on;
                let prog = if is_full_2 {
                    vdbe::compile_full_join2(
                        sel, &oj_cols, &oj_tables, &oj_aff, &oj_coll, n_outer, on,
                    )?
                } else {
                    vdbe::compile_left_join2(
                        sel, &oj_cols, &oj_tables, &oj_aff, &oj_coll, n_outer, on,
                    )?
                };
                let result = vdbe::run_rows_multi(&prog, &[&sources[outer].4, &sources[inner].4])?;
                return Ok(QueryResult {
                    columns: prog.columns,
                    rows: result,
                });
            }
            // Merge the existing WHERE with every join's ON predicate (AND).
            let mut merged = sel.where_clause.clone();
            for j in &from.joins {
                if let Some(on) = &j.on {
                    merged = Some(match merged {
                        Some(w) => sql::ast::Expr::Binary {
                            op: sql::ast::BinaryOp::And,
                            left: alloc::boxed::Box::new(w),
                            right: alloc::boxed::Box::new(on.clone()),
                        },
                        None => on.clone(),
                    });
                }
            }
            let mut joined = sel.clone();
            joined.where_clause = merged;
            // Defer an ambiguous-column query to the tree-walker, which rejects it
            // with "ambiguous column name" (the same check over this join's combined
            // column list). `compile_table_select` bails on some ambiguous bare refs
            // but not all (e.g. one consumed only by GROUP BY), so check here too.
            let join_cols: Vec<ColumnInfo> = (0..combined.len())
                .map(|i| ColumnInfo {
                    name: combined[i].clone(),
                    table: combined_tables[i].clone(),
                    affinity: combined_aff[i],
                    collation: combined_coll[i],
                })
                .collect();
            if validate_unambiguous_columns(sel, &join_cols).is_err() {
                return Err(Error::Unsupported("VDBE: ambiguous column name"));
            }
            // B5b-1: a plain N-table inner join with a nested-loopable shape
            // (projection + WHERE + constant LIMIT/OFFSET) runs as an N-deep
            // nested loop over one cursor per table — no `t1 × … × tN`
            // cross-product is materialized. The row order (each cursor advancing
            // innermost-first, leftmost outermost) is identical, so the result
            // matches the cross-product path. Any other shape bails below.
            {
                // Cumulative per-cursor column counts: boundaries[i] is the end of
                // cursor i's columns in the combined row.
                let mut boundaries = Vec::with_capacity(sources.len());
                let mut acc = 0;
                for src in &sources {
                    acc += src.0.len();
                    boundaries.push(acc);
                }
                // A bare-aggregate join (`count(*)`, `sum(a.x)`, … no GROUP BY)
                // folds over the nested loop too, emitting one row — no
                // cross-product is materialized. Same answer as the fallback.
                if let Ok(prog) = vdbe::compile_aggregate_join(
                    &joined,
                    &combined,
                    &combined_tables,
                    &combined_aff,
                    &combined_coll,
                    &boundaries,
                ) {
                    let rowsets: Vec<&[Vec<Value>]> =
                        sources.iter().map(|s| s.4.as_slice()).collect();
                    let result = vdbe::run_rows_multi(&prog, &rowsets)?;
                    return Ok(QueryResult {
                        columns: prog.columns,
                        rows: result,
                    });
                }
                // A `GROUP BY` join (keys + aggregates, with optional HAVING /
                // ORDER BY / LIMIT) folds each group over the nested loop and emits
                // one row per group — again with no cross-product materialized.
                if let Ok(prog) = vdbe::compile_group_join(
                    &joined,
                    &combined,
                    &combined_tables,
                    &combined_aff,
                    &combined_coll,
                    &boundaries,
                ) {
                    let rowsets: Vec<&[Vec<Value>]> =
                        sources.iter().map(|s| s.4.as_slice()).collect();
                    let result = vdbe::run_rows_multi(&prog, &rowsets)?;
                    return Ok(QueryResult {
                        columns: prog.columns,
                        rows: result,
                    });
                }
                if let Ok(prog) = vdbe::compile_join2(
                    &joined,
                    &combined,
                    &combined_tables,
                    &combined_aff,
                    &combined_coll,
                    &boundaries,
                ) {
                    let rowsets: Vec<&[Vec<Value>]> =
                        sources.iter().map(|s| s.4.as_slice()).collect();
                    let result = vdbe::run_rows_multi(&prog, &rowsets)?;
                    return Ok(QueryResult {
                        columns: prog.columns,
                        rows: result,
                    });
                }
            }
            // N-way cross-product, leftmost source outermost.
            let mut rows: Vec<Vec<Value>> = sources[0].4.clone();
            for src in &sources[1..] {
                let mut next = Vec::with_capacity(rows.len().saturating_mul(src.4.len()));
                for a in &rows {
                    for b in &src.4 {
                        let mut row = a.clone();
                        row.extend(b.iter().cloned());
                        next.push(row);
                    }
                }
                rows = next;
            }
            let prog = vdbe::compile_table_select(
                &joined,
                &combined,
                &combined_tables,
                &combined_aff,
                &combined_coll,
                // rowid over a join is ambiguous across tables; not modeled here.
                false,
            )?;
            let result = vdbe::run_rows(&prog, &rows)?;
            return Ok(QueryResult {
                columns: prog.columns,
                rows: result,
            });
        }

        // Single source — a plain table or a derived table (`scan_one` materializes
        // a safe FROM subquery; a table-valued function is out of scope).
        if from.first.tvf_args.is_some() {
            return Err(Error::Unsupported("VDBE: table-valued function source"));
        }
        let (col_names, col_tables, col_aff, col_coll, mut rows, rowids) = scan_one(&from.first)?;
        // Append each row's rowid as a hidden trailing value so a `rowid`/`_rowid_`/
        // `oid` reference resolves (a `WITHOUT ROWID` table has none → `rowids` is
        // `None`, and such references fall back to the tree-walker, which errors).
        let has_rowid = rowids.is_some();
        if let Some(ids) = rowids {
            for (row, id) in rows.iter_mut().zip(ids) {
                row.push(Value::Integer(id));
            }
        }
        // A `t.*` projection is only handled when its qualifier names this single
        // table (by name or alias); any other qualifier falls back so the
        // tree-walker can resolve or reject it.
        for rc in &sel.columns {
            if let sql::ast::ResultColumn::TableWildcard(q) = rc {
                let matches = q.eq_ignore_ascii_case(&from.first.name)
                    || from
                        .first
                        .alias
                        .as_deref()
                        .is_some_and(|a| q.eq_ignore_ascii_case(a));
                if !matches {
                    return Err(Error::Unsupported("VDBE: unknown table.* qualifier"));
                }
            }
        }
        let prog = vdbe::compile_table_select(
            sel,
            &col_names,
            &col_tables,
            &col_aff,
            &col_coll,
            has_rowid,
        )?;
        let result = vdbe::run_rows(&prog, &rows)?;
        Ok(QueryResult {
            columns: prog.columns,
            rows: result,
        })
    }

    /// Run a compound `SELECT` (`UNION` / `UNION ALL` / `INTERSECT` / `EXCEPT`)
    /// on the VDBE (Track B, B5c-3). Each constituent SELECT is executed through
    /// [`run_select_vdbe`](Self::run_select_vdbe); the set combination, the
    /// post-dedup sort, and the overall `ORDER BY` / `LIMIT` / `OFFSET` reuse the
    /// exact helpers the tree-walker uses ([`apply_compound`],
    /// [`compound_order_limit`](Self::compound_order_limit)), so the result is
    /// byte-identical. Returns `Unsupported` — falling back to the tree-walker —
    /// if any arm is a shape the VDBE cannot run, or carries CTEs or its own
    /// nested compound (e.g. a multi-row `VALUES`, which desugars to a nested
    /// `UNION ALL` chain).
    fn run_compound_vdbe(&self, sel: &Select) -> Result<QueryResult> {
        if !sel.ctes.is_empty() {
            return Err(Error::Unsupported("VDBE: compound with CTEs"));
        }
        // Each arm must be a flat (non-compound, CTE-free) SELECT so the
        // left-associative fold matches SQLite without recursing into operand
        // tails (a multi-row `VALUES` operand keeps its rows in its own compound
        // tail — defer those to the tree-walker).
        if sel
            .compound
            .iter()
            .any(|(_, c)| !c.compound.is_empty() || !c.ctes.is_empty())
        {
            return Err(Error::Unsupported("VDBE: nested compound arm"));
        }
        // The first core, stripped of the compound tail and the whole-query
        // ORDER BY / LIMIT / OFFSET.
        let mut first = sel.clone();
        first.compound = Vec::new();
        first.order_by = Vec::new();
        first.limit = None;
        first.offset = None;
        let mut result = self.run_select_vdbe(&first)?;
        // Set comparison uses the left SELECT's per-column output collations.
        let params = eval::Params::default();
        let colls = {
            let (cols, _) = self.scan_source(&first, &params)?;
            self.output_collations(&first, &cols, &params)
        };
        for (op, operand) in &sel.compound {
            let r = self.run_select_vdbe(operand)?;
            // Every operand must project the same number of columns; SQLite names
            // the operator at the mismatch.
            if r.columns.len() != result.columns.len() {
                let kw = match op {
                    CompoundOp::Union => "UNION",
                    CompoundOp::UnionAll => "UNION ALL",
                    CompoundOp::Intersect => "INTERSECT",
                    CompoundOp::Except => "EXCEPT",
                };
                return Err(Error::Error(alloc::format!(
                    "SELECTs to the left and right of {kw} do not have the same \
                     number of result columns"
                )));
            }
            result.rows = apply_compound(*op, result.rows, r.rows, &colls);
        }
        // A dedup set operation (UNION / INTERSECT / EXCEPT) emits rows in sorted
        // order in SQLite (its dedup is a sorter); with no explicit ORDER BY,
        // sort the combined result by all output columns to match.
        if sel.order_by.is_empty()
            && sel
                .compound
                .iter()
                .any(|(op, _)| *op != CompoundOp::UnionAll)
        {
            result.rows.sort_by(|a, b| {
                for (i, va) in a.iter().enumerate() {
                    let coll = colls.get(i).copied().unwrap_or_default();
                    let ord = crate::value::cmp_values_coll(va, &b[i], coll);
                    if ord != core::cmp::Ordering::Equal {
                        return ord;
                    }
                }
                core::cmp::Ordering::Equal
            });
        }
        self.compound_order_limit(&mut result, sel, &params, &colls)?;
        Ok(result)
    }

    /// Like [`query`](Self::query) but with bound parameters.
    pub fn query_params(&self, sql: &str, params: &Params) -> Result<QueryResult> {
        match sql::parse_one(sql)? {
            Statement::Select(sel) => self.run_select(&sel, params),
            Statement::Pragma(p) => self.run_pragma(&p),
            Statement::Explain { query_plan, stmt } => {
                if query_plan {
                    self.explain_query_plan(&stmt, params)
                } else {
                    self.explain_bytecode(&stmt)
                }
            }
            _ => Err(Error::Unsupported(
                "use execute() for non-SELECT statements",
            )),
        }
    }

    /// Evaluate the read-only `PRAGMA`s that return a result set.
    fn run_pragma(&self, p: &Pragma) -> Result<QueryResult> {
        let name = p.name.to_ascii_lowercase();
        let header = self.backend.source().header();
        let single = |col: &str, v: Value| QueryResult {
            columns: alloc::vec![String::from(col)],
            rows: alloc::vec![alloc::vec![v]],
        };
        match name.as_str() {
            "page_size" => Ok(single("page_size", Value::Integer(header.page_size as i64))),
            "page_count" => Ok(single(
                "page_count",
                Value::Integer(self.backend.source().page_count() as i64),
            )),
            "user_version" => Ok(single(
                // Stored as a 32-bit value; SQLite reports it signed.
                "user_version",
                Value::Integer(header.user_version as i32 as i64),
            )),
            "schema_version" => Ok(single(
                "schema_version",
                Value::Integer(header.schema_cookie as i64),
            )),
            "encoding" => Ok(single(
                "encoding",
                Value::Text(
                    match header.text_encoding {
                        crate::format::TextEncoding::Utf8 => "UTF-8",
                        crate::format::TextEncoding::Utf16Le => "UTF-16le",
                        crate::format::TextEncoding::Utf16Be => "UTF-16be",
                    }
                    .into(),
                ),
            )),
            "freelist_count" => Ok(single(
                "freelist_count",
                Value::Integer(header.freelist_count as i64),
            )),
            // 0 = NONE, 1 = FULL, 2 = INCREMENTAL. Auto-vacuum is on when the
            // header's largest-root-page field is non-zero; the incremental flag
            // then distinguishes the two modes.
            "auto_vacuum" => Ok(single(
                "auto_vacuum",
                Value::Integer(auto_vacuum_mode(header) as i64),
            )),
            "application_id" => Ok(single(
                "application_id",
                Value::Integer(header.application_id as i32 as i64),
            )),
            "data_version" => Ok(single("data_version", Value::Integer(1))),
            "table_info" => self.pragma_table_info(p, false),
            "table_xinfo" => self.pragma_table_info(p, true),
            "index_list" => self.pragma_index_list(p),
            "index_info" => self.pragma_index_info(p, false),
            "index_xinfo" => self.pragma_index_info(p, true),
            "database_list" => Ok(self.pragma_database_list()),
            "table_list" => self.pragma_table_list(p),
            // The collating sequences graphite implements (built-ins only; it
            // registers no custom collations).
            "collation_list" => Ok(QueryResult {
                columns: alloc::vec!["seq".into(), "name".into()],
                rows: ["RTRIM", "NOCASE", "BINARY"]
                    .iter()
                    .enumerate()
                    .map(|(i, n)| alloc::vec![Value::Integer(i as i64), Value::Text((*n).into())])
                    .collect(),
            }),
            "foreign_key_list" => self.pragma_foreign_key_list(p),
            "foreign_key_check" => self.pragma_foreign_key_check(p),
            "integrity_check" | "quick_check" => self.pragma_integrity_check(),
            "foreign_keys" => Ok(single(
                "foreign_keys",
                Value::Integer(self.foreign_keys as i64),
            )),
            "recursive_triggers" => Ok(single(
                "recursive_triggers",
                Value::Integer(self.recursive_triggers as i64),
            )),
            "journal_mode" => {
                // An in-memory database (empty main file) uses the `memory`
                // journal, like sqlite; a file database defaults to `delete`.
                let mode = if self.backend.wal_mode() {
                    "wal"
                } else if self.main_file.is_empty() {
                    "memory"
                } else {
                    "delete"
                };
                Ok(single("journal_mode", Value::Text(mode.into())))
            }
            // Read-only getters for tuning knobs graphite does not expose. It
            // has no configurable page cache, durability mode, or lock manager
            // beyond what it already implements, so each reports SQLite's fixed
            // default — what an unconfigured connection observes. This keeps the
            // shell drop-in for tools/ORMs that probe these on connect.
            "cache_size" => Ok(single("cache_size", Value::Integer(self.cache_size.get()))),
            // The reference sqlite build has memory-mapped I/O disabled
            // (SQLITE_MAX_MMAP_SIZE = 0), so `PRAGMA mmap_size` yields no rows.
            "mmap_size" => Ok(QueryResult {
                columns: alloc::vec![String::from("mmap_size")],
                rows: Vec::new(),
            }),
            "synchronous" => Ok(single("synchronous", Value::Integer(2))),
            "temp_store" => Ok(single("temp_store", Value::Integer(0))),
            "secure_delete" => Ok(single(
                "secure_delete",
                Value::Integer(self.secure_delete.get()),
            )),
            "read_uncommitted" => Ok(single("read_uncommitted", Value::Integer(0))),
            "cell_size_check" => Ok(single("cell_size_check", Value::Integer(0))),
            "checkpoint_fullfsync" => Ok(single("checkpoint_fullfsync", Value::Integer(0))),
            "fullfsync" => Ok(single("fullfsync", Value::Integer(0))),
            // `busy_timeout` round-trips the lock-wait timeout (graphite never
            // blocks, so it is advisory). The set form clamps a negative value to 0
            // and echoes it; the plain form reads it back — like sqlite. The result
            // column is named "timeout".
            "busy_timeout" => {
                if let Some(e) = &p.value {
                    let v = eval::to_i64(&eval::eval(e, &EvalCtx::rowless(&Params::default()))?);
                    self.busy_timeout.set(v.max(0));
                }
                Ok(single("timeout", Value::Integer(self.busy_timeout.get())))
            }
            // `wal_checkpoint[(mode)]` — graphite never runs in WAL mode (its
            // journal is delete/memory), so a checkpoint is a no-op. sqlite still
            // returns one `(busy, log, checkpointed)` row; for a non-WAL database
            // that is always `0, -1, -1`.
            "wal_checkpoint" => Ok(QueryResult {
                columns: alloc::vec![
                    String::from("busy"),
                    String::from("log"),
                    String::from("checkpointed"),
                ],
                rows: alloc::vec![alloc::vec![
                    Value::Integer(0),
                    Value::Integer(-1),
                    Value::Integer(-1),
                ]],
            }),
            "wal_autocheckpoint" => Ok(single("wal_autocheckpoint", Value::Integer(1000))),
            "max_page_count" => Ok(single("max_page_count", Value::Integer(4294967294))),
            "locking_mode" => Ok(single("locking_mode", Value::Text("normal".into()))),
            // Recognized boolean / legacy no-op pragmas: graphite does not act on
            // them, but reports SQLite's fixed default so a probing tool/ORM sees a
            // normal connection. `legacy_file_format` and `case_sensitive_like`
            // (a setter-only spelling) yield no rows, as in SQLite.
            "legacy_file_format" | "case_sensitive_like" => Ok(QueryResult {
                columns: alloc::vec![name.clone()],
                rows: Vec::new(),
            }),
            // `analysis_limit` stores/reports the ANALYZE sample cap. The set form
            // (`PRAGMA analysis_limit = N`) clamps a negative N to 0 and echoes the
            // resulting value, exactly like sqlite; the plain form reads it back.
            "analysis_limit" => {
                if let Some(e) = &p.value {
                    let v = eval::to_i64(&eval::eval(e, &EvalCtx::rowless(&Params::default()))?);
                    self.analysis_limit.set(v.max(0));
                }
                Ok(single(
                    "analysis_limit",
                    Value::Integer(self.analysis_limit.get()),
                ))
            }
            // `optimize` runs recommended maintenance; graphite keeps its stats
            // current, so there is nothing to do and — like sqlite in its default,
            // non-verbose mode — it returns no rows.
            "optimize" => Ok(QueryResult {
                columns: alloc::vec![name.clone()],
                rows: Vec::new(),
            }),
            "short_column_names" | "automatic_index" => Ok(single(&name, Value::Integer(1))),
            "legacy_alter_table"
            | "count_changes"
            | "full_column_names"
            | "empty_result_callbacks"
            | "defer_foreign_keys"
            | "ignore_check_constraints"
            | "reverse_unordered_selects"
            | "query_only"
            | "writable_schema"
            | "threads"
            | "soft_heap_limit"
            | "hard_heap_limit" => Ok(single(&name, Value::Integer(0))),
            // `incremental_vacuum` (bare or `(N)`) performs a write, so it cannot
            // run on the read-only query path. Signal the caller to re-run it via
            // execute() (the CLI retries on this message); the `= N` form already
            // routes to execute() directly.
            "incremental_vacuum" => Err(Error::Unsupported(
                "PRAGMA incremental_vacuum modifies the database; use execute()",
            )),
            _ => Err(Error::Unsupported("this PRAGMA")),
        }
    }

    /// `PRAGMA database_list` → `(seq, name, file)` for `main`, then each
    /// attached database in attachment order. In-memory databases report an
    /// empty file path, as in SQLite.
    /// `PRAGMA table_list [(name)]`: one row per table/view across every
    /// database — `(schema, name, type, ncol, wr, strict)` — plus each
    /// database's synthetic schema table. Row order is unspecified in sqlite
    /// (hash order); we emit database order, then catalog order within each.
    fn pragma_table_list(&self, p: &Pragma) -> Result<QueryResult> {
        use crate::schema::ObjectType;
        let filter = match &p.value {
            Some(Expr::Column { column, .. }) => Some(column.clone()),
            Some(Expr::Literal(Literal::Str(s))) => Some(s.clone()),
            _ => None,
        };
        let params = Params::default();
        // (display name, which database, that database's schema-table name).
        // `temp` is always listed here (matching sqlite) even before it exists —
        // unlike `database_list`, which omits it until first use.
        let mut dbs: Vec<(String, DbRef, &str)> = alloc::vec![
            ("main".into(), DbRef::Main, "sqlite_schema"),
            ("temp".into(), DbRef::Temp, "sqlite_temp_schema"),
        ];
        for (i, d) in self.attached.iter().enumerate() {
            dbs.push((d.name.clone(), DbRef::Attached(i), "sqlite_schema"));
        }
        let matches = |n: &str| filter.as_deref().is_none_or(|f| f.eq_ignore_ascii_case(n));
        let mut rows: Vec<Vec<Value>> = Vec::new();
        for (db_name, db, schema_tab) in &dbs {
            // `temp` may be listed before it has been created (no user objects).
            let objects: &[crate::schema::SchemaObject] =
                if matches!(db, DbRef::Temp) && self.temp_db.is_none() {
                    &[]
                } else {
                    self.db_parts(*db).0.objects()
                };
            for obj in objects {
                let typ = match obj.obj_type {
                    ObjectType::Table => "table",
                    ObjectType::View => "view",
                    _ => continue,
                };
                if !matches(&obj.name) {
                    continue;
                }
                let (ncol, wr, strict) = self.table_list_dims(*db, obj, &params);
                rows.push(alloc::vec![
                    Value::Text(db_name.clone()),
                    Value::Text(obj.name.clone()),
                    Value::Text(typ.into()),
                    Value::Integer(ncol),
                    Value::Integer(wr),
                    Value::Integer(strict),
                ]);
            }
            // The database's own schema table (also matchable as `sqlite_master`).
            if matches(schema_tab)
                || filter
                    .as_deref()
                    .is_some_and(|f| f.eq_ignore_ascii_case("sqlite_master"))
            {
                rows.push(alloc::vec![
                    Value::Text(db_name.clone()),
                    Value::Text((*schema_tab).into()),
                    Value::Text("table".into()),
                    Value::Integer(5),
                    Value::Integer(0),
                    Value::Integer(0),
                ]);
            }
        }
        Ok(QueryResult {
            columns: alloc::vec![
                "schema".into(),
                "name".into(),
                "type".into(),
                "ncol".into(),
                "wr".into(),
                "strict".into(),
            ],
            rows,
        })
    }

    /// `(ncol, wr, strict)` for one `table_list` row: a table's column count,
    /// WITHOUT ROWID flag, and STRICT flag; a view's output-column count (its
    /// `wr`/`strict` are always 0). Best-effort — an unreadable object yields 0s.
    fn table_list_dims(
        &self,
        db: DbRef,
        obj: &crate::schema::SchemaObject,
        params: &Params,
    ) -> (i64, i64, i64) {
        use crate::schema::ObjectType;
        match obj.obj_type {
            ObjectType::Table => {
                let (schema, _) = self.db_parts(db);
                match self.table_meta_in(schema, &obj.name, None) {
                    Ok(m) => (
                        m.columns.len() as i64,
                        m.without_rowid as i64,
                        m.strict_types.is_some() as i64,
                    ),
                    Err(_) => (0, 0, 0),
                }
            }
            ObjectType::View => {
                let ncol = self
                    .scan_db_view(db, &obj.name, None, params)
                    .ok()
                    .flatten()
                    .map_or(0, |(c, _)| c.len() as i64);
                (ncol, 0, 0)
            }
            _ => (0, 0, 0),
        }
    }

    fn pragma_database_list(&self) -> QueryResult {
        let mut rows = alloc::vec![alloc::vec![
            Value::Integer(0),
            Value::Text("main".into()),
            Value::Text(self.main_file.clone()),
        ]];
        // `temp` occupies seq 1 once it exists; attached databases begin at seq 2.
        if self.temp_db.is_some() {
            rows.push(alloc::vec![
                Value::Integer(1),
                Value::Text("temp".into()),
                Value::Text(String::new()),
            ]);
        }
        for (i, db) in self.attached.iter().enumerate() {
            rows.push(alloc::vec![
                Value::Integer((i + 2) as i64),
                Value::Text(db.name.clone()),
                Value::Text(db.file.clone()),
            ]);
        }
        QueryResult {
            columns: alloc::vec!["seq".into(), "name".into(), "file".into()],
            rows,
        }
    }

    /// `PRAGMA table_info(name)` → one row per column
    /// `(cid, name, type, notnull, dflt_value, pk)`.
    fn pragma_table_info(&self, p: &Pragma, extended: bool) -> Result<QueryResult> {
        let table = match &p.value {
            Some(Expr::Column { column, .. }) => column.clone(),
            Some(Expr::Literal(Literal::Str(s))) => s.clone(),
            _ => {
                return Err(Error::Error(
                    "PRAGMA table_info requires a table name".into(),
                ))
            }
        };
        // The schema catalog is queryable but has no stored CREATE statement;
        // report its fixed five columns, as SQLite does for `sqlite_master` /
        // `sqlite_schema` (and their `sqlite_temp_*` aliases).
        if matches!(
            table.to_ascii_lowercase().as_str(),
            "sqlite_master" | "sqlite_schema" | "sqlite_temp_master" | "sqlite_temp_schema"
        ) {
            let cols = [
                ("type", "TEXT"),
                ("name", "TEXT"),
                ("tbl_name", "TEXT"),
                ("rootpage", "INT"),
                ("sql", "TEXT"),
            ];
            let mut rows = Vec::new();
            for (i, (name, ty)) in cols.iter().enumerate() {
                let mut row = alloc::vec![
                    Value::Integer(i as i64),
                    Value::Text((*name).into()),
                    Value::Text((*ty).into()),
                    Value::Integer(0),
                    Value::Null,
                    Value::Integer(0),
                ];
                if extended {
                    row.push(Value::Integer(0));
                }
                rows.push(row);
            }
            let columns = table_info_columns(extended);
            return Ok(QueryResult { columns, rows });
        }
        // The eponymous read-only vtabs (`dbstat`, `sqlite_dbpage`) answer
        // table_info with their fixed column shape, unless a real table of the
        // name shadows them. Each entry is `(name, type, pk, hidden)`:
        // `sqlite_dbpage.pgno` is PRIMARY KEY, and both carry trailing hidden
        // columns that only `table_xinfo` (the extended form) reports.
        if self.schema.table(&table).is_none() {
            let lower = table.to_ascii_lowercase();
            let fixed: &[(&str, &str, i64, bool)] = match lower.as_str() {
                "sqlite_dbpage" => &[
                    ("pgno", "INTEGER", 1, false),
                    ("data", "BLOB", 0, false),
                    ("schema", "", 0, true),
                ],
                "dbstat" => &[
                    ("name", "TEXT", 0, false),
                    ("path", "TEXT", 0, false),
                    ("pageno", "INTEGER", 0, false),
                    ("pagetype", "TEXT", 0, false),
                    ("ncell", "INTEGER", 0, false),
                    ("payload", "INTEGER", 0, false),
                    ("unused", "INTEGER", 0, false),
                    ("mx_payload", "INTEGER", 0, false),
                    ("pgoffset", "INTEGER", 0, false),
                    ("pgsize", "INTEGER", 0, false),
                    ("schema", "TEXT", 0, true),
                    ("aggregate", "BOOLEAN", 0, true),
                ],
                _ => &[],
            };
            if !fixed.is_empty() {
                // Non-extended `table_info` omits hidden columns entirely; the
                // `cid` is the position in the emitted sequence (hidden columns
                // always trail, so visible indices are unaffected).
                let rows = fixed
                    .iter()
                    .filter(|(_, _, _, hidden)| extended || !hidden)
                    .enumerate()
                    .map(|(i, (name, ty, pk, hidden))| {
                        let mut row = alloc::vec![
                            Value::Integer(i as i64),
                            Value::Text((*name).into()),
                            Value::Text((*ty).into()),
                            Value::Integer(0),
                            Value::Null,
                            Value::Integer(*pk),
                        ];
                        if extended {
                            row.push(Value::Integer(*hidden as i64));
                        }
                        row
                    })
                    .collect();
                return Ok(QueryResult {
                    columns: table_info_columns(extended),
                    rows,
                });
            }
        }
        // A VIEW also answers table_info: its columns with their resolved types
        // (notnull/dflt/pk are always 0/empty for a view).
        if let Some(vobj) = self.schema.objects().iter().find(|o| {
            o.obj_type == crate::schema::ObjectType::View && o.name.eq_ignore_ascii_case(&table)
        }) {
            if let Some(sql) = &vobj.sql {
                if let Statement::CreateView(cv) = sql::parse_one(sql)? {
                    return self.view_table_info(&cv, &table, extended);
                }
            }
        }
        // A virtual table answers table_info with its module's declared columns
        // and (optionally) their types; notnull / default / pk are 0/empty (the
        // safe module interface carries no such info).
        if self.is_virtual_table(&table) {
            let (_, _, schema) = self.vtab_meta(&table)?;
            let rows = schema
                .columns
                .iter()
                .enumerate()
                .map(|(i, name)| {
                    let ty = schema.types.get(i).cloned().unwrap_or_default();
                    let mut row = alloc::vec![
                        Value::Integer(i as i64),
                        Value::Text(name.clone()),
                        Value::Text(ty),
                        Value::Integer(0),
                        Value::Null,
                        Value::Integer(0),
                    ];
                    if extended {
                        row.push(Value::Integer(0));
                    }
                    row
                })
                .collect();
            return Ok(QueryResult {
                columns: table_info_columns(extended),
                rows,
            });
        }
        // `table_info` / `table_xinfo` of a non-existent table yields no rows (not
        // an error), matching sqlite — both the `PRAGMA` form and the
        // `pragma_table_info('x')` table-valued function.
        let Some(obj) = self.schema.table(&table) else {
            return Ok(QueryResult {
                columns: table_info_columns(extended),
                rows: Vec::new(),
            });
        };
        let sql = obj.sql.as_deref().unwrap_or("");
        let Statement::CreateTable(ct) = sql::parse_one(sql)? else {
            return Err(Error::Corrupt("schema sql is not CREATE TABLE".into()));
        };
        // The `pk` column is the 1-based position of the column within the
        // PRIMARY KEY (0 if not part of it) — so a composite `PRIMARY KEY(b,a)`
        // reports b=1, a=2, matching SQLite. A single-column or INTEGER PK is 1.
        let pk_positions = primary_key_positions(&ct);

        let mut rows = Vec::new();
        for (i, col) in ct.columns.iter().enumerate() {
            // A generated column's storage kind (`Some(stored)`), or `None`.
            let generated = col.constraints.iter().find_map(|c| match c {
                ColumnConstraint::Generated { stored, .. } => Some(*stored),
                _ => None,
            });
            // `table_info` hides generated columns; `table_xinfo` includes them
            // with a `hidden` flag (2 = virtual, 3 = stored generated; 0 = normal).
            if generated.is_some() && !extended {
                continue;
            }
            let hidden = match generated {
                None => 0,
                Some(false) => 2,
                Some(true) => 3,
            };
            // SQLite reports `notnull` from an explicit `NOT NULL` only — an
            // INTEGER PRIMARY KEY (the rowid) is shown as notnull=0.
            let notnull = col
                .constraints
                .iter()
                .any(|c| matches!(c, ColumnConstraint::NotNull(_)));
            // `dflt_value` is the SQL text of the default expression (SQLite
            // preserves the literal as written — e.g. a string keeps its quotes,
            // `DEFAULT NULL` shows `NULL`), so reprint rather than evaluate it.
            let dflt = col.constraints.iter().find_map(|c| match c {
                ColumnConstraint::Default(e) => Some(sql::print::expr(e)),
                _ => None,
            });
            let pk = pk_positions
                .iter()
                .position(|&pos| pos == i)
                .map_or(0, |n| n as i64 + 1);
            let mut row = alloc::vec![
                Value::Integer(i as i64),
                Value::Text(col.name.clone()),
                Value::Text(col.type_name.clone().unwrap_or_default()),
                Value::Integer(notnull as i64),
                dflt.map(Value::Text).unwrap_or(Value::Null),
                Value::Integer(pk),
            ];
            if extended {
                row.push(Value::Integer(hidden));
            }
            rows.push(row);
        }
        Ok(QueryResult {
            columns: table_info_columns(extended),
            rows,
        })
    }

    /// `table_info` for a VIEW: its output columns, each with the declared type
    /// SQLite reports — a direct column reference takes its origin column's type
    /// (an untyped origin shows `BLOB`), and any other expression shows an empty
    /// type. notnull/dflt/pk are always 0/NULL/0.
    fn view_table_info(
        &self,
        cv: &CreateView,
        view_name: &str,
        extended: bool,
    ) -> Result<QueryResult> {
        // (name, declared type) per output column. Prefer the static resolver;
        // fall back to running the view for names (with empty types) when the
        // body is too complex to resolve column origins statically.
        let mut cols: NamedColumns = match self.resolved_view_columns(&cv.select) {
            Some(c) => c,
            None => self
                .view_columns(view_name, &Params::default())?
                .into_iter()
                .map(|c| (c.name, None))
                .collect(),
        };
        // An explicit `CREATE VIEW v(x, y)` column list overrides the names.
        if !cv.columns.is_empty() && cv.columns.len() == cols.len() {
            for (slot, name) in cols.iter_mut().zip(&cv.columns) {
                slot.0 = name.clone();
            }
        }
        let rows = cols
            .into_iter()
            .enumerate()
            .map(|(i, (name, ty))| {
                let mut row = alloc::vec![
                    Value::Integer(i as i64),
                    Value::Text(name),
                    Value::Text(ty.unwrap_or_default()),
                    Value::Integer(0),
                    Value::Null,
                    Value::Integer(0),
                ];
                if extended {
                    row.push(Value::Integer(0));
                }
                row
            })
            .collect();
        Ok(QueryResult {
            columns: table_info_columns(extended),
            rows,
        })
    }

    /// Resolve a SELECT's output columns to `(name, declared-type)` pairs for
    /// `view_table_info`, recursing through subqueries and views. Returns `None`
    /// when a source cannot be resolved statically (a table-valued function, or a
    /// wildcard over a NATURAL/USING join whose column coalescing isn't modelled),
    /// so the caller can fall back to names-only.
    fn resolved_view_columns(&self, select: &Select) -> Option<NamedColumns> {
        // Resolve each FROM source to its labelled (name, type) columns.
        let mut sources: Vec<(String, NamedColumns)> = Vec::new();
        if let Some(fc) = &select.from {
            let mut refs = alloc::vec![&fc.first];
            let mut coalesced = false;
            for j in &fc.joins {
                refs.push(&j.table);
                if j.natural || !j.using.is_empty() {
                    coalesced = true;
                }
            }
            let has_wild = select
                .columns
                .iter()
                .any(|c| matches!(c, ResultColumn::Wildcard | ResultColumn::TableWildcard(_)));
            if coalesced && has_wild {
                return None; // `*` over coalesced columns — don't guess.
            }
            for tref in refs {
                let label = tref.alias.clone().unwrap_or_else(|| tref.name.clone());
                sources.push((label, self.source_columns_of(tref)?));
            }
        }
        let lookup = |table: Option<&str>, col: &str| -> Option<String> {
            for (label, cols) in &sources {
                if table.is_some_and(|t| !t.eq_ignore_ascii_case(label)) {
                    continue;
                }
                if let Some((_, ty)) = cols.iter().find(|(n, _)| n.eq_ignore_ascii_case(col)) {
                    return ty.clone();
                }
            }
            None
        };
        let mut out = Vec::new();
        for rc in &select.columns {
            match rc {
                ResultColumn::Wildcard => {
                    for (_, cols) in &sources {
                        out.extend(cols.iter().cloned());
                    }
                }
                ResultColumn::TableWildcard(t) => {
                    let (_, cols) = sources.iter().find(|(l, _)| l.eq_ignore_ascii_case(t))?;
                    out.extend(cols.iter().cloned());
                }
                ResultColumn::Expr {
                    expr,
                    alias,
                    source,
                } => {
                    let name = result_column_label(expr, alias, source);
                    // Only a bare column reference carries a type through.
                    let ty = match expr {
                        Expr::Column { table, column } => lookup(table.as_deref(), column),
                        _ => None,
                    };
                    out.push((name, ty));
                }
            }
        }
        Some(out)
    }

    /// The `(name, declared-type)` columns a FROM source contributes. A base
    /// table's untyped columns report `BLOB` (as SQLite does for a view); views
    /// and subqueries recurse; TVFs return `None` (unresolved).
    fn source_columns_of(&self, tref: &TableRef) -> Option<NamedColumns> {
        if tref.tvf_args.is_some() {
            return None;
        }
        if let Some(sub) = &tref.subquery {
            return self.resolved_view_columns(sub);
        }
        // A named source: a view recurses; otherwise a base table's columns.
        if let Some(o) = self.schema.objects().iter().find(|o| {
            o.obj_type == crate::schema::ObjectType::View && o.name.eq_ignore_ascii_case(&tref.name)
        }) {
            if let Some(Ok(Statement::CreateView(cv))) = o.sql.as_deref().map(sql::parse_one) {
                return self.resolved_view_columns(&cv.select);
            }
            return None;
        }
        let obj = self.schema.table(&tref.name)?;
        let Ok(Statement::CreateTable(ct)) = sql::parse_one(obj.sql.as_deref()?) else {
            return None;
        };
        Some(
            ct.columns
                .iter()
                .map(|c| {
                    // A direct reference to an untyped column shows `BLOB`.
                    let ty = c.type_name.clone().unwrap_or_else(|| String::from("BLOB"));
                    (c.name.clone(), Some(ty))
                })
                .collect(),
        )
    }

    /// The single name argument of a `PRAGMA foo(name)` / `PRAGMA foo = name`.
    fn pragma_arg_name(p: &Pragma) -> Result<String> {
        match &p.value {
            Some(Expr::Column { column, .. }) => Ok(column.clone()),
            Some(Expr::Literal(Literal::Str(s))) => Ok(s.clone()),
            _ => Err(Error::Error("PRAGMA requires a name argument".into())),
        }
    }

    /// `PRAGMA index_list(table)` → `(seq, name, unique, origin, partial)`, newest
    /// index first (as SQLite lists them).
    fn pragma_index_list(&self, p: &Pragma) -> Result<QueryResult> {
        let table = Self::pragma_arg_name(p)?;
        let objs: Vec<_> = self.schema.indexes_on(&table).collect();

        // To label an automatic index's origin `pk` vs `u`, find the PRIMARY KEY's
        // column set. An INTEGER PRIMARY KEY is the rowid (no auto-index), so only
        // a non-integer / composite PK yields a `pk`-origin auto-index. The set
        // matches one of `collect_unique_sets`, which mirrors SQLite's auto-index
        // numbering.
        let pk_set: Vec<usize> = self
            .schema
            .table(&table)
            .and_then(|o| o.sql.as_deref())
            .and_then(|sql| sql::parse_one(sql).ok())
            .and_then(|st| match st {
                Statement::CreateTable(ct) => {
                    let ipk = find_integer_primary_key(&ct);
                    let pk = primary_key_positions(&ct);
                    // A single integer-PK column is the rowid, not an auto-index;
                    // a table with no PK has no `pk`-origin auto-index either.
                    if pk.is_empty() || (pk.len() == 1 && Some(pk[0]) == ipk) {
                        None
                    } else {
                        Some(pk)
                    }
                }
                _ => None,
            })
            .unwrap_or_default();
        let tmeta = self.table_meta(&table, None).ok();

        let mut rows = Vec::new();
        for obj in objs.iter().rev() {
            let (unique, origin, partial) = match &obj.sql {
                Some(sql) => match sql::parse_one(sql) {
                    Ok(Statement::CreateIndex(ci)) => {
                        (ci.unique as i64, "c", ci.where_clause.is_some() as i64)
                    }
                    _ => (0, "c", 0),
                },
                None => {
                    // Automatic index: `pk` when its column set is the PRIMARY
                    // KEY's, otherwise a plain UNIQUE (`u`).
                    let cols = autoindex_number(&obj.name, &table)
                        .and_then(|n| tmeta.as_ref().and_then(|m| m.unique.get(n - 1)))
                        .map(|s| s.0.clone())
                        .unwrap_or_default();
                    let origin = if !pk_set.is_empty() && cols == pk_set {
                        "pk"
                    } else {
                        "u"
                    };
                    (1, origin, 0)
                }
            };
            rows.push(alloc::vec![
                Value::Integer(rows.len() as i64),
                Value::Text(obj.name.clone()),
                Value::Integer(unique),
                Value::Text(origin.into()),
                Value::Integer(partial),
            ]);
        }
        // A WITHOUT ROWID table's PRIMARY KEY is the table b-tree itself; SQLite
        // still reports it as `sqlite_autoindex_<t>_1` (origin `pk`) — and, being
        // auto-index #1 (the oldest), it comes *last* in this newest-first list.
        // graphite keeps no separate index object for it, so synthesize the row.
        if tmeta.as_ref().is_some_and(|m| m.without_rowid) && !pk_set.is_empty() {
            rows.push(alloc::vec![
                Value::Integer(rows.len() as i64),
                Value::Text(alloc::format!("sqlite_autoindex_{table}_1")),
                Value::Integer(1),
                Value::Text("pk".into()),
                Value::Integer(0),
            ]);
        }
        Ok(QueryResult {
            columns: ["seq", "name", "unique", "origin", "partial"]
                .iter()
                .map(|s| String::from(*s))
                .collect(),
            rows,
        })
    }

    /// `PRAGMA index_info(index)` → `(seqno, cid, name)` for each indexed column.
    fn pragma_index_info(&self, p: &Pragma, extended: bool) -> Result<QueryResult> {
        let index = Self::pragma_arg_name(p)?;
        let obj = self
            .schema
            .index(&index)
            .ok_or_else(|| Error::Error(format!("no such index: {index}")))?;
        let tmeta = self.table_meta(&obj.tbl_name, None)?;
        // Per key column: (cid, name, descending, collation). A bare column takes
        // its position + name; an EXPRESSION column is `cid = -2` with a NULL name,
        // as SQLite reports (its collation defaults to BINARY unless COLLATE-d).
        type Key = (i64, Option<String>, bool, crate::value::Collation);
        let keys: Vec<Key> = match &obj.sql {
            Some(sql) => match sql::parse_one(sql)? {
                Statement::CreateIndex(ci) => ci
                    .columns
                    .iter()
                    .map(|term| {
                        let (inner, explicit) = match &term.expr {
                            Expr::Collate { expr, collation } => {
                                (expr.as_ref(), crate::value::Collation::parse(collation))
                            }
                            e => (e, None),
                        };
                        match inner {
                            Expr::Column { column, .. } => {
                                match tmeta
                                    .columns
                                    .iter()
                                    .position(|c| c.name.eq_ignore_ascii_case(column))
                                {
                                    Some(p) => (
                                        p as i64,
                                        Some(tmeta.columns[p].name.clone()),
                                        term.descending,
                                        explicit.unwrap_or(tmeta.columns[p].collation),
                                    ),
                                    None => {
                                        (-2, None, term.descending, explicit.unwrap_or_default())
                                    }
                                }
                            }
                            _ => (-2, None, term.descending, explicit.unwrap_or_default()),
                        }
                    })
                    .collect(),
                _ => Vec::new(),
            },
            None => autoindex_number(&obj.name, &obj.tbl_name)
                .and_then(|n| tmeta.unique.get(n - 1))
                .map(|s| s.0.clone())
                .unwrap_or_default()
                .into_iter()
                .map(|cid| {
                    (
                        cid as i64,
                        Some(tmeta.columns[cid].name.clone()),
                        false,
                        tmeta.columns[cid].collation,
                    )
                })
                .collect(),
        };
        let coll_name = |c: crate::value::Collation| match c {
            crate::value::Collation::NoCase => "NOCASE",
            crate::value::Collation::RTrim => "RTRIM",
            crate::value::Collation::Binary => "BINARY",
        };
        let mut rows = Vec::new();
        for (seqno, (cid, name, desc, coll)) in keys.iter().enumerate() {
            let name_val = name.clone().map_or(Value::Null, Value::Text);
            if extended {
                rows.push(alloc::vec![
                    Value::Integer(seqno as i64),
                    Value::Integer(*cid),
                    name_val,
                    Value::Integer(*desc as i64),
                    Value::Text(coll_name(*coll).into()),
                    Value::Integer(1), // key column
                ]);
            } else {
                rows.push(alloc::vec![
                    Value::Integer(seqno as i64),
                    Value::Integer(*cid),
                    name_val
                ]);
            }
        }
        // index_xinfo appends the index's implicit trailing auxiliary (non-key)
        // columns: the rowid for an ordinary table, or the PRIMARY KEY columns (in
        // key order, those not already index keys) for a WITHOUT ROWID table.
        if extended {
            if tmeta.without_rowid {
                let key_cids: Vec<i64> = keys.iter().map(|(cid, ..)| *cid).collect();
                let mut seqno = keys.len();
                for &pcid in &tmeta.storage_order[..tmeta.pk_len] {
                    if key_cids.contains(&(pcid as i64)) {
                        continue;
                    }
                    rows.push(alloc::vec![
                        Value::Integer(seqno as i64),
                        Value::Integer(pcid as i64),
                        Value::Text(tmeta.columns[pcid].name.clone()),
                        Value::Integer(0),
                        Value::Text(coll_name(tmeta.columns[pcid].collation).into()),
                        Value::Integer(0), // auxiliary, non-key
                    ]);
                    seqno += 1;
                }
            } else {
                rows.push(alloc::vec![
                    Value::Integer(keys.len() as i64),
                    Value::Integer(-1),
                    Value::Null,
                    Value::Integer(0),
                    Value::Text("BINARY".into()),
                    Value::Integer(0),
                ]);
            }
        }
        let columns: Vec<String> = if extended {
            ["seqno", "cid", "name", "desc", "coll", "key"]
                .iter()
                .map(|s| String::from(*s))
                .collect()
        } else {
            ["seqno", "cid", "name"]
                .iter()
                .map(|s| String::from(*s))
                .collect()
        };
        Ok(QueryResult { columns, rows })
    }

    /// `PRAGMA foreign_key_list(table)` →
    /// `(id, seq, table, from, to, on_update, on_delete, match)`.
    fn pragma_foreign_key_list(&self, p: &Pragma) -> Result<QueryResult> {
        let table = Self::pragma_arg_name(p)?;
        let obj = self
            .schema
            .table(&table)
            .ok_or_else(|| Error::Error(format!("no such table: {table}")))?;
        let Statement::CreateTable(ct) = sql::parse_one(obj.sql.as_deref().unwrap_or(""))? else {
            // A virtual table (non-CREATE-TABLE schema) has no foreign keys.
            return Ok(QueryResult {
                columns: [
                    "id",
                    "seq",
                    "table",
                    "from",
                    "to",
                    "on_update",
                    "on_delete",
                    "match",
                ]
                .iter()
                .map(|s| String::from(*s))
                .collect(),
                rows: Vec::new(),
            });
        };
        let action = |a: FkAction| -> &'static str {
            match a {
                FkAction::NoAction => "NO ACTION",
                FkAction::Restrict => "RESTRICT",
                FkAction::Cascade => "CASCADE",
                FkAction::SetNull => "SET NULL",
                FkAction::SetDefault => "SET DEFAULT",
            }
        };
        // Collect (from-cols, fk) pairs from column-level and table-level FKs.
        let mut fks: Vec<(Vec<String>, &ForeignKey)> = Vec::new();
        for col in &ct.columns {
            for c in &col.constraints {
                if let ColumnConstraint::References(fk) = c {
                    fks.push((alloc::vec![col.name.clone()], fk));
                }
            }
        }
        for c in &ct.constraints {
            if let TableConstraint::ForeignKey(fk) = c {
                fks.push((fk.columns.clone(), fk));
            }
        }
        let mut rows = Vec::new();
        // SQLite numbers foreign keys from the last declared (id 0) backward, and
        // lists them by id ascending — so iterate in reverse declaration order.
        let n = fks.len();
        for (i, (from_cols, fk)) in fks.iter().enumerate().rev() {
            let id = (n - 1 - i) as i64;
            for (seq, from) in from_cols.iter().enumerate() {
                let to = fk.ref_columns.get(seq).cloned().unwrap_or_default();
                rows.push(alloc::vec![
                    Value::Integer(id),
                    Value::Integer(seq as i64),
                    Value::Text(fk.ref_table.clone()),
                    Value::Text(from.clone()),
                    if to.is_empty() {
                        Value::Null
                    } else {
                        Value::Text(to)
                    },
                    Value::Text(action(fk.on_update).into()),
                    Value::Text(action(fk.on_delete).into()),
                    Value::Text("NONE".into()),
                ]);
            }
        }
        Ok(QueryResult {
            columns: [
                "id",
                "seq",
                "table",
                "from",
                "to",
                "on_update",
                "on_delete",
                "match",
            ]
            .iter()
            .map(|s| String::from(*s))
            .collect(),
            rows,
        })
    }

    /// `PRAGMA foreign_key_check[(table)]` → one `(table, rowid, parent, fkid)`
    /// row per child row that references a missing parent key. `fkid` matches the
    /// `id` reported by `foreign_key_list`.
    fn pragma_foreign_key_check(&self, p: &Pragma) -> Result<QueryResult> {
        use crate::schema::ObjectType;
        let tables: Vec<String> = match &p.value {
            Some(_) => alloc::vec![Self::pragma_arg_name(p)?],
            None => self
                .schema
                .objects()
                .iter()
                .filter(|o| o.obj_type == ObjectType::Table && !o.name.starts_with("sqlite_"))
                .map(|o| o.name.clone())
                .collect(),
        };
        let mut rows = Vec::new();
        for table in &tables {
            let meta = self.table_meta(table, None)?;
            if meta.without_rowid {
                continue; // rowid-less FK reporting not modeled yet
            }
            let fks = self.foreign_keys_of(table)?;
            if fks.is_empty() {
                continue;
            }
            let n = fks.len();
            for (rowid, values) in self.scan_table(&meta)? {
                for (i, fk) in fks.iter().enumerate() {
                    let Some(key) = self.child_key_values(&meta, fk, &values) else {
                        continue; // a NULL key column => satisfied
                    };
                    if !self.parent_has_key(fk, &key)? {
                        rows.push(alloc::vec![
                            Value::Text(table.clone()),
                            Value::Integer(rowid),
                            Value::Text(fk.ref_table.clone()),
                            Value::Integer((n - 1 - i) as i64),
                        ]);
                    }
                }
            }
        }
        Ok(QueryResult {
            columns: ["table", "rowid", "parent", "fkid"]
                .iter()
                .map(|s| String::from(*s))
                .collect(),
            rows,
        })
    }

    /// `PRAGMA integrity_check` / `quick_check`: walk every table and index
    /// b-tree and verify each index holds exactly the entries its table implies
    /// (honoring partial-index predicates). Returns the single value `ok` when the
    /// database is consistent, else one row per detected problem.
    fn pragma_integrity_check(&self) -> Result<QueryResult> {
        use crate::schema::ObjectType;
        let single = |v: Value| QueryResult {
            columns: alloc::vec![String::from("integrity_check")],
            rows: alloc::vec![alloc::vec![v]],
        };
        let tables: Vec<String> = self
            .schema
            .objects()
            .iter()
            // Skip virtual tables: they have no b-tree of their own (a persistent
            // module's rows live in its `<name>_data` backing table, itself an
            // ordinary table that is checked here).
            .filter(|o| {
                o.obj_type == ObjectType::Table
                    && !o.name.starts_with("sqlite_")
                    && !matches!(
                        o.sql.as_deref().map(sql::parse_one),
                        Some(Ok(Statement::CreateVirtualTable(_)))
                    )
            })
            .map(|o| o.name.clone())
            .collect();

        let mut problems = Vec::new();
        for table in &tables {
            let meta = self.table_meta(table, None)?;
            // The rows that physically exist, and how many each index should hold.
            let rows: Vec<Vec<Value>> = if meta.without_rowid {
                self.scan_without_rowid(&meta)?
            } else {
                self.scan_table(&meta)?
                    .into_iter()
                    .map(|(_, v)| v)
                    .collect()
            };
            let no_params = Params::default();
            for idx in self.indexes_of(table)? {
                let expected = rows
                    .iter()
                    .filter_map(|r| self.row_in_index(&idx, &meta, r, None, &no_params).ok())
                    .filter(|&keep| keep)
                    .count();
                // Count the index b-tree's entries.
                let mut cur = crate::btree::IndexCursor::new(self.backend.source(), idx.root);
                let mut got = 0usize;
                while cur.next()?.is_some() {
                    got += 1;
                }
                if got != expected {
                    problems.push(alloc::format!("wrong # of entries in index {}", idx.name));
                }
            }
        }

        if problems.is_empty() {
            Ok(single(Value::Text("ok".into())))
        } else {
            Ok(QueryResult {
                columns: alloc::vec![String::from("integrity_check")],
                rows: problems
                    .into_iter()
                    .map(|p| alloc::vec![Value::Text(p)])
                    .collect(),
            })
        }
    }

    /// Execute a single non-`SELECT` statement, returning the number of rows
    /// affected (0 for DDL and transaction control).
    pub fn execute(&mut self, sql: &str) -> Result<usize> {
        self.execute_params(sql, &Params::default())
    }

    /// Register a virtual-table [`module`](crate::vtab::VTabModule) under `name`,
    /// the identifier used after `USING` in `CREATE VIRTUAL TABLE … USING <name>`.
    /// A module implementing [`VTabModule::update`](crate::vtab::VTabModule::update)
    /// makes its tables writable; the default leaves them read-only. Fails if a
    /// module is already registered under that name (case-insensitively).
    pub fn register_module(
        &mut self,
        name: &str,
        module: impl DynVTabModule + 'static,
    ) -> Result<()> {
        self.vtab_registry.register(name, Box::new(module))
    }

    /// Register a user-defined scalar function callable from SQL by `name`. `f`
    /// receives the evaluated argument values and returns a result [`Value`]. A
    /// built-in function of the same name takes precedence; registering an existing
    /// user function replaces it. The callback should validate its own argument
    /// count and types (returning an error otherwise), like SQLite's
    /// `sqlite3_create_function` callbacks.
    pub fn register_function(
        &mut self,
        name: &str,
        f: impl Fn(&[Value]) -> Result<Value> + 'static,
    ) {
        self.functions
            .insert(name.to_ascii_lowercase(), Box::new(f));
    }

    /// Register a user-defined aggregate function callable from SQL by `name`.
    /// `factory` builds a fresh [`AggregateFunction`] accumulator for each group;
    /// the engine calls `step` once per group row (with the evaluated arguments)
    /// then `finalize`. Built-in aggregates of the same name take precedence.
    pub fn register_aggregate_function(
        &mut self,
        name: &str,
        factory: impl Fn() -> Box<dyn AggregateFunction> + 'static,
    ) {
        self.aggregates
            .insert(name.to_ascii_lowercase(), Box::new(factory));
    }

    /// Execute a `;`-separated script of one or more statements, like SQLite's
    /// `sqlite3_exec`. Each statement runs in order through the normal
    /// single-statement path (so per-statement `CREATE` text is preserved and
    /// each autocommits unless the script opens its own transaction); execution
    /// stops at the first error. `;` inside string literals, `--`/`/* */`
    /// comments, and `BEGIN…END` / `CASE…END` blocks does not split a statement.
    /// A `SELECT` runs and its rows are discarded (as `sqlite3_exec` does without
    /// a callback). [`execute`](Self::execute) stays single-statement.
    pub fn execute_batch(&mut self, sql: &str) -> Result<()> {
        for stmt in split_sql_script(sql) {
            if matches!(sql::parse_one(stmt), Ok(Statement::Select(_))) {
                self.query(stmt)?;
            } else {
                self.execute_params(stmt, &Params::default())?;
            }
        }
        Ok(())
    }

    /// Like [`execute`](Self::execute) but with bound parameters.
    pub fn execute_params(&mut self, sql: &str, params: &Params) -> Result<usize> {
        let stmt = sql::parse_one(sql)?;
        // Transaction control is handled directly (no autocommit around it).
        match &stmt {
            Statement::Begin => {
                if self.in_tx {
                    return Err(Error::Error(
                        "cannot start a transaction within a transaction".into(),
                    ));
                }
                self.in_tx = true;
                return Ok(0);
            }
            Statement::Commit => {
                if !self.in_tx && self.open_savepoints == 0 {
                    return Err(Error::Error(
                        "cannot commit - no transaction is active".into(),
                    ));
                }
                // Deferred foreign keys are verified here. On violation the
                // transaction stays open (SQLite leaves it active so the caller
                // can repair the data and COMMIT again) — nothing is committed.
                self.check_deferred_fks()?;
                self.backend.writer()?.commit()?;
                // Cross-database transaction: commit the temp + attached
                // databases alongside main (a clean pager commit is a no-op).
                self.commit_attached()?;
                self.in_tx = false;
                self.open_savepoints = 0;
                return Ok(0);
            }
            Statement::Savepoint(name) => {
                self.backend.writer()?.savepoint(name);
                self.savepoint_attached(name)?;
                self.open_savepoints += 1;
                return Ok(0);
            }
            Statement::Release(name) => {
                self.backend.writer()?.release_savepoint(name)?;
                self.release_attached(name)?;
                self.open_savepoints = self.backend.writer()?.savepoint_depth();
                // Releasing the outermost savepoint of an implicit transaction
                // finalizes it — verify deferred foreign keys first.
                if self.open_savepoints == 0 && !self.in_tx {
                    self.check_deferred_fks()?;
                    self.backend.writer()?.commit()?;
                    self.commit_attached()?;
                    self.schema = Schema::read(self.backend.source())?;
                }
                return Ok(0);
            }
            Statement::RollbackTo(name) => {
                self.backend.writer()?.rollback_to_savepoint(name)?;
                self.rollback_to_attached(name)?;
                self.open_savepoints = self.backend.writer()?.savepoint_depth();
                // The schema may have reverted to the savepoint's state.
                self.schema = Schema::read(self.backend.source())?;
                return Ok(0);
            }
            Statement::Rollback => {
                if !self.in_tx && self.open_savepoints == 0 {
                    return Err(Error::Error(
                        "cannot rollback - no transaction is active".into(),
                    ));
                }
                self.backend.writer()?.rollback();
                // Cross-database transaction: roll back the temp + attached
                // databases too, discarding their staged changes.
                self.rollback_attached()?;
                self.in_tx = false;
                self.open_savepoints = 0;
                self.schema = Schema::read(self.backend.source())?;
                return Ok(0);
            }
            _ => {}
        }

        // A DDL/DML statement targeting a non-main database (`… aux.t`,
        // `CREATE TEMP …`, or an unqualified name that a temp table shadows) runs
        // against that database: a single write touches exactly one database, so
        // we make it the active `main` for the duration (swapping back
        // afterwards, even on error). Cross-database *joins* are handled
        // separately in the read path.
        let target = self.target_db(&stmt)?;
        if target == DbRef::Temp {
            self.ensure_temp()?;
        }
        match target {
            DbRef::Main => self.exec_parsed(stmt, sql, params),
            other => {
                // `INSERT INTO <non-main>.t SELECT … FROM s`: the SELECT's
                // unqualified names resolve in the normal (main-first) order, not
                // the target database. Materialize the source rows here, before
                // swapping to the target — but only if they resolve in this
                // (original) context; otherwise leave it unchanged so the swapped
                // path still handles a source that lives in the target db.
                let stmt = self.prematerialize_insert_source(stmt, params);
                self.swap_db(other);
                let r = self.exec_parsed(stmt, sql, params);
                self.swap_db(other);
                r
            }
        }
    }

    /// For an `INSERT` whose source reads the original database (a `SELECT`, or a
    /// `VALUES` row with a subquery), evaluate it in the current (pre-swap) context
    /// and replace the source with literal rows, so a later swap to the target
    /// database does not re-resolve those table names there — matching SQLite's
    /// main-first resolution for a cross-database `INSERT INTO aux.t SELECT … FROM
    /// main_table` (or `… VALUES ((SELECT … FROM main_table))`). If it does not
    /// resolve here — e.g. the source lives only in the target db — the statement
    /// is returned unchanged so the swapped-context path handles it; the read is
    /// side-effect-free, so the discarded attempt is safe. A plain literal `VALUES`
    /// is left untouched (it needs no resolution).
    fn prematerialize_insert_source(&self, stmt: Statement, params: &Params) -> Statement {
        if let Statement::Insert(mut ins) = stmt {
            match &ins.source {
                InsertSource::Select(sel) => {
                    if let Ok(result) = self.run_select(sel, params) {
                        let rows: Vec<Vec<Expr>> = result
                            .rows
                            .into_iter()
                            .map(|row| row.into_iter().map(value_to_literal_expr).collect())
                            .collect();
                        ins.source = InsertSource::Values(rows);
                    }
                }
                // A `VALUES` row with a subquery (`VALUES ((SELECT … FROM m))`):
                // evaluate every expression here so the subquery resolves
                // main-first. Untouched when none has a subquery (plain literals).
                InsertSource::Values(rows) if rows.iter().flatten().any(expr_has_subquery) => {
                    let ctx = EvalCtx::rowless(params).with_subqueries(self);
                    let mut out = Vec::with_capacity(rows.len());
                    let materialized = rows.iter().try_for_each(|row| {
                        let mut r = Vec::with_capacity(row.len());
                        for e in row {
                            r.push(value_to_literal_expr(eval::eval(e, &ctx)?));
                        }
                        out.push(r);
                        Ok::<(), Error>(())
                    });
                    if materialized.is_ok() {
                        ins.source = InsertSource::Values(out);
                    }
                }
                _ => {}
            }
            return Statement::Insert(ins);
        }
        stmt
    }

    /// The database a DDL/DML statement targets: an explicit `schema.` qualifier
    /// (including `CREATE TEMP …` → `Temp`), else — for DML/`DROP` — the temp
    /// database when it shadows the unqualified name, else `main`.
    fn target_db(&self, stmt: &Statement) -> Result<DbRef> {
        let resolved = |s: Option<&str>, name: &str| -> Result<DbRef> {
            match s {
                Some(_) => self.resolve_db(s),
                None => Ok(self.unqualified_db(name)),
            }
        };
        match stmt {
            // CREATE never temp-shadows: a bare `CREATE TABLE t` goes to main.
            Statement::CreateTable(s) => self.resolve_db(s.schema.as_deref()),
            Statement::Insert(s) => resolved(s.schema.as_deref(), &s.table),
            Statement::Update(s) => resolved(s.schema.as_deref(), &s.table),
            Statement::Delete(s) => resolved(s.schema.as_deref(), &s.table),
            Statement::Drop(s) => resolved(s.schema.as_deref(), &s.name),
            Statement::Alter(a) => resolved(a.schema.as_deref(), &a.table),
            // The index lives in the schema named on the index (or, unqualified,
            // wherever its table lives — so a temp table's index goes to temp).
            Statement::CreateIndex(ci) => resolved(ci.schema.as_deref(), &ci.table),
            // A view lives in the schema named on it (`CREATE TEMP VIEW` → temp);
            // an unqualified `CREATE VIEW` stays in main.
            Statement::CreateView(cv) => self.resolve_db(cv.schema.as_deref()),
            // A trigger lives in the schema named on it (or, unqualified,
            // wherever the table it fires on lives).
            Statement::CreateTrigger(ct) => resolved(ct.schema.as_deref(), &ct.table),
            // A virtual table lives in the schema named on it; bare → main.
            Statement::CreateVirtualTable(cvt) => self.resolve_db(cvt.schema.as_deref()),
            _ => Ok(DbRef::Main),
        }
    }

    /// Commit pending changes in the temp + attached databases, refreshing each
    /// catalog from its committed image. Part of a cross-database transaction
    /// commit; a clean pager commit is a no-op.
    fn commit_attached(&mut self) -> Result<()> {
        if let Some(t) = &mut self.temp_db {
            t.backend.writer()?.commit()?;
            t.schema = Schema::read(t.backend.source())?;
        }
        for d in &mut self.attached {
            d.backend.writer()?.commit()?;
            d.schema = Schema::read(d.backend.source())?;
        }
        Ok(())
    }

    /// Roll back staged changes in the temp + attached databases and reload each
    /// catalog. Part of a cross-database transaction rollback.
    fn rollback_attached(&mut self) -> Result<()> {
        if let Some(t) = &mut self.temp_db {
            t.backend.writer()?.rollback();
            t.schema = Schema::read(t.backend.source())?;
        }
        for d in &mut self.attached {
            d.backend.writer()?.rollback();
            d.schema = Schema::read(d.backend.source())?;
        }
        Ok(())
    }

    /// Open a savepoint in the temp + attached databases too, so a later
    /// `ROLLBACK TO`/`RELEASE` reaches their staged changes.
    fn savepoint_attached(&mut self, name: &str) -> Result<()> {
        if let Some(t) = &mut self.temp_db {
            t.backend.writer()?.savepoint(name);
        }
        for d in &mut self.attached {
            d.backend.writer()?.savepoint(name);
        }
        Ok(())
    }

    /// Release a savepoint in the temp + attached databases. A database attached
    /// after the savepoint was opened has no such savepoint; that is not an error
    /// here (it simply had nothing staged at that point).
    fn release_attached(&mut self, name: &str) -> Result<()> {
        if let Some(t) = &mut self.temp_db {
            let _ = t.backend.writer()?.release_savepoint(name);
        }
        for d in &mut self.attached {
            let _ = d.backend.writer()?.release_savepoint(name);
        }
        Ok(())
    }

    /// Roll the temp + attached databases back to a savepoint, reloading the
    /// catalog of each that actually had it (see [`release_attached`]).
    fn rollback_to_attached(&mut self, name: &str) -> Result<()> {
        if let Some(t) = &mut self.temp_db {
            let did = t.backend.writer()?.rollback_to_savepoint(name).is_ok();
            if did {
                t.schema = Schema::read(t.backend.source())?;
            }
        }
        for d in &mut self.attached {
            let did = d.backend.writer()?.rollback_to_savepoint(name).is_ok();
            if did {
                d.schema = Schema::read(d.backend.source())?;
            }
        }
        Ok(())
    }

    /// Make `db` the active `main` (or swap it back) by exchanging the backend
    /// and schema. Used around a write to a non-main database.
    fn swap_db(&mut self, db: DbRef) {
        match db {
            DbRef::Main => {}
            DbRef::Temp => {
                let t = self.temp_db.as_mut().expect("temp db exists");
                core::mem::swap(&mut self.backend, &mut t.backend);
                core::mem::swap(&mut self.schema, &mut t.schema);
            }
            DbRef::Attached(i) => self.swap_attached(i),
        }
    }

    fn swap_attached(&mut self, i: usize) {
        core::mem::swap(&mut self.backend, &mut self.attached[i].backend);
        core::mem::swap(&mut self.schema, &mut self.attached[i].schema);
    }

    /// Execute a parsed non-transaction-control statement on the active database.
    fn exec_parsed(&mut self, stmt: Statement, sql: &str, params: &Params) -> Result<usize> {
        // `changes()`/`total_changes()` track only INSERT/UPDATE/DELETE.
        let is_dml = matches!(
            stmt,
            Statement::Insert(_) | Statement::Update(_) | Statement::Delete(_)
        );
        // Writes to an `auto_vacuum` database are now supported: the write-side
        // pager maintains the pointer-map pages on commit (see
        // `WritePager::rebuild_ptrmap`), so the C6a guard that used to refuse
        // such writes has been lifted. auto_vacuum=NONE databases take the
        // unchanged plain write path.
        // An INSERT/UPDATE/DELETE is atomic: if it fails partway (a constraint
        // violation, a trigger `RAISE(ABORT)`, …) the rows it already changed are
        // undone, leaving the database as if the statement never ran — unless the
        // failing conflict policy was `OR FAIL`, which keeps the partial change.
        // We realise this with an internal savepoint snapshotting the writer
        // overlay(s) before the statement and rolling back to it on an
        // abort-class error. (A no-op for DDL, which doesn't set `is_dml`.)
        if is_dml {
            self.stmt_keep_partial.set(false);
            self.stmt_rollback_tx.set(false);
            return self.run_dml_atomic(stmt, params);
        }
        let affected = match stmt {
            Statement::CreateTable(ct) => {
                self.exec_create_table(&ct, ddl_text(sql))?;
                0
            }
            Statement::Insert(_) | Statement::Delete(_) | Statement::Update(_) => unreachable!(),
            Statement::CreateIndex(ci) => {
                self.exec_create_index(&ci, ddl_text(sql))?;
                0
            }
            Statement::CreateView(cv) => {
                self.exec_create_view(&cv, ddl_text(sql))?;
                0
            }
            Statement::CreateTrigger(ct) => {
                self.exec_create_trigger(&ct, ddl_text(sql))?;
                0
            }
            Statement::CreateVirtualTable(cvt) => {
                self.exec_create_virtual_table(&cvt, ddl_text(sql))?;
                0
            }
            Statement::Drop(d) => {
                self.exec_drop(&d)?;
                0
            }
            Statement::Alter(a) => {
                self.exec_alter(&a)?;
                0
            }
            Statement::Pragma(p) => {
                self.exec_pragma(&p, params)?;
                0
            }
            Statement::Vacuum { schema, into } => {
                // A named database must exist (main/temp/an attached schema);
                // sqlite errors "unknown database <name>" otherwise. VACUUM itself
                // operates on the whole connection regardless of the named schema.
                if let Some(name) = schema {
                    let name = name.as_str();
                    let known = name.eq_ignore_ascii_case("main")
                        || name.eq_ignore_ascii_case("temp")
                        || self
                            .attached
                            .iter()
                            .any(|a| a.name.eq_ignore_ascii_case(name));
                    if !known {
                        return Err(Error::Error(format!("unknown database {name}")));
                    }
                }
                self.exec_vacuum(into.as_deref())?;
                0
            }
            // Indexes are kept current on every write, so REINDEX is a no-op — but
            // a named target must identify a collation, table, or index, else
            // sqlite errors "unable to identify the object to be reindexed".
            Statement::Reindex(target) => {
                if let Some(name) = target {
                    let name = name.as_str();
                    let known = crate::value::Collation::parse(name).is_some()
                        || self.schema.table(name).is_some()
                        || self.schema.index(name).is_some();
                    if !known {
                        return Err(Error::Error(
                            "unable to identify the object to be reindexed".into(),
                        ));
                    }
                }
                0
            }
            Statement::Analyze(target) => {
                self.exec_analyze(target.as_deref())?;
                0
            }
            Statement::Attach { file, name } => {
                self.exec_attach(&file, &name, params)?;
                0
            }
            Statement::Detach(name) => {
                self.exec_detach(&name)?;
                0
            }
            Statement::Select(_) => return Err(Error::Unsupported("use query() for SELECT")),
            Statement::Explain { .. } => return Err(Error::Unsupported("use query() for EXPLAIN")),
            Statement::Begin
            | Statement::Commit
            | Statement::Rollback
            | Statement::Savepoint(_)
            | Statement::Release(_)
            | Statement::RollbackTo(_) => unreachable!(),
        };

        if !self.in_tx && self.open_savepoints == 0 {
            self.backend.writer()?.commit()?;
            // Refresh the catalog from the committed image.
            self.schema = Schema::read(self.backend.source())?;
        }
        Ok(affected)
    }

    /// Execute one INSERT/UPDATE/DELETE under an internal savepoint so it is
    /// atomic: on an abort-class failure (a constraint violation, a trigger
    /// `RAISE(ABORT)`, …) the writer overlay(s) are rolled back to the
    /// pre-statement snapshot, so no partial change survives. `OR FAIL` keeps the
    /// rows changed before the failure; `OR ROLLBACK` unwinds the whole
    /// transaction.
    /// Build the constraint error for a conflict under conflict policy `oc`,
    /// arming the statement-atomicity flags so `run_dml_atomic` keeps partial
    /// changes (`OR FAIL`) or unwinds the transaction (`OR ROLLBACK`).
    fn conflict_error(&self, oc: OnConflict, msg: &str) -> Error {
        match oc {
            OnConflict::Fail => self.stmt_keep_partial.set(true),
            OnConflict::Rollback => self.stmt_rollback_tx.set(true),
            _ => {}
        }
        Error::Constraint(String::from(msg))
    }

    /// Resolve `NOT NULL` violations for an INSERT/UPDATE row under its conflict
    /// mode, mutating `values` as needed. For each `NOT NULL` column that is NULL,
    /// the effective action is the statement's `OR <action>` (when it wrote one)
    /// else the column's declared `ON CONFLICT` action: `REPLACE` substitutes the
    /// column's DEFAULT (erroring if there is none, like SQLite), `IGNORE` skips
    /// the whole row (returns `Ok(false)`), and `ABORT`/`FAIL`/`ROLLBACK` error
    /// with the action's rollback semantics. `Ok(true)` means the row may proceed.
    fn resolve_not_null(
        &self,
        meta: &TableMeta,
        values: &mut [Value],
        stmt_oc: OnConflict,
        stmt_explicit: bool,
        params: &Params,
    ) -> Result<bool> {
        for (i, slot) in values.iter_mut().enumerate() {
            if !matches!(slot, Value::Null) {
                continue;
            }
            let Some(col_oc) = meta.not_null[i] else {
                continue;
            };
            let oc = if stmt_explicit { stmt_oc } else { col_oc };
            let fail = || {
                let msg = format!(
                    "NOT NULL constraint failed: {}.{}",
                    meta.columns[i].table, meta.columns[i].name
                );
                self.conflict_error(oc, &msg)
            };
            match oc {
                OnConflict::Ignore => return Ok(false),
                OnConflict::Replace => {
                    // Substitute the column's DEFAULT; a missing or NULL default
                    // leaves the violation, which then errors.
                    let v = match &meta.defaults[i] {
                        Some(e) => eval::eval(e, &EvalCtx::rowless(params)).unwrap_or(Value::Null),
                        None => Value::Null,
                    };
                    if matches!(v, Value::Null) {
                        return Err(fail());
                    }
                    *slot = v;
                }
                _ => return Err(fail()),
            }
        }
        Ok(true)
    }

    fn run_dml_atomic(&mut self, stmt: Statement, params: &Params) -> Result<usize> {
        const SP: &str = "\u{0}graphite_stmt";
        self.backend.writer()?.savepoint(SP);
        self.savepoint_attached(SP)?;
        let result = match stmt {
            Statement::Insert(ins) => self.exec_insert(&ins, params),
            Statement::Delete(del) => self.exec_delete(&del, params),
            Statement::Update(upd) => self.exec_update(&upd, params),
            _ => unreachable!("run_dml_atomic only handles DML"),
        };
        match result {
            Ok(affected) => {
                let _ = self.backend.writer()?.release_savepoint(SP);
                let _ = self.release_attached(SP);
                self.changes.set(affected as i64);
                self.total_changes
                    .set(self.total_changes.get() + affected as i64);
                if !self.in_tx && self.open_savepoints == 0 {
                    self.backend.writer()?.commit()?;
                    self.schema = Schema::read(self.backend.source())?;
                }
                Ok(affected)
            }
            Err(e) => {
                if self.stmt_rollback_tx.get() {
                    // `OR ROLLBACK`: discard the entire (implicit or explicit)
                    // transaction's staged changes.
                    self.backend.writer()?.rollback();
                    self.rollback_attached()?;
                    self.in_tx = false;
                    self.open_savepoints = 0;
                    self.schema = Schema::read(self.backend.source())?;
                } else if self.stmt_keep_partial.get() {
                    // `OR FAIL`: keep what was changed before the failure.
                    let _ = self.backend.writer()?.release_savepoint(SP);
                    let _ = self.release_attached(SP);
                    if !self.in_tx && self.open_savepoints == 0 {
                        self.backend.writer()?.commit()?;
                        self.schema = Schema::read(self.backend.source())?;
                    }
                } else {
                    // `OR ABORT` (the default): undo just this statement.
                    let _ = self.backend.writer()?.rollback_to_savepoint(SP);
                    let _ = self.backend.writer()?.release_savepoint(SP);
                    let _ = self.rollback_to_attached(SP);
                    let _ = self.release_attached(SP);
                    if !self.in_tx && self.open_savepoints == 0 {
                        // Outside a transaction the rolled-back statement leaves
                        // nothing to commit; drop any other staged state too.
                        self.backend.writer()?.rollback();
                        self.rollback_attached()?;
                        self.schema = Schema::read(self.backend.source())?;
                    }
                }
                Err(e)
            }
        }
    }

    /// Execute an `INSERT`/`UPDATE`/`DELETE` with a `RETURNING` clause, returning
    /// the projected rows as a [`QueryResult`]. Without a `RETURNING` list the
    /// result has no columns and no rows (the statement still runs for its
    /// effects). Errors on `SELECT`/DDL — use [`query`](Self::query) or
    /// [`execute`](Self::execute) for those.
    pub fn execute_returning(&mut self, sql: &str, params: &Params) -> Result<QueryResult> {
        let stmt = sql::parse_one(sql)?;
        let returning: &[ResultColumn] = match &stmt {
            Statement::Insert(i) => &i.returning,
            Statement::Update(u) => &u.returning,
            Statement::Delete(d) => &d.returning,
            _ => {
                return Err(Error::Unsupported(
                    "execute_returning expects INSERT/UPDATE/DELETE",
                ))
            }
        };
        if returning.is_empty() {
            self.execute_params(sql, params)?;
            return Ok(QueryResult {
                columns: Vec::new(),
                rows: Vec::new(),
            });
        }
        let table = match &stmt {
            Statement::Insert(i) => &i.table,
            Statement::Update(u) => &u.table,
            Statement::Delete(d) => &d.table,
            _ => unreachable!(),
        };
        let meta = self.table_meta(table, None)?;
        let columns = returning_labels(returning, &meta.columns);
        self.returning_rows.borrow_mut().clear();
        self.execute_params(sql, params)?;
        let rows = core::mem::take(&mut *self.returning_rows.borrow_mut());
        Ok(QueryResult { columns, rows })
    }

    /// `ATTACH <expr> AS <name>`: open another database under `name`. An empty
    /// or `:memory:` path creates a fresh in-memory database; a real file path is
    /// not yet supported (track piece C5).
    fn exec_attach(&mut self, file: &Expr, name: &str, params: &Params) -> Result<()> {
        let path = {
            let ctx = EvalCtx::rowless(params).with_subqueries(self);
            eval::to_text(&eval::eval(file, &ctx)?)
        };
        if name.eq_ignore_ascii_case("main")
            || name.eq_ignore_ascii_case("temp")
            || self
                .attached
                .iter()
                .any(|d| d.name.eq_ignore_ascii_case(name))
        {
            return Err(Error::Error(alloc::format!(
                "database {name} is already in use"
            )));
        }
        let (backend, file) = if path.is_empty() || path.eq_ignore_ascii_case(":memory:") {
            // A fresh in-memory database (same pattern as `open_memory`).
            let vfs = crate::vfs::memory::MemoryVfs::new();
            let f = vfs.open(name, OpenFlags::READ_WRITE_CREATE)?;
            let mut db = WritePager::create(f, None, 4096)?;
            db.commit()?;
            (Backend::Write(Box::new(db)), String::new())
        } else {
            (self.open_attached_file(&path)?, path)
        };
        let schema = Schema::read(backend.source())?;
        self.attached.push(AttachedDb {
            name: name.to_string(),
            file,
            backend,
            schema,
        });
        Ok(())
    }

    /// Open (or create, if absent/empty) a real file as an attached database's
    /// backend. Requires the `std` file VFS.
    #[cfg(feature = "std")]
    fn open_attached_file(&self, path: &str) -> Result<Backend> {
        let vfs = crate::vfs::std_file::StdVfs::new();
        let main = vfs.open(path, OpenFlags::READ_WRITE_CREATE)?;
        let journal = vfs.open(&journal_path(path), OpenFlags::READ_WRITE_CREATE)?;
        // Rollback-journal (non-WAL) mode: commits land directly in the main
        // file, so the attached database is immediately readable by sqlite3
        // without needing a WAL checkpoint when the connection closes.
        let db = if main.size()? == 0 {
            let mut db = WritePager::create(main, Some(journal), 4096)?;
            db.commit()?;
            db
        } else {
            WritePager::open(main, Some(journal))?
        };
        Ok(Backend::Write(Box::new(db)))
    }

    #[cfg(not(feature = "std"))]
    fn open_attached_file(&self, _path: &str) -> Result<Backend> {
        Err(Error::Unsupported("ATTACH of a file database requires std"))
    }

    /// `DETACH <name>`: close an attached database. `main`/`temp` cannot be
    /// detached; an unknown name is an error.
    fn exec_detach(&mut self, name: &str) -> Result<()> {
        if name.eq_ignore_ascii_case("main") || name.eq_ignore_ascii_case("temp") {
            return Err(Error::Error(alloc::format!(
                "cannot detach database {name}"
            )));
        }
        match self
            .attached
            .iter()
            .position(|d| d.name.eq_ignore_ascii_case(name))
        {
            Some(i) => {
                self.attached.remove(i);
                Ok(())
            }
            None => Err(Error::Error(alloc::format!("no such database: {name}"))),
        }
    }

    /// `VACUUM`: rebuild the database into a fresh, compact image (no free pages,
    /// defragmented b-trees) and replace the file. Implemented by replaying the
    /// stored `CREATE` statements and re-inserting all rows into a throwaway
    /// in-memory database, then copying its pages over. A no-op for read-only
    /// backends.
    fn exec_vacuum(&mut self, into: Option<&Expr>) -> Result<()> {
        use crate::schema::ObjectType;
        // In-place VACUUM on a read-only backend is a no-op; `VACUUM … INTO`
        // only reads the source, so it proceeds regardless of the backend.
        if into.is_none() && !matches!(self.backend, Backend::Write(_)) {
            return Ok(());
        }
        // Flush any WAL frames into the main image first (in-place rewrite only).
        if into.is_none() && self.backend.wal_mode() {
            self.backend.writer()?.checkpoint()?;
        }
        let user_version = self.backend.source().header().user_version;

        // Snapshot the catalog: (type, name, sql), preserving creation order.
        let objs: Vec<(ObjectType, String, Option<String>)> = self
            .schema
            .objects()
            .iter()
            .map(|o| (o.obj_type, o.name.clone(), o.sql.clone()))
            .collect();

        let quote = |n: &str| alloc::format!("\"{}\"", n.replace('"', "\"\""));

        // Virtual tables and their `<name>_data` backing tables need special care:
        // recreating the `CREATE VIRTUAL TABLE` already creates the backing table,
        // so the backing table must not be created (or its rows copied) separately
        // — a persistent vtab's rows are repopulated by re-inserting through the
        // vtab itself, and a computed (non-persistent) vtab has no rows to copy.
        let is_vtab = |sql: &Option<String>| {
            matches!(
                sql.as_deref().map(sql::parse_one),
                Some(Ok(Statement::CreateVirtualTable(_)))
            )
        };
        let vtab_names: alloc::collections::BTreeSet<String> = objs
            .iter()
            .filter(|(ty, _, sql)| *ty == ObjectType::Table && is_vtab(sql))
            .map(|(_, n, _)| n.clone())
            .collect();
        let table_names: alloc::collections::BTreeSet<String> = objs
            .iter()
            .filter(|(ty, _, _)| *ty == ObjectType::Table)
            .map(|(_, n, _)| n.clone())
            .collect();
        let is_backing = |name: &str| {
            [
                "_data", "_node", "_rowid", "_parent", "_content", "_docsize", "_config", "_idx",
            ]
            .iter()
            .any(|sfx| {
                name.strip_suffix(sfx)
                    .is_some_and(|p| vtab_names.contains(p))
            })
        };
        // A vtab is persistent (has rows to copy through it) iff a backing table
        // exists — the generic `_data` or an R-Tree's `_node`.
        let persistent_vtab = |name: &str| {
            vtab_names.contains(name)
                && (table_names.contains(&alloc::format!("{name}_data"))
                    || table_names.contains(&alloc::format!("{name}_node")))
        };

        // Build a compact copy in a throwaway in-memory database.
        let mut tmp = Connection::open_memory()?;
        // 1. Tables (this also recreates their automatic indexes). Skip a vtab's
        //    backing table — its `CREATE VIRTUAL TABLE` recreates it.
        for (ty, name, sql) in &objs {
            if *ty == ObjectType::Table && !is_backing(name) {
                if let Some(s) = sql {
                    tmp.execute(s)?;
                }
            }
        }
        // 2. Explicit secondary indexes (auto-indexes have no SQL).
        for (ty, _, sql) in &objs {
            if *ty == ObjectType::Index {
                if let Some(s) = sql {
                    tmp.execute(s)?;
                }
            }
        }
        // 3. Re-insert every table's rows (before triggers exist, so none fire).
        //    Skip a vtab's backing table (repopulated through the vtab) and a
        //    computed vtab (no rows); a persistent vtab is copied via the vtab,
        //    whose INSERTs rewrite the backing table.
        for (ty, name, _) in &objs {
            if *ty != ObjectType::Table
                || is_backing(name)
                || (vtab_names.contains(name) && !persistent_vtab(name))
            {
                continue;
            }
            let result = self.query(&alloc::format!("SELECT * FROM {}", quote(name)))?;
            let ncols = result.columns.len();
            if ncols == 0 {
                continue;
            }
            let placeholders = (1..=ncols)
                .map(|i| alloc::format!("?{i}"))
                .collect::<Vec<_>>()
                .join(",");
            let stmt = alloc::format!("INSERT INTO {} VALUES ({placeholders})", quote(name));
            for row in result.rows {
                let params = Params {
                    positional: row,
                    named: Vec::new(),
                };
                tmp.execute_params(&stmt, &params)?;
            }
        }
        // 4. Views, then 5. triggers (last, so loading data didn't fire them).
        for (ty, _, sql) in &objs {
            if *ty == ObjectType::View {
                if let Some(s) = sql {
                    tmp.execute(s)?;
                }
            }
        }
        for (ty, _, sql) in &objs {
            if *ty == ObjectType::Trigger {
                if let Some(s) = sql {
                    tmp.execute(s)?;
                }
            }
        }

        // Snapshot the compact image's pages.
        let count = tmp.backend.source().page_count();
        let mut image = Vec::with_capacity(count as usize);
        for n in 1..=count {
            image.push(tmp.backend.source().page(n)?.data().to_vec());
        }

        // `VACUUM … INTO <file>`: write the image to a new database file.
        if let Some(expr) = into {
            return self.vacuum_write_into(expr, image);
        }

        // Plain `VACUUM`: copy the compact image's pages over the current file.
        self.backend.writer()?.replace_image(image)?;

        // Preserve user_version across the rebuild.
        if user_version != 0 {
            self.backend.writer()?.header_mut().user_version = user_version;
            // Re-stamp page 1 via a commit.
            let mut page1 = self.backend.writer()?.read_page(1)?;
            self.backend.writer()?.header().write_to(&mut page1)?;
            self.backend.writer()?.write_page(1, page1)?;
            self.backend.writer()?.commit()?;
        }
        self.schema = Schema::read(self.backend.source())?;
        Ok(())
    }

    /// Write a freshly-built compact page `image` to a NEW database file for
    /// `VACUUM … INTO <file>`. The target path comes from evaluating `expr`; it
    /// must not already exist (matching SQLite). `std`-only — creating a file
    /// needs the OS VFS.
    #[cfg(feature = "std")]
    fn vacuum_write_into(&self, expr: &Expr, image: Vec<Vec<u8>>) -> Result<()> {
        let params = Params::default();
        let path = match eval::eval(expr, &EvalCtx::rowless(&params))? {
            Value::Null => return Err(Error::Error("VACUUM INTO target is NULL".into())),
            Value::Text(s) => s,
            other => eval::to_text(&other),
        };
        if std::path::Path::new(&path).exists() {
            return Err(Error::Error(alloc::format!(
                "output file already exists: {path}"
            )));
        }
        let user_version = self.backend.source().header().user_version;
        let mut dst = Connection::create(&path)?;
        dst.backend.writer()?.replace_image(image)?;
        if user_version != 0 {
            dst.backend.writer()?.header_mut().user_version = user_version;
        }
        // Stamp page 1 (the header, incl. user_version) and flush to disk.
        let mut page1 = dst.backend.writer()?.read_page(1)?;
        dst.backend.writer()?.header().write_to(&mut page1)?;
        dst.backend.writer()?.write_page(1, page1)?;
        dst.backend.writer()?.commit()?;
        Ok(())
    }

    /// Without `std` there is no file VFS to create the target, so `VACUUM …
    /// INTO` is unsupported (the in-place form still works).
    #[cfg(not(feature = "std"))]
    fn vacuum_write_into(&self, _expr: &Expr, _image: Vec<Vec<u8>>) -> Result<()> {
        Err(Error::Error(
            "VACUUM INTO requires the std feature (file I/O)".into(),
        ))
    }

    /// `ANALYZE`: gather index selectivity statistics into the `sqlite_stat1`
    /// table. The `stat` string for an index is `nRow avgEq1 avgEq2 …`, where
    /// `avgEqK = (nRow + dK/2) / dK` and `dK` is the number of distinct values of
    /// the index's leftmost `K` columns — the same integers SQLite records. A
    /// table with no index gets a single `(tbl, NULL, nRow)` row.
    fn exec_analyze(&mut self, target: Option<&str>) -> Result<()> {
        use crate::schema::ObjectType;
        // Which user tables to (re)analyze.
        let analyze: Vec<String> = match target {
            None => self
                .schema
                .objects()
                .iter()
                .filter(|o| o.obj_type == ObjectType::Table && !o.name.starts_with("sqlite_"))
                .map(|o| o.name.clone())
                .collect(),
            Some(name) => {
                if let Some(t) = self.schema.table(name) {
                    alloc::vec![t.name.clone()]
                } else if let Some(ix) = self.schema.index(name) {
                    alloc::vec![ix.tbl_name.clone()]
                } else if name.eq_ignore_ascii_case("main") {
                    // `ANALYZE <database>` analyzes that schema; for `main` that is
                    // every main user table (the no-argument form's behavior).
                    self.schema
                        .objects()
                        .iter()
                        .filter(|o| {
                            o.obj_type == ObjectType::Table && !o.name.starts_with("sqlite_")
                        })
                        .map(|o| o.name.clone())
                        .collect()
                } else if is_main_schema_table(name)
                    || name.eq_ignore_ascii_case("temp")
                    || self
                        .attached
                        .iter()
                        .any(|a| a.name.eq_ignore_ascii_case(name))
                {
                    // A valid schema table or attached/temp database: graphite keeps
                    // stats only for main, so this is a no-op — but not an error,
                    // matching sqlite (which only errors on a genuinely unknown name).
                    Vec::new()
                } else {
                    return Err(Error::Error(format!("no such table: {name}")));
                }
            }
        };

        // Compute the new stat rows up front (read-only phase).
        let mut new_rows: Vec<(String, Option<String>, String)> = Vec::new();
        for tname in &analyze {
            let meta = self.table_meta(tname, None)?;
            let rows: Vec<Vec<Value>> = if meta.without_rowid {
                self.scan_without_rowid(&meta)?
            } else {
                self.scan_table(&meta)?
                    .into_iter()
                    .map(|(_, v)| v)
                    .collect()
            };
            let n = rows.len();
            let indexes = self.indexes_of(tname)?;
            if indexes.is_empty() {
                if n > 0 {
                    new_rows.push((tname.clone(), None, alloc::format!("{n}")));
                }
            } else {
                for idx in &indexes {
                    if n == 0 {
                        continue; // SQLite records nothing for an empty index
                    }
                    let stat = index_stat_string(&idx.cols, &idx.collations, &rows);
                    new_rows.push((tname.clone(), Some(idx.name.clone()), stat));
                }
            }
        }

        // Ensure the sqlite_stat1 catalog table exists.
        if self.schema.table("sqlite_stat1").is_none() {
            const STAT1_SQL: &str = "CREATE TABLE sqlite_stat1(tbl,idx,stat)";
            let Statement::CreateTable(ct) = sql::parse_one(STAT1_SQL)? else {
                unreachable!()
            };
            self.exec_create_table(&ct, STAT1_SQL)?;
        }
        let stat_root = self.schema.table("sqlite_stat1").unwrap().rootpage;

        // Replace existing rows for the analyzed tables.
        let stat_meta = self.table_meta("sqlite_stat1", None)?;
        let victims: Vec<i64> = self
            .scan_table(&stat_meta)?
            .into_iter()
            .filter(
                |(_, vals)| matches!(&vals[0], Value::Text(t) if analyze.iter().any(|a| a == t)),
            )
            .map(|(rid, _)| rid)
            .collect();
        for rid in victims {
            delete_table(self.backend.writer()?, stat_root, rid)?;
        }

        let base = self.next_rowid(stat_root)?;
        for (i, (tbl, idx, stat)) in new_rows.into_iter().enumerate() {
            let rec = encode_record(&[
                Value::Text(tbl),
                idx.map_or(Value::Null, Value::Text),
                Value::Text(stat),
            ]);
            insert_table(self.backend.writer()?, stat_root, base + i as i64, &rec)?;
        }
        self.schema = Schema::read(self.backend.source())?;
        Ok(())
    }

    // ---- DDL / DML ----------------------------------------------------------

    fn exec_create_table(&mut self, ct: &CreateTable, sql_text: &str) -> Result<()> {
        if let Some(select) = &ct.as_select {
            return self.exec_create_table_as_select(ct, select);
        }
        // The schema-qualified form (`CREATE TABLE aux.t …`) must be stored in the
        // target database's catalog WITHOUT the `schema.` prefix — otherwise the
        // stored SQL is invalid in that database's own namespace (and unreadable
        // by sqlite3). Reprint the bare-name form when a qualifier was present.
        let reprinted;
        let sql_text = if ct.schema.is_some() {
            reprinted = sql::print::create_table(ct);
            reprinted.as_str()
        } else {
            sql_text
        };
        if self.schema.table(&ct.name).is_some() {
            if ct.if_not_exists {
                return Ok(());
            }
            return Err(Error::Error(format!("table {} already exists", ct.name)));
        }
        // STRICT tables restrict column types to the six rigid types; reject any
        // other (or missing) declared type at CREATE, like SQLite.
        if ct.strict {
            for c in &ct.columns {
                if strict_column_type(c.type_name.as_deref()).is_none() {
                    return Err(match &c.type_name {
                        Some(t) => Error::Error(format!(
                            "unknown datatype for {}.{}: \"{t}\"",
                            ct.name, c.name
                        )),
                        None => {
                            Error::Error(format!("missing datatype for {}.{}", ct.name, c.name))
                        }
                    });
                }
            }
        }
        // SQLite forbids subqueries in CHECK constraints and generated columns.
        for c in &ct.columns {
            for k in &c.constraints {
                match k {
                    ColumnConstraint::Check(e, _) if expr_has_subquery(e) => {
                        return Err(Error::Error(
                            "subqueries prohibited in CHECK constraints".into(),
                        ));
                    }
                    ColumnConstraint::Generated { expr, .. } if expr_has_subquery(expr) => {
                        return Err(Error::Error(
                            "subqueries prohibited in generated columns".into(),
                        ));
                    }
                    ColumnConstraint::Generated { expr, .. } if expr_is_nondeterministic(expr) => {
                        return Err(Error::Error(
                            "non-deterministic functions prohibited in generated columns".into(),
                        ));
                    }
                    _ => {}
                }
            }
        }
        // Generated-column constraint rules SQLite rejects at CREATE: a generated
        // column may not carry a second `AS (…)`, a `DEFAULT`, or be part of the
        // PRIMARY KEY (whether declared column-level or in a table-level
        // `PRIMARY KEY (…)`).
        let table_pk_cols: Vec<&str> = ct
            .constraints
            .iter()
            .filter_map(|tc| match tc {
                TableConstraint::PrimaryKey(cols, _) => Some(cols),
                _ => None,
            })
            .flatten()
            .map(String::as_str)
            .collect();
        for c in &ct.columns {
            let generated = c
                .constraints
                .iter()
                .filter(|k| matches!(k, ColumnConstraint::Generated { .. }))
                .count();
            if generated == 0 {
                continue;
            }
            if generated > 1 {
                return Err(Error::Error(alloc::format!(
                    "error in generated column \"{}\"",
                    c.name
                )));
            }
            if c.constraints
                .iter()
                .any(|k| matches!(k, ColumnConstraint::Default(_)))
            {
                return Err(Error::Error(
                    "cannot use DEFAULT on a generated column".into(),
                ));
            }
            let in_primary_key = c
                .constraints
                .iter()
                .any(|k| matches!(k, ColumnConstraint::PrimaryKey { .. }))
                || table_pk_cols
                    .iter()
                    .any(|p| p.eq_ignore_ascii_case(&c.name));
            if in_primary_key {
                return Err(Error::Error(
                    "generated columns cannot be part of the PRIMARY KEY".into(),
                ));
            }
        }
        // SQLite rejects an aggregate function in a CHECK or generated-column
        // expression at CREATE ("misuse of aggregate function NAME()").
        for c in &ct.columns {
            for k in &c.constraints {
                let agg = match k {
                    ColumnConstraint::Check(e, _) | ColumnConstraint::Generated { expr: e, .. } => {
                        first_aggregate_call_name(e)
                    }
                    _ => None,
                };
                if let Some(name) = agg {
                    return Err(Error::Error(format!(
                        "misuse of aggregate function {name}()"
                    )));
                }
            }
        }
        for tc in &ct.constraints {
            if let TableConstraint::Check(e, _) = tc {
                if expr_has_subquery(e) {
                    return Err(Error::Error(
                        "subqueries prohibited in CHECK constraints".into(),
                    ));
                }
                if let Some(name) = first_aggregate_call_name(e) {
                    return Err(Error::Error(format!(
                        "misuse of aggregate function {name}()"
                    )));
                }
            }
        }
        // A CHECK / generated-column expression may reference only the table's own
        // columns, like SQLite (which rejects an unknown column at CREATE). A
        // generated column additionally may not reference the rowid; a CHECK may.
        let known: Vec<String> = ct.columns.iter().map(|c| c.name.clone()).collect();
        for c in &ct.columns {
            for k in &c.constraints {
                // A column's `COLLATE <name>` must name a known collating sequence
                // (BINARY/NOCASE/RTRIM); sqlite errors "no such collation sequence"
                // at CREATE rather than silently falling back to BINARY.
                if let ColumnConstraint::Collate(name) = k {
                    if crate::value::Collation::parse(name).is_none() {
                        return Err(Error::Error(format!("no such collation sequence: {name}")));
                    }
                }
                let bad = match k {
                    ColumnConstraint::Check(e, _) => unknown_column_ref(e, &known, true),
                    ColumnConstraint::Generated { expr, .. } => {
                        unknown_column_ref(expr, &known, false)
                    }
                    _ => None,
                };
                if let Some(col) = bad {
                    return Err(Error::Error(format!("no such column: {col}")));
                }
            }
        }
        for tc in &ct.constraints {
            if let TableConstraint::Check(e, _) = tc {
                if let Some(col) = unknown_column_ref(e, &known, true) {
                    return Err(Error::Error(format!("no such column: {col}")));
                }
            }
            // A table-level FOREIGN KEY's *local* columns must each be a declared
            // column (a generated column counts; `rowid` does not), as SQLite
            // rejects at CREATE. The referenced parent table/columns are not
            // checked here — SQLite resolves those lazily.
            if let TableConstraint::ForeignKey(fk) = tc {
                for col in &fk.columns {
                    if !known.iter().any(|k| k.eq_ignore_ascii_case(col)) {
                        return Err(Error::Error(format!(
                            "unknown column \"{col}\" in foreign key definition"
                        )));
                    }
                }
            }
        }
        // A table must have at least one non-generated (real) column, as in SQLite.
        if !ct.columns.is_empty()
            && ct.columns.iter().all(|c| {
                c.constraints
                    .iter()
                    .any(|k| matches!(k, ColumnConstraint::Generated { .. }))
            })
        {
            return Err(Error::Error(
                "must have at least one non-generated column".into(),
            ));
        }
        // Duplicate column names are rejected.
        for (i, c) in ct.columns.iter().enumerate() {
            if ct.columns[..i]
                .iter()
                .any(|p| p.name.eq_ignore_ascii_case(&c.name))
            {
                return Err(Error::Error(alloc::format!(
                    "duplicate column name: {}",
                    c.name
                )));
            }
        }
        // At most one PRIMARY KEY (column-level + table-level).
        let pk_count = ct
            .columns
            .iter()
            .flat_map(|c| &c.constraints)
            .filter(|k| matches!(k, ColumnConstraint::PrimaryKey { .. }))
            .count()
            + ct.constraints
                .iter()
                .filter(|tc| matches!(tc, TableConstraint::PrimaryKey(..)))
                .count();
        if pk_count > 1 {
            return Err(Error::Error(alloc::format!(
                "table {} has more than one primary key",
                ct.name
            )));
        }
        // Table-level PRIMARY KEY/UNIQUE column lists must name real columns.
        for tc in &ct.constraints {
            let cols = match tc {
                TableConstraint::PrimaryKey(cols, _) | TableConstraint::Unique(cols, _) => cols,
                _ => continue,
            };
            for name in cols {
                if !ct.columns.iter().any(|c| c.name.eq_ignore_ascii_case(name)) {
                    return Err(Error::Error(alloc::format!("no such column: {name}")));
                }
            }
        }
        // AUTOINCREMENT is only valid on a rowid `INTEGER PRIMARY KEY` column.
        let ipk = find_integer_primary_key(ct);
        let has_autoinc = |i: usize| {
            ct.columns[i].constraints.iter().any(|k| {
                matches!(
                    k,
                    ColumnConstraint::PrimaryKey {
                        autoincrement: true,
                        ..
                    }
                )
            })
        };
        if (0..ct.columns.len()).any(has_autoinc) {
            if ct.without_rowid {
                return Err(Error::Error(
                    "AUTOINCREMENT not allowed on WITHOUT ROWID tables".into(),
                ));
            }
            if !(0..ct.columns.len()).any(|i| has_autoinc(i) && Some(i) == ipk) {
                return Err(Error::Error(
                    "AUTOINCREMENT is only allowed on an INTEGER PRIMARY KEY".into(),
                ));
            }
        }
        // A WITHOUT ROWID table is stored as a PK-clustered index b-tree; an
        // ordinary table uses a rowid table b-tree.
        let root = if ct.without_rowid {
            // A WITHOUT ROWID table must have a PRIMARY KEY (it is the b-tree key).
            if primary_key_positions(ct).is_empty() {
                return Err(Error::Error(
                    "WITHOUT ROWID table must have a PRIMARY KEY".into(),
                ));
            }
            create_index_root(self.backend.writer()?)?
        } else {
            create_table_root(self.backend.writer()?)?
        };
        let next = self.next_rowid(crate::schema::SCHEMA_ROOT_PAGE)?;
        let row = encode_record(&[
            Value::Text("table".into()),
            Value::Text(ct.name.clone()),
            Value::Text(ct.name.clone()),
            Value::Integer(root as i64),
            Value::Text(sql_text.into()),
        ]);
        insert_table(
            self.backend.writer()?,
            crate::schema::SCHEMA_ROOT_PAGE,
            next,
            &row,
        )?;

        // Create the automatic indexes SQLite implies for UNIQUE / non-rowid
        // PRIMARY KEY constraints, so the file is a valid SQLite database (it
        // otherwise reports "wrong # of entries in index sqlite_autoindex_*").
        // For a WITHOUT ROWID table the PRIMARY KEY *is* the table (no separate
        // b-tree), but it still consumes its `sqlite_autoindex_<t>_<n>` slot.
        let ipk = if ct.without_rowid {
            None
        } else {
            find_integer_primary_key(ct)
        };
        let unique = collect_unique_sets(ct, ipk);
        let pk = if ct.without_rowid {
            primary_key_positions(ct)
        } else {
            Vec::new()
        };
        let mut schema_rowid = next + 1;
        for (n, (set, _)) in unique.iter().enumerate() {
            // The clustered PRIMARY KEY of a WITHOUT ROWID table gets no b-tree.
            if ct.without_rowid && *set == pk {
                continue;
            }
            let idx_root = create_index_root(self.backend.writer()?)?;
            let idx_row = encode_record(&[
                Value::Text("index".into()),
                Value::Text(alloc::format!("sqlite_autoindex_{}_{}", ct.name, n + 1)),
                Value::Text(ct.name.clone()),
                Value::Integer(idx_root as i64),
                Value::Null, // automatic indexes carry no CREATE SQL
            ]);
            insert_table(
                self.backend.writer()?,
                crate::schema::SCHEMA_ROOT_PAGE,
                schema_rowid,
                &idx_row,
            )?;
            schema_rowid += 1;
        }

        // An `AUTOINCREMENT` table requires the `sqlite_sequence` catalog, which
        // SQLite creates (empty) the first time such a table is created.
        let is_autoinc = ipk.is_some_and(|i| {
            ct.columns[i].constraints.iter().any(|k| {
                matches!(
                    k,
                    ColumnConstraint::PrimaryKey {
                        autoincrement: true,
                        ..
                    }
                )
            })
        });
        if is_autoinc && self.schema.table("sqlite_sequence").is_none() {
            const SEQ_SQL: &str = "CREATE TABLE sqlite_sequence(name,seq)";
            let Statement::CreateTable(seq_ct) = sql::parse_one(SEQ_SQL)? else {
                unreachable!()
            };
            self.exec_create_table(&seq_ct, SEQ_SQL)?;
        }

        let cookie = self
            .backend
            .writer()?
            .header()
            .schema_cookie
            .wrapping_add(1);
        self.backend.writer()?.header_mut().schema_cookie = cookie;
        // Make the new table visible to subsequent statements in this tx.
        self.schema = Schema::read(self.backend.source())?;
        Ok(())
    }

    /// `CREATE TABLE name AS SELECT …`: create a table whose columns are the
    /// query's output labels (no declared types/constraints), then populate it
    /// with the query's rows.
    fn exec_create_table_as_select(&mut self, ct: &CreateTable, select: &Select) -> Result<()> {
        if self.schema.table(&ct.name).is_some() {
            if ct.if_not_exists {
                return Ok(());
            }
            return Err(Error::Error(format!("table {} already exists", ct.name)));
        }
        let result = self.run_select(select, &Params::default())?;
        // SQLite auto-renames duplicate output column names in CTAS — the second
        // `a` becomes `a:1`, the third `a:2`, etc. — rather than erroring like an
        // explicit `CREATE TABLE` column list. Names compare case-insensitively.
        let mut counts: alloc::collections::BTreeMap<String, usize> =
            alloc::collections::BTreeMap::new();
        let deduped: Vec<String> = result
            .columns
            .iter()
            .map(|c| {
                let n = counts.entry(c.to_ascii_lowercase()).or_insert(0);
                let name = if *n == 0 {
                    c.clone()
                } else {
                    alloc::format!("{c}:{n}")
                };
                *n += 1;
                name
            })
            .collect();
        // Build and create the resolved table `name(col1, col2, …)`.
        let cols = deduped
            .iter()
            .map(|c| crate::sql::print::ident(c))
            .collect::<Vec<_>>()
            .join(", ");
        let create_sql = format!(
            "CREATE TABLE {}({cols})",
            crate::sql::print::ident(&ct.name)
        );
        let Statement::CreateTable(syn) = sql::parse_one(&create_sql)? else {
            return Err(Error::Corrupt("generated CTAS schema is invalid".into()));
        };
        self.exec_create_table(&syn, &create_sql)?;
        // Populate it with the query's rows via the normal insert path.
        if !result.rows.is_empty() {
            let value_rows: Vec<Vec<Expr>> = result
                .rows
                .into_iter()
                .map(|row| {
                    row.into_iter()
                        .map(|v| Expr::Literal(value_to_literal(v)))
                        .collect()
                })
                .collect();
            let ins = Insert {
                table: ct.name.clone(),
                schema: None,
                columns: Vec::new(),
                source: InsertSource::Values(value_rows),
                on_conflict: OnConflict::Abort,
                // A VACUUM re-insert of already-valid rows keeps the plain default.
                on_conflict_explicit: true,
                upsert: Vec::new(),
                returning: Vec::new(),
            };
            self.exec_insert(&ins, &Params::default())?;
        }
        Ok(())
    }

    /// Handle a settable `PRAGMA` (currently only `foreign_keys`). Unknown
    /// pragmas are accepted as no-ops, matching SQLite's leniency.
    fn exec_pragma(&mut self, p: &Pragma, params: &Params) -> Result<()> {
        if p.name.eq_ignore_ascii_case("foreign_keys") {
            if let Some(e) = &p.value {
                self.foreign_keys = pragma_truth(e, params);
            }
        } else if p.name.eq_ignore_ascii_case("recursive_triggers") {
            if let Some(e) = &p.value {
                self.recursive_triggers = pragma_truth(e, params);
            }
        } else if p.name.eq_ignore_ascii_case("cache_size") {
            // Round-trip the value verbatim (graphite keeps all pages resident, so
            // it changes nothing) — `PRAGMA cache_size` then reports it back.
            if let Some(e) = &p.value {
                self.cache_size
                    .set(eval::to_i64(&eval::eval(e, &EvalCtx::rowless(params))?));
            }
        } else if p.name.eq_ignore_ascii_case("analysis_limit") {
            // The ANALYZE sample cap (advisory here); store it, clamping a negative
            // value to 0 like sqlite, so a later `PRAGMA analysis_limit` reads back.
            if let Some(e) = &p.value {
                let v = eval::to_i64(&eval::eval(e, &EvalCtx::rowless(params))?);
                self.analysis_limit.set(v.max(0));
            }
        } else if p.name.eq_ignore_ascii_case("busy_timeout") {
            // Advisory (graphite never blocks on a lock); store it, clamping a
            // negative value to 0, so a later `PRAGMA busy_timeout` reads it back.
            if let Some(e) = &p.value {
                let v = eval::to_i64(&eval::eval(e, &EvalCtx::rowless(params))?);
                self.busy_timeout.set(v.max(0));
            }
        } else if p.name.eq_ignore_ascii_case("secure_delete") {
            // sqlite maps the argument to 0 (off), 2 (the `fast` keyword only), or
            // 1 (any other true / non-zero value). The pager zeroes freed pages
            // when the setting is non-zero.
            if let Some(e) = &p.value {
                let v = match pragma_text(e).to_ascii_lowercase().as_str() {
                    "fast" => 2,
                    _ if pragma_truth(e, params) => 1,
                    _ => 0,
                };
                self.secure_delete.set(v);
                if let Backend::Write(w) = &mut self.backend {
                    w.set_secure_delete(v != 0);
                }
            }
        } else if p.name.eq_ignore_ascii_case("journal_mode") {
            if let Some(e) = &p.value {
                if pragma_text(e).eq_ignore_ascii_case("wal") {
                    self.backend.writer()?.set_wal_mode()?;
                }
                // Other modes (delete/truncate/persist/memory/off) keep the
                // rollback-journal path; switching back out of WAL is a no-op.
            }
        } else if p.name.eq_ignore_ascii_case("wal_checkpoint") {
            self.backend.writer()?.checkpoint()?;
        } else if p.name.eq_ignore_ascii_case("user_version") {
            if let Some(e) = &p.value {
                let v = eval::to_i64(&eval::eval(e, &EvalCtx::rowless(params))?) as u32;
                self.backend.writer()?.header_mut().user_version = v;
            }
        } else if p.name.eq_ignore_ascii_case("application_id") {
            if let Some(e) = &p.value {
                let v = eval::to_i64(&eval::eval(e, &EvalCtx::rowless(params))?) as u32;
                self.backend.writer()?.header_mut().application_id = v;
            }
        } else if p.name.eq_ignore_ascii_case("auto_vacuum") {
            if let Some(e) = &p.value {
                // Accept the symbolic and numeric spellings.
                let mode = match pragma_text(e).to_ascii_lowercase().as_str() {
                    "none" => 0,
                    "full" => 1,
                    "incremental" => 2,
                    _ => eval::to_i64(&eval::eval(e, &EvalCtx::rowless(params))?),
                };
                // SQLite only honours a change of auto-vacuum mode on an *empty*
                // database (before any table is created); afterwards it is a
                // no-op until the next VACUUM. graphite mirrors that: on an empty
                // database we stamp the header into the requested mode and the
                // pager maintains pointer-map pages from then on; on a non-empty
                // database the pragma is silently ignored.
                let target = match mode {
                    0 => AutoVacuum::None,
                    1 => AutoVacuum::Full,
                    2 => AutoVacuum::Incremental,
                    _ => return Err(Error::Error(format!("invalid auto_vacuum mode {mode}"))),
                };
                self.backend.writer()?.set_auto_vacuum_if_empty(target)?;
            }
        } else if p.name.eq_ignore_ascii_case("incremental_vacuum") {
            // `PRAGMA incremental_vacuum` (or `= N` / `(N)`): reclaim up to N free
            // pages off the end of an `auto_vacuum=INCREMENTAL` database. With no
            // argument (or N <= 0) reclaim as many as possible. The pager makes it
            // a no-op for NONE/FULL, mirroring SQLite. The reclamation is staged
            // like any other write; the caller's normal commit (the implicit
            // auto-commit when not in a transaction, or an explicit COMMIT) flushes
            // the now-smaller file to disk.
            let n = match &p.value {
                Some(e) => eval::to_i64(&eval::eval(e, &EvalCtx::rowless(params))?),
                None => 0,
            };
            self.backend.writer()?.incremental_vacuum(n)?;
        }
        Ok(())
    }

    /// The foreign keys declared by `table`, with child columns resolved and
    /// parent columns defaulted to the parent's primary key when omitted.
    fn foreign_keys_of(&self, table: &str) -> Result<Vec<ForeignKey>> {
        let Some(obj) = self.schema.table(table) else {
            return Ok(Vec::new());
        };
        let Some(sql) = &obj.sql else {
            return Ok(Vec::new());
        };
        let Statement::CreateTable(ct) = sql::parse_one(sql)? else {
            return Ok(Vec::new());
        };
        let mut out = Vec::new();
        for col in &ct.columns {
            for c in &col.constraints {
                if let ColumnConstraint::References(fk) = c {
                    out.push(self.resolve_fk(fk)?);
                }
            }
        }
        for c in &ct.constraints {
            if let TableConstraint::ForeignKey(fk) = c {
                out.push(self.resolve_fk(fk)?);
            }
        }
        Ok(out)
    }

    /// Fill in a foreign key's parent columns from the parent's primary key when
    /// the `REFERENCES` clause omitted them.
    fn resolve_fk(&self, fk: &ForeignKey) -> Result<ForeignKey> {
        let mut fk = fk.clone();
        if fk.ref_columns.is_empty() {
            fk.ref_columns = self.primary_key_columns(&fk.ref_table)?;
        }
        Ok(fk)
    }

    /// The primary-key column names of `table` (the INTEGER PRIMARY KEY, or a
    /// declared PRIMARY KEY constraint).
    fn primary_key_columns(&self, table: &str) -> Result<Vec<String>> {
        let Some(obj) = self.schema.table(table) else {
            return Err(Error::Error(format!("no such table: {table}")));
        };
        let sql = obj.sql.as_deref().unwrap_or("");
        let Statement::CreateTable(ct) = sql::parse_one(sql)? else {
            return Ok(Vec::new());
        };
        for col in &ct.columns {
            if col
                .constraints
                .iter()
                .any(|c| matches!(c, ColumnConstraint::PrimaryKey { .. }))
            {
                return Ok(alloc::vec![col.name.clone()]);
            }
        }
        for c in &ct.constraints {
            if let TableConstraint::PrimaryKey(cols, _) = c {
                return Ok(cols.clone());
            }
        }
        Ok(Vec::new())
    }

    /// Verify, for a row being inserted/updated into `table`, that every foreign
    /// key it declares points at an existing parent row. NULL key columns are
    /// skipped (MATCH SIMPLE).
    fn check_fk_child(&self, table: &str, meta: &TableMeta, values: &[Value]) -> Result<()> {
        if !self.foreign_keys {
            return Ok(());
        }
        for fk in self.foreign_keys_of(table)? {
            // A `DEFERRABLE INITIALLY DEFERRED` key is checked at COMMIT, not now
            // — but only inside an explicit transaction. In autocommit the
            // statement *is* the transaction, so its implicit commit is immediate.
            if fk.initially_deferred && self.in_tx {
                continue;
            }
            let key = match self.child_key_values(meta, &fk, values) {
                Some(k) => k,
                None => continue, // a NULL column => constraint satisfied
            };
            if !self.parent_has_key(&fk, &key)? {
                return Err(Error::Constraint("FOREIGN KEY constraint failed".into()));
            }
        }
        Ok(())
    }

    /// Verify every `DEFERRABLE INITIALLY DEFERRED` foreign key across all tables
    /// — run at `COMMIT` to catch a constraint that was temporarily violated
    /// inside the transaction and never repaired.
    fn check_deferred_fks(&self) -> Result<()> {
        if !self.foreign_keys {
            return Ok(());
        }
        for obj in self.schema.objects() {
            if obj.obj_type != crate::schema::ObjectType::Table {
                continue;
            }
            let fks: Vec<ForeignKey> = self
                .foreign_keys_of(&obj.name)?
                .into_iter()
                .filter(|fk| fk.initially_deferred)
                .collect();
            if fks.is_empty() {
                continue;
            }
            let meta = self.table_meta(&obj.name, None)?;
            for (_, row) in self.scan_table(&meta)? {
                for fk in &fks {
                    if let Some(key) = self.child_key_values(&meta, fk, &row) {
                        if !self.parent_has_key(fk, &key)? {
                            return Err(Error::Constraint("FOREIGN KEY constraint failed".into()));
                        }
                    }
                }
            }
        }
        Ok(())
    }

    /// The child key values for `fk` from a child row, or `None` if any is NULL.
    fn child_key_values(
        &self,
        meta: &TableMeta,
        fk: &ForeignKey,
        values: &[Value],
    ) -> Option<Vec<Value>> {
        let mut key = Vec::with_capacity(fk.columns.len());
        for cname in &fk.columns {
            let pos = meta
                .columns
                .iter()
                .position(|c| c.name.eq_ignore_ascii_case(cname))?;
            let v = values.get(pos)?;
            if matches!(v, Value::Null) {
                return None;
            }
            key.push(v.clone());
        }
        Some(key)
    }

    /// Whether the parent table of `fk` has a row whose referenced columns equal
    /// `key`.
    fn parent_has_key(&self, fk: &ForeignKey, key: &[Value]) -> Result<bool> {
        let pmeta = self.table_meta(&fk.ref_table, None)?;
        let positions = self.column_positions(&pmeta, &fk.ref_columns)?;
        for (_, row) in self.scan_table(&pmeta)? {
            if positions.iter().zip(key).all(|(&p, k)| {
                // SQLite compares under the *parent* key column's affinity and
                // collation: a text child '1' matches an INTEGER parent key 1 (and
                // 'x' cannot), and a NOCASE parent key matches case-insensitively.
                let (pv, kv) = eval::apply_comparison_affinity(
                    row[p].clone(),
                    Some(pmeta.columns[p].affinity),
                    k.clone(),
                    None,
                );
                crate::value::cmp_values_coll(&pv, &kv, pmeta.columns[p].collation)
                    == core::cmp::Ordering::Equal
            }) {
                return Ok(true);
            }
        }
        Ok(false)
    }

    /// Column positions in `meta` for the given names.
    fn column_positions(&self, meta: &TableMeta, names: &[String]) -> Result<Vec<usize>> {
        names
            .iter()
            .map(|n| {
                meta.columns
                    .iter()
                    .position(|c| c.name.eq_ignore_ascii_case(n))
                    .ok_or_else(|| Error::Error(format!("no such column: {n}")))
            })
            .collect()
    }

    /// Enforce referential actions when a parent row changes. `old_key` is the
    /// parent row's referenced-column values before the change; `new_key` is the
    /// values after (for `UPDATE`), or `None` for `DELETE`.
    fn enforce_parent_change(
        &mut self,
        parent_table: &str,
        old_vals: &[Value],
        new_vals: Option<&[Value]>,
        params: &Params,
    ) -> Result<()> {
        if !self.foreign_keys {
            return Ok(());
        }
        // Find every (child table, fk) that references this parent.
        let table_names: Vec<String> = self
            .schema
            .objects()
            .iter()
            .filter(|o| o.obj_type == crate::schema::ObjectType::Table)
            .map(|o| o.name.clone())
            .collect();
        let mut referencing: Vec<(String, ForeignKey)> = Vec::new();
        for name in table_names {
            for fk in self.foreign_keys_of(&name)? {
                if fk.ref_table.eq_ignore_ascii_case(parent_table) {
                    referencing.push((name.clone(), fk));
                }
            }
        }
        if referencing.is_empty() {
            return Ok(());
        }
        let pmeta = self.table_meta(parent_table, None)?;
        for (child_table, fk) in referencing {
            let ppos = self.column_positions(&pmeta, &fk.ref_columns)?;
            let old_key: Vec<Value> = ppos.iter().map(|&p| old_vals[p].clone()).collect();
            // A NULL parent key can't be referenced.
            if old_key.iter().any(|v| matches!(v, Value::Null)) {
                continue;
            }
            let is_delete = new_vals.is_none();
            let action = if is_delete {
                fk.on_delete
            } else {
                fk.on_update
            };
            // A deferred FK's NO ACTION orphan check waits for COMMIT (inside an
            // explicit transaction); RESTRICT and the data-changing actions
            // (CASCADE / SET NULL / SET DEFAULT) always run now.
            if action == FkAction::NoAction && fk.initially_deferred && self.in_tx {
                continue;
            }
            // If this is an UPDATE that didn't change the referenced key, skip.
            if let Some(nv) = new_vals {
                let new_key: Vec<Value> = ppos.iter().map(|&p| nv[p].clone()).collect();
                if new_key
                    .iter()
                    .zip(&old_key)
                    .all(|(a, b)| eval::compare(a, b) == core::cmp::Ordering::Equal)
                {
                    continue;
                }
            }
            self.apply_fk_action(&child_table, &fk, &old_key, new_vals, &ppos, action, params)?;
        }
        Ok(())
    }

    #[allow(clippy::too_many_arguments)]
    fn apply_fk_action(
        &mut self,
        child_table: &str,
        fk: &ForeignKey,
        old_key: &[Value],
        new_parent: Option<&[Value]>,
        parent_pos: &[usize],
        action: FkAction,
        params: &Params,
    ) -> Result<()> {
        let cmeta = self.table_meta(child_table, None)?;
        let cpos = self.column_positions(&cmeta, &fk.columns)?;
        // The parent key columns' affinities — applied to the child value when
        // matching, the same rule as the child→parent existence check
        // (`parent_has_key`): a text child '1' matches an INTEGER parent key 1.
        let pmeta = self.table_meta(&fk.ref_table, None)?;
        // Find child rowids whose key matches old_key.
        let mut matches: Vec<i64> = Vec::new();
        for (rowid, row) in self.scan_table(&cmeta)? {
            if cpos
                .iter()
                .zip(old_key)
                .zip(parent_pos)
                .all(|((&cp, k), &pp)| {
                    let (pv, kv) = eval::apply_comparison_affinity(
                        k.clone(),
                        Some(pmeta.columns[pp].affinity),
                        row[cp].clone(),
                        None,
                    );
                    crate::value::cmp_values_coll(&pv, &kv, pmeta.columns[pp].collation)
                        == core::cmp::Ordering::Equal
                })
            {
                matches.push(rowid);
            }
        }
        if matches.is_empty() {
            return Ok(());
        }
        match action {
            FkAction::NoAction | FkAction::Restrict => {
                Err(Error::Constraint("FOREIGN KEY constraint failed".into()))
            }
            FkAction::Cascade if new_parent.is_none() => {
                // DELETE CASCADE: delete the matching child rows (recursively).
                for rowid in matches {
                    self.delete_row_cascade(child_table, &cmeta, rowid, params)?;
                }
                Ok(())
            }
            FkAction::Cascade => {
                // UPDATE CASCADE: set child key columns to the new parent key.
                let new_parent = new_parent.unwrap();
                let new_key: Vec<Value> =
                    parent_pos.iter().map(|&p| new_parent[p].clone()).collect();
                for rowid in matches {
                    self.update_child_key(&cmeta, child_table, rowid, &cpos, &new_key)?;
                }
                Ok(())
            }
            FkAction::SetNull => {
                let nulls = alloc::vec![Value::Null; cpos.len()];
                for rowid in matches {
                    self.update_child_key(&cmeta, child_table, rowid, &cpos, &nulls)?;
                }
                Ok(())
            }
            FkAction::SetDefault => {
                let defaults: Vec<Value> = cpos
                    .iter()
                    .map(|&p| match &cmeta.defaults[p] {
                        Some(e) => eval::eval(e, &EvalCtx::rowless(params)).unwrap_or(Value::Null),
                        None => Value::Null,
                    })
                    .collect();
                for rowid in matches {
                    self.update_child_key(&cmeta, child_table, rowid, &cpos, &defaults)?;
                }
                Ok(())
            }
        }
    }

    /// Delete one child row by rowid, first cascading to its own children.
    fn delete_row_cascade(
        &mut self,
        table: &str,
        meta: &TableMeta,
        rowid: i64,
        params: &Params,
    ) -> Result<()> {
        // Read the row so its own dependents can be enforced.
        let old = self.read_row(meta, rowid)?;
        if let Some(old) = old {
            self.enforce_parent_change(table, &old, None, params)?;
        }
        delete_table(self.backend.writer()?, meta.root, rowid)?;
        let indexes = self.indexes_of(table)?;
        if !indexes.is_empty() {
            self.rebuild_indexes(meta, &indexes)?;
        }
        Ok(())
    }

    /// Set specific columns of a child row (by position) to new values.
    fn update_child_key(
        &mut self,
        meta: &TableMeta,
        table: &str,
        rowid: i64,
        positions: &[usize],
        new_vals: &[Value],
    ) -> Result<()> {
        let Some(mut row) = self.read_row(meta, rowid)? else {
            return Ok(());
        };
        for (&p, v) in positions.iter().zip(new_vals) {
            row[p] = v.clone();
        }
        // Re-encode and rewrite the row (rowid unchanged here).
        let mut stored = row.clone();
        if let Some(ipk) = meta.ipk {
            stored[ipk] = Value::Null;
        }
        let record = encode_record(&stored);
        insert_table(self.backend.writer()?, meta.root, rowid, &record)?;
        let indexes = self.indexes_of(table)?;
        if !indexes.is_empty() {
            self.rebuild_indexes(meta, &indexes)?;
        }
        Ok(())
    }

    /// Read a single row's full column values by rowid (IPK filled in), or None.
    fn read_row(&self, meta: &TableMeta, rowid: i64) -> Result<Option<Vec<Value>>> {
        let encoding = self.backend.source().header().text_encoding;
        let mut cur = TableCursor::new(self.backend.source(), meta.root);
        if cur.seek(rowid)? {
            let values = self.decode_full_row(meta, rowid, &cur.payload()?, encoding)?;
            Ok(Some(values))
        } else {
            Ok(None)
        }
    }

    /// Store a `CREATE TRIGGER` in `sqlite_schema` (type `trigger`, no b-tree).
    fn exec_create_trigger(&mut self, ct: &CreateTrigger, sql_text: &str) -> Result<()> {
        // A schema-qualified `CREATE TRIGGER aux.tr …` stores its SQL bare-named.
        let stripped;
        let sql_text = match ct.schema.as_deref() {
            Some(s) => {
                stripped = strip_schema_qualifier(sql_text, s)?;
                stripped.as_str()
            }
            None => sql_text,
        };
        if self
            .schema
            .objects()
            .iter()
            .any(|o| o.name.eq_ignore_ascii_case(&ct.name))
        {
            if ct.if_not_exists {
                return Ok(());
            }
            return Err(Error::Error(format!("trigger {} already exists", ct.name)));
        }
        // The target may be a table or (for INSTEAD OF triggers) a view. A temp
        // trigger may fire on a main table, so when the temp database is the active
        // schema also consult the swapped-out catalog (which then holds main).
        let table_in_other = self
            .temp_db
            .as_ref()
            .is_some_and(|t| t.schema.table(&ct.table).is_some());
        if self.schema.table(&ct.table).is_none() && !table_in_other && !self.is_view(&ct.table) {
            // SQLite schema-qualifies the missing table in CREATE TRIGGER/INDEX
            // (the object's target schema, `main` by default).
            return Err(Error::Error(format!(
                "no such table: {}.{}",
                ct.schema.as_deref().unwrap_or("main"),
                ct.table
            )));
        }
        let next = self.next_rowid(crate::schema::SCHEMA_ROOT_PAGE)?;
        let row = encode_record(&[
            Value::Text("trigger".into()),
            Value::Text(ct.name.clone()),
            Value::Text(ct.table.clone()),
            Value::Integer(0),
            Value::Text(sql_text.into()),
        ]);
        insert_table(
            self.backend.writer()?,
            crate::schema::SCHEMA_ROOT_PAGE,
            next,
            &row,
        )?;
        let cookie = self
            .backend
            .writer()?
            .header()
            .schema_cookie
            .wrapping_add(1);
        self.backend.writer()?.header_mut().schema_cookie = cookie;
        self.schema = Schema::read(self.backend.source())?;
        Ok(())
    }

    /// Triggers on `table` matching `kind`/`timing`, parsed from their schema SQL.
    fn triggers_for(
        &self,
        table: &str,
        kind: TrigEvent,
        timing: TriggerTiming,
    ) -> Result<Vec<CreateTrigger>> {
        let mut out = Vec::new();
        // The active schema plus the temp catalog: a temp trigger fires on writes
        // to its (possibly main) table, and a main trigger fires even while a temp
        // database is swapped in. `swap_db` exchanges `self.schema` with the temp
        // db's, so these two catalogs are always exactly {main, temp}.
        self.collect_triggers(self.schema.objects(), table, kind, timing, &mut out);
        if let Some(t) = &self.temp_db {
            self.collect_triggers(t.schema.objects(), table, kind, timing, &mut out);
        }
        // SQLite keeps a per-table trigger list that prepends on creation, so
        // triggers of the same event/timing fire in REVERSE creation order
        // (most-recently-created first). `objects()` is in creation order, so
        // reverse to match.
        out.reverse();
        Ok(out)
    }

    /// Append triggers from `objects` matching `table`/`kind`/`timing` to `out`.
    fn collect_triggers(
        &self,
        objects: &[crate::schema::SchemaObject],
        table: &str,
        kind: TrigEvent,
        timing: TriggerTiming,
        out: &mut Vec<CreateTrigger>,
    ) {
        for obj in objects {
            if obj.obj_type != crate::schema::ObjectType::Trigger
                || !obj.tbl_name.eq_ignore_ascii_case(table)
            {
                continue;
            }
            let Some(sql) = &obj.sql else { continue };
            let Ok(Statement::CreateTrigger(ct)) = sql::parse_one(sql) else {
                continue;
            };
            let event_ok = matches!(
                (&ct.event, kind),
                (TriggerEvent::Insert, TrigEvent::Insert)
                    | (TriggerEvent::Delete, TrigEvent::Delete)
                    | (TriggerEvent::Update(_), TrigEvent::Update)
            );
            if ct.timing == timing && event_ok {
                out.push(ct);
            }
        }
    }

    /// Fire row triggers for one row change. `old`/`new` carry the affected row's
    /// values and rowid before/after the change. Non-recursive: triggers fire
    /// only at the top level (matching `recursive_triggers = OFF`).
    #[allow(clippy::too_many_arguments)]
    fn fire_triggers(
        &mut self,
        table: &str,
        kind: TrigEvent,
        timing: TriggerTiming,
        columns: &[ColumnInfo],
        old: Option<(&[Value], i64)>,
        new: Option<(&[Value], i64)>,
        params: &Params,
        changed_cols: Option<&[String]>,
    ) -> Result<bool> {
        // Non-recursive by default; with PRAGMA recursive_triggers a trigger may
        // fire others, bounded to avoid runaway recursion (SQLite caps at 1000).
        let depth = self.trigger_depth.get();
        let limit = if self.recursive_triggers { 1000 } else { 1 };
        if depth >= limit {
            return if self.recursive_triggers {
                Err(Error::Error("too many levels of trigger recursion".into()))
            } else {
                Ok(false)
            };
        }
        let mut trigs = self.triggers_for(table, kind, timing)?;
        // An `UPDATE OF col, …` trigger fires only when one of its named columns
        // appears in the UPDATE's SET list (SQLite semantics).
        if let Some(changed) = changed_cols {
            trigs.retain(|t| match &t.event {
                TriggerEvent::Update(cols) if !cols.is_empty() => cols
                    .iter()
                    .any(|c| changed.iter().any(|ch| ch.eq_ignore_ascii_case(c))),
                _ => true,
            });
        }
        if trigs.is_empty() {
            return Ok(false);
        }
        self.trigger_depth.set(depth + 1);
        let base = self.outer_scope.borrow().len();
        if let Some((vals, rid)) = old {
            self.push_row_frame("old", columns, vals, rid);
        }
        if let Some((vals, rid)) = new {
            self.push_row_frame("new", columns, vals, rid);
        }
        let result = self.run_trigger_bodies(&trigs, params);
        self.outer_scope.borrow_mut().truncate(base);
        self.trigger_depth.set(depth);
        result.map(|()| true)
    }

    fn push_row_frame(&self, label: &str, columns: &[ColumnInfo], values: &[Value], rowid: i64) {
        let columns = columns
            .iter()
            .map(|c| ColumnInfo {
                name: c.name.clone(),
                table: String::from(label),
                affinity: c.affinity,
                collation: c.collation,
            })
            .collect();
        self.outer_scope.borrow_mut().push(OuterFrame {
            columns,
            row: values.to_vec(),
            rowid: Some(rowid),
        });
    }

    /// Whether `name` is a view in main (or a temp view, which shadows main).
    fn is_view(&self, name: &str) -> bool {
        self.temp_has_view(name)
            || self.schema.objects().iter().any(|o| {
                o.obj_type == crate::schema::ObjectType::View && o.name.eq_ignore_ascii_case(name)
            })
    }

    /// Whether the temp database holds a view named `name`.
    fn temp_has_view(&self, name: &str) -> bool {
        self.temp_db.as_ref().is_some_and(|t| {
            t.schema.objects().iter().any(|o| {
                o.obj_type == crate::schema::ObjectType::View && o.name.eq_ignore_ascii_case(name)
            })
        })
    }

    /// The output columns of a view (labeled with the view name).
    fn view_columns(&self, name: &str, params: &Params) -> Result<Vec<ColumnInfo>> {
        match self.try_view(name, None, params)? {
            Some((cols, _)) => Ok(cols),
            None => Err(Error::Error(format!("no such view: {name}"))),
        }
    }

    /// `INSERT` into a view: fire its `INSTEAD OF INSERT` triggers (per row), or
    /// error if none exist.
    fn exec_view_insert(
        &mut self,
        ins: &Insert,
        rows: &[Vec<Expr>],
        params: &Params,
    ) -> Result<usize> {
        let cols = self.view_columns(&ins.table, params)?;
        if self
            .triggers_for(&ins.table, TrigEvent::Insert, TriggerTiming::InsteadOf)?
            .is_empty()
        {
            return Err(Error::Error(format!(
                "cannot modify {} — it is a view",
                ins.table
            )));
        }
        let target: Vec<usize> = if ins.columns.is_empty() {
            (0..cols.len()).collect()
        } else {
            ins.columns
                .iter()
                .map(|name| {
                    cols.iter()
                        .position(|c| c.name.eq_ignore_ascii_case(name))
                        .ok_or_else(|| Error::Error(format!("no such column: {name}")))
                })
                .collect::<Result<_>>()?
        };
        let mut affected = 0;
        for row_exprs in rows {
            let ctx = EvalCtx::rowless(params).with_subqueries(self);
            let mut new = alloc::vec![Value::Null; cols.len()];
            for (i, e) in row_exprs.iter().enumerate() {
                new[target[i]] = eval::eval(e, &ctx)?;
            }
            self.fire_triggers(
                &ins.table,
                TrigEvent::Insert,
                TriggerTiming::InsteadOf,
                &cols,
                None,
                Some((&new, 0)),
                params,
                None,
            )?;
            if self.raise_ignore.replace(false) {
                continue;
            }
            affected += 1;
        }
        Ok(affected)
    }

    /// `DELETE` from a view: fire `INSTEAD OF DELETE` triggers for each row that
    /// the view yields and the `WHERE` selects.
    fn exec_view_delete(&mut self, del: &Delete, params: &Params) -> Result<usize> {
        let (cols, rows) = self
            .try_view(&del.table, None, params)?
            .ok_or_else(|| Error::Error(format!("no such view: {}", del.table)))?;
        if self
            .triggers_for(&del.table, TrigEvent::Delete, TriggerTiming::InsteadOf)?
            .is_empty()
        {
            return Err(Error::Error(format!(
                "cannot modify {} — it is a view",
                del.table
            )));
        }
        let mut affected = 0;
        for row in rows {
            if let Some(p) = &del.where_clause {
                let ctx = row_ctx(&row.values, &cols, None, params).with_subqueries(self);
                if eval::truth(&eval::eval(p, &ctx)?) != Some(true) {
                    continue;
                }
            }
            self.fire_triggers(
                &del.table,
                TrigEvent::Delete,
                TriggerTiming::InsteadOf,
                &cols,
                Some((&row.values, 0)),
                None,
                params,
                None,
            )?;
            if self.raise_ignore.replace(false) {
                continue;
            }
            affected += 1;
        }
        Ok(affected)
    }

    /// `UPDATE` a view: fire `INSTEAD OF UPDATE` triggers with OLD/NEW for each
    /// selected row.
    /// Apply `SET (cols) = (SELECT …)` row-value-subquery assignments for one
    /// target row: run each subquery once against `ctx` (the caller's original-row
    /// context, so it is a correlated, simultaneous read) and write its first
    /// row's columns into `target` at the positions named by the assignment's
    /// column list (no row → NULLs; a column-count mismatch errors). `meta`, when
    /// given, rejects assigning to a generated column.
    fn apply_row_subquery_assignments(
        &self,
        row_assignments: &[(Vec<String>, Box<Select>)],
        cols: &[ColumnInfo],
        meta: Option<&TableMeta>,
        ctx: &EvalCtx,
        target: &mut [Value],
    ) -> Result<()> {
        for (targets, select) in row_assignments {
            let mut positions = Vec::with_capacity(targets.len());
            for c in targets {
                let pos = cols
                    .iter()
                    .position(|mc| mc.name.eq_ignore_ascii_case(c))
                    .ok_or_else(|| Error::Error(format!("no such column: {c}")))?;
                if meta.is_some_and(|m| m.is_generated(pos)) {
                    return Err(Error::Error(format!(
                        "cannot UPDATE generated column \"{c}\""
                    )));
                }
                positions.push(pos);
            }
            let produced = eval::Subqueries::rows(self, select, ctx)?;
            let first = produced.into_iter().next();
            if let Some(r) = &first {
                if r.len() != positions.len() {
                    return Err(Error::Error(format!(
                        "{} columns assigned {} values",
                        positions.len(),
                        r.len()
                    )));
                }
            }
            for (i, &pos) in positions.iter().enumerate() {
                target[pos] = first.as_ref().map_or(Value::Null, |r| r[i].clone());
            }
        }
        Ok(())
    }

    fn exec_view_update(&mut self, upd: &Update, params: &Params) -> Result<usize> {
        let (cols, rows) = self
            .try_view(&upd.table, None, params)?
            .ok_or_else(|| Error::Error(format!("no such view: {}", upd.table)))?;
        if self
            .triggers_for(&upd.table, TrigEvent::Update, TriggerTiming::InsteadOf)?
            .is_empty()
        {
            return Err(Error::Error(format!(
                "cannot modify {} — it is a view",
                upd.table
            )));
        }
        let mut changed: Vec<String> = upd.assignments.iter().map(|(c, _)| c.clone()).collect();
        for (rcols, _) in &upd.row_assignments {
            changed.extend(rcols.iter().cloned());
        }
        let mut affected = 0;
        for row in rows {
            let old = row.values.clone();
            if let Some(p) = &upd.where_clause {
                let ctx = row_ctx(&old, &cols, None, params).with_subqueries(self);
                if eval::truth(&eval::eval(p, &ctx)?) != Some(true) {
                    continue;
                }
            }
            let mut new = old.clone();
            for (col, expr) in &upd.assignments {
                let pos = cols
                    .iter()
                    .position(|c| c.name.eq_ignore_ascii_case(col))
                    .ok_or_else(|| Error::Error(format!("no such column: {col}")))?;
                // Simultaneous assignment: evaluate against the original row.
                let ctx = row_ctx(&old, &cols, None, params).with_subqueries(self);
                new[pos] = eval::eval(expr, &ctx)?;
            }
            if !upd.row_assignments.is_empty() {
                let ctx = row_ctx(&old, &cols, None, params).with_subqueries(self);
                self.apply_row_subquery_assignments(
                    &upd.row_assignments,
                    &cols,
                    None,
                    &ctx,
                    &mut new,
                )?;
            }
            self.fire_triggers(
                &upd.table,
                TrigEvent::Update,
                TriggerTiming::InsteadOf,
                &cols,
                Some((&old, 0)),
                Some((&new, 0)),
                params,
                Some(&changed),
            )?;
            if self.raise_ignore.replace(false) {
                continue;
            }
            affected += 1;
        }
        Ok(affected)
    }

    fn run_trigger_bodies(&mut self, trigs: &[CreateTrigger], params: &Params) -> Result<()> {
        for trig in trigs {
            if let Some(when) = &trig.when {
                let fires = {
                    let ctx = EvalCtx::rowless(params).with_subqueries(self);
                    eval::truth(&eval::eval(when, &ctx)?) == Some(true)
                };
                if !fires {
                    continue;
                }
            }
            for stmt in &trig.body {
                match stmt {
                    Statement::Insert(ins) => {
                        self.exec_insert(ins, params)?;
                    }
                    Statement::Update(u) => {
                        self.exec_update(u, params)?;
                    }
                    Statement::Delete(d) => {
                        self.exec_delete(d, params)?;
                    }
                    // A `SELECT` in a trigger body is side-effect free *except* for
                    // a `RAISE(…)`, which aborts or ignores the firing operation.
                    Statement::Select(sel) => {
                        self.run_trigger_select(sel, params)?;
                        // `RAISE(IGNORE)` abandons the row: stop running the rest of
                        // this (and later) trigger program(s).
                        if self.raise_ignore.get() {
                            return Ok(());
                        }
                    }
                    _ => return Err(Error::Unsupported("statement type in trigger body")),
                }
            }
        }
        Ok(())
    }

    /// Evaluate a trigger-body `SELECT` for a `RAISE(…)` call. A bare
    /// `SELECT RAISE(…)` (optionally wrapped in a single `CASE`) is the standard
    /// form; we evaluate each projected expression so any `RAISE` that the row
    /// reaches takes effect. `RAISE(ABORT|FAIL|ROLLBACK, msg)` raises a constraint
    /// error (arming the statement-atomicity flags); `RAISE(IGNORE)` sets
    /// `raise_ignore` so the firing row operation is silently skipped.
    fn run_trigger_select(&self, sel: &Select, params: &Params) -> Result<()> {
        // A bare `SELECT RAISE(…) [WHERE cond]` (no FROM) reaches the RAISE only
        // for the single row that passes WHERE — `SELECT RAISE(IGNORE) WHERE
        // NEW.a<0` must NOT raise when the condition is false. Evaluate the WHERE
        // in the trigger's row context (NEW/OLD via the subquery runner) and skip
        // the projection when it is not true. (A trigger-body SELECT with a FROM
        // is not a RAISE form handled here; leave it to the projection scan.)
        if sel.from.is_none() {
            if let Some(w) = &sel.where_clause {
                let ctx = EvalCtx::rowless(params).with_subqueries(self);
                if eval::truth(&eval::eval(w, &ctx)?) != Some(true) {
                    return Ok(());
                }
            }
        }
        for col in &sel.columns {
            if let ResultColumn::Expr { expr, .. } = col {
                self.eval_raise_expr(expr, params)?;
                if self.raise_ignore.get() {
                    return Ok(());
                }
            }
        }
        Ok(())
    }

    /// Evaluate `expr` looking for a `RAISE(…)` that the row reaches: a direct
    /// `RAISE(…)` call, or one selected by a `CASE` branch. Other expressions are
    /// side-effect free here and are skipped.
    fn eval_raise_expr(&self, expr: &Expr, params: &Params) -> Result<()> {
        match expr {
            Expr::Function { name, args, .. } if name.eq_ignore_ascii_case("raise") => {
                self.fire_raise(args, params)
            }
            Expr::Paren(inner) => self.eval_raise_expr(inner, params),
            Expr::Case {
                operand,
                when_then,
                else_result,
            } => {
                let ctx = EvalCtx::rowless(params).with_subqueries(self);
                let base = match operand {
                    Some(op) => Some(eval::eval(op, &ctx)?),
                    None => None,
                };
                for (when, then) in when_then {
                    let hit = match &base {
                        // `CASE x WHEN v …`: the branch fires when x == v.
                        Some(b) => {
                            let w = eval::eval(when, &ctx)?;
                            crate::value::cmp_values(b, &w) == core::cmp::Ordering::Equal
                        }
                        // `CASE WHEN cond …`: the branch fires when cond is true.
                        None => eval::truth(&eval::eval(when, &ctx)?) == Some(true),
                    };
                    if hit {
                        return self.eval_raise_expr(then, params);
                    }
                }
                if let Some(e) = else_result {
                    return self.eval_raise_expr(e, params);
                }
                Ok(())
            }
            _ => Ok(()),
        }
    }

    /// Apply a parsed `RAISE(action[, msg])`. `action` is the lower-cased keyword
    /// stored as the first argument; `msg` (when present) is the second.
    fn fire_raise(&self, args: &[Expr], params: &Params) -> Result<()> {
        let action = match args.first() {
            Some(Expr::Literal(Literal::Str(s))) => s.as_str(),
            _ => return Err(Error::Error("malformed RAISE()".into())),
        };
        if action == "ignore" {
            self.raise_ignore.set(true);
            return Ok(());
        }
        let ctx = EvalCtx::rowless(params).with_subqueries(self);
        let msg = match args.get(1) {
            Some(e) => match eval::eval(e, &ctx)? {
                Value::Null => String::new(),
                Value::Text(s) => s,
                Value::Integer(i) => {
                    let mut s = String::new();
                    let _ = core::fmt::write(&mut s, format_args!("{i}"));
                    s
                }
                Value::Real(r) => eval::format_real(r),
                Value::Blob(_) => String::new(),
            },
            None => String::new(),
        };
        match action {
            "fail" => self.stmt_keep_partial.set(true),
            "rollback" => self.stmt_rollback_tx.set(true),
            _ => {} // "abort" — the default statement rollback
        }
        Err(Error::Constraint(msg))
    }

    /// The AUTOINCREMENT high-water mark stored for `table` in `sqlite_sequence`,
    /// or `None` if that catalog or row is absent.
    fn sequence_value(&self, table: &str) -> Result<Option<i64>> {
        if self.schema.table("sqlite_sequence").is_none() {
            return Ok(None);
        }
        let meta = self.table_meta("sqlite_sequence", None)?;
        for (_, vals) in self.scan_table(&meta)? {
            if matches!(&vals[0], Value::Text(t) if t == table) {
                return Ok(Some(eval::to_i64(&vals[1])));
            }
        }
        Ok(None)
    }

    /// Persist the AUTOINCREMENT high-water mark `seq` for `table` into
    /// `sqlite_sequence` — updating the existing row in place (same rowid) or
    /// inserting a new one — like SQLite. A no-op if the catalog is absent.
    fn set_sequence(&mut self, table: &str, seq: i64) -> Result<()> {
        let Some(seq_obj) = self.schema.table("sqlite_sequence") else {
            return Ok(());
        };
        let root = seq_obj.rootpage;
        let meta = self.table_meta("sqlite_sequence", None)?;
        let existing: Option<i64> = self
            .scan_table(&meta)?
            .into_iter()
            .find(|(_, v)| matches!(&v[0], Value::Text(t) if t == table))
            .map(|(rid, _)| rid);
        let rec = encode_record(&[Value::Text(table.into()), Value::Integer(seq)]);
        let rid = match existing {
            Some(rid) => {
                delete_table(self.backend.writer()?, root, rid)?;
                rid
            }
            None => self.next_rowid(root)?,
        };
        insert_table(self.backend.writer()?, root, rid, &rec)?;
        Ok(())
    }

    fn exec_insert(&mut self, ins: &Insert, params: &Params) -> Result<usize> {
        reject_schema_write(&ins.table)?;
        // A virtual table routes INSERT to its module's `update` (xUpdate); only
        // the `VALUES`/`SELECT` source needs materializing first.
        if self.is_virtual_table(&ins.table) {
            let rows: Vec<Vec<Expr>> = match &ins.source {
                InsertSource::Values(rows) => rows.clone(),
                InsertSource::DefaultValues => alloc::vec![Vec::new()],
                InsertSource::Select(sel) => self
                    .run_select(sel, params)?
                    .rows
                    .into_iter()
                    .map(|row| row.into_iter().map(value_to_literal_expr).collect())
                    .collect(),
            };
            return self.exec_vtab_insert(ins, &rows, params);
        }
        // `INSERT … SELECT` is evaluated to a snapshot of value rows first (so
        // `INSERT INTO t SELECT … FROM t` reads the pre-insert state), then each
        // row flows through the normal VALUES path as literal expressions.
        // A multi-row `INSERT … VALUES (…),(…)` must have rows of equal arity.
        // SQLite rejects a mismatch up front ("all VALUES must have the same
        // number of terms"); validate before any row is written so a short row
        // never half-completes the insert.
        if let InsertSource::Values(rows) = &ins.source {
            if let Some(first) = rows.first() {
                if rows.iter().any(|r| r.len() != first.len()) {
                    return Err(Error::Error(
                        "all VALUES must have the same number of terms".into(),
                    ));
                }
            }
        }
        let (rows, is_default_values) = match &ins.source {
            InsertSource::Values(rows) => (rows.clone(), false),
            InsertSource::DefaultValues => (alloc::vec![Vec::new()], true),
            InsertSource::Select(sel) => {
                let result = self.run_select(sel, params)?;
                let rows = result
                    .rows
                    .into_iter()
                    .map(|row| row.into_iter().map(value_to_literal_expr).collect())
                    .collect();
                (rows, false)
            }
        };
        if self.is_view(&ins.table) {
            return self.exec_view_insert(ins, &rows, params);
        }
        let meta = self.table_meta(&ins.table, None)?;
        if meta.without_rowid {
            if !ins.upsert.is_empty() || !ins.returning.is_empty() {
                return Err(Error::Unsupported(
                    "UPSERT / RETURNING on WITHOUT ROWID tables",
                ));
            }
            return self.exec_insert_without_rowid(ins, &meta, &rows, params);
        }
        let n_cols = meta.columns.len();

        // Map the provided column list (or all columns) to table positions.
        let target: Vec<usize> = if ins.columns.is_empty() {
            // A bare `INSERT … VALUES`/`SELECT` (no column list) targets the
            // NON-GENERATED columns, in order — SQLite excludes generated columns
            // from the implicit list (they are always computed), so the value
            // count must match the non-generated columns and an `INSERT INTO t
            // VALUES(…)` works on a table that has generated columns.
            (0..n_cols).filter(|&i| !meta.is_generated(i)).collect()
        } else {
            let mut t = Vec::new();
            for name in &ins.columns {
                let pos = meta
                    .columns
                    .iter()
                    .position(|c| c.name.eq_ignore_ascii_case(name))
                    .ok_or_else(|| Error::Error(format!("no such column: {name}")))?;
                t.push(pos);
            }
            t
        };

        let indexes = self.indexes_of(&ins.table)?;
        let mut next_auto = self.next_rowid(meta.root)?;
        // AUTOINCREMENT never reuses a rowid at or below the persisted high-water
        // mark, so seed the counter past it (a deleted maximum is not recycled).
        if meta.autoincrement {
            if let Some(seq) = self.sequence_value(&ins.table)? {
                next_auto = next_auto.max(seq + 1);
            }
        }
        let mut affected = 0;
        let mut replaced = false;
        for row_exprs in &rows {
            // Every supplied row must match the target column count (DEFAULT
            // VALUES is the one exception — it supplies an empty row meaning
            // "all defaults").
            if !is_default_values && row_exprs.len() != target.len() {
                return Err(Error::Error("INSERT column/value count mismatch".into()));
            }
            // Start every column at its DEFAULT (or NULL), then apply provided.
            // Subqueries are attached so INSERT … VALUES can use scalar subqueries
            // and trigger bodies can read NEW/OLD via the outer scope.
            let ctx = EvalCtx::rowless(params).with_subqueries(self);
            let mut values: Vec<Value> = meta
                .defaults
                .iter()
                .map(|d| match d {
                    Some(e) => eval::eval(e, &ctx),
                    None => Ok(Value::Null),
                })
                .collect::<Result<_>>()?;
            for (i, e) in row_exprs.iter().enumerate() {
                if meta.is_generated(target[i]) {
                    return Err(Error::Error(format!(
                        "cannot INSERT into generated column \"{}\"",
                        meta.columns[target[i]].name
                    )));
                }
                values[target[i]] = eval::eval(e, &ctx)?;
            }
            apply_column_affinity(&meta, &mut values);
            self.materialize_generated(&meta, &mut values, params)?;

            // Determine the rowid (explicit INTEGER PRIMARY KEY value or auto).
            let rowid = match meta.ipk {
                Some(ipk) if !matches!(values[ipk], Value::Null) => {
                    // An INTEGER PRIMARY KEY *is* the rowid, so the supplied value
                    // must be an integer. Column affinity has already coerced an
                    // integer-valued real or numeric text (2.0, '5', '5.0') to
                    // Integer; anything still non-integer (1.5, 'x', a blob) is a
                    // datatype mismatch in SQLite, not a silent `to_i64` coercion.
                    let r = match &values[ipk] {
                        Value::Integer(i) => *i,
                        _ => return Err(Error::Error("datatype mismatch".into())),
                    };
                    next_auto = next_auto.max(r + 1);
                    r
                }
                _ => {
                    let r = next_auto;
                    next_auto += 1;
                    r
                }
            };
            // Capture column values (with the IPK = rowid) for index keys, then
            // NULL the IPK column in the stored record (it aliases the rowid).
            if let Some(ipk) = meta.ipk {
                values[ipk] = Value::Integer(rowid);
            }
            // NOT NULL / STRICT-type / CHECK constraints. `INSERT OR IGNORE`
            // skips a row that violates any of these (rather than failing the
            // statement); every other conflict policy lets the error propagate.
            {
                // NOT NULL honors the column's (or statement's) ON CONFLICT action;
                // a skipped row (IGNORE) drops out here, a REPLACE substitutes the
                // column default into `values`.
                if !self.resolve_not_null(
                    &meta,
                    &mut values,
                    ins.on_conflict,
                    ins.on_conflict_explicit,
                    params,
                )? {
                    continue;
                }
                let r = self
                    .check_strict_types(&meta, &values)
                    .and_then(|()| self.check_constraints(&meta, &values, Some(rowid), params));
                match r {
                    Ok(()) => {}
                    Err(Error::Constraint(_)) if ins.on_conflict == OnConflict::Ignore => continue,
                    Err(Error::Constraint(m)) => {
                        return Err(self.conflict_error(ins.on_conflict, &m))
                    }
                    Err(e) => return Err(e),
                }
            }
            self.check_fk_child(&ins.table, &meta, &values)?;

            // Resolve UNIQUE / PRIMARY KEY (incl. rowid) conflicts.
            let (conflicts, constraint_oc) =
                self.find_conflicts(&ins.table, &meta, rowid, &values, None, params)?;
            // A statement-level `OR <action>` overrides the constraint's declared
            // `ON CONFLICT <action>`; a plain `INSERT` uses the constraint's action.
            let effective_oc = if ins.on_conflict_explicit {
                ins.on_conflict
            } else {
                constraint_oc
            };
            if !conflicts.is_empty() {
                // An `ON CONFLICT … DO …` upsert clause intercepts the conflict,
                // but only when the conflict is on the index it targets (a bare
                // `ON CONFLICT` with no target matches any unique conflict). A
                // conflict on a *different* index is a hard error, exactly as in
                // SQLite.
                let mut matched = None;
                for up in &ins.upsert {
                    if self.upsert_target_matches(&meta, up, &conflicts, &values, rowid, params)? {
                        matched = Some(up);
                        break;
                    }
                }
                if let Some(up) = matched {
                    match &up.action {
                        UpsertAction::Nothing => continue, // skip the conflicting row
                        UpsertAction::Update {
                            assignments,
                            where_clause,
                        } => {
                            if self.upsert_do_update(
                                &ins.table,
                                &meta,
                                conflicts[0],
                                &values,
                                assignments,
                                where_clause.as_ref(),
                                &ins.returning,
                                params,
                            )? {
                                affected += 1;
                                replaced = true; // index entries changed; rebuild
                            }
                            continue;
                        }
                    }
                }
                match effective_oc {
                    oc @ (OnConflict::Abort | OnConflict::Fail | OnConflict::Rollback) => {
                        let m = self.unique_violation_message(
                            &ins.table, &meta, rowid, &values, None, params,
                        );
                        return Err(self.conflict_error(oc, &m));
                    }
                    OnConflict::Ignore => continue, // skip this row
                    OnConflict::Replace => {
                        // Deleting the conflicting rows to make room fires their FK
                        // `ON DELETE` actions (CASCADE / SET NULL / …) via
                        // `delete_row_cascade`, exactly like sqlite — but NOT DELETE
                        // triggers (sqlite gates those on `recursive_triggers`, off
                        // by default, and `delete_row_cascade` fires none).
                        for cr in conflicts {
                            self.delete_row_cascade(&ins.table, &meta, cr, params)?;
                        }
                        replaced = true;
                    }
                }
            }

            let index_values = values.clone();
            self.fire_triggers(
                &ins.table,
                TrigEvent::Insert,
                TriggerTiming::Before,
                &meta.columns,
                None,
                Some((&index_values, rowid)),
                params,
                None,
            )?;
            // A `BEFORE INSERT` trigger's `RAISE(IGNORE)` abandons just this row.
            if self.raise_ignore.replace(false) {
                continue;
            }
            let record = self.encode_table_record(&meta, &index_values);
            insert_table(self.backend.writer()?, meta.root, rowid, &record)?;
            // `last_insert_rowid()` tracks the most recent insert (a later insert
            // from an AFTER trigger overwrites this, matching SQLite).
            self.last_insert_rowid.set(rowid);
            for idx in &indexes {
                if !self.row_in_index(idx, &meta, &index_values, Some(rowid), params)? {
                    continue; // partial index excludes this row
                }
                let key = self.index_key_bytes(idx, &meta, &index_values, rowid, params)?;
                insert_index(self.backend.writer()?, idx.root, &key, &idx.collations)?;
            }
            self.fire_triggers(
                &ins.table,
                TrigEvent::Insert,
                TriggerTiming::After,
                &meta.columns,
                None,
                Some((&index_values, rowid)),
                params,
                None,
            )?;
            if !ins.returning.is_empty() {
                self.collect_returning(&ins.returning, &meta, &index_values, Some(rowid), params)?;
            }
            affected += 1;
        }
        // Persist the AUTOINCREMENT high-water mark: `next_auto - 1` is the largest
        // rowid assigned or seen this statement. Only advance `sqlite_sequence`
        // (never lower it), matching SQLite.
        if meta.autoincrement && affected > 0 {
            let high = next_auto - 1;
            if high > self.sequence_value(&ins.table)?.unwrap_or(i64::MIN) {
                self.set_sequence(&ins.table, high)?;
            }
        }
        // REPLACE removed rows whose index entries were maintained incrementally;
        // rebuild from the final table state to be safe.
        if replaced {
            self.rebuild_indexes(&meta, &indexes)?;
        }
        Ok(affected)
    }

    /// Apply an `ON CONFLICT … DO UPDATE` action to the existing conflicting
    /// row `existing_rowid`. `proposed` is the row the `INSERT` would have added,
    /// exposed to the `SET`/`WHERE` expressions as the `excluded` pseudo-table.
    /// Returns whether a row was actually updated (the optional `WHERE` can veto).
    #[allow(clippy::too_many_arguments)]
    fn upsert_do_update(
        &mut self,
        table: &str,
        meta: &TableMeta,
        existing_rowid: i64,
        proposed: &[Value],
        assignments: &[(String, Expr)],
        where_clause: Option<&Expr>,
        returning: &[ResultColumn],
        params: &Params,
    ) -> Result<bool> {
        let Some(old_row) = self.read_row(meta, existing_rowid)? else {
            return Ok(false);
        };
        let changed: Vec<String> = assignments.iter().map(|(c, _)| c.clone()).collect();
        // Column scope for the SET/WHERE expressions: the target table's columns,
        // then the same columns again under the `excluded` table label.
        let mut cols: Vec<ColumnInfo> = meta.columns.clone();
        cols.extend(meta.columns.iter().map(|c| ColumnInfo {
            name: c.name.clone(),
            table: String::from("excluded"),
            affinity: c.affinity,
            collation: c.collation,
        }));
        // Evaluate the DO UPDATE WHERE and SET right-hand sides against the
        // combined (existing row + excluded) scope, then drop the borrow.
        let mut values = old_row.clone();
        {
            let mut combined = old_row.clone();
            combined.extend_from_slice(proposed);
            let ctx = EvalCtx {
                row: &combined,
                columns: &cols,
                rowid: Some(existing_rowid),
                params,
                anon_counter: core::cell::Cell::new(0),
                subqueries: None,
            }
            .with_subqueries(self);
            if let Some(w) = where_clause {
                if eval::truth(&eval::eval(w, &ctx)?) != Some(true) {
                    return Ok(false);
                }
            }
            for (col, e) in assignments {
                let pos = meta
                    .columns
                    .iter()
                    .position(|c| c.name.eq_ignore_ascii_case(col))
                    .ok_or_else(|| Error::Error(format!("no such column: {col}")))?;
                if meta.is_generated(pos) {
                    return Err(Error::Error(format!(
                        "cannot UPDATE generated column \"{col}\""
                    )));
                }
                values[pos] = eval::eval(e, &ctx)?;
            }
        }
        apply_column_affinity(meta, &mut values);
        self.materialize_generated(meta, &mut values, params)?;
        // An UPDATE of the INTEGER PRIMARY KEY (the rowid) must leave it an
        // integer: NULL or a non-integer value (after affinity) is a datatype
        // mismatch in SQLite — checked before NOT NULL, which would otherwise
        // mis-report a `SET ipk = NULL`.
        if let Some(ipk) = meta.ipk {
            if !matches!(values[ipk], Value::Integer(_)) {
                return Err(Error::Error("datatype mismatch".into()));
            }
        }
        check_not_null(meta, &values)?;
        self.check_strict_types(meta, &values)?;
        self.check_constraints(meta, &values, Some(existing_rowid), params)?;
        self.check_fk_child(table, meta, &values)?;
        if self.foreign_keys {
            self.enforce_parent_change(table, &old_row, Some(&values), params)?;
        }
        let new_rowid = match meta.ipk {
            Some(ipk) => eval::to_i64(&values[ipk]),
            None => existing_rowid,
        };
        self.fire_triggers(
            table,
            TrigEvent::Update,
            TriggerTiming::Before,
            &meta.columns,
            Some((&old_row, existing_rowid)),
            Some((&values, new_rowid)),
            params,
            Some(&changed),
        )?;
        if !self
            .find_conflicts(
                table,
                meta,
                new_rowid,
                &values,
                Some(existing_rowid),
                params,
            )?
            .0
            .is_empty()
        {
            return Err(Error::Constraint(self.unique_violation_message(
                table,
                meta,
                new_rowid,
                &values,
                Some(existing_rowid),
                params,
            )));
        }
        let new_full = values.clone();
        let record = self.encode_table_record(meta, &new_full);
        delete_table(self.backend.writer()?, meta.root, existing_rowid)?;
        insert_table(self.backend.writer()?, meta.root, new_rowid, &record)?;
        self.fire_triggers(
            table,
            TrigEvent::Update,
            TriggerTiming::After,
            &meta.columns,
            Some((&old_row, existing_rowid)),
            Some((&new_full, new_rowid)),
            params,
            Some(&changed),
        )?;
        if !returning.is_empty() {
            self.collect_returning(returning, meta, &new_full, Some(new_rowid), params)?;
        }
        Ok(true)
    }

    /// Project a `RETURNING` row from `values` (a full table row) and stash it in
    /// [`returning_rows`](Self::returning_rows) for `execute_returning` to drain.
    fn collect_returning(
        &self,
        returning: &[ResultColumn],
        meta: &TableMeta,
        values: &[Value],
        rowid: Option<i64>,
        params: &Params,
    ) -> Result<()> {
        let ctx = row_ctx(values, &meta.columns, rowid, params).with_subqueries(self);
        let mut out = Vec::new();
        for col in returning {
            project_column(col, &meta.columns, &ctx, &mut out)?;
        }
        self.returning_rows.borrow_mut().push(out);
        Ok(())
    }

    /// Load `ANALYZE` statistics, mapping each index name to its parsed `stat`
    /// integers (`[nRow, avgEq1, avgEq2, …]`). Empty when the database has not
    /// been analyzed. Used by the cost-based index chooser.
    fn stat1_map(&self) -> alloc::collections::BTreeMap<String, Vec<u64>> {
        let mut map = alloc::collections::BTreeMap::new();
        if self.schema.table("sqlite_stat1").is_none() {
            return map;
        }
        let Ok(meta) = self.table_meta("sqlite_stat1", None) else {
            return map;
        };
        let Ok(rows) = self.scan_table(&meta) else {
            return map;
        };
        for (_, vals) in rows {
            if let (Some(Value::Text(idx)), Some(Value::Text(stat))) = (vals.get(1), vals.get(2)) {
                let nums: Vec<u64> = stat
                    .split_whitespace()
                    .filter_map(|t| t.parse().ok())
                    .collect();
                if !nums.is_empty() {
                    map.insert(idx.clone(), nums);
                }
            }
        }
        map
    }

    /// Rowids of existing rows that conflict with a candidate row on the rowid
    /// or any UNIQUE/PRIMARY KEY column set (NULLs are considered distinct).
    fn find_conflicts(
        &self,
        table: &str,
        meta: &TableMeta,
        rowid: i64,
        values: &[Value],
        exclude: Option<i64>,
        params: &Params,
    ) -> Result<(Vec<i64>, OnConflict)> {
        // Unique standalone indexes (named `CREATE UNIQUE INDEX`, incl. partial
        // and expression indexes) are not represented in `meta.unique` — those
        // sets come only from inline CREATE TABLE constraints (whose automatic
        // indexes we therefore skip here). Precompute each such index's key
        // values for the new row; a NULL key term or an excluding partial
        // predicate means the new row can't collide on that index.
        let uniq_idx: Vec<(IndexMeta, Vec<Value>)> = self
            .indexes_of(table)?
            .into_iter()
            .filter(|i| i.unique && autoindex_number(&i.name, table).is_none())
            .filter_map(|i| {
                if !self
                    .row_in_index(&i, meta, values, Some(rowid), params)
                    .unwrap_or(false)
                {
                    return None;
                }
                let key = self
                    .index_key_values(&i, meta, values, rowid, params)
                    .ok()?;
                if key.iter().any(|v| matches!(v, Value::Null)) {
                    return None; // a NULL makes the key distinct
                }
                Some((i, key))
            })
            .collect();

        let mut out = Vec::new();
        // The declared `ON CONFLICT` action of the first inline UNIQUE/PRIMARY KEY
        // set the new row collides on (used when the statement has no `OR <action>`).
        let mut action: Option<OnConflict> = None;
        for (er, ev) in self.scan_table(meta)? {
            if Some(er) == exclude {
                continue;
            }
            if er == rowid {
                out.push(er);
                continue;
            }
            let mut conflicted = false;
            for (set, set_oc) in &meta.unique {
                let new_tuple: Vec<&Value> = set.iter().map(|&i| &values[i]).collect();
                if new_tuple.iter().any(|v| matches!(v, Value::Null)) {
                    continue; // a NULL makes the key distinct
                }
                let conflict = set.iter().zip(&new_tuple).all(|(&i, nv)| {
                    crate::value::cmp_values_coll(&ev[i], nv, meta.columns[i].collation)
                        == core::cmp::Ordering::Equal
                });
                if conflict {
                    out.push(er);
                    action.get_or_insert(*set_oc);
                    conflicted = true;
                    break;
                }
            }
            if conflicted {
                continue;
            }
            // Then the unique standalone/partial/expression indexes.
            for (idx, new_key) in &uniq_idx {
                if !self.row_in_index(idx, meta, &ev, Some(er), params)? {
                    continue; // existing row not in this partial index
                }
                let ex_key = self.index_key_values(idx, meta, &ev, er, params)?;
                let conflict = ex_key.len() == new_key.len()
                    && ex_key
                        .iter()
                        .zip(new_key)
                        .zip(&idx.collations)
                        .all(|((a, b), &coll)| {
                            crate::value::cmp_values_coll(a, b, coll) == core::cmp::Ordering::Equal
                        });
                if conflict {
                    out.push(er);
                    break;
                }
            }
        }
        Ok((out, action.unwrap_or(OnConflict::Abort)))
    }

    /// SQLite's UNIQUE-violation message for the *first* unique constraint the new
    /// row collides on: `UNIQUE constraint failed: t.a[, t.b]` (or `: index 'name'`
    /// for an expression index). Checks the rowid/INTEGER PRIMARY KEY, then inline
    /// `UNIQUE`/`PRIMARY KEY` sets, then standalone unique indexes — falling back to
    /// the bare message if none can be pinpointed. Runs only on the (cold) error
    /// path, so the extra table scans are immaterial.
    fn unique_violation_message(
        &self,
        table: &str,
        meta: &TableMeta,
        rowid: i64,
        values: &[Value],
        exclude: Option<i64>,
        params: &Params,
    ) -> String {
        let bare = String::from("UNIQUE constraint failed");
        let qualify = |cols: &[usize]| {
            cols.iter()
                .map(|&i| alloc::format!("{}.{}", meta.columns[i].table, meta.columns[i].name))
                .collect::<Vec<_>>()
                .join(", ")
        };
        let rows = match self.scan_table(meta) {
            Ok(r) => r,
            Err(_) => return bare,
        };
        // A rowid / INTEGER PRIMARY KEY collision.
        if let Some(ipk) = meta.ipk {
            if rows
                .iter()
                .any(|(er, _)| *er == rowid && Some(*er) != exclude)
            {
                return alloc::format!("UNIQUE constraint failed: {}", qualify(&[ipk]));
            }
        }
        // Inline UNIQUE / PRIMARY KEY constraint sets, in declaration order.
        for (set, _) in &meta.unique {
            if set.iter().any(|&i| matches!(values[i], Value::Null)) {
                continue;
            }
            let hit = rows.iter().any(|(er, ev)| {
                Some(*er) != exclude
                    && set.iter().all(|&i| {
                        crate::value::cmp_values_coll(&ev[i], &values[i], meta.columns[i].collation)
                            == core::cmp::Ordering::Equal
                    })
            });
            if hit {
                return alloc::format!("UNIQUE constraint failed: {}", qualify(set));
            }
        }
        // Standalone unique indexes (a `CREATE UNIQUE INDEX`; the inline sets'
        // automatic indexes are already covered above and skipped here).
        if let Ok(idxs) = self.indexes_of(table) {
            for idx in idxs
                .iter()
                .filter(|i| i.unique && autoindex_number(&i.name, table).is_none())
            {
                if !self
                    .row_in_index(idx, meta, values, Some(rowid), params)
                    .unwrap_or(false)
                {
                    continue;
                }
                let Ok(new_key) = self.index_key_values(idx, meta, values, rowid, params) else {
                    continue;
                };
                if new_key.iter().any(|v| matches!(v, Value::Null)) {
                    continue;
                }
                let hit = rows.iter().any(|(er, ev)| {
                    Some(*er) != exclude
                        && self
                            .row_in_index(idx, meta, ev, Some(*er), params)
                            .unwrap_or(false)
                        && self
                            .index_key_values(idx, meta, ev, *er, params)
                            .map(|ek| {
                                ek.iter().zip(&new_key).enumerate().all(|(k, (a, b))| {
                                    crate::value::cmp_values_coll(a, b, idx.collations[k])
                                        == core::cmp::Ordering::Equal
                                })
                            })
                            .unwrap_or(false)
                });
                if hit {
                    let detail = if idx.key_exprs.is_some() {
                        alloc::format!("index '{}'", idx.name)
                    } else {
                        qualify(&idx.cols)
                    };
                    return alloc::format!("UNIQUE constraint failed: {detail}");
                }
            }
        }
        bare
    }

    /// Does an `ON CONFLICT (target…) DO …` upsert clause apply to the conflict
    /// that just occurred? A bare `ON CONFLICT` (no target) absorbs any unique
    /// conflict. A targeted clause applies only when the proposed row actually
    /// collides with a conflicting row on the **target** columns — a conflict on
    /// a different unique index is a hard error, exactly as SQLite behaves.
    #[allow(clippy::too_many_arguments)]
    fn upsert_target_matches(
        &self,
        meta: &TableMeta,
        up: &Upsert,
        conflicts: &[i64],
        values: &[Value],
        rowid: i64,
        params: &Params,
    ) -> Result<bool> {
        if up.target.is_empty() {
            return Ok(true);
        }
        // Resolve the target column names to column indices.
        let target_cols: Vec<usize> = up
            .target
            .iter()
            .map(|name| {
                meta.columns
                    .iter()
                    .position(|c| c.name.eq_ignore_ascii_case(name))
                    .ok_or_else(|| Error::Error(format!("no such column: {name}")))
            })
            .collect::<Result<_>>()?;
        // The target names the rowid / INTEGER PRIMARY KEY: it matches when a
        // conflicting row shares the candidate rowid.
        if let Some(ipk) = meta.ipk {
            if target_cols == [ipk] {
                return Ok(conflicts.contains(&rowid));
            }
        }
        // The conflict matches the target only if the proposed row equals some
        // conflicting row on every target column (NULLs never match — a NULL key
        // is distinct, so it could not have produced this conflict). The target
        // must also actually be a UNIQUE/PK constraint, but if the rows collide on
        // those columns there necessarily is one.
        for &er in conflicts {
            let Some(existing) = self.read_row(meta, er)? else {
                continue;
            };
            let collide = target_cols.iter().all(|&c| {
                !matches!(values[c], Value::Null)
                    && crate::value::cmp_values_coll(
                        &existing[c],
                        &values[c],
                        meta.columns[c].collation,
                    ) == core::cmp::Ordering::Equal
            });
            if collide {
                return Ok(true);
            }
        }
        let _ = params;
        Ok(false)
    }

    /// The key values for a row under `idx` (excluding the trailing rowid): the
    /// indexed column values, or the evaluated key expressions for an expression
    /// index. Used for uniqueness comparison (collation applied by the caller).
    fn index_key_values(
        &self,
        idx: &IndexMeta,
        meta: &TableMeta,
        values: &[Value],
        rowid: i64,
        params: &Params,
    ) -> Result<Vec<Value>> {
        match &idx.key_exprs {
            None => Ok(idx.cols.iter().map(|&c| values[c].clone()).collect()),
            Some(exprs) => {
                let ctx = row_ctx(values, &meta.columns, Some(rowid), params).with_subqueries(self);
                exprs.iter().map(|e| eval::eval(e, &ctx)).collect()
            }
        }
    }

    /// Whether rows `a` and `b` collide on any unique *standalone* index of
    /// `table` (plain or partial — expression indexes are rejected on WITHOUT
    /// ROWID tables). Complements [`unique_match`], which covers only the inline
    /// PRIMARY KEY / UNIQUE constraints; used by the WITHOUT ROWID write paths.
    fn wr_index_collision(
        &self,
        table: &str,
        meta: &TableMeta,
        a: &[Value],
        b: &[Value],
        params: &Params,
    ) -> Result<bool> {
        for idx in self
            .indexes_of(table)?
            .iter()
            .filter(|i| i.unique && autoindex_number(&i.name, table).is_none())
        {
            if !self.row_in_index(idx, meta, a, None, params)?
                || !self.row_in_index(idx, meta, b, None, params)?
            {
                continue;
            }
            let ka = self.index_key_values(idx, meta, a, 0, params)?;
            if ka.iter().any(|v| matches!(v, Value::Null)) {
                continue; // a NULL makes the key distinct
            }
            let kb = self.index_key_values(idx, meta, b, 0, params)?;
            let eq = ka.len() == kb.len()
                && ka.iter().zip(&kb).zip(&idx.collations).all(|((x, y), &c)| {
                    crate::value::cmp_values_coll(x, y, c) == core::cmp::Ordering::Equal
                });
            if eq {
                return Ok(true);
            }
        }
        Ok(false)
    }

    fn exec_delete(&mut self, del: &Delete, params: &Params) -> Result<usize> {
        // A leading `WITH` makes its CTEs visible to the WHERE subqueries; push
        // them for the duration of the statement, then restore the scope.
        if del.ctes.is_empty() {
            return self.exec_delete_inner(del, params);
        }
        let base = self.cte_env.borrow().len();
        let pushed = self.push_ctes(&del.ctes, params, None);
        let result = pushed.and_then(|()| self.exec_delete_inner(del, params));
        self.cte_env.borrow_mut().truncate(base);
        result
    }

    fn exec_delete_inner(&mut self, del: &Delete, params: &Params) -> Result<usize> {
        reject_schema_write(&del.table)?;
        if self.is_virtual_table(&del.table) {
            return self.exec_vtab_delete(del, params);
        }
        if self.is_view(&del.table) {
            return self.exec_view_delete(del, params);
        }
        let meta = self.table_meta(&del.table, None)?;
        if meta.without_rowid {
            if !del.returning.is_empty() {
                return Err(Error::Unsupported("RETURNING on WITHOUT ROWID tables"));
            }
            return self.exec_delete_without_rowid(del, &meta, params);
        }
        let indexes = self.indexes_of(&del.table)?;
        let mut victims = self.matching_rowids(&meta, del.where_clause.as_ref(), params)?;
        if !del.order_by.is_empty() || del.limit.is_some() || del.offset.is_some() {
            victims = self.order_limit_rowids(
                &meta,
                victims,
                &del.order_by,
                del.limit.as_ref(),
                del.offset.as_ref(),
                params,
            )?;
        }
        let mut deleted = 0;
        for rowid in &victims {
            let old = self.read_row(&meta, *rowid)?;
            if let Some(old) = &old {
                self.fire_triggers(
                    &del.table,
                    TrigEvent::Delete,
                    TriggerTiming::Before,
                    &meta.columns,
                    Some((old, *rowid)),
                    None,
                    params,
                    None,
                )?;
                // A `BEFORE DELETE` trigger's `RAISE(IGNORE)` spares this row.
                if self.raise_ignore.replace(false) {
                    continue;
                }
                if !del.returning.is_empty() {
                    self.collect_returning(&del.returning, &meta, old, Some(*rowid), params)?;
                }
            }
            // Enforce referential actions on dependent child tables.
            if self.foreign_keys {
                if let Some(old) = &old {
                    self.enforce_parent_change(&del.table, old, None, params)?;
                }
            }
            delete_table(self.backend.writer()?, meta.root, *rowid)?;
            deleted += 1;
            if let Some(old) = &old {
                self.fire_triggers(
                    &del.table,
                    TrigEvent::Delete,
                    TriggerTiming::After,
                    &meta.columns,
                    Some((old, *rowid)),
                    None,
                    params,
                    None,
                )?;
            }
        }
        if deleted > 0 {
            self.compact_table(&meta)?;
            self.rebuild_indexes(&meta, &indexes)?;
        }
        Ok(deleted)
    }

    /// Reclaim empty/underfull table b-tree pages left by deletes: if the table
    /// has any empty leaf page, rebuild the b-tree compactly in place (root page
    /// number preserved), freeing the slack to the freelist. This is graphitesql's
    /// page-merging-on-delete — using the well-tested insert path rather than
    /// in-place sibling rebalancing — and keeps the tree balanced and compact.
    fn compact_table(&mut self, meta: &TableMeta) -> Result<()> {
        if !table_has_empty_leaf(self.backend.source(), meta.root)? {
            return Ok(());
        }
        // Collect every surviving (rowid, raw payload) in key order.
        let mut rows: Vec<(i64, Vec<u8>)> = Vec::new();
        {
            let mut cur = TableCursor::new(self.backend.source(), meta.root);
            let mut ok = cur.first()?;
            while ok {
                rows.push((cur.rowid()?, cur.payload()?));
                ok = cur.next()?;
            }
        }
        let w = self.backend.writer()?;
        clear_table(w, meta.root)?;
        for (rowid, payload) in &rows {
            insert_table(w, meta.root, *rowid, payload)?;
        }
        Ok(())
    }

    fn exec_update(&mut self, upd: &Update, params: &Params) -> Result<usize> {
        // A leading `WITH` exposes its CTEs to the SET/WHERE/FROM subqueries.
        if upd.ctes.is_empty() {
            return self.exec_update_inner(upd, params);
        }
        let base = self.cte_env.borrow().len();
        let pushed = self.push_ctes(&upd.ctes, params, None);
        let result = pushed.and_then(|()| self.exec_update_inner(upd, params));
        self.cte_env.borrow_mut().truncate(base);
        result
    }

    fn exec_update_inner(&mut self, upd: &Update, params: &Params) -> Result<usize> {
        reject_schema_write(&upd.table)?;
        if self.is_virtual_table(&upd.table) {
            return self.exec_vtab_update(upd, params);
        }
        if self.is_view(&upd.table) {
            return self.exec_view_update(upd, params);
        }
        let meta = self.table_meta(&upd.table, None)?;
        // Validate the SET-target columns up front: sqlite rejects an unknown
        // assignment column at prepare time, even when the table has no rows.
        // graphite otherwise resolves them lazily in the per-row loop and so
        // silently accepted a bogus column on an empty table.
        for col in upd
            .assignments
            .iter()
            .map(|(c, _)| c)
            .chain(upd.row_assignments.iter().flat_map(|(cs, _)| cs))
        {
            if !meta
                .columns
                .iter()
                .any(|c| c.name.eq_ignore_ascii_case(col))
            {
                return Err(Error::Error(alloc::format!("no such column: {col}")));
            }
        }
        if meta.without_rowid {
            if !upd.returning.is_empty() {
                return Err(Error::Unsupported("RETURNING on WITHOUT ROWID tables"));
            }
            if upd.from.is_some() {
                return Err(Error::Unsupported("UPDATE … FROM on WITHOUT ROWID tables"));
            }
            return self.exec_update_without_rowid(upd, &meta, params);
        }
        let indexes = self.indexes_of(&upd.table)?;
        // Columns named in the SET list — drives `UPDATE OF col,…` trigger firing.
        let mut changed: Vec<String> = upd.assignments.iter().map(|(c, _)| c.clone()).collect();
        for (rcols, _) in &upd.row_assignments {
            changed.extend(rcols.iter().cloned());
        }
        // UPDATE … FROM: materialize the extra tables once. Each target row is
        // joined to the first FROM-row combination satisfying WHERE, and that
        // row's columns are visible to SET/WHERE. Without FROM, `from_rows` is
        // empty and the target is matched against WHERE directly.
        let from_data = match &upd.from {
            Some(fc) => {
                // A from-only synthetic SELECT to reuse the join scanner. Its WHERE
                // stays empty (the UPDATE's WHERE references the target too and is
                // applied per target row below), so the scan is a plain superset.
                let synth = Select {
                    ctes: Vec::new(),
                    compound: Vec::new(),
                    distinct: false,
                    columns: Vec::new(),
                    from: Some(fc.clone()),
                    where_clause: None,
                    group_by: Vec::new(),
                    having: None,
                    window_defs: Vec::new(),
                    order_by: Vec::new(),
                    limit: None,
                    offset: None,
                };
                let (cols, rows) = self.scan_source(&synth, params)?;
                Some((cols, rows.into_iter().map(|r| r.values).collect::<Vec<_>>()))
            }
            None => None,
        };
        let combined_columns: Vec<ColumnInfo> = match &from_data {
            Some((cols, _)) => meta.columns.iter().chain(cols).cloned().collect(),
            None => Vec::new(),
        };
        // Collect (rowid, current values, matched FROM row) for matching rows.
        let mut targets: Vec<(i64, Vec<Value>, Option<Vec<Value>>)> = Vec::new();
        {
            let mut cur = TableCursor::new(self.backend.source(), meta.root);
            let encoding = self.backend.source().header().text_encoding;
            let mut ok = cur.first()?;
            while ok {
                let rowid = cur.rowid()?;
                let values = self.decode_full_row(&meta, rowid, &cur.payload()?, encoding)?;
                match &from_data {
                    // UPDATE … FROM: find the first joined row passing WHERE.
                    Some((_, from_rows)) => {
                        let mut matched = None;
                        for fr in from_rows {
                            let mut combined = values.clone();
                            combined.extend_from_slice(fr);
                            let ok = match &upd.where_clause {
                                Some(p) => {
                                    let ctx =
                                        row_ctx(&combined, &combined_columns, Some(rowid), params)
                                            .with_subqueries(self);
                                    eval::truth(&eval::eval(p, &ctx)?) == Some(true)
                                }
                                None => true,
                            };
                            if ok {
                                matched = Some(fr.clone());
                                break;
                            }
                        }
                        if let Some(fr) = matched {
                            targets.push((rowid, values, Some(fr)));
                        }
                    }
                    None => {
                        let matches = match &upd.where_clause {
                            Some(p) => {
                                let ctx = row_ctx(&values, &meta.columns, Some(rowid), params)
                                    .with_subqueries(self);
                                eval::truth(&eval::eval(p, &ctx)?) == Some(true)
                            }
                            None => true,
                        };
                        if matches {
                            targets.push((rowid, values, None));
                        }
                    }
                }
                ok = cur.next()?;
            }
        }
        // `ORDER BY … LIMIT …` selects which matching rows to update.
        if !upd.order_by.is_empty() || upd.limit.is_some() || upd.offset.is_some() {
            let rowids: Vec<i64> = targets.iter().map(|(r, _, _)| *r).collect();
            let kept = self.order_limit_rowids(
                &meta,
                rowids,
                &upd.order_by,
                upd.limit.as_ref(),
                upd.offset.as_ref(),
                params,
            )?;
            // Reorder/filter `targets` to the kept rowids, preserving kept order.
            let mut by_id: alloc::collections::BTreeMap<i64, (Vec<Value>, Option<Vec<Value>>)> =
                targets.into_iter().map(|(r, v, f)| (r, (v, f))).collect();
            targets = kept
                .into_iter()
                .filter_map(|r| by_id.remove(&r).map(|(v, f)| (r, v, f)))
                .collect();
        }

        // Evaluate every target row's SET assignments against the table as it is
        // BEFORE any write, so a subquery in a SET expression sees a consistent
        // snapshot — `UPDATE t SET b=(SELECT sum(b) FROM t)` uses the original sum
        // for every row, exactly like sqlite — rather than observing rows updated
        // earlier in the same statement. Writes happen in the second pass below.
        let mut prepared: Vec<(i64, Vec<Value>, Vec<Value>)> = Vec::with_capacity(targets.len());
        for (rowid, mut values, matched_from) in targets {
            let old_row = values.clone();
            for (col, expr) in &upd.assignments {
                let pos = meta
                    .columns
                    .iter()
                    .position(|c| c.name.eq_ignore_ascii_case(col))
                    .ok_or_else(|| Error::Error(format!("no such column: {col}")))?;
                if meta.is_generated(pos) {
                    return Err(Error::Error(format!(
                        "cannot UPDATE generated column \"{col}\""
                    )));
                }
                // SQLite evaluates every SET expression against the ORIGINAL row
                // (assignments are simultaneous): `SET a=b, b=a` swaps. Evaluate
                // against `old_row`, not the progressively-mutated `values`.
                let new = match &matched_from {
                    Some(fr) => {
                        let mut combined = old_row.clone();
                        combined.extend_from_slice(fr);
                        let ctx = row_ctx(&combined, &combined_columns, Some(rowid), params)
                            .with_subqueries(self);
                        eval::eval(expr, &ctx)?
                    }
                    None => {
                        let ctx = row_ctx(&old_row, &meta.columns, Some(rowid), params)
                            .with_subqueries(self);
                        eval::eval(expr, &ctx)?
                    }
                };
                values[pos] = new;
            }
            if !upd.row_assignments.is_empty() {
                // Build the same (possibly FROM-combined) original-row context the
                // per-expr assignments used, then run each row-value subquery.
                let combined_row;
                let (ctx_row, ctx_cols): (&[Value], &[ColumnInfo]) = match &matched_from {
                    Some(fr) => {
                        let mut c = old_row.clone();
                        c.extend_from_slice(fr);
                        combined_row = c;
                        (&combined_row, &combined_columns)
                    }
                    None => (&old_row, &meta.columns),
                };
                let ctx = row_ctx(ctx_row, ctx_cols, Some(rowid), params).with_subqueries(self);
                self.apply_row_subquery_assignments(
                    &upd.row_assignments,
                    &meta.columns,
                    Some(&meta),
                    &ctx,
                    &mut values,
                )?;
            }
            apply_column_affinity(&meta, &mut values);
            self.materialize_generated(&meta, &mut values, params)?;
            prepared.push((rowid, old_row, values));
        }

        let mut affected = 0;
        for (rowid, old_row, mut values) in prepared {
            // An UPDATE of the INTEGER PRIMARY KEY (the rowid) must leave it an
            // integer; NULL or a non-integer (after affinity) is a datatype
            // mismatch — a hard error checked before NOT NULL (which would else
            // mis-report `SET ipk = NULL`) and not skipped by UPDATE OR IGNORE.
            if let Some(ipk) = meta.ipk {
                if !matches!(values[ipk], Value::Integer(_)) {
                    return Err(Error::Error("datatype mismatch".into()));
                }
            }
            // NOT NULL / CHECK / STRICT-type constraints. `UPDATE OR IGNORE` skips
            // a row that violates one rather than failing the statement.
            {
                if !self.resolve_not_null(
                    &meta,
                    &mut values,
                    upd.on_conflict,
                    upd.on_conflict_explicit,
                    params,
                )? {
                    continue;
                }
                let r = self
                    .check_strict_types(&meta, &values)
                    .and_then(|()| self.check_constraints(&meta, &values, Some(rowid), params));
                match r {
                    Ok(()) => {}
                    Err(Error::Constraint(_)) if upd.on_conflict == OnConflict::Ignore => continue,
                    Err(Error::Constraint(m)) => {
                        return Err(self.conflict_error(upd.on_conflict, &m))
                    }
                    Err(e) => return Err(e),
                }
            }
            // Foreign keys: this row as a child must still point at a parent, and
            // as a parent it must propagate referenced-key changes to children.
            self.check_fk_child(&upd.table, &meta, &values)?;
            if self.foreign_keys {
                self.enforce_parent_change(&upd.table, &old_row, Some(&values), params)?;
            }
            // New rowid if the IPK column was changed, else unchanged.
            let new_rowid = match meta.ipk {
                Some(ipk) => eval::to_i64(&values[ipk]),
                None => rowid,
            };
            self.fire_triggers(
                &upd.table,
                TrigEvent::Update,
                TriggerTiming::Before,
                &meta.columns,
                Some((&old_row, rowid)),
                Some((&values, new_rowid)),
                params,
                Some(&changed),
            )?;
            // A `BEFORE UPDATE` trigger's `RAISE(IGNORE)` leaves this row alone.
            if self.raise_ignore.replace(false) {
                continue;
            }
            // UNIQUE/PK conflict against any other row. `UPDATE OR IGNORE` skips
            // this row; `UPDATE OR REPLACE` deletes the conflicting rows first.
            let (conflicts, constraint_oc) =
                self.find_conflicts(&upd.table, &meta, new_rowid, &values, Some(rowid), params)?;
            let effective_oc = if upd.on_conflict_explicit {
                upd.on_conflict
            } else {
                constraint_oc
            };
            if !conflicts.is_empty() {
                match effective_oc {
                    OnConflict::Ignore => continue,
                    OnConflict::Replace => {
                        for cr in conflicts {
                            delete_table(self.backend.writer()?, meta.root, cr)?;
                        }
                    }
                    oc @ (OnConflict::Abort | OnConflict::Fail | OnConflict::Rollback) => {
                        let m = self.unique_violation_message(
                            &upd.table,
                            &meta,
                            new_rowid,
                            &values,
                            Some(rowid),
                            params,
                        );
                        return Err(self.conflict_error(oc, &m));
                    }
                }
            }
            let new_full = values.clone();
            let record = self.encode_table_record(&meta, &new_full);
            delete_table(self.backend.writer()?, meta.root, rowid)?;
            insert_table(self.backend.writer()?, meta.root, new_rowid, &record)?;
            self.fire_triggers(
                &upd.table,
                TrigEvent::Update,
                TriggerTiming::After,
                &meta.columns,
                Some((&old_row, rowid)),
                Some((&new_full, new_rowid)),
                params,
                Some(&changed),
            )?;
            if !upd.returning.is_empty() {
                self.collect_returning(&upd.returning, &meta, &new_full, Some(new_rowid), params)?;
            }
            affected += 1;
        }
        if affected > 0 {
            self.compact_table(&meta)?;
            self.rebuild_indexes(&meta, &indexes)?;
        }
        Ok(affected)
    }

    // ---- index DDL & maintenance --------------------------------------------

    fn exec_create_index(&mut self, ci: &CreateIndex, sql_text: &str) -> Result<()> {
        // A schema-qualified `CREATE INDEX aux.idx …` stores its SQL bare-named
        // in the target catalog (the `aux.` prefix is invalid there). Reprint.
        let reprinted;
        let sql_text = if ci.schema.is_some() {
            reprinted = sql::print::create_index(ci);
            reprinted.as_str()
        } else {
            sql_text
        };
        if self.schema.index(&ci.name).is_some() {
            if ci.if_not_exists {
                return Ok(());
            }
            return Err(Error::Error(format!("index {} already exists", ci.name)));
        }
        if self.is_virtual_table(&ci.table) {
            return Err(Error::Error("virtual tables may not be indexed".into()));
        }
        // A missing index target is schema-qualified by SQLite (`main` default),
        // unlike the bare "no such table" of a DML/SELECT reference.
        if self.schema.table(&ci.table).is_none() {
            return Err(Error::Error(format!(
                "no such table: {}.{}",
                ci.schema.as_deref().unwrap_or("main"),
                ci.table
            )));
        }
        let tmeta = self.table_meta(&ci.table, None)?;
        // SQLite rejects non-deterministic functions in an index expression (or a
        // partial-index predicate): the stored key could never match a recomputed
        // probe. Reject before building anything.
        if ci.columns.iter().any(|t| expr_is_nondeterministic(&t.expr))
            || ci
                .where_clause
                .as_ref()
                .is_some_and(expr_is_nondeterministic)
        {
            return Err(Error::Error(
                "non-deterministic functions prohibited in index expressions".into(),
            ));
        }
        // Each key's explicit `COLLATE <name>` must name a known collating
        // sequence; sqlite errors "no such collation sequence" rather than
        // silently using BINARY.
        for term in &ci.columns {
            if let Some(name) = unknown_collation(&term.expr) {
                return Err(Error::Error(format!("no such collation sequence: {name}")));
            }
        }
        let (cols, key_exprs, colls) = self.index_key_spec(&tmeta, ci)?;
        if key_exprs.is_some() && tmeta.without_rowid {
            return Err(Error::Unsupported(
                "expression indexes on WITHOUT ROWID tables",
            ));
        }
        let schema_next = self.next_rowid(crate::schema::SCHEMA_ROOT_PAGE)?;

        // A partial index (`CREATE INDEX … WHERE p`) only stores rows for which
        // the predicate holds; evaluate it up front (before the writer borrow).
        let no_params = Params::default();
        let keep_row = |values: &[Value], rowid: Option<i64>| -> Result<bool> {
            match &ci.where_clause {
                None => Ok(true),
                Some(p) => {
                    let ctx =
                        row_ctx(values, &tmeta.columns, rowid, &no_params).with_subqueries(self);
                    Ok(eval::truth(&eval::eval(p, &ctx)?) == Some(true))
                }
            }
        };

        // WITHOUT ROWID secondary indexes are keyed by (indexed cols, PK cols)
        // instead of (indexed cols, rowid).
        let root = if tmeta.without_rowid {
            let rows = self.scan_without_rowid(&tmeta)?;
            let keep: Vec<bool> = rows
                .iter()
                .map(|row| keep_row(row, None))
                .collect::<Result<_>>()?;
            let pk_cols = tmeta.storage_order[..tmeta.pk_len].to_vec();
            let mut key_colls = colls.clone();
            key_colls.extend(self.col_collations(&tmeta, &pk_cols));
            let w = self.backend.writer()?;
            let root = create_index_root(w)?;
            for (row, &k) in rows.iter().zip(&keep) {
                if k {
                    insert_index(w, root, &wr_index_key(&cols, &pk_cols, row), &key_colls)?;
                }
            }
            root
        } else {
            let rows = self.scan_table(&tmeta)?;
            // Precompute the key bytes of every included row (column values, or
            // evaluated expressions for an expression index) before the writer
            // borrow.
            let mut keys: Vec<Vec<u8>> = Vec::new();
            for (rowid, values) in &rows {
                if !keep_row(values, Some(*rowid))? {
                    continue;
                }
                keys.push(match &key_exprs {
                    None => index_key(&cols, values, *rowid),
                    Some(exprs) => {
                        let ctx = row_ctx(values, &tmeta.columns, Some(*rowid), &no_params)
                            .with_subqueries(self);
                        let mut k: Vec<Value> = exprs
                            .iter()
                            .map(|e| eval::eval(e, &ctx))
                            .collect::<Result<_>>()?;
                        k.push(Value::Integer(*rowid));
                        encode_record(&k)
                    }
                });
            }
            let w = self.backend.writer()?;
            let root = create_index_root(w)?;
            for key in &keys {
                insert_index(w, root, key, &colls)?;
            }
            root
        };
        let w = self.backend.writer()?;
        let schema_row = encode_record(&[
            Value::Text("index".into()),
            Value::Text(ci.name.clone()),
            Value::Text(ci.table.clone()),
            Value::Integer(root as i64),
            Value::Text(sql_text.into()),
        ]);
        insert_table(w, crate::schema::SCHEMA_ROOT_PAGE, schema_next, &schema_row)?;
        let cookie = w.header().schema_cookie.wrapping_add(1);
        w.header_mut().schema_cookie = cookie;
        self.schema = Schema::read(self.backend.source())?;
        Ok(())
    }

    fn exec_create_view(&mut self, cv: &CreateView, sql_text: &str) -> Result<()> {
        // A schema-qualified `CREATE VIEW aux.v …` stores its SQL bare-named.
        let stripped;
        let sql_text = match cv.schema.as_deref() {
            Some(s) => {
                stripped = strip_schema_qualifier(sql_text, s)?;
                stripped.as_str()
            }
            None => sql_text,
        };
        let exists = self.schema.objects().iter().any(|o| o.name == cv.name);
        if exists {
            if cv.if_not_exists {
                return Ok(());
            }
            return Err(Error::Error(format!("table {} already exists", cv.name)));
        }
        let next = self.next_rowid(crate::schema::SCHEMA_ROOT_PAGE)?;
        let row = encode_record(&[
            Value::Text("view".into()),
            Value::Text(cv.name.clone()),
            Value::Text(cv.name.clone()),
            Value::Integer(0), // views have no b-tree root
            Value::Text(sql_text.into()),
        ]);
        insert_table(
            self.backend.writer()?,
            crate::schema::SCHEMA_ROOT_PAGE,
            next,
            &row,
        )?;
        let cookie = self
            .backend
            .writer()?
            .header()
            .schema_cookie
            .wrapping_add(1);
        self.backend.writer()?.header_mut().schema_cookie = cookie;
        self.schema = Schema::read(self.backend.source())?;
        Ok(())
    }

    /// Execute `CREATE VIRTUAL TABLE … USING module(args)`: look the module up in
    /// the registry, validate the arguments by connecting (so a bad CREATE fails
    /// now, not at first query), and persist a `sqlite_schema` row with
    /// `type='table'`, `rootpage=0`, and `sql` = the original CREATE text.
    fn exec_create_virtual_table(
        &mut self,
        cvt: &CreateVirtualTable,
        sql_text: &str,
    ) -> Result<()> {
        // A schema-qualified `CREATE VIRTUAL TABLE aux.v …` stores its SQL
        // bare-named, like CREATE TABLE/VIEW.
        let stripped;
        let sql_text = match cvt.schema.as_deref() {
            Some(s) => {
                stripped = strip_schema_qualifier(sql_text, s)?;
                stripped.as_str()
            }
            None => sql_text,
        };
        let exists = self.schema.objects().iter().any(|o| o.name == cvt.name);
        if exists {
            if cvt.if_not_exists {
                return Ok(());
            }
            return Err(Error::Error(format!("table {} already exists", cvt.name)));
        }
        // The module must be registered, and must accept these arguments.
        let module = self
            .vtab_registry
            .get(&cvt.module)
            .ok_or_else(|| Error::Error(format!("no such module: {}", cvt.module)))?;
        let arg_refs: Vec<&str> = cvt.args.iter().map(String::as_str).collect();
        let schema = module.dyn_connect(&arg_refs)?;
        let persistent = module.dyn_persistent();
        let cols = schema.columns;
        // An R-Tree with no auxiliary columns uses SQLite's byte-compatible node
        // format (`_node`/`_rowid`/`_parent`) so its file round-trips through
        // sqlite3; an aux-column R-Tree and all other persistent modules keep the
        // generic `<name>_data` backing table.
        let rtree_n_coord = (cvt.module.eq_ignore_ascii_case("rtree")
            || cvt.module.eq_ignore_ascii_case("rtree_i32"))
        .then(|| crate::vtab::RTreeModule::n_coords(&arg_refs))
        .filter(|n| cols.len() == 1 + n);
        #[cfg(feature = "fts5")]
        let is_fts5 = cvt.module.eq_ignore_ascii_case("fts5");
        #[cfg(not(feature = "fts5"))]
        let is_fts5 = false;
        if let Some(n_coord) = rtree_n_coord {
            let integer = cvt.module.eq_ignore_ascii_case("rtree_i32");
            self.rtree_create_storage(&cvt.name, n_coord, integer)?;
        } else if is_fts5 {
            // FTS5 uses sqlite's five shadow tables (so the file round-trips
            // through stock sqlite), not the generic `<name>_data` store.
            #[cfg(feature = "fts5")]
            self.fts5_create_storage(&cvt.name, cols.len())?;
        } else if persistent {
            let coldefs = cols
                .iter()
                .map(|c| sql::print::ident(c))
                .collect::<Vec<_>>()
                .join(", ");
            let backing_sql = format!(
                "CREATE TABLE {}({coldefs})",
                sql::print::ident(&format!("{}_data", cvt.name))
            );
            let Statement::CreateTable(ct) = sql::parse_one(&backing_sql)? else {
                unreachable!("constructed a CREATE TABLE");
            };
            self.exec_create_table(&ct, &backing_sql)?;
        }

        let next = self.next_rowid(crate::schema::SCHEMA_ROOT_PAGE)?;
        let row = encode_record(&[
            Value::Text("table".into()),
            Value::Text(cvt.name.clone()),
            Value::Text(cvt.name.clone()),
            Value::Integer(0), // virtual tables have no b-tree root
            Value::Text(sql_text.into()),
        ]);
        insert_table(
            self.backend.writer()?,
            crate::schema::SCHEMA_ROOT_PAGE,
            next,
            &row,
        )?;
        let cookie = self
            .backend
            .writer()?
            .header()
            .schema_cookie
            .wrapping_add(1);
        self.backend.writer()?.header_mut().schema_cookie = cookie;
        self.schema = Schema::read(self.backend.source())?;
        Ok(())
    }

    /// Whether the named object is a virtual table (a `type='table'` schema row
    /// whose stored SQL is a `CREATE VIRTUAL TABLE`). Such a table has no b-tree
    /// (`rootpage = 0`) and is scanned through its registered module instead.
    fn is_virtual_table(&self, name: &str) -> bool {
        self.schema
            .objects()
            .iter()
            .filter(|o| {
                o.obj_type == crate::schema::ObjectType::Table && o.name.eq_ignore_ascii_case(name)
            })
            .any(|o| {
                matches!(
                    o.sql.as_deref().map(sql::parse_one),
                    Some(Ok(Statement::CreateVirtualTable(_)))
                )
            })
    }

    /// The module name, `USING` arguments, and declared column names of a virtual
    /// table — by reparsing its stored `CREATE VIRTUAL TABLE` and asking the
    /// module to `connect`. Used by the write path.
    fn vtab_meta(&self, name: &str) -> Result<(String, Vec<String>, crate::vtab::VTabSchema)> {
        use crate::schema::ObjectType;
        let obj = self
            .schema
            .objects()
            .iter()
            .find(|o| o.obj_type == ObjectType::Table && o.name.eq_ignore_ascii_case(name))
            .ok_or_else(|| Error::Error(format!("no such table: {name}")))?;
        let Some(Ok(Statement::CreateVirtualTable(cvt))) = obj.sql.as_deref().map(sql::parse_one)
        else {
            return Err(Error::Error(format!("{name} is not a virtual table")));
        };
        let module = self
            .vtab_registry
            .get(&cvt.module)
            .ok_or_else(|| Error::Error(format!("no such module: {}", cvt.module)))?;
        let arg_refs: Vec<&str> = cvt.args.iter().map(String::as_str).collect();
        let schema = module.dyn_connect(&arg_refs)?;
        Ok((cvt.module.clone(), cvt.args.clone(), schema))
    }

    /// `INSERT` into a virtual table: evaluate each row's values into the module's
    /// declared column order and hand them to its
    /// [`update`](crate::vtab::VTabModule::update) (SQLite's `xUpdate` insert).
    /// A read-only module's default `update` rejects the write.
    /// Run `f` with the named module taken out of the registry and a [`VTabStore`]
    /// over its `<table>_data` backing table, re-registering the module afterward.
    /// Taking the module out lets the store hold `&mut Connection` without aliasing
    /// the borrowed module. Callers do all read-only work (evaluating values,
    /// scanning rows) *before* this, then only persist inside `f`.
    fn with_vtab_store<F>(
        &mut self,
        module_name: &str,
        args: &[String],
        table: &str,
        f: F,
    ) -> Result<usize>
    where
        F: FnOnce(&dyn DynVTabModule, &mut dyn VTabStore, &[&str]) -> Result<usize>,
    {
        let module = self
            .vtab_registry
            .unregister(module_name)
            .ok_or_else(|| Error::Error(format!("no such module: {module_name}")))?;
        // FTS5 keeps its documents in `<name>_content` (sqlite's layout); every
        // other persistent module uses the generic `<name>_data` store.
        let backing = if module_name.eq_ignore_ascii_case("fts5") {
            format!("{table}_content")
        } else {
            format!("{table}_data")
        };
        let arg_refs: Vec<&str> = args.iter().map(String::as_str).collect();
        let result = {
            let mut store = ExecVTabStore {
                conn: self,
                backing: &backing,
                ipk_prefix: module_name.eq_ignore_ascii_case("fts5"),
            };
            f(&*module, &mut store, &arg_refs)
        };
        self.vtab_registry.register(module_name, module)?;
        result
    }

    fn exec_vtab_insert(
        &mut self,
        ins: &Insert,
        rows: &[Vec<Expr>],
        params: &Params,
    ) -> Result<usize> {
        if !ins.upsert.is_empty() || !ins.returning.is_empty() {
            return Err(Error::Unsupported("UPSERT / RETURNING on a virtual table"));
        }
        let (module_name, args, schema) = self.vtab_meta(&ins.table)?;
        let col_names = schema.columns;
        let ncols = col_names.len();
        // FTS5 exposes a hidden column named after the table that accepts special
        // commands: `INSERT INTO t(t) VALUES('rebuild'|'optimize')` issues a
        // maintenance command rather than inserting a row. graphite's `fts5` index
        // is scan-based, so `rebuild` and `optimize` are no-ops (there is no
        // separate index to rebuild); other commands fall through to the usual
        // column resolution (and its "no such column" error), matching SQLite,
        // which rejects `delete`/`delete-all` on an ordinary content table.
        #[cfg(feature = "fts5")]
        if module_name.eq_ignore_ascii_case("fts5")
            && ins.columns.len() == 1
            && ins.columns[0].eq_ignore_ascii_case(&ins.table)
        {
            let commands = rows
                .iter()
                .map(|row| {
                    let ctx = EvalCtx::rowless(params).with_subqueries(self);
                    Ok(eval::to_text(&eval::eval(&row[0], &ctx)?))
                })
                .collect::<Result<Vec<_>>>()?;
            if commands
                .iter()
                .all(|c| matches!(c.as_str(), "rebuild" | "optimize"))
            {
                return Ok(0);
            }
        }
        // Map the (possibly explicit) column list onto declared column positions.
        // `None` marks a `rowid`/`_rowid_`/`oid` term (a vtab's hidden rowid),
        // whose value becomes the inserted row's explicit rowid.
        let target: Vec<Option<usize>> = if ins.columns.is_empty() {
            (0..ncols).map(Some).collect()
        } else {
            ins.columns
                .iter()
                .map(
                    |name| match col_names.iter().position(|c| c.eq_ignore_ascii_case(name)) {
                        Some(p) => Ok(Some(p)),
                        None if matches!(
                            name.to_ascii_lowercase().as_str(),
                            "rowid" | "_rowid_" | "oid"
                        ) =>
                        {
                            Ok(None)
                        }
                        None => Err(Error::Error(format!("no such column: {name}"))),
                    },
                )
                .collect::<Result<_>>()?
        };
        // Evaluate every row up front (a read-only borrow of self), then persist.
        let mut changes: Vec<(Option<i64>, Vec<Value>)> = Vec::with_capacity(rows.len());
        for row in rows {
            if row.len() != target.len() {
                return Err(Error::Error(format!(
                    "{} values for {} columns",
                    row.len(),
                    target.len()
                )));
            }
            let mut values = alloc::vec![Value::Null; ncols];
            let mut rowid = None;
            for (j, expr) in row.iter().enumerate() {
                let ctx = EvalCtx::rowless(params).with_subqueries(self);
                let v = eval::eval(expr, &ctx)?;
                match target[j] {
                    Some(col) => values[col] = v,
                    None => rowid = Some(eval::to_i64(&v)),
                }
            }
            changes.push((rowid, values));
        }
        let on_conflict = ins.on_conflict;
        let table = ins.table.clone();
        let id_col = col_names
            .first()
            .cloned()
            .unwrap_or_else(|| String::from("rowid"));
        // R-Tree with no aux columns: store in SQLite's byte-compatible node tree.
        let arg_refs: Vec<&str> = args.iter().map(String::as_str).collect();
        let rtree_nc = (module_name.eq_ignore_ascii_case("rtree")
            || module_name.eq_ignore_ascii_case("rtree_i32"))
        .then(|| crate::vtab::RTreeModule::n_coords(&arg_refs))
        .filter(|n| ncols == 1 + n);
        if let Some(n_coord) = rtree_nc {
            let integer = module_name.eq_ignore_ascii_case("rtree_i32");
            let mut existing: alloc::collections::BTreeSet<i64> = self
                .rtree_entries(&table, n_coord, integer)?
                .iter()
                .map(|c| c.key)
                .collect();
            let mut next_auto = existing.iter().max().copied().unwrap_or(0) + 1;
            let mut cells: Vec<RtreeCell> = Vec::new();
            let mut n = 0;
            for (rowid, values) in &changes {
                let rid = rowid
                    .or(match values.first() {
                        Some(Value::Integer(i)) => Some(*i),
                        _ => None,
                    })
                    .unwrap_or_else(|| {
                        let r = next_auto;
                        next_auto += 1;
                        r
                    });
                if existing.contains(&rid) {
                    match on_conflict {
                        OnConflict::Replace => {}
                        OnConflict::Ignore => continue,
                        _ => {
                            return Err(Error::Constraint(format!(
                                "UNIQUE constraint failed: {table}.{id_col}"
                            )))
                        }
                    }
                }
                existing.insert(rid);
                cells.retain(|c| c.key != rid); // OR REPLACE within this batch
                cells.push(rtree_cell_from_values(rid, values, n_coord, integer)?);
                n += 1;
            }
            self.rtree_apply(&table, n_coord, integer, cells, &[])?;
            return Ok(n);
        }
        let inserted = self.with_vtab_store(
            &module_name,
            &args,
            &ins.table,
            |module, store, arg_refs| {
                // An explicit rowid that already exists is a UNIQUE conflict on the
                // implicit rowid — error (or skip/replace per `OR IGNORE`/`REPLACE`),
                // matching sqlite, rather than silently overwriting the row. Only a
                // store-backed (persistent) vtab is checked here; a non-persistent
                // module (no `<name>_data` table → `rows()` errors) manages its own.
                let mut existing: alloc::collections::BTreeSet<i64> = store
                    .rows()
                    .map(|rows| rows.iter().map(|(r, _)| *r).collect())
                    .unwrap_or_default();
                // The effective rowid is the explicit `rowid` term, or — for a
                // module with a rowid-alias column (rtree's `id`) — that column's
                // value when not NULL.
                let rowid_col = module.dyn_rowid_column();
                let mut n = 0;
                for (rowid, values) in &changes {
                    let effective = rowid.or_else(|| {
                        let v = values.get(rowid_col?)?;
                        (!matches!(v, Value::Null)).then(|| eval::to_i64(v))
                    });
                    if let Some(id) = effective {
                        if existing.contains(&id) {
                            match on_conflict {
                                OnConflict::Replace => {}
                                OnConflict::Ignore => continue,
                                _ => {
                                    return Err(Error::Constraint(format!(
                                        "UNIQUE constraint failed: {table}.{id_col}"
                                    )))
                                }
                            }
                        }
                    }
                    let assigned = module.dyn_update(
                        arg_refs,
                        VTabChange::Insert {
                            rowid: *rowid,
                            values,
                        },
                        store,
                    )?;
                    existing.insert(assigned);
                    n += 1;
                }
                Ok(n)
            },
        )?;
        self.fts5_maybe_rebuild(&module_name, &ins.table)?;
        Ok(inserted)
    }

    /// `DELETE` from a virtual table: scan it for rows matching the `WHERE`, then
    /// call the module's [`update`](crate::vtab::VTabModule::update) with
    /// [`VTabChange::Delete`] for each (over a materialized snapshot, so deleting
    /// during iteration is safe).
    fn exec_vtab_delete(&mut self, del: &Delete, params: &Params) -> Result<usize> {
        if !del.returning.is_empty() {
            return Err(Error::Unsupported("RETURNING on a virtual table"));
        }
        let (module_name, args, _) = self.vtab_meta(&del.table)?;
        let (columns, rows) = self
            .try_virtual_table(&del.table, None, None)?
            .ok_or_else(|| Error::Error(format!("{} is not a virtual table", del.table)))?;
        // Collect the matching rowids first (read-only), then persist.
        let mut victims: Vec<i64> = Vec::new();
        for r in &rows {
            if let Some(pred) = &del.where_clause {
                let ctx = r.ctx(&columns, params).with_subqueries(self);
                if eval::truth(&eval::eval(pred, &ctx)?) != Some(true) {
                    continue;
                }
            }
            victims.push(
                r.rowid
                    .ok_or_else(|| Error::Error("virtual-table row has no rowid".into()))?,
            );
        }
        // R-Tree with no aux columns: rebuild the node tree without the victims.
        let arg_refs: Vec<&str> = args.iter().map(String::as_str).collect();
        let rtree_nc = (module_name.eq_ignore_ascii_case("rtree")
            || module_name.eq_ignore_ascii_case("rtree_i32"))
        .then(|| crate::vtab::RTreeModule::n_coords(&arg_refs))
        .filter(|n| columns.len() == 1 + n);
        if let Some(n_coord) = rtree_nc {
            let integer = module_name.eq_ignore_ascii_case("rtree_i32");
            self.rtree_apply(&del.table, n_coord, integer, Vec::new(), &victims)?;
            return Ok(victims.len());
        }
        let deleted = self.with_vtab_store(
            &module_name,
            &args,
            &del.table,
            |module, store, arg_refs| {
                for rowid in &victims {
                    module.dyn_update(arg_refs, VTabChange::Delete { rowid: *rowid }, store)?;
                }
                Ok(victims.len())
            },
        )?;
        self.fts5_maybe_rebuild(&module_name, &del.table)?;
        Ok(deleted)
    }

    /// `UPDATE` of a virtual table: scan for rows matching the `WHERE`, evaluate
    /// the `SET` assignments against each, and call the module's
    /// [`update`](crate::vtab::VTabModule::update) with [`VTabChange::Update`].
    fn exec_vtab_update(&mut self, upd: &Update, params: &Params) -> Result<usize> {
        if !upd.returning.is_empty() {
            return Err(Error::Unsupported("RETURNING on a virtual table"));
        }
        if !upd.row_assignments.is_empty() {
            return Err(Error::Unsupported(
                "UPDATE SET (…) = (SELECT …) on a virtual table",
            ));
        }
        if upd.from.is_some() {
            return Err(Error::Unsupported("UPDATE … FROM on a virtual table"));
        }
        let (module_name, args, schema) = self.vtab_meta(&upd.table)?;
        let col_names = schema.columns;
        // Resolve each SET target to a declared column position.
        let assigns: Vec<(usize, &Expr)> = upd
            .assignments
            .iter()
            .map(|(name, value)| {
                col_names
                    .iter()
                    .position(|c| c.eq_ignore_ascii_case(name))
                    .map(|pos| (pos, value))
                    .ok_or_else(|| Error::Error(format!("no such column: {name}")))
            })
            .collect::<Result<_>>()?;
        let (columns, rows) = self
            .try_virtual_table(&upd.table, None, None)?
            .ok_or_else(|| Error::Error(format!("{} is not a virtual table", upd.table)))?;
        // Compute the new (rowid, values) for each matching row first, then persist.
        let mut changes: Vec<(i64, Vec<Value>)> = Vec::new();
        for r in &rows {
            let ctx = r.ctx(&columns, params).with_subqueries(self);
            if let Some(pred) = &upd.where_clause {
                if eval::truth(&eval::eval(pred, &ctx)?) != Some(true) {
                    continue;
                }
            }
            // Every SET RHS evaluates against the original row (simultaneous).
            let mut values = r.values.clone();
            for (pos, expr) in &assigns {
                values[*pos] = eval::eval(expr, &ctx)?;
            }
            let rowid = r
                .rowid
                .ok_or_else(|| Error::Error("virtual-table row has no rowid".into()))?;
            changes.push((rowid, values));
        }
        // R-Tree with no aux columns: rebuild the node tree (delete old + insert
        // new; the `id` column may move the rowid).
        let arg_refs: Vec<&str> = args.iter().map(String::as_str).collect();
        let rtree_nc = (module_name.eq_ignore_ascii_case("rtree")
            || module_name.eq_ignore_ascii_case("rtree_i32"))
        .then(|| crate::vtab::RTreeModule::n_coords(&arg_refs))
        .filter(|n| columns.len() == 1 + n);
        if let Some(n_coord) = rtree_nc {
            let integer = module_name.eq_ignore_ascii_case("rtree_i32");
            let mut deletes = Vec::with_capacity(changes.len());
            let mut inserts = Vec::with_capacity(changes.len());
            for (old_rowid, values) in &changes {
                deletes.push(*old_rowid);
                let new_rid = match values.first() {
                    Some(Value::Null) | None => *old_rowid,
                    Some(v) => eval::to_i64(v),
                };
                inserts.push(rtree_cell_from_values(new_rid, values, n_coord, integer)?);
            }
            self.rtree_apply(&upd.table, n_coord, integer, inserts, &deletes)?;
            return Ok(changes.len());
        }
        let updated = self.with_vtab_store(
            &module_name,
            &args,
            &upd.table,
            |module, store, arg_refs| {
                for (rowid, values) in &changes {
                    module.dyn_update(
                        arg_refs,
                        VTabChange::Update {
                            rowid: *rowid,
                            new_rowid: *rowid,
                            values,
                        },
                        store,
                    )?;
                }
                Ok(changes.len())
            },
        )?;
        self.fts5_maybe_rebuild(&module_name, &upd.table)?;
        Ok(updated)
    }

    /// D2b-2: try to answer a `MATCH` over the FTS5 table `name` from its segment
    /// index instead of scanning every `_content` document. Returns
    /// `Some(rows)` (the matching `_content` rows, leading `id` column dropped,
    /// in ascending rowid order — exactly the scan's order) for the shapes proven
    /// to give identical results: a TABLE-WIDE, SINGLE BARE-TERM query
    /// (`tbl MATCH 'word'`) — matched in any column — a COLUMN-SCOPED single
    /// bare term (`tbl MATCH 'col : word'`) — matched only in the named column — and
    /// a TWO-TERM PHRASE, table-wide (`tbl MATCH '"a b"'`) or column-scoped
    /// (`tbl MATCH 'col : "a b"'`) — the two tokens at adjacent positions in some /
    /// the named column — all over a fully-indexed table whose `_data` holds a
    /// single height-0 segment. Returns `None` (the caller falls back to the
    /// document scan) for every other case — a `col MATCH …` operand, an `UNINDEXED`
    /// column, a phrase of ≠2 terms, a prefix/anchor inside the phrase, a `NEAR`
    /// group that is not exactly two single-token bare operands, multiple column
    /// filters, a multi-segment or interior/doclist-index index, or no `MATCH` at
    /// all.
    ///
    /// Correctness: for a lone bare term over a fully-indexed table the scan's
    /// per-row predicate ([`crate::vtab::fts5_query_matches`]) is true iff the
    /// token appears in some column — exactly the term's index doclist; for a
    /// `col:word` filter it is true iff the token appears in that one column —
    /// exactly the postings whose per-column position list for that column is
    /// non-empty. run_core re-applies the full WHERE to whatever this returns, so
    /// the result is a superset and never wrong; the rowid-ascending order matches
    /// the scan.
    #[cfg(feature = "fts5")]
    fn fts5_try_index_match(
        &self,
        name: &str,
        alias: Option<&str>,
        arg_refs: &[&str],
        pushdown: Option<(&Select, &Params)>,
    ) -> Result<Option<Vec<InputRow>>> {
        let (sel, params) = match pushdown {
            Some(p) => p,
            None => return Ok(None),
        };
        let where_expr = match sel.where_clause.as_ref() {
            Some(e) => e,
            None => return Ok(None),
        };
        // The query must be a MATCH whose operand names the TABLE (a table-wide
        // search) — its name or its FROM alias — not a single `col MATCH …` (which
        // scopes to one column and so does not equal the term's any-column
        // doclist).
        let (query, operand) = match self.fts5_match_query(where_expr, params) {
            Some(qo) => qo,
            None => return Ok(None),
        };
        let names_table = operand.eq_ignore_ascii_case(name)
            || alias.is_some_and(|a| operand.eq_ignore_ascii_case(a));
        if !names_table {
            return Ok(None);
        }
        // Only fully-indexed tables: an `UNINDEXED` column is stored but excluded
        // from the scan's any-column match, while graphite indexes every column —
        // so the doclist would over-match. Leave those on the scan.
        let indexed = crate::vtab::fts5_indexed_columns(arg_refs);
        let ncols = self.vtab_meta(name)?.2.columns.len();
        if indexed.len() != ncols {
            return Ok(None);
        }
        let tok = crate::vtab::fts5_tok_config(arg_refs);
        // Index-routable shapes over the term reader:
        //   * a TABLE-WIDE single bare term (`'word'`) — matches in ANY column;
        //   * a COLUMN-SCOPED single bare term (`'col : word'`) — matches only in
        //     the named column. The per-column positions in the term's doclist let
        //     us keep exactly the postings carrying a hit in that column;
        //   * a TABLE-WIDE K-term phrase (`'"t0 t1 …"'`, K ≥ 2) — the tokens occur
        //     at CONSECUTIVE positions in some column;
        //   * a COLUMN-SCOPED K-term phrase (`'col : "t0 t1 …"'`) — consecutive in
        //     the named column.
        //   * a TABLE-WIDE two-single-token bare-term `NEAR` group
        //     (`'NEAR(a b, n)'`, default `n = 10`) — the two tokens occur within
        //     `n + 1` positions of each other in some column.
        // Resolve which (if any) applies; anything else stays on the scan.
        enum Routed {
            AnyColumn(Vec<u8>),
            InColumn(Vec<u8>, usize),
            /// A TABLE-WIDE K-term phrase (`'"t0 t1 …"'`, K ≥ 2) — the tokens occur
            /// at CONSECUTIVE positions in some column. The 2-term `'"a b"'` is the
            /// K = 2 instance.
            Phrase(Vec<Vec<u8>>),
            /// A COLUMN-SCOPED K-term phrase (`'col : "t0 t1 …"'`) — consecutive in
            /// the named column.
            PhraseInColumn(Vec<Vec<u8>>, usize),
            /// A TABLE-WIDE two-single-token bare-term `NEAR` group
            /// (`'NEAR(a b, n)'`, default `n = 10`) — the two tokens occur within
            /// `n + 1` positions of each other in some column.
            Near(Vec<u8>, Vec<u8>, u32),
            /// An N-operand bare-term boolean TREE (`a AND b AND c`,
            /// `(a OR b) AND NOT c`, the two-operand `a AND/OR/NOT b`, the
            /// implicit-AND `a b c`, …) served by bottom-up doclist set-ops over
            /// the leaves' rowid lists, exactly as the scan's `fts5_eval` walks it.
            BoolTree(crate::vtab::Fts5BoolTree),
            /// A TABLE-WIDE single bare prefix term (`'word*'`) — matches in ANY
            /// column any document with an indexed term starting with the prefix.
            PrefixAnyColumn(Vec<u8>),
            /// A COLUMN-SCOPED single bare prefix term (`'col : word*'`) — restricted
            /// to a prefix hit in the named column.
            PrefixInColumn(Vec<u8>, usize),
        }
        // Resolve a column NAME to its position in the table's full column list (the
        // same index the writer records positions under). A name that is not a
        // column matches no document — but rather than build that empty result here,
        // fall back to the scan (which yields the same empty set).
        let resolve_col = |col: &str| -> Result<Option<usize>> {
            Ok(self
                .vtab_meta(name)?
                .2
                .columns
                .iter()
                .position(|c| c.eq_ignore_ascii_case(col)))
        };
        let routed = if let Some(t) = crate::vtab::fts5_single_bare_term(&query, tok) {
            Routed::AnyColumn(t)
        } else if let Some((col, t)) = crate::vtab::fts5_single_bare_term_column(&query, tok) {
            match resolve_col(&col)? {
                Some(ci) => Routed::InColumn(t, ci),
                None => return Ok(None),
            }
        } else if let Some(terms) = crate::vtab::fts5_phrase_terms(&query, tok) {
            Routed::Phrase(terms)
        } else if let Some((col, terms)) = crate::vtab::fts5_phrase_terms_column(&query, tok) {
            match resolve_col(&col)? {
                Some(ci) => Routed::PhraseInColumn(terms, ci),
                None => return Ok(None),
            }
        } else if let Some((a, b, n)) = crate::vtab::fts5_two_term_near(&query, tok) {
            Routed::Near(a, b, n as u32)
        } else if let Some(tree) = crate::vtab::fts5_bare_term_bool_tree(&query, tok) {
            // Any boolean tree of table-wide bare terms (2 operands or N, with
            // parentheses / mixed AND/OR/NOT). The single-bare-term shapes are
            // already handled above, so this fires only for genuine boolean trees.
            Routed::BoolTree(tree)
        } else if let Some(p) = crate::vtab::fts5_single_prefix_term(&query, tok) {
            Routed::PrefixAnyColumn(p)
        } else if let Some((col, p)) = crate::vtab::fts5_single_prefix_term_column(&query, tok) {
            match resolve_col(&col)? {
                Some(ci) => Routed::PrefixInColumn(p, ci),
                None => return Ok(None),
            }
        } else {
            return Ok(None);
        };
        // Read the segment index (`_data`) and resolve the matching rowids. A `None`
        // means the index shape isn't servable → fall back to the scan.
        let dmeta = self.table_meta(&format!("{name}_data"), None)?;
        let data: Vec<(i64, Vec<u8>)> = self
            .scan_table(&dmeta)?
            .into_iter()
            .filter_map(|(rowid, mut values)| {
                // `_data` is `(id INTEGER PRIMARY KEY, block BLOB)`; the id is the
                // rowid, the block is the second column.
                match values.drain(..).nth(1) {
                    Some(Value::Blob(b)) => Some((rowid, b)),
                    _ => None,
                }
            })
            .collect();
        let rowids_opt = match &routed {
            Routed::AnyColumn(term) => crate::fts5_index::lookup_term_rowids(&data, term),
            Routed::InColumn(term, ci) => {
                crate::fts5_index::lookup_term_rowids_in_column(&data, term, *ci)
            }
            Routed::Phrase(terms) => {
                let refs: Vec<&[u8]> = terms.iter().map(Vec::as_slice).collect();
                crate::fts5_index::lookup_phrase_rowids_k(&data, &refs)
            }
            Routed::PhraseInColumn(terms, ci) => {
                let refs: Vec<&[u8]> = terms.iter().map(Vec::as_slice).collect();
                crate::fts5_index::lookup_phrase_rowids_in_column_k(&data, &refs, *ci)
            }
            Routed::Near(a, b, n) => crate::fts5_index::lookup_near_rowids(&data, a, b, *n),
            Routed::BoolTree(tree) => crate::fts5_index::lookup_bool_tree_rowids(&data, tree),
            Routed::PrefixAnyColumn(p) => crate::fts5_index::lookup_prefix_rowids(&data, p),
            Routed::PrefixInColumn(p, ci) => {
                crate::fts5_index::lookup_prefix_rowids_in_column(&data, p, *ci)
            }
        };
        let rowids = match rowids_opt {
            Some(r) => r,
            None => return Ok(None),
        };
        // Fetch exactly the matching `_content` rows, by rowid, ascending (the
        // doclist is already ascending). Drop the leading `id` column.
        let cmeta = self.table_meta(&format!("{name}_content"), None)?;
        let encoding = self.backend.source().header().text_encoding;
        let mut rows = Vec::with_capacity(rowids.len());
        let mut cur = TableCursor::new(self.backend.source(), cmeta.root);
        for rid in rowids {
            if cur.seek(rid)? {
                let mut values = self.decode_full_row(&cmeta, rid, &cur.payload()?, encoding)?;
                if !values.is_empty() {
                    values.remove(0);
                }
                rows.push(InputRow {
                    values,
                    rowid: Some(rid),
                });
            }
            // A doclist rowid with no `_content` row can't happen for a consistent
            // index; if it ever did, omitting it is still a valid superset (the
            // scan wouldn't have produced it either).
        }
        Ok(Some(rows))
    }

    /// Produce the columns and rows of a virtual table used as a `FROM` source:
    /// reparse its stored `CREATE VIRTUAL TABLE`, look the module up in the
    /// registry, `connect` for its column schema, then `open` a cursor and drain
    /// it. Returns `Ok(None)` when `name` is not a virtual table.
    ///
    /// `pushdown`, when given as `Some((sel, params))`, lets the module restrict
    /// what it produces from the query's `WHERE` (constraint pushdown via
    /// [`best_index`](crate::vtab::VTabModule::best_index) /
    /// [`filter`](crate::vtab::VTabModule::filter)). The plan is always a superset:
    /// the caller's `run_core` re-applies the full `WHERE`, so even a partially
    /// consumed or ignored constraint stays correct.
    fn try_virtual_table(
        &self,
        name: &str,
        alias: Option<&str>,
        pushdown: Option<(&Select, &Params)>,
    ) -> Result<Option<(Vec<ColumnInfo>, Vec<InputRow>)>> {
        use crate::schema::ObjectType;
        let obj = match self
            .schema
            .objects()
            .iter()
            .find(|o| o.obj_type == ObjectType::Table && o.name.eq_ignore_ascii_case(name))
        {
            Some(o) => o,
            None => return Ok(None),
        };
        let sql = match obj.sql.as_deref() {
            Some(s) => s,
            None => return Ok(None),
        };
        let cvt = match sql::parse_one(sql) {
            Ok(Statement::CreateVirtualTable(cvt)) => cvt,
            _ => return Ok(None),
        };
        // `fts5vocab` is derived from another FTS5 table's documents; compute it
        // here (the module's cursor has no database access).
        #[cfg(feature = "fts5")]
        if cvt.module.eq_ignore_ascii_case("fts5vocab") {
            return Ok(Some(self.scan_fts5vocab(&cvt.args, name, alias)?));
        }
        let module = self
            .vtab_registry
            .get(&cvt.module)
            .ok_or_else(|| Error::Error(format!("no such module: {}", cvt.module)))?;
        let arg_refs: Vec<&str> = cvt.args.iter().map(String::as_str).collect();
        let schema = module.dyn_connect(&arg_refs)?;
        let label = alias.unwrap_or(name).to_string();
        let columns: Vec<ColumnInfo> = schema
            .columns
            .iter()
            .map(|n| ColumnInfo {
                name: n.clone(),
                table: label.clone(),
                affinity: eval::Affinity::Blob,
                collation: crate::value::Collation::default(),
            })
            .collect();
        // A persistent module keeps its rows in the `<vtab>_data` backing table;
        // scan that directly (run_core re-applies the full WHERE, so the rows are
        // a valid superset). Computed modules go through the cursor path below.
        if module.dyn_persistent() {
            // An R-Tree written by SQLite keeps its entries in the `<name>_node`
            // b-tree of nodes (byte-compatible on-disk format), not graphite's
            // generic `<name>_data` backing table. Read the node tree directly so
            // graphite can query a sqlite-written R-Tree. (No-aux R-Trees only;
            // aux columns live in `<name>_rowid` — handled when graphite also
            // writes the node format.)
            let rtree = cvt.module.eq_ignore_ascii_case("rtree")
                || cvt.module.eq_ignore_ascii_case("rtree_i32");
            if rtree
                && self.schema.table(&format!("{name}_node")).is_some()
                && self.schema.table(&format!("{name}_data")).is_none()
            {
                let n_coords = crate::vtab::RTreeModule::n_coords(&arg_refs);
                if columns.len() == 1 + n_coords {
                    let integer = cvt.module.eq_ignore_ascii_case("rtree_i32");
                    // Spatial pushdown: turn the query's coordinate comparisons into
                    // per-dimension bounds the node walk uses to prune subtrees.
                    // Column 0 is the rowid/id; columns 1.. are the coordinates.
                    let bbox: Vec<(usize, ConstraintOp, f64)> = match pushdown {
                        Some((sel, params)) => {
                            let (cs, vs) = collect_vtab_constraints(sel, &columns, params);
                            cs.iter()
                                .zip(vs)
                                .filter_map(|(c, v)| {
                                    let ci = c.column.checked_sub(1)?;
                                    if ci >= n_coords {
                                        return None;
                                    }
                                    let fv = match v {
                                        Value::Integer(i) => i as f64,
                                        Value::Real(r) => r,
                                        _ => return None,
                                    };
                                    matches!(
                                        c.op,
                                        ConstraintOp::Eq
                                            | ConstraintOp::Gt
                                            | ConstraintOp::Le
                                            | ConstraintOp::Lt
                                            | ConstraintOp::Ge
                                    )
                                    .then_some((ci, c.op, fv))
                                })
                                .collect()
                        }
                        None => Vec::new(),
                    };
                    let rows = self.scan_rtree_nodes(name, n_coords, integer, &bbox)?;
                    return Ok(Some((columns, rows)));
                }
            }
            // A SQLite-written FTS5 keeps its documents in `<name>_content`
            // (`id, c0, c1, …`), with the inverted index in `<name>_data`/`_idx`.
            // graphite answers queries — including `MATCH` — from the documents via
            // its scan-based matcher, so reading the content is sufficient.
            // (graphite's own FTS5 has no `_content`; it stores docs in `_data`.)
            #[cfg(feature = "fts5")]
            if cvt.module.eq_ignore_ascii_case("fts5")
                && self.schema.table(&format!("{name}_content")).is_some()
            {
                // D2b-2: a single bare-term `MATCH` (`tbl MATCH 'word'`) reads the
                // term's doclist from the segment index and fetches only those
                // `_content` rows by rowid, instead of scanning + tokenizing every
                // document. Falls back to the full scan for any shape the index
                // can't serve identically. run_core re-applies the full WHERE, so
                // the rows (rowid-ascending, like the scan) stay a valid superset.
                if let Some(rows) = self.fts5_try_index_match(name, alias, &arg_refs, pushdown)? {
                    return Ok(Some((columns, rows)));
                }
                let cmeta = self.table_meta(&format!("{name}_content"), None)?;
                let rows = self
                    .scan_table(&cmeta)?
                    .into_iter()
                    .map(|(rowid, mut values)| {
                        // Drop the leading `id` column; the rest are the fts5 columns.
                        if !values.is_empty() {
                            values.remove(0);
                        }
                        InputRow {
                            values,
                            rowid: Some(rowid),
                        }
                    })
                    .collect();
                return Ok(Some((columns, rows)));
            }
            let backing = format!("{name}_data");
            let bmeta = self.table_meta(&backing, None)?;
            let rows = self
                .scan_table(&bmeta)?
                .into_iter()
                .map(|(rowid, values)| InputRow {
                    values,
                    rowid: Some(rowid),
                })
                .collect();
            return Ok(Some((columns, rows)));
        }
        // Constraint pushdown: offer the WHERE's usable comparisons to the module,
        // let it choose a plan, then hand back the bound values it requested.
        let (constraints, bound_values) = match pushdown {
            Some((sel, params)) => collect_vtab_constraints(sel, &columns, params),
            None => (Vec::new(), Vec::new()),
        };
        let plan = module.dyn_best_index(&constraints)?;
        let argv = order_vtab_argv(&plan, &bound_values);
        let mut cursor = module.dyn_open(&arg_refs, &plan, &argv)?;
        let ncols = columns.len();
        let mut rows = Vec::new();
        while let Some(row) = cursor.dyn_next()? {
            let values = (0..ncols).map(|i| row.dyn_column(i)).collect();
            rows.push(InputRow {
                values,
                rowid: Some(row.dyn_rowid()),
            });
        }
        Ok(Some((columns, rows)))
    }

    /// Materialize each `WITH` CTE of `sel` into the environment, in declaration
    /// order (so a later CTE may reference an earlier one). Recursive CTEs are
    /// evaluated with the fixed-point loop.
    /// Materialize `ctes` into the environment. `outer_cap` (the consuming query's
    /// `LIMIT`+`OFFSET`, set only when that query streams the CTE 1:1 — see
    /// `recursive_cte_outer_cap`) bounds an otherwise-infinite recursive CTE so a
    /// `SELECT … FROM rcte LIMIT k` over an unterminated recursion yields `k` rows
    /// like sqlite instead of running to the runaway guard.
    fn push_ctes(&self, ctes: &[Cte], params: &Params, outer_cap: Option<usize>) -> Result<()> {
        for cte in ctes {
            let binding = if references_name(&cte.select, &cte.name) {
                self.eval_recursive_cte(cte, params, outer_cap)?
            } else {
                self.materialize_plain_cte(cte, params)?
            };
            self.cte_env.borrow_mut().push(binding);
        }
        Ok(())
    }

    /// Look up a CTE by name in the current environment (innermost first),
    /// returning a copy of its columns + rows relabeled to `alias` if given.
    fn lookup_cte(
        &self,
        name: &str,
        alias: Option<&str>,
    ) -> Option<(Vec<ColumnInfo>, Vec<InputRow>)> {
        let env = self.cte_env.borrow();
        let b = env
            .iter()
            .rev()
            .find(|b| b.name.eq_ignore_ascii_case(name))?;
        let label = alias.unwrap_or(&b.name);
        let columns = b
            .columns
            .iter()
            .map(|c| ColumnInfo {
                name: c.name.clone(),
                table: label.to_string(),
                affinity: c.affinity,
                collation: c.collation,
            })
            .collect();
        Some((columns, b.rows.clone()))
    }

    /// Build the column metadata for a CTE from its body's output labels (or its
    /// explicit `(col, …)` list), labeled with the CTE name.
    fn cte_columns(&self, cte: &Cte, body_cols: &[String]) -> Result<Vec<ColumnInfo>> {
        let names = if cte.columns.is_empty() {
            body_cols.to_vec()
        } else {
            // An explicit column list must match the body's column count, as in
            // SQLite (`table t has N values for M columns`).
            if cte.columns.len() != body_cols.len() {
                return Err(Error::Error(alloc::format!(
                    "table {} has {} values for {} columns",
                    cte.name,
                    body_cols.len(),
                    cte.columns.len()
                )));
            }
            cte.columns.clone()
        };
        Ok(names
            .into_iter()
            .map(|n| ColumnInfo {
                name: n,
                table: cte.name.clone(),
                affinity: eval::Affinity::Blob,
                collation: crate::value::Collation::default(),
            })
            .collect())
    }

    /// A non-recursive CTE: run its body once.
    fn materialize_plain_cte(&self, cte: &Cte, params: &Params) -> Result<CteBinding> {
        let result = self.run_select(&cte.select, params)?;
        let columns = self.cte_columns(cte, &result.columns)?;
        let rows = result
            .rows
            .into_iter()
            .map(|values| InputRow {
                values,
                rowid: None,
            })
            .collect();
        Ok(CteBinding {
            name: cte.name.clone(),
            columns,
            rows,
        })
    }

    /// A recursive CTE: `anchor [UNION [ALL] recursive]`. Evaluate the anchor,
    /// then repeatedly evaluate the recursive term against the rows produced by
    /// the previous step (bound to the CTE's name) until no new rows appear.
    fn eval_recursive_cte(
        &self,
        cte: &Cte,
        params: &Params,
        outer_cap: Option<usize>,
    ) -> Result<CteBinding> {
        // Flatten the body into arms: (op-before-this-arm, select). The first
        // arm has no preceding op.
        let mut arms: Vec<(Option<CompoundOp>, Select)> = Vec::new();
        let mut base = (*cte.select).clone();
        // A LIMIT/OFFSET on the CTE definition bounds the rows it produces — and
        // crucially terminates an otherwise-infinite recursion. Capture them
        // before stripping the per-arm clauses below. (A negative LIMIT means
        // "no limit", as elsewhere in SQLite.)
        let rec_limit = match &base.limit {
            Some(e) => {
                let n = must_be_int(eval::eval(
                    e,
                    &EvalCtx::rowless(params).with_subqueries(self),
                )?)?;
                (n >= 0).then_some(n as usize)
            }
            None => None,
        };
        let rec_offset = match &base.offset {
            Some(e) => must_be_int(eval::eval(
                e,
                &EvalCtx::rowless(params).with_subqueries(self),
            )?)?
            .max(0) as usize,
            None => 0,
        };
        let compound = core::mem::take(&mut base.compound);
        base.order_by.clear();
        base.limit = None;
        base.offset = None;
        arms.push((None, base));
        for (op, mut s) in compound {
            s.order_by.clear();
            s.limit = None;
            s.offset = None;
            arms.push((Some(op), s));
        }

        // Partition into leading anchor arms and trailing recursive arms.
        let mut anchor: Vec<Select> = Vec::new();
        let mut recursive: Vec<Select> = Vec::new();
        let mut rec_distinct = false;
        let mut in_rec = false;
        for (op, s) in arms {
            if !in_rec && references_name_select(&s, &cte.name) {
                in_rec = true;
                rec_distinct = matches!(op, Some(CompoundOp::Union));
            }
            if in_rec {
                recursive.push(s);
            } else {
                anchor.push(s);
            }
        }
        if anchor.is_empty() || recursive.is_empty() {
            return Err(Error::Unsupported(
                "recursive CTE must have a non-recursive anchor and a recursive term",
            ));
        }

        // Evaluate the anchor (a compound of the anchor arms).
        let mut anchor_rows: Vec<Vec<Value>> = Vec::new();
        for a in &anchor {
            let r = self.run_select(a, params)?;
            anchor_rows.extend(r.rows);
        }
        let body_cols = self.run_select(&anchor[0], params)?.columns;
        let columns = self.cte_columns(cte, &body_cols)?;

        if rec_distinct {
            dedup_rows(&mut anchor_rows);
        }
        let mut all_rows = anchor_rows.clone();
        let mut working = anchor_rows;

        // Push a working binding the recursive term resolves against; update it
        // each iteration. Guard against runaway recursion.
        let slot = self.cte_env.borrow().len();
        self.cte_env.borrow_mut().push(CteBinding {
            name: cte.name.clone(),
            columns: columns.clone(),
            rows: Vec::new(),
        });
        let mut guard = 0usize;
        let result = loop {
            guard += 1;
            if guard > 1_000_000 {
                self.cte_env.borrow_mut().truncate(slot);
                return Err(Error::Error("recursive CTE did not terminate".into()));
            }
            // Bind the working set.
            self.cte_env.borrow_mut()[slot].rows = working
                .iter()
                .cloned()
                .map(|values| InputRow {
                    values,
                    rowid: None,
                })
                .collect();

            let mut produced: Vec<Vec<Value>> = Vec::new();
            for r in &recursive {
                match self.run_select(r, params) {
                    Ok(res) => produced.extend(res.rows),
                    Err(e) => {
                        self.cte_env.borrow_mut().truncate(slot);
                        return Err(e);
                    }
                }
            }
            // Keep only genuinely new rows (for UNION; UNION ALL keeps all but
            // still must terminate — SQLite requires the recursive query to
            // eventually produce nothing).
            let mut fresh: Vec<Vec<Value>> = Vec::new();
            for row in produced {
                if rec_distinct && all_rows.iter().any(|s| rows_equal(s, &row)) {
                    continue;
                }
                fresh.push(row);
            }
            if fresh.is_empty() {
                break Ok(());
            }
            all_rows.extend(fresh.iter().cloned());
            working = fresh;
            // Stop once the CTE's LIMIT (after OFFSET) is satisfied.
            if let Some(lim) = rec_limit {
                if all_rows.len() >= rec_offset.saturating_add(lim) {
                    break Ok(());
                }
            }
            // Stop once the consuming query's LIMIT (+OFFSET) is satisfied — this
            // terminates an otherwise-infinite recursion `SELECT … FROM rcte LIMIT k`.
            if let Some(cap) = outer_cap {
                if all_rows.len() >= cap {
                    break Ok(());
                }
            }
        };
        self.cte_env.borrow_mut().truncate(slot);
        result?;

        // Apply the CTE definition's OFFSET/LIMIT to the produced rows.
        if rec_offset > 0 {
            all_rows.drain(..rec_offset.min(all_rows.len()));
        }
        if let Some(lim) = rec_limit {
            all_rows.truncate(lim);
        }

        let rows = all_rows
            .into_iter()
            .map(|values| InputRow {
                values,
                rowid: None,
            })
            .collect();
        Ok(CteBinding {
            name: cte.name.clone(),
            columns,
            rows,
        })
    }

    /// If `name` is a view, run its `SELECT` and return its columns + rows.
    /// A temp view shadows a main view of the same name (like a temp table), and
    /// is read through its own (temp) database via [`scan_db_view`](Self::scan_db_view).
    fn try_view(
        &self,
        name: &str,
        alias: Option<&str>,
        params: &Params,
    ) -> Result<Option<(Vec<ColumnInfo>, Vec<InputRow>)>> {
        use crate::schema::ObjectType;
        if self.temp_has_view(name) {
            return self.scan_db_view(DbRef::Temp, name, alias, params);
        }
        let obj = match self
            .schema
            .objects()
            .iter()
            .find(|o| o.obj_type == ObjectType::View && o.name.eq_ignore_ascii_case(name))
        {
            Some(o) => o.clone(),
            None => return Ok(None),
        };
        let sql = obj
            .sql
            .as_deref()
            .ok_or_else(|| Error::Corrupt("view has no CREATE statement".into()))?;
        let Statement::CreateView(cv) = sql::parse_one(sql)? else {
            return Err(Error::Corrupt("schema sql is not CREATE VIEW".into()));
        };
        let result = self.run_select(&cv.select, params)?;
        let label = alias.unwrap_or(name).to_string();
        // Column names: explicit view columns, else the SELECT's output labels.
        let names = if cv.columns.is_empty() {
            result.columns.clone()
        } else {
            cv.columns.clone()
        };
        // A view column inherits the affinity AND collation of its defining
        // expression's origin (a direct column reference takes its base column's),
        // exactly as a derived-table subquery does — so `ORDER BY`/`WHERE`/`min`/
        // `max` over the view honor a NOCASE base column. Explicit `(col, …)` names
        // only rename; the origin is positional from the body.
        let origins = self.subquery_column_origins(&cv.select);
        let columns: Vec<ColumnInfo> = names
            .into_iter()
            .enumerate()
            .map(|(i, n)| {
                let (affinity, collation) = origins
                    .as_ref()
                    .and_then(|o| o.get(i).copied())
                    .unwrap_or((eval::Affinity::Blob, crate::value::Collation::default()));
                ColumnInfo {
                    name: n,
                    table: label.clone(),
                    affinity,
                    collation,
                }
            })
            .collect();
        let rows = result
            .rows
            .into_iter()
            .map(|values| InputRow {
                values,
                rowid: None,
            })
            .collect();
        Ok(Some((columns, rows)))
    }

    fn exec_drop(&mut self, d: &Drop) -> Result<()> {
        use crate::schema::ObjectType;
        // Dropping a persistent virtual table also drops its shadow tables, as
        // sqlite does: the generic `<name>_data` backing, or an R-Tree's
        // `_node`/`_rowid`/`_parent` node tables.
        if matches!(d.kind, DropKind::Table) && self.is_virtual_table(&d.name) {
            for suffix in [
                "_data", "_node", "_rowid", "_parent", "_content", "_docsize", "_config", "_idx",
            ] {
                let backing = format!("{}{suffix}", d.name);
                if self.schema.table(&backing).is_some() {
                    self.exec_drop(&Drop {
                        kind: DropKind::Table,
                        if_exists: false,
                        name: backing,
                        schema: d.schema.clone(),
                    })?;
                }
            }
        }
        let want = match d.kind {
            DropKind::Table => ObjectType::Table,
            DropKind::Index => ObjectType::Index,
            DropKind::View => ObjectType::View,
            DropKind::Trigger => ObjectType::Trigger,
        };
        // Find the object (and, for a table, its dependent indexes) to remove.
        let target = self
            .schema
            .objects()
            .iter()
            .find(|o| o.obj_type == want && o.name == d.name)
            .cloned();
        let Some(obj) = target else {
            // SQLite's table↔view confusion hint when a same-named object of the
            // other kind exists. This fires even with `IF EXISTS` — that clause
            // suppresses a *missing* object, not a *wrong-type* one.
            if let Some(other) = self.schema.objects().iter().find(|o| o.name == d.name) {
                match (d.kind, other.obj_type) {
                    (DropKind::Table, ObjectType::View) => {
                        return Err(Error::Error(format!(
                            "use DROP VIEW to delete view {}",
                            d.name
                        )))
                    }
                    (DropKind::View, ObjectType::Table) => {
                        return Err(Error::Error(format!(
                            "use DROP TABLE to delete table {}",
                            d.name
                        )))
                    }
                    _ => {}
                }
            }
            if d.if_exists {
                return Ok(());
            }
            let kind = match d.kind {
                DropKind::Table => "table",
                DropKind::Index => "index",
                DropKind::View => "view",
                DropKind::Trigger => "trigger",
            };
            return Err(Error::Error(format!("no such {kind}: {}", d.name)));
        };

        // Collect the schema rows (by rowid) and b-tree roots to drop.
        let mut roots_to_free = Vec::new();
        let mut names_to_remove = Vec::new();
        roots_to_free.push(obj.rootpage);
        names_to_remove.push(obj.name.clone());
        if want == ObjectType::Table {
            for idx in self.schema.indexes_on(&obj.name) {
                roots_to_free.push(idx.rootpage);
                names_to_remove.push(idx.name.clone());
            }
            // Triggers on the table are dropped with it (SQLite cascades these).
            for o in self.schema.objects() {
                if o.obj_type == ObjectType::Trigger && o.tbl_name.eq_ignore_ascii_case(&obj.name) {
                    roots_to_free.push(o.rootpage); // triggers have rootpage 0
                    names_to_remove.push(o.name.clone());
                }
            }
        }
        // Map names -> sqlite_schema rowids (scan page 1).
        let victim_rowids = self.schema_rowids_for(&names_to_remove)?;

        let w = self.backend.writer()?;
        for root in roots_to_free {
            if root != 0 {
                free_tree(w, root)?;
            }
        }
        for rid in victim_rowids {
            delete_table(w, crate::schema::SCHEMA_ROOT_PAGE, rid)?;
        }
        let cookie = w.header().schema_cookie.wrapping_add(1);
        w.header_mut().schema_cookie = cookie;
        self.schema = Schema::read(self.backend.source())?;
        // Dropping a table also removes its AUTOINCREMENT row from
        // `sqlite_sequence`, like SQLite.
        if want == ObjectType::Table && self.schema.table("sqlite_sequence").is_some() {
            let root = self.schema.table("sqlite_sequence").unwrap().rootpage;
            let meta = self.table_meta("sqlite_sequence", None)?;
            let victims: Vec<i64> = self
                .scan_table(&meta)?
                .into_iter()
                .filter(|(_, v)| matches!(&v[0], Value::Text(t) if t == &obj.name))
                .map(|(rid, _)| rid)
                .collect();
            for rid in victims {
                delete_table(self.backend.writer()?, root, rid)?;
            }
        }
        Ok(())
    }

    fn exec_alter(&mut self, a: &Alter) -> Result<()> {
        // A virtual table can be renamed (sqlite renames its backing tables too),
        // but not otherwise altered — and it isn't a CREATE TABLE, so it must not
        // reach the regular path below.
        if self.is_virtual_table(&a.table) {
            if let AlterAction::RenameTable(new_name) = &a.action {
                return self.rename_virtual_table(&a.table, new_name);
            }
            return Err(Error::Error("virtual tables may not be altered".into()));
        }
        let obj = self
            .schema
            .table(&a.table)
            .cloned()
            .ok_or_else(|| Error::Error(format!("no such table: {}", a.table)))?;
        let sql = obj
            .sql
            .as_deref()
            .ok_or_else(|| Error::Corrupt("table has no CREATE statement".into()))?;
        let Statement::CreateTable(mut ct) = sql::parse_one(sql)? else {
            return Err(Error::Corrupt("schema sql is not CREATE TABLE".into()));
        };

        if let AlterAction::DropColumn(name) = &a.action {
            return self.exec_drop_column(a, ct, name);
        }
        match &a.action {
            AlterAction::DropColumn(_) => unreachable!("handled above"),
            AlterAction::AddColumn(cd, col_text) => {
                if ct
                    .columns
                    .iter()
                    .any(|c| c.name.eq_ignore_ascii_case(&cd.name))
                {
                    return Err(Error::Error(format!("duplicate column name: {}", cd.name)));
                }
                // SQLite forbids a few constraints on ADD COLUMN: a UNIQUE or
                // PRIMARY KEY column is always rejected; a NOT NULL column whose
                // default is NULL is rejected only when the table already has
                // rows (which would otherwise hold a NULL).
                for k in &cd.constraints {
                    match k {
                        ColumnConstraint::Unique(_) => {
                            return Err(Error::Error("Cannot add a UNIQUE column".into()));
                        }
                        ColumnConstraint::PrimaryKey { .. } => {
                            return Err(Error::Error("Cannot add a PRIMARY KEY column".into()));
                        }
                        _ => {}
                    }
                }
                let not_null = cd
                    .constraints
                    .iter()
                    .any(|k| matches!(k, ColumnConstraint::NotNull(_)));
                if not_null {
                    let default = cd.constraints.iter().find_map(|k| match k {
                        ColumnConstraint::Default(e) => Some(e),
                        _ => None,
                    });
                    let no_params = Params::default();
                    let default_is_null = match default {
                        None => true,
                        Some(e) => {
                            let ctx = EvalCtx::rowless(&no_params).with_subqueries(self);
                            matches!(eval::eval(e, &ctx), Ok(Value::Null) | Err(_))
                        }
                    };
                    if default_is_null && !self.table_is_empty(&a.table)? {
                        return Err(Error::Error(
                            "Cannot add a NOT NULL column with default value NULL".into(),
                        ));
                    }
                }
                ct.columns.push(cd.clone());
                // Append the new column's verbatim text to the stored CREATE (like
                // sqlite); fall back to reprinting from the AST if its source or
                // the column-list close can't be located.
                let reprint = sql::print::create_table(&ct);
                let table = a.table.clone();
                let col_text = col_text.clone();
                self.rewrite_schema_rows(|cols| {
                    if is_text(&cols[0], "table") && is_text(&cols[1], &table) {
                        let updated = match (&col_text, cols.get(4)) {
                            (Some(t), Some(Value::Text(old))) => {
                                append_column_to_create(old, t).unwrap_or_else(|| reprint.clone())
                            }
                            _ => reprint.clone(),
                        };
                        cols[4] = Value::Text(updated);
                        true
                    } else {
                        false
                    }
                })?;
            }
            AlterAction::RenameTable(new_name) => {
                // The new name must not collide with any existing table or index,
                // including renaming a table to its own name, as in SQLite.
                if self
                    .schema
                    .objects()
                    .iter()
                    .any(|o| o.name.eq_ignore_ascii_case(new_name))
                {
                    return Err(Error::Error(format!(
                        "there is already another table or index with this name: {new_name}"
                    )));
                }
                let old = a.table.clone();
                let new_name = new_name.clone();
                self.rewrite_schema_rows(|cols| {
                    if is_text(&cols[0], "table") && is_text(&cols[1], &old) {
                        cols[1] = Value::Text(new_name.clone());
                        cols[2] = Value::Text(new_name.clone());
                        // Edit the table name in the stored CREATE text in place
                        // (preserving the body verbatim), like SQLite — rather than
                        // reprinting the whole definition from the AST.
                        if let Some(Value::Text(old_sql)) = cols.get(4).cloned() {
                            // Rename the table token itself, and any self-referential
                            // foreign key (`REFERENCES <old>`) in its own body.
                            let renamed = rename_table_token_after(&old_sql, "table", &new_name);
                            cols[4] = Value::Text(rewrite_fk_references(&renamed, &old, &new_name));
                        }
                        true
                    } else if is_text(&cols[2], &old) {
                        // Dependent index/trigger/view: repoint, and rewrite an
                        // index's `ON` clause / a trigger's body to the new name.
                        cols[2] = Value::Text(new_name.clone());
                        if is_text(&cols[0], "index") {
                            // Repoint the index's `ON <table>` to the new name in
                            // place (preserving the rest), like SQLite.
                            if let Some(Value::Text(isql)) = cols.get(4).cloned() {
                                cols[4] =
                                    Value::Text(rename_table_token_after(&isql, "on", &new_name));
                            }
                        } else if is_text(&cols[0], "trigger") {
                            // A trigger ON the renamed table: rewrite the renamed
                            // name throughout its stored text (the `ON` clause and
                            // any body references), like SQLite.
                            if let Some(Value::Text(tsql)) = cols.get(4).cloned() {
                                cols[4] = Value::Text(rewrite_ident_tokens(
                                    &tsql,
                                    &old,
                                    &sql::print::ident(&new_name),
                                ));
                            }
                        }
                        true
                    } else if is_text(&cols[0], "view") {
                        // A view whose SELECT references the renamed table: rewrite
                        // the table name throughout its stored body (formatting
                        // preserved), so `SELECT … FROM v` keeps working.
                        match cols.get(4).cloned() {
                            Some(Value::Text(vsql)) if view_uses_table(&vsql, &old) => {
                                cols[4] = Value::Text(rewrite_ident_tokens(
                                    &vsql,
                                    &old,
                                    &sql::print::ident(&new_name),
                                ));
                                true
                            }
                            _ => false,
                        }
                    } else if is_text(&cols[0], "trigger") {
                        // A trigger on ANOTHER table whose body references the
                        // renamed table (e.g. `INSERT INTO <table> …`): rewrite the
                        // renamed name throughout its stored text.
                        match cols.get(4).cloned() {
                            Some(Value::Text(tsql)) if trigger_uses_table(&tsql, &old) => {
                                cols[4] = Value::Text(rewrite_ident_tokens(
                                    &tsql,
                                    &old,
                                    &sql::print::ident(&new_name),
                                ));
                                true
                            }
                            _ => false,
                        }
                    } else if is_text(&cols[0], "table") {
                        // Another table whose foreign key targets the renamed table:
                        // repoint its `REFERENCES <old>` to the new name (leaving its
                        // own name and any references to other tables untouched).
                        match cols.get(4).cloned() {
                            Some(Value::Text(tsql)) => {
                                let rewritten = rewrite_fk_references(&tsql, &old, &new_name);
                                if rewritten != tsql {
                                    cols[4] = Value::Text(rewritten);
                                    true
                                } else {
                                    false
                                }
                            }
                            _ => false,
                        }
                    } else {
                        false
                    }
                })?;
            }
            AlterAction::RenameColumn { old, new, new_text } => {
                let pos = ct
                    .columns
                    .iter()
                    .position(|c| c.name.eq_ignore_ascii_case(old))
                    .ok_or_else(|| Error::Error(format!("no such column: {old}")))?;
                // Renaming onto an existing column name is rejected, like SQLite.
                if ct
                    .columns
                    .iter()
                    .enumerate()
                    .any(|(i, c)| i != pos && c.name.eq_ignore_ascii_case(new))
                {
                    return Err(Error::Error(format!("duplicate column name: {new}")));
                }
                ct.columns[pos].name = new.clone();
                // Propagate the rename into the table's own expressions and
                // column lists, which still reference the old name (otherwise the
                // CHECK / generated / default would break after the rename).
                let rename = |e: &mut Expr| rename_column_ref(e, &a.table, old, new);
                for col in &mut ct.columns {
                    for k in &mut col.constraints {
                        match k {
                            ColumnConstraint::Check(e, _) | ColumnConstraint::Default(e) => {
                                rename(e)
                            }
                            ColumnConstraint::Generated { expr, .. } => rename(expr),
                            _ => {}
                        }
                    }
                }
                for tc in &mut ct.constraints {
                    match tc {
                        TableConstraint::PrimaryKey(n, _) | TableConstraint::Unique(n, _) => {
                            for nm in n {
                                if nm.eq_ignore_ascii_case(old) {
                                    *nm = new.clone();
                                }
                            }
                        }
                        TableConstraint::Check(e, _) => rename(e),
                        TableConstraint::ForeignKey(fk) => {
                            for nm in &mut fk.columns {
                                if nm.eq_ignore_ascii_case(old) {
                                    *nm = new.clone();
                                }
                            }
                        }
                    }
                }
                // The AST reprint is only a fallback; normally we edit the stored
                // text in place so the column's formatting is preserved like sqlite.
                let reprint = sql::print::create_table(&ct);
                let table = a.table.clone();
                let old = old.clone();
                let new_text = new_text.clone();
                // Snapshot every base table's column names, so a multi-source view
                // rewrite (A-rn3) can tell whether the renamed column name is
                // unique across a join's sources.
                let table_cols: alloc::collections::BTreeMap<String, Vec<String>> = self
                    .schema
                    .objects()
                    .iter()
                    .filter(|o| o.obj_type == crate::schema::ObjectType::Table)
                    .filter_map(|o| {
                        self.table_meta(&o.name, None).ok().map(|m| {
                            (
                                o.name.clone(),
                                m.columns.iter().map(|c| c.name.clone()).collect(),
                            )
                        })
                    })
                    .collect();
                self.rewrite_schema_rows(|cols| {
                    if is_text(&cols[0], "table") && is_text(&cols[1], &table) {
                        cols[4] = Value::Text(match cols.get(4) {
                            Some(Value::Text(s)) => rewrite_ident_tokens(s, &old, &new_text),
                            _ => reprint.clone(),
                        });
                        true
                    } else if is_text(&cols[0], "index") && is_text(&cols[2], &table) {
                        // Rewrite an index over this table if it names the column.
                        if let Some(Value::Text(isql)) = cols.get(4).cloned() {
                            let rewritten = rewrite_ident_tokens(&isql, &old, &new_text);
                            if rewritten != isql {
                                cols[4] = Value::Text(rewritten);
                                return true;
                            }
                        }
                        false
                    } else if is_text(&cols[0], "table") {
                        // Another table whose foreign key references the renamed
                        // parent column: rewrite `REFERENCES <table>(old)` only.
                        if let Some(Value::Text(csql)) = cols.get(4).cloned() {
                            let rewritten =
                                rewrite_fk_parent_column(&csql, &table, &old, &new_text);
                            if rewritten != csql {
                                cols[4] = Value::Text(rewritten);
                                return true;
                            }
                        }
                        false
                    } else if is_text(&cols[0], "view") {
                        // A single-source view (only the renamed table) rewrites
                        // every reference (bare + qualified). A multi-source view
                        // (a join of base tables) rewrites `<renamed-table>.old`
                        // always, and a bare `old` only when that name is unique
                        // across the sources (A-rn3). Views with subqueries/CTEs/
                        // non-base sources are still left untouched.
                        match cols.get(4).cloned() {
                            Some(Value::Text(vsql)) => {
                                let rewritten = if let Some(quals) =
                                    view_single_source_column_quals(&vsql, &table, &old)
                                {
                                    rewrite_column_tokens(&vsql, &quals, &old, &new_text, true)
                                } else if let Some((quals, bare)) =
                                    view_multi_source_quals(&vsql, &table, &old, &table_cols)
                                {
                                    rewrite_column_tokens(&vsql, &quals, &old, &new_text, bare)
                                } else {
                                    vsql.clone()
                                };
                                if rewritten != vsql {
                                    cols[4] = Value::Text(rewritten);
                                    return true;
                                }
                                false
                            }
                            _ => false,
                        }
                    } else if is_text(&cols[0], "trigger") {
                        // A trigger ON the renamed table whose body references ONLY
                        // that table: NEW/OLD and bare/qualified column refs all
                        // resolve to it, so a full token rewrite is safe and
                        // complete. When the body also touches other tables, the
                        // bare refs are ambiguous, but `NEW.old`/`OLD.old` still
                        // bind to the renamed table, so rewrite just those. (The
                        // remaining multi-source bare/`UPDATE OF` refs are the
                        // A-rn3 remainder.)
                        match cols.get(4).cloned() {
                            Some(Value::Text(tsql)) => {
                                let rewritten = if let Some(quals) =
                                    trigger_single_source_quals(&tsql, &table, &old)
                                {
                                    rewrite_column_tokens(&tsql, &quals, &old, &new_text, true)
                                } else if trigger_on_renamed_table(&tsql, &table, &old) {
                                    rewrite_column_tokens(
                                        &tsql,
                                        &[String::from("NEW"), String::from("OLD")],
                                        &old,
                                        &new_text,
                                        false,
                                    )
                                } else if trigger_body_single_source_over(&tsql, &table, &old) {
                                    // A trigger on ANOTHER table whose body reads/
                                    // writes only the renamed table: every bare and
                                    // `<table>.`-qualified ref binds to it (its own
                                    // NEW/OLD belong to a different table and are
                                    // left alone, as `<table>` is the only qual).
                                    rewrite_column_tokens(
                                        &tsql,
                                        core::slice::from_ref(&table),
                                        &old,
                                        &new_text,
                                        true,
                                    )
                                } else {
                                    tsql.clone()
                                };
                                if rewritten != tsql {
                                    cols[4] = Value::Text(rewritten);
                                    return true;
                                }
                                false
                            }
                            _ => false,
                        }
                    } else {
                        false
                    }
                })?;
            }
        }

        let cookie = self
            .backend
            .writer()?
            .header()
            .schema_cookie
            .wrapping_add(1);
        self.backend.writer()?.header_mut().schema_cookie = cookie;
        self.schema = Schema::read(self.backend.source())?;
        Ok(())
    }

    /// `ALTER TABLE … RENAME TO` for a virtual table: rename its persistent
    /// `<name>_data` backing table (a normal table) and rewrite its own schema row
    /// (name, tbl_name, and the stored `CREATE VIRTUAL TABLE` text), matching
    /// sqlite, which renames a vtab and its shadow tables.
    fn rename_virtual_table(&mut self, old: &str, new: &str) -> Result<()> {
        if self
            .schema
            .objects()
            .iter()
            .any(|o| o.name.eq_ignore_ascii_case(new))
        {
            return Err(Error::Error(format!(
                "there is already another table or index with this name: {new}"
            )));
        }
        // Rename the persistent shadow tables first (ordinary tables): the
        // generic `<name>_data`, or an R-Tree's `_node`/`_rowid`/`_parent`.
        for suffix in [
            "_data", "_node", "_rowid", "_parent", "_content", "_docsize", "_config", "_idx",
        ] {
            let backing_old = format!("{old}{suffix}");
            if self.schema.table(&backing_old).is_some() {
                self.exec_alter(&Alter {
                    schema: None,
                    table: backing_old,
                    action: AlterAction::RenameTable(format!("{new}{suffix}")),
                })?;
            }
        }
        let old_s = old.to_string();
        let new_s = new.to_string();
        self.rewrite_schema_rows(|cols| {
            if is_text(&cols[0], "table") && is_text(&cols[1], &old_s) {
                cols[1] = Value::Text(new_s.clone());
                cols[2] = Value::Text(new_s.clone());
                if let Some(Value::Text(s)) = cols.get(4).cloned() {
                    cols[4] =
                        Value::Text(rewrite_ident_tokens(&s, &old_s, &sql::print::ident(&new_s)));
                }
                true
            } else {
                false
            }
        })?;
        let cookie = self
            .backend
            .writer()?
            .header()
            .schema_cookie
            .wrapping_add(1);
        self.backend.writer()?.header_mut().schema_cookie = cookie;
        self.schema = Schema::read(self.backend.source())?;
        Ok(())
    }

    /// `ALTER TABLE … DROP COLUMN name`: remove the column from the schema and
    /// rewrite every row without it, then rebuild the indexes. To stay correct,
    /// columns that participate in the structure (PRIMARY KEY, UNIQUE, an index,
    /// a foreign key, a CHECK, or generation) are refused — matching SQLite, which
    /// rejects dropping such columns.
    fn exec_drop_column(&mut self, a: &Alter, mut ct: CreateTable, name: &str) -> Result<()> {
        let pos = ct
            .columns
            .iter()
            .position(|c| c.name.eq_ignore_ascii_case(name))
            .ok_or_else(|| Error::Error(format!("no such column: \"{name}\"")))?;
        if ct.columns.len() <= 1 {
            return Err(Error::Error(format!(
                "cannot drop column \"{name}\": no other columns exist"
            )));
        }
        let cannot = |why: &str| {
            Err(Error::Error(format!(
                "cannot drop column \"{name}\": {why}"
            )))
        };
        // The dropped column must not be structural.
        for c in &ct.columns[pos].constraints {
            match c {
                ColumnConstraint::PrimaryKey { .. } => return cannot("PRIMARY KEY"),
                ColumnConstraint::Unique(_) => return cannot("UNIQUE"),
                ColumnConstraint::Check(..) => return cannot("CHECK"),
                ColumnConstraint::References(_) => return cannot("FOREIGN KEY"),
                ColumnConstraint::Generated { .. } => return cannot("generated"),
                _ => {}
            }
        }
        // Table-level constraints / other generated columns force a refusal too
        // (conservatively, any of these on the table that could reference it).
        for tc in &ct.constraints {
            match tc {
                TableConstraint::PrimaryKey(n, _) | TableConstraint::Unique(n, _) => {
                    if n.iter().any(|x| x.eq_ignore_ascii_case(name)) {
                        return cannot("PRIMARY KEY or UNIQUE");
                    }
                }
                TableConstraint::Check(..) => return cannot("a table CHECK constraint exists"),
                TableConstraint::ForeignKey(_) => {
                    return cannot("a table FOREIGN KEY constraint exists")
                }
            }
        }
        if ct.columns.iter().enumerate().any(|(i, c)| {
            i != pos
                && c.constraints
                    .iter()
                    .any(|x| matches!(x, ColumnConstraint::Generated { .. }))
        }) {
            return cannot("a generated column exists");
        }
        let meta = self.table_meta(&a.table, None)?;
        if meta.ipk == Some(pos) {
            return cannot("PRIMARY KEY");
        }
        let indexes = self.indexes_of(&a.table)?;
        if indexes
            .iter()
            .any(|i| i.cols.contains(&pos) || i.key_exprs.is_some() || i.partial.is_some())
        {
            return cannot("it is indexed");
        }

        // Read the rows, drop the column's value from each.
        let new_rows: Vec<(i64, Vec<Value>)> = self
            .scan_table(&meta)?
            .into_iter()
            .map(|(rid, mut vals)| {
                vals.remove(pos);
                (rid, vals)
            })
            .collect();

        // Update the schema's CREATE TABLE text.
        ct.columns.remove(pos);
        // Remove the column from the stored CREATE text in place (preserving the
        // other columns verbatim), like sqlite; fall back to an AST reprint.
        let reprint = sql::print::create_table(&ct);
        let table = a.table.clone();
        let dropped = name.to_string();
        self.rewrite_schema_rows(|cols| {
            if is_text(&cols[0], "table") && is_text(&cols[1], &table) {
                let updated = match cols.get(4) {
                    Some(Value::Text(old)) => {
                        drop_column_from_create(old, &dropped).unwrap_or_else(|| reprint.clone())
                    }
                    _ => reprint.clone(),
                };
                cols[4] = Value::Text(updated);
                true
            } else {
                false
            }
        })?;
        self.schema = Schema::read(self.backend.source())?;
        let new_meta = self.table_meta(&a.table, None)?;

        // Rewrite the table b-tree with the narrowed rows.
        clear_table(self.backend.writer()?, new_meta.root)?;
        for (rid, vals) in &new_rows {
            let mut stored = vals.clone();
            if let Some(ipk) = new_meta.ipk {
                stored[ipk] = Value::Null;
            }
            let record = encode_record(&stored);
            insert_table(self.backend.writer()?, new_meta.root, *rid, &record)?;
        }
        // Index column positions shifted; rebuild them.
        let new_indexes = self.indexes_of(&a.table)?;
        self.rebuild_indexes(&new_meta, &new_indexes)?;

        let cookie = self
            .backend
            .writer()?
            .header()
            .schema_cookie
            .wrapping_add(1);
        self.backend.writer()?.header_mut().schema_cookie = cookie;
        self.schema = Schema::read(self.backend.source())?;
        Ok(())
    }

    /// Scan `sqlite_schema`, let `f` mutate each decoded 5-column row in place,
    /// and rewrite (delete + re-insert at the same rowid) the rows it changed.
    fn rewrite_schema_rows(&mut self, mut f: impl FnMut(&mut Vec<Value>) -> bool) -> Result<()> {
        let encoding = self.backend.source().header().text_encoding;
        let mut changes: Vec<(i64, Vec<u8>)> = Vec::new();
        {
            let mut cur = TableCursor::new(self.backend.source(), crate::schema::SCHEMA_ROOT_PAGE);
            let mut ok = cur.first()?;
            while ok {
                let mut cols = decode_record(&cur.payload()?, encoding)?;
                cols.resize(5, Value::Null);
                if f(&mut cols) {
                    changes.push((cur.rowid()?, encode_record(&cols)));
                }
                ok = cur.next()?;
            }
        }
        let w = self.backend.writer()?;
        for (rid, rec) in changes {
            delete_table(w, crate::schema::SCHEMA_ROOT_PAGE, rid)?;
            insert_table(w, crate::schema::SCHEMA_ROOT_PAGE, rid, &rec)?;
        }
        Ok(())
    }

    /// Resolve the `sqlite_schema` rowids of the objects named in `names`.
    fn schema_rowids_for(&self, names: &[String]) -> Result<Vec<i64>> {
        let encoding = self.backend.source().header().text_encoding;
        let mut out = Vec::new();
        let mut cur = TableCursor::new(self.backend.source(), crate::schema::SCHEMA_ROOT_PAGE);
        let mut ok = cur.first()?;
        while ok {
            let cols = decode_record(&cur.payload()?, encoding)?;
            if let Some(Value::Text(name)) = cols.get(1) {
                if names.iter().any(|n| n == name) {
                    out.push(cur.rowid()?);
                }
            }
            ok = cur.next()?;
        }
        Ok(out)
    }

    /// Seek a `WITHOUT ROWID` table's clustered PRIMARY KEY b-tree for the rows
    /// whose leading PK columns the `WHERE` constrains by equality (`… WHERE
    /// pk = ?`), instead of scanning. The b-tree entries are the rows themselves,
    /// stored PK-first, so an equality-prefix seek yields them directly.
    /// `run_core` re-applies the full `WHERE`, so returning a superset is fine.
    /// Returns `None` (→ caller scans) when no leading-PK equality is usable.
    fn try_without_rowid_pk_seek(
        &self,
        meta: &TableMeta,
        sel: &Select,
        params: &Params,
    ) -> Result<Option<Vec<InputRow>>> {
        let Some(where_expr) = &sel.where_clause else {
            return Ok(None);
        };
        let hint = sel.from.as_ref().and_then(|f| f.first.index_hint.as_ref());
        if matches!(hint, Some(IndexHint::NotIndexed)) {
            return Ok(None);
        }
        let pk = &meta.storage_order[..meta.pk_len];
        if pk.is_empty() {
            return Ok(None);
        }
        let mut eqs: Vec<(usize, Value)> = Vec::new();
        collect_eq_constraints(where_expr, &meta.columns, params, &mut eqs);
        // Build the seek key from the longest leading-PK prefix the WHERE
        // constrains by `= const`, with the b-tree's storage collations.
        let storage_colls = wr_storage_collations(meta);
        let mut key = Vec::new();
        let mut colls = Vec::new();
        for (i, &c) in pk.iter().enumerate() {
            let Some((_, v)) = eqs.iter().find(|(col, _)| *col == c) else {
                break;
            };
            if matches!(v, Value::Null) {
                break; // PK columns are NOT NULL; `pk = NULL` matches nothing
            }
            key.push(meta.columns[c].affinity.coerce(v.clone()));
            colls.push(storage_colls[i]);
        }
        if key.is_empty() {
            return Ok(None);
        }
        let records =
            crate::btree::index_seek_records(self.backend.source(), meta.root, &key, &colls)?;
        let mut out = Vec::with_capacity(records.len());
        for storage in records {
            let mut row = unpermute_row(meta, storage);
            self.compute_generated(meta, &mut row, params)?;
            out.push(InputRow {
                values: row,
                rowid: None,
            });
        }
        Ok(Some(out))
    }

    /// Range variant of [`try_without_rowid_pk_seek`](Self::try_without_rowid_pk_seek):
    /// a `< / <= / > / >= / BETWEEN` bound on the *leading* PK column walks the
    /// clustered b-tree between bounds instead of scanning. A superset is fine
    /// (`run_core` re-applies the full `WHERE`). Returns `None` (→ scan) when the
    /// leading PK column has no range bound.
    fn try_without_rowid_pk_range(
        &self,
        meta: &TableMeta,
        sel: &Select,
        params: &Params,
    ) -> Result<Option<Vec<InputRow>>> {
        let Some(where_expr) = &sel.where_clause else {
            return Ok(None);
        };
        let hint = sel.from.as_ref().and_then(|f| f.first.index_hint.as_ref());
        if matches!(hint, Some(IndexHint::NotIndexed)) {
            return Ok(None);
        }
        let pk = &meta.storage_order[..meta.pk_len];
        let Some(&lead) = pk.first() else {
            return Ok(None);
        };
        let mut ranges: alloc::collections::BTreeMap<usize, RangeBound> =
            alloc::collections::BTreeMap::new();
        collect_range_constraints(where_expr, &meta.columns, params, &mut ranges);
        let Some(b) = ranges.get(&lead) else {
            return Ok(None);
        };
        let aff = meta.columns[lead].affinity;
        let coll = wr_storage_collations(meta)[0];
        let lower = b.lower.as_ref().map(|(v, i)| (aff.coerce(v.clone()), *i));
        let upper = b.upper.as_ref().map(|(v, i)| (aff.coerce(v.clone()), *i));
        let colls = [coll];
        let lower_arg = lower
            .as_ref()
            .map(|(v, inc)| (core::slice::from_ref(v), *inc));
        let upper_arg = upper
            .as_ref()
            .map(|(v, inc)| (core::slice::from_ref(v), *inc));
        let records = crate::btree::index_range_records(
            self.backend.source(),
            meta.root,
            lower_arg,
            upper_arg,
            &colls,
        )?;
        let mut out = Vec::with_capacity(records.len());
        for storage in records {
            let mut row = unpermute_row(meta, storage);
            self.compute_generated(meta, &mut row, params)?;
            out.push(InputRow {
                values: row,
                rowid: None,
            });
        }
        Ok(Some(out))
    }

    /// Seek a *secondary* index of a WITHOUT ROWID table on an equality of its
    /// leading column(s). A WITHOUT ROWID index record is `(indexed cols…, PK
    /// cols…)`, so when the index plus the PK covers every referenced column the
    /// row is read straight from the index record; otherwise the PK columns from
    /// each record seek the clustered b-tree for the full row. `run_core`
    /// re-applies the full WHERE, so a superset is fine.
    fn try_without_rowid_index_seek(
        &self,
        meta: &TableMeta,
        table_name: &str,
        sel: &Select,
        params: &Params,
    ) -> Result<Option<Vec<InputRow>>> {
        let Some(where_expr) = &sel.where_clause else {
            return Ok(None);
        };
        let hint = sel.from.as_ref().and_then(|f| f.first.index_hint.as_ref());
        if matches!(hint, Some(IndexHint::NotIndexed)) {
            return Ok(None);
        }
        let mut eqs: Vec<(usize, Value)> = Vec::new();
        collect_eq_constraints(where_expr, &meta.columns, params, &mut eqs);
        eqs.retain(|(_, v)| !matches!(v, Value::Null));
        if eqs.is_empty() {
            return Ok(None);
        }
        let pk: Vec<usize> = meta.storage_order[..meta.pk_len].to_vec();
        let indexes = self.indexes_of(table_name)?;
        if let Some(IndexHint::IndexedBy(n)) = hint {
            if !indexes.iter().any(|i| i.name.eq_ignore_ascii_case(n)) {
                return Err(Error::Error(alloc::format!("no such index: {n}")));
            }
        }
        let src = self.backend.source();
        for idx in &indexes {
            if let Some(IndexHint::IndexedBy(n)) = hint {
                if !idx.name.eq_ignore_ascii_case(n) {
                    continue;
                }
            }
            if idx.partial.is_some() || idx.key_exprs.is_some() {
                continue;
            }
            // Equality prefix over the index's leading columns.
            let mut key = Vec::new();
            let mut colls = Vec::new();
            for (i, &c) in idx.cols.iter().enumerate() {
                let Some((_, v)) = eqs.iter().find(|(col, _)| *col == c) else {
                    break;
                };
                key.push(meta.columns[c].affinity.coerce(v.clone()));
                colls.push(idx.collations.get(i).copied().unwrap_or_default());
            }
            if key.is_empty() {
                continue;
            }
            let records = crate::btree::index_seek_records(src, idx.root, &key, &colls)?;
            let covering = self.wr_index_covers(idx, &pk, meta, sel, where_expr);
            return Ok(Some(
                self.wr_index_rows(meta, idx, &pk, records, covering, params)?,
            ));
        }
        Ok(None)
    }

    /// Whether a WITHOUT ROWID secondary index covers the query (so its rows can
    /// be read straight from the index records). A *named* index counts as holding
    /// its columns plus the trailing PK columns; an implicit UNIQUE/PK autoindex
    /// (`sqlite_autoindex_*`) counts only its own — matching SQLite's `COVERING
    /// INDEX` vs `INDEX` wording.
    fn wr_index_covers(
        &self,
        idx: &IndexMeta,
        pk: &[usize],
        meta: &TableMeta,
        sel: &Select,
        where_expr: &Expr,
    ) -> bool {
        let mut avail = idx.cols.clone();
        if !idx.name.starts_with("sqlite_autoindex_") {
            for &p in pk {
                if !avail.contains(&p) {
                    avail.push(p);
                }
            }
        }
        self.seek_index_covers(sel, meta, &avail, where_expr)
    }

    /// Build rows from a WITHOUT ROWID secondary index's seeked/scanned records.
    /// Each record is `(indexed cols…, PK cols…)`: when `covering`, reconstruct
    /// the referenced columns straight from it (the rest are unreferenced, left
    /// NULL); otherwise the trailing PK columns seek the clustered b-tree for the
    /// full row.
    fn wr_index_rows(
        &self,
        meta: &TableMeta,
        idx: &IndexMeta,
        pk: &[usize],
        records: Vec<Vec<Value>>,
        covering: bool,
        params: &Params,
    ) -> Result<Vec<InputRow>> {
        let mut out = Vec::with_capacity(records.len());
        if covering {
            for rec in &records {
                let mut values = alloc::vec![Value::Null; meta.columns.len()];
                for (i, &mc) in idx.cols.iter().enumerate() {
                    values[mc] = rec[i].clone();
                }
                for (j, &pc) in pk.iter().enumerate() {
                    values[pc] = rec[idx.cols.len() + j].clone();
                }
                out.push(InputRow {
                    values,
                    rowid: None,
                });
            }
        } else {
            let src = self.backend.source();
            let pk_colls: Vec<crate::value::Collation> =
                wr_storage_collations(meta)[..pk.len()].to_vec();
            for rec in &records {
                let pk_key: Vec<Value> = (0..pk.len())
                    .map(|j| rec[idx.cols.len() + j].clone())
                    .collect();
                for storage in crate::btree::index_seek_records(src, meta.root, &pk_key, &pk_colls)?
                {
                    let mut row = unpermute_row(meta, storage);
                    self.compute_generated(meta, &mut row, params)?;
                    out.push(InputRow {
                        values: row,
                        rowid: None,
                    });
                }
            }
        }
        Ok(out)
    }

    /// Range variant of [`try_without_rowid_index_seek`](Self::try_without_rowid_index_seek):
    /// a bound on the *leading* column of a WITHOUT ROWID secondary index walks
    /// the index between bounds (covering or PK-fetching, as above).
    fn try_without_rowid_index_range(
        &self,
        meta: &TableMeta,
        table_name: &str,
        sel: &Select,
        params: &Params,
    ) -> Result<Option<Vec<InputRow>>> {
        let Some(where_expr) = &sel.where_clause else {
            return Ok(None);
        };
        let hint = sel.from.as_ref().and_then(|f| f.first.index_hint.as_ref());
        if matches!(hint, Some(IndexHint::NotIndexed)) {
            return Ok(None);
        }
        let mut ranges: alloc::collections::BTreeMap<usize, RangeBound> =
            alloc::collections::BTreeMap::new();
        collect_range_constraints(where_expr, &meta.columns, params, &mut ranges);
        if ranges.is_empty() {
            return Ok(None);
        }
        let pk: Vec<usize> = meta.storage_order[..meta.pk_len].to_vec();
        let indexes = self.indexes_of(table_name)?;
        if let Some(IndexHint::IndexedBy(n)) = hint {
            if !indexes.iter().any(|i| i.name.eq_ignore_ascii_case(n)) {
                return Err(Error::Error(alloc::format!("no such index: {n}")));
            }
        }
        for idx in &indexes {
            if let Some(IndexHint::IndexedBy(n)) = hint {
                if !idx.name.eq_ignore_ascii_case(n) {
                    continue;
                }
            }
            if idx.partial.is_some() || idx.key_exprs.is_some() {
                continue;
            }
            let Some(&lead) = idx.cols.first() else {
                continue;
            };
            let Some(b) = ranges.get(&lead) else {
                continue;
            };
            let aff = meta.columns[lead].affinity;
            let coll = idx.collations.first().copied().unwrap_or_default();
            let lower = b.lower.as_ref().map(|(v, i)| (aff.coerce(v.clone()), *i));
            let upper = b.upper.as_ref().map(|(v, i)| (aff.coerce(v.clone()), *i));
            let colls = [coll];
            let lower_arg = lower
                .as_ref()
                .map(|(v, inc)| (core::slice::from_ref(v), *inc));
            let upper_arg = upper
                .as_ref()
                .map(|(v, inc)| (core::slice::from_ref(v), *inc));
            let records = crate::btree::index_range_records(
                self.backend.source(),
                idx.root,
                lower_arg,
                upper_arg,
                &colls,
            )?;
            let covering = self.wr_index_covers(idx, &pk, meta, sel, where_expr);
            return Ok(Some(
                self.wr_index_rows(meta, idx, &pk, records, covering, params)?,
            ));
        }
        Ok(None)
    }

    /// The index metadata (root + indexed column positions) for `table`.
    /// Try to satisfy a single-table query with an index equality lookup instead
    /// of a full scan: pick the index whose longest leftmost column prefix is
    /// covered by `col = const` predicates in the `WHERE`, seek it, and fetch the
    /// matching rows by rowid. Returns `None` (→ full scan) if no index applies.
    fn try_index_lookup(
        &self,
        meta: &TableMeta,
        table_name: &str,
        sel: &Select,
        params: &Params,
    ) -> Result<Option<Vec<InputRow>>> {
        let Some(where_expr) = &sel.where_clause else {
            return Ok(None);
        };
        // `NOT INDEXED` forbids any index for this table; `INDEXED BY name`
        // restricts to one named index (validated below).
        let hint = sel.from.as_ref().and_then(|f| f.first.index_hint.as_ref());
        if matches!(hint, Some(IndexHint::NotIndexed)) {
            return Ok(None);
        }
        // `rowid` / `_rowid_` / `oid` `= N` or `IN (list)`: seek the rowid table
        // b-tree directly — works with or without an explicit INTEGER PRIMARY KEY
        // column, and is cheaper than any secondary index. `INDEXED BY` names a
        // specific index, so it forbids this fast path. (`run_core` re-applies the
        // full WHERE, so the seeked rows are a valid superset.)
        if !matches!(hint, Some(IndexHint::IndexedBy(_))) {
            if let Some(rowids) = rowid_seek_constraint(where_expr, &meta.columns, params) {
                let encoding = self.backend.source().header().text_encoding;
                let mut cur = TableCursor::new(self.backend.source(), meta.root);
                let mut out = Vec::new();
                let mut seen: Vec<i64> = Vec::new();
                for rid in rowids {
                    if seen.contains(&rid) {
                        continue;
                    }
                    seen.push(rid);
                    if cur.seek(rid)? {
                        let values = self.decode_full_row(meta, rid, &cur.payload()?, encoding)?;
                        out.push(InputRow {
                            values,
                            rowid: Some(rid),
                        });
                    }
                }
                return Ok(Some(out));
            }
        }
        let mut eqs: Vec<(usize, Value)> = Vec::new();
        collect_eq_constraints(where_expr, &meta.columns, params, &mut eqs);
        if eqs.is_empty() || eqs.iter().any(|(_, v)| matches!(v, Value::Null)) {
            // No usable column equality (`col = NULL` is never true). A plain or
            // partial *column* index can't seek, but an *expression* index might
            // (e.g. `lower(x) = 'b'` leaves no column eq behind). Try that, then
            // let the scan handle the rest.
            return self.partial_expr_lookup(meta, table_name, sel, where_expr, params);
        }

        // Rowid (INTEGER PRIMARY KEY) equality: seek the table b-tree directly
        // by rowid. run_core re-applies the full WHERE, so returning the single
        // candidate row is a valid superset even when the literal isn't an exact
        // integer (e.g. `id = 5.5` seeks rowid 5, then gets filtered out).
        // The rowid (INTEGER PRIMARY KEY) is not a named index, so `INDEXED BY`
        // forbids this fast path.
        if !matches!(hint, Some(IndexHint::IndexedBy(_))) {
            if let Some(ipk) = meta.ipk {
                if let Some((_, v)) = eqs.iter().find(|(c, _)| *c == ipk) {
                    let rid = eval::to_i64(v);
                    let encoding = self.backend.source().header().text_encoding;
                    let mut cur = TableCursor::new(self.backend.source(), meta.root);
                    let mut out = Vec::new();
                    if cur.seek(rid)? {
                        let values = self.decode_full_row(meta, rid, &cur.payload()?, encoding)?;
                        out.push(InputRow {
                            values,
                            rowid: Some(rid),
                        });
                    }
                    return Ok(Some(out));
                }
            }
        }

        // Choose the index to seek. Each candidate covers the longest leftmost
        // prefix of the index's columns that the WHERE constrains by equality.
        // With `ANALYZE` statistics we pick the most selective (fewest estimated
        // rows); absent stats we fall back to the longest matched prefix.
        let indexes = self.indexes_of(table_name)?;
        // `INDEXED BY name` must name a real index of this table.
        if let Some(IndexHint::IndexedBy(n)) = hint {
            if !indexes.iter().any(|i| i.name.eq_ignore_ascii_case(n)) {
                return Err(Error::Error(alloc::format!("no such index: {n}")));
            }
        }
        let stats = self.stat1_map();
        #[allow(clippy::type_complexity)]
        let mut best: Option<(
            u32,
            Vec<Value>,
            Vec<crate::value::Collation>,
            Vec<usize>,
            u64,
        )> = None;
        for idx in &indexes {
            // Honor `INDEXED BY`: consider only the named index.
            if let Some(IndexHint::IndexedBy(n)) = hint {
                if !idx.name.eq_ignore_ascii_case(n) {
                    continue;
                }
            }
            // A partial index covers only some rows; an expression index is keyed
            // by computed values, not columns. Neither is used for a plain
            // column-equality seek — leave those to the table scan.
            if idx.partial.is_some() || idx.key_exprs.is_some() {
                continue;
            }
            let mut key = Vec::new();
            for &c in &idx.cols {
                match eqs.iter().find(|(col, _)| *col == c) {
                    Some((_, v)) => key.push(meta.columns[c].affinity.coerce(v.clone())),
                    None => break,
                }
            }
            if key.is_empty() {
                continue;
            }
            // Estimated rows returned: the stat's avgEq at the matched prefix
            // length when available, else a sentinel that prefers longer prefixes.
            let est = stats
                .get(&idx.name)
                .and_then(|s| s.get(key.len()).copied())
                .unwrap_or(u64::MAX - key.len() as u64);
            let better = match &best {
                None => true,
                Some((_, bk, _, _, be)) => est < *be || (est == *be && key.len() > bk.len()),
            };
            if better {
                // Carry the index's full collation vector so a trailing range on
                // the column after the equality prefix can be seeked too.
                best = Some((idx.root, key, idx.collations.clone(), idx.cols.clone(), est));
            }
        }
        // Plain column indexes take priority. If none applied, try a partial or
        // expression index whose eligibility we can prove from the `WHERE`
        // structure (see `partial_expr_seek`). This keeps plain-index behavior
        // byte-identical while extending seeks to the new index kinds.
        let (root, key, full_colls, idx_cols) = match best {
            Some((root, key, colls, idx_cols, _)) => (root, key, colls, idx_cols),
            None => {
                return self.partial_expr_lookup(meta, table_name, sel, where_expr, params);
            }
        };
        if key.is_empty() {
            return Ok(None);
        }

        // Covering seek: when the chosen index holds every referenced column (the
        // result columns, the `WHERE` columns, and any `ORDER BY`), read straight
        // from the index — `eqp_access` reports `USING COVERING INDEX` for the
        // same decision. Stays in lockstep with the table-fetch path below
        // (`run_core` re-applies the full `WHERE` to the superset of index rows).
        if self.seek_index_covers(sel, meta, &idx_cols, where_expr) {
            return Ok(Some(self.covering_seek_rows(meta, root, &idx_cols)?));
        }

        // Equality prefix followed by a range on the *next* index column
        // (`x=? AND y>?`): extend the exact-prefix seek to a bounded range over
        // `[eq…, low] .. [eq…, high]`, matching SQLite (and reported the same way
        // by `eqp_access`). Falls through to the plain prefix seek otherwise.
        let next_pos = key.len();
        if let Some(&next_col) = idx_cols.get(next_pos) {
            let mut ranges: alloc::collections::BTreeMap<usize, RangeBound> =
                alloc::collections::BTreeMap::new();
            collect_range_constraints(where_expr, &meta.columns, params, &mut ranges);
            if let Some(b) = ranges.get(&next_col) {
                let aff = meta.columns[next_col].affinity;
                let colls = full_colls[..=next_pos].to_vec();
                let mut lo_key = key.clone();
                let lo_inc = match b.lower.as_ref() {
                    Some((v, inc)) => {
                        lo_key.push(aff.coerce(v.clone()));
                        *inc
                    }
                    None => true,
                };
                let mut hi_key = key.clone();
                let hi_inc = match b.upper.as_ref() {
                    Some((v, inc)) => {
                        hi_key.push(aff.coerce(v.clone()));
                        *inc
                    }
                    None => true,
                };
                let rowids = crate::btree::index_range_rowids(
                    self.backend.source(),
                    root,
                    Some((lo_key.as_slice(), lo_inc)),
                    Some((hi_key.as_slice(), hi_inc)),
                    &colls,
                )?;
                let encoding = self.backend.source().header().text_encoding;
                let mut cur = TableCursor::new(self.backend.source(), meta.root);
                let mut out = Vec::new();
                for rid in rowids {
                    if cur.seek(rid)? {
                        let values = self.decode_full_row(meta, rid, &cur.payload()?, encoding)?;
                        out.push(InputRow {
                            values,
                            rowid: Some(rid),
                        });
                    }
                }
                return Ok(Some(out));
            }
        }

        self.index_seek_fetch(meta, root, &key, &full_colls[..key.len()])
    }

    /// Fetch table rows for an equality index seek: collect the matching rowids
    /// from the index, then read each row from the table b-tree. Returns a
    /// superset (`run_core` re-applies the full `WHERE`).
    fn index_seek_fetch(
        &self,
        meta: &TableMeta,
        root: u32,
        key: &[Value],
        colls: &[crate::value::Collation],
    ) -> Result<Option<Vec<InputRow>>> {
        let rowids = crate::btree::index_seek_rowids(self.backend.source(), root, key, colls)?;
        let encoding = self.backend.source().header().text_encoding;
        let mut cur = TableCursor::new(self.backend.source(), meta.root);
        let mut out = Vec::new();
        for rid in rowids {
            if cur.seek(rid)? {
                let values = self.decode_full_row(meta, rid, &cur.payload()?, encoding)?;
                out.push(InputRow {
                    values,
                    rowid: Some(rid),
                });
            }
        }
        Ok(Some(out))
    }

    /// Equality-seek fallback for partial / expression indexes, used when no
    /// plain column index applied. Picks the first index (honoring `INDEXED BY`)
    /// for which [`partial_expr_seek`](Self::partial_expr_seek) proves a seek is
    /// valid, fetches its rows, and returns the superset. Returns `None` (→ scan)
    /// when none qualifies. `eqp_access` mirrors this exact choice.
    fn partial_expr_lookup(
        &self,
        meta: &TableMeta,
        table_name: &str,
        sel: &Select,
        where_expr: &Expr,
        params: &Params,
    ) -> Result<Option<Vec<InputRow>>> {
        let hint = sel.from.as_ref().and_then(|f| f.first.index_hint.as_ref());
        for idx in self.indexes_of(table_name)? {
            if let Some(IndexHint::IndexedBy(n)) = hint {
                if !idx.name.eq_ignore_ascii_case(n) {
                    continue;
                }
            }
            if let Some((key, colls)) = self.partial_expr_seek(&idx, where_expr, meta, params)? {
                // Expression indexes don't map keys back to table columns, so they
                // are never a covering seek here; fetch table rows by rowid (a
                // superset re-filtered by `run_core`).
                return self.index_seek_fetch(meta, idx.root, &key, &colls);
            }
        }
        Ok(None)
    }

    /// Decide whether a *partial* or *expression* index can serve an equality
    /// seek for `where_expr`, and if so return the seek `(key, collations)`.
    ///
    /// The rules are deliberately conservative (no general implication):
    ///
    /// * **Partial index** (`CREATE INDEX … WHERE pred`): usable only when `pred`
    ///   appears verbatim (modulo redundant parens) as a top-level `AND` conjunct
    ///   of the query's `WHERE`, so every row the seek can return is one the index
    ///   actually stores. A partial index over plain columns then seeks like an
    ///   ordinary column index; a partial *expression* index must additionally
    ///   satisfy the expression rule below.
    /// * **Expression index** (`CREATE INDEX … (expr)`): usable when a top-level
    ///   `AND` conjunct is `<indexed-expr> = <const>` (either operand order), with
    ///   `<indexed-expr>` structurally equal to the index's single key expression.
    ///   The seek key is the evaluated constant; the index stores that same value
    ///   per row, so the seek finds a superset.
    ///
    /// Returns `None` for plain column indexes (handled by the caller's main
    /// loop) and whenever the proof above fails. `eqp_access` calls this same
    /// helper, keeping the plan string in lockstep with what executes.
    fn partial_expr_seek(
        &self,
        idx: &IndexMeta,
        where_expr: &Expr,
        meta: &TableMeta,
        params: &Params,
    ) -> Result<Option<(Vec<Value>, Vec<crate::value::Collation>)>> {
        // Plain column index: not our concern.
        if idx.partial.is_none() && idx.key_exprs.is_none() {
            return Ok(None);
        }
        let mut conjuncts = Vec::new();
        and_conjuncts(where_expr, &mut conjuncts);

        // A partial predicate must be guaranteed by a top-level conjunct.
        if let Some(pred) = &idx.partial {
            if !conjuncts.iter().any(|c| expr_eq_modulo_parens(c, pred)) {
                return Ok(None);
            }
        }

        match &idx.key_exprs {
            // Partial index over plain columns: seek as an ordinary column index.
            None => {
                let mut key = Vec::new();
                let mut colls = Vec::new();
                let mut eqs: Vec<(usize, Value)> = Vec::new();
                collect_eq_constraints(where_expr, &meta.columns, params, &mut eqs);
                for (pos, &c) in idx.cols.iter().enumerate() {
                    match eqs
                        .iter()
                        .find(|(col, v)| *col == c && !matches!(v, Value::Null))
                    {
                        Some((_, v)) => {
                            key.push(meta.columns[c].affinity.coerce(v.clone()));
                            colls.push(idx.collations[pos]);
                        }
                        None => break,
                    }
                }
                if key.is_empty() {
                    return Ok(None);
                }
                Ok(Some((key, colls)))
            }
            // Expression index: match a conjunct `<key_expr> = <const>`. Only a
            // single-term key is supported (the common `lower(x)` shape).
            Some(exprs) => {
                let [key_expr] = exprs.as_slice() else {
                    return Ok(None);
                };
                for c in &conjuncts {
                    let Expr::Binary {
                        op: BinaryOp::Eq,
                        left,
                        right,
                    } = unparen(c)
                    else {
                        continue;
                    };
                    // `<key_expr> = <const>` or `<const> = <key_expr>`.
                    let val = if expr_eq_modulo_parens(left, key_expr) {
                        const_value(right, params)
                    } else if expr_eq_modulo_parens(right, key_expr) {
                        const_value(left, params)
                    } else {
                        None
                    };
                    if let Some(v) = val {
                        if matches!(v, Value::Null) {
                            continue; // `expr = NULL` is never true
                        }
                        let coll = idx.collations.first().copied().unwrap_or_default();
                        return Ok(Some((alloc::vec![v], alloc::vec![coll])));
                    }
                }
                Ok(None)
            }
        }
    }

    /// Try to satisfy a single-table query with an index *range* scan: pick an
    /// index whose leading column is constrained by a `<`/`<=`/`>`/`>=`/`BETWEEN`
    /// predicate, walk the index between those bounds, and fetch the rows by
    /// rowid. Like [`try_index_lookup`](Self::try_index_lookup) this returns a
    /// superset — `run_core` re-applies the full `WHERE`. Returns `None` (→ scan)
    /// when no index applies.
    fn try_index_range(
        &self,
        meta: &TableMeta,
        table_name: &str,
        sel: &Select,
        params: &Params,
    ) -> Result<Option<Vec<InputRow>>> {
        let Some(where_expr) = &sel.where_clause else {
            return Ok(None);
        };
        let hint = sel.from.as_ref().and_then(|f| f.first.index_hint.as_ref());
        if matches!(hint, Some(IndexHint::NotIndexed)) {
            return Ok(None);
        }
        let mut ranges: alloc::collections::BTreeMap<usize, RangeBound> =
            alloc::collections::BTreeMap::new();
        collect_range_constraints(where_expr, &meta.columns, params, &mut ranges);
        if ranges.is_empty() {
            return Ok(None);
        }

        // Rowid (INTEGER PRIMARY KEY) range: walk the table b-tree between integer
        // bounds. `INDEXED BY` forbids this (the rowid is not a named index). Only
        // integer bounds are taken (a non-integer literal falls to the scan); the
        // returned span is a superset, so the boundary rows are filtered by the
        // re-applied WHERE.
        if !matches!(hint, Some(IndexHint::IndexedBy(_))) {
            if let Some(ipk) = meta.ipk {
                if let Some(b) = ranges.get(&ipk) {
                    let int_bound = |o: &Option<(Value, bool)>| match o {
                        Some((Value::Integer(i), _)) => Some(*i),
                        None => None,
                        _ => Some(i64::MAX), // sentinel: a non-integer bound disables it
                    };
                    let lo = int_bound(&b.lower);
                    let hi = int_bound(&b.upper);
                    // Disable when a present bound is non-integer (sentinel hit on
                    // the wrong side).
                    let lo_ok =
                        b.lower.is_none() || matches!(b.lower, Some((Value::Integer(_), _)));
                    let hi_ok =
                        b.upper.is_none() || matches!(b.upper, Some((Value::Integer(_), _)));
                    if lo_ok && hi_ok {
                        let start = lo.unwrap_or(i64::MIN);
                        let stop = hi.unwrap_or(i64::MAX);
                        let encoding = self.backend.source().header().text_encoding;
                        let mut cur = TableCursor::new(self.backend.source(), meta.root);
                        let mut out = Vec::new();
                        let mut ok = if start == i64::MIN {
                            cur.first()?
                        } else {
                            cur.seek(start)?;
                            cur.is_valid()
                        };
                        while ok {
                            let rid = cur.rowid()?;
                            if rid > stop {
                                break;
                            }
                            let values =
                                self.decode_full_row(meta, rid, &cur.payload()?, encoding)?;
                            out.push(InputRow {
                                values,
                                rowid: Some(rid),
                            });
                            ok = cur.next()?;
                        }
                        return Ok(Some(out));
                    }
                }
            }
        }

        // Pick the first plain (non-partial, non-expression) index whose leading
        // column has a range bound, honoring `INDEXED BY`.
        let indexes = self.indexes_of(table_name)?;
        if let Some(IndexHint::IndexedBy(n)) = hint {
            if !indexes.iter().any(|i| i.name.eq_ignore_ascii_case(n)) {
                return Err(Error::Error(alloc::format!("no such index: {n}")));
            }
        }
        let mut chosen: Option<(u32, RangeBound, crate::value::Collation, Vec<usize>)> = None;
        for idx in &indexes {
            if let Some(IndexHint::IndexedBy(n)) = hint {
                if !idx.name.eq_ignore_ascii_case(n) {
                    continue;
                }
            }
            if idx.partial.is_some() || idx.key_exprs.is_some() {
                continue;
            }
            let Some(&lead) = idx.cols.first() else {
                continue;
            };
            if let Some(b) = ranges.get(&lead) {
                let coll = idx.collations.first().copied().unwrap_or_default();
                let aff = meta.columns[lead].affinity;
                let b = RangeBound {
                    lower: b.lower.as_ref().map(|(v, i)| (aff.coerce(v.clone()), *i)),
                    upper: b.upper.as_ref().map(|(v, i)| (aff.coerce(v.clone()), *i)),
                };
                chosen = Some((idx.root, b, coll, idx.cols.clone()));
                break;
            }
        }
        match chosen {
            Some((root, bound, coll, idx_cols)) => {
                // Covering range seek: read from the index when it holds every
                // referenced column (lockstep with `eqp_access`'s `COVERING INDEX`).
                if self.seek_index_covers(sel, meta, &idx_cols, where_expr) {
                    return Ok(Some(self.covering_seek_rows(meta, root, &idx_cols)?));
                }
                Ok(Some(self.range_seek_fetch(meta, root, &bound, coll)?))
            }
            None => {
                // A3b: a partial or expression index whose key column / expression
                // has a range bound (and, for a partial index, whose predicate the
                // WHERE guarantees). Always a non-covering fetch — `eqp_access`
                // mirrors this in its partial/expression range fallback.
                for idx in &indexes {
                    if let Some(IndexHint::IndexedBy(n)) = hint {
                        if !idx.name.eq_ignore_ascii_case(n) {
                            continue;
                        }
                    }
                    if let Some((bound, coll)) =
                        self.partial_expr_range(idx, where_expr, meta, params)
                    {
                        return Ok(Some(self.range_seek_fetch(meta, idx.root, &bound, coll)?));
                    }
                }
                Ok(None)
            }
        }
    }

    /// Walk an index between `bound`'s lower/upper keys (single leading column,
    /// under `coll`) and fetch each matching row from the table by rowid. Returns
    /// a superset — `run_core` re-applies the full `WHERE`.
    fn range_seek_fetch(
        &self,
        meta: &TableMeta,
        root: u32,
        bound: &RangeBound,
        coll: crate::value::Collation,
    ) -> Result<Vec<InputRow>> {
        let colls = [coll];
        let lower_key = bound.lower.as_ref().map(|(v, _)| core::slice::from_ref(v));
        let upper_key = bound.upper.as_ref().map(|(v, _)| core::slice::from_ref(v));
        let lower = lower_key.map(|k| (k, bound.lower.as_ref().unwrap().1));
        let upper = upper_key.map(|k| (k, bound.upper.as_ref().unwrap().1));
        let rowids =
            crate::btree::index_range_rowids(self.backend.source(), root, lower, upper, &colls)?;

        let encoding = self.backend.source().header().text_encoding;
        let mut cur = TableCursor::new(self.backend.source(), meta.root);
        let mut out = Vec::new();
        for rid in rowids {
            if cur.seek(rid)? {
                let values = self.decode_full_row(meta, rid, &cur.payload()?, encoding)?;
                out.push(InputRow {
                    values,
                    rowid: Some(rid),
                });
            }
        }
        Ok(out)
    }

    /// Seek each key through an index (single leading column/expression, under
    /// `colls`), union the matching rowids, and fetch each row from the table.
    /// Shared by the plain, partial, and expression `IN`-list seek paths. Returns
    /// a superset (`run_core` re-applies the full `WHERE`).
    fn in_seek_fetch(
        &self,
        meta: &TableMeta,
        root: u32,
        colls: &[crate::value::Collation],
        keys: &[Vec<Value>],
    ) -> Result<Vec<InputRow>> {
        let src = self.backend.source();
        let encoding = src.header().text_encoding;
        let mut rowids: Vec<i64> = Vec::new();
        for key in keys {
            for rid in crate::btree::index_seek_rowids(src, root, key, colls)? {
                if !rowids.contains(&rid) {
                    rowids.push(rid);
                }
            }
        }
        let mut cur = TableCursor::new(src, meta.root);
        let mut out = Vec::new();
        for rid in rowids {
            if cur.seek(rid)? {
                let values = self.decode_full_row(meta, rid, &cur.payload()?, encoding)?;
                out.push(InputRow {
                    values,
                    rowid: Some(rid),
                });
            }
        }
        Ok(out)
    }

    /// A3b range analogue of [`partial_expr_seek`](Self::partial_expr_seek): for a
    /// partial or expression index, return the range bound (and collation) to seek
    /// — a `<`/`<=`/`>`/`>=` constraint on the partial index's leading column (with
    /// its predicate guaranteed by the `WHERE`), or on an expression index's keyed
    /// expression. `None` when the index doesn't apply.
    fn partial_expr_range(
        &self,
        idx: &IndexMeta,
        where_expr: &Expr,
        meta: &TableMeta,
        params: &Params,
    ) -> Option<(RangeBound, crate::value::Collation)> {
        if idx.partial.is_none() && idx.key_exprs.is_none() {
            return None;
        }
        let mut conjuncts = Vec::new();
        and_conjuncts(where_expr, &mut conjuncts);
        if let Some(pred) = &idx.partial {
            if !conjuncts.iter().any(|c| expr_eq_modulo_parens(c, pred)) {
                return None;
            }
        }
        let coll = idx.collations.first().copied().unwrap_or_default();
        match &idx.key_exprs {
            // Partial index over plain columns: a range on the leading column.
            None => {
                let lead = *idx.cols.first()?;
                let mut ranges = alloc::collections::BTreeMap::new();
                collect_range_constraints(where_expr, &meta.columns, params, &mut ranges);
                let b = ranges.get(&lead)?;
                let aff = meta.columns[lead].affinity;
                Some((
                    RangeBound {
                        lower: b.lower.as_ref().map(|(v, i)| (aff.coerce(v.clone()), *i)),
                        upper: b.upper.as_ref().map(|(v, i)| (aff.coerce(v.clone()), *i)),
                    },
                    coll,
                ))
            }
            // Expression index: collect range conjuncts `<key_expr> <op> <const>`.
            Some(exprs) => {
                let [key_expr] = exprs.as_slice() else {
                    return None;
                };
                let mut bound = RangeBound {
                    lower: None,
                    upper: None,
                };
                for c in &conjuncts {
                    let Expr::Binary { op, left, right } = unparen(c) else {
                        continue;
                    };
                    // Normalize to `key_expr <op> const`, mirroring the operator
                    // when the expression is on the right.
                    let (val, op) = if expr_eq_modulo_parens(left, key_expr) {
                        (const_value(right, params), *op)
                    } else if expr_eq_modulo_parens(right, key_expr) {
                        (const_value(left, params), mirror_comparison(*op))
                    } else {
                        continue;
                    };
                    let Some(v) = val else { continue };
                    if matches!(v, Value::Null) {
                        continue;
                    }
                    match op {
                        BinaryOp::Gt => bound.lower = Some((v, false)),
                        BinaryOp::GtEq => bound.lower = Some((v, true)),
                        BinaryOp::Lt => bound.upper = Some((v, false)),
                        BinaryOp::LtEq => bound.upper = Some((v, true)),
                        _ => {}
                    }
                }
                if bound.lower.is_none() && bound.upper.is_none() {
                    return None;
                }
                Some((bound, coll))
            }
        }
    }

    /// Try to satisfy a single-table query with per-value index seeks for a
    /// `column IN (const, …)` predicate: seek each list value through an index on
    /// that column (or the rowid b-tree for an `INTEGER PRIMARY KEY`), union the
    /// rowids, and fetch the rows. Returns a superset (`run_core` re-applies the
    /// full `WHERE`), or `None` (→ scan) when no index applies.
    fn try_index_in(
        &self,
        meta: &TableMeta,
        table_name: &str,
        sel: &Select,
        params: &Params,
    ) -> Result<Option<Vec<InputRow>>> {
        let Some(where_expr) = &sel.where_clause else {
            return Ok(None);
        };
        let hint = sel.from.as_ref().and_then(|f| f.first.index_hint.as_ref());
        if matches!(hint, Some(IndexHint::NotIndexed)) {
            return Ok(None);
        }
        let indexes = self.indexes_of(table_name)?;
        if let Some(IndexHint::IndexedBy(n)) = hint {
            if !indexes.iter().any(|i| i.name.eq_ignore_ascii_case(n)) {
                return Err(Error::Error(alloc::format!("no such index: {n}")));
            }
        }
        let by_name = |idx: &IndexMeta| match hint {
            Some(IndexHint::IndexedBy(n)) => idx.name.eq_ignore_ascii_case(n),
            _ => true,
        };

        // Column `IN (…)`: rowid b-tree, a plain index, or a partial index whose
        // leading column is the IN column (and whose predicate the WHERE proves).
        if let Some((col, values)) = find_in_constraint(where_expr, &meta.columns, params) {
            // `x IN (NULL)` is never true/usable as a seek key.
            if !values.iter().any(|v| matches!(v, Value::Null)) {
                let encoding = self.backend.source().header().text_encoding;
                let aff = meta.columns[col].affinity;

                // Rowid IN-list: seek the table b-tree directly for each value.
                if !matches!(hint, Some(IndexHint::IndexedBy(_))) {
                    if let Some(ipk) = meta.ipk {
                        if col == ipk {
                            let mut cur = TableCursor::new(self.backend.source(), meta.root);
                            let mut out = Vec::new();
                            let mut seen: Vec<i64> = Vec::new();
                            for v in &values {
                                let rid = eval::to_i64(v);
                                if seen.contains(&rid) {
                                    continue;
                                }
                                seen.push(rid);
                                if cur.seek(rid)? {
                                    let values =
                                        self.decode_full_row(meta, rid, &cur.payload()?, encoding)?;
                                    out.push(InputRow {
                                        values,
                                        rowid: Some(rid),
                                    });
                                }
                            }
                            return Ok(Some(out));
                        }
                    }
                }

                let keys: Vec<Vec<Value>> = values
                    .iter()
                    .map(|v| alloc::vec![aff.coerce(v.clone())])
                    .collect();
                // A plain index whose leading column is the IN column.
                for idx in &indexes {
                    if !by_name(idx) || idx.partial.is_some() || idx.key_exprs.is_some() {
                        continue;
                    }
                    if idx.cols.first() == Some(&col) {
                        if self.seek_index_covers(sel, meta, &idx.cols, where_expr) {
                            return Ok(Some(self.covering_seek_rows(meta, idx.root, &idx.cols)?));
                        }
                        let coll = idx.collations.first().copied().unwrap_or_default();
                        return Ok(Some(self.in_seek_fetch(meta, idx.root, &[coll], &keys)?));
                    }
                }
                // A3b: a partial index on the IN column with its predicate proven.
                for idx in &indexes {
                    if !by_name(idx) || idx.key_exprs.is_some() || idx.partial.is_none() {
                        continue;
                    }
                    if idx.cols.first() == Some(&col) && partial_pred_guaranteed(idx, where_expr) {
                        let coll = idx.collations.first().copied().unwrap_or_default();
                        return Ok(Some(self.in_seek_fetch(meta, idx.root, &[coll], &keys)?));
                    }
                }
            }
        }

        // A3b: an expression index keyed by `<expr>` with `<expr> IN (…)`.
        for idx in &indexes {
            if !by_name(idx) {
                continue;
            }
            let Some(exprs) = &idx.key_exprs else {
                continue;
            };
            let [key_expr] = exprs.as_slice() else {
                continue;
            };
            if !partial_pred_guaranteed(idx, where_expr) {
                continue;
            }
            let Some(values) = find_expr_in_values(key_expr, where_expr, params) else {
                continue;
            };
            if values.iter().any(|v| matches!(v, Value::Null)) {
                continue;
            }
            let coll = idx.collations.first().copied().unwrap_or_default();
            let keys: Vec<Vec<Value>> = values.iter().map(|v| alloc::vec![v.clone()]).collect();
            return Ok(Some(self.in_seek_fetch(meta, idx.root, &[coll], &keys)?));
        }

        Ok(None)
    }

    /// Find a plain (non-partial, non-expression) index whose leading column is
    /// `col`, returning its root page and leading collation. Honors `INDEXED BY`.
    fn leading_index_for(
        &self,
        table_name: &str,
        col: usize,
        hint: Option<&IndexHint>,
    ) -> Result<Option<(u32, crate::value::Collation)>> {
        for idx in &self.indexes_of(table_name)? {
            if let Some(IndexHint::IndexedBy(n)) = hint {
                if !idx.name.eq_ignore_ascii_case(n) {
                    continue;
                }
            }
            if idx.partial.is_some() || idx.key_exprs.is_some() {
                continue;
            }
            if idx.cols.first() == Some(&col) {
                return Ok(Some((
                    idx.root,
                    idx.collations.first().copied().unwrap_or_default(),
                )));
            }
        }
        Ok(None)
    }

    /// Rowids matching `col IN values` (or `col = v` with a one-element slice) via
    /// the rowid b-tree or an index, or `None` when neither applies.
    fn seek_col_values(
        &self,
        meta: &TableMeta,
        table_name: &str,
        hint: Option<&IndexHint>,
        col: usize,
        values: &[Value],
    ) -> Result<Option<Vec<i64>>> {
        let mut rowids: Vec<i64> = Vec::new();
        // Rowid column: each value is itself a candidate rowid.
        if !matches!(hint, Some(IndexHint::IndexedBy(_))) && meta.ipk == Some(col) {
            for v in values {
                let rid = eval::to_i64(v);
                if !rowids.contains(&rid) {
                    rowids.push(rid);
                }
            }
            return Ok(Some(rowids));
        }
        let Some((root, coll)) = self.leading_index_for(table_name, col, hint)? else {
            return Ok(None);
        };
        let aff = meta.columns[col].affinity;
        let colls = [coll];
        for v in values {
            let key = [aff.coerce(v.clone())];
            for rid in crate::btree::index_seek_rowids(self.backend.source(), root, &key, &colls)? {
                if !rowids.contains(&rid) {
                    rowids.push(rid);
                }
            }
        }
        Ok(Some(rowids))
    }

    /// Rowids matching a range `bound` on `col` via the rowid b-tree (integer
    /// bounds) or an index, or `None` when neither applies.
    fn seek_col_range(
        &self,
        meta: &TableMeta,
        table_name: &str,
        hint: Option<&IndexHint>,
        col: usize,
        bound: &RangeBound,
    ) -> Result<Option<Vec<i64>>> {
        // Rowid integer range: walk the table b-tree between bounds.
        if !matches!(hint, Some(IndexHint::IndexedBy(_))) && meta.ipk == Some(col) {
            let lo_int =
                bound.lower.is_none() || matches!(bound.lower, Some((Value::Integer(_), _)));
            let hi_int =
                bound.upper.is_none() || matches!(bound.upper, Some((Value::Integer(_), _)));
            if !(lo_int && hi_int) {
                return Ok(None);
            }
            let start = match &bound.lower {
                Some((Value::Integer(i), _)) => *i,
                _ => i64::MIN,
            };
            let stop = match &bound.upper {
                Some((Value::Integer(i), _)) => *i,
                _ => i64::MAX,
            };
            let mut cur = TableCursor::new(self.backend.source(), meta.root);
            let mut rowids = Vec::new();
            let mut ok = if start == i64::MIN {
                cur.first()?
            } else {
                cur.seek(start)?;
                cur.is_valid()
            };
            while ok {
                let rid = cur.rowid()?;
                if rid > stop {
                    break;
                }
                rowids.push(rid);
                ok = cur.next()?;
            }
            return Ok(Some(rowids));
        }
        let Some((root, coll)) = self.leading_index_for(table_name, col, hint)? else {
            return Ok(None);
        };
        let aff = meta.columns[col].affinity;
        let lo = bound
            .lower
            .as_ref()
            .map(|(v, i)| (aff.coerce(v.clone()), *i));
        let hi = bound
            .upper
            .as_ref()
            .map(|(v, i)| (aff.coerce(v.clone()), *i));
        let colls = [coll];
        let lower = lo.as_ref().map(|(v, i)| (core::slice::from_ref(v), *i));
        let upper = hi.as_ref().map(|(v, i)| (core::slice::from_ref(v), *i));
        let rowids =
            crate::btree::index_range_rowids(self.backend.source(), root, lower, upper, &colls)?;
        Ok(Some(rowids))
    }

    /// Rowids for one seekable predicate atom (`col = c`, `col IN (…)`, or a range
    /// on `col`), or `None` if it is not index/rowid-seekable. Superset semantics:
    /// the caller re-applies the full `WHERE`.
    fn predicate_rowids(
        &self,
        meta: &TableMeta,
        table_name: &str,
        hint: Option<&IndexHint>,
        pred: &Expr,
        params: &Params,
    ) -> Result<Option<Vec<i64>>> {
        if let Some((col, vals)) = find_in_constraint(pred, &meta.columns, params) {
            if vals.iter().any(|v| matches!(v, Value::Null)) {
                return Ok(None);
            }
            return self.seek_col_values(meta, table_name, hint, col, &vals);
        }
        let mut eqs: Vec<(usize, Value)> = Vec::new();
        collect_eq_constraints(pred, &meta.columns, params, &mut eqs);
        eqs.retain(|(_, v)| !matches!(v, Value::Null));
        if let Some((col, v)) = eqs.into_iter().next() {
            return self.seek_col_values(meta, table_name, hint, col, &[v]);
        }
        let mut ranges: alloc::collections::BTreeMap<usize, RangeBound> =
            alloc::collections::BTreeMap::new();
        collect_range_constraints(pred, &meta.columns, params, &mut ranges);
        if let Some((&col, bound)) = ranges.iter().next() {
            return self.seek_col_range(meta, table_name, hint, col, bound);
        }
        Ok(None)
    }

    /// Try to satisfy a single-table query whose `WHERE` is a top-level `OR` of
    /// individually-seekable predicates: seek each disjunct, union the rowids, and
    /// fetch the rows once. Returns `None` (→ scan) unless *every* disjunct is
    /// seekable. Superset semantics — `run_core` re-applies the full `WHERE`.
    fn try_index_or(
        &self,
        meta: &TableMeta,
        table_name: &str,
        sel: &Select,
        params: &Params,
    ) -> Result<Option<Vec<InputRow>>> {
        let Some(where_expr) = &sel.where_clause else {
            return Ok(None);
        };
        let hint = sel.from.as_ref().and_then(|f| f.first.index_hint.as_ref());
        if matches!(hint, Some(IndexHint::NotIndexed)) {
            return Ok(None);
        }
        // Flatten the top-level OR chain; require at least two disjuncts.
        let mut disjuncts: Vec<&Expr> = Vec::new();
        flatten_or(where_expr, &mut disjuncts);
        if disjuncts.len() < 2 {
            return Ok(None);
        }
        // Every disjunct must be seekable, else a scan is needed regardless.
        let mut rowids: Vec<i64> = Vec::new();
        for d in disjuncts {
            match self.predicate_rowids(meta, table_name, hint, d, params)? {
                Some(rs) => {
                    for r in rs {
                        if !rowids.contains(&r) {
                            rowids.push(r);
                        }
                    }
                }
                None => return Ok(None),
            }
        }
        let encoding = self.backend.source().header().text_encoding;
        let mut cur = TableCursor::new(self.backend.source(), meta.root);
        let mut out = Vec::new();
        for rid in rowids {
            if cur.seek(rid)? {
                let values = self.decode_full_row(meta, rid, &cur.payload()?, encoding)?;
                out.push(InputRow {
                    values,
                    rowid: Some(rid),
                });
            }
        }
        Ok(Some(out))
    }

    /// `EXPLAIN QUERY PLAN <stmt>` -> the `(id, parent, notused, detail)` rows
    /// that SQLite's API returns. The detail strings describe graphitesql's
    /// *actual* execution plan (it does not reorder joins), matching SQLite's
    /// format for the single-table SCAN/SEARCH cases.
    fn explain_query_plan(&self, stmt: &Statement, params: &Params) -> Result<QueryResult> {
        let mut details: Vec<(i64, i64, String)> = Vec::new();
        let mut next_id = 1i64;
        match stmt {
            Statement::Select(sel) => {
                self.eqp_select(sel, 0, &mut next_id, &mut details, params)?
            }
            Statement::Delete(d) => {
                let meta = self.table_meta(&d.table, None)?;
                let detail = self.eqp_access(
                    &d.table,
                    &d.table,
                    &meta,
                    d.where_clause.as_ref(),
                    None,
                    params,
                )?;
                details.push((next_id, 0, detail));
            }
            Statement::Update(u) => {
                let meta = self.table_meta(&u.table, None)?;
                let detail = self.eqp_access(
                    &u.table,
                    &u.table,
                    &meta,
                    u.where_clause.as_ref(),
                    None,
                    params,
                )?;
                details.push((next_id, 0, detail));
            }
            Statement::Insert(ins) => {
                if let InsertSource::Select(sel) = &ins.source {
                    self.eqp_select(sel, 0, &mut next_id, &mut details, params)?;
                }
            }
            _ => return Err(Error::Unsupported("EXPLAIN QUERY PLAN for this statement")),
        }
        Ok(QueryResult {
            columns: alloc::vec![
                String::from("id"),
                String::from("parent"),
                String::from("notused"),
                String::from("detail"),
            ],
            rows: details
                .into_iter()
                .map(|(id, parent, detail)| {
                    alloc::vec![
                        Value::Integer(id),
                        Value::Integer(parent),
                        Value::Integer(0),
                        Value::Text(detail),
                    ]
                })
                .collect(),
        })
    }

    /// Emit query-plan nodes for one SELECT under `parent`.
    /// EXPLAIN QUERY PLAN detail for a virtual-table scan: sqlite's
    /// `SCAN <label> VIRTUAL TABLE INDEX <idxNum>:<idxStr>`. The module's
    /// `best_index` chooses the plan from the offered `WHERE` constraints; a
    /// persistent module (which scans its backing table) reports a plain scan.
    fn eqp_vtab_detail(
        &self,
        name: &str,
        label: &str,
        sel: &Select,
        params: &Params,
    ) -> Result<String> {
        use crate::schema::ObjectType;
        let plain = || alloc::format!("SCAN {label} VIRTUAL TABLE INDEX 0:");
        let cvt = self
            .schema
            .objects()
            .iter()
            .find(|o| o.obj_type == ObjectType::Table && o.name.eq_ignore_ascii_case(name))
            .and_then(|o| o.sql.as_deref())
            .and_then(|s| match sql::parse_one(s) {
                Ok(Statement::CreateVirtualTable(cvt)) => Some(cvt),
                _ => None,
            });
        let Some(cvt) = cvt else { return Ok(plain()) };
        let Some(module) = self.vtab_registry.get(&cvt.module) else {
            return Ok(plain());
        };
        // The module's `best_index` chooses the reported plan from the offered
        // `WHERE` constraints — even for a persistent module, whose execution scans
        // `<name>_data` but whose reported `idxNum:idxStr` should still match SQLite
        // (e.g. rtree's spatial encoding). A module with no pushdown returns the
        // default plan, rendering the plain `INDEX 0:`.
        let arg_refs: Vec<&str> = cvt.args.iter().map(String::as_str).collect();
        let schema = module.dyn_connect(&arg_refs)?;
        let columns: Vec<ColumnInfo> = schema
            .columns
            .iter()
            .map(|n| ColumnInfo {
                name: n.clone(),
                table: label.to_string(),
                affinity: eval::Affinity::Blob,
                collation: crate::value::Collation::default(),
            })
            .collect();
        // FTS5's plan is driven by `MATCH` (a desugared `match()` function the
        // generic constraint collector doesn't see) and `ORDER BY rank`, so report
        // it directly to match sqlite's `xBestIndex`: `MATCH` is `M<col>` (the
        // matched column's 0-based index, or the column count for a table-wide
        // match), a rowid equality is `=`, and `ORDER BY rank` sets the
        // order-by-consumed bit (32) in idxNum.
        #[cfg(feature = "fts5")]
        if cvt.module.eq_ignore_ascii_case("fts5") {
            let mut idx_str = String::new();
            let mut matched = false;
            if let Some(where_expr) = &sel.where_clause {
                if let Some((_, operand)) = self.fts5_match_query(where_expr, params) {
                    let col = schema
                        .columns
                        .iter()
                        .position(|c| c.eq_ignore_ascii_case(&operand))
                        .unwrap_or(schema.columns.len());
                    idx_str = alloc::format!("M{col}");
                    matched = true;
                } else if fts5_rowid_eq(where_expr, params) {
                    idx_str.push('=');
                }
            }
            // With a MATCH, FTS5 can return rows already ordered by `rank` (idxNum
            // bit 32) or by `rowid` (bit 64), consuming the ORDER BY.
            let order_bit = if matched && sel.order_by.len() == 1 && !sel.order_by[0].descending {
                match &sel.order_by[0].expr {
                    Expr::Column {
                        table: None,
                        column,
                    } if column.eq_ignore_ascii_case("rank") => 32,
                    Expr::Column {
                        table: None,
                        column,
                    } if matches!(
                        column.to_ascii_lowercase().as_str(),
                        "rowid" | "_rowid_" | "oid"
                    ) =>
                    {
                        64
                    }
                    _ => 0,
                }
            } else {
                0
            };
            return Ok(alloc::format!(
                "SCAN {label} VIRTUAL TABLE INDEX {order_bit}:{idx_str}"
            ));
        }
        let (constraints, _) = collect_vtab_constraints(sel, &columns, params);
        let plan = module.dyn_best_index(&constraints)?;
        Ok(alloc::format!(
            "SCAN {label} VIRTUAL TABLE INDEX {}:{}",
            plan.idx_num,
            plan.idx_str.as_deref().unwrap_or("")
        ))
    }

    fn eqp_select(
        &self,
        sel: &Select,
        parent: i64,
        next_id: &mut i64,
        out: &mut Vec<(i64, i64, String)>,
        params: &Params,
    ) -> Result<()> {
        // Mirror run_core's comma-join → ON promotion so the plan reflects how the
        // query actually runs.
        let rewritten;
        let sel = match promote_comma_join_ons(sel) {
            Some(r) => {
                rewritten = r;
                &rewritten
            }
            None => sel,
        };
        let Some(from) = &sel.from else {
            return Ok(()); // SELECT with no FROM => no scan node
        };
        let label = eqp_label(&from.first);
        // A virtual table scans through its module, not a b-tree — render sqlite's
        // `VIRTUAL TABLE INDEX <n>:<str>` node and skip the regular-table planning
        // (which would otherwise parse the CREATE VIRTUAL TABLE as a CREATE TABLE
        // and fail).
        if from.joins.is_empty()
            && from.first.subquery.is_none()
            && from.first.tvf_args.is_none()
            && self.lookup_cte(&from.first.name, None).is_none()
            && self.is_virtual_table(&from.first.name)
        {
            let detail = self.eqp_vtab_detail(&from.first.name, &label, sel, params)?;
            let id = *next_id;
            *next_id += 1;
            out.push((id, parent, detail));
            return Ok(());
        }
        // First source.
        let meta = self.table_meta(&from.first.name, from.first.alias.as_deref())?;
        // A top-level OR of seekable disjuncts is a MULTI-INDEX OR plan (multiple
        // rows); otherwise a single SCAN/SEARCH node.
        if from.joins.is_empty()
            && self.eqp_or_plan(
                &label,
                &from.first.name,
                &meta,
                sel.where_clause.as_ref(),
                parent,
                next_id,
                out,
                params,
            )?
        {
            // rows already emitted
        } else {
            let detail = if from.joins.is_empty() {
                // `SELECT count(*)` answered by counting a full secondary index
                // (B2b) reads as `USING COVERING INDEX`. Kept in lockstep with
                // `run_core` via the shared `count_covering_index` helper.
                if let Some((name, _)) = self.count_covering_index(sel) {
                    alloc::format!("SCAN {label} USING COVERING INDEX {name}")
                }
                // A full index scanned to satisfy ORDER BY reads as `USING INDEX`,
                // or `USING COVERING INDEX` when it holds every referenced column.
                else if let Some(s) = self.order_index_scan(sel) {
                    let kind = if s.covering {
                        "COVERING INDEX"
                    } else {
                        "INDEX"
                    };
                    alloc::format!("SCAN {label} USING {kind} {}", s.name)
                }
                // A covered query with no seek reads from a covering index (B2),
                // in lockstep with `run_core`'s `covering_scan`.
                else if let Some((name, _, _)) = self.covering_scan(sel, &meta, params) {
                    alloc::format!("SCAN {label} USING COVERING INDEX {name}")
                } else {
                    self.eqp_access(
                        &label,
                        &from.first.name,
                        &meta,
                        sel.where_clause.as_ref(),
                        Some(sel),
                        params,
                    )?
                }
            } else {
                // Joins run in FROM order as nested-loop scans (no reordering).
                alloc::format!("SCAN {label}")
            };
            let id = *next_id;
            *next_id += 1;
            out.push((id, parent, detail));
        }
        // Fold each join in FROM order, tracking the accumulated left columns so
        // the rowid-seek decision (shared with the executor via `rowid_join_seek`)
        // can print `SEARCH … USING INTEGER PRIMARY KEY (rowid=?)` in lockstep
        // with how it actually runs.
        if !from.joins.is_empty() {
            let mut left_columns = self.resolve_join_source(&from.first, params)?.0;
            for join in &from.joins {
                let label = eqp_label(&join.table);
                // Most joins emit one plan row; an automatic-index (hash) join
                // emits two (a BLOOM FILTER then the SEARCH), so collect details.
                let (details, jcols): (Vec<String>, Vec<ColumnInfo>) = if let Some((
                    _,
                    inner_meta,
                )) =
                    self.rowid_join_seek(join, &left_columns)
                {
                    (
                        alloc::vec![alloc::format!(
                            "SEARCH {label} USING INTEGER PRIMARY KEY (rowid=?)"
                        )],
                        inner_meta.columns,
                    )
                } else if let Some((_, inner_meta, idx)) = self.index_join_seek(join, &left_columns)
                {
                    let col = &inner_meta.columns[idx.cols[0]].name;
                    (
                        alloc::vec![alloc::format!(
                            "SEARCH {label} USING INDEX {} ({col}=?)",
                            idx.name
                        )],
                        inner_meta.columns,
                    )
                } else if let Some((_, inner_meta)) =
                    self.without_rowid_pk_join_seek(join, &left_columns)
                {
                    let col = &inner_meta.columns[inner_meta.storage_order[0]].name;
                    let suffix = if matches!(join.kind, JoinKind::Left) {
                        " LEFT-JOIN"
                    } else {
                        ""
                    };
                    (
                        alloc::vec![alloc::format!(
                            "SEARCH {label} USING PRIMARY KEY ({col}=?){suffix}"
                        )],
                        inner_meta.columns,
                    )
                } else {
                    let jcols = self.resolve_join_source(&join.table, params)?.0;
                    // The executor builds a transient hash index for an INNER/LEFT
                    // equi-join (`ON l.x = r.y`) on an otherwise-unindexed inner
                    // table; SQLite reports that as a BLOOM FILTER + AUTOMATIC
                    // COVERING INDEX seek (NATURAL/USING and non-equi joins stay a
                    // plain SCAN, as graphite runs them with a nested loop).
                    let auto_col = if join.natural
                        || !join.using.is_empty()
                        || !matches!(join.kind, JoinKind::Inner | JoinKind::Left)
                    {
                        None
                    } else {
                        join.on.as_ref().and_then(|on| {
                            let mut combined = left_columns.clone();
                            combined.extend(jcols.iter().cloned());
                            join_equi_cols(on, &combined, left_columns.len())
                                .map(|(_, ri)| jcols[ri].name.clone())
                        })
                    };
                    match auto_col {
                        Some(col) => {
                            let suffix = if matches!(join.kind, JoinKind::Left) {
                                " LEFT-JOIN"
                            } else {
                                ""
                            };
                            (
                                alloc::vec![
                                    alloc::format!("BLOOM FILTER ON {label} ({col}=?)"),
                                    alloc::format!(
                                        "SEARCH {label} USING AUTOMATIC COVERING INDEX ({col}=?){suffix}"
                                    ),
                                ],
                                jcols,
                            )
                        }
                        None => (alloc::vec![alloc::format!("SCAN {label}")], jcols),
                    }
                };
                for detail in details {
                    let id = *next_id;
                    *next_id += 1;
                    out.push((id, parent, detail));
                }
                let left_width = left_columns.len();
                left_columns.extend(jcols);
                // Mirror the executor's NATURAL / USING coalescing: each join
                // column folds into its left output position and the right
                // duplicate is dropped, so a later join's `left_width` stays
                // aligned (a rowid-seek join never uses NATURAL / USING).
                if join.natural || !join.using.is_empty() {
                    let mut drop: Vec<usize> = if join.natural {
                        (left_width..left_columns.len())
                            .filter(|&rl| {
                                left_columns[..left_width]
                                    .iter()
                                    .any(|c| c.name.eq_ignore_ascii_case(&left_columns[rl].name))
                            })
                            .collect()
                    } else {
                        join.using
                            .iter()
                            .filter_map(|name| {
                                (left_width..left_columns.len())
                                    .find(|&rl| left_columns[rl].name.eq_ignore_ascii_case(name))
                            })
                            .collect()
                    };
                    drop.sort_unstable();
                    drop.dedup();
                    for &d in drop.iter().rev() {
                        left_columns.remove(d);
                    }
                }
            }
        }
        // ORDER BY that we satisfy with an in-memory sort — unless the scan already
        // yields the requested order (no temp b-tree then, like sqlite). When a
        // seek walks a *prefix* of the ORDER BY in order, only the trailing terms
        // are sorted, which sqlite reports as "LAST n TERM[S] OF ORDER BY".
        if !sel.order_by.is_empty() && self.order_satisfied_by_scan(sel, params).is_none() {
            let n = sel.order_by.len();
            // Only the trailing terms are sorted when the access walks a prefix of
            // the ORDER BY in order: a non-covering index walk (mixed direction,
            // `order_index_scan.sorted_suffix`), a WHERE seek (`seek_order_prefix`),
            // or a no-WHERE covering-index scan (`scan_order_prefix`).
            let sorted = if let Some(s) = self.order_index_scan(sel) {
                s.sorted_suffix.min(n)
            } else if let Some((k, _)) = self.seek_order_prefix(sel, params) {
                n - k.min(n)
            } else {
                n - self.scan_order_prefix(sel, params).min(n)
            };
            let detail = match sorted {
                _ if sorted >= n => String::from("USE TEMP B-TREE FOR ORDER BY"),
                1 => String::from("USE TEMP B-TREE FOR LAST TERM OF ORDER BY"),
                _ => alloc::format!("USE TEMP B-TREE FOR LAST {sorted} TERMS OF ORDER BY"),
            };
            let id = *next_id;
            *next_id += 1;
            out.push((id, parent, detail));
        }
        Ok(())
    }

    /// Emit a SQLite-style `MULTI-INDEX OR` plan when `where_clause` is a
    /// top-level `OR` whose every disjunct is index/rowid-seekable (i.e. each
    /// disjunct's [`eqp_access`](Self::eqp_access) yields a `SEARCH`). Returns
    /// `true` (rows pushed) when it applies, else `false` (caller emits the plain
    /// node). Mirrors [`try_index_or`](Self::try_index_or)'s applicability.
    #[allow(clippy::too_many_arguments)]
    fn eqp_or_plan(
        &self,
        label: &str,
        table: &str,
        meta: &TableMeta,
        where_clause: Option<&Expr>,
        parent: i64,
        next_id: &mut i64,
        out: &mut Vec<(i64, i64, String)>,
        params: &Params,
    ) -> Result<bool> {
        let Some(where_expr) = where_clause else {
            return Ok(false);
        };
        let mut disjuncts: Vec<&Expr> = Vec::new();
        flatten_or(where_expr, &mut disjuncts);
        if disjuncts.len() < 2 {
            return Ok(false);
        }
        // Each disjunct must seek (its eqp_access is a SEARCH, not a SCAN).
        let mut details = Vec::with_capacity(disjuncts.len());
        for d in &disjuncts {
            let detail = self.eqp_access(label, table, meta, Some(d), None, params)?;
            if !detail.starts_with("SEARCH") {
                return Ok(false);
            }
            details.push(detail);
        }
        let or_id = *next_id;
        *next_id += 1;
        out.push((or_id, parent, String::from("MULTI-INDEX OR")));
        for (i, detail) in details.into_iter().enumerate() {
            let idx_id = *next_id;
            *next_id += 1;
            out.push((idx_id, or_id, alloc::format!("INDEX {}", i + 1)));
            let search_id = *next_id;
            *next_id += 1;
            out.push((search_id, idx_id, detail));
        }
        Ok(true)
    }

    /// The SCAN/SEARCH detail string for accessing one table given its WHERE.
    /// `label` is the display name (alias if any); `table` is the real table
    /// name used to look up its indexes. `sel`, when present, is the enclosing
    /// `SELECT`: a seek whose index covers every referenced column reads as
    /// `USING COVERING INDEX` (B2b), kept in lockstep with the executor's
    /// [`seek_index_covers`](Self::seek_index_covers) decision. `None` (DELETE /
    /// UPDATE / OR-plan disjuncts, which all touch the table) never covers.
    fn eqp_access(
        &self,
        label: &str,
        table: &str,
        meta: &TableMeta,
        where_clause: Option<&Expr>,
        sel: Option<&Select>,
        params: &Params,
    ) -> Result<String> {
        let Some(where_expr) = where_clause else {
            return Ok(alloc::format!("SCAN {label}"));
        };
        // `INDEX` vs `COVERING INDEX` for a seek through `idx_cols`: the same
        // decision the executor's seek paths make via `seek_index_covers`.
        let index_kw = |idx_cols: &[usize]| -> &'static str {
            match sel {
                Some(s) if self.seek_index_covers(s, meta, idx_cols, where_expr) => {
                    "COVERING INDEX"
                }
                _ => "INDEX",
            }
        };
        let mut eqs: Vec<(usize, Value)> = Vec::new();
        collect_eq_constraints(where_expr, &meta.columns, params, &mut eqs);
        eqs.retain(|(_, v)| !matches!(v, Value::Null));
        // WITHOUT ROWID: the executor seeks the clustered PRIMARY KEY b-tree on a
        // leading-PK equality (`try_without_rowid_pk_seek`) and otherwise scans —
        // it never uses a secondary index — so report exactly that.
        if meta.without_rowid {
            let pk = &meta.storage_order[..meta.pk_len];
            // A leading-PK equality prefix (matches try_without_rowid_pk_seek).
            let mut names = Vec::new();
            for &c in pk {
                if eqs.iter().any(|(col, _)| *col == c) {
                    names.push(alloc::format!("{}=?", meta.columns[c].name));
                } else {
                    break;
                }
            }
            if !names.is_empty() {
                return Ok(alloc::format!(
                    "SEARCH {label} USING PRIMARY KEY ({})",
                    names.join(" AND ")
                ));
            }
            // Else a range bound on the leading PK column (try_without_rowid_pk_range).
            if let Some(&lead) = pk.first() {
                let mut ranges: alloc::collections::BTreeMap<usize, RangeBound> =
                    alloc::collections::BTreeMap::new();
                collect_range_constraints(where_expr, &meta.columns, params, &mut ranges);
                if let Some(b) = ranges.get(&lead) {
                    let name = &meta.columns[lead].name;
                    // SQLite renders bounds as `>`/`<` regardless of inclusivity.
                    let cond = match (&b.lower, &b.upper) {
                        (Some(_), Some(_)) => alloc::format!("{name}>? AND {name}<?"),
                        (Some(_), None) => alloc::format!("{name}>?"),
                        (None, Some(_)) => alloc::format!("{name}<?"),
                        (None, None) => String::new(),
                    };
                    if !cond.is_empty() {
                        return Ok(alloc::format!("SEARCH {label} USING PRIMARY KEY ({cond})"));
                    }
                }
            }
            // A secondary index whose leading column(s) the WHERE constrains by
            // equality (matches try_without_rowid_index_seek). Its records carry
            // the PK columns, so covering accounts for idx.cols ∪ pk.
            for idx in self.indexes_of(table)? {
                if idx.partial.is_some() || idx.key_exprs.is_some() {
                    continue;
                }
                let mut matched = Vec::new();
                for &c in &idx.cols {
                    if eqs.iter().any(|(col, _)| *col == c) {
                        matched.push(c);
                    } else {
                        break;
                    }
                }
                if matched.is_empty() {
                    continue;
                }
                let mut avail = idx.cols.clone();
                if !idx.name.starts_with("sqlite_autoindex_") {
                    for &p in pk {
                        if !avail.contains(&p) {
                            avail.push(p);
                        }
                    }
                }
                let kw = match sel {
                    Some(s) if self.seek_index_covers(s, meta, &avail, where_expr) => {
                        "COVERING INDEX"
                    }
                    _ => "INDEX",
                };
                let cond = matched
                    .iter()
                    .map(|&c| alloc::format!("{}=?", meta.columns[c].name))
                    .collect::<Vec<_>>()
                    .join(" AND ");
                return Ok(alloc::format!(
                    "SEARCH {label} USING {kw} {} ({cond})",
                    idx.name
                ));
            }
            // Else a range bound on a secondary index's leading column
            // (matches try_without_rowid_index_range).
            let mut ranges: alloc::collections::BTreeMap<usize, RangeBound> =
                alloc::collections::BTreeMap::new();
            collect_range_constraints(where_expr, &meta.columns, params, &mut ranges);
            for idx in self.indexes_of(table)? {
                if idx.partial.is_some() || idx.key_exprs.is_some() {
                    continue;
                }
                let Some(&lead) = idx.cols.first() else {
                    continue;
                };
                let Some(b) = ranges.get(&lead) else {
                    continue;
                };
                let name = &meta.columns[lead].name;
                let cond = match (&b.lower, &b.upper) {
                    (Some(_), Some(_)) => alloc::format!("{name}>? AND {name}<?"),
                    (Some(_), None) => alloc::format!("{name}>?"),
                    (None, Some(_)) => alloc::format!("{name}<?"),
                    (None, None) => continue,
                };
                let mut avail = idx.cols.clone();
                if !idx.name.starts_with("sqlite_autoindex_") {
                    for &p in pk {
                        if !avail.contains(&p) {
                            avail.push(p);
                        }
                    }
                }
                let kw = match sel {
                    Some(s) if self.seek_index_covers(s, meta, &avail, where_expr) => {
                        "COVERING INDEX"
                    }
                    _ => "INDEX",
                };
                return Ok(alloc::format!(
                    "SEARCH {label} USING {kw} {} ({cond})",
                    idx.name
                ));
            }
            return Ok(alloc::format!("SCAN {label}"));
        }
        // A `rowid`/`_rowid_`/`oid` `= N` or `IN (list)` seek wins (matches the
        // rowid fast path at the top of try_index_lookup), with or without an IPK.
        if rowid_seek_constraint(where_expr, &meta.columns, params).is_some() {
            return Ok(alloc::format!(
                "SEARCH {label} USING INTEGER PRIMARY KEY (rowid=?)"
            ));
        }
        // Rowid equality wins, as in try_index_lookup.
        if let Some(ipk) = meta.ipk {
            if eqs.iter().any(|(c, _)| *c == ipk) {
                return Ok(alloc::format!(
                    "SEARCH {label} USING INTEGER PRIMARY KEY (rowid=?)"
                ));
            }
        }
        // Index covering the longest leftmost prefix of equalities, preferring
        // the most selective one when `ANALYZE` statistics are available (kept in
        // step with the cost-based chooser in try_index_lookup).
        let stats = self.stat1_map();
        #[allow(clippy::type_complexity)]
        let mut best: Option<(String, Vec<usize>, Vec<usize>, u64)> = None;
        // Iterate the SAME index set `try_index_lookup` does (via `indexes_of`,
        // which includes the implicit `sqlite_autoindex_*` PK/UNIQUE indexes) so
        // the EQP reports the seek the executor actually performs — e.g. a
        // non-integer PRIMARY KEY or UNIQUE column reads as `SEARCH … USING INDEX
        // sqlite_autoindex_…`, not `SCAN`. Partial/expression indexes are handled
        // by the separate fallback below.
        for idx in self.indexes_of(table)? {
            if idx.partial.is_some() || idx.key_exprs.is_some() {
                continue;
            }
            let mut matched = Vec::new();
            for &c in &idx.cols {
                if eqs.iter().any(|(col, _)| *col == c) {
                    matched.push(c);
                } else {
                    break;
                }
            }
            if matched.is_empty() {
                continue;
            }
            let est = stats
                .get(&idx.name)
                .and_then(|s| s.get(matched.len()).copied())
                .unwrap_or(u64::MAX - matched.len() as u64);
            let better = match &best {
                None => true,
                Some((_, bm, _, be)) => est < *be || (est == *be && matched.len() > bm.len()),
            };
            if better {
                best = Some((idx.name.clone(), matched, idx.cols.clone(), est));
            }
        }
        if let Some((idx_name, matched, idx_cols, _)) = best {
            if !matched.is_empty() {
                let mut conds = matched
                    .iter()
                    .map(|&c| alloc::format!("{}=?", meta.columns[c].name))
                    .collect::<Vec<_>>();
                // A range on the column after the equality prefix is seeked too
                // (matches the eq-prefix + range path in try_index_lookup).
                if let Some(&next_col) = idx_cols.get(matched.len()) {
                    let mut ranges: alloc::collections::BTreeMap<usize, RangeBound> =
                        alloc::collections::BTreeMap::new();
                    collect_range_constraints(where_expr, &meta.columns, params, &mut ranges);
                    if let Some(b) = ranges.get(&next_col) {
                        let name = &meta.columns[next_col].name;
                        if b.lower.is_some() {
                            conds.push(alloc::format!("{name}>?"));
                        }
                        if b.upper.is_some() {
                            conds.push(alloc::format!("{name}<?"));
                        }
                    }
                }
                let kw = index_kw(&idx_cols);
                return Ok(alloc::format!(
                    "SEARCH {label} USING {kw} {idx_name} ({})",
                    conds.join(" AND ")
                ));
            }
        }

        // Partial / expression equality seek — in lockstep with the same
        // fallback in `try_index_lookup` (plain column indexes win first; this
        // fires only when none applied). `partial_expr_seek` proves eligibility.
        for idx in self.indexes_of(table)? {
            if self
                .partial_expr_seek(&idx, where_expr, meta, params)?
                .is_some()
            {
                let cond = match &idx.key_exprs {
                    // Partial column index: render the matched leading columns.
                    None => idx
                        .cols
                        .iter()
                        .take_while(|&&c| eqs.iter().any(|(col, _)| *col == c))
                        .map(|&c| alloc::format!("{}=?", meta.columns[c].name))
                        .collect::<Vec<_>>()
                        .join(" AND "),
                    // Expression index: the indexed expression compared to a value.
                    Some(_) => "<expr>=?".into(),
                };
                return Ok(alloc::format!(
                    "SEARCH {label} USING INDEX {} ({cond})",
                    idx.name
                ));
            }
        }

        // No equality index applied. Mirror run_core's remaining fast paths
        // (range, then IN) so the plan reflects what actually executes. Find the
        // name/columns of a plain index by its leading column.
        let leading_index = |target: usize| -> Option<(String, Vec<usize>)> {
            for obj in self.schema.indexes_on(table) {
                let sql = obj.sql.as_ref()?;
                let Ok(Statement::CreateIndex(ci)) = sql::parse_one(sql) else {
                    continue;
                };
                if ci.where_clause.is_some() {
                    continue;
                }
                let Ok(cols) = self.index_columns(meta, &ci) else {
                    continue;
                };
                if cols.first() == Some(&target) {
                    return Some((obj.name.clone(), cols));
                }
            }
            None
        };

        // Range scan: rowid (integer bounds) walks the table b-tree; an indexed
        // leading column seeks its index.
        let mut ranges: alloc::collections::BTreeMap<usize, RangeBound> =
            alloc::collections::BTreeMap::new();
        collect_range_constraints(where_expr, &meta.columns, params, &mut ranges);
        if let Some(ipk) = meta.ipk {
            if let Some(b) = ranges.get(&ipk) {
                let lo_int = b.lower.is_none() || matches!(b.lower, Some((Value::Integer(_), _)));
                let hi_int = b.upper.is_none() || matches!(b.upper, Some((Value::Integer(_), _)));
                if lo_int && hi_int {
                    let cond = match (&b.lower, &b.upper) {
                        (Some(_), Some(_)) => "rowid>? AND rowid<?",
                        (Some(_), None) => "rowid>?",
                        (None, Some(_)) => "rowid<?",
                        (None, None) => "",
                    };
                    if !cond.is_empty() {
                        return Ok(alloc::format!(
                            "SEARCH {label} USING INTEGER PRIMARY KEY ({cond})"
                        ));
                    }
                }
            }
        }
        for (&col, bound) in &ranges {
            if let Some((idx_name, idx_cols)) = leading_index(col) {
                let name = &meta.columns[col].name;
                // SQLite's EQP renders bounds as `>`/`<` regardless of inclusivity.
                let cond = match (&bound.lower, &bound.upper) {
                    (Some(_), Some(_)) => alloc::format!("{name}>? AND {name}<?"),
                    (Some(_), None) => alloc::format!("{name}>?"),
                    (None, Some(_)) => alloc::format!("{name}<?"),
                    (None, None) => continue,
                };
                let kw = index_kw(&idx_cols);
                return Ok(alloc::format!(
                    "SEARCH {label} USING {kw} {idx_name} ({cond})"
                ));
            }
        }

        // A3b: a partial or expression index range seek (mirrors the
        // `partial_expr_range` fallback in try_index_range; always non-covering).
        for idx in self.indexes_of(table)? {
            if let Some((bound, _)) = self.partial_expr_range(&idx, where_expr, meta, params) {
                let cond = |name: &str| match (&bound.lower, &bound.upper) {
                    (Some(_), Some(_)) => alloc::format!("{name}>? AND {name}<?"),
                    (Some(_), None) => alloc::format!("{name}>?"),
                    (None, Some(_)) => alloc::format!("{name}<?"),
                    (None, None) => String::new(),
                };
                let rendered = match &idx.key_exprs {
                    None => cond(&meta.columns[idx.cols[0]].name),
                    Some(_) => cond("<expr>"),
                };
                if !rendered.is_empty() {
                    return Ok(alloc::format!(
                        "SEARCH {label} USING INDEX {} ({rendered})",
                        idx.name
                    ));
                }
            }
        }

        // IN-list seek: rowid b-tree, a plain/partial index on the IN column, or
        // an expression index keyed by the IN'd expression (mirrors try_index_in).
        if let Some((col, _)) = find_in_constraint(where_expr, &meta.columns, params) {
            if meta.ipk == Some(col) {
                return Ok(alloc::format!(
                    "SEARCH {label} USING INTEGER PRIMARY KEY (rowid=?)"
                ));
            }
            if let Some((idx_name, idx_cols)) = leading_index(col) {
                let name = &meta.columns[col].name;
                let kw = index_kw(&idx_cols);
                return Ok(alloc::format!(
                    "SEARCH {label} USING {kw} {idx_name} ({name}=?)"
                ));
            }
            // A3b: a partial index on the IN column with its predicate proven.
            for idx in self.indexes_of(table)? {
                if idx.key_exprs.is_some() || idx.partial.is_none() {
                    continue;
                }
                if idx.cols.first() == Some(&col) && partial_pred_guaranteed(&idx, where_expr) {
                    let name = &meta.columns[col].name;
                    return Ok(alloc::format!(
                        "SEARCH {label} USING INDEX {} ({name}=?)",
                        idx.name
                    ));
                }
            }
        }
        // A3b: an expression index keyed by `<expr>` with `<expr> IN (…)`.
        for idx in self.indexes_of(table)? {
            let Some(exprs) = &idx.key_exprs else {
                continue;
            };
            let [key_expr] = exprs.as_slice() else {
                continue;
            };
            if partial_pred_guaranteed(&idx, where_expr)
                && find_expr_in_values(key_expr, where_expr, params).is_some()
            {
                return Ok(alloc::format!(
                    "SEARCH {label} USING INDEX {} (<expr>=?)",
                    idx.name
                ));
            }
        }

        Ok(alloc::format!("SCAN {label}"))
    }

    fn indexes_of(&self, table: &str) -> Result<Vec<IndexMeta>> {
        let tmeta = match self.schema.table(table) {
            Some(_) => self.table_meta(table, None)?,
            None => return Ok(Vec::new()),
        };
        let mut out = Vec::new();
        for obj in self.schema.indexes_on(table) {
            match &obj.sql {
                Some(sql) => {
                    let Statement::CreateIndex(ci) = sql::parse_one(sql)? else {
                        continue;
                    };
                    let (cols, key_exprs, collations) = self.index_key_spec(&tmeta, &ci)?;
                    out.push(IndexMeta {
                        name: obj.name.clone(),
                        root: obj.rootpage,
                        cols,
                        collations,
                        partial: ci.where_clause.clone(),
                        key_exprs,
                        unique: ci.unique,
                    });
                }
                // Automatic index: its columns are the n-th UNIQUE/PK set.
                None => {
                    if let Some(n) = autoindex_number(&obj.name, table) {
                        if let Some((cols, _)) = tmeta.unique.get(n - 1) {
                            let collations = self.col_collations(&tmeta, cols);
                            out.push(IndexMeta {
                                name: obj.name.clone(),
                                root: obj.rootpage,
                                cols: cols.clone(),
                                collations,
                                partial: None,
                                key_exprs: None,
                                unique: true,
                            });
                        }
                    }
                }
            }
        }
        Ok(out)
    }

    fn index_columns(&self, tmeta: &TableMeta, ci: &CreateIndex) -> Result<Vec<usize>> {
        Ok(self.index_columns_coll(tmeta, ci)?.0)
    }

    /// Resolve an index's columns to `(positions, collations)`. A column may
    /// carry an explicit `COLLATE name`; otherwise it inherits the table
    /// column's declared collation.
    fn index_columns_coll(
        &self,
        tmeta: &TableMeta,
        ci: &CreateIndex,
    ) -> Result<(Vec<usize>, Vec<crate::value::Collation>)> {
        let mut cols = Vec::new();
        let mut colls = Vec::new();
        for term in &ci.columns {
            // Peel an explicit COLLATE off the index column expression.
            let (inner, explicit) = match &term.expr {
                Expr::Collate { expr, collation } => {
                    (expr.as_ref(), crate::value::Collation::parse(collation))
                }
                e => (e, None),
            };
            let Expr::Column { column, .. } = inner else {
                return Err(Error::Unsupported("expression indexes"));
            };
            let pos = tmeta
                .columns
                .iter()
                .position(|c| c.name.eq_ignore_ascii_case(column))
                .ok_or_else(|| Error::Error(format!("no such column: {column}")))?;
            cols.push(pos);
            colls.push(explicit.unwrap_or(tmeta.columns[pos].collation));
        }
        Ok((cols, colls))
    }

    /// Resolve an index's key terms to `(cols, key_exprs, collations)`. When every
    /// term is a plain column, `key_exprs` is `None` and `cols` holds the column
    /// positions. When any term is an expression (`lower(x)`, `a + b`, …), it is
    /// an expression index: `key_exprs` holds the COLLATE-peeled term expressions
    /// (evaluated per row to form the key) and `cols` is empty.
    #[allow(clippy::type_complexity)]
    fn index_key_spec(
        &self,
        tmeta: &TableMeta,
        ci: &CreateIndex,
    ) -> Result<(Vec<usize>, Option<Vec<Expr>>, Vec<crate::value::Collation>)> {
        let mut cols = Vec::new();
        let mut exprs = Vec::new();
        let mut colls = Vec::new();
        let mut is_expr = false;
        for term in &ci.columns {
            let (inner, explicit) = match &term.expr {
                Expr::Collate { expr, collation } => {
                    (expr.as_ref(), crate::value::Collation::parse(collation))
                }
                e => (e, None),
            };
            exprs.push(inner.clone());
            match inner {
                Expr::Column { column, .. } => {
                    let pos = tmeta
                        .columns
                        .iter()
                        .position(|c| c.name.eq_ignore_ascii_case(column))
                        .ok_or_else(|| Error::Error(format!("no such column: {column}")))?;
                    cols.push(pos);
                    colls.push(explicit.unwrap_or(tmeta.columns[pos].collation));
                }
                _ => {
                    is_expr = true;
                    colls.push(explicit.unwrap_or_default());
                }
            }
        }
        if is_expr {
            Ok((Vec::new(), Some(exprs), colls))
        } else {
            Ok((cols, None, colls))
        }
    }

    /// The on-disk index key bytes for `idx` over a table row: evaluated key
    /// expressions for an expression index, else the column values.
    fn index_key_bytes(
        &self,
        idx: &IndexMeta,
        meta: &TableMeta,
        values: &[Value],
        rowid: i64,
        params: &Params,
    ) -> Result<Vec<u8>> {
        match &idx.key_exprs {
            None => Ok(index_key(&idx.cols, values, rowid)),
            Some(exprs) => {
                let ctx = row_ctx(values, &meta.columns, Some(rowid), params).with_subqueries(self);
                let mut key: Vec<Value> = exprs
                    .iter()
                    .map(|e| eval::eval(e, &ctx))
                    .collect::<Result<_>>()?;
                key.push(Value::Integer(rowid));
                Ok(encode_record(&key))
            }
        }
    }

    /// The declared collations of a set of table columns (for autoindexes).
    fn col_collations(&self, tmeta: &TableMeta, cols: &[usize]) -> Vec<crate::value::Collation> {
        cols.iter().map(|&c| tmeta.columns[c].collation).collect()
    }

    /// Whether a row belongs in `idx`: always for a full index, else whether the
    /// partial-index predicate holds for the row.
    fn row_in_index(
        &self,
        idx: &IndexMeta,
        tmeta: &TableMeta,
        values: &[Value],
        rowid: Option<i64>,
        params: &Params,
    ) -> Result<bool> {
        match &idx.partial {
            None => Ok(true),
            Some(pred) => {
                let ctx = row_ctx(values, &tmeta.columns, rowid, params).with_subqueries(self);
                Ok(eval::truth(&eval::eval(pred, &ctx)?) == Some(true))
            }
        }
    }

    /// Rebuild every index of a table in place (used after DELETE/UPDATE).
    fn rebuild_indexes(&mut self, tmeta: &TableMeta, indexes: &[IndexMeta]) -> Result<()> {
        if indexes.is_empty() {
            return Ok(());
        }
        let rows = self.scan_table(tmeta)?;
        let no_params = Params::default();
        // Precompute, per index, the key bytes for each included row (partial
        // predicate + expression evaluation) before taking the writer borrow.
        let mut per_index: Vec<Vec<Vec<u8>>> = Vec::with_capacity(indexes.len());
        for idx in indexes {
            let mut keys = Vec::new();
            for (rowid, values) in &rows {
                if self.row_in_index(idx, tmeta, values, Some(*rowid), &no_params)? {
                    keys.push(self.index_key_bytes(idx, tmeta, values, *rowid, &no_params)?);
                }
            }
            per_index.push(keys);
        }
        let w = self.backend.writer()?;
        for (idx, keys) in indexes.iter().zip(&per_index) {
            clear_index(w, idx.root)?;
            for key in keys {
                insert_index(w, idx.root, key, &idx.collations)?;
            }
        }
        Ok(())
    }

    /// Rowids of rows in `meta` satisfying `pred` (all rows if `None`).
    /// Reduce candidate rowids by an `UPDATE`/`DELETE` `ORDER BY … LIMIT …`
    /// clause (the SQLite update/delete-limit extension): order the rows by the
    /// terms, then apply `OFFSET`/`LIMIT` (a negative limit means no limit). With
    /// no `ORDER BY`, the candidates keep their scan (rowid) order.
    fn order_limit_rowids(
        &self,
        meta: &TableMeta,
        rowids: Vec<i64>,
        order_by: &[OrderTerm],
        limit: Option<&Expr>,
        offset: Option<&Expr>,
        params: &Params,
    ) -> Result<Vec<i64>> {
        let mut rowids = rowids;
        if !order_by.is_empty() {
            let mut keyed: Vec<(i64, Vec<Value>)> = Vec::with_capacity(rowids.len());
            for rid in rowids {
                let row = self.read_row(meta, rid)?.unwrap_or_default();
                let ctx = row_ctx(&row, &meta.columns, Some(rid), params).with_subqueries(self);
                let keys = order_by
                    .iter()
                    .map(|t| eval::eval(&t.expr, &ctx))
                    .collect::<Result<Vec<_>>>()?;
                keyed.push((rid, keys));
            }
            keyed.sort_by(|a, b| {
                for (i, t) in order_by.iter().enumerate() {
                    let o = cmp_order(
                        &a.1[i],
                        &b.1[i],
                        t.descending,
                        t.nulls_first,
                        crate::value::Collation::Binary,
                    );
                    if o != core::cmp::Ordering::Equal {
                        return o;
                    }
                }
                core::cmp::Ordering::Equal
            });
            rowids = keyed.into_iter().map(|(r, _)| r).collect();
        }
        let off = match offset {
            Some(e) => must_be_int(eval::eval(
                e,
                &EvalCtx::rowless(params).with_subqueries(self),
            )?)?
            .max(0) as usize,
            None => 0,
        };
        if off > 0 {
            rowids.drain(0..off.min(rowids.len()));
        }
        if let Some(e) = limit {
            let n = eval::to_i64(&eval::eval(e, &EvalCtx::rowless(params))?);
            if n >= 0 {
                rowids.truncate(n as usize);
            }
        }
        Ok(rowids)
    }

    fn matching_rowids(
        &self,
        meta: &TableMeta,
        pred: Option<&Expr>,
        params: &Params,
    ) -> Result<Vec<i64>> {
        let mut out = Vec::new();
        let mut cur = TableCursor::new(self.backend.source(), meta.root);
        let encoding = self.backend.source().header().text_encoding;
        let mut ok = cur.first()?;
        while ok {
            let rowid = cur.rowid()?;
            let values = self.decode_full_row(meta, rowid, &cur.payload()?, encoding)?;
            let keep = match pred {
                Some(p) => {
                    let ctx =
                        row_ctx(&values, &meta.columns, Some(rowid), params).with_subqueries(self);
                    eval::truth(&eval::eval(p, &ctx)?) == Some(true)
                }
                None => true,
            };
            if keep {
                out.push(rowid);
            }
            ok = cur.next()?;
        }
        Ok(out)
    }

    /// The next rowid to assign for the table b-tree at `root` (max + 1, or 1).
    fn next_rowid(&self, root: u32) -> Result<i64> {
        let mut cur = TableCursor::new(self.backend.source(), root);
        if cur.last()? {
            Ok(cur.rowid()? + 1)
        } else {
            Ok(1)
        }
    }

    // ---- SELECT execution ---------------------------------------------------

    /// The cap (`LIMIT`+`OFFSET`) to bound a recursive CTE by, when `sel` streams a
    /// single recursive CTE 1:1 — `SELECT <cols> FROM <rcte> LIMIT k [OFFSET o]`
    /// with no WHERE / ORDER BY / GROUP BY / DISTINCT / join / aggregate / compound.
    /// Then an unterminated recursion still yields `k` rows, as sqlite (which
    /// evaluates the CTE lazily) does; the outer LIMIT/OFFSET still slice as usual.
    fn recursive_cte_outer_cap(&self, sel: &Select, params: &Params) -> Option<usize> {
        if sel.ctes.len() != 1
            || !sel.compound.is_empty()
            || sel.distinct
            || !sel.group_by.is_empty()
            || !sel.order_by.is_empty()
            || sel.where_clause.is_some()
            || sel.having.is_some()
            || self.has_aggregate(sel)
        {
            return None;
        }
        let cte = &sel.ctes[0];
        if !references_name(&cte.select, &cte.name) {
            return None; // not a recursive CTE
        }
        let from = sel.from.as_ref()?;
        if !from.joins.is_empty()
            || from.first.subquery.is_some()
            || from.first.tvf_args.is_some()
            || !from.first.name.eq_ignore_ascii_case(&cte.name)
        {
            return None;
        }
        let ctx = EvalCtx::rowless(params).with_subqueries(self);
        let n = must_be_int(eval::eval(sel.limit.as_ref()?, &ctx).ok()?).ok()?;
        if n < 0 {
            return None; // a negative LIMIT is unbounded — nothing to cap with
        }
        let offset = match &sel.offset {
            Some(e) => must_be_int(eval::eval(e, &ctx).ok()?).ok()?.max(0) as usize,
            None => 0,
        };
        Some((n as usize).saturating_add(offset))
    }

    fn run_select(&self, sel: &Select, params: &Params) -> Result<QueryResult> {
        // An explicit `COLLATE <name>` that is actually consumed (a comparison,
        // ORDER BY/GROUP BY/DISTINCT key, IN/BETWEEN, or min/max) must name a known
        // collating sequence — sqlite errors "no such collation sequence" there
        // (but not on an unused projection COLLATE). Nested subqueries validate
        // themselves when they run.
        validate_used_collations(sel)?;
        // Materialize this query's `WITH` CTEs into the environment for the
        // duration of the query, then restore the previous scope. (The opt-in
        // VDBE fast path is attempted per query block inside `run_core`, so it
        // also covers each arm of a compound query.)
        let base = self.cte_env.borrow().len();
        let outer_cap = self.recursive_cte_outer_cap(sel, params);
        let pushed = self.push_ctes(&sel.ctes, params, outer_cap);
        let result = pushed.and_then(|()| self.run_select_compound(sel, params));
        self.cte_env.borrow_mut().truncate(base);
        result
    }

    fn run_select_compound(&self, sel: &Select, params: &Params) -> Result<QueryResult> {
        if sel.compound.is_empty() {
            return self.run_core(sel, params);
        }
        // Compound query: run the first core (without the trailing ORDER BY/LIMIT
        // and compound tail), then fold in each operand, then order/limit the whole.
        let mut first = sel.clone();
        first.compound = Vec::new();
        first.order_by = Vec::new();
        first.limit = None;
        first.offset = None;
        let mut result = self.run_core(&first, params)?;
        // Compound set operations (UNION/INTERSECT/EXCEPT) compare rows under the
        // left SELECT's per-column collations.
        let colls = {
            let (cols, _) = self.scan_source(&first, params)?;
            self.output_collations(&first, &cols, params)
        };
        // A multi-row `VALUES (…),(…)` desugars to a `UNION ALL` chain whose
        // operands are bare FROM-less projections auto-aliased `column1`,
        // `column2`, … (see `values_core`); an explicit `SELECT … UNION ALL
        // SELECT …` is also FROM-less but does not carry those aliases. SQLite
        // rejects a column-count mismatch in either case but with different
        // wording, so pick the message by which kind this is — matching only the
        // VALUES alias shape avoids misreporting an explicit `UNION ALL`.
        let is_values = sel.from.is_none()
            && sel.where_clause.is_none()
            && sel.group_by.is_empty()
            && is_values_projection(&sel.columns)
            && sel.compound.iter().all(|(op, c)| {
                *op == CompoundOp::UnionAll && c.from.is_none() && is_values_projection(&c.columns)
            });
        for (op, operand) in &sel.compound {
            // Run the operand fully: a `VALUES (…),(…)` operand desugars to a
            // SELECT carrying its extra rows in its *own* compound tail, so it
            // must be expanded (not just its first core) or those rows are lost.
            let r = self.run_select_compound(operand, params)?;
            // Every operand of a compound query (and every row of a multi-row
            // `VALUES`) must project the same number of columns. SQLite rejects a
            // mismatch; match that (errors-vs-succeeds, not exact text).
            if r.columns.len() != result.columns.len() {
                return Err(Error::Error(if is_values {
                    "all VALUES must have the same number of terms".into()
                } else {
                    // SQLite names the specific operator at the mismatch.
                    let kw = match op {
                        CompoundOp::Union => "UNION",
                        CompoundOp::UnionAll => "UNION ALL",
                        CompoundOp::Intersect => "INTERSECT",
                        CompoundOp::Except => "EXCEPT",
                    };
                    alloc::format!(
                        "SELECTs to the left and right of {kw} do not have the same \
                         number of result columns"
                    )
                }));
            }
            result.rows = apply_compound(*op, result.rows, r.rows, &colls);
        }
        // A dedup set operation (UNION/INTERSECT/EXCEPT) yields rows in sorted
        // order in SQLite — its dedup is implemented via a sorter — whereas
        // UNION ALL preserves order. With no explicit ORDER BY, sort the combined
        // result by all output columns (ascending, under each column's collation;
        // NULLs first) to match. An explicit ORDER BY is applied below instead.
        if sel.order_by.is_empty()
            && sel
                .compound
                .iter()
                .any(|(op, _)| *op != CompoundOp::UnionAll)
        {
            result.rows.sort_by(|a, b| {
                for (i, va) in a.iter().enumerate() {
                    let coll = colls.get(i).copied().unwrap_or_default();
                    let ord = crate::value::cmp_values_coll(va, &b[i], coll);
                    if ord != core::cmp::Ordering::Equal {
                        return ord;
                    }
                }
                core::cmp::Ordering::Equal
            });
        }
        self.compound_order_limit(&mut result, sel, params, &colls)?;
        Ok(result)
    }

    /// Apply a compound query's overall `ORDER BY` / `LIMIT` / `OFFSET` to the
    /// already-combined rows (terms must reference output columns by position or
    /// name).
    fn compound_order_limit(
        &self,
        result: &mut QueryResult,
        sel: &Select,
        params: &Params,
        colls: &[crate::value::Collation],
    ) -> Result<()> {
        if !sel.order_by.is_empty() {
            // A positional ORDER BY term must name an output column (SQLite).
            check_positional_terms(&[], &sel.order_by, result.columns.len())?;
            let mut keys = Vec::new();
            for (i, term) in sel.order_by.iter().enumerate() {
                let idx = resolve_order_index(&term.expr, &result.columns, result.columns.len())
                    .ok_or_else(|| {
                        // SQLite: a compound ORDER BY term must name an output
                        // column (by position or alias); an arbitrary expression
                        // is rejected with the term's 1-based ordinal.
                        Error::Error(alloc::format!(
                            "{} ORDER BY term does not match any column in the result set",
                            ordinal(i + 1),
                        ))
                    })?;
                // The output column's collation (from the left SELECT) applies.
                let coll = colls.get(idx).copied().unwrap_or_default();
                keys.push((idx, term.descending, term.nulls_first, coll));
            }
            result.rows.sort_by(|a, b| {
                for (idx, desc, nf, coll) in &keys {
                    let ord = cmp_order(&a[*idx], &b[*idx], *desc, *nf, *coll);
                    if ord != core::cmp::Ordering::Equal {
                        return ord;
                    }
                }
                core::cmp::Ordering::Equal
            });
        }
        let offset = match &sel.offset {
            Some(e) => must_be_int(eval::eval(
                e,
                &EvalCtx::rowless(params).with_subqueries(self),
            )?)?
            .max(0) as usize,
            None => 0,
        };
        // A negative LIMIT means "no limit" in SQLite (OFFSET still applies).
        let limit = match &sel.limit {
            Some(e) => {
                let n = must_be_int(eval::eval(
                    e,
                    &EvalCtx::rowless(params).with_subqueries(self),
                )?)?;
                if n < 0 {
                    None
                } else {
                    Some(n as usize)
                }
            }
            None => None,
        };
        if offset > 0 {
            result.rows.drain(0..offset.min(result.rows.len()));
        }
        if let Some(n) = limit {
            result.rows.truncate(n);
        }
        Ok(())
    }

    /// Compute every window function in `sel` over `rows`, append each result as
    /// a synthetic column on `columns`/`rows`, and return a rewritten `SELECT`
    /// whose projection/ORDER BY reference those columns.
    fn apply_windows(
        &self,
        sel: &Select,
        columns: &mut Vec<ColumnInfo>,
        rows: &mut [InputRow],
        params: &Params,
    ) -> Result<Select> {
        let wins = window::collect_window_exprs(sel);
        let mut new_sel = sel.clone();
        for (k, wexpr) in wins.iter().enumerate() {
            // Resolve `OVER name` against the query's WINDOW definitions, then
            // compute with the resolved spec (but replace the original node).
            let resolved = resolve_window_ref(wexpr, &sel.window_defs)?;
            let values = self.compute_window(&resolved, columns, rows, params)?;
            let col_name = alloc::format!("__win{k}");
            columns.push(ColumnInfo {
                name: col_name.clone(),
                table: String::new(),
                affinity: eval::Affinity::Blob,
                collation: crate::value::Collation::default(),
            });
            for (row, v) in rows.iter_mut().zip(values) {
                row.values.push(v);
            }
            let repl = Expr::Column {
                table: None,
                column: col_name,
            };
            window::replace_window_expr(&mut new_sel, wexpr, &repl);
        }
        Ok(new_sel)
    }

    /// Compute one window function across all `rows`, returning a value per row
    /// (aligned with `rows`).
    fn compute_window(
        &self,
        wexpr: &Expr,
        columns: &[ColumnInfo],
        rows: &[InputRow],
        params: &Params,
    ) -> Result<Vec<Value>> {
        let Expr::Function {
            name,
            distinct,
            args,
            star,
            filter,
            over: Some(spec),
            ..
        } = wexpr
        else {
            return Err(Error::Error("not a window function".into()));
        };
        // SQLite rejects DISTINCT in a window function.
        if *distinct {
            return Err(Error::Error(
                "DISTINCT is not supported for window functions".into(),
            ));
        }
        let lname = name.to_ascii_lowercase();
        let n = rows.len();

        // Arity validation for the built-in ranking/value window functions (an
        // aggregate used as a window function — `sum(x) OVER …` — falls through to
        // the aggregate path). SQLite rejects a wrong count: `row_number(1)`,
        // `lag()`, `ntile()`, `nth_value(1)` are all "wrong number of arguments".
        let win_arity: Option<(usize, usize)> = match lname.as_str() {
            "row_number" | "rank" | "dense_rank" | "percent_rank" | "cume_dist" => Some((0, 0)),
            "ntile" | "first_value" | "last_value" => Some((1, 1)),
            "nth_value" => Some((2, 2)),
            "lag" | "lead" => Some((1, 3)),
            _ => None,
        };
        if let Some((lo, hi)) = win_arity {
            if args.len() < lo || args.len() > hi {
                return Err(Error::Error(alloc::format!(
                    "wrong number of arguments to function {lname}()"
                )));
            }
        }

        // Per-row partition keys, order keys, argument values, and FILTER mask.
        let mut part_keys: Vec<Vec<Value>> = Vec::with_capacity(n);
        let mut ord_keys: Vec<Vec<Value>> = Vec::with_capacity(n);
        let mut arg_vals: Vec<Vec<Value>> = Vec::with_capacity(n);
        let mut passes: Vec<bool> = Vec::with_capacity(n);
        for r in rows {
            let ctx = r.ctx(columns, params).with_subqueries(self);
            part_keys.push(
                spec.partition_by
                    .iter()
                    .map(|e| eval::eval(e, &ctx))
                    .collect::<Result<_>>()?,
            );
            ord_keys.push(
                spec.order_by
                    .iter()
                    .map(|t| eval::eval(&t.expr, &ctx))
                    .collect::<Result<_>>()?,
            );
            arg_vals.push(
                args.iter()
                    .map(|e| eval::eval(e, &ctx))
                    .collect::<Result<_>>()?,
            );
            // FILTER (WHERE …) restricts which rows the aggregate sees.
            passes.push(match filter {
                Some(pred) => eval::truth(&eval::eval(pred, &ctx)?) == Some(true),
                None => true,
            });
        }
        let descending: Vec<bool> = spec.order_by.iter().map(|t| t.descending).collect();

        // Partition rows by partition key, preserving first-seen order.
        let mut partitions: Vec<Vec<usize>> = Vec::new();
        let mut part_of: Vec<usize> = Vec::new();
        for i in 0..n {
            let p = partitions
                .iter()
                .position(|members| rows_equal(&part_keys[members[0]], &part_keys[i]));
            match p {
                Some(idx) => {
                    partitions[idx].push(i);
                    part_of.push(idx);
                }
                None => {
                    part_of.push(partitions.len());
                    partitions.push(alloc::vec![i]);
                }
            }
        }

        let mut result = alloc::vec![Value::Null; n];
        for members in &partitions {
            // Order the partition's rows (stable).
            let mut ordered = members.clone();
            ordered.sort_by(|&a, &b| cmp_keys(&ord_keys[a], &ord_keys[b], &descending));
            self.fill_window_partition(
                &lname,
                *star,
                &ordered,
                &ord_keys,
                &arg_vals,
                &passes,
                spec,
                &mut result,
            )?;
        }
        Ok(result)
    }

    /// Fill `result` for one ordered partition `ordered` (indices into the row
    /// arrays), honoring `spec`'s frame (or the default frame).
    #[allow(clippy::too_many_arguments)]
    fn fill_window_partition(
        &self,
        lname: &str,
        star: bool,
        ordered: &[usize],
        ord_keys: &[Vec<Value>],
        arg_vals: &[Vec<Value>],
        passes: &[bool],
        spec: &WindowSpec,
        result: &mut [Value],
    ) -> Result<()> {
        let m = ordered.len();
        // Peer-group id per ordered position (for RANGE/GROUPS frames).
        let mut gid = alloc::vec![0usize; m];
        for q in 1..m {
            gid[q] = gid[q - 1]
                + usize::from(
                    !cmp_keys(&ord_keys[ordered[q - 1]], &ord_keys[ordered[q]], &[]).is_eq(),
                );
        }
        // The single ORDER BY value per ordered position, for RANGE value
        // offsets (`RANGE n PRECEDING/FOLLOWING`, which SQLite restricts to one
        // ordering term), and its direction.
        let ovals: Vec<Value> = if spec.order_by.len() == 1 {
            ordered
                .iter()
                .map(|&i| ord_keys[i].first().cloned().unwrap_or(Value::Null))
                .collect()
        } else {
            Vec::new()
        };
        let desc = spec.order_by.first().map(|t| t.descending).unwrap_or(false);
        // The frame's EXCLUDE clause (default NO OTHERS).
        let exclude = spec
            .frame
            .as_ref()
            .map(|f| f.exclude)
            .unwrap_or(FrameExclude::NoOthers);
        // Ranking values per ordered position.
        for p in 0..m {
            let idx = ordered[p];
            let (fstart, fend) = frame_bounds(p, m, &gid, spec, &ovals, desc);
            // Positions of the frame after applying EXCLUDE.
            let fpos: Vec<usize> = (fstart..fend)
                .filter(|&k| match exclude {
                    FrameExclude::NoOthers => true,
                    FrameExclude::CurrentRow => k != p,
                    FrameExclude::Group => gid[k] != gid[p],
                    FrameExclude::Ties => gid[k] != gid[p] || k == p,
                })
                .collect();
            let val = match lname {
                "row_number" => Value::Integer(p as i64 + 1),
                "rank" => {
                    // 1 + number of strictly-preceding rows by order key.
                    let mut r = p;
                    while r > 0 && cmp_keys(&ord_keys[ordered[r - 1]], &ord_keys[idx], &[]).is_eq()
                    {
                        r -= 1;
                    }
                    Value::Integer(r as i64 + 1)
                }
                "dense_rank" => {
                    let mut dr = 1i64;
                    for q in 1..=p {
                        if !cmp_keys(&ord_keys[ordered[q - 1]], &ord_keys[ordered[q]], &[]).is_eq()
                        {
                            dr += 1;
                        }
                    }
                    Value::Integer(dr)
                }
                "percent_rank" => {
                    // (rank - 1) / (rows - 1); 0 for a single-row partition.
                    let mut r = p;
                    while r > 0 && cmp_keys(&ord_keys[ordered[r - 1]], &ord_keys[idx], &[]).is_eq()
                    {
                        r -= 1;
                    }
                    if m > 1 {
                        Value::Real(r as f64 / (m - 1) as f64)
                    } else {
                        Value::Real(0.0)
                    }
                }
                "cume_dist" => {
                    // (# rows ordered <= current, incl. peers) / rows.
                    let mut last = p;
                    while last + 1 < m
                        && cmp_keys(&ord_keys[idx], &ord_keys[ordered[last + 1]], &[]).is_eq()
                    {
                        last += 1;
                    }
                    Value::Real((last + 1) as f64 / m as f64)
                }
                "ntile" => {
                    // SQLite takes the integer value (truncating a real, parsing
                    // text) and requires it >= 1, else errors.
                    let buckets = arg_vals[idx].first().map(eval::to_i64).unwrap_or(0);
                    if buckets < 1 {
                        return Err(Error::Error(
                            "argument of ntile must be a positive integer".into(),
                        ));
                    }
                    Value::Integer(ntile_bucket(p, m, buckets))
                }
                "lag" | "lead" => {
                    let offset = arg_vals[idx].get(1).map(eval::to_i64).unwrap_or(1);
                    let default = arg_vals[idx].get(2).cloned().unwrap_or(Value::Null);
                    let target = if lname == "lag" {
                        p as i64 - offset
                    } else {
                        p as i64 + offset
                    };
                    if target >= 0 && (target as usize) < m {
                        arg_vals[ordered[target as usize]]
                            .first()
                            .cloned()
                            .unwrap_or(Value::Null)
                    } else {
                        default
                    }
                }
                "first_value" => fpos
                    .first()
                    .and_then(|&k| arg_vals[ordered[k]].first().cloned())
                    .unwrap_or(Value::Null),
                "last_value" => fpos
                    .last()
                    .and_then(|&k| arg_vals[ordered[k]].first().cloned())
                    .unwrap_or(Value::Null),
                "nth_value" => {
                    // SQLite requires the second argument to be a positive integer
                    // under numeric affinity: 2.0 and '2' are accepted, but 1.5,
                    // 0, a negative, or NULL error.
                    let raw = arg_vals[idx].get(1).cloned().unwrap_or(Value::Null);
                    let nth = match eval::Affinity::Numeric.coerce(raw) {
                        Value::Integer(n) if n >= 1 => n,
                        _ => {
                            return Err(Error::Error(
                                "second argument to nth_value must be a positive integer".into(),
                            ))
                        }
                    };
                    // nth row within the (post-EXCLUDE) frame (1-based).
                    fpos.get((nth - 1) as usize)
                        .and_then(|&k| arg_vals[ordered[k]].first().cloned())
                        .unwrap_or(Value::Null)
                }
                // Aggregate windows over the frame (honoring any FILTER mask).
                _ => {
                    let frame: Vec<&Vec<Value>> = fpos
                        .iter()
                        .filter(|&&k| passes[ordered[k]])
                        .map(|&k| &arg_vals[ordered[k]])
                        .collect();
                    window_aggregate(lname, star, &frame)?
                }
            };
            result[idx] = val;
        }
        Ok(())
    }

    /// The collating sequence to apply to each `ORDER BY` term (an explicit
    /// `COLLATE`, else the underlying column's collation, else `BINARY`).
    fn order_collations(
        &self,
        sel: &Select,
        columns: &[ColumnInfo],
        params: &Params,
    ) -> Vec<crate::value::Collation> {
        let ctx = row_ctx(&[], columns, None, params);
        sel.order_by
            .iter()
            .map(|t| eval::key_collation(&t.expr, &ctx))
            .collect()
    }

    /// The collation of each projected output column (a column's collation, an
    /// explicit `COLLATE`, else `BINARY`). Wildcards expand to the source columns.
    fn output_collations(
        &self,
        sel: &Select,
        columns: &[ColumnInfo],
        params: &Params,
    ) -> Vec<crate::value::Collation> {
        let ctx = row_ctx(&[], columns, None, params);
        let mut out = Vec::new();
        for col in &sel.columns {
            match col {
                ResultColumn::Expr { expr, .. } => out.push(eval::key_collation(expr, &ctx)),
                ResultColumn::Wildcard => {
                    out.extend(columns.iter().map(|c| c.collation));
                }
                ResultColumn::TableWildcard(t) => out.extend(
                    columns
                        .iter()
                        .filter(|c| c.table.eq_ignore_ascii_case(t))
                        .map(|c| c.collation),
                ),
            }
        }
        out
    }

    /// When a query's sole `ORDER BY` term is the rowid / INTEGER PRIMARY KEY of
    /// a single plain table that is scanned in full (no `WHERE`, no grouping,
    /// aggregate, window, or `DISTINCT`), the table b-tree already yields rows in
    /// rowid order — so the sort is redundant. Returns `Some(descending)` in that
    /// case (the caller reverses for `DESC`), else `None` (sort normally). Shared
    /// by `run_core` and `eqp_access` so execution and `EXPLAIN QUERY PLAN` agree.
    fn rowid_ordered_scan(&self, sel: &Select) -> Option<bool> {
        let from = sel.from.as_ref()?;
        if !from.joins.is_empty() {
            return None;
        }
        let t = &from.first;
        if t.subquery.is_some() || t.tvf_args.is_some() || t.schema.is_some() {
            return None;
        }
        if sel.where_clause.is_some()
            || !sel.group_by.is_empty()
            || sel.having.is_some()
            || sel.distinct
            || sel.order_by.len() != 1
        {
            return None;
        }
        if self.has_aggregate(sel) || window::has_window(sel) {
            return None;
        }
        // The single ORDER BY term must be a plain (un-COLLATE'd) reference to the
        // rowid or the INTEGER PRIMARY KEY column of this table.
        let term = &sel.order_by[0];
        let (tbl, col) = match &term.expr {
            Expr::Column { table, column } => (table.as_deref(), column.as_str()),
            _ => return None,
        };
        // A CTE/view of the same name is not a rowid table scan.
        if self.lookup_cte(&t.name, None).is_some() || self.is_view(&t.name) {
            return None;
        }
        let label = t.alias.as_deref().unwrap_or(&t.name);
        if tbl.is_some_and(|tn| !tn.eq_ignore_ascii_case(label)) {
            return None;
        }
        let meta = self.table_meta(&t.name, t.alias.as_deref()).ok()?;
        if meta.without_rowid {
            return None;
        }
        let shadowed = meta
            .columns
            .iter()
            .any(|c| c.name.eq_ignore_ascii_case(col));
        let is_rowid_alias = matches!(
            col.to_ascii_lowercase().as_str(),
            "rowid" | "_rowid_" | "oid"
        ) && !shadowed;
        let is_ipk = meta
            .ipk
            .is_some_and(|i| meta.columns[i].name.eq_ignore_ascii_case(col));
        if is_rowid_alias || is_ipk {
            Some(term.descending)
        } else {
            None
        }
    }

    /// The secondary-index analogue of [`rowid_ordered_scan`]: when the same
    /// single-table full-scan shape has its sole `ORDER BY` term as a plain
    /// column that is the leading column of a full (non-partial, non-expression)
    /// index whose collation matches the column's, scanning that index in key
    /// order yields rows in `ORDER BY` order. Returns `(index name, root,
    /// collations, descending)`. NULLs sort first in the index (ascending),
    /// matching `ORDER BY col ASC`; reversing for `DESC` puts them last, matching
    /// `ORDER BY col DESC` — so both directions are exact.
    fn order_index_scan(&self, sel: &Select) -> Option<OrderIndexScan> {
        let from = sel.from.as_ref()?;
        if !from.joins.is_empty() {
            return None;
        }
        let t = &from.first;
        if t.subquery.is_some() || t.tvf_args.is_some() || t.schema.is_some() {
            return None;
        }
        if sel.where_clause.is_some()
            || !sel.group_by.is_empty()
            || sel.having.is_some()
            || sel.distinct
            || sel.order_by.is_empty()
        {
            return None;
        }
        if self.has_aggregate(sel) || window::has_window(sel) {
            return None;
        }
        if self.lookup_cte(&t.name, None).is_some() || self.is_view(&t.name) {
            return None;
        }
        let label = t.alias.as_deref().unwrap_or(&t.name);
        let meta = self.table_meta(&t.name, t.alias.as_deref()).ok()?;
        if meta.without_rowid {
            return None;
        }
        // Resolve every `ORDER BY` term to a plain table column. A secondary index
        // (stored ascending; reversed for a leading DESC) walks its columns in ONE
        // direction, so it satisfies a uniform leading PREFIX of the ORDER BY;
        // trailing terms that change direction are sorted by the caller (`sorted_
        // suffix`). The default-NULLs walk can't honour an explicit `NULLS
        // FIRST`/`LAST`, and a `COLLATE`/non-column term isn't a plain column —
        // both still disqualify the scan entirely.
        let descending = sel.order_by[0].descending;
        let mut cols: Vec<usize> = Vec::with_capacity(sel.order_by.len());
        let mut uniform_prefix = 0usize;
        let mut prefix_open = true;
        for term in &sel.order_by {
            if term.nulls_first.is_some() {
                return None;
            }
            let (tbl, col_name) = match &term.expr {
                Expr::Column { table, column } => (table.as_deref(), column.as_str()),
                _ => return None,
            };
            if tbl.is_some_and(|tn| !tn.eq_ignore_ascii_case(label)) {
                return None;
            }
            let col = meta
                .columns
                .iter()
                .position(|c| c.name.eq_ignore_ascii_case(col_name))?;
            cols.push(col);
            if prefix_open && term.descending == descending {
                uniform_prefix += 1;
            } else {
                prefix_open = false;
            }
        }
        let sorted_suffix = sel.order_by.len() - uniform_prefix;
        // A lone rowid/IPK term is the `rowid_ordered_scan` case.
        if cols.len() == 1 && meta.ipk == Some(cols[0]) {
            return None;
        }
        // A full index whose leading columns are exactly `cols` (in order), each
        // with the column's own collation (so index order == ORDER BY order for
        // the uniform prefix). When the ORDER BY is fully uniform (`sorted_suffix
        // == 0`) the walk needs no sort; a mixed-direction ORDER BY is taken only
        // for the NON-covering case (the covered one is `covering_scan` +
        // `scan_order_prefix`, which already reads in order).
        for idx in self.indexes_of(&t.name).ok()? {
            if idx.partial.is_some() || idx.key_exprs.is_some() {
                continue;
            }
            if idx.cols.len() < cols.len() || idx.cols[..cols.len()] != cols[..] {
                continue;
            }
            let coll_ok = cols
                .iter()
                .enumerate()
                .all(|(i, &c)| idx.collations[i] == meta.columns[c].collation);
            if !coll_ok {
                continue;
            }
            let covering = self.index_covers_query(sel, &meta, &idx.cols);
            if sorted_suffix > 0 && covering {
                continue;
            }
            return Some(OrderIndexScan {
                name: idx.name,
                root: idx.root,
                colls: idx.collations,
                cols: idx.cols,
                descending,
                covering,
                sorted_suffix,
            });
        }
        None
    }

    /// For a no-`WHERE` query whose access is a covering-index scan
    /// ([`covering_scan`]) but whose `ORDER BY` is NOT fully satisfied by that
    /// walk (mixed directions), the number of LEADING `ORDER BY` terms the index
    /// already yields in order. The walk direction is fixed by the first term;
    /// each further term must stay in that direction and continue matching the
    /// index's columns/collations, else the prefix ends there. sqlite sorts only
    /// the remaining terms — "USE TEMP B-TREE FOR LAST n TERMS OF ORDER BY". Zero
    /// when no covering scan applies or the first term already breaks.
    fn scan_order_prefix(&self, sel: &Select, params: &Params) -> usize {
        if sel.order_by.is_empty() {
            return 0;
        }
        let Some(from) = sel.from.as_ref() else {
            return 0;
        };
        if !from.joins.is_empty() {
            return 0;
        }
        let Ok(meta) = self.table_meta(&from.first.name, from.first.alias.as_deref()) else {
            return 0;
        };
        // The index `covering_scan` reads from (its choice must match the EQP).
        let Some((name, _, _)) = self.covering_scan(sel, &meta, params) else {
            return 0;
        };
        let Ok(indexes) = self.indexes_of(&from.first.name) else {
            return 0;
        };
        let Some(idx) = indexes
            .into_iter()
            .find(|i| i.name.eq_ignore_ascii_case(&name))
        else {
            return 0;
        };
        let label = from.first.alias.as_deref().unwrap_or(&from.first.name);
        let backward = sel.order_by[0].descending;
        let mut k = 0usize;
        for (i, term) in sel.order_by.iter().enumerate() {
            if i >= idx.cols.len() || term.nulls_first.is_some() || term.descending != backward {
                break;
            }
            let (tbl, col_name) = match &term.expr {
                Expr::Column { table, column } => (table.as_deref(), column.as_str()),
                _ => break,
            };
            if tbl.is_some_and(|tn| !tn.eq_ignore_ascii_case(label)) {
                break;
            }
            let Some(col) = meta
                .columns
                .iter()
                .position(|c| c.name.eq_ignore_ascii_case(col_name))
            else {
                break;
            };
            if col != idx.cols[i] || idx.collations[i] != meta.columns[col].collation {
                break;
            }
            k += 1;
        }
        k
    }

    /// Covering check for a WHERE-driven *seek* (B2b, seek case): on top of
    /// [`index_covers_query`](Self::index_covers_query) (result columns + `ORDER
    /// BY`), every column the `WHERE` clause references must also be covered by
    /// `idx_cols` or be the rowid. The seek's own index column is covered by
    /// construction, but a residual predicate on some *other* column (e.g.
    /// `WHERE c=5 AND b>0`) would still need the table unless that column is in
    /// the index too. Conservative: any construct whose referenced columns can't
    /// be enumerated (a subquery/`EXISTS`/`IN (SELECT …)`) makes this `false`, so
    /// the caller falls back to the always-correct table-fetch path.
    fn seek_index_covers(
        &self,
        sel: &Select,
        meta: &TableMeta,
        idx_cols: &[usize],
        where_expr: &Expr,
    ) -> bool {
        if !self.index_covers_query(sel, meta, idx_cols) {
            return false;
        }
        where_cols_covered(where_expr, meta, idx_cols)
    }

    /// Build the input rows of a covering seek by walking the chosen index and
    /// keeping every record (a superset — `run_core` re-applies the full `WHERE`,
    /// so the seek's own predicate filters out non-matching keys). Each record is
    /// `(indexed col values…, rowid)`; indexed columns are mapped onto their table
    /// positions and the rowid fills the `INTEGER PRIMARY KEY` column, exactly as
    /// the ordered covering scan does. Reads only the index b-tree — never the
    /// table.
    fn covering_seek_rows(
        &self,
        meta: &TableMeta,
        root: u32,
        idx_cols: &[usize],
    ) -> Result<Vec<InputRow>> {
        let src = self.backend.source();
        let encoding = src.header().text_encoding;
        let mut icur = IndexCursor::new(src, root);
        let mut out = Vec::new();
        while let Some(payload) = icur.next()? {
            let rec = decode_record(&payload, encoding)?;
            let rowid = match rec.get(idx_cols.len()) {
                Some(Value::Integer(r)) => *r,
                _ => return Err(Error::Corrupt("index record missing rowid".into())),
            };
            let mut values = alloc::vec![Value::Null; meta.columns.len()];
            for (i, &mc) in idx_cols.iter().enumerate() {
                values[mc] = rec[i].clone();
            }
            if let Some(ipk) = meta.ipk {
                values[ipk] = Value::Integer(rowid);
            }
            out.push(InputRow {
                values,
                rowid: Some(rowid),
            });
        }
        Ok(out)
    }

    /// Conservative covering check (B2): every column the query references
    /// (result columns + `ORDER BY`) is an indexed column or the rowid, which is
    /// present in every index record. Returns `false` on anything it cannot prove
    /// covered — an expression/function/subquery result column, a wildcard over a
    /// non-covered column, or any generated column on the table.
    fn index_covers_query(&self, sel: &Select, meta: &TableMeta, idx_cols: &[usize]) -> bool {
        if meta.generated.iter().any(|g| g.is_some()) {
            return false;
        }
        let covered = |ci: usize| idx_cols.contains(&ci) || meta.ipk == Some(ci);
        let col_ok = |expr: &Expr| -> bool {
            match expr {
                Expr::Column { column, .. } => match meta
                    .columns
                    .iter()
                    .position(|c| c.name.eq_ignore_ascii_case(column))
                {
                    Some(ci) => covered(ci),
                    None => matches!(
                        column.to_ascii_lowercase().as_str(),
                        "rowid" | "_rowid_" | "oid"
                    ),
                },
                _ => false,
            }
        };
        for rc in &sel.columns {
            match rc {
                ResultColumn::Wildcard | ResultColumn::TableWildcard(_) => {
                    if !(0..meta.columns.len()).all(covered) {
                        return false;
                    }
                }
                ResultColumn::Expr { expr, .. } => {
                    if !col_ok(expr) {
                        return false;
                    }
                }
            }
        }
        sel.order_by.iter().all(|t| col_ok(&t.expr))
    }

    /// Thorough covering test for a *full-table covering scan*: every column the
    /// query references anywhere — result projection (including aggregate
    /// arguments), `GROUP BY`, `HAVING`, `ORDER BY`, and `WHERE` — is held by
    /// `idx_cols` or is the rowid. Conservative: a wildcard over an uncovered
    /// column, a generated column, a window function, or a subquery makes it
    /// `false`. Unlike [`index_covers_query`](Self::index_covers_query) (plain
    /// projections only) this recurses through function calls, so an aggregate
    /// like `count(*)` / `sum(b)` over covered columns qualifies.
    fn query_cols_covered(&self, sel: &Select, meta: &TableMeta, idx_cols: &[usize]) -> bool {
        if meta.generated.iter().any(|g| g.is_some()) {
            return false;
        }
        let covered_all =
            (0..meta.columns.len()).all(|ci| idx_cols.contains(&ci) || meta.ipk == Some(ci));
        for rc in &sel.columns {
            match rc {
                ResultColumn::Wildcard | ResultColumn::TableWildcard(_) => {
                    if !covered_all {
                        return false;
                    }
                }
                ResultColumn::Expr { expr, .. } => {
                    if !where_cols_covered(expr, meta, idx_cols) {
                        return false;
                    }
                }
            }
        }
        sel.group_by
            .iter()
            .all(|e| where_cols_covered(e, meta, idx_cols))
            && sel
                .having
                .as_ref()
                .is_none_or(|h| where_cols_covered(h, meta, idx_cols))
            && sel
                .order_by
                .iter()
                .all(|t| where_cols_covered(&t.expr, meta, idx_cols))
            && sel
                .where_clause
                .as_ref()
                .is_none_or(|w| where_cols_covered(w, meta, idx_cols))
    }

    /// Choose a full secondary index to satisfy a query by a *covering scan* —
    /// reading every needed column from the index instead of the table — when no
    /// `WHERE` seek and no ORDER-BY index walk applies. Restricted to the
    /// no-`WHERE` case so no seek competes for the plan (keeping `eqp_select` and
    /// `run_core` trivially in lockstep), to ordinary rowid tables, and — like
    /// [`count_covering_index`](Self::count_covering_index) — to the *unambiguous*
    /// case of **exactly one** covering index, so the chosen name matches sqlite
    /// without replicating its cost-based tie-break. Returns `(name, root, cols)`.
    fn covering_scan(
        &self,
        sel: &Select,
        meta: &TableMeta,
        params: &Params,
    ) -> Option<(String, u32, Vec<usize>)> {
        let from = sel.from.as_ref()?;
        if !from.joins.is_empty() {
            return None;
        }
        let t = &from.first;
        if t.subquery.is_some() || t.tvf_args.is_some() || t.schema.is_some() {
            return None;
        }
        if sel.where_clause.is_some() || window::has_window(sel) || meta.without_rowid {
            return None;
        }
        if self.lookup_cte(&t.name, None).is_some() || self.is_view(&t.name) {
            return None;
        }
        // If the ORDER BY is already satisfied by a scan's natural order — the
        // rowid order of a table scan (`rowid_ordered_scan`) or an index walk
        // (`order_index_scan`) — leave it alone. A covering scan reads in index
        // order, which would silently break a `rowid_ordered_scan` that assumed
        // the rows arrive in rowid order (and the ordered-index case already
        // renders as covering).
        if self.order_satisfied_by_scan(sel, params).is_some() {
            return None;
        }
        let mut covering = self.indexes_of(&t.name).ok()?.into_iter().filter(|idx| {
            idx.partial.is_none()
                && idx.key_exprs.is_none()
                && self.query_cols_covered(sel, meta, &idx.cols)
        });
        let chosen = covering.next()?;
        // Ambiguous (two or more covering indexes): keep the plain scan rather
        // than guess which one sqlite's cost model would pick.
        if covering.next().is_some() {
            return None;
        }
        Some((chosen.name, chosen.root, chosen.cols))
    }

    /// `SELECT count(*) FROM <single rowid table>` can be answered by counting a
    /// full secondary index's entries instead of scanning the table — a full,
    /// non-partial index has exactly one entry per table row, and its b-tree is
    /// usually smaller (B2b). This returns `Some((index name, root))` only in the
    /// unambiguous case so execution and `EXPLAIN QUERY PLAN` agree:
    ///
    /// * the query is exactly one bare `count(*)` projection — no `WHERE`,
    ///   `GROUP BY`, `HAVING`, `DISTINCT`, `ORDER BY`, joins, subquery, or TVF;
    /// * the source is an ordinary rowid table (not `WITHOUT ROWID`, view, or CTE);
    /// * the table has **exactly one** full (non-partial, non-expression)
    ///   secondary index, so the chosen name is unambiguous and matches sqlite.
    ///
    /// Zero or multiple such indexes → `None` (fall back to the plain `SCAN t`),
    /// never guessing. Shared by `run_core` and `eqp_select`.
    fn count_covering_index(&self, sel: &Select) -> Option<(String, u32)> {
        let from = sel.from.as_ref()?;
        if !from.joins.is_empty() {
            return None;
        }
        let t = &from.first;
        if t.subquery.is_some() || t.tvf_args.is_some() || t.schema.is_some() {
            return None;
        }
        if sel.where_clause.is_some()
            || !sel.group_by.is_empty()
            || sel.having.is_some()
            || sel.distinct
            || !sel.order_by.is_empty()
        {
            return None;
        }
        if window::has_window(sel) {
            return None;
        }
        // The projection must be exactly a single bare `count(*)`.
        if sel.columns.len() != 1 {
            return None;
        }
        let ResultColumn::Expr { expr, .. } = &sel.columns[0] else {
            return None;
        };
        match expr {
            Expr::Function {
                name,
                distinct: false,
                star: true,
                filter: None,
                over: None,
                ..
            } if name.eq_ignore_ascii_case("count") => {}
            _ => return None,
        }
        // The source must be an ordinary rowid table (not a view or CTE).
        if self.lookup_cte(&t.name, None).is_some() || self.is_view(&t.name) {
            return None;
        }
        let meta = self.table_meta(&t.name, t.alias.as_deref()).ok()?;
        if meta.without_rowid {
            return None;
        }
        // Exactly one full (non-partial, non-expression) secondary index.
        let mut chosen: Option<(String, u32)> = None;
        for idx in self.indexes_of(&t.name).ok()? {
            if idx.partial.is_some() || idx.key_exprs.is_some() {
                continue;
            }
            if chosen.is_some() {
                return None; // ambiguous: more than one candidate
            }
            chosen = Some((idx.name, idx.root));
        }
        chosen
    }

    /// Whether a single-table scan already yields rows in the query's `ORDER BY`
    /// order (so `run_core` can skip the sort, reversing for `DESC`). Combines the
    /// rowid/IPK and secondary-index cases; shared with `eqp_access`.
    fn order_satisfied_by_scan(&self, sel: &Select, params: &Params) -> Option<bool> {
        if let Some(d) = self.rowid_ordered_scan(sel) {
            return Some(d);
        }
        if let Some(s) = self.order_index_scan(sel) {
            // A mixed-direction walk only orders the leading prefix; the caller
            // still sorts, so the ORDER BY is not fully satisfied by the scan.
            if s.sorted_suffix == 0 {
                return Some(s.descending);
            }
        }
        // A `WHERE` seek that walks an index in key order satisfies the ORDER BY
        // when *every* term matches the walked columns (B0b-iii).
        match self.seek_order_prefix(sel, params) {
            Some((k, descending)) if k == sel.order_by.len() => Some(descending),
            _ => None,
        }
    }

    /// How many leading `ORDER BY` terms a `WHERE` seek already produces in order,
    /// and the walk direction — the shared core of B0b-iii (full match → skip the
    /// sort) and the partial-sort EXPLAIN label. A seek walks its index in key
    /// order, so the rows arrive ordered by the index columns that follow any
    /// equality prefix; this returns `(k, descending)` where `k` of the ORDER BY
    /// terms match that walk (uniform direction, matching collation, default
    /// NULLs). `k == order_by.len()` means no sort is needed; `0 < k < n` is a
    /// partial sort. Returns `None` when no unambiguous seek applies.
    ///
    /// Mirrors `try_index_lookup` / `try_index_range`'s index choice conservatively
    /// so it never claims an order the executor will not produce: an equality seek
    /// needs exactly one plain secondary index whose leading column the `WHERE`
    /// constrains by equality (and no rowid equality); a range seek needs no column
    /// equality at all (so `try_index_lookup` declines), no partial/expression
    /// index on the table, no range on the rowid, and exactly one plain secondary
    /// index whose leading column is range-constrained. Any looseness only mislabels
    /// EXPLAIN (the sort still runs), and the ORDER-BY differential corpus catches it.
    fn seek_order_prefix(&self, sel: &Select, params: &Params) -> Option<(usize, bool)> {
        let from = sel.from.as_ref()?;
        if !from.joins.is_empty() {
            return None;
        }
        let t = &from.first;
        if t.subquery.is_some()
            || t.tvf_args.is_some()
            || t.schema.is_some()
            || from.first.index_hint.is_some()
        {
            return None;
        }
        let where_expr = sel.where_clause.as_ref()?;
        if sel.order_by.is_empty()
            || !sel.group_by.is_empty()
            || sel.having.is_some()
            || sel.distinct
            || self.has_aggregate(sel)
            || window::has_window(sel)
        {
            return None;
        }
        if self.lookup_cte(&t.name, None).is_some() || self.is_view(&t.name) {
            return None;
        }
        let label = t.alias.as_deref().unwrap_or(&t.name);
        let meta = self.table_meta(&t.name, t.alias.as_deref()).ok()?;
        if meta.without_rowid {
            return None;
        }
        let indexes = self.indexes_of(&t.name).ok()?;
        let mut eqs: Vec<(usize, Value)> = Vec::new();
        collect_eq_constraints(where_expr, &meta.columns, params, &mut eqs);
        eqs.retain(|(_, v)| !matches!(v, Value::Null));
        // The columns the chosen seek walks in index-ascending order (those after
        // any equality prefix), with their index collations.
        let (walk_cols, walk_colls): (&[usize], &[crate::value::Collation]) = if !eqs.is_empty() {
            // Equality seek (try_index_lookup). A rowid/IPK equality returns at most
            // one row — a different path; bail to the cheap, correct sort.
            if meta
                .ipk
                .is_some_and(|ipk| eqs.iter().any(|(c, _)| *c == ipk))
            {
                return None;
            }
            let mut seekable = indexes.iter().filter(|idx| {
                idx.partial.is_none()
                    && idx.key_exprs.is_none()
                    && idx
                        .cols
                        .first()
                        .is_some_and(|c| eqs.iter().any(|(col, _)| col == c))
            });
            let idx = seekable.next()?;
            if seekable.next().is_some() {
                return None;
            }
            let prefix = idx
                .cols
                .iter()
                .take_while(|&&c| eqs.iter().any(|(col, _)| *col == c))
                .count();
            (&idx.cols[prefix..], &idx.collations[prefix..])
        } else {
            // Range seek (try_index_range). Guard so the chosen index is exactly the
            // one the executor walks (see the doc comment).
            let mut ranges: alloc::collections::BTreeMap<usize, RangeBound> =
                alloc::collections::BTreeMap::new();
            collect_range_constraints(where_expr, &meta.columns, params, &mut ranges);
            if ranges.is_empty() {
                return None;
            }
            if meta.ipk.is_some_and(|ipk| ranges.contains_key(&ipk)) {
                return None;
            }
            if indexes
                .iter()
                .any(|idx| idx.partial.is_some() || idx.key_exprs.is_some())
            {
                return None;
            }
            let mut seekable = indexes
                .iter()
                .filter(|idx| idx.cols.first().is_some_and(|c| ranges.contains_key(c)));
            let idx = seekable.next()?;
            if seekable.next().is_some() {
                return None;
            }
            (&idx.cols[..], &idx.collations[..])
        };
        // Count the leading ORDER BY terms the walk already produces: each must be a
        // plain column of this table, in the walk's uniform direction (default
        // NULLs), matching the next walked column under its own collation.
        let descending = sel.order_by[0].descending;
        let mut k = 0;
        for term in &sel.order_by {
            if k >= walk_cols.len() || term.descending != descending || term.nulls_first.is_some() {
                break;
            }
            let (tbl, col_name) = match &term.expr {
                Expr::Column { table, column } => (table.as_deref(), column.as_str()),
                _ => break,
            };
            if tbl.is_some_and(|tn| !tn.eq_ignore_ascii_case(label)) {
                break;
            }
            let Some(oc) = meta
                .columns
                .iter()
                .position(|c| c.name.eq_ignore_ascii_case(col_name))
            else {
                break;
            };
            if walk_cols[k] != oc || walk_colls[k] != meta.columns[oc].collation {
                break;
            }
            k += 1;
        }
        Some((k, descending))
    }

    /// The first `match(query, operand)` call in a WHERE clause's `AND`/`OR` tree,
    /// as `(query text, operand column name)`. The operand names either the table
    /// (a table-wide match) or a single column (`col MATCH …`, which scopes the
    /// score to that column).
    #[cfg(feature = "fts5")]
    fn fts5_match_query(&self, expr: &Expr, params: &Params) -> Option<(String, String)> {
        match expr {
            Expr::Function { name, args, .. }
                if name.eq_ignore_ascii_case("match") && args.len() == 2 =>
            {
                let v = eval::eval(&args[0], &eval::EvalCtx::rowless(params)).ok()?;
                let operand = match &args[1] {
                    Expr::Column { column, .. } => column.clone(),
                    _ => return None,
                };
                Some((eval::to_text(&v), operand))
            }
            Expr::Binary { left, right, .. } => self
                .fts5_match_query(left, params)
                .or_else(|| self.fts5_match_query(right, params)),
            Expr::Unary { expr, .. } | Expr::Paren(expr) => self.fts5_match_query(expr, params),
            _ => None,
        }
    }

    /// Build the per-query [`Fts5QueryCtx`] for an FTS5 `MATCH` query over a single
    /// `fts5` table that references `rank`/`bm25()`/`highlight()`, or `None`. The
    /// bm25 corpus is computed (over `input_rows`, the whole scanned corpus) only
    /// when `rank`/`bm25()` is referenced — `highlight()` needs just the query.
    #[cfg(feature = "fts5")]
    fn fts5_query_ctx(
        &self,
        sel: &Select,
        columns: &[ColumnInfo],
        input_rows: &[InputRow],
        params: &Params,
    ) -> Option<Fts5QueryCtx> {
        const AUX: &[&str] = &["rank", "bm25", "highlight", "snippet"];
        const RANK: &[&str] = &["rank", "bm25"];
        if !select_mentions(sel, AUX) {
            return None;
        }
        let from = sel.from.as_ref()?;
        if !from.joins.is_empty()
            || from.first.subquery.is_some()
            || from.first.tvf_args.is_some()
            || from.first.schema.is_some()
        {
            return None;
        }
        // The source must be an `fts5` virtual table.
        let (module, vargs, _) = self.vtab_meta(&from.first.name).ok()?;
        if !module.eq_ignore_ascii_case("fts5") {
            return None;
        }
        // Columns declared `UNINDEXED` are excluded from matching/ranking; `None`
        // when every column is searchable (avoids per-row name checks).
        let arg_refs: Vec<&str> = vargs.iter().map(String::as_str).collect();
        let all = crate::vtab::fts5_indexed_columns(&arg_refs);
        let indexed = (all.len() != columns.len()).then_some(all);
        let tok = crate::vtab::fts5_tok_config(&arg_refs);
        let (query, operand) = self.fts5_match_query(sel.where_clause.as_ref()?, params)?;
        let col_names: Vec<String> = columns.iter().map(|c| c.name.clone()).collect();
        // A `col MATCH …` operand scopes the query to that column; a table-wide
        // `t MATCH …` (operand names the table, not a column) does not.
        let scope = col_names
            .iter()
            .find(|n| n.eq_ignore_ascii_case(&operand))
            .cloned();
        // Score the corpus only when ranking is actually referenced.
        let bm25 = select_mentions(sel, RANK).then(|| {
            let docs: Vec<Vec<String>> = input_rows
                .iter()
                .map(|r| r.values.iter().map(eval::to_text).collect())
                .collect();
            let corpus = crate::vtab::fts5_bm25_corpus(
                &query,
                &col_names,
                &docs,
                scope.as_deref(),
                indexed.as_deref(),
                tok,
            );
            let index = input_rows
                .iter()
                .enumerate()
                .filter_map(|(i, r)| Some((r.rowid?, i)))
                .collect();
            (corpus, index)
        });
        Some(Fts5QueryCtx {
            col_names,
            query,
            scope,
            indexed,
            tok,
            bm25,
        })
    }

    fn run_core(&self, sel: &Select, params: &Params) -> Result<QueryResult> {
        // Opt-in VDBE fast path (Track B, B7a): when enabled and this block takes
        // no bound parameters, try the experimental engine first and use its
        // result only on success — every unsupported shape, and every error, is
        // left to the tree-walker, which remains the source of truth. The VDBE
        // never alters state, so a failed attempt is side-effect-free. Routing
        // here (per query block) rather than at the whole-query level means each
        // arm of a compound query is accelerated too, while the tree-walker still
        // performs the set combination. Skipped inside a correlated/nested scope
        // (non-empty `outer_scope`): the spike resolves columns by bare name and
        // would mis-resolve an outer-qualified reference to a same-named inner
        // column.
        if self.use_vdbe.get() && self.outer_scope.borrow().is_empty() {
            // No params → run the VDBE on `sel` directly. With params, substitute
            // the explicit (`?N`/`:name`) ones into the compiled expressions so the
            // param-less VDBE can run the query; an anonymous `?` (or no explicit
            // param in those expressions) returns None → fall through.
            let substituted;
            let vsel = if params.positional.is_empty() && params.named.is_empty() {
                Some(sel)
            } else {
                match substitute_params(sel, params) {
                    Some(s) => {
                        substituted = s;
                        Some(&substituted)
                    }
                    None => None,
                }
            };
            if let Some(vsel) = vsel {
                if let Ok(result) = self.run_select_vdbe(vsel) {
                    return Ok(result);
                }
            }
        }
        // Promote `FROM a, b WHERE a.x = b.y` to an explicit join `ON` so the join
        // fold can seek/hash it (the equality stays in WHERE, so results are
        // identical). All later uses of `sel` see the rewritten form.
        let rewritten;
        let sel = match promote_comma_join_ons(sel) {
            Some(r) => {
                rewritten = r;
                &rewritten
            }
            None => sel,
        };
        // `SELECT count(*) FROM t` over a single rowid table with exactly one full
        // secondary index counts that index's entries instead of scanning the
        // table (B2b). Kept in lockstep with `eqp_select` via the shared
        // `count_covering_index` helper so EQP reports `USING COVERING INDEX`.
        if let Some((_, root)) = self.count_covering_index(sel) {
            let mut cur = IndexCursor::new(self.backend.source(), root);
            let mut n = 0i64;
            while cur.next()?.is_some() {
                n += 1;
            }
            let label = self.output_labels(sel, &[]).pop().unwrap_or_default();
            return Ok(QueryResult {
                columns: alloc::vec![label],
                rows: alloc::vec![alloc::vec![Value::Integer(n)]],
            });
        }

        let (columns, input_rows) = self.scan_source(sel, params)?;

        // FTS5 relevance: if this query references `rank` / `bm25()` over an `fts5`
        // table, build its query context (and bm25 corpus, if ranked) now and
        // expose it to `rank`/`bm25()`/`highlight()` during projection and ORDER BY.
        // The guard restores any outer query's context (and clears it for a
        // non-FTS5 query) when this scope ends.
        #[cfg(feature = "fts5")]
        let _fts5_rank_guard = Fts5RankGuard {
            conn: self,
            prev: core::mem::replace(
                &mut *self.fts5_rank.borrow_mut(),
                self.fts5_query_ctx(sel, &columns, &input_rows, params),
            ),
        };

        // SQLite lets WHERE/GROUP BY/HAVING reference a SELECT-list alias, with a
        // real column of the same name taking precedence. Rewrite those clauses
        // by substituting each unshadowed alias with its defining expression.
        let alias_rewritten;
        let sel = match alias_substituted(sel, &columns) {
            Some(s) => {
                alias_rewritten = s;
                &alias_rewritten
            }
            None => sel,
        };

        // An unqualified (or self-join-qualified) column reference that matches
        // columns from two different FROM sources is ambiguous — SQLite rejects
        // it. Checked after alias substitution so an ORDER BY/GROUP BY/HAVING
        // reference to an unshadowed output alias is already rewritten to its
        // defining expression and not mistaken for an ambiguous column.
        validate_unambiguous_columns(sel, &columns)?;
        // SQLite also rejects an ambiguous reference *inside a subquery* that binds
        // to an enclosing FROM, statically (whether or not the subquery executes).
        // Run that scope-aware pass once, at the outermost query: `columns` here is
        // the known top scope, and each nested level resolves against it.
        if self.outer_scope.borrow().is_empty() {
            self.validate_nested_ambiguity(sel, &columns)?;
        }

        // A positional `GROUP BY` / `ORDER BY` term (an integer literal) must name
        // an output column (1..=ncols); SQLite rejects one out of range. The count
        // is taken after wildcard expansion.
        let ncols = self.output_labels(sel, &columns).len();
        check_positional_terms(&sel.group_by, &sel.order_by, ncols)?;

        // Apply WHERE.
        let mut rows: Vec<InputRow> = Vec::new();
        for r in input_rows {
            if let Some(pred) = &sel.where_clause {
                let ctx = r.ctx(&columns, params).with_subqueries(self);
                if eval::truth(&eval::eval(pred, &ctx)?) != Some(true) {
                    continue;
                }
            }
            rows.push(r);
        }

        // Windows, aggregation/grouping, projection, DISTINCT, ORDER BY and
        // LIMIT/OFFSET all run over these post-WHERE rows. Factored into
        // `finish_from_rows` so the VDBE window dispatcher can reuse the exact same
        // tail after producing the base rows itself.
        self.finish_from_rows(sel, columns, rows, params)
    }

    /// Finish a query block from its post-`WHERE` rows: apply window functions,
    /// aggregation/grouping and projection, then `DISTINCT`, `ORDER BY` and
    /// `LIMIT`/`OFFSET`. `columns` is the input rows' column metadata (windows
    /// append synthetic columns to it). This is the second half of `run_core`,
    /// extracted so the VDBE window path ([`run_window_vdbe`]) can drive it over
    /// rows it scanned itself.
    fn finish_from_rows(
        &self,
        sel: &Select,
        mut columns: Vec<ColumnInfo>,
        mut rows: Vec<InputRow>,
        params: &Params,
    ) -> Result<QueryResult> {
        // A window function combined with GROUP BY / aggregates: SQLite applies
        // the window *after* grouping (it runs over the post-aggregation rows, and
        // an aggregate inside a window argument or spec is the group's aggregate).
        // `eval_windowed_aggregate` handles grouping, the windows, and projection,
        // returning rows + sort keys just like the other eval paths — so it feeds
        // the same DISTINCT / ORDER BY / LIMIT post-processing below.
        let windowed_agg =
            window::has_window(sel) && (!sel.group_by.is_empty() || self.has_aggregate(sel));

        // Plain window functions (no GROUP BY/aggregate): compute over the
        // post-WHERE rows, append the results as synthetic columns, and rewrite the
        // projection to reference them. Capture the output labels from the ORIGINAL
        // projection first — `apply_windows` rewrites each window call to a `__winN`
        // column reference, which would otherwise name the output column `__winN`
        // instead of its source text (`sum(a) OVER ()`).
        let window_labels = if window::has_window(sel) && !windowed_agg {
            Some(self.output_labels(sel, &columns))
        } else {
            None
        };
        let rewritten;
        let sel = if window::has_window(sel) && !windowed_agg {
            rewritten = self.apply_windows(sel, &mut columns, &mut rows, params)?;
            &rewritten
        } else {
            sel
        };

        let aggregated = !sel.group_by.is_empty() || self.has_aggregate(sel);
        // A HAVING clause requires an aggregate *context*: a GROUP BY, or an
        // aggregate in the result columns. An aggregate that appears *only* inside
        // HAVING does not make the query aggregate — SQLite rejects HAVING there
        // ("HAVING clause on a non-aggregate query"), e.g. `SELECT 1 HAVING max(x)`.
        if sel.having.is_some() && sel.group_by.is_empty() && !self.has_result_aggregate(sel) {
            return Err(Error::Error(
                "HAVING clause on a non-aggregate query".into(),
            ));
        }
        let (mut out_labels, mut out) = if windowed_agg {
            self.eval_windowed_aggregate(sel, &columns, rows, params)?
        } else if aggregated {
            self.eval_aggregated(sel, &columns, rows, params)?
        } else {
            self.eval_simple(sel, &columns, rows, params)?
        };
        // Restore the pre-rewrite labels for a plain windowed query (above).
        if let Some(labels) = window_labels {
            out_labels = labels;
        }

        // DISTINCT (dedupe on output values, preserving first occurrence), each
        // output column compared under its collation.
        if sel.distinct {
            let colls = self.output_collations(sel, &columns, params);
            let mut seen: Vec<Vec<Value>> = Vec::new();
            out.retain(|row| {
                if seen.iter().any(|s| rows_equal_coll(s, &row.values, &colls)) {
                    false
                } else {
                    seen.push(row.values.clone());
                    true
                }
            });
        }

        // ORDER BY. A query already produced in rowid order by the table scan
        // (sole ORDER BY term = rowid / INTEGER PRIMARY KEY) skips the sort —
        // just reversing for DESC — matching sqlite's plain SCAN with no temp
        // b-tree.
        if !sel.order_by.is_empty() {
            match self.order_satisfied_by_scan(sel, params) {
                Some(true) => out.reverse(),
                Some(false) => {}
                None => {
                    let colls = self.order_collations(sel, &columns, params);
                    // Stable sort by the precomputed sort keys, each under its collation.
                    out.sort_by(|a, b| {
                        for (i, term) in sel.order_by.iter().enumerate() {
                            let ord = cmp_order(
                                &a.sort_keys[i],
                                &b.sort_keys[i],
                                term.descending,
                                term.nulls_first,
                                colls[i],
                            );
                            if ord != core::cmp::Ordering::Equal {
                                return ord;
                            }
                        }
                        core::cmp::Ordering::Equal
                    });
                }
            }
        }

        // OFFSET / LIMIT.
        let offset = match &sel.offset {
            Some(e) => must_be_int(eval::eval(
                e,
                &EvalCtx::rowless(params).with_subqueries(self),
            )?)?
            .max(0) as usize,
            None => 0,
        };
        // A negative LIMIT means "no limit" in SQLite (OFFSET still applies).
        let limit = match &sel.limit {
            Some(e) => {
                let n = must_be_int(eval::eval(
                    e,
                    &EvalCtx::rowless(params).with_subqueries(self),
                )?)?;
                if n < 0 {
                    None
                } else {
                    Some(n as usize)
                }
            }
            None => None,
        };
        let mut final_rows: Vec<Vec<Value>> =
            out.into_iter().skip(offset).map(|r| r.values).collect();
        if let Some(n) = limit {
            final_rows.truncate(n);
        }

        Ok(QueryResult {
            columns: out_labels,
            rows: final_rows,
        })
    }

    /// Run a window-function `SELECT` over a single plain table on the VDBE
    /// (Track B5c-4). The window evaluation itself is not bytecode; instead the
    /// base table is scanned (with `WHERE` applied) by the VDBE, and the rows are
    /// fed to the shared `finish_from_rows` tail — analogous to how
    /// `run_compound_vdbe` reuses the set-combine helpers. The base scan appends
    /// each row's rowid as a trailing column so a `rowid`/`_rowid_`/`oid`
    /// reference anywhere in the query resolves; a `WITHOUT ROWID` table makes
    /// that projection bail, so such queries fall back. Any shape the base scan
    /// cannot run (a join, a derived/virtual/view source, a non-`main` schema, …)
    /// returns `Unsupported`, falling the whole query back to the tree-walker.
    fn run_window_vdbe(&self, sel: &Select) -> Result<QueryResult> {
        // Whether `sel` references a `rowid`/`_rowid_`/`oid` pseudo-column anywhere
        // in its expressions (projection, `WHERE`, `GROUP BY`, `HAVING`, `ORDER BY`,
        // or any window's `PARTITION BY`/`ORDER BY`, including a nested `OVER`).
        // The join path below supplies no per-row rowid (a joined row has none), so
        // it must defer whenever a `None` rowid could become observable.
        fn is_rowid_name(n: &str) -> bool {
            n.eq_ignore_ascii_case("rowid")
                || n.eq_ignore_ascii_case("_rowid_")
                || n.eq_ignore_ascii_case("oid")
        }
        fn spec_has_rowid(spec: &WindowSpec) -> bool {
            spec.partition_by.iter().any(expr_has_rowid)
                || spec.order_by.iter().any(|t| expr_has_rowid(&t.expr))
        }
        fn expr_has_rowid(e: &Expr) -> bool {
            let mut found = false;
            window::visit(e, &mut |node| match node {
                Expr::Column { column, .. } if is_rowid_name(column) => found = true,
                Expr::Function {
                    over: Some(spec), ..
                } if spec_has_rowid(spec) => found = true,
                _ => {}
            });
            found
        }
        fn select_mentions_rowid(sel: &Select) -> bool {
            sel.columns
                .iter()
                .any(|c| matches!(c, ResultColumn::Expr { expr, .. } if expr_has_rowid(expr)))
                || sel.where_clause.as_ref().is_some_and(expr_has_rowid)
                || sel.group_by.iter().any(expr_has_rowid)
                || sel.having.as_ref().is_some_and(expr_has_rowid)
                || sel.order_by.iter().any(|t| expr_has_rowid(&t.expr))
                || sel.window_defs.iter().any(|(_, spec)| spec_has_rowid(spec))
        }

        // A `WITH` of its own could shadow the base table with a CTE the VDBE
        // scan cannot open — defer.
        if !sel.ctes.is_empty() {
            return Err(Error::Unsupported("VDBE window: query carries CTEs"));
        }
        let Some(from) = &sel.from else {
            return Err(Error::Unsupported("VDBE window: no FROM"));
        };
        // The source is either a single plain rowid table (rowid is appended so a
        // `rowid` reference resolves) or a plain N-table join (a joined row has no
        // single rowid, so the path is only taken when no rowid is referenced).
        let is_join = !from.joins.is_empty();
        let columns = if is_join {
            if select_mentions_rowid(sel) {
                return Err(Error::Unsupported("VDBE window: join references rowid"));
            }
            // `static_scope_columns` yields the `SELECT *` column set in expansion
            // order, and returns `None` for exactly the join shapes whose column set
            // the VDBE scan can't reproduce (`NATURAL`/`USING` coalescing, a view,
            // CTE, derived table, table-valued function, or schema-qualified name).
            let Some(cols) = self.static_scope_columns(sel) else {
                return Err(Error::Unsupported("VDBE window: non-plain join source"));
            };
            cols
        } else {
            let tref = &from.first;
            if tref.subquery.is_some()
                || tref.tvf_args.is_some()
                || tref.index_hint.is_some()
                || tref.schema.is_some()
                || self.is_pragma_tvf(tref)
                || self.is_view(&tref.name)
                || self.is_virtual_table(&tref.name)
                || self
                    .cte_env
                    .borrow()
                    .iter()
                    .any(|b| b.name.eq_ignore_ascii_case(&tref.name))
            {
                return Err(Error::Unsupported("VDBE window: non-plain source"));
            }
            self.table_meta(&tref.name, tref.alias.as_deref())?.columns
        };
        let ncols = columns.len();
        // Scan the base source with `WHERE` applied; for a single table append each
        // row's rowid as a trailing column. Everything else (`GROUP BY`, `HAVING`,
        // `ORDER BY`, `LIMIT`, `DISTINCT`, the windows) is stripped — the shared
        // `finish_from_rows` tail re-runs it over the scanned rows.
        let mut base = sel.clone();
        base.distinct = false;
        base.group_by = Vec::new();
        base.having = None;
        base.window_defs = Vec::new();
        base.order_by = Vec::new();
        base.limit = None;
        base.offset = None;
        base.columns = if is_join {
            alloc::vec![ResultColumn::Wildcard]
        } else {
            alloc::vec![
                ResultColumn::Wildcard,
                ResultColumn::Expr {
                    expr: Expr::Column {
                        table: None,
                        column: "rowid".into(),
                    },
                    alias: Some("__winrowid__".into()),
                    source: None,
                },
            ]
        };
        let scanned = self.run_select_vdbe(&base)?;
        let mut rows: Vec<InputRow> = Vec::with_capacity(scanned.rows.len());
        for mut values in scanned.rows {
            let rowid = if is_join {
                if values.len() != ncols {
                    return Err(Error::Unsupported("VDBE window: column count mismatch"));
                }
                None
            } else {
                // [base columns…, rowid]: split the trailing rowid back off.
                if values.len() != ncols + 1 {
                    return Err(Error::Unsupported("VDBE window: column count mismatch"));
                }
                match values.pop() {
                    Some(Value::Integer(id)) => Some(id),
                    _ => None,
                }
            };
            rows.push(InputRow { values, rowid });
        }
        self.finish_from_rows(sel, columns, rows, &Params::default())
    }

    /// The column metadata visible to `sel`'s expressions (its `FROM` sources'
    /// columns), derived *statically* — no rows are read — for the ambiguity
    /// check. Returns `None` ("unknown") for anything but plain main-database
    /// tables joined by comma/`ON` (a view, CTE, derived table, table-valued
    /// function, schema-qualified name, or `NATURAL`/`USING` coalescing), so the
    /// caller never guesses a binding it cannot prove. A `NATURAL`/`USING` join is
    /// treated as unknown rather than approximated, since its coalescing changes
    /// the column set.
    fn static_scope_columns(&self, sel: &Select) -> Option<Vec<ColumnInfo>> {
        let Some(from) = &sel.from else {
            return Some(Vec::new());
        };
        if from.joins.iter().any(|j| j.natural || !j.using.is_empty()) {
            return None;
        }
        let mut cols = Vec::new();
        for tref in core::iter::once(&from.first).chain(from.joins.iter().map(|j| &j.table)) {
            // Only a plain, unqualified, main-database table is statically known.
            if tref.subquery.is_some()
                || tref.tvf_args.is_some()
                || tref.schema.is_some()
                || self.is_pragma_tvf(tref)
                || self.is_view(&tref.name)
                || self
                    .cte_env
                    .borrow()
                    .iter()
                    .any(|b| b.name.eq_ignore_ascii_case(&tref.name))
            {
                return None;
            }
            let meta = self.table_meta(&tref.name, tref.alias.as_deref()).ok()?;
            cols.extend(meta.columns);
        }
        Some(cols)
    }

    /// Static, scope-aware ambiguity check for nested subqueries, run once at the
    /// top level (`outer_scope` empty). SQLite rejects an ambiguous column
    /// reference at prepare time — including one inside a subquery that binds to
    /// an enclosing query's `FROM` — regardless of whether the subquery ever
    /// executes. `top` is this query's own (known) column list. Each nested
    /// subquery is resolved against [its own scope, … enclosing scopes]; an
    /// undeterminable scope simply stops resolution for a reference (see
    /// [`first_ambiguous_in_scopes`]), so the check never reports a false positive.
    fn validate_nested_ambiguity(&self, sel: &Select, top: &[ColumnInfo]) -> Result<()> {
        let scopes = alloc::vec![Some(top.to_vec())];
        self.walk_nested_ambiguity(sel, &scopes)
    }

    fn walk_nested_ambiguity(
        &self,
        sel: &Select,
        scopes: &[Option<Vec<ColumnInfo>>],
    ) -> Result<()> {
        // Gather this level's directly-nested subqueries (scalar, EXISTS, IN); each
        // is recursed into below with its own scope pushed.
        let mut subs: Vec<&Select> = Vec::new();
        vdbe_block_exprs(sel, &mut |e| collect_subselects(e, &mut subs));
        for sub in subs {
            let mut child: Vec<Option<Vec<ColumnInfo>>> =
                alloc::vec![self.static_scope_columns(sub)];
            child.extend(scopes.iter().cloned());
            if let Some(msg) = first_ambiguous_in_scopes(sub, &child) {
                return Err(Error::Error(msg));
            }
            self.walk_nested_ambiguity(sub, &child)?;
        }
        Ok(())
    }

    /// Scan the `FROM` source into column metadata and decoded input rows.
    fn scan_source(
        &self,
        sel: &Select,
        params: &Params,
    ) -> Result<(Vec<ColumnInfo>, Vec<InputRow>)> {
        let Some(from) = &sel.from else {
            // No FROM: a single empty row (e.g. `SELECT 1+1`).
            return Ok((
                Vec::new(),
                alloc::vec![InputRow {
                    values: Vec::new(),
                    rowid: None
                }],
            ));
        };
        // `INDEXED BY <name>` requires the named index to exist on the table —
        // sqlite errors "no such index" otherwise, even though graphite may
        // full-scan regardless of the hint. Accept an explicit index by name or an
        // `sqlite_autoindex_<table>_*` implicit index (lenient on the exact number).
        for tref in core::iter::once(&from.first).chain(from.joins.iter().map(|j| &j.table)) {
            if let Some(IndexHint::IndexedBy(name)) = &tref.index_hint {
                if self.schema.table(&tref.name).is_some() {
                    let auto_prefix =
                        alloc::format!("sqlite_autoindex_{}_", tref.name.to_ascii_lowercase());
                    let known = self
                        .schema
                        .indexes_on(&tref.name)
                        .any(|o| o.name.eq_ignore_ascii_case(name))
                        || name.to_ascii_lowercase().starts_with(&auto_prefix);
                    if !known {
                        return Err(Error::Error(alloc::format!("no such index: {name}")));
                    }
                }
            }
        }
        if from.joins.is_empty() && from.first.subquery.is_none() && from.first.tvf_args.is_none() {
            // An explicit qualifier picks the database; an unqualified name may be
            // shadowed by a temp table. A non-main database is read by
            // materializing the table through its own backend.
            // `sqlite_temp_master`/`sqlite_temp_schema` read the temp catalog
            // (empty when no temp database exists).
            if from.first.schema.is_none() && is_temp_schema_table(&from.first.name) {
                let alias = from.first.alias.as_deref();
                return match &self.temp_db {
                    Some(_) => self.scan_db_table(DbRef::Temp, "sqlite_master", alias),
                    None => Ok((
                        schema_table_meta(alias.unwrap_or(&from.first.name)).columns,
                        Vec::new(),
                    )),
                };
            }
            // The eponymous read-only vtabs (`dbstat` — per-page storage stats;
            // `sqlite_dbpage` — raw page bytes) exist in *every* schema, but the
            // database they report is governed by their hidden `schema` column,
            // which SQLite defaults to `main`. The table qualifier
            // (`main.`/`temp.`/`<attached>.`) only selects which schema's table
            // object is referenced — it does NOT change the reported database, so
            // `aux.dbstat` and `temp.dbstat` both still report `main`. (Targeting
            // another database needs a `WHERE schema='aux'` constraint — a hidden-
            // column pushdown not yet implemented.) A real user table of the name
            // in the *referenced* schema shadows the eponymous table.
            let lname = from.first.name.to_ascii_lowercase();
            if matches!(lname.as_str(), "dbstat" | "sqlite_dbpage") {
                let qual_db = match from.first.schema.as_deref() {
                    None => DbRef::Main,
                    Some(s) => self.resolve_db(Some(s))?,
                };
                let shadowed = match qual_db {
                    DbRef::Main => self.schema.table(&lname).is_some(),
                    DbRef::Temp => self
                        .temp_db
                        .as_ref()
                        .is_some_and(|t| t.schema.table(&lname).is_some()),
                    DbRef::Attached(i) => self.attached[i].schema.table(&lname).is_some(),
                };
                if !shadowed {
                    // Always report `main` (the default `schema` column value).
                    let alias = from.first.alias.as_deref();
                    let src = self.backend.source();
                    return match lname.as_str() {
                        "dbstat" => self.scan_dbstat(&self.schema, src, alias),
                        _ => self.scan_dbpage(src, alias),
                    };
                }
            }
            let db = match from.first.schema.as_deref() {
                Some(_) => self.resolve_db(from.first.schema.as_deref())?,
                // Don't let a temp table shadow a CTE or view of the same name.
                None if self.lookup_cte(&from.first.name, None).is_none()
                    && !self.is_view(&from.first.name) =>
                {
                    self.unqualified_db(&from.first.name)
                }
                None => DbRef::Main,
            };
            if db != DbRef::Main {
                self.guard_qualified_temp(db, from.first.schema.as_deref(), &from.first.name)?;
                let alias = from.first.alias.as_deref();
                if let Some(r) = self.scan_db_view(db, &from.first.name, alias, params)? {
                    return Ok(r);
                }
                return self.scan_db_table(db, &from.first.name, alias);
            }
        }
        // A table-valued function used as the sole source.
        if from.joins.is_empty()
            && (from.first.tvf_args.is_some() || self.is_pragma_tvf(&from.first))
        {
            let (columns, rows) = self.tvf_rows(&from.first, params)?;
            let input = rows
                .into_iter()
                .map(|values| InputRow {
                    values,
                    rowid: None,
                })
                .collect();
            return Ok((columns, input));
        }
        // A derived-table subquery used as the sole source.
        if from.joins.is_empty() {
            if let Some(sub) = &from.first.subquery {
                let (columns, rows) =
                    self.run_subquery_source(sub, from.first.alias.as_deref(), params)?;
                let input = rows
                    .into_iter()
                    .map(|values| InputRow {
                        values,
                        rowid: None,
                    })
                    .collect();
                return Ok((columns, input));
            }
        }
        // A `WITH` common table expression used as the sole source.
        if from.joins.is_empty() {
            if let Some((columns, rows)) =
                self.lookup_cte(&from.first.name, from.first.alias.as_deref())
            {
                return Ok((columns, rows));
            }
        }
        // A view as the sole source: run its SELECT in place.
        if from.joins.is_empty() {
            if let Some((columns, rows)) =
                self.try_view(&from.first.name, from.first.alias.as_deref(), params)?
            {
                return Ok((columns, rows));
            }
        }
        // A virtual table as the sole source: drain its module's cursor, pushing
        // the query's WHERE constraints into the module (it may restrict what it
        // produces; run_core still re-applies the full WHERE, so this is a
        // superset — never wrong).
        if from.joins.is_empty() && from.first.schema.is_none() {
            if let Some((columns, rows)) = self.try_virtual_table(
                &from.first.name,
                from.first.alias.as_deref(),
                Some((sel, params)),
            )? {
                return Ok((columns, rows));
            }
        }

        // Single-table fast path. Try an index-driven equality lookup first; the
        // full WHERE is still applied by run_core, so the index only needs to
        // return a superset of matching rows.
        if from.joins.is_empty() {
            let first_meta = self.table_meta(&from.first.name, from.first.alias.as_deref())?;
            if first_meta.without_rowid {
                // A leading-PK equality or range seeks the clustered b-tree; else
                // scan.
                if let Some(rows) = self.try_without_rowid_pk_seek(&first_meta, sel, params)? {
                    return Ok((first_meta.columns, rows));
                }
                if let Some(rows) = self.try_without_rowid_pk_range(&first_meta, sel, params)? {
                    return Ok((first_meta.columns, rows));
                }
                if let Some(rows) =
                    self.try_without_rowid_index_seek(&first_meta, &from.first.name, sel, params)?
                {
                    return Ok((first_meta.columns, rows));
                }
                if let Some(rows) =
                    self.try_without_rowid_index_range(&first_meta, &from.first.name, sel, params)?
                {
                    return Ok((first_meta.columns, rows));
                }
                let input_rows = self
                    .scan_without_rowid(&first_meta)?
                    .into_iter()
                    .map(|values| InputRow {
                        values,
                        rowid: None,
                    })
                    .collect();
                return Ok((first_meta.columns, input_rows));
            }
            if let Some(rows) = self.try_index_lookup(&first_meta, &from.first.name, sel, params)? {
                return Ok((first_meta.columns, rows));
            }
            if let Some(rows) = self.try_index_range(&first_meta, &from.first.name, sel, params)? {
                return Ok((first_meta.columns, rows));
            }
            if let Some(rows) = self.try_index_in(&first_meta, &from.first.name, sel, params)? {
                return Ok((first_meta.columns, rows));
            }
            if let Some(rows) = self.try_index_or(&first_meta, &from.first.name, sel, params)? {
                return Ok((first_meta.columns, rows));
            }
            // ORDER BY satisfied by a full secondary index (B0): walk that index
            // in key order, so `run_core` can skip the sort. Must stay in lockstep
            // with `order_satisfied_by_scan`/`eqp_access`. When the index covers
            // every referenced column (B2), build rows from the index records and
            // skip the table b-tree entirely; otherwise fetch each row by rowid.
            if let Some(s) = self.order_index_scan(sel) {
                let src = self.backend.source();
                let encoding = src.header().text_encoding;
                if s.covering {
                    let mut icur = IndexCursor::new(src, s.root);
                    let mut input_rows = Vec::new();
                    while let Some(payload) = icur.next()? {
                        let rec = decode_record(&payload, encoding)?;
                        // The record is `(indexed col values…, rowid)`.
                        let rowid = match rec.get(s.cols.len()) {
                            Some(Value::Integer(r)) => *r,
                            _ => return Err(Error::Corrupt("index record missing rowid".into())),
                        };
                        let mut values = alloc::vec![Value::Null; first_meta.columns.len()];
                        for (i, &mc) in s.cols.iter().enumerate() {
                            values[mc] = rec[i].clone();
                        }
                        if let Some(ipk) = first_meta.ipk {
                            values[ipk] = Value::Integer(rowid);
                        }
                        input_rows.push(InputRow {
                            values,
                            rowid: Some(rowid),
                        });
                    }
                    return Ok((first_meta.columns, input_rows));
                }
                let rowids = crate::btree::index_range_rowids(src, s.root, None, None, &s.colls)?;
                let mut cur = TableCursor::new(src, first_meta.root);
                let mut input_rows = Vec::with_capacity(rowids.len());
                for rid in rowids {
                    if cur.seek(rid)? {
                        let values =
                            self.decode_full_row(&first_meta, rid, &cur.payload()?, encoding)?;
                        input_rows.push(InputRow {
                            values,
                            rowid: Some(rid),
                        });
                    }
                }
                return Ok((first_meta.columns, input_rows));
            }
            // Covering scan (B2): no seek and no ORDER-BY index walk applied, but a
            // full index holds every column the query needs — read the rows from
            // that index instead of the table. `eqp_select` reports the matching
            // `SCAN … USING COVERING INDEX`.
            if let Some((_, root, cols)) = self.covering_scan(sel, &first_meta, params) {
                return Ok((
                    first_meta.columns.clone(),
                    self.covering_seek_rows(&first_meta, root, &cols)?,
                ));
            }
            let input_rows = self
                .scan_table(&first_meta)?
                .into_iter()
                .map(|(rowid, values)| InputRow {
                    values,
                    rowid: Some(rowid),
                })
                .collect();
            return Ok((first_meta.columns, input_rows));
        }

        // Join case: resolve the first source (CTE, view, or table), then fold
        // in joins.
        let (mut columns, mut rows) = self.resolve_join_source(&from.first, params)?;

        // Fold each join in with a nested-loop, evaluating its ON predicate
        // against the columns accumulated so far plus the joined table's.
        for join in &from.joins {
            // Roadmap B1a: when the inner table's join column is its rowid IPK,
            // seek the one inner row by rowid per outer row instead of
            // materializing and nested-looping it. Identical results to the
            // materialize path (the full `ON` is re-evaluated on the seeked row).
            if let Some((outer_col, inner_meta)) = self.rowid_join_seek(join, &columns) {
                let (new_columns, joined) = self.exec_rowid_join_seek(
                    join,
                    &columns,
                    &rows,
                    outer_col,
                    &inner_meta,
                    params,
                )?;
                columns = new_columns;
                rows = joined;
                continue;
            }

            // Roadmap B1a² (index case): when the inner join column is the
            // leading column of a usable secondary index, seek that index per
            // outer row instead of materializing the inner table. A non-unique
            // key may fan out to several inner rows. Identical results to the
            // materialize path (the full `ON` is re-evaluated on each seeked row).
            if let Some((outer_col, inner_meta, idx)) = self.index_join_seek(join, &columns) {
                let (new_columns, joined) = self.exec_index_join_seek(
                    join,
                    &columns,
                    &rows,
                    outer_col,
                    &inner_meta,
                    &idx,
                    params,
                )?;
                columns = new_columns;
                rows = joined;
                continue;
            }

            // WITHOUT ROWID inner table joined on its leading PRIMARY KEY: seek the
            // clustered b-tree per outer row instead of materializing it.
            if let Some((outer_col, inner_meta)) = self.without_rowid_pk_join_seek(join, &columns) {
                let (new_columns, joined) = self.exec_without_rowid_pk_join_seek(
                    join,
                    &columns,
                    &rows,
                    outer_col,
                    &inner_meta,
                    params,
                )?;
                columns = new_columns;
                rows = joined;
                continue;
            }

            let (jcols, jrows) = self.resolve_join_source(&join.table, params)?;

            let left_width = columns.len();
            // `NATURAL` / `USING` join columns, as `(left index, right local
            // index)` pairs: the join matches on equality of these and coalesces
            // each into the single left-side output column. `NATURAL` pairs every
            // commonly-named column; with no common column it degrades to a cross
            // join (empty `pairs`), matching SQLite.
            let pairs: Vec<(usize, usize)> = if join.natural {
                jcols
                    .iter()
                    .enumerate()
                    .filter_map(|(rl, rc)| {
                        columns
                            .iter()
                            .position(|c| c.name.eq_ignore_ascii_case(&rc.name))
                            .map(|li| (li, rl))
                    })
                    .collect()
            } else if !join.using.is_empty() {
                let mut v = Vec::with_capacity(join.using.len());
                for name in &join.using {
                    let li = columns
                        .iter()
                        .position(|c| c.name.eq_ignore_ascii_case(name));
                    let rl = jcols.iter().position(|c| c.name.eq_ignore_ascii_case(name));
                    match (li, rl) {
                        (Some(li), Some(rl)) => v.push((li, rl)),
                        _ => {
                            return Err(Error::Error(format!(
                            "cannot join using column {name} - column not present in both tables"
                        )))
                        }
                    }
                }
                v
            } else {
                Vec::new()
            };

            let mut new_columns = columns.clone();
            new_columns.extend(jcols.iter().cloned());
            let n_jcols = jcols.len();

            let mut joined: Vec<Vec<Value>> = Vec::new();
            let mut right_matched = alloc::vec![false; jrows.len()];

            // Build a hash index on the joined table when the ON predicate has an
            // equi-join `left.col = right.col`, turning the O(n*m) nested loop into
            // a probe. The full ON is still evaluated on each candidate (the hash
            // only narrows which right rows to test), so semantics are unchanged.
            // `NATURAL`/`USING` joins evaluate their equality directly (below) and
            // use the nested loop.
            let equi = if pairs.is_empty() {
                join.on
                    .as_ref()
                    .and_then(|on| join_equi_cols(on, &new_columns, left_width))
            } else {
                None
            };
            let hash: Option<(usize, alloc::collections::BTreeMap<JoinKey, Vec<usize>>)> = equi
                .map(|(li, ri_local)| {
                    let mut map: alloc::collections::BTreeMap<JoinKey, Vec<usize>> =
                        alloc::collections::BTreeMap::new();
                    for (ri, right) in jrows.iter().enumerate() {
                        for k in join_keys_of(&right[ri_local]) {
                            map.entry(k).or_default().push(ri);
                        }
                    }
                    (li, map)
                });

            for left in &rows {
                let mut matched = false;
                // Right rows to test: the hash candidates (sorted, deduped, so the
                // output order matches the nested loop) or every right row.
                let candidates: Vec<usize> = match &hash {
                    Some((li, map)) => {
                        let mut c: Vec<usize> = Vec::new();
                        for k in join_keys_of(&left[*li]) {
                            if let Some(idxs) = map.get(&k) {
                                c.extend_from_slice(idxs);
                            }
                        }
                        c.sort_unstable();
                        c.dedup();
                        c
                    }
                    None => (0..jrows.len()).collect(),
                };
                for ri in candidates {
                    let right = &jrows[ri];
                    let mut combined = left.clone();
                    combined.extend(right.iter().cloned());
                    let keep = if !pairs.is_empty() {
                        // NATURAL / USING: all join columns must be `=` equal (a
                        // NULL on either side is not a match), each under the left
                        // column's collation.
                        pairs.iter().all(|&(li, rl)| {
                            let coll = new_columns[li].collation;
                            // Apply each side's column affinity, like an `ON l = r`
                            // equality, so a cross-type USING/NATURAL key matches
                            // (INTEGER 1 = TEXT '1').
                            let (lv, rv) = eval::apply_comparison_affinity(
                                combined[li].clone(),
                                Some(new_columns[li].affinity),
                                combined[left_width + rl].clone(),
                                Some(new_columns[left_width + rl].affinity),
                            );
                            eval::truth(&eval::compare_op(BinaryOp::Eq, &lv, &rv, coll))
                                == Some(true)
                        })
                    } else {
                        match &join.on {
                            Some(on) => {
                                let ctx = row_ctx(&combined, &new_columns, None, params);
                                eval::truth(&eval::eval(on, &ctx)?) == Some(true)
                            }
                            None => true, // CROSS / comma join
                        }
                    };
                    if keep {
                        joined.push(combined);
                        matched = true;
                        right_matched[ri] = true;
                    }
                }
                // LEFT/FULL: emit the left row with NULLs when nothing matched.
                if !matched && matches!(join.kind, JoinKind::Left | JoinKind::Full) {
                    let mut combined = left.clone();
                    combined.extend(core::iter::repeat_n(Value::Null, n_jcols));
                    joined.push(combined);
                }
            }
            // RIGHT/FULL: emit each unmatched right row with NULLs for the left.
            if matches!(join.kind, JoinKind::Right | JoinKind::Full) {
                for (ri, right) in jrows.iter().enumerate() {
                    if !right_matched[ri] {
                        let mut combined = alloc::vec![Value::Null; left_width];
                        combined.extend(right.iter().cloned());
                        joined.push(combined);
                    }
                }
            }

            // NATURAL / USING: coalesce each join column into its left output
            // position (`COALESCE(left, right)` — the left value, or the right's
            // when the left side is NULL from an outer join), then drop the right
            // duplicate columns so each join column appears once.
            if !pairs.is_empty() {
                let mut drop: Vec<usize> = pairs.iter().map(|&(_, rl)| left_width + rl).collect();
                drop.sort_unstable();
                drop.dedup();
                for row in &mut joined {
                    for &(li, rl) in &pairs {
                        if matches!(row[li], Value::Null) {
                            row[li] = row[left_width + rl].clone();
                        }
                    }
                    for &d in drop.iter().rev() {
                        row.remove(d);
                    }
                }
                for &d in drop.iter().rev() {
                    new_columns.remove(d);
                }
            }

            columns = new_columns;
            rows = joined;
        }

        let input_rows = rows
            .into_iter()
            .map(|values| InputRow {
                values,
                rowid: None, // ambiguous across joined tables
            })
            .collect();
        Ok((columns, input_rows))
    }

    /// Resolve one table reference in a join to its columns + row values,
    /// consulting the CTE environment before the schema (so a CTE — including a
    /// recursive one — can appear as a join source).
    /// Run a derived-table subquery (`FROM (SELECT …) AS alias`) into column
    /// metadata (labeled with the alias) and row values.
    /// A bare `pragma_<name>` (no parentheses) used as a `FROM` source is the
    /// zero-argument table-valued form of that PRAGMA — unless a real table,
    /// view, or CTE of the same name shadows it.
    fn is_pragma_tvf(&self, tref: &TableRef) -> bool {
        tref.tvf_args.is_none()
            && tref.subquery.is_none()
            && tref.schema.is_none()
            && tref.name.to_ascii_lowercase().starts_with("pragma_")
            && self.lookup_cte(&tref.name, None).is_none()
            && !self.is_view(&tref.name)
            && self.unqualified_db(&tref.name) == DbRef::Main
            && self.schema.table(&tref.name).is_none()
    }

    /// Produce the rows of a table-valued function (`generate_series`, `json_each`,
    /// `json_tree`) used as a `FROM` source.
    fn tvf_rows(
        &self,
        tref: &TableRef,
        params: &Params,
    ) -> Result<(Vec<ColumnInfo>, Vec<Vec<Value>>)> {
        let args = tref.tvf_args.as_deref().unwrap_or(&[]);
        let lname = tref.name.to_ascii_lowercase();
        let label = tref.alias.clone().unwrap_or_else(|| tref.name.clone());
        let ctx = EvalCtx::rowless(params).with_subqueries(self);
        let col = |name: &str, affinity| ColumnInfo {
            name: String::from(name),
            table: label.clone(),
            affinity,
            collation: crate::value::Collation::default(),
        };
        match lname.as_str() {
            "generate_series" => {
                if args.is_empty() {
                    return Err(Error::Error("generate_series() requires arguments".into()));
                }
                let nums: Vec<i64> = args
                    .iter()
                    .map(|a| eval::eval(a, &ctx).map(|v| eval::to_i64(&v)))
                    .collect::<Result<_>>()?;
                let start = nums[0];
                let stop = nums.get(1).copied().unwrap_or(start);
                // SQLite's generate_series treats a step of 0 as 1.
                let step = match nums.get(2).copied().unwrap_or(1) {
                    0 => 1,
                    s => s,
                };
                let mut rows = Vec::new();
                if step != 0 {
                    let mut v = start;
                    loop {
                        let in_range = if step > 0 { v <= stop } else { v >= stop };
                        if !in_range {
                            break;
                        }
                        rows.push(alloc::vec![Value::Integer(v)]);
                        match v.checked_add(step) {
                            Some(n) => v = n,
                            None => break, // i64 overflow ends the series
                        }
                    }
                }
                Ok((alloc::vec![col("value", eval::Affinity::Integer)], rows))
            }
            "json_each" | "json_tree" => {
                let columns = alloc::vec![
                    col("key", eval::Affinity::Blob),
                    col("value", eval::Affinity::Blob),
                    col("type", eval::Affinity::Text),
                    col("atom", eval::Affinity::Blob),
                    col("id", eval::Affinity::Integer),
                    col("parent", eval::Affinity::Integer),
                    col("fullkey", eval::Affinity::Text),
                    col("path", eval::Affinity::Text),
                ];
                let Some(doc_arg) = args.first() else {
                    return Err(Error::Error(format!("{lname}() requires a JSON argument")));
                };
                let doc = eval::eval(doc_arg, &ctx)?;
                if matches!(doc, Value::Null) {
                    return Ok((columns, Vec::new()));
                }
                let Some(root) = crate::exec::json::parse(&eval::to_text(&doc)) else {
                    return Err(Error::Error("malformed JSON".into()));
                };
                // An optional second argument is a path to navigate to first; the
                // walk is then rooted at that element (e.g. `json_each(x, '$.a')`
                // iterates `$.a`'s children, with `$.a…` paths). A path that does
                // not resolve yields no rows.
                let (target, root_path) = match args.get(1) {
                    Some(path_arg) => {
                        let p = eval::to_text(&eval::eval(path_arg, &ctx)?);
                        match crate::exec::json::navigate(&root, &p) {
                            Some(sub) => (sub, p),
                            None => return Ok((columns, Vec::new())),
                        }
                    }
                    None => (&root, String::from("$")),
                };
                let mut rows = Vec::new();
                let mut next_id = 0i64;
                if lname == "json_tree" {
                    // The root row carries the path's final component as its key and
                    // its parent path in the `path` column.
                    let (parent_path, key) = split_json_path(&root_path);
                    json_tree_walk(
                        target,
                        key,
                        &root_path,
                        &parent_path,
                        None,
                        &mut next_id,
                        &mut rows,
                    );
                } else {
                    json_each_children(target, &root_path, &mut next_id, &mut rows);
                }
                Ok((columns, rows))
            }
            // `pragma_<name>(arg)` is the table-valued form of a PRAGMA, usable in
            // a FROM clause (e.g. `SELECT name FROM pragma_table_info('t')`).
            pragma if pragma.starts_with("pragma_") => {
                let p = Pragma {
                    name: String::from(&pragma["pragma_".len()..]),
                    value: args.first().cloned(),
                };
                let result = self.run_pragma(&p)?;
                let columns = result
                    .columns
                    .iter()
                    .map(|n| col(n, eval::Affinity::Blob))
                    .collect();
                Ok((columns, result.rows))
            }
            _ => Err(Error::Error(format!(
                "no such table-valued function: {}",
                tref.name
            ))),
        }
    }

    fn run_subquery_source(
        &self,
        select: &Select,
        alias: Option<&str>,
        params: &Params,
    ) -> Result<(Vec<ColumnInfo>, Vec<Vec<Value>>)> {
        let result = self.run_select(select, params)?;
        let label = alias.unwrap_or("").to_string();
        // A derived column inherits the affinity AND collation of its origin (a
        // direct column reference, transparent through parens / an explicit
        // `COLLATE`), matching sqlite; an expression column has NONE affinity and
        // BINARY collation. Resolved for a single-base-table subquery; a join /
        // nested subquery / TVF source leaves the conservative NONE/BINARY default.
        let origins = self.subquery_column_origins(select);
        let columns = result
            .columns
            .iter()
            .enumerate()
            .map(|(i, n)| {
                let (affinity, collation) = origins
                    .as_ref()
                    .and_then(|o| o.get(i).copied())
                    .unwrap_or((eval::Affinity::Blob, crate::value::Collation::default()));
                ColumnInfo {
                    name: n.clone(),
                    table: label.clone(),
                    affinity,
                    collation,
                }
            })
            .collect();
        Ok((columns, result.rows))
    }

    /// The `(affinity, collation)` each output column of a single-base-table
    /// subquery inherits from its origin — a direct column reference (through
    /// parens / `COLLATE`) takes its base column's affinity and collation (an
    /// explicit `COLLATE` overrides the collation); any other expression is
    /// `(BLOB, BINARY)`. Returns `None` (caller defaults all to `BLOB`/`BINARY`)
    /// for a compound / join / nested / TVF subquery, or a count mismatch.
    fn subquery_column_origins(&self, select: &Select) -> Option<Vec<ColOrigin>> {
        if !select.compound.is_empty() {
            return None;
        }
        let from = select.from.as_ref()?;
        if !from.joins.is_empty() {
            return None;
        }
        // The single source's named columns, each with its `(affinity, collation)`.
        // A base table reads them from its meta; a nested subquery recurses, so a
        // collation/affinity flows through any depth of single-source derived tables.
        let src = self.named_source_origins(&from.first)?;
        let label = from
            .first
            .alias
            .clone()
            .unwrap_or_else(|| from.first.name.clone());
        let base = |table: Option<&str>, col: &str| -> Option<ColOrigin> {
            if table.is_some_and(|t| !t.eq_ignore_ascii_case(&label)) {
                return None;
            }
            src.iter()
                .find(|(n, _)| n.eq_ignore_ascii_case(col))
                .map(|(_, o)| *o)
        };
        fn origin(e: &Expr, base: &dyn Fn(Option<&str>, &str) -> Option<ColOrigin>) -> ColOrigin {
            match e {
                Expr::Paren(inner) => origin(inner, base),
                Expr::Column { table, column } => base(table.as_deref(), column)
                    .unwrap_or((eval::Affinity::Blob, crate::value::Collation::default())),
                Expr::Collate { expr, collation } => {
                    let (aff, base_coll) = origin(expr, base);
                    (
                        aff,
                        crate::value::Collation::parse(collation).unwrap_or(base_coll),
                    )
                }
                _ => (eval::Affinity::Blob, crate::value::Collation::default()),
            }
        }
        let mut out = Vec::new();
        for rc in &select.columns {
            match rc {
                ResultColumn::Wildcard => out.extend(src.iter().map(|(_, o)| *o)),
                ResultColumn::TableWildcard(t) if t.eq_ignore_ascii_case(&label) => {
                    out.extend(src.iter().map(|(_, o)| *o))
                }
                ResultColumn::TableWildcard(_) => return None,
                ResultColumn::Expr { expr, .. } => out.push(origin(expr, &base)),
            }
        }
        Some(out)
    }

    /// A single FROM source's `(name, (affinity, collation))` per column. A base
    /// table reads its meta; a nested subquery recurses through
    /// `subquery_column_origins` (its names from `resolved_view_columns`), so an
    /// inherited affinity/collation flows through nested single-source derived
    /// tables. A view / CTE / TVF / join-or-compound subquery returns `None`.
    fn named_source_origins(&self, tref: &TableRef) -> Option<Vec<(String, ColOrigin)>> {
        if tref.tvf_args.is_some() {
            return None;
        }
        if let Some(sub) = &tref.subquery {
            let names = self.resolved_view_columns(sub)?;
            let origins = self.subquery_column_origins(sub)?;
            if names.len() != origins.len() {
                return None;
            }
            return Some(
                names
                    .into_iter()
                    .zip(origins)
                    .map(|((n, _), o)| (n, o))
                    .collect(),
            );
        }
        // A base table only — a view/CTE source defers to the conservative default.
        self.schema.table(&tref.name)?;
        let meta = self.table_meta(&tref.name, tref.alias.as_deref()).ok()?;
        Some(
            meta.columns
                .iter()
                .map(|c| (c.name.clone(), (c.affinity, c.collation)))
                .collect(),
        )
    }

    /// The single shared decision for the rowid-seek join optimization (roadmap
    /// B1a): when a `JOIN`'s `ON` is a lone equi-join `outer.col = u.ipk` (or the
    /// mirror) whose right side is the inner table `u`'s INTEGER PRIMARY KEY, the
    /// inner row can be fetched by rowid per outer row instead of materializing
    /// and nested-looping `u`. Returns `(outer_col_index, inner_meta)` when it
    /// applies; `None` otherwise (the caller falls back to materialize/hash).
    ///
    /// Used by BOTH the executor (to seek) and the join EQP emitter (to print
    /// `SEARCH … USING INTEGER PRIMARY KEY (rowid=?)` instead of `SCAN`), so the
    /// two never diverge. `left_columns` is the column list accumulated for the
    /// left side so far (its width is where the inner table's columns begin).
    fn rowid_join_seek(
        &self,
        join: &Join,
        left_columns: &[ColumnInfo],
    ) -> Option<(usize, TableMeta)> {
        // Only plain INNER / LEFT joins with a single `ON` equality — never
        // NATURAL / USING / CROSS / RIGHT / FULL.
        if !matches!(join.kind, JoinKind::Inner | JoinKind::Left)
            || join.natural
            || !join.using.is_empty()
        {
            return None;
        }
        let on = join.on.as_ref()?;
        let tref = &join.table;
        // The inner table must be a plain base table in `main`: not a subquery /
        // CTE / view / TVF, and not schema-qualified.
        if tref.subquery.is_some()
            || tref.tvf_args.is_some()
            || self.is_pragma_tvf(tref)
            || tref.schema.is_some()
            || self.lookup_cte(&tref.name, tref.alias.as_deref()).is_some()
            || self.is_view(&tref.name)
            || self.unqualified_db(&tref.name) != DbRef::Main
        {
            return None;
        }
        let meta = self.table_meta(&tref.name, tref.alias.as_deref()).ok()?;
        // Must have a rowid IPK (rules out WITHOUT ROWID, which has `ipk == None`).
        let ipk = meta.ipk?;
        // The `ON` must be a single top-level `=` (after unwrapping parens), one
        // side the inner table's IPK column and the other a left-side column.
        let mut on = on;
        while let Expr::Paren(inner) = on {
            on = inner;
        }
        let left_width = left_columns.len();
        let mut combined = left_columns.to_vec();
        combined.extend(meta.columns.iter().cloned());
        let (a, b) = match on {
            Expr::Binary {
                op: BinaryOp::Eq,
                left,
                right,
            } => (col_index(left, &combined)?, col_index(right, &combined)?),
            _ => return None,
        };
        // Identify which side is the inner IPK (`left_width + ipk`) and which is
        // the outer column (a left-side index).
        let inner_ipk = left_width + ipk;
        let outer = if a == inner_ipk && b < left_width {
            b
        } else if b == inner_ipk && a < left_width {
            a
        } else {
            return None;
        };
        Some((outer, meta))
    }

    /// The index-seek companion of [`rowid_join_seek`](Self::rowid_join_seek)
    /// (roadmap B1a², index case): when a `JOIN`'s `ON` is a lone equi-join
    /// `outer.col = u.k` whose right side `u.k` is the *leading column of a full
    /// (non-partial, non-expression) secondary index* on the inner plain base
    /// table `u`, the matching inner rows can be found by seeking that index per
    /// outer row instead of materializing and nested-looping `u`. Returns the
    /// outer column index, the inner table meta, and the chosen index when it
    /// applies; `None` otherwise.
    ///
    /// The rowid/IPK case is preferred — callers must consult
    /// [`rowid_join_seek`](Self::rowid_join_seek) first and only fall through to
    /// this when that returns `None`. Shared by BOTH the executor (to seek) and
    /// the join EQP emitter (to print `SEARCH … USING INDEX <name> (<col>=?)`),
    /// so the two never diverge.
    fn index_join_seek(
        &self,
        join: &Join,
        left_columns: &[ColumnInfo],
    ) -> Option<(usize, TableMeta, IndexMeta)> {
        if !matches!(join.kind, JoinKind::Inner | JoinKind::Left)
            || join.natural
            || !join.using.is_empty()
        {
            return None;
        }
        let on = join.on.as_ref()?;
        let tref = &join.table;
        // The inner table must be a plain base table in `main`: not a subquery /
        // CTE / view / TVF, and not schema-qualified.
        if tref.subquery.is_some()
            || tref.tvf_args.is_some()
            || self.is_pragma_tvf(tref)
            || tref.schema.is_some()
            || self.lookup_cte(&tref.name, tref.alias.as_deref()).is_some()
            || self.is_view(&tref.name)
            || self.unqualified_db(&tref.name) != DbRef::Main
        {
            return None;
        }
        let meta = self.table_meta(&tref.name, tref.alias.as_deref()).ok()?;
        if meta.without_rowid {
            return None;
        }
        // The `ON` must be a single top-level `=` (after unwrapping parens), one
        // side an inner-table column and the other a left-side column.
        let mut on = on;
        while let Expr::Paren(inner) = on {
            on = inner;
        }
        let left_width = left_columns.len();
        let mut combined = left_columns.to_vec();
        combined.extend(meta.columns.iter().cloned());
        let (a, b) = match on {
            Expr::Binary {
                op: BinaryOp::Eq,
                left,
                right,
            } => (col_index(left, &combined)?, col_index(right, &combined)?),
            _ => return None,
        };
        // One side must be an inner column (>= left_width) and the other a
        // left-side column (< left_width).
        let (inner_idx, outer) = if a >= left_width && b < left_width {
            (a - left_width, b)
        } else if b >= left_width && a < left_width {
            (b - left_width, a)
        } else {
            return None;
        };
        // The inner join column must be the *leading* column of a full index (not
        // partial, not expression). Pick the first such index by catalog order so
        // the choice is deterministic and matches the EQP emitter.
        let indexes = self.indexes_of(&tref.name).ok()?;
        let idx = indexes.into_iter().find(|i| {
            i.partial.is_none() && i.key_exprs.is_none() && i.cols.first() == Some(&inner_idx)
        })?;
        Some((outer, meta, idx))
    }

    /// The WITHOUT ROWID companion of [`index_join_seek`](Self::index_join_seek):
    /// when the inner table is WITHOUT ROWID and the `ON` equates an outer column
    /// with its *leading* PRIMARY KEY column, the inner row is found by seeking
    /// the clustered b-tree per outer row (`SEARCH … USING PRIMARY KEY (col=?)`)
    /// instead of scanning. Callers consult this after `rowid_join_seek` and
    /// `index_join_seek` (which both decline WITHOUT ROWID tables). Returns
    /// `(outer column index, inner meta)`.
    fn without_rowid_pk_join_seek(
        &self,
        join: &Join,
        left_columns: &[ColumnInfo],
    ) -> Option<(usize, TableMeta)> {
        if !matches!(join.kind, JoinKind::Inner | JoinKind::Left)
            || join.natural
            || !join.using.is_empty()
        {
            return None;
        }
        let on = join.on.as_ref()?;
        let tref = &join.table;
        if tref.subquery.is_some()
            || tref.tvf_args.is_some()
            || self.is_pragma_tvf(tref)
            || tref.schema.is_some()
            || self.lookup_cte(&tref.name, tref.alias.as_deref()).is_some()
            || self.is_view(&tref.name)
            || self.unqualified_db(&tref.name) != DbRef::Main
        {
            return None;
        }
        let meta = self.table_meta(&tref.name, tref.alias.as_deref()).ok()?;
        if !meta.without_rowid || meta.pk_len == 0 {
            return None;
        }
        let lead_pk = meta.storage_order[0];
        let mut on = on;
        while let Expr::Paren(inner) = on {
            on = inner;
        }
        let left_width = left_columns.len();
        let mut combined = left_columns.to_vec();
        combined.extend(meta.columns.iter().cloned());
        let (a, b) = match on {
            Expr::Binary {
                op: BinaryOp::Eq,
                left,
                right,
            } => (col_index(left, &combined)?, col_index(right, &combined)?),
            _ => return None,
        };
        let (inner_idx, outer) = if a >= left_width && b < left_width {
            (a - left_width, b)
        } else if b >= left_width && a < left_width {
            (b - left_width, a)
        } else {
            return None;
        };
        if inner_idx != lead_pk {
            return None;
        }
        Some((outer, meta))
    }

    /// Execute a WITHOUT ROWID PK-seek join (decided by
    /// [`without_rowid_pk_join_seek`](Self::without_rowid_pk_join_seek)): for each
    /// outer row, seek the inner table's clustered b-tree by the join key, decode
    /// each matching record to a row, combine, and re-evaluate the full `ON`.
    /// INNER drops an unmatched outer row; LEFT NULL-extends it.
    fn exec_without_rowid_pk_join_seek(
        &self,
        join: &Join,
        columns: &[ColumnInfo],
        rows: &[Vec<Value>],
        outer_col: usize,
        inner_meta: &TableMeta,
        params: &Params,
    ) -> Result<(Vec<ColumnInfo>, Vec<Vec<Value>>)> {
        let mut new_columns = columns.to_vec();
        new_columns.extend(inner_meta.columns.iter().cloned());
        let n_jcols = inner_meta.columns.len();
        let on = join.on.as_ref();
        let is_left = matches!(join.kind, JoinKind::Left);
        let lead = inner_meta.storage_order[0];
        let coll = wr_storage_collations(inner_meta)[0];
        let src = self.backend.source();
        let mut joined: Vec<Vec<Value>> = Vec::new();
        for left in rows {
            let mut matched = false;
            if !matches!(left[outer_col], Value::Null) {
                let key = [inner_meta.columns[lead]
                    .affinity
                    .coerce(left[outer_col].clone())];
                let records =
                    crate::btree::index_seek_records(src, inner_meta.root, &key, &[coll])?;
                for storage in records {
                    let mut inner = unpermute_row(inner_meta, storage);
                    self.compute_generated(inner_meta, &mut inner, params)?;
                    let mut row = left.clone();
                    row.extend(inner);
                    let keep = match on {
                        Some(on) => {
                            let ctx = row_ctx(&row, &new_columns, None, params);
                            eval::truth(&eval::eval(on, &ctx)?) == Some(true)
                        }
                        None => true,
                    };
                    if keep {
                        joined.push(row);
                        matched = true;
                    }
                }
            }
            if !matched && is_left {
                let mut combined = left.clone();
                combined.extend(core::iter::repeat_n(Value::Null, n_jcols));
                joined.push(combined);
            }
        }
        Ok((new_columns, joined))
    }

    /// Execute one index-seek join (decided by
    /// [`index_join_seek`](Self::index_join_seek)): for each outer row, take the
    /// join-key value, seek the chosen secondary index for matching rowids, fetch
    /// each inner row by rowid, combine, and re-evaluate the full `ON` so results
    /// are byte-identical to the materialize/hash path. A non-unique index key may
    /// match multiple inner rows — one combined row is emitted per match. INNER
    /// drops an outer row with no inner match; LEFT NULL-extends it. A NULL key
    /// (or one with no index match) yields no inner rows.
    #[allow(clippy::too_many_arguments)]
    fn exec_index_join_seek(
        &self,
        join: &Join,
        columns: &[ColumnInfo],
        rows: &[Vec<Value>],
        outer_col: usize,
        inner_meta: &TableMeta,
        idx: &IndexMeta,
        params: &Params,
    ) -> Result<(Vec<ColumnInfo>, Vec<Vec<Value>>)> {
        let encoding = self.backend.source().header().text_encoding;
        let mut new_columns = columns.to_vec();
        new_columns.extend(inner_meta.columns.iter().cloned());
        let n_jcols = inner_meta.columns.len();
        let on = join.on.as_ref();
        let is_left = matches!(join.kind, JoinKind::Left);

        let lead = idx.cols[0];
        let coll = idx.collations[0];
        let src = self.backend.source();
        let mut cur = TableCursor::new(self.backend.source(), inner_meta.root);
        let mut joined: Vec<Vec<Value>> = Vec::new();
        for left in rows {
            let mut matched = false;
            // A NULL outer key never equi-joins; skip the seek (no inner match).
            if !matches!(left[outer_col], Value::Null) {
                // Coerce the key to the leading column's affinity, mirroring
                // `try_index_lookup` so the index comparison is identical.
                let key = [inner_meta.columns[lead]
                    .affinity
                    .coerce(left[outer_col].clone())];
                let colls = [coll];
                let rowids = crate::btree::index_seek_rowids(src, idx.root, &key, &colls)?;
                for rid in rowids {
                    if cur.seek(rid)? {
                        let inner =
                            self.decode_full_row(inner_meta, rid, &cur.payload()?, encoding)?;
                        let mut row = left.clone();
                        row.extend(inner);
                        let keep = match on {
                            Some(on) => {
                                let ctx = row_ctx(&row, &new_columns, None, params);
                                eval::truth(&eval::eval(on, &ctx)?) == Some(true)
                            }
                            None => true,
                        };
                        if keep {
                            joined.push(row);
                            matched = true;
                        }
                    }
                }
            }
            // LEFT: emit the outer row NULL-extended when nothing matched.
            if !matched && is_left {
                let mut combined = left.clone();
                combined.extend(core::iter::repeat_n(Value::Null, n_jcols));
                joined.push(combined);
            }
        }
        Ok((new_columns, joined))
    }

    /// Execute one rowid-seek join (decided by [`rowid_join_seek`](Self::rowid_join_seek)):
    /// for each outer row, coerce its join column to an integer rowid, seek the
    /// inner table's b-tree, and combine. The full `ON` is re-evaluated on the
    /// fetched row so results are identical to the materialize/hash path. INNER
    /// drops an outer row with no inner match; LEFT NULL-extends it.
    fn exec_rowid_join_seek(
        &self,
        join: &Join,
        columns: &[ColumnInfo],
        rows: &[Vec<Value>],
        outer_col: usize,
        inner_meta: &TableMeta,
        params: &Params,
    ) -> Result<(Vec<ColumnInfo>, Vec<Vec<Value>>)> {
        let encoding = self.backend.source().header().text_encoding;
        let mut new_columns = columns.to_vec();
        new_columns.extend(inner_meta.columns.iter().cloned());
        let n_jcols = inner_meta.columns.len();
        let on = join.on.as_ref();
        let is_left = matches!(join.kind, JoinKind::Left);

        let mut cur = TableCursor::new(self.backend.source(), inner_meta.root);
        let mut joined: Vec<Vec<Value>> = Vec::new();
        for left in rows {
            // Coerce the outer join value to a candidate rowid. A NULL (or any
            // value that isn't an exact integer) never equi-joins; the `ON`
            // re-eval below rejects a spurious truncation (e.g. `2.5` → 2).
            let key = &left[outer_col];
            let candidate = match key {
                Value::Integer(i) => Some(*i),
                Value::Real(_) | Value::Text(_) => match eval::to_number(key) {
                    Value::Integer(i) => Some(i),
                    Value::Real(r) if r == (r as i64) as f64 => Some(r as i64),
                    _ => None,
                },
                Value::Null | Value::Blob(_) => None,
            };
            let mut matched = false;
            if let Some(rid) = candidate {
                if cur.seek(rid)? {
                    let inner = self.decode_full_row(inner_meta, rid, &cur.payload()?, encoding)?;
                    let mut combined = left.clone();
                    combined.extend(inner);
                    let keep = match on {
                        Some(on) => {
                            let ctx = row_ctx(&combined, &new_columns, None, params);
                            eval::truth(&eval::eval(on, &ctx)?) == Some(true)
                        }
                        None => true,
                    };
                    if keep {
                        joined.push(combined);
                        matched = true;
                    }
                }
            }
            // LEFT: emit the outer row NULL-extended when nothing matched.
            if !matched && is_left {
                let mut combined = left.clone();
                combined.extend(core::iter::repeat_n(Value::Null, n_jcols));
                joined.push(combined);
            }
        }
        Ok((new_columns, joined))
    }

    fn resolve_join_source(
        &self,
        tref: &TableRef,
        params: &Params,
    ) -> Result<(Vec<ColumnInfo>, Vec<Vec<Value>>)> {
        if tref.tvf_args.is_some() || self.is_pragma_tvf(tref) {
            return self.tvf_rows(tref, params);
        }
        if let Some(sub) = &tref.subquery {
            return self.run_subquery_source(sub, tref.alias.as_deref(), params);
        }
        if let Some((cols, rows)) = self.lookup_cte(&tref.name, tref.alias.as_deref()) {
            return Ok((cols, rows.into_iter().map(|r| r.values).collect()));
        }
        if let Some((cols, rows)) = self.try_view(&tref.name, tref.alias.as_deref(), params)? {
            return Ok((cols, rows.into_iter().map(|r| r.values).collect()));
        }
        if tref.schema.is_none() {
            // In a join, the WHERE may reference other tables, so no pushdown here
            // (full scan + the join's re-applied WHERE keeps it correct).
            if let Some((cols, rows)) =
                self.try_virtual_table(&tref.name, tref.alias.as_deref(), None)?
            {
                return Ok((cols, rows.into_iter().map(|r| r.values).collect()));
            }
        }
        // Cross-database join source: an explicit qualifier (`aux.t`) picks the
        // database; an unqualified name may be shadowed by a temp table. Either
        // way a non-main source is materialized through its own backend.
        let db = match tref.schema.as_deref() {
            Some(_) => self.resolve_db(tref.schema.as_deref())?,
            None => self.unqualified_db(&tref.name),
        };
        if db != DbRef::Main {
            self.guard_qualified_temp(db, tref.schema.as_deref(), &tref.name)?;
            if let Some((cols, input)) =
                self.scan_db_view(db, &tref.name, tref.alias.as_deref(), params)?
            {
                return Ok((cols, input.into_iter().map(|r| r.values).collect()));
            }
            let (cols, input) = self.scan_db_table(db, &tref.name, tref.alias.as_deref())?;
            return Ok((cols, input.into_iter().map(|r| r.values).collect()));
        }
        let meta = self.table_meta(&tref.name, tref.alias.as_deref())?;
        let rows = if meta.without_rowid {
            self.scan_without_rowid(&meta)?
        } else {
            self.scan_table(&meta)?
                .into_iter()
                .map(|(_, v)| v)
                .collect()
        };
        Ok((meta.columns, rows))
    }

    /// Scan a `WITHOUT ROWID` table's clustered index b-tree, decoding each entry
    /// (stored PK-first) back into declared column order.
    fn scan_without_rowid(&self, meta: &TableMeta) -> Result<Vec<Vec<Value>>> {
        let encoding = self.backend.source().header().text_encoding;
        let mut cur = IndexCursor::new(self.backend.source(), meta.root);
        let params = Params::default();
        let mut out = Vec::new();
        while let Some(payload) = cur.next()? {
            let storage = decode_record(&payload, encoding)?;
            let mut row = unpermute_row(meta, storage);
            self.compute_generated(meta, &mut row, &params)?;
            out.push(row);
        }
        Ok(out)
    }

    /// Build a row (declared order) from an INSERT's column list + value exprs,
    /// applying defaults and affinity. Shared by the WITHOUT ROWID insert path.
    fn build_insert_row(
        &self,
        meta: &TableMeta,
        target: &[usize],
        row_exprs: &[Expr],
        params: &Params,
    ) -> Result<Vec<Value>> {
        let ctx = EvalCtx::rowless(params).with_subqueries(self);
        let mut values: Vec<Value> = meta
            .defaults
            .iter()
            .map(|d| match d {
                Some(e) => eval::eval(e, &ctx),
                None => Ok(Value::Null),
            })
            .collect::<Result<_>>()?;
        for (i, e) in row_exprs.iter().enumerate() {
            if meta.is_generated(target[i]) {
                return Err(Error::Error(format!(
                    "cannot INSERT into generated column \"{}\"",
                    meta.columns[target[i]].name
                )));
            }
            values[target[i]] = eval::eval(e, &ctx)?;
        }
        apply_column_affinity(meta, &mut values);
        self.materialize_generated(meta, &mut values, params)?;
        self.check_strict_types(meta, &values)?;
        Ok(values)
    }

    /// INSERT into a WITHOUT ROWID (PK-clustered) table.
    fn exec_insert_without_rowid(
        &mut self,
        ins: &Insert,
        meta: &TableMeta,
        rows: &[Vec<Expr>],
        params: &Params,
    ) -> Result<usize> {
        let n_cols = meta.columns.len();
        let target: Vec<usize> = if ins.columns.is_empty() {
            // Non-generated columns only (see exec_insert): a bare INSERT into a
            // WITHOUT ROWID table with generated columns must not expect a value
            // for the computed columns.
            (0..n_cols).filter(|&i| !meta.is_generated(i)).collect()
        } else {
            ins.columns
                .iter()
                .map(|name| {
                    meta.columns
                        .iter()
                        .position(|c| c.name.eq_ignore_ascii_case(name))
                        .ok_or_else(|| Error::Error(format!("no such column: {name}")))
                })
                .collect::<Result<_>>()?
        };
        let pk = &meta.storage_order[..meta.pk_len];
        let mut affected = 0;
        for row_exprs in rows {
            if !ins.columns.is_empty() && row_exprs.len() != target.len() {
                return Err(Error::Error("INSERT column/value count mismatch".into()));
            }
            let values = self.build_insert_row(meta, &target, row_exprs, params)?;
            // PRIMARY KEY / NOT NULL / CHECK constraints. `INSERT OR IGNORE`
            // skips a violating row; any other policy lets the error propagate.
            {
                let r = (|| {
                    // PRIMARY KEY columns are implicitly NOT NULL in a WITHOUT
                    // ROWID table.
                    for &c in pk {
                        if matches!(values[c], Value::Null) {
                            return Err(Error::Constraint(format!(
                                "NOT NULL constraint failed: {}.{}",
                                meta.columns[c].table, meta.columns[c].name
                            )));
                        }
                    }
                    check_not_null(meta, &values)?;
                    self.check_constraints(meta, &values, None, params)
                })();
                match r {
                    Ok(()) => {}
                    Err(Error::Constraint(_)) if ins.on_conflict == OnConflict::Ignore => continue,
                    Err(e) => return Err(e),
                }
            }

            // Reject a duplicate primary key, an inline UNIQUE constraint, or a
            // standalone UNIQUE index (incl. partial). Collect colliding rows so
            // REPLACE can rebuild without them.
            let existing = self.scan_without_rowid(meta)?;
            let mut collide = Vec::new();
            for (i, r) in existing.iter().enumerate() {
                if unique_match(meta, r, &values)
                    || self.wr_index_collision(&ins.table, meta, r, &values, params)?
                {
                    collide.push(i);
                }
            }
            if !collide.is_empty() {
                match ins.on_conflict {
                    oc @ (OnConflict::Abort | OnConflict::Fail | OnConflict::Rollback) => {
                        let m = wr_unique_message(meta, &existing[collide[0]], &values);
                        return Err(self.conflict_error(oc, &m));
                    }
                    OnConflict::Ignore => continue,
                    OnConflict::Replace => {
                        // Rebuild without the conflicting row(s), then insert.
                        let kept: Vec<Vec<Value>> = existing
                            .into_iter()
                            .enumerate()
                            .filter(|(i, _)| !collide.contains(i))
                            .map(|(_, r)| r)
                            .collect();
                        self.rewrite_without_rowid(meta, kept.into_iter())?;
                    }
                }
            }
            let record = encode_record(&permute_row(meta, &values));
            let scolls = wr_storage_collations(meta);
            insert_index(self.backend.writer()?, meta.root, &record, &scolls)?;
            affected += 1;
        }
        if affected > 0 {
            self.rebuild_wr_indexes(meta, &ins.table)?;
        }
        Ok(affected)
    }

    /// DELETE from a WITHOUT ROWID table: keep non-matching rows, rebuild.
    fn exec_delete_without_rowid(
        &mut self,
        del: &Delete,
        meta: &TableMeta,
        params: &Params,
    ) -> Result<usize> {
        let all = self.scan_without_rowid(meta)?;
        let mut kept = Vec::new();
        let mut deleted = 0;
        for row in all {
            let keep = match &del.where_clause {
                Some(p) => {
                    let ctx = row_ctx(&row, &meta.columns, None, params).with_subqueries(self);
                    eval::truth(&eval::eval(p, &ctx)?) != Some(true)
                }
                None => false,
            };
            if keep {
                kept.push(row);
            } else {
                deleted += 1;
            }
        }
        if deleted > 0 {
            self.rewrite_without_rowid(meta, kept.into_iter())?;
            self.rebuild_wr_indexes(meta, &del.table)?;
        }
        Ok(deleted)
    }

    /// UPDATE a WITHOUT ROWID table: recompute matching rows, rebuild.
    fn exec_update_without_rowid(
        &mut self,
        upd: &Update,
        meta: &TableMeta,
        params: &Params,
    ) -> Result<usize> {
        let all = self.scan_without_rowid(meta)?;
        let mut out = Vec::with_capacity(all.len());
        let mut affected = 0;
        for mut row in all {
            let matches = match &upd.where_clause {
                Some(p) => {
                    let ctx = row_ctx(&row, &meta.columns, None, params).with_subqueries(self);
                    eval::truth(&eval::eval(p, &ctx)?) == Some(true)
                }
                None => true,
            };
            if matches {
                // Assignments are simultaneous: evaluate every SET expression
                // against the original row, not the progressively-mutated one.
                let original = row.clone();
                for (col, expr) in &upd.assignments {
                    let pos = meta
                        .columns
                        .iter()
                        .position(|c| c.name.eq_ignore_ascii_case(col))
                        .ok_or_else(|| Error::Error(format!("no such column: {col}")))?;
                    if meta.is_generated(pos) {
                        return Err(Error::Error(format!(
                            "cannot UPDATE generated column \"{col}\""
                        )));
                    }
                    let ctx = row_ctx(&original, &meta.columns, None, params).with_subqueries(self);
                    row[pos] = eval::eval(expr, &ctx)?;
                }
                if !upd.row_assignments.is_empty() {
                    let ctx = row_ctx(&original, &meta.columns, None, params).with_subqueries(self);
                    self.apply_row_subquery_assignments(
                        &upd.row_assignments,
                        &meta.columns,
                        Some(meta),
                        &ctx,
                        &mut row,
                    )?;
                }
                apply_column_affinity(meta, &mut row);
                self.materialize_generated(meta, &mut row, params)?;
                check_not_null(meta, &row)?;
                self.check_strict_types(meta, &row)?;
                self.check_constraints(meta, &row, None, params)?;
                affected += 1;
            }
            out.push(row);
        }
        // Reject duplicate primary keys or UNIQUE values produced by the update
        // (inline constraints and standalone unique indexes alike).
        for i in 0..out.len() {
            for j in (i + 1)..out.len() {
                if unique_match(meta, &out[i], &out[j])
                    || self.wr_index_collision(&upd.table, meta, &out[i], &out[j], params)?
                {
                    return Err(Error::Constraint(wr_unique_message(meta, &out[i], &out[j])));
                }
            }
        }
        if affected > 0 {
            self.rewrite_without_rowid(meta, out.into_iter())?;
            self.rebuild_wr_indexes(meta, &upd.table)?;
        }
        Ok(affected)
    }

    /// Replace a WITHOUT ROWID table's entire contents with `rows` (declared
    /// order), re-encoding each into PK-first storage order.
    fn rewrite_without_rowid(
        &mut self,
        meta: &TableMeta,
        rows: impl Iterator<Item = Vec<Value>>,
    ) -> Result<()> {
        let records: Vec<Vec<u8>> = rows
            .map(|r| encode_record(&permute_row(meta, &r)))
            .collect();
        let scolls = wr_storage_collations(meta);
        let w = self.backend.writer()?;
        clear_index(w, meta.root)?;
        for rec in &records {
            insert_index(w, meta.root, rec, &scolls)?;
        }
        Ok(())
    }

    /// Rebuild every secondary index of a `WITHOUT ROWID` table from its current
    /// rows, keying entries by (indexed cols, PK cols).
    fn rebuild_wr_indexes(&mut self, meta: &TableMeta, table: &str) -> Result<()> {
        let indexes = self.indexes_of(table)?;
        if indexes.is_empty() {
            return Ok(());
        }
        let rows = self.scan_without_rowid(meta)?;
        let pk_cols = meta.storage_order[..meta.pk_len].to_vec();
        let pk_colls: Vec<crate::value::Collation> =
            pk_cols.iter().map(|&c| meta.columns[c].collation).collect();
        // Precompute partial-index membership before the writer borrow.
        let mut keep: Vec<Vec<usize>> = Vec::with_capacity(indexes.len());
        for idx in &indexes {
            let mut ks = Vec::new();
            for (i, row) in rows.iter().enumerate() {
                if self.row_in_index(idx, meta, row, None, &Params::default())? {
                    ks.push(i);
                }
            }
            keep.push(ks);
        }
        let w = self.backend.writer()?;
        for (idx, ks) in indexes.iter().zip(&keep) {
            let mut key_colls = idx.collations.clone();
            key_colls.extend(pk_colls.iter().copied());
            clear_index(w, idx.root)?;
            for &i in ks {
                insert_index(
                    w,
                    idx.root,
                    &wr_index_key(&idx.cols, &pk_cols, &rows[i]),
                    &key_colls,
                )?;
            }
        }
        Ok(())
    }

    /// Scan a whole table into `(rowid, column values)`.
    /// Whether the named table currently holds no rows (handles both rowid and
    /// WITHOUT ROWID storage).
    fn table_is_empty(&self, table: &str) -> Result<bool> {
        let meta = self.table_meta(table, None)?;
        if meta.without_rowid {
            Ok(self.scan_without_rowid(&meta)?.is_empty())
        } else {
            Ok(self.scan_table(&meta)?.is_empty())
        }
    }

    /// Resolve a `schema.` qualifier to a database: `None`/`main` → `Main`;
    /// `temp`/`temporary` → `Temp`; an attached name → `Attached(index)`; an
    /// unknown name is an error.
    fn resolve_db(&self, schema: Option<&str>) -> Result<DbRef> {
        match schema {
            None => Ok(DbRef::Main),
            Some(s) if s.eq_ignore_ascii_case("main") => Ok(DbRef::Main),
            Some(s) if s.eq_ignore_ascii_case("temp") || s.eq_ignore_ascii_case("temporary") => {
                Ok(DbRef::Temp)
            }
            Some(s) => self
                .attached
                .iter()
                .position(|d| d.name.eq_ignore_ascii_case(s))
                .map(DbRef::Attached)
                .ok_or_else(|| Error::Error(alloc::format!("unknown database {s}"))),
        }
    }

    /// A `temp.`-qualified read is only resolvable once the temp database has
    /// been materialized (by a temp write). Until then SQLite reports the name
    /// as missing (the temp schema simply holds no such table) — without this
    /// guard a read would reach [`db_parts`](Self::db_parts) and panic.
    fn guard_qualified_temp(&self, db: DbRef, qualifier: Option<&str>, name: &str) -> Result<()> {
        if db == DbRef::Temp && self.temp_db.is_none() {
            return Err(Error::Error(alloc::format!(
                "no such table: {}.{}",
                qualifier.unwrap_or("temp"),
                name
            )));
        }
        Ok(())
    }

    /// The schema catalog and backend for a resolved database. `Temp` requires
    /// the temp database to exist (created by [`ensure_temp`](Self::ensure_temp)).
    fn db_parts(&self, db: DbRef) -> (&Schema, &Backend) {
        match db {
            DbRef::Main => (&self.schema, &self.backend),
            DbRef::Temp => {
                let t = self.temp_db.as_ref().expect("temp db exists");
                (&t.schema, &t.backend)
            }
            DbRef::Attached(i) => (&self.attached[i].schema, &self.attached[i].backend),
        }
    }

    /// The database an *unqualified* table name resolves to: the `temp` database
    /// when it holds the table (temp shadows main), else `main`.
    fn unqualified_db(&self, name: &str) -> DbRef {
        if let Some(t) = &self.temp_db {
            if t.schema.table(name).is_some() {
                return DbRef::Temp;
            }
        }
        // Inside a cross-database view read, unqualified names resolve in the
        // view's own database (when it has the table) before falling back to
        // main; nested subqueries inherit this via the shared cell.
        let def = self.read_default.get();
        if def != DbRef::Main {
            let (schema, _) = self.db_parts(def);
            if schema.table(name).is_some() {
                return def;
            }
        }
        // The active `main` schema wins next — SQLite resolves an unqualified name
        // main-first.
        if self.schema.table(name).is_some() {
            return DbRef::Main;
        }
        // Then attached databases, in attach order (SQLite's `main → temp →
        // attached` search). This lets `SELECT … FROM s` find a table living only
        // in an attached database; and, because a cross-database write swaps the
        // original `main` into the target's attached slot, it also lets a subquery
        // inside `UPDATE/DELETE aux.t …` resolve a `main` table while the write
        // targets `aux` (ROADMAP Track E). A name present in *both* the active db
        // and an attached one still binds to the active db, above.
        for (i, d) in self.attached.iter().enumerate() {
            if d.schema.table(name).is_some() {
                return DbRef::Attached(i);
            }
        }
        DbRef::Main
    }

    /// Create the `temp` database if it does not yet exist (a fresh in-memory
    /// database, like an attachment).
    fn ensure_temp(&mut self) -> Result<()> {
        if self.temp_db.is_some() {
            return Ok(());
        }
        let vfs = crate::vfs::memory::MemoryVfs::new();
        let f = vfs.open("temp", OpenFlags::READ_WRITE_CREATE)?;
        let mut db = WritePager::create(f, None, 4096)?;
        db.commit()?;
        let backend = Backend::Write(Box::new(db));
        let schema = Schema::read(backend.source())?;
        self.temp_db = Some(AttachedDb {
            name: "temp".into(),
            file: String::new(),
            backend,
            schema,
        });
        Ok(())
    }

    /// Materialize a rowid table from a non-main database into `(columns, rows)`
    /// — the cross-database read path (C3/C4). Reads through that database's own
    /// backend, so its page numbers resolve correctly.
    fn scan_db_table(
        &self,
        db: DbRef,
        name: &str,
        alias: Option<&str>,
    ) -> Result<(Vec<ColumnInfo>, Vec<InputRow>)> {
        let (schema, backend) = self.db_parts(db);
        let meta = self.table_meta_in(schema, name, alias)?;
        let source = backend.source();
        let encoding = source.header().text_encoding;
        // WITHOUT ROWID: walk the clustered index b-tree (records stored
        // PK-first) and decode each entry back into declared column order.
        if meta.without_rowid {
            let params = Params::default();
            let mut rows = Vec::new();
            let mut cur = IndexCursor::new(source, meta.root);
            while let Some(payload) = cur.next()? {
                let storage = decode_record(&payload, encoding)?;
                let mut values = unpermute_row(&meta, storage);
                self.compute_generated(&meta, &mut values, &params)?;
                rows.push(InputRow {
                    values,
                    rowid: None,
                });
            }
            return Ok((meta.columns, rows));
        }
        let mut rows = Vec::new();
        let mut cur = TableCursor::new(source, meta.root);
        let mut ok = cur.first()?;
        while ok {
            let rowid = cur.rowid()?;
            let values = self.decode_full_row(&meta, rowid, &cur.payload()?, encoding)?;
            rows.push(InputRow {
                values,
                rowid: Some(rowid),
            });
            ok = cur.next()?;
        }
        Ok((meta.columns, rows))
    }

    /// Read a view from a non-main database: run its body with unqualified
    /// table names resolving in that database (via `read_default`, restored
    /// afterwards). Returns `None` when `name` is not a view in `db`, so the
    /// caller can fall back to reading it as a table.
    fn scan_db_view(
        &self,
        db: DbRef,
        name: &str,
        alias: Option<&str>,
        params: &Params,
    ) -> Result<Option<(Vec<ColumnInfo>, Vec<InputRow>)>> {
        use crate::schema::ObjectType;
        let (schema, _) = self.db_parts(db);
        let obj = match schema
            .objects()
            .iter()
            .find(|o| o.obj_type == ObjectType::View && o.name.eq_ignore_ascii_case(name))
        {
            Some(o) => o.clone(),
            None => return Ok(None),
        };
        let sql = obj
            .sql
            .as_deref()
            .ok_or_else(|| Error::Corrupt("view has no CREATE statement".into()))?;
        let Statement::CreateView(cv) = sql::parse_one(sql)? else {
            return Err(Error::Corrupt("schema sql is not CREATE VIEW".into()));
        };
        // Resolve the view body's unqualified names in `db`; restore on the way
        // out (even on error) so an outer query's resolution is unaffected.
        let prev = self.read_default.get();
        self.read_default.set(db);
        let run = self.run_select(&cv.select, params);
        self.read_default.set(prev);
        let result = run?;
        let label = alias.unwrap_or(name).to_string();
        let names = if cv.columns.is_empty() {
            result.columns.clone()
        } else {
            cv.columns.clone()
        };
        // NOTE: a temp/attached view column's affinity/collation still defaults to
        // BLOB/BINARY — `subquery_column_origins` resolves base columns through the
        // main schema only, so it cannot see a temp/attached base table. The
        // common main-database case is handled in `try_view`.
        let columns: Vec<ColumnInfo> = names
            .into_iter()
            .map(|n| ColumnInfo {
                name: n,
                table: label.clone(),
                affinity: eval::Affinity::Blob,
                collation: crate::value::Collation::default(),
            })
            .collect();
        let rows = result
            .rows
            .into_iter()
            .map(|values| InputRow {
                values,
                rowid: None,
            })
            .collect();
        Ok(Some((columns, rows)))
    }

    /// The `dbstat` eponymous read-only virtual table: one row per b-tree page
    /// (plus one per overflow page), reporting SQLite-compatible per-page storage
    /// statistics (`name, path, pageno, pagetype, ncell, payload, unused,
    /// mx_payload, pgoffset, pgsize`). Byte-compatible with SQLite's dbstat
    /// extension: `unused` is derived from the page header's free-space pointer,
    /// fragmented-bytes count, and freeblock chain; `payload` sums the locally
    /// stored cell bytes; `mx_payload` is the largest total cell payload. The
    /// `path` strings use SQLite's `/<hex-child>/` and `+<hex-overflow>` format.
    /// The `sqlite_dbpage` read-only virtual table: one row per database page,
    /// `(pgno INTEGER, data BLOB)`, where `data` is the page's raw bytes (page 1
    /// includes the 100-byte file header). Read access only (sqlite's `dbpage` is
    /// also writable; that is `dbpage-2`). `src` is the page source of the target
    /// database (`main`, an attached, or `temp`).
    fn scan_dbpage(
        &self,
        src: &dyn PageSource,
        alias: Option<&str>,
    ) -> Result<(Vec<ColumnInfo>, Vec<InputRow>)> {
        use eval::Affinity::{Blob, Integer};
        let label = alias.unwrap_or("sqlite_dbpage").to_string();
        let col = |name: &str, affinity| ColumnInfo {
            name: String::from(name),
            table: label.clone(),
            affinity,
            collation: crate::value::Collation::default(),
        };
        let columns = alloc::vec![col("pgno", Integer), col("data", Blob)];
        let count = src.page_count();
        let mut rows: Vec<InputRow> = Vec::with_capacity(count as usize);
        for pgno in 1..=count {
            let page = src.page(pgno)?;
            rows.push(InputRow {
                values: alloc::vec![
                    Value::Integer(pgno as i64),
                    Value::Blob(page.data().to_vec()),
                ],
                rowid: Some(pgno as i64),
            });
        }
        Ok((columns, rows))
    }

    fn scan_dbstat(
        &self,
        schema: &Schema,
        src: &dyn PageSource,
        alias: Option<&str>,
    ) -> Result<(Vec<ColumnInfo>, Vec<InputRow>)> {
        use crate::btree::page::{BtreePage, PageType};
        use eval::Affinity::{Integer, Text};

        let label = alias.unwrap_or("dbstat").to_string();
        let col = |name: &str, affinity| ColumnInfo {
            name: String::from(name),
            table: label.clone(),
            affinity,
            collation: crate::value::Collation::default(),
        };
        let columns = alloc::vec![
            col("name", Text),
            col("path", Text),
            col("pageno", Integer),
            col("pagetype", Text),
            col("ncell", Integer),
            col("payload", Integer),
            col("unused", Integer),
            col("mx_payload", Integer),
            col("pgoffset", Integer),
            col("pgsize", Integer),
        ];

        let usable = src.usable_size();
        let page_size = src.header().page_size as i64;
        let be16 = |d: &[u8], off: usize| u16::from_be_bytes([d[off], d[off + 1]]) as usize;

        // The b-trees to walk: `sqlite_schema` (page 1) first, then every object
        // that owns a root page (tables and indexes), in catalog order.
        let mut btrees: Vec<(String, u32)> = alloc::vec![(String::from("sqlite_schema"), 1)];
        for obj in schema.objects() {
            if obj.rootpage != 0 {
                btrees.push((obj.name.clone(), obj.rootpage));
            }
        }

        let mut rows: Vec<InputRow> = Vec::new();
        for (name, root) in btrees {
            // Pre-order DFS; child order does not affect per-page stats.
            let mut stack = alloc::vec![(root, String::from("/"))];
            while let Some((pgno, path)) = stack.pop() {
                let page = src.page(pgno)?;
                let bp = BtreePage::parse(page)?;
                let data = bp.data();
                let body = if pgno == 1 { 100 } else { 0 };
                let ncell = bp.num_cells();
                let is_leaf = bp.page_type().is_leaf();
                let nhdr = body + if is_leaf { 8 } else { 12 };
                let ptype = if is_leaf { "leaf" } else { "internal" };

                let mut payload = 0i64;
                let mut mx = 0i64;
                // SQLite's dbstat reports an overflow page's `pgoffset` as the
                // offset of the *previously visited* page (the owning leaf for a
                // chain's first page, the prior chain page after) — an off-by-one
                // in its statSizeAndOffset. `prev_pgno` reproduces that lag; it
                // starts at the leaf and carries across this page's cells.
                let mut prev_pgno = pgno;
                // Sum local payload and emit overflow-page rows.
                for i in 0..ncell {
                    let pl = match bp.page_type() {
                        PageType::LeafTable => bp.table_leaf_cell(i, usable)?.payload,
                        PageType::LeafIndex | PageType::InteriorIndex => {
                            bp.index_cell(i, usable)?.payload
                        }
                        // Interior-table cells carry no payload.
                        PageType::InteriorTable => continue,
                    };
                    payload += pl.local_len as i64;
                    mx = mx.max(pl.total_len as i64);

                    // Walk this cell's overflow chain, one row per overflow page.
                    let mut ovfl = pl.overflow;
                    let mut remaining = pl.total_len - pl.local_len;
                    let mut iovfl = 0usize;
                    while ovfl != 0 {
                        let opage = src.page(ovfl)?;
                        let odata = opage.data();
                        let next = u32::from_be_bytes([odata[0], odata[1], odata[2], odata[3]]);
                        let cap = usable - 4;
                        let (opayload, ounused) = if remaining <= cap {
                            (remaining as i64, (cap - remaining) as i64)
                        } else {
                            (cap as i64, 0)
                        };
                        rows.push(InputRow {
                            values: alloc::vec![
                                Value::Text(name.clone()),
                                Value::Text(alloc::format!("{path}{i:03x}+{iovfl:06x}")),
                                Value::Integer(ovfl as i64),
                                Value::Text(String::from("overflow")),
                                Value::Integer(0),
                                Value::Integer(opayload),
                                Value::Integer(ounused),
                                Value::Integer(0),
                                Value::Integer((prev_pgno as i64 - 1) * page_size),
                                Value::Integer(page_size),
                            ],
                            rowid: None,
                        });
                        remaining = remaining.saturating_sub(cap);
                        iovfl += 1;
                        prev_pgno = ovfl;
                        ovfl = next;
                    }
                }

                // Free space: (cell-content-area-start - header - cell-pointer
                // array) + fragmented free bytes + the freeblock chain.
                let cc = match be16(data, body + 5) {
                    0 => 65536,
                    n => n,
                };
                let mut unused = cc as i64 - nhdr as i64 - 2 * ncell as i64 + data[body + 7] as i64;
                let mut fb = be16(data, body + 1);
                while fb != 0 && fb + 4 <= data.len() {
                    unused += be16(data, fb + 2) as i64;
                    fb = be16(data, fb);
                }

                rows.push(InputRow {
                    values: alloc::vec![
                        Value::Text(name.clone()),
                        Value::Text(path.clone()),
                        Value::Integer(pgno as i64),
                        Value::Text(String::from(ptype)),
                        Value::Integer(ncell as i64),
                        Value::Integer(payload),
                        Value::Integer(unused),
                        Value::Integer(mx),
                        Value::Integer((pgno as i64 - 1) * page_size),
                        Value::Integer(page_size),
                    ],
                    rowid: None,
                });

                // Descend into children of an interior page.
                if !is_leaf {
                    for i in 0..=ncell {
                        let child = bp.child_pointer(i)?;
                        if child != 0 {
                            stack.push((child, alloc::format!("{path}{i:03x}/")));
                        }
                    }
                }
            }
        }

        Ok((columns, rows))
    }

    /// The `fts5vocab` virtual table: a read-only view over another FTS5 table's
    /// vocabulary. `args` is the `USING fts5vocab(...)` list; `vocab_name`/`alias`
    /// label the result. Tokenizes the referenced table's documents (with the
    /// same `fts5_tokenize` used for indexing) and aggregates per the requested
    /// form — `row` (term, doc, cnt), `col` (term, col, doc, cnt), or `instance`
    /// (term, doc, col, offset) — byte-compatible with SQLite's fts5vocab.
    #[cfg(feature = "fts5")]
    fn scan_fts5vocab(
        &self,
        args: &[String],
        vocab_name: &str,
        alias: Option<&str>,
    ) -> Result<(Vec<ColumnInfo>, Vec<InputRow>)> {
        use alloc::collections::{BTreeMap, BTreeSet};

        let arg_refs: Vec<&str> = args.iter().map(String::as_str).collect();
        let (ft_name, form) = crate::vtab::fts5vocab_args(&arg_refs)?;

        let label = alias.unwrap_or(vocab_name).to_string();
        let colnames: &[&str] = match form.as_str() {
            "row" => &["term", "doc", "cnt"],
            "col" => &["term", "col", "doc", "cnt"],
            _ => &["term", "doc", "col", "offset"],
        };
        let columns: Vec<ColumnInfo> = colnames
            .iter()
            .map(|n| ColumnInfo {
                name: String::from(*n),
                table: label.clone(),
                affinity: eval::Affinity::Blob,
                collation: crate::value::Collation::default(),
            })
            .collect();

        // The referenced FTS5 table: its column names + documents (the persistent
        // `<ft>_data` backing table holds one row per document, column-ordered).
        let (ft_module, ft_args, ft_schema) = self.vtab_meta(&ft_name)?;
        if !ft_module.eq_ignore_ascii_case("fts5") {
            return Err(Error::Error(format!("no such fts5 table: {ft_name}")));
        }
        let ft_cols = ft_schema.columns;
        // Tokenize with the referenced table's own tokenizer (porter / diacritics).
        let ft_refs: Vec<&str> = ft_args.iter().map(String::as_str).collect();
        let ft_tok = crate::vtab::fts5_tok_config(&ft_refs);
        // Documents live in `<ft>_content` (sqlite's layout): `(id, c0, c1, …)`.
        // Drop the leading `id` so `vals` is the column-ordered document.
        let bmeta = self.table_meta(&format!("{ft_name}_content"), None)?;
        let docs: Vec<(i64, Vec<Value>)> = self
            .scan_table(&bmeta)?
            .into_iter()
            .map(|(rowid, mut vals)| {
                if !vals.is_empty() {
                    vals.remove(0);
                }
                (rowid, vals)
            })
            .collect();

        // FTS5 columns store text; coerce other stored types the way SQLite does
        // (NULL/blob contribute no tokens).
        let to_text = |v: &Value| -> Option<String> {
            match v {
                Value::Text(s) => Some(s.clone()),
                Value::Integer(i) => Some(i.to_string()),
                Value::Real(r) => Some(eval::format_real(*r)),
                Value::Null | Value::Blob(_) => None,
            }
        };

        let mut rows: Vec<InputRow> = Vec::new();
        match form.as_str() {
            "row" => {
                // term → (distinct documents, total occurrences)
                let mut map: BTreeMap<String, (BTreeSet<i64>, i64)> = BTreeMap::new();
                for (rowid, vals) in &docs {
                    for v in vals.iter().take(ft_cols.len()) {
                        if let Some(t) = to_text(v) {
                            for tok in crate::vtab::fts5_tokenize(&t, ft_tok) {
                                let e = map.entry(tok).or_default();
                                e.0.insert(*rowid);
                                e.1 += 1;
                            }
                        }
                    }
                }
                for (term, (ds, cnt)) in map {
                    rows.push(InputRow {
                        values: alloc::vec![
                            Value::Text(term),
                            Value::Integer(ds.len() as i64),
                            Value::Integer(cnt),
                        ],
                        rowid: None,
                    });
                }
            }
            "col" => {
                // (term, column index) → (distinct documents, total occurrences)
                let mut map: BTreeMap<(String, usize), (BTreeSet<i64>, i64)> = BTreeMap::new();
                for (rowid, vals) in &docs {
                    for (ci, v) in vals.iter().take(ft_cols.len()).enumerate() {
                        if let Some(t) = to_text(v) {
                            for tok in crate::vtab::fts5_tokenize(&t, ft_tok) {
                                let e = map.entry((tok, ci)).or_default();
                                e.0.insert(*rowid);
                                e.1 += 1;
                            }
                        }
                    }
                }
                for ((term, ci), (ds, cnt)) in map {
                    rows.push(InputRow {
                        values: alloc::vec![
                            Value::Text(term),
                            Value::Text(ft_cols[ci].clone()),
                            Value::Integer(ds.len() as i64),
                            Value::Integer(cnt),
                        ],
                        rowid: None,
                    });
                }
            }
            _ => {
                // instance: one row per token occurrence (term, doc, col, offset),
                // offset being the 0-based token position within that column.
                let mut insts: Vec<(String, i64, usize, i64)> = Vec::new();
                for (rowid, vals) in &docs {
                    for (ci, v) in vals.iter().take(ft_cols.len()).enumerate() {
                        if let Some(t) = to_text(v) {
                            for (off, tok) in crate::vtab::fts5_tokenize(&t, ft_tok)
                                .into_iter()
                                .enumerate()
                            {
                                insts.push((tok, *rowid, ci, off as i64));
                            }
                        }
                    }
                }
                insts.sort();
                for (term, rowid, ci, off) in insts {
                    rows.push(InputRow {
                        values: alloc::vec![
                            Value::Text(term),
                            Value::Integer(rowid),
                            Value::Text(ft_cols[ci].clone()),
                            Value::Integer(off),
                        ],
                        rowid: None,
                    });
                }
            }
        }
        Ok((columns, rows))
    }

    /// Read a SQLite-format R-Tree's entries by walking its `<name>_node` b-tree
    /// of nodes. Each node blob is a 2-byte BE depth (meaningful in the root) +
    /// 2-byte BE cell count, then cells of an 8-byte BE rowid (leaf) / child
    /// node-number (interior) followed by `n_coords` 4-byte BE coordinates (f32
    /// for `rtree`, i32 for `rtree_i32`). Yields one `InputRow` per leaf entry:
    /// `[id, coord0, …]`. The traversal collects a superset; `run_core` re-applies
    /// the full WHERE.
    fn scan_rtree_nodes(
        &self,
        name: &str,
        n_coords: usize,
        integer: bool,
        bbox: &[(usize, ConstraintOp, f64)],
    ) -> Result<Vec<InputRow>> {
        use alloc::collections::BTreeMap;
        let node_meta = self.table_meta(&format!("{name}_node"), None)?;
        let mut nodes: BTreeMap<i64, Vec<u8>> = BTreeMap::new();
        for (nodeno, vals) in self.scan_table(&node_meta)? {
            // `<name>_node` is `(nodeno INTEGER PRIMARY KEY, data)`; the blob is
            // the `data` column (the first value is the rowid/nodeno itself).
            if let Some(Value::Blob(b)) = vals.into_iter().find(|v| matches!(v, Value::Blob(_))) {
                nodes.insert(nodeno, b);
            }
        }
        let cell_size = 8 + n_coords * 4;
        // Read coordinate `j` (0-based) of the cell whose 8-byte key starts at `off`.
        let coord_at = |blob: &[u8], off: usize, j: usize| -> f64 {
            let p = off + 8 + j * 4;
            let b: [u8; 4] = blob[p..p + 4].try_into().expect("4 bytes");
            if integer {
                f64::from(i32::from_be_bytes(b))
            } else {
                f64::from(f32::from_be_bytes(b))
            }
        };
        // Spatial pushdown: a subtree's stored cell is the MBR of its entries —
        // `[lo, hi]` per dimension — so a constraint on either coordinate column of
        // dimension `d` can be satisfied by some entry only if the MBR overlaps it.
        // The on-disk MBR is a superset (f32 rounds min down / max up), so this
        // prune never drops a matching entry; `run_core` re-applies the full WHERE,
        // making the visited rows a correct superset. Constraints whose dimension
        // can't possibly be satisfied prune the whole subtree.
        let subtree_matches = |blob: &[u8], off: usize| -> bool {
            bbox.iter().all(|&(ci, op, v)| {
                let d = ci / 2;
                let lo = coord_at(blob, off, 2 * d);
                let hi = coord_at(blob, off, 2 * d + 1);
                match op {
                    ConstraintOp::Ge => hi >= v,
                    ConstraintOp::Gt => hi > v,
                    ConstraintOp::Le => lo <= v,
                    ConstraintOp::Lt => lo < v,
                    ConstraintOp::Eq => lo <= v && v <= hi,
                    _ => true,
                }
            })
        };
        let mut out = Vec::new();
        let Some(root) = nodes.get(&1) else {
            return Ok(out);
        };
        if root.len() < 4 {
            return Ok(out);
        }
        // The root header's depth field is the tree height; descend that many
        // levels to reach the leaves.
        let depth = i64::from(u16::from_be_bytes([root[0], root[1]]));
        let mut stack: Vec<(i64, i64)> = alloc::vec![(1, depth)];
        while let Some((nodeno, level)) = stack.pop() {
            let Some(blob) = nodes.get(&nodeno) else {
                continue;
            };
            if blob.len() < 4 {
                continue;
            }
            let ncell = u16::from_be_bytes([blob[2], blob[3]]) as usize;
            for i in 0..ncell {
                let off = 4 + i * cell_size;
                if off + cell_size > blob.len() {
                    break;
                }
                let key = i64::from_be_bytes(blob[off..off + 8].try_into().expect("8 bytes"));
                if level > 0 {
                    // Interior cell: the 8-byte field is a child node number. Skip
                    // the whole subtree when its MBR can't satisfy the constraints.
                    if !bbox.is_empty() && !subtree_matches(blob, off) {
                        continue;
                    }
                    stack.push((key, level - 1));
                    continue;
                }
                // Leaf cell: the 8-byte field is the entry's rowid.
                let mut row = Vec::with_capacity(1 + n_coords);
                row.push(Value::Integer(key));
                for c in 0..n_coords {
                    let p = off + 8 + c * 4;
                    let b: [u8; 4] = blob[p..p + 4].try_into().expect("4 bytes");
                    row.push(if integer {
                        Value::Integer(i64::from(i32::from_be_bytes(b)))
                    } else {
                        Value::Real(f64::from(f32::from_be_bytes(b)))
                    });
                }
                out.push(InputRow {
                    values: row,
                    rowid: Some(key),
                });
            }
        }
        Ok(out)
    }

    /// The fixed R-Tree node size for this database's page size.
    fn rtree_node_size_for(&self, n_coord: usize) -> usize {
        rtree_node_size(n_coord, self.backend.source().header().page_size as usize)
    }

    /// The current entries of an R-Tree as `(rowid, coords)` cells (via the M1
    /// node reader; coords come back as the stored f32/i32 values widened to f64).
    fn rtree_entries(&self, name: &str, n_coord: usize, integer: bool) -> Result<Vec<RtreeCell>> {
        Ok(self
            .scan_rtree_nodes(name, n_coord, integer, &[])?
            .into_iter()
            .map(|r| {
                let key = match r.values.first() {
                    Some(Value::Integer(i)) => *i,
                    _ => 0,
                };
                let coords = r.values[1..1 + n_coord]
                    .iter()
                    .map(|v| match v {
                        Value::Integer(i) => *i as f64,
                        Value::Real(f) => *f,
                        _ => 0.0,
                    })
                    .collect();
                RtreeCell { key, coords }
            })
            .collect())
    }

    /// Replace an R-Tree's three shadow tables with a freshly bulk-built tree.
    fn rtree_write_build(&mut self, name: &str, build: &RtreeBuild) -> Result<()> {
        let node_t = sql::print::ident(&format!("{name}_node"));
        let rowid_t = sql::print::ident(&format!("{name}_rowid"));
        let parent_t = sql::print::ident(&format!("{name}_parent"));
        let pv = |vals: Vec<Value>| Params {
            positional: vals,
            named: Vec::new(),
        };
        self.execute(&format!("DELETE FROM {node_t}"))?;
        self.execute(&format!("DELETE FROM {rowid_t}"))?;
        self.execute(&format!("DELETE FROM {parent_t}"))?;
        for (nodeno, blob) in &build.nodes {
            self.execute_params(
                &format!("INSERT INTO {node_t} VALUES(?1,?2)"),
                &pv(alloc::vec![
                    Value::Integer(*nodeno),
                    Value::Blob(blob.clone())
                ]),
            )?;
        }
        for (rowid, nodeno) in &build.rowids {
            self.execute_params(
                &format!("INSERT INTO {rowid_t} VALUES(?1,?2)"),
                &pv(alloc::vec![Value::Integer(*rowid), Value::Integer(*nodeno)]),
            )?;
        }
        for (child, parent) in &build.parents {
            self.execute_params(
                &format!("INSERT INTO {parent_t} VALUES(?1,?2)"),
                &pv(alloc::vec![Value::Integer(*child), Value::Integer(*parent)]),
            )?;
        }
        Ok(())
    }

    /// Create an R-Tree's storage: the `_node`/`_rowid`/`_parent` shadow tables
    /// (byte-compatible with SQLite) plus an empty root node.
    fn rtree_create_storage(&mut self, name: &str, n_coord: usize, integer: bool) -> Result<()> {
        for (suffix, cols) in [
            ("_node", "nodeno INTEGER PRIMARY KEY, data"),
            ("_rowid", "rowid INTEGER PRIMARY KEY, nodeno"),
            ("_parent", "nodeno INTEGER PRIMARY KEY, parentnode"),
        ] {
            let sql = format!(
                "CREATE TABLE {}({cols})",
                sql::print::ident(&format!("{name}{suffix}"))
            );
            let Statement::CreateTable(ct) = sql::parse_one(&sql)? else {
                unreachable!("constructed a CREATE TABLE")
            };
            self.exec_create_table(&ct, &sql)?;
        }
        let build = rtree_bulk_build(
            Vec::new(),
            n_coord,
            integer,
            self.rtree_node_size_for(n_coord),
        );
        self.rtree_write_build(name, &build)
    }

    /// Apply inserts and/or a delete to an R-Tree by rebuilding its node tree
    /// (read all entries, apply, bulk-build, rewrite). `inserts` carry coords
    /// already rounded to the conservative f32/i32 form.
    fn rtree_apply(
        &mut self,
        name: &str,
        n_coord: usize,
        integer: bool,
        inserts: Vec<RtreeCell>,
        deletes: &[i64],
    ) -> Result<()> {
        let mut entries = self.rtree_entries(name, n_coord, integer)?;
        let removed: alloc::collections::BTreeSet<i64> = deletes
            .iter()
            .copied()
            .chain(inserts.iter().map(|c| c.key))
            .collect();
        entries.retain(|c| !removed.contains(&c.key));
        entries.extend(inserts);
        let build = rtree_bulk_build(entries, n_coord, integer, self.rtree_node_size_for(n_coord));
        self.rtree_write_build(name, &build)
    }

    /// After a write to an FTS5 table, rebuild its inverted index from the
    /// updated `<name>_content` documents. A no-op for every other module.
    fn fts5_maybe_rebuild(&mut self, module_name: &str, table: &str) -> Result<()> {
        #[cfg(feature = "fts5")]
        if module_name.eq_ignore_ascii_case("fts5") {
            return self.fts5_rebuild_index(table);
        }
        let _ = (module_name, table);
        Ok(())
    }

    /// Create an FTS5 table's storage: SQLite's five shadow tables
    /// (`_content`/`_docsize`/`_config`/`_idx`/`_data`) instead of graphite's
    /// generic `<name>_data` store, so a graphite-written FTS5 table is readable
    /// (and `MATCH`-able) by stock sqlite. `_content` holds the documents (same
    /// `(id, c0, c1, …)` shape graphite already reads); the inverted index in
    /// `_data`/`_idx` is rebuilt from `_content` on every write.
    #[cfg(feature = "fts5")]
    fn fts5_create_storage(&mut self, name: &str, ncols: usize) -> Result<()> {
        let content_cols: Vec<String> = (0..ncols).map(|c| format!("c{c}")).collect();
        let q = |s: &str| sql::print::ident(s);
        let defs = [
            (
                format!("{name}_content"),
                format!("id INTEGER PRIMARY KEY, {}", content_cols.join(", ")),
                "",
            ),
            (
                format!("{name}_docsize"),
                "id INTEGER PRIMARY KEY, sz BLOB".to_string(),
                "",
            ),
            (
                format!("{name}_config"),
                "k PRIMARY KEY, v".to_string(),
                " WITHOUT ROWID",
            ),
            (
                format!("{name}_idx"),
                "segid, term, pgno, PRIMARY KEY(segid, term)".to_string(),
                " WITHOUT ROWID",
            ),
            (
                format!("{name}_data"),
                "id INTEGER PRIMARY KEY, block BLOB".to_string(),
                "",
            ),
        ];
        for (tname, cols, tail) in &defs {
            let sql = format!("CREATE TABLE {}({cols}){tail}", q(tname));
            let Statement::CreateTable(ct) = sql::parse_one(&sql)? else {
                unreachable!("constructed a CREATE TABLE")
            };
            self.exec_create_table(&ct, &sql)?;
        }
        // The configuration version row, then the empty segment index. The vtab's
        // own schema row is not inserted yet, so write the initial `_data` rows
        // directly (the index is rebuilt from `_content` on the first write).
        self.execute_params(
            &format!(
                "INSERT INTO {} VALUES('version', 4)",
                q(&format!("{name}_config"))
            ),
            &Params::default(),
        )?;
        let seg = crate::fts5_index::build_segment(&[], 0, &alloc::vec![0u64; ncols], &[], 4050, 0);
        let data_t = q(&format!("{name}_data"));
        for (id, block) in &seg.data {
            self.execute_params(
                &format!("INSERT INTO {data_t} VALUES(?1,?2)"),
                &Params {
                    positional: alloc::vec![Value::Integer(*id), Value::Blob(block.clone())],
                    named: Vec::new(),
                },
            )?;
        }
        Ok(())
    }

    /// Rebuild an FTS5 table's `%_data`/`%_idx`/`%_docsize` from the documents in
    /// `<name>_content` (a bulk rebuild, like the R-Tree). Tokenizes each column
    /// with the table's tokenizer and writes a byte-compatible segment index.
    #[cfg(feature = "fts5")]
    fn fts5_rebuild_index(&mut self, name: &str) -> Result<()> {
        use crate::fts5_index::{self, IdxRow, Posting};
        use alloc::collections::BTreeMap;
        let (_module, args, schema) = self.vtab_meta(name)?;
        let ncols = schema.columns.len();
        let arg_refs: Vec<&str> = args.iter().map(String::as_str).collect();
        let tok = crate::vtab::fts5_tok_config(&arg_refs);

        let cmeta = self.table_meta(&format!("{name}_content"), None)?;
        let docs = self.scan_table(&cmeta)?;

        // term bytes -> rowid -> per-column positions
        let mut index: BTreeMap<Vec<u8>, BTreeMap<i64, Vec<Vec<u32>>>> = BTreeMap::new();
        let mut col_totals = alloc::vec![0u64; ncols];
        let mut doc_sizes: Vec<(i64, Vec<u64>)> = Vec::new();
        for (rowid, values) in &docs {
            let mut sizes = alloc::vec![0u64; ncols];
            for c in 0..ncols {
                let text = match values.get(c + 1) {
                    Some(v) if !matches!(v, Value::Null) => eval::to_text(v),
                    _ => String::new(),
                };
                let toks = crate::vtab::fts5_tokenize(&text, tok);
                sizes[c] = toks.len() as u64;
                col_totals[c] += toks.len() as u64;
                for (pos, tok) in toks.iter().enumerate() {
                    index
                        .entry(tok.as_bytes().to_vec())
                        .or_default()
                        .entry(*rowid)
                        .or_insert_with(|| alloc::vec![Vec::new(); ncols])[c]
                        .push(pos as u32);
                }
            }
            doc_sizes.push((*rowid, sizes));
        }
        let terms: Vec<(Vec<u8>, Vec<Posting>)> = index
            .into_iter()
            .map(|(term, per_doc)| {
                let postings = per_doc
                    .into_iter()
                    .map(|(rowid, cols)| Posting { rowid, cols })
                    .collect();
                (term, postings)
            })
            .collect();

        let seg =
            fts5_index::build_segment(&terms, docs.len() as u64, &col_totals, &doc_sizes, 4050, 0);

        let q = |s: &str| sql::print::ident(s);
        let pv = |vals: Vec<Value>| Params {
            positional: vals,
            named: Vec::new(),
        };
        self.execute(&format!("DELETE FROM {}", q(&format!("{name}_data"))))?;
        self.execute(&format!("DELETE FROM {}", q(&format!("{name}_idx"))))?;
        self.execute(&format!("DELETE FROM {}", q(&format!("{name}_docsize"))))?;
        let data_t = q(&format!("{name}_data"));
        for (id, block) in &seg.data {
            self.execute_params(
                &format!("INSERT INTO {data_t} VALUES(?1,?2)"),
                &pv(alloc::vec![Value::Integer(*id), Value::Blob(block.clone())]),
            )?;
        }
        let idx_t = q(&format!("{name}_idx"));
        for IdxRow { segid, term, pgno } in &seg.idx {
            self.execute_params(
                &format!("INSERT INTO {idx_t} VALUES(?1,?2,?3)"),
                &pv(alloc::vec![
                    Value::Integer(*segid),
                    Value::Blob(term.clone()),
                    Value::Integer(*pgno)
                ]),
            )?;
        }
        let docsize_t = q(&format!("{name}_docsize"));
        for (rowid, sz) in &seg.docsize {
            self.execute_params(
                &format!("INSERT INTO {docsize_t} VALUES(?1,?2)"),
                &pv(alloc::vec![Value::Integer(*rowid), Value::Blob(sz.clone())]),
            )?;
        }
        Ok(())
    }

    fn scan_table(&self, meta: &TableMeta) -> Result<Vec<(i64, Vec<Value>)>> {
        let encoding = self.backend.source().header().text_encoding;
        let mut rows = Vec::new();
        let mut cur = TableCursor::new(self.backend.source(), meta.root);
        let mut ok = cur.first()?;
        while ok {
            let rowid = cur.rowid()?;
            let values = self.decode_full_row(meta, rowid, &cur.payload()?, encoding)?;
            rows.push((rowid, values));
            ok = cur.next()?;
        }
        Ok(rows)
    }

    /// Decode a stored row into full column values: pad missing trailing columns
    /// with their `DEFAULT` (or NULL), and fill the INTEGER PRIMARY KEY column
    /// from the rowid. This is how `ALTER TABLE ADD COLUMN` defaults show up for
    /// rows written before the column existed.
    fn decode_full_row(
        &self,
        meta: &TableMeta,
        rowid: i64,
        payload: &[u8],
        encoding: crate::format::TextEncoding,
    ) -> Result<Vec<Value>> {
        let record = decode_record(payload, encoding)?;
        let n = meta.columns.len();
        let mut values = alloc::vec![Value::Null; n];
        let p = Params::default();
        // Map stored record values onto declared columns, skipping VIRTUAL
        // generated columns (which occupy no record slot). A record shorter than
        // the stored-column count means columns added by ALTER use their default.
        let mut ri = 0usize;
        for (i, def) in meta.defaults.iter().enumerate() {
            if meta.is_virtual(i) {
                continue;
            }
            if ri < record.len() {
                values[i] = record[ri].clone();
            } else if let Some(e) = def {
                values[i] = eval::eval(e, &EvalCtx::rowless(&p))?;
            }
            ri += 1;
        }
        if let Some(ipk) = meta.ipk {
            values[ipk] = Value::Integer(rowid);
        }
        self.compute_generated(meta, &mut values, &p)?;
        Ok(values)
    }

    /// Fill in the VIRTUAL generated columns of `values` (computed on read).
    /// STORED generated columns are read back from the record, not recomputed.
    fn compute_generated(
        &self,
        meta: &TableMeta,
        values: &mut [Value],
        params: &Params,
    ) -> Result<()> {
        if meta.generated.iter().all(|g| g.is_none()) {
            return Ok(());
        }
        for i in 0..meta.columns.len() {
            if let Some((expr, stored)) = &meta.generated[i] {
                if !stored {
                    let ctx = row_ctx(values, &meta.columns, None, params).with_subqueries(self);
                    let v = eval::eval(expr, &ctx)?;
                    values[i] = meta.columns[i].affinity.coerce(v);
                }
            }
        }
        Ok(())
    }

    /// Materialize all generated columns (STORED and VIRTUAL) into `values`,
    /// applied on the write path so CHECK/UNIQUE/indexes see their values.
    fn materialize_generated(
        &self,
        meta: &TableMeta,
        values: &mut [Value],
        params: &Params,
    ) -> Result<()> {
        if meta.generated.iter().all(|g| g.is_none()) {
            return Ok(());
        }
        for i in 0..meta.columns.len() {
            if let Some((expr, _)) = &meta.generated[i] {
                let ctx = row_ctx(values, &meta.columns, None, params).with_subqueries(self);
                let v = eval::eval(expr, &ctx)?;
                values[i] = meta.columns[i].affinity.coerce(v);
            }
        }
        Ok(())
    }

    /// Encode a table record from `values`, omitting VIRTUAL generated columns
    /// (not stored) and nulling the rowid-aliased `INTEGER PRIMARY KEY`.
    fn encode_table_record(&self, meta: &TableMeta, values: &[Value]) -> Vec<u8> {
        let stored: Vec<Value> = (0..meta.columns.len())
            .filter(|&i| !meta.is_virtual(i))
            .map(|i| {
                if Some(i) == meta.ipk {
                    Value::Null
                } else {
                    values[i].clone()
                }
            })
            .collect();
        encode_record(&stored)
    }

    /// Non-aggregated projection: one output row per input row.
    fn eval_simple(
        &self,
        sel: &Select,
        columns: &[ColumnInfo],
        rows: Vec<InputRow>,
        params: &Params,
    ) -> Result<(Vec<String>, Vec<OutRow>)> {
        let labels = self.output_labels(sel, columns);
        let mut out = Vec::with_capacity(rows.len());
        for r in &rows {
            let ctx = r.ctx(columns, params).with_subqueries(self);
            let mut values = Vec::new();
            for col in &sel.columns {
                project_column(col, columns, &ctx, &mut values)?;
            }
            // ORDER BY: resolve by position/alias against the output, else
            // evaluate against the input row (allows ordering by unselected cols).
            let mut sort_keys = Vec::new();
            for term in &sel.order_by {
                match resolve_order_index(&term.expr, &labels, values.len()) {
                    Some(idx) => sort_keys.push(values[idx].clone()),
                    None => sort_keys.push(eval::eval(&term.expr, &ctx)?),
                }
            }
            out.push(OutRow { values, sort_keys });
        }
        Ok((labels, out))
    }

    /// Aggregated/grouped projection.
    fn eval_aggregated(
        &self,
        sel: &Select,
        columns: &[ColumnInfo],
        rows: Vec<InputRow>,
        params: &Params,
    ) -> Result<(Vec<String>, Vec<OutRow>)> {
        // Expand any `*` / `table.*` into explicit column references so the
        // bare-column rule below applies to them (SQLite allows `SELECT *,
        // count(*) …`, each bare column taking the representative row's value).
        let expanded;
        let sel = if sel
            .columns
            .iter()
            .any(|c| matches!(c, ResultColumn::Wildcard | ResultColumn::TableWildcard(_)))
        {
            expanded = expand_agg_wildcards(sel, columns);
            &expanded
        } else {
            sel
        };

        // Resolve a positional `GROUP BY N` (an integer literal) to the N-th
        // output column's expression, matching sqlite — `GROUP BY 1` groups by
        // the first result column, not by the constant 1. (Range was already
        // validated upstream by `check_positional_terms`.)
        let group_by: Vec<Expr> = sel
            .group_by
            .iter()
            .map(|g| {
                if let Expr::Literal(Literal::Integer(n)) = g {
                    if *n >= 1 {
                        if let Some(ResultColumn::Expr { expr, .. }) =
                            sel.columns.get((*n - 1) as usize)
                        {
                            return expr.clone();
                        }
                    }
                }
                g.clone()
            })
            .collect();

        // Partition rows into groups (first-seen order), comparing each grouping
        // key under its column collation.
        let group_colls: Vec<crate::value::Collation> = {
            let cctx = row_ctx(&[], columns, None, params);
            group_by
                .iter()
                .map(|g| eval::key_collation(g, &cctx))
                .collect()
        };
        let mut group_keys: Vec<Vec<Value>> = Vec::new();
        let mut groups: Vec<Vec<usize>> = Vec::new();
        for (i, r) in rows.iter().enumerate() {
            let ctx = r.ctx(columns, params).with_subqueries(self);
            let mut key = Vec::new();
            for g in &group_by {
                key.push(eval::eval(g, &ctx)?);
            }
            match group_keys
                .iter()
                .position(|k| rows_equal_coll(k, &key, &group_colls))
            {
                Some(idx) => groups[idx].push(i),
                None => {
                    group_keys.push(key);
                    groups.push(alloc::vec![i]);
                }
            }
        }
        // No GROUP BY but aggregates present => a single group over all rows
        // (which yields one row even when there are zero input rows).
        if sel.group_by.is_empty() {
            groups = alloc::vec![(0..rows.len()).collect()];
        } else {
            // SQLite emits grouped rows ordered by the GROUP BY keys (ascending,
            // under each key's collation, NULLs first) — its grouping is done via
            // a sort. An explicit ORDER BY re-sorts later; with none, this is the
            // order. Reorder the groups (and their keys) to match.
            let mut order: Vec<usize> = (0..groups.len()).collect();
            order.sort_by(|&i, &j| {
                for (k, coll) in group_colls.iter().enumerate() {
                    let ord =
                        crate::value::cmp_values_coll(&group_keys[i][k], &group_keys[j][k], *coll);
                    if ord != core::cmp::Ordering::Equal {
                        return ord;
                    }
                }
                core::cmp::Ordering::Equal
            });
            let mut sorted = Vec::with_capacity(groups.len());
            for i in order {
                sorted.push(core::mem::take(&mut groups[i]));
            }
            groups = sorted;
        }

        let labels = self.output_labels(sel, columns);
        // SQLite's bare-column rule: with exactly one min()/max(), bare columns
        // come from the row achieving that extreme (else the group's first row).
        let minmax = single_minmax_arg(sel);
        let mut out = Vec::new();
        for group in &groups {
            // Representative row context for bare column references.
            let repr_idx = match &minmax {
                Some((is_max, arg)) => {
                    self.argextreme_row(group, columns, &rows, arg, *is_max, params)?
                }
                None => group.first().copied(),
            };
            let repr = repr_idx.map(|i| &rows[i]);
            let empty = InputRow {
                values: alloc::vec![Value::Null; columns.len()],
                rowid: None,
            };
            let repr_ctx = repr
                .unwrap_or(&empty)
                .ctx(columns, params)
                .with_subqueries(self);

            // Compute the output row, substituting aggregate calls with values.
            let mut values = Vec::new();
            for col in &sel.columns {
                let ResultColumn::Expr { expr, .. } = col else {
                    unreachable!("wildcards rejected above")
                };
                let substituted =
                    self.substitute_aggregates(expr, columns, &rows, group, params)?;
                values.push(eval::eval(&substituted, &repr_ctx)?);
            }

            // HAVING (aggregate-aware). It may reference SELECT-output aliases, so
            // evaluate against a context that also exposes the output columns by
            // their labels (table columns still take precedence).
            if let Some(having) = &sel.having {
                let h = self.substitute_aggregates(having, columns, &rows, group, params)?;
                let mut aug_cols = columns.to_vec();
                for label in &labels {
                    aug_cols.push(ColumnInfo {
                        name: label.clone(),
                        table: String::new(),
                        affinity: eval::Affinity::Blob,
                        collation: crate::value::Collation::Binary,
                    });
                }
                let mut aug_vals = repr.unwrap_or(&empty).values.clone();
                aug_vals.extend(values.iter().cloned());
                let aug_row = InputRow {
                    values: aug_vals,
                    rowid: repr.and_then(|r| r.rowid),
                };
                let actx = aug_row.ctx(&aug_cols, params).with_subqueries(self);
                if eval::truth(&eval::eval(&h, &actx)?) != Some(true) {
                    continue;
                }
            }

            // Sort keys (aggregate-aware) for ORDER BY.
            let mut sort_keys = Vec::new();
            for term in &sel.order_by {
                if let Some(idx) = resolve_order_index(&term.expr, &labels, values.len()) {
                    sort_keys.push(values[idx].clone());
                } else {
                    let s =
                        self.substitute_aggregates(&term.expr, columns, &rows, group, params)?;
                    sort_keys.push(eval::eval(&s, &repr_ctx)?);
                }
            }
            out.push(OutRow { values, sort_keys });
        }
        Ok((labels, out))
    }

    /// Replace every aggregate call (an aggregate function with no `OVER`) inside
    /// `e` — including ones nested in window-function arguments and in a window's
    /// `PARTITION BY` / `ORDER BY` — with a reference to a synthetic `__aggN`
    /// column, recording each original aggregate expression in `aggs` (its index
    /// = N). The rewritten expression has no aggregates, only window functions and
    /// column references, so it evaluates against the per-group rows that carry the
    /// materialized aggregate values.
    fn extract_aggregates(&self, e: &Expr, aggs: &mut Vec<Expr>) -> Expr {
        let is_agg = matches!(e, Expr::Function { name, args, star, over: None, .. }
            if func::is_aggregate_call(name, args.len(), *star)
                || self.aggregates.contains_key(&name.to_ascii_lowercase()));
        if is_agg {
            let idx = aggs.len();
            aggs.push(e.clone());
            return Expr::Column {
                table: None,
                column: alloc::format!("__agg{idx}"),
            };
        }
        match e {
            Expr::Function {
                name,
                distinct,
                args,
                star,
                filter,
                order_by,
                over,
            } => {
                let new_args = args
                    .iter()
                    .map(|a| self.extract_aggregates(a, aggs))
                    .collect();
                let new_filter = filter
                    .as_ref()
                    .map(|f| Box::new(self.extract_aggregates(f, aggs)));
                // Recurse into the window spec's PARTITION/ORDER expressions, which
                // may themselves contain aggregates (`row_number() OVER (ORDER BY
                // sum(v))`).
                let new_over = over.as_ref().map(|spec| {
                    let mut s = spec.clone();
                    s.partition_by = spec
                        .partition_by
                        .iter()
                        .map(|p| self.extract_aggregates(p, aggs))
                        .collect();
                    s.order_by = spec
                        .order_by
                        .iter()
                        .map(|t| OrderTerm {
                            expr: self.extract_aggregates(&t.expr, aggs),
                            descending: t.descending,
                            nulls_first: t.nulls_first,
                        })
                        .collect();
                    s
                });
                Expr::Function {
                    name: name.clone(),
                    distinct: *distinct,
                    args: new_args,
                    star: *star,
                    filter: new_filter,
                    order_by: order_by.clone(),
                    over: new_over,
                }
            }
            Expr::Binary { op, left, right } => Expr::Binary {
                op: *op,
                left: Box::new(self.extract_aggregates(left, aggs)),
                right: Box::new(self.extract_aggregates(right, aggs)),
            },
            Expr::Unary { op, expr } => Expr::Unary {
                op: *op,
                expr: Box::new(self.extract_aggregates(expr, aggs)),
            },
            Expr::Paren(x) => Expr::Paren(Box::new(self.extract_aggregates(x, aggs))),
            Expr::Cast { expr, type_name } => Expr::Cast {
                expr: Box::new(self.extract_aggregates(expr, aggs)),
                type_name: type_name.clone(),
            },
            Expr::Collate { expr, collation } => Expr::Collate {
                expr: Box::new(self.extract_aggregates(expr, aggs)),
                collation: collation.clone(),
            },
            Expr::IsNull { expr, negated } => Expr::IsNull {
                expr: Box::new(self.extract_aggregates(expr, aggs)),
                negated: *negated,
            },
            Expr::Between {
                expr,
                low,
                high,
                negated,
            } => Expr::Between {
                expr: Box::new(self.extract_aggregates(expr, aggs)),
                low: Box::new(self.extract_aggregates(low, aggs)),
                high: Box::new(self.extract_aggregates(high, aggs)),
                negated: *negated,
            },
            Expr::InList {
                expr,
                list,
                negated,
                candidate_affinity,
            } => Expr::InList {
                expr: Box::new(self.extract_aggregates(expr, aggs)),
                list: list
                    .iter()
                    .map(|x| self.extract_aggregates(x, aggs))
                    .collect(),
                negated: *negated,
                candidate_affinity: candidate_affinity.clone(),
            },
            Expr::Case {
                operand,
                when_then,
                else_result,
            } => Expr::Case {
                operand: operand
                    .as_ref()
                    .map(|o| Box::new(self.extract_aggregates(o, aggs))),
                when_then: when_then
                    .iter()
                    .map(|(w, t)| {
                        (
                            self.extract_aggregates(w, aggs),
                            self.extract_aggregates(t, aggs),
                        )
                    })
                    .collect(),
                else_result: else_result
                    .as_ref()
                    .map(|x| Box::new(self.extract_aggregates(x, aggs))),
            },
            Expr::RowValue(items) => Expr::RowValue(
                items
                    .iter()
                    .map(|x| self.extract_aggregates(x, aggs))
                    .collect(),
            ),
            // Literals, columns, parameters, and subqueries pass through (a
            // subquery's own aggregates belong to that subquery's scope).
            other => other.clone(),
        }
    }

    /// Evaluate a query that combines `GROUP BY`/aggregates with window functions.
    /// SQLite applies window functions *after* grouping — each window operates on
    /// the post-aggregation rows, and an aggregate inside a window argument or
    /// spec is the group's aggregate. We materialize each group into one row
    /// carrying its aggregate values (as `__aggN` columns), rewrite the query to
    /// reference those columns, apply `HAVING`, run the windows over the grouped
    /// rows, then project. Returns `(labels, rows)` like the other eval paths.
    fn eval_windowed_aggregate(
        &self,
        sel: &Select,
        columns: &[ColumnInfo],
        rows: Vec<InputRow>,
        params: &Params,
    ) -> Result<(Vec<String>, Vec<OutRow>)> {
        // `*` over a grouped+windowed query is rare and would need representative-
        // row expansion alongside the synthetic columns; defer it (errors as
        // before) rather than risk a wrong column set.
        if sel
            .columns
            .iter()
            .any(|c| matches!(c, ResultColumn::Wildcard | ResultColumn::TableWildcard(_)))
        {
            return Err(Error::Unsupported(
                "SELECT * with window functions over GROUP BY",
            ));
        }
        // Output labels reflect the ORIGINAL expressions (e.g. the verbatim
        // `sum(sum(v)) OVER ()`), so compute them before any rewrite.
        let labels = self.output_labels(sel, columns);

        // --- Partition rows into groups (mirrors eval_aggregated). ---
        let group_by: Vec<Expr> = sel
            .group_by
            .iter()
            .map(|g| {
                if let Expr::Literal(Literal::Integer(n)) = g {
                    if *n >= 1 {
                        if let Some(ResultColumn::Expr { expr, .. }) =
                            sel.columns.get((*n - 1) as usize)
                        {
                            return expr.clone();
                        }
                    }
                }
                g.clone()
            })
            .collect();
        let group_colls: Vec<crate::value::Collation> = {
            let cctx = row_ctx(&[], columns, None, params);
            group_by
                .iter()
                .map(|g| eval::key_collation(g, &cctx))
                .collect()
        };
        let mut group_keys: Vec<Vec<Value>> = Vec::new();
        let mut groups: Vec<Vec<usize>> = Vec::new();
        for (i, r) in rows.iter().enumerate() {
            let ctx = r.ctx(columns, params).with_subqueries(self);
            let mut key = Vec::new();
            for g in &group_by {
                key.push(eval::eval(g, &ctx)?);
            }
            match group_keys
                .iter()
                .position(|k| rows_equal_coll(k, &key, &group_colls))
            {
                Some(idx) => groups[idx].push(i),
                None => {
                    group_keys.push(key);
                    groups.push(alloc::vec![i]);
                }
            }
        }
        if sel.group_by.is_empty() {
            groups = alloc::vec![(0..rows.len()).collect()];
        } else {
            let mut order: Vec<usize> = (0..groups.len()).collect();
            order.sort_by(|&i, &j| {
                for (k, coll) in group_colls.iter().enumerate() {
                    let ord =
                        crate::value::cmp_values_coll(&group_keys[i][k], &group_keys[j][k], *coll);
                    if ord != core::cmp::Ordering::Equal {
                        return ord;
                    }
                }
                core::cmp::Ordering::Equal
            });
            let mut sorted = Vec::with_capacity(groups.len());
            for i in order {
                sorted.push(core::mem::take(&mut groups[i]));
            }
            groups = sorted;
        }

        // --- Rewrite the query so each aggregate becomes a `__aggN` column. ---
        let mut aggs: Vec<Expr> = Vec::new();
        let mut rsel = sel.clone();
        for col in &mut rsel.columns {
            if let ResultColumn::Expr { expr, .. } = col {
                *expr = self.extract_aggregates(expr, &mut aggs);
            }
        }
        if let Some(h) = rsel.having.take() {
            rsel.having = Some(self.extract_aggregates(&h, &mut aggs));
        }
        for t in &mut rsel.order_by {
            t.expr = self.extract_aggregates(&t.expr, &mut aggs);
        }
        // Named WINDOW definitions (`WINDOW w AS (ORDER BY sum(v))`) referenced via
        // `OVER w` carry their PARTITION/ORDER expressions here, not in the call's
        // own spec, so rewrite their aggregates too.
        for (_, ws) in &mut rsel.window_defs {
            for p in &mut ws.partition_by {
                *p = self.extract_aggregates(p, &mut aggs);
            }
            for t in &mut ws.order_by {
                t.expr = self.extract_aggregates(&t.expr, &mut aggs);
            }
        }

        // --- Augment the column set with one synthetic column per aggregate. ---
        let mut cols: Vec<ColumnInfo> = columns.to_vec();
        for i in 0..aggs.len() {
            cols.push(ColumnInfo {
                name: alloc::format!("__agg{i}"),
                table: String::new(),
                affinity: eval::Affinity::Blob,
                collation: crate::value::Collation::default(),
            });
        }

        // --- One grouped row per group: representative base values ++ aggregate
        //     values (computed over the group via the existing machinery). ---
        let empty = InputRow {
            values: alloc::vec![Value::Null; columns.len()],
            rowid: None,
        };
        let mut grows: Vec<InputRow> = Vec::with_capacity(groups.len());
        for group in &groups {
            let repr_idx = group.first().copied();
            let repr = repr_idx.map(|i| &rows[i]).unwrap_or(&empty);
            let repr_ctx = repr.ctx(columns, params).with_subqueries(self);
            let mut vals = repr.values.clone();
            for agg in &aggs {
                let sub = self.substitute_aggregates(agg, columns, &rows, group, params)?;
                vals.push(eval::eval(&sub, &repr_ctx)?);
            }
            grows.push(InputRow {
                values: vals,
                rowid: repr_idx.and_then(|i| rows[i].rowid),
            });
        }

        // --- HAVING (now over the grouped rows; references `__aggN`). ---
        if let Some(having) = &rsel.having {
            let mut kept = Vec::with_capacity(grows.len());
            for r in grows {
                let ctx = r.ctx(&cols, params).with_subqueries(self);
                if eval::truth(&eval::eval(having, &ctx)?) == Some(true) {
                    kept.push(r);
                }
            }
            grows = kept;
        }

        // --- Window functions over the grouped rows, then project. ---
        let mut wcols = cols;
        let win_sel = self.apply_windows(&rsel, &mut wcols, &mut grows, params)?;
        let mut out = Vec::with_capacity(grows.len());
        for r in &grows {
            let ctx = r.ctx(&wcols, params).with_subqueries(self);
            let mut values = Vec::new();
            for col in &win_sel.columns {
                project_column(col, &wcols, &ctx, &mut values)?;
            }
            let mut sort_keys = Vec::new();
            for term in &win_sel.order_by {
                match resolve_order_index(&term.expr, &labels, values.len()) {
                    Some(idx) => sort_keys.push(values[idx].clone()),
                    None => sort_keys.push(eval::eval(&term.expr, &ctx)?),
                }
            }
            out.push(OutRow { values, sort_keys });
        }
        Ok((labels, out))
    }

    /// The index (into `rows`) of the group member achieving the maximum (or
    /// minimum) value of `arg`, ignoring NULLs; falls back to the group's first
    /// row when every value is NULL. Implements SQLite's bare-column min/max rule.
    fn argextreme_row(
        &self,
        group: &[usize],
        columns: &[ColumnInfo],
        rows: &[InputRow],
        arg: &Expr,
        is_max: bool,
        params: &Params,
    ) -> Result<Option<usize>> {
        let mut best: Option<(usize, Value)> = None;
        for &i in group {
            let ctx = rows[i].ctx(columns, params).with_subqueries(self);
            let v = eval::eval(arg, &ctx)?;
            if matches!(v, Value::Null) {
                continue;
            }
            let take = match &best {
                None => true,
                Some((_, bv)) => {
                    let ord = eval::compare(&v, bv);
                    if is_max {
                        ord == core::cmp::Ordering::Greater
                    } else {
                        ord == core::cmp::Ordering::Less
                    }
                }
            };
            if take {
                best = Some((i, v));
            }
        }
        Ok(best.map(|(i, _)| i).or_else(|| group.first().copied()))
    }

    /// Replace aggregate function calls in `expr` with their computed values for
    /// the given group, returning an aggregate-free expression.
    fn substitute_aggregates(
        &self,
        expr: &Expr,
        columns: &[ColumnInfo],
        rows: &[InputRow],
        group: &[usize],
        params: &Params,
    ) -> Result<Expr> {
        Ok(match expr {
            Expr::Function {
                name,
                distinct,
                args,
                star,
                filter,
                order_by,
                over: None,
            } if func::is_aggregate_call(name, args.len(), *star)
                || self.aggregates.contains_key(&name.to_ascii_lowercase()) =>
            {
                // `FILTER (WHERE …)` narrows the group's rows before aggregating.
                let filtered;
                let group = match filter {
                    Some(pred) => {
                        filtered = self.filter_group(pred, columns, rows, group, params)?;
                        &filtered[..]
                    }
                    None => group,
                };
                let v = self.compute_aggregate(
                    name, *distinct, args, *star, order_by, columns, rows, group, params,
                )?;
                let lit = Expr::Literal(value_to_literal(v));
                // The JSON aggregates emit a value carrying SQLite's JSON subtype.
                // Substitution to a bare literal would drop that, so an enclosing
                // json_quote/json_array/json_object would re-quote it. Re-wrap in
                // json() (idempotent on valid JSON) so the subtype marker — which
                // func::produces_json keys off the expression — survives.
                if matches!(
                    name.to_ascii_lowercase().as_str(),
                    "json_group_array" | "json_group_object"
                ) {
                    Expr::Function {
                        name: String::from("json"),
                        distinct: false,
                        args: alloc::vec![lit],
                        star: false,
                        filter: None,
                        order_by: Vec::new(),
                        over: None,
                    }
                } else {
                    lit
                }
            }
            Expr::Function {
                name,
                distinct,
                args,
                star,
                filter,
                order_by,
                over,
            } => {
                let mut new_args = Vec::with_capacity(args.len());
                for a in args {
                    new_args.push(self.substitute_aggregates(a, columns, rows, group, params)?);
                }
                Expr::Function {
                    name: name.clone(),
                    distinct: *distinct,
                    args: new_args,
                    star: *star,
                    filter: filter.clone(),
                    order_by: order_by.clone(),
                    over: over.clone(),
                }
            }
            Expr::Binary { op, left, right } => Expr::Binary {
                op: *op,
                left: Box::new(self.substitute_aggregates(left, columns, rows, group, params)?),
                right: Box::new(self.substitute_aggregates(right, columns, rows, group, params)?),
            },
            Expr::Unary { op, expr } => Expr::Unary {
                op: *op,
                expr: Box::new(self.substitute_aggregates(expr, columns, rows, group, params)?),
            },
            Expr::Paren(e) => Expr::Paren(Box::new(
                self.substitute_aggregates(e, columns, rows, group, params)?,
            )),
            Expr::Cast { expr, type_name } => Expr::Cast {
                expr: Box::new(self.substitute_aggregates(expr, columns, rows, group, params)?),
                type_name: type_name.clone(),
            },
            Expr::IsNull { expr, negated } => Expr::IsNull {
                expr: Box::new(self.substitute_aggregates(expr, columns, rows, group, params)?),
                negated: *negated,
            },
            Expr::Between {
                expr,
                low,
                high,
                negated,
            } => Expr::Between {
                expr: Box::new(self.substitute_aggregates(expr, columns, rows, group, params)?),
                low: Box::new(self.substitute_aggregates(low, columns, rows, group, params)?),
                high: Box::new(self.substitute_aggregates(high, columns, rows, group, params)?),
                negated: *negated,
            },
            Expr::InList {
                expr,
                list,
                negated,
                candidate_affinity,
            } => {
                let mut new_list = Vec::with_capacity(list.len());
                for e in list {
                    new_list.push(self.substitute_aggregates(e, columns, rows, group, params)?);
                }
                Expr::InList {
                    expr: Box::new(self.substitute_aggregates(expr, columns, rows, group, params)?),
                    list: new_list,
                    negated: *negated,
                    candidate_affinity: candidate_affinity.clone(),
                }
            }
            Expr::Case {
                operand,
                when_then,
                else_result,
            } => {
                let operand = match operand {
                    Some(o) => Some(Box::new(
                        self.substitute_aggregates(o, columns, rows, group, params)?,
                    )),
                    None => None,
                };
                let mut new_wt = Vec::with_capacity(when_then.len());
                for (w, t) in when_then {
                    new_wt.push((
                        self.substitute_aggregates(w, columns, rows, group, params)?,
                        self.substitute_aggregates(t, columns, rows, group, params)?,
                    ));
                }
                let else_result = match else_result {
                    Some(e) => Some(Box::new(
                        self.substitute_aggregates(e, columns, rows, group, params)?,
                    )),
                    None => None,
                };
                Expr::Case {
                    operand,
                    when_then: new_wt,
                    else_result,
                }
            }
            // Literals, columns, parameters, and subqueries are left as-is
            // (a subquery's own aggregates belong to that subquery).
            other => other.clone(),
        })
    }

    /// The subset of `group`'s row indices for which `pred` (an aggregate
    /// `FILTER (WHERE …)`) evaluates true.
    fn filter_group(
        &self,
        pred: &Expr,
        columns: &[ColumnInfo],
        rows: &[InputRow],
        group: &[usize],
        params: &Params,
    ) -> Result<Vec<usize>> {
        let mut out = Vec::new();
        for &i in group {
            let ctx = rows[i].ctx(columns, params).with_subqueries(self);
            if eval::truth(&eval::eval(pred, &ctx)?) == Some(true) {
                out.push(i);
            }
        }
        Ok(out)
    }

    #[allow(clippy::too_many_arguments)]
    #[allow(clippy::too_many_arguments)]
    fn compute_aggregate(
        &self,
        name: &str,
        distinct: bool,
        args: &[Expr],
        star: bool,
        order_by: &[OrderTerm],
        columns: &[ColumnInfo],
        rows: &[InputRow],
        group: &[usize],
        params: &Params,
    ) -> Result<Value> {
        let lname = name.to_ascii_lowercase();

        // Arity guards: every aggregate but `count(*)` needs at least one
        // argument, and `json_group_object` needs two. SQLite rejects a short
        // call ("wrong number of arguments"); without this we would index
        // `args[…]` out of bounds and panic (e.g. `group_concat()`).
        if !star && args.is_empty() {
            return Err(Error::Error(format!(
                "wrong number of arguments to function {lname}()"
            )));
        }
        if (lname == "json_group_object" || lname == "jsonb_group_object") && args.len() < 2 {
            return Err(Error::Error(format!(
                "wrong number of arguments to function {lname}()"
            )));
        }
        // Upper-bound arity for the builtin aggregates (a registered UDAF carries
        // its own). SQLite rejects too many arguments ("wrong number of
        // arguments"): `sum(1,2)`, `avg(1,2)`, `count(1,2)` are all errors. The
        // two-argument forms are `group_concat`/`string_agg` and the
        // `json[b]_group_object` pair; every other builtin aggregate takes one.
        if !self.aggregates.contains_key(&lname) {
            let max_args = match lname.as_str() {
                "group_concat" | "string_agg" | "json_group_object" | "jsonb_group_object" => 2,
                _ => 1,
            };
            if args.len() > max_args {
                return Err(Error::Error(format!(
                    "wrong number of arguments to function {lname}()"
                )));
            }
        }

        // An `ORDER BY` inside the aggregate (`group_concat(x ORDER BY y)`) sorts
        // the group's rows before the values are gathered.
        let ordered_group;
        let group = if order_by.is_empty() {
            group
        } else {
            let mut g = group.to_vec();
            let mut err = None;
            g.sort_by(|&a, &b| {
                for term in order_by {
                    let ca = rows[a].ctx(columns, params).with_subqueries(self);
                    let cb = rows[b].ctx(columns, params).with_subqueries(self);
                    let (va, vb) = match (eval::eval(&term.expr, &ca), eval::eval(&term.expr, &cb))
                    {
                        (Ok(x), Ok(y)) => (x, y),
                        (Err(e), _) | (_, Err(e)) => {
                            err.get_or_insert(e);
                            return core::cmp::Ordering::Equal;
                        }
                    };
                    let coll = eval::key_collation(&term.expr, &ca);
                    let ord = cmp_order(&va, &vb, term.descending, term.nulls_first, coll);
                    if ord != core::cmp::Ordering::Equal {
                        return ord;
                    }
                }
                core::cmp::Ordering::Equal
            });
            if let Some(e) = err {
                return Err(e);
            }
            ordered_group = g;
            &ordered_group[..]
        };

        // JSON aggregates build their result directly from the (NULL-inclusive,
        // possibly multi-argument) per-row values, so they bypass the NULL-
        // stripping single-value collection used by the other aggregates.
        if lname == "json_group_array" || lname == "jsonb_group_array" {
            let mut vals = Vec::new();
            for &i in group {
                let ctx = rows[i].ctx(columns, params).with_subqueries(self);
                vals.push(eval::eval(&args[0], &ctx)?);
            }
            // `json_group_array(DISTINCT x)` dedupes the values (first-seen order),
            // like other DISTINCT aggregates, before serializing.
            if distinct {
                dedup_values(&mut vals, crate::value::Collation::default());
            }
            let items: Vec<_> = vals
                .iter()
                .map(|v| func::arg_to_json(v, args.first()))
                .collect();
            let arr = json::Json::Array(items);
            return Ok(if lname.starts_with("jsonb") {
                Value::Blob(arr.to_jsonb())
            } else {
                Value::Text(arr.serialize())
            });
        }
        if lname == "json_group_object" || lname == "jsonb_group_object" {
            let mut pairs = Vec::new();
            for &i in group {
                let ctx = rows[i].ctx(columns, params).with_subqueries(self);
                let k = eval::eval(&args[0], &ctx)?;
                let v = eval::eval(&args[1], &ctx)?;
                pairs.push((eval::to_text(&k), func::arg_to_json(&v, args.get(1))));
            }
            let obj = json::Json::Object(pairs);
            return Ok(if lname.starts_with("jsonb") {
                Value::Blob(obj.to_jsonb())
            } else {
                Value::Text(obj.serialize())
            });
        }

        // Gather the (non-NULL for most) argument values across the group.
        let mut vals: Vec<Value> = Vec::new();
        let mut count_rows = 0usize; // for count(*)
        for &i in group {
            count_rows += 1;
            if star {
                continue;
            }
            let ctx = rows[i].ctx(columns, params).with_subqueries(self);
            let v = eval::eval(&args[0], &ctx)?;
            if !matches!(v, Value::Null) {
                vals.push(v);
            }
        }
        if distinct {
            let coll = if star || args.is_empty() {
                crate::value::Collation::default()
            } else {
                let cctx = row_ctx(&[], columns, None, params);
                eval::key_collation(&args[0], &cctx)
            };
            dedup_values(&mut vals, coll);
        }

        // `min`/`max` compare under the argument's collation (e.g. a NOCASE
        // column), not plain BINARY.
        let arg_coll = if args.is_empty() {
            crate::value::Collation::default()
        } else {
            let cctx = row_ctx(&[], columns, None, params);
            eval::key_collation(&args[0], &cctx)
        };

        Ok(match lname.as_str() {
            "count" => {
                if star {
                    Value::Integer(count_rows as i64)
                } else {
                    Value::Integer(vals.len() as i64)
                }
            }
            "sum" => {
                if vals.is_empty() {
                    Value::Null
                } else if vals.iter().all(|v| matches!(v, Value::Integer(_))) {
                    let mut acc: i64 = 0;
                    let mut overflow = false;
                    for v in &vals {
                        if let Value::Integer(i) = v {
                            match acc.checked_add(*i) {
                                Some(s) => acc = s,
                                None => {
                                    overflow = true;
                                    break;
                                }
                            }
                        }
                    }
                    if overflow {
                        // Like SQLite: an integer `sum()` that overflows i64 is an
                        // error (use `total()` for a non-failing real sum).
                        return Err(Error::Error("integer overflow".into()));
                    } else {
                        Value::Integer(acc)
                    }
                } else {
                    Value::Real(vals.iter().map(eval::to_f64).sum())
                }
            }
            "total" => Value::Real(vals.iter().map(eval::to_f64).sum()),
            "avg" => {
                if vals.is_empty() {
                    Value::Null
                } else {
                    let sum: f64 = vals.iter().map(eval::to_f64).sum();
                    Value::Real(sum / vals.len() as f64)
                }
            }
            "min" => vals
                .into_iter()
                .reduce(|a, b| {
                    if crate::value::cmp_values_coll(&b, &a, arg_coll) == core::cmp::Ordering::Less
                    {
                        b
                    } else {
                        a
                    }
                })
                .unwrap_or(Value::Null),
            "max" => vals
                .into_iter()
                .reduce(|a, b| {
                    if crate::value::cmp_values_coll(&b, &a, arg_coll)
                        == core::cmp::Ordering::Greater
                    {
                        b
                    } else {
                        a
                    }
                })
                .unwrap_or(Value::Null),
            // `string_agg` is SQLite's standard-SQL alias for `group_concat`.
            "group_concat" | "string_agg" => {
                if vals.is_empty() {
                    Value::Null
                } else {
                    let sep = if args.len() >= 2 {
                        let ctx = EvalCtx::rowless(params);
                        eval::to_text(&eval::eval(&args[1], &ctx)?)
                    } else {
                        ",".to_string()
                    };
                    let parts: Vec<String> = vals.iter().map(eval::to_text).collect();
                    Value::Text(parts.join(&sep))
                }
            }
            _ => {
                // A user-defined aggregate registered via
                // `register_aggregate_function`: build a fresh accumulator, step
                // it over the group's evaluated argument values, then finalize.
                if let Some(factory) = self.aggregates.get(&lname) {
                    let mut acc = factory();
                    let mut seen: Vec<Vec<Value>> = Vec::new();
                    for &i in group {
                        let ctx = rows[i].ctx(columns, params).with_subqueries(self);
                        let vals: Vec<Value> = args
                            .iter()
                            .map(|a| eval::eval(a, &ctx))
                            .collect::<Result<_>>()?;
                        if distinct {
                            if seen.contains(&vals) {
                                continue;
                            }
                            seen.push(vals.clone());
                        }
                        acc.step(&vals)?;
                    }
                    return acc.finalize();
                }
                return Err(Error::Error(format!("no such function: {name}")));
            }
        })
    }

    /// An aggregate function in the *result columns* (not HAVING). This is what
    /// makes a query an aggregate query for the purpose of permitting a HAVING
    /// clause — an aggregate appearing only inside HAVING does not count.
    fn has_result_aggregate(&self, sel: &Select) -> bool {
        // Recognize both built-in and user-registered aggregate names.
        let is_agg = |name: &str, n: usize, star: bool| {
            func::is_aggregate_call(name, n, star)
                || self.aggregates.contains_key(&name.to_ascii_lowercase())
        };
        sel.columns.iter().any(|c| match c {
            ResultColumn::Expr { expr, .. } => expr_contains_agg(expr, &is_agg),
            _ => false,
        })
    }

    fn has_aggregate(&self, sel: &Select) -> bool {
        if self.has_result_aggregate(sel) {
            return true;
        }
        // Recognize both built-in and user-registered aggregate names.
        let is_agg = |name: &str, n: usize, star: bool| {
            func::is_aggregate_call(name, n, star)
                || self.aggregates.contains_key(&name.to_ascii_lowercase())
        };
        sel.having
            .as_ref()
            .is_some_and(|h| expr_contains_agg(h, &is_agg))
    }

    fn output_labels(&self, sel: &Select, columns: &[ColumnInfo]) -> Vec<String> {
        let mut labels = Vec::new();
        for col in &sel.columns {
            match col {
                ResultColumn::Wildcard => {
                    for c in columns {
                        labels.push(c.name.clone());
                    }
                }
                // `t.*` names only that table's columns (by owning-table qualifier),
                // matching the projected data — over a join a bare `*` lists every
                // column but `t.*` must not.
                ResultColumn::TableWildcard(t) => {
                    for c in columns.iter().filter(|c| c.table.eq_ignore_ascii_case(t)) {
                        labels.push(c.name.clone());
                    }
                }
                ResultColumn::Expr {
                    expr,
                    alias,
                    source,
                } => {
                    labels.push(result_column_label(expr, alias, source));
                }
            }
        }
        labels
    }

    fn table_meta(&self, name: &str, alias: Option<&str>) -> Result<TableMeta> {
        self.table_meta_in(&self.schema, name, alias)
    }

    /// Like [`table_meta`](Self::table_meta) but resolving `name` in an explicit
    /// schema catalog (the `main` schema or an attached database's).
    fn table_meta_in(&self, schema: &Schema, name: &str, alias: Option<&str>) -> Result<TableMeta> {
        // The schema catalog itself is queryable as `sqlite_schema` /
        // `sqlite_master` (a 5-column rowid table rooted at page 1).
        if is_main_schema_table(name) {
            return Ok(schema_table_meta(alias.unwrap_or(name)));
        }
        let obj = schema
            .table(name)
            .ok_or_else(|| Error::Error(alloc::format!("no such table: {name}")))?;
        let sql = obj
            .sql
            .as_ref()
            .ok_or_else(|| Error::Corrupt("table has no CREATE statement".into()))?;
        let Statement::CreateTable(ct) = sql::parse_one(sql)? else {
            return Err(Error::Corrupt("schema sql is not CREATE TABLE".into()));
        };
        let table_label = alias.unwrap_or(name).to_string();
        let columns: Vec<ColumnInfo> = ct
            .columns
            .iter()
            .map(|c| ColumnInfo {
                name: c.name.clone(),
                table: table_label.clone(),
                affinity: eval::Affinity::from_type(c.type_name.as_deref()),
                collation: column_collation(c),
            })
            .collect();
        let defaults: Vec<Option<Expr>> = ct
            .columns
            .iter()
            .map(|c| {
                c.constraints.iter().find_map(|k| match k {
                    ColumnConstraint::Default(e) => Some(e.clone()),
                    _ => None,
                })
            })
            .collect();
        // A WITHOUT ROWID table has no rowid, so `INTEGER PRIMARY KEY` is an
        // ordinary column there (no rowid aliasing).
        let ipk = if ct.without_rowid {
            None
        } else {
            find_integer_primary_key(&ct)
        };
        // `None` = nullable; `Some(action)` = NOT NULL with that conflict action.
        let not_null: Vec<Option<OnConflict>> = ct
            .columns
            .iter()
            .enumerate()
            .map(|(i, c)| {
                // The INTEGER PRIMARY KEY (rowid alias) is implicitly NOT NULL.
                if Some(i) == ipk {
                    return Some(OnConflict::Abort);
                }
                c.constraints.iter().find_map(|k| match k {
                    ColumnConstraint::NotNull(oc) => Some(*oc),
                    _ => None,
                })
            })
            .collect();
        // Generated columns: `… AS (expr) [STORED|VIRTUAL]`.
        let generated: Vec<Option<(Expr, bool)>> = ct
            .columns
            .iter()
            .map(|c| {
                c.constraints.iter().find_map(|k| match k {
                    ColumnConstraint::Generated { expr, stored } => Some((expr.clone(), *stored)),
                    _ => None,
                })
            })
            .collect();
        // CHECK constraints (column-level + table-level); each is evaluated
        // against the full row on INSERT/UPDATE.
        let mut checks: Vec<(Expr, Option<String>)> = Vec::new();
        for col in &ct.columns {
            for k in &col.constraints {
                if let ColumnConstraint::Check(e, label) = k {
                    checks.push((e.clone(), label.clone()));
                }
            }
        }
        for tc in &ct.constraints {
            if let TableConstraint::Check(e, label) = tc {
                checks.push((e.clone(), label.clone()));
            }
        }
        // UNIQUE / PRIMARY KEY column sets that must be unique (the rowid IPK is
        // handled separately). Order matches SQLite's auto-index numbering.
        let unique = collect_unique_sets(&ct, ipk);

        // WITHOUT ROWID: derive the PK-first storage order.
        let (without_rowid, storage_order, pk_len) = if ct.without_rowid {
            let pk = primary_key_positions(&ct);
            if pk.is_empty() {
                return Err(Error::Error(
                    "WITHOUT ROWID table must have a PRIMARY KEY".into(),
                ));
            }
            // Storage order: PK columns first, then the remaining *stored*
            // columns (VIRTUAL generated columns are never written).
            let mut order = pk.clone();
            for (i, gen) in generated.iter().enumerate() {
                let is_virtual = matches!(gen, Some((_, false)));
                if !pk.contains(&i) && !is_virtual {
                    order.push(i);
                }
            }
            let pk_len = pk.len();
            (true, order, pk_len)
        } else {
            (false, Vec::new(), 0)
        };

        // STRICT tables: record each column's rigid type for write-time checking,
        // and give `ANY` columns no affinity (values stored exactly as supplied).
        let strict_types: Option<Vec<(StrictType, String)>> = if ct.strict {
            let mut v = Vec::with_capacity(columns.len());
            for c in &ct.columns {
                let st = strict_column_type(c.type_name.as_deref()).unwrap_or(StrictType::Any);
                let decl = c.type_name.clone().unwrap_or_default();
                v.push((st, decl));
            }
            Some(v)
        } else {
            None
        };
        let mut columns = columns;
        if let Some(st) = &strict_types {
            for (col, (ty, _)) in columns.iter_mut().zip(st) {
                if *ty == StrictType::Any {
                    col.affinity = eval::Affinity::Blob; // ANY: store as-is
                }
            }
        }

        Ok(TableMeta {
            root: obj.rootpage,
            columns,
            defaults,
            not_null,
            checks,
            unique,
            ipk,
            generated,
            without_rowid,
            storage_order,
            pk_len,
            strict_types,
            autoincrement: ipk.is_some_and(|i| {
                ct.columns[i].constraints.iter().any(|k| {
                    matches!(
                        k,
                        ColumnConstraint::PrimaryKey {
                            autoincrement: true,
                            ..
                        }
                    )
                })
            }),
        })
    }

    /// Enforce a `STRICT` table's column types against a row whose affinity has
    /// already been applied. NULL always passes; otherwise the stored value's
    /// storage class must match the column's rigid type (`ANY` accepts anything).
    /// `INT`/`REAL` columns accept their numeric class after affinity coercion
    /// (an integer in a `REAL` column has been turned into a real already).
    fn check_strict_types(&self, meta: &TableMeta, values: &[Value]) -> Result<()> {
        let Some(stypes) = &meta.strict_types else {
            return Ok(());
        };
        for (i, (st, decl)) in stypes.iter().enumerate() {
            let v = &values[i];
            let ok = matches!(
                (st, v),
                (_, Value::Null)
                    | (StrictType::Any, _)
                    | (StrictType::Int, Value::Integer(_))
                    | (StrictType::Real, Value::Real(_))
                    | (StrictType::Text, Value::Text(_))
                    | (StrictType::Blob, Value::Blob(_))
            );
            if !ok {
                let class = match v {
                    Value::Integer(_) => "INT",
                    Value::Real(_) => "REAL",
                    Value::Text(_) => "TEXT",
                    Value::Blob(_) => "BLOB",
                    Value::Null => unreachable!(),
                };
                return Err(Error::Constraint(format!(
                    "cannot store {class} value in {decl} column {}.{}",
                    meta.columns[i].table, meta.columns[i].name
                )));
            }
        }
        Ok(())
    }

    /// Evaluate CHECK constraints against a fully-built row (with the IPK column
    /// holding the rowid). A constraint fails only when it evaluates to false;
    /// NULL (unknown) passes, matching SQLite.
    fn check_constraints(
        &self,
        meta: &TableMeta,
        values: &[Value],
        rowid: Option<i64>,
        params: &Params,
    ) -> Result<()> {
        for (expr, label) in &meta.checks {
            let ctx = row_ctx(values, &meta.columns, rowid, params).with_subqueries(self);
            if eval::truth(&eval::eval(expr, &ctx)?) == Some(false) {
                let msg = match label {
                    Some(l) => alloc::format!("CHECK constraint failed: {l}"),
                    None => String::from("CHECK constraint failed"),
                };
                return Err(Error::Constraint(msg));
            }
        }
        Ok(())
    }
}

struct TableMeta {
    root: u32,
    columns: Vec<ColumnInfo>,
    /// Per-column `DEFAULT` expression, if declared (aligned with `columns`).
    defaults: Vec<Option<Expr>>,
    /// Per-column `NOT NULL` flag (aligned with `columns`).
    /// `None` = nullable; `Some(action)` = `NOT NULL` with its `ON CONFLICT` action.
    not_null: Vec<Option<OnConflict>>,
    /// CHECK constraint expressions (column-level and table-level).
    /// CHECK constraints with their error-message label (name or source text).
    checks: Vec<(Expr, Option<String>)>,
    /// Column-index sets that must be UNIQUE (excludes the rowid IPK), each with
    /// its declared `ON CONFLICT` action (default `Abort`).
    unique: Vec<(Vec<usize>, OnConflict)>,
    ipk: Option<usize>,
    /// Per-column generated-column spec `(expr, stored)`, if the column is
    /// `… AS (expr) [STORED|VIRTUAL]`. `VIRTUAL` (stored = false) columns are not
    /// written to disk; `STORED` ones are. Aligned with `columns`.
    generated: Vec<Option<(Expr, bool)>>,
    /// `true` for a `WITHOUT ROWID` table (stored as a PK-clustered index b-tree
    /// rather than a rowid table b-tree).
    without_rowid: bool,
    /// For a `WITHOUT ROWID` table, the on-disk column order: PRIMARY KEY columns
    /// first (in key order), then the remaining columns in declared order. Empty
    /// for ordinary rowid tables. `pk_len` is how many leading entries are PK.
    storage_order: Vec<usize>,
    pk_len: usize,
    /// For a `STRICT` table, each column's rigid type and its declared type name
    /// (aligned with `columns`); `None` for an ordinary table. Drives write-time
    /// type checking.
    strict_types: Option<Vec<(StrictType, String)>>,
    /// `true` when the `INTEGER PRIMARY KEY` is declared `AUTOINCREMENT`: assigned
    /// rowids never reuse a value below the high-water mark persisted in
    /// `sqlite_sequence`, matching SQLite.
    autoincrement: bool,
}

/// Return a copy of `sel` with any `*` / `table.*` result column expanded to
/// explicit table-qualified column references drawn from `columns`. Used by the
/// aggregate path so bare wildcards follow the same representative-row rule as
/// named bare columns.
fn expand_agg_wildcards(sel: &Select, columns: &[ColumnInfo]) -> Select {
    let col_ref = |c: &ColumnInfo| ResultColumn::Expr {
        expr: Expr::Column {
            table: Some(c.table.clone()),
            column: c.name.clone(),
        },
        alias: None,
        source: None,
    };
    let mut new_cols = Vec::new();
    for col in &sel.columns {
        match col {
            ResultColumn::Wildcard => new_cols.extend(columns.iter().map(&col_ref)),
            ResultColumn::TableWildcard(t) => new_cols.extend(
                columns
                    .iter()
                    .filter(|c| c.table.eq_ignore_ascii_case(t))
                    .map(&col_ref),
            ),
            other => new_cols.push(other.clone()),
        }
    }
    let mut s = sel.clone();
    s.columns = new_cols;
    s
}

/// If `sel`'s WHERE/GROUP BY/HAVING reference any SELECT-list alias that is not
/// shadowed by a real input column, return a copy of `sel` with those alias
/// references replaced by their defining expressions (SQLite resolves aliases in
/// these clauses, with real columns winning). Returns `None` when no rewrite is
/// needed, so the common path clones nothing.
fn alias_substituted(sel: &Select, columns: &[ColumnInfo]) -> Option<Select> {
    // Explicit `AS` aliases that don't collide with a real input column name.
    let mut aliases: Vec<(String, Expr)> = Vec::new();
    for c in &sel.columns {
        if let ResultColumn::Expr {
            expr,
            alias: Some(name),
            ..
        } = c
        {
            if !columns
                .iter()
                .any(|col| col.name.eq_ignore_ascii_case(name))
                && !aliases.iter().any(|(a, _)| a.eq_ignore_ascii_case(name))
            {
                aliases.push((name.clone(), expr.clone()));
            }
        }
    }
    if aliases.is_empty() {
        return None;
    }
    // Only rewrite if a clause actually references one of those aliases.
    let mentions = |e: &Expr| -> bool {
        let mut found = false;
        window::visit(e, &mut |n| {
            if let Expr::Column {
                table: None,
                column,
            } = n
            {
                if aliases.iter().any(|(a, _)| a.eq_ignore_ascii_case(column)) {
                    found = true;
                }
            }
        });
        found
    };
    let used = sel.where_clause.as_ref().is_some_and(&mentions)
        || sel.group_by.iter().any(&mentions)
        || sel.having.as_ref().is_some_and(&mentions);
    if !used {
        return None;
    }
    let mut out = sel.clone();
    let apply = |e: &mut Expr| {
        for (name, repl) in &aliases {
            let target = Expr::Column {
                table: None,
                column: name.clone(),
            };
            window::replace_expr(e, &target, repl);
        }
    };
    if let Some(w) = &mut out.where_clause {
        apply(w);
    }
    for g in &mut out.group_by {
        apply(g);
    }
    if let Some(h) = &mut out.having {
        apply(h);
    }
    Some(out)
}

/// Wrap a runtime [`Value`] as a literal [`Expr`], so rows produced by an
/// `INSERT … SELECT` can flow through the ordinary VALUES insert path.
fn value_to_literal_expr(v: Value) -> Expr {
    Expr::Literal(match v {
        Value::Null => Literal::Null,
        Value::Integer(i) => Literal::Integer(i),
        Value::Real(r) => Literal::Real(r),
        Value::Text(s) => Literal::Str(s),
        Value::Blob(b) => Literal::Blob(b),
    })
}

/// Whether `name` refers to the main schema catalog table, which SQLite exposes
/// under both the modern `sqlite_schema` and the historical `sqlite_master`.
fn is_main_schema_table(name: &str) -> bool {
    name.eq_ignore_ascii_case("sqlite_schema") || name.eq_ignore_ascii_case("sqlite_master")
}

/// Whether `name` is the temp-database catalog (`sqlite_temp_schema` /
/// `sqlite_temp_master`), which reads the `temp` database's `sqlite_master`.
fn is_temp_schema_table(name: &str) -> bool {
    name.eq_ignore_ascii_case("sqlite_temp_schema")
        || name.eq_ignore_ascii_case("sqlite_temp_master")
}

/// Reject a direct DML write to the schema catalog, as SQLite does (the catalog
/// is maintained by DDL, not by `INSERT`/`UPDATE`/`DELETE`).
fn reject_schema_write(table: &str) -> Result<()> {
    if is_main_schema_table(table) {
        return Err(Error::Error(alloc::format!(
            "table {table} may not be modified"
        )));
    }
    Ok(())
}

/// A synthetic [`TableMeta`] for the schema catalog (`sqlite_schema`): the
/// 5-column rowid table physically rooted at page 1. Read-only — writes are
/// rejected before reaching here.
fn schema_table_meta(label: &str) -> TableMeta {
    let col = |n: &str, aff: eval::Affinity| ColumnInfo {
        name: n.to_string(),
        table: label.to_string(),
        affinity: aff,
        collation: crate::value::Collation::default(),
    };
    let columns = alloc::vec![
        col("type", eval::Affinity::Text),
        col("name", eval::Affinity::Text),
        col("tbl_name", eval::Affinity::Text),
        col("rootpage", eval::Affinity::Integer),
        col("sql", eval::Affinity::Text),
    ];
    let n = columns.len();
    TableMeta {
        root: crate::schema::SCHEMA_ROOT_PAGE,
        columns,
        defaults: alloc::vec![None; n],
        not_null: alloc::vec![None; n],
        checks: Vec::new(),
        unique: Vec::new(),
        ipk: None,
        generated: alloc::vec![None; n],
        without_rowid: false,
        storage_order: Vec::new(),
        pk_len: 0,
        strict_types: None,
        autoincrement: false,
    }
}

/// The first column reference in `e` that names neither a column in `known` nor
/// Validate the explicit `COLLATE <name>`s in `sel` that are actually CONSUMED
/// for ordering/comparison (sqlite errors "no such collation sequence" there, but
/// not on an unused projection COLLATE). Covers comparisons, `ORDER BY`/
/// `GROUP BY`/`DISTINCT` keys, `IN`/`BETWEEN`, `CASE x WHEN`, and `min`/`max`.
/// Nested subqueries are not walked here — they validate themselves when run.
fn validate_used_collations(sel: &Select) -> Result<()> {
    for (_, arm) in &sel.compound {
        validate_used_collations(arm)?;
    }
    if let Some(w) = &sel.where_clause {
        consumed_collations(w)?;
    }
    if let Some(h) = &sel.having {
        consumed_collations(h)?;
    }
    if let Some(from) = &sel.from {
        for j in &from.joins {
            if let Some(on) = &j.on {
                consumed_collations(on)?;
            }
        }
    }
    for t in &sel.order_by {
        top_collation(&t.expr)?;
        consumed_collations(&t.expr)?;
    }
    for g in &sel.group_by {
        top_collation(g)?;
        consumed_collations(g)?;
    }
    for c in &sel.columns {
        if let ResultColumn::Expr { expr, .. } = c {
            if sel.distinct {
                top_collation(expr)?;
            }
            consumed_collations(expr)?;
        }
    }
    Ok(())
}

/// SQLite rejects a column reference that matches columns from two different
/// FROM sources — "ambiguous column name". `columns` is this query block's
/// resolved column list; a NATURAL/USING join already coalesces its shared
/// column to a single entry there, so a plain count over `columns` excludes
/// them. A bare name matching 2+ entries, or a `t.col` whose qualifier matches
/// 2+ entries (an unaliased self-join), is ambiguous. A result-set wildcard over
/// an unaliased self-join is ambiguous too — two entries then share *both* name
/// and qualifier, which even `*` cannot tell apart. Nested subqueries validate
/// their own references when they run, so this neither descends into them nor
/// considers the outer scope.
fn validate_unambiguous_columns(sel: &Select, columns: &[ColumnInfo]) -> Result<()> {
    let mut ambiguous: Option<String> = None;
    vdbe_block_exprs(sel, &mut |e| {
        window::visit(e, &mut |sub| {
            if ambiguous.is_some() {
                return;
            }
            if let Expr::Column { table, column } = sub {
                let n = columns
                    .iter()
                    .filter(|c| {
                        c.name.eq_ignore_ascii_case(column)
                            && table
                                .as_deref()
                                .is_none_or(|t| c.table.eq_ignore_ascii_case(t))
                    })
                    .count();
                if n >= 2 {
                    ambiguous = Some(alloc::format!("ambiguous column name: {column}"));
                }
            }
        });
    });
    if let Some(msg) = ambiguous {
        return Err(Error::Error(msg));
    }
    // A result-set wildcard (`*` / `t.*`) over an unaliased self-join: two
    // columns then carry the same name *and* qualifier, so even `*` cannot
    // disambiguate them (`SELECT * FROM z, z`).
    let has_wildcard = sel
        .columns
        .iter()
        .any(|c| matches!(c, ResultColumn::Wildcard | ResultColumn::TableWildcard(_)));
    if has_wildcard {
        for (i, a) in columns.iter().enumerate() {
            if let Some(b) = columns[i + 1..].iter().find(|b| {
                a.name.eq_ignore_ascii_case(&b.name) && a.table.eq_ignore_ascii_case(&b.table)
            }) {
                return Err(Error::Error(alloc::format!(
                    "ambiguous column name: {}.{}",
                    b.table,
                    b.name
                )));
            }
        }
    }
    Ok(())
}

/// Collect the immediately-nested subquery `SELECT`s of `e` (scalar `(SELECT …)`,
/// `EXISTS`, and `IN (SELECT …)`), descending through ordinary sub-expressions but
/// NOT into the collected subqueries' own bodies — each is recursed into
/// separately, with its own scope. Lifetime-preserving (unlike `window::visit`) so
/// the borrowed `&Select`s outlive the walk.
fn collect_subselects<'a>(e: &'a Expr, out: &mut Vec<&'a Select>) {
    match e {
        Expr::Subquery(s) => out.push(s),
        Expr::Exists { select, .. } => out.push(select),
        Expr::InSelect { select, expr, .. } => {
            out.push(select);
            collect_subselects(expr, out);
        }
        Expr::Unary { expr, .. } => collect_subselects(expr, out),
        Expr::Binary { left, right, .. } => {
            collect_subselects(left, out);
            collect_subselects(right, out);
        }
        Expr::Function { args, .. } => {
            for a in args {
                collect_subselects(a, out);
            }
        }
        Expr::IsNull { expr, .. } => collect_subselects(expr, out),
        Expr::InList { expr, list, .. } => {
            collect_subselects(expr, out);
            for a in list {
                collect_subselects(a, out);
            }
        }
        Expr::Between {
            expr, low, high, ..
        } => {
            collect_subselects(expr, out);
            collect_subselects(low, out);
            collect_subselects(high, out);
        }
        Expr::Case {
            operand,
            when_then,
            else_result,
        } => {
            if let Some(o) = operand {
                collect_subselects(o, out);
            }
            for (w, t) in when_then {
                collect_subselects(w, out);
                collect_subselects(t, out);
            }
            if let Some(el) = else_result {
                collect_subselects(el, out);
            }
        }
        Expr::Cast { expr, .. } => collect_subselects(expr, out),
        Expr::Collate { expr, .. } => collect_subselects(expr, out),
        Expr::Paren(inner) => collect_subselects(inner, out),
        _ => {}
    }
}

/// Resolve each direct column reference in `sel`'s own clauses against a stack of
/// scopes (innermost first; `scopes[0]` is `sel`'s own FROM columns, the rest are
/// enclosing queries) and return the first name that is ambiguous — i.e. matches
/// 2+ columns in the *nearest* scope that resolves it, mirroring how SQLite binds
/// a name to the innermost scope containing it. A `None` scope (columns that could
/// not be determined statically) stops the walk for that reference: the name might
/// bind there, so we never guess past it — this keeps the check free of false
/// positives. Only this level's own expressions are inspected; nested subqueries
/// are walked separately with their own scope pushed.
fn first_ambiguous_in_scopes(sel: &Select, scopes: &[Option<Vec<ColumnInfo>>]) -> Option<String> {
    let mut found: Option<String> = None;
    vdbe_block_exprs(sel, &mut |e| {
        window::visit(e, &mut |node| {
            if found.is_some() {
                return;
            }
            if let Expr::Column { table, column } = node {
                for scope in scopes {
                    let Some(cols) = scope else {
                        // Unknown scope: the name may bind here — stop, don't guess.
                        break;
                    };
                    let n = cols
                        .iter()
                        .filter(|c| {
                            c.name.eq_ignore_ascii_case(column)
                                && table
                                    .as_deref()
                                    .is_none_or(|t| c.table.eq_ignore_ascii_case(t))
                        })
                        .count();
                    if n >= 1 {
                        // Resolved in this scope; ambiguous iff 2+ here.
                        if n >= 2 {
                            found = Some(alloc::format!("ambiguous column name: {column}"));
                        }
                        break;
                    }
                }
            }
        });
    });
    found
}

/// Validate the top-level explicit `COLLATE` (through redundant parens) of an
/// expression used directly as a comparison/ordering key.
fn top_collation(e: &Expr) -> Result<()> {
    match e {
        Expr::Collate { collation, expr } => {
            if crate::value::Collation::parse(collation).is_none() {
                return Err(Error::Error(format!(
                    "no such collation sequence: {collation}"
                )));
            }
            top_collation(expr)
        }
        Expr::Paren(inner) => top_collation(inner),
        _ => Ok(()),
    }
}

/// Walk `e`, validating the `COLLATE` of each operand that lands in a
/// collation-consuming position (comparison/`BETWEEN`/`IN`/`CASE x WHEN`/
/// `min`/`max`). A `COLLATE` elsewhere (arithmetic, `||`, an ordinary function
/// argument, a bare projection) is not consumed and so is left unvalidated, as in
/// sqlite. Nested subqueries are not descended into.
fn consumed_collations(e: &Expr) -> Result<()> {
    match e {
        Expr::Binary { op, left, right } => {
            if matches!(
                op,
                BinaryOp::Eq
                    | BinaryOp::NotEq
                    | BinaryOp::Lt
                    | BinaryOp::LtEq
                    | BinaryOp::Gt
                    | BinaryOp::GtEq
            ) {
                top_collation(left)?;
                top_collation(right)?;
            }
            consumed_collations(left)?;
            consumed_collations(right)?;
        }
        Expr::Between {
            expr, low, high, ..
        } => {
            top_collation(expr)?;
            top_collation(low)?;
            top_collation(high)?;
            consumed_collations(expr)?;
            consumed_collations(low)?;
            consumed_collations(high)?;
        }
        Expr::InList { expr, list, .. } => {
            top_collation(expr)?;
            consumed_collations(expr)?;
            for it in list {
                top_collation(it)?;
                consumed_collations(it)?;
            }
        }
        Expr::InSelect { expr, .. } => {
            top_collation(expr)?;
            consumed_collations(expr)?;
        }
        Expr::Case {
            operand,
            when_then,
            else_result,
        } => {
            if let Some(o) = operand {
                // `CASE x WHEN y` compares x to each y.
                top_collation(o)?;
                consumed_collations(o)?;
                for (w, t) in when_then {
                    top_collation(w)?;
                    consumed_collations(w)?;
                    consumed_collations(t)?;
                }
            } else {
                for (w, t) in when_then {
                    consumed_collations(w)?;
                    consumed_collations(t)?;
                }
            }
            if let Some(er) = else_result {
                consumed_collations(er)?;
            }
        }
        Expr::Function { name, args, .. } => {
            // min()/max() (scalar or aggregate) compare their arguments.
            let lname = name.to_ascii_lowercase();
            if matches!(lname.as_str(), "min" | "max") {
                for a in args {
                    top_collation(a)?;
                }
            }
            for a in args {
                consumed_collations(a)?;
            }
        }
        Expr::Unary { expr, .. }
        | Expr::Paren(expr)
        | Expr::IsNull { expr, .. }
        | Expr::Cast { expr, .. }
        | Expr::Collate { expr, .. } => consumed_collations(expr)?,
        Expr::RowValue(items) => {
            for it in items {
                consumed_collations(it)?;
            }
        }
        _ => {}
    }
    Ok(())
}

/// The first explicit `COLLATE <name>` in `e` whose name is not a known
/// collating sequence (BINARY/NOCASE/RTRIM) — for rejecting it at `CREATE INDEX`,
/// where sqlite errors "no such collation sequence" rather than using BINARY.
fn unknown_collation(e: &Expr) -> Option<&str> {
    match e {
        Expr::Collate { expr, collation } => {
            if crate::value::Collation::parse(collation).is_none() {
                Some(collation)
            } else {
                unknown_collation(expr)
            }
        }
        Expr::Binary { left, right, .. } => {
            unknown_collation(left).or_else(|| unknown_collation(right))
        }
        Expr::Unary { expr, .. }
        | Expr::Paren(expr)
        | Expr::Cast { expr, .. }
        | Expr::IsNull { expr, .. } => unknown_collation(expr),
        Expr::Function { args, .. } => args.iter().find_map(unknown_collation),
        _ => None,
    }
}

/// (when `allow_rowid`) a rowid alias — the unknown column SQLite rejects at
/// `CREATE` in a CHECK constraint or generated-column expression. Generated
/// columns may not reference the rowid (`allow_rowid=false`); a CHECK may.
fn unknown_column_ref(e: &Expr, known: &[String], allow_rowid: bool) -> Option<String> {
    let mut bad: Option<String> = None;
    window::visit(e, &mut |n| {
        if let Expr::Column { column, .. } = n {
            if bad.is_none()
                && !known.iter().any(|c| c.eq_ignore_ascii_case(column))
                && !(allow_rowid && eval::is_rowid_alias(column))
            {
                bad = Some(column.clone());
            }
        }
    });
    bad
}

/// Whether `e` contains a subquery (scalar `(SELECT …)`, `EXISTS`, or `IN
/// (SELECT …)`) anywhere — SQLite forbids these in CHECK constraints and
/// generated-column expressions.
fn expr_has_subquery(e: &Expr) -> bool {
    let mut found = false;
    window::visit(e, &mut |n| {
        if matches!(
            n,
            Expr::Subquery(_) | Expr::Exists { .. } | Expr::InSelect { .. }
        ) {
            found = true;
        }
    });
    found
}

/// The verbatim name of the first built-in aggregate call in `e` (a plain
/// aggregate, not a windowed `… OVER (…)`), or `None`. SQLite rejects an
/// aggregate in a CHECK or generated-column expression at `CREATE` with "misuse
/// of aggregate function NAME()", preserving the name's case as written.
/// `min`/`max` count as aggregates only at arity one (the two-arg forms are
/// scalar); `count(*)` carries `star`. (For an expression with several
/// aggregates SQLite names one of them per its own resolver walk; reporting the
/// first found here still rejects with the right message form.)
fn first_aggregate_call_name(e: &Expr) -> Option<String> {
    let mut found: Option<String> = None;
    window::visit(e, &mut |n| {
        if found.is_some() {
            return;
        }
        if let Expr::Function {
            name,
            args,
            star,
            over,
            ..
        } = n
        {
            if over.is_none() && func::is_aggregate_call(name, args.len(), *star) {
                found = Some(name.clone());
            }
        }
    });
    found
}

/// Whether `e` calls a non-deterministic function — one that can return a
/// different value for the same inputs. SQLite prohibits these in contexts that
/// must be reproducible (index expressions, generated columns): an index built
/// over `random()` would never match a recomputed probe. Only the unambiguous
/// per-call-varying builtins are flagged here.
fn expr_is_nondeterministic(e: &Expr) -> bool {
    let mut found = false;
    window::visit(e, &mut |n| {
        if let Expr::Function { name, .. } = n {
            if matches!(
                name.to_ascii_lowercase().as_str(),
                "random" | "randomblob" | "last_insert_rowid" | "changes" | "total_changes"
            ) {
                found = true;
            }
        }
    });
    found
}

/// The rigid column type of a `STRICT` table column.
#[derive(Clone, Copy, PartialEq, Eq)]
enum StrictType {
    Int,
    Real,
    Text,
    Blob,
    Any,
}

/// The `STRICT` rigid type for a declared type name, or `None` if the name is
/// not one of the six allowed (`INT`/`INTEGER`/`REAL`/`TEXT`/`BLOB`/`ANY`) — in
/// which case a `STRICT` table rejects the `CREATE`.
fn strict_column_type(type_name: Option<&str>) -> Option<StrictType> {
    let t = type_name?.trim();
    if t.eq_ignore_ascii_case("INT") || t.eq_ignore_ascii_case("INTEGER") {
        Some(StrictType::Int)
    } else if t.eq_ignore_ascii_case("REAL") {
        Some(StrictType::Real)
    } else if t.eq_ignore_ascii_case("TEXT") {
        Some(StrictType::Text)
    } else if t.eq_ignore_ascii_case("BLOB") {
        Some(StrictType::Blob)
    } else if t.eq_ignore_ascii_case("ANY") {
        Some(StrictType::Any)
    } else {
        None
    }
}

impl TableMeta {
    /// Whether column `i` is a VIRTUAL generated column (computed, never stored).
    fn is_virtual(&self, i: usize) -> bool {
        matches!(self.generated[i], Some((_, false)))
    }

    /// Whether column `i` is generated (STORED or VIRTUAL).
    fn is_generated(&self, i: usize) -> bool {
        self.generated[i].is_some()
    }
}

/// An index's b-tree root and the table column positions it covers.
/// A planner decision to satisfy `ORDER BY` by scanning a secondary index in key
/// order (B0), shared by `scan_source`, `run_core`, and `eqp_access`.
/// Apply `f` to each expression the VDBE actually compiles for a single-block
/// query: projections, `WHERE`, `GROUP BY`, `HAVING`, `ORDER BY`, `LIMIT`/`OFFSET`
/// and join `ON`s. (Not CTEs/compound/subqueries — the VDBE bails on those.)
fn vdbe_block_exprs<'a>(sel: &'a Select, f: &mut impl FnMut(&'a Expr)) {
    for c in &sel.columns {
        if let ResultColumn::Expr { expr, .. } = c {
            f(expr);
        }
    }
    sel.where_clause.iter().for_each(&mut *f);
    sel.group_by.iter().for_each(&mut *f);
    sel.having.iter().for_each(&mut *f);
    for t in &sel.order_by {
        f(&t.expr);
    }
    sel.limit.iter().for_each(&mut *f);
    sel.offset.iter().for_each(&mut *f);
    if let Some(from) = &sel.from {
        for j in &from.joins {
            if let Some(on) = &j.on {
                f(on);
            }
        }
    }
}

/// Mutable counterpart of [`vdbe_block_exprs`].
fn vdbe_block_exprs_mut(sel: &mut Select, f: &mut impl FnMut(&mut Expr)) {
    for c in &mut sel.columns {
        if let ResultColumn::Expr { expr, .. } = c {
            f(expr);
        }
    }
    sel.where_clause.iter_mut().for_each(&mut *f);
    sel.group_by.iter_mut().for_each(&mut *f);
    sel.having.iter_mut().for_each(&mut *f);
    for t in &mut sel.order_by {
        f(&mut t.expr);
    }
    sel.limit.iter_mut().for_each(&mut *f);
    sel.offset.iter_mut().for_each(&mut *f);
    if let Some(from) = &mut sel.from {
        for j in &mut from.joins {
            if let Some(on) = &mut j.on {
                f(on);
            }
        }
    }
}

/// Substitute bound parameters into the expressions the VDBE compiles so a
/// PARAMETERIZED query can run on the (otherwise param-less) VDBE engine.
/// Returns the rewritten `Select`, or `None` to leave the query to the
/// tree-walker when an ANONYMOUS `?` is present — its index is assigned at eval
/// time (`EvalCtx::anon_counter`, affected by AND/OR short-circuit), so a static
/// substitution could diverge — or when those expressions hold no explicit
/// (`?N`/`:name`) parameter to substitute.
fn substitute_params(sel: &Select, params: &Params) -> Option<Select> {
    use crate::sql::token::Param;
    let mut anon = false;
    let mut explicit: Vec<Param> = Vec::new();
    vdbe_block_exprs(sel, &mut |e| {
        window::visit(e, &mut |x| {
            if let Expr::Parameter(p) = x {
                if matches!(p, Param::Anonymous) {
                    anon = true;
                } else if !explicit.contains(p) {
                    explicit.push(p.clone());
                }
            }
        });
    });
    if anon || explicit.is_empty() {
        return None;
    }
    let mut out = sel.clone();
    for p in &explicit {
        let v = match p {
            Param::Numbered(n) => params
                .positional
                .get((*n as usize).checked_sub(1)?)?
                .clone(),
            Param::Named(name) => params
                .named
                .iter()
                .find(|(k, _)| k == name)
                .map(|(_, v)| v.clone())?,
            Param::Anonymous => return None,
        };
        let target = Expr::Parameter(p.clone());
        let repl = Expr::Literal(value_to_literal(v));
        vdbe_block_exprs_mut(&mut out, &mut |e| window::replace_expr(e, &target, &repl));
    }
    Some(out)
}

struct OrderIndexScan {
    /// The index name (for `EXPLAIN QUERY PLAN`).
    name: String,
    /// Root page of the index b-tree.
    root: u32,
    /// Collations of the index's columns (for the b-tree walk).
    colls: Vec<crate::value::Collation>,
    /// Table-column index of each index column (record layout `cols…, rowid`).
    cols: Vec<usize>,
    /// `ORDER BY … DESC` (the ascending scan is reversed).
    descending: bool,
    /// The index holds every column the query references (B2): rows can be built
    /// from index records without touching the table b-tree.
    covering: bool,
    /// Number of trailing `ORDER BY` terms the index walk does NOT order (because
    /// they change direction): the walk yields the uniform leading prefix, then
    /// the caller still sorts. 0 means the walk fully satisfies the ORDER BY (no
    /// sort). Only set (>0) for the NON-covering mixed-direction case — the
    /// covered mixed case is handled by `covering_scan` + `scan_order_prefix`.
    sorted_suffix: usize,
}

struct IndexMeta {
    /// The index name (as in `sqlite_schema`), used by `ANALYZE`.
    name: String,
    root: u32,
    cols: Vec<usize>,
    /// Collating sequence for each indexed column (aligned with `cols`).
    collations: Vec<crate::value::Collation>,
    /// `CREATE INDEX … WHERE <predicate>` — a partial index only stores rows for
    /// which the predicate is true. `None` for a full index.
    partial: Option<Expr>,
    /// For an expression index (`CREATE INDEX … (lower(x))`), the per-term key
    /// expressions evaluated against each row to form the key. `None` for an
    /// ordinary column index (which uses `cols`).
    key_exprs: Option<Vec<Expr>>,
    /// `true` for a `UNIQUE` index (or an automatic UNIQUE/PK index). Drives
    /// uniqueness enforcement for standalone/partial/expression indexes, which
    /// the inline-constraint `TableMeta::unique` sets do not cover.
    unique: bool,
}

impl Connection {
    /// Run `body` with `outer`'s row pushed as a correlation frame, then pop it
    /// (even on error). The subquery runs with the outer query's parameters.
    fn with_outer_frame<T>(
        &self,
        outer: &EvalCtx,
        body: impl FnOnce(&Params) -> Result<T>,
    ) -> Result<T> {
        self.outer_scope.borrow_mut().push(OuterFrame {
            columns: outer.columns.to_vec(),
            row: outer.row.to_vec(),
            rowid: outer.rowid,
        });
        let params_ptr = outer.params;
        let out = body(params_ptr);
        self.outer_scope.borrow_mut().pop();
        out
    }
}

impl eval::Subqueries for Connection {
    fn last_insert_rowid(&self) -> i64 {
        self.last_insert_rowid.get()
    }
    fn changes(&self) -> i64 {
        self.changes.get()
    }
    fn total_changes(&self) -> i64 {
        self.total_changes.get()
    }
    fn next_random(&self) -> i64 {
        // SplitMix64: advance a 64-bit counter by the golden-ratio increment,
        // then avalanche. Good distribution, tiny state, no_std-friendly, and
        // works from any seed (including 0).
        let s = self.rng_state.get().wrapping_add(0x9E37_79B9_7F4A_7C15);
        self.rng_state.set(s);
        let mut z = s;
        z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
        z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
        z ^= z >> 31;
        z as i64
    }
    fn call_udf(&self, name: &str, args: &[Value]) -> Option<Result<Value>> {
        self.functions.get(name).map(|f| f(args))
    }
    #[cfg(feature = "fts5")]
    fn fts5_bm25(&self, rowid: i64, weights: &[f64]) -> Option<f64> {
        let cell = self.fts5_rank.borrow();
        let (corpus, index) = cell.as_ref()?.bm25.as_ref()?;
        Some(corpus.score(*index.get(&rowid)?, weights))
    }
    #[cfg(feature = "fts5")]
    fn fts5_highlight(&self, col: usize, text: &str, open: &str, close: &str) -> Option<String> {
        let cell = self.fts5_rank.borrow();
        let ctx = cell.as_ref()?;
        // An `UNINDEXED` column carries no matches, so it is returned verbatim.
        if ctx.col_names.get(col).is_some_and(|n| !ctx.col_indexed(n)) {
            return Some(String::from(text));
        }
        Some(crate::vtab::fts5_highlight(
            &ctx.query,
            &ctx.col_names,
            ctx.scope.as_deref(),
            col,
            text,
            ctx.tok,
            open,
            close,
        ))
    }
    #[cfg(feature = "fts5")]
    fn fts5_indexed_columns(&self, table: &str) -> Option<Vec<String>> {
        let (module, args, _) = self.vtab_meta(table).ok()?;
        if !module.eq_ignore_ascii_case("fts5") {
            return None;
        }
        let refs: Vec<&str> = args.iter().map(String::as_str).collect();
        Some(crate::vtab::fts5_indexed_columns(&refs))
    }
    #[cfg(feature = "fts5")]
    fn fts5_tok(&self, table: &str) -> crate::vtab::Fts5Tok {
        let Ok((module, args, _)) = self.vtab_meta(table) else {
            return crate::vtab::Fts5Tok::default();
        };
        if !module.eq_ignore_ascii_case("fts5") {
            return crate::vtab::Fts5Tok::default();
        }
        let refs: Vec<&str> = args.iter().map(String::as_str).collect();
        crate::vtab::fts5_tok_config(&refs)
    }
    #[cfg(feature = "fts5")]
    fn fts5_snippet(
        &self,
        col: i64,
        cols: &[String],
        open: &str,
        close: &str,
        ellipsis: &str,
        ntokens: usize,
    ) -> Option<String> {
        let cell = self.fts5_rank.borrow();
        let ctx = cell.as_ref()?;
        Some(crate::vtab::fts5_snippet(
            &ctx.query,
            &ctx.col_names,
            ctx.scope.as_deref(),
            col,
            cols,
            ctx.indexed.as_deref(),
            ctx.tok,
            open,
            close,
            ellipsis,
            ntokens,
        ))
    }
    fn scalar(&self, select: &Select, outer: &EvalCtx) -> Result<Value> {
        self.with_outer_frame(outer, |params| {
            let r = self.run_select(select, params)?;
            // A scalar subquery must yield exactly one column; sqlite rejects
            // `(SELECT 1, 2)` ("sub-select returns 2 columns - expected 1") rather
            // than silently taking the first. (Row-value / `IN` subqueries use the
            // separate `rows`/`column` paths and may have several columns.)
            if r.columns.len() > 1 {
                return Err(Error::Error(alloc::format!(
                    "sub-select returns {} columns - expected 1",
                    r.columns.len()
                )));
            }
            Ok(r.rows
                .first()
                .and_then(|row| row.first())
                .cloned()
                .unwrap_or(Value::Null))
        })
    }

    fn column(&self, select: &Select, outer: &EvalCtx) -> Result<Vec<Value>> {
        self.with_outer_frame(outer, |params| {
            let r = self.run_select(select, params)?;
            Ok(r.rows
                .into_iter()
                .map(|mut row| {
                    if row.is_empty() {
                        Value::Null
                    } else {
                        row.swap_remove(0)
                    }
                })
                .collect())
        })
    }

    fn column_affinity(&self, select: &Select) -> Option<eval::Affinity> {
        self.row_column_affinities(select)
            .into_iter()
            .next()
            .flatten()
    }

    fn row_column_affinities(&self, select: &Select) -> Vec<Option<eval::Affinity>> {
        // Each output column's affinity: a column inherits its declared affinity,
        // a computed expression has none. Derived from the FROM sources' column
        // metadata (no rows needed for the affinity itself).
        let params = Params::default();
        let Ok((columns, _)) = self.scan_source(select, &params) else {
            return Vec::new();
        };
        let ctx = row_ctx(&[], &columns, None, &params);
        let mut out = Vec::new();
        for col in &select.columns {
            match col {
                ResultColumn::Expr { expr, .. } => out.push(eval::expr_affinity(expr, &ctx)),
                ResultColumn::Wildcard => out.extend(columns.iter().map(|c| Some(c.affinity))),
                ResultColumn::TableWildcard(t) => out.extend(
                    columns
                        .iter()
                        .filter(|c| c.table.eq_ignore_ascii_case(t))
                        .map(|c| Some(c.affinity)),
                ),
            }
        }
        out
    }

    fn rows(&self, select: &Select, outer: &EvalCtx) -> Result<Vec<Vec<Value>>> {
        self.with_outer_frame(outer, |params| Ok(self.run_select(select, params)?.rows))
    }

    fn exists(&self, select: &Select, outer: &EvalCtx) -> Result<bool> {
        self.with_outer_frame(outer, |params| {
            Ok(!self.run_select(select, params)?.rows.is_empty())
        })
    }

    fn resolve_outer(&self, table: Option<&str>, name: &str) -> Option<Value> {
        let scope = self.outer_scope.borrow();
        for frame in scope.iter().rev() {
            // A rowid alias, optionally qualified by the frame's label (e.g.
            // `NEW.rowid`/`OLD.rowid` in a trigger, or `t.rowid` in a correlated
            // subquery). A real column of that name in the frame wins.
            if eval::is_rowid_alias(name) {
                let qualifies = match table {
                    None => true,
                    Some(t) => frame
                        .columns
                        .iter()
                        .any(|c| c.table.eq_ignore_ascii_case(t)),
                };
                let has_real = frame.columns.iter().any(|c| {
                    c.name.eq_ignore_ascii_case(name)
                        && table.is_none_or(|t| c.table.eq_ignore_ascii_case(t))
                });
                if qualifies && !has_real {
                    if let Some(r) = frame.rowid {
                        return Some(Value::Integer(r));
                    }
                }
            }
            for (i, col) in frame.columns.iter().enumerate() {
                let name_ok = col.name.eq_ignore_ascii_case(name);
                let table_ok = table.is_none_or(|t| col.table.eq_ignore_ascii_case(t));
                if name_ok && table_ok {
                    return Some(frame.row[i].clone());
                }
            }
        }
        None
    }
}

/// Whether a value is the given text (used to match `sqlite_schema` columns).
fn is_text(v: &Value, s: &str) -> bool {
    matches!(v, Value::Text(t) if t == s)
}

/// Collect `column = constant` equalities from the top-level `AND` conjuncts of a
/// `WHERE` clause, as `(column index, constant value)` pairs. Used to drive
/// index selection; non-equality and non-constant terms are ignored (the full
/// `WHERE` is still applied afterward).
/// Does `select` (across all its compound arms) read from a source named `name`?
fn references_name(select: &Select, name: &str) -> bool {
    if references_name_select(select, name) {
        return true;
    }
    select
        .compound
        .iter()
        .any(|(_, s)| references_name_select(s, name))
}

/// Does this single `SELECT` arm read from a source named `name` (first table or
/// any joined table)?
fn references_name_select(select: &Select, name: &str) -> bool {
    let Some(from) = &select.from else {
        return false;
    };
    if from.first.name.eq_ignore_ascii_case(name) {
        return true;
    }
    from.joins
        .iter()
        .any(|j| j.table.name.eq_ignore_ascii_case(name))
}

/// Is `e` a bare column reference (ignoring transparent `(…)`/`COLLATE` wrappers)?
/// A scalar subquery projecting one is only foldable with care — it would carry
/// that column's affinity/collation, which a plain literal does not — so the
/// scalar fold excludes this case.
fn is_bare_column_expr(e: &Expr) -> bool {
    match e {
        Expr::Column { .. } => true,
        Expr::Paren(inner) | Expr::Collate { expr: inner, .. } => is_bare_column_expr(inner),
        _ => false,
    }
}

/// The canonical SQL type name whose declared-type affinity rule
/// (`Affinity::from_type`) round-trips back to `aff` — so a folded bare-column
/// `IN (SELECT col)` can carry the candidate column's affinity through the AST as
/// a type-name `String` (keeping `ast.rs` free of `eval` types).
fn affinity_type_name(aff: eval::Affinity) -> alloc::string::String {
    match aff {
        eval::Affinity::Integer => "INTEGER",
        eval::Affinity::Text => "TEXT",
        eval::Affinity::Real => "REAL",
        eval::Affinity::Numeric => "NUMERIC",
        eval::Affinity::Blob => "BLOB",
    }
    .into()
}

/// Does `e` reference only columns of `quals`/`cols` (its own query's sources),
/// with no bound parameter and no nested subquery? Used to prove a subquery is
/// non-correlated before folding it to a constant. Conservative: any nested
/// subquery, parameter, or out-of-scope column makes it return `false`.
fn expr_is_internal(e: &Expr, quals: &[String], cols: &[String]) -> bool {
    let rec = |x: &Expr| expr_is_internal(x, quals, cols);
    match e {
        Expr::Literal(_) => true,
        // A parameter would need the statement's bindings to evaluate; the fold
        // runs with empty params, so bail and let the normal path handle it.
        Expr::Parameter(_) => false,
        // A nested subquery may itself reference our outer scope; without deeper
        // scope tracking, refuse to prove non-correlation.
        Expr::Subquery(_) | Expr::Exists { .. } | Expr::InSelect { .. } => false,
        Expr::Column { table, column } => match table {
            Some(q) => quals.iter().any(|x| x.eq_ignore_ascii_case(q)),
            None => {
                cols.iter().any(|c| c.eq_ignore_ascii_case(column))
                    || column.eq_ignore_ascii_case("rowid")
                    || column.eq_ignore_ascii_case("_rowid_")
                    || column.eq_ignore_ascii_case("oid")
            }
        },
        Expr::Unary { expr, .. } => rec(expr),
        Expr::Binary { left, right, .. } => rec(left) && rec(right),
        Expr::IsNull { expr, .. } => rec(expr),
        Expr::InList { expr, list, .. } => rec(expr) && list.iter().all(rec),
        Expr::Between {
            expr, low, high, ..
        } => rec(expr) && rec(low) && rec(high),
        Expr::Case {
            operand,
            when_then,
            else_result,
        } => {
            operand.as_deref().map(rec).unwrap_or(true)
                && when_then.iter().all(|(w, t)| rec(w) && rec(t))
                && else_result.as_deref().map(rec).unwrap_or(true)
        }
        Expr::Cast { expr, .. } => rec(expr),
        Expr::Paren(inner) => rec(inner),
        Expr::Collate { expr, .. } => rec(expr),
        Expr::RowValue(items) => items.iter().all(rec),
        // A window function would not compile on the VDBE anyway; a non-windowed
        // call is internal when its arguments and `FILTER` are.
        Expr::Function {
            args,
            filter,
            order_by,
            over,
            ..
        } => {
            over.is_none()
                && args.iter().all(rec)
                && filter.as_deref().map(rec).unwrap_or(true)
                && order_by.iter().all(|t| rec(&t.expr))
        }
    }
}

/// Compare two ordering-key vectors with per-position `descending` flags
/// (missing flags default to ascending).
fn cmp_keys(a: &[Value], b: &[Value], desc: &[bool]) -> core::cmp::Ordering {
    use core::cmp::Ordering;
    for (i, (x, y)) in a.iter().zip(b).enumerate() {
        let o = cmp_order(
            x,
            y,
            desc.get(i).copied().unwrap_or(false),
            None,
            crate::value::Collation::Binary,
        );
        if o != Ordering::Equal {
            return o;
        }
    }
    Ordering::Equal
}

/// Compare two `ORDER BY` key values honoring `DESC` and NULL placement. NULL
/// ordering follows the explicit `NULLS FIRST`/`LAST` when given, else SQLite's
/// default (NULLs first under `ASC`, last under `DESC`); the non-NULL comparison
/// uses the column collation and is reversed by `DESC`.
pub(crate) fn cmp_order(
    a: &Value,
    b: &Value,
    descending: bool,
    nulls_first: Option<bool>,
    coll: crate::value::Collation,
) -> core::cmp::Ordering {
    use core::cmp::Ordering;
    let a_null = matches!(a, Value::Null);
    let b_null = matches!(b, Value::Null);
    let nulls_first = nulls_first.unwrap_or(!descending);
    match (a_null, b_null) {
        (true, true) => Ordering::Equal,
        (true, false) => {
            if nulls_first {
                Ordering::Less
            } else {
                Ordering::Greater
            }
        }
        (false, true) => {
            if nulls_first {
                Ordering::Greater
            } else {
                Ordering::Less
            }
        }
        (false, false) => {
            let ord = crate::value::cmp_values_coll(a, b, coll);
            if descending {
                ord.reverse()
            } else {
                ord
            }
        }
    }
}

/// The `[start, end)` frame indices (into the ordered partition) for position
/// `p`, given peer-group ids `gid` and the window `spec`.
///
/// With no explicit frame: the whole partition when there is no `ORDER BY`, else
/// `UNBOUNDED PRECEDING` through the current row's last peer — SQLite's default.
/// `ROWS` frames use physical offsets; `RANGE`/`GROUPS` use peer-group offsets.
/// Resolve a window function's `OVER name` (or `OVER (name …)`) reference against
/// the query's `WINDOW name AS (…)` definitions, returning a clone of `wexpr`
/// whose spec is the effective one. A spec with no `base_name` is returned as-is.
fn resolve_window_ref(wexpr: &Expr, defs: &[(String, WindowSpec)]) -> Result<Expr> {
    let Expr::Function {
        name,
        distinct,
        args,
        star,
        filter,
        order_by,
        over: Some(spec),
    } = wexpr
    else {
        return Ok(wexpr.clone());
    };
    let Some(base) = &spec.base_name else {
        return Ok(wexpr.clone());
    };
    let def = defs
        .iter()
        .find(|(n, _)| n.eq_ignore_ascii_case(base))
        .map(|(_, s)| s)
        .ok_or_else(|| Error::Error(alloc::format!("no such window: {base}")))?;
    // The named window provides PARTITION BY; the referencing use may add ORDER BY
    // and a frame when the base omits them.
    let effective = WindowSpec {
        partition_by: def.partition_by.clone(),
        order_by: if spec.order_by.is_empty() {
            def.order_by.clone()
        } else {
            spec.order_by.clone()
        },
        frame: spec.frame.clone().or_else(|| def.frame.clone()),
        base_name: None,
    };
    Ok(Expr::Function {
        name: name.clone(),
        distinct: *distinct,
        args: args.clone(),
        star: *star,
        filter: filter.clone(),
        order_by: order_by.clone(),
        over: Some(effective),
    })
}

/// Emit one `json_each`/`json_tree` row for `node` and return its assigned id.
/// `key` is the member name / array index (None for a top-level scalar or the
/// `json_tree` root); `fullkey`/`path` are the element's path and its parent's.
fn json_emit_node(
    node: &crate::exec::json::Json,
    key: Option<Value>,
    fullkey: &str,
    path: &str,
    parent: Option<i64>,
    next_id: &mut i64,
    rows: &mut Vec<Vec<Value>>,
) -> i64 {
    use crate::exec::json::Json;
    let id = *next_id;
    *next_id += 1;
    let is_container = matches!(node, Json::Object(_) | Json::Array(_));
    let value = node.to_sql();
    let atom = if is_container {
        Value::Null
    } else {
        value.clone()
    };
    rows.push(alloc::vec![
        key.unwrap_or(Value::Null),
        value,
        Value::Text(String::from(node.type_name())),
        atom,
        Value::Integer(id),
        parent.map(Value::Integer).unwrap_or(Value::Null),
        Value::Text(String::from(fullkey)),
        Value::Text(String::from(path)),
    ]);
    id
}

/// `json_each`: emit a row for each *direct* child of `root` (or a single row for
/// a scalar root). `root_path` is the document path `root` sits at (`"$"`, or the
/// `json_each(x, path)` argument), used as the prefix of each child's `fullkey`.
fn json_each_children(
    root: &crate::exec::json::Json,
    root_path: &str,
    next_id: &mut i64,
    rows: &mut Vec<Vec<Value>>,
) {
    use crate::exec::json::Json;
    match root {
        Json::Object(members) => {
            for (k, v) in members {
                let fullkey = alloc::format!("{root_path}.{k}");
                json_emit_node(
                    v,
                    Some(Value::Text(k.clone())),
                    &fullkey,
                    root_path,
                    None,
                    next_id,
                    rows,
                );
            }
        }
        Json::Array(items) => {
            for (i, v) in items.iter().enumerate() {
                let fullkey = alloc::format!("{root_path}[{i}]");
                json_emit_node(
                    v,
                    Some(Value::Integer(i as i64)),
                    &fullkey,
                    root_path,
                    None,
                    next_id,
                    rows,
                );
            }
        }
        scalar => {
            json_emit_node(scalar, None, root_path, root_path, None, next_id, rows);
        }
    }
}

/// Split a JSON path (`$.a.b`, `$.a[2]`, `$[0]`) into its parent path and the
/// final component rendered as a `json_tree` root key (a text member name or an
/// integer array index). The bare root `$` yields `("$", None)`.
fn split_json_path(path: &str) -> (alloc::string::String, Option<Value>) {
    if path.ends_with(']') {
        if let Some(open) = path.rfind('[') {
            if let Ok(i) = path[open + 1..path.len() - 1].parse::<i64>() {
                return (String::from(&path[..open]), Some(Value::Integer(i)));
            }
        }
    }
    if let Some(dot) = path.rfind('.') {
        let name = path[dot + 1..].trim_matches('"');
        return (
            String::from(&path[..dot]),
            Some(Value::Text(String::from(name))),
        );
    }
    (String::from(path), None)
}

/// `json_tree`: emit `node` then recurse depth-first into its children.
fn json_tree_walk(
    node: &crate::exec::json::Json,
    key: Option<Value>,
    fullkey: &str,
    path: &str,
    parent: Option<i64>,
    next_id: &mut i64,
    rows: &mut Vec<Vec<Value>>,
) {
    use crate::exec::json::Json;
    let id = json_emit_node(node, key, fullkey, path, parent, next_id, rows);
    match node {
        Json::Object(members) => {
            for (k, v) in members {
                let child = alloc::format!("{fullkey}.{k}");
                json_tree_walk(
                    v,
                    Some(Value::Text(k.clone())),
                    &child,
                    fullkey,
                    Some(id),
                    next_id,
                    rows,
                );
            }
        }
        Json::Array(items) => {
            for (i, v) in items.iter().enumerate() {
                let child = alloc::format!("{fullkey}[{i}]");
                json_tree_walk(
                    v,
                    Some(Value::Integer(i as i64)),
                    &child,
                    fullkey,
                    Some(id),
                    next_id,
                    rows,
                );
            }
        }
        _ => {}
    }
}

fn frame_bounds(
    p: usize,
    m: usize,
    gid: &[usize],
    spec: &WindowSpec,
    ovals: &[Value],
    desc: bool,
) -> (usize, usize) {
    let Some(frame) = &spec.frame else {
        if spec.order_by.is_empty() {
            return (0, m);
        }
        // Default: UNBOUNDED PRECEDING .. CURRENT ROW (peers included).
        let mut e = p + 1;
        while e < m && gid[e] == gid[p] {
            e += 1;
        }
        return (0, e);
    };
    let (start, end) = match frame.mode {
        FrameMode::Rows => (
            row_bound(&frame.start, p, m, true),
            row_bound(&frame.end, p, m, false),
        ),
        // RANGE with a numeric offset bounds the frame by the ORDER BY *value*
        // (within `value ± n`); CURRENT ROW / UNBOUNDED still use peer groups.
        FrameMode::Range
            if !ovals.is_empty()
                && (matches!(
                    frame.start,
                    FrameBound::Preceding(_) | FrameBound::Following(_)
                ) || matches!(
                    frame.end,
                    FrameBound::Preceding(_) | FrameBound::Following(_)
                )) =>
        {
            (
                range_value_bound(&frame.start, p, m, gid, ovals, desc, true),
                range_value_bound(&frame.end, p, m, gid, ovals, desc, false),
            )
        }
        FrameMode::Range | FrameMode::Groups => (
            group_bound(&frame.start, p, m, gid, true),
            group_bound(&frame.end, p, m, gid, false),
        ),
    };
    let start = start.min(m);
    (start, end.min(m).max(start))
}

/// A `RANGE` frame bound measured by the ORDER BY value: the frame includes rows
/// whose value is within `[value - start_n, value + end_n]` (signs flipped for a
/// `DESC` ordering). `CURRENT ROW` and `UNBOUNDED` fall back to peer-group edges.
/// Falls back to peer-group edges if the current value is not numeric.
fn range_value_bound(
    b: &FrameBound,
    p: usize,
    m: usize,
    gid: &[usize],
    ovals: &[Value],
    desc: bool,
    is_start: bool,
) -> usize {
    // A NULL current value has no numeric range: NULLs form their own peer group,
    // so a PRECEDING/FOLLOWING offset collapses to the current (NULL) peer group
    // rather than spanning into the adjacent value groups — matching sqlite.
    // (UNBOUNDED bounds are handled below and stay unbounded.)
    if matches!(
        b,
        FrameBound::CurrentRow | FrameBound::Preceding(_) | FrameBound::Following(_)
    ) && matches!(ovals[p], Value::Null)
    {
        return group_bound(&FrameBound::CurrentRow, p, m, gid, is_start);
    }
    let val = eval::to_f64(&ovals[p]);
    // The frame edge as an ORDER BY value. Under ASC, PRECEDING subtracts and
    // FOLLOWING adds; under DESC the sequence decreases so the signs flip.
    let threshold = match b {
        FrameBound::UnboundedPreceding => return 0,
        FrameBound::UnboundedFollowing => return m,
        FrameBound::CurrentRow => val,
        FrameBound::Preceding(n) => {
            if desc {
                val + *n as f64
            } else {
                val - *n as f64
            }
        }
        FrameBound::Following(n) => {
            if desc {
                val - *n as f64
            } else {
                val + *n as f64
            }
        }
    };
    // Values run ascending (ASC) or descending (DESC) across positions. The frame
    // is the contiguous span of rows on the inclusive side of `threshold`.
    let inside = |vk: f64, edge: f64| if desc { vk >= edge } else { vk <= edge };
    if is_start {
        // First row at/after the start edge.
        (0..m)
            .find(|&k| {
                !matches!(ovals[k], Value::Null) && {
                    let vk = eval::to_f64(&ovals[k]);
                    if desc {
                        vk <= threshold
                    } else {
                        vk >= threshold
                    }
                }
            })
            .unwrap_or(m)
    } else {
        // One past the last *non-NULL* row at/before the end edge. NULL rows are
        // never in a numeric range frame, so trailing NULLs (which sort last under
        // DESC) must not extend the end — track the last in-frame row instead of
        // defaulting to `m`.
        let mut e = 0;
        for (k, ov) in ovals.iter().enumerate().take(m) {
            if matches!(ov, Value::Null) {
                continue;
            }
            if inside(eval::to_f64(ov), threshold) {
                e = k + 1;
            } else {
                break;
            }
        }
        e
    }
}

/// A `ROWS` frame bound as an index; `is_start` selects inclusive-start vs
/// exclusive-end semantics.
fn row_bound(b: &FrameBound, p: usize, m: usize, is_start: bool) -> usize {
    match (b, is_start) {
        (FrameBound::UnboundedPreceding, _) => 0,
        (FrameBound::UnboundedFollowing, _) => m,
        (FrameBound::CurrentRow, true) => p,
        (FrameBound::CurrentRow, false) => p + 1,
        (FrameBound::Preceding(n), true) => p.saturating_sub(*n as usize),
        (FrameBound::Preceding(n), false) => (p + 1).saturating_sub(*n as usize),
        (FrameBound::Following(n), true) => (p + *n as usize).min(m),
        (FrameBound::Following(n), false) => (p + 1 + *n as usize).min(m),
    }
}

/// A `RANGE`/`GROUPS` frame bound, measured in peer groups.
fn group_bound(b: &FrameBound, p: usize, m: usize, gid: &[usize], is_start: bool) -> usize {
    let maxg = if m == 0 { 0 } else { gid[m - 1] as i64 };
    let target = |g: i64| -> i64 { gid[p] as i64 + g };
    // First ordered index of peer-group `g` (clamped: below 0 -> 0, above max -> m).
    let first_of = |g: i64| -> usize {
        if g < 0 {
            0
        } else if g > maxg {
            m
        } else {
            (0..m).find(|&i| gid[i] as i64 == g).unwrap_or(m)
        }
    };
    // One past the last ordered index of peer-group `g` (same clamping).
    let after_last_of = |g: i64| -> usize {
        if g < 0 {
            0
        } else if g > maxg {
            m
        } else {
            (0..m)
                .rev()
                .find(|&i| gid[i] as i64 == g)
                .map_or(0, |i| i + 1)
        }
    };
    match (b, is_start) {
        (FrameBound::UnboundedPreceding, _) => 0,
        (FrameBound::UnboundedFollowing, _) => m,
        (FrameBound::CurrentRow, true) => first_of(target(0)),
        (FrameBound::CurrentRow, false) => after_last_of(target(0)),
        (FrameBound::Preceding(n), true) => first_of(target(-(*n))),
        (FrameBound::Preceding(n), false) => after_last_of(target(-(*n))),
        (FrameBound::Following(n), true) => first_of(target(*n)),
        (FrameBound::Following(n), false) => after_last_of(target(*n)),
    }
}

/// The 1-based `ntile` bucket for ordered position `p` of `m` rows split into
/// `buckets` groups (earlier groups absorb the remainder).
fn ntile_bucket(p: usize, m: usize, buckets: i64) -> i64 {
    let buckets = (buckets.max(1) as usize).min(m.max(1));
    let size = m / buckets;
    let rem = m % buckets;
    let big = rem * (size + 1);
    if p < big {
        (p / (size + 1)) as i64 + 1
    } else {
        (rem + (p - big) / size.max(1)) as i64 + 1
    }
}

/// Evaluate an aggregate window function over a frame of per-row argument
/// values, matching `compute_aggregate`'s numeric semantics.
fn window_aggregate(lname: &str, star: bool, frame: &[&Vec<Value>]) -> Result<Value> {
    let mut vals: Vec<Value> = Vec::new();
    for row in frame {
        if star {
            continue;
        }
        if let Some(v) = row.first() {
            if !matches!(v, Value::Null) {
                vals.push(v.clone());
            }
        }
    }
    Ok(match lname {
        "count" => {
            if star {
                Value::Integer(frame.len() as i64)
            } else {
                Value::Integer(vals.len() as i64)
            }
        }
        "sum" => {
            if vals.is_empty() {
                Value::Null
            } else if vals.iter().all(|v| matches!(v, Value::Integer(_))) {
                let mut acc: i64 = 0;
                let mut overflow = false;
                for v in &vals {
                    if let Value::Integer(i) = v {
                        match acc.checked_add(*i) {
                            Some(s) => acc = s,
                            None => {
                                overflow = true;
                                break;
                            }
                        }
                    }
                }
                if overflow {
                    Value::Real(vals.iter().map(eval::to_f64).sum())
                } else {
                    Value::Integer(acc)
                }
            } else {
                Value::Real(vals.iter().map(eval::to_f64).sum())
            }
        }
        "total" => Value::Real(vals.iter().map(eval::to_f64).sum()),
        "avg" => {
            if vals.is_empty() {
                Value::Null
            } else {
                let sum: f64 = vals.iter().map(eval::to_f64).sum();
                Value::Real(sum / vals.len() as f64)
            }
        }
        "min" => vals
            .into_iter()
            .reduce(|a, b| {
                if eval::compare(&b, &a) == core::cmp::Ordering::Less {
                    b
                } else {
                    a
                }
            })
            .unwrap_or(Value::Null),
        "max" => vals
            .into_iter()
            .reduce(|a, b| {
                if eval::compare(&b, &a) == core::cmp::Ordering::Greater {
                    b
                } else {
                    a
                }
            })
            .unwrap_or(Value::Null),
        "group_concat" | "string_agg" => {
            if vals.is_empty() {
                Value::Null
            } else {
                // The optional 2nd argument is the separator (default ","), the
                // same for every row of the frame.
                let sep = frame
                    .first()
                    .and_then(|r| r.get(1))
                    .map(eval::to_text)
                    .unwrap_or_else(|| String::from(","));
                let parts: Vec<String> = vals.iter().map(eval::to_text).collect();
                Value::Text(parts.join(&sep))
            }
        }
        _ => return Err(Error::Unsupported("window function")),
    })
}

/// Dedupe rows in place, preserving first-occurrence order.
fn dedup_rows(rows: &mut Vec<Vec<Value>>) {
    let mut seen: Vec<Vec<Value>> = Vec::new();
    rows.retain(|row| {
        if seen.iter().any(|s| rows_equal(s, row)) {
            false
        } else {
            seen.push(row.clone());
            true
        }
    });
}

/// A `PRAGMA name = value` argument as text (a bare keyword like `WAL` or a
/// quoted string).
fn pragma_text(e: &Expr) -> String {
    match e {
        Expr::Column { column, .. } => column.clone(),
        Expr::Literal(Literal::Str(s)) => s.clone(),
        _ => String::new(),
    }
}

/// Interpret a `PRAGMA name = value` argument as a boolean, accepting
/// `1`/`0`, `on`/`off`, `yes`/`no`, `true`/`false`.
fn pragma_truth(e: &Expr, params: &Params) -> bool {
    match e {
        Expr::Column { column, .. } => {
            matches!(column.to_ascii_lowercase().as_str(), "on" | "yes" | "true")
        }
        Expr::Literal(Literal::Str(s)) => {
            matches!(s.to_ascii_lowercase().as_str(), "on" | "yes" | "true" | "1")
        }
        _ => eval::eval(e, &EvalCtx::rowless(params))
            .map(|v| eval::to_i64(&v) != 0)
            .unwrap_or(false),
    }
}

/// The EXPLAIN QUERY PLAN display label for a table reference: SQLite shows
/// `name AS alias` when an alias is present, else just the name.
fn eqp_label(t: &TableRef) -> String {
    match &t.alias {
        Some(a) => alloc::format!("{} AS {}", t.name, a),
        None => t.name.clone(),
    }
}

/// Whether every column the `WHERE` expression references is covered by the
/// index (`idx_cols`) or is the rowid — the seek-covering precondition. Walks the
/// expression tree and returns `false` the moment it finds an uncovered column,
/// an unknown column name that is not a rowid alias, or a construct whose columns
/// can't be enumerated locally (a scalar subquery / `EXISTS` / `IN (SELECT …)`),
/// so the caller conservatively falls back to the table-fetch path.
/// Is a partial index's predicate guaranteed by a top-level conjunct of the
/// `WHERE`? Always true for a non-partial index.
fn partial_pred_guaranteed(idx: &IndexMeta, where_expr: &Expr) -> bool {
    match &idx.partial {
        None => true,
        Some(pred) => {
            let mut conjuncts = Vec::new();
            and_conjuncts(where_expr, &mut conjuncts);
            conjuncts.iter().any(|c| expr_eq_modulo_parens(c, pred))
        }
    }
}

/// Find a conjunct `<key_expr> IN (const, …)` (walking top-level `AND`s) and
/// return the evaluated list values — the expression-index analogue of
/// [`find_in_constraint`].
fn find_expr_in_values(key_expr: &Expr, e: &Expr, params: &Params) -> Option<Vec<Value>> {
    match e {
        Expr::Binary {
            op: BinaryOp::And,
            left,
            right,
        } => find_expr_in_values(key_expr, left, params)
            .or_else(|| find_expr_in_values(key_expr, right, params)),
        Expr::Paren(inner) => find_expr_in_values(key_expr, inner, params),
        Expr::InList {
            expr,
            list,
            negated: false,
            ..
        } => {
            if list.is_empty() || !expr_eq_modulo_parens(expr, key_expr) {
                return None;
            }
            let mut vals = Vec::with_capacity(list.len());
            for item in list {
                vals.push(const_value(item, params)?);
            }
            Some(vals)
        }
        _ => None,
    }
}

/// The executor's [`VTabStore`] implementation: a persistent virtual table's
/// backing `<vtab>_data` regular table, read/written through the normal table
/// machinery. Built (with the module taken out of the registry, so
/// `&mut Connection` doesn't alias the borrowed module) for one `update` call.
struct ExecVTabStore<'a> {
    conn: &'a mut Connection,
    backing: &'a str,
    /// The backing table leads with an `INTEGER PRIMARY KEY` `id` column (FTS5's
    /// `_content`), stored as a NULL placeholder serial (the rowid is the b-tree
    /// key). Module values are the columns after `id`, so prepend a NULL on write
    /// and drop the leading value on read.
    ipk_prefix: bool,
}

impl VTabStore for ExecVTabStore<'_> {
    fn rows(&self) -> Result<Vec<(i64, Vec<Value>)>> {
        let meta = self.conn.table_meta(self.backing, None)?;
        let mut rows = self.conn.scan_table(&meta)?;
        if self.ipk_prefix {
            for (_, values) in &mut rows {
                if !values.is_empty() {
                    values.remove(0);
                }
            }
        }
        Ok(rows)
    }
    fn put(&mut self, rowid: i64, values: &[Value]) -> Result<()> {
        let root = self.conn.table_meta(self.backing, None)?.root;
        let payload = if self.ipk_prefix {
            let mut row = alloc::vec![Value::Null];
            row.extend_from_slice(values);
            encode_record(&row)
        } else {
            encode_record(values)
        };
        let w = self.conn.backend.writer()?;
        // Replace semantics: drop any existing row, then insert.
        crate::btree::delete_table(w, root, rowid)?;
        crate::btree::insert_table(w, root, rowid, &payload)?;
        Ok(())
    }
    fn delete(&mut self, rowid: i64) -> Result<()> {
        let root = self.conn.table_meta(self.backing, None)?.root;
        let w = self.conn.backend.writer()?;
        crate::btree::delete_table(w, root, rowid)?;
        Ok(())
    }
}

/// Flip a comparison operator for a swapped operand order: `a < b` ⇔ `b > a`.
/// Non-ordering operators are returned unchanged.
fn mirror_comparison(op: BinaryOp) -> BinaryOp {
    match op {
        BinaryOp::Lt => BinaryOp::Gt,
        BinaryOp::LtEq => BinaryOp::GtEq,
        BinaryOp::Gt => BinaryOp::Lt,
        BinaryOp::GtEq => BinaryOp::LtEq,
        other => other,
    }
}

fn where_cols_covered(e: &Expr, meta: &TableMeta, idx_cols: &[usize]) -> bool {
    let covered = |ci: usize| idx_cols.contains(&ci) || meta.ipk == Some(ci);
    match e {
        Expr::Literal(_) | Expr::Parameter(_) => true,
        Expr::Column { column, .. } => match meta
            .columns
            .iter()
            .position(|c| c.name.eq_ignore_ascii_case(column))
        {
            Some(ci) => covered(ci),
            None => matches!(
                column.to_ascii_lowercase().as_str(),
                "rowid" | "_rowid_" | "oid"
            ),
        },
        Expr::Unary { expr, .. }
        | Expr::IsNull { expr, .. }
        | Expr::Cast { expr, .. }
        | Expr::Collate { expr, .. }
        | Expr::Paren(expr) => where_cols_covered(expr, meta, idx_cols),
        Expr::Binary { left, right, .. } => {
            where_cols_covered(left, meta, idx_cols) && where_cols_covered(right, meta, idx_cols)
        }
        Expr::Between {
            expr, low, high, ..
        } => {
            where_cols_covered(expr, meta, idx_cols)
                && where_cols_covered(low, meta, idx_cols)
                && where_cols_covered(high, meta, idx_cols)
        }
        Expr::InList { expr, list, .. } => {
            where_cols_covered(expr, meta, idx_cols)
                && list.iter().all(|x| where_cols_covered(x, meta, idx_cols))
        }
        Expr::RowValue(items) => items.iter().all(|x| where_cols_covered(x, meta, idx_cols)),
        Expr::Function {
            args, filter, over, ..
        } => {
            over.is_none()
                && filter.is_none()
                && args.iter().all(|x| where_cols_covered(x, meta, idx_cols))
        }
        Expr::Case {
            operand,
            when_then,
            else_result,
        } => {
            operand
                .as_deref()
                .map(|o| where_cols_covered(o, meta, idx_cols))
                .unwrap_or(true)
                && when_then.iter().all(|(w, t)| {
                    where_cols_covered(w, meta, idx_cols) && where_cols_covered(t, meta, idx_cols)
                })
                && else_result
                    .as_deref()
                    .map(|x| where_cols_covered(x, meta, idx_cols))
                    .unwrap_or(true)
        }
        // A subquery may read other tables/columns we can't enumerate here; bail.
        Expr::Subquery(_) | Expr::Exists { .. } | Expr::InSelect { .. } => false,
    }
}

/// Gather the virtual-table constraints to offer `best_index` from a query's
/// `WHERE`, plus, in lockstep, each constraint's bound right-hand [`Value`].
///
/// Walks the top-level `AND` conjuncts looking for `col <op> const` comparisons
/// (and `BETWEEN`, expanded to a `>=`/`<=` pair) where `col` is one of this
/// table's `columns` and the other side is row-independent. The returned
/// `(constraints, values)` vectors are parallel: `values[i]` is the evaluated
/// bound of `constraints[i]`. Only the comparison *shape* goes to the module (as
/// SQLite does); the values are held back and handed to `filter` per the plan's
/// `argv_index`.
/// Whether a WHERE clause contains a `rowid = <const>` term (rowid/`_rowid_`/`oid`)
/// in its `AND` tree — used to report FTS5's `INDEX 0:=` rowid-lookup plan.
#[cfg(feature = "fts5")]
fn fts5_rowid_eq(expr: &Expr, params: &Params) -> bool {
    let is_rowid = |e: &Expr| {
        matches!(e, Expr::Column { column, .. }
            if matches!(column.to_ascii_lowercase().as_str(), "rowid" | "_rowid_" | "oid"))
    };
    match expr {
        Expr::Binary {
            op: BinaryOp::Eq,
            left,
            right,
        } => {
            (is_rowid(left) && const_value(right, params).is_some())
                || (is_rowid(right) && const_value(left, params).is_some())
        }
        Expr::Binary {
            op: BinaryOp::And,
            left,
            right,
        } => fts5_rowid_eq(left, params) || fts5_rowid_eq(right, params),
        Expr::Paren(e) => fts5_rowid_eq(e, params),
        _ => false,
    }
}

fn collect_vtab_constraints(
    sel: &Select,
    columns: &[ColumnInfo],
    params: &Params,
) -> (Vec<IndexConstraint>, Vec<Value>) {
    let mut constraints = Vec::new();
    let mut values = Vec::new();
    let Some(where_expr) = &sel.where_clause else {
        return (constraints, values);
    };
    let mut conjuncts = Vec::new();
    and_conjuncts(where_expr, &mut conjuncts);
    let mut push = |col: usize, op: ConstraintOp, v: Value| {
        constraints.push(IndexConstraint {
            column: col,
            op,
            usable: true,
        });
        values.push(v);
    };
    for c in conjuncts {
        match c {
            Expr::Binary { op, left, right }
                if matches!(
                    op,
                    BinaryOp::Eq | BinaryOp::Lt | BinaryOp::LtEq | BinaryOp::Gt | BinaryOp::GtEq
                ) =>
            {
                if let (Some(ci), Some(v)) = (col_index(left, columns), const_value(right, params))
                {
                    if let Some(cop) = binop_to_constraint(*op) {
                        push(ci, cop, v);
                    }
                } else if let (Some(ci), Some(v)) =
                    (col_index(right, columns), const_value(left, params))
                {
                    if let Some(cop) = binop_to_constraint(flip_cmp(*op)) {
                        push(ci, cop, v);
                    }
                }
            }
            Expr::Between {
                expr,
                low,
                high,
                negated: false,
            } => {
                if let Some(ci) = col_index(expr, columns) {
                    if let Some(v) = const_value(low, params) {
                        push(ci, ConstraintOp::Ge, v);
                    }
                    if let Some(v) = const_value(high, params) {
                        push(ci, ConstraintOp::Le, v);
                    }
                }
            }
            _ => {}
        }
    }
    (constraints, values)
}

/// Map a comparison [`BinaryOp`] to a vtab [`ConstraintOp`], or `None` for a
/// non-comparison operator.
fn binop_to_constraint(op: BinaryOp) -> Option<ConstraintOp> {
    Some(match op {
        BinaryOp::Eq => ConstraintOp::Eq,
        BinaryOp::Lt => ConstraintOp::Lt,
        BinaryOp::LtEq => ConstraintOp::Le,
        BinaryOp::Gt => ConstraintOp::Gt,
        BinaryOp::GtEq => ConstraintOp::Ge,
        _ => return None,
    })
}

/// Order the bound constraint `values` by the plan's 1-based `argv_index`, the
/// argument vector handed to [`crate::vtab::VTabModule::filter`].
///
/// `argv_index[i]` is the position (1-based) the module wants `values[i]` passed
/// at, or `0` to drop it. A robust pass: collect `(pos, value)` for every nonzero
/// entry, sort by `pos`, and emit the values. Gaps or duplicate positions are
/// tolerated (the module decides what its own positions mean).
fn order_vtab_argv(plan: &IndexPlan, values: &[Value]) -> Vec<Value> {
    let mut slots: Vec<(u32, Value)> = plan
        .argv_index
        .iter()
        .zip(values.iter())
        .filter(|(pos, _)| **pos != 0)
        .map(|(pos, v)| (*pos, v.clone()))
        .collect();
    slots.sort_by_key(|(pos, _)| *pos);
    slots.into_iter().map(|(_, v)| v).collect()
}

fn collect_eq_constraints(
    e: &Expr,
    columns: &[ColumnInfo],
    params: &Params,
    out: &mut Vec<(usize, Value)>,
) {
    match e {
        Expr::Binary {
            op: BinaryOp::And,
            left,
            right,
        } => {
            collect_eq_constraints(left, columns, params, out);
            collect_eq_constraints(right, columns, params, out);
        }
        Expr::Paren(inner) => collect_eq_constraints(inner, columns, params, out),
        Expr::Binary {
            op: BinaryOp::Eq,
            left,
            right,
        } => {
            if let (Some(ci), Some(v)) = (col_index(left, columns), const_value(right, params)) {
                out.push((ci, v));
            } else if let (Some(ci), Some(v)) =
                (col_index(right, columns), const_value(left, params))
            {
                out.push((ci, v));
            }
        }
        _ => {}
    }
}

/// Strip redundant outer parentheses from an expression, so structural
/// comparison ignores grouping (`(active = 1)` ≡ `active = 1`).
fn unparen(e: &Expr) -> &Expr {
    let mut cur = e;
    while let Expr::Paren(inner) = cur {
        cur = inner;
    }
    cur
}

/// Two expressions are equal modulo redundant parentheses. Used to match a
/// partial-index predicate (or an expression-index key) against a query's
/// `WHERE` structurally — this is the conservative rule (no general implication),
/// so it only recurses through `Paren`; everything else uses derived `PartialEq`.
fn expr_eq_modulo_parens(a: &Expr, b: &Expr) -> bool {
    unparen(a) == unparen(b)
}

/// Collect the top-level `AND` conjuncts of `e` (descending through `Paren` and
/// `AND` nodes), pushing each non-`AND` leaf as a borrowed reference.
fn and_conjuncts<'e>(e: &'e Expr, out: &mut Vec<&'e Expr>) {
    match unparen(e) {
        Expr::Binary {
            op: BinaryOp::And,
            left,
            right,
        } => {
            and_conjuncts(left, out);
            and_conjuncts(right, out);
        }
        other => out.push(other),
    }
}

/// A hash-join bucket key. Over-keying (one value yielding several keys) is safe:
/// the join's full `ON` predicate is re-evaluated on every candidate, so extra
/// keys only cost comparisons — they never drop a real match.
#[derive(PartialEq, Eq, PartialOrd, Ord)]
enum JoinKey {
    /// Numeric value, keyed by canonical `f64` bits (so `5` and `5.0` collide).
    Num(u64),
    /// Text value (exact bytes).
    Text(String),
    /// Blob value.
    Blob(Vec<u8>),
}

/// Canonical bits for a number, normalizing `-0.0` to `0.0` so the two compare
/// equal (as they do in SQL).
fn num_bits(f: f64) -> u64 {
    (if f == 0.0 { 0.0 } else { f }).to_bits()
}

/// The set of hash-join keys a value participates in. A numeric value keys by its
/// number *and* its text form; text that parses as a number keys by both too — so
/// affinity-driven cross-type equality (`5 = '5'`) never misses (the `ON` re-eval
/// rejects the spurious ones). `NULL` keys nothing (it never equi-joins).
fn join_keys_of(v: &Value) -> Vec<JoinKey> {
    match v {
        Value::Null => Vec::new(),
        Value::Integer(i) => alloc::vec![
            JoinKey::Num(num_bits(*i as f64)),
            JoinKey::Text(i.to_string())
        ],
        Value::Real(r) => {
            alloc::vec![
                JoinKey::Num(num_bits(*r)),
                JoinKey::Text(eval::format_real(*r))
            ]
        }
        Value::Text(s) => {
            let mut keys = alloc::vec![JoinKey::Text(s.clone())];
            match eval::to_number(&Value::Text(s.clone())) {
                Value::Integer(i) => keys.push(JoinKey::Num(num_bits(i as f64))),
                Value::Real(r) => keys.push(JoinKey::Num(num_bits(r))),
                _ => {}
            }
            keys
        }
        Value::Blob(b) => alloc::vec![JoinKey::Blob(b.clone())],
    }
}

/// Promote a comma join's filtering equality from `WHERE` into its `ON`, so the
/// common `FROM a, b WHERE a.x = b.y` pattern can use the same hash/index seek
/// path (and EXPLAIN QUERY PLAN node) as `a JOIN b ON a.x = b.y`. The equality is
/// *copied*, not moved — it stays in `WHERE` — so the result is unchanged: the
/// `ON` is a subset of `WHERE`, applied redundantly. Only a qualified
/// `t.col = u.col` equality linking the joined table to an already-introduced one
/// is promoted. Returns the rewritten `Select`, or `None` if nothing applied.
fn promote_comma_join_ons(sel: &Select) -> Option<Select> {
    let from = sel.from.as_ref()?;
    let where_clause = sel.where_clause.as_ref()?;
    let promotable = |j: &Join| {
        j.on.is_none() && !j.natural && j.using.is_empty() && matches!(j.kind, JoinKind::Inner)
    };
    if !from.joins.iter().any(promotable) {
        return None;
    }
    let mut conjuncts: Vec<&Expr> = Vec::new();
    and_conjuncts(where_clause, &mut conjuncts);
    let label = |t: &TableRef| t.alias.clone().unwrap_or_else(|| t.name.clone());
    let mut available: Vec<String> = alloc::vec![label(&from.first)];
    let mut new_joins = from.joins.clone();
    let mut changed = false;
    for (i, join) in from.joins.iter().enumerate() {
        let jlabel = label(&join.table);
        if promotable(join) {
            if let Some(cond) = conjuncts
                .iter()
                .find_map(|c| eligible_join_equi(c, &jlabel, &available))
            {
                new_joins[i].on = Some(cond);
                changed = true;
            }
        }
        available.push(jlabel);
    }
    if !changed {
        return None;
    }
    let mut new_sel = sel.clone();
    new_sel.from = Some(FromClause {
        first: from.first.clone(),
        joins: new_joins,
    });
    Some(new_sel)
}

/// A qualified `A.x = B.y` equality where one qualifier is `jlabel` and the other
/// is in `available` — eligible to become a comma join's `ON`. Returns the cloned
/// equality (with any enclosing parens stripped).
fn eligible_join_equi(c: &Expr, jlabel: &str, available: &[String]) -> Option<Expr> {
    let mut c = c;
    while let Expr::Paren(inner) = c {
        c = inner;
    }
    let (l, r) = match c {
        Expr::Binary {
            op: BinaryOp::Eq,
            left,
            right,
        } => (left.as_ref(), right.as_ref()),
        _ => return None,
    };
    let lt = column_qualifier(l)?;
    let rt = column_qualifier(r)?;
    let here = |t: &str| t.eq_ignore_ascii_case(jlabel);
    let earlier = |t: &str| available.iter().any(|a| a.eq_ignore_ascii_case(t));
    if (here(lt) && earlier(rt)) || (here(rt) && earlier(lt)) {
        Some(c.clone())
    } else {
        None
    }
}

/// The table qualifier of a qualified column reference (`t.col` → `t`).
fn column_qualifier(e: &Expr) -> Option<&str> {
    match e {
        Expr::Column { table: Some(t), .. } => Some(t),
        Expr::Paren(inner) => column_qualifier(inner),
        _ => None,
    }
}

/// Extract a single equi-join `left.col = right.col` from the top-level `AND`
/// conjuncts of an `ON` predicate, returning `(left column index, right column
/// index within the joined table)`. Both columns must use `BINARY` collation
/// (otherwise text equality is collation-sensitive and a hash on exact bytes
/// could miss a match — fall back to the nested loop). `cols` is the combined
/// left+right column list; `left_width` is the number of left columns.
fn join_equi_cols(on: &Expr, cols: &[ColumnInfo], left_width: usize) -> Option<(usize, usize)> {
    match on {
        Expr::Binary {
            op: BinaryOp::And,
            left,
            right,
        } => join_equi_cols(left, cols, left_width)
            .or_else(|| join_equi_cols(right, cols, left_width)),
        Expr::Paren(inner) => join_equi_cols(inner, cols, left_width),
        Expr::Binary {
            op: BinaryOp::Eq,
            left,
            right,
        } => {
            let a = col_index(left, cols)?;
            let b = col_index(right, cols)?;
            let binary = |i: usize| cols[i].collation == crate::value::Collation::Binary;
            let (l, r) = if a < left_width && b >= left_width {
                (a, b)
            } else if b < left_width && a >= left_width {
                (b, a)
            } else {
                return None;
            };
            if binary(l) && binary(r) {
                Some((l, r - left_width))
            } else {
                None
            }
        }
        _ => None,
    }
}

/// Flatten a top-level `OR` chain into its disjuncts (unwrapping parentheses),
/// e.g. `a OR (b OR c)` → `[a, b, c]`. A non-`OR` expression yields itself.
fn flatten_or<'a>(e: &'a Expr, out: &mut Vec<&'a Expr>) {
    match e {
        Expr::Binary {
            op: BinaryOp::Or,
            left,
            right,
        } => {
            flatten_or(left, out);
            flatten_or(right, out);
        }
        Expr::Paren(inner) => flatten_or(inner, out),
        other => out.push(other),
    }
}

/// Find a top-level `column IN (const, const, …)` conjunct (not `NOT IN`, all
/// list entries constant), returning the column index and the constant values.
/// Used to drive per-value index seeks; only the first such term is returned.
fn find_in_constraint(
    e: &Expr,
    columns: &[ColumnInfo],
    params: &Params,
) -> Option<(usize, Vec<Value>)> {
    match e {
        Expr::Binary {
            op: BinaryOp::And,
            left,
            right,
        } => find_in_constraint(left, columns, params)
            .or_else(|| find_in_constraint(right, columns, params)),
        Expr::Paren(inner) => find_in_constraint(inner, columns, params),
        Expr::InList {
            expr,
            list,
            negated: false,
            ..
        } => {
            let ci = col_index(expr, columns)?;
            if list.is_empty() {
                return None;
            }
            let mut vals = Vec::with_capacity(list.len());
            for item in list {
                vals.push(const_value(item, params)?);
            }
            Some((ci, vals))
        }
        _ => None,
    }
}

// ─── R-Tree byte-compatible on-disk node format (D3c) ───────────────────────
//
// SQLite stores an R-Tree as a b-tree of fixed-size nodes in `<name>_node`
// (`nodeno INTEGER PRIMARY KEY, data`), with `<name>_rowid` (rowid → leaf nodeno)
// and `<name>_parent` (node → parent node) maps. A node blob is: 2-byte BE depth
// (the tree height; meaningful only in the root, nodeno 1, else 0) + 2-byte BE
// cell count, then cells, zero-padded to the node size. Each cell is an 8-byte BE
// key (leaf: rowid; interior: child nodeno) followed by `n_coord` 4-byte BE
// coordinates (f32 for `rtree`, i32 for `rtree_i32`), laid out per dimension as
// (min, max).
//
// graphite reuses its M1 reader to get the current entries, applies the
// insert/delete, then BULK-REBUILDS a valid tree and rewrites the three shadow
// tables. SQLite reads any structurally-valid R-Tree (rtreecheck does not require
// a particular shape), so a simple balanced bulk build is byte-readable without
// reproducing SQLite's incremental quadratic-split tree shape.

/// One R-Tree entry / cell: an 8-byte key (rowid or child nodeno) and `2*nDim`
/// coordinates as f64 (exact for both the f32 and i32 on-disk forms).
#[derive(Clone)]
struct RtreeCell {
    key: i64,
    coords: Vec<f64>,
}

/// The fixed node size SQLite uses: `min(page_size - 64, 4 + 51*cell_size)`,
/// `cell_size = 8 + n_coord*4`, `51 = RTREE_MAXCELLS`.
fn rtree_node_size(n_coord: usize, page_size: usize) -> usize {
    let cell = 8 + n_coord * 4;
    page_size.saturating_sub(64).min(4 + 51 * cell)
}

/// Encode one node to its zero-padded blob. `is_root` puts the tree `depth` in
/// the header; non-root nodes carry 0 there.
fn rtree_encode_node(
    cells: &[RtreeCell],
    n_coord: usize,
    is_root: bool,
    depth: u16,
    integer: bool,
    node_size: usize,
) -> Vec<u8> {
    let mut b = alloc::vec![0u8; node_size];
    b[0..2].copy_from_slice(&(if is_root { depth } else { 0 }).to_be_bytes());
    b[2..4].copy_from_slice(&(cells.len() as u16).to_be_bytes());
    let cell_size = 8 + n_coord * 4;
    for (i, c) in cells.iter().enumerate() {
        let off = 4 + i * cell_size;
        b[off..off + 8].copy_from_slice(&c.key.to_be_bytes());
        for (d, &v) in c.coords.iter().enumerate() {
            let p = off + 8 + d * 4;
            let bytes = if integer {
                (v as i32).to_be_bytes()
            } else {
                (v as f32).to_be_bytes()
            };
            b[p..p + 4].copy_from_slice(&bytes);
        }
    }
    b
}

/// The bounding box (per-dimension min/max, in coordinate-column order) of a set
/// of cells: union of their boxes.
fn rtree_union(cells: &[RtreeCell], n_coord: usize) -> Vec<f64> {
    let mut bb = alloc::vec![0.0f64; n_coord];
    for (ci, c) in cells.iter().enumerate() {
        for (d, slot) in bb.iter_mut().enumerate() {
            let v = c.coords.get(d).copied().unwrap_or(0.0);
            if ci == 0 {
                *slot = v;
            } else if d % 2 == 0 {
                *slot = slot.min(v); // a `min` coordinate column
            } else {
                *slot = slot.max(v); // a `max` coordinate column
            }
        }
    }
    bb
}

/// A bulk-built R-Tree, ready to write to the shadow tables.
struct RtreeBuild {
    /// `(nodeno, encoded blob)` for every node.
    nodes: Vec<(i64, Vec<u8>)>,
    /// `(rowid, leaf nodeno)` for every entry.
    rowids: Vec<(i64, i64)>,
    /// `(child nodeno, parent nodeno)` for every non-root node.
    parents: Vec<(i64, i64)>,
}

/// Bulk-build a balanced R-Tree from `entries`. The root is always nodeno 1.
fn rtree_bulk_build(
    entries: Vec<RtreeCell>,
    n_coord: usize,
    integer: bool,
    node_size: usize,
) -> RtreeBuild {
    let max_cells = ((node_size - 4) / (8 + n_coord * 4)).max(1);
    // Empty tree: a single empty leaf root.
    if entries.is_empty() {
        return RtreeBuild {
            nodes: alloc::vec![(
                1,
                rtree_encode_node(&[], n_coord, true, 0, integer, node_size)
            )],
            rowids: Vec::new(),
            parents: Vec::new(),
        };
    }
    // Build levels bottom-up. A node is its list of cells; an interior cell's key
    // is a placeholder index into the child level, resolved to a nodeno later.
    // levels[0] = leaves; cells there carry the real rowid keys.
    let mut levels: Vec<Vec<Vec<RtreeCell>>> = Vec::new();
    levels.push(entries.chunks(max_cells).map(<[_]>::to_vec).collect());
    while levels.last().map_or(0, Vec::len) > 1 {
        let child_level = levels.len() - 1;
        let children = &levels[child_level];
        // Each parent cell summarizes one child: key = child index (placeholder).
        let parent_cells: Vec<RtreeCell> = (0..children.len())
            .map(|idx| RtreeCell {
                key: idx as i64,
                coords: rtree_union(&children[idx], n_coord),
            })
            .collect();
        levels.push(parent_cells.chunks(max_cells).map(<[_]>::to_vec).collect());
    }
    let root_level = levels.len() - 1;
    let depth = root_level as u16;

    // Assign node numbers: the root (top level, node 0) is 1; everything else
    // follows. Record nodeno for each (level, node-index).
    let mut nodeno_of: alloc::collections::BTreeMap<(usize, usize), i64> =
        alloc::collections::BTreeMap::new();
    nodeno_of.insert((root_level, 0), 1);
    let mut next = 2i64;
    for level in (0..levels.len()).rev() {
        for idx in 0..levels[level].len() {
            nodeno_of.entry((level, idx)).or_insert_with(|| {
                let n = next;
                next += 1;
                n
            });
        }
    }

    let mut nodes = Vec::new();
    let mut rowids = Vec::new();
    let mut parents = Vec::new();
    for level in 0..levels.len() {
        let is_leaf = level == 0;
        for (idx, cells) in levels[level].iter().enumerate() {
            let nodeno = nodeno_of[&(level, idx)];
            let is_root = level == root_level;
            // Resolve interior placeholder keys to child nodenos, and record the
            // parent + rowid maps.
            let resolved: Vec<RtreeCell> = cells
                .iter()
                .map(|c| {
                    if is_leaf {
                        rowids.push((c.key, nodeno));
                        c.clone()
                    } else {
                        let child = nodeno_of[&(level - 1, c.key as usize)];
                        parents.push((child, nodeno));
                        RtreeCell {
                            key: child,
                            coords: c.coords.clone(),
                        }
                    }
                })
                .collect();
            nodes.push((
                nodeno,
                rtree_encode_node(&resolved, n_coord, is_root, depth, integer, node_size),
            ));
        }
    }
    RtreeBuild {
        nodes,
        rowids,
        parents,
    }
}

/// Build a leaf cell from an R-Tree INSERT's column values `[id, c0, c1, …]`,
/// rounding each coordinate to the conservative f32 form (min columns down, max
/// columns up — SQLite's rtreeValueDown/Up) or clamping to i32 for `rtree_i32`.
/// Rejects a coordinate pair with `min > max`, like SQLite.
fn rtree_cell_from_values(
    rowid: i64,
    values: &[Value],
    n_coord: usize,
    integer: bool,
) -> Result<RtreeCell> {
    for d in 0..n_coord / 2 {
        let mn = values.get(1 + 2 * d).map_or(0.0, crate::vtab::coord_f64);
        let mx = values.get(2 + 2 * d).map_or(0.0, crate::vtab::coord_f64);
        if mn > mx {
            return Err(Error::Error("rtree constraint failed".into()));
        }
    }
    let coords = (0..n_coord)
        .map(|d| {
            let v = values.get(1 + d).map_or(0.0, crate::vtab::coord_f64);
            if integer {
                (v as i64).clamp(i64::from(i32::MIN), i64::from(i32::MAX)) as f64
            } else if d % 2 == 0 {
                crate::vtab::round_min_f32(v)
            } else {
                crate::vtab::round_max_f32(v)
            }
        })
        .collect();
    Ok(RtreeCell { key: rowid, coords })
}

/// Whether `e` is a `rowid` / `_rowid_` / `oid` reference (case-insensitive,
/// optionally table-qualified) that is NOT shadowed by a real column of that
/// name — i.e. it denotes the table's rowid, seekable directly in the table
/// b-tree whether or not the table has an explicit INTEGER PRIMARY KEY column.
fn is_rowid_ref(e: &Expr, columns: &[ColumnInfo]) -> bool {
    matches!(e, Expr::Column { column, .. }
        if matches!(column.to_ascii_lowercase().as_str(), "rowid" | "_rowid_" | "oid")
            && !columns.iter().any(|c| c.name.eq_ignore_ascii_case(column)))
}

/// Detect a `rowid = const` equality or `rowid IN (list)` in `where_expr` (the
/// rowid alias not shadowed by a real column), returning the candidate rowids to
/// seek directly in the table b-tree. `run_core` re-applies the full WHERE, so a
/// non-integer literal (`rowid = 5.5`) is a harmless superset.
fn rowid_seek_constraint(
    where_expr: &Expr,
    columns: &[ColumnInfo],
    params: &Params,
) -> Option<Vec<i64>> {
    match where_expr {
        Expr::Binary {
            op: BinaryOp::And,
            left,
            right,
        } => rowid_seek_constraint(left, columns, params)
            .or_else(|| rowid_seek_constraint(right, columns, params)),
        Expr::Paren(inner) => rowid_seek_constraint(inner, columns, params),
        Expr::Binary {
            op: BinaryOp::Eq,
            left,
            right,
        } => {
            let other = if is_rowid_ref(left, columns) {
                right
            } else if is_rowid_ref(right, columns) {
                left
            } else {
                return None;
            };
            Some(alloc::vec![eval::to_i64(&const_value(other, params)?)])
        }
        Expr::InList {
            expr,
            list,
            negated: false,
            ..
        } if is_rowid_ref(expr, columns) && !list.is_empty() => {
            let mut out = Vec::with_capacity(list.len());
            for item in list {
                out.push(eval::to_i64(&const_value(item, params)?));
            }
            Some(out)
        }
        _ => None,
    }
}

/// A per-column range constraint gathered from `WHERE`: optional lower and upper
/// bounds, each `(value, inclusive)`.
#[derive(Default, Clone)]
struct RangeBound {
    lower: Option<(Value, bool)>,
    upper: Option<(Value, bool)>,
}

/// Fold one comparison `column <op> value` into a [`RangeBound`]. Overwriting an
/// existing bound is safe: the index range scan only needs to return a superset
/// (the full `WHERE` is re-applied), and either of two bounds on the same side
/// yields a valid superset.
fn apply_bound(b: &mut RangeBound, op: BinaryOp, v: Value) {
    match op {
        BinaryOp::Gt => b.lower = Some((v, false)),
        BinaryOp::GtEq => b.lower = Some((v, true)),
        BinaryOp::Lt => b.upper = Some((v, false)),
        BinaryOp::LtEq => b.upper = Some((v, true)),
        _ => {}
    }
}

/// The comparison with its operands swapped (`a < b` ⇔ `b > a`).
fn flip_cmp(op: BinaryOp) -> BinaryOp {
    match op {
        BinaryOp::Lt => BinaryOp::Gt,
        BinaryOp::LtEq => BinaryOp::GtEq,
        BinaryOp::Gt => BinaryOp::Lt,
        BinaryOp::GtEq => BinaryOp::LtEq,
        other => other,
    }
}

/// Collect per-column range bounds (`<`/`<=`/`>`/`>=`/`BETWEEN`) from the
/// top-level `AND` conjuncts of `WHERE`, keyed by column index. Drives an index
/// range scan; non-range and non-constant terms are ignored (the full `WHERE` is
/// re-applied afterward).
fn collect_range_constraints(
    e: &Expr,
    columns: &[ColumnInfo],
    params: &Params,
    out: &mut alloc::collections::BTreeMap<usize, RangeBound>,
) {
    match e {
        Expr::Binary {
            op: BinaryOp::And,
            left,
            right,
        } => {
            collect_range_constraints(left, columns, params, out);
            collect_range_constraints(right, columns, params, out);
        }
        Expr::Paren(inner) => collect_range_constraints(inner, columns, params, out),
        Expr::Binary { op, left, right }
            if matches!(
                op,
                BinaryOp::Lt | BinaryOp::LtEq | BinaryOp::Gt | BinaryOp::GtEq
            ) =>
        {
            if let (Some(ci), Some(v)) = (col_index(left, columns), const_value(right, params)) {
                apply_bound(out.entry(ci).or_default(), *op, v);
            } else if let (Some(ci), Some(v)) =
                (col_index(right, columns), const_value(left, params))
            {
                apply_bound(out.entry(ci).or_default(), flip_cmp(*op), v);
            }
        }
        Expr::Between {
            expr,
            low,
            high,
            negated: false,
        } => {
            if let Some(ci) = col_index(expr, columns) {
                let b = out.entry(ci).or_default();
                if let Some(v) = const_value(low, params) {
                    apply_bound(b, BinaryOp::GtEq, v);
                }
                if let Some(v) = const_value(high, params) {
                    apply_bound(b, BinaryOp::LtEq, v);
                }
            }
        }
        _ => {}
    }
}

/// The column index a bare/qualified column expression resolves to, if any.
fn col_index(e: &Expr, columns: &[ColumnInfo]) -> Option<usize> {
    if let Expr::Column { table, column } = e {
        columns.iter().position(|c| {
            c.name.eq_ignore_ascii_case(column)
                && table
                    .as_deref()
                    .is_none_or(|t| c.table.eq_ignore_ascii_case(t))
        })
    } else {
        None
    }
}

/// Evaluate `e` as a constant (no column references), or `None` if it depends on
/// a row.
fn const_value(e: &Expr, params: &Params) -> Option<Value> {
    eval::eval(e, &EvalCtx::rowless(params)).ok()
}

/// Coerce each value to its column's type affinity (SQLite storage affinity).
fn apply_column_affinity(meta: &TableMeta, values: &mut [Value]) {
    for (i, v) in values.iter_mut().enumerate() {
        let taken = core::mem::replace(v, Value::Null);
        *v = meta.columns[i].affinity.coerce(taken);
    }
}

/// Enforce declared `NOT NULL` column constraints over a fully-built row.
fn check_not_null(meta: &TableMeta, values: &[Value]) -> Result<()> {
    for (i, v) in values.iter().enumerate() {
        if meta.not_null[i].is_some() && matches!(v, Value::Null) {
            return Err(Error::Constraint(format!(
                "NOT NULL constraint failed: {}.{}",
                meta.columns[i].table, meta.columns[i].name
            )));
        }
    }
    Ok(())
}

/// Build an index key record: the indexed column values followed by the trailing
/// rowid (which makes every index key unique and supports lookups).
fn index_key(cols: &[usize], values: &[Value], rowid: i64) -> Vec<u8> {
    let mut key: Vec<Value> = cols.iter().map(|&p| values[p].clone()).collect();
    key.push(Value::Integer(rowid));
    encode_record(&key)
}

/// Whether rows `a` and `b` collide on any UNIQUE/PRIMARY KEY column set (all
/// columns of the set equal and none NULL — NULLs are distinct, as in SQLite).
/// Build the `sqlite_stat1` `stat` string for an index over `rows`: `nRow`
/// followed by, for each leftmost prefix length `K`, `(nRow + dK/2) / dK` where
/// `dK` is the number of distinct prefixes of length `K` (collation-aware).
fn index_stat_string(
    cols: &[usize],
    colls: &[crate::value::Collation],
    rows: &[Vec<Value>],
) -> String {
    let n = rows.len();
    let mut tuples: Vec<Vec<Value>> = rows
        .iter()
        .map(|r| cols.iter().map(|&c| r[c].clone()).collect())
        .collect();
    tuples.sort_by(|a, b| stat_prefix_cmp(a, b, colls, cols.len()));
    let mut s = alloc::format!("{n}");
    for k in 1..=cols.len() {
        let mut distinct = 1usize; // n > 0 guaranteed by the caller
        for w in tuples.windows(2) {
            if stat_prefix_cmp(&w[0], &w[1], colls, k) != core::cmp::Ordering::Equal {
                distinct += 1;
            }
        }
        let avg = (n + distinct / 2) / distinct;
        s.push(' ');
        s.push_str(&avg.to_string());
    }
    s
}

/// Compare the leftmost `len` columns of two index tuples under per-column
/// collations (used to count distinct prefixes for `ANALYZE`).
fn stat_prefix_cmp(
    a: &[Value],
    b: &[Value],
    colls: &[crate::value::Collation],
    len: usize,
) -> core::cmp::Ordering {
    for i in 0..len {
        let coll = colls.get(i).copied().unwrap_or_default();
        let ord = crate::value::cmp_values_coll(&a[i], &b[i], coll);
        if ord != core::cmp::Ordering::Equal {
            return ord;
        }
    }
    core::cmp::Ordering::Equal
}

fn unique_match(meta: &TableMeta, a: &[Value], b: &[Value]) -> bool {
    meta.unique.iter().any(|(set, _)| {
        set.iter().all(|&c| {
            !matches!(a[c], Value::Null)
                && !matches!(b[c], Value::Null)
                && crate::value::cmp_values_coll(&a[c], &b[c], meta.columns[c].collation).is_eq()
        })
    })
}

/// SQLite's UNIQUE-violation message for two WITHOUT ROWID rows that collide on
/// an inline `UNIQUE`/`PRIMARY KEY` set (`UNIQUE constraint failed: t.a[, t.b]`),
/// or the bare message when the collision is on a standalone unique index.
fn wr_unique_message(meta: &TableMeta, a: &[Value], b: &[Value]) -> String {
    meta.unique
        .iter()
        .find(|(set, _)| {
            set.iter().all(|&c| {
                !matches!(a[c], Value::Null)
                    && !matches!(b[c], Value::Null)
                    && crate::value::cmp_values_coll(&a[c], &b[c], meta.columns[c].collation)
                        .is_eq()
            })
        })
        .map(|(set, _)| {
            let cols = set
                .iter()
                .map(|&i| alloc::format!("{}.{}", meta.columns[i].table, meta.columns[i].name))
                .collect::<Vec<_>>()
                .join(", ");
            alloc::format!("UNIQUE constraint failed: {cols}")
        })
        .unwrap_or_else(|| String::from("UNIQUE constraint failed"))
}

/// An index record for a `WITHOUT ROWID` table: the indexed columns followed by
/// the table's PRIMARY KEY columns (which make the entry unique), as SQLite does.
fn wr_index_key(cols: &[usize], pk_cols: &[usize], values: &[Value]) -> Vec<u8> {
    let mut key: Vec<Value> = cols.iter().map(|&p| values[p].clone()).collect();
    key.extend(pk_cols.iter().map(|&p| values[p].clone()));
    encode_record(&key)
}

#[derive(Clone)]
struct InputRow {
    values: Vec<Value>,
    rowid: Option<i64>,
}

impl InputRow {
    fn ctx<'a>(&'a self, columns: &'a [ColumnInfo], params: &'a Params) -> EvalCtx<'a> {
        EvalCtx {
            row: &self.values,
            columns,
            rowid: self.rowid,
            params,
            anon_counter: core::cell::Cell::new(0),
            subqueries: None,
        }
    }
}

/// Build an evaluation context for a standalone `(values, rowid)` row.
fn row_ctx<'a>(
    values: &'a [Value],
    columns: &'a [ColumnInfo],
    rowid: Option<i64>,
    params: &'a Params,
) -> EvalCtx<'a> {
    EvalCtx {
        row: values,
        columns,
        rowid,
        params,
        anon_counter: core::cell::Cell::new(0),
        subqueries: None,
    }
}

/// The conventional `<path>-journal` companion file name.
fn journal_path(path: &str) -> String {
    let mut p = String::from(path);
    p.push_str("-journal");
    p
}

/// The conventional `<path>-wal` companion file name.
fn wal_path(path: &str) -> String {
    let mut p = String::from(path);
    p.push_str("-wal");
    p
}

struct OutRow {
    values: Vec<Value>,
    sort_keys: Vec<Value>,
}

/// Output column labels for a `RETURNING` projection (mirrors a `SELECT` list:
/// `*`/`tbl.*` expand to table column names, expressions use their alias or a
/// derived label).
fn returning_labels(returning: &[ResultColumn], columns: &[ColumnInfo]) -> Vec<String> {
    let mut labels = Vec::new();
    for col in returning {
        match col {
            ResultColumn::Wildcard => {
                for c in columns {
                    labels.push(c.name.clone());
                }
            }
            ResultColumn::TableWildcard(t) => {
                for c in columns {
                    if c.table.eq_ignore_ascii_case(t) {
                        labels.push(c.name.clone());
                    }
                }
            }
            ResultColumn::Expr {
                expr,
                alias,
                source,
            } => {
                labels.push(result_column_label(expr, alias, source));
            }
        }
    }
    labels
}

fn project_column(
    col: &ResultColumn,
    columns: &[ColumnInfo],
    ctx: &EvalCtx,
    out: &mut Vec<Value>,
) -> Result<()> {
    match col {
        ResultColumn::Wildcard => {
            for v in ctx.row {
                out.push(v.clone());
            }
        }
        ResultColumn::TableWildcard(table) => {
            for (i, c) in columns.iter().enumerate() {
                if c.table.eq_ignore_ascii_case(table) {
                    out.push(ctx.row[i].clone());
                }
            }
        }
        ResultColumn::Expr { expr, .. } => {
            out.push(eval::eval(expr, ctx)?);
        }
    }
    Ok(())
}

/// If `expr` is a positional reference — a (possibly negated) integer literal,
/// optionally wrapped in parentheses or a `COLLATE` clause — return its signed
/// value. SQLite reads such a term in `GROUP BY` / `ORDER BY` as a 1-based output
/// column index; an expression like `1+1` is *not* positional. Used only for
/// range validation: in-range resolution still goes through
/// [`resolve_order_index`].
fn positional_int(expr: &Expr) -> Option<i64> {
    match expr {
        Expr::Literal(Literal::Integer(n)) => Some(*n),
        Expr::Unary {
            op: UnaryOp::Negate,
            expr,
        } => match expr.as_ref() {
            Expr::Literal(Literal::Integer(n)) => Some(n.wrapping_neg()),
            _ => None,
        },
        // Unary `+` is a SQLite no-op the parser folds away, so `+2` resolves to
        // positional 2 (verified: `ORDER BY +2` errors with 1 output column).
        Expr::Unary {
            op: UnaryOp::Identity,
            expr,
        } => positional_int(expr),
        Expr::Collate { expr, .. } | Expr::Paren(expr) => positional_int(expr),
        _ => None,
    }
}

/// Whether a projection has the exact shape `values_core` produces for a desugared
/// multi-row `VALUES`: every column is a bare expression auto-aliased `column1`,
/// `column2`, … in order, with no source span. Used to tell a real `VALUES` from
/// an explicit FROM-less `SELECT … UNION ALL SELECT …` when reporting a
/// column-count mismatch.
fn is_values_projection(cols: &[ResultColumn]) -> bool {
    !cols.is_empty()
        && cols.iter().enumerate().all(|(i, c)| {
            matches!(
                c,
                ResultColumn::Expr { alias: Some(a), source: None, .. }
                    if *a == alloc::format!("column{}", i + 1)
            )
        })
}

/// SQLite's `%r` ordinal: `1`→`1st`, `2`→`2nd`, `3`→`3rd`, others `th`, with
/// `11`/`12`/`13` always `th`.
fn ordinal(n: usize) -> alloc::string::String {
    let suffix = if (11..=13).contains(&(n % 100)) {
        "th"
    } else {
        match n % 10 {
            1 => "st",
            2 => "nd",
            3 => "rd",
            _ => "th",
        }
    };
    alloc::format!("{n}{suffix}")
}

/// Reject any `GROUP BY` / `ORDER BY` positional term that falls outside
/// `1..=ncols`, byte-matching SQLite's
/// `<ordinal> <clause> term out of range - should be between 1 and <ncols>`.
/// The ordinal is the offending term's 1-based position *within its clause*
/// (counting non-positional terms too). `ncols` is the output-column count.
/// SQLite resolves `ORDER BY` before `GROUP BY`, so when both clauses have an
/// out-of-range term the `ORDER BY` one is reported.
fn check_positional_terms(group_by: &[Expr], order_by: &[OrderTerm], ncols: usize) -> Result<()> {
    for (i, t) in order_by.iter().enumerate() {
        if let Some(n) = positional_int(&t.expr) {
            if n < 1 || (n as u64) > ncols as u64 {
                return Err(Error::Error(alloc::format!(
                    "{} ORDER BY term out of range - should be between 1 and {ncols}",
                    ordinal(i + 1),
                )));
            }
        }
    }
    for (i, g) in group_by.iter().enumerate() {
        if let Some(n) = positional_int(g) {
            if n < 1 || (n as u64) > ncols as u64 {
                return Err(Error::Error(alloc::format!(
                    "{} GROUP BY term out of range - should be between 1 and {ncols}",
                    ordinal(i + 1),
                )));
            }
        }
    }
    Ok(())
}

/// Apply SQLite's `OP_MustBeInt` to a `LIMIT`/`OFFSET` value: it must be an
/// integer, or a real / fully-numeric text string that is exactly integer-valued
/// and in range. A non-integral real (`1.9`), text with trailing garbage
/// (`'2abc'`), NULL, or a blob is a `datatype mismatch` error — SQLite does not
/// silently truncate or treat NULL as zero here.
fn must_be_int(v: Value) -> Result<i64> {
    fn real_exact(r: f64) -> Result<i64> {
        if r.is_finite()
            && r == crate::util::float::trunc(r)
            && r >= i64::MIN as f64
            && r < 9_223_372_036_854_775_808.0
        {
            Ok(r as i64)
        } else {
            Err(Error::Error("datatype mismatch".into()))
        }
    }
    match v {
        Value::Integer(i) => Ok(i),
        Value::Real(r) => real_exact(r),
        Value::Text(s) => {
            let t = s.trim();
            if let Ok(i) = t.parse::<i64>() {
                Ok(i)
            } else if let Ok(r) = t.parse::<f64>() {
                real_exact(r)
            } else {
                Err(Error::Error("datatype mismatch".into()))
            }
        }
        Value::Null | Value::Blob(_) => Err(Error::Error("datatype mismatch".into())),
    }
}

/// Resolve an `ORDER BY` term to an output-column index when it refers to one:
/// a positive integer literal `N` (1-based position), or a bare column name that
/// matches a result-column label/alias. Returns `None` for general expressions,
/// which are evaluated against the row instead.
fn resolve_order_index(expr: &Expr, labels: &[String], ncols: usize) -> Option<usize> {
    match expr {
        Expr::Literal(Literal::Integer(n)) => {
            let idx = (*n as usize).checked_sub(1)?;
            (idx < ncols).then_some(idx)
        }
        Expr::Column {
            table: None,
            column,
        } => labels.iter().position(|l| l.eq_ignore_ascii_case(column)),
        // `ORDER BY <alias> COLLATE …` (or a parenthesized term) still resolves to
        // the output column; the explicit collation is applied by the sort
        // comparison via `order_collations`/`key_collation`.
        Expr::Collate { expr, .. } | Expr::Paren(expr) => resolve_order_index(expr, labels, ncols),
        _ => None,
    }
}

/// Invoke `f(is_max, arg)` for each plain (non-window) single-argument `min()` /
/// `max()` aggregate call in `expr`. Used to detect SQLite's bare-column rule:
/// a query with exactly one `min`/`max` takes bare columns from the extreme row.
fn for_each_minmax(expr: &Expr, f: &mut dyn FnMut(bool, &Expr)) {
    match expr {
        Expr::Function {
            over: Some(_),
            args,
            ..
        } => {
            for a in args {
                for_each_minmax(a, f);
            }
        }
        Expr::Function {
            name,
            args,
            star: false,
            ..
        } => {
            if args.len() == 1 {
                let l = name.to_ascii_lowercase();
                if l == "min" || l == "max" {
                    f(l == "max", &args[0]);
                }
            }
            for a in args {
                for_each_minmax(a, f);
            }
        }
        Expr::Function { args, .. } => {
            for a in args {
                for_each_minmax(a, f);
            }
        }
        Expr::Binary { left, right, .. } => {
            for_each_minmax(left, f);
            for_each_minmax(right, f);
        }
        Expr::Unary { expr, .. }
        | Expr::Paren(expr)
        | Expr::IsNull { expr, .. }
        | Expr::Cast { expr, .. }
        | Expr::Collate { expr, .. } => for_each_minmax(expr, f),
        Expr::Between {
            expr, low, high, ..
        } => {
            for_each_minmax(expr, f);
            for_each_minmax(low, f);
            for_each_minmax(high, f);
        }
        Expr::InList { expr, list, .. } => {
            for_each_minmax(expr, f);
            for l in list {
                for_each_minmax(l, f);
            }
        }
        Expr::Case {
            operand,
            when_then,
            else_result,
        } => {
            if let Some(o) = operand {
                for_each_minmax(o, f);
            }
            for (w, t) in when_then {
                for_each_minmax(w, f);
                for_each_minmax(t, f);
            }
            if let Some(e) = else_result {
                for_each_minmax(e, f);
            }
        }
        _ => {}
    }
}

/// If a grouped query references exactly one `min()`/`max()` aggregate (anywhere
/// in its result columns, `HAVING`, or `ORDER BY`), return `(is_max, arg)`: bare
/// columns then take their values from the row achieving that extreme, per
/// SQLite. `min(a,b)`/`max(a,b)` (scalar, 2-arg) and window forms don't qualify.
fn single_minmax_arg(sel: &Select) -> Option<(bool, Expr)> {
    let mut hits: Vec<(bool, Expr)> = Vec::new();
    let mut collect =
        |e: &Expr| for_each_minmax(e, &mut |is_max, arg| hits.push((is_max, arg.clone())));
    for col in &sel.columns {
        if let ResultColumn::Expr { expr, .. } = col {
            collect(expr);
        }
    }
    if let Some(h) = &sel.having {
        collect(h);
    }
    for term in &sel.order_by {
        collect(&term.expr);
    }
    if hits.len() == 1 {
        hits.pop()
    } else {
        None
    }
}

/// Whether `expr` contains an aggregate-function call, using a caller-supplied
/// predicate to decide whether a function name (with its arg count / `*` flag) is
/// an aggregate — so `has_aggregate` can recognize built-in *and* user-registered
/// aggregate functions. A window call (`f(…) OVER (…)`) is not itself an aggregate.
/// Per-query FTS5 state for the aux columns/functions, built by `run_core` for a
/// `MATCH` query over a single `fts5` table and read by `rank`/`bm25()`/
/// `highlight()` during projection and `ORDER BY`.
#[cfg(feature = "fts5")]
struct Fts5QueryCtx {
    /// The fts5 table's column names.
    col_names: Vec<String>,
    /// The literal `MATCH` query string.
    query: String,
    /// A `col MATCH …` operand column (whole-query scope), if any.
    scope: Option<String>,
    /// The searchable (indexed) column names — every column except those declared
    /// `UNINDEXED`. `None` when all columns are indexed (the common case).
    indexed: Option<Vec<String>>,
    /// The table's resolved tokenizer config (Porter stemming + `remove_diacritics`
    /// level), so `highlight()`/`snippet()` fold exactly like the indexed docs.
    tok: crate::vtab::Fts5Tok,
    /// The bm25 corpus + rowid→document-index map — present only when `rank` /
    /// `bm25()` is referenced (`highlight()` needs only the query, not the corpus).
    bm25: Option<(
        crate::vtab::Fts5Bm25,
        alloc::collections::BTreeMap<i64, usize>,
    )>,
}

#[cfg(feature = "fts5")]
impl Fts5QueryCtx {
    /// Whether `col` is searchable (not `UNINDEXED`).
    fn col_indexed(&self, col: &str) -> bool {
        self.indexed
            .as_ref()
            .is_none_or(|cols| cols.iter().any(|n| n.eq_ignore_ascii_case(col)))
    }
}

/// Restores [`Connection::fts5_rank`] when a `run_core` invocation ends, so a
/// nested query's FTS5 state never leaks into the caller (or vice versa).
#[cfg(feature = "fts5")]
struct Fts5RankGuard<'a> {
    conn: &'a Connection,
    prev: Option<Fts5QueryCtx>,
}

#[cfg(feature = "fts5")]
impl core::ops::Drop for Fts5RankGuard<'_> {
    fn drop(&mut self) {
        *self.conn.fts5_rank.borrow_mut() = self.prev.take();
    }
}

/// Whether an expression references one of `names` as an unqualified column (the
/// FTS5 `rank` column) or as a function call (`bm25(…)`, `highlight(…)`, …).
#[cfg(feature = "fts5")]
fn expr_mentions_any(expr: &Expr, names: &[&str]) -> bool {
    let rec = |e: &Expr| expr_mentions_any(e, names);
    match expr {
        Expr::Column {
            table: None,
            column,
        } => names.iter().any(|n| column.eq_ignore_ascii_case(n)),
        Expr::Function { name, args, .. } => {
            names.iter().any(|n| name.eq_ignore_ascii_case(n)) || args.iter().any(rec)
        }
        Expr::Binary { left, right, .. } => rec(left) || rec(right),
        Expr::Unary { expr, .. } | Expr::Paren(expr) => rec(expr),
        Expr::IsNull { expr, .. } => rec(expr),
        Expr::Between {
            expr, low, high, ..
        } => rec(expr) || rec(low) || rec(high),
        Expr::InList { expr, list, .. } => rec(expr) || list.iter().any(rec),
        Expr::Case {
            operand,
            when_then,
            else_result,
        } => {
            operand.as_deref().is_some_and(rec)
                || when_then.iter().any(|(w, t)| rec(w) || rec(t))
                || else_result.as_deref().is_some_and(rec)
        }
        Expr::Cast { expr, .. } => rec(expr),
        _ => false,
    }
}

/// Whether a SELECT's projection, `ORDER BY`, or `HAVING` references any of
/// `names` — the cheap gate before building FTS5 query state.
#[cfg(feature = "fts5")]
fn select_mentions(sel: &Select, names: &[&str]) -> bool {
    sel.columns
        .iter()
        .any(|c| matches!(c, ResultColumn::Expr { expr, .. } if expr_mentions_any(expr, names)))
        || sel
            .order_by
            .iter()
            .any(|t| expr_mentions_any(&t.expr, names))
        || sel
            .having
            .as_ref()
            .is_some_and(|h| expr_mentions_any(h, names))
}

fn expr_contains_agg(expr: &Expr, is_agg: &dyn Fn(&str, usize, bool) -> bool) -> bool {
    let rec = |e: &Expr| expr_contains_agg(e, is_agg);
    match expr {
        // A window function (`f(…) OVER (…)`) is not a plain aggregate, even when
        // `f` is an aggregate name; only its arguments might contain aggregates.
        Expr::Function {
            over: Some(_),
            args,
            ..
        } => args.iter().any(rec),
        Expr::Function {
            name, args, star, ..
        } => is_agg(name, args.len(), *star) || args.iter().any(rec),
        Expr::Binary { left, right, .. } => rec(left) || rec(right),
        Expr::Unary { expr, .. } | Expr::Paren(expr) => rec(expr),
        Expr::IsNull { expr, .. } => rec(expr),
        Expr::Between {
            expr, low, high, ..
        } => rec(expr) || rec(low) || rec(high),
        Expr::InList { expr, list, .. } => rec(expr) || list.iter().any(rec),
        Expr::Case {
            operand,
            when_then,
            else_result,
        } => {
            operand.as_deref().is_some_and(rec)
                || when_then.iter().any(|(w, t)| rec(w) || rec(t))
                || else_result.as_deref().is_some_and(rec)
        }
        Expr::Cast { expr, .. } => rec(expr),
        _ => false,
    }
}

/// Combine two compound-query operand row sets per the operator.
fn apply_compound(
    op: CompoundOp,
    left: Vec<Vec<Value>>,
    right: Vec<Vec<Value>>,
    colls: &[crate::value::Collation],
) -> Vec<Vec<Value>> {
    // Set comparison uses the left SELECT's per-column collations (SQLite).
    let eq = |a: &[Value], b: &[Value]| rows_equal_coll(a, b, colls);
    // Deduplicate, keeping the *last* occurrence's representation: when two rows
    // are equal but differ in type (e.g. `1` vs `1.0`), SQLite's compound dedup
    // keeps the later one (`SELECT 1 UNION SELECT 1.0` yields `1.0`).
    let dedup = |rows: Vec<Vec<Value>>| -> Vec<Vec<Value>> {
        let mut seen: Vec<Vec<Value>> = Vec::new();
        for r in rows {
            match seen.iter().position(|s| eq(s, &r)) {
                Some(i) => seen[i] = r,
                None => seen.push(r),
            }
        }
        seen
    };
    match op {
        CompoundOp::UnionAll => {
            let mut out = left;
            out.extend(right);
            out
        }
        CompoundOp::Union => {
            let mut out = left;
            out.extend(right);
            dedup(out)
        }
        CompoundOp::Intersect => dedup(
            left.into_iter()
                .filter(|l| right.iter().any(|r| eq(l, r)))
                .collect(),
        ),
        CompoundOp::Except => dedup(
            left.into_iter()
                .filter(|l| !right.iter().any(|r| eq(l, r)))
                .collect(),
        ),
    }
}

fn rows_equal(a: &[Value], b: &[Value]) -> bool {
    a.len() == b.len()
        && a.iter()
            .zip(b)
            .all(|(x, y)| eval::compare(x, y) == core::cmp::Ordering::Equal)
}

/// Like [`rows_equal`] but comparing column `i` under collation `colls[i]`
/// (missing entries default to `BINARY`).
fn rows_equal_coll(a: &[Value], b: &[Value], colls: &[crate::value::Collation]) -> bool {
    a.len() == b.len()
        && a.iter().zip(b).enumerate().all(|(i, (x, y))| {
            let c = colls.get(i).copied().unwrap_or_default();
            crate::value::cmp_values_coll(x, y, c) == core::cmp::Ordering::Equal
        })
}

fn dedup_values(vals: &mut Vec<Value>, coll: crate::value::Collation) {
    let mut seen: Vec<Value> = Vec::new();
    vals.retain(|v| {
        if seen
            .iter()
            .any(|s| crate::value::cmp_values_coll(s, v, coll) == core::cmp::Ordering::Equal)
        {
            false
        } else {
            seen.push(v.clone());
            true
        }
    });
}

fn value_to_literal(v: Value) -> Literal {
    match v {
        Value::Null => Literal::Null,
        Value::Integer(i) => Literal::Integer(i),
        Value::Real(r) => Literal::Real(r),
        Value::Text(s) => Literal::Str(s),
        Value::Blob(b) => Literal::Blob(b),
    }
}

/// A list of `(column name, declared type)` pairs — a resolved column set for
/// `view_table_info` (the type is `None` for an expression column).
type NamedColumns = Vec<(String, Option<String>)>;

/// A column's inherited `(affinity, collating sequence)` — what a derived-table
/// column takes from its origin column (see `subquery_column_origins`).
type ColOrigin = (eval::Affinity, crate::value::Collation);

/// The column headers for `PRAGMA table_info` / `table_xinfo`.
fn table_info_columns(extended: bool) -> Vec<String> {
    let mut c: Vec<String> = ["cid", "name", "type", "notnull", "dflt_value", "pk"]
        .iter()
        .map(|s| String::from(*s))
        .collect();
    if extended {
        c.push(String::from("hidden"));
    }
    c
}

/// Rename every reference to column `old` (of table `table`) to `new` within an
/// expression — both unqualified (`old`) and table-qualified (`table.old`) forms.
/// Used to keep CHECK / generated / DEFAULT expressions valid across an
/// `ALTER TABLE … RENAME COLUMN`. (CHECK/generated/default forbid subqueries, so
/// the non-recursing `replace_expr` covers them.)
fn rename_column_ref(e: &mut Expr, table: &str, old: &str, new: &str) {
    window::replace_expr(
        e,
        &Expr::Column {
            table: None,
            column: String::from(old),
        },
        &Expr::Column {
            table: None,
            column: String::from(new),
        },
    );
    window::replace_expr(
        e,
        &Expr::Column {
            table: Some(String::from(table)),
            column: String::from(old),
        },
        &Expr::Column {
            table: Some(String::from(table)),
            column: String::from(new),
        },
    );
}

/// Rename every reference to table `old` → `new` throughout a `Select`: its
/// `FROM` table references and every table-qualified `old.col` / `old.*`, recursing
/// into subqueries, CTE bodies, and compound parts. Used to keep a dependent view
/// body valid across `ALTER TABLE … RENAME TO`. A same-level CTE named `old`
/// shadows the table, so `FROM old`/`old.*` there is left alone.
fn rename_table_in_select(sel: &mut Select, old: &str, new: &str) {
    let shadowed = sel.ctes.iter().any(|c| c.name.eq_ignore_ascii_case(old));
    for cte in &mut sel.ctes {
        rename_table_in_select(&mut cte.select, old, new);
    }
    if let Some(from) = &mut sel.from {
        rename_table_in_ref(&mut from.first, old, new, shadowed);
        for j in &mut from.joins {
            rename_table_in_ref(&mut j.table, old, new, shadowed);
            if let Some(on) = &mut j.on {
                rename_table_in_expr(on, old, new);
            }
        }
    }
    for rc in &mut sel.columns {
        match rc {
            ResultColumn::Expr { expr, .. } => rename_table_in_expr(expr, old, new),
            ResultColumn::TableWildcard(t) if !shadowed && t.eq_ignore_ascii_case(old) => {
                *t = String::from(new);
            }
            _ => {}
        }
    }
    if let Some(w) = &mut sel.where_clause {
        rename_table_in_expr(w, old, new);
    }
    for e in &mut sel.group_by {
        rename_table_in_expr(e, old, new);
    }
    if let Some(h) = &mut sel.having {
        rename_table_in_expr(h, old, new);
    }
    for t in &mut sel.order_by {
        rename_table_in_expr(&mut t.expr, old, new);
    }
    for (_, ws) in &mut sel.window_defs {
        rename_table_in_window(ws, old, new);
    }
    if let Some(e) = &mut sel.limit {
        rename_table_in_expr(e, old, new);
    }
    if let Some(e) = &mut sel.offset {
        rename_table_in_expr(e, old, new);
    }
    for (_, comp) in &mut sel.compound {
        rename_table_in_select(comp, old, new);
    }
}

/// Rename a table reference within a `FROM` source (recursing into a derived
/// subquery). A real table named `old` (not schema-qualified, not shadowed by a
/// same-level CTE) is repointed to `new`.
fn rename_table_in_ref(tref: &mut TableRef, old: &str, new: &str, shadowed: bool) {
    if let Some(sub) = &mut tref.subquery {
        rename_table_in_select(sub, old, new);
    } else if tref.schema.is_none() && !shadowed && tref.name.eq_ignore_ascii_case(old) {
        tref.name = String::from(new);
    }
}

/// Rename `old` → `new` in a window spec's `PARTITION BY` / `ORDER BY` expressions.
fn rename_table_in_window(ws: &mut WindowSpec, old: &str, new: &str) {
    for e in &mut ws.partition_by {
        rename_table_in_expr(e, old, new);
    }
    for t in &mut ws.order_by {
        rename_table_in_expr(&mut t.expr, old, new);
    }
}

/// Rename a table qualifier `old.col` → `new.col` throughout an expression,
/// recursing into every sub-expression and nested subquery.
fn rename_table_in_expr(e: &mut Expr, old: &str, new: &str) {
    match e {
        Expr::Column { table: Some(t), .. } if t.eq_ignore_ascii_case(old) => {
            *t = String::from(new)
        }
        Expr::Column { .. } | Expr::Literal(_) | Expr::Parameter(_) => {}
        Expr::Unary { expr, .. }
        | Expr::IsNull { expr, .. }
        | Expr::Cast { expr, .. }
        | Expr::Paren(expr)
        | Expr::Collate { expr, .. } => rename_table_in_expr(expr, old, new),
        Expr::Binary { left, right, .. } => {
            rename_table_in_expr(left, old, new);
            rename_table_in_expr(right, old, new);
        }
        Expr::Function {
            args,
            filter,
            order_by,
            over,
            ..
        } => {
            for a in args {
                rename_table_in_expr(a, old, new);
            }
            if let Some(f) = filter {
                rename_table_in_expr(f, old, new);
            }
            for t in order_by {
                rename_table_in_expr(&mut t.expr, old, new);
            }
            if let Some(w) = over {
                rename_table_in_window(w, old, new);
            }
        }
        Expr::InList { expr, list, .. } => {
            rename_table_in_expr(expr, old, new);
            for a in list {
                rename_table_in_expr(a, old, new);
            }
        }
        Expr::Between {
            expr, low, high, ..
        } => {
            rename_table_in_expr(expr, old, new);
            rename_table_in_expr(low, old, new);
            rename_table_in_expr(high, old, new);
        }
        Expr::Case {
            operand,
            when_then,
            else_result,
        } => {
            if let Some(o) = operand {
                rename_table_in_expr(o, old, new);
            }
            for (w, t) in when_then {
                rename_table_in_expr(w, old, new);
                rename_table_in_expr(t, old, new);
            }
            if let Some(el) = else_result {
                rename_table_in_expr(el, old, new);
            }
        }
        Expr::RowValue(items) => {
            for i in items {
                rename_table_in_expr(i, old, new);
            }
        }
        Expr::Subquery(s) => rename_table_in_select(s, old, new),
        Expr::Exists { select, .. } => rename_table_in_select(select, old, new),
        Expr::InSelect { expr, select, .. } => {
            rename_table_in_expr(expr, old, new);
            rename_table_in_select(select, old, new);
        }
    }
}

/// Split a `;`-separated SQL script into trimmed statement slices for
/// [`Connection::execute_batch`]. Reuses the tokenizer, so string literals and
/// `--`/`/* */` comments never split a statement, and tracks `BEGIN…END` /
/// `CASE…END` nesting so a `;` inside a trigger body or `CASE` expression is not
/// a boundary. A leading `BEGIN` (transaction control) does not open a block —
/// only a mid-statement one (e.g. `CREATE TRIGGER … BEGIN`) does. Comment-only
/// and empty segments are dropped.
fn split_sql_script(sql: &str) -> Vec<&str> {
    let toks = match sql::token::tokenize(sql) {
        Ok(t) => t,
        // Let the caller surface the real parse error on the whole input.
        Err(_) => return alloc::vec![sql.trim()],
    };
    let mut out = Vec::new();
    let mut depth: u32 = 0;
    let mut seg_start = 0usize;
    let mut seen = false;
    for sp in &toks {
        match &sp.token {
            sql::token::Token::Semicolon if depth == 0 => {
                if seen {
                    out.push(sql[seg_start..sp.start].trim());
                }
                seg_start = sp.end;
                seen = false;
            }
            sql::token::Token::Word(w) => {
                match w.to_ascii_uppercase().as_str() {
                    "BEGIN" if seen => depth += 1,
                    "CASE" => depth += 1,
                    "END" => depth = depth.saturating_sub(1),
                    _ => {}
                }
                seen = true;
            }
            _ => seen = true,
        }
    }
    if seen {
        out.push(sql[seg_start..].trim());
    }
    out
}

/// The text stored in `sqlite_master.sql` for a DDL statement: the source from
/// its first real token (skipping leading comments and whitespace) to the trimmed
/// end. SQLite records the schema text from the `CREATE` keyword onward, so an
/// inter-statement `-- comment` preceding the statement is not captured.
fn ddl_text(sql: &str) -> &str {
    match sql::token::tokenize(sql) {
        Ok(toks) if !toks.is_empty() => sql[toks[0].start..].trim_end(),
        _ => sql.trim(),
    }
}

/// Does this stored `CREATE VIEW` body reference table `name`? Used to decide
/// whether an `ALTER TABLE name RENAME TO` must rewrite the view to stay valid —
/// we parse and run the table-rename walker against a sentinel and see if it
/// touched anything, so unrelated views are left byte-for-byte untouched.
/// Whether a `SELECT` references base table `name` anywhere (FROM/joins/
/// subqueries/CTEs/compound) — detected by probe-renaming it to a sentinel and
/// checking the AST changed (reuses `rename_table_in_select`'s full walk).
fn select_reads_table(sel: &Select, name: &str) -> bool {
    let mut probe = sel.clone();
    rename_table_in_select(
        &mut probe,
        name,
        "\u{1}\u{1}graphite_rename_probe\u{1}\u{1}",
    );
    probe != *sel
}

/// Whether a `FROM` clause names table `name` as its first source or a join.
fn from_refs_table(f: &FromClause, name: &str) -> bool {
    f.first.name.eq_ignore_ascii_case(name)
        || f.joins
            .iter()
            .any(|j| j.table.name.eq_ignore_ascii_case(name))
}

/// Whether a `CREATE TRIGGER` references table `name` — either it is attached to
/// it (`ON name`) or a body statement targets/reads it. Used to decide whether a
/// `RENAME TABLE` must rewrite the renamed name inside the trigger's stored text.
fn trigger_uses_table(trigger_sql: &str, name: &str) -> bool {
    let Ok(Statement::CreateTrigger(ct)) = sql::parse_one(trigger_sql) else {
        return false;
    };
    if ct.table.eq_ignore_ascii_case(name) {
        return true;
    }
    ct.body.iter().any(|s| match s {
        Statement::Select(sel) => select_reads_table(sel, name),
        Statement::Insert(i) => {
            i.table.eq_ignore_ascii_case(name)
                || matches!(&i.source, InsertSource::Select(sel) if select_reads_table(sel, name))
        }
        Statement::Update(u) => {
            u.table.eq_ignore_ascii_case(name)
                || u.from.as_ref().is_some_and(|f| from_refs_table(f, name))
        }
        Statement::Delete(d) => d.table.eq_ignore_ascii_case(name),
        _ => false,
    })
}

fn view_uses_table(view_sql: &str, name: &str) -> bool {
    match sql::parse_one(view_sql) {
        Ok(Statement::CreateView(cv)) => {
            let mut probe = cv.select.clone();
            rename_table_in_select(
                &mut probe,
                name,
                "\u{1}\u{1}graphite_rename_probe\u{1}\u{1}",
            );
            *probe != *cv.select
        }
        _ => false,
    }
}

/// Rewrite stored DDL text, repointing every bare or double-quoted identifier
/// token equal to `old` (case-insensitively) to the already-rendered `rendered`
/// text while preserving all other source text — whitespace, comments, and
/// string/blob literals (which tokenize as `Str`/`Blob`, never identifiers, so
/// their contents are never touched). This mirrors SQLite's text-preserving
/// rename rather than reprinting from the AST. `rendered` is the replacement as
/// it should appear (a table rename passes the double-quoted name; a column
/// rename passes the new name bare or quoted exactly as the user wrote it).
/// Rewrite a foreign-key parent-column reference after the parent's column is
/// renamed: in `sql` (another table's `CREATE`), rename `old` → `rendered` but
/// only inside a `REFERENCES <parent>(…)` column list — so a child column that
/// happens to share the old name is left untouched. Used for cross-object
/// `ALTER TABLE … RENAME COLUMN` propagation into foreign keys.
fn rewrite_fk_parent_column(sql: &str, parent: &str, old: &str, rendered: &str) -> String {
    use sql::token::Token;
    let toks = match sql::token::tokenize(sql) {
        Ok(t) => t,
        Err(_) => return String::from(sql),
    };
    let is_word = |t: &Token, w: &str| matches!(t, Token::Word(x) | Token::Ident(x) if x.eq_ignore_ascii_case(w));
    let mut spans: Vec<(usize, usize)> = Vec::new();
    let mut i = 0;
    while i < toks.len() {
        // `REFERENCES <parent> ( … )` — rename `old` within the column list.
        if is_word(&toks[i].token, "references")
            && toks.get(i + 1).is_some_and(|p| is_word(&p.token, parent))
            && toks
                .get(i + 2)
                .is_some_and(|l| matches!(l.token, Token::LParen))
        {
            let mut m = i + 3;
            while m < toks.len() && !matches!(toks[m].token, Token::RParen) {
                if is_word(&toks[m].token, old) {
                    spans.push((toks[m].start, toks[m].end));
                }
                m += 1;
            }
            i = m;
            continue;
        }
        i += 1;
    }
    if spans.is_empty() {
        return String::from(sql);
    }
    let mut out = String::new();
    let mut cursor = 0;
    for (s, e) in spans {
        out.push_str(&sql[cursor..s]);
        out.push_str(rendered);
        cursor = e;
    }
    out.push_str(&sql[cursor..]);
    out
}

/// For a `CREATE VIEW` whose `SELECT` draws from exactly one source — the
/// renamed `table`, with no joins, subqueries, CTEs, or compound parts — return
/// the qualifiers under which that table's columns can appear (its name plus any
/// alias) so a column rename can be applied by a token rewrite. Returns `None`
/// when a rewrite could be unsafe (multi-source, a subquery that could reach
/// another table, the renamed column's name collides with the table or an alias)
/// — those views are left unchanged, the remaining scope-aware A-rn3 work.
fn view_single_source_column_quals(view_sql: &str, table: &str, old: &str) -> Option<Vec<String>> {
    let Ok(Statement::CreateView(cv)) = sql::parse_one(view_sql) else {
        return None;
    };
    let sel = &cv.select;
    if !sel.ctes.is_empty() || !sel.compound.is_empty() {
        return None;
    }
    // A column named the same as its table would make the table-name token in
    // `FROM <table>` indistinguishable from a column reference — bail.
    if old.eq_ignore_ascii_case(table) {
        return None;
    }
    let from = sel.from.as_ref()?;
    if !from.joins.is_empty() || from.first.subquery.is_some() || from.first.tvf_args.is_some() {
        return None;
    }
    if !from.first.name.eq_ignore_ascii_case(table) {
        return None;
    }
    let mut quals = alloc::vec![table.to_string()];
    if let Some(a) = &from.first.alias {
        if a.eq_ignore_ascii_case(old) {
            return None; // alias collides with the renamed column name
        }
        quals.push(a.clone());
    }
    // Any subquery could reference another table (breaking the single-source
    // guarantee); a result-column alias equal to `old` would be wrongly renamed.
    for rc in &sel.columns {
        if let ResultColumn::Expr { expr, alias, .. } = rc {
            if expr_has_subquery(expr) {
                return None;
            }
            if alias
                .as_deref()
                .is_some_and(|a| a.eq_ignore_ascii_case(old))
            {
                return None;
            }
        }
    }
    let mut clean = true;
    for e in sel
        .where_clause
        .iter()
        .chain(sel.group_by.iter())
        .chain(sel.having.iter())
    {
        clean &= !expr_has_subquery(e);
    }
    for t in &sel.order_by {
        clean &= !expr_has_subquery(&t.expr);
    }
    if !clean {
        return None;
    }
    Some(quals)
}

/// A-rn3: column-rename rewrite plan for a MULTI-source view (a join of plain
/// base tables). Returns `(quals, rewrite_bare)`: SQLite always renames a
/// `<renamed-table>.old` reference (so `quals` is the renamed table's name +
/// alias), and renames a *bare* `old` only when that column name is unique across
/// all the join's sources (else a bare `old` would be ambiguous — an invalid view
/// anyway). Bails (→ None, leaving the view untouched) on any subquery/CTE/
/// compound, a NATURAL/USING join, a non-base-table source, the renamed table
/// appearing other than exactly once, or a result alias colliding with `old`.
/// `table_cols` maps each base table's name to its column names.
fn view_multi_source_quals(
    view_sql: &str,
    table: &str,
    old: &str,
    table_cols: &alloc::collections::BTreeMap<String, Vec<String>>,
) -> Option<(Vec<String>, bool)> {
    let Ok(Statement::CreateView(cv)) = sql::parse_one(view_sql) else {
        return None;
    };
    let sel = &cv.select;
    if !sel.ctes.is_empty() || !sel.compound.is_empty() || old.eq_ignore_ascii_case(table) {
        return None;
    }
    let from = sel.from.as_ref()?;
    if from.joins.is_empty() {
        return None; // single-source is handled separately
    }
    // Collect every source; each must be a plain base table (no subquery/tvf/
    // schema-qualifier), and a NATURAL/USING join's column coalescing is bailed.
    let mut srcs: Vec<(String, Option<String>)> = Vec::new();
    let mut push = |tr: &crate::sql::ast::TableRef| -> bool {
        if tr.subquery.is_some() || tr.tvf_args.is_some() || tr.schema.is_some() {
            return false;
        }
        srcs.push((tr.name.clone(), tr.alias.clone()));
        true
    };
    if !push(&from.first) {
        return None;
    }
    for j in &from.joins {
        if j.natural || !j.using.is_empty() || !push(&j.table) {
            return None;
        }
    }
    // The renamed table must be a source exactly once; its name+alias qualify it.
    let renamed: Vec<&(String, Option<String>)> = srcs
        .iter()
        .filter(|(n, _)| n.eq_ignore_ascii_case(table))
        .collect();
    if renamed.len() != 1 {
        return None;
    }
    let mut quals = alloc::vec![renamed[0].0.clone()];
    if let Some(a) = &renamed[0].1 {
        if a.eq_ignore_ascii_case(old) {
            return None;
        }
        quals.push(a.clone());
    }
    // `old` is safe to rename as a bare reference only if exactly one source has a
    // column of that name. Every source must be a known base table.
    let has_old = |name: &str| -> Option<bool> {
        let cols = table_cols
            .iter()
            .find(|(t, _)| t.eq_ignore_ascii_case(name))
            .map(|(_, c)| c)?;
        Some(cols.iter().any(|c| c.eq_ignore_ascii_case(old)))
    };
    let mut count = 0usize;
    for (n, _) in &srcs {
        if has_old(n)? {
            count += 1;
        }
    }
    let rewrite_bare = count == 1;
    // A subquery anywhere could reach another table (breaking the analysis); a
    // result alias equal to `old` would be wrongly renamed.
    for rc in &sel.columns {
        if let ResultColumn::Expr { expr, alias, .. } = rc {
            if expr_has_subquery(expr)
                || alias
                    .as_deref()
                    .is_some_and(|a| a.eq_ignore_ascii_case(old))
            {
                return None;
            }
        }
    }
    for e in sel
        .where_clause
        .iter()
        .chain(sel.group_by.iter())
        .chain(sel.having.iter())
    {
        if expr_has_subquery(e) {
            return None;
        }
    }
    for t in &sel.order_by {
        if expr_has_subquery(&t.expr) {
            return None;
        }
    }
    Some((quals, rewrite_bare))
}

/// Whether a `SELECT` references at most the single source `table` (its `FROM`,
/// if any, is exactly `table` with no alias, joins, subquery source, CTEs,
/// compound parts, or any subquery expression). Conservative: a `false` result
/// just means "don't token-rewrite", never corruption.
fn select_single_source_ok(sel: &Select, table: &str) -> bool {
    if !sel.ctes.is_empty() || !sel.compound.is_empty() {
        return false;
    }
    if let Some(from) = &sel.from {
        if !from.joins.is_empty()
            || from.first.subquery.is_some()
            || from.first.tvf_args.is_some()
            || from.first.alias.is_some()
            || !from.first.name.eq_ignore_ascii_case(table)
        {
            return false;
        }
    }
    let mut ok = true;
    for rc in &sel.columns {
        if let ResultColumn::Expr { expr, alias, .. } = rc {
            ok &= !expr_has_subquery(expr) && alias.is_none();
        }
    }
    for e in sel
        .where_clause
        .iter()
        .chain(sel.group_by.iter())
        .chain(sel.having.iter())
    {
        ok &= !expr_has_subquery(e);
    }
    for t in &sel.order_by {
        ok &= !expr_has_subquery(&t.expr);
    }
    ok
}

/// For a `CREATE TRIGGER` ON the renamed `table` whose body and `WHEN` reference
/// ONLY that table (every body statement targets `table`, draws from at most
/// `table`, and contains no subquery), return the qualifiers under which the
/// renamed column can appear (`table`, `NEW`, `OLD`) so a column rename can be
/// token-rewritten. Returns `None` (leave the trigger unchanged) on anything
/// outside this provably-safe shape — the multi-table / scope-aware remainder.
fn trigger_single_source_quals(trigger_sql: &str, table: &str, old: &str) -> Option<Vec<String>> {
    let Ok(Statement::CreateTrigger(ct)) = sql::parse_one(trigger_sql) else {
        return None;
    };
    // Only triggers attached to the renamed table (so NEW/OLD are its rows). A
    // column named like the table or like the NEW/OLD aliases is ambiguous.
    if !ct.table.eq_ignore_ascii_case(table)
        || old.eq_ignore_ascii_case(table)
        || old.eq_ignore_ascii_case("new")
        || old.eq_ignore_ascii_case("old")
    {
        return None;
    }
    if ct.when.as_ref().is_some_and(expr_has_subquery) {
        return None;
    }
    // A subquery anywhere could reach another table, breaking the single-source
    // guarantee; `expr_has_subquery` is a plain fn so it passes by value freely.
    for stmt in &ct.body {
        let safe = match stmt {
            Statement::Select(sel) => select_single_source_ok(sel, table),
            Statement::Insert(i) => {
                i.schema.is_none()
                    && i.returning.is_empty()
                    && i.upsert.is_empty()
                    && i.table.eq_ignore_ascii_case(table)
                    && match &i.source {
                        InsertSource::DefaultValues => true,
                        InsertSource::Values(rows) => {
                            !rows.iter().any(|r| r.iter().any(expr_has_subquery))
                        }
                        InsertSource::Select(sel) => select_single_source_ok(sel, table),
                    }
            }
            Statement::Update(u) => {
                u.schema.is_none()
                    && u.from.is_none()
                    && u.returning.is_empty()
                    && u.table.eq_ignore_ascii_case(table)
                    && u.row_assignments.is_empty()
                    && !u.assignments.iter().any(|(_, e)| expr_has_subquery(e))
                    && !u.where_clause.as_ref().is_some_and(expr_has_subquery)
                    && !u.order_by.iter().any(|t| expr_has_subquery(&t.expr))
                    && !u.limit.as_ref().is_some_and(expr_has_subquery)
                    && !u.offset.as_ref().is_some_and(expr_has_subquery)
            }
            Statement::Delete(d) => {
                d.schema.is_none()
                    && d.returning.is_empty()
                    && d.table.eq_ignore_ascii_case(table)
                    && !d.where_clause.as_ref().is_some_and(expr_has_subquery)
                    && !d.order_by.iter().any(|t| expr_has_subquery(&t.expr))
                    && !d.limit.as_ref().is_some_and(expr_has_subquery)
                    && !d.offset.as_ref().is_some_and(expr_has_subquery)
            }
            _ => false,
        };
        if !safe {
            return None;
        }
    }
    Some(alloc::vec![
        table.to_string(),
        String::from("NEW"),
        String::from("OLD"),
    ])
}

/// Whether `trigger_sql`'s body+WHEN reference `table` as their ONLY base table
/// (every body statement targets/reads just `table`, no other table, no
/// subquery, no alias/CTE/compound) — regardless of which table the trigger is
/// attached to. When true, every bare and `table.`-qualified column reference in
/// the body binds to `table`, so a rename can be token-rewritten safely. Used for
/// a trigger on ANOTHER table whose body reads/writes the renamed table (the
/// cross-object case `trigger_single_source_quals` does not cover, since that
/// one also rewrites `NEW`/`OLD`, which here belong to the trigger's own table).
/// Conservative: any construct it cannot prove single-source makes it `false`.
fn trigger_body_single_source_over(trigger_sql: &str, table: &str, old: &str) -> bool {
    let Ok(Statement::CreateTrigger(ct)) = sql::parse_one(trigger_sql) else {
        return false;
    };
    // `old` colliding with NEW/OLD would make a bare-vs-pseudo-column ambiguous.
    if old.eq_ignore_ascii_case("new") || old.eq_ignore_ascii_case("old") {
        return false;
    }
    if ct.when.as_ref().is_some_and(expr_has_subquery) {
        return false;
    }
    for stmt in &ct.body {
        let safe = match stmt {
            Statement::Select(sel) => select_single_source_ok(sel, table),
            Statement::Insert(i) => {
                i.schema.is_none()
                    && i.returning.is_empty()
                    && i.upsert.is_empty()
                    && i.table.eq_ignore_ascii_case(table)
                    && match &i.source {
                        InsertSource::DefaultValues => true,
                        InsertSource::Values(rows) => {
                            !rows.iter().any(|r| r.iter().any(expr_has_subquery))
                        }
                        InsertSource::Select(sel) => select_single_source_ok(sel, table),
                    }
            }
            Statement::Update(u) => {
                u.schema.is_none()
                    && u.from.is_none()
                    && u.returning.is_empty()
                    && u.table.eq_ignore_ascii_case(table)
                    && u.row_assignments.is_empty()
                    && !u.assignments.iter().any(|(_, e)| expr_has_subquery(e))
                    && !u.where_clause.as_ref().is_some_and(expr_has_subquery)
            }
            Statement::Delete(d) => {
                d.schema.is_none()
                    && d.returning.is_empty()
                    && d.table.eq_ignore_ascii_case(table)
                    && !d.where_clause.as_ref().is_some_and(expr_has_subquery)
            }
            _ => false,
        };
        if !safe {
            return false;
        }
    }
    // Require at least one statement (an empty body has nothing to rewrite).
    !ct.body.is_empty()
}

/// Whether `trigger_sql` is a trigger attached to `table`, with `old` not an
/// ambiguous name (the table itself or the `NEW`/`OLD` aliases). When true, the
/// trigger's `NEW.old` / `OLD.old` references unambiguously bind to `table`'s
/// renamed column — safe to rewrite even when the body touches other tables
/// (unlike [`trigger_single_source_quals`], which also needs bare refs to resolve).
fn trigger_on_renamed_table(trigger_sql: &str, table: &str, old: &str) -> bool {
    matches!(sql::parse_one(trigger_sql), Ok(Statement::CreateTrigger(ct))
        if ct.table.eq_ignore_ascii_case(table)
            && !old.eq_ignore_ascii_case(table)
            && !old.eq_ignore_ascii_case("new")
            && !old.eq_ignore_ascii_case("old"))
}

/// Token-rewrite a column rename in DDL where every reference to `old` is known
/// to belong to one of `quals` (a single-source object's table name / aliases):
/// rename a qualified `<q>.old` whose qualifier `q` is in `quals`, preserving all
/// other text. When `rewrite_bare` is true, an unqualified `old` ident is also
/// renamed (safe only when every bare reference provably resolves to the renamed
/// table — i.e. a single-source object); when false, only qualified references
/// are touched (e.g. a multi-source trigger where only `NEW.old`/`OLD.old` are
/// provably the renamed column). A function name (`old(`) and a column tail
/// qualified by anything else are left intact.
fn rewrite_column_tokens(
    sql: &str,
    quals: &[String],
    old: &str,
    rendered: &str,
    rewrite_bare: bool,
) -> String {
    use sql::token::Token;
    let toks = match sql::token::tokenize(sql) {
        Ok(t) => t,
        Err(_) => return String::from(sql),
    };
    let mut out = String::new();
    let mut cursor = 0usize;
    for (i, sp) in toks.iter().enumerate() {
        let hit =
            matches!(&sp.token, Token::Word(w) | Token::Ident(w) if w.eq_ignore_ascii_case(old));
        if !hit {
            continue;
        }
        // A function name (`old(`) is never a column reference.
        if toks
            .get(i + 1)
            .is_some_and(|n| matches!(n.token, Token::LParen))
        {
            continue;
        }
        let after_dot = i > 0 && matches!(toks[i - 1].token, Token::Dot);
        if after_dot {
            // Rename only `<qualifier>.old` where the qualifier is the table or an
            // alias; leave any other `x.old` untouched.
            let qual_ok = i >= 2
                && matches!(&toks[i - 2].token, Token::Word(q) | Token::Ident(q)
                    if quals.iter().any(|t| t.eq_ignore_ascii_case(q)));
            if !qual_ok {
                continue;
            }
        } else if !rewrite_bare {
            // A bare reference is only provably the renamed column in a
            // single-source context; skip it otherwise.
            continue;
        }
        out.push_str(&sql[cursor..sp.start]);
        out.push_str(rendered);
        cursor = sp.end;
    }
    out.push_str(&sql[cursor..]);
    out
}

fn rewrite_ident_tokens(sql: &str, old: &str, rendered: &str) -> String {
    let toks = match sql::token::tokenize(sql) {
        Ok(t) => t,
        Err(_) => return String::from(sql),
    };
    let mut out = String::new();
    let mut cursor = 0usize;
    for (i, sp) in toks.iter().enumerate() {
        let hit = matches!(
            &sp.token,
            sql::token::Token::Word(w) | sql::token::Token::Ident(w) if w.eq_ignore_ascii_case(old)
        );
        if !hit {
            continue;
        }
        // A token equal to the table name is only a *table reference* worth
        // renaming when it is neither a column-name tail (`x.old`) nor a function
        // name (`old(`). Skipping those keeps a like-named column or function
        // (e.g. a table named `count` vs the `count()` function) intact.
        let after_dot = i > 0 && matches!(toks[i - 1].token, sql::token::Token::Dot);
        let before_lparen = toks
            .get(i + 1)
            .is_some_and(|n| matches!(n.token, sql::token::Token::LParen));
        if after_dot || before_lparen {
            continue;
        }
        out.push_str(&sql[cursor..sp.start]);
        out.push_str(rendered);
        cursor = sp.end;
    }
    out.push_str(&sql[cursor..]);
    out
}

/// Replace the table-name token that follows the `anchor` keyword (`TABLE` for a
/// `CREATE TABLE`, `ON` for a `CREATE INDEX`) with `new` (double-quoted, as
/// SQLite does), preserving the rest of the text verbatim — so a `RENAME TO`
/// keeps the original formatting rather than reprinting from the AST. Returns the
/// input unchanged if the name token can't be located.
fn rename_table_token_after(sql: &str, anchor: &str, new: &str) -> String {
    use sql::token::Token;
    let toks = match sql::token::tokenize(sql) {
        Ok(t) => t,
        Err(_) => return String::from(sql),
    };
    let kw = |t: &Token, k: &str| matches!(t, Token::Word(w) if w.eq_ignore_ascii_case(k));
    let mut i = 0;
    while i < toks.len() && !kw(&toks[i].token, anchor) {
        i += 1;
    }
    i += 1;
    // Optional `IF NOT EXISTS` (only after TABLE).
    if i + 2 < toks.len()
        && kw(&toks[i].token, "if")
        && kw(&toks[i + 1].token, "not")
        && kw(&toks[i + 2].token, "exists")
    {
        i += 3;
    }
    // Optional `schema.` qualifier before the table name.
    if i + 1 < toks.len() && matches!(toks[i + 1].token, Token::Dot) {
        i += 2;
    }
    let Some(sp) = toks.get(i) else {
        return String::from(sql);
    };
    let mut out = String::with_capacity(sql.len() + new.len());
    out.push_str(&sql[..sp.start]);
    out.push_str(&sql::print::ident(new));
    out.push_str(&sql[sp.end..]);
    out
}

/// Rewrite the target of every `REFERENCES <old>` clause in a `CREATE TABLE`
/// text to `new` (double-quoted), preserving the rest verbatim — so an
/// `ALTER TABLE … RENAME TO` updates the foreign keys of OTHER tables (and any
/// self-reference) that point at the renamed table, as SQLite does. Only the
/// table-name token immediately after `REFERENCES` is touched, so references to
/// other tables — and a column that happens to share the old name — are left
/// intact. (SQLite forbids a schema qualifier after `REFERENCES`, so the target
/// is always a single bare/quoted name.)
fn rewrite_fk_references(sql: &str, old: &str, new: &str) -> String {
    use sql::token::Token;
    let toks = match sql::token::tokenize(sql) {
        Ok(t) => t,
        Err(_) => return String::from(sql),
    };
    let mut out = String::new();
    let mut cursor = 0usize;
    for (i, sp) in toks.iter().enumerate() {
        if !matches!(&sp.token, Token::Word(w) if w.eq_ignore_ascii_case("references")) {
            continue;
        }
        let Some(target) = toks.get(i + 1) else {
            continue;
        };
        if matches!(&target.token, Token::Word(w) | Token::Ident(w) if w.eq_ignore_ascii_case(old))
        {
            out.push_str(&sql[cursor..target.start]);
            out.push_str(&sql::print::ident(new));
            cursor = target.end;
        }
    }
    out.push_str(&sql[cursor..]);
    out
}

/// Insert `, <col_text>` before the column-list's closing paren of a `CREATE
/// TABLE` statement's text, preserving everything else verbatim — how SQLite
/// records an `ADD COLUMN`. Returns `None` if the column list can't be located.
fn append_column_to_create(sql: &str, col_text: &str) -> Option<String> {
    use sql::token::Token;
    let toks = sql::token::tokenize(sql).ok()?;
    let open = toks.iter().position(|t| matches!(t.token, Token::LParen))?;
    let mut depth = 0i32;
    let mut close = None;
    for (i, sp) in toks.iter().enumerate().skip(open) {
        match sp.token {
            Token::LParen => depth += 1,
            Token::RParen => {
                depth -= 1;
                if depth == 0 {
                    close = Some(i);
                    break;
                }
            }
            _ => {}
        }
    }
    let pos = toks[close?].start;
    let mut out = String::with_capacity(sql.len() + col_text.len() + 2);
    out.push_str(&sql[..pos]);
    out.push_str(", ");
    out.push_str(col_text.trim());
    out.push_str(&sql[pos..]);
    Some(out)
}

/// Remove the column named `col` (and one adjacent comma) from a `CREATE TABLE`
/// statement's text, preserving everything else verbatim — how SQLite records a
/// `DROP COLUMN`. Returns `None` if the column or list can't be located.
fn drop_column_from_create(sql: &str, col: &str) -> Option<String> {
    use sql::token::Token;
    let toks = sql::token::tokenize(sql).ok()?;
    let open = toks.iter().position(|t| matches!(t.token, Token::LParen))?;
    // The matching close of the column list, and the top-level comma separators.
    let mut depth = 0i32;
    let mut close = None;
    let mut seps = Vec::new();
    for (i, sp) in toks.iter().enumerate().skip(open) {
        match sp.token {
            Token::LParen => depth += 1,
            Token::RParen => {
                depth -= 1;
                if depth == 0 {
                    close = Some(i);
                    break;
                }
            }
            Token::Comma if depth == 1 => seps.push(i),
            _ => {}
        }
    }
    let close = close?;
    // Segment boundaries: the opener, each top-level comma, then the closer. The
    // first token after each boundary begins a column def or table constraint.
    let mut bounds = alloc::vec![open];
    bounds.extend_from_slice(&seps);
    bounds.push(close);
    let n = bounds.len() - 1; // number of segments
    let is_named = |i: usize| {
        matches!(&toks.get(i).map(|t| &t.token),
            Some(Token::Word(w) | Token::Ident(w)) if w.eq_ignore_ascii_case(col))
    };
    let j = (0..n).find(|&j| bounds[j] + 1 < bounds[j + 1] && is_named(bounds[j] + 1))?;
    let (del_start, del_end) = if j < n - 1 {
        // Not the last segment: drop it and the comma that follows.
        (toks[bounds[j] + 1].start, toks[bounds[j + 1] + 1].start)
    } else {
        // The last segment: drop the comma that precedes it through its last token.
        (toks[bounds[j]].start, toks[close - 1].end)
    };
    let mut out = String::with_capacity(sql.len());
    out.push_str(&sql[..del_start]);
    out.push_str(&sql[del_end..]);
    Some(out)
}

/// Best-effort label for an unaliased result expression.
fn expr_label(expr: &Expr) -> String {
    match expr {
        Expr::Column { column, .. } => column.clone(),
        Expr::Literal(Literal::Integer(i)) => i.to_string(),
        Expr::Literal(Literal::Str(s)) => s.clone(),
        Expr::Function { name, .. } => name.clone(),
        Expr::Paren(e) => expr_label(e),
        _ => "expr".to_string(),
    }
}

/// The name of a result column, matching SQLite: an `AS` alias wins; a bare
/// column reference uses the column name; any other expression is named after
/// its verbatim source span (`SELECT a+b` → `a+b`), falling back to
/// [`expr_label`] when no span was captured (synthetic columns).
fn result_column_label(expr: &Expr, alias: &Option<String>, source: &Option<String>) -> String {
    if let Some(a) = alias {
        return a.clone();
    }
    match expr {
        Expr::Column { column, .. } => column.clone(),
        _ => source.clone().unwrap_or_else(|| expr_label(expr)),
    }
}

/// Detect an `INTEGER PRIMARY KEY` rowid alias column (must be declared exactly
/// `INTEGER`, per SQLite — `INT PRIMARY KEY` does not alias the rowid).
/// The collating sequences for a `WITHOUT ROWID` table's stored columns, in
/// on-disk (PK-first) order — used to order its clustered b-tree.
fn wr_storage_collations(meta: &TableMeta) -> Vec<crate::value::Collation> {
    meta.storage_order
        .iter()
        .map(|&c| meta.columns[c].collation)
        .collect()
}

/// The declared collating sequence of a column (`COLLATE name`), `BINARY` if
/// none or unrecognized.
fn column_collation(col: &ColumnDef) -> crate::value::Collation {
    col.constraints
        .iter()
        .find_map(|c| match c {
            ColumnConstraint::Collate(name) => crate::value::Collation::parse(name),
            _ => None,
        })
        .unwrap_or_default()
}

/// The UNIQUE / non-rowid PRIMARY KEY column-index sets of a table, in
/// declaration order (column-level constraints first, in column order, then
/// table-level constraints). This is exactly the order SQLite numbers its
/// `sqlite_autoindex_<table>_<n>` automatic indexes.
fn collect_unique_sets(ct: &CreateTable, ipk: Option<usize>) -> Vec<(Vec<usize>, OnConflict)> {
    let col_pos = |name: &str| {
        ct.columns
            .iter()
            .position(|c| c.name.eq_ignore_ascii_case(name))
    };
    // Each unique set carries its declared `ON CONFLICT` action (default `Abort`),
    // applied when an INSERT/UPDATE without its own `OR <action>` violates it.
    let mut unique: Vec<(Vec<usize>, OnConflict)> = Vec::new();
    for (i, c) in ct.columns.iter().enumerate() {
        for k in &c.constraints {
            match k {
                ColumnConstraint::Unique(oc) => unique.push((alloc::vec![i], *oc)),
                ColumnConstraint::PrimaryKey { on_conflict, .. } if Some(i) != ipk => {
                    unique.push((alloc::vec![i], *on_conflict))
                }
                _ => {}
            }
        }
    }
    for tc in &ct.constraints {
        let (names, oc) = match tc {
            TableConstraint::Unique(n, oc) | TableConstraint::PrimaryKey(n, oc) => (n, *oc),
            _ => continue,
        };
        let idxs: Option<Vec<usize>> = names.iter().map(|n| col_pos(n)).collect();
        if let Some(set) = idxs {
            // Skip a single-column PK that is the rowid alias.
            if !(set.len() == 1 && Some(set[0]) == ipk) {
                unique.push((set, oc));
            }
        }
    }
    unique
}

/// Convert a `WITHOUT ROWID` row from declared column order to on-disk storage
/// order (PK columns first, then the rest).
fn permute_row(meta: &TableMeta, declared: &[Value]) -> Vec<Value> {
    meta.storage_order
        .iter()
        .map(|&i| declared[i].clone())
        .collect()
}

/// The auto-vacuum mode recorded in a database header: 0 = NONE, 1 = FULL,
/// 2 = INCREMENTAL. Auto-vacuum is on iff the largest-root-page field is
/// non-zero; the incremental-vacuum flag then selects the mode.
fn auto_vacuum_mode(header: &crate::format::DatabaseHeader) -> u32 {
    if header.largest_root_page == 0 {
        0
    } else if header.incremental_vacuum == 0 {
        1
    } else {
        2
    }
}

/// Remove an explicit `schema.` qualifier from a qualified `CREATE` statement's
/// text so the SQL stored in the target catalog is bare-named (the `schema.`
/// prefix is invalid in that database's own namespace, and sqlite3 rejects it).
///
/// In an *explicitly* qualified CREATE the first `.` token is the object-name
/// qualifier (only keywords precede the name). `schema` is the resolved
/// qualifier; when it came from the `TEMP` keyword rather than the text (so the
/// first `.` is something else, e.g. `NEW.col` in a trigger body) the leading
/// identifier won't match and the text is returned unchanged.
fn strip_schema_qualifier(sql: &str, schema: &str) -> Result<String> {
    use crate::sql::token::Token;
    let toks = crate::sql::token::tokenize(sql)?;
    for (i, t) in toks.iter().enumerate() {
        if i == 0 || !matches!(t.token, Token::Dot) {
            continue;
        }
        let lead = match &toks[i - 1].token {
            Token::Word(s) | Token::Ident(s) => Some(s.as_str()),
            _ => None,
        };
        if lead.is_some_and(|s| s.eq_ignore_ascii_case(schema)) {
            let schema_start = toks[i - 1].start;
            let name_start = toks.get(i + 1).map_or(sql.len(), |s| s.start);
            let mut out = String::with_capacity(sql.len());
            out.push_str(&sql[..schema_start]);
            out.push_str(&sql[name_start..]);
            return Ok(out);
        }
        // The first `.` is not the object qualifier — nothing to strip.
        break;
    }
    Ok(sql.into())
}

/// The inverse of [`permute_row`]: storage order back to declared column order.
fn unpermute_row(meta: &TableMeta, storage: Vec<Value>) -> Vec<Value> {
    let mut row = alloc::vec![Value::Null; meta.columns.len()];
    for (k, &col) in meta.storage_order.iter().enumerate() {
        if let Some(v) = storage.get(k) {
            row[col] = v.clone();
        }
    }
    row
}

/// The column positions of a table's PRIMARY KEY, in key order (column-level
/// `PRIMARY KEY` or a table-level `PRIMARY KEY(...)`). Empty if none.
fn primary_key_positions(ct: &CreateTable) -> Vec<usize> {
    for (i, c) in ct.columns.iter().enumerate() {
        if c.constraints
            .iter()
            .any(|k| matches!(k, ColumnConstraint::PrimaryKey { .. }))
        {
            return alloc::vec![i];
        }
    }
    for tc in &ct.constraints {
        if let TableConstraint::PrimaryKey(names, _) = tc {
            let pos: Option<Vec<usize>> = names
                .iter()
                .map(|n| {
                    ct.columns
                        .iter()
                        .position(|c| c.name.eq_ignore_ascii_case(n))
                })
                .collect();
            if let Some(pos) = pos {
                return pos;
            }
        }
    }
    Vec::new()
}

/// Parse the `<n>` from `sqlite_autoindex_<table>_<n>` (1-based), if `name` is an
/// automatic index for `table`.
fn autoindex_number(name: &str, table: &str) -> Option<usize> {
    let prefix = alloc::format!("sqlite_autoindex_{table}_");
    name.strip_prefix(&prefix)?.parse::<usize>().ok()
}

fn find_integer_primary_key(ct: &CreateTable) -> Option<usize> {
    for (i, c) in ct.columns.iter().enumerate() {
        let is_integer = c
            .type_name
            .as_deref()
            .is_some_and(|t| t.eq_ignore_ascii_case("integer"));
        // A column-level `INTEGER PRIMARY KEY` is the rowid alias — EXCEPT when it
        // carries the `DESC` keyword, which sqlite treats as an ordinary table
        // (the column gets its own index and the rowid is auto-assigned). `ASC`
        // and the table-level `PRIMARY KEY(col)` form remain aliases.
        let is_pk_alias = c.constraints.iter().any(|k| {
            matches!(
                k,
                ColumnConstraint::PrimaryKey {
                    descending: false,
                    ..
                }
            )
        });
        if is_integer && is_pk_alias {
            return Some(i);
        }
    }
    // Table-level single-column PRIMARY KEY over an INTEGER column.
    for tc in &ct.constraints {
        if let TableConstraint::PrimaryKey(cols, _) = tc {
            if cols.len() == 1 {
                if let Some(i) = ct.columns.iter().position(|c| c.name == cols[0]) {
                    if ct.columns[i]
                        .type_name
                        .as_deref()
                        .is_some_and(|t| t.eq_ignore_ascii_case("integer"))
                    {
                        return Some(i);
                    }
                }
            }
        }
    }
    None
}

#[cfg(all(test, feature = "fts5", feature = "std"))]
mod fts5_index_route_tests {
    use super::Connection;
    use crate::fts5_index::INDEX_ROUTE_HITS;
    use crate::value::Value;
    use core::sync::atomic::Ordering;
    use std::sync::Mutex;

    /// The global [`INDEX_ROUTE_HITS`] counter is shared across the whole test
    /// binary, so these two tests — which assert on its DELTA — must not run
    /// concurrently. Serialize them through this lock.
    static SERIALIZE: Mutex<()> = Mutex::new(());

    fn texts(c: &mut Connection, sql: &str) -> alloc::vec::Vec<alloc::string::String> {
        c.query(sql)
            .unwrap()
            .rows
            .into_iter()
            .map(|r| match &r[0] {
                Value::Text(s) => s.clone(),
                other => alloc::format!("{other:?}"),
            })
            .collect()
    }

    /// A single bare-term, table-wide `MATCH` is served by the segment index
    /// (`INDEX_ROUTE_HITS` rises), and returns exactly the same rows — in the same
    /// rowid order — as the documents that contain the term.
    #[test]
    fn bare_term_match_takes_index_route() {
        let _guard = SERIALIZE.lock().unwrap_or_else(|e| e.into_inner());
        let mut c = Connection::open_memory().unwrap();
        c.execute("CREATE VIRTUAL TABLE t USING fts5(body)")
            .unwrap();
        for (i, body) in [
            "the quick brown fox",
            "lazy dog sleeps",
            "fox and hound",
            "nothing relevant here",
            "a quick test",
        ]
        .iter()
        .enumerate()
        {
            c.execute(&alloc::format!(
                "INSERT INTO t(rowid, body) VALUES({}, '{}')",
                i + 1,
                body
            ))
            .unwrap();
        }

        // Bare single term → index route.
        let before = INDEX_ROUTE_HITS.load(Ordering::Relaxed);
        let rows = texts(&mut c, "SELECT body FROM t WHERE t MATCH 'fox'");
        let after = INDEX_ROUTE_HITS.load(Ordering::Relaxed);
        assert!(after > before, "bare-term MATCH must take the index route");
        assert_eq!(rows, ["the quick brown fox", "fox and hound"]);

        // Repeated-in-one-doc, multi-doc, and absent terms.
        assert_eq!(
            texts(&mut c, "SELECT body FROM t WHERE t MATCH 'quick'"),
            ["the quick brown fox", "a quick test"]
        );
        assert!(texts(&mut c, "SELECT body FROM t WHERE t MATCH 'zebra'").is_empty());
    }

    /// Shapes that are neither a single bare term nor a two-term phrase stay on the
    /// document scan (`INDEX_ROUTE_HITS` unchanged), still returning correct results.
    #[test]
    fn non_bare_shapes_stay_on_scan() {
        let _guard = SERIALIZE.lock().unwrap_or_else(|e| e.into_inner());
        let mut c = Connection::open_memory().unwrap();
        c.execute("CREATE VIRTUAL TABLE t USING fts5(body)")
            .unwrap();
        for (i, body) in ["quick brown fox", "slow brown bear", "quick red fox"]
            .iter()
            .enumerate()
        {
            c.execute(&alloc::format!(
                "INSERT INTO t(rowid, body) VALUES({}, '{}')",
                i + 1,
                body
            ))
            .unwrap();
        }
        // A prefixed/anchored phrase, a NEAR group with the wrong shape, and a
        // boolean mixing a phrase/prefix/column-scoped operand must not be
        // index-routed. (A bare K-term phrase IS, for any K ≥ 2 — see
        // `two_term_phrase_match_takes_index_route` /
        // `k_term_phrase_match_takes_index_route` — an N-operand bare-term boolean
        // TREE IS — see `bare_term_boolean_tree_match_takes_index_route` — a lone
        // bare prefix term IS — see `prefix_term_match_takes_index_route` — and a
        // lone two-single-token bare-term NEAR group IS — see
        // `two_term_near_match_takes_index_route`.) Every leaf of a routed boolean
        // tree must be a plain table-wide bare term; a single non-bare leaf forces
        // the whole query back to the scan, and a NEAR group only routes when it is
        // the entire query with exactly two bare single-token operands.
        for q in [
            "\"quick brown\" OR fox",
            "^\"quick brown\"",
            "^qui*",                        // anchored prefix → stays on scan
            "qui* AND fox",                 // prefix operand in a boolean → stays on scan
            "NEAR(quick brown fox, 3)",     // 3 NEAR operands → stays on scan
            "NEAR(\"quick brown\" fox)",    // a phrase NEAR operand → stays on scan
            "NEAR(quick fo*)",              // a prefix NEAR operand → stays on scan
            "fox AND NEAR(quick brown)",    // NEAR inside a boolean → stays on scan
            "\"quick brown\" OR bear",      // phrase operand → stays on scan
            "title : quick OR fox",         // column-scoped operand → stays on scan
            "quick AND brown AND qui*",     // 3 operands, one a prefix → scan
            "(quick OR brown) AND fox*",    // parenthesized, one a prefix → scan
            "quick AND NEAR(brown fox, 2)", // a NEAR leaf in the tree → scan
        ] {
            let before = INDEX_ROUTE_HITS.load(Ordering::Relaxed);
            let sql = alloc::format!("SELECT body FROM t WHERE t MATCH '{q}'");
            let _ = c.query(&sql).unwrap();
            let after = INDEX_ROUTE_HITS.load(Ordering::Relaxed);
            assert_eq!(after, before, "query {q:?} must stay on the scan");
        }
    }

    /// A two-term phrase (`tbl MATCH '"a b"'`, table-wide and column-scoped) over a
    /// fully indexed table is served by the segment index (`INDEX_ROUTE_HITS` rises)
    /// and returns exactly the documents whose tokens occur at adjacent positions —
    /// the same set the document scan produces.
    #[test]
    fn two_term_phrase_match_takes_index_route() {
        let _guard = SERIALIZE.lock().unwrap_or_else(|e| e.into_inner());
        let mut c = Connection::open_memory().unwrap();
        c.execute("CREATE VIRTUAL TABLE t USING fts5(title, body)")
            .unwrap();
        // "quick brown" is adjacent in row 1 (title) and row 4 (body); rows 2/3 have
        // the words but not adjacent / not in order / split across columns.
        let docs = [
            ("the quick brown fox", "nothing here"),
            ("quick red brown fox", "all separate words"),
            ("brown then quick", "reversed order only"),
            ("plain title text", "a quick brown hare"),
            ("quick", "brown"), // split across columns: NOT a phrase match
        ];
        for (i, (title, body)) in docs.iter().enumerate() {
            c.execute(&alloc::format!(
                "INSERT INTO t(rowid, title, body) VALUES({}, '{}', '{}')",
                i + 1,
                title,
                body
            ))
            .unwrap();
        }
        // Table-wide phrase: adjacent in some column → rows 1 and 4.
        let before = INDEX_ROUTE_HITS.load(Ordering::Relaxed);
        let rows: alloc::vec::Vec<i64> = c
            .query("SELECT rowid FROM t WHERE t MATCH '\"quick brown\"' ORDER BY rowid")
            .unwrap()
            .rows
            .into_iter()
            .map(|r| match r[0] {
                Value::Integer(i) => i,
                ref o => panic!("non-integer rowid: {o:?}"),
            })
            .collect();
        assert!(
            INDEX_ROUTE_HITS.load(Ordering::Relaxed) > before,
            "table-wide phrase must take the index route"
        );
        assert_eq!(rows, [1, 4]);

        // Column-scoped phrase: only the body column → row 4.
        let before = INDEX_ROUTE_HITS.load(Ordering::Relaxed);
        let rows: alloc::vec::Vec<i64> = c
            .query("SELECT rowid FROM t WHERE t MATCH 'body : \"quick brown\"' ORDER BY rowid")
            .unwrap()
            .rows
            .into_iter()
            .map(|r| match r[0] {
                Value::Integer(i) => i,
                ref o => panic!("non-integer rowid: {o:?}"),
            })
            .collect();
        assert!(
            INDEX_ROUTE_HITS.load(Ordering::Relaxed) > before,
            "column-scoped phrase must take the index route"
        );
        assert_eq!(rows, [4]);
    }

    /// A K-term phrase (K ≥ 3, `tbl MATCH '"a b c"'`, table-wide and column-scoped,
    /// including a repeated-word phrase) over a fully indexed table is served by the
    /// segment index (`INDEX_ROUTE_HITS` rises) and returns exactly the documents
    /// whose tokens occur at CONSECUTIVE positions in one column — the same set the
    /// document scan produces. A run that straddles a column boundary must NOT match.
    #[test]
    fn k_term_phrase_match_takes_index_route() {
        let _guard = SERIALIZE.lock().unwrap_or_else(|e| e.into_inner());
        let mut c = Connection::open_memory().unwrap();
        c.execute("CREATE VIRTUAL TABLE t USING fts5(title, body)")
            .unwrap();
        // "quick brown fox" is consecutive in row 1 (title) and row 4 (body); row 2
        // has the words non-consecutive, row 3 reversed, row 5 splits the run across
        // the column boundary (title ends "quick brown", body starts "fox") so it
        // must NOT match. Row 6 carries the repeated-word run "na na na" in title.
        let docs = [
            ("the quick brown fox runs", "nothing here at all"),
            ("quick red brown gray fox", "all separate words here"),
            ("fox brown quick reversed", "still reversed only here"),
            ("plain title text here", "a quick brown fox hops"),
            ("ends with quick brown", "fox starts the body now"),
            ("na na na batman here", "plain body without it now"),
        ];
        for (i, (title, body)) in docs.iter().enumerate() {
            c.execute(&alloc::format!(
                "INSERT INTO t(rowid, title, body) VALUES({}, '{}', '{}')",
                i + 1,
                title,
                body
            ))
            .unwrap();
        }
        // Table-wide 3-word phrase: consecutive in some column → rows 1 and 4. Row 5
        // (split across columns) must NOT appear.
        let before = INDEX_ROUTE_HITS.load(Ordering::Relaxed);
        let rows: alloc::vec::Vec<i64> = c
            .query("SELECT rowid FROM t WHERE t MATCH '\"quick brown fox\"' ORDER BY rowid")
            .unwrap()
            .rows
            .into_iter()
            .map(|r| match r[0] {
                Value::Integer(i) => i,
                ref o => panic!("non-integer rowid: {o:?}"),
            })
            .collect();
        assert!(
            INDEX_ROUTE_HITS.load(Ordering::Relaxed) > before,
            "table-wide K-term phrase must take the index route"
        );
        assert_eq!(rows, [1, 4]);

        // Column-scoped K-term phrase: only the body column → row 4.
        let before = INDEX_ROUTE_HITS.load(Ordering::Relaxed);
        let rows: alloc::vec::Vec<i64> = c
            .query("SELECT rowid FROM t WHERE t MATCH 'body : \"quick brown fox\"' ORDER BY rowid")
            .unwrap()
            .rows
            .into_iter()
            .map(|r| match r[0] {
                Value::Integer(i) => i,
                ref o => panic!("non-integer rowid: {o:?}"),
            })
            .collect();
        assert!(
            INDEX_ROUTE_HITS.load(Ordering::Relaxed) > before,
            "column-scoped K-term phrase must take the index route"
        );
        assert_eq!(rows, [4]);

        // Repeated-word 3-term phrase: "na na na" consecutive in title → row 6.
        let before = INDEX_ROUTE_HITS.load(Ordering::Relaxed);
        let rows: alloc::vec::Vec<i64> = c
            .query("SELECT rowid FROM t WHERE t MATCH '\"na na na\"' ORDER BY rowid")
            .unwrap()
            .rows
            .into_iter()
            .map(|r| match r[0] {
                Value::Integer(i) => i,
                ref o => panic!("non-integer rowid: {o:?}"),
            })
            .collect();
        assert!(
            INDEX_ROUTE_HITS.load(Ordering::Relaxed) > before,
            "repeated-word K-term phrase must take the index route"
        );
        assert_eq!(rows, [6]);
    }

    /// A lone two-single-token bare-term `NEAR` group (`tbl MATCH 'NEAR(a b, n)'`,
    /// and the default-distance `NEAR(a b)` = n=10) over a fully indexed table is
    /// served by the segment index (`INDEX_ROUTE_HITS` rises): it intersects the two
    /// terms' doclists and keeps the documents with positions `|pa − pb| <= n + 1`
    /// in some column — exactly the set the document scan's NEAR predicate matches.
    #[test]
    fn two_term_near_match_takes_index_route() {
        let _guard = SERIALIZE.lock().unwrap_or_else(|e| e.into_inner());
        let mut c = Connection::open_memory().unwrap();
        c.execute("CREATE VIRTUAL TABLE t USING fts5(title, body)")
            .unwrap();
        // a@pos / b@pos per column. Gaps: row1 adjacent (1), row2 gap 2, row3 gap 3,
        // row4 only `a`, row5 the pair split across columns (never a NEAR match),
        // row6 the pair adjacent only in `body`.
        let docs = [
            ("alpha beta", "nothing here"),        // 1: gap 1 in title
            ("alpha x beta", "irrelevant"),        // 2: gap 2 in title
            ("alpha x y beta", "irrelevant"),      // 3: gap 3 in title
            ("alpha only here", "no second term"), // 4: only alpha
            ("alpha here", "beta there"),          // 5: split across columns
            ("plain title", "alpha beta close"),   // 6: gap 1 in body
        ];
        for (i, (title, body)) in docs.iter().enumerate() {
            c.execute(&alloc::format!(
                "INSERT INTO t(rowid, title, body) VALUES({}, '{}', '{}')",
                i + 1,
                title,
                body
            ))
            .unwrap();
        }
        // NEAR(alpha beta, 1) → |pa-pb| <= 2: gap-1 (rows 1, 6) and gap-2 (row 2).
        let before = INDEX_ROUTE_HITS.load(Ordering::Relaxed);
        let rows: alloc::vec::Vec<i64> = c
            .query("SELECT rowid FROM t WHERE t MATCH 'NEAR(alpha beta, 1)' ORDER BY rowid")
            .unwrap()
            .rows
            .into_iter()
            .map(|r| match r[0] {
                Value::Integer(i) => i,
                ref o => panic!("non-integer rowid: {o:?}"),
            })
            .collect();
        assert!(
            INDEX_ROUTE_HITS.load(Ordering::Relaxed) > before,
            "two-term NEAR must take the index route"
        );
        assert_eq!(rows, [1, 2, 6]);

        // NEAR(alpha beta, 0) → |pa-pb| <= 1: only adjacent rows 1 and 6.
        let before = INDEX_ROUTE_HITS.load(Ordering::Relaxed);
        let rows: alloc::vec::Vec<i64> = c
            .query("SELECT rowid FROM t WHERE t MATCH 'NEAR(alpha beta, 0)' ORDER BY rowid")
            .unwrap()
            .rows
            .into_iter()
            .map(|r| match r[0] {
                Value::Integer(i) => i,
                ref o => panic!("non-integer rowid: {o:?}"),
            })
            .collect();
        assert!(
            INDEX_ROUTE_HITS.load(Ordering::Relaxed) > before,
            "two-term NEAR(.,0) must take the index route"
        );
        assert_eq!(rows, [1, 6]);

        // Default distance NEAR(alpha beta) = n=10 → all docs with both terms in
        // some column within 11 positions: rows 1, 2, 3, 6 (row 5 is split columns).
        let before = INDEX_ROUTE_HITS.load(Ordering::Relaxed);
        let rows: alloc::vec::Vec<i64> = c
            .query("SELECT rowid FROM t WHERE t MATCH 'NEAR(alpha beta)' ORDER BY rowid")
            .unwrap()
            .rows
            .into_iter()
            .map(|r| match r[0] {
                Value::Integer(i) => i,
                ref o => panic!("non-integer rowid: {o:?}"),
            })
            .collect();
        assert!(
            INDEX_ROUTE_HITS.load(Ordering::Relaxed) > before,
            "default-distance NEAR must take the index route"
        );
        assert_eq!(rows, [1, 2, 3, 6]);
    }

    /// A lone bare PREFIX term (`tbl MATCH 'pre*'`, table-wide and column-scoped)
    /// over a fully indexed table is served by the segment index
    /// (`INDEX_ROUTE_HITS` rises): it unions the doclists of every indexed term that
    /// begins with the prefix, returning exactly the documents the scan's
    /// `doc_token.starts_with(prefix)` predicate matches, in rowid order.
    #[test]
    fn prefix_term_match_takes_index_route() {
        let _guard = SERIALIZE.lock().unwrap_or_else(|e| e.into_inner());
        let mut c = Connection::open_memory().unwrap();
        c.execute("CREATE VIRTUAL TABLE t USING fts5(title, body)")
            .unwrap();
        // terms beginning with "qu": quick(1,3 title), quiet(2 body); "fo": fox.
        let docs = [
            ("quick brown fox", "nothing here"),
            ("calm title", "quiet body now"),
            ("quick red fox", "all separate"),
            ("plain title", "no match in body"),
        ];
        for (i, (title, body)) in docs.iter().enumerate() {
            c.execute(&alloc::format!(
                "INSERT INTO t(rowid, title, body) VALUES({}, '{}', '{}')",
                i + 1,
                title,
                body
            ))
            .unwrap();
        }
        // Table-wide prefix: any term starting "qu" → rows 1, 2, 3.
        let before = INDEX_ROUTE_HITS.load(Ordering::Relaxed);
        let rows: alloc::vec::Vec<i64> = c
            .query("SELECT rowid FROM t WHERE t MATCH 'qu*' ORDER BY rowid")
            .unwrap()
            .rows
            .into_iter()
            .map(|r| match r[0] {
                Value::Integer(i) => i,
                ref o => panic!("non-integer rowid: {o:?}"),
            })
            .collect();
        assert!(
            INDEX_ROUTE_HITS.load(Ordering::Relaxed) > before,
            "table-wide prefix must take the index route"
        );
        assert_eq!(rows, [1, 2, 3]);

        // Column-scoped prefix: only the title column → quick in rows 1, 3.
        let before = INDEX_ROUTE_HITS.load(Ordering::Relaxed);
        let rows: alloc::vec::Vec<i64> = c
            .query("SELECT rowid FROM t WHERE t MATCH 'title : qu*' ORDER BY rowid")
            .unwrap()
            .rows
            .into_iter()
            .map(|r| match r[0] {
                Value::Integer(i) => i,
                ref o => panic!("non-integer rowid: {o:?}"),
            })
            .collect();
        assert!(
            INDEX_ROUTE_HITS.load(Ordering::Relaxed) > before,
            "column-scoped prefix must take the index route"
        );
        assert_eq!(rows, [1, 3]);
    }

    /// An N-operand bare-term boolean TREE — two operands (`a AND b`, `a OR b`,
    /// `a NOT b`, the implicit-AND `a b`) AND 3+ operands with mixed AND/OR/NOT and
    /// parentheses — over a fully indexed table is served by the segment index
    /// (`INDEX_ROUTE_HITS` rises) via bottom-up doclist set-ops, returning exactly
    /// the same documents — in the same rowid order — as the document scan, with
    /// FTS5's `NOT` > `AND` > `OR` precedence honored.
    #[test]
    fn bare_term_boolean_tree_match_takes_index_route() {
        let _guard = SERIALIZE.lock().unwrap_or_else(|e| e.into_inner());
        let mut c = Connection::open_memory().unwrap();
        c.execute("CREATE VIRTUAL TABLE t USING fts5(body)")
            .unwrap();
        // term presence by rowid:
        //   fox:   1, 3, 4, 5      brown: 1, 2, 4      dog: 2, 5
        let docs = [
            "the quick brown fox", // 1: fox brown
            "lazy brown dog",      // 2: brown dog
            "fox in the henhouse", // 3: fox
            "brown fox runs",      // 4: fox brown
            "a fox and a dog",     // 5: fox dog
        ];
        for (i, body) in docs.iter().enumerate() {
            c.execute(&alloc::format!(
                "INSERT INTO t(rowid, body) VALUES({}, '{}')",
                i + 1,
                body
            ))
            .unwrap();
        }
        let ids = |c: &mut Connection, sql: &str| -> alloc::vec::Vec<i64> {
            c.query(sql)
                .unwrap()
                .rows
                .into_iter()
                .map(|r| match r[0] {
                    Value::Integer(i) => i,
                    ref o => panic!("non-integer rowid: {o:?}"),
                })
                .collect()
        };
        // (query, expected rowids) — AND=intersection, OR=union, NOT=difference,
        // and the bare juxtaposition is implicit AND.
        for (q, want) in [
            ("fox AND brown", alloc::vec![1i64, 4]),
            ("fox OR dog", alloc::vec![1, 2, 3, 4, 5]),
            ("fox NOT brown", alloc::vec![3, 5]),
            ("brown NOT fox", alloc::vec![2]),
            ("fox brown", alloc::vec![1, 4]), // implicit AND
            ("zebra AND fox", alloc::vec![]), // absent operand → empty
            ("zebra OR dog", alloc::vec![2, 5]),
            // 3+ operands and parentheses (term presence by rowid above):
            //   fox{1,3,4,5} brown{1,2,4} dog{2,5}
            ("fox AND brown AND dog", alloc::vec![]), // ∩ = {}
            ("fox OR brown OR dog", alloc::vec![1, 2, 3, 4, 5]), // ∪ = all
            ("fox brown dog", alloc::vec![]),         // implicit AND of three
            // Precedence: `fox OR brown AND dog` = `fox OR (brown AND dog)`.
            //   brown∩dog = {2}; fox{1,3,4,5} ∪ {2} = {1,2,3,4,5}.
            ("fox OR brown AND dog", alloc::vec![1, 2, 3, 4, 5]),
            // Parentheses override: `(fox OR brown) AND dog`.
            //   fox∪brown = {1,2,3,4,5}; ∩ dog{2,5} = {2,5}.
            ("(fox OR brown) AND dog", alloc::vec![2, 5]),
            // A NOT inside a parenthesized tree: `(fox OR brown) NOT dog`.
            //   {1,2,3,4,5} − dog{2,5} = {1,3,4}.
            ("(fox OR brown) NOT dog", alloc::vec![1, 3, 4]),
            // NOT binds tighter than AND: `fox AND brown NOT dog`
            //   = `fox AND (brown NOT dog)`; brown−dog = {1,4}; ∩ fox = {1,4}.
            ("fox AND brown NOT dog", alloc::vec![1, 4]),
        ] {
            let before = INDEX_ROUTE_HITS.load(Ordering::Relaxed);
            let rows = ids(
                &mut c,
                &alloc::format!("SELECT rowid FROM t WHERE t MATCH '{q}' ORDER BY rowid"),
            );
            let after = INDEX_ROUTE_HITS.load(Ordering::Relaxed);
            assert!(after > before, "boolean {q:?} must take the index route");
            assert_eq!(rows, want, "boolean {q:?}");
        }
    }

    /// A column-scoped single bare term (`tbl MATCH 'col : word'`) over a fully
    /// indexed multi-column table is served by the segment index
    /// (`INDEX_ROUTE_HITS` rises) and returns exactly the documents whose named
    /// column contains the term — the same set the document scan produces.
    #[test]
    fn column_scoped_bare_term_match_takes_index_route() {
        let _guard = SERIALIZE.lock().unwrap_or_else(|e| e.into_inner());
        let mut c = Connection::open_memory().unwrap();
        c.execute("CREATE VIRTUAL TABLE t USING fts5(title, body)")
            .unwrap();
        // "fox" lands in title for rows 1,4; in body for rows 2,3; in both for 5.
        let docs = [
            ("the fox", "sleeps soundly"),
            ("a lazy dog", "chases a fox"),
            ("quiet night", "fox runs past"),
            ("fox tracks", "across the snow"),
            ("fox tale", "the fox returns"),
        ];
        for (i, (title, body)) in docs.iter().enumerate() {
            c.execute(&alloc::format!(
                "INSERT INTO t(rowid, title, body) VALUES({}, '{}', '{}')",
                i + 1,
                title,
                body
            ))
            .unwrap();
        }

        let ids = |c: &mut Connection, sql: &str| -> alloc::vec::Vec<i64> {
            c.query(sql)
                .unwrap()
                .rows
                .into_iter()
                .map(|r| match r[0] {
                    Value::Integer(i) => i,
                    ref o => panic!("non-integer rowid: {o:?}"),
                })
                .collect()
        };

        // title:fox → rows whose TITLE has fox = 1, 4, 5. Index-routed.
        let before = INDEX_ROUTE_HITS.load(Ordering::Relaxed);
        let rows = ids(
            &mut c,
            "SELECT rowid FROM t WHERE t MATCH 'title : fox' ORDER BY rowid",
        );
        let after = INDEX_ROUTE_HITS.load(Ordering::Relaxed);
        assert!(
            after > before,
            "column-scoped MATCH must take the index route"
        );
        assert_eq!(rows, [1, 4, 5]);

        // body:fox → rows whose BODY has fox = 2, 3, 5. Also index-routed.
        let before = INDEX_ROUTE_HITS.load(Ordering::Relaxed);
        let rows = ids(
            &mut c,
            "SELECT rowid FROM t WHERE t MATCH 'body:fox' ORDER BY rowid",
        );
        let after = INDEX_ROUTE_HITS.load(Ordering::Relaxed);
        assert!(
            after > before,
            "compact `body:fox` must take the index route"
        );
        assert_eq!(rows, [2, 3, 5]);

        // A column filter naming a non-existent column matches nothing and stays on
        // the scan (which also yields nothing).
        let before = INDEX_ROUTE_HITS.load(Ordering::Relaxed);
        let rows = ids(
            &mut c,
            "SELECT rowid FROM t WHERE t MATCH 'nope:fox' ORDER BY rowid",
        );
        let after = INDEX_ROUTE_HITS.load(Ordering::Relaxed);
        assert_eq!(after, before, "unknown-column filter must stay on the scan");
        assert!(rows.is_empty());
    }
}