mongreldb-query 0.31.1

DataFusion SQL + Arrow frontend for MongrelDB.
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
//! DataFusion SQL + Arrow frontend for MongrelDB.
//!
//! [`MongrelProvider`] implements DataFusion's `TableProvider`: each `scan()`
//! takes an MVCC snapshot of the table, materializes the visible columns, and
//! hands DataFusion a streaming `MongrelScanExec` (see `scan.rs`) that emits one
//! `RecordBatch` per 65 536-row chunk. DataFusion then runs the SQL —
//! projection, filter, aggregation, limit — with its own vectorized kernels,
//! pipelined across those small batches so a `LIMIT` short-circuits and peak
//! memory stays bounded. MongrelDB owns storage/writes/indexes; DataFusion owns
//! the vectorized execution.
//!
//! Example (skipped from doctests; see `tests/sql.rs` for runnable ones):
//! ```ignore
//! # use mongreldb_core::Table;
//! # use mongreldb_query::MongrelSession;
//! # async fn run() -> anyhow::Result<()> {
//! let db = Table::create("travel.mongreldb", /* schema */ unimplemented!(), 1)?;
//! let session = MongrelSession::new(db);
//! session.register("travel_trips").await?;
//! let batches = session.run("select * from travel_trips where cost < 300").await?;
//! # Ok(()) }
//! ```

pub mod arrow_conv;
mod commands;
mod error;
pub mod extended_sql_functions;
mod external_modules;
mod fk_join;
mod native_agg;
mod percentile;
mod scan;
mod shadow;
mod udf;

pub use error::{MongrelQueryError, Result};
pub use external_modules::{
    ExternalBaseWrite, ExternalModuleDescriptor, ExternalModuleIndex, ExternalModuleRegistry,
    ExternalPlan, ExternalPlanRequest, ExternalScan, ExternalTable, ExternalTableModule,
    ExternalTxn, ExternalWriteOp, ExternalWriteResult, ModuleConnectCtx,
};

use arrow::array::{Array, ArrayRef, Int64Array, StringArray};
use arrow::datatypes::SchemaRef;
use arrow::record_batch::RecordBatch;
use datafusion::catalog::{Session, TableProvider};
use datafusion::common::{DataFusionError, Result as DFResult};
use datafusion::logical_expr::{AggregateUDF, Expr, ScalarUDF, TableType, WindowUDF};
use datafusion::physical_plan::ExecutionPlan;
use datafusion::prelude::SessionContext;
use mongreldb_core::{
    AlterColumn, ColumnFlags, Cursor, Database, Schema as CoreSchema, Table, TypeId,
};
use parking_lot::Mutex;
use std::collections::{HashMap, HashSet};
use std::sync::Arc;

/// A MongrelDB table exposed to DataFusion. Holds the live `Table` behind a mutex;
/// each scan takes a fresh MVCC snapshot.
pub struct MongrelProvider {
    db: Arc<Mutex<Table>>,
    schema: SchemaRef,
}

#[derive(Debug, Clone)]
pub(crate) struct ViewDef {
    pub sql: String,
    pub schema: CoreSchema,
    pub input_types: HashMap<u16, Option<TypeId>>,
}

impl MongrelProvider {
    pub fn new(db: Arc<Mutex<Table>>) -> Result<Self> {
        let schema = {
            let db = db.lock();
            arrow_conv::arrow_schema(db.schema())?
        };
        Ok(Self { db, schema })
    }

    pub fn arrow_schema(&self) -> SchemaRef {
        self.schema.clone()
    }
}

impl std::fmt::Debug for MongrelProvider {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("MongrelProvider").finish_non_exhaustive()
    }
}

#[async_trait::async_trait]
impl TableProvider for MongrelProvider {
    fn schema(&self) -> SchemaRef {
        self.schema.clone()
    }

    fn table_type(&self) -> TableType {
        TableType::Base
    }

    /// Tell DataFusion which filters the pushdown serves exactly so it does not
    /// double-filter (and, for `ann_search`, never evaluates the no-op UDF).
    /// LIKE/FM is `Inexact`: the FM pushdown is a substring *superset*, so
    /// DataFusion must still re-apply the real wildcard semantics.
    fn supports_filters_pushdown(
        &self,
        filters: &[&Expr],
    ) -> DFResult<Vec<datafusion::logical_expr::TableProviderFilterPushDown>> {
        use datafusion::logical_expr::TableProviderFilterPushDown;
        let schema_ref = self.db.lock().schema().clone();
        Ok(filters
            .iter()
            .map(|f| match translate_filter(f, &schema_ref) {
                Some(
                    mongreldb_core::Condition::FmContains { .. }
                    | mongreldb_core::Condition::FmContainsAll { .. },
                ) => TableProviderFilterPushDown::Inexact,
                Some(_) => TableProviderFilterPushDown::Exact,
                None => match translate_ann_search(f, &schema_ref)
                    .or_else(|| translate_sparse_match(f, &schema_ref))
                {
                    Some(_) => TableProviderFilterPushDown::Exact,
                    None => TableProviderFilterPushDown::Unsupported,
                },
            })
            .collect())
    }

    async fn scan(
        &self,
        _state: &dyn Session,
        projection: Option<&Vec<usize>>,
        filters: &[Expr],
        _limit: Option<usize>,
    ) -> DFResult<Arc<dyn ExecutionPlan>> {
        let core_err = |e: mongreldb_core::MongrelError| {
            DataFusionError::External(Box::new(MongrelQueryError::Core(e)))
        };
        let mut db = self.db.lock();
        let snap = db.snapshot();
        let schema_ref = db.schema().clone();

        // Translate WHERE filters into index-backed Conditions.
        let translated: Vec<mongreldb_core::Condition> = filters
            .iter()
            .filter_map(|f| {
                translate_filter(f, &schema_ref)
                    .or_else(|| translate_ann_search(f, &schema_ref))
                    .or_else(|| translate_sparse_match(f, &schema_ref))
            })
            .collect();

        // Index-served conditions require complete live indexes; a deferred
        // bulk load pays its one-time build here (Phase 14.7 lazy contract).
        if !translated.is_empty() {
            db.ensure_indexes_complete().map_err(core_err)?;
        }

        // `COUNT(*)`-style queries (empty projection) need only a row count.
        // Unfiltered ⇒ O(1) via the maintained `live_count` metadata; a pushed
        // WHERE ⇒ decode one column through the pushdown path to count survivors.
        let empty_proj = projection.map(|p| p.is_empty()).unwrap_or(false);
        if empty_proj {
            let total: usize = if translated.is_empty() {
                mongreldb_core::trace::QueryTrace::record(|t| {
                    t.scan_mode = mongreldb_core::trace::ScanMode::CountMetadata;
                });
                db.count() as usize
            } else if let Some(count) = db.count_conditions(&translated, snap).map_err(core_err)? {
                count as usize
            } else {
                match schema_ref.columns.first() {
                    Some(cdef) => {
                        let one = [cdef.id];
                        let cols = match db
                            .query_columns_native_cached(&translated, Some(&one), snap)
                            .map_err(core_err)?
                        {
                            Some(c) => c,
                            None => db
                                .visible_columns_native(snap, Some(&one))
                                .map_err(core_err)?,
                        };
                        mongreldb_core::trace::QueryTrace::record(|t| {
                            t.scan_mode = mongreldb_core::trace::ScanMode::Materialized;
                        });
                        cols.first().map(|(_, c)| c.len()).unwrap_or(0)
                    }
                    None => 0,
                }
            };
            return Ok(Arc::new(scan::MongrelScanExec::new_row_count(total)));
        }

        // Output column ids + Arrow schema for this scan, in scan-field order.
        // DataFusion's projection already includes every column a retained
        // (Inexact / Unsupported) filter still needs, so decoding exactly this
        // set is correct. `None` ⇒ the full schema.
        let (col_ids, scan_schema): (Vec<u16>, SchemaRef) = match projection {
            Some(p) if !p.is_empty() => {
                let ids = p.iter().map(|&idx| schema_ref.columns[idx].id).collect();
                let fields: Vec<arrow::datatypes::Field> = p
                    .iter()
                    .map(|&idx| self.schema.field(idx).clone())
                    .collect();
                (ids, Arc::new(arrow::datatypes::Schema::new(fields)))
            }
            _ => (
                schema_ref.columns.iter().map(|c| c.id).collect(),
                self.schema.clone(),
            ),
        };

        // Projection pairs (column id, type) in scan-field order.
        let mut proj_pairs: Vec<(u16, mongreldb_core::schema::TypeId)> =
            Vec::with_capacity(col_ids.len());
        let mut types: Vec<mongreldb_core::schema::TypeId> = Vec::with_capacity(col_ids.len());
        for cid in &col_ids {
            let ty = schema_ref
                .columns
                .iter()
                .find(|c| c.id == *cid)
                .map(|c| c.ty)
                .ok_or_else(|| {
                    DataFusionError::External(Box::new(MongrelQueryError::Arrow(format!(
                        "unknown column {cid}"
                    ))))
                })?;
            proj_pairs.push((*cid, ty));
            types.push(ty);
        }

        // Phase 7.1: exact per-column min/max from page stats, but only for an
        // unfiltered full scan over an insert-only table (gated in core). A
        // pushed WHERE or a table with deletes ⇒ all-Absent (DataFusion scans).
        let col_stats_map = if translated.is_empty() {
            db.exact_column_stats(snap, &col_ids).map_err(core_err)?
        } else {
            None
        };
        let column_stats: Vec<datafusion::physical_plan::ColumnStatistics> = col_ids
            .iter()
            .map(|cid| scan::to_col_statistics(col_stats_map.as_ref().and_then(|m| m.get(cid))))
            .collect();

        // Phase 15.5: Arrow IPC shadow — zero-copy scan for clean single-run
        // unfiltered tables. The shadow is a derived Arrow IPC file that was
        // written on a prior scan; reading it avoids per-column decode entirely.
        if translated.is_empty()
            && db.run_count() == 1
            && db.memtable_is_empty()
            && db.mutable_run_len() == 0
            && db.single_run_is_clean()
        {
            let shadow = shadow::ArrowShadow::new(db.dir());
            let run_ids: HashSet<u128> = db.run_ids().into_iter().collect();
            shadow.sweep(&run_ids);
            if let Some(&run_id) = run_ids.iter().next() {
                if let Some(batch) = shadow.try_read(run_id) {
                    if let Some(projected) =
                        project_batch(&batch, &col_ids, &schema_ref, &scan_schema)
                    {
                        mongreldb_core::trace::QueryTrace::record(|t| {
                            t.scan_mode = mongreldb_core::trace::ScanMode::ArrowShadow;
                        });
                        return Ok(Arc::new(scan::MongrelScanExec::new_batch(
                            scan_schema,
                            projected,
                            column_stats,
                        )));
                    }
                }
            }
        }

        // Phase 6.2 / 16.1: drive a lazy streaming cursor that fuses the
        // predicate, skips pages with no survivors, and decodes only the
        // projected columns of surviving pages. `scan_cursor` picks the page-plan
        // fast path for a single run or the k-way-merge cursor for multi-run —
        // both avoid fully materializing every row. Anything else (e.g. an empty
        // table with only memtable rows) falls through to materialize-then-chunk.
        let cursor: Option<Box<dyn Cursor>> = db
            .scan_cursor(snap, proj_pairs, &translated)
            .map_err(core_err)?;
        if let Some(cursor) = cursor {
            let num_rows = cursor.remaining_rows();
            // Phase 16.3a: extract the LIKE pattern for residual pre-filtering.
            let residual = extract_residual_filter(filters, &col_ids, &schema_ref);
            return Ok(Arc::new(scan::MongrelScanExec::new_cursor(
                scan_schema,
                types,
                cursor,
                num_rows,
                column_stats,
                residual,
            )));
        }

        // Pushdown returns exactly `col_ids` when it accepts; the full-scan
        // fallback returns all columns, of which we keep `col_ids`.
        let cols = if !translated.is_empty() {
            match db
                .query_columns_native_cached(&translated, Some(&col_ids), snap)
                .map_err(core_err)?
            {
                Some(c) => c,
                None => db
                    .visible_columns_native(snap, Some(&col_ids))
                    .map_err(core_err)?,
            }
        } else {
            db.visible_columns_native(snap, Some(&col_ids))
                .map_err(core_err)?
        };

        // Order the decoded columns into scan-field order for the streaming exec.
        let mut ordered: Vec<mongreldb_core::columnar::NativeColumn> =
            Vec::with_capacity(col_ids.len());
        for cid in &col_ids {
            let col = cols
                .iter()
                .find(|(id, _)| id == cid)
                .map(|(_, c)| c.clone())
                .ok_or_else(|| {
                    DataFusionError::External(Box::new(MongrelQueryError::Arrow(format!(
                        "missing column {cid}"
                    ))))
                })?;
            ordered.push(col);
        }
        let num_rows = ordered.first().map(|c| c.len()).unwrap_or(0);

        // Collect data needed for the shadow write before releasing the lock.
        let shadow_write: Option<(
            std::path::PathBuf,
            u128,
            Vec<arrow::array::ArrayRef>,
            SchemaRef,
        )> = if translated.is_empty()
            && db.run_count() == 1
            && db.memtable_is_empty()
            && db.mutable_run_len() == 0
            && db.single_run_is_clean()
        {
            let all_schema_ids: Vec<u16> = schema_ref.columns.iter().map(|c| c.id).collect();
            if col_ids == all_schema_ids {
                let dir = db.dir().to_path_buf();
                let run_id = db.run_ids().first().copied();
                run_id.map(|rid| {
                    let arrays = ordered
                        .iter()
                        .zip(types.iter())
                        .map(|(col, &ty)| arrow_conv::native_to_array(ty, col))
                        .collect::<Result<_>>()
                        .unwrap_or_default();
                    (dir, rid, arrays, scan_schema.clone())
                })
            } else {
                None
            }
        } else {
            None
        };

        drop(db);

        // Phase 15.5: write the Arrow IPC shadow for future scans (best-effort,
        // outside the Table lock).
        if let Some((dir, run_id, arrays, schema)) = shadow_write {
            if let Ok(batch) = RecordBatch::try_new(schema, arrays) {
                shadow::ArrowShadow::new(&dir).write(run_id, &batch);
            }
        }

        mongreldb_core::trace::QueryTrace::record(|t| {
            t.scan_mode = mongreldb_core::trace::ScanMode::Materialized;
            t.row_materialized = true;
        });
        Ok(Arc::new(scan::MongrelScanExec::new(
            scan_schema,
            ordered,
            types,
            num_rows,
            column_stats,
        )))
    }
}

/// Phase 15.5: project columns from a full-schema shadow `RecordBatch` to match
/// the scan's requested column IDs and Arrow schema. Returns `None` if any
/// requested column is not present in the shadow batch (schema mismatch → miss).
fn project_batch(
    batch: &RecordBatch,
    col_ids: &[u16],
    schema_ref: &mongreldb_core::schema::Schema,
    scan_schema: &arrow::datatypes::SchemaRef,
) -> Option<RecordBatch> {
    // Map schema column ids to field names for lookup in the shadow batch.
    let arrays: Vec<arrow::array::ArrayRef> = col_ids
        .iter()
        .map(|cid| {
            // Find the column name for this id in the live schema.
            let name = schema_ref
                .columns
                .iter()
                .find(|c| c.id == *cid)
                .map(|c| c.name.as_str())?;
            // Look up the column in the shadow batch by name.
            let idx = batch.schema().index_of(name).ok()?;
            Some(batch.column(idx).clone())
        })
        .collect::<Option<Vec<_>>>()?;
    RecordBatch::try_new(scan_schema.clone(), arrays).ok()
}

/// Translate a DataFusion WHERE filter expression into a MongrelDB
/// index-backed [`Condition`]. Supported translations (all index/scan-served by
/// `Table::query_columns_native`):
///
/// * `col = literal` → [`Condition::BitmapEq`] (bitmap index) or
///   [`Condition::Pk`] (primary key).
/// * `col <, >, <=, >= literal` and `col BETWEEN a AND b` →
///   [`Condition::Range`] (Int64) / [`Condition::RangeF64`] (Float64).
/// * `col LIKE '%pat%'` → [`Condition::FmContains`] (FM index). Any `%`/`_`
///   wildcard pattern is mapped to its longest literal segment; DataFusion
///   re-applies the real LIKE on the returned batch, so correctness is exact
///   even though the pushdown is a substring superset.
///
/// Everything else is left to DataFusion's post-scan filter. Because DataFusion
/// always re-applies the full WHERE on the returned batch, a pushdown only ever
/// needs to return a *superset* of the survivors — it is a pure optimization,
/// never a correctness risk.
pub(crate) fn translate_filter(
    expr: &Expr,
    schema: &mongreldb_core::Schema,
) -> Option<mongreldb_core::Condition> {
    use datafusion::common::ScalarValue;
    use datafusion::logical_expr::{Between, BinaryExpr, Like, Operator};
    use mongreldb_core::{ColumnFlags, Condition, IndexKind, TypeId, Value};

    // Extended int extraction: handles every integer width (narrow ints are
    // stored widened to Int64 internally), Date32, and all Timestamp* precision
    // variants DataFusion emits. The numeric value is the raw i64.
    let int_val = |s: &ScalarValue| match s {
        ScalarValue::Int8(Some(v)) => Some(*v as i64),
        ScalarValue::Int16(Some(v)) => Some(*v as i64),
        ScalarValue::Int32(Some(v)) => Some(*v as i64),
        ScalarValue::Int64(Some(v)) => Some(*v),
        ScalarValue::UInt8(Some(v)) => Some(*v as i64),
        ScalarValue::UInt16(Some(v)) => Some(*v as i64),
        ScalarValue::UInt32(Some(v)) => Some(*v as i64),
        ScalarValue::UInt64(Some(v)) => Some(*v as i64),
        ScalarValue::Date32(Some(v)) => Some(*v as i64),
        ScalarValue::TimestampSecond(Some(v), _) => Some(*v),
        ScalarValue::TimestampMillisecond(Some(v), _) => Some(*v),
        ScalarValue::TimestampMicrosecond(Some(v), _) => Some(*v),
        ScalarValue::TimestampNanosecond(Some(v), _) => Some(*v),
        _ => None,
    };
    let float_val = |s: &ScalarValue| match s {
        ScalarValue::Float32(Some(f)) => Some(*f as f64),
        ScalarValue::Float64(Some(f)) => Some(*f),
        _ => None,
    };
    let bytes_val = |s: &ScalarValue| match s {
        ScalarValue::Utf8(Some(s)) => Some(s.as_bytes().to_vec()),
        _ => None,
    };
    let _ = bytes_val; // retained for clarity; equality uses the generic `val` below.

    let val = |s: &ScalarValue| -> Option<Value> {
        // Integer literals of any width coerce to Int64 (the storage width);
        // Float32 widens to Float64. This keeps equality pushdown working on
        // narrow-int / float32 bitmap and primary-key columns.
        if let Some(i) = int_val(s) {
            return Some(Value::Int64(i));
        }
        match s {
            ScalarValue::Utf8(Some(s)) => Some(Value::Bytes(s.as_bytes().to_vec())),
            ScalarValue::Float32(Some(f)) => Some(Value::Float64(*f as f64)),
            ScalarValue::Float64(Some(f)) => Some(Value::Float64(*f)),
            ScalarValue::Boolean(Some(b)) => Some(Value::Bool(*b)),
            _ => None,
        }
    };

    let col_def = |name: &str| schema.columns.iter().find(|c| c.name == name);
    let has_fm = |cid: u16| {
        schema
            .indexes
            .iter()
            .any(|i| i.column_id == cid && i.kind == IndexKind::FmIndex)
    };
    let has_bitmap = |cid: u16| {
        schema
            .indexes
            .iter()
            .any(|i| i.column_id == cid && i.kind == IndexKind::Bitmap)
    };

    match expr {
        // `col OP literal` (and the mirrored `literal OP col`).
        // Also handles `col = v1 OR col = v2 OR ...` → BitmapIn.
        Expr::BinaryExpr(BinaryExpr { left, op, right }) => {
            // OR-of-equalities on the same column → BitmapIn (Priority 6).
            if *op == Operator::Or {
                return try_or_as_bitmap_in(expr, schema);
            }
            // Unwrap single-layer Cast wrappers (canonicalization).
            let left = peel_cast(left);
            let right = peel_cast(right);
            let (col_name, scalar, flipped) = match (left.as_ref(), right.as_ref()) {
                (Expr::Column(c), Expr::Literal(s, _)) => (&c.name, s, false),
                (Expr::Literal(s, _), Expr::Column(c)) => (&c.name, s, true),
                _ => return None,
            };
            let op = if flipped { flip_op(*op)? } else { *op };
            let cdef = col_def(col_name)?;

            // Equality: bitmap index or primary key.
            if op == Operator::Eq {
                let v = val(scalar)?;
                if has_bitmap(cdef.id) {
                    return Some(Condition::BitmapEq {
                        column_id: cdef.id,
                        value: v.encode_key(),
                    });
                }
                if cdef.flags.contains(ColumnFlags::PRIMARY_KEY) {
                    return Some(Condition::Pk(v.encode_key()));
                }
                return None;
            }

            // Range on a typed numeric column. Every integer width is stored
            // widened to Int64, so they all share the integer Range path.
            match cdef.ty {
                TypeId::Int8
                | TypeId::Int16
                | TypeId::Int32
                | TypeId::Int64
                | TypeId::UInt8
                | TypeId::UInt16
                | TypeId::UInt32
                | TypeId::UInt64
                | TypeId::TimestampNanos
                | TypeId::Date32 => {
                    let v = int_val(scalar)?;
                    let (lo, hi) = int_bounds(op, v)?;
                    Some(Condition::Range {
                        column_id: cdef.id,
                        lo,
                        hi,
                    })
                }
                TypeId::Float32 | TypeId::Float64 => {
                    let v = float_val(scalar)?;
                    let (lo, lo_inc, hi, hi_inc) = float_bounds(op, v)?;
                    Some(Condition::RangeF64 {
                        column_id: cdef.id,
                        lo,
                        lo_inclusive: lo_inc,
                        hi,
                        hi_inclusive: hi_inc,
                    })
                }
                _ => None,
            }
        }

        // `col BETWEEN low AND high` (and `col NOT BETWEEN ...` → skip).
        Expr::Between(Between {
            expr,
            negated,
            low,
            high,
        }) => {
            if *negated {
                return None;
            }
            let Expr::Column(c) = expr.as_ref() else {
                return None;
            };
            let cdef = col_def(&c.name)?;
            let (lo_s, hi_s) = match (low.as_ref(), high.as_ref()) {
                (Expr::Literal(lo, _), Expr::Literal(hi, _)) => (lo, hi),
                _ => return None,
            };
            match cdef.ty {
                TypeId::Int8
                | TypeId::Int16
                | TypeId::Int32
                | TypeId::Int64
                | TypeId::UInt8
                | TypeId::UInt16
                | TypeId::UInt32
                | TypeId::UInt64
                | TypeId::TimestampNanos
                | TypeId::Date32 => {
                    let (Some(lo), Some(hi)) = (int_val(lo_s), int_val(hi_s)) else {
                        return None;
                    };
                    Some(Condition::Range {
                        column_id: cdef.id,
                        lo,
                        hi,
                    })
                }
                TypeId::Float32 | TypeId::Float64 => {
                    let (Some(lo), Some(hi)) = (float_val(lo_s), float_val(hi_s)) else {
                        return None;
                    };
                    Some(Condition::RangeF64 {
                        column_id: cdef.id,
                        lo,
                        lo_inclusive: true,
                        hi,
                        hi_inclusive: true,
                    })
                }
                _ => None,
            }
        }

        // `col LIKE pattern` → FM-index substring on the longest literal segment.
        Expr::Like(Like {
            negated,
            expr,
            pattern,
            ..
        }) => {
            if *negated {
                return None;
            }
            let Expr::Column(c) = expr.as_ref() else {
                return None;
            };
            let Expr::Literal(ScalarValue::Utf8(Some(pat)), _) = pattern.as_ref() else {
                return None;
            };
            let cdef = col_def(&c.name)?;
            // §5.6: anchored prefix `LIKE 'literal%'` (no embedded wildcards)
            // on a bitmap-indexed column → exact BytesPrefix, tighter than the
            // FM substring superset. Checked before the FM path.
            if has_bitmap(cdef.id) {
                if let Some(prefix) = anchored_like_prefix(pat) {
                    return Some(Condition::BytesPrefix {
                        column_id: cdef.id,
                        prefix: mongreldb_core::Value::Bytes(prefix.as_bytes().to_vec())
                            .encode_key(),
                    });
                }
            }
            if !has_fm(cdef.id) {
                return None;
            }
            // Priority 12: extract ALL literal segments (≥3 chars) and intersect
            // their FM results for a much tighter superset than the single
            // longest segment. Falls back to the longest when only one qualifies.
            let segments: Vec<Vec<u8>> = pat
                .split(['%', '_'])
                .filter(|s| s.len() >= 3)
                .map(|s| s.as_bytes().to_vec())
                .collect();
            match segments.len() {
                0 => longest_like_segment(pat).map(|seg| Condition::FmContains {
                    column_id: cdef.id,
                    pattern: seg,
                }),
                1 => Some(Condition::FmContains {
                    column_id: cdef.id,
                    pattern: segments.into_iter().next().unwrap(),
                }),
                _ => Some(Condition::FmContainsAll {
                    column_id: cdef.id,
                    patterns: segments,
                }),
            }
        }

        // `col IN (lit1, lit2, …)` → BitmapIn (bitmap union). Phase 13.5:
        // runtime-filter pushdown for semi-joins and IN-list filters. Only when
        // the column has a bitmap index and every list entry is a literal.
        Expr::InList(il) if !il.negated => {
            let Expr::Column(c) = il.expr.as_ref() else {
                return None;
            };
            let cdef = col_def(&c.name)?;
            if !has_bitmap(cdef.id) {
                return None;
            }
            let values: Vec<Vec<u8>> = il
                .list
                .iter()
                .filter_map(|e| match e {
                    Expr::Literal(s, _) => val(s).map(|v| v.encode_key()),
                    _ => None,
                })
                .collect();
            if values.is_empty() || values.len() != il.list.len() {
                return None;
            }
            Some(Condition::BitmapIn {
                column_id: cdef.id,
                values,
            })
        }

        // `col IS NULL` → page-stat-pruned column scan for null validity.
        Expr::IsNull(inner) => {
            let col_name = match inner.as_ref() {
                Expr::Column(c) => &c.name,
                _ => return None,
            };
            let cdef = col_def(col_name)?;
            Some(Condition::IsNull { column_id: cdef.id })
        }

        // `col IS NOT NULL` → complement of IS NULL.
        Expr::IsNotNull(inner) => {
            let col_name = match inner.as_ref() {
                Expr::Column(c) => &c.name,
                _ => return None,
            };
            let cdef = col_def(col_name)?;
            Some(Condition::IsNotNull { column_id: cdef.id })
        }

        _ => None,
    }
}

/// Phase 16.3a: extract the SQL `LIKE` pattern from `filters` for residual
/// pre-filtering on `NativeColumn` buffers. Returns a `ResidualFilter` when a
/// non-negated LIKE on a Bytes column is found among the filters.
pub(crate) fn extract_residual_filter(
    filters: &[Expr],
    col_ids: &[u16],
    schema: &mongreldb_core::Schema,
) -> Option<std::sync::Arc<scan::ResidualFilter>> {
    use datafusion::common::ScalarValue;
    use datafusion::logical_expr::Like;
    for f in filters {
        if let Expr::Like(Like {
            negated: false,
            expr,
            pattern,
            ..
        }) = f
        {
            let Expr::Column(c) = expr.as_ref() else {
                continue;
            };
            let Expr::Literal(ScalarValue::Utf8(Some(pat)), _) = pattern.as_ref() else {
                continue;
            };
            let cdef = schema.columns.iter().find(|col| col.name == c.name)?;
            let col_idx = col_ids.iter().position(|&id| id == cdef.id)?;
            return Some(std::sync::Arc::new(scan::ResidualFilter::new(
                col_idx,
                pat.as_bytes().to_vec(),
            )));
        }
    }
    None
}

/// Translate `ann_search(<embedding-col>, '<json f32 array>', k)` — the SQL hook
/// for HNSW semantic search — into [`Condition::Ann`]. The `ann_search` UDF is
/// registered by [`MongrelSession`] purely so the SQL parses; the provider's
/// pushdown serves the real top-k, and `supports_filters_pushdown` marks the
/// filter `Exact` so DataFusion never evaluates the (no-op) UDF itself.
pub(crate) fn translate_ann_search(
    expr: &Expr,
    schema: &mongreldb_core::Schema,
) -> Option<mongreldb_core::Condition> {
    use datafusion::common::ScalarValue;
    use mongreldb_core::Condition;

    let Expr::ScalarFunction(sf) = expr else {
        return None;
    };
    if !sf.func.name().eq_ignore_ascii_case("ann_search") || sf.args.len() != 3 {
        return None;
    }
    let (Expr::Column(c), query_expr, k_expr) = (&sf.args[0], &sf.args[1], &sf.args[2]) else {
        return None;
    };
    let cdef = schema.columns.iter().find(|col| col.name == c.name)?;
    let json = match query_expr {
        Expr::Literal(ScalarValue::Utf8(Some(s)), _) => s.as_str(),
        _ => return None,
    };
    let k: i64 = match k_expr {
        Expr::Literal(scalar, _) => match scalar {
            ScalarValue::Int64(Some(k)) => *k,
            ScalarValue::UInt64(Some(k)) => *k as i64,
            ScalarValue::Int32(Some(k)) => *k as i64,
            _ => return None,
        },
        _ => return None,
    };
    let query: Vec<f32> = serde_json::from_str(json).ok()?;
    Some(Condition::Ann {
        column_id: cdef.id,
        query,
        k: k.max(1) as usize,
    })
}

/// Translate `sparse_match(<sparse-col>, '<json [[token, weight], …]>', k)` —
/// the SQL hook for SPLADE-style sparse retrieval — into
/// [`Condition::SparseMatch`]. The UDF is registered by [`MongrelSession`]
/// purely so the SQL parses; the provider's pushdown serves the real top-k.
pub(crate) fn translate_sparse_match(
    expr: &Expr,
    schema: &mongreldb_core::Schema,
) -> Option<mongreldb_core::Condition> {
    use datafusion::common::ScalarValue;
    use mongreldb_core::Condition;

    let Expr::ScalarFunction(sf) = expr else {
        return None;
    };
    if !sf.func.name().eq_ignore_ascii_case("sparse_match") || sf.args.len() != 3 {
        return None;
    }
    let (Expr::Column(c), query_expr, k_expr) = (&sf.args[0], &sf.args[1], &sf.args[2]) else {
        return None;
    };
    let cdef = schema.columns.iter().find(|col| col.name == c.name)?;
    let json = match query_expr {
        Expr::Literal(ScalarValue::Utf8(Some(s)), _) => s.as_str(),
        _ => return None,
    };
    let k: i64 = match k_expr {
        Expr::Literal(scalar, _) => match scalar {
            ScalarValue::Int64(Some(k)) => *k,
            ScalarValue::UInt64(Some(k)) => *k as i64,
            ScalarValue::Int32(Some(k)) => *k as i64,
            _ => return None,
        },
        _ => return None,
    };
    let query: Vec<(u32, f32)> = serde_json::from_str(json).ok()?;
    Some(Condition::SparseMatch {
        column_id: cdef.id,
        query,
        k: k.max(1) as usize,
    })
}

/// Mirror a comparison operator for the `literal OP col` form.
fn flip_op(op: datafusion::logical_expr::Operator) -> Option<datafusion::logical_expr::Operator> {
    use datafusion::logical_expr::Operator;
    Some(match op {
        Operator::Eq => Operator::Eq,
        Operator::Lt => Operator::Gt,
        Operator::Gt => Operator::Lt,
        Operator::LtEq => Operator::GtEq,
        Operator::GtEq => Operator::LtEq,
        _ => return None,
    })
}

/// Convert `col OP v` into inclusive Int64 `[lo, hi]` bounds (exact for all of
/// `<`, `>`, `<=`, `>=` via saturating ±1).
fn int_bounds(op: datafusion::logical_expr::Operator, v: i64) -> Option<(i64, i64)> {
    use datafusion::logical_expr::Operator;
    Some(match op {
        Operator::Gt => (v.saturating_add(1), i64::MAX),
        Operator::GtEq => (v, i64::MAX),
        Operator::Lt => (i64::MIN, v.saturating_sub(1)),
        Operator::LtEq => (i64::MIN, v),
        _ => return None,
    })
}

/// Convert `col OP v` into Float64 bounds with per-bound inclusivity.
fn float_bounds(op: datafusion::logical_expr::Operator, v: f64) -> Option<(f64, bool, f64, bool)> {
    use datafusion::logical_expr::Operator;
    Some(match op {
        Operator::Gt => (v, false, f64::INFINITY, false),
        Operator::GtEq => (v, true, f64::INFINITY, false),
        Operator::Lt => (f64::NEG_INFINITY, false, v, false),
        Operator::LtEq => (f64::NEG_INFINITY, false, v, true),
        _ => return None,
    })
}

/// Longest contiguous literal (non-`%`, non-`_`) segment of a SQL LIKE pattern;
/// `None` if the pattern is all wildcards (matches everything → no pushdown).
/// Splitting on BOTH wildcards (not just `%`) keeps the segment a true literal
/// substring of every match, so the FM-index search is a correct *superset* —
/// e.g. `%City_1%` ⇒ segment `City` (not the literal `City_1`, which no match
/// like `City11` actually contains). DataFusion re-applies the real wildcard.
fn longest_like_segment(pat: &str) -> Option<Vec<u8>> {
    pat.split(['%', '_'])
        .map(|s| s.as_bytes())
        .max_by_key(|s| s.len())
        .filter(|s| !s.is_empty())
        .map(|s| s.to_vec())
}

/// Detect an anchored-prefix LIKE pattern: `literal%` with no `%` or `_` in
/// the literal part and a single trailing `%`. Returns the prefix (without the
/// `%`). Used to emit an exact `BytesPrefix` condition on bitmap-indexed
/// columns — tighter than the FM substring superset. (§5.6)
fn anchored_like_prefix(pat: &str) -> Option<&str> {
    let rest = pat.strip_suffix('%')?;
    if rest.is_empty() || rest.contains(['%', '_']) {
        return None;
    }
    Some(rest)
}

/// Unwrap a single-layer `Expr::Cast` wrapper to enable pushdown for queries
/// like `WHERE CAST(col AS BIGINT) = 5` (canonicalization). Returns the
/// original `Box` unchanged for non-cast expressions.
fn peel_cast(expr: &Expr) -> std::borrow::Cow<'_, Expr> {
    match expr {
        Expr::Cast(datafusion::logical_expr::Cast { expr, .. }) => std::borrow::Cow::Borrowed(expr),
        _ => std::borrow::Cow::Borrowed(expr),
    }
}

/// Flatten an OR tree of same-column equality comparisons into a `BitmapIn`.
/// Handles `col = v1 OR col = v2 OR ...` (and nested OR) that DataFusion's
/// optimizer may not have rewritten into `IN`. Returns `None` if the OR spans
/// different columns, non-equality comparisons, or a non-bitmap-indexed column.
fn try_or_as_bitmap_in(
    expr: &Expr,
    schema: &mongreldb_core::Schema,
) -> Option<mongreldb_core::Condition> {
    use datafusion::logical_expr::{BinaryExpr, Operator};
    let mut values: Vec<Vec<u8>> = Vec::new();
    let mut target_col: Option<u16> = None;
    let mut stack = vec![expr];
    while let Some(e) = stack.pop() {
        match e {
            Expr::BinaryExpr(BinaryExpr {
                left,
                op: Operator::Or,
                right,
            }) => {
                stack.push(left);
                stack.push(right);
            }
            Expr::BinaryExpr(BinaryExpr {
                left,
                op: Operator::Eq,
                right,
            }) => {
                let (col_name, scalar) = match (left.as_ref(), right.as_ref()) {
                    (Expr::Column(c), Expr::Literal(s, _)) => (&c.name, s),
                    (Expr::Literal(s, _), Expr::Column(c)) => (&c.name, s),
                    _ => return None,
                };
                let cdef = schema.columns.iter().find(|c| &c.name == col_name)?;
                if !schema
                    .indexes
                    .iter()
                    .any(|i| i.column_id == cdef.id && i.kind == mongreldb_core::IndexKind::Bitmap)
                {
                    return None;
                }
                match target_col {
                    None => target_col = Some(cdef.id),
                    Some(id) if id != cdef.id => return None,
                    _ => {}
                }
                let v = match scalar {
                    datafusion::common::ScalarValue::Int64(Some(v)) => {
                        mongreldb_core::Value::Int64(*v)
                    }
                    datafusion::common::ScalarValue::Utf8(Some(s)) => {
                        mongreldb_core::Value::Bytes(s.as_bytes().to_vec())
                    }
                    datafusion::common::ScalarValue::Float64(Some(f)) => {
                        mongreldb_core::Value::Float64(*f)
                    }
                    datafusion::common::ScalarValue::Boolean(Some(b)) => {
                        mongreldb_core::Value::Bool(*b)
                    }
                    _ => return None,
                };
                values.push(v.encode_key());
            }
            _ => return None,
        }
    }
    let col_id = target_col?;
    if values.is_empty() {
        return None;
    }
    Some(mongreldb_core::Condition::BitmapIn {
        column_id: col_id,
        values,
    })
}

// ──────────────────────────────────────────────────────────────────────────
// §5.3 direct SQL dispatch: translate a sqlparser AST WHERE clause into the
// engine's exact Condition set (no DataFusion involvement). Only predicates
// whose Condition is EXACT are accepted; everything else returns None so the
// caller falls through to the DataFusion path (which re-applies residuals).

fn sp_ident_name(expr: &sqlparser::ast::Expr) -> Option<&str> {
    use sqlparser::ast::Expr;
    match expr {
        Expr::Identifier(ident) => Some(ident.value.as_str()),
        Expr::CompoundIdentifier(idents) => idents.last().map(|i| i.value.as_str()),
        _ => None,
    }
}

/// A sqlparser literal → core Value. Numbers widen to Int64 (or Float64 if they
/// don't fit i64); single-quoted strings → Bytes; booleans → Bool.
fn sp_literal(expr: &sqlparser::ast::Expr) -> Option<mongreldb_core::Value> {
    use sqlparser::ast::Expr;
    let v = match expr {
        Expr::Value(v) => v,
        _ => return None,
    };
    use sqlparser::ast::Value as SpValue;
    match &v.value {
        SpValue::Number(s, _) => s
            .parse::<i64>()
            .map(mongreldb_core::Value::Int64)
            .or_else(|_| s.parse::<f64>().map(mongreldb_core::Value::Float64))
            .ok(),
        SpValue::SingleQuotedString(s) => Some(mongreldb_core::Value::Bytes(s.as_bytes().to_vec())),
        SpValue::Boolean(b) => Some(mongreldb_core::Value::Bool(*b)),
        _ => None,
    }
}

fn is_int_ty(ty: mongreldb_core::schema::TypeId) -> bool {
    use mongreldb_core::schema::TypeId::*;
    matches!(
        ty,
        Int8 | Int16 | Int32 | Int64 | UInt8 | UInt16 | UInt32 | UInt64 | TimestampNanos | Date32
    )
}

fn is_float_ty(ty: mongreldb_core::schema::TypeId) -> bool {
    matches!(
        ty,
        mongreldb_core::schema::TypeId::Float32 | mongreldb_core::schema::TypeId::Float64
    )
}

/// Translate ONE sqlparser predicate `Expr` into one exact `Condition`.
/// Returns `None` for anything inexact or unsupported (→ caller falls through).
fn translate_sqlparser_predicate(
    expr: &sqlparser::ast::Expr,
    schema: &mongreldb_core::Schema,
) -> Option<mongreldb_core::Condition> {
    use mongreldb_core::{schema::ColumnFlags, Condition, IndexKind, Value};
    use sqlparser::ast::{BinaryOperator, Expr};

    let col_def = |name: &str| schema.columns.iter().find(|c| c.name == name);
    let has_bitmap = |cid: u16| {
        schema
            .indexes
            .iter()
            .any(|i| i.column_id == cid && i.kind == IndexKind::Bitmap)
    };

    match expr {
        // `a = b OR a = c …` (one column, all literals) → BitmapIn.
        Expr::BinaryOp {
            left,
            op: BinaryOperator::Or,
            right,
        } => {
            let mut values: Vec<Vec<u8>> = Vec::new();
            let mut target: Option<u16> = None;
            let mut stack: Vec<&Expr> = vec![left.as_ref(), right.as_ref()];
            while let Some(e) = stack.pop() {
                match e {
                    Expr::BinaryOp {
                        left,
                        op: BinaryOperator::Or,
                        right,
                    } => {
                        stack.push(left.as_ref());
                        stack.push(right.as_ref());
                    }
                    Expr::BinaryOp {
                        left,
                        op: BinaryOperator::Eq,
                        right,
                    } => {
                        let (name, lit) = match (left.as_ref(), right.as_ref()) {
                            (l, r) if sp_ident_name(l).is_some() && sp_literal(r).is_some() => {
                                (l, r)
                            }
                            (l, r) if sp_ident_name(r).is_some() && sp_literal(l).is_some() => {
                                (r, l)
                            }
                            _ => return None,
                        };
                        let cdef = col_def(sp_ident_name(name)?)?;
                        if !has_bitmap(cdef.id) {
                            return None;
                        }
                        match target {
                            None => target = Some(cdef.id),
                            Some(id) if id != cdef.id => return None,
                            _ => {}
                        }
                        values.push(sp_literal(lit)?.encode_key());
                    }
                    _ => return None,
                }
            }
            let cid = target?;
            (!values.is_empty()).then_some(Condition::BitmapIn {
                column_id: cid,
                values,
            })
        }
        // Comparison `col OP literal` (or mirrored).
        Expr::BinaryOp { left, op, right } => {
            let flipped;
            let (col_expr, lit_expr) = match (
                sp_ident_name(left),
                sp_literal(right),
                sp_ident_name(right),
                sp_literal(left),
            ) {
                (Some(_), Some(_), _, _) => {
                    flipped = false;
                    (left.as_ref(), right.as_ref())
                }
                (_, _, Some(_), Some(_)) => {
                    flipped = true;
                    (right.as_ref(), left.as_ref())
                }
                _ => return None,
            };
            let name = sp_ident_name(col_expr)?;
            let cdef = col_def(name)?;
            let v = sp_literal(lit_expr)?;
            use sqlparser::ast::BinaryOperator::*;
            // Inline the comparison→Range/RangeF64 bounds, fusing the flip
            // (BinaryOperator is not Copy, so we match the &op directly).
            match op {
                Eq => {
                    if has_bitmap(cdef.id) {
                        Some(Condition::BitmapEq {
                            column_id: cdef.id,
                            value: v.encode_key(),
                        })
                    } else if cdef.flags.contains(ColumnFlags::PRIMARY_KEY) {
                        Some(Condition::Pk(v.encode_key()))
                    } else {
                        None
                    }
                }
                Lt | LtEq | Gt | GtEq if is_int_ty(cdef.ty) => {
                    let n = match v {
                        Value::Int64(n) => n,
                        _ => return None,
                    };
                    // `col OP v`, or the mirrored `v OP col` with the flipped op.
                    let (lo, hi) = match (flipped, op) {
                        (false, Lt) | (true, Gt) => (i64::MIN, n.saturating_sub(1)),
                        (false, Gt) | (true, Lt) => (n.saturating_add(1), i64::MAX),
                        (false, LtEq) | (true, GtEq) => (i64::MIN, n),
                        (false, GtEq) | (true, LtEq) => (n, i64::MAX),
                        _ => (i64::MIN, i64::MAX),
                    };
                    Some(Condition::Range {
                        column_id: cdef.id,
                        lo,
                        hi,
                    })
                }
                Lt | LtEq | Gt | GtEq if is_float_ty(cdef.ty) => {
                    let f = match v {
                        Value::Float64(f) => f,
                        _ => return None,
                    };
                    let (lo, li, hi, hi_i) = match (flipped, op) {
                        (false, Lt) | (true, Gt) => (f64::NEG_INFINITY, true, f, false),
                        (false, Gt) | (true, Lt) => (f, false, f64::INFINITY, true),
                        (false, LtEq) | (true, GtEq) => (f64::NEG_INFINITY, true, f, true),
                        (false, GtEq) | (true, LtEq) => (f, true, f64::INFINITY, true),
                        _ => (f64::NEG_INFINITY, true, f64::INFINITY, true),
                    };
                    Some(Condition::RangeF64 {
                        column_id: cdef.id,
                        lo,
                        lo_inclusive: li,
                        hi,
                        hi_inclusive: hi_i,
                    })
                }
                _ => None,
            }
        }
        Expr::Between {
            expr,
            negated,
            low,
            high,
        } if !negated => {
            let name = sp_ident_name(expr)?;
            let cdef = col_def(name)?;
            if is_int_ty(cdef.ty) {
                let lo = match sp_literal(low)? {
                    Value::Int64(n) => n,
                    _ => return None,
                };
                let hi = match sp_literal(high)? {
                    Value::Int64(n) => n,
                    _ => return None,
                };
                Some(Condition::Range {
                    column_id: cdef.id,
                    lo,
                    hi,
                })
            } else if is_float_ty(cdef.ty) {
                let lo = match sp_literal(low)? {
                    Value::Float64(f) => f,
                    _ => return None,
                };
                let hi = match sp_literal(high)? {
                    Value::Float64(f) => f,
                    _ => return None,
                };
                Some(Condition::RangeF64 {
                    column_id: cdef.id,
                    lo,
                    lo_inclusive: true,
                    hi,
                    hi_inclusive: true,
                })
            } else {
                None
            }
        }
        Expr::InList {
            expr,
            list,
            negated,
        } if !negated => {
            let name = sp_ident_name(expr)?;
            let cdef = col_def(name)?;
            if !has_bitmap(cdef.id) {
                return None;
            }
            let values: Vec<Vec<u8>> = list
                .iter()
                .map(|e| sp_literal(e).map(|v| v.encode_key()))
                .collect::<Option<_>>()?;
            (!values.is_empty()).then_some(Condition::BitmapIn {
                column_id: cdef.id,
                values,
            })
        }
        // `col IS NULL` / `col IS NOT NULL`. sqlparser 0.62 represents these as
        // `IsNull(expr)` / `IsNotNull(expr)` (and, defensively, `IsBoolean`).
        Expr::IsNull(inner) => {
            let cid = col_def(sp_ident_name(inner)?)?.id;
            Some(Condition::IsNull { column_id: cid })
        }
        Expr::IsNotNull(inner) => {
            let cid = col_def(sp_ident_name(inner)?)?.id;
            Some(Condition::IsNotNull { column_id: cid })
        }
        _ => None,
    }
}

/// Split a top-level AND tree into conjuncts, translating each to an exact
/// Condition. Returns `None` if any conjunct is inexact/unsupported.
fn translate_sqlparser_filter(
    expr: &sqlparser::ast::Expr,
    schema: &mongreldb_core::Schema,
) -> Option<Vec<mongreldb_core::Condition>> {
    use sqlparser::ast::{BinaryOperator, Expr};
    let mut out = Vec::new();
    let mut stack = vec![expr];
    while let Some(e) = stack.pop() {
        match e {
            Expr::BinaryOp {
                left,
                op: BinaryOperator::And,
                right,
            } => {
                stack.push(left.as_ref());
                stack.push(right.as_ref());
            }
            other => out.push(translate_sqlparser_predicate(other, schema)?),
        }
    }
    Some(out)
}

/// Convenience wrapper: a DataFusion `SessionContext` bound to a live MongrelDB,
/// with a result cache keyed by `(sql, snapshot_epoch)` that auto-invalidates
/// when a commit advances the epoch.
pub struct MongrelSession {
    ctx: SessionContext,
    db: Option<Arc<Mutex<Table>>>,
    /// P4.1: the multi-table `Database` when opened via `open()`. When `Some`,
    /// the cache epoch is driven by `Database::visible_epoch()` instead of the
    /// legacy `combined_epoch()` fold.
    database: Option<Arc<Database>>,
    cache: ResultCache,
    /// Phase 16.5: logical-plan cache keyed by SQL string.
    plan_cache: parking_lot::Mutex<HashMap<String, datafusion::logical_expr::LogicalPlan>>,
    /// `table name → owning Table handle` for every registered table.
    tables: parking_lot::Mutex<HashMap<String, Arc<Mutex<Table>>>>,
    /// Phase 17.3: named materialized views — `view name → defining SQL`.
    /// On `run("SELECT * FROM <view>")`, the defining SQL is executed (or the
    /// result-cache is hit). Invalidated automatically on commit (epoch bump).
    views: parking_lot::Mutex<HashMap<String, ViewDef>>,
    /// Databases attached via `ATTACH 'path' AS alias`, kept alive for the
    /// session's lifetime so their tables remain registered on the DataFusion
    /// context. Keyed by alias.
    attached_databases: parking_lot::Mutex<HashMap<String, Arc<Database>>>,
    /// SQL `BEGIN`/`COMMIT` staging for DML statements. Reads remain
    /// snapshot-at-scan; this batches SQL writes atomically when a client sends
    /// an explicit transaction block.
    sql_txn: parking_lot::Mutex<Option<Vec<commands::PendingSqlOp>>>,
    /// SAVEPOINT stack: `(name, staged-ops-length-at-savepoint)`. Truncated on
    /// `ROLLBACK TO name` and removed on `RELEASE name`.
    savepoints: parking_lot::Mutex<Vec<(String, usize)>>,
    /// Per-session state for SQL compatibility functions such as changes().
    sql_fn_state: Arc<extended_sql_functions::ExtendedSqlState>,
    /// Built-in plus app-provided external table modules available to this
    /// session.
    external_modules: Arc<ExternalModuleRegistry>,
}

/// `(sql, snapshot_epoch) → cached result batches`.
type CacheKey = (String, u64);
type ResultCache = parking_lot::Mutex<std::collections::HashMap<CacheKey, Arc<Vec<RecordBatch>>>>;

impl MongrelSession {
    /// Create a session over a live `Table`. Takes ownership; wrap in `Arc` if you
    /// need to keep a handle for writes after registering the provider. Registers
    /// the `ann_search` UDF so SQL semantic-search predicates parse.
    pub fn new(db: Table) -> Self {
        let db = Arc::new(Mutex::new(db));
        let ctx = SessionContext::new();
        let sql_fn_state = Arc::new(extended_sql_functions::ExtendedSqlState::default());
        register_mongrel_functions(&ctx, Arc::clone(&sql_fn_state));
        let external_modules = Arc::new(ExternalModuleRegistry::default());
        Self {
            ctx,
            db: Some(db),
            database: None,
            cache: parking_lot::Mutex::new(std::collections::HashMap::new()),
            plan_cache: parking_lot::Mutex::new(HashMap::new()),
            tables: parking_lot::Mutex::new(HashMap::new()),
            views: parking_lot::Mutex::new(HashMap::new()),
            attached_databases: parking_lot::Mutex::new(HashMap::new()),
            savepoints: parking_lot::Mutex::new(Vec::new()),
            sql_txn: parking_lot::Mutex::new(None),
            sql_fn_state,
            external_modules,
        }
    }

    pub fn new_with_external_modules(
        db: Table,
        modules: impl IntoIterator<Item = Arc<dyn ExternalTableModule>>,
    ) -> Result<Self> {
        let session = Self::new(db);
        for module in modules {
            session.register_external_module(module)?;
        }
        Ok(session)
    }

    /// Open a session over a multi-table [`Database`] (spec §12). Auto-registers
    /// every live table as a `MongrelProvider`; the cache epoch is driven by
    /// `Database::visible_epoch()` so any table's commit invalidates cached
    /// results.
    pub fn open(database: Arc<Database>) -> Result<Self> {
        Self::open_with_external_modules(database, std::iter::empty())
    }

    pub fn open_with_external_modules(
        database: Arc<Database>,
        modules: impl IntoIterator<Item = Arc<dyn ExternalTableModule>>,
    ) -> Result<Self> {
        let ctx = SessionContext::new();
        let sql_fn_state = Arc::new(extended_sql_functions::ExtendedSqlState::default());
        register_mongrel_functions(&ctx, Arc::clone(&sql_fn_state));
        let external_modules = Arc::new(ExternalModuleRegistry::default());
        for module in modules {
            external_modules.register(module)?;
        }

        let mut tables: HashMap<String, Arc<Mutex<Table>>> = HashMap::new();
        for name in database.table_names() {
            let handle = database.table(&name)?;
            let provider = MongrelProvider::new(handle.clone())?;
            ctx.register_table(&name, Arc::new(provider))
                .map_err(|e| MongrelQueryError::DataFusion(e.to_string()))?;
            tables.insert(name, handle);
        }
        for entry in database.external_tables() {
            let provider = external_modules.external_table_provider(&database, &entry)?;
            ctx.register_table(&entry.name, provider)
                .map_err(|e| MongrelQueryError::DataFusion(e.to_string()))?;
        }

        // Pick a stable "primary" (lexicographically smallest name) for legacy
        // `db()` accessors. If the database is empty, `db()` returns `None`.
        let primary = {
            let mut names: Vec<&String> = tables.keys().collect();
            names.sort();
            names.first().and_then(|n| tables.get(*n).cloned())
        };

        Ok(Self {
            ctx,
            db: primary,
            database: Some(database),
            cache: parking_lot::Mutex::new(std::collections::HashMap::new()),
            plan_cache: parking_lot::Mutex::new(HashMap::new()),
            tables: parking_lot::Mutex::new(tables),
            views: parking_lot::Mutex::new(HashMap::new()),
            attached_databases: parking_lot::Mutex::new(HashMap::new()),
            savepoints: parking_lot::Mutex::new(Vec::new()),
            sql_txn: parking_lot::Mutex::new(None),
            sql_fn_state,
            external_modules,
        })
    }

    pub fn register_external_module(&self, module: Arc<dyn ExternalTableModule>) -> Result<()> {
        self.external_modules.register(module)?;
        self.clear_cache();
        Ok(())
    }

    /// The underlying Table handle (Phase 19.3: used by the daemon for direct
    /// put/delete/commit/count access). Returns `None` when the session was
    /// opened over an empty `Database`.
    pub fn db(&self) -> Option<&Arc<Mutex<Table>>> {
        self.db.as_ref()
    }

    /// Phase 17.3: create a named materialized view backed by a SQL query.
    /// `SELECT * FROM <name>` resolves to the view's defining SQL, which is
    /// executed (or served from the result cache) transparently. The view is
    /// automatically invalidated on commit (via the epoch-keyed result cache).
    pub fn create_view(&self, name: &str, sql: &str) {
        self.create_view_with_schema(name, sql, CoreSchema::default(), HashMap::new());
    }

    pub(crate) fn create_view_with_schema(
        &self,
        name: &str,
        sql: &str,
        schema: CoreSchema,
        input_types: HashMap<u16, Option<TypeId>>,
    ) {
        self.views.lock().insert(
            name.to_string(),
            ViewDef {
                sql: sql.to_string(),
                schema,
                input_types,
            },
        );
    }

    /// Drop a named materialized view.
    pub fn drop_view(&self, name: &str) {
        self.views.lock().remove(name);
    }

    pub(crate) fn view_schema(&self, name: &str) -> Option<CoreSchema> {
        self.views.lock().get(name).map(|view| view.schema.clone())
    }

    pub(crate) fn view_definition(&self, name: &str) -> Option<ViewDef> {
        self.views.lock().get(name).cloned()
    }

    /// Register the table under `name` so `select * from <name>` resolves.
    pub async fn register(&self, name: &str) -> Result<()> {
        let db = self.db.clone().ok_or(MongrelQueryError::Core(
            mongreldb_core::MongrelError::NotFound("no primary table".into()),
        ))?;
        let provider = MongrelProvider::new(db.clone())?;
        self.tables.lock().insert(name.to_string(), db);
        self.ctx
            .register_table(name, Arc::new(provider))
            .map_err(|e| MongrelQueryError::DataFusion(e.to_string()))?;
        Ok(())
    }

    /// Register a second (or further) live `Table` as another table on the same
    /// session, enabling cross-table SQL joins. The first `Table` (passed to
    /// [`Self::new`]) still owns the result-cache epoch: cached results are
    /// invalidated on its commits, so mutate the primary table last or call
    /// [`Self::clear_cache`] after writing a secondary table.
    pub async fn register_db(&self, name: &str, db: Table) -> Result<()> {
        let db_arc = Arc::new(Mutex::new(db));
        let provider = MongrelProvider::new(db_arc.clone())?;
        self.tables.lock().insert(name.to_string(), db_arc);
        self.ctx
            .register_table(name, Arc::new(provider))
            .map_err(|e| MongrelQueryError::DataFusion(e.to_string()))?;
        Ok(())
    }

    fn refresh_registered_table(&self, db: &Arc<Database>, name: &str) -> Result<()> {
        self.ctx
            .deregister_table(name)
            .map_err(|e| MongrelQueryError::DataFusion(e.to_string()))?;
        let handle = db.table(name)?;
        let provider = MongrelProvider::new(handle.clone())?;
        self.ctx
            .register_table(name, Arc::new(provider))
            .map_err(|e| MongrelQueryError::DataFusion(e.to_string()))?;
        self.tables.lock().insert(name.to_string(), handle);
        Ok(())
    }

    /// Run a SQL statement and return the result batches. Repeated identical SQL
    /// against the same snapshot returns the cached batches without re-executing.
    /// Run a SQL statement and return the result batches. DDL statements
    /// (`CREATE TABLE`, `DROP TABLE`, `ALTER TABLE`) are intercepted when a
    /// Intercept `SELECT ... FROM information_schema.tables` and return
    /// a synthesized batch listing tables, views, and triggers. Returns
    /// `None` if the SQL doesn't reference that name.
    fn try_catalog_introspection(&self, sql: &str) -> Result<Option<Vec<RecordBatch>>> {
        let lower = sql.to_ascii_lowercase();
        if !lower.contains("information_schema.tables") {
            return Ok(None);
        }
        use arrow::array::{ArrayRef, Int64Array, StringArray};
        use arrow::datatypes::{DataType, Field, Schema};
        use arrow::record_batch::RecordBatch;

        let mut types: Vec<String> = Vec::new();
        let mut names: Vec<String> = Vec::new();
        let mut tbl_names: Vec<String> = Vec::new();

        // Tables.
        for name in self.tables.lock().keys() {
            types.push("table".into());
            names.push(name.clone());
            tbl_names.push(name.clone());
        }
        // Views (session-scoped).
        for name in self.views.lock().keys() {
            types.push("view".into());
            names.push(name.clone());
            tbl_names.push(name.clone());
        }
        // Triggers (engine-side, if a Database is attached).
        if let Some(db) = &self.database {
            for t in db.triggers() {
                let target_name = match &t.target {
                    mongreldb_core::trigger::TriggerTarget::Table(n)
                    | mongreldb_core::trigger::TriggerTarget::View(n) => n.clone(),
                };
                types.push("trigger".into());
                names.push(t.name.clone());
                tbl_names.push(target_name);
            }
        }

        let schema = Arc::new(Schema::new(vec![
            Field::new("type", DataType::Utf8, false),
            Field::new("name", DataType::Utf8, false),
            Field::new("tbl_name", DataType::Utf8, false),
            Field::new("rootpage", DataType::Int64, false),
            Field::new("sql", DataType::Utf8, true),
        ]));
        let n = names.len();
        let rootpages: Vec<i64> = vec![0; n];
        let sqls: Vec<Option<&str>> = vec![None; n];
        let batch = RecordBatch::try_new(
            schema,
            vec![
                Arc::new(StringArray::from(types)) as ArrayRef,
                Arc::new(StringArray::from(names)) as ArrayRef,
                Arc::new(StringArray::from(tbl_names)) as ArrayRef,
                Arc::new(Int64Array::from(rootpages)) as ArrayRef,
                Arc::new(StringArray::from(sqls)) as ArrayRef,
            ],
        )
        .map_err(|e| MongrelQueryError::Arrow(e.to_string()))?;
        Ok(Some(vec![batch]))
    }

    /// §5.3 direct SQL dispatch: recognize a simple single-table `SELECT` from
    /// the raw SQL via the vendored `sqlparser` AST and serve it straight from
    /// the native column cursor, **bypassing DataFusion parse+plan+optimize**.
    /// Returns `Ok(None)` (→ fall through to `ctx.sql()`) for any shape it
    /// cannot serve *exactly*, or on any parse error. See the design doc at
    /// `docs/superpowers/plans/2026-07-02-direct-sql-dispatch.md`.
    fn try_direct_dispatch(&self, sql: &str) -> Result<Option<Vec<RecordBatch>>> {
        use arrow::array::ArrayRef;
        use mongreldb_core::Condition;
        use sqlparser::ast::{Expr, Query, SelectItem, SetExpr, Statement, TableFactor};
        use sqlparser::dialect::PostgreSqlDialect;
        use sqlparser::parser::Parser;

        // Any parse error, or more than one statement → fall through.
        let Ok(stmts) = Parser::parse_sql(&PostgreSqlDialect {}, sql) else {
            return Ok(None);
        };
        if stmts.len() != 1 {
            return Ok(None);
        }
        let Statement::Query(query) = stmts.into_iter().next().unwrap() else {
            return Ok(None);
        };
        let Query { body, .. } = *query;
        let select = match *body {
            SetExpr::Select(s) => *s,
            _ => return Ok(None),
        };
        // v1: fall through if LIMIT/OFFSET is present (can't read the fields
        // portably; a conservative token check keeps correctness safe).
        let lower_sql = sql.to_lowercase();
        if lower_sql.contains(" limit ") || lower_sql.contains(" offset ") {
            return Ok(None);
        }
        // Reject shapes we don't handle: DISTINCT / GROUP BY / HAVING / multi-FROM / joins.
        use sqlparser::ast::GroupByExpr;
        if select.distinct.is_some()
            || !matches!(&select.group_by, GroupByExpr::Expressions(e, _) if e.is_empty())
            || select.having.is_some()
            || select.from.len() != 1
            || !select.from[0].joins.is_empty()
        {
            return Ok(None);
        }
        let table_name = match &select.from[0].relation {
            TableFactor::Table { name, .. } => Some(name.to_string()),
            _ => return Ok(None),
        };
        let Some(table_name) = table_name else {
            return Ok(None);
        };

        // v1 only dispatches FILTERED single-table SELECTs. An unfiltered `SELECT
        // *`/`SELECT cols` already streams efficiently through the scan path
        // (with ≤65 536-row batch chunking + Arrow shadow writes), which the
        // direct path's single-shot column decode can't preserve — so leave it
        // to DataFusion. The win here is the cold filtered-SELECT planning cost.
        if select.selection.is_none() {
            return Ok(None);
        }

        // Projection: only `*` or a list of bare column identifiers.
        let mut proj_names: Option<Vec<String>> = None;
        for item in &select.projection {
            match item {
                SelectItem::Wildcard(_) => {}
                SelectItem::UnnamedExpr(Expr::Identifier(ident)) => {
                    proj_names
                        .get_or_insert_with(Vec::new)
                        .push(ident.value.clone());
                }
                SelectItem::UnnamedExpr(Expr::CompoundIdentifier(idents)) => {
                    if let Some(last) = idents.last() {
                        proj_names
                            .get_or_insert_with(Vec::new)
                            .push(last.value.clone());
                    }
                }
                _ => return Ok(None),
            }
        }

        // Resolve the table handle.
        let handle = match self.tables.lock().get(&table_name).cloned() {
            Some(h) => h,
            None => return Ok(None),
        };

        let mut db = handle.lock();
        let schema = db.schema().clone();
        // Translate WHERE against the live schema; an inexact/unsupported
        // predicate → fall through to DataFusion (which re-applies residuals).
        let conditions: Vec<Condition> = match &select.selection {
            Some(expr) => match translate_sqlparser_filter(expr, &schema) {
                Some(c) => c,
                None => return Ok(None),
            },
            None => Vec::new(),
        };
        if !conditions.is_empty() && db.ensure_indexes_complete().is_err() {
            return Ok(None);
        }
        let snap = db.snapshot();

        // Resolve projected column ids + Arrow field list (in projection order).
        let mut col_ids: Vec<u16> = Vec::new();
        let mut fields: Vec<arrow::datatypes::Field> = Vec::new();
        let resolve_col = |name: &str| -> Option<&mongreldb_core::schema::ColumnDef> {
            schema.columns.iter().find(|c| c.name == name)
        };
        match &proj_names {
            None => {
                for c in &schema.columns {
                    col_ids.push(c.id);
                    fields.push(arrow::datatypes::Field::new(
                        &c.name,
                        arrow_conv::arrow_data_type(&c.ty)?,
                        c.flags.contains(mongreldb_core::ColumnFlags::NULLABLE),
                    ));
                }
            }
            Some(names) => {
                for n in names {
                    let cdef = match resolve_col(n) {
                        Some(c) => c,
                        None => return Ok(None), // unknown column → let DataFusion error
                    };
                    col_ids.push(cdef.id);
                    fields.push(arrow::datatypes::Field::new(
                        &cdef.name,
                        arrow_conv::arrow_data_type(&cdef.ty)?,
                        cdef.flags.contains(mongreldb_core::ColumnFlags::NULLABLE),
                    ));
                }
            }
        }

        // Execute via the same native column path MongrelProvider::scan uses.
        let cols = if !conditions.is_empty() {
            match db.query_columns_native_cached(&conditions, Some(&col_ids), snap) {
                Ok(Some(c)) => c,
                Ok(None) => db
                    .visible_columns_native(snap, Some(&col_ids))
                    .map_err(MongrelQueryError::Core)?,
                Err(_) => return Ok(None),
            }
        } else {
            db.visible_columns_native(snap, Some(&col_ids))
                .map_err(MongrelQueryError::Core)?
        };
        drop(db);

        // Order decoded columns into projection order, then build one batch.
        let mut arrays: Vec<ArrayRef> = Vec::with_capacity(col_ids.len());
        for cid in &col_ids {
            let col = cols
                .iter()
                .find(|(id, _)| id == cid)
                .map(|(_, c)| c.clone());
            let Some(col) = col else { return Ok(None) };
            let ty = schema
                .columns
                .iter()
                .find(|c| c.id == *cid)
                .map(|c| c.ty)
                .unwrap_or(mongreldb_core::schema::TypeId::Int64);
            arrays.push(arrow_conv::native_to_array(ty, &col)?);
        }
        let batch_schema = Arc::new(arrow::datatypes::Schema::new(fields));
        let batch = RecordBatch::try_new(batch_schema, arrays)
            .map_err(|e| MongrelQueryError::Arrow(format!("direct dispatch batch build: {e}")))?;

        mongreldb_core::trace::QueryTrace::record(|t| {
            t.scan_mode = mongreldb_core::trace::ScanMode::DirectDispatch;
            t.planning_nanos = 0; // we bypassed DataFusion planning
        });
        Ok(Some(vec![batch]))
    }

    /// Run a SQL statement: DDL/commands are intercepted; otherwise a result
    /// cache keyed by `(normalized SQL, snapshot epoch)` memoizes batches.
    /// §5.3: simple single-table SELECTs are served by [`try_direct_dispatch`]
    /// (no DataFusion planning) before falling back to the full DataFusion path.
    pub async fn run(&self, sql: &str) -> Result<Vec<RecordBatch>> {
        if let Some(inner) = strip_explain_query_plan(sql) {
            return self.explain_query_plan(inner).await;
        }
        if let Some(batches) = commands::try_run_command(self, sql).await? {
            return Ok(batches);
        }
        // P4.2: intercept DDL when a Database is attached.
        let lower = sql.trim_start().to_lowercase();
        if lower.starts_with("create table") {
            if let Some(db) = &self.database {
                let (name, schema) = parse_create_table(sql)?;
                db.create_table(&name, schema)?;
                let handle = db.table(&name)?;
                let provider = MongrelProvider::new(handle.clone())?;
                self.ctx
                    .register_table(&name, Arc::new(provider))
                    .map_err(|e| MongrelQueryError::DataFusion(e.to_string()))?;
                self.tables.lock().insert(name, handle);
                self.clear_cache();
                return Ok(Vec::new());
            }
        }
        if lower.starts_with("drop table") {
            if let Some(db) = &self.database {
                let (name, if_exists) = parse_drop_table(sql)?;
                let drop_result = db.drop_table(&name);
                if let Err(e) = drop_result {
                    // IF EXISTS tolerates NotFound.
                    let is_not_found = matches!(e, mongreldb_core::MongrelError::NotFound(_));
                    if !(if_exists && is_not_found) {
                        return Err(e.into());
                    }
                } else {
                    self.ctx
                        .deregister_table(&name)
                        .map_err(|e| MongrelQueryError::DataFusion(e.to_string()))?;
                    self.tables.lock().remove(&name);
                }
                self.clear_cache();
                return Ok(Vec::new());
            }
        }
        if lower.starts_with("alter table") {
            if let Some(db) = &self.database {
                match parse_alter_table(sql)? {
                    ParsedAlterTable::RenameTable { old_name, new_name } => {
                        db.rename_table(&old_name, &new_name)?;
                        // Re-key DataFusion + the session's handle cache under the new
                        // name. The table_id and underlying table object are unchanged
                        // by a rename, so a fresh handle resolves to the same table.
                        self.ctx
                            .deregister_table(&old_name)
                            .map_err(|e| MongrelQueryError::DataFusion(e.to_string()))?;
                        self.tables.lock().remove(&old_name);
                        let handle = db.table(&new_name)?;
                        let provider = MongrelProvider::new(handle.clone())?;
                        self.ctx
                            .register_table(&new_name, Arc::new(provider))
                            .map_err(|e| MongrelQueryError::DataFusion(e.to_string()))?;
                        self.tables.lock().insert(new_name, handle);
                    }
                    ParsedAlterTable::RenameColumn {
                        table_name,
                        column_name,
                        new_name,
                    } => {
                        db.alter_column(&table_name, &column_name, AlterColumn::rename(new_name))?;
                        self.refresh_registered_table(db, &table_name)?;
                    }
                    ParsedAlterTable::AlterColumnType {
                        table_name,
                        column_name,
                        ty,
                    } => {
                        db.alter_column(&table_name, &column_name, AlterColumn::set_type(ty))?;
                        self.refresh_registered_table(db, &table_name)?;
                    }
                    ParsedAlterTable::SetNotNull {
                        table_name,
                        column_name,
                    } => {
                        let flags = current_column_flags(db, &table_name, &column_name)?
                            .without(ColumnFlags::NULLABLE);
                        db.alter_column(&table_name, &column_name, AlterColumn::set_flags(flags))?;
                        self.refresh_registered_table(db, &table_name)?;
                    }
                    ParsedAlterTable::DropNotNull {
                        table_name,
                        column_name,
                    } => {
                        let flags = current_column_flags(db, &table_name, &column_name)?
                            .with(ColumnFlags::NULLABLE);
                        db.alter_column(&table_name, &column_name, AlterColumn::set_flags(flags))?;
                        self.refresh_registered_table(db, &table_name)?;
                    }
                }
                self.clear_cache();
                return Ok(Vec::new());
            }
        }

        // Phase 17.3: intercept `SELECT ... FROM <view_name>` and rewrite to
        // the view's defining SQL.
        let resolved = self.resolve_view_sql(sql);
        let resolved = self.rewrite_external_module_compat_sql(&resolved);
        let resolved = rewrite_compat_function_calls(&resolved);
        // Canonicalize whitespace outside literals/comments so queries that
        // differ only in spacing share a cache key (and parse identically — SQL
        // is whitespace-insensitive between tokens).
        let effective_sql = normalize_sql(&resolved);
        let sql = effective_sql.as_str();
        // The cache key uses the Database's visible epoch (P4.1) when opened
        // via `open()`, or the legacy `combined_epoch()` fold for multi-table
        // sessions created via `new()` + `register_db()`.
        let epoch = self.cache_epoch();
        let key = (sql.to_string(), epoch);
        let result_cacheable = !extended_sql_functions::contains_volatile_extended_function(sql);
        if result_cacheable {
            if let Some(hit) = self.cache.lock().get(&key) {
                return Ok((**hit).clone());
            }
        }
        // information_schema.tables: intercept catalog-introspection SELECTs
        // and synthesize a result batch.
        if let Some(batches) = self.try_catalog_introspection(sql)? {
            if result_cacheable {
                self.cache.lock().insert(key, Arc::new(batches.clone()));
            }
            return Ok(batches);
        }
        // §5.3: direct SQL dispatch for simple single-table SELECTs — bypasses
        // DataFusion parse+plan+optimize. Served batches are memoized into the
        // result cache like the normal path. Returns None (→ fall through) for
        // any shape it cannot serve exactly.
        if let Some(batches) = self.try_direct_dispatch(sql)? {
            if result_cacheable {
                self.cache.lock().insert(key, Arc::new(batches.clone()));
            }
            return Ok(batches);
        }
        // Phase 16.5: check the logical-plan cache before re-parsing.
        let plan_start = std::time::Instant::now();
        let external_module_scan = self.query_references_external_module(sql);
        let df = {
            let cached_plan = self.plan_cache.lock().get(sql).cloned();
            if let Some(plan) = cached_plan {
                datafusion::dataframe::DataFrame::new(self.ctx.state(), plan)
            } else {
                let df = self
                    .ctx
                    .sql(sql)
                    .await
                    .map_err(|e| MongrelQueryError::DataFusion(e.to_string()))?;
                self.plan_cache
                    .lock()
                    .insert(sql.to_string(), df.logical_plan().clone());
                df
            }
        };
        // Priority 8: record logical-planning time (parse + plan; ~0 on a
        // plan-cache hit), separate from execution.
        let planning_nanos = plan_start.elapsed().as_nanos() as u64;
        mongreldb_core::trace::QueryTrace::record(|t| t.planning_nanos = planning_nanos);

        // Phase 7.2/8.3 fast path: serve a simple single aggregate (SUM/MIN/MAX/
        // AVG/COUNT) over the primary table from the incremental aggregate
        // cache — warm cache ⇒ delta merge on commit; cold ⇒ vectorized scan.
        // Falls through to DataFusion for everything it cannot serve exactly.
        let agg_key = sql_cache_key(sql);
        let batches = match self.try_native_aggregate(df.logical_plan(), agg_key) {
            Ok(Some(batch)) => vec![batch],
            _ => {
                // Phase 8.1 fast path: serve a PK↔FK equi-join over two
                // registered tables via roaring-bitmap intersection, with no
                // hash-join materialization. Falls through otherwise.
                match self.try_fk_join(df.logical_plan()) {
                    Ok(Some(b)) => {
                        // Priority 13: the native FK-bitmap path served the join.
                        mongreldb_core::trace::QueryTrace::record(|t| {
                            t.join_mode = mongreldb_core::trace::JoinMode::FkBitmap;
                        });
                        b
                    }
                    _ => df
                        .collect()
                        .await
                        .map_err(|e| MongrelQueryError::DataFusion(e.to_string()))?,
                }
            }
        };
        if external_module_scan {
            mongreldb_core::trace::QueryTrace::record(|t| {
                t.scan_mode = mongreldb_core::trace::ScanMode::ExternalModule;
            });
        }
        if result_cacheable {
            self.cache.lock().insert(key, Arc::new(batches.clone()));
        }
        Ok(batches)
    }

    /// [`Self::run`] with a captured [`mongreldb_core::trace::QueryTrace`].
    ///
    /// Runs the SQL query inside a trace-capture scope so that path-decision
    /// recordings from both the SQL scan layer (`MongrelProvider::scan`) and
    /// the core engine (`Table::native_page_cursor`, `query_columns_native`,
    /// `count_conditions`, etc.) are collected into a single returned trace.
    ///
    /// The session-level result cache returns before `scan()` runs on a hit, so
    /// a session-cache hit yields `scan_mode = Unknown`. For scan-level
    /// result-cache tracing, use
    /// [`mongreldb_core::Table::query_columns_native_cached_traced`].
    pub async fn run_sql_traced(
        &self,
        sql: &str,
    ) -> Result<(Vec<RecordBatch>, mongreldb_core::trace::QueryTrace)> {
        mongreldb_core::trace::QueryTrace::push_scope();
        let result = self.run(sql).await;
        let trace = mongreldb_core::trace::QueryTrace::pop_scope();
        Ok((result?, trace))
    }

    /// Drop all cached results (e.g. after a manual data change you want
    /// reflected immediately).
    pub fn clear_cache(&self) {
        self.cache.lock().clear();
        self.plan_cache.lock().clear();
    }

    async fn explain_query_plan(&self, sql: &str) -> Result<Vec<RecordBatch>> {
        let explain_sql = format!("EXPLAIN {}", sql.trim().trim_end_matches(';'));
        let batches = self
            .ctx
            .sql(&explain_sql)
            .await
            .map_err(|e| MongrelQueryError::DataFusion(e.to_string()))?
            .collect()
            .await
            .map_err(|e| MongrelQueryError::DataFusion(e.to_string()))?;
        let mut detail = self.mongrel_query_plan_details(sql);
        for batch in &batches {
            if batch.num_columns() < 2 {
                continue;
            }
            let Some(plan_type) = batch.column(0).as_any().downcast_ref::<StringArray>() else {
                continue;
            };
            let Some(plan) = batch.column(1).as_any().downcast_ref::<StringArray>() else {
                continue;
            };
            for row in 0..batch.num_rows() {
                let prefix = plan_type.value(row);
                for line in plan.value(row).lines() {
                    let line = line.trim();
                    if !line.is_empty() {
                        detail.push(format!("DATAFUSION {prefix}: {line}"));
                    }
                }
            }
        }
        if detail.is_empty() {
            detail.push("plan unavailable".to_string());
        }
        let ids = (0..detail.len()).map(|i| i as i64).collect::<Vec<_>>();
        let parents = vec![0_i64; detail.len()];
        let notused = vec![0_i64; detail.len()];
        let schema = Arc::new(arrow::datatypes::Schema::new(vec![
            arrow::datatypes::Field::new("id", arrow::datatypes::DataType::Int64, false),
            arrow::datatypes::Field::new("parent", arrow::datatypes::DataType::Int64, false),
            arrow::datatypes::Field::new("notused", arrow::datatypes::DataType::Int64, false),
            arrow::datatypes::Field::new("detail", arrow::datatypes::DataType::Utf8, false),
        ]));
        let batch = RecordBatch::try_new(
            schema,
            vec![
                Arc::new(Int64Array::from(ids)) as ArrayRef,
                Arc::new(Int64Array::from(parents)),
                Arc::new(Int64Array::from(notused)),
                Arc::new(StringArray::from(detail)),
            ],
        )
        .map_err(|e| MongrelQueryError::Arrow(e.to_string()))?;
        Ok(vec![batch])
    }

    fn mongrel_query_plan_details(&self, sql: &str) -> Vec<String> {
        use sqlparser::ast::{GroupByExpr, OrderByKind, SetExpr, Statement};
        use sqlparser::dialect::PostgreSqlDialect;
        use sqlparser::parser::Parser;

        let Ok(stmts) = Parser::parse_sql(&PostgreSqlDialect {}, sql) else {
            return Vec::new();
        };
        let Some(Statement::Query(query)) = stmts.first() else {
            return Vec::new();
        };

        fn collect(session: &MongrelSession, query: &sqlparser::ast::Query, out: &mut Vec<String>) {
            use sqlparser::ast::{SetOperator, TableWithJoins};
            match query.body.as_ref() {
                SetExpr::Select(select) => {
                    for TableWithJoins { relation, joins } in &select.from {
                        session.push_table_plan(relation, select.selection.as_ref(), out);
                        for join in joins {
                            session.push_table_plan(&join.relation, None, out);
                        }
                    }
                    if select.distinct.is_some() {
                        out.push("USE TEMP B-TREE FOR DISTINCT".to_string());
                    }
                    let grouped = match &select.group_by {
                        GroupByExpr::All(_) => true,
                        GroupByExpr::Expressions(exprs, _) => !exprs.is_empty(),
                    };
                    if grouped {
                        out.push("USE TEMP B-TREE FOR GROUP BY".to_string());
                    }
                    let ordered = query.order_by.as_ref().is_some_and(|order_by| {
                        matches!(order_by.kind, OrderByKind::All(_))
                            || matches!(&order_by.kind, OrderByKind::Expressions(exprs) if !exprs.is_empty())
                    });
                    if ordered {
                        out.push("USE TEMP B-TREE FOR ORDER BY".to_string());
                    }
                }
                SetExpr::Query(query) => collect(session, query, out),
                SetExpr::SetOperation {
                    left, op, right, ..
                } => {
                    let label = match op {
                        SetOperator::Union => "COMPOUND QUERY UNION",
                        SetOperator::Except => "COMPOUND QUERY EXCEPT",
                        SetOperator::Intersect => "COMPOUND QUERY INTERSECT",
                        _ => "COMPOUND QUERY",
                    };
                    out.push(label.to_string());
                    collect_set_expr(session, left, out);
                    collect_set_expr(session, right, out);
                }
                _ => {}
            }
        }

        fn collect_set_expr(session: &MongrelSession, expr: &SetExpr, out: &mut Vec<String>) {
            match expr {
                SetExpr::Select(select) => {
                    for table in &select.from {
                        session.push_table_plan(&table.relation, select.selection.as_ref(), out);
                    }
                }
                SetExpr::Query(query) => collect(session, query, out),
                SetExpr::SetOperation { left, right, .. } => {
                    collect_set_expr(session, left, out);
                    collect_set_expr(session, right, out);
                }
                _ => {}
            }
        }

        let mut out = Vec::new();
        collect(self, query, &mut out);
        out
    }

    fn push_table_plan(
        &self,
        relation: &sqlparser::ast::TableFactor,
        selection: Option<&sqlparser::ast::Expr>,
        out: &mut Vec<String>,
    ) {
        let sqlparser::ast::TableFactor::Table { name, alias, .. } = relation else {
            out.push("SCAN SUBQUERY".to_string());
            return;
        };
        let table_name = name.to_string();
        let display_name = alias
            .as_ref()
            .map(|alias| alias.name.value.clone())
            .unwrap_or_else(|| table_name.clone());
        let Some(handle) = self.tables.lock().get(&table_name).cloned() else {
            out.push(format!("SCAN {display_name}"));
            return;
        };
        let schema = handle.lock().schema().clone();
        let searchable = selection
            .and_then(|expr| translate_sqlparser_filter(expr, &schema))
            .is_some_and(|conditions| !conditions.is_empty());
        if searchable {
            out.push(format!("SEARCH {display_name} USING MONGREL INDEX"));
        } else {
            out.push(format!("SCAN {display_name}"));
        }
    }

    /// A cache key epoch combining the primary table's epoch with every
    /// secondary table's, so any registered table's commit invalidates cached
    /// results (correctness for multi-table joins).
    /// Phase 17.3: rewrite `FROM <view_name>` to `FROM (<view_sql>) AS <view_name>`.
    fn resolve_view_sql(&self, sql: &str) -> String {
        let views = self.views.lock();
        if views.is_empty() {
            return sql.to_string();
        }
        let mut result = sql.to_string();
        for (name, view) in views.iter() {
            result = replace_from_view(&result, name, &view.sql);
        }
        result
    }

    fn rewrite_external_module_compat_sql(&self, sql: &str) -> String {
        let Some(db) = &self.database else {
            return sql.to_string();
        };
        rewrite_fts_match_compat_sql(sql, db)
    }

    fn query_references_external_module(&self, sql: &str) -> bool {
        use sqlparser::ast::Statement;
        use sqlparser::dialect::PostgreSqlDialect;
        use sqlparser::parser::Parser;

        Parser::parse_sql(&PostgreSqlDialect {}, sql)
            .ok()
            .is_some_and(|statements| {
                statements.iter().any(|statement| match statement {
                    Statement::Query(query) => self.query_uses_external_module(query),
                    _ => false,
                })
            })
    }

    fn query_uses_external_module(&self, query: &sqlparser::ast::Query) -> bool {
        self.set_expr_uses_external_module(query.body.as_ref())
    }

    fn set_expr_uses_external_module(&self, expr: &sqlparser::ast::SetExpr) -> bool {
        use sqlparser::ast::SetExpr;

        match expr {
            SetExpr::Select(select) => select
                .from
                .iter()
                .any(|table| self.table_with_joins_uses_external_module(table)),
            SetExpr::Query(query) => self.query_uses_external_module(query),
            SetExpr::SetOperation { left, right, .. } => {
                self.set_expr_uses_external_module(left)
                    || self.set_expr_uses_external_module(right)
            }
            _ => false,
        }
    }

    fn table_with_joins_uses_external_module(
        &self,
        table: &sqlparser::ast::TableWithJoins,
    ) -> bool {
        self.table_factor_uses_external_module(&table.relation)
            || table
                .joins
                .iter()
                .any(|join| self.table_factor_uses_external_module(&join.relation))
    }

    fn table_factor_uses_external_module(&self, relation: &sqlparser::ast::TableFactor) -> bool {
        use sqlparser::ast::{Expr, TableFactor};

        match relation {
            TableFactor::Table { name, args, .. } => {
                let table_name = name.to_string();
                self.database
                    .as_ref()
                    .is_some_and(|db| db.external_table(&table_name).is_some())
                    || (args.is_some() && self.external_modules.contains(&table_name))
            }
            TableFactor::Function { name, .. } => self.external_modules.contains(&name.to_string()),
            TableFactor::TableFunction {
                expr: Expr::Function(func),
                ..
            } => self.external_modules.contains(&func.name.to_string()),
            TableFactor::Derived { subquery, .. } => self.query_uses_external_module(subquery),
            _ => false,
        }
    }

    /// Cache epoch: uses `Database::visible_epoch()` when a Database is
    /// attached (P4.1), otherwise falls back to the legacy `combined_epoch()`.
    fn cache_epoch(&self) -> u64 {
        if let Some(db) = &self.database {
            db.visible_epoch().0
        } else {
            self.combined_epoch()
        }
    }

    fn combined_epoch(&self) -> u64 {
        let primary = self.db.as_ref().expect("no primary table");
        let mut combined = primary.lock().snapshot().epoch.0;
        let tables = self.tables.lock();
        for arc in tables.values() {
            if !Arc::ptr_eq(arc, primary) {
                let e = arc.lock().snapshot().epoch.0;
                combined = combined.wrapping_mul(31).wrapping_add(e);
            }
        }
        combined
    }

    /// Attempt the Phase 7.2/8.3 native aggregate fast path against `plan`.
    /// Returns `Ok(Some(batch))` when served natively, `Ok(None)` to fall
    /// through. `cache_key` ties the result to the incremental cache (Phase 8.3).
    fn try_native_aggregate(
        &self,
        plan: &datafusion::logical_expr::LogicalPlan,
        cache_key: u64,
    ) -> Result<Option<RecordBatch>> {
        let Some(primary) = self.db.as_ref() else {
            return Ok(None);
        };
        let mut db = primary.lock();
        let schema = db.schema().clone();
        let snap = db.snapshot();
        native_agg::try_native_aggregate(&mut db, &schema, snap, plan, cache_key)
    }

    /// Attempt the Phase 8.1 FK-join (bitmap-intersection) fast path against
    /// `plan`. Returns `Ok(Some(batches))` when served natively, `Ok(None)` to
    /// fall through to DataFusion.
    fn try_fk_join(
        &self,
        plan: &datafusion::logical_expr::LogicalPlan,
    ) -> Result<Option<Vec<RecordBatch>>> {
        let tables = self.tables.lock();
        fk_join::try_fk_join(&tables, plan)
    }

    pub fn context(&self) -> &SessionContext {
        &self.ctx
    }

    /// Register a custom scalar SQL function on this session.
    ///
    /// This is the Rust escape hatch for application-defined SQL functions. The
    /// session's plan and result caches are cleared because function resolution
    /// can change query output without advancing the storage epoch.
    pub fn register_scalar_udf(&self, f: ScalarUDF) {
        self.ctx.register_udf(f);
        self.clear_cache();
    }

    /// Register a custom aggregate SQL function on this session.
    pub fn register_aggregate_udf(&self, f: AggregateUDF) {
        self.ctx.register_udaf(f);
        self.clear_cache();
    }

    /// Register a custom window SQL function on this session.
    pub fn register_window_udf(&self, f: WindowUDF) {
        self.ctx.register_udwf(f);
        self.clear_cache();
    }
}

fn register_mongrel_functions(
    ctx: &SessionContext,
    sql_fn_state: Arc<extended_sql_functions::ExtendedSqlState>,
) {
    ctx.register_udf(ScalarUDF::from(udf::AnnSearchUdf::new()));
    ctx.register_udf(ScalarUDF::from(udf::SparseMatchUdf::new()));
    ctx.register_udf(ScalarUDF::from(udf::RTreeIntersectsUdf::new()));
    for udaf in percentile::percentile_udafs() {
        ctx.register_udaf(udaf);
    }
    extended_sql_functions::register_extended_sql_functions_with_state(ctx, sql_fn_state);
}

fn strip_explain_query_plan(sql: &str) -> Option<&str> {
    let trimmed = sql.trim_start();
    let lower = trimmed.to_ascii_lowercase();
    if !lower.starts_with("explain") {
        return None;
    }
    let after_explain = trimmed.get(7..)?.trim_start();
    let after_explain_lower = after_explain.to_ascii_lowercase();
    if !after_explain_lower.starts_with("query") {
        return None;
    }
    let after_query = after_explain.get(5..)?.trim_start();
    let after_query_lower = after_query.to_ascii_lowercase();
    if !after_query_lower.starts_with("plan") {
        return None;
    }
    Some(after_query.get(4..)?.trim_start())
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum SqlCompatTokenKind {
    Ident,
    String,
    Dot,
    LParen,
    RParen,
    Comma,
}

#[derive(Debug, Clone)]
struct SqlCompatToken {
    kind: SqlCompatTokenKind,
    raw: String,
    normalized: String,
    start: usize,
    end: usize,
}

#[derive(Debug, Clone)]
struct FtsMatchBinding {
    query_ref: String,
}

#[derive(Debug, Clone)]
struct SqlReplacement {
    start: usize,
    end: usize,
    replacement: String,
}

fn rewrite_fts_match_compat_sql(sql: &str, db: &Database) -> String {
    let tokens = sql_compat_tokens(sql);
    if tokens.is_empty() {
        return sql.to_string();
    }
    let bindings = fts_match_bindings(sql, db, &tokens);
    if bindings.is_empty() {
        return sql.to_string();
    }
    let unique_refs = bindings
        .values()
        .map(|binding| binding.query_ref.as_str())
        .collect::<HashSet<_>>();
    let unique_binding = if unique_refs.len() == 1 {
        bindings.values().next().cloned()
    } else {
        None
    };
    let mut replacements = Vec::new();
    for (idx, token) in tokens.iter().enumerate() {
        if token.kind != SqlCompatTokenKind::Ident || token.normalized != "match" {
            continue;
        }
        let Some(rhs) = tokens.get(idx + 1) else {
            continue;
        };
        if rhs.kind != SqlCompatTokenKind::String {
            continue;
        }
        let Some((lhs_start, _lhs_end, query_ref)) =
            fts_match_lhs_query_ref(&tokens, idx, &bindings, unique_binding.as_ref())
        else {
            continue;
        };
        replacements.push(SqlReplacement {
            start: lhs_start,
            end: rhs.end,
            replacement: format!("{query_ref}.query = {}", rhs.raw),
        });
    }
    apply_sql_replacements(sql, &replacements)
}

fn fts_match_lhs_query_ref(
    tokens: &[SqlCompatToken],
    match_idx: usize,
    bindings: &HashMap<String, FtsMatchBinding>,
    unique_binding: Option<&FtsMatchBinding>,
) -> Option<(usize, usize, String)> {
    if match_idx == 0 {
        return None;
    }
    let lhs = tokens.get(match_idx - 1)?;
    if lhs.kind != SqlCompatTokenKind::Ident {
        return None;
    }

    if match_idx >= 3
        && tokens.get(match_idx - 2)?.kind == SqlCompatTokenKind::Dot
        && tokens.get(match_idx - 3)?.kind == SqlCompatTokenKind::Ident
    {
        let owner = tokens.get(match_idx - 3)?;
        let binding = bindings.get(&owner.normalized)?;
        if lhs.normalized == "query" || lhs.normalized == "text" {
            return Some((owner.start, lhs.end, binding.query_ref.clone()));
        }
        return None;
    }

    if let Some(binding) = bindings.get(&lhs.normalized) {
        return Some((lhs.start, lhs.end, binding.query_ref.clone()));
    }
    if lhs.normalized == "text" {
        let binding = unique_binding?;
        return Some((lhs.start, lhs.end, binding.query_ref.clone()));
    }
    None
}

fn fts_match_bindings(
    sql: &str,
    db: &Database,
    tokens: &[SqlCompatToken],
) -> HashMap<String, FtsMatchBinding> {
    let mut out = HashMap::new();
    let mut i = 0;
    while i < tokens.len() {
        let token = &tokens[i];
        let starts_table_ref = token.kind == SqlCompatTokenKind::Ident
            && matches!(token.normalized.as_str(), "from" | "join");
        if !starts_table_ref {
            i += 1;
            continue;
        }
        let mut table_idx = i + 1;
        if tokens
            .get(table_idx)
            .is_some_and(|token| token.kind == SqlCompatTokenKind::LParen)
        {
            i += 1;
            continue;
        }
        let Some(table) = tokens.get(table_idx) else {
            break;
        };
        if table.kind != SqlCompatTokenKind::Ident {
            i += 1;
            continue;
        }
        let mut table_name = table.normalized.clone();
        let mut table_ref = table.raw.clone();
        if tokens
            .get(table_idx + 1)
            .is_some_and(|token| token.kind == SqlCompatTokenKind::Dot)
            && tokens
                .get(table_idx + 2)
                .is_some_and(|token| token.kind == SqlCompatTokenKind::Ident)
        {
            let qualified = tokens.get(table_idx + 2).unwrap();
            table_name = qualified.normalized.clone();
            table_ref = sql[table.start..qualified.end].to_string();
            table_idx += 2;
        }
        if !is_fts_docs_table(db, &table_name) {
            i = table_idx + 1;
            continue;
        }
        let mut query_ref = table_ref.clone();
        let mut alias_key = None;
        let mut next = table_idx + 1;
        if tokens.get(next).is_some_and(|token| {
            token.kind == SqlCompatTokenKind::Ident && token.normalized == "as"
        }) {
            next += 1;
        }
        if let Some(alias) = tokens.get(next) {
            if alias.kind == SqlCompatTokenKind::Ident && !is_table_ref_boundary(&alias.normalized)
            {
                alias_key = Some(alias.normalized.clone());
                query_ref = alias.raw.clone();
                next += 1;
            }
        }
        out.insert(
            table_name,
            FtsMatchBinding {
                query_ref: query_ref.clone(),
            },
        );
        if let Some(alias_key) = alias_key {
            out.insert(alias_key, FtsMatchBinding { query_ref });
        }
        i = next;
    }
    out
}

fn is_fts_docs_table(db: &Database, name: &str) -> bool {
    db.external_table(name)
        .is_some_and(|entry| entry.module == "fts_docs")
}

fn is_table_ref_boundary(normalized: &str) -> bool {
    matches!(
        normalized,
        "where"
            | "join"
            | "left"
            | "right"
            | "inner"
            | "outer"
            | "full"
            | "cross"
            | "on"
            | "using"
            | "group"
            | "order"
            | "having"
            | "limit"
            | "offset"
            | "union"
            | "except"
            | "intersect"
    )
}

fn sql_compat_tokens(sql: &str) -> Vec<SqlCompatToken> {
    let bytes = sql.as_bytes();
    let mut tokens = Vec::new();
    let mut i = 0;
    while i < bytes.len() {
        match bytes[i] {
            b if b.is_ascii_whitespace() => i += 1,
            b'-' if i + 1 < bytes.len() && bytes[i + 1] == b'-' => {
                i += 2;
                while i < bytes.len() && bytes[i] != b'\n' {
                    i += 1;
                }
            }
            b'/' if i + 1 < bytes.len() && bytes[i + 1] == b'*' => {
                i = skip_block_comment(bytes, i);
            }
            b'\'' => {
                let end = skip_quoted(bytes, i, b'\'');
                tokens.push(sql_token(sql, SqlCompatTokenKind::String, i, end));
                i = end;
            }
            b'E' | b'e' if i + 1 < bytes.len() && bytes[i + 1] == b'\'' => {
                let end = skip_quoted(bytes, i + 1, b'\'');
                tokens.push(sql_token(sql, SqlCompatTokenKind::String, i, end));
                i = end;
            }
            b'$' => {
                let (end, matched) = skip_dollar_quoted(bytes, i);
                if matched {
                    tokens.push(sql_token(sql, SqlCompatTokenKind::String, i, end));
                    i = end;
                } else {
                    i += 1;
                }
            }
            b'"' => {
                let end = skip_quoted(bytes, i, b'"');
                let raw = sql[i..end].to_string();
                let normalized = unquote_sql_ident(&raw).to_ascii_lowercase();
                tokens.push(SqlCompatToken {
                    kind: SqlCompatTokenKind::Ident,
                    raw,
                    normalized,
                    start: i,
                    end,
                });
                i = end;
            }
            b'.' => {
                tokens.push(sql_token(sql, SqlCompatTokenKind::Dot, i, i + 1));
                i += 1;
            }
            b'(' => {
                tokens.push(sql_token(sql, SqlCompatTokenKind::LParen, i, i + 1));
                i += 1;
            }
            b')' => {
                tokens.push(sql_token(sql, SqlCompatTokenKind::RParen, i, i + 1));
                i += 1;
            }
            b',' => {
                tokens.push(sql_token(sql, SqlCompatTokenKind::Comma, i, i + 1));
                i += 1;
            }
            b if is_sql_ident_byte(b) => {
                let start = i;
                i += 1;
                while i < bytes.len() && is_sql_ident_byte(bytes[i]) {
                    i += 1;
                }
                tokens.push(sql_token(sql, SqlCompatTokenKind::Ident, start, i));
            }
            _ => i += 1,
        }
    }
    tokens
}

fn sql_token(sql: &str, kind: SqlCompatTokenKind, start: usize, end: usize) -> SqlCompatToken {
    let raw = sql[start..end].to_string();
    SqlCompatToken {
        kind,
        normalized: raw.to_ascii_lowercase(),
        raw,
        start,
        end,
    }
}

fn unquote_sql_ident(raw: &str) -> String {
    if raw.len() >= 2 && raw.starts_with('"') && raw.ends_with('"') {
        raw[1..raw.len() - 1].replace("\"\"", "\"")
    } else {
        raw.to_string()
    }
}

fn apply_sql_replacements(sql: &str, replacements: &[SqlReplacement]) -> String {
    if replacements.is_empty() {
        return sql.to_string();
    }
    let mut ordered = replacements.to_vec();
    ordered.sort_by_key(|replacement| replacement.start);
    let mut out = String::with_capacity(sql.len());
    let mut cursor = 0;
    for replacement in ordered {
        if replacement.start < cursor || replacement.end > sql.len() {
            continue;
        }
        out.push_str(&sql[cursor..replacement.start]);
        out.push_str(&replacement.replacement);
        cursor = replacement.end;
    }
    out.push_str(&sql[cursor..]);
    out
}

fn rewrite_compat_function_calls(sql: &str) -> String {
    let bytes = sql.as_bytes();
    let mut out = String::with_capacity(sql.len());
    let mut i = 0;
    while i < bytes.len() {
        match bytes[i] {
            b'\'' => i = copy_quoted_to_string(&mut out, bytes, i, b'\''),
            b'"' => i = copy_quoted_to_string(&mut out, bytes, i, b'"'),
            b'E' | b'e' if i + 1 < bytes.len() && bytes[i + 1] == b'\'' => {
                out.push(bytes[i] as char);
                i += 1;
                i = copy_quoted_to_string(&mut out, bytes, i, b'\'');
            }
            b'-' if i + 1 < bytes.len() && bytes[i + 1] == b'-' => {
                out.push('-');
                out.push('-');
                i += 2;
                while i < bytes.len() {
                    let ch = bytes[i] as char;
                    out.push(ch);
                    i += 1;
                    if ch == '\n' {
                        break;
                    }
                }
            }
            b'/' if i + 1 < bytes.len() && bytes[i + 1] == b'*' => {
                let start = i;
                i = skip_block_comment(bytes, i);
                out.push_str(&sql[start..i.min(bytes.len())]);
            }
            b'$' => {
                let start_len = out.len();
                let (next, matched) = copy_dollar_quoted_to_string(&mut out, bytes, i);
                if matched {
                    i = next;
                } else {
                    out.truncate(start_len);
                    out.push('$');
                    i += 1;
                }
            }
            b'g' | b'G' | b'm' | b'M' | b't' | b'T' => {
                if let Some((replacement, next)) = compat_function_rewrite_at(sql, i) {
                    out.push_str(&replacement);
                    i = next;
                } else {
                    out.push(bytes[i] as char);
                    i += 1;
                }
            }
            _ => {
                out.push(bytes[i] as char);
                i += 1;
            }
        }
    }
    out
}

fn compat_function_rewrite_at(sql: &str, start: usize) -> Option<(String, usize)> {
    let bytes = sql.as_bytes();
    let (name, kind) = if ident_eq_at(bytes, start, b"max") {
        ("max", CompatRewriteKind::ScalarMax)
    } else if ident_eq_at(bytes, start, b"min") {
        ("min", CompatRewriteKind::ScalarMin)
    } else if ident_eq_at(bytes, start, b"group_concat") {
        ("group_concat", CompatRewriteKind::GroupConcat)
    } else if ident_eq_at(bytes, start, b"total") {
        ("total", CompatRewriteKind::Total)
    } else {
        return None;
    };
    let before_ok = start == 0 || !is_sql_ident_byte(bytes[start - 1]);
    let after_name = start + name.len();
    let after_ok = bytes
        .get(after_name)
        .is_some_and(|b| !is_sql_ident_byte(*b));
    if !before_ok || !after_ok {
        return None;
    }
    let mut open = after_name;
    while open < bytes.len() && bytes[open].is_ascii_whitespace() {
        open += 1;
    }
    if bytes.get(open) != Some(&b'(') {
        return None;
    }
    let summary = call_arg_summary(sql, open)?;
    match kind {
        CompatRewriteKind::ScalarMax if summary.top_level_commas > 0 => {
            Some(("__mongreldb_scalar_max(".to_string(), open + 1))
        }
        CompatRewriteKind::ScalarMin if summary.top_level_commas > 0 => {
            Some(("__mongreldb_scalar_min(".to_string(), open + 1))
        }
        CompatRewriteKind::GroupConcat => {
            let args = &sql[open + 1..summary.close];
            let rewritten = if summary.top_level_commas == 0 {
                format!("string_agg({args}, ',')")
            } else {
                format!("string_agg({args})")
            };
            Some((rewritten, summary.close + 1))
        }
        CompatRewriteKind::Total if summary.top_level_commas == 0 => {
            let args = &sql[open + 1..summary.close];
            let suffix_end = aggregate_suffix_end(sql, summary.close + 1);
            let suffix = &sql[summary.close + 1..suffix_end];
            Some((
                format!("coalesce(cast(sum({args}){suffix} as double), 0.0)"),
                suffix_end,
            ))
        }
        _ => None,
    }
}

#[derive(Clone, Copy)]
enum CompatRewriteKind {
    ScalarMax,
    ScalarMin,
    GroupConcat,
    Total,
}

fn ident_eq_at(bytes: &[u8], start: usize, ident: &[u8]) -> bool {
    bytes
        .get(start..start + ident.len())
        .is_some_and(|slice| slice.eq_ignore_ascii_case(ident))
}

fn is_sql_ident_byte(b: u8) -> bool {
    b.is_ascii_alphanumeric() || b == b'_' || b == b'$'
}

fn keyword_at(bytes: &[u8], start: usize, keyword: &[u8]) -> bool {
    if !ident_eq_at(bytes, start, keyword) {
        return false;
    }
    let before_ok = start == 0 || !is_sql_ident_byte(bytes[start - 1]);
    let after = start + keyword.len();
    let after_ok = after >= bytes.len() || !is_sql_ident_byte(bytes[after]);
    before_ok && after_ok
}

fn skip_sql_whitespace(bytes: &[u8], mut i: usize) -> usize {
    while i < bytes.len() && bytes[i].is_ascii_whitespace() {
        i += 1;
    }
    i
}

fn aggregate_suffix_end(sql: &str, start: usize) -> usize {
    let bytes = sql.as_bytes();
    let mut suffix_end = start;
    let mut i = skip_sql_whitespace(bytes, start);

    if keyword_at(bytes, i, b"filter") {
        let open = skip_sql_whitespace(bytes, i + b"filter".len());
        if bytes.get(open) != Some(&b'(') {
            return start;
        }
        let Some(summary) = call_arg_summary(sql, open) else {
            return start;
        };
        suffix_end = summary.close + 1;
        i = skip_sql_whitespace(bytes, suffix_end);
    }

    if keyword_at(bytes, i, b"over") {
        let after_over = skip_sql_whitespace(bytes, i + b"over".len());
        if bytes.get(after_over) == Some(&b'(') {
            let Some(summary) = call_arg_summary(sql, after_over) else {
                return suffix_end;
            };
            suffix_end = summary.close + 1;
        } else {
            let mut end = after_over;
            while end < bytes.len() && is_sql_ident_byte(bytes[end]) {
                end += 1;
            }
            if end > after_over {
                suffix_end = end;
            }
        }
    }

    suffix_end
}

struct CallArgSummary {
    close: usize,
    top_level_commas: usize,
}

fn call_arg_summary(sql: &str, open: usize) -> Option<CallArgSummary> {
    let bytes = sql.as_bytes();
    let mut depth = 1;
    let mut i = open + 1;
    let mut top_level_commas = 0;
    while i < bytes.len() {
        match bytes[i] {
            b'\'' => i = skip_quoted(bytes, i, b'\''),
            b'"' => i = skip_quoted(bytes, i, b'"'),
            b'E' | b'e' if i + 1 < bytes.len() && bytes[i + 1] == b'\'' => {
                i = skip_quoted(bytes, i + 1, b'\'')
            }
            b'$' => {
                let (next, matched) = skip_dollar_quoted(bytes, i);
                i = if matched { next } else { i + 1 };
            }
            b'-' if i + 1 < bytes.len() && bytes[i + 1] == b'-' => {
                i += 2;
                while i < bytes.len() && bytes[i] != b'\n' {
                    i += 1;
                }
            }
            b'/' if i + 1 < bytes.len() && bytes[i + 1] == b'*' => {
                i = skip_block_comment(bytes, i);
            }
            b'(' => {
                depth += 1;
                i += 1;
            }
            b')' => {
                depth -= 1;
                if depth == 0 {
                    return Some(CallArgSummary {
                        close: i,
                        top_level_commas,
                    });
                }
                i += 1;
            }
            b',' if depth == 1 => {
                top_level_commas += 1;
                i += 1;
            }
            _ => i += 1,
        }
    }
    None
}

fn copy_quoted_to_string(out: &mut String, bytes: &[u8], start: usize, delim: u8) -> usize {
    let end = skip_quoted(bytes, start, delim);
    out.push_str(std::str::from_utf8(&bytes[start..end]).unwrap_or_default());
    end
}

fn skip_quoted(bytes: &[u8], start: usize, delim: u8) -> usize {
    let mut i = start;
    if i < bytes.len() {
        i += 1;
    }
    while i < bytes.len() {
        if bytes[i] == delim {
            i += 1;
            if i < bytes.len() && bytes[i] == delim {
                i += 1;
                continue;
            }
            break;
        }
        i += 1;
    }
    i
}

fn copy_dollar_quoted_to_string(out: &mut String, bytes: &[u8], start: usize) -> (usize, bool) {
    let (end, matched) = skip_dollar_quoted(bytes, start);
    if matched {
        out.push_str(std::str::from_utf8(&bytes[start..end]).unwrap_or_default());
    }
    (end, matched)
}

fn skip_dollar_quoted(bytes: &[u8], start: usize) -> (usize, bool) {
    if bytes.get(start) != Some(&b'$') {
        return (start, false);
    }
    let mut j = start + 1;
    while j < bytes.len() && (bytes[j].is_ascii_alphanumeric() || bytes[j] == b'_') {
        j += 1;
    }
    if bytes.get(j) != Some(&b'$') {
        return (start, false);
    }
    let tag = &bytes[start..=j];
    let mut i = j + 1;
    while i + tag.len() <= bytes.len() {
        if &bytes[i..i + tag.len()] == tag {
            return (i + tag.len(), true);
        }
        i += 1;
    }
    (start, false)
}

fn skip_block_comment(bytes: &[u8], start: usize) -> usize {
    let mut i = start + 2;
    let mut depth = 1;
    while i + 1 < bytes.len() && depth > 0 {
        if bytes[i] == b'/' && bytes[i + 1] == b'*' {
            depth += 1;
            i += 2;
        } else if bytes[i] == b'*' && bytes[i + 1] == b'/' {
            depth -= 1;
            i += 2;
        } else {
            i += 1;
        }
    }
    i
}

/// Stable 64-bit cache key for a SQL string (Phase 8.3 incremental cache).
fn sql_cache_key(sql: &str) -> u64 {
    use std::hash::{Hash, Hasher};
    let mut h = std::collections::hash_map::DefaultHasher::new();
    sql.hash(&mut h);
    h.finish()
}

/// Replace the first whole-word `FROM <name>` reference (case-insensitive) in
/// `sql` with `FROM (<view_sql>) AS <name>`. Unlike a raw substring search this
/// requires a word boundary on both sides, so a view named `log` will **not**
/// rewrite `FROM logs` (the prior behavior matched the `from log` prefix and
/// left a dangling `s`). Original (non-lowercased) casing is preserved outside
/// the rewritten span.
fn replace_from_view(sql: &str, name: &str, view_sql: &str) -> String {
    let lower = sql.to_ascii_lowercase();
    let bytes = lower.as_bytes();
    let name_b = name.as_bytes();
    let mut i = 0usize;
    while let Some(rel) = lower[i..].find("from") {
        let from_start = i + rel;
        let after_from = from_start + 4;
        i = after_from;
        // Left boundary: "from" must not be a suffix of a longer identifier.
        if from_start > 0 && is_ident_byte(bytes[from_start - 1]) {
            continue;
        }
        // Must be followed by whitespace then the name.
        let mut j = after_from;
        while j < bytes.len() && bytes[j].is_ascii_whitespace() {
            j += 1;
        }
        if j == after_from || !bytes[j..].starts_with(name_b) {
            continue;
        }
        let after_name = j + name_b.len();
        // Right boundary: the name must not be a prefix of a longer identifier.
        if after_name < bytes.len() && is_ident_byte(bytes[after_name]) {
            continue;
        }
        // Preserve the original `FROM ` casing/whitespace (sql[from_start..j]),
        // then wrap the view body as a subquery aliased back to the view name.
        let mut out = String::with_capacity(sql.len() + view_sql.len() + name.len() + 8);
        out.push_str(&sql[..from_start]);
        out.push_str(&sql[from_start..j]);
        out.push('(');
        out.push_str(view_sql);
        out.push_str(") AS ");
        out.push_str(name);
        out.push_str(&sql[after_name..]);
        return out;
    }
    sql.to_string()
}

fn is_ident_byte(b: u8) -> bool {
    b.is_ascii_alphanumeric() || b == b'_'
}

/// Canonicalize a SQL string for caching/parsing: collapse runs of ASCII
/// whitespace outside of literals/comments to a single space and trim. String
/// literals (`'...'`, with `''` escapes), quoted identifiers (`"..."`), escape
/// strings (`E'...'`), line comments (`--`), block comments (`/* */`), and
/// dollar-quoting (`$tag$...$tag$`) are passed through verbatim so their
/// internal whitespace (which IS semantically significant) is never altered.
/// SQL parsing is whitespace-insensitive outside literals, so the normalized
/// form parses identically while making `SELECT  *  FROM t`, `SELECT * FROM t`,
/// and `\n  SELECT * FROM t  \n` share one cache key.
fn normalize_sql(sql: &str) -> String {
    let b = sql.as_bytes();
    let n = b.len();
    let mut out: Vec<u8> = Vec::with_capacity(n);
    // Whether a single separating space should precede the next emitted token
    // (i.e. we're between tokens, not at the very start of the output).
    let mut want_space = false;
    let mut i = 0usize;
    while i < n {
        let c = b[i];
        // Whitespace and comments both act only as token separators — they set
        // the pending-space flag but never emit a byte themselves, so a run of
        // "1  -- c\nFROM" collapses to a single separating space.
        if c.is_ascii_whitespace() {
            want_space = true;
            i += 1;
            continue;
        }
        if c == b'-' && i + 1 < n && b[i + 1] == b'-' {
            // Line comment: skip to end of line.
            i += 2;
            while i < n && b[i] != b'\n' {
                i += 1;
            }
            want_space = !out.is_empty();
            continue;
        }
        if c == b'/' && i + 1 < n && b[i + 1] == b'*' {
            // Block comment: skip to the matching close `*/`, honoring nesting
            // (Postgres/DataFusion allow `/* /* */ */`).
            i += 2;
            let mut depth = 1usize;
            while i + 1 < n && depth > 0 {
                if b[i] == b'/' && b[i + 1] == b'*' {
                    depth += 1;
                    i += 2;
                } else if b[i] == b'*' && b[i + 1] == b'/' {
                    depth -= 1;
                    i += 2;
                } else {
                    i += 1;
                }
            }
            want_space = !out.is_empty();
            continue;
        }
        // A real token byte (or a literal/quote opener) — emit the separator.
        if want_space && !out.is_empty() {
            out.push(b' ');
        }
        want_space = false;
        match c {
            // Escape string E'...' (backslash escapes; '' is still an escape).
            b'E' | b'e' if i + 1 < n && b[i + 1] == b'\'' => {
                out.push(c);
                i += 1;
                i = copy_quoted(&mut out, b, i, n, b'\'');
                continue;
            }
            // Single-quoted string literal ('...' with '' escape).
            b'\'' => {
                i = copy_quoted(&mut out, b, i, n, b'\'');
                continue;
            }
            // Double-quoted identifier ("..." with "" escape).
            b'"' => {
                i = copy_quoted(&mut out, b, i, n, b'"');
                continue;
            }
            // Dollar-quoting: $tag$ ... $tag$ (tag optional/empty).
            b'$' => {
                let (consumed, matched) = copy_dollar_quoted(&mut out, b, i, n);
                if matched {
                    i = consumed;
                    continue;
                }
                out.push(c);
                i += 1;
                continue;
            }
            _ => {
                out.push(c);
                i += 1;
            }
        }
    }
    String::from_utf8(out).unwrap_or_else(|_| sql.to_string())
}

/// Copy a quote-delimited span starting at `start` (the opening quote byte is
/// `delim`), including the opening and closing delimiters and any doubled
/// escapes, verbatim into `out`. Returns the index past the closing quote.
fn copy_quoted(out: &mut Vec<u8>, b: &[u8], start: usize, n: usize, delim: u8) -> usize {
    out.push(b[start]);
    let mut i = start + 1;
    while i < n {
        let c = b[i];
        out.push(c);
        if c == delim {
            // Doubled delimiter (e.g. '' or "") is an escape, not the end.
            if i + 1 < n && b[i + 1] == delim {
                out.push(b[i + 1]);
                i += 2;
                continue;
            }
            return i + 1;
        }
        i += 1;
    }
    i
}

/// Copy a dollar-quoted span starting at the opening `$`. Returns
/// `(index_past_close, true)` if a matching close delimiter was found, or
/// `(start + 1, false)` if this `$` does not open a dollar-quote.
fn copy_dollar_quoted(out: &mut Vec<u8>, b: &[u8], start: usize, n: usize) -> (usize, bool) {
    // Parse the opening delimiter: '$' [tag] '$'. An empty tag ($$..$$) is
    // allowed; a non-empty tag must be identifier bytes starting with a
    // letter/underscore.
    let mut j = start + 1;
    let tag_start = j;
    while j < n && b[j] != b'$' && is_dollar_tag_byte(b[j]) {
        j += 1;
    }
    if j >= n || b[j] != b'$' {
        return (start + 1, false);
    }
    if tag_start < j && !(b[tag_start].is_ascii_alphabetic() || b[tag_start] == b'_') {
        return (start + 1, false);
    }
    let close_end = j + 1; // index just past the opening '$'
    let delim = &b[start..close_end];
    // Copy the opening delimiter verbatim.
    out.extend_from_slice(delim);
    // Find the matching close delimiter.
    let mut k = close_end;
    while k + delim.len() <= n {
        if &b[k..k + delim.len()] == delim {
            out.extend_from_slice(delim);
            return (k + delim.len(), true);
        }
        out.push(b[k]);
        k += 1;
    }
    // Unterminated: copy the remainder verbatim (don't corrupt).
    out.extend_from_slice(&b[close_end..n]);
    (n, true)
}

fn is_dollar_tag_byte(b: u8) -> bool {
    b.is_ascii_alphanumeric() || b == b'_'
}

/// Strip an ASCII case-insensitive prefix from `s`, returning the remainder.
fn strip_prefix_ci<'a>(s: &'a str, prefix: &str) -> Option<&'a str> {
    let bytes = s.as_bytes();
    let pb = prefix.as_bytes();
    if bytes.len() >= pb.len() && bytes[..pb.len()].eq_ignore_ascii_case(pb) {
        Some(&s[pb.len()..])
    } else {
        None
    }
}

/// Recognized column constraints in `CREATE TABLE` column definitions. Each
/// entry maps a SQL phrase (matched case-insensitively as a substring of the
/// whitespace-normalized constraint clause) to the [`ColumnFlags`] bit it sets.
///
/// Multi-word phrases such as `"primary key"` match regardless of internal
/// spacing because the clause is normalized to single spaces before matching.
///
/// **Adding a new column constraint is a one-line change:** append `(phrase,
/// flag)` here. This keeps the DDL shim's grammar in one place rather than
/// scattering `contains(...)` checks across the parser. (A full SQL grammar is
/// deliberately out of scope — only the DDL shapes handled below are
/// intercepted here; all query parsing is delegated to DataFusion.)
const COLUMN_CONSTRAINTS: &[(&str, u32)] = &[
    ("primary key", ColumnFlags::PRIMARY_KEY),
    // Both spellings are accepted: `AUTOINCREMENT` (SQLite) and `AUTO_INCREMENT`
    // (MySQL). The engine enforces that the flag is valid only on a single
    // non-nullable `Int64` primary key (see `Schema::validate_auto_increment`),
    // so recognizing the keyword on any column here is safe — invalid
    // placements are rejected at table-creation time, before the schema is
    // durably logged.
    ("autoincrement", ColumnFlags::AUTO_INCREMENT),
    ("auto_increment", ColumnFlags::AUTO_INCREMENT),
];

/// Translate a column's constraint clause (the text following `<name> <type>`
/// in a `CREATE TABLE` column definition) into [`ColumnFlags`]. The clause is
/// lowercased and its internal whitespace collapsed to single spaces so
/// multi-word phrases match regardless of formatting. See
/// [`COLUMN_CONSTRAINTS`] for the recognized phrases; add new ones there.
fn parse_column_constraints(constraint_text: &str) -> ColumnFlags {
    let normalized = constraint_text.to_lowercase();
    let mut flags = ColumnFlags::empty();
    for (phrase, bit) in COLUMN_CONSTRAINTS {
        if normalized.contains(phrase) {
            flags = flags.with(*bit);
        }
    }
    flags
}

fn parse_sql_type(ty_str: &str) -> Result<mongreldb_core::schema::TypeId> {
    use mongreldb_core::schema::TypeId;

    match ty_str.trim().trim_end_matches(';').to_lowercase().as_str() {
        "bigint" | "int8" | "int64" | "integer" | "int" => Ok(TypeId::Int64),
        "double" | "float8" | "float64" | "real" | "float" => Ok(TypeId::Float64),
        "varchar" | "text" | "string" | "bytes" => Ok(TypeId::Bytes),
        "boolean" | "bool" => Ok(TypeId::Bool),
        other => Err(MongrelQueryError::Schema(format!(
            "unsupported column type: {other}"
        ))),
    }
}

/// Parse `CREATE TABLE [IF NOT EXISTS] <name> (<col> <type> <constraints>, ...)`
/// into a MongrelDB table name + schema. Supports BIGINT/INTEGER/INT, DOUBLE,
/// VARCHAR/TEXT, BOOLEAN. Recognized column constraints (`PRIMARY KEY`,
/// `AUTOINCREMENT` / `AUTO_INCREMENT`) are listed in [`COLUMN_CONSTRAINTS`].
/// Table name may be double-quoted.
fn parse_create_table(sql: &str) -> Result<(String, mongreldb_core::schema::Schema)> {
    use mongreldb_core::schema::*;

    let open = sql
        .find('(')
        .ok_or(MongrelQueryError::Schema("CREATE TABLE missing '('".into()))?;
    let close = sql
        .rfind(')')
        .ok_or(MongrelQueryError::Schema("CREATE TABLE missing ')'".into()))?;
    let head = sql[..open].trim();
    let after_kw = strip_prefix_ci(head, "CREATE TABLE")
        .or_else(|| strip_prefix_ci(head, "create table"))
        .unwrap_or("")
        .trim();
    // Skip optional `IF NOT EXISTS`.
    let after_kw = after_kw
        .strip_prefix("IF NOT EXISTS")
        .or_else(|| after_kw.strip_prefix("if not exists"))
        .map(str::trim)
        .unwrap_or(after_kw);
    let name = after_kw.trim_matches('"').to_string();
    if name.is_empty() {
        return Err(MongrelQueryError::Schema(
            "CREATE TABLE missing table name".into(),
        ));
    }

    let body = &sql[open + 1..close];
    let mut columns = Vec::new();
    let schema_id: u64 = 0; // Database::create_table overrides with the table_id.
    for (i, raw) in body.split(',').enumerate() {
        let part = raw.trim();
        if part.is_empty() {
            continue;
        }
        let mut tokens = part.split_whitespace();
        let col_name = tokens
            .next()
            .ok_or(MongrelQueryError::Schema("missing column name".into()))?
            .trim_matches('"');
        let ty_str = tokens
            .next()
            .ok_or(MongrelQueryError::Schema("missing column type".into()))?
            .to_lowercase();
        let ty = parse_sql_type(&ty_str)?;
        // Everything after `<name> <type>` is the column's constraint clause
        // (e.g. `PRIMARY KEY`, `PRIMARY KEY AUTOINCREMENT`). The remaining
        // tokens are matched against `COLUMN_CONSTRAINTS`.
        let constraint_clause: String = tokens.collect::<Vec<_>>().join(" ");
        let flags = parse_column_constraints(&constraint_clause);
        columns.push(ColumnDef {
            id: (i + 1) as u16,
            name: col_name.to_string(),
            ty,
            flags,
        });
    }

    Ok((
        name,
        Schema {
            schema_id,
            columns,
            indexes: vec![],
            colocation: vec![],
            constraints: Default::default(),
            clustered: false,
        },
    ))
}

/// Parse `DROP TABLE [IF EXISTS] <name>`. Returns `(name, if_exists)`.
fn parse_drop_table(sql: &str) -> Result<(String, bool)> {
    let head = sql.trim();
    let after_kw = strip_prefix_ci(head, "DROP TABLE")
        .or_else(|| strip_prefix_ci(head, "drop table"))
        .unwrap_or("")
        .trim();
    // Detect optional `IF EXISTS`.
    let (rest, if_exists) = if let Some(r) = after_kw
        .strip_prefix("IF EXISTS")
        .or_else(|| after_kw.strip_prefix("if exists"))
        .map(str::trim)
    {
        (r, true)
    } else {
        (after_kw, false)
    };
    let name = rest.trim_matches(';').trim_matches('"').trim();
    if name.is_empty() {
        return Err(MongrelQueryError::Schema(
            "DROP TABLE missing table name".into(),
        ));
    }
    Ok((name.to_string(), if_exists))
}

enum ParsedAlterTable {
    RenameTable {
        old_name: String,
        new_name: String,
    },
    RenameColumn {
        table_name: String,
        column_name: String,
        new_name: String,
    },
    AlterColumnType {
        table_name: String,
        column_name: String,
        ty: mongreldb_core::schema::TypeId,
    },
    SetNotNull {
        table_name: String,
        column_name: String,
    },
    DropNotNull {
        table_name: String,
        column_name: String,
    },
}

fn current_column_flags(db: &Arc<Database>, table: &str, column: &str) -> Result<ColumnFlags> {
    let handle = db.table(table)?;
    let table = handle.lock();
    table
        .schema()
        .column(column)
        .map(|c| c.flags)
        .ok_or_else(|| MongrelQueryError::Schema(format!("unknown column {column}")))
}

fn parse_alter_table(sql: &str) -> Result<ParsedAlterTable> {
    let trimmed = strip_statement_semicolon(sql.trim());
    let after_kw = strip_prefix_ci(trimmed, "ALTER TABLE")
        .ok_or_else(|| MongrelQueryError::Schema("not an ALTER TABLE statement".into()))?
        .trim();
    let (table_name, rest) = take_sql_ident(after_kw, "ALTER TABLE missing table name")?;
    let rest = rest.trim();

    if let Some(after) = strip_prefix_ci(rest, "RENAME TO") {
        let new_name = parse_trailing_identifier(after, "ALTER TABLE missing new table name")?;
        return Ok(ParsedAlterTable::RenameTable {
            old_name: table_name,
            new_name,
        });
    }

    if let Some(after) = strip_prefix_ci(rest, "RENAME COLUMN") {
        let (column_name, after_col) =
            take_sql_ident(after, "ALTER TABLE RENAME COLUMN missing column name")?;
        let after_to = strip_prefix_ci(after_col.trim(), "TO").ok_or_else(|| {
            MongrelQueryError::Schema("ALTER TABLE RENAME COLUMN missing TO".into())
        })?;
        let new_name = parse_trailing_identifier(
            after_to,
            "ALTER TABLE RENAME COLUMN missing new column name",
        )?;
        return Ok(ParsedAlterTable::RenameColumn {
            table_name,
            column_name,
            new_name,
        });
    }

    let after_alter = strip_prefix_ci(rest, "ALTER COLUMN")
        .or_else(|| strip_prefix_ci(rest, "ALTER"))
        .ok_or_else(|| {
            MongrelQueryError::Schema(
                "ALTER TABLE must be RENAME TO, RENAME COLUMN, or ALTER COLUMN".into(),
            )
        })?;
    let (column_name, action) =
        take_sql_ident(after_alter, "ALTER TABLE ALTER COLUMN missing column name")?;
    let action = action.trim();

    if let Some(after_type) =
        strip_prefix_ci(action, "TYPE").or_else(|| strip_prefix_ci(action, "SET DATA TYPE"))
    {
        let ty = parse_type_tail(after_type)?;
        return Ok(ParsedAlterTable::AlterColumnType {
            table_name,
            column_name,
            ty,
        });
    }
    if strip_prefix_ci(action, "SET NOT NULL").is_some() {
        return Ok(ParsedAlterTable::SetNotNull {
            table_name,
            column_name,
        });
    }
    if strip_prefix_ci(action, "DROP NOT NULL").is_some() {
        return Ok(ParsedAlterTable::DropNotNull {
            table_name,
            column_name,
        });
    }

    Err(MongrelQueryError::Schema(
        "unsupported ALTER COLUMN action".into(),
    ))
}

fn strip_statement_semicolon(s: &str) -> &str {
    s.trim().trim_end_matches(';').trim()
}

fn take_sql_ident<'a>(s: &'a str, missing: &str) -> Result<(String, &'a str)> {
    let s = s.trim();
    if s.is_empty() {
        return Err(MongrelQueryError::Schema(missing.into()));
    }
    if let Some(rest) = s.strip_prefix('"') {
        let Some(end) = rest.find('"') else {
            return Err(MongrelQueryError::Schema(
                "unterminated quoted identifier".into(),
            ));
        };
        let ident = rest[..end].to_string();
        if ident.is_empty() {
            return Err(MongrelQueryError::Schema(missing.into()));
        }
        return Ok((ident, &rest[end + 1..]));
    }
    let end = s.find(|c: char| c.is_ascii_whitespace()).unwrap_or(s.len());
    let ident = s[..end].trim_matches('"').to_string();
    if ident.is_empty() {
        return Err(MongrelQueryError::Schema(missing.into()));
    }
    Ok((ident, &s[end..]))
}

fn parse_trailing_identifier(s: &str, missing: &str) -> Result<String> {
    let (ident, rest) = take_sql_ident(s, missing)?;
    if !strip_statement_semicolon(rest).is_empty() {
        return Err(MongrelQueryError::Schema(
            "unexpected tokens after identifier".into(),
        ));
    }
    Ok(ident)
}

fn parse_type_tail(s: &str) -> Result<mongreldb_core::schema::TypeId> {
    let tail = strip_statement_semicolon(s);
    let ty = tail
        .split_whitespace()
        .next()
        .ok_or_else(|| MongrelQueryError::Schema("ALTER COLUMN TYPE missing type".into()))?;
    parse_sql_type(ty)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn normalize_collapses_and_trims_whitespace() {
        assert_eq!(normalize_sql("SELECT * FROM t"), "SELECT * FROM t");
        assert_eq!(normalize_sql("  SELECT  *   FROM   t  "), "SELECT * FROM t");
        assert_eq!(
            normalize_sql("\n\tSELECT\n*\nFROM\n\tt\n"),
            "SELECT * FROM t"
        );
        assert_eq!(
            normalize_sql("SELECT   a,   b   FROM   t"),
            normalize_sql("SELECT a, b FROM t")
        );
    }

    #[test]
    fn normalize_preserves_string_literal_whitespace() {
        assert_eq!(
            normalize_sql("SELECT 'hello   world' FROM t"),
            "SELECT 'hello   world' FROM t"
        );
        assert_eq!(
            normalize_sql("SELECT 'it''s   ok' FROM t"),
            "SELECT 'it''s   ok' FROM t"
        );
        assert_eq!(
            normalize_sql("  SELECT  'a  b'  FROM  t  "),
            "SELECT 'a  b' FROM t"
        );
    }

    #[test]
    fn normalize_preserves_quoted_identifier_and_dollar_quote() {
        assert_eq!(
            normalize_sql("  SELECT  \"my col\"  FROM  t  "),
            "SELECT \"my col\" FROM t"
        );
        assert_eq!(
            normalize_sql("  SELECT  $$a   b$$  FROM  t  "),
            "SELECT $$a   b$$ FROM t"
        );
        assert_eq!(
            normalize_sql("SELECT $tag$body   with spaces$tag$ FROM t"),
            "SELECT $tag$body   with spaces$tag$ FROM t"
        );
    }

    #[test]
    fn normalize_strips_comments() {
        assert_eq!(
            normalize_sql("SELECT 1 -- trailing comment\nFROM t"),
            "SELECT 1 FROM t"
        );
        assert_eq!(
            normalize_sql("SELECT /* block */ 1 FROM t"),
            "SELECT 1 FROM t"
        );
        // Comment with a quote-like body must not confuse the scanner.
        assert_eq!(
            normalize_sql("SELECT /* 'not a string' */ 1 FROM t"),
            "SELECT 1 FROM t"
        );
        // Nested block comments are honored (Postgres/DataFusion allow nesting).
        assert_eq!(
            normalize_sql("SELECT /* outer /* inner */ still outer */ 1 FROM t"),
            "SELECT 1 FROM t"
        );
    }

    #[test]
    fn normalize_escape_string_preserved() {
        assert_eq!(
            normalize_sql("SELECT E'line\\nbreak' FROM t"),
            "SELECT E'line\\nbreak' FROM t"
        );
    }

    #[test]
    fn replace_from_view_matches_whole_word_only() {
        let out = replace_from_view("SELECT * FROM logs", "log", "SELECT 1");
        assert_eq!(out, "SELECT * FROM logs");

        let out = replace_from_view("SELECT * FROM log", "log", "SELECT 1");
        assert_eq!(out, "SELECT * FROM (SELECT 1) AS log");

        let out = replace_from_view("select * from log where x", "log", "SELECT 1");
        assert_eq!(out, "select * from (SELECT 1) AS log where x");

        let out = replace_from_view("SELECT * FROM log)", "log", "SELECT 1");
        assert_eq!(out, "SELECT * FROM (SELECT 1) AS log)");

        let out = replace_from_view("SELECT * xfrom log", "log", "SELECT 1");
        assert_eq!(out, "SELECT * xfrom log");
    }

    #[test]
    fn compat_function_rewrite_handles_sqlite_compatibility_calls() {
        assert_eq!(
            rewrite_compat_function_calls("select max(id), min(id) from t"),
            "select max(id), min(id) from t"
        );
        assert_eq!(
            rewrite_compat_function_calls("select max(1, min(2, 3), 'max(4,5)')"),
            "select __mongreldb_scalar_max(1, __mongreldb_scalar_min(2, 3), 'max(4,5)')"
        );
        assert_eq!(
            rewrite_compat_function_calls("select /* max(1,2) */ min(1, (2 + 3))"),
            "select /* max(1,2) */ __mongreldb_scalar_min(1, (2 + 3))"
        );
        assert_eq!(
            rewrite_compat_function_calls("select max_value, min_value from t"),
            "select max_value, min_value from t"
        );
        assert_eq!(
            rewrite_compat_function_calls(
                "select group_concat(label), group_concat(label, '|') from t"
            ),
            "select string_agg(label, ','), string_agg(label, '|') from t"
        );
        assert_eq!(
            rewrite_compat_function_calls("select total(val), total(val) filter (where grp = 2) from t"),
            "select coalesce(cast(sum(val) as double), 0.0), coalesce(cast(sum(val) filter (where grp = 2) as double), 0.0) from t"
        );
        assert_eq!(
            rewrite_compat_function_calls(
                "select total(val) over (partition by grp order by id) from t"
            ),
            "select coalesce(cast(sum(val) over (partition by grp order by id) as double), 0.0) from t"
        );
    }
}