reddb-io-rql 1.15.0

RedDB Query Language (RQL) front-end + conformance authority (ADR 0053). Owns the sqllogictest-format conformance suite whose truth comes from the public SQLite corpus; depends only on reddb-io-types.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
use crate::ast::{
    AlterMetricQuery, AlterQueueQuery, AlterTableQuery, AlterUserStmt, ApplyMigrationQuery,
    AskQuery, BinOp, CompareOp, ConfigCommand, CopyFormat, CopyFromQuery, CreateCollectionQuery,
    CreateForeignTableQuery, CreateIndexQuery, CreateMetricQuery, CreateMigrationQuery,
    CreatePolicyQuery, CreateQueueQuery, CreateSchemaQuery, CreateSequenceQuery, CreateServerQuery,
    CreateSloQuery, CreateTableQuery, CreateTimeSeriesQuery, CreateTreeQuery, CreateUserStmt,
    CreateVectorQuery, CreateViewQuery, DeleteQuery, DropCollectionQuery, DropDocumentQuery,
    DropForeignTableQuery, DropGraphQuery, DropIndexQuery, DropKvQuery, DropPolicyQuery,
    DropQueueQuery, DropSchemaQuery, DropSequenceQuery, DropServerQuery, DropTableQuery,
    DropTimeSeriesQuery, DropTreeQuery, DropVectorQuery, DropViewQuery, EventsBackfillQuery,
    ExplainAlterQuery, ExplainMigrationQuery, Expr, FieldRef, Filter, ForeignColumnDef, GrantStmt,
    GraphCommand, GraphQuery, HybridQuery, InsertQuery, JoinQuery, KvCommand, MaintenanceCommand,
    PathQuery, PolicyAction, ProbabilisticCommand, QueryExpr, QueueCommand, QueueSelectQuery,
    RankOfQuery, RankRangeQuery, RefreshMaterializedViewQuery, RevokeStmt, RollbackMigrationQuery,
    SearchCommand, Span, TableQuery, TreeCommand, TruncateQuery, TxnControl, UpdateQuery,
    VectorQuery,
};
use crate::lexer::Token;
use crate::parser::{ParseError, Parser, SafeTokenDisplay};
use crate::sql_lowering::filter_to_expr;
use reddb_types::catalog::CollectionModel;
use reddb_types::types::Value;

/// Canonical SQL frontend command surface.
///
/// This is the single entrypoint for SQL/RQL-style commands before they are
/// lowered into the broader multi-backend `QueryExpr` space.
#[derive(Debug, Clone)]
pub enum SqlStatement {
    Query(SqlQuery),
    Mutation(SqlMutation),
    Schema(SqlSchemaCommand),
    Admin(SqlAdminCommand),
}

#[derive(Debug, Clone)]
#[allow(clippy::large_enum_variant)]
pub enum FrontendStatement {
    Sql(SqlStatement),
    Graph(GraphQuery),
    GraphCommand(GraphCommand),
    Path(PathQuery),
    Vector(VectorQuery),
    Hybrid(HybridQuery),
    Search(SearchCommand),
    Ask(AskQuery),
    QueueSelect(QueueSelectQuery),
    QueueCommand(QueueCommand),
    EventsBackfill(EventsBackfillQuery),
    EventsBackfillStatus { collection: String },
    TreeCommand(TreeCommand),
    ProbabilisticCommand(ProbabilisticCommand),
    KvCommand(KvCommand),
    ConfigCommand(ConfigCommand),
    Ranking(QueryExpr),
}

#[derive(Debug, Clone)]
pub enum SqlCommand {
    Select(TableQuery),
    Join(JoinQuery),
    Insert(InsertQuery),
    Update(UpdateQuery),
    Delete(DeleteQuery),
    ExplainAlter(ExplainAlterQuery),
    CreateTable(CreateTableQuery),
    CreateCollection(CreateCollectionQuery),
    CreateVector(CreateVectorQuery),
    DropTable(DropTableQuery),
    DropGraph(DropGraphQuery),
    DropVector(DropVectorQuery),
    DropDocument(DropDocumentQuery),
    DropKv(DropKvQuery),
    DropCollection(DropCollectionQuery),
    Truncate(TruncateQuery),
    AlterTable(AlterTableQuery),
    CreateIndex(CreateIndexQuery),
    DropIndex(DropIndexQuery),
    CreateTimeSeries(CreateTimeSeriesQuery),
    CreateMetric(CreateMetricQuery),
    AlterMetric(AlterMetricQuery),
    CreateSlo(CreateSloQuery),
    DropTimeSeries(DropTimeSeriesQuery),
    CreateQueue(CreateQueueQuery),
    AlterQueue(AlterQueueQuery),
    DropQueue(DropQueueQuery),
    CreateTree(CreateTreeQuery),
    DropTree(DropTreeQuery),
    Probabilistic(ProbabilisticCommand),
    SetConfig {
        key: String,
        value: Value,
    },
    ShowConfig {
        prefix: Option<String>,
        as_json: bool,
    },
    SetSecret {
        key: String,
        value: Value,
    },
    DeleteSecret {
        key: String,
    },
    ShowSecrets {
        prefix: Option<String>,
    },
    SetTenant(Option<String>),
    ShowTenant,
    TransactionControl(TxnControl),
    Maintenance(MaintenanceCommand),
    CreateSchema(CreateSchemaQuery),
    DropSchema(DropSchemaQuery),
    CreateSequence(CreateSequenceQuery),
    DropSequence(DropSequenceQuery),
    CopyFrom(CopyFromQuery),
    CreateView(CreateViewQuery),
    DropView(DropViewQuery),
    RefreshMaterializedView(RefreshMaterializedViewQuery),
    CreatePolicy(CreatePolicyQuery),
    DropPolicy(DropPolicyQuery),
    CreateServer(CreateServerQuery),
    DropServer(DropServerQuery),
    CreateForeignTable(CreateForeignTableQuery),
    DropForeignTable(DropForeignTableQuery),
    /// `GRANT … ON … TO …`
    Grant(GrantStmt),
    /// `REVOKE … ON … FROM …`
    Revoke(RevokeStmt),
    /// `ALTER USER name <attrs>`
    AlterUser(AlterUserStmt),
    /// `CREATE USER name PASSWORD '...' [ROLE read|write|admin]`
    CreateUser(CreateUserStmt),
    /// IAM policy DDL (CREATE POLICY '...' AS '...', DROP POLICY '...',
    /// ATTACH/DETACH POLICY, SHOW POLICIES, SIMULATE, SHOW EFFECTIVE
    /// PERMISSIONS). Stored as a pre-built QueryExpr so the dispatcher
    /// can route the multitude of shapes through a single arm.
    IamPolicy(QueryExpr),
    CreateMigration(CreateMigrationQuery),
    ApplyMigration(ApplyMigrationQuery),
    RollbackMigration(RollbackMigrationQuery),
    ExplainMigration(ExplainMigrationQuery),
}

/// Issue #789 — Analytics v0 non-goal map for `CREATE …` forms.
///
/// PRD #782 ringfences Analytics v0 around a metric-centric catalog and
/// explicitly excludes generic analytics objects, a separate event
/// storage model, cohorts, funnels, SLA contracts, and adapter surfaces.
/// When the parser sees one of these idents in the `CREATE` head, return
/// a stable v0-scoped rejection message; otherwise return `None` and let
/// the regular CREATE fallback handle the token.
fn analytics_v0_non_goal_create(token: &Token) -> Option<String> {
    let ident = match token {
        Token::Ident(s) => s,
        _ => return None,
    };
    let upper = ident.to_ascii_uppercase();
    let message = match upper.as_str() {
        "ANALYTICS" => {
            "CREATE ANALYTICS is not supported in Analytics v0 — \
             use CREATE METRIC <dotted.path> for the metric-centric \
             catalog (PRD #782 non-goal)"
        }
        "EVENT" => {
            "CREATE EVENT is not supported in Analytics v0 — \
             event-shaped data lives in ordinary TABLE/DOCUMENT \
             collections, not a new storage model (PRD #782 non-goal)"
        }
        "COHORT" => {
            "CREATE COHORT is not supported in Analytics v0 — \
             cohort surfaces are deferred (PRD #782 non-goal)"
        }
        "FUNNEL" => {
            "CREATE FUNNEL is not supported in Analytics v0 — \
             funnel surfaces are deferred (PRD #782 non-goal)"
        }
        "SLA" => {
            "CREATE SLA is not supported in Analytics v0 — \
             SLA/legal/commercial contract modeling is post-MVP \
             (PRD #782 non-goal)"
        }
        "ADAPTER" => {
            "CREATE ADAPTER is not supported in Analytics v0 — \
             Prometheus/Grafana/Snowplow/Google Analytics adapters \
             are deferred (PRD #782 non-goal)"
        }
        _ => return None,
    };
    Some(message.to_string())
}

fn collection_model_filter(model: &str) -> Filter {
    Filter::Compare {
        field: FieldRef::column("", "model"),
        op: CompareOp::Eq,
        value: Value::Text(model.to_string().into()),
    }
}

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

    fn frontend(input: &str) -> FrontendStatement {
        parse_frontend(input)
            .unwrap_or_else(|err| panic!("failed to parse frontend {input:?}: {err:?}"))
    }

    fn expr(input: &str) -> QueryExpr {
        frontend(input).into_query_expr()
    }

    fn sql_command(input: &str) -> SqlCommand {
        sql_command_result(input)
            .unwrap_or_else(|err| panic!("failed to parse SQL command {input:?}: {err:?}"))
    }

    fn sql_command_result(input: &str) -> Result<SqlCommand, ParseError> {
        let mut parser = Parser::new(input)?;
        parser.parse_sql_command()
    }

    fn assert_text(value: &Value, expected: &str) {
        match value {
            Value::Text(text) => assert_eq!(text.as_ref(), expected),
            other => panic!("expected text {expected:?}, got {other:?}"),
        }
    }

    #[test]
    fn parse_frontend_routes_core_sql_statements() {
        let FrontendStatement::Sql(SqlStatement::Query(SqlQuery::Select(query))) =
            frontend("SELECT * FROM users")
        else {
            panic!("SELECT should route to SqlStatement::Query::Select");
        };
        assert_eq!(query.table, "users");

        let QueryExpr::Insert(query) = expr("INSERT INTO users (id, name) VALUES (1, 'ada')")
        else {
            panic!("INSERT should lower through the SQL frontend");
        };
        assert_eq!(query.table, "users");
        assert_eq!(query.columns, vec!["id", "name"]);
        assert_eq!(query.values.len(), 1);

        let QueryExpr::Update(query) = expr("UPDATE users SET name = 'ada' WHERE id = 1") else {
            panic!("UPDATE should lower through the SQL frontend");
        };
        assert_eq!(query.table, "users");
        assert_eq!(query.assignments[0].0, "name");

        let QueryExpr::Delete(query) = expr("DELETE FROM users WHERE id = 1") else {
            panic!("DELETE should lower through the SQL frontend");
        };
        assert_eq!(query.table, "users");
        assert!(query.filter.is_some());

        let QueryExpr::CreateTable(query) = expr("CREATE TABLE users (id INT, name TEXT)") else {
            panic!("CREATE TABLE should lower through the SQL frontend");
        };
        assert_eq!(query.collection_model, CollectionModel::Table);
        assert_eq!(query.name, "users");
        assert_eq!(query.columns[0].name, "id");

        let QueryExpr::DropTable(query) = expr("DROP TABLE IF EXISTS users") else {
            panic!("DROP TABLE should lower through the SQL frontend");
        };
        assert_eq!(query.name, "users");
        assert!(query.if_exists);
    }

    #[test]
    fn parse_frontend_routes_admin_and_catalog_sql() {
        let QueryExpr::Table(query) = expr("SHOW COLLECTIONS") else {
            panic!("SHOW COLLECTIONS should become a red.collections table query");
        };
        assert_eq!(query.table, "red.collections");
        assert!(query.filter.is_some());

        let QueryExpr::Table(query) = expr("SHOW TABLES LIMIT 5") else {
            panic!("SHOW TABLES should become a filtered red.collections table query");
        };
        assert_eq!(query.table, "red.collections");
        assert_eq!(query.limit, Some(5));
        assert!(query.filter.is_some());

        assert!(matches!(
            expr("SHOW CONFIG durability.mode"),
            QueryExpr::ShowConfig { prefix: Some(prefix), as_json: false } if prefix == "durability.mode"
        ));
        assert!(matches!(
            expr("SHOW CONFIG"),
            QueryExpr::ShowConfig {
                prefix: None,
                as_json: false
            }
        ));
        assert!(matches!(
            expr("SHOW CONFIG runtime.result_cache AS JSON"),
            QueryExpr::ShowConfig { prefix: Some(prefix), as_json: true } if prefix == "runtime.result_cache"
        ));
        assert!(matches!(
            expr("SHOW CONFIG FORMAT JSON"),
            QueryExpr::ShowConfig {
                prefix: None,
                as_json: true
            }
        ));

        let QueryExpr::SetConfig { key, value } = expr("SET CONFIG durability.mode = 'sync'")
        else {
            panic!("SET CONFIG should stay on the SQL admin surface");
        };
        assert_eq!(key, "durability.mode");
        assert_text(&value, "sync");

        let QueryExpr::SetSecret { key, value } = expr("SET SECRET provider.api_key = 'sk_test'")
        else {
            panic!("SET SECRET should stay on the SQL admin surface");
        };
        assert_eq!(key, "provider.api_key");
        assert_text(&value, "sk_test");
        assert!(matches!(
            expr("SET SECRET red.secrets.provider.api_key = 'sk_test'"),
            QueryExpr::SetSecret { key, .. } if key == "red.secret.provider.api_key"
        ));

        assert!(matches!(
            expr("DELETE SECRET provider.api_key"),
            QueryExpr::DeleteSecret { key } if key == "provider.api_key"
        ));
        assert!(matches!(
            expr("DELETE SECRET red.secrets.provider.api_key"),
            QueryExpr::DeleteSecret { key } if key == "red.secret.provider.api_key"
        ));
        assert!(matches!(
            expr("SHOW SECRETS provider"),
            QueryExpr::ShowSecrets { prefix: Some(prefix) } if prefix == "provider"
        ));
        assert!(matches!(
            expr("SHOW SECRETS red.secrets.provider"),
            QueryExpr::ShowSecrets { prefix: Some(prefix) } if prefix == "red.secret.provider"
        ));
        assert!(matches!(
            expr("SET TENANT 'acme'"),
            QueryExpr::SetTenant(Some(tenant)) if tenant == "acme"
        ));
        assert!(matches!(expr("RESET TENANT"), QueryExpr::SetTenant(None)));
        assert!(matches!(expr("SHOW TENANT"), QueryExpr::ShowTenant));
        assert!(matches!(
            expr("BEGIN ISOLATION LEVEL SNAPSHOT"),
            QueryExpr::TransactionControl(TxnControl::Begin)
        ));
        assert!(matches!(
            expr("ROLLBACK TO SAVEPOINT sp1"),
            QueryExpr::TransactionControl(TxnControl::RollbackToSavepoint(name)) if name == "sp1"
        ));
        assert!(matches!(
            expr("VACUUM FULL users"),
            QueryExpr::MaintenanceCommand(MaintenanceCommand::Vacuum {
                target: Some(target),
                full: true,
            }) if target == "users"
        ));
    }

    #[test]
    fn parse_frontend_routes_extended_schema_sql() {
        assert!(matches!(
            expr("CREATE SCHEMA IF NOT EXISTS app"),
            QueryExpr::CreateSchema(CreateSchemaQuery {
                name,
                if_not_exists: true,
            }) if name == "app"
        ));
        assert!(matches!(
            expr("DROP SCHEMA IF EXISTS app CASCADE"),
            QueryExpr::DropSchema(DropSchemaQuery {
                name,
                if_exists: true,
                cascade: true,
            }) if name == "app"
        ));
        assert!(matches!(
            expr("CREATE SEQUENCE IF NOT EXISTS seq START WITH 10 INCREMENT BY 2"),
            QueryExpr::CreateSequence(CreateSequenceQuery {
                name,
                if_not_exists: true,
                start: 10,
                increment: 2,
            }) if name == "seq"
        ));
        assert!(matches!(
            expr("DROP SEQUENCE IF EXISTS seq"),
            QueryExpr::DropSequence(DropSequenceQuery {
                name,
                if_exists: true,
            }) if name == "seq"
        ));

        let QueryExpr::CopyFrom(copy) = expr(
            "COPY users FROM '/tmp/u.csv' WITH (FORMAT = csv, HEADER = true, DELIMITER = ';')",
        ) else {
            panic!("COPY should lower through SQL frontend");
        };
        assert_eq!(copy.table, "users");
        assert_eq!(copy.path, "/tmp/u.csv");
        assert_eq!(copy.format, CopyFormat::Csv);
        assert_eq!(copy.delimiter, Some(';'));
        assert!(copy.has_header);

        let QueryExpr::CreateView(view) = expr(
            "CREATE MATERIALIZED VIEW IF NOT EXISTS mv WITH RETENTION 1 h \
             AS SELECT id FROM users REFRESH EVERY 5 s",
        ) else {
            panic!("CREATE MATERIALIZED VIEW should lower through SQL frontend");
        };
        assert_eq!(view.name, "mv");
        assert!(view.materialized);
        assert!(view.if_not_exists);
        assert_eq!(view.retention_duration_ms, Some(3_600_000));
        assert_eq!(view.refresh_every_ms, Some(5_000));
        assert!(matches!(*view.query, QueryExpr::Table(_)));

        assert!(matches!(
            expr("DROP MATERIALIZED VIEW IF EXISTS mv"),
            QueryExpr::DropView(DropViewQuery {
                name,
                materialized: true,
                if_exists: true,
            }) if name == "mv"
        ));
        assert!(matches!(
            expr("REFRESH MATERIALIZED VIEW mv"),
            QueryExpr::RefreshMaterializedView(RefreshMaterializedViewQuery { name }) if name == "mv"
        ));
    }

    #[test]
    fn parse_frontend_routes_fdw_policy_auth_and_migrations() {
        let QueryExpr::CreateServer(server) = expr(
            "CREATE SERVER IF NOT EXISTS csvsrv FOREIGN DATA WRAPPER csv OPTIONS (path '/data')",
        ) else {
            panic!("CREATE SERVER should lower through SQL frontend");
        };
        assert_eq!(server.name, "csvsrv");
        assert_eq!(server.wrapper, "csv");
        assert!(server.if_not_exists);
        assert_eq!(
            server.options,
            vec![("path".to_string(), "/data".to_string())]
        );

        let QueryExpr::CreateForeignTable(table) = expr(
            "CREATE FOREIGN TABLE IF NOT EXISTS ext_users \
             (id INT, name TEXT) SERVER csvsrv OPTIONS (file 'users.csv')",
        ) else {
            panic!("CREATE FOREIGN TABLE should lower through SQL frontend");
        };
        assert_eq!(table.name, "ext_users");
        assert_eq!(table.server, "csvsrv");
        assert!(table.if_not_exists);
        assert_eq!(table.columns.len(), 2);
        assert!(!table.columns[0].not_null);

        assert!(matches!(
            expr("DROP SERVER IF EXISTS csvsrv CASCADE"),
            QueryExpr::DropServer(DropServerQuery {
                name,
                if_exists: true,
                cascade: true,
            }) if name == "csvsrv"
        ));
        assert!(matches!(
            expr("DROP FOREIGN TABLE IF EXISTS ext_users"),
            QueryExpr::DropForeignTable(DropForeignTableQuery {
                name,
                if_exists: true,
            }) if name == "ext_users"
        ));

        let QueryExpr::CreatePolicy(policy) = expr(
            "CREATE POLICY readonly ON NODES OF mygraph FOR SELECT TO analytics USING (public = 1)",
        ) else {
            panic!("CREATE POLICY should lower through SQL frontend");
        };
        assert_eq!(policy.name, "readonly");
        assert_eq!(policy.table, "mygraph");
        assert_eq!(policy.action, Some(PolicyAction::Select));
        assert_eq!(policy.role.as_deref(), Some("analytics"));
        assert_eq!(policy.target_kind.as_ident(), "nodes");

        assert!(matches!(
            expr("DROP POLICY IF EXISTS readonly ON mygraph"),
            QueryExpr::DropPolicy(DropPolicyQuery {
                name,
                table,
                if_exists: true,
            }) if name == "readonly" && table == "mygraph"
        ));

        assert!(matches!(
            expr("GRANT SELECT ON TABLE public.users TO tenant1.alice"),
            QueryExpr::Grant(grant)
                if grant.actions == vec!["SELECT"]
                    && grant.objects[0].schema.as_deref() == Some("public")
        ));
        assert!(matches!(
            expr("REVOKE GRANT OPTION FOR USAGE ON SCHEMA analytics FROM GROUP analysts"),
            QueryExpr::Revoke(revoke) if revoke.grant_option_for && revoke.all == false
        ));
        assert!(matches!(
            expr("ALTER USER bob ENABLE SET search_path TO 'public'"),
            QueryExpr::AlterUser(user)
                if user.username == "bob" && user.attributes.len() == 2
        ));
        assert!(matches!(
            expr("CREATE USER tenant1.alice WITH PASSWORD 'pw' ROLE write"),
            QueryExpr::CreateUser(user)
                if user.tenant.as_deref() == Some("tenant1")
                    && user.username == "alice"
                    && user.password == "pw"
                    && user.role == "write"
        ));

        assert!(matches!(
            expr("CREATE POLICY 'readonly' AS '{\"Statement\":[]}'"),
            QueryExpr::CreateIamPolicy { id, json }
                if id == "readonly" && json == "{\"Statement\":[]}"
        ));
        assert!(matches!(
            expr("DROP POLICY 'readonly'"),
            QueryExpr::DropIamPolicy { id } if id == "readonly"
        ));

        assert!(matches!(
            expr("CREATE MIGRATION m2 DEPENDS ON m0 BATCH 10 ROWS AS CREATE TABLE accounts (id INT)"),
            QueryExpr::CreateMigration(migration)
                if migration.name == "m2"
                    && migration.depends_on == vec!["m0".to_string()]
                    && migration.batch_size == Some(10)
        ));
        assert!(matches!(
            expr("APPLY MIGRATION * FOR TENANT tenant1"),
            QueryExpr::ApplyMigration(apply)
                if apply.for_tenant.as_deref() == Some("tenant1")
        ));
        assert!(matches!(
            expr("ROLLBACK MIGRATION m2"),
            QueryExpr::RollbackMigration(RollbackMigrationQuery { name }) if name == "m2"
        ));
        assert!(matches!(
            expr("EXPLAIN MIGRATION m2"),
            QueryExpr::ExplainMigration(ExplainMigrationQuery { name }) if name == "m2"
        ));
    }

    #[test]
    fn parse_sql_statement_covers_statement_category_wrapping() {
        enum Expected {
            Select,
            Insert,
            CreateSchema,
            SetTenant,
        }

        let cases = [
            ("SELECT * FROM users", Expected::Select),
            ("INSERT INTO users (id) VALUES (1)", Expected::Insert),
            ("CREATE SCHEMA app", Expected::CreateSchema),
            ("SET TENANT 'acme'", Expected::SetTenant),
        ];

        for (input, expected) in cases {
            let mut parser = Parser::new(input).expect("lexer");
            let statement = parser
                .parse_sql_statement()
                .unwrap_or_else(|err| panic!("failed to parse {input:?}: {err:?}"));
            let matched = match expected {
                Expected::Select => matches!(statement, SqlStatement::Query(SqlQuery::Select(_))),
                Expected::Insert => {
                    matches!(statement, SqlStatement::Mutation(SqlMutation::Insert(_)))
                }
                Expected::CreateSchema => matches!(
                    statement,
                    SqlStatement::Schema(SqlSchemaCommand::CreateSchema(_))
                ),
                Expected::SetTenant => {
                    matches!(
                        statement,
                        SqlStatement::Admin(SqlAdminCommand::SetTenant(_))
                    )
                }
            };
            assert!(matched, "{input}");
        }
    }

    #[test]
    fn parse_frontend_routes_non_sql_frontends() {
        let QueryExpr::KvCommand(KvCommand::Get {
            model,
            collection,
            key,
        }) = expr("KV GET settings.feature")
        else {
            panic!("KV GET should route to FrontendStatement::KvCommand");
        };
        assert_eq!(model, CollectionModel::Kv);
        assert_eq!(collection, "settings");
        assert_eq!(key, "feature");

        let QueryExpr::ConfigCommand(ConfigCommand::Watch {
            collection,
            key,
            prefix,
            from_lsn,
        }) = expr("WATCH CONFIG app PREFIX feature FROM LSN 7")
        else {
            panic!("WATCH CONFIG should route to FrontendStatement::ConfigCommand");
        };
        assert_eq!(collection, "app");
        assert_eq!(key, "feature");
        assert!(prefix);
        assert_eq!(from_lsn, Some(7));

        let QueryExpr::ConfigCommand(ConfigCommand::List {
            collection,
            prefix,
            limit,
            offset,
        }) = expr("LIST CONFIG app PREFIX feature LIMIT 3 OFFSET 1")
        else {
            panic!("LIST CONFIG should route to FrontendStatement::ConfigCommand");
        };
        assert_eq!(collection, "app");
        assert_eq!(prefix.as_deref(), Some("feature"));
        assert_eq!(limit, Some(3));
        assert_eq!(offset, 1);

        let QueryExpr::KvCommand(KvCommand::List {
            model,
            collection,
            prefix,
            limit,
            offset,
            as_json,
        }) = expr("KV LIST settings PREFIX 'feature.' LIMIT 10 OFFSET 2")
        else {
            panic!("KV LIST should route to FrontendStatement::KvCommand");
        };
        assert_eq!(model, CollectionModel::Kv);
        assert_eq!(collection, "settings");
        assert_eq!(prefix.as_deref(), Some("feature."));
        assert_eq!(limit, Some(10));
        assert_eq!(offset, 2);
        assert!(!as_json);

        let QueryExpr::KvCommand(KvCommand::List {
            model,
            collection,
            prefix,
            limit,
            offset,
            as_json,
        }) = expr("LIST KV settings PREFIX feature LIMIT 10 OFFSET 2")
        else {
            panic!("LIST KV should route to FrontendStatement::KvCommand");
        };
        assert_eq!(model, CollectionModel::Kv);
        assert_eq!(collection, "settings");
        assert_eq!(prefix.as_deref(), Some("feature"));
        assert_eq!(limit, Some(10));
        assert_eq!(offset, 2);
        assert!(!as_json);

        let QueryExpr::KvCommand(KvCommand::List {
            model,
            collection,
            prefix,
            as_json,
            ..
        }) = expr("KV LIST settings PREFIX feature AS JSON")
        else {
            panic!("KV LIST AS JSON should route to FrontendStatement::KvCommand");
        };
        assert_eq!(model, CollectionModel::Kv);
        assert_eq!(collection, "settings");
        assert_eq!(prefix.as_deref(), Some("feature"));
        assert!(as_json);

        let QueryExpr::KvCommand(KvCommand::Watch {
            model,
            collection,
            key,
            prefix,
            from_lsn,
        }) = expr("WATCH sessions.user.* FROM LSN 3")
        else {
            panic!("bare WATCH should route to FrontendStatement::KvCommand");
        };
        assert_eq!(model, CollectionModel::Kv);
        assert_eq!(collection, "sessions");
        assert_eq!(key, "user");
        assert!(prefix);
        assert_eq!(from_lsn, Some(3));

        let QueryExpr::KvCommand(KvCommand::Watch {
            model,
            collection,
            key,
            prefix,
            from_lsn,
        }) = expr("WATCH VAULT secrets PREFIX api FROM LSN 7")
        else {
            panic!("WATCH VAULT should route to FrontendStatement::KvCommand");
        };
        assert_eq!(model, CollectionModel::Vault);
        assert_eq!(collection, "secrets");
        assert_eq!(key, "api");
        assert!(prefix);
        assert_eq!(from_lsn, Some(7));

        let QueryExpr::KvCommand(KvCommand::List {
            model,
            collection,
            prefix,
            limit,
            offset,
            as_json,
        }) = expr("LIST VAULT secrets PREFIX api LIMIT 10 OFFSET 2")
        else {
            panic!("LIST VAULT should route to FrontendStatement::KvCommand");
        };
        assert_eq!(model, CollectionModel::Vault);
        assert_eq!(collection, "secrets");
        assert_eq!(prefix.as_deref(), Some("api"));
        assert_eq!(limit, Some(10));
        assert_eq!(offset, 2);
        assert!(!as_json);

        assert!(matches!(
            expr("INVALIDATE CONFIG app feature_flag"),
            QueryExpr::ConfigCommand(ConfigCommand::InvalidVolatileOperation {
                operation,
                collection,
                key: Some(key),
            }) if operation == "INVALIDATE" && collection == "app" && key == "feature_flag"
        ));
        assert!(matches!(
            expr("INVALIDATE TAGS [user:42, org:7] FROM sessions"),
            QueryExpr::KvCommand(KvCommand::InvalidateTags { collection, tags })
                if collection == "sessions" && tags == vec!["user:42".to_string(), "org:7".to_string()]
        ));

        let QueryExpr::EventsBackfill(query) =
            expr("EVENTS BACKFILL users WHERE status = 'active' TO audit LIMIT 10")
        else {
            panic!("EVENTS BACKFILL should route to FrontendStatement::EventsBackfill");
        };
        assert_eq!(query.collection, "users");
        assert_eq!(query.where_filter.as_deref(), Some("status = 'active'"));
        assert_eq!(query.target_queue, "audit");
        assert_eq!(query.limit, Some(10));

        let QueryExpr::Table(query) = expr("EVENTS STATUS users LIMIT 2") else {
            panic!("EVENTS STATUS should route through the SQL select surface");
        };
        assert_eq!(query.table, "red.subscriptions");
        assert_eq!(query.limit, Some(2));
        assert!(query.filter.is_some());

        assert!(matches!(
            expr("EVENTS BACKFILL STATUS users"),
            QueryExpr::EventsBackfillStatus { collection } if collection == "users"
        ));
        assert!(parse_frontend("LIST UNKNOWN").is_err());
        assert!(parse_frontend("EVENTS UNKNOWN").is_err());
    }

    #[test]
    fn parse_frontend_routes_ranking_reads() {
        assert!(matches!(
            expr("RANK OF 42 IN page_rank"),
            QueryExpr::RankOf(RankOfQuery { ranking, entity_id })
                if ranking == "page_rank" && entity_id == 42
        ));
        assert!(matches!(
            expr("APPROX RANK OF 7 IN page_rank"),
            QueryExpr::ApproxRankOf(RankOfQuery { ranking, entity_id })
                if ranking == "page_rank" && entity_id == 7
        ));
        assert!(matches!(
            expr("RANK RANGE 1 TO 3 IN page_rank"),
            QueryExpr::RankRange(RankRangeQuery { ranking, lo, hi })
                if ranking == "page_rank" && lo == 1 && hi == 3
        ));
        assert!(matches!(
            expr("ZRANK page_rank 0"),
            QueryExpr::RankOf(RankOfQuery { ranking, entity_id })
                if ranking == "page_rank" && entity_id == 0
        ));
        assert!(matches!(
            expr("ZRANGE page_rank 0 3 WITHSCORES"),
            QueryExpr::RankRange(RankRangeQuery { ranking, lo, hi })
                if ranking == "page_rank" && lo == 1 && hi == 4
        ));
        assert!(
            parse_frontend("RANK RANGE 3 TO 1 IN page_rank").is_err(),
            "rank range must reject reversed bounds"
        );
    }

    #[test]
    fn parse_frontend_covers_multimodel_command_routing() {
        assert!(matches!(
            expr("GRAPH CENTRALITY ALGORITHM pagerank LIMIT 5"),
            QueryExpr::GraphCommand(GraphCommand::Centrality {
                algorithm,
                limit: Some(5),
                ..
            }) if algorithm == "pagerank"
        ));
        assert!(matches!(
            expr("SEARCH TEXT 'login failure' COLLECTION incidents LIMIT 20 FUZZY"),
            QueryExpr::SearchCommand(SearchCommand::Text {
                query,
                collection: Some(collection),
                limit: 20,
                fuzzy: true,
                ..
            }) if query == "login failure" && collection == "incidents"
        ));
        assert!(matches!(
            expr("ASK 'why did login fail?' USING openai LIMIT 3"),
            QueryExpr::Ask(query)
                if query.question == "why did login fail?"
                    && query.provider.as_deref() == Some("openai")
                    && query.limit == Some(3)
        ));
        assert!(matches!(
            expr("QUEUE LEN tasks"),
            QueryExpr::QueueCommand(QueueCommand::Len { queue }) if queue == "tasks"
        ));
        assert!(matches!(
            expr("TREE REBALANCE forest.org DRY RUN"),
            QueryExpr::TreeCommand(TreeCommand::Rebalance {
                collection,
                tree_name,
                dry_run: true,
            }) if collection == "forest" && tree_name == "org"
        ));
        assert!(matches!(
            expr("HLL COUNT visitors"),
            QueryExpr::ProbabilisticCommand(ProbabilisticCommand::HllCount { names })
                if names == vec!["visitors".to_string()]
        ));
    }

    #[test]
    fn sql_command_round_trips_multimodel_schema_variants() {
        macro_rules! assert_command_round_trip {
            ($input:expr, $pattern:pat) => {{
                let command = sql_command($input);
                assert!(matches!(command, $pattern), "unexpected command for {}", $input);

                let statement = sql_command($input).into_statement();
                let command = statement.into_command();
                assert!(
                    matches!(command, $pattern),
                    "statement round trip changed command for {}",
                    $input
                );

                let expr = sql_command($input).into_query_expr();
                assert!(
                    !matches!(expr, QueryExpr::Table(TableQuery { table, .. }) if table.is_empty()),
                    "lowering produced an empty table placeholder for {}",
                    $input
                );
            }};
        }

        assert_command_round_trip!(
            "EXPLAIN ALTER FOR CREATE TABLE users (id INT) FORMAT JSON",
            SqlCommand::ExplainAlter(_)
        );
        assert_command_round_trip!("CREATE TABLE users (id INT)", SqlCommand::CreateTable(_));
        assert_command_round_trip!("DROP TABLE IF EXISTS users", SqlCommand::DropTable(_));
        assert_command_round_trip!(
            "ALTER TABLE users ADD COLUMN status TEXT",
            SqlCommand::AlterTable(_)
        );
        assert_command_round_trip!(
            "CREATE INDEX idx_email ON users (email) USING HASH",
            SqlCommand::CreateIndex(_)
        );
        assert_command_round_trip!(
            "DROP INDEX IF EXISTS idx_email ON users",
            SqlCommand::DropIndex(_)
        );
        assert_command_round_trip!("CREATE GRAPH identity", SqlCommand::CreateTable(_));
        assert_command_round_trip!("CREATE DOCUMENT docs", SqlCommand::CreateTable(_));
        assert_command_round_trip!(
            "CREATE VECTOR embeddings DIM 4",
            SqlCommand::CreateVector(_)
        );
        assert_command_round_trip!(
            "CREATE COLLECTION turbo KIND vector.turbo DIM 3",
            SqlCommand::CreateCollection(_)
        );
        assert_command_round_trip!("CREATE KV settings", SqlCommand::CreateTable(_));
        assert_command_round_trip!("CREATE CONFIG app", SqlCommand::CreateTable(_));
        assert_command_round_trip!(
            "CREATE VAULT secrets WITH OWN MASTER KEY",
            SqlCommand::CreateTable(_)
        );
        assert_command_round_trip!(
            "CREATE TIMESERIES metrics RETENTION 90 d",
            SqlCommand::CreateTimeSeries(_)
        );
        assert_command_round_trip!(
            "CREATE METRIC svc.latency TYPE gauge ROLE sli",
            SqlCommand::CreateMetric(_)
        );
        assert_command_round_trip!(
            "ALTER METRIC svc.latency SET ROLE internal",
            SqlCommand::AlterMetric(_)
        );
        assert_command_round_trip!(
            "CREATE SLO svc.availability ON svc.latency TARGET 99.9 WINDOW 5 m",
            SqlCommand::CreateSlo(_)
        );
        assert_command_round_trip!(
            "CREATE QUEUE tasks MAX_SIZE 100",
            SqlCommand::CreateQueue(_)
        );
        assert_command_round_trip!(
            "ALTER QUEUE tasks SET MODE FANOUT",
            SqlCommand::AlterQueue(_)
        );
        assert_command_round_trip!(
            "CREATE TREE org IN forest ROOT LABEL root MAX_CHILDREN 4",
            SqlCommand::CreateTree(_)
        );
        assert_command_round_trip!(
            "CREATE HLL visitors PRECISION 14",
            SqlCommand::Probabilistic(_)
        );
        assert_command_round_trip!(
            "CREATE SKETCH freqs WIDTH 512 DEPTH 3",
            SqlCommand::Probabilistic(_)
        );
        assert_command_round_trip!(
            "CREATE FILTER seen CAPACITY 1024",
            SqlCommand::Probabilistic(_)
        );
        assert_command_round_trip!("COPY users FROM '/tmp/u.csv'", SqlCommand::CopyFrom(_));
        assert_command_round_trip!(
            "CREATE VIEW active_users AS SELECT * FROM users",
            SqlCommand::CreateView(_)
        );
        assert_command_round_trip!("DROP VIEW active_users", SqlCommand::DropView(_));
        assert_command_round_trip!(
            "REFRESH MATERIALIZED VIEW active_users",
            SqlCommand::RefreshMaterializedView(_)
        );
        assert_command_round_trip!(
            "CREATE SERVER mycsv FOREIGN DATA WRAPPER csv OPTIONS (base_path '/data')",
            SqlCommand::CreateServer(_)
        );
        assert_command_round_trip!(
            "DROP SERVER IF EXISTS mycsv CASCADE",
            SqlCommand::DropServer(_)
        );
        assert_command_round_trip!(
            "CREATE FOREIGN TABLE ext_users (id INT, name TEXT) SERVER mycsv OPTIONS (path 'users.csv')",
            SqlCommand::CreateForeignTable(_)
        );
        assert_command_round_trip!(
            "DROP FOREIGN TABLE IF EXISTS ext_users",
            SqlCommand::DropForeignTable(_)
        );
    }

    #[test]
    fn sql_command_round_trips_drop_truncate_and_maintenance_variants() {
        macro_rules! assert_command_round_trip {
            ($input:expr, $pattern:pat) => {{
                let command = sql_command($input);
                assert!(
                    matches!(command, $pattern),
                    "unexpected command for {}",
                    $input
                );
                let statement = sql_command($input).into_statement();
                assert!(
                    matches!(statement.into_command(), $pattern),
                    "statement round trip changed command for {}",
                    $input
                );
            }};
        }

        assert_command_round_trip!("DROP GRAPH IF EXISTS identity", SqlCommand::DropGraph(_));
        assert_command_round_trip!(
            "DROP VECTOR IF EXISTS embeddings",
            SqlCommand::DropVector(_)
        );
        assert_command_round_trip!("DROP DOCUMENT IF EXISTS docs", SqlCommand::DropDocument(_));
        assert_command_round_trip!("DROP KV IF EXISTS settings", SqlCommand::DropKv(_));
        assert_command_round_trip!("DROP CONFIG IF EXISTS app", SqlCommand::DropKv(_));
        assert_command_round_trip!("DROP VAULT IF EXISTS secrets", SqlCommand::DropKv(_));
        assert_command_round_trip!(
            "DROP COLLECTION IF EXISTS docs",
            SqlCommand::DropCollection(_)
        );
        assert_command_round_trip!(
            "DROP TIMESERIES IF EXISTS metrics",
            SqlCommand::DropTimeSeries(_)
        );
        assert_command_round_trip!(
            "DROP HYPERTABLE IF EXISTS metrics",
            SqlCommand::DropTimeSeries(_)
        );
        assert_command_round_trip!("DROP QUEUE IF EXISTS tasks", SqlCommand::DropQueue(_));
        assert_command_round_trip!("DROP TREE IF EXISTS org IN forest", SqlCommand::DropTree(_));
        assert_command_round_trip!("DROP HLL IF EXISTS visitors", SqlCommand::Probabilistic(_));
        assert_command_round_trip!("DROP SKETCH IF EXISTS freqs", SqlCommand::Probabilistic(_));
        assert_command_round_trip!("DROP FILTER IF EXISTS seen", SqlCommand::Probabilistic(_));
        assert_command_round_trip!(
            "TRUNCATE VECTOR IF EXISTS embeddings",
            SqlCommand::Truncate(_)
        );
        assert_command_round_trip!(
            "COMMIT WORK",
            SqlCommand::TransactionControl(TxnControl::Commit)
        );
        assert_command_round_trip!(
            "ROLLBACK",
            SqlCommand::TransactionControl(TxnControl::Rollback)
        );
        assert_command_round_trip!(
            "SAVEPOINT before_batch",
            SqlCommand::TransactionControl(TxnControl::Savepoint(_))
        );
        assert_command_round_trip!(
            "RELEASE SAVEPOINT before_batch",
            SqlCommand::TransactionControl(TxnControl::ReleaseSavepoint(_))
        );
        assert_command_round_trip!(
            "ANALYZE users",
            SqlCommand::Maintenance(MaintenanceCommand::Analyze { .. })
        );
        assert_command_round_trip!(
            "VACUUM",
            SqlCommand::Maintenance(MaintenanceCommand::Vacuum { .. })
        );
    }

    #[test]
    fn parse_sql_command_covers_show_and_error_branches() {
        assert!(matches!(
            sql_command("SHOW CREATE TABLE public.users"),
            SqlCommand::Select(TableQuery { table, .. }) if table == "red.show_create"
        ));
        assert!(matches!(
            sql_command("SHOW COLLECTIONS INCLUDING INTERNAL LIMIT 2"),
            SqlCommand::Select(TableQuery { table, limit: Some(2), .. }) if table == "red.collections"
        ));
        assert!(matches!(
            sql_command("SHOW QUEUES INCLUDING INTERNAL"),
            SqlCommand::Select(TableQuery { table, filter: None, .. }) if table == "red.queues"
        ));
        assert!(matches!(
            sql_command("SHOW INDICES ON users"),
            SqlCommand::Select(TableQuery { table, filter: Some(_), .. }) if table == "red.show_indexes"
        ));
        assert!(matches!(
            sql_command("SHOW POLICIES ON users WHERE action = 'SELECT'"),
            SqlCommand::Select(TableQuery { table, filter: Some(_), .. }) if table == "red.policies"
        ));
        assert!(matches!(
            sql_command("SHOW STATS 'users' WHERE rows > 0"),
            SqlCommand::Select(TableQuery { table, filter: Some(_), .. }) if table == "red.stats"
        ));
        assert!(matches!(
            sql_command("SHOW SAMPLE users"),
            SqlCommand::Select(TableQuery { table, limit: Some(10), .. }) if table == "users"
        ));
        assert!(matches!(
            sql_command("DESC public.users"),
            SqlCommand::Select(TableQuery { table, filter: Some(_), .. }) if table == "red.describe"
        ));
        assert!(
            sql_command_result("CREATE VIEW v WITH RETENTION 1 h AS SELECT * FROM users").is_err()
        );
        assert!(sql_command_result("CREATE TABLE bad WITH ANALYTICS (centrality)").is_err());
        assert!(sql_command_result("BEGIN ISOLATION LEVEL SERIALIZABLE").is_err());
        assert!(sql_command_result("EVENTS BACKFILL STATUS users").is_err());
    }

    #[test]
    fn parse_sql_command_covers_remaining_catalog_and_copy_shapes() {
        for input in [
            "SHOW VECTORS",
            "SHOW DOCUMENTS",
            "SHOW TIMESERIES",
            "SHOW GRAPHS",
            "SHOW CONFIGS",
            "SHOW VAULTS",
            "SHOW KV",
            "SHOW SCHEMA public.users",
        ] {
            assert!(
                matches!(sql_command(input), SqlCommand::Select(_)),
                "{input}"
            );
        }

        for input in [
            "TRUNCATE TABLE users",
            "TRUNCATE GRAPH identity",
            "TRUNCATE DOCUMENT docs",
            "TRUNCATE TIMESERIES metrics",
            "TRUNCATE METRICS metrics",
            "TRUNCATE KV settings",
            "TRUNCATE QUEUE tasks",
            "TRUNCATE COLLECTION docs",
        ] {
            assert!(
                matches!(sql_command(input), SqlCommand::Truncate(_)),
                "{input}"
            );
        }
        assert!(sql_command_result("TRUNCATE UNKNOWN users").is_err());

        let SqlCommand::CopyFrom(copy) = sql_command("COPY users FROM '/tmp/u.csv' WITH (HEADER)")
        else {
            panic!("expected COPY");
        };
        assert!(copy.has_header);
        assert_eq!(copy.delimiter, None);

        let SqlCommand::CopyFrom(copy) =
            sql_command("COPY users FROM '/tmp/u.csv' WITH (HEADER = false)")
        else {
            panic!("expected COPY");
        };
        assert!(!copy.has_header);

        let SqlCommand::CopyFrom(copy) =
            sql_command("COPY users FROM '/tmp/u.csv' DELIMITER '|' HEADER")
        else {
            panic!("expected COPY");
        };
        assert_eq!(copy.delimiter, Some('|'));
        assert!(copy.has_header);
    }

    #[test]
    fn parse_sql_command_covers_remaining_ranking_and_event_errors() {
        assert!(matches!(
            expr("APPROXIMATE RANK OF 9 IN page_rank"),
            QueryExpr::ApproxRankOf(RankOfQuery { ranking, entity_id })
                if ranking == "page_rank" && entity_id == 9
        ));
        assert!(parse_frontend("APPROX OF 7 IN page_rank").is_err());
        assert!(parse_frontend("RANK 1 IN page_rank").is_err());
        assert!(parse_frontend("RANK RANGE 0 TO 3 IN page_rank").is_err());
        assert!(parse_frontend("ZRANK page_rank -1").is_err());
        assert!(parse_frontend("ZRANGE page_rank 3 1").is_err());

        let QueryExpr::Table(query) = expr("EVENTS STATUS 'users' WHERE active = true") else {
            panic!("EVENTS STATUS should accept a quoted collection");
        };
        assert_eq!(query.table, "red.subscriptions");
        assert!(query.filter.is_some());
        assert!(query.where_expr.is_some());

        let QueryExpr::EventsBackfill(query) = expr("EVENTS BACKFILL users TO audit") else {
            panic!("EVENTS BACKFILL should allow omitted filter and limit");
        };
        assert_eq!(query.collection, "users");
        assert_eq!(query.where_filter, None);
        assert_eq!(query.limit, None);

        assert!(parse_frontend("EVENTS BACKFILL users WHERE TO audit").is_err());
    }

    #[test]
    fn parse_sql_command_covers_analytics_non_goal_rejections() {
        for head in ["ANALYTICS", "EVENT", "COHORT", "FUNNEL", "SLA", "ADAPTER"] {
            let err = sql_command_result(&format!("CREATE {head} demo"))
                .expect_err("analytics v0 non-goal should be rejected");
            assert!(err.to_string().contains(&format!("CREATE {head}")), "{err}");
        }
    }

    #[test]
    fn parse_sql_command_covers_transaction_isolation_edges() {
        for input in [
            "BEGIN ISOLATION LEVEL READ UNCOMMITTED",
            "BEGIN ISOLATION LEVEL READ COMMITTED",
            "BEGIN ISOLATION LEVEL REPEATABLE READ",
            "START TRANSACTION ISOLATION LEVEL SNAPSHOT",
        ] {
            assert!(
                matches!(
                    sql_command(input),
                    SqlCommand::TransactionControl(TxnControl::Begin)
                ),
                "{input}"
            );
        }

        assert!(sql_command_result("BEGIN ISOLATION LEVEL READ").is_err());
        assert!(sql_command_result("BEGIN ISOLATION LEVEL REPEATABLE").is_err());
        assert!(sql_command_result("BEGIN ISOLATION LEVEL CHAOS").is_err());
    }

    #[test]
    fn parse_sql_command_covers_iam_and_hypertable_dispatch_edges() {
        assert!(matches!(
            expr("CREATE HYPERTABLE metrics TIME_COLUMN ts CHUNK_INTERVAL '1d'"),
            QueryExpr::CreateTimeSeries(query)
                if query.name == "metrics" && query.hypertable.is_some()
        ));
        assert!(sql_command_result("CREATE OR TABLE bad (id INT)").is_err());
        assert!(sql_command_result("DROP MATERIALIZED TABLE bad").is_err());

        assert!(matches!(
            expr("ATTACH POLICY 'readonly' TO USER tenant1.alice"),
            QueryExpr::AttachPolicy { policy_id, .. } if policy_id == "readonly"
        ));
        assert!(matches!(
            expr("DETACH POLICY 'readonly' FROM GROUP analysts"),
            QueryExpr::DetachPolicy { policy_id, .. } if policy_id == "readonly"
        ));
        assert!(matches!(
            expr("SHOW POLICIES FOR USER alice"),
            QueryExpr::ShowPolicies { filter: Some(_) }
        ));
        assert!(matches!(
            expr("SHOW EFFECTIVE PERMISSIONS FOR alice"),
            QueryExpr::ShowEffectivePermissions { resource: None, .. }
        ));
        assert!(matches!(
            expr("SIMULATE alice ACTION 'iam:PassRole' ON TABLE:public.orders"),
            QueryExpr::SimulatePolicy { action, .. } if action == "iam:PassRole"
        ));
        assert!(matches!(
            expr("LINT POLICY JSON '{\"Statement\":[]}'"),
            QueryExpr::LintPolicy { .. }
        ));
        assert!(matches!(
            expr("MIGRATE POLICY MODE TO 'policy_only' DRY RUN"),
            QueryExpr::MigratePolicyMode {
                target,
                dry_run: true,
            } if target == "policy_only"
        ));
        assert!(parse_frontend("MIGRATE OTHER").is_err());
    }

    #[test]
    fn parse_frontend_rejects_trailing_tokens() {
        let err = parse_frontend("SET TENANT 'acme' junk")
            .expect_err("parse_frontend should reject trailing tokens");
        assert!(
            err.to_string().contains("Unexpected token after query"),
            "{err}"
        );
    }
}

fn add_table_filter(query: &mut TableQuery, filter: Filter) {
    let combined = match query.filter.take() {
        Some(existing) => existing.and(filter),
        None => filter,
    };
    query.where_expr = Some(filter_to_expr(&combined));
    query.filter = Some(combined);
}

fn parse_show_collections_by_model(
    parser: &mut Parser<'_>,
    model: &str,
) -> Result<TableQuery, ParseError> {
    let mut query = TableQuery::new("red.collections");
    parser.parse_table_clauses(&mut query)?;
    add_table_filter(&mut query, collection_model_filter(model));
    Ok(query)
}

#[derive(Debug, Clone)]
#[allow(clippy::large_enum_variant)]
pub enum SqlQuery {
    Select(TableQuery),
    Join(JoinQuery),
}

#[derive(Debug, Clone)]
pub enum SqlMutation {
    Insert(InsertQuery),
    Update(UpdateQuery),
    Delete(DeleteQuery),
}

#[derive(Debug, Clone)]
pub enum SqlSchemaCommand {
    ExplainAlter(ExplainAlterQuery),
    CreateTable(CreateTableQuery),
    CreateCollection(CreateCollectionQuery),
    CreateVector(CreateVectorQuery),
    DropTable(DropTableQuery),
    DropGraph(DropGraphQuery),
    DropVector(DropVectorQuery),
    DropDocument(DropDocumentQuery),
    DropKv(DropKvQuery),
    DropCollection(DropCollectionQuery),
    Truncate(TruncateQuery),
    AlterTable(AlterTableQuery),
    CreateIndex(CreateIndexQuery),
    DropIndex(DropIndexQuery),
    CreateTimeSeries(CreateTimeSeriesQuery),
    CreateMetric(CreateMetricQuery),
    AlterMetric(AlterMetricQuery),
    CreateSlo(CreateSloQuery),
    DropTimeSeries(DropTimeSeriesQuery),
    CreateQueue(CreateQueueQuery),
    AlterQueue(AlterQueueQuery),
    DropQueue(DropQueueQuery),
    CreateTree(CreateTreeQuery),
    DropTree(DropTreeQuery),
    Probabilistic(ProbabilisticCommand),
    CreateSchema(CreateSchemaQuery),
    DropSchema(DropSchemaQuery),
    CreateSequence(CreateSequenceQuery),
    DropSequence(DropSequenceQuery),
    CopyFrom(CopyFromQuery),
    CreateView(CreateViewQuery),
    DropView(DropViewQuery),
    RefreshMaterializedView(RefreshMaterializedViewQuery),
    CreatePolicy(CreatePolicyQuery),
    DropPolicy(DropPolicyQuery),
    CreateServer(CreateServerQuery),
    DropServer(DropServerQuery),
    CreateForeignTable(CreateForeignTableQuery),
    DropForeignTable(DropForeignTableQuery),
    CreateMigration(CreateMigrationQuery),
    ApplyMigration(ApplyMigrationQuery),
    RollbackMigration(RollbackMigrationQuery),
    ExplainMigration(ExplainMigrationQuery),
}

#[derive(Debug, Clone)]
#[allow(clippy::large_enum_variant)]
pub enum SqlAdminCommand {
    SetConfig {
        key: String,
        value: Value,
    },
    ShowConfig {
        prefix: Option<String>,
        as_json: bool,
    },
    SetSecret {
        key: String,
        value: Value,
    },
    DeleteSecret {
        key: String,
    },
    ShowSecrets {
        prefix: Option<String>,
    },
    SetTenant(Option<String>),
    ShowTenant,
    TransactionControl(TxnControl),
    Maintenance(MaintenanceCommand),
    Grant(GrantStmt),
    Revoke(RevokeStmt),
    AlterUser(AlterUserStmt),
    CreateUser(CreateUserStmt),
    IamPolicy(QueryExpr),
}

impl SqlStatement {
    pub fn into_command(self) -> SqlCommand {
        match self {
            SqlStatement::Query(SqlQuery::Select(query)) => SqlCommand::Select(query),
            SqlStatement::Query(SqlQuery::Join(query)) => SqlCommand::Join(query),
            SqlStatement::Mutation(SqlMutation::Insert(query)) => SqlCommand::Insert(query),
            SqlStatement::Mutation(SqlMutation::Update(query)) => SqlCommand::Update(query),
            SqlStatement::Mutation(SqlMutation::Delete(query)) => SqlCommand::Delete(query),
            SqlStatement::Schema(SqlSchemaCommand::ExplainAlter(query)) => {
                SqlCommand::ExplainAlter(query)
            }
            SqlStatement::Schema(SqlSchemaCommand::CreateTable(query)) => {
                SqlCommand::CreateTable(query)
            }
            SqlStatement::Schema(SqlSchemaCommand::CreateCollection(query)) => {
                SqlCommand::CreateCollection(query)
            }
            SqlStatement::Schema(SqlSchemaCommand::CreateVector(query)) => {
                SqlCommand::CreateVector(query)
            }
            SqlStatement::Schema(SqlSchemaCommand::DropTable(query)) => {
                SqlCommand::DropTable(query)
            }
            SqlStatement::Schema(SqlSchemaCommand::DropGraph(query)) => {
                SqlCommand::DropGraph(query)
            }
            SqlStatement::Schema(SqlSchemaCommand::DropVector(query)) => {
                SqlCommand::DropVector(query)
            }
            SqlStatement::Schema(SqlSchemaCommand::DropDocument(query)) => {
                SqlCommand::DropDocument(query)
            }
            SqlStatement::Schema(SqlSchemaCommand::DropKv(query)) => SqlCommand::DropKv(query),
            SqlStatement::Schema(SqlSchemaCommand::DropCollection(query)) => {
                SqlCommand::DropCollection(query)
            }
            SqlStatement::Schema(SqlSchemaCommand::Truncate(query)) => SqlCommand::Truncate(query),
            SqlStatement::Schema(SqlSchemaCommand::AlterTable(query)) => {
                SqlCommand::AlterTable(query)
            }
            SqlStatement::Schema(SqlSchemaCommand::CreateIndex(query)) => {
                SqlCommand::CreateIndex(query)
            }
            SqlStatement::Schema(SqlSchemaCommand::DropIndex(query)) => {
                SqlCommand::DropIndex(query)
            }
            SqlStatement::Schema(SqlSchemaCommand::CreateTimeSeries(query)) => {
                SqlCommand::CreateTimeSeries(query)
            }
            SqlStatement::Schema(SqlSchemaCommand::CreateMetric(query)) => {
                SqlCommand::CreateMetric(query)
            }
            SqlStatement::Schema(SqlSchemaCommand::AlterMetric(query)) => {
                SqlCommand::AlterMetric(query)
            }
            SqlStatement::Schema(SqlSchemaCommand::CreateSlo(query)) => {
                SqlCommand::CreateSlo(query)
            }
            SqlStatement::Schema(SqlSchemaCommand::DropTimeSeries(query)) => {
                SqlCommand::DropTimeSeries(query)
            }
            SqlStatement::Schema(SqlSchemaCommand::CreateQueue(query)) => {
                SqlCommand::CreateQueue(query)
            }
            SqlStatement::Schema(SqlSchemaCommand::AlterQueue(query)) => {
                SqlCommand::AlterQueue(query)
            }
            SqlStatement::Schema(SqlSchemaCommand::DropQueue(query)) => {
                SqlCommand::DropQueue(query)
            }
            SqlStatement::Schema(SqlSchemaCommand::CreateTree(query)) => {
                SqlCommand::CreateTree(query)
            }
            SqlStatement::Schema(SqlSchemaCommand::DropTree(query)) => SqlCommand::DropTree(query),
            SqlStatement::Schema(SqlSchemaCommand::Probabilistic(command)) => {
                SqlCommand::Probabilistic(command)
            }
            SqlStatement::Admin(SqlAdminCommand::SetConfig { key, value }) => {
                SqlCommand::SetConfig { key, value }
            }
            SqlStatement::Admin(SqlAdminCommand::ShowConfig { prefix, as_json }) => {
                SqlCommand::ShowConfig { prefix, as_json }
            }
            SqlStatement::Admin(SqlAdminCommand::SetSecret { key, value }) => {
                SqlCommand::SetSecret { key, value }
            }
            SqlStatement::Admin(SqlAdminCommand::DeleteSecret { key }) => {
                SqlCommand::DeleteSecret { key }
            }
            SqlStatement::Admin(SqlAdminCommand::ShowSecrets { prefix }) => {
                SqlCommand::ShowSecrets { prefix }
            }
            SqlStatement::Admin(SqlAdminCommand::SetTenant(value)) => SqlCommand::SetTenant(value),
            SqlStatement::Admin(SqlAdminCommand::ShowTenant) => SqlCommand::ShowTenant,
            SqlStatement::Admin(SqlAdminCommand::TransactionControl(ctl)) => {
                SqlCommand::TransactionControl(ctl)
            }
            SqlStatement::Admin(SqlAdminCommand::Maintenance(cmd)) => SqlCommand::Maintenance(cmd),
            SqlStatement::Schema(SqlSchemaCommand::CreateSchema(q)) => SqlCommand::CreateSchema(q),
            SqlStatement::Schema(SqlSchemaCommand::DropSchema(q)) => SqlCommand::DropSchema(q),
            SqlStatement::Schema(SqlSchemaCommand::CreateSequence(q)) => {
                SqlCommand::CreateSequence(q)
            }
            SqlStatement::Schema(SqlSchemaCommand::DropSequence(q)) => SqlCommand::DropSequence(q),
            SqlStatement::Schema(SqlSchemaCommand::CopyFrom(q)) => SqlCommand::CopyFrom(q),
            SqlStatement::Schema(SqlSchemaCommand::CreateView(q)) => SqlCommand::CreateView(q),
            SqlStatement::Schema(SqlSchemaCommand::DropView(q)) => SqlCommand::DropView(q),
            SqlStatement::Schema(SqlSchemaCommand::RefreshMaterializedView(q)) => {
                SqlCommand::RefreshMaterializedView(q)
            }
            SqlStatement::Schema(SqlSchemaCommand::CreatePolicy(q)) => SqlCommand::CreatePolicy(q),
            SqlStatement::Schema(SqlSchemaCommand::DropPolicy(q)) => SqlCommand::DropPolicy(q),
            SqlStatement::Schema(SqlSchemaCommand::CreateServer(q)) => SqlCommand::CreateServer(q),
            SqlStatement::Schema(SqlSchemaCommand::DropServer(q)) => SqlCommand::DropServer(q),
            SqlStatement::Schema(SqlSchemaCommand::CreateForeignTable(q)) => {
                SqlCommand::CreateForeignTable(q)
            }
            SqlStatement::Schema(SqlSchemaCommand::DropForeignTable(q)) => {
                SqlCommand::DropForeignTable(q)
            }
            SqlStatement::Admin(SqlAdminCommand::Grant(s)) => SqlCommand::Grant(s),
            SqlStatement::Admin(SqlAdminCommand::Revoke(s)) => SqlCommand::Revoke(s),
            SqlStatement::Admin(SqlAdminCommand::AlterUser(s)) => SqlCommand::AlterUser(s),
            SqlStatement::Admin(SqlAdminCommand::CreateUser(s)) => SqlCommand::CreateUser(s),
            SqlStatement::Admin(SqlAdminCommand::IamPolicy(e)) => SqlCommand::IamPolicy(e),
            SqlStatement::Schema(SqlSchemaCommand::CreateMigration(q)) => {
                SqlCommand::CreateMigration(q)
            }
            SqlStatement::Schema(SqlSchemaCommand::ApplyMigration(q)) => {
                SqlCommand::ApplyMigration(q)
            }
            SqlStatement::Schema(SqlSchemaCommand::RollbackMigration(q)) => {
                SqlCommand::RollbackMigration(q)
            }
            SqlStatement::Schema(SqlSchemaCommand::ExplainMigration(q)) => {
                SqlCommand::ExplainMigration(q)
            }
        }
    }

    pub fn into_query_expr(self) -> QueryExpr {
        self.into_command().into_query_expr()
    }
}

impl FrontendStatement {
    pub fn into_query_expr(self) -> QueryExpr {
        match self {
            FrontendStatement::Sql(statement) => statement.into_query_expr(),
            FrontendStatement::Graph(query) => QueryExpr::Graph(query),
            FrontendStatement::GraphCommand(command) => QueryExpr::GraphCommand(command),
            FrontendStatement::Path(query) => QueryExpr::Path(query),
            FrontendStatement::Vector(query) => QueryExpr::Vector(query),
            FrontendStatement::Hybrid(query) => QueryExpr::Hybrid(query),
            FrontendStatement::Search(command) => QueryExpr::SearchCommand(command),
            FrontendStatement::Ask(query) => QueryExpr::Ask(query),
            FrontendStatement::QueueSelect(query) => QueryExpr::QueueSelect(query),
            FrontendStatement::QueueCommand(command) => QueryExpr::QueueCommand(command),
            FrontendStatement::EventsBackfill(query) => QueryExpr::EventsBackfill(query),
            FrontendStatement::EventsBackfillStatus { collection } => {
                QueryExpr::EventsBackfillStatus { collection }
            }
            FrontendStatement::TreeCommand(command) => QueryExpr::TreeCommand(command),
            FrontendStatement::ProbabilisticCommand(command) => {
                QueryExpr::ProbabilisticCommand(command)
            }
            FrontendStatement::KvCommand(command) => QueryExpr::KvCommand(command),
            FrontendStatement::ConfigCommand(command) => QueryExpr::ConfigCommand(command),
            FrontendStatement::Ranking(expr) => expr,
        }
    }
}

pub fn parse_frontend(input: &str) -> Result<FrontendStatement, ParseError> {
    let mut parser = Parser::new(input)?;
    let statement = parser.parse_frontend_statement()?;
    if !parser.check(&Token::Eof) {
        return Err(ParseError::new(
            // F-05: `Token::Ident` / `Token::String` / `Token::JsonLiteral`
            // Display arms emit raw user bytes. Render via `{:?}` so
            // embedded CR/LF/NUL/quotes are escaped before the message
            // reaches downstream JSON / audit / log / gRPC sinks.
            format!("Unexpected token after query: {:?}", parser.current.token),
            parser.position(),
        ));
    }
    Ok(statement)
}

impl SqlCommand {
    pub fn into_query_expr(self) -> QueryExpr {
        match self {
            SqlCommand::Select(query) => QueryExpr::Table(query),
            SqlCommand::Join(query) => QueryExpr::Join(query),
            SqlCommand::Insert(query) => QueryExpr::Insert(query),
            SqlCommand::Update(query) => QueryExpr::Update(query),
            SqlCommand::Delete(query) => QueryExpr::Delete(query),
            SqlCommand::ExplainAlter(query) => QueryExpr::ExplainAlter(query),
            SqlCommand::CreateTable(query) => QueryExpr::CreateTable(query),
            SqlCommand::CreateCollection(query) => QueryExpr::CreateCollection(query),
            SqlCommand::CreateVector(query) => QueryExpr::CreateVector(query),
            SqlCommand::DropTable(query) => QueryExpr::DropTable(query),
            SqlCommand::DropGraph(query) => QueryExpr::DropGraph(query),
            SqlCommand::DropVector(query) => QueryExpr::DropVector(query),
            SqlCommand::DropDocument(query) => QueryExpr::DropDocument(query),
            SqlCommand::DropKv(query) => QueryExpr::DropKv(query),
            SqlCommand::DropCollection(query) => QueryExpr::DropCollection(query),
            SqlCommand::Truncate(query) => QueryExpr::Truncate(query),
            SqlCommand::AlterTable(query) => QueryExpr::AlterTable(query),
            SqlCommand::CreateIndex(query) => QueryExpr::CreateIndex(query),
            SqlCommand::DropIndex(query) => QueryExpr::DropIndex(query),
            SqlCommand::CreateTimeSeries(query) => QueryExpr::CreateTimeSeries(query),
            SqlCommand::CreateMetric(query) => QueryExpr::CreateMetric(query),
            SqlCommand::AlterMetric(query) => QueryExpr::AlterMetric(query),
            SqlCommand::CreateSlo(query) => QueryExpr::CreateSlo(query),
            SqlCommand::DropTimeSeries(query) => QueryExpr::DropTimeSeries(query),
            SqlCommand::CreateQueue(query) => QueryExpr::CreateQueue(query),
            SqlCommand::AlterQueue(query) => QueryExpr::AlterQueue(query),
            SqlCommand::DropQueue(query) => QueryExpr::DropQueue(query),
            SqlCommand::CreateTree(query) => QueryExpr::CreateTree(query),
            SqlCommand::DropTree(query) => QueryExpr::DropTree(query),
            SqlCommand::Probabilistic(command) => QueryExpr::ProbabilisticCommand(command),
            SqlCommand::SetConfig { key, value } => QueryExpr::SetConfig { key, value },
            SqlCommand::ShowConfig { prefix, as_json } => QueryExpr::ShowConfig { prefix, as_json },
            SqlCommand::SetSecret { key, value } => QueryExpr::SetSecret { key, value },
            SqlCommand::DeleteSecret { key } => QueryExpr::DeleteSecret { key },
            SqlCommand::ShowSecrets { prefix } => QueryExpr::ShowSecrets { prefix },
            SqlCommand::SetTenant(value) => QueryExpr::SetTenant(value),
            SqlCommand::ShowTenant => QueryExpr::ShowTenant,
            SqlCommand::TransactionControl(ctl) => QueryExpr::TransactionControl(ctl),
            SqlCommand::Maintenance(cmd) => QueryExpr::MaintenanceCommand(cmd),
            SqlCommand::CreateSchema(q) => QueryExpr::CreateSchema(q),
            SqlCommand::DropSchema(q) => QueryExpr::DropSchema(q),
            SqlCommand::CreateSequence(q) => QueryExpr::CreateSequence(q),
            SqlCommand::DropSequence(q) => QueryExpr::DropSequence(q),
            SqlCommand::CopyFrom(q) => QueryExpr::CopyFrom(q),
            SqlCommand::CreateView(q) => QueryExpr::CreateView(q),
            SqlCommand::DropView(q) => QueryExpr::DropView(q),
            SqlCommand::RefreshMaterializedView(q) => QueryExpr::RefreshMaterializedView(q),
            SqlCommand::CreatePolicy(q) => QueryExpr::CreatePolicy(q),
            SqlCommand::DropPolicy(q) => QueryExpr::DropPolicy(q),
            SqlCommand::CreateServer(q) => QueryExpr::CreateServer(q),
            SqlCommand::DropServer(q) => QueryExpr::DropServer(q),
            SqlCommand::CreateForeignTable(q) => QueryExpr::CreateForeignTable(q),
            SqlCommand::DropForeignTable(q) => QueryExpr::DropForeignTable(q),
            SqlCommand::Grant(s) => QueryExpr::Grant(s),
            SqlCommand::Revoke(s) => QueryExpr::Revoke(s),
            SqlCommand::AlterUser(s) => QueryExpr::AlterUser(s),
            SqlCommand::CreateUser(s) => QueryExpr::CreateUser(s),
            SqlCommand::IamPolicy(e) => e,
            SqlCommand::CreateMigration(q) => QueryExpr::CreateMigration(q),
            SqlCommand::ApplyMigration(q) => QueryExpr::ApplyMigration(q),
            SqlCommand::RollbackMigration(q) => QueryExpr::RollbackMigration(q),
            SqlCommand::ExplainMigration(q) => QueryExpr::ExplainMigration(q),
        }
    }

    pub fn into_statement(self) -> SqlStatement {
        match self {
            SqlCommand::Select(query) => SqlStatement::Query(SqlQuery::Select(query)),
            SqlCommand::Join(query) => SqlStatement::Query(SqlQuery::Join(query)),
            SqlCommand::Insert(query) => SqlStatement::Mutation(SqlMutation::Insert(query)),
            SqlCommand::Update(query) => SqlStatement::Mutation(SqlMutation::Update(query)),
            SqlCommand::Delete(query) => SqlStatement::Mutation(SqlMutation::Delete(query)),
            SqlCommand::ExplainAlter(query) => {
                SqlStatement::Schema(SqlSchemaCommand::ExplainAlter(query))
            }
            SqlCommand::CreateTable(query) => {
                SqlStatement::Schema(SqlSchemaCommand::CreateTable(query))
            }
            SqlCommand::CreateCollection(query) => {
                SqlStatement::Schema(SqlSchemaCommand::CreateCollection(query))
            }
            SqlCommand::CreateVector(query) => {
                SqlStatement::Schema(SqlSchemaCommand::CreateVector(query))
            }
            SqlCommand::DropTable(query) => {
                SqlStatement::Schema(SqlSchemaCommand::DropTable(query))
            }
            SqlCommand::DropGraph(query) => {
                SqlStatement::Schema(SqlSchemaCommand::DropGraph(query))
            }
            SqlCommand::DropVector(query) => {
                SqlStatement::Schema(SqlSchemaCommand::DropVector(query))
            }
            SqlCommand::DropDocument(query) => {
                SqlStatement::Schema(SqlSchemaCommand::DropDocument(query))
            }
            SqlCommand::DropKv(query) => SqlStatement::Schema(SqlSchemaCommand::DropKv(query)),
            SqlCommand::DropCollection(query) => {
                SqlStatement::Schema(SqlSchemaCommand::DropCollection(query))
            }
            SqlCommand::Truncate(query) => SqlStatement::Schema(SqlSchemaCommand::Truncate(query)),
            SqlCommand::AlterTable(query) => {
                SqlStatement::Schema(SqlSchemaCommand::AlterTable(query))
            }
            SqlCommand::CreateIndex(query) => {
                SqlStatement::Schema(SqlSchemaCommand::CreateIndex(query))
            }
            SqlCommand::DropIndex(query) => {
                SqlStatement::Schema(SqlSchemaCommand::DropIndex(query))
            }
            SqlCommand::CreateTimeSeries(query) => {
                SqlStatement::Schema(SqlSchemaCommand::CreateTimeSeries(query))
            }
            SqlCommand::CreateMetric(query) => {
                SqlStatement::Schema(SqlSchemaCommand::CreateMetric(query))
            }
            SqlCommand::AlterMetric(query) => {
                SqlStatement::Schema(SqlSchemaCommand::AlterMetric(query))
            }
            SqlCommand::CreateSlo(query) => {
                SqlStatement::Schema(SqlSchemaCommand::CreateSlo(query))
            }
            SqlCommand::DropTimeSeries(query) => {
                SqlStatement::Schema(SqlSchemaCommand::DropTimeSeries(query))
            }
            SqlCommand::CreateQueue(query) => {
                SqlStatement::Schema(SqlSchemaCommand::CreateQueue(query))
            }
            SqlCommand::AlterQueue(query) => {
                SqlStatement::Schema(SqlSchemaCommand::AlterQueue(query))
            }
            SqlCommand::DropQueue(query) => {
                SqlStatement::Schema(SqlSchemaCommand::DropQueue(query))
            }
            SqlCommand::CreateTree(query) => {
                SqlStatement::Schema(SqlSchemaCommand::CreateTree(query))
            }
            SqlCommand::DropTree(query) => SqlStatement::Schema(SqlSchemaCommand::DropTree(query)),
            SqlCommand::Probabilistic(command) => {
                SqlStatement::Schema(SqlSchemaCommand::Probabilistic(command))
            }
            SqlCommand::SetConfig { key, value } => {
                SqlStatement::Admin(SqlAdminCommand::SetConfig { key, value })
            }
            SqlCommand::ShowConfig { prefix, as_json } => {
                SqlStatement::Admin(SqlAdminCommand::ShowConfig { prefix, as_json })
            }
            SqlCommand::SetSecret { key, value } => {
                SqlStatement::Admin(SqlAdminCommand::SetSecret { key, value })
            }
            SqlCommand::DeleteSecret { key } => {
                SqlStatement::Admin(SqlAdminCommand::DeleteSecret { key })
            }
            SqlCommand::ShowSecrets { prefix } => {
                SqlStatement::Admin(SqlAdminCommand::ShowSecrets { prefix })
            }
            SqlCommand::SetTenant(value) => SqlStatement::Admin(SqlAdminCommand::SetTenant(value)),
            SqlCommand::ShowTenant => SqlStatement::Admin(SqlAdminCommand::ShowTenant),
            SqlCommand::TransactionControl(ctl) => {
                SqlStatement::Admin(SqlAdminCommand::TransactionControl(ctl))
            }
            SqlCommand::Maintenance(cmd) => SqlStatement::Admin(SqlAdminCommand::Maintenance(cmd)),
            SqlCommand::CreateSchema(q) => SqlStatement::Schema(SqlSchemaCommand::CreateSchema(q)),
            SqlCommand::DropSchema(q) => SqlStatement::Schema(SqlSchemaCommand::DropSchema(q)),
            SqlCommand::CreateSequence(q) => {
                SqlStatement::Schema(SqlSchemaCommand::CreateSequence(q))
            }
            SqlCommand::DropSequence(q) => SqlStatement::Schema(SqlSchemaCommand::DropSequence(q)),
            SqlCommand::CopyFrom(q) => SqlStatement::Schema(SqlSchemaCommand::CopyFrom(q)),
            SqlCommand::CreateView(q) => SqlStatement::Schema(SqlSchemaCommand::CreateView(q)),
            SqlCommand::DropView(q) => SqlStatement::Schema(SqlSchemaCommand::DropView(q)),
            SqlCommand::RefreshMaterializedView(q) => {
                SqlStatement::Schema(SqlSchemaCommand::RefreshMaterializedView(q))
            }
            SqlCommand::CreatePolicy(q) => SqlStatement::Schema(SqlSchemaCommand::CreatePolicy(q)),
            SqlCommand::DropPolicy(q) => SqlStatement::Schema(SqlSchemaCommand::DropPolicy(q)),
            SqlCommand::CreateServer(q) => SqlStatement::Schema(SqlSchemaCommand::CreateServer(q)),
            SqlCommand::DropServer(q) => SqlStatement::Schema(SqlSchemaCommand::DropServer(q)),
            SqlCommand::CreateForeignTable(q) => {
                SqlStatement::Schema(SqlSchemaCommand::CreateForeignTable(q))
            }
            SqlCommand::DropForeignTable(q) => {
                SqlStatement::Schema(SqlSchemaCommand::DropForeignTable(q))
            }
            SqlCommand::Grant(s) => SqlStatement::Admin(SqlAdminCommand::Grant(s)),
            SqlCommand::Revoke(s) => SqlStatement::Admin(SqlAdminCommand::Revoke(s)),
            SqlCommand::AlterUser(s) => SqlStatement::Admin(SqlAdminCommand::AlterUser(s)),
            SqlCommand::CreateUser(s) => SqlStatement::Admin(SqlAdminCommand::CreateUser(s)),
            SqlCommand::IamPolicy(e) => SqlStatement::Admin(SqlAdminCommand::IamPolicy(e)),
            SqlCommand::CreateMigration(q) => {
                SqlStatement::Schema(SqlSchemaCommand::CreateMigration(q))
            }
            SqlCommand::ApplyMigration(q) => {
                SqlStatement::Schema(SqlSchemaCommand::ApplyMigration(q))
            }
            SqlCommand::RollbackMigration(q) => {
                SqlStatement::Schema(SqlSchemaCommand::RollbackMigration(q))
            }
            SqlCommand::ExplainMigration(q) => {
                SqlStatement::Schema(SqlSchemaCommand::ExplainMigration(q))
            }
        }
    }
}

impl<'a> Parser<'a> {
    fn parse_events_command(&mut self) -> Result<QueryExpr, ParseError> {
        self.expect_ident()?; // EVENTS
        if self.consume_ident_ci("STATUS")? {
            let mut query = TableQuery::new("red.subscriptions");
            let collection = match self.peek().clone() {
                Token::Ident(name) => {
                    self.advance()?;
                    Some(name)
                }
                Token::String(name) => {
                    self.advance()?;
                    Some(name)
                }
                _ => None,
            };
            self.parse_table_clauses(&mut query)?;
            if let Some(collection) = collection {
                let filter = Filter::compare(
                    FieldRef::column("red.subscriptions", "collection"),
                    CompareOp::Eq,
                    Value::text(collection),
                );
                let expr = filter_to_expr(&filter);
                query.where_expr = Some(match query.where_expr.take() {
                    Some(existing) => Expr::binop(BinOp::And, existing, expr),
                    None => expr,
                });
                query.filter = Some(match query.filter.take() {
                    Some(existing) => existing.and(filter),
                    None => filter,
                });
            }
            return Ok(QueryExpr::Table(query));
        }

        if !self.consume_ident_ci("BACKFILL")? {
            return Err(ParseError::expected(
                vec!["BACKFILL", "STATUS"],
                self.peek(),
                self.position(),
            ));
        }

        if self.consume_ident_ci("STATUS")? {
            let collection = self.expect_ident()?;
            return Ok(QueryExpr::EventsBackfillStatus { collection });
        }

        let collection = self.expect_ident()?;
        let where_filter = if self.consume(&Token::Where)? {
            let mut parts = Vec::new();
            while !self.check(&Token::Eof) && !self.check(&Token::To) {
                parts.push(self.peek().to_string());
                self.advance()?;
            }
            if parts.is_empty() {
                return Err(ParseError::expected(
                    vec!["predicate"],
                    self.peek(),
                    self.position(),
                ));
            }
            Some(parts.join(" "))
        } else {
            None
        };

        self.expect(Token::To)?;
        let target_queue = self.expect_ident()?;
        let limit = if self.consume(&Token::Limit)? {
            Some(self.parse_positive_integer("LIMIT")? as u64)
        } else {
            None
        };

        Ok(QueryExpr::EventsBackfill(EventsBackfillQuery {
            collection,
            where_filter,
            target_queue,
            limit,
        }))
    }

    /// Parse an optional `OPTIONS (key 'value', key2 'value2', ...)` clause
    /// used by Phase 3.2 FDW DDL statements. Returns an empty vec when the
    /// clause is absent. Values are always single-quoted string literals —
    /// consistent with PG's generic-options model.
    pub(crate) fn parse_fdw_options_clause(&mut self) -> Result<Vec<(String, String)>, ParseError> {
        if !self.consume(&Token::Options)? {
            return Ok(Vec::new());
        }
        self.expect(Token::LParen)?;
        let mut out: Vec<(String, String)> = Vec::new();
        loop {
            // Option keys frequently collide with reserved words
            // (`path`, `format`, `delimiter`, `header`, …) — accept
            // the keyword form and lowercase it so downstream
            // option-name matching stays case-insensitive.
            let was_ident = matches!(self.peek(), Token::Ident(_));
            let raw = self.expect_ident_or_keyword()?;
            let key = if was_ident {
                raw
            } else {
                raw.to_ascii_lowercase()
            };
            // Value is a single-quoted string literal.
            let value = self.parse_string()?;
            out.push((key, value));
            if !self.consume(&Token::Comma)? {
                break;
            }
        }
        self.expect(Token::RParen)?;
        Ok(out)
    }

    /// Parse any top-level frontend statement through a single shared surface.
    pub fn parse_frontend_statement(&mut self) -> Result<FrontendStatement, ParseError> {
        match self.peek() {
            Token::Select => match self.parse_select_query()? {
                QueryExpr::Table(query) => Ok(FrontendStatement::Sql(SqlStatement::Query(
                    SqlQuery::Select(query),
                ))),
                QueryExpr::Join(query) => Ok(FrontendStatement::Sql(SqlStatement::Query(
                    SqlQuery::Join(query),
                ))),
                QueryExpr::QueueSelect(query) => Ok(FrontendStatement::QueueSelect(query)),
                other => Err(ParseError::new(
                    format!("internal: SELECT produced unexpected query kind {other:?}"),
                    self.position(),
                )),
            },
            Token::From
            | Token::Insert
            | Token::Update
            | Token::Truncate
            | Token::Create
            | Token::Drop
            | Token::Alter
            | Token::Set
            | Token::Begin
            | Token::Commit
            | Token::Rollback
            | Token::Savepoint
            | Token::Release
            | Token::Start
            | Token::Vacuum
            | Token::Analyze
            | Token::Copy
            | Token::Refresh => self.parse_sql_statement().map(FrontendStatement::Sql),
            Token::Explain => {
                if matches!(
                    self.peek_next()?,
                    Token::Ident(name) if name.eq_ignore_ascii_case("ASK")
                ) {
                    match self.parse_explain_ask_query()? {
                        QueryExpr::Ask(query) => Ok(FrontendStatement::Ask(query)),
                        other => Err(ParseError::new(
                            format!(
                                "internal: EXPLAIN ASK produced unexpected query kind {other:?}"
                            ),
                            self.position(),
                        )),
                    }
                } else {
                    self.parse_sql_statement().map(FrontendStatement::Sql)
                }
            }
            Token::Ident(name) if name.eq_ignore_ascii_case("SHOW") => {
                self.parse_sql_statement().map(FrontendStatement::Sql)
            }
            Token::Ident(name) if name.eq_ignore_ascii_case("RESET") => {
                self.parse_sql_statement().map(FrontendStatement::Sql)
            }
            Token::Ident(name)
                if name.eq_ignore_ascii_case("RANK")
                    || name.eq_ignore_ascii_case("APPROX")
                    || name.eq_ignore_ascii_case("APPROXIMATE")
                    || name.eq_ignore_ascii_case("ZRANK")
                    || name.eq_ignore_ascii_case("ZRANGE") =>
            {
                self.parse_ranking_read().map(FrontendStatement::Ranking)
            }
            Token::Desc => self.parse_sql_statement().map(FrontendStatement::Sql),
            Token::Ident(name)
                if name.eq_ignore_ascii_case("DESCRIBE") || name.eq_ignore_ascii_case("DESC") =>
            {
                self.parse_sql_statement().map(FrontendStatement::Sql)
            }
            Token::Ident(name)
                if name.eq_ignore_ascii_case("GRANT")
                    || name.eq_ignore_ascii_case("REVOKE")
                    || name.eq_ignore_ascii_case("SIMULATE")
                    || name.eq_ignore_ascii_case("LINT")
                    || name.eq_ignore_ascii_case("MIGRATE")
                    || name.eq_ignore_ascii_case("APPLY") =>
            {
                self.parse_sql_statement().map(FrontendStatement::Sql)
            }
            Token::Ident(name) if name.eq_ignore_ascii_case("WATCH") => {
                self.advance()?;
                if matches!(
                    self.peek(),
                    Token::Ident(name) if name.eq_ignore_ascii_case("CONFIG")
                ) {
                    match self.parse_config_watch_after_watch()? {
                        QueryExpr::ConfigCommand(command) => {
                            Ok(FrontendStatement::ConfigCommand(command))
                        }
                        other => Err(ParseError::new(
                            format!(
                                "internal: WATCH CONFIG produced unexpected query kind {other:?}"
                            ),
                            self.position(),
                        )),
                    }
                } else if matches!(
                    self.peek(),
                    Token::Ident(name) if name.eq_ignore_ascii_case("VAULT")
                ) {
                    match self.parse_vault_watch_after_watch()? {
                        QueryExpr::KvCommand(command) => Ok(FrontendStatement::KvCommand(command)),
                        other => Err(ParseError::new(
                            format!(
                                "internal: WATCH VAULT produced unexpected query kind {other:?}"
                            ),
                            self.position(),
                        )),
                    }
                } else {
                    match self.parse_kv_watch(reddb_types::catalog::CollectionModel::Kv)? {
                        QueryExpr::KvCommand(command) => Ok(FrontendStatement::KvCommand(command)),
                        other => Err(ParseError::new(
                            format!("internal: WATCH produced unexpected query kind {other:?}"),
                            self.position(),
                        )),
                    }
                }
            }
            Token::List => {
                self.advance()?;
                if matches!(
                    self.peek(),
                    Token::Ident(name) if name.eq_ignore_ascii_case("CONFIG")
                ) {
                    match self.parse_config_list_after_list()? {
                        QueryExpr::ConfigCommand(command) => {
                            Ok(FrontendStatement::ConfigCommand(command))
                        }
                        other => Err(ParseError::new(
                            format!(
                                "internal: LIST CONFIG produced unexpected query kind {other:?}"
                            ),
                            self.position(),
                        )),
                    }
                } else if matches!(self.peek(), Token::Kv) {
                    match self.parse_kv_list_after_list()? {
                        QueryExpr::KvCommand(command) => Ok(FrontendStatement::KvCommand(command)),
                        other => Err(ParseError::new(
                            format!("internal: LIST KV produced unexpected query kind {other:?}"),
                            self.position(),
                        )),
                    }
                } else if matches!(
                    self.peek(),
                    Token::Ident(name) if name.eq_ignore_ascii_case("VAULT")
                ) {
                    match self.parse_vault_list_after_list()? {
                        QueryExpr::KvCommand(command) => Ok(FrontendStatement::KvCommand(command)),
                        other => Err(ParseError::new(
                            format!(
                                "internal: LIST VAULT produced unexpected query kind {other:?}"
                            ),
                            self.position(),
                        )),
                    }
                } else {
                    Err(ParseError::expected(
                        vec!["CONFIG", "KV", "VAULT"],
                        self.peek(),
                        self.position(),
                    ))
                }
            }
            Token::Ident(name) if name.eq_ignore_ascii_case("LIST") => {
                self.advance()?;
                if matches!(
                    self.peek(),
                    Token::Ident(name) if name.eq_ignore_ascii_case("CONFIG")
                ) {
                    match self.parse_config_list_after_list()? {
                        QueryExpr::ConfigCommand(command) => {
                            Ok(FrontendStatement::ConfigCommand(command))
                        }
                        other => Err(ParseError::new(
                            format!(
                                "internal: LIST CONFIG produced unexpected query kind {other:?}"
                            ),
                            self.position(),
                        )),
                    }
                } else if matches!(self.peek(), Token::Kv) {
                    match self.parse_kv_list_after_list()? {
                        QueryExpr::KvCommand(command) => Ok(FrontendStatement::KvCommand(command)),
                        other => Err(ParseError::new(
                            format!("internal: LIST KV produced unexpected query kind {other:?}"),
                            self.position(),
                        )),
                    }
                } else if matches!(
                    self.peek(),
                    Token::Ident(name) if name.eq_ignore_ascii_case("VAULT")
                ) {
                    match self.parse_vault_list_after_list()? {
                        QueryExpr::KvCommand(command) => Ok(FrontendStatement::KvCommand(command)),
                        other => Err(ParseError::new(
                            format!(
                                "internal: LIST VAULT produced unexpected query kind {other:?}"
                            ),
                            self.position(),
                        )),
                    }
                } else {
                    Err(ParseError::expected(
                        vec!["CONFIG", "KV", "VAULT"],
                        self.peek(),
                        self.position(),
                    ))
                }
            }
            Token::Ident(name) if name.eq_ignore_ascii_case("INVALIDATE") => {
                if matches!(
                    self.peek_next()?,
                    Token::Ident(next) if next.eq_ignore_ascii_case("CONFIG")
                ) {
                    match self.parse_config_command()? {
                        QueryExpr::ConfigCommand(command) => {
                            Ok(FrontendStatement::ConfigCommand(command))
                        }
                        other => Err(ParseError::new(
                            format!("internal: CONFIG produced unexpected query kind {other:?}"),
                            self.position(),
                        )),
                    }
                } else {
                    self.advance()?;
                    match self.parse_kv_invalidate_tags_after_invalidate()? {
                        QueryExpr::KvCommand(command) => Ok(FrontendStatement::KvCommand(command)),
                        other => Err(ParseError::new(
                            format!(
                                "internal: INVALIDATE produced unexpected query kind {other:?}"
                            ),
                            self.position(),
                        )),
                    }
                }
            }
            Token::Attach | Token::Detach => self.parse_sql_statement().map(FrontendStatement::Sql),
            Token::Match => match self.parse_match_query()? {
                QueryExpr::Graph(query) => Ok(FrontendStatement::Graph(query)),
                other => Err(ParseError::new(
                    format!("internal: MATCH produced unexpected query kind {other:?}"),
                    self.position(),
                )),
            },
            Token::Path => match self.parse_path_query()? {
                QueryExpr::Path(query) => Ok(FrontendStatement::Path(query)),
                other => Err(ParseError::new(
                    format!("internal: PATH produced unexpected query kind {other:?}"),
                    self.position(),
                )),
            },
            Token::Vector => match self.parse_vector_query()? {
                QueryExpr::Vector(query) => Ok(FrontendStatement::Vector(query)),
                other => Err(ParseError::new(
                    format!("internal: VECTOR produced unexpected query kind {other:?}"),
                    self.position(),
                )),
            },
            Token::Hybrid => match self.parse_hybrid_query()? {
                QueryExpr::Hybrid(query) => Ok(FrontendStatement::Hybrid(query)),
                other => Err(ParseError::new(
                    format!("internal: HYBRID produced unexpected query kind {other:?}"),
                    self.position(),
                )),
            },
            Token::Graph => match self.parse_graph_command()? {
                QueryExpr::GraphCommand(command) => Ok(FrontendStatement::GraphCommand(command)),
                other => Err(ParseError::new(
                    format!("internal: GRAPH produced unexpected query kind {other:?}"),
                    self.position(),
                )),
            },
            Token::Search => match self.parse_search_command()? {
                QueryExpr::SearchCommand(command) => Ok(FrontendStatement::Search(command)),
                other => Err(ParseError::new(
                    format!("internal: SEARCH produced unexpected query kind {other:?}"),
                    self.position(),
                )),
            },
            Token::Ident(name) if name.eq_ignore_ascii_case("ASK") => {
                match self.parse_ask_query()? {
                    QueryExpr::Ask(query) => Ok(FrontendStatement::Ask(query)),
                    other => Err(ParseError::new(
                        format!("internal: ASK produced unexpected query kind {other:?}"),
                        self.position(),
                    )),
                }
            }
            Token::Ident(name) if name.eq_ignore_ascii_case("UNSEAL") => {
                match self.parse_unseal_vault_command()? {
                    QueryExpr::KvCommand(command) => Ok(FrontendStatement::KvCommand(command)),
                    other => Err(ParseError::new(
                        format!("internal: UNSEAL VAULT produced unexpected query kind {other:?}"),
                        self.position(),
                    )),
                }
            }
            Token::Queue => match self.parse_queue_command()? {
                QueryExpr::QueueCommand(command) => Ok(FrontendStatement::QueueCommand(command)),
                other => Err(ParseError::new(
                    format!("internal: QUEUE produced unexpected query kind {other:?}"),
                    self.position(),
                )),
            },
            Token::Ident(name) if name.eq_ignore_ascii_case("EVENTS") => {
                match self.parse_events_command()? {
                    QueryExpr::Table(query) => Ok(FrontendStatement::Sql(SqlStatement::Query(
                        SqlQuery::Select(query),
                    ))),
                    QueryExpr::EventsBackfill(query) => {
                        Ok(FrontendStatement::EventsBackfill(query))
                    }
                    QueryExpr::EventsBackfillStatus { collection } => {
                        Ok(FrontendStatement::EventsBackfillStatus { collection })
                    }
                    other => Err(ParseError::new(
                        format!("internal: EVENTS produced unexpected query kind {other:?}"),
                        self.position(),
                    )),
                }
            }
            Token::Kv => match self.parse_kv_command()? {
                QueryExpr::KvCommand(command) => Ok(FrontendStatement::KvCommand(command)),
                other => Err(ParseError::new(
                    format!("internal: KV produced unexpected query kind {other:?}"),
                    self.position(),
                )),
            },
            Token::Delete => {
                if matches!(
                    self.peek_next()?,
                    Token::Ident(name) if name.eq_ignore_ascii_case("CONFIG")
                ) {
                    match self.parse_config_command()? {
                        QueryExpr::ConfigCommand(command) => {
                            Ok(FrontendStatement::ConfigCommand(command))
                        }
                        other => Err(ParseError::new(
                            format!("internal: CONFIG produced unexpected query kind {other:?}"),
                            self.position(),
                        )),
                    }
                } else if matches!(
                    self.peek_next()?,
                    Token::Ident(name) if name.eq_ignore_ascii_case("VAULT")
                ) {
                    match self.parse_vault_lifecycle_command()? {
                        QueryExpr::KvCommand(command) => Ok(FrontendStatement::KvCommand(command)),
                        other => Err(ParseError::new(
                            format!("internal: VAULT produced unexpected query kind {other:?}"),
                            self.position(),
                        )),
                    }
                } else {
                    self.parse_sql_statement().map(FrontendStatement::Sql)
                }
            }
            Token::Add => match self.parse_config_command()? {
                QueryExpr::ConfigCommand(command) => Ok(FrontendStatement::ConfigCommand(command)),
                other => Err(ParseError::new(
                    format!("internal: CONFIG produced unexpected query kind {other:?}"),
                    self.position(),
                )),
            },
            Token::Purge => match self.parse_vault_lifecycle_command()? {
                QueryExpr::KvCommand(command) => Ok(FrontendStatement::KvCommand(command)),
                other => Err(ParseError::new(
                    format!("internal: VAULT produced unexpected query kind {other:?}"),
                    self.position(),
                )),
            },
            Token::Ident(name)
                if name.eq_ignore_ascii_case("PUT")
                    || name.eq_ignore_ascii_case("GET")
                    || name.eq_ignore_ascii_case("RESOLVE")
                    || name.eq_ignore_ascii_case("ROTATE")
                    || name.eq_ignore_ascii_case("HISTORY")
                    || name.eq_ignore_ascii_case("PURGE")
                    || name.eq_ignore_ascii_case("INCR")
                    || name.eq_ignore_ascii_case("DECR")
                    || name.eq_ignore_ascii_case("INVALIDATE") =>
            {
                if matches!(
                    self.peek_next()?,
                    Token::Ident(next) if next.eq_ignore_ascii_case("VAULT")
                ) {
                    match self.parse_vault_lifecycle_command()? {
                        QueryExpr::KvCommand(command) => Ok(FrontendStatement::KvCommand(command)),
                        other => Err(ParseError::new(
                            format!("internal: VAULT produced unexpected query kind {other:?}"),
                            self.position(),
                        )),
                    }
                } else {
                    match self.parse_config_command()? {
                        QueryExpr::ConfigCommand(command) => {
                            Ok(FrontendStatement::ConfigCommand(command))
                        }
                        other => Err(ParseError::new(
                            format!("internal: CONFIG produced unexpected query kind {other:?}"),
                            self.position(),
                        )),
                    }
                }
            }
            Token::Ident(name) if name.eq_ignore_ascii_case("VAULT") => {
                match self.parse_vault_command()? {
                    QueryExpr::KvCommand(command) => Ok(FrontendStatement::KvCommand(command)),
                    other => Err(ParseError::new(
                        format!("internal: VAULT produced unexpected query kind {other:?}"),
                        self.position(),
                    )),
                }
            }
            Token::Tree => match self.parse_tree_command()? {
                QueryExpr::TreeCommand(command) => Ok(FrontendStatement::TreeCommand(command)),
                other => Err(ParseError::new(
                    format!("internal: TREE produced unexpected query kind {other:?}"),
                    self.position(),
                )),
            },
            Token::Ident(name) if name.eq_ignore_ascii_case("HLL") => {
                match self.parse_hll_command()? {
                    QueryExpr::ProbabilisticCommand(command) => {
                        Ok(FrontendStatement::ProbabilisticCommand(command))
                    }
                    other => Err(ParseError::new(
                        format!("internal: HLL produced unexpected query kind {other:?}"),
                        self.position(),
                    )),
                }
            }
            Token::Ident(name) if name.eq_ignore_ascii_case("SKETCH") => {
                match self.parse_sketch_command()? {
                    QueryExpr::ProbabilisticCommand(command) => {
                        Ok(FrontendStatement::ProbabilisticCommand(command))
                    }
                    other => Err(ParseError::new(
                        format!("internal: SKETCH produced unexpected query kind {other:?}"),
                        self.position(),
                    )),
                }
            }
            Token::Ident(name) if name.eq_ignore_ascii_case("FILTER") => {
                match self.parse_filter_command()? {
                    QueryExpr::ProbabilisticCommand(command) => {
                        Ok(FrontendStatement::ProbabilisticCommand(command))
                    }
                    other => Err(ParseError::new(
                        format!("internal: FILTER produced unexpected query kind {other:?}"),
                        self.position(),
                    )),
                }
            }
            Token::Ident(name) if name.eq_ignore_ascii_case("EVENTS") => self
                .parse_sql_command()
                .map(SqlCommand::into_statement)
                .map(FrontendStatement::Sql),
            other => Err(ParseError::expected(
                vec![
                    "SELECT", "MATCH", "PATH", "FROM", "VECTOR", "HYBRID", "INSERT", "UPDATE",
                    "DELETE", "TRUNCATE", "CREATE", "DROP", "ALTER", "GRAPH", "SEARCH", "ASK",
                    "QUEUE", "EVENTS", "KV", "HLL", "TREE", "SKETCH", "FILTER", "SET", "SHOW",
                    "RESET", "DESCRIBE", "DESC", "RANK", "ZRANK", "ZRANGE",
                ],
                other,
                self.position(),
            )),
        }
    }

    fn parse_ranking_read(&mut self) -> Result<QueryExpr, ParseError> {
        let head = self.expect_ident()?;
        if head.eq_ignore_ascii_case("RANK") {
            return self.parse_rank_after_rank(false);
        }
        if head.eq_ignore_ascii_case("APPROX") || head.eq_ignore_ascii_case("APPROXIMATE") {
            if !self.consume_ident_ci("RANK")? {
                return Err(ParseError::expected(
                    vec!["RANK"],
                    self.peek(),
                    self.position(),
                ));
            }
            return self.parse_rank_after_rank(true);
        }
        if head.eq_ignore_ascii_case("ZRANK") {
            return self.parse_zrank();
        }
        if head.eq_ignore_ascii_case("ZRANGE") {
            return self.parse_zrange();
        }
        Err(ParseError::expected(
            vec!["RANK", "APPROX RANK", "ZRANK", "ZRANGE"],
            self.peek(),
            self.position(),
        ))
    }

    fn parse_rank_after_rank(&mut self, approximate: bool) -> Result<QueryExpr, ParseError> {
        if self.consume(&Token::Of)? {
            let entity_id = self.parse_u64_slot("rank entity id")?;
            self.expect(Token::In)?;
            let ranking = self.expect_ident()?;
            let query = RankOfQuery { ranking, entity_id };
            return Ok(if approximate {
                QueryExpr::ApproxRankOf(query)
            } else {
                QueryExpr::RankOf(query)
            });
        }

        if !approximate && self.consume(&Token::Range)? {
            let lo = self.parse_positive_u64_slot("rank range lower bound")?;
            self.expect(Token::To)?;
            let hi = self.parse_positive_u64_slot("rank range upper bound")?;
            if hi < lo {
                return Err(ParseError::value_out_of_range(
                    "rank range upper bound",
                    "must be greater than or equal to the lower bound",
                    self.position(),
                ));
            }
            self.expect(Token::In)?;
            let ranking = self.expect_ident()?;
            return Ok(QueryExpr::RankRange(RankRangeQuery { ranking, lo, hi }));
        }

        Err(ParseError::expected(
            if approximate {
                vec!["OF"]
            } else {
                vec!["OF", "RANGE"]
            },
            self.peek(),
            self.position(),
        ))
    }

    fn parse_zrank(&mut self) -> Result<QueryExpr, ParseError> {
        let ranking = self.expect_ident()?;
        let entity_id = self.parse_u64_slot("ZRANK entity id")?;
        Ok(QueryExpr::RankOf(RankOfQuery { ranking, entity_id }))
    }

    fn parse_zrange(&mut self) -> Result<QueryExpr, ParseError> {
        let ranking = self.expect_ident()?;
        let start = self.parse_u64_slot("ZRANGE start")?;
        let stop = self.parse_u64_slot("ZRANGE stop")?;
        if stop < start {
            return Err(ParseError::value_out_of_range(
                "ZRANGE stop",
                "must be greater than or equal to start",
                self.position(),
            ));
        }
        let _with_scores = self.consume_ident_ci("WITHSCORES")?;
        Ok(QueryExpr::RankRange(RankRangeQuery {
            ranking,
            lo: start + 1,
            hi: stop + 1,
        }))
    }

    fn parse_positive_u64_slot(&mut self, field: &'static str) -> Result<u64, ParseError> {
        let value = self.parse_u64_slot(field)?;
        if value == 0 {
            return Err(ParseError::value_out_of_range(
                field,
                "must be a positive integer",
                self.position(),
            ));
        }
        Ok(value)
    }

    fn parse_u64_slot(&mut self, field: &'static str) -> Result<u64, ParseError> {
        let pos = self.position();
        if matches!(self.peek(), Token::Minus | Token::Dash) {
            return Err(ParseError::value_out_of_range(
                field,
                "must be an unsigned integer",
                pos,
            ));
        }
        let raw = self.parse_integer()?;
        u64::try_from(raw)
            .map_err(|_| ParseError::value_out_of_range(field, "must be an unsigned integer", pos))
    }

    /// Parse any SQL/RQL-style command into the canonical SQL frontend IR.
    pub fn parse_sql_statement(&mut self) -> Result<SqlStatement, ParseError> {
        self.parse_sql_command().map(SqlCommand::into_statement)
    }

    fn parse_dotted_admin_path(&mut self, lowercase: bool) -> Result<String, ParseError> {
        let mut path = self.expect_ident()?;
        while self.consume(&Token::Dot)? {
            let next = self.expect_ident_or_keyword()?;
            path = format!("{path}.{next}");
        }
        Ok(if lowercase {
            path.to_ascii_lowercase()
        } else {
            path
        })
    }

    fn normalize_secret_admin_path(path: String) -> String {
        if let Some(rest) = path.strip_prefix("red.secrets.") {
            format!("red.secret.{rest}")
        } else if path == "red.secrets" {
            "red.secret".to_string()
        } else {
            path
        }
    }

    /// Parse any SQL/RQL-style command through a single frontend module.
    /// Parse a `CREATE ...` statement. Split out of
    /// [`parse_sql_command`] so its very large per-arm locals
    /// (every CREATE variant's query struct) live in their own
    /// stack frame instead of inflating the dispatcher's frame.
    /// `parse_sql_command` recurses (CREATE VIEW ... AS <stmt>,
    /// nested subqueries), so a fat dispatcher frame stacked on
    /// itself overflowed small (2 MiB) worker-thread stacks (#635).
    #[inline(never)]
    fn parse_create_command(&mut self) -> Result<SqlCommand, ParseError> {
        let pos = self.position();
        self.advance()?;

        // CREATE [OR REPLACE] [MATERIALIZED] VIEW [IF NOT EXISTS] name AS <select>
        // Detect the VIEW path early so OR REPLACE / MATERIALIZED modifiers
        // don't collide with other CREATE variants (TABLE, INDEX, etc.).
        let mut or_replace = false;
        if self.consume(&Token::Or)? || self.consume_ident_ci("OR")? {
            let _ = self.consume_ident_ci("REPLACE")?;
            or_replace = true;
        }
        let materialized = self.consume(&Token::Materialized)?;
        if self.check(&Token::View) {
            self.advance()?;
            let if_not_exists = self.match_if_not_exists()?;
            let name = self.expect_ident()?;
            // Issue #584 slice 12 — `WITH RETENTION <duration>`
            // on CREATE MATERIALIZED VIEW. Parsed before `AS`
            // so the SELECT body parser cannot consume the
            // trailing `WITH` for its own (TTL / METADATA /
            // …) clauses. Persisted on the view definition;
            // the physical sweep against view-backing rows
            // activates with the slice-9 row-storage follow-up.
            let mut retention_duration_ms: Option<u64> = None;
            if self.check(&Token::With) {
                self.advance()?;
                if !self.consume(&Token::Retention)? && !self.consume_ident_ci("RETENTION")? {
                    return Err(ParseError::expected(
                        vec!["RETENTION"],
                        self.peek(),
                        self.position(),
                    ));
                }
                if !materialized {
                    return Err(ParseError::new(
                        "WITH RETENTION is only valid on \
                                 CREATE MATERIALIZED VIEW"
                            .to_string(),
                        self.position(),
                    ));
                }
                let value = self.parse_float()?;
                let unit_mult = self.parse_duration_unit()?;
                retention_duration_ms = Some((value * unit_mult).round() as u64);
            }
            // Accept `AS` — the lexer promotes it to `Token::As`
            // (keyword) but some paths still see it as an ident.
            if !self.consume(&Token::As)? && !self.consume_ident_ci("AS")? {
                return Err(ParseError::expected(
                    vec!["AS"],
                    self.peek(),
                    self.position(),
                ));
            }
            // Recursive parse of the body. Any QueryExpr that the
            // rest of the grammar accepts is valid (Select, Join, etc.).
            let body = self.parse_sql_command()?.into_query_expr();
            // Optional `REFRESH EVERY <duration>` clause on
            // materialized views (issue #583 slice 10). The
            // background scheduler reads this off the view
            // descriptor and ticks the view on its cadence.
            let mut refresh_every_ms: Option<u64> = None;
            if self.check(&Token::Refresh) {
                if !materialized {
                    return Err(ParseError::new(
                        "REFRESH EVERY is only valid on \
                                 CREATE MATERIALIZED VIEW"
                            .to_string(),
                        self.position(),
                    ));
                }
                self.advance()?;
                if !self.consume_ident_ci("EVERY")? {
                    return Err(ParseError::expected(
                        vec!["EVERY"],
                        self.peek(),
                        self.position(),
                    ));
                }
                let value = self.parse_float()?;
                let unit_mult = self.parse_duration_unit()?;
                refresh_every_ms = Some((value * unit_mult).round() as u64);
            }
            return Ok(SqlCommand::CreateView(CreateViewQuery {
                name,
                query: Box::new(body),
                materialized,
                if_not_exists,
                or_replace,
                refresh_every_ms,
                retention_duration_ms,
            }));
        }
        // If OR REPLACE / MATERIALIZED was consumed but VIEW was not,
        // bail out — no other CREATE form accepts those modifiers.
        if or_replace || materialized {
            return Err(ParseError::expected(
                vec!["VIEW"],
                self.peek(),
                self.position(),
            ));
        }

        if matches!(self.peek(), Token::Ident(name) if name.eq_ignore_ascii_case("USER")) {
            let stmt = self.parse_create_user_statement()?;
            Ok(SqlCommand::CreateUser(stmt))
        } else if self.check(&Token::Index) || self.check(&Token::Unique) {
            match self.parse_create_index_query()? {
                QueryExpr::CreateIndex(query) => Ok(SqlCommand::CreateIndex(query)),
                other => Err(ParseError::new(
                    format!("internal: CREATE INDEX produced unexpected kind {other:?}"),
                    self.position(),
                )),
            }
        } else if self.check(&Token::Table) {
            self.expect(Token::Table)?;
            match self.parse_create_table_body()? {
                QueryExpr::CreateTable(query) => Ok(SqlCommand::CreateTable(query)),
                other => Err(ParseError::new(
                    format!("internal: CREATE TABLE produced unexpected kind {other:?}"),
                    self.position(),
                )),
            }
        } else if self.check(&Token::Graph) {
            self.advance()?;
            match self.parse_create_collection_model_body(CollectionModel::Graph)? {
                QueryExpr::CreateTable(query) => Ok(SqlCommand::CreateTable(query)),
                other => Err(ParseError::new(
                    format!("internal: CREATE GRAPH produced unexpected kind {other:?}"),
                    self.position(),
                )),
            }
        } else if self.check(&Token::Document) {
            self.advance()?;
            match self.parse_create_collection_model_body(CollectionModel::Document)? {
                QueryExpr::CreateTable(query) => Ok(SqlCommand::CreateTable(query)),
                other => Err(ParseError::new(
                    format!("internal: CREATE DOCUMENT produced unexpected kind {other:?}"),
                    self.position(),
                )),
            }
        } else if self.check(&Token::Vector) {
            self.advance()?;
            match self.parse_create_vector_body()? {
                QueryExpr::CreateVector(query) => Ok(SqlCommand::CreateVector(query)),
                other => Err(ParseError::new(
                    format!("internal: CREATE VECTOR produced unexpected kind {other:?}"),
                    self.position(),
                )),
            }
        } else if self.check(&Token::Collection) {
            self.advance()?;
            match self.parse_create_collection_body()? {
                QueryExpr::CreateCollection(query) => Ok(SqlCommand::CreateCollection(query)),
                other => Err(ParseError::new(
                    format!("internal: CREATE COLLECTION produced unexpected kind {other:?}"),
                    self.position(),
                )),
            }
        } else if self.check(&Token::Kv) {
            self.advance()?;
            match self.parse_create_keyed_body(CollectionModel::Kv)? {
                QueryExpr::CreateTable(query) => Ok(SqlCommand::CreateTable(query)),
                other => Err(ParseError::new(
                    format!("internal: CREATE KV produced unexpected kind {other:?}"),
                    self.position(),
                )),
            }
        } else if self.consume_ident_ci("CONFIG")? {
            match self.parse_create_keyed_body(CollectionModel::Config)? {
                QueryExpr::CreateTable(query) => Ok(SqlCommand::CreateTable(query)),
                other => Err(ParseError::new(
                    format!("internal: CREATE CONFIG produced unexpected kind {other:?}"),
                    self.position(),
                )),
            }
        } else if self.consume_ident_ci("VAULT")? {
            match self.parse_create_keyed_body(CollectionModel::Vault)? {
                QueryExpr::CreateTable(query) => Ok(SqlCommand::CreateTable(query)),
                other => Err(ParseError::new(
                    format!("internal: CREATE VAULT produced unexpected kind {other:?}"),
                    self.position(),
                )),
            }
        } else if self.check(&Token::Timeseries) {
            self.advance()?;
            match self.parse_create_timeseries_body()? {
                QueryExpr::CreateTimeSeries(query) => Ok(SqlCommand::CreateTimeSeries(query)),
                other => Err(ParseError::new(
                    format!("internal: CREATE TIMESERIES produced unexpected kind {other:?}"),
                    self.position(),
                )),
            }
        } else if self.check(&Token::Metric) {
            self.advance()?;
            match self.parse_create_metric_body()? {
                QueryExpr::CreateMetric(query) => Ok(SqlCommand::CreateMetric(query)),
                other => Err(ParseError::new(
                    format!("internal: CREATE METRIC produced unexpected kind {other:?}"),
                    self.position(),
                )),
            }
        } else if self.consume_ident_ci("METRICS")? {
            match self.parse_create_metrics_body()? {
                QueryExpr::CreateTable(query) => Ok(SqlCommand::CreateTable(query)),
                other => Err(ParseError::new(
                    format!("internal: CREATE METRICS produced unexpected kind {other:?}"),
                    self.position(),
                )),
            }
        } else if self.consume_ident_ci("SLO")? {
            match self.parse_create_slo_body()? {
                QueryExpr::CreateSlo(query) => Ok(SqlCommand::CreateSlo(query)),
                other => Err(ParseError::new(
                    format!("internal: CREATE SLO produced unexpected kind {other:?}"),
                    self.position(),
                )),
            }
        } else if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("HYPERTABLE")) {
            self.advance()?;
            match self.parse_create_hypertable_body()? {
                QueryExpr::CreateTimeSeries(query) => Ok(SqlCommand::CreateTimeSeries(query)),
                other => Err(ParseError::new(
                    format!("internal: CREATE HYPERTABLE produced unexpected kind {other:?}"),
                    self.position(),
                )),
            }
        } else if self.check(&Token::Queue) {
            self.advance()?;
            match self.parse_create_queue_body()? {
                QueryExpr::CreateQueue(query) => Ok(SqlCommand::CreateQueue(query)),
                other => Err(ParseError::new(
                    format!("internal: CREATE QUEUE produced unexpected kind {other:?}"),
                    self.position(),
                )),
            }
        } else if self.check(&Token::Tree) {
            self.advance()?;
            match self.parse_create_tree_body()? {
                QueryExpr::CreateTree(query) => Ok(SqlCommand::CreateTree(query)),
                other => Err(ParseError::new(
                    format!("internal: CREATE TREE produced unexpected kind {other:?}"),
                    self.position(),
                )),
            }
        } else if matches!(self.peek(), Token::Ident(n) if
                    n.eq_ignore_ascii_case("HLL") ||
                    n.eq_ignore_ascii_case("SKETCH") ||
                    n.eq_ignore_ascii_case("FILTER"))
        {
            match self.parse_create_probabilistic()? {
                QueryExpr::ProbabilisticCommand(command) => Ok(SqlCommand::Probabilistic(command)),
                other => Err(ParseError::new(
                    format!("internal: CREATE probabilistic produced unexpected kind {other:?}"),
                    self.position(),
                )),
            }
        } else if self.check(&Token::Schema) {
            // CREATE SCHEMA [IF NOT EXISTS] name
            self.advance()?;
            let if_not_exists = self.match_if_not_exists()?;
            let name = self.expect_ident()?;
            Ok(SqlCommand::CreateSchema(CreateSchemaQuery {
                name,
                if_not_exists,
            }))
        } else if self.check(&Token::Policy) {
            // Two forms share the leading `CREATE POLICY` tokens:
            //   * IAM:   CREATE POLICY '<id>' AS '<json>'          (string literal id)
            //   * RLS:   CREATE POLICY <name> ON <target> ...      (bare ident name)
            // Disambiguate by peeking the token after POLICY.
            self.advance()?;
            if matches!(self.peek(), Token::String(_)) {
                // IAM form — short-circuit out of the SQL command stack.
                let expr = self.parse_create_iam_policy_after_keywords()?;
                // Inline command-wrapping: produce a synthetic SqlCommand by
                // routing through a generic IAM admin holder. We don't
                // have a dedicated SqlCommand variant for IAM yet, so we
                // bounce through the existing Grant-shaped Admin slot
                // which expects no further tokens.
                return Ok(SqlCommand::IamPolicy(expr));
            }
            let name = self.expect_ident()?;
            self.expect(Token::On)?;

            let (target_kind, table) = {
                use crate::ast::PolicyTargetKind;
                let kw = match self.peek() {
                    Token::Ident(s) => Some(s.to_ascii_uppercase()),
                    _ => None,
                };
                let kind = kw.as_deref().and_then(|k| match k {
                    "NODES" => Some(PolicyTargetKind::Nodes),
                    "EDGES" => Some(PolicyTargetKind::Edges),
                    "VECTORS" => Some(PolicyTargetKind::Vectors),
                    "MESSAGES" => Some(PolicyTargetKind::Messages),
                    "POINTS" => Some(PolicyTargetKind::Points),
                    "DOCUMENTS" => Some(PolicyTargetKind::Documents),
                    _ => None,
                });
                if let Some(k) = kind {
                    self.advance()?;
                    self.expect(Token::Of)?;
                    let coll = self.expect_ident()?;
                    (k, coll)
                } else {
                    let coll = self.expect_ident()?;
                    (PolicyTargetKind::Table, coll)
                }
            };

            let action = if self.consume(&Token::For)? {
                let a = match self.peek() {
                    Token::Select => {
                        self.advance()?;
                        Some(PolicyAction::Select)
                    }
                    Token::Insert => {
                        self.advance()?;
                        Some(PolicyAction::Insert)
                    }
                    Token::Update => {
                        self.advance()?;
                        Some(PolicyAction::Update)
                    }
                    Token::Delete => {
                        self.advance()?;
                        Some(PolicyAction::Delete)
                    }
                    Token::All => {
                        self.advance()?;
                        None
                    }
                    _ => None,
                };
                a
            } else {
                None
            };

            let role = if self.consume(&Token::To)? {
                Some(self.expect_ident()?)
            } else {
                None
            };

            self.expect(Token::Using)?;
            self.expect(Token::LParen)?;
            let filter = self.parse_filter()?;
            self.expect(Token::RParen)?;

            Ok(SqlCommand::CreatePolicy(CreatePolicyQuery {
                name,
                table,
                action,
                role,
                using: Box::new(filter),
                target_kind,
            }))
        } else if self.check(&Token::Server) {
            // CREATE SERVER [IF NOT EXISTS] name
            //   FOREIGN DATA WRAPPER kind
            //   [OPTIONS (key 'value', ...)]
            self.advance()?;
            let if_not_exists = self.match_if_not_exists()?;
            let name = self.expect_ident()?;
            self.expect(Token::Foreign)?;
            self.expect(Token::Data)?;
            self.expect(Token::Wrapper)?;
            let wrapper = self.expect_ident()?;
            let options = self.parse_fdw_options_clause()?;
            Ok(SqlCommand::CreateServer(CreateServerQuery {
                name,
                wrapper,
                options,
                if_not_exists,
            }))
        } else if self.check(&Token::Foreign) {
            // CREATE FOREIGN TABLE [IF NOT EXISTS] name (cols)
            //   SERVER server_name
            //   [OPTIONS (key 'value', ...)]
            self.advance()?;
            self.expect(Token::Table)?;
            let if_not_exists = self.match_if_not_exists()?;
            let name = self.expect_ident()?;
            self.expect(Token::LParen)?;
            let mut columns = Vec::new();
            loop {
                let col_name = self.expect_ident()?;
                let data_type = self.expect_ident_or_keyword()?;
                // Inline NOT NULL check — the CREATE TABLE path's helper is
                // private and coupling to it just for FDW columns isn't worth it.
                let mut not_null = false;
                if matches!(self.peek(), Token::Ident(n) if n.eq_ignore_ascii_case("NOT")) {
                    self.advance()?;
                    if matches!(self.peek(), Token::Ident(n) if n.eq_ignore_ascii_case("NULL")) {
                        self.advance()?;
                        not_null = true;
                    }
                }
                columns.push(ForeignColumnDef {
                    name: col_name,
                    data_type,
                    not_null,
                });
                if !self.consume(&Token::Comma)? {
                    break;
                }
            }
            self.expect(Token::RParen)?;
            self.expect(Token::Server)?;
            let server = self.expect_ident()?;
            let options = self.parse_fdw_options_clause()?;
            Ok(SqlCommand::CreateForeignTable(CreateForeignTableQuery {
                name,
                server,
                columns,
                options,
                if_not_exists,
            }))
        } else if self.check(&Token::Sequence) {
            // CREATE SEQUENCE [IF NOT EXISTS] name
            //   [START [WITH] n] [INCREMENT [BY] n]
            self.advance()?;
            let if_not_exists = self.match_if_not_exists()?;
            let name = self.expect_ident()?;
            let mut start: i64 = 1;
            let mut increment: i64 = 1;
            // Loop over optional clauses in any order.
            loop {
                if self.consume(&Token::Start)? {
                    // Accept `START 100` or `START WITH 100`.
                    let _ = self.consume(&Token::With)? || self.consume_ident_ci("WITH")?;
                    start = self.parse_integer()?;
                } else if self.consume(&Token::Increment)? {
                    // Accept `INCREMENT 5` or `INCREMENT BY 5`.
                    let _ = self.consume(&Token::By)? || self.consume_ident_ci("BY")?;
                    increment = self.parse_integer()?;
                } else {
                    break;
                }
            }
            Ok(SqlCommand::CreateSequence(CreateSequenceQuery {
                name,
                if_not_exists,
                start,
                increment,
            }))
        } else if matches!(self.peek(), Token::Ident(n) if n.eq_ignore_ascii_case("MIGRATION")) {
            self.advance()?; // consume MIGRATION
            match self.parse_create_migration_body()? {
                QueryExpr::CreateMigration(q) => Ok(SqlCommand::CreateMigration(q)),
                other => Err(ParseError::new(
                    format!("internal: CREATE MIGRATION produced unexpected kind {other:?}"),
                    self.position(),
                )),
            }
        } else if let Some(reason) = analytics_v0_non_goal_create(self.peek()) {
            // Issue #789 — enforce Analytics v0 non-goals at the parser
            // surface. The parent PRD (#782) explicitly excludes generic
            // analytics objects, a new event storage model, cohorts,
            // funnels, SLA contracts, and adapters from v0. Reject these
            // CREATE forms here with a stable, non-goal-specific message
            // so accidental use surfaces an obvious "out of scope for v0"
            // error rather than the generic CREATE fallback.
            Err(ParseError::new(reason, self.position()))
        } else if let Some(err) =
            ParseError::unsupported_recognized_token(self.peek(), self.position())
        {
            Err(err)
        } else {
            Err(ParseError::expected(
                vec![
                    "TABLE",
                    "GRAPH",
                    "VECTOR",
                    "DOCUMENT",
                    "KV",
                    "COLLECTION",
                    "INDEX",
                    "UNIQUE",
                    "METRIC",
                    "TIMESERIES",
                    "QUEUE",
                    "TREE",
                    "HLL",
                    "SKETCH",
                    "FILTER",
                    "SCHEMA",
                    "SEQUENCE",
                    "USER",
                    "MIGRATION",
                ],
                self.peek(),
                pos,
            ))
        }
    }

    pub fn parse_sql_command(&mut self) -> Result<SqlCommand, ParseError> {
        match self.peek() {
            Token::Select => match self.parse_select_query()? {
                QueryExpr::Table(query) => Ok(SqlCommand::Select(query)),
                QueryExpr::Join(query) => Ok(SqlCommand::Join(query)),
                other => Err(ParseError::new(
                    format!("internal: SELECT produced unexpected query kind {other:?}"),
                    self.position(),
                )),
            },
            Token::From => match self.parse_from_query()? {
                QueryExpr::Table(query) => Ok(SqlCommand::Select(query)),
                QueryExpr::Join(query) => Ok(SqlCommand::Join(query)),
                other => Err(ParseError::new(
                    format!("internal: FROM produced unexpected query kind {other:?}"),
                    self.position(),
                )),
            },
            Token::Insert => match self.parse_insert_query()? {
                QueryExpr::Insert(query) => Ok(SqlCommand::Insert(query)),
                other => Err(ParseError::new(
                    format!("internal: INSERT produced unexpected query kind {other:?}"),
                    self.position(),
                )),
            },
            Token::Update => match self.parse_update_query()? {
                QueryExpr::Update(query) => Ok(SqlCommand::Update(query)),
                other => Err(ParseError::new(
                    format!("internal: UPDATE produced unexpected query kind {other:?}"),
                    self.position(),
                )),
            },
            Token::Delete => {
                if matches!(self.peek_next()?, Token::Ident(n) if n.eq_ignore_ascii_case("SECRET"))
                {
                    self.advance()?; // DELETE
                    self.advance()?; // SECRET
                    let key =
                        Self::normalize_secret_admin_path(self.parse_dotted_admin_path(true)?);
                    Ok(SqlCommand::DeleteSecret { key })
                } else {
                    match self.parse_delete_query()? {
                        QueryExpr::Delete(query) => Ok(SqlCommand::Delete(query)),
                        other => Err(ParseError::new(
                            format!("internal: DELETE produced unexpected query kind {other:?}"),
                            self.position(),
                        )),
                    }
                }
            }
            Token::Truncate => {
                self.advance()?;
                let model = if self.consume(&Token::Table)? {
                    Some(CollectionModel::Table)
                } else if self.consume(&Token::Graph)? {
                    Some(CollectionModel::Graph)
                } else if self.consume(&Token::Vector)? {
                    Some(CollectionModel::Vector)
                } else if self.consume(&Token::Document)? {
                    Some(CollectionModel::Document)
                } else if self.consume(&Token::Timeseries)? {
                    Some(CollectionModel::TimeSeries)
                } else if self.consume_ident_ci("METRICS")? {
                    Some(CollectionModel::Metrics)
                } else if self.consume(&Token::Kv)? {
                    Some(CollectionModel::Kv)
                } else if self.consume(&Token::Queue)? {
                    Some(CollectionModel::Queue)
                } else if self.consume(&Token::Collection)? {
                    None
                } else {
                    return Err(ParseError::expected(
                        vec![
                            "TABLE",
                            "GRAPH",
                            "VECTOR",
                            "DOCUMENT",
                            "TIMESERIES",
                            "METRICS",
                            "KV",
                            "QUEUE",
                            "COLLECTION",
                        ],
                        self.peek(),
                        self.position(),
                    ));
                };
                match self.parse_truncate_body(model)? {
                    QueryExpr::Truncate(query) => Ok(SqlCommand::Truncate(query)),
                    other => Err(ParseError::new(
                        format!("internal: TRUNCATE produced unexpected kind {other:?}"),
                        self.position(),
                    )),
                }
            }
            Token::Explain => {
                // Peek ahead: EXPLAIN MIGRATION name → ExplainMigration
                // EXPLAIN ALTER FOR ... → ExplainAlter (existing path)
                if matches!(self.peek_next()?, Token::Ident(n) if n.eq_ignore_ascii_case("MIGRATION"))
                {
                    self.advance()?; // consume EXPLAIN
                    match self.parse_explain_migration_after_keyword()? {
                        QueryExpr::ExplainMigration(q) => Ok(SqlCommand::ExplainMigration(q)),
                        other => Err(ParseError::new(
                            format!(
                                "internal: EXPLAIN MIGRATION produced unexpected kind {other:?}"
                            ),
                            self.position(),
                        )),
                    }
                } else {
                    match self.parse_explain_alter_query()? {
                        QueryExpr::ExplainAlter(query) => Ok(SqlCommand::ExplainAlter(query)),
                        other => Err(ParseError::new(
                            format!("internal: EXPLAIN produced unexpected query kind {other:?}"),
                            self.position(),
                        )),
                    }
                }
            }
            Token::Create => self.parse_create_command(),
            Token::Drop => {
                let pos = self.position();
                self.advance()?;

                // DROP [MATERIALIZED] VIEW [IF EXISTS] name
                let materialized = self.consume(&Token::Materialized)?;
                if self.check(&Token::View) {
                    self.advance()?;
                    let if_exists = self.match_if_exists()?;
                    let name = self.expect_ident()?;
                    return Ok(SqlCommand::DropView(DropViewQuery {
                        name,
                        materialized,
                        if_exists,
                    }));
                }
                if materialized {
                    return Err(ParseError::expected(
                        vec!["VIEW"],
                        self.peek(),
                        self.position(),
                    ));
                }

                if self.check(&Token::Index) {
                    match self.parse_drop_index_query()? {
                        QueryExpr::DropIndex(query) => Ok(SqlCommand::DropIndex(query)),
                        other => Err(ParseError::new(
                            format!("internal: DROP INDEX produced unexpected kind {other:?}"),
                            self.position(),
                        )),
                    }
                } else if self.check(&Token::Table) {
                    self.expect(Token::Table)?;
                    match self.parse_drop_table_body()? {
                        QueryExpr::DropTable(query) => Ok(SqlCommand::DropTable(query)),
                        other => Err(ParseError::new(
                            format!("internal: DROP TABLE produced unexpected kind {other:?}"),
                            self.position(),
                        )),
                    }
                } else if self.check(&Token::Graph) {
                    self.advance()?;
                    match self.parse_drop_graph_body()? {
                        QueryExpr::DropGraph(query) => Ok(SqlCommand::DropGraph(query)),
                        other => Err(ParseError::new(
                            format!("internal: DROP GRAPH produced unexpected kind {other:?}"),
                            self.position(),
                        )),
                    }
                } else if self.check(&Token::Vector) {
                    self.advance()?;
                    match self.parse_drop_vector_body()? {
                        QueryExpr::DropVector(query) => Ok(SqlCommand::DropVector(query)),
                        other => Err(ParseError::new(
                            format!("internal: DROP VECTOR produced unexpected kind {other:?}"),
                            self.position(),
                        )),
                    }
                } else if self.check(&Token::Document) {
                    self.advance()?;
                    match self.parse_drop_document_body()? {
                        QueryExpr::DropDocument(query) => Ok(SqlCommand::DropDocument(query)),
                        other => Err(ParseError::new(
                            format!("internal: DROP DOCUMENT produced unexpected kind {other:?}"),
                            self.position(),
                        )),
                    }
                } else if self.check(&Token::Kv) {
                    self.advance()?;
                    match self.parse_drop_kv_body()? {
                        QueryExpr::DropKv(query) => Ok(SqlCommand::DropKv(query)),
                        other => Err(ParseError::new(
                            format!("internal: DROP KV produced unexpected kind {other:?}"),
                            self.position(),
                        )),
                    }
                } else if self.consume_ident_ci("CONFIG")? {
                    match self.parse_drop_keyed_body(CollectionModel::Config)? {
                        QueryExpr::DropKv(query) => Ok(SqlCommand::DropKv(query)),
                        other => Err(ParseError::new(
                            format!("internal: DROP CONFIG produced unexpected kind {other:?}"),
                            self.position(),
                        )),
                    }
                } else if self.consume_ident_ci("VAULT")? {
                    match self.parse_drop_keyed_body(CollectionModel::Vault)? {
                        QueryExpr::DropKv(query) => Ok(SqlCommand::DropKv(query)),
                        other => Err(ParseError::new(
                            format!("internal: DROP VAULT produced unexpected kind {other:?}"),
                            self.position(),
                        )),
                    }
                } else if self.check(&Token::Collection) {
                    self.advance()?;
                    match self.parse_drop_collection_body()? {
                        QueryExpr::DropCollection(query) => Ok(SqlCommand::DropCollection(query)),
                        other => Err(ParseError::new(
                            format!("internal: DROP COLLECTION produced unexpected kind {other:?}"),
                            self.position(),
                        )),
                    }
                } else if self.check(&Token::Timeseries) {
                    self.advance()?;
                    match self.parse_drop_timeseries_body()? {
                        QueryExpr::DropTimeSeries(query) => Ok(SqlCommand::DropTimeSeries(query)),
                        other => Err(ParseError::new(
                            format!("internal: DROP TIMESERIES produced unexpected kind {other:?}"),
                            self.position(),
                        )),
                    }
                } else if self.consume_ident_ci("METRICS")? {
                    match self.parse_drop_collection_model_body(Some(CollectionModel::Metrics))? {
                        QueryExpr::DropCollection(query) => Ok(SqlCommand::DropCollection(query)),
                        other => Err(ParseError::new(
                            format!("internal: DROP METRICS produced unexpected kind {other:?}"),
                            self.position(),
                        )),
                    }
                } else if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("HYPERTABLE"))
                {
                    // DROP HYPERTABLE name reuses the same AST as
                    // DROP TIMESERIES — runtime clears the registry
                    // entry *and* drops the backing collection.
                    self.advance()?;
                    match self.parse_drop_timeseries_body()? {
                        QueryExpr::DropTimeSeries(query) => Ok(SqlCommand::DropTimeSeries(query)),
                        other => Err(ParseError::new(
                            format!("internal: DROP HYPERTABLE produced unexpected kind {other:?}"),
                            self.position(),
                        )),
                    }
                } else if self.check(&Token::Queue) {
                    self.advance()?;
                    match self.parse_drop_queue_body()? {
                        QueryExpr::DropQueue(query) => Ok(SqlCommand::DropQueue(query)),
                        other => Err(ParseError::new(
                            format!("internal: DROP QUEUE produced unexpected kind {other:?}"),
                            self.position(),
                        )),
                    }
                } else if self.check(&Token::Tree) {
                    self.advance()?;
                    match self.parse_drop_tree_body()? {
                        QueryExpr::DropTree(query) => Ok(SqlCommand::DropTree(query)),
                        other => Err(ParseError::new(
                            format!("internal: DROP TREE produced unexpected kind {other:?}"),
                            self.position(),
                        )),
                    }
                } else if matches!(self.peek(), Token::Ident(n) if
                    n.eq_ignore_ascii_case("HLL") ||
                    n.eq_ignore_ascii_case("SKETCH") ||
                    n.eq_ignore_ascii_case("FILTER"))
                {
                    match self.parse_drop_probabilistic()? {
                        QueryExpr::ProbabilisticCommand(command) => {
                            Ok(SqlCommand::Probabilistic(command))
                        }
                        other => Err(ParseError::new(
                            format!(
                                "internal: DROP probabilistic produced unexpected kind {other:?}"
                            ),
                            self.position(),
                        )),
                    }
                } else if self.check(&Token::Schema) {
                    // DROP SCHEMA [IF EXISTS] name [CASCADE]
                    self.advance()?;
                    let if_exists = self.match_if_exists()?;
                    let name = self.expect_ident()?;
                    let cascade = self.consume(&Token::Cascade)?;
                    Ok(SqlCommand::DropSchema(DropSchemaQuery {
                        name,
                        if_exists,
                        cascade,
                    }))
                } else if self.check(&Token::Policy) {
                    // Two forms:
                    //   * IAM:   DROP POLICY '<id>'
                    //   * RLS:   DROP POLICY [IF EXISTS] name ON table
                    self.advance()?;
                    if matches!(self.peek(), Token::String(_)) {
                        let expr = self.parse_drop_iam_policy_after_keywords()?;
                        return Ok(SqlCommand::IamPolicy(expr));
                    }
                    let if_exists = self.match_if_exists()?;
                    let name = self.expect_ident()?;
                    self.expect(Token::On)?;
                    let table = self.expect_ident()?;
                    Ok(SqlCommand::DropPolicy(DropPolicyQuery {
                        name,
                        table,
                        if_exists,
                    }))
                } else if self.check(&Token::Server) {
                    // DROP SERVER [IF EXISTS] name [CASCADE]
                    self.advance()?;
                    let if_exists = self.match_if_exists()?;
                    let name = self.expect_ident()?;
                    let cascade = self.consume(&Token::Cascade)?;
                    Ok(SqlCommand::DropServer(DropServerQuery {
                        name,
                        if_exists,
                        cascade,
                    }))
                } else if self.check(&Token::Foreign) {
                    // DROP FOREIGN TABLE [IF EXISTS] name
                    self.advance()?;
                    self.expect(Token::Table)?;
                    let if_exists = self.match_if_exists()?;
                    let name = self.expect_ident()?;
                    Ok(SqlCommand::DropForeignTable(DropForeignTableQuery {
                        name,
                        if_exists,
                    }))
                } else if self.check(&Token::Sequence) {
                    // DROP SEQUENCE [IF EXISTS] name
                    self.advance()?;
                    let if_exists = self.match_if_exists()?;
                    let name = self.expect_ident()?;
                    Ok(SqlCommand::DropSequence(DropSequenceQuery {
                        name,
                        if_exists,
                    }))
                } else if let Some(err) =
                    ParseError::unsupported_recognized_token(self.peek(), self.position())
                {
                    Err(err)
                } else {
                    Err(ParseError::expected(
                        vec![
                            "TABLE",
                            "INDEX",
                            "TIMESERIES",
                            "QUEUE",
                            "TREE",
                            "HLL",
                            "SKETCH",
                            "FILTER",
                            "SCHEMA",
                            "SEQUENCE",
                        ],
                        self.peek(),
                        pos,
                    ))
                }
            }
            Token::Alter => {
                // Disambiguate ALTER USER / ALTER QUEUE / ALTER TABLE without
                // committing to a path until we've seen the target.
                // We peek the *next* token (without consuming) and
                // dispatch accordingly.
                let next = self.peek_next()?.clone();
                if matches!(next, Token::Ident(ref s) if s.eq_ignore_ascii_case("USER")) {
                    self.advance()?; // consume ALTER
                    let stmt = self.parse_alter_user_statement()?;
                    Ok(SqlCommand::AlterUser(stmt))
                } else if matches!(next, Token::Queue) {
                    self.advance()?; // consume ALTER
                    self.advance()?; // consume QUEUE
                    match self.parse_alter_queue_body()? {
                        QueryExpr::AlterQueue(query) => Ok(SqlCommand::AlterQueue(query)),
                        other => Err(ParseError::new(
                            format!("internal: ALTER QUEUE produced unexpected kind {other:?}"),
                            self.position(),
                        )),
                    }
                } else if matches!(next, Token::Metric) {
                    self.advance()?; // consume ALTER
                    self.advance()?; // consume METRIC
                    match self.parse_alter_metric_body()? {
                        QueryExpr::AlterMetric(query) => Ok(SqlCommand::AlterMetric(query)),
                        other => Err(ParseError::new(
                            format!("internal: ALTER METRIC produced unexpected kind {other:?}"),
                            self.position(),
                        )),
                    }
                } else if matches!(next, Token::Graph) {
                    // Issue #801 — `ALTER GRAPH name ADD|DROP ANALYTICS ...`
                    // shares the AlterTable AST so analytics-config lifecycle
                    // mutations dispatch through the existing executor path.
                    match self.parse_alter_graph_query()? {
                        QueryExpr::AlterTable(query) => Ok(SqlCommand::AlterTable(query)),
                        other => Err(ParseError::new(
                            format!(
                                "internal: ALTER GRAPH produced unexpected query kind {other:?}"
                            ),
                            self.position(),
                        )),
                    }
                } else if matches!(next, Token::Table)
                    || matches!(next, Token::Collection)
                    || matches!(next, Token::Ident(ref s) if s.eq_ignore_ascii_case("COLLECTION"))
                {
                    // Issue #522 — `ALTER COLLECTION` shares the AlterTable
                    // AST so signer-registry mutations dispatch through the
                    // existing executor. The DDL parser body accepts either
                    // keyword interchangeably for the open-vocabulary alters
                    // we own (currently `ADD|REVOKE SIGNER`).
                    match self.parse_alter_table_query()? {
                        QueryExpr::AlterTable(query) => Ok(SqlCommand::AlterTable(query)),
                        other => Err(ParseError::new(
                            format!(
                                "internal: ALTER TABLE produced unexpected query kind {other:?}"
                            ),
                            self.position(),
                        )),
                    }
                } else if let Some(err) =
                    ParseError::unsupported_recognized_token(&next, self.position())
                {
                    Err(err)
                } else {
                    match self.parse_alter_table_query()? {
                        QueryExpr::AlterTable(query) => Ok(SqlCommand::AlterTable(query)),
                        other => Err(ParseError::new(
                            format!("internal: ALTER produced unexpected query kind {other:?}"),
                            self.position(),
                        )),
                    }
                }
            }
            Token::Ident(name) if name.eq_ignore_ascii_case("GRANT") => {
                let stmt = self.parse_grant_statement()?;
                Ok(SqlCommand::Grant(stmt))
            }
            Token::Ident(name) if name.eq_ignore_ascii_case("REVOKE") => {
                let stmt = self.parse_revoke_statement()?;
                Ok(SqlCommand::Revoke(stmt))
            }
            Token::Ident(name) if name.eq_ignore_ascii_case("EVENTS") => {
                self.advance()?;
                if self.consume_ident_ci("BACKFILL")? {
                    return Err(ParseError::new(
                        "EVENTS BACKFILL STATUS is not implemented; EVENTS BACKFILL runtime is available but durable progress tracking is not"
                            .to_string(),
                        self.position(),
                    ));
                }
                if !self.consume_ident_ci("STATUS")? {
                    return Err(ParseError::expected(
                        vec!["STATUS"],
                        self.peek(),
                        self.position(),
                    ));
                }

                let mut query = TableQuery::new("red.subscriptions");
                let collection = match self.peek().clone() {
                    Token::Ident(name) => {
                        self.advance()?;
                        Some(name)
                    }
                    Token::String(name) => {
                        self.advance()?;
                        Some(name)
                    }
                    _ => None,
                };
                self.parse_table_clauses(&mut query)?;
                if let Some(collection) = collection {
                    let filter = Filter::compare(
                        FieldRef::column("red.subscriptions", "collection"),
                        CompareOp::Eq,
                        Value::text(collection),
                    );
                    let expr = filter_to_expr(&filter);
                    query.where_expr = Some(match query.where_expr.take() {
                        Some(existing) => Expr::binop(BinOp::And, existing, expr),
                        None => expr,
                    });
                    query.filter = Some(match query.filter.take() {
                        Some(existing) => existing.and(filter),
                        None => filter,
                    });
                }
                Ok(SqlCommand::Select(query))
            }
            Token::Attach => {
                let expr = self.parse_attach_policy()?;
                Ok(SqlCommand::IamPolicy(expr))
            }
            Token::Detach => {
                let expr = self.parse_detach_policy()?;
                Ok(SqlCommand::IamPolicy(expr))
            }
            Token::Ident(name) if name.eq_ignore_ascii_case("SIMULATE") => {
                let expr = self.parse_simulate_policy()?;
                Ok(SqlCommand::IamPolicy(expr))
            }
            Token::Ident(name) if name.eq_ignore_ascii_case("LINT") => {
                let expr = self.parse_lint_policy()?;
                Ok(SqlCommand::IamPolicy(expr))
            }
            Token::Ident(name) if name.eq_ignore_ascii_case("MIGRATE") => {
                // `MIGRATE POLICY MODE TO ...` is the S5B (#714) path.
                // Lookahead one token because `MIGRATE` is otherwise
                // unused at this layer.
                let next = self.peek_next()?.clone();
                let is_policy_mode = matches!(&next, Token::Policy)
                    || matches!(&next, Token::Ident(name)
                        if name.eq_ignore_ascii_case("POLICY"));
                if is_policy_mode {
                    let expr = self.parse_migrate_policy_mode()?;
                    return Ok(SqlCommand::IamPolicy(expr));
                }
                Err(ParseError::expected(
                    vec!["POLICY"],
                    self.peek(),
                    self.position(),
                ))
            }
            Token::Set => {
                self.advance()?;
                if self.consume_ident_ci("CONFIG")? {
                    let full_key = self.parse_dotted_admin_path(true)?;
                    self.expect(Token::Eq)?;
                    let value = self.parse_literal_value()?;
                    Ok(SqlCommand::SetConfig {
                        key: full_key,
                        value,
                    })
                } else if self.consume_ident_ci("SECRET")? {
                    let key =
                        Self::normalize_secret_admin_path(self.parse_dotted_admin_path(true)?);
                    self.expect(Token::Eq)?;
                    let value = self.parse_literal_value()?;
                    Ok(SqlCommand::SetSecret { key, value })
                } else if self.consume_ident_ci("TENANT")? {
                    // SET TENANT 'id'  |  SET TENANT = 'id'  |
                    // SET TENANT NULL  |  SET TENANT = NULL
                    let _ = self.consume(&Token::Eq)?;
                    if self.consume_ident_ci("NULL")? {
                        Ok(SqlCommand::SetTenant(None))
                    } else {
                        let value = self.parse_literal_value()?;
                        match value {
                            Value::Text(s) => Ok(SqlCommand::SetTenant(Some(s.to_string()))),
                            Value::Null => Ok(SqlCommand::SetTenant(None)),
                            other => Err(ParseError::new(
                                format!("SET TENANT expects a text literal or NULL, got {other:?}"),
                                self.position(),
                            )),
                        }
                    }
                } else {
                    Err(ParseError::expected(
                        vec!["CONFIG", "SECRET", "TENANT"],
                        self.peek(),
                        self.position(),
                    ))
                }
            }
            Token::Ident(name) if name.eq_ignore_ascii_case("APPLY") => {
                self.advance()?;
                match self.parse_apply_migration()? {
                    QueryExpr::ApplyMigration(q) => Ok(SqlCommand::ApplyMigration(q)),
                    other => Err(ParseError::new(
                        format!("internal: APPLY MIGRATION produced unexpected kind {other:?}"),
                        self.position(),
                    )),
                }
            }
            Token::Ident(name) if name.eq_ignore_ascii_case("RESET") => {
                // RESET TENANT — session-local clear
                self.advance()?;
                if self.consume_ident_ci("TENANT")? {
                    Ok(SqlCommand::SetTenant(None))
                } else {
                    Err(ParseError::expected(
                        vec!["TENANT"],
                        self.peek(),
                        self.position(),
                    ))
                }
            }
            Token::Ident(name)
                if name.eq_ignore_ascii_case("DESCRIBE") || name.eq_ignore_ascii_case("DESC") =>
            {
                self.advance()?;
                let collection = self.parse_dotted_admin_path(false)?;
                let mut query = TableQuery::new("red.describe");
                query.filter = Some(Filter::compare(
                    FieldRef::column("", "collection"),
                    CompareOp::Eq,
                    Value::text(collection),
                ));
                Ok(SqlCommand::Select(query))
            }
            Token::Desc => {
                self.advance()?;
                let collection = self.parse_dotted_admin_path(false)?;
                let mut query = TableQuery::new("red.describe");
                query.filter = Some(Filter::compare(
                    FieldRef::column("", "collection"),
                    CompareOp::Eq,
                    Value::text(collection),
                ));
                Ok(SqlCommand::Select(query))
            }
            Token::Ident(name) if name.eq_ignore_ascii_case("SHOW") => {
                self.advance()?;
                if self.consume(&Token::Create)? || self.consume_ident_ci("CREATE")? {
                    if !(self.consume(&Token::Table)? || self.consume_ident_ci("TABLE")?) {
                        return Err(ParseError::expected(
                            vec!["TABLE"],
                            self.peek(),
                            self.position(),
                        ));
                    }
                    let collection = self.parse_dotted_admin_path(false)?;
                    let mut query = TableQuery::new("red.show_create");
                    query.filter = Some(Filter::compare(
                        FieldRef::column("", "collection"),
                        CompareOp::Eq,
                        Value::text(collection),
                    ));
                    Ok(SqlCommand::Select(query))
                } else if self.consume_ident_ci("CONFIG")? {
                    // Accept dotted prefixes the same way SET CONFIG does
                    // (`SHOW CONFIG durability.mode`), and empty prefix
                    // (`SHOW CONFIG`) for a catalog-wide listing.
                    let prefix = if !(self.check(&Token::Eof)
                        || self.check(&Token::As)
                        || self.check(&Token::Format))
                    {
                        let first = self.expect_ident()?;
                        let mut full = first;
                        while self.consume(&Token::Dot)? {
                            let next = self.expect_ident_or_keyword()?;
                            full = format!("{full}.{next}");
                        }
                        // Match SET CONFIG: lowercase so keyword segments
                        // come out consistent with the stored keys.
                        Some(full.to_ascii_lowercase())
                    } else {
                        None
                    };
                    let as_json = if self.consume(&Token::As)? || self.consume(&Token::Format)? {
                        if !self.consume(&Token::Json)? {
                            return Err(ParseError::expected(
                                vec!["JSON"],
                                self.peek(),
                                self.position(),
                            ));
                        }
                        true
                    } else {
                        false
                    };
                    Ok(SqlCommand::ShowConfig { prefix, as_json })
                } else if self.consume_ident_ci("COLLECTIONS")? {
                    let mut query = TableQuery::new("red.collections");
                    let include_internal = if self.consume_ident_ci("INCLUDING")? {
                        if !self.consume_ident_ci("INTERNAL")? {
                            return Err(ParseError::expected(
                                vec!["INTERNAL"],
                                self.peek(),
                                self.position(),
                            ));
                        }
                        true
                    } else {
                        false
                    };
                    self.parse_table_clauses(&mut query)?;
                    if !include_internal {
                        let user_filter = query.filter.take();
                        let hide_internal = crate::ast::Filter::Compare {
                            field: FieldRef::column("", "internal"),
                            op: CompareOp::Eq,
                            value: Value::Boolean(false),
                        };
                        query.filter = Some(match user_filter {
                            Some(filter) => filter.and(hide_internal),
                            None => hide_internal,
                        });
                    }
                    Ok(SqlCommand::Select(query))
                } else if self.consume_ident_ci("TABLES")? {
                    Ok(SqlCommand::Select(parse_show_collections_by_model(
                        self, "table",
                    )?))
                } else if self.consume_ident_ci("QUEUES")? {
                    // Issue #535 — `SHOW QUEUES` desugars to the
                    // `red.queues` virtual table (queue-shaped
                    // columns), not the filtered `red.collections`
                    // view. `INCLUDING INTERNAL` mirrors the
                    // `SHOW COLLECTIONS` opt-in: without it, DLQ
                    // targets and other auto-created queues are
                    // hidden via the `internal = false` filter.
                    let mut query = TableQuery::new("red.queues");
                    let include_internal = if self.consume_ident_ci("INCLUDING")? {
                        if !self.consume_ident_ci("INTERNAL")? {
                            return Err(ParseError::expected(
                                vec!["INTERNAL"],
                                self.peek(),
                                self.position(),
                            ));
                        }
                        true
                    } else {
                        false
                    };
                    self.parse_table_clauses(&mut query)?;
                    if !include_internal {
                        let hide_internal = Filter::Compare {
                            field: FieldRef::column("", "internal"),
                            op: CompareOp::Eq,
                            value: Value::Boolean(false),
                        };
                        add_table_filter(&mut query, hide_internal);
                    }
                    Ok(SqlCommand::Select(query))
                } else if self.consume(&Token::Vectors)? || self.consume_ident_ci("VECTORS")? {
                    Ok(SqlCommand::Select(parse_show_collections_by_model(
                        self, "vector",
                    )?))
                } else if self.consume_ident_ci("DOCUMENTS")? {
                    Ok(SqlCommand::Select(parse_show_collections_by_model(
                        self, "document",
                    )?))
                } else if self.consume(&Token::Timeseries)?
                    || self.consume_ident_ci("TIMESERIES")?
                {
                    Ok(SqlCommand::Select(parse_show_collections_by_model(
                        self,
                        "timeseries",
                    )?))
                } else if self.consume_ident_ci("GRAPHS")? {
                    Ok(SqlCommand::Select(parse_show_collections_by_model(
                        self, "graph",
                    )?))
                } else if self.consume_ident_ci("CONFIGS")? {
                    Ok(SqlCommand::Select(parse_show_collections_by_model(
                        self, "config",
                    )?))
                } else if self.consume_ident_ci("VAULTS")? {
                    Ok(SqlCommand::Select(parse_show_collections_by_model(
                        self, "vault",
                    )?))
                } else if self.consume(&Token::Kv)?
                    || self.consume_ident_ci("KV")?
                    || self.consume_ident_ci("KVS")?
                {
                    Ok(SqlCommand::Select(parse_show_collections_by_model(
                        self, "kv",
                    )?))
                } else if self.consume(&Token::Schema)? || self.consume_ident_ci("SCHEMA")? {
                    let collection = self.parse_dotted_admin_path(false)?;
                    let mut query = TableQuery::new("red.columns");
                    query.filter = Some(Filter::compare(
                        FieldRef::column("", "collection"),
                        CompareOp::Eq,
                        Value::text(collection),
                    ));
                    Ok(SqlCommand::Select(query))
                } else if self.consume_ident_ci("INDICES")? || self.consume_ident_ci("INDEXES")? {
                    let mut query = TableQuery::new("red.show_indexes");
                    if self.consume(&Token::On)? {
                        let collection = self.expect_ident_or_keyword()?;
                        let filter = Filter::Compare {
                            field: FieldRef::column("", "table"),
                            op: CompareOp::Eq,
                            value: Value::text(collection),
                        };
                        query.where_expr = Some(filter_to_expr(&filter));
                        query.filter = Some(filter);
                    }
                    self.parse_table_clauses(&mut query)?;
                    Ok(SqlCommand::Select(query))
                } else if self.consume_ident_ci("POLICIES")? {
                    if self.consume(&Token::For)? || self.consume_ident_ci("FOR")? {
                        let principal = self.parse_iam_principal_kind()?;
                        return Ok(SqlCommand::IamPolicy(QueryExpr::ShowPolicies {
                            filter: Some(principal),
                        }));
                    }
                    let mut query = TableQuery::new("red.policies");
                    let collection_filter =
                        if self.consume(&Token::On)? || self.consume_ident_ci("ON")? {
                            let collection = self.parse_dotted_admin_path(false)?;
                            Some(Filter::Compare {
                                field: FieldRef::TableColumn {
                                    table: String::new(),
                                    column: "collection".to_string(),
                                },
                                op: CompareOp::Eq,
                                value: Value::text(collection),
                            })
                        } else {
                            None
                        };
                    self.parse_table_clauses(&mut query)?;
                    if let Some(collection_filter) = collection_filter {
                        let combined = match query.filter.take() {
                            Some(existing) => {
                                Filter::And(Box::new(collection_filter), Box::new(existing))
                            }
                            None => collection_filter,
                        };
                        query.where_expr = Some(filter_to_expr(&combined));
                        query.filter = Some(combined);
                    }
                    Ok(SqlCommand::Select(query))
                } else if self.consume_ident_ci("STATS")? {
                    let mut query = TableQuery::new("red.stats");
                    let collection = match self.peek().clone() {
                        Token::Ident(name) => {
                            self.advance()?;
                            Some(name)
                        }
                        Token::String(name) => {
                            self.advance()?;
                            Some(name)
                        }
                        _ => None,
                    };
                    self.parse_table_clauses(&mut query)?;
                    if let Some(collection) = collection {
                        let filter = Filter::compare(
                            FieldRef::column("red.stats", "collection"),
                            CompareOp::Eq,
                            Value::text(collection),
                        );
                        let expr = filter_to_expr(&filter);
                        query.where_expr = Some(match query.where_expr.take() {
                            Some(existing) => Expr::binop(BinOp::And, existing, expr),
                            None => expr,
                        });
                        query.filter = Some(match query.filter.take() {
                            Some(existing) => existing.and(filter),
                            None => filter,
                        });
                    }
                    Ok(SqlCommand::Select(query))
                } else if self.consume_ident_ci("SAMPLE")? {
                    let mut query = TableQuery::new(&self.expect_ident()?);
                    query.limit = if self.consume(&Token::Limit)? {
                        Some(self.parse_integer()? as u64)
                    } else {
                        Some(10)
                    };
                    Ok(SqlCommand::Select(query))
                } else if self.consume_ident_ci("SECRET")? || self.consume_ident_ci("SECRETS")? {
                    let prefix = if !self.check(&Token::Eof) {
                        Some(Self::normalize_secret_admin_path(
                            self.parse_dotted_admin_path(true)?,
                        ))
                    } else {
                        None
                    };
                    Ok(SqlCommand::ShowSecrets { prefix })
                } else if self.consume_ident_ci("TENANT")? {
                    Ok(SqlCommand::ShowTenant)
                } else if let Some(expr) = self.parse_show_iam_after_show()? {
                    Ok(SqlCommand::IamPolicy(expr))
                } else {
                    Err(ParseError::expected(
                        vec![
                            "CONFIG",
                            "SECRET",
                            "SECRETS",
                            "COLLECTIONS",
                            "TABLES",
                            "QUEUES",
                            "VECTORS",
                            "DOCUMENTS",
                            "TIMESERIES",
                            "GRAPHS",
                            "KV",
                            "SCHEMA",
                            "INDICES",
                            "INDEXES",
                            "SAMPLE",
                            "POLICIES",
                            "STATS",
                            "TENANT",
                            "EFFECTIVE",
                        ],
                        self.peek(),
                        self.position(),
                    ))
                }
            }
            // Transaction control statements (Phase 1.1 PG parity).
            // BEGIN [WORK | TRANSACTION] [ISOLATION LEVEL <mode>]
            // START TRANSACTION [ISOLATION LEVEL <mode>]
            //
            // We only implement SNAPSHOT ISOLATION (our default). We
            // accept READ UNCOMMITTED / READ COMMITTED / REPEATABLE
            // READ / SNAPSHOT as PG-compatible no-ops, but reject
            // SERIALIZABLE outright — the previous behaviour of
            // silently degrading to snapshot made the parser
            // dishonest. Real SSI (Serializable Snapshot Isolation)
            // is tracked as a future milestone.
            Token::Begin | Token::Start => {
                self.advance()?;
                let _ = self.consume(&Token::Work)? || self.consume(&Token::Transaction)?;
                // Optional ISOLATION LEVEL clause.
                if self.consume_ident_ci("ISOLATION")? {
                    self.expect(Token::Level)?;
                    // The level identifier can span multiple words
                    // (READ UNCOMMITTED / READ COMMITTED / REPEATABLE
                    // READ). Collect them case-insensitively.
                    let mut parts: Vec<String> = Vec::new();
                    if self.consume_ident_ci("READ")? {
                        parts.push("READ".to_string());
                        if self.consume_ident_ci("UNCOMMITTED")? {
                            parts.push("UNCOMMITTED".to_string());
                        } else if self.consume_ident_ci("COMMITTED")? {
                            parts.push("COMMITTED".to_string());
                        } else {
                            return Err(ParseError::expected(
                                vec!["UNCOMMITTED", "COMMITTED"],
                                self.peek(),
                                self.position(),
                            ));
                        }
                    } else if self.consume_ident_ci("REPEATABLE")? {
                        parts.push("REPEATABLE".to_string());
                        if !self.consume_ident_ci("READ")? {
                            return Err(ParseError::expected(
                                vec!["READ"],
                                self.peek(),
                                self.position(),
                            ));
                        }
                        parts.push("READ".to_string());
                    } else if self.consume_ident_ci("SNAPSHOT")? {
                        parts.push("SNAPSHOT".to_string());
                    } else if self.consume_ident_ci("SERIALIZABLE")? {
                        return Err(ParseError::new(
                            "ISOLATION LEVEL SERIALIZABLE is not yet supported — reddb \
                             currently provides SNAPSHOT ISOLATION (which PG calls \
                             REPEATABLE READ). Use REPEATABLE READ / SNAPSHOT / \
                             READ COMMITTED, or omit ISOLATION LEVEL for the default."
                                .to_string(),
                            self.position(),
                        ));
                    } else {
                        return Err(ParseError::expected(
                            vec!["READ", "REPEATABLE", "SNAPSHOT", "SERIALIZABLE"],
                            self.peek(),
                            self.position(),
                        ));
                    }
                    // All accepted modes map to our snapshot engine today.
                    let _ = parts;
                }
                Ok(SqlCommand::TransactionControl(TxnControl::Begin))
            }
            // COMMIT [WORK | TRANSACTION]
            Token::Commit => {
                self.advance()?;
                let _ = self.consume(&Token::Work)? || self.consume(&Token::Transaction)?;
                Ok(SqlCommand::TransactionControl(TxnControl::Commit))
            }
            // ROLLBACK [WORK | TRANSACTION] [TO [SAVEPOINT] name]
            // ROLLBACK MIGRATION name
            Token::Rollback => {
                self.advance()?;
                if matches!(self.peek(), Token::Ident(n) if n.eq_ignore_ascii_case("MIGRATION")) {
                    match self.parse_rollback_migration_after_keyword()? {
                        QueryExpr::RollbackMigration(q) => Ok(SqlCommand::RollbackMigration(q)),
                        other => Err(ParseError::new(
                            format!(
                                "internal: ROLLBACK MIGRATION produced unexpected kind {other:?}"
                            ),
                            self.position(),
                        )),
                    }
                } else {
                    let _ = self.consume(&Token::Work)? || self.consume(&Token::Transaction)?;
                    if self.consume(&Token::To)? {
                        let _ = self.consume(&Token::Savepoint)?;
                        let name = self.expect_ident()?;
                        Ok(SqlCommand::TransactionControl(
                            TxnControl::RollbackToSavepoint(name),
                        ))
                    } else {
                        Ok(SqlCommand::TransactionControl(TxnControl::Rollback))
                    }
                }
            }
            // SAVEPOINT name
            Token::Savepoint => {
                self.advance()?;
                let name = self.expect_ident()?;
                Ok(SqlCommand::TransactionControl(TxnControl::Savepoint(name)))
            }
            // RELEASE [SAVEPOINT] name
            Token::Release => {
                self.advance()?;
                let _ = self.consume(&Token::Savepoint)?;
                let name = self.expect_ident()?;
                Ok(SqlCommand::TransactionControl(
                    TxnControl::ReleaseSavepoint(name),
                ))
            }
            // VACUUM [FULL] [table]
            Token::Vacuum => {
                self.advance()?;
                let full = self.consume(&Token::Full)?;
                let target = if self.check(&Token::Eof) {
                    None
                } else {
                    Some(self.expect_ident()?)
                };
                Ok(SqlCommand::Maintenance(MaintenanceCommand::Vacuum {
                    target,
                    full,
                }))
            }
            // REFRESH MATERIALIZED VIEW name
            Token::Refresh => {
                self.advance()?;
                self.expect(Token::Materialized)?;
                self.expect(Token::View)?;
                let name = self.expect_ident()?;
                Ok(SqlCommand::RefreshMaterializedView(
                    RefreshMaterializedViewQuery { name },
                ))
            }
            // ANALYZE [table]
            Token::Analyze => {
                self.advance()?;
                let target = if self.check(&Token::Eof) {
                    None
                } else {
                    Some(self.expect_ident()?)
                };
                Ok(SqlCommand::Maintenance(MaintenanceCommand::Analyze {
                    target,
                }))
            }
            // COPY table FROM 'path' [WITH (...)] [DELIMITER 'x'] [HEADER [true|false]]
            //
            // Accepts both PG-style `WITH (FORMAT csv, HEADER true)` and the
            // short-form `DELIMITER ',' HEADER`. The only supported format
            // today is CSV.
            Token::Copy => {
                self.advance()?;
                let table = self.expect_ident()?;
                self.expect(Token::From)?;
                let path = self.parse_string()?;

                let mut delimiter: Option<char> = None;
                let mut has_header = false;
                let format = CopyFormat::Csv;

                // Optional `WITH (FORMAT csv, HEADER true, DELIMITER ',')` block.
                // `WITH` is a reserved keyword token — accept both the keyword
                // form and the ident form that non-CTE callers sometimes emit.
                if self.consume(&Token::With)? || self.consume_ident_ci("WITH")? {
                    self.expect(Token::LParen)?;
                    loop {
                        if self.consume(&Token::Format)? || self.consume_ident_ci("FORMAT")? {
                            let _ = self.consume(&Token::Eq)?;
                            // Only CSV for now — accept the ident and move on.
                            let _ = self.expect_ident()?;
                        } else if self.consume(&Token::Header)? {
                            let _ = self.consume(&Token::Eq)?;
                            // Accept `HEADER`, `HEADER = true`, `HEADER = false`,
                            // or an ident spelling of true/false.
                            has_header = match self.peek().clone() {
                                Token::True => {
                                    self.advance()?;
                                    true
                                }
                                Token::False => {
                                    self.advance()?;
                                    false
                                }
                                Token::Ident(ref n) if n.eq_ignore_ascii_case("true") => {
                                    self.advance()?;
                                    true
                                }
                                Token::Ident(ref n) if n.eq_ignore_ascii_case("false") => {
                                    self.advance()?;
                                    false
                                }
                                _ => true,
                            };
                        } else if self.consume(&Token::Delimiter)? {
                            let _ = self.consume(&Token::Eq)?;
                            let s = self.parse_string()?;
                            delimiter = s.chars().next();
                        } else {
                            break;
                        }
                        if !self.consume(&Token::Comma)? {
                            break;
                        }
                    }
                    self.expect(Token::RParen)?;
                }

                // Short form clauses outside WITH (in either order).
                loop {
                    if self.consume(&Token::Delimiter)? {
                        let s = self.parse_string()?;
                        delimiter = s.chars().next();
                    } else if self.consume(&Token::Header)? {
                        has_header = true;
                    } else {
                        break;
                    }
                }

                Ok(SqlCommand::CopyFrom(CopyFromQuery {
                    table,
                    path,
                    format,
                    delimiter,
                    has_header,
                }))
            }
            other => Err(ParseError::expected(
                vec![
                    "SELECT",
                    "FROM",
                    "INSERT",
                    "UPDATE",
                    "DELETE",
                    "EXPLAIN",
                    "CREATE",
                    "DROP",
                    "ALTER",
                    "SET",
                    "SHOW",
                    "BEGIN",
                    "COMMIT",
                    "ROLLBACK",
                    "SAVEPOINT",
                    "RELEASE",
                    "START",
                    "VACUUM",
                    "ANALYZE",
                    "COPY",
                    "REFRESH",
                    "DESCRIBE",
                    "DESC",
                ],
                other,
                self.position(),
            )),
        }
    }
}