graphitesql 0.0.7

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
//! 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>,
    /// 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.
    fts5_rank: core::cell::RefCell<Option<Fts5QueryCtx>>,
}

/// 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),
            functions: alloc::collections::BTreeMap::new(),
            aggregates: alloc::collections::BTreeMap::new(),
            fts5_rank: core::cell::RefCell::new(None),
        })
    }

    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),
            functions: alloc::collections::BTreeMap::new(),
            aggregates: alloc::collections::BTreeMap::new(),
            fts5_rank: core::cell::RefCell::new(None),
        })
    }

    /// 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"));
        };
        // 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,
            });
        };
        // Single plain table: materialize its rows and run a cursor program.
        if !from.joins.is_empty() || from.first.subquery.is_some() || from.first.tvf_args.is_some()
        {
            return Err(Error::Unsupported("VDBE: only a single plain table"));
        }
        let meta = self.table_meta(&from.first.name, from.first.alias.as_deref())?;
        let col_names: Vec<String> = meta.columns.iter().map(|c| c.name.clone()).collect();
        let prog = vdbe::compile_table_select(&sel, &col_names)?;
        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 result = vdbe::run_rows(&prog, &rows)?;
        Ok(QueryResult {
            columns: prog.columns,
            rows: 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 {
                    return Err(Error::Unsupported(
                        "plain EXPLAIN (VDBE bytecode); use EXPLAIN QUERY PLAN",
                    ));
                }
                self.explain_query_plan(&stmt, params)
            }
            _ => 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" => {
                let mode = if self.backend.wal_mode() {
                    "wal"
                } 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(0))),
            "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" => Ok(single("timeout", Value::Integer(0))),
            "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()))),
            _ => 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 });
        }
        // 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,
            });
        }
        let obj = self
            .schema
            .table(&table)
            .ok_or_else(|| 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 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)))
                        .cloned()
                        .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 descending flags (from the CREATE INDEX text).
        let descs: Vec<bool> = match &obj.sql {
            Some(sql) => match sql::parse_one(sql)? {
                Statement::CreateIndex(ci) => ci.columns.iter().map(|c| c.descending).collect(),
                _ => Vec::new(),
            },
            None => Vec::new(),
        };
        let cols: Vec<usize> = match &obj.sql {
            Some(sql) => match sql::parse_one(sql)? {
                Statement::CreateIndex(ci) => self.index_columns(&tmeta, &ci)?,
                _ => Vec::new(),
            },
            None => autoindex_number(&obj.name, &obj.tbl_name)
                .and_then(|n| tmeta.unique.get(n - 1).cloned())
                .unwrap_or_default(),
        };
        let mut rows = Vec::new();
        for (seqno, &cid) in cols.iter().enumerate() {
            if extended {
                let coll = match tmeta.columns[cid].collation {
                    crate::value::Collation::NoCase => "NOCASE",
                    crate::value::Collation::RTrim => "RTRIM",
                    crate::value::Collation::Binary => "BINARY",
                };
                rows.push(alloc::vec![
                    Value::Integer(seqno as i64),
                    Value::Integer(cid as i64),
                    Value::Text(tmeta.columns[cid].name.clone()),
                    Value::Integer(descs.get(seqno).copied().unwrap_or(false) as i64),
                    Value::Text(coll.into()),
                    Value::Integer(1), // key column
                ]);
            } else {
                rows.push(alloc::vec![
                    Value::Integer(seqno as i64),
                    Value::Integer(cid as i64),
                    Value::Text(tmeta.columns[cid].name.clone()),
                ]);
            }
        }
        // index_xinfo appends the implicit trailing rowid (an auxiliary, non-key
        // column) for an ordinary rowid table.
        if extended && !tmeta.without_rowid {
            rows.push(alloc::vec![
                Value::Integer(cols.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.
        let n = fks.len();
        for (i, (from_cols, fk)) in fks.iter().enumerate() {
            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 => {
                self.swap_db(other);
                let r = self.exec_parsed(stmt, sql, params);
                self.swap_db(other);
                r
            }
        }
    }

    /// 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 => {
                self.exec_vacuum()?;
                0
            }
            // Indexes are kept current on every write, so REINDEX is a no-op.
            Statement::Reindex => 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))
    }

    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) -> Result<()> {
        use crate::schema::ObjectType;
        if !matches!(self.backend, Backend::Write(_)) {
            return Ok(());
        }
        // Flush any WAL frames into the main image first.
        if 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| {
            name.strip_suffix("_data")
                .is_some_and(|p| vtab_names.contains(p))
        };
        // A vtab is persistent (has rows to copy) iff its backing table exists.
        let persistent_vtab = |name: &str| {
            vtab_names.contains(name) && table_names.contains(&alloc::format!("{name}_data"))
        };

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

        // Copy the compact image's pages over the current database file.
        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());
        }
        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(())
    }

    /// `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 {
                    return Ok(()); // unknown object: no-op, like SQLite
                }
            }
        };

        // 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(),
                        ));
                    }
                    _ => {}
                }
            }
        }
        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(),
                    ));
                }
            }
        }
        // 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;
        }

        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())?;
        // Build and create the resolved table `name(col1, col2, …)`.
        let cols = result
            .columns
            .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,
                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("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)| eval::compare(&row[p], k) == 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)?;
        // 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)
                .all(|(&p, k)| eval::compare(&row[p], k) == 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) {
            return Err(Error::Error(format!("no such table: {}", 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);
        }
        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.
    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 changed: Vec<String> = upd.assignments.iter().map(|(c, _)| c.clone()).collect();
        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)?;
            }
            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<()> {
        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))
    }

    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() {
            (0..n_cols).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)?;
        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) => {
                    let r = eval::to_i64(&values[ipk]);
                    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.
            {
                let r = check_not_null(&meta, &values)
                    .and_then(|()| 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 = self.find_conflicts(&ins.table, &meta, rowid, &values, None, params)?;
            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 ins.on_conflict {
                    oc @ (OnConflict::Abort | OnConflict::Fail | OnConflict::Rollback) => {
                        return Err(self.conflict_error(oc, "UNIQUE constraint failed"))
                    }
                    OnConflict::Ignore => continue, // skip this row
                    OnConflict::Replace => {
                        for cr in conflicts {
                            delete_table(self.backend.writer()?, meta.root, cr)?;
                        }
                        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;
        }
        // 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)?;
        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,
            )?
            .is_empty()
        {
            return Err(Error::Constraint("UNIQUE constraint failed".into()));
        }
        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>> {
        // 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();
        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 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);
                    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)
    }

    /// 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> {
        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> {
        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)?;
        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 changed: Vec<String> = upd.assignments.iter().map(|(c, _)| c.clone()).collect();
        // 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();
        }

        let mut affected = 0;
        for (rowid, mut values, matched_from) in targets {
            let old_row = values.clone();
            // Apply SET assignments evaluated against the current row (joined to
            // the matched FROM row, for UPDATE … FROM).
            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;
            }
            apply_column_affinity(&meta, &mut values);
            self.materialize_generated(&meta, &mut values, params)?;
            // NOT NULL / CHECK / STRICT-type constraints. `UPDATE OR IGNORE` skips
            // a row that violates one rather than failing the statement.
            {
                let r = check_not_null(&meta, &values)
                    .and_then(|()| 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 =
                self.find_conflicts(&upd.table, &meta, new_rowid, &values, Some(rowid), params)?;
            if !conflicts.is_empty() {
                match upd.on_conflict {
                    OnConflict::Ignore => continue,
                    OnConflict::Replace => {
                        for cr in conflicts {
                            delete_table(self.backend.writer()?, meta.root, cr)?;
                        }
                    }
                    oc @ (OnConflict::Abort | OnConflict::Fail | OnConflict::Rollback) => {
                        return Err(self.conflict_error(oc, "UNIQUE constraint failed"))
                    }
                }
            }
            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()));
        }
        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(),
            ));
        }
        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;
        // A persistent module keeps its rows in a backing `<name>_data` regular
        // table (as SQLite's FTS5/R-Tree shadow tables do). Create it now, reusing
        // the normal table machinery so it is transactional and integrity-checked.
        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}")))?;
        let backing = 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,
            };
            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();
        // 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));
        }
        self.with_vtab_store(
            &module_name,
            &args,
            &ins.table,
            |module, store, arg_refs| {
                for (rowid, values) in &changes {
                    module.dyn_update(
                        arg_refs,
                        VTabChange::Insert {
                            rowid: *rowid,
                            values,
                        },
                        store,
                    )?;
                }
                Ok(changes.len())
            },
        )
    }

    /// `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()))?,
            );
        }
        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())
            },
        )
    }

    /// `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.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));
        }
        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())
            },
        )
    }

    /// 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),
        };
        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() {
            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.
    fn push_ctes(&self, sel: &Select, params: &Params) -> Result<()> {
        for cte in &sel.ctes {
            let binding = if references_name(&cte.select, &cte.name) {
                self.eval_recursive_cte(cte, params)?
            } 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) -> 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(());
                }
            }
        };
        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()
        };
        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)))
    }

    fn exec_drop(&mut self, d: &Drop) -> Result<()> {
        use crate::schema::ObjectType;
        // Dropping a persistent virtual table also drops its `<name>_data` backing
        // table, as sqlite removes a vtab's shadow tables.
        if matches!(d.kind, DropKind::Table) && self.is_virtual_table(&d.name) {
            let backing = format!("{}_data", 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 {
            if d.if_exists {
                return Ok(());
            }
            // SQLite's table↔view confusion hint when a same-named object of the
            // other kind exists; otherwise a lowercase "no such <kind>".
            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
                        )))
                    }
                    _ => {}
                }
            }
            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())?;
        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) => {
                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());
                let new_sql = sql::print::create_table(&ct);
                let table = a.table.clone();
                self.rewrite_schema_rows(|cols| {
                    if is_text(&cols[0], "table") && is_text(&cols[1], &table) {
                        cols[4] = Value::Text(new_sql.clone());
                        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}"
                    )));
                }
                ct.name = new_name.clone();
                let new_table_sql = sql::print::create_table(&ct);
                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());
                        cols[4] = Value::Text(new_table_sql.clone());
                        true
                    } else if is_text(&cols[2], &old) {
                        // Dependent index/trigger/view: repoint, and rewrite an
                        // index's CREATE text to reference the new table name.
                        cols[2] = Value::Text(new_name.clone());
                        if is_text(&cols[0], "index") {
                            if let Some(Value::Text(isql)) = cols.get(4).cloned() {
                                if let Ok(Statement::CreateIndex(mut ci)) = sql::parse_one(&isql) {
                                    ci.table = new_name.clone();
                                    cols[4] = Value::Text(sql::print::create_index(&ci));
                                }
                            }
                        }
                        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, &new_name));
                                true
                            }
                            _ => false,
                        }
                    } else {
                        false
                    }
                })?;
            }
            AlterAction::RenameColumn { old, new } => {
                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();
                                }
                            }
                        }
                    }
                }
                let new_table_sql = sql::print::create_table(&ct);
                let table = a.table.clone();
                let old = old.clone();
                let new = new.clone();
                self.rewrite_schema_rows(|cols| {
                    if is_text(&cols[0], "table") && is_text(&cols[1], &table) {
                        cols[4] = Value::Text(new_table_sql.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() {
                            if let Ok(Statement::CreateIndex(mut ci)) = sql::parse_one(&isql) {
                                let mut changed = false;
                                for term in &mut ci.columns {
                                    if let Expr::Column { column, .. } = &mut term.expr {
                                        if column.eq_ignore_ascii_case(&old) {
                                            *column = new.clone();
                                            changed = true;
                                        }
                                    }
                                }
                                if changed {
                                    cols[4] = Value::Text(sql::print::create_index(&ci));
                                    return true;
                                }
                            }
                        }
                        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 backing table first (it is an ordinary table).
        let backing_old = format!("{old}_data");
        if self.schema.table(&backing_old).is_some() {
            self.exec_alter(&Alter {
                schema: None,
                table: backing_old,
                action: AlterAction::RenameTable(format!("{new}_data")),
            })?;
        }
        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, &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);
        let new_sql = sql::print::create_table(&ct);
        let table = a.table.clone();
        self.rewrite_schema_rows(|cols| {
            if is_text(&cols[0], "table") && is_text(&cols[1], &table) {
                cols[4] = Value::Text(new_sql.clone());
                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);
        }
        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());
        };
        // A persistent module bypasses best_index (it scans `<name>_data`).
        if module.dyn_persistent() {
            return Ok(plain());
        }
        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();
        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();
            let sorted = n - self
                .seek_order_prefix(sel, params)
                .map_or(0, |(k, _)| k.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}"));
        }
        // 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 ---------------------------------------------------

    fn run_select(&self, sel: &Select, params: &Params) -> Result<QueryResult> {
        // Materialize this query's `WITH` CTEs into the environment for the
        // duration of the query, then restore the previous scope.
        let base = self.cte_env.borrow().len();
        let pushed = self.push_ctes(sel, params);
        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 projections (no FROM); a real set operation joins
        // genuine SELECTs. SQLite rejects a column-count mismatch in either case,
        // but with different wording, so pick the message by which kind this is.
        let is_values = sel.from.is_none()
            && sel.where_clause.is_none()
            && sel.group_by.is_empty()
            && sel
                .compound
                .iter()
                .all(|(op, c)| *op == CompoundOp::UnionAll && c.from.is_none());
        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 {
                    "SELECTs to the left and right of the compound operator do not have the same \
                     number of result columns"
                        .into()
                }));
            }
            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 term in &sel.order_by {
                let idx = resolve_order_index(&term.expr, &result.columns, result.columns.len())
                    .ok_or(Error::Unsupported(
                        "ORDER BY term must be an output column in a compound query",
                    ))?;
                // 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();

        // 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" => {
                    let buckets = arg_vals[idx].first().map(eval::to_i64).unwrap_or(1).max(1);
                    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" => {
                    let nth = arg_vals[idx].get(1).map(eval::to_i64).unwrap_or(1);
                    // nth row within the (post-EXCLUDE) frame (1-based).
                    if nth >= 1 {
                        fpos.get((nth - 1) as usize)
                            .and_then(|&k| arg_vals[ordered[k]].first().cloned())
                            .unwrap_or(Value::Null)
                    } else {
                        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) can satisfy the ordering only when all terms share
        // one direction — walked forward for all-ASC, reversed for all-DESC — and
        // use the default NULLs placement, which the walk already yields (NULLs
        // first ascending, last descending). Mixed directions, an explicit `NULLS
        // FIRST`/`LAST`, a `COLLATE`, or any non-column term disqualifies it.
        let descending = sel.order_by[0].descending;
        let mut cols: Vec<usize> = Vec::with_capacity(sel.order_by.len());
        for term in &sel.order_by {
            if term.descending != descending || 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);
        }
        // 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 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);
            return Some(OrderIndexScan {
                name: idx.name,
                root: idx.root,
                colls: idx.collations,
                cols: idx.cols,
                descending,
                covering,
            });
        }
        None
    }

    /// 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) {
            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).
    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.
    fn fts5_query_ctx(
        &self,
        sel: &Select,
        columns: &[ColumnInfo],
        input_rows: &[InputRow],
        params: &Params,
    ) -> Option<Fts5QueryCtx> {
        const AUX: &[&str] = &["rank", "bm25", "highlight"];
        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, _, _) = self.vtab_meta(&from.first.name).ok()?;
        if !module.eq_ignore_ascii_case("fts5") {
            return None;
        }
        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());
            let index = input_rows
                .iter()
                .enumerate()
                .filter_map(|(i, r)| Some((r.rowid?, i)))
                .collect();
            (corpus, index)
        });
        Some(Fts5QueryCtx {
            col_names,
            query,
            scope,
            bm25,
        })
    }

    fn run_core(&self, sel: &Select, params: &Params) -> Result<QueryResult> {
        // 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 (mut 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.
        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,
        };

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

        // Window functions: compute over the post-WHERE rows, append the results
        // as synthetic columns, and rewrite the projection to reference them.
        let rewritten;
        let sel = if window::has_window(sel) {
            if !sel.group_by.is_empty() || self.has_aggregate(sel) {
                return Err(Error::Unsupported(
                    "window functions combined with GROUP BY / aggregates",
                ));
            }
            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 any
        // aggregate function); SQLite rejects it on a plain query.
        if sel.having.is_some() && !aggregated {
            return Err(Error::Error(
                "HAVING clause on a non-aggregate query".into(),
            ));
        }
        let (out_labels, mut out) = if aggregated {
            self.eval_aggregated(sel, &columns, rows, params)?
        } else {
            self.eval_simple(sel, &columns, rows, params)?
        };

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

    /// 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
                }],
            ));
        };
        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(),
                    )),
                };
            }
            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 {
                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;
                            eval::truth(&eval::compare_op(
                                BinaryOp::Eq,
                                &combined[li],
                                &combined[left_width + rl],
                                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();
        let columns = result
            .columns
            .iter()
            .map(|n| ColumnInfo {
                name: n.clone(),
                table: label.clone(),
                affinity: eval::Affinity::Blob,
                collation: crate::value::Collation::default(),
            })
            .collect();
        Ok((columns, result.rows))
    }

    /// 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 {
            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() {
            (0..n_cols).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("NOT NULL constraint failed".into()));
                        }
                    }
                    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) => {
                        return Err(self.conflict_error(oc, "UNIQUE constraint failed"))
                    }
                    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)?;
                }
                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("UNIQUE constraint failed".into()));
                }
            }
        }
        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}"))),
        }
    }

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

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

    /// 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,
                )?;
                Expr::Literal(value_to_literal(v))
            }
            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,
            } => {
                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,
                }
            }
            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}()"
            )));
        }

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

    fn has_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,
        }) || 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 | ResultColumn::TableWildcard(_) => {
                    for c in columns {
                        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)
        };
        let not_null: Vec<bool> = ct
            .columns
            .iter()
            .enumerate()
            .map(|(i, c)| {
                // The INTEGER PRIMARY KEY (rowid alias) is implicitly NOT NULL.
                Some(i) == ipk
                    || c.constraints
                        .iter()
                        .any(|k| matches!(k, ColumnConstraint::NotNull))
            })
            .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> = Vec::new();
        for col in &ct.columns {
            for k in &col.constraints {
                if let ColumnConstraint::Check(e) = k {
                    checks.push(e.clone());
                }
            }
        }
        for tc in &ct.constraints {
            if let TableConstraint::Check(e) = tc {
                checks.push(e.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,
        })
    }

    /// 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 in &meta.checks {
            let ctx = row_ctx(values, &meta.columns, rowid, params).with_subqueries(self);
            if eval::truth(&eval::eval(expr, &ctx)?) == Some(false) {
                return Err(Error::Constraint("CHECK constraint failed".into()));
            }
        }
        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`).
    not_null: Vec<bool>,
    /// CHECK constraint expressions (column-level and table-level).
    checks: Vec<Expr>,
    /// Column-index sets that must be UNIQUE (excludes the rowid IPK).
    unique: Vec<Vec<usize>>,
    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)>>,
}

/// 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![false; 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,
    }
}

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

/// 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`.
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,
}

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))
    }
    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))
    }
    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()?;
        Some(crate::vtab::fts5_highlight(
            &ctx.query,
            &ctx.col_names,
            ctx.scope.as_deref(),
            col,
            text,
            open,
            close,
        ))
    }
    fn scalar(&self, select: &Select, outer: &EvalCtx) -> Result<Value> {
        self.with_outer_frame(outer, |params| {
            let r = self.run_select(select, params)?;
            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 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))
}

/// 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 {
    // Non-numeric/NULL current value: fall back to peer-group edges.
    if matches!(
        b,
        FrameBound::CurrentRow | FrameBound::Preceding(_) | FrameBound::Following(_)
    ) && matches!(ovals[p], Value::Null)
    {
        return group_bound(b, 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 row at/before the end edge.
        let mut e = m;
        for (k, ov) in ovals.iter().enumerate().take(m) {
            if matches!(ov, Value::Null) {
                continue;
            }
            if !inside(eval::to_f64(ov), threshold) {
                e = k;
                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,
}

impl VTabStore for ExecVTabStore<'_> {
    fn rows(&self) -> Result<Vec<(i64, Vec<Value>)>> {
        let meta = self.conn.table_meta(self.backing, None)?;
        self.conn.scan_table(&meta)
    }
    fn put(&mut self, rowid: i64, values: &[Value]) -> Result<()> {
        let root = self.conn.table_meta(self.backing, None)?.root;
        let payload = 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`.
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,
    }
}

/// 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] && 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()
        })
    })
}

/// 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,
        },
        Expr::Collate { expr, .. } | Expr::Paren(expr) => positional_int(expr),
        _ => None,
    }
}

/// Reject any `GROUP BY` / `ORDER BY` positional term that falls outside
/// `1..=ncols`, matching SQLite's "Nth GROUP BY/ORDER BY term out of range".
/// `ncols` is the query's output-column count.
fn check_positional_terms(group_by: &[Expr], order_by: &[OrderTerm], ncols: usize) -> Result<()> {
    for g in group_by {
        if let Some(n) = positional_int(g) {
            if n < 1 || (n as u64) > ncols as u64 {
                return Err(Error::Error("GROUP BY term out of range".into()));
            }
        }
    }
    for t in order_by {
        if let Some(n) = positional_int(&t.expr) {
            if n < 1 || (n as u64) > ncols as u64 {
                return Err(Error::Error("ORDER BY term out of range".into()));
            }
        }
    }
    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`.
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 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>,
    )>,
}

/// 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).
struct Fts5RankGuard<'a> {
    conn: &'a Connection,
    prev: Option<Fts5QueryCtx>,
}

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(…)`, …).
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.
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>)>;

/// 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.
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 `new` 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.
fn rewrite_ident_tokens(sql: &str, old: &str, new: &str) -> String {
    let toks = match sql::token::tokenize(sql) {
        Ok(t) => t,
        Err(_) => return String::from(sql),
    };
    // SQLite double-quotes the substituted name in a rename rewrite; match that.
    let rendered = sql::print::ident(new);
    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
}

/// 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>> {
    let col_pos = |name: &str| {
        ct.columns
            .iter()
            .position(|c| c.name.eq_ignore_ascii_case(name))
    };
    let mut unique: Vec<Vec<usize>> = Vec::new();
    for (i, c) in ct.columns.iter().enumerate() {
        for k in &c.constraints {
            match k {
                ColumnConstraint::Unique => unique.push(alloc::vec![i]),
                ColumnConstraint::PrimaryKey { .. } if Some(i) != ipk => {
                    unique.push(alloc::vec![i])
                }
                _ => {}
            }
        }
    }
    for tc in &ct.constraints {
        let names = match tc {
            TableConstraint::Unique(n) | TableConstraint::PrimaryKey(n) => n,
            _ => 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);
            }
        }
    }
    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"));
        let is_pk = c
            .constraints
            .iter()
            .any(|k| matches!(k, ColumnConstraint::PrimaryKey { .. }));
        if is_integer && is_pk {
            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
}