graphitesql 0.0.5

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
//! 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::{PageSource, WritePager};
use crate::schema::Schema;
use crate::sql::ast::*;
use crate::sql::{self};
use crate::value::Value;
use crate::vfs::{OpenFlags, Vfs};
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>,
    /// 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>,
}

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

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

    /// 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())))
            }
            _ => 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(),
                ))
            }
        };
        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()));
        };
        let ipk = find_integer_primary_key(&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 = if Some(i) == ipk
                || col
                    .constraints
                    .iter()
                    .any(|c| matches!(c, ColumnConstraint::PrimaryKey { .. }))
            {
                1
            } else {
                0
            };
            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);
        }
        let columns: Vec<String> = if extended {
            [
                "cid",
                "name",
                "type",
                "notnull",
                "dflt_value",
                "pk",
                "hidden",
            ]
            .iter()
            .map(|s| String::from(*s))
            .collect()
        } else {
            ["cid", "name", "type", "notnull", "dflt_value", "pk"]
                .iter()
                .map(|s| String::from(*s))
                .collect()
        };
        Ok(QueryResult { columns, rows })
    }

    /// 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();
        let mut rows = Vec::new();
        for (seq, obj) in objs.iter().rev().enumerate() {
            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 => (1, "u", 0), // an automatic UNIQUE/PK index
            };
            rows.push(alloc::vec![
                Value::Integer(seq as i64),
                Value::Text(obj.name.clone()),
                Value::Integer(unique),
                Value::Text(origin.into()),
                Value::Integer(partial),
            ]);
        }
        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 {
            return Err(Error::Corrupt("schema sql is not CREATE TABLE".into()));
        };
        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()
            .filter(|o| o.obj_type == ObjectType::Table && !o.name.starts_with("sqlite_"))
            .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())
    }

    /// 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(),
                    ));
                }
                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.
                if self.open_savepoints == 0 && !self.in_tx {
                    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),
            _ => 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(_)
        );
        // graphite does not yet maintain pointer-map pages, so writing a page to
        // an `auto_vacuum` database (one sqlite3 created with that mode) would
        // corrupt its ptrmap. Refuse such writes rather than silently corrupt the
        // file; reads, and writes to ordinary (auto_vacuum=NONE) databases, are
        // unaffected. The active backend here is already the statement's target
        // (a non-main write swaps its database in as `main` beforehand).
        let mutates_pages = matches!(
            stmt,
            Statement::CreateTable(_)
                | Statement::Insert(_)
                | Statement::Update(_)
                | Statement::Delete(_)
                | Statement::CreateIndex(_)
                | Statement::CreateView(_)
                | Statement::CreateTrigger(_)
                | Statement::Drop(_)
                | Statement::Alter(_)
        );
        if mutates_pages && auto_vacuum_mode(self.backend.source().header()) != 0 {
            return Err(Error::Unsupported(
                "writing an auto_vacuum database (pointer-map maintenance not yet implemented)",
            ));
        }
        let affected = match stmt {
            Statement::CreateTable(ct) => {
                self.exec_create_table(&ct, sql.trim())?;
                0
            }
            Statement::Insert(ins) => self.exec_insert(&ins, params)?,
            Statement::Delete(del) => self.exec_delete(&del, params)?,
            Statement::Update(upd) => self.exec_update(&upd, params)?,
            Statement::CreateIndex(ci) => {
                self.exec_create_index(&ci, sql.trim())?;
                0
            }
            Statement::CreateView(cv) => {
                self.exec_create_view(&cv, sql.trim())?;
                0
            }
            Statement::CreateTrigger(ct) => {
                self.exec_create_trigger(&ct, sql.trim())?;
                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 is_dml {
            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()?;
            // Refresh the catalog from the committed image.
            self.schema = Schema::read(self.backend.source())?;
        }
        Ok(affected)
    }

    /// 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('"', "\"\""));

        // Build a compact copy in a throwaway in-memory database.
        let mut tmp = Connection::open_memory()?;
        // 1. Tables (this also recreates their automatic indexes).
        for (ty, _, sql) in &objs {
            if *ty == ObjectType::Table {
                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).
        for (ty, name, _) in &objs {
            if *ty != ObjectType::Table {
                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(),
                        ));
                    }
                    _ => {}
                }
            }
        }
        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: None,
                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("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))?),
                };
                // graphite creates only `auto_vacuum=NONE` databases and cannot
                // maintain pointer-map pages, so accept NONE (the status quo) and
                // reject FULL/INCREMENTAL rather than claim a mode it can't honor.
                if mode != 0 {
                    return Err(Error::Unsupported(
                        "PRAGMA auto_vacuum = FULL/INCREMENTAL (pointer-map maintenance not yet implemented)",
                    ));
                }
            }
        }
        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)? {
            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(())
    }

    /// 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
            };
            // 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,
            )?;
            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,
            )?;
            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}")))?;
                let ctx = row_ctx(&new, &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),
            )?;
            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)?;
                    }
                    Statement::Select(_) => {} // side-effect free in our engine
                    _ => return Err(Error::Unsupported("statement type in trigger body")),
                }
            }
        }
        Ok(())
    }

    fn exec_insert(&mut self, ins: &Insert, params: &Params) -> Result<usize> {
        reject_schema_write(&ins.table)?;
        // `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.
        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_some() || !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);
            }
            check_not_null(&meta, &values)?;
            self.check_strict_types(&meta, &values)?;
            self.check_constraints(&meta, &values, Some(rowid), params)?;
            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.
                if let Some(up) = &ins.upsert {
                    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 {
                    OnConflict::Abort => {
                        return Err(Error::Constraint("UNIQUE constraint failed".into()))
                    }
                    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,
            )?;
            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)
    }

    /// 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_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,
            )?;
        }
        for rowid in &victims {
            let old = self.read_row(&meta, *rowid)?;
            if let Some(old) = &old {
                if !del.returning.is_empty() {
                    self.collect_returning(&del.returning, &meta, old, Some(*rowid), params)?;
                }
                self.fire_triggers(
                    &del.table,
                    TrigEvent::Delete,
                    TriggerTiming::Before,
                    &meta.columns,
                    Some((old, *rowid)),
                    None,
                    params,
                    None,
                )?;
            }
            // 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)?;
            if let Some(old) = &old {
                self.fire_triggers(
                    &del.table,
                    TrigEvent::Delete,
                    TriggerTiming::After,
                    &meta.columns,
                    Some((old, *rowid)),
                    None,
                    params,
                    None,
                )?;
            }
        }
        if !victims.is_empty() {
            self.compact_table(&meta)?;
            self.rebuild_indexes(&meta, &indexes)?;
        }
        Ok(victims.len())
    }

    /// 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_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}\""
                    )));
                }
                let new = match &matched_from {
                    Some(fr) => {
                        let mut combined = values.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(&values, &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(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),
            )?;
            // 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)?;
                        }
                    }
                    OnConflict::Abort => {
                        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, 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)));
        }
        let tmeta = self.table_meta(&ci.table, None)?;
        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(())
    }

    /// 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 = eval::to_i64(&eval::eval(e, &EvalCtx::rowless(params))?);
                (n >= 0).then_some(n as usize)
            }
            None => None,
        };
        let rec_offset = match &base.offset {
            Some(e) => eval::to_i64(&eval::eval(e, &EvalCtx::rowless(params))?).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;
        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());
            }
        }
        // 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<()> {
        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 {
                        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();
                // Update table-level PK/UNIQUE column lists that name the column.
                for tc in &mut ct.constraints {
                    let names = match tc {
                        TableConstraint::PrimaryKey(n) | TableConstraint::Unique(n) => n,
                        _ => continue,
                    };
                    for nm in names {
                        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 … 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)
    }

    /// 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)) {
            return Ok(None); // `col = NULL` is never true; let the scan handle it
        }

        // 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();
        let mut best: Option<(u32, Vec<Value>, Vec<crate::value::Collation>, 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();
            let mut colls = Vec::new();
            for (pos, &c) in idx.cols.iter().enumerate() {
                match eqs.iter().find(|(col, _)| *col == c) {
                    Some((_, v)) => {
                        key.push(meta.columns[c].affinity.coerce(v.clone()));
                        colls.push(idx.collations[pos]);
                    }
                    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 {
                best = Some((idx.root, key, colls, est));
            }
        }
        let Some((root, key, seek_colls, _)) = best else {
            return Ok(None);
        };
        if key.is_empty() {
            return Ok(None);
        }

        let rowids =
            crate::btree::index_seek_rowids(self.backend.source(), root, &key, &seek_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))
    }

    /// 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)> = 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));
                break;
            }
        }
        let Some((root, bound, coll)) = chosen else {
            return Ok(None);
        };

        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(Some(out))
    }

    /// 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 Some((col, values)) = find_in_constraint(where_expr, &meta.columns, params) else {
            return Ok(None);
        };
        // Skip if any list value is NULL (`x IN (NULL)` is never true/usable here).
        if values.iter().any(|v| matches!(v, Value::Null)) {
            return Ok(None);
        }
        let encoding = self.backend.source().header().text_encoding;

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

        // Otherwise pick a plain index whose leading column is the IN column.
        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, crate::value::Collation)> = 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;
            }
            if idx.cols.first() == Some(&col) {
                chosen = Some((
                    idx.root,
                    idx.collations.first().copied().unwrap_or_default(),
                ));
                break;
            }
        }
        let Some((root, coll)) = chosen else {
            return Ok(None);
        };
        let aff = meta.columns[col].affinity;
        let colls = [coll];
        let mut rowids: Vec<i64> = Vec::new();
        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);
                }
            }
        }
        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))
    }

    /// 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(), 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(), 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`.
    fn eqp_select(
        &self,
        sel: &Select,
        parent: i64,
        next_id: &mut i64,
        out: &mut Vec<(i64, i64, String)>,
        params: &Params,
    ) -> Result<()> {
        let Some(from) = &sel.from else {
            return Ok(()); // SELECT with no FROM => no scan node
        };
        // First source.
        let meta = self.table_meta(&from.first.name, from.first.alias.as_deref())?;
        let label = eqp_label(&from.first);
        // 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)
                } else {
                    self.eqp_access(
                        &label,
                        &from.first.name,
                        &meta,
                        sel.where_clause.as_ref(),
                        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));
        }
        for join in &from.joins {
            let id = *next_id;
            *next_id += 1;
            out.push((
                id,
                parent,
                alloc::format!("SCAN {}", eqp_label(&join.table)),
            ));
        }
        // ORDER BY that we satisfy with an in-memory sort — unless the rowid scan
        // already yields the requested order (no temp b-tree then, like sqlite).
        if !sel.order_by.is_empty() && self.order_satisfied_by_scan(sel).is_none() {
            let id = *next_id;
            *next_id += 1;
            out.push((id, parent, String::from("USE TEMP B-TREE FOR ORDER BY")));
        }
        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), 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.
    fn eqp_access(
        &self,
        label: &str,
        table: &str,
        meta: &TableMeta,
        where_clause: Option<&Expr>,
        params: &Params,
    ) -> Result<String> {
        let Some(where_expr) = where_clause else {
            return Ok(alloc::format!("SCAN {label}"));
        };
        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));
        // 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();
        let mut best: Option<(String, Vec<usize>, u64)> = None;
        for obj in self.schema.indexes_on(table) {
            let Some(sql) = &obj.sql else { continue };
            let Ok(Statement::CreateIndex(ci)) = sql::parse_one(sql) else {
                continue;
            };
            if ci.where_clause.is_some() {
                continue; // partial indexes are not used for seeks (see try_index_lookup)
            }
            let Ok(cols) = self.index_columns(meta, &ci) else {
                continue;
            };
            let mut matched = Vec::new();
            for &c in &cols {
                if eqs.iter().any(|(col, _)| *col == c) {
                    matched.push(c);
                } else {
                    break;
                }
            }
            if matched.is_empty() {
                continue;
            }
            let est = stats
                .get(&obj.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((obj.name.clone(), matched, est));
            }
        }
        if let Some((idx_name, matched, _)) = best {
            if !matched.is_empty() {
                let cond = matched
                    .iter()
                    .map(|&c| alloc::format!("{}=?", meta.columns[c].name))
                    .collect::<Vec<_>>()
                    .join(" AND ");
                return Ok(alloc::format!(
                    "SEARCH {label} USING INDEX {idx_name} ({cond})"
                ));
            }
        }

        // 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, _)) = 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,
                };
                return Ok(alloc::format!(
                    "SEARCH {label} USING INDEX {idx_name} ({cond})"
                ));
            }
        }

        // IN-list seek: rowid b-tree, or an index on the IN column.
        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, _)) = leading_index(col) {
                let name = &meta.columns[col].name;
                return Ok(alloc::format!(
                    "SEARCH {label} USING INDEX {idx_name} ({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) => eval::to_i64(&eval::eval(e, &EvalCtx::rowless(params))?).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)
        };
        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)?;
            result.rows = apply_compound(*op, result.rows, r.rows, &colls);
        }
        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() {
            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) => eval::to_i64(&eval::eval(e, &EvalCtx::rowless(params))?).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 = eval::to_i64(&eval::eval(e, &EvalCtx::rowless(params))?);
                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.len() != 1
        {
            return None;
        }
        if self.has_aggregate(sel) || window::has_window(sel) {
            return None;
        }
        let term = &sel.order_by[0];
        let (tbl, col_name) = match &term.expr {
            Expr::Column { table, column } => (table.as_deref(), column.as_str()),
            _ => 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);
        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 col = meta
            .columns
            .iter()
            .position(|c| c.name.eq_ignore_ascii_case(col_name))?;
        if meta.ipk == Some(col) {
            return None; // the rowid/IPK case is handled by rowid_ordered_scan
        }
        let col_coll = meta.columns[col].collation;
        // A full index whose leading column is `col` with the column's collation.
        for idx in self.indexes_of(&t.name).ok()? {
            if idx.partial.is_some() || idx.key_exprs.is_some() {
                continue;
            }
            if idx.cols.first() == Some(&col) && idx.collations.first() == Some(&col_coll) {
                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: term.descending,
                    covering,
                });
            }
        }
        None
    }

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

    /// `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) -> Option<bool> {
        if let Some(d) = self.rowid_ordered_scan(sel) {
            return Some(d);
        }
        self.order_index_scan(sel).map(|s| s.descending)
    }

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

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

        // 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) {
                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) => eval::to_i64(&eval::eval(e, &EvalCtx::rowless(params))?).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 = eval::to_i64(&eval::eval(e, &EvalCtx::rowless(params))?);
                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));
            }
        }

        // 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 {
                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));
            }
            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 {
            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);
                let step = nums.get(2).copied().unwrap_or(1);
                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()));
                };
                let mut rows = Vec::new();
                let mut next_id = 0i64;
                if lname == "json_tree" {
                    json_tree_walk(&root, None, "$", "$", None, &mut next_id, &mut rows);
                } else {
                    json_each_children(&root, &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))
    }

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

            // 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 {
                    OnConflict::Abort => {
                        return Err(Error::Constraint("UNIQUE constraint failed".into()))
                    }
                    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 {
                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(&row, &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
        };

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

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

        // 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" {
            let mut items = Vec::new();
            for &i in group {
                let ctx = rows[i].ctx(columns, params).with_subqueries(self);
                let v = eval::eval(&args[0], &ctx)?;
                items.push(func::arg_to_json(&v, args.first()));
            }
            return Ok(Value::Text(json::Json::Array(items).serialize()));
        }
        if lname == "json_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))));
            }
            return Ok(Value::Text(json::Json::Object(pairs).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))
                }
            }
            _ => return Err(Error::Unsupported("aggregate function")),
        })
    }

    fn has_aggregate(&self, sel: &Select) -> bool {
        sel.columns.iter().any(|c| match c {
            ResultColumn::Expr { expr, .. } => contains_aggregate(expr),
            _ => false,
        }) || sel.having.as_ref().is_some_and(contains_aggregate)
    }

    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 } => {
                    labels.push(alias.clone().unwrap_or_else(|| expr_label(expr)));
                }
            }
        }
        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,
    };
    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
}

/// 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 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).
fn json_each_children(
    root: &crate::exec::json::Json,
    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!("$.{k}");
                json_emit_node(
                    v,
                    Some(Value::Text(k.clone())),
                    &fullkey,
                    "$",
                    None,
                    next_id,
                    rows,
                );
            }
        }
        Json::Array(items) => {
            for (i, v) in items.iter().enumerate() {
                let fullkey = alloc::format!("$[{i}]");
                json_emit_node(
                    v,
                    Some(Value::Integer(i as i64)),
                    &fullkey,
                    "$",
                    None,
                    next_id,
                    rows,
                );
            }
        }
        scalar => {
            json_emit_node(scalar, None, "$", "$", None, next_id, rows);
        }
    }
}

/// `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 {
                let parts: Vec<String> = vals.iter().map(eval::to_text).collect();
                Value::Text(parts.join(","))
            }
        }
        _ => 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(),
    }
}

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

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

/// 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 } => {
                labels.push(alias.clone().unwrap_or_else(|| expr_label(expr)));
            }
        }
    }
    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(())
}

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

fn contains_aggregate(expr: &Expr) -> bool {
    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(contains_aggregate),
        Expr::Function {
            name, args, star, ..
        } => {
            func::is_aggregate_call(name, args.len(), *star) || args.iter().any(contains_aggregate)
        }
        Expr::Binary { left, right, .. } => contains_aggregate(left) || contains_aggregate(right),
        Expr::Unary { expr, .. } | Expr::Paren(expr) => contains_aggregate(expr),
        Expr::IsNull { expr, .. } => contains_aggregate(expr),
        Expr::Between {
            expr, low, high, ..
        } => contains_aggregate(expr) || contains_aggregate(low) || contains_aggregate(high),
        Expr::InList { expr, list, .. } => {
            contains_aggregate(expr) || list.iter().any(contains_aggregate)
        }
        Expr::Case {
            operand,
            when_then,
            else_result,
        } => {
            operand.as_deref().is_some_and(contains_aggregate)
                || when_then
                    .iter()
                    .any(|(w, t)| contains_aggregate(w) || contains_aggregate(t))
                || else_result.as_deref().is_some_and(contains_aggregate)
        }
        Expr::Cast { expr, .. } => contains_aggregate(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),
    }
}

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

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