reddb-io-server 1.1.2

RedDB server-side engine: storage, runtime, replication, MCP, AI, and the gRPC/HTTP/RedWire/PG-wire dispatchers. Re-exported by the umbrella `reddb` crate.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
//! Parser tests

use super::*;
use crate::catalog::SubscriptionOperation;
use crate::storage::engine::vector_metadata::MetadataValue;
use crate::storage::query::ast::{
    CompareOp, ConfigCommand, ConfigValueType, DistanceMetric, EdgeDirection, Expr, FieldRef,
    Filter, FusionStrategy, JoinType, KvCommand, MetadataFilter, Projection, QueueCommand,
    TableQuery, TreeCommand, TreePosition, VectorSource,
};

/// Test helper that returns the legacy `QueryExpr` shape. The
/// top-level `parser::parse` returns `QueryWithCte` since #40; these
/// tests pre-date that change and don't exercise CTEs, so unwrap the
/// inner query for assertion ergonomics. CTE-specific tests should
/// call [`super::parse`] directly and inspect `with_clause`.
fn parse(input: &str) -> Result<QueryExpr, error::ParseError> {
    super::parse(input).map(|q| q.query)
}

#[test]
fn test_parse_simple_select() {
    let query = parse("SELECT ip, hostname FROM hosts").unwrap();
    if let QueryExpr::Table(tq) = query {
        assert_eq!(tq.table, "hosts");
        assert_eq!(tq.columns.len(), 2);
    } else {
        panic!("Expected TableQuery");
    }
}

fn assert_unsupported_token(input: &str, token: &str) {
    let err = parse(input).unwrap_err();
    assert!(
        err.to_string().contains(&format!(
            "token {token} is recognized but not supported in this position"
        )),
        "{err}"
    );
    assert!(
        !err.to_string().contains("expected:"),
        "unsupported-token errors must not render an expected list: {err}"
    );
    assert!(matches!(
        err.kind,
        ParseErrorKind::UnsupportedToken { token: ref found } if found == token
    ));
}

#[test]
fn test_parse_create_unsupported_recognized_tokens_use_clear_error() {
    for (input, token) in [("CREATE SELECT vt", "SELECT")] {
        assert_unsupported_token(input, token);
    }
}

#[test]
fn test_parse_create_graph_document_and_collection_forms() {
    let graph = parse("CREATE GRAPH g").unwrap();
    let QueryExpr::CreateTable(graph) = graph else {
        panic!("Expected CreateTableQuery");
    };
    assert_eq!(graph.name, "g");
    assert_eq!(
        graph.collection_model,
        crate::catalog::CollectionModel::Graph
    );

    let document = parse("CREATE DOCUMENT docs").unwrap();
    let QueryExpr::CreateTable(document) = document else {
        panic!("Expected CreateTableQuery");
    };
    assert_eq!(document.name, "docs");
    assert_eq!(
        document.collection_model,
        crate::catalog::CollectionModel::Document
    );

    let collection = parse("CREATE COLLECTION c KIND graph").unwrap();
    let QueryExpr::CreateCollection(collection) = collection else {
        panic!("Expected CreateCollectionQuery");
    };
    assert_eq!(collection.name, "c");
    assert_eq!(collection.kind, "graph");
    assert!(!collection.if_not_exists);

    let unknown = parse("CREATE COLLECTION c KIND mystery").unwrap();
    let QueryExpr::CreateCollection(unknown) = unknown else {
        panic!("Expected CreateCollectionQuery");
    };
    assert_eq!(unknown.kind, "mystery");

    let hll = parse("CREATE HLL h PRECISION 14").unwrap();
    let QueryExpr::ProbabilisticCommand(
        crate::storage::query::ast::ProbabilisticCommand::CreateHll {
            name, precision, ..
        },
    ) = hll
    else {
        panic!("Expected CreateHll");
    };
    assert_eq!(name, "h");
    assert_eq!(precision, 14);
}

#[test]
fn test_parse_create_vector_forms() {
    let vector = parse("CREATE VECTOR embeddings DIM 4").unwrap();
    let QueryExpr::CreateVector(vector) = vector else {
        panic!("Expected CreateVectorQuery");
    };
    assert_eq!(vector.name, "embeddings");
    assert_eq!(vector.dimension, 4);
    assert_eq!(
        vector.metric,
        crate::storage::engine::distance::DistanceMetric::Cosine
    );

    let vector = parse("CREATE VECTOR embeddings DIM 4 METRIC cosine").unwrap();
    let QueryExpr::CreateVector(vector) = vector else {
        panic!("Expected CreateVectorQuery");
    };
    assert_eq!(
        vector.metric,
        crate::storage::engine::distance::DistanceMetric::Cosine
    );

    let err = parse("CREATE VECTOR embeddings DIM 4 METRIC unknown").unwrap_err();
    assert!(err.to_string().contains("Unknown distance metric: unknown"));
    assert!(err.to_string().contains("L2, COSINE, INNER_PRODUCT"));

    let err = parse("CREATE VECTOR embeddings").unwrap_err();
    assert!(err.to_string().contains("DIM"));
}

#[test]
fn test_parse_unsupported_recognized_tokens_in_other_statement_positions() {
    assert_unsupported_token("DROP SELECT vt", "SELECT");
    assert_unsupported_token("ALTER VECTOR vt ADD COLUMN x INTEGER", "VECTOR");
}

#[test]
fn test_parse_aggregate_keywords_as_column_identifiers() {
    let create = parse("CREATE TABLE tw (word TEXT, count INTEGER, sum INTEGER, avg INTEGER, min INTEGER, max INTEGER)").unwrap();
    let QueryExpr::CreateTable(table) = create else {
        panic!("Expected CreateTableQuery");
    };
    let column_names = table
        .columns
        .iter()
        .map(|column| column.name.as_str())
        .collect::<Vec<_>>();
    assert_eq!(
        column_names,
        vec!["word", "count", "sum", "avg", "min", "max"]
    );

    let insert =
        parse("INSERT INTO tw (word, count, sum, avg, min, max) VALUES ('wolf', 5, 6, 7, 8, 9)")
            .unwrap();
    let QueryExpr::Insert(insert) = insert else {
        panic!("Expected InsertQuery");
    };
    assert_eq!(
        insert.columns,
        vec!["word", "count", "sum", "avg", "min", "max"]
    );

    let select =
        parse("SELECT count, sum, avg, min, max, SUM(count), AVG(avg), MIN(min), MAX(max) FROM tw")
            .unwrap();
    let QueryExpr::Table(table) = select else {
        panic!("Expected TableQuery");
    };
    assert!(matches!(
        &table.columns[0],
        Projection::Field(FieldRef::TableColumn { column, .. }, _) if column == "count"
    ));
    assert!(matches!(
        &table.columns[5],
        Projection::Function(name, args)
            if name == "SUM"
                && matches!(
                    args.first(),
                    Some(Projection::Field(FieldRef::TableColumn { column, .. }, _))
                        if column == "count"
                )
    ));
}

#[test]
fn test_parse_arithmetic_projection_sub() {
    // Regression: Fase 1.3 projection Pratt referenced Token::Minus
    // but the lexer emits Token::Dash. Subtraction silently fell
    // through to parse_field_ref and errored. Ensure `a - b` parses
    // into the nested Function("SUB", [col(a), col(b)]) form.
    let query = parse("SELECT a - b FROM t").unwrap();
    let QueryExpr::Table(tq) = query else {
        panic!("Expected TableQuery");
    };
    assert_eq!(tq.columns.len(), 1);
    let Projection::Function(name, args) = &tq.columns[0] else {
        panic!("expected arithmetic Function, got {:?}", tq.columns[0]);
    };
    assert_eq!(name, "SUB");
    assert_eq!(args.len(), 2);
}

#[test]
fn test_parse_arithmetic_projection_chain() {
    // `a - b - c` is left-associative → SUB(SUB(a,b), c).
    let query = parse("SELECT a - b - c FROM t").unwrap();
    let QueryExpr::Table(tq) = query else {
        panic!("Expected TableQuery");
    };
    let Projection::Function(name, args) = &tq.columns[0] else {
        panic!("expected Function");
    };
    assert_eq!(name, "SUB");
    // lhs should itself be a SUB
    assert!(matches!(&args[0], Projection::Function(n, _) if n == "SUB"));
}

#[test]
fn test_parse_cast_column_to_text() {
    let query = parse("SELECT CAST(age AS TEXT) FROM users").unwrap();
    let QueryExpr::Table(tq) = query else {
        panic!("Expected TableQuery");
    };
    assert_eq!(tq.columns.len(), 1);
    let Projection::Function(name, args) = &tq.columns[0] else {
        panic!("Expected Function, got {:?}", tq.columns[0]);
    };
    assert_eq!(name, "CAST");
    assert_eq!(args.len(), 2);
    assert!(
        matches!(&args[0], Projection::Column(c) if c == "age")
            || matches!(&args[0], Projection::Field(f, _) if matches!(f, FieldRef::TableColumn { column, .. } if column == "age"))
    );
    assert!(
        matches!(&args[1], Projection::Column(c) if c == "TYPE:TEXT")
            || matches!(&args[1], Projection::Field(f, _) if matches!(f, FieldRef::TableColumn { column, .. } if column == "TYPE:TEXT"))
    );
}

#[test]
fn test_parse_cast_with_alias() {
    let query = parse("SELECT CAST(score AS INT) AS score_int FROM matches").unwrap();
    let QueryExpr::Table(tq) = query else {
        panic!("Expected TableQuery");
    };
    let Projection::Function(name, args) = &tq.columns[0] else {
        panic!("Expected Function");
    };
    assert_eq!(name, "CAST:score_int");
    // Pratt path emits TYPE:INTEGER (DataType display); legacy path emits TYPE:INT (raw SQL name)
    assert!(
        matches!(&args[1], Projection::Column(c) if c == "TYPE:INT" || c == "TYPE:INTEGER"),
        "unexpected type arg: {:?}",
        &args[1]
    );
}

#[test]
fn test_parse_cast_literal_integer() {
    let query = parse("SELECT CAST(42 AS TEXT) FROM users").unwrap();
    let QueryExpr::Table(tq) = query else {
        panic!("Expected TableQuery");
    };
    let Projection::Function(name, args) = &tq.columns[0] else {
        panic!("Expected Function");
    };
    assert_eq!(name, "CAST");
    assert!(matches!(&args[0], Projection::Column(c) if c == "LIT:42"));
    assert!(matches!(&args[1], Projection::Column(c) if c == "TYPE:TEXT"));
}

#[test]
fn test_parse_money_scalar_function() {
    let query = parse("SELECT MONEY('BTC 0.125') FROM wallets").unwrap();
    let QueryExpr::Table(tq) = query else {
        panic!("Expected TableQuery");
    };
    let Projection::Function(name, args) = &tq.columns[0] else {
        panic!("Expected Function");
    };
    assert_eq!(name, "MONEY");
    assert_eq!(args.len(), 1);
}

#[test]
fn test_parse_between_with_column_bounds() {
    // BETWEEN where both bounds are columns decomposes into
    // AND(CompareFields(target, >=, low), CompareFields(target, <=, high)).
    let query = parse("SELECT * FROM sensors WHERE temp BETWEEN min_temp AND max_temp").unwrap();
    let QueryExpr::Table(tq) = query else {
        panic!("Expected TableQuery");
    };
    let Some(Filter::And(left, right)) = tq.filter else {
        panic!("Expected AND of CompareFields, got {:?}", tq.filter);
    };
    let Filter::CompareFields {
        op: op_lo,
        right: lo,
        ..
    } = &*left
    else {
        panic!("Expected CompareFields on lower bound");
    };
    let Filter::CompareFields {
        op: op_hi,
        right: hi,
        ..
    } = &*right
    else {
        panic!("Expected CompareFields on upper bound");
    };
    assert_eq!(*op_lo, CompareOp::Ge);
    assert_eq!(*op_hi, CompareOp::Le);
    let FieldRef::TableColumn { column: lo_col, .. } = lo else {
        panic!("lower bound not a column ref");
    };
    let FieldRef::TableColumn { column: hi_col, .. } = hi else {
        panic!("upper bound not a column ref");
    };
    assert_eq!(lo_col, "min_temp");
    assert_eq!(hi_col, "max_temp");
}

#[test]
fn test_parse_between_literal_bounds_preserved() {
    // Literal bounds still emit the classic Filter::Between form so
    // existing planner / executor paths are untouched.
    let query = parse("SELECT * FROM sensors WHERE temp BETWEEN 10 AND 20").unwrap();
    let QueryExpr::Table(tq) = query else {
        panic!("Expected TableQuery");
    };
    assert!(
        matches!(tq.filter, Some(Filter::Between { .. })),
        "literal BETWEEN must stay on the classic variant"
    );
}

#[test]
fn test_parse_between_mixed_bounds() {
    // Mixed: literal low + column high. Decomposes to
    // AND(Compare(field >= lit), CompareFields(field <= col)).
    let query = parse("SELECT * FROM sensors WHERE temp BETWEEN 0 AND max_temp").unwrap();
    let QueryExpr::Table(tq) = query else {
        panic!("Expected TableQuery");
    };
    let Some(Filter::And(left, right)) = tq.filter else {
        panic!("Expected AND for mixed bounds");
    };
    assert!(matches!(
        &*left,
        Filter::Compare {
            op: CompareOp::Ge,
            ..
        }
    ));
    assert!(matches!(
        &*right,
        Filter::CompareFields {
            op: CompareOp::Le,
            ..
        }
    ));
}

#[test]
fn test_parse_compare_rhs_bare_identifier_uses_compare_fields() {
    let query = parse("SELECT * FROM sensors WHERE temp = max_temp").unwrap();
    let QueryExpr::Table(tq) = query else {
        panic!("Expected TableQuery");
    };
    let Some(Filter::CompareFields { op, right, .. }) = tq.filter else {
        panic!("Expected CompareFields, got {:?}", tq.filter);
    };
    assert_eq!(op, CompareOp::Eq);
    let FieldRef::TableColumn { table, column } = right else {
        panic!("Expected table column rhs");
    };
    assert!(table.is_empty());
    assert_eq!(column, "max_temp");
}

#[test]
fn test_parse_compare_rhs_column_expression_stays_compare_expr() {
    let query = parse("SELECT * FROM sensors WHERE temp = max_temp + 1").unwrap();
    let QueryExpr::Table(tq) = query else {
        panic!("Expected TableQuery");
    };
    assert!(
        matches!(tq.filter, Some(Filter::CompareExpr { .. })),
        "column arithmetic rhs must stay on CompareExpr"
    );
}

#[test]
fn test_parse_compare_rhs_current_timestamp_expression_stays_compare_expr() {
    let query =
        parse("SELECT * FROM sensors WHERE created_at >= CURRENT_TIMESTAMP - 86400000").unwrap();
    let QueryExpr::Table(tq) = query else {
        panic!("Expected TableQuery");
    };
    let Some(Filter::CompareExpr { rhs, .. }) = tq.filter else {
        panic!("Expected CompareExpr, got {:?}", tq.filter);
    };
    let Expr::BinaryOp { lhs, .. } = rhs else {
        panic!("Expected binary timestamp expression");
    };
    let Expr::FunctionCall { name, args, .. } = *lhs else {
        panic!("Expected CURRENT_TIMESTAMP function call");
    };
    assert_eq!(name, "CURRENT_TIMESTAMP");
    assert!(args.is_empty());
}

#[test]
fn test_parse_cast_lowercase_keyword() {
    // keyword should be case-insensitive
    let query = parse("SELECT cast(age as float) FROM users").unwrap();
    let QueryExpr::Table(tq) = query else {
        panic!("Expected TableQuery");
    };
    let Projection::Function(name, args) = &tq.columns[0] else {
        panic!("Expected Function");
    };
    assert_eq!(name, "CAST");
    assert!(matches!(&args[1], Projection::Column(c) if c == "TYPE:FLOAT"));
}

#[test]
fn test_parse_select_star() {
    let query = parse("SELECT * FROM hosts").unwrap();
    if let QueryExpr::Table(tq) = query {
        assert_eq!(tq.table, "hosts");
        assert!(tq.columns.is_empty()); // * means all
    } else {
        panic!("Expected TableQuery");
    }
}

#[test]
fn test_parse_select_star_from_asterisk_defaults_to_any() {
    let query = parse("SELECT * FROM *").unwrap();
    if let QueryExpr::Table(tq) = query {
        assert_eq!(tq.table, "*");
    } else {
        panic!("Expected TableQuery");
    }
}

#[test]
fn test_parse_select_without_from_defaults_to_any() {
    let query = parse("SELECT *").unwrap();
    if let QueryExpr::Table(tq) = query {
        assert_eq!(tq.table, "any");
        assert_eq!(tq.columns.len(), 0);
        assert!(tq.alias.is_none());
    } else {
        panic!("Expected TableQuery");
    }
}

#[test]
fn test_parse_select_without_from_with_trailing_identifier_errors() {
    let err = parse("SELECT * docs").unwrap_err();
    assert!(matches!(err.to_string(), s if s.contains("Unexpected token after query")));
}

#[test]
fn test_parse_select_with_alias() {
    let query = parse("SELECT h.ip FROM hosts h").unwrap();
    if let QueryExpr::Table(tq) = query {
        assert_eq!(tq.table, "hosts");
        assert_eq!(tq.alias, Some("h".to_string()));
    } else {
        panic!("Expected TableQuery");
    }
}

#[test]
fn test_parse_select_any_with_alias() {
    let query = parse("SELECT * FROM ANY u").unwrap();
    if let QueryExpr::Table(tq) = query {
        assert_eq!(tq.table, "ANY");
        assert_eq!(tq.alias, Some("u".to_string()));
    } else {
        panic!("Expected TableQuery");
    }
}

#[test]
fn test_parse_select_entity_with_alias() {
    let query = parse("SELECT * FROM entity e").unwrap();
    if let QueryExpr::Table(tq) = query {
        assert_eq!(tq.table, "entity");
        assert_eq!(tq.alias, Some("e".to_string()));
    } else {
        panic!("Expected TableQuery");
    }
}

#[test]
fn test_parse_select_with_where() {
    let query = parse("SELECT ip FROM hosts WHERE os = 'Linux'").unwrap();
    if let QueryExpr::Table(tq) = query {
        assert!(tq.filter.is_some());
    } else {
        panic!("Expected TableQuery");
    }
}

#[test]
fn test_parse_select_any_with_where() {
    let query = parse("SELECT * FROM ANY WHERE _entity_type = 'graph_node'").unwrap();
    if let QueryExpr::Table(tq) = query {
        assert_eq!(tq.table, "ANY");
        assert!(tq.filter.is_some());
    } else {
        panic!("Expected TableQuery");
    }
}

#[test]
fn test_parse_select_any_with_alias_where_order_limit() {
    let query = parse("SELECT u._entity_type FROM ANY u WHERE u._entity_type = 'vector' ORDER BY u._score DESC LIMIT 10").unwrap();
    if let QueryExpr::Table(tq) = query {
        assert_eq!(tq.table, "ANY");
        assert_eq!(tq.alias.as_deref(), Some("u"));
        assert!(tq.filter.is_some());
        assert_eq!(tq.order_by.len(), 1);
        assert!(!tq.order_by[0].ascending);
        assert_eq!(tq.limit, Some(10));
    } else {
        panic!("Expected TableQuery");
    }
}

#[test]
fn test_parse_select_any_document_path_projection() {
    let query = parse("SELECT payload.name FROM ANY").unwrap();
    if let QueryExpr::Table(tq) = query {
        assert_eq!(tq.table, "ANY");
        match &tq.columns[0] {
            Projection::Field(FieldRef::TableColumn { table, column }, _) => {
                assert_eq!(table, "payload");
                assert_eq!(column, "name");
            }
            other => panic!("Expected field projection, got {other:?}"),
        }
    } else {
        panic!("Expected TableQuery");
    }
}

#[test]
fn test_parse_select_any_nested_document_path_projection() {
    let query = parse("SELECT payload.owner.name FROM ANY").unwrap();
    if let QueryExpr::Table(tq) = query {
        assert_eq!(tq.table, "ANY");
        match &tq.columns[0] {
            Projection::Field(FieldRef::TableColumn { table, column }, _) => {
                assert_eq!(table, "payload");
                assert_eq!(column, "owner.name");
            }
            other => panic!("Expected field projection, got {other:?}"),
        }
    } else {
        panic!("Expected TableQuery");
    }
}

#[test]
fn test_parse_select_alt_any_with_where() {
    let query = parse("SELECT * FROM _any WHERE _entity_type = 'vector'").unwrap();
    if let QueryExpr::Table(tq) = query {
        assert_eq!(tq.table, "_any");
        assert!(tq.alias.is_none());
        assert!(tq.filter.is_some());
    } else {
        panic!("Expected TableQuery");
    }
}

#[test]
fn test_parse_select_all_with_where() {
    let query = parse("SELECT * FROM all WHERE _entity_type = 'vector'").unwrap();
    if let QueryExpr::Table(tq) = query {
        assert_eq!(tq.table, "all");
        assert!(tq.alias.is_none());
        assert!(tq.filter.is_some());
    } else {
        panic!("Expected TableQuery");
    }
}

#[test]
fn test_parse_select_all_keyword_with_where() {
    let query = parse("SELECT * FROM ALL WHERE _entity_type = 'vector'").unwrap();
    if let QueryExpr::Table(tq) = query {
        assert_eq!(tq.table, "all");
        assert!(tq.alias.is_none());
        assert!(tq.filter.is_some());
    } else {
        panic!("Expected TableQuery");
    }
}

#[test]
fn test_parse_select_any_with_capabilities_in() {
    let query =
        parse("SELECT * FROM ANY WHERE _capabilities IN ('vector', 'graph_node', 'document')")
            .unwrap();
    if let QueryExpr::Table(tq) = query {
        match tq.filter {
            Some(Filter::In { .. }) => {}
            _ => panic!("Expected IN filter"),
        }
    } else {
        panic!("Expected TableQuery");
    }
}

#[test]
fn test_parse_select_universal_with_where() {
    let query = parse("SELECT * FROM UNIVERSAL WHERE _entity_type = 'vector'").unwrap();
    if let QueryExpr::Table(tq) = query {
        assert_eq!(tq.table, "UNIVERSAL");
        assert!(tq.filter.is_some());
    } else {
        panic!("Expected TableQuery");
    }
}

#[test]
fn test_parse_select_mixed_with_where() {
    let query = parse("SELECT * FROM mixed WHERE _entity_type = 'document'").unwrap();
    if let QueryExpr::Table(tq) = query {
        assert_eq!(tq.table, "mixed");
        assert!(tq.filter.is_some());
    } else {
        panic!("Expected TableQuery");
    }
}

#[test]
fn test_parse_select_entity_with_where() {
    let query = parse("SELECT * FROM ENTITY WHERE _entity_type = 'document'").unwrap();
    if let QueryExpr::Table(tq) = query {
        assert_eq!(tq.table, "ENTITY");
        assert!(tq.alias.is_none());
        assert!(tq.filter.is_some());
    } else {
        panic!("Expected TableQuery");
    }
}

#[test]
fn test_parse_select_entity_lowercase_without_from_alias() {
    let query = parse("SELECT * FROM entity e").unwrap();
    if let QueryExpr::Table(tq) = query {
        assert_eq!(tq.table, "entity");
        assert_eq!(tq.alias.as_deref(), Some("e"));
    } else {
        panic!("Expected TableQuery");
    }
}

#[test]
fn test_parse_select_table_alias_nested_document_path_projection() {
    let query = parse("SELECT d.payload.owner.name FROM docs AS d").unwrap();
    if let QueryExpr::Table(tq) = query {
        assert_eq!(tq.table, "docs");
        assert_eq!(tq.alias.as_deref(), Some("d"));
        match &tq.columns[0] {
            Projection::Field(FieldRef::TableColumn { table, column }, _) => {
                assert_eq!(table, "d");
                assert_eq!(column, "payload.owner.name");
            }
            other => panic!("Expected field projection, got {other:?}"),
        }
    } else {
        panic!("Expected TableQuery");
    }
}

#[test]
fn test_parse_select_with_order_limit() {
    let query = parse("SELECT ip FROM hosts ORDER BY created_at DESC LIMIT 10").unwrap();
    if let QueryExpr::Table(tq) = query {
        assert_eq!(tq.order_by.len(), 1);
        assert!(!tq.order_by[0].ascending);
        assert_eq!(tq.limit, Some(10));
    } else {
        panic!("Expected TableQuery");
    }
}

#[test]
fn test_parse_where_and_or() {
    let query = parse("SELECT * FROM hosts WHERE os = 'Linux' AND status = 'active'").unwrap();
    if let QueryExpr::Table(tq) = query {
        match tq.filter {
            Some(Filter::And(_, _)) => {}
            _ => panic!("Expected AND filter"),
        }
    } else {
        panic!("Expected TableQuery");
    }
}

#[test]
fn test_parse_where_between() {
    let query = parse("SELECT * FROM hosts WHERE port BETWEEN 80 AND 443").unwrap();
    if let QueryExpr::Table(tq) = query {
        match tq.filter {
            Some(Filter::Between { .. }) => {}
            _ => panic!("Expected BETWEEN filter"),
        }
    } else {
        panic!("Expected TableQuery");
    }
}

#[test]
fn test_parse_where_in() {
    let query = parse("SELECT * FROM hosts WHERE os IN ('Linux', 'Windows')").unwrap();
    if let QueryExpr::Table(tq) = query {
        match tq.filter {
            Some(Filter::In { values, .. }) => {
                assert_eq!(values.len(), 2);
            }
            _ => panic!("Expected IN filter"),
        }
    } else {
        panic!("Expected TableQuery");
    }
}

#[test]
fn test_parse_where_like() {
    let query = parse("SELECT * FROM hosts WHERE hostname LIKE '%server%'").unwrap();
    if let QueryExpr::Table(tq) = query {
        match tq.filter {
            Some(Filter::Like { .. }) => {}
            _ => panic!("Expected LIKE filter"),
        }
    } else {
        panic!("Expected TableQuery");
    }
}

#[test]
fn test_parse_simple_match() {
    let query = parse("MATCH (h:Host) RETURN h").unwrap();
    if let QueryExpr::Graph(gq) = query {
        assert_eq!(gq.pattern.nodes.len(), 1);
        assert_eq!(gq.pattern.nodes[0].alias, "h");
        assert_eq!(gq.pattern.nodes[0].node_label.as_deref(), Some("host"));
    } else {
        panic!("Expected GraphQuery");
    }
}

#[test]
fn test_parse_match_with_edge() {
    let query = parse("MATCH (h:Host)-[:HAS_SERVICE]->(s:Service) RETURN h, s").unwrap();
    if let QueryExpr::Graph(gq) = query {
        assert_eq!(gq.pattern.nodes.len(), 2);
        assert_eq!(gq.pattern.edges.len(), 1);
        assert_eq!(
            gq.pattern.edges[0].edge_label.as_deref(),
            Some("has_service")
        );
        assert_eq!(gq.pattern.edges[0].direction, EdgeDirection::Outgoing);
    } else {
        panic!("Expected GraphQuery");
    }
}

#[test]
fn test_parse_match_variable_length() {
    let query = parse("MATCH (a)-[*1..5]->(b) RETURN a, b").unwrap();
    if let QueryExpr::Graph(gq) = query {
        assert_eq!(gq.pattern.edges[0].min_hops, 1);
        assert_eq!(gq.pattern.edges[0].max_hops, 5);
    } else {
        panic!("Expected GraphQuery");
    }
}

#[test]
fn test_parse_match_incoming_edge() {
    let query = parse("MATCH (a)<-[:CONTAINS]-(b) RETURN a, b").unwrap();
    if let QueryExpr::Graph(gq) = query {
        assert_eq!(gq.pattern.edges[0].direction, EdgeDirection::Incoming);
    } else {
        panic!("Expected GraphQuery");
    }
}

#[test]
fn test_parse_match_limit() {
    let query = parse("MATCH (n) RETURN n LIMIT 1").unwrap();
    if let QueryExpr::Graph(gq) = query {
        assert_eq!(gq.limit, Some(1));
    } else {
        panic!("Expected GraphQuery");
    }
}

#[test]
fn test_parse_match_limit_zero() {
    let query = parse("MATCH (n) RETURN n LIMIT 0").unwrap();
    if let QueryExpr::Graph(gq) = query {
        assert_eq!(gq.limit, Some(0));
    } else {
        panic!("Expected GraphQuery");
    }
}

#[test]
fn test_parse_match_limit_rejects_negative_and_non_integer() {
    let negative = parse("MATCH (n) RETURN n LIMIT -1").unwrap_err();
    assert!(
        negative.to_string().contains("MATCH LIMIT"),
        "negative LIMIT error should name MATCH LIMIT, got {negative}"
    );

    let non_integer = parse("MATCH (n) RETURN n LIMIT nope").unwrap_err();
    assert!(
        non_integer.to_string().contains("integer"),
        "non-integer LIMIT error should mention integer, got {non_integer}"
    );
}

#[test]
fn test_parse_path_query() {
    let query =
        parse("PATH FROM host('192.168.1.1') TO host('10.0.0.1') VIA [:AUTH_ACCESS]").unwrap();
    if let QueryExpr::Path(pq) = query {
        assert_eq!(pq.via.len(), 1);
        assert_eq!(pq.via[0], "auth_access");
    } else {
        panic!("Expected PathQuery");
    }
}

#[test]
fn test_parse_join_query() {
    let query =
        parse("FROM hosts h JOIN GRAPH (n:Host)-[:AFFECTED_BY]->(v) AS g ON h.ip = n.id").unwrap();
    if let QueryExpr::Join(jq) = query {
        assert!(matches!(*jq.left, QueryExpr::Table(_)));
        match jq.right.as_ref() {
            QueryExpr::Graph(gq) => assert_eq!(gq.alias.as_deref(), Some("g")),
            _ => panic!("Expected GraphQuery"),
        }
    } else {
        panic!("Expected JoinQuery");
    }
}

#[test]
fn test_parse_join_with_universal_left_alias() {
    let query =
        parse("FROM ANY a JOIN GRAPH (n:Host)-[:AFFECTED_BY]->(v) ON a._entity_id = n.id").unwrap();
    if let QueryExpr::Join(jq) = query {
        match &*jq.left {
            QueryExpr::Table(tq) => assert_eq!(tq.alias.as_deref(), Some("a")),
            _ => panic!("Expected left table"),
        }
        assert!(matches!(*jq.right, QueryExpr::Graph(_)));
    } else {
        panic!("Expected JoinQuery");
    }
}

#[test]
fn test_parse_join_with_universal_right_alias() {
    let query =
        parse("FROM hosts h JOIN ANY a ON h.id = a._entity_id RETURN h.id, a._score").unwrap();
    if let QueryExpr::Join(jq) = query {
        match &*jq.right {
            QueryExpr::Table(tq) => {
                assert_eq!(tq.table, "ANY");
                assert_eq!(tq.alias.as_deref(), Some("a"));
            }
            _ => panic!("Expected right table"),
        }
    } else {
        panic!("Expected JoinQuery");
    }
}

#[test]
fn test_parse_join_with_all_keyword() {
    let query = parse(
        "FROM docs d JOIN ALL a ON d.id = a._entity_id WHERE a._entity_type = 'vector' LIMIT 2",
    )
    .unwrap();
    if let QueryExpr::Join(jq) = query {
        match &*jq.right {
            QueryExpr::Table(tq) => {
                assert_eq!(tq.table, "all");
                assert_eq!(tq.alias.as_deref(), Some("a"));
            }
            _ => panic!("Expected right table"),
        }
        assert!(jq.filter.is_some());
    } else {
        panic!("Expected JoinQuery");
    }
}

#[test]
fn test_parse_left_join() {
    let query = parse("FROM hosts h LEFT JOIN GRAPH (n:Host) ON h.ip = n.id").unwrap();
    if let QueryExpr::Join(jq) = query {
        assert_eq!(jq.join_type, JoinType::LeftOuter);
    } else {
        panic!("Expected JoinQuery");
    }
}

#[test]
fn test_parse_table_join_variants_and_from_subquery() {
    let query =
        parse("FROM users u RIGHT OUTER JOIN orders o ON u.id = o.user_id RETURN u.id, o.id")
            .unwrap();
    let QueryExpr::Join(join) = query else {
        panic!("Expected JoinQuery");
    };
    assert_eq!(join.join_type, JoinType::RightOuter);
    assert_eq!(join.return_.len(), 2);

    let query =
        parse("FROM users u FULL OUTER JOIN profiles p ON u.id = p.user_id WHERE p.id IS NOT NULL")
            .unwrap();
    let QueryExpr::Join(join) = query else {
        panic!("Expected JoinQuery");
    };
    assert_eq!(join.join_type, JoinType::FullOuter);
    assert!(join.filter.is_some());

    let query = parse("FROM users u CROSS JOIN regions r LIMIT 5 OFFSET 2").unwrap();
    let QueryExpr::Join(join) = query else {
        panic!("Expected JoinQuery");
    };
    assert_eq!(join.join_type, JoinType::Cross);
    assert_eq!(join.limit, Some(5));
    assert_eq!(join.offset, Some(2));

    let query = parse("FROM (SELECT id FROM users WHERE active = true) AS u RETURN u.id").unwrap();
    let QueryExpr::Table(table) = query else {
        panic!("Expected TableQuery");
    };
    assert_eq!(table.table, "__subq_u");
    assert_eq!(table.alias.as_deref(), Some("u"));
    assert_eq!(table.columns.len(), 1);
    assert!(table.source.is_some());

    assert!(parse("FROM (MATCH (n) RETURN n) AS g").is_err());
}

#[test]
fn test_parse_select_led_table_join_variants() {
    let cases = [
        (
            "SELECT u.name, o.total FROM users u JOIN orders o ON u.id = o.user_id",
            JoinType::Inner,
        ),
        (
            "SELECT u.name, o.total FROM users u INNER JOIN orders o ON u.id = o.user_id",
            JoinType::Inner,
        ),
        (
            "SELECT u.name, o.total FROM users u LEFT JOIN orders o ON u.id = o.user_id",
            JoinType::LeftOuter,
        ),
        (
            "SELECT u.name, o.total FROM users u RIGHT JOIN orders o ON u.id = o.user_id",
            JoinType::RightOuter,
        ),
        (
            "SELECT u.name, o.total FROM users u FULL JOIN orders o ON u.id = o.user_id",
            JoinType::FullOuter,
        ),
        (
            "SELECT u.name, r.name FROM users u CROSS JOIN regions r",
            JoinType::Cross,
        ),
    ];

    for (sql, expected) in cases {
        let query = parse(sql).unwrap_or_else(|err| panic!("failed to parse {sql}: {err}"));
        let QueryExpr::Join(join) = query else {
            panic!("expected SELECT-led JOIN for {sql}");
        };
        assert_eq!(join.join_type, expected, "wrong join type for {sql}");
        assert_eq!(join.return_items.len(), 2, "wrong return items for {sql}");
        assert_eq!(join.return_.len(), 2, "wrong projections for {sql}");
        let QueryExpr::Table(left) = join.left.as_ref() else {
            panic!("expected table left side for {sql}");
        };
        assert!(left.select_items.is_empty());
        assert!(left.columns.is_empty());
    }
}

#[test]
fn test_parse_select_led_multiple_table_joins() {
    let query = parse(
        "SELECT u.name, o.total, r.name \
         FROM users u JOIN orders o ON u.id = o.user_id \
         JOIN regions r ON o.region_id = r.id",
    )
    .unwrap();
    let QueryExpr::Join(join) = query else {
        panic!("expected SELECT-led JOIN");
    };
    assert_eq!(join.return_items.len(), 3);
    assert!(matches!(join.left.as_ref(), QueryExpr::Join(_)));
}

#[test]
fn test_parse_join_vector_query() {
    let query = parse(
        "FROM docs d JOIN VECTOR SEARCH embeddings SIMILAR TO [0.1, 0.2] LIMIT 5 AS sim ON d.id = sim.entity_id RETURN d.id, sim.score",
    )
    .unwrap();
    if let QueryExpr::Join(jq) = query {
        assert!(matches!(*jq.left, QueryExpr::Table(_)));
        match jq.right.as_ref() {
            QueryExpr::Vector(vq) => assert_eq!(vq.alias.as_deref(), Some("sim")),
            _ => panic!("Expected VectorQuery"),
        }
        assert_eq!(jq.limit, None);
        assert_eq!(jq.return_.len(), 2);
    } else {
        panic!("Expected JoinQuery");
    }
}

#[test]
fn test_parse_join_vector_query_with_implicit_alias() {
    let query = parse(
        "FROM docs d JOIN VECTOR SEARCH embeddings SIMILAR TO [0.1, 0.2] LIMIT 5 sim ON d.id = sim.entity_id RETURN d.id, sim.score",
    )
    .unwrap();
    if let QueryExpr::Join(jq) = query {
        match jq.right.as_ref() {
            QueryExpr::Vector(vq) => assert_eq!(vq.alias.as_deref(), Some("sim")),
            _ => panic!("Expected VectorQuery"),
        }
    } else {
        panic!("Expected JoinQuery");
    }
}

#[test]
fn test_parse_join_path_query() {
    let query = parse(
        "FROM hosts h JOIN PATH FROM host('host:a') TO host('host:b') LIMIT 4 AS p ON h.id = p.entity_id WHERE h.status = 'active' RETURN h.id, p.entity_id",
    )
    .unwrap();
    if let QueryExpr::Join(jq) = query {
        assert!(matches!(*jq.left, QueryExpr::Table(_)));
        match jq.right.as_ref() {
            QueryExpr::Path(pq) => assert_eq!(pq.alias.as_deref(), Some("p")),
            _ => panic!("Expected PathQuery"),
        }
        assert!(jq.filter.is_some());
        assert_eq!(jq.return_.len(), 2);
    } else {
        panic!("Expected JoinQuery");
    }
}

#[test]
fn test_parse_join_path_query_with_implicit_alias() {
    let query = parse(
        "FROM hosts h JOIN PATH FROM host('host:a') TO host('host:b') LIMIT 4 p ON h.id = p.entity_id RETURN h.id, p.entity_id",
    )
    .unwrap();
    if let QueryExpr::Join(jq) = query {
        match jq.right.as_ref() {
            QueryExpr::Path(pq) => assert_eq!(pq.alias.as_deref(), Some("p")),
            _ => panic!("Expected PathQuery"),
        }
    } else {
        panic!("Expected JoinQuery");
    }
}

#[test]
fn test_parse_join_hybrid_query() {
    let query = parse(
        "FROM docs d JOIN HYBRID SELECT * FROM hosts VECTOR SEARCH embeddings SIMILAR TO [0.1, 0.2] FUSION RERANK AS hy ON d.id = hy.entity_id RETURN d.id, hy.score",
    )
    .unwrap();
    if let QueryExpr::Join(jq) = query {
        assert!(matches!(*jq.left, QueryExpr::Table(_)));
        match jq.right.as_ref() {
            QueryExpr::Hybrid(hq) => assert_eq!(hq.alias.as_deref(), Some("hy")),
            _ => panic!("Expected HybridQuery"),
        }
        assert_eq!(jq.return_.len(), 2);
    } else {
        panic!("Expected JoinQuery");
    }
}

#[test]
fn test_parse_join_hybrid_query_with_implicit_alias() {
    let query = parse(
        "FROM docs d JOIN HYBRID SELECT * FROM hosts VECTOR SEARCH embeddings SIMILAR TO [0.1, 0.2] FUSION RERANK h ON d.id = h.entity_id RETURN d.id, h.score",
    )
    .unwrap();
    if let QueryExpr::Join(jq) = query {
        match jq.right.as_ref() {
            QueryExpr::Hybrid(hq) => assert_eq!(hq.alias.as_deref(), Some("h")),
            _ => panic!("Expected HybridQuery"),
        }
    } else {
        panic!("Expected JoinQuery");
    }
}

// ========================================================================
// Vector Query Tests
// ========================================================================

#[test]
fn test_parse_simple_vector_query() {
    let query = parse("VECTOR SEARCH embeddings SIMILAR TO [0.1, 0.2, 0.3] LIMIT 10").unwrap();
    if let QueryExpr::Vector(vq) = query {
        assert_eq!(vq.collection, "embeddings");
        assert_eq!(vq.k, 10);
        match vq.query_vector {
            VectorSource::Literal(v) => {
                assert_eq!(v.len(), 3);
                assert!((v[0] - 0.1).abs() < 0.001);
            }
            _ => panic!("Expected literal vector"),
        }
    } else {
        panic!("Expected VectorQuery");
    }
}

#[test]
fn test_parse_vector_query_with_text() {
    let query =
        parse("VECTOR SEARCH cve_embeddings SIMILAR TO 'remote code execution' LIMIT 5").unwrap();
    if let QueryExpr::Vector(vq) = query {
        assert_eq!(vq.collection, "cve_embeddings");
        assert_eq!(vq.k, 5);
        match vq.query_vector {
            VectorSource::Text(t) => assert_eq!(t, "remote code execution"),
            _ => panic!("Expected text source"),
        }
    } else {
        panic!("Expected VectorQuery");
    }
}

#[test]
fn test_parse_vector_query_with_subquery() {
    let query = parse(
        "VECTOR SEARCH embeddings \
         SIMILAR TO (VECTOR SEARCH seeds SIMILAR TO [1.0, 0.0] LIMIT 1) \
         LIMIT 3",
    )
    .unwrap();

    if let QueryExpr::Vector(vq) = query {
        assert_eq!(vq.collection, "embeddings");
        assert_eq!(vq.k, 3);
        match vq.query_vector {
            VectorSource::Subquery(expr) => match *expr {
                QueryExpr::Vector(inner) => {
                    assert_eq!(inner.collection, "seeds");
                    assert_eq!(inner.k, 1);
                    match inner.query_vector {
                        VectorSource::Literal(vector) => assert_eq!(vector, vec![1.0, 0.0]),
                        other => panic!("expected literal inner vector, got {other:?}"),
                    }
                }
                other => panic!("expected inner vector query, got {other:?}"),
            },
            other => panic!("expected subquery source, got {other:?}"),
        }
    } else {
        panic!("Expected VectorQuery");
    }
}

#[test]
fn test_parse_vector_query_with_filter() {
    let query =
        parse("VECTOR SEARCH docs SIMILAR TO [0.5, 0.5] WHERE source = 'nmap' LIMIT 20").unwrap();
    if let QueryExpr::Vector(vq) = query {
        assert_eq!(vq.collection, "docs");
        assert!(vq.filter.is_some());
        match vq.filter.unwrap() {
            MetadataFilter::Eq(field, value) => {
                assert_eq!(field, "source");
                assert_eq!(value, MetadataValue::String("nmap".to_string()));
            }
            _ => panic!("Expected Eq filter"),
        }
    } else {
        panic!("Expected VectorQuery");
    }
}

#[test]
fn test_parse_vector_query_with_metric() {
    // Use "embeddings" instead of "vectors" since "VECTORS" is a reserved keyword
    let query =
        parse("VECTOR SEARCH embeddings SIMILAR TO [1.0, 0.0] METRIC COSINE LIMIT 5").unwrap();
    if let QueryExpr::Vector(vq) = query {
        assert_eq!(vq.metric, Some(DistanceMetric::Cosine));
    } else {
        panic!("Expected VectorQuery");
    }
}

#[test]
fn test_parse_vector_query_full() {
    let query = parse(
        "VECTOR SEARCH knowledge SIMILAR TO 'vulnerability scan' \
         WHERE severity >= 7 AND type = 'CVE' \
         METRIC L2 THRESHOLD 0.5 INCLUDE VECTORS INCLUDE METADATA LIMIT 100",
    )
    .unwrap();
    if let QueryExpr::Vector(vq) = query {
        assert_eq!(vq.collection, "knowledge");
        assert_eq!(vq.k, 100);
        assert!(vq.filter.is_some());
        assert_eq!(vq.metric, Some(DistanceMetric::L2));
        assert_eq!(vq.threshold, Some(0.5));
        assert!(vq.include_vectors);
        assert!(vq.include_metadata);
    } else {
        panic!("Expected VectorQuery");
    }
}

#[test]
fn test_parse_hybrid_query() {
    let query = parse(
        "HYBRID \
         SELECT * FROM hosts WHERE os = 'Linux' \
         VECTOR SEARCH embeddings SIMILAR TO [0.1, 0.2] \
         FUSION RERANK(0.7) LIMIT 50",
    )
    .unwrap();
    if let QueryExpr::Hybrid(hq) = query {
        assert!(matches!(*hq.structured, QueryExpr::Table(_)));
        assert_eq!(hq.vector.collection, "embeddings");
        assert!(
            matches!(hq.fusion, FusionStrategy::Rerank { weight } if (weight - 0.7).abs() < 0.01)
        );
        assert_eq!(hq.limit, Some(50));
    } else {
        panic!("Expected HybridQuery");
    }
}

#[test]
fn test_parse_hybrid_with_graph() {
    let query = parse(
        "HYBRID \
         MATCH (h:Host)-[:HAS_SERVICE]->(s:Service) RETURN h, s \
         VECTOR SEARCH service_vectors SIMILAR TO 'ssh vulnerable' \
         FUSION RRF(60) LIMIT 20",
    )
    .unwrap();
    if let QueryExpr::Hybrid(hq) = query {
        assert!(matches!(*hq.structured, QueryExpr::Graph(_)));
        assert_eq!(hq.vector.collection, "service_vectors");
        assert!(matches!(hq.fusion, FusionStrategy::RRF { k: 60 }));
    } else {
        panic!("Expected HybridQuery");
    }
}

#[test]
fn test_parse_fusion_strategies() {
    // RERANK
    let query =
        parse("HYBRID FROM hosts VECTOR SEARCH e SIMILAR TO [0.1] FUSION RERANK LIMIT 10").unwrap();
    if let QueryExpr::Hybrid(hq) = query {
        assert!(matches!(hq.fusion, FusionStrategy::Rerank { .. }));
    }

    // RRF
    let query = parse("HYBRID FROM hosts VECTOR SEARCH e SIMILAR TO [0.1] FUSION RRF(30) LIMIT 10")
        .unwrap();
    if let QueryExpr::Hybrid(hq) = query {
        assert!(matches!(hq.fusion, FusionStrategy::RRF { k: 30 }));
    }

    // INTERSECTION
    let query =
        parse("HYBRID FROM hosts VECTOR SEARCH e SIMILAR TO [0.1] FUSION INTERSECTION LIMIT 10")
            .unwrap();
    if let QueryExpr::Hybrid(hq) = query {
        assert!(matches!(hq.fusion, FusionStrategy::Intersection));
    }

    // UNION
    let query =
        parse("HYBRID FROM hosts VECTOR SEARCH e SIMILAR TO [0.1] FUSION UNION(0.3, 0.7) LIMIT 10")
            .unwrap();
    if let QueryExpr::Hybrid(hq) = query {
        if let FusionStrategy::Union {
            structured_weight,
            vector_weight,
        } = hq.fusion
        {
            assert!((structured_weight - 0.3).abs() < 0.01);
            assert!((vector_weight - 0.7).abs() < 0.01);
        } else {
            panic!("Expected Union fusion");
        }
    }
}

// ========================================================================
// DML Tests: INSERT, UPDATE, DELETE
// ========================================================================

#[test]
fn test_parse_insert_single_row() {
    let query = parse("INSERT INTO hosts (ip, hostname) VALUES ('10.0.0.1', 'web01')").unwrap();
    if let QueryExpr::Insert(iq) = query {
        assert_eq!(iq.table, "hosts");
        assert_eq!(iq.columns, vec!["ip", "hostname"]);
        assert_eq!(iq.values.len(), 1);
        assert_eq!(iq.values[0].len(), 2);
        assert!(iq.returning.is_none());
    } else {
        panic!("Expected InsertQuery");
    }
}

#[test]
fn test_parse_insert_multi_row() {
    let query = parse(
        "INSERT INTO hosts (ip, port) VALUES ('10.0.0.1', 22), ('10.0.0.2', 80), ('10.0.0.3', 443)",
    )
    .unwrap();
    if let QueryExpr::Insert(iq) = query {
        assert_eq!(iq.table, "hosts");
        assert_eq!(iq.columns, vec!["ip", "port"]);
        assert_eq!(iq.values.len(), 3);
        assert_eq!(iq.values[0].len(), 2);
        assert_eq!(iq.values[1].len(), 2);
        assert_eq!(iq.values[2].len(), 2);
    } else {
        panic!("Expected InsertQuery");
    }
}

#[test]
fn test_parse_insert_returning_star() {
    let query =
        parse("INSERT INTO hosts (ip, hostname) VALUES ('10.0.0.1', 'web01') RETURNING *").unwrap();
    if let QueryExpr::Insert(iq) = query {
        let items = iq.returning.as_ref().expect("RETURNING parsed");
        assert_eq!(items.len(), 1);
        assert!(matches!(
            items[0],
            crate::storage::query::ast::ReturningItem::All
        ));
    } else {
        panic!("Expected InsertQuery");
    }
}

#[test]
fn test_parse_insert_returning_columns() {
    let query = parse(
        "INSERT INTO hosts (ip, hostname) VALUES ('10.0.0.1', 'web01') RETURNING ip, hostname",
    )
    .unwrap();
    if let QueryExpr::Insert(iq) = query {
        let items = iq.returning.as_ref().expect("RETURNING parsed");
        assert_eq!(items.len(), 2);
        match &items[0] {
            crate::storage::query::ast::ReturningItem::Column(c) => assert_eq!(c, "ip"),
            other => panic!("expected column, got {other:?}"),
        }
        match &items[1] {
            crate::storage::query::ast::ReturningItem::Column(c) => assert_eq!(c, "hostname"),
            other => panic!("expected column, got {other:?}"),
        }
    } else {
        panic!("Expected InsertQuery");
    }
}

#[test]
fn test_parse_insert_bare_returning_errors() {
    let err = parse("INSERT INTO hosts (ip) VALUES ('10.0.0.1') RETURNING");
    assert!(err.is_err(), "bare RETURNING must require * or column list");
}

#[test]
fn test_parse_update_returning_star() {
    let query = parse("UPDATE hosts SET hostname = 'x' WHERE ip = '10.0.0.1' RETURNING *").unwrap();
    if let QueryExpr::Update(uq) = query {
        let items = uq.returning.as_ref().expect("RETURNING parsed");
        assert_eq!(items.len(), 1);
        assert!(matches!(
            items[0],
            crate::storage::query::ast::ReturningItem::All
        ));
    } else {
        panic!("Expected UpdateQuery");
    }
}

#[test]
fn test_parse_update_returning_columns() {
    let query =
        parse("UPDATE hosts SET hostname = 'x' WHERE id = 1 RETURNING id, hostname").unwrap();
    if let QueryExpr::Update(uq) = query {
        let items = uq.returning.as_ref().expect("RETURNING parsed");
        assert_eq!(items.len(), 2);
    } else {
        panic!("Expected UpdateQuery");
    }
}

#[test]
fn test_parse_delete_returning_star() {
    let query = parse("DELETE FROM hosts WHERE id = 1 RETURNING *").unwrap();
    if let QueryExpr::Delete(dq) = query {
        let items = dq.returning.as_ref().expect("RETURNING parsed");
        assert_eq!(items.len(), 1);
        assert!(matches!(
            items[0],
            crate::storage::query::ast::ReturningItem::All
        ));
    } else {
        panic!("Expected DeleteQuery");
    }
}

#[test]
fn test_parse_delete_returning_columns() {
    let query = parse("DELETE FROM hosts WHERE id = 1 RETURNING id, hostname").unwrap();
    if let QueryExpr::Delete(dq) = query {
        let items = dq.returning.as_ref().expect("RETURNING parsed");
        assert_eq!(items.len(), 2);
    } else {
        panic!("Expected DeleteQuery");
    }
}

#[test]
fn test_parse_insert_mixed_types() {
    let query =
        parse("INSERT INTO metrics (name, value, active) VALUES ('cpu', 3.14, true)").unwrap();
    if let QueryExpr::Insert(iq) = query {
        assert_eq!(iq.values[0].len(), 3);
        assert!(matches!(
            iq.values[0][0],
            crate::storage::schema::Value::Text(_)
        ));
        assert!(matches!(
            iq.values[0][1],
            crate::storage::schema::Value::Float(_)
        ));
        assert!(matches!(
            iq.values[0][2],
            crate::storage::schema::Value::Boolean(true)
        ));
    } else {
        panic!("Expected InsertQuery");
    }
}

#[test]
fn test_parse_insert_with_password_literal_constructor() {
    let query =
        parse("INSERT INTO accounts (username, pw) VALUES ('alice', PASSWORD('MyP@ss123'))")
            .unwrap();
    if let QueryExpr::Insert(iq) = query {
        assert_eq!(
            iq.values[0][1],
            crate::storage::schema::Value::Password("@@plain@@MyP@ss123".to_string())
        );
    } else {
        panic!("Expected InsertQuery");
    }
}

#[test]
fn test_parse_insert_with_secret_literal_constructor() {
    let query =
        parse("INSERT INTO creds (name, token) VALUES ('stripe', SECRET('sk_live_abc'))").unwrap();
    if let QueryExpr::Insert(iq) = query {
        assert_eq!(
            iq.values[0][1],
            crate::storage::schema::Value::Secret(b"@@plain@@sk_live_abc".to_vec())
        );
    } else {
        panic!("Expected InsertQuery");
    }
}

#[test]
fn test_parse_dml_extended_literals_auto_embed_and_ask_forms() {
    use crate::storage::query::ast::{Expr, ReturningItem};
    use crate::storage::schema::Value;

    let query = parse(
        "INSERT INTO docs (id, body) VALUES (1, 'hello') WITH AUTO EMBED (body) USING ollama MODEL 'nomic-embed-text'",
    )
    .unwrap();
    let QueryExpr::Insert(insert) = query else {
        panic!("Expected InsertQuery");
    };
    let auto_embed = insert.auto_embed.expect("auto embed config");
    assert_eq!(auto_embed.fields, vec!["body"]);
    assert_eq!(auto_embed.provider, "ollama");
    assert_eq!(auto_embed.model.as_deref(), Some("nomic-embed-text"));

    let query = parse("INSERT INTO docs (body) VALUES ('hello') WITH AUTO EMBED (body)").unwrap();
    let QueryExpr::Insert(insert) = query else {
        panic!("Expected InsertQuery");
    };
    let auto_embed = insert.auto_embed.expect("auto embed config");
    assert_eq!(auto_embed.provider, "openai");
    assert_eq!(auto_embed.model, None);

    let query = parse(
        "INSERT INTO payloads (tags, body) VALUES (['a', true, null], {'kind' = 'event', count: 2})",
    )
    .unwrap();
    let QueryExpr::Insert(insert) = query else {
        panic!("Expected InsertQuery");
    };
    assert!(matches!(insert.values[0][0], Value::Json(_)));
    assert!(matches!(insert.values[0][1], Value::Json(_)));

    let query =
        parse("INSERT INTO cache (key) VALUES ('k') WITH EXPIRES AT '1735689600000'").unwrap();
    let QueryExpr::Insert(insert) = query else {
        panic!("Expected InsertQuery");
    };
    assert_eq!(insert.expires_at_ms, Some(1_735_689_600_000));

    let query = parse(
        "INSERT INTO events (name) VALUES ('login') WITH TTL 42 WITH METADATA (empty = [], mixed = ['a', true, null, 3, 1.5], nested = {kind: 'event', attrs: {ok: true}}, raw = {\"x\":1})",
    )
    .unwrap();
    let QueryExpr::Insert(insert) = query else {
        panic!("Expected InsertQuery");
    };
    assert_eq!(insert.ttl_ms, Some(42_000));
    assert_eq!(insert.with_metadata.len(), 4);
    assert!(insert
        .with_metadata
        .iter()
        .all(|(_, value)| matches!(value, Value::Json(_))));

    let query =
        parse("UPDATE counters SET value = value + 1 WHERE id = 7 LIMIT 50 RETURNING id").unwrap();
    let QueryExpr::Update(update) = query else {
        panic!("Expected UpdateQuery");
    };
    assert_eq!(update.limit, Some(50));
    assert_eq!(update.assignment_exprs.len(), 1);
    assert!(update.assignments.is_empty());
    assert!(matches!(
        update.returning.as_deref(),
        Some([ReturningItem::Column(col)]) if col == "id"
    ));
    assert!(matches!(
        update.assignment_exprs[0].1,
        Expr::BinaryOp { .. } | Expr::FunctionCall { .. }
    ));

    let query =
        parse("ASK 'why did login fail?' USING openai MODEL 'gpt-4.1-mini' DEPTH 3 LIMIT 25 MIN_SCORE 0.7 COLLECTION events")
            .unwrap();
    assert!(matches!(
        query,
        QueryExpr::Ask(ask)
            if ask.question == "why did login fail?"
                && ask.provider.as_deref() == Some("openai")
                && ask.model.as_deref() == Some("gpt-4.1-mini")
                && ask.depth == Some(3)
                && ask.limit == Some(25)
                && ask.min_score == Some(0.7)
                && ask.collection.as_deref() == Some("events")
                && ask.temperature.is_none()
                && ask.seed.is_none()
    ));

    // Issue #400: TEMPERATURE / SEED per-query overrides.
    let query = parse("ASK 'q' TEMPERATURE 0.7 SEED 42").unwrap();
    let QueryExpr::Ask(ask) = query else {
        panic!("Expected AskQuery");
    };
    assert_eq!(ask.temperature, Some(0.7_f32));
    assert_eq!(ask.seed, Some(42_u64));

    // Order-independent with the other clauses.
    let query = parse("ASK 'q' SEED 7 USING openai TEMPERATURE 0").unwrap();
    let QueryExpr::Ask(ask) = query else {
        panic!("Expected AskQuery");
    };
    assert_eq!(ask.provider.as_deref(), Some("openai"));
    assert_eq!(ask.temperature, Some(0.0_f32));
    assert_eq!(ask.seed, Some(7_u64));

    let query = parse("ASK 'q' USING 'groq,openai'").unwrap();
    let QueryExpr::Ask(ask) = query else {
        panic!("Expected AskQuery");
    };
    assert_eq!(ask.provider.as_deref(), Some("groq,openai"));

    let query = parse("ASK $1 USING openai LIMIT 1").unwrap();
    let QueryExpr::Ask(ask) = query else {
        panic!("Expected AskQuery");
    };
    assert_eq!(ask.question_param, Some(0));
    assert!(ask.question.is_empty());
    assert_eq!(ask.provider.as_deref(), Some("openai"));

    // Issue #395: strict citation validation is on by default and can
    // be disabled per ASK.
    let query = parse("ASK 'q' STRICT OFF").unwrap();
    let QueryExpr::Ask(ask) = query else {
        panic!("Expected AskQuery");
    };
    assert!(!ask.strict);

    let query = parse("ASK 'q' STRICT ON").unwrap();
    let QueryExpr::Ask(ask) = query else {
        panic!("Expected AskQuery");
    };
    assert!(ask.strict);

    let query = parse("ASK 'q' STREAM").unwrap();
    let QueryExpr::Ask(ask) = query else {
        panic!("Expected AskQuery");
    };
    assert!(ask.stream);
    assert!(!ask.explain);

    let query = parse("ASK 'q' CACHE TTL '5m'").unwrap();
    let QueryExpr::Ask(ask) = query else {
        panic!("Expected AskQuery");
    };
    assert!(matches!(
        ask.cache,
        crate::storage::query::ast::AskCacheClause::CacheTtl(ref ttl) if ttl == "5m"
    ));

    let query = parse("ASK 'q' NOCACHE").unwrap();
    let QueryExpr::Ask(ask) = query else {
        panic!("Expected AskQuery");
    };
    assert!(matches!(
        ask.cache,
        crate::storage::query::ast::AskCacheClause::NoCache
    ));

    let query = parse("EXPLAIN ASK 'q' USING openai LIMIT 3 MIN_SCORE 0.7 DEPTH 2").unwrap();
    let QueryExpr::Ask(ask) = query else {
        panic!("Expected AskQuery");
    };
    assert!(ask.explain);
    assert_eq!(ask.provider.as_deref(), Some("openai"));
    assert_eq!(ask.limit, Some(3));
    assert_eq!(ask.min_score, Some(0.7_f32));
    assert_eq!(ask.depth, Some(2));

    for sql in [
        "INSERT INTO docs (body) VALUES ('x') WITH UNKNOWN",
        "INSERT INTO docs (body) VALUES ('x') WITH TTL 1 parsec",
        "INSERT INTO docs (body) VALUES ('x') WITH EXPIRES AT 'tomorrow'",
        "INSERT INTO docs (body) VALUES ('x') WITH EXPIRES AT true",
        "INSERT INTO docs (body) VALUES ('x') WITH METADATA (source)",
        "INSERT INTO docs (body) VALUES ('x') WITH AUTO EMBED ()",
        "INSERT INTO docs (body) VALUES ('x') WITH AUTO EMBED (body) USING",
        "ASK",
        "ASK 'q' MODEL gpt4",
        "ASK 'q' DEPTH",
        "ASK 'q' COLLECTION",
        "ASK 'q' TEMPERATURE",
        "ASK 'q' SEED",
        "ASK 'q' STRICT",
        "ASK 'q' STRICT MAYBE",
        "ASK 'q' CACHE",
        "ASK 'q' CACHE FOR '5m'",
        "ASK 'q' CACHE TTL",
        "ASK 'q' CACHE TTL '5m' NOCACHE",
        "ASK 'q' NOCACHE CACHE TTL '5m'",
    ] {
        assert!(parse(sql).is_err(), "{sql}");
    }
}

#[test]
fn test_parse_dml_literal_value_array_and_object_branches() {
    use crate::storage::schema::Value;

    let mut parser = Parser::new("[1, 2.5]").unwrap();
    let value = parser.parse_literal_value().unwrap();
    assert!(matches!(value, Value::Vector(values) if values == vec![1.0, 2.5]));

    let mut parser = Parser::new("[]").unwrap();
    let value = parser.parse_literal_value().unwrap();
    let Value::Json(bytes) = value else {
        panic!("Expected Value::Json");
    };
    let parsed: crate::json::Value = crate::json::from_slice(&bytes).unwrap();
    assert!(parsed.as_array().is_some_and(|items| items.is_empty()));

    let mut parser = Parser::new("[PASSWORD('pw')]").unwrap();
    let value = parser.parse_literal_value().unwrap();
    let Value::Json(bytes) = value else {
        panic!("Expected Value::Json");
    };
    let parsed: crate::json::Value = crate::json::from_slice(&bytes).unwrap();
    assert_eq!(
        parsed.as_array().and_then(|items| items.first()),
        Some(&crate::json::Value::Null)
    );

    let mut parser = Parser::new(
        "{'quoted': 'text', ident = 1, type: true, nested: {ok: false}, raw: {\"x\":1}, secret: SECRET('s')}",
    )
    .unwrap();
    let value = parser.parse_literal_value().unwrap();
    let Value::Json(bytes) = value else {
        panic!("Expected Value::Json");
    };
    let parsed: crate::json::Value = crate::json::from_slice(&bytes).unwrap();
    assert_eq!(parsed.get("quoted").and_then(|v| v.as_str()), Some("text"));
    assert_eq!(parsed.get("ident").and_then(|v| v.as_f64()), Some(1.0));
    assert_eq!(parsed.get("type").and_then(|v| v.as_bool()), Some(true));
    assert_eq!(
        parsed
            .get("nested")
            .and_then(|v| v.get("ok"))
            .and_then(|v| v.as_bool()),
        Some(false)
    );
    assert_eq!(
        parsed
            .get("raw")
            .and_then(|v| v.get("x"))
            .and_then(|v| v.as_f64()),
        Some(1.0)
    );
    assert_eq!(parsed.get("secret"), Some(&crate::json::Value::Null));
}

#[test]
fn test_parse_update_with_where() {
    let query = parse("UPDATE hosts SET hostname = 'new-name' WHERE ip = '10.0.0.1'").unwrap();
    if let QueryExpr::Update(uq) = query {
        assert_eq!(uq.table, "hosts");
        assert_eq!(uq.assignments.len(), 1);
        assert_eq!(uq.assignments[0].0, "hostname");
        assert!(uq.filter.is_some());
    } else {
        panic!("Expected UpdateQuery");
    }
}

#[test]
fn test_parse_update_no_where() {
    let query = parse("UPDATE hosts SET status = 'inactive'").unwrap();
    if let QueryExpr::Update(uq) = query {
        assert_eq!(uq.table, "hosts");
        assert_eq!(uq.assignments.len(), 1);
        assert!(uq.filter.is_none());
    } else {
        panic!("Expected UpdateQuery");
    }
}

#[test]
fn test_parse_update_multiple_assignments() {
    let query =
        parse("UPDATE hosts SET hostname = 'web01', port = 8080, active = true WHERE id = 1")
            .unwrap();
    if let QueryExpr::Update(uq) = query {
        assert_eq!(uq.assignments.len(), 3);
        assert_eq!(uq.assignments[0].0, "hostname");
        assert_eq!(uq.assignments[1].0, "port");
        assert_eq!(uq.assignments[2].0, "active");
        assert!(uq.filter.is_some());
    } else {
        panic!("Expected UpdateQuery");
    }
}

#[test]
fn test_parse_delete_with_where() {
    let query = parse("DELETE FROM hosts WHERE status = 'inactive'").unwrap();
    if let QueryExpr::Delete(dq) = query {
        assert_eq!(dq.table, "hosts");
        assert!(dq.filter.is_some());
    } else {
        panic!("Expected DeleteQuery");
    }
}

#[test]
fn test_parse_delete_no_where() {
    let query = parse("DELETE FROM hosts").unwrap();
    if let QueryExpr::Delete(dq) = query {
        assert_eq!(dq.table, "hosts");
        assert!(dq.filter.is_none());
    } else {
        panic!("Expected DeleteQuery");
    }
}

#[test]
fn test_parse_set_secret() {
    let query = parse("SET SECRET mycompany.stripe.key = 'sk_live'").unwrap();
    if let QueryExpr::SetSecret { key, value } = query {
        assert_eq!(key, "mycompany.stripe.key");
        assert_eq!(value, crate::storage::schema::Value::Text("sk_live".into()));
    } else {
        panic!("Expected SetSecret");
    }
}

#[test]
fn test_parse_delete_secret() {
    let query = parse("DELETE SECRET mycompany.stripe.key").unwrap();
    if let QueryExpr::DeleteSecret { key } = query {
        assert_eq!(key, "mycompany.stripe.key");
    } else {
        panic!("Expected DeleteSecret");
    }
}

#[test]
fn test_parse_show_secret_prefix() {
    let query = parse("SHOW SECRET mycompany.stripe").unwrap();
    if let QueryExpr::ShowSecrets { prefix } = query {
        assert_eq!(prefix.as_deref(), Some("mycompany.stripe"));
    } else {
        panic!("Expected ShowSecrets");
    }
}

#[test]
fn test_parse_show_secrets_all() {
    let query = parse("SHOW SECRETS").unwrap();
    if let QueryExpr::ShowSecrets { prefix } = query {
        assert!(prefix.is_none());
    } else {
        panic!("Expected ShowSecrets");
    }
}

#[test]
fn test_parse_show_collections_desugars_to_red_collections_select() {
    let query = parse("SHOW COLLECTIONS").unwrap();
    if let QueryExpr::Table(tq) = query {
        assert_eq!(tq.table, "red.collections");
        assert!(tq.columns.is_empty());
        assert!(tq.select_items.is_empty());
        assert!(matches!(
            tq.filter,
            Some(Filter::Compare {
                field: FieldRef::TableColumn { ref column, .. },
                op: CompareOp::Eq,
                value: crate::storage::schema::Value::Boolean(false),
            }) if column == "internal"
        ));
    } else {
        panic!("Expected Table");
    }
}

#[test]
fn test_parse_show_collections_including_internal_desugars_without_filter() {
    let query = parse("SHOW COLLECTIONS INCLUDING INTERNAL").unwrap();
    if let QueryExpr::Table(tq) = query {
        assert_eq!(tq.table, "red.collections");
        assert!(tq.columns.is_empty());
        assert!(tq.select_items.is_empty());
        assert!(tq.filter.is_none());
    } else {
        panic!("Expected Table");
    }
}

#[test]
fn test_parse_show_collections_where_desugars_with_filter() {
    let query = parse("SHOW COLLECTIONS WHERE model = 'table'").unwrap();
    if let QueryExpr::Table(tq) = query {
        assert_eq!(tq.table, "red.collections");
        assert!(matches!(
            tq.filter,
            Some(Filter::And(ref left, ref right))
                if matches!(
                    left.as_ref(),
                    Filter::Compare {
                        field: FieldRef::TableColumn { column, .. },
                        op: CompareOp::Eq,
                        value: crate::storage::schema::Value::Text(value),
                    } if column == "model" && value.as_ref() == "table"
                ) && matches!(
                    right.as_ref(),
                    Filter::Compare {
                        field: FieldRef::TableColumn { column, .. },
                        op: CompareOp::Eq,
                        value: crate::storage::schema::Value::Boolean(false),
                    } if column == "internal"
                )
        ));
    } else {
        panic!("Expected Table");
    }
}

#[test]
fn test_parse_typed_show_desugars_to_red_collections_model_filter() {
    for (input, model) in [
        ("SHOW TABLES", "table"),
        ("SHOW QUEUES", "queue"),
        ("SHOW VECTORS", "vector"),
        ("SHOW DOCUMENTS", "document"),
        ("SHOW TIMESERIES", "timeseries"),
        ("SHOW GRAPHS", "graph"),
        ("SHOW KV", "kv"),
        ("SHOW KVS", "kv"),
        ("SHOW CONFIGS", "config"),
        ("SHOW VAULTS", "vault"),
    ] {
        let query = parse(input).unwrap();
        if let QueryExpr::Table(tq) = query {
            assert_eq!(tq.table, "red.collections");
            assert!(tq.columns.is_empty());
            assert!(tq.select_items.is_empty());
            assert!(matches!(
                tq.filter,
                Some(Filter::Compare {
                    field: FieldRef::TableColumn { ref column, .. },
                    op: CompareOp::Eq,
                    value: crate::storage::schema::Value::Text(ref value),
                }) if column == "model" && value.as_ref() == model
            ));
        } else {
            panic!("Expected Table for {input}");
        }
    }
}

#[test]
fn test_parse_show_schema_desugars_to_red_columns_select() {
    let query = parse("SHOW SCHEMA users").unwrap();
    if let QueryExpr::Table(tq) = query {
        assert_eq!(tq.table, "red.columns");
        assert!(matches!(
            tq.filter,
            Some(Filter::Compare {
                field: FieldRef::TableColumn { ref column, .. },
                op: CompareOp::Eq,
                value: crate::storage::schema::Value::Text(ref value),
            }) if column == "collection" && value.as_ref() == "users"
        ));
    } else {
        panic!("Expected Table");
    }
}

#[test]
fn test_parse_describe_desugars_to_red_describe_select() {
    for input in ["DESCRIBE users", "DESC users"] {
        let query = parse(input).unwrap();
        if let QueryExpr::Table(tq) = query {
            assert_eq!(tq.table, "red.describe");
            assert!(matches!(
                tq.filter,
                Some(Filter::Compare {
                    field: FieldRef::TableColumn { ref column, .. },
                    op: CompareOp::Eq,
                    value: crate::storage::schema::Value::Text(ref value),
                }) if column == "collection" && value.as_ref() == "users"
            ));
        } else {
            panic!("Expected Table for {input}");
        }
    }
}

#[test]
fn test_parse_show_indices_desugars_to_red_indices_select() {
    let query = parse("SHOW INDICES").unwrap();
    if let QueryExpr::Table(tq) = query {
        assert_eq!(tq.table, "red.indices");
        assert!(tq.columns.is_empty());
        assert!(tq.select_items.is_empty());
        assert!(tq.filter.is_none());
    } else {
        panic!("Expected Table");
    }
}

#[test]
fn test_parse_show_indices_on_desugars_with_collection_filter() {
    let query = parse("SHOW INDICES ON users").unwrap();
    if let QueryExpr::Table(tq) = query {
        assert_eq!(tq.table, "red.indices");
        assert!(matches!(
            tq.filter,
            Some(Filter::Compare {
                field: FieldRef::TableColumn { ref column, .. },
                op: CompareOp::Eq,
                value: crate::storage::schema::Value::Text(ref value),
            }) if column == "collection" && value.as_ref() == "users"
        ));
    } else {
        panic!("Expected Table");
    }
}

#[test]
fn test_parse_show_policies_desugars_to_red_policies_select() {
    let query = parse("SHOW POLICIES").unwrap();
    if let QueryExpr::Table(tq) = query {
        assert_eq!(tq.table, "red.policies");
        assert!(tq.columns.is_empty());
        assert!(tq.select_items.is_empty());
        assert!(tq.filter.is_none());
    } else {
        panic!("Expected Table");
    }
}

#[test]
fn test_parse_show_policies_on_desugars_with_collection_filter() {
    let query = parse("SHOW POLICIES ON users").unwrap();
    if let QueryExpr::Table(tq) = query {
        assert_eq!(tq.table, "red.policies");
        assert!(matches!(
            tq.filter,
            Some(Filter::Compare {
                field: FieldRef::TableColumn { ref column, .. },
                op: CompareOp::Eq,
                value: crate::storage::schema::Value::Text(ref value),
            }) if column == "collection" && value.as_ref() == "users"
        ));
    } else {
        panic!("Expected Table");
    }
}

#[test]
fn test_parse_show_stats_desugars_to_red_stats_select() {
    let query = parse("SHOW STATS").unwrap();
    if let QueryExpr::Table(tq) = query {
        assert_eq!(tq.table, "red.stats");
        assert!(tq.columns.is_empty());
        assert!(tq.select_items.is_empty());
        assert!(tq.filter.is_none());
    } else {
        panic!("Expected Table");
    }
}

#[test]
fn test_parse_show_stats_name_desugars_with_collection_filter() {
    let query = parse("SHOW STATS users").unwrap();
    if let QueryExpr::Table(tq) = query {
        assert_eq!(tq.table, "red.stats");
        assert!(matches!(
            tq.filter,
            Some(Filter::Compare {
                field: FieldRef::TableColumn { ref column, .. },
                op: CompareOp::Eq,
                value: crate::storage::schema::Value::Text(ref value),
            }) if column == "collection" && value.as_ref() == "users"
        ));
    } else {
        panic!("Expected Table");
    }
}

#[test]
fn test_parse_events_status_desugars_to_red_subscriptions_select() {
    let query = parse("EVENTS STATUS").unwrap();
    if let QueryExpr::Table(tq) = query {
        assert_eq!(tq.table, "red.subscriptions");
        assert!(tq.columns.is_empty());
        assert!(tq.select_items.is_empty());
        assert!(tq.filter.is_none());
    } else {
        panic!("Expected Table");
    }
}

#[test]
fn test_parse_events_status_name_desugars_with_collection_filter() {
    let query = parse("EVENTS STATUS users").unwrap();
    if let QueryExpr::Table(tq) = query {
        assert_eq!(tq.table, "red.subscriptions");
        assert!(matches!(
            tq.filter,
            Some(Filter::Compare {
                field: FieldRef::TableColumn { ref column, .. },
                op: CompareOp::Eq,
                value: crate::storage::schema::Value::Text(ref value),
            }) if column == "collection" && value.as_ref() == "users"
        ));
    } else {
        panic!("Expected Table");
    }
}

#[test]
fn test_parse_show_sample_desugars_to_limited_select() {
    let query = parse("SHOW SAMPLE users").unwrap();
    if let QueryExpr::Table(tq) = query {
        assert_eq!(tq.table, "users");
        assert!(tq.columns.is_empty());
        assert!(tq.select_items.is_empty());
        assert_eq!(tq.limit, Some(10));
        assert!(tq.filter.is_none());
        assert!(tq.order_by.is_empty());
    } else {
        panic!("Expected Table");
    }
}

#[test]
fn test_parse_show_sample_accepts_explicit_limit() {
    let query = parse("SHOW SAMPLE users LIMIT 5").unwrap();
    if let QueryExpr::Table(tq) = query {
        assert_eq!(tq.table, "users");
        assert_eq!(tq.limit, Some(5));
    } else {
        panic!("Expected Table");
    }
}

#[test]
fn test_parse_show_sample_rejects_where_and_order_by() {
    assert!(parse("SHOW SAMPLE users WHERE active = true").is_err());
    assert!(parse("SHOW SAMPLE users ORDER BY id").is_err());
}

#[test]
fn test_parse_dollar_secret_reference_projection() {
    let query = parse("SELECT $secret.mycompany.stripe.key AS secret_value FROM tokens").unwrap();
    if let QueryExpr::Table(tq) = query {
        assert_eq!(tq.table, "tokens");
        assert_eq!(tq.columns.len(), 1);
        match &tq.columns[0] {
            Projection::Function(name, args) => {
                assert_eq!(name, "__SECRET_REF:secret_value");
                assert_eq!(args.len(), 1);
            }
            other => panic!("Expected secret projection function, got {other:?}"),
        }
    } else {
        panic!("Expected TableQuery");
    }
}

#[test]
fn test_parse_dollar_secret_reference_filter() {
    let query = parse("SELECT id FROM tokens WHERE token = $red.secret.tokens.active").unwrap();
    if let QueryExpr::Table(tq) = query {
        assert_eq!(tq.table, "tokens");
        assert!(
            matches!(tq.filter, Some(Filter::CompareExpr { .. })),
            "secret reference RHS must parse as CompareExpr"
        );
    } else {
        panic!("Expected TableQuery");
    }
}

#[test]
fn test_parse_dollar_config_reference_projection() {
    let query = parse("SELECT $red.config.ai.provider AS provider FROM tokens").unwrap();
    if let QueryExpr::Table(tq) = query {
        match &tq.columns[0] {
            Projection::Function(name, args) => {
                assert_eq!(name, "CONFIG:provider");
                assert_eq!(args.len(), 1);
            }
            other => panic!("Expected config projection function, got {other:?}"),
        }
    } else {
        panic!("Expected TableQuery");
    }
}

// ========================================================================
// DDL Tests: CREATE TABLE, DROP TABLE, ALTER TABLE
// ========================================================================

#[test]
fn test_parse_create_table_simple() {
    let query = parse("CREATE TABLE hosts (ip TEXT, hostname TEXT, port INTEGER)").unwrap();
    if let QueryExpr::CreateTable(ct) = query {
        assert_eq!(ct.collection_model, crate::catalog::CollectionModel::Table);
        assert_eq!(ct.name, "hosts");
        assert_eq!(ct.columns.len(), 3);
        assert!(!ct.if_not_exists);
        assert_eq!(ct.default_ttl_ms, None);
        assert_eq!(ct.columns[0].name, "ip");
        assert_eq!(ct.columns[0].data_type, "TEXT");
        assert_eq!(ct.columns[1].name, "hostname");
        assert_eq!(ct.columns[2].name, "port");
        assert_eq!(ct.columns[2].data_type, "INTEGER");
    } else {
        panic!("Expected CreateTableQuery");
    }
}

#[test]
fn test_parse_create_keyed_models() {
    use crate::catalog::CollectionModel;

    for (sql, name, model, if_not_exists) in [
        ("CREATE KV sessions", "sessions", CollectionModel::Kv, false),
        (
            "CREATE CONFIG IF NOT EXISTS app_settings",
            "app_settings",
            CollectionModel::Config,
            true,
        ),
        (
            "CREATE VAULT secrets",
            "secrets",
            CollectionModel::Vault,
            false,
        ),
    ] {
        match parse(sql).unwrap() {
            QueryExpr::CreateTable(query) => {
                assert_eq!(query.name, name);
                assert_eq!(query.collection_model, model);
                assert_eq!(query.if_not_exists, if_not_exists);
                assert!(query.columns.is_empty());
            }
            other => panic!("unexpected parse result for {sql}: {other:?}"),
        }
    }
}

#[test]
fn test_parse_create_vault_with_own_master_key() {
    match parse("CREATE VAULT secrets WITH OWN MASTER KEY").unwrap() {
        QueryExpr::CreateTable(query) => {
            assert_eq!(query.name, "secrets");
            assert_eq!(
                query.collection_model,
                crate::catalog::CollectionModel::Vault
            );
            assert!(query.vault_own_master_key);
        }
        other => panic!("unexpected parse result: {other:?}"),
    }
}

#[test]
fn test_parse_create_table_full() {
    let query = parse(
        "CREATE TABLE IF NOT EXISTS users (\
         id INTEGER PRIMARY KEY, \
         email TEXT NOT NULL UNIQUE, \
         name TEXT DEFAULT = 'unknown', \
         bio TEXT COMPRESS:3\
         )",
    )
    .unwrap();
    if let QueryExpr::CreateTable(ct) = query {
        assert_eq!(ct.name, "users");
        assert!(ct.if_not_exists);
        assert_eq!(ct.default_ttl_ms, None);
        assert_eq!(ct.columns.len(), 4);

        // id column
        assert_eq!(ct.columns[0].name, "id");
        assert_eq!(ct.columns[0].data_type, "INTEGER");
        assert!(ct.columns[0].primary_key);

        // email column
        assert_eq!(ct.columns[1].name, "email");
        assert_eq!(ct.columns[1].data_type, "TEXT");
        assert!(ct.columns[1].not_null);
        assert!(ct.columns[1].unique);

        // name column
        assert_eq!(ct.columns[2].name, "name");
        assert_eq!(ct.columns[2].default, Some("unknown".to_string()));

        // bio column
        assert_eq!(ct.columns[3].name, "bio");
        assert_eq!(ct.columns[3].compress, Some(3));
    } else {
        panic!("Expected CreateTableQuery");
    }
}

#[test]
fn test_parse_create_table_with_enum() {
    let query =
        parse("CREATE TABLE statuses (status ENUM('active','inactive','pending'))").unwrap();
    if let QueryExpr::CreateTable(ct) = query {
        assert_eq!(
            ct.columns[0].data_type,
            "ENUM('active','inactive','pending')"
        );
        assert_eq!(ct.default_ttl_ms, None);
    } else {
        panic!("Expected CreateTableQuery");
    }
}

#[test]
fn test_parse_create_table_with_ttl_clause() {
    let query = parse("CREATE TABLE sessions (token TEXT, user_id TEXT) WITH TTL 60s").unwrap();
    if let QueryExpr::CreateTable(ct) = query {
        assert_eq!(ct.name, "sessions");
        assert_eq!(ct.default_ttl_ms, Some(60_000));
        assert_eq!(ct.columns.len(), 2);
    } else {
        panic!("Expected CreateTableQuery");
    }
}

#[test]
fn test_parse_create_table_with_events_default_queue() {
    let query = parse("CREATE TABLE users (id INT) WITH EVENTS").unwrap();
    let QueryExpr::CreateTable(ct) = query else {
        panic!("Expected CreateTableQuery");
    };
    assert_eq!(ct.subscriptions.len(), 1);
    let subscription = &ct.subscriptions[0];
    assert_eq!(subscription.source, "users");
    assert_eq!(subscription.target_queue, "users_events");
    assert!(subscription.ops_filter.is_empty());
    assert!(subscription.redact_fields.is_empty());
    assert_eq!(subscription.where_filter, None);
    assert!(subscription.enabled);
}

#[test]
fn test_parse_create_table_with_events_options() {
    let query = parse(
        "CREATE TABLE users (id INT, email TEXT, phone TEXT, status TEXT) WITH EVENTS (INSERT, UPDATE) TO audit_log REDACT (email, phone) WHERE status = 'active'",
    )
    .unwrap();
    let QueryExpr::CreateTable(ct) = query else {
        panic!("Expected CreateTableQuery");
    };
    let subscription = &ct.subscriptions[0];
    assert_eq!(subscription.target_queue, "audit_log");
    assert_eq!(
        subscription.ops_filter,
        vec![SubscriptionOperation::Insert, SubscriptionOperation::Update]
    );
    assert_eq!(subscription.redact_fields, vec!["email", "phone"]);
    assert_eq!(
        subscription.where_filter.as_deref(),
        Some("status = 'active'")
    );
}

#[test]
fn test_parse_events_backfill() {
    let query = parse("EVENTS BACKFILL users WHERE status = 'active' TO audit LIMIT 10").unwrap();
    let QueryExpr::EventsBackfill(backfill) = query else {
        panic!("Expected EventsBackfill");
    };
    assert_eq!(backfill.collection, "users");
    assert_eq!(backfill.where_filter.as_deref(), Some("status = 'active'"));
    assert_eq!(backfill.target_queue, "audit");
    assert_eq!(backfill.limit, Some(10));
}

#[test]
fn test_parse_events_backfill_status_stub() {
    let query = parse("EVENTS BACKFILL STATUS users").unwrap();
    let QueryExpr::EventsBackfillStatus { collection } = query else {
        panic!("Expected EventsBackfillStatus");
    };
    assert_eq!(collection, "users");
}

#[test]
fn test_parse_drop_table() {
    let query = parse("DROP TABLE hosts").unwrap();
    if let QueryExpr::DropTable(dt) = query {
        assert_eq!(dt.name, "hosts");
        assert!(!dt.if_exists);
    } else {
        panic!("Expected DropTableQuery");
    }
}

#[test]
fn test_parse_drop_table_if_exists() {
    let query = parse("DROP TABLE IF EXISTS hosts").unwrap();
    if let QueryExpr::DropTable(dt) = query {
        assert_eq!(dt.name, "hosts");
        assert!(dt.if_exists);
    } else {
        panic!("Expected DropTableQuery");
    }
}

#[test]
fn test_parse_polymorphic_drop_models() {
    let cases = [
        ("DROP GRAPH identity", "identity", false, "graph"),
        ("DROP VECTOR notes", "notes", false, "vector"),
        ("DROP DOCUMENT logs", "logs", false, "document"),
        ("DROP KV settings", "settings", false, "kv"),
        ("DROP CONFIG app_settings", "app_settings", false, "config"),
        ("DROP VAULT secrets", "secrets", false, "vault"),
        (
            "DROP COLLECTION IF EXISTS users",
            "users",
            true,
            "collection",
        ),
    ];

    for (sql, name, if_exists, kind) in cases {
        match (parse(sql).unwrap(), kind) {
            (QueryExpr::DropGraph(query), "graph") => {
                assert_eq!(query.name, name);
                assert_eq!(query.if_exists, if_exists);
            }
            (QueryExpr::DropVector(query), "vector") => {
                assert_eq!(query.name, name);
                assert_eq!(query.if_exists, if_exists);
            }
            (QueryExpr::DropDocument(query), "document") => {
                assert_eq!(query.name, name);
                assert_eq!(query.if_exists, if_exists);
            }
            (QueryExpr::DropKv(query), "kv") => {
                assert_eq!(query.name, name);
                assert_eq!(query.if_exists, if_exists);
                assert_eq!(query.model, crate::catalog::CollectionModel::Kv);
            }
            (QueryExpr::DropKv(query), "config") => {
                assert_eq!(query.name, name);
                assert_eq!(query.if_exists, if_exists);
                assert_eq!(query.model, crate::catalog::CollectionModel::Config);
            }
            (QueryExpr::DropKv(query), "vault") => {
                assert_eq!(query.name, name);
                assert_eq!(query.if_exists, if_exists);
                assert_eq!(query.model, crate::catalog::CollectionModel::Vault);
            }
            (QueryExpr::DropCollection(query), "collection") => {
                assert_eq!(query.name, name);
                assert_eq!(query.if_exists, if_exists);
            }
            (other, _) => panic!("unexpected parse result for {sql}: {other:?}"),
        }
    }
}

#[test]
fn test_parse_polymorphic_truncate_models() {
    use crate::catalog::CollectionModel;

    let cases = [
        (
            "TRUNCATE TABLE users",
            "users",
            false,
            Some(CollectionModel::Table),
        ),
        (
            "TRUNCATE GRAPH identity",
            "identity",
            false,
            Some(CollectionModel::Graph),
        ),
        (
            "TRUNCATE VECTOR notes",
            "notes",
            false,
            Some(CollectionModel::Vector),
        ),
        (
            "TRUNCATE DOCUMENT IF EXISTS logs",
            "logs",
            true,
            Some(CollectionModel::Document),
        ),
        (
            "TRUNCATE TIMESERIES metrics",
            "metrics",
            false,
            Some(CollectionModel::TimeSeries),
        ),
        (
            "TRUNCATE KV settings",
            "settings",
            false,
            Some(CollectionModel::Kv),
        ),
        (
            "TRUNCATE QUEUE tasks",
            "tasks",
            false,
            Some(CollectionModel::Queue),
        ),
        ("TRUNCATE COLLECTION IF EXISTS users", "users", true, None),
    ];

    for (sql, name, if_exists, model) in cases {
        match parse(sql).unwrap() {
            QueryExpr::Truncate(query) => {
                assert_eq!(query.name, name);
                assert_eq!(query.if_exists, if_exists);
                assert_eq!(query.model, model);
            }
            other => panic!("unexpected parse result for {sql}: {other:?}"),
        }
    }
}

#[test]
fn test_parse_alter_table_add_column() {
    let query = parse("ALTER TABLE hosts ADD COLUMN status TEXT NOT NULL").unwrap();
    if let QueryExpr::AlterTable(at) = query {
        assert_eq!(at.name, "hosts");
        assert_eq!(at.operations.len(), 1);
        match &at.operations[0] {
            crate::storage::query::ast::AlterOperation::AddColumn(col) => {
                assert_eq!(col.name, "status");
                assert_eq!(col.data_type, "TEXT");
                assert!(col.not_null);
            }
            _ => panic!("Expected AddColumn"),
        }
    } else {
        panic!("Expected AlterTableQuery");
    }
}

#[test]
fn test_parse_alter_table_drop_column() {
    let query = parse("ALTER TABLE hosts DROP COLUMN old_field").unwrap();
    if let QueryExpr::AlterTable(at) = query {
        assert_eq!(at.name, "hosts");
        assert_eq!(at.operations.len(), 1);
        match &at.operations[0] {
            crate::storage::query::ast::AlterOperation::DropColumn(name) => {
                assert_eq!(name, "old_field");
            }
            _ => panic!("Expected DropColumn"),
        }
    } else {
        panic!("Expected AlterTableQuery");
    }
}

#[test]
fn test_parse_alter_table_rename_column() {
    let query = parse("ALTER TABLE hosts RENAME COLUMN old_name TO new_name").unwrap();
    if let QueryExpr::AlterTable(at) = query {
        assert_eq!(at.name, "hosts");
        assert_eq!(at.operations.len(), 1);
        match &at.operations[0] {
            crate::storage::query::ast::AlterOperation::RenameColumn { from, to } => {
                assert_eq!(from, "old_name");
                assert_eq!(to, "new_name");
            }
            _ => panic!("Expected RenameColumn"),
        }
    } else {
        panic!("Expected AlterTableQuery");
    }
}

#[test]
fn test_parse_ddl_table_options_types_and_alter_forms() {
    use crate::storage::query::ast::{AlterOperation, ExplainFormat, PartitionKind};

    let mut legacy_parser = Parser::new(
        "CREATE TABLE legacy (id INT, body TEXT) WITH CONTEXT INDEX ON (body) WITH TIMESTAMPS = true WITH TTL 2 h",
    )
    .unwrap();
    let legacy = legacy_parser.parse_create_table_query().unwrap();
    let QueryExpr::CreateTable(table) = legacy else {
        panic!("Expected CreateTableQuery");
    };
    assert_eq!(table.name, "legacy");
    assert_eq!(table.context_index_fields, vec!["body"]);
    assert!(table.context_index_enabled);
    assert!(table.timestamps);
    assert_eq!(table.default_ttl_ms, Some(7_200_000));

    let mut legacy_parser = Parser::new("DROP TABLE IF EXISTS legacy").unwrap();
    let legacy = legacy_parser.parse_drop_table_query().unwrap();
    assert!(matches!(
        legacy,
        QueryExpr::DropTable(drop) if drop.name == "legacy" && drop.if_exists
    ));

    let query = parse(
        "CREATE TABLE IF NOT EXISTS audit (\
         id DECIMAL(10) PRIMARY KEY, \
         tags ARRAY(TEXT), \
         active BOOLEAN DEFAULT = true, \
         score FLOAT DEFAULT = 1.5, \
         deleted_at TEXT DEFAULT = null\
         ) WITH (tenant_by = 'tenant_id', append_only = true, timestamps = true, context_index = false)",
    )
    .unwrap();
    let QueryExpr::CreateTable(table) = query else {
        panic!("Expected CreateTableQuery");
    };
    assert_eq!(table.name, "audit");
    assert!(table.if_not_exists);
    assert_eq!(table.tenant_by.as_deref(), Some("tenant_id"));
    assert!(table.append_only);
    assert!(table.timestamps);
    assert!(!table.context_index_enabled);
    assert_eq!(table.columns[0].decimal_precision, Some(10));
    assert_eq!(table.columns[1].array_element.as_deref(), Some("TEXT"));
    assert_eq!(table.columns[2].default.as_deref(), Some("true"));
    assert_eq!(table.columns[3].default.as_deref(), Some("1.5"));
    assert_eq!(table.columns[4].default.as_deref(), Some("null"));

    let query =
        parse("CREATE TABLE events (id INT) PARTITION BY HASH (id) APPEND ONLY TENANT BY (metadata.tenant)")
            .unwrap();
    let QueryExpr::CreateTable(table) = query else {
        panic!("Expected CreateTableQuery");
    };
    assert_eq!(
        table.partition_by.expect("partition").kind,
        PartitionKind::Hash
    );
    assert!(table.append_only);
    assert_eq!(table.tenant_by.as_deref(), Some("METADATA.tenant"));

    let query =
        parse("EXPLAIN ALTER FOR CREATE TABLE users (id INT, email TEXT NOT NULL) FORMAT JSON")
            .unwrap();
    assert!(matches!(
        query,
        QueryExpr::ExplainAlter(explain) if matches!(explain.format, ExplainFormat::Json)
            && explain.target.name == "users"
    ));

    let query = parse(
        "ALTER TABLE users ADD nickname TEXT DEFAULT = 'n/a', DROP old_name, RENAME nickname TO display_name",
    )
    .unwrap();
    let QueryExpr::AlterTable(alter) = query else {
        panic!("Expected AlterTableQuery");
    };
    assert_eq!(alter.operations.len(), 3);
    assert!(matches!(alter.operations[0], AlterOperation::AddColumn(_)));
    assert!(matches!(alter.operations[1], AlterOperation::DropColumn(_)));
    assert!(matches!(
        alter.operations[2],
        AlterOperation::RenameColumn { .. }
    ));

    let query = parse("ALTER TABLE users ENABLE TENANCY ON (metadata.tenant)").unwrap();
    assert!(matches!(
        query,
        QueryExpr::AlterTable(alter)
            if matches!(&alter.operations[0], AlterOperation::EnableTenancy { column } if column == "METADATA.tenant")
    ));

    let query = parse("ALTER TABLE users DISABLE TENANCY").unwrap();
    assert!(matches!(
        query,
        QueryExpr::AlterTable(alter)
            if matches!(alter.operations[0], AlterOperation::DisableTenancy)
    ));

    let query = parse("ALTER TABLE users ENABLE EVENTS (DELETE) TO audit_log").unwrap();
    let QueryExpr::AlterTable(alter) = query else {
        panic!("Expected AlterTableQuery");
    };
    match &alter.operations[0] {
        AlterOperation::EnableEvents(subscription) => {
            assert_eq!(subscription.source, "users");
            assert_eq!(subscription.target_queue, "audit_log");
            assert_eq!(subscription.ops_filter, vec![SubscriptionOperation::Delete]);
        }
        other => panic!("expected EnableEvents, got {other:?}"),
    }

    let query = parse("ALTER TABLE users DISABLE EVENTS").unwrap();
    assert!(matches!(
        query,
        QueryExpr::AlterTable(alter)
            if matches!(alter.operations[0], AlterOperation::DisableEvents)
    ));

    let query = parse("ALTER TABLE users SET APPEND_ONLY = false").unwrap();
    assert!(matches!(
        query,
        QueryExpr::AlterTable(alter)
            if matches!(alter.operations[0], AlterOperation::SetAppendOnly(false))
    ));

    let query = parse("ALTER TABLE users SET VERSIONED = true").unwrap();
    assert!(matches!(
        query,
        QueryExpr::AlterTable(alter)
            if matches!(alter.operations[0], AlterOperation::SetVersioned(true))
    ));

    for sql in [
        "CREATE TABLE bad (id INT NOT UNIQUE)",
        "CREATE TABLE bad (id INT DEFAULT = {})",
        "CREATE TABLE bad (id INT) WITH (tenant_by = 42)",
        "CREATE TABLE bad (id INT) WITH (append_only = maybe)",
        "CREATE TABLE bad (id INT) WITH unknown = true",
        "CREATE TABLE bad (id INT) WITH TTL 0.1 ms",
        "CREATE TABLE bad (id INT) WITH TTL 1 parsec",
        "CREATE TABLE bad (id INT) WITH TTL -1 s",
        "CREATE TABLE bad (id INT) PARTITION BY RANDOM (id)",
        "CREATE TABLE bad (id INT) APPEND SOMETIMES",
        "CREATE TABLE bad (id INT) TENANT id",
        "EXPLAIN ALTER FOR CREATE TABLE bad (id INT) FORMAT YAML",
        "ALTER TABLE users ENABLE TENANCY id",
        "ALTER TABLE users SET OTHER = true",
        "ALTER TABLE users UNKNOWN action",
    ] {
        assert!(parse(sql).is_err(), "{sql}");
    }
}

// ========================================================================
// INSERT with entity types: NODE, EDGE, VECTOR, DOCUMENT, KV
// ========================================================================

#[test]
fn test_parse_insert_row_default() {
    let query = parse("INSERT INTO hosts (ip, port) VALUES ('10.0.0.1', 22)").unwrap();
    if let QueryExpr::Insert(ins) = query {
        assert_eq!(ins.table, "hosts");
        assert_eq!(
            ins.entity_type,
            crate::storage::query::ast::InsertEntityType::Row
        );
        assert_eq!(ins.columns, vec!["ip", "port"]);
        assert_eq!(ins.values.len(), 1);
    } else {
        panic!("Expected InsertQuery");
    }
}

#[test]
fn test_parse_insert_node() {
    let query = parse(
        "INSERT INTO network NODE (label, node_type, ip) VALUES ('router', 'device', '10.0.0.1')",
    )
    .unwrap();
    if let QueryExpr::Insert(ins) = query {
        assert_eq!(ins.table, "network");
        assert_eq!(
            ins.entity_type,
            crate::storage::query::ast::InsertEntityType::Node
        );
        assert_eq!(ins.columns, vec!["label", "node_type", "ip"]);
        assert_eq!(ins.values.len(), 1);
        assert_eq!(ins.values[0].len(), 3);
    } else {
        panic!("Expected InsertQuery with Node entity type");
    }
}

#[test]
fn test_parse_insert_edge() {
    let query =
        parse("INSERT INTO network EDGE (label, from, to, weight) VALUES ('connects', 1, 2, 0.5)")
            .unwrap();
    if let QueryExpr::Insert(ins) = query {
        assert_eq!(ins.table, "network");
        assert_eq!(
            ins.entity_type,
            crate::storage::query::ast::InsertEntityType::Edge
        );
        // Keywords as column names are returned uppercase
        assert_eq!(ins.columns.len(), 4);
        assert!(ins.columns[0].eq_ignore_ascii_case("label"));
        assert!(ins.columns[1].eq_ignore_ascii_case("from"));
        assert!(ins.columns[2].eq_ignore_ascii_case("to"));
        assert!(ins.columns[3].eq_ignore_ascii_case("weight"));
    } else {
        panic!("Expected InsertQuery with Edge entity type");
    }
}

#[test]
fn test_parse_insert_vector() {
    let query = parse(
        "INSERT INTO embeddings VECTOR (dense, content) VALUES ([0.1, 0.2, 0.3], 'hello world')",
    )
    .unwrap();
    if let QueryExpr::Insert(ins) = query {
        assert_eq!(ins.table, "embeddings");
        assert_eq!(
            ins.entity_type,
            crate::storage::query::ast::InsertEntityType::Vector
        );
        assert_eq!(ins.columns, vec!["dense", "content"]);
        assert_eq!(ins.values.len(), 1);
        // The vector literal should be parsed as Value::Vector
        match &ins.values[0][0] {
            crate::storage::schema::Value::Vector(v) => {
                assert_eq!(v.len(), 3);
                assert!((v[0] - 0.1).abs() < 0.01);
            }
            other => panic!("Expected Vector value, got {other:?}"),
        }
    } else {
        panic!("Expected InsertQuery with Vector entity type");
    }
}

#[test]
fn test_parse_insert_document() {
    let query =
        parse(r#"INSERT INTO docs DOCUMENT (body) VALUES ('{"name":"test","value":42}')"#).unwrap();
    if let QueryExpr::Insert(ins) = query {
        assert_eq!(ins.table, "docs");
        assert_eq!(
            ins.entity_type,
            crate::storage::query::ast::InsertEntityType::Document
        );
        assert_eq!(ins.columns, vec!["body"]);
    } else {
        panic!("Expected InsertQuery with Document entity type");
    }
}

#[test]
fn test_parse_insert_kv() {
    let query =
        parse("INSERT INTO cache KV (key, value) VALUES ('session:123', 'token-abc')").unwrap();
    if let QueryExpr::Insert(ins) = query {
        assert_eq!(ins.table, "cache");
        assert_eq!(
            ins.entity_type,
            crate::storage::query::ast::InsertEntityType::Kv
        );
        assert_eq!(ins.columns.len(), 2);
        assert!(ins.columns[0].eq_ignore_ascii_case("key"));
        assert!(ins.columns[1].eq_ignore_ascii_case("value"));
    } else {
        panic!("Expected InsertQuery with Kv entity type");
    }
}

#[test]
fn test_parse_insert_vector_array_literal() {
    // Test array literal parsing in VALUES
    let query = parse("INSERT INTO emb VECTOR (dense) VALUES ([1, 2, 3])").unwrap();
    if let QueryExpr::Insert(ins) = query {
        match &ins.values[0][0] {
            crate::storage::schema::Value::Vector(v) => {
                assert_eq!(v, &[1.0, 2.0, 3.0]);
            }
            other => panic!("Expected Vector value, got {other:?}"),
        }
    } else {
        panic!("Expected InsertQuery");
    }
}

// ========================================================================
// GRAPH Command Tests
// ========================================================================

#[test]
fn test_parse_graph_neighborhood_defaults() {
    let query = parse("GRAPH NEIGHBORHOOD 'node_1'").unwrap();
    if let QueryExpr::GraphCommand(crate::storage::query::ast::GraphCommand::Neighborhood {
        source,
        depth,
        direction,
        edge_labels,
    }) = query
    {
        assert_eq!(source, "node_1");
        assert_eq!(depth, 3);
        assert_eq!(direction, "outgoing");
        assert_eq!(edge_labels, None);
    } else {
        panic!("Expected GraphCommand::Neighborhood");
    }
}

#[test]
fn test_parse_graph_neighborhood_with_options() {
    let query = parse("GRAPH NEIGHBORHOOD 'node_a' DEPTH 5 DIRECTION both").unwrap();
    if let QueryExpr::GraphCommand(crate::storage::query::ast::GraphCommand::Neighborhood {
        source,
        depth,
        direction,
        edge_labels,
    }) = query
    {
        assert_eq!(source, "node_a");
        assert_eq!(depth, 5);
        assert!(direction.eq_ignore_ascii_case("both"));
        assert_eq!(edge_labels, None);
    } else {
        panic!("Expected GraphCommand::Neighborhood");
    }
}

#[test]
fn test_parse_graph_neighborhood_edges_in() {
    let query = parse("GRAPH NEIGHBORHOOD 'node_a' DEPTH 5 EDGES IN ('EATS', 'KILLS')").unwrap();
    if let QueryExpr::GraphCommand(crate::storage::query::ast::GraphCommand::Neighborhood {
        source,
        depth,
        direction,
        edge_labels,
    }) = query
    {
        assert_eq!(source, "node_a");
        assert_eq!(depth, 5);
        assert_eq!(direction, "outgoing");
        assert_eq!(
            edge_labels,
            Some(vec!["EATS".to_string(), "KILLS".to_string()])
        );
    } else {
        panic!("Expected GraphCommand::Neighborhood");
    }
}

#[test]
fn test_parse_graph_shortest_path() {
    let query = parse("GRAPH SHORTEST_PATH 'a' TO 'b' ALGORITHM dijkstra").unwrap();
    if let QueryExpr::GraphCommand(crate::storage::query::ast::GraphCommand::ShortestPath {
        source,
        target,
        algorithm,
        direction,
        ..
    }) = query
    {
        assert_eq!(source, "a");
        assert_eq!(target, "b");
        assert_eq!(algorithm, "dijkstra");
        assert_eq!(direction, "outgoing");
    } else {
        panic!("Expected GraphCommand::ShortestPath");
    }
}

#[test]
fn test_parse_graph_shortest_path_astar() {
    let query = parse("GRAPH SHORTEST_PATH 'a' TO 'b' ALGORITHM astar").unwrap();
    if let QueryExpr::GraphCommand(crate::storage::query::ast::GraphCommand::ShortestPath {
        algorithm,
        ..
    }) = query
    {
        assert_eq!(algorithm, "astar");
    } else {
        panic!("Expected GraphCommand::ShortestPath");
    }
}

#[test]
fn test_parse_graph_shortest_path_bellman_ford() {
    let query = parse("GRAPH SHORTEST_PATH 'a' TO 'b' ALGORITHM bellman_ford").unwrap();
    if let QueryExpr::GraphCommand(crate::storage::query::ast::GraphCommand::ShortestPath {
        algorithm,
        ..
    }) = query
    {
        assert_eq!(algorithm, "bellman_ford");
    } else {
        panic!("Expected GraphCommand::ShortestPath");
    }
}

#[test]
fn test_parse_graph_traverse() {
    let query = parse("GRAPH TRAVERSE 'root' STRATEGY dfs DEPTH 10 DIRECTION incoming").unwrap();
    if let QueryExpr::GraphCommand(crate::storage::query::ast::GraphCommand::Traverse {
        source,
        strategy,
        depth,
        direction,
        edge_labels,
    }) = query
    {
        assert_eq!(source, "root");
        assert_eq!(strategy, "dfs");
        assert_eq!(depth, 10);
        assert!(direction.eq_ignore_ascii_case("incoming"));
        assert_eq!(edge_labels, None);
    } else {
        panic!("Expected GraphCommand::Traverse");
    }
}

#[test]
fn test_parse_graph_traverse_docs_form() {
    // Pin the docs syntax: `GRAPH TRAVERSE FROM '...' STRATEGY ... DIRECTION ... MAX_DEPTH n`
    // (see docs/query/graph-commands.md). Regression for #417.
    let query =
        parse("GRAPH TRAVERSE FROM 'alice' STRATEGY bfs DIRECTION outgoing MAX_DEPTH 3").unwrap();
    if let QueryExpr::GraphCommand(crate::storage::query::ast::GraphCommand::Traverse {
        source,
        strategy,
        depth,
        direction,
        edge_labels,
    }) = query
    {
        assert_eq!(source, "alice");
        assert_eq!(strategy, "bfs");
        assert_eq!(depth, 3);
        assert!(direction.eq_ignore_ascii_case("outgoing"));
        assert_eq!(edge_labels, None);
    } else {
        panic!("Expected GraphCommand::Traverse");
    }
}

#[test]
fn test_parse_graph_traverse_edges_in() {
    let query =
        parse("GRAPH TRAVERSE FROM 'alice' EDGES IN ('EATS') STRATEGY bfs MAX_DEPTH 3").unwrap();
    if let QueryExpr::GraphCommand(crate::storage::query::ast::GraphCommand::Traverse {
        source,
        strategy,
        depth,
        direction,
        edge_labels,
    }) = query
    {
        assert_eq!(source, "alice");
        assert_eq!(strategy, "bfs");
        assert_eq!(depth, 3);
        assert_eq!(direction, "outgoing");
        assert_eq!(edge_labels, Some(vec!["EATS".to_string()]));
    } else {
        panic!("Expected GraphCommand::Traverse");
    }
}

#[test]
fn test_parse_graph_shortest_path_docs_form() {
    // Pin `GRAPH SHORTEST_PATH FROM '...' TO '...' ALGORITHM ...` (docs). Regression for #417.
    let query = parse("GRAPH SHORTEST_PATH FROM 'alice' TO 'charlie' ALGORITHM dijkstra").unwrap();
    if let QueryExpr::GraphCommand(crate::storage::query::ast::GraphCommand::ShortestPath {
        source,
        target,
        algorithm,
        ..
    }) = query
    {
        assert_eq!(source, "alice");
        assert_eq!(target, "charlie");
        assert_eq!(algorithm, "dijkstra");
    } else {
        panic!("Expected GraphCommand::ShortestPath");
    }
}

#[test]
fn test_parse_graph_centrality() {
    let query = parse("GRAPH CENTRALITY ALGORITHM pagerank").unwrap();
    if let QueryExpr::GraphCommand(crate::storage::query::ast::GraphCommand::Centrality {
        algorithm,
        limit,
        ..
    }) = query
    {
        assert_eq!(algorithm, "pagerank");
        assert_eq!(limit, None);
    } else {
        panic!("Expected GraphCommand::Centrality");
    }
}

#[test]
fn test_parse_graph_centrality_default() {
    let query = parse("GRAPH CENTRALITY").unwrap();
    if let QueryExpr::GraphCommand(crate::storage::query::ast::GraphCommand::Centrality {
        algorithm,
        limit,
        ..
    }) = query
    {
        assert_eq!(algorithm, "degree");
        assert_eq!(limit, None);
    } else {
        panic!("Expected GraphCommand::Centrality with default algorithm");
    }
}

#[test]
fn test_parse_graph_centrality_with_limit() {
    let query = parse("GRAPH CENTRALITY LIMIT 10").unwrap();
    if let QueryExpr::GraphCommand(crate::storage::query::ast::GraphCommand::Centrality {
        algorithm,
        limit,
        ..
    }) = query
    {
        assert_eq!(algorithm, "degree");
        assert_eq!(limit, Some(10));
    } else {
        panic!("Expected GraphCommand::Centrality with LIMIT");
    }

    let query = parse("GRAPH CENTRALITY ALGORITHM pagerank LIMIT 5").unwrap();
    if let QueryExpr::GraphCommand(crate::storage::query::ast::GraphCommand::Centrality {
        algorithm,
        limit,
        ..
    }) = query
    {
        assert_eq!(algorithm, "pagerank");
        assert_eq!(limit, Some(5));
    } else {
        panic!("Expected GraphCommand::Centrality with algorithm+limit");
    }
}

#[test]
fn test_parse_graph_centrality_negative_limit_errors() {
    // Negative literals never reach the guard — the lexer rejects `-` at the
    // integer slot. Pin both: a literal `-1` errors at parse time, and a
    // syntactically-valid `LIMIT 0` is accepted (zero-row semantics handled
    // in the runtime, not the parser).
    let err = parse("GRAPH CENTRALITY LIMIT -1").unwrap_err();
    let msg = format!("{}", err);
    assert!(msg.contains("expected: integer"), "unexpected error: {msg}");

    let query = parse("GRAPH CENTRALITY LIMIT 0").unwrap();
    if let QueryExpr::GraphCommand(crate::storage::query::ast::GraphCommand::Centrality {
        limit,
        ..
    }) = query
    {
        assert_eq!(limit, Some(0));
    } else {
        panic!("Expected GraphCommand::Centrality LIMIT 0");
    }
}

#[test]
fn test_parse_graph_community() {
    let query = parse("GRAPH COMMUNITY ALGORITHM louvain MAX_ITERATIONS 50").unwrap();
    if let QueryExpr::GraphCommand(crate::storage::query::ast::GraphCommand::Community {
        algorithm,
        max_iterations,
        ..
    }) = query
    {
        assert_eq!(algorithm, "louvain");
        assert_eq!(max_iterations, 50);
    } else {
        panic!("Expected GraphCommand::Community");
    }
}

#[test]
fn test_parse_graph_components() {
    let query = parse("GRAPH COMPONENTS MODE strong").unwrap();
    if let QueryExpr::GraphCommand(crate::storage::query::ast::GraphCommand::Components {
        mode,
        limit,
        ..
    }) = query
    {
        assert_eq!(mode, "strong");
        assert_eq!(limit, None);
    } else {
        panic!("Expected GraphCommand::Components");
    }
}

#[test]
fn test_parse_graph_cycles() {
    let query = parse("GRAPH CYCLES MAX_LENGTH 5").unwrap();
    if let QueryExpr::GraphCommand(crate::storage::query::ast::GraphCommand::Cycles {
        max_length,
    }) = query
    {
        assert_eq!(max_length, 5);
    } else {
        panic!("Expected GraphCommand::Cycles");
    }
}

#[test]
fn test_parse_graph_clustering() {
    let query = parse("GRAPH CLUSTERING").unwrap();
    assert!(matches!(
        query,
        QueryExpr::GraphCommand(crate::storage::query::ast::GraphCommand::Clustering)
    ));
}

#[test]
fn test_parse_graph_topological_sort() {
    let query = parse("GRAPH TOPOLOGICAL_SORT").unwrap();
    assert!(matches!(
        query,
        QueryExpr::GraphCommand(crate::storage::query::ast::GraphCommand::TopologicalSort)
    ));
}

#[test]
fn test_parse_graph_properties() {
    let query = parse("GRAPH PROPERTIES").unwrap();
    assert!(matches!(
        query,
        QueryExpr::GraphCommand(crate::storage::query::ast::GraphCommand::Properties {
            source: None
        })
    ));
}

#[test]
fn test_parse_graph_properties_with_source() {
    // #423: GRAPH PROPERTIES '<id-or-label>' resolves per-node property bag.
    let query = parse("GRAPH PROPERTIES 'cinderella'").unwrap();
    match query {
        QueryExpr::GraphCommand(crate::storage::query::ast::GraphCommand::Properties {
            source: Some(s),
        }) => assert_eq!(s, "cinderella"),
        other => panic!("expected Properties {{ source: Some(\"cinderella\") }}, got {other:?}"),
    }

    let numeric = parse("GRAPH PROPERTIES '177'").unwrap();
    match numeric {
        QueryExpr::GraphCommand(crate::storage::query::ast::GraphCommand::Properties {
            source: Some(s),
        }) => assert_eq!(s, "177"),
        other => panic!("expected numeric source, got {other:?}"),
    }
}

// ========================================================================
// SEARCH Command Tests
// ========================================================================

#[test]
fn test_parse_search_similar() {
    let query = parse("SEARCH SIMILAR [0.1, 0.2, 0.3] COLLECTION embeddings LIMIT 5 MIN_SCORE 0.8")
        .unwrap();
    if let QueryExpr::SearchCommand(crate::storage::query::ast::SearchCommand::Similar {
        vector,
        collection,
        limit,
        min_score,
        ..
    }) = query
    {
        assert_eq!(vector.len(), 3);
        assert!((vector[0] - 0.1).abs() < 0.01);
        assert_eq!(collection, "embeddings");
        assert_eq!(limit, 5);
        assert!((min_score - 0.8).abs() < 0.01);
    } else {
        panic!("Expected SearchCommand::Similar");
    }
}

#[test]
fn test_parse_search_similar_defaults() {
    let query = parse("SEARCH SIMILAR [1, 2, 3] COLLECTION vecs").unwrap();
    if let QueryExpr::SearchCommand(crate::storage::query::ast::SearchCommand::Similar {
        limit,
        min_score,
        ..
    }) = query
    {
        assert_eq!(limit, 10);
        assert!((min_score).abs() < 0.01);
    } else {
        panic!("Expected SearchCommand::Similar");
    }
}

#[test]
fn test_parse_search_text() {
    let query =
        parse("SEARCH TEXT 'find all vulnerabilities' COLLECTION hosts LIMIT 20 FUZZY").unwrap();
    if let QueryExpr::SearchCommand(crate::storage::query::ast::SearchCommand::Text {
        query: q,
        collection,
        limit,
        fuzzy,
        ..
    }) = query
    {
        assert_eq!(q, "find all vulnerabilities");
        assert_eq!(collection, Some("hosts".to_string()));
        assert_eq!(limit, 20);
        assert!(fuzzy);
    } else {
        panic!("Expected SearchCommand::Text");
    }
}

#[test]
fn test_parse_search_text_minimal() {
    let query = parse("SEARCH TEXT 'hello world'").unwrap();
    if let QueryExpr::SearchCommand(crate::storage::query::ast::SearchCommand::Text {
        query: q,
        collection,
        limit,
        fuzzy,
        ..
    }) = query
    {
        assert_eq!(q, "hello world");
        assert_eq!(collection, None);
        assert_eq!(limit, 10);
        assert!(!fuzzy);
    } else {
        panic!("Expected SearchCommand::Text");
    }
}

#[test]
fn test_parse_search_hybrid() {
    let query =
        parse("SEARCH HYBRID SIMILAR [0.1, 0.2] TEXT 'query string' COLLECTION data LIMIT 15")
            .unwrap();
    if let QueryExpr::SearchCommand(crate::storage::query::ast::SearchCommand::Hybrid {
        vector,
        query: q,
        collection,
        limit,
        ..
    }) = query
    {
        assert_eq!(vector.unwrap().len(), 2);
        assert_eq!(q.unwrap(), "query string");
        assert_eq!(collection, "data");
        assert_eq!(limit, 15);
    } else {
        panic!("Expected SearchCommand::Hybrid");
    }
}

#[test]
fn test_parse_search_hybrid_text_only() {
    let query = parse("SEARCH HYBRID TEXT 'query' COLLECTION data").unwrap();
    if let QueryExpr::SearchCommand(crate::storage::query::ast::SearchCommand::Hybrid {
        vector,
        query: q,
        ..
    }) = query
    {
        assert!(vector.is_none());
        assert_eq!(q.unwrap(), "query");
    } else {
        panic!("Expected SearchCommand::Hybrid");
    }
}

#[test]
fn test_parse_search_hybrid_vector_only() {
    let query = parse("SEARCH HYBRID SIMILAR [1, 2, 3] COLLECTION data").unwrap();
    if let QueryExpr::SearchCommand(crate::storage::query::ast::SearchCommand::Hybrid {
        vector,
        query: q,
        ..
    }) = query
    {
        assert!(vector.is_some());
        assert!(q.is_none());
    } else {
        panic!("Expected SearchCommand::Hybrid");
    }
}

#[test]
fn test_parse_search_hybrid_requires_input() {
    // Must have at least SIMILAR or TEXT
    let result = parse("SEARCH HYBRID COLLECTION data");
    assert!(result.is_err());
}

#[test]
fn test_parse_search_multimodal() {
    let query =
        parse("SEARCH MULTIMODAL 'CPF: 000.000.000-00' COLLECTION people LIMIT 20").unwrap();
    if let QueryExpr::SearchCommand(crate::storage::query::ast::SearchCommand::Multimodal {
        query,
        collection,
        limit,
        ..
    }) = query
    {
        assert_eq!(query, "CPF: 000.000.000-00");
        assert_eq!(collection, Some("people".to_string()));
        assert_eq!(limit, 20);
    } else {
        panic!("Expected SearchCommand::Multimodal");
    }
}

#[test]
fn test_parse_search_multimodal_defaults() {
    let query = parse("SEARCH MULTIMODAL 'user:123'").unwrap();
    if let QueryExpr::SearchCommand(crate::storage::query::ast::SearchCommand::Multimodal {
        query,
        collection,
        limit,
        ..
    }) = query
    {
        assert_eq!(query, "user:123");
        assert_eq!(collection, None);
        assert_eq!(limit, 25);
    } else {
        panic!("Expected SearchCommand::Multimodal");
    }
}

#[test]
fn test_parse_search_index_defaults() {
    let query = parse("SEARCH INDEX cpf VALUE '000.000.000-00'").unwrap();
    if let QueryExpr::SearchCommand(crate::storage::query::ast::SearchCommand::Index {
        index,
        value,
        collection,
        limit,
        exact,
        ..
    }) = query
    {
        assert_eq!(index, "cpf");
        assert_eq!(value, "000.000.000-00");
        assert_eq!(collection, None);
        assert_eq!(limit, 25);
        assert!(exact);
    } else {
        panic!("Expected SearchCommand::Index");
    }
}

#[test]
fn test_parse_search_index_with_collection_limit_fuzzy() {
    let query =
        parse("SEARCH INDEX cpf VALUE '000.000.000-00' COLLECTION people LIMIT 20 FUZZY").unwrap();
    if let QueryExpr::SearchCommand(crate::storage::query::ast::SearchCommand::Index {
        index,
        value,
        collection,
        limit,
        exact,
        ..
    }) = query
    {
        assert_eq!(index, "cpf");
        assert_eq!(value, "000.000.000-00");
        assert_eq!(collection, Some("people".to_string()));
        assert_eq!(limit, 20);
        assert!(!exact);
    } else {
        panic!("Expected SearchCommand::Index");
    }
}

#[test]
fn test_parse_search_context_defaults() {
    let query = parse("SEARCH CONTEXT '000.000.000-00'").unwrap();
    if let QueryExpr::SearchCommand(crate::storage::query::ast::SearchCommand::Context {
        query: q,
        field,
        collection,
        limit,
        depth,
        ..
    }) = query
    {
        assert_eq!(q, "000.000.000-00");
        assert_eq!(field, None);
        assert_eq!(collection, None);
        assert_eq!(limit, 25);
        assert_eq!(depth, 1);
    } else {
        panic!("Expected SearchCommand::Context");
    }
}

#[test]
fn test_parse_search_context_with_field_collection_limit_depth() {
    let query =
        parse("SEARCH CONTEXT '000.000.000-00' FIELD cpf COLLECTION customers LIMIT 50 DEPTH 2")
            .unwrap();
    if let QueryExpr::SearchCommand(crate::storage::query::ast::SearchCommand::Context {
        query: q,
        field,
        collection,
        limit,
        depth,
        ..
    }) = query
    {
        assert_eq!(q, "000.000.000-00");
        assert_eq!(field, Some("cpf".to_string()));
        assert_eq!(collection, Some("customers".to_string()));
        assert_eq!(limit, 50);
        assert_eq!(depth, 2);
    } else {
        panic!("Expected SearchCommand::Context");
    }
}

#[test]
fn test_parse_group_by() {
    let query = parse("SELECT status FROM users GROUP BY status").unwrap();
    if let QueryExpr::Table(tq) = query {
        assert_eq!(tq.table, "users");
        assert_eq!(tq.group_by, vec!["status".to_string()]);
        assert!(tq.having.is_none());
    } else {
        panic!("Expected TableQuery");
    }
}

#[test]
fn test_parse_group_by_multiple_fields() {
    let query = parse("SELECT dept, role FROM employees GROUP BY dept, role").unwrap();
    if let QueryExpr::Table(tq) = query {
        assert_eq!(tq.table, "employees");
        assert_eq!(tq.group_by, vec!["dept".to_string(), "role".to_string()]);
    } else {
        panic!("Expected TableQuery");
    }
}

#[test]
fn test_parse_group_by_with_having() {
    let query =
        parse("SELECT dept FROM employees GROUP BY dept HAVING dept > 5 ORDER BY dept").unwrap();
    if let QueryExpr::Table(tq) = query {
        assert_eq!(tq.table, "employees");
        assert_eq!(tq.group_by, vec!["dept".to_string()]);
        assert!(tq.having.is_some());
        assert!(!tq.order_by.is_empty());
    } else {
        panic!("Expected TableQuery");
    }
}

#[test]
fn test_parse_group_by_with_limit() {
    let query = parse("SELECT * FROM logs GROUP BY level LIMIT 10").unwrap();
    if let QueryExpr::Table(tq) = query {
        assert_eq!(tq.table, "logs");
        assert_eq!(tq.group_by, vec!["level".to_string()]);
        assert_eq!(tq.limit, Some(10));
    } else {
        panic!("Expected TableQuery");
    }
}

#[test]
fn test_parse_group_by_time_bucket() {
    let query = parse(
        "SELECT time_bucket(5m) AS bucket, avg(value) AS avg_value FROM cpu_metrics GROUP BY time_bucket(5m)",
    )
    .unwrap();
    if let QueryExpr::Table(tq) = query {
        assert_eq!(tq.table, "cpu_metrics");
        assert_eq!(tq.group_by, vec!["TIME_BUCKET(5m)".to_string()]);
        assert_eq!(tq.columns.len(), 2);
        assert_eq!(
            tq.columns[0],
            Projection::Function(
                "TIME_BUCKET:bucket".to_string(),
                vec![Projection::Column("LIT:5m".to_string())]
            )
        );
        // Parser may emit Column("value") or Field({ column: "value" }) depending on version.
        let avg_col = match &tq.columns[1] {
            Projection::Function(name, args) if name == "AVG:avg_value" && args.len() == 1 => {
                &args[0]
            }
            other => panic!("Expected AVG:avg_value function, got {:?}", other),
        };
        assert!(
            matches!(avg_col, Projection::Column(c) if c == "value")
                || matches!(avg_col, Projection::Field(f, _) if matches!(f, FieldRef::TableColumn { column, .. } if column == "value")),
            "unexpected avg arg: {:?}",
            avg_col
        );
    } else {
        panic!("Expected TableQuery");
    }
}

#[test]
fn test_parse_keyword_field_reference_in_where() {
    let query = parse("SELECT metric FROM cpu_metrics WHERE metric = 'cpu.usage'").unwrap();
    if let QueryExpr::Table(tq) = query {
        assert_eq!(tq.table, "cpu_metrics");
        match tq.filter {
            Some(Filter::Compare { field, .. }) => match field {
                FieldRef::TableColumn { table, column } => {
                    assert!(table.is_empty());
                    assert_eq!(column, "metric");
                }
                other => panic!("expected table-column field ref, got {other:?}"),
            },
            other => panic!("expected compare filter, got {other:?}"),
        }
    } else {
        panic!("Expected TableQuery");
    }
}

#[test]
fn test_parse_insert_with_ttl() {
    let query = parse("INSERT INTO sessions (token) VALUES ('abc') WITH TTL 60 s").unwrap();
    if let QueryExpr::Insert(iq) = query {
        assert_eq!(iq.table, "sessions");
        assert_eq!(iq.ttl_ms, Some(60_000));
        assert!(iq.with_metadata.is_empty());
    } else {
        panic!("Expected InsertQuery");
    }
}

#[test]
fn test_parse_insert_with_ttl_hours() {
    let query = parse("INSERT INTO cache (key, value) VALUES ('k', 'v') WITH TTL 24 h").unwrap();
    if let QueryExpr::Insert(iq) = query {
        assert_eq!(iq.ttl_ms, Some(24 * 3_600_000));
    } else {
        panic!("Expected InsertQuery");
    }
}

#[test]
fn test_parse_insert_with_metadata() {
    let query = parse(
        "INSERT INTO events (name) VALUES ('login') WITH METADATA (priority = 'high', level = 3)",
    )
    .unwrap();
    if let QueryExpr::Insert(iq) = query {
        assert_eq!(iq.table, "events");
        assert_eq!(iq.with_metadata.len(), 2);
        assert_eq!(iq.with_metadata[0].0, "priority");
        assert_eq!(iq.with_metadata[1].0, "level");
    } else {
        panic!("Expected InsertQuery");
    }
}

#[test]
fn test_parse_insert_with_ttl_and_metadata() {
    let query = parse(
        "INSERT INTO sessions (token) VALUES ('abc') WITH TTL 1 h WITH METADATA (source = 'web')",
    )
    .unwrap();
    if let QueryExpr::Insert(iq) = query {
        assert_eq!(iq.ttl_ms, Some(3_600_000));
        assert_eq!(iq.with_metadata.len(), 1);
        assert_eq!(iq.with_metadata[0].0, "source");
    } else {
        panic!("Expected InsertQuery");
    }
}

#[test]
fn test_parse_insert_with_expires_at() {
    let query =
        parse("INSERT INTO events (name) VALUES ('launch') WITH EXPIRES AT 1735689600000").unwrap();
    if let QueryExpr::Insert(iq) = query {
        assert_eq!(iq.expires_at_ms, Some(1735689600000));
        assert_eq!(iq.ttl_ms, None);
    } else {
        panic!("Expected InsertQuery");
    }
}

#[test]
fn test_parse_update_with_ttl() {
    let query = parse("UPDATE sessions SET active = true WHERE id = 1 WITH TTL 2 h").unwrap();
    if let QueryExpr::Update(uq) = query {
        assert_eq!(uq.table, "sessions");
        assert_eq!(uq.ttl_ms, Some(7_200_000));
        assert!(uq.filter.is_some());
    } else {
        panic!("Expected UpdateQuery");
    }
}

#[test]
fn test_parse_update_with_metadata() {
    let query =
        parse("UPDATE users SET name = 'Alice' WHERE id = 1 WITH METADATA (role = 'admin')")
            .unwrap();
    if let QueryExpr::Update(uq) = query {
        assert_eq!(uq.with_metadata.len(), 1);
        assert_eq!(uq.with_metadata[0].0, "role");
    } else {
        panic!("Expected UpdateQuery");
    }
}

#[test]
fn test_parse_update_with_expires_at() {
    let query =
        parse("UPDATE cache SET value = 'x' WHERE name = 'k' WITH EXPIRES AT 1735689600000")
            .unwrap();
    if let QueryExpr::Update(uq) = query {
        assert_eq!(uq.expires_at_ms, Some(1735689600000));
    } else {
        panic!("Expected UpdateQuery");
    }
}

#[test]
fn test_parse_select_with_expand_graph() {
    let query =
        parse("SELECT * FROM customers WHERE cpf = '081' WITH EXPAND GRAPH DEPTH 2").unwrap();
    if let QueryExpr::Table(tq) = query {
        let expand = tq.expand.unwrap();
        assert!(expand.graph);
        assert_eq!(expand.graph_depth, 2);
    } else {
        panic!("Expected TableQuery");
    }
}

#[test]
fn test_parse_select_with_expand_cross_refs() {
    let query = parse("SELECT * FROM ANY WHERE name = 'Alice' WITH EXPAND CROSS_REFS").unwrap();
    if let QueryExpr::Table(tq) = query {
        let expand = tq.expand.unwrap();
        assert!(expand.cross_refs);
        assert!(!expand.graph);
    } else {
        panic!("Expected TableQuery");
    }
}

#[test]
fn test_parse_select_with_expand_all() {
    let query = parse("SELECT * FROM hosts WITH EXPAND ALL").unwrap();
    if let QueryExpr::Table(tq) = query {
        let expand = tq.expand.unwrap();
        assert!(expand.graph);
        assert!(expand.cross_refs);
    } else {
        panic!("Expected TableQuery");
    }
}

#[test]
fn test_parse_create_table_with_context_index() {
    let query = parse(
        "CREATE TABLE customers (name TEXT, cpf TEXT, email TEXT) WITH CONTEXT INDEX ON (cpf, email)",
    )
    .unwrap();
    if let QueryExpr::CreateTable(ct) = query {
        assert_eq!(ct.name, "customers");
        assert_eq!(
            ct.context_index_fields,
            vec!["cpf".to_string(), "email".to_string()]
        );
    } else {
        panic!("Expected CreateTableQuery");
    }
}

#[test]
fn test_parse_create_table_with_ttl_and_context_index() {
    let query =
        parse("CREATE TABLE sessions (token TEXT) WITH TTL 24 h WITH CONTEXT INDEX ON (token)")
            .unwrap();
    if let QueryExpr::CreateTable(ct) = query {
        assert_eq!(ct.default_ttl_ms, Some(86_400_000));
        assert_eq!(ct.context_index_fields, vec!["token".to_string()]);
    } else {
        panic!("Expected CreateTableQuery");
    }
}

// ========================================================================
// JSON inline literal tests
// ========================================================================

#[test]
fn test_parse_insert_with_inline_json_object() {
    let query = parse("INSERT INTO logs (data) VALUES ({level: 'info', msg: 'hello'})").unwrap();
    if let QueryExpr::Insert(iq) = query {
        assert_eq!(iq.table, "logs");
        assert_eq!(iq.values.len(), 1);
        // The JSON value should be Value::Json(...)
        match &iq.values[0][0] {
            crate::storage::schema::Value::Json(bytes) => {
                let parsed: crate::json::Value = crate::json::from_slice(bytes).unwrap();
                assert_eq!(parsed.get("level").and_then(|v| v.as_str()), Some("info"));
                assert_eq!(parsed.get("msg").and_then(|v| v.as_str()), Some("hello"));
            }
            other => panic!("Expected Value::Json, got {:?}", other),
        }
    } else {
        panic!("Expected InsertQuery");
    }
}

#[test]
fn test_parse_insert_with_nested_json() {
    let query =
        parse("INSERT INTO events (payload) VALUES ({type: 'click', meta: {x: 100, y: 200}})")
            .unwrap();
    if let QueryExpr::Insert(iq) = query {
        match &iq.values[0][0] {
            crate::storage::schema::Value::Json(bytes) => {
                let parsed: crate::json::Value = crate::json::from_slice(bytes).unwrap();
                assert_eq!(parsed.get("type").and_then(|v| v.as_str()), Some("click"));
                let meta = parsed.get("meta").unwrap();
                assert_eq!(meta.get("x").and_then(|v| v.as_f64()), Some(100.0));
                assert_eq!(meta.get("y").and_then(|v| v.as_f64()), Some(200.0));
            }
            other => panic!("Expected Value::Json, got {:?}", other),
        }
    } else {
        panic!("Expected InsertQuery");
    }
}

#[test]
fn test_parse_insert_json_with_colon_separator() {
    // JSON-style with colons (standard JSON syntax)
    let query =
        parse(r#"INSERT INTO logs (data) VALUES ({"host": "srv1", "port": 8080})"#).unwrap();
    if let QueryExpr::Insert(iq) = query {
        match &iq.values[0][0] {
            crate::storage::schema::Value::Json(bytes) => {
                let parsed: crate::json::Value = crate::json::from_slice(bytes).unwrap();
                assert_eq!(parsed.get("host").and_then(|v| v.as_str()), Some("srv1"));
                assert_eq!(parsed.get("port").and_then(|v| v.as_f64()), Some(8080.0));
            }
            other => panic!("Expected Value::Json, got {:?}", other),
        }
    } else {
        panic!("Expected InsertQuery");
    }
}

#[test]
fn test_parse_create_timeseries() {
    let query = parse("CREATE TIMESERIES cpu_metrics RETENTION 90 d").unwrap();
    if let QueryExpr::CreateTimeSeries(ts) = query {
        assert_eq!(ts.name, "cpu_metrics");
        assert_eq!(ts.retention_ms, Some(90 * 86_400_000));
        assert!(ts.downsample_policies.is_empty());
    } else {
        panic!("Expected CreateTimeSeriesQuery");
    }
}

#[test]
fn test_parse_create_timeseries_with_downsample() {
    let query =
        parse("CREATE TIMESERIES cpu_metrics RETENTION 90 d DOWNSAMPLE 1h:5m:avg, 1d:1h:max")
            .unwrap();
    if let QueryExpr::CreateTimeSeries(ts) = query {
        assert_eq!(
            ts.downsample_policies,
            vec!["1h:5m:avg".to_string(), "1d:1h:max".to_string()]
        );
    } else {
        panic!("Expected CreateTimeSeriesQuery");
    }
}

#[test]
fn test_parse_timeseries_duration_downsample_and_hypertable_forms() {
    let query =
        parse("CREATE TIMESERIES IF NOT EXISTS metrics CHUNK_SIZE 2048 RETENTION 5 min").unwrap();
    let QueryExpr::CreateTimeSeries(ts) = query else {
        panic!("Expected CreateTimeSeriesQuery");
    };
    assert_eq!(ts.name, "metrics");
    assert!(ts.if_not_exists);
    assert_eq!(ts.chunk_size, Some(2048));
    assert_eq!(ts.retention_ms, Some(5 * 60_000));

    let query = parse("CREATE TIMESERIES metrics DOWNSAMPLE 1.5h:raw, 10m:1m:sum").unwrap();
    let QueryExpr::CreateTimeSeries(ts) = query else {
        panic!("Expected CreateTimeSeriesQuery");
    };
    assert_eq!(
        ts.downsample_policies,
        vec!["1.5h:raw:avg".to_string(), "10m:1m:sum".to_string()]
    );

    let query = parse(
        "CREATE HYPERTABLE metrics TIME_COLUMN ts CHUNK_INTERVAL '1d' TTL '2h' RETENTION 7 day",
    )
    .unwrap();
    let QueryExpr::CreateTimeSeries(ts) = query else {
        panic!("Expected CreateTimeSeriesQuery");
    };
    let hypertable = ts.hypertable.expect("hypertable ddl");
    assert_eq!(hypertable.time_column, "ts");
    assert_eq!(hypertable.chunk_interval_ns, 86_400_000_000_000);
    assert_eq!(hypertable.default_ttl_ns, Some(7_200_000_000_000));
    assert_eq!(ts.retention_ms, Some(7 * 86_400_000));

    let query = parse("DROP HYPERTABLE IF EXISTS metrics").unwrap();
    assert!(matches!(
        query,
        QueryExpr::DropTimeSeries(ts) if ts.name == "metrics" && ts.if_exists
    ));

    for sql in [
        "CREATE TIMESERIES metrics RETENTION 1 fortnights",
        "CREATE TIMESERIES metrics RETENTION 1 MAX",
        "CREATE TIMESERIES metrics RETENTION 1 AVG",
        "CREATE TIMESERIES metrics DOWNSAMPLE raw:",
        "CREATE HYPERTABLE metrics CHUNK_INTERVAL '1d'",
        "CREATE HYPERTABLE metrics TIME_COLUMN ts",
        "CREATE HYPERTABLE metrics TIME_COLUMN ts CHUNK_INTERVAL 42",
        "CREATE HYPERTABLE metrics TIME_COLUMN ts CHUNK_INTERVAL 'nope'",
    ] {
        assert!(parse(sql).is_err(), "{sql}");
    }
}

#[test]
fn test_parse_create_queue() {
    let query = parse("CREATE QUEUE tasks MAX_SIZE 1000 PRIORITY").unwrap();
    if let QueryExpr::CreateQueue(q) = query {
        assert_eq!(q.name, "tasks");
        assert_eq!(q.mode, crate::storage::queue::QueueMode::Work);
        assert_eq!(q.max_size, Some(1000));
        assert!(q.priority);
        assert_eq!(q.max_attempts, 3);
        assert_eq!(q.dlq, None);
    } else {
        panic!("Expected CreateQueueQuery");
    }
}

#[test]
fn test_parse_queue_mode_ddl() {
    use crate::storage::queue::QueueMode;

    let query = parse("CREATE QUEUE fanout_tasks FANOUT").unwrap();
    assert!(matches!(
        query,
        QueryExpr::CreateQueue(q) if q.name == "fanout_tasks" && q.mode == QueueMode::Fanout
    ));

    let query = parse("CREATE QUEUE work_tasks WORK").unwrap();
    assert!(matches!(
        query,
        QueryExpr::CreateQueue(q) if q.name == "work_tasks" && q.mode == QueueMode::Work
    ));

    let query = parse("ALTER QUEUE fanout_tasks SET MODE FANOUT").unwrap();
    assert!(matches!(
        query,
        QueryExpr::AlterQueue(q) if q.name == "fanout_tasks" && q.mode == QueueMode::Fanout
    ));
}

#[test]
fn test_parse_create_queue_with_dlq_and_attempts() {
    let query = parse("CREATE QUEUE tasks WITH DLQ failed_tasks MAX_ATTEMPTS 5").unwrap();
    if let QueryExpr::CreateQueue(q) = query {
        assert_eq!(q.name, "tasks");
        assert_eq!(q.dlq.as_deref(), Some("failed_tasks"));
        assert_eq!(q.max_attempts, 5);
    } else {
        panic!("Expected CreateQueueQuery");
    }
}

#[test]
fn test_parse_create_queue_with_events_rejected() {
    let err = parse("CREATE QUEUE tasks WITH EVENTS").expect_err("queue events must fail");
    assert!(
        err.to_string()
            .contains("queues cannot have event subscriptions"),
        "{err}"
    );
}

#[test]
fn test_parse_queue_control_and_group_command_forms() {
    use crate::storage::query::ast::QueueSide;

    let query = parse("CREATE QUEUE IF NOT EXISTS tasks WITH TTL 2.5 s").unwrap();
    assert!(matches!(
        query,
        QueryExpr::CreateQueue(q)
            if q.name == "tasks" && q.if_not_exists && q.ttl_ms == Some(2_500)
    ));

    for (sql, expected_ttl_ms) in [
        ("CREATE QUEUE q_ms WITH TTL 10 ms", 10),
        ("CREATE QUEUE q_min WITH TTL 2 mins", 120_000),
        ("CREATE QUEUE q_hr WITH TTL 3 hrs", 10_800_000),
        ("CREATE QUEUE q_day WITH TTL 1 day", 86_400_000),
        ("CREATE QUEUE q_default WITH TTL 4", 4_000),
    ] {
        let query = parse(sql).unwrap();
        assert!(matches!(
            query,
            QueryExpr::CreateQueue(q) if q.ttl_ms == Some(expected_ttl_ms)
        ));
    }

    let query = parse("CREATE QUEUE retries MAXATTEMPTS 0 MAXSIZE 10").unwrap();
    assert!(matches!(
        query,
        QueryExpr::CreateQueue(q)
            if q.max_attempts == 1 && q.max_size == Some(10)
    ));

    let query = parse("QUEUE PEEK tasks 5").unwrap();
    assert!(matches!(
        query,
        QueryExpr::QueueCommand(QueueCommand::Peek { queue, count })
            if queue == "tasks" && count == 5
    ));

    let query = parse("QUEUE PEEK tasks COUNT 5").unwrap();
    assert!(matches!(
        query,
        QueryExpr::QueueCommand(QueueCommand::Peek { queue, count })
            if queue == "tasks" && count == 5
    ));

    let query = parse("QUEUE PEEK tasks").unwrap();
    assert!(matches!(
        query,
        QueryExpr::QueueCommand(QueueCommand::Peek { queue, count })
            if queue == "tasks" && count == 1
    ));

    let query = parse("QUEUE LEN tasks").unwrap();
    assert!(matches!(
        query,
        QueryExpr::QueueCommand(QueueCommand::Len { queue }) if queue == "tasks"
    ));

    let query = parse("QUEUE PURGE tasks").unwrap();
    assert!(matches!(
        query,
        QueryExpr::QueueCommand(QueueCommand::Purge { queue }) if queue == "tasks"
    ));

    let query = parse("QUEUE MOVE FROM failed_jobs TO jobs WHERE attempts >= 3 LIMIT 100").unwrap();
    assert!(matches!(
        query,
        QueryExpr::QueueCommand(QueueCommand::Move {
            source,
            destination,
            limit,
            filter: Some(_),
        }) if source == "failed_jobs" && destination == "jobs" && limit == 100
    ));

    let query = parse("QUEUE MOVE FROM failed_jobs TO jobs").unwrap();
    assert!(matches!(
        query,
        QueryExpr::QueueCommand(QueueCommand::Move {
            source,
            destination,
            limit: 1,
            filter: None,
        }) if source == "failed_jobs" && destination == "jobs"
    ));

    let err = parse("QUEUE MOVE FROM failed_jobs TO jobs WHERE attempts >= 3")
        .expect_err("filtered queue move requires a limit");
    assert!(err.to_string().contains("LIMIT"), "{err}");

    let query = parse(
        "SELECT id, payload, attempts, last_error, enqueued_at FROM QUEUE failed_jobs WHERE attempts >= 3 LIMIT 50",
    )
    .unwrap();
    assert!(matches!(
        query,
        QueryExpr::QueueSelect(q)
            if q.queue == "failed_jobs"
                && q.columns == vec!["id", "payload", "attempts", "last_error", "enqueued_at"]
                && q.filter.is_some()
                && q.limit == Some(50)
    ));

    let query = parse("QUEUE GROUP CREATE tasks workers").unwrap();
    assert!(matches!(
        query,
        QueryExpr::QueueCommand(QueueCommand::GroupCreate { queue, group })
            if queue == "tasks" && group == "workers"
    ));

    let query = parse("QUEUE READ tasks GROUP workers CONSUMER worker1 COUNT 10").unwrap();
    assert!(matches!(
        query,
        QueryExpr::QueueCommand(QueueCommand::GroupRead {
            queue,
            group: Some(group),
            consumer,
            count,
        }) if queue == "tasks" && group == "workers" && consumer == "worker1" && count == 10
    ));

    let query = parse("QUEUE READ tasks CONSUMER worker1 COUNT 10").unwrap();
    assert!(matches!(
        query,
        QueryExpr::QueueCommand(QueueCommand::GroupRead {
            queue,
            group: None,
            consumer,
            count,
        }) if queue == "tasks" && consumer == "worker1" && count == 10
    ));

    let query = parse("QUEUE ACK tasks GROUP workers 'msg-1'").unwrap();
    assert!(matches!(
        query,
        QueryExpr::QueueCommand(QueueCommand::Ack {
            queue,
            group,
            message_id,
        }) if queue == "tasks" && group == "workers" && message_id == "msg-1"
    ));

    let query = parse("QUEUE NACK tasks GROUP workers 'msg-2'").unwrap();
    assert!(matches!(
        query,
        QueryExpr::QueueCommand(QueueCommand::Nack {
            queue,
            group,
            message_id,
        }) if queue == "tasks" && group == "workers" && message_id == "msg-2"
    ));

    let query = parse("QUEUE RPUSH tasks 'right' PRIORITY 9").unwrap();
    assert!(matches!(
        query,
        QueryExpr::QueueCommand(QueueCommand::Push {
            queue,
            side: QueueSide::Right,
            priority: Some(9),
            ..
        }) if queue == "tasks"
    ));

    let query = parse("QUEUE POP tasks COUNT 3").unwrap();
    assert!(matches!(
        query,
        QueryExpr::QueueCommand(QueueCommand::Pop {
            queue,
            side: QueueSide::Left,
            count: 3,
        }) if queue == "tasks"
    ));

    let query = parse("DROP QUEUE tasks").unwrap();
    assert!(matches!(
        query,
        QueryExpr::DropQueue(q) if q.name == "tasks" && !q.if_exists
    ));

    for sql in [
        "CREATE QUEUE q WITH TTL 5 fortnights",
        "QUEUE READ tasks workers CONSUMER worker1",
        "QUEUE CLAIM tasks GROUP workers CONSUMER worker1",
        "QUEUE CLAIM tasks GROUP workers MIN_IDLE 1",
        "QUEUE ACK tasks GROUP workers",
        "QUEUE UNKNOWN tasks",
    ] {
        assert!(parse(sql).is_err(), "{sql}");
    }
}

#[test]
fn test_parse_queue_push() {
    let query = parse("QUEUE PUSH tasks 'hello world'").unwrap();
    if let QueryExpr::QueueCommand(QueueCommand::Push { queue, value, .. }) = query {
        assert_eq!(queue, "tasks");
        assert_eq!(
            value,
            crate::storage::schema::Value::text("hello world".to_string())
        );
    } else {
        panic!("Expected QueueCommand::Push");
    }
}

#[test]
fn test_parse_queue_push_inline_json_literal() {
    let query = parse("QUEUE PUSH tasks {job: 'hello', retries: 3}").unwrap();
    if let QueryExpr::QueueCommand(QueueCommand::Push { queue, value, .. }) = query {
        assert_eq!(queue, "tasks");
        match value {
            crate::storage::schema::Value::Json(bytes) => {
                let json: crate::json::Value =
                    crate::json::from_slice(&bytes).expect("queue payload json should decode");
                assert_eq!(
                    json.get("job").and_then(crate::json::Value::as_str),
                    Some("hello")
                );
                assert_eq!(
                    json.get("retries").and_then(crate::json::Value::as_i64),
                    Some(3)
                );
            }
            other => panic!("Expected JSON queue payload, got {other:?}"),
        }
    } else {
        panic!("Expected QueueCommand::Push");
    }
}

#[test]
fn test_parse_queue_pop() {
    let query = parse("QUEUE POP tasks").unwrap();
    if let QueryExpr::QueueCommand(QueueCommand::Pop { queue, count, .. }) = query {
        assert_eq!(queue, "tasks");
        assert_eq!(count, 1);
    } else {
        panic!("Expected QueueCommand::Pop");
    }
}

#[test]
fn test_parse_queue_alias_sides() {
    let lpush = parse("QUEUE LPUSH tasks 'left'").unwrap();
    if let QueryExpr::QueueCommand(QueueCommand::Push { side, .. }) = lpush {
        assert_eq!(side, crate::storage::query::ast::QueueSide::Left);
    } else {
        panic!("Expected QueueCommand::Push");
    }

    let rpush = parse("QUEUE RPUSH tasks 'right'").unwrap();
    if let QueryExpr::QueueCommand(QueueCommand::Push { side, .. }) = rpush {
        assert_eq!(side, crate::storage::query::ast::QueueSide::Right);
    } else {
        panic!("Expected QueueCommand::Push");
    }

    let lpop = parse("QUEUE LPOP tasks").unwrap();
    if let QueryExpr::QueueCommand(QueueCommand::Pop { side, .. }) = lpop {
        assert_eq!(side, crate::storage::query::ast::QueueSide::Left);
    } else {
        panic!("Expected QueueCommand::Pop");
    }

    let rpop = parse("QUEUE RPOP tasks").unwrap();
    if let QueryExpr::QueueCommand(QueueCommand::Pop { side, .. }) = rpop {
        assert_eq!(side, crate::storage::query::ast::QueueSide::Right);
    } else {
        panic!("Expected QueueCommand::Pop");
    }
}

#[test]
fn test_parse_queue_pending() {
    let query = parse("QUEUE PENDING tasks GROUP workers").unwrap();
    if let QueryExpr::QueueCommand(QueueCommand::Pending { queue, group }) = query {
        assert_eq!(queue, "tasks");
        assert_eq!(group, "workers");
    } else {
        panic!("Expected QueueCommand::Pending");
    }
}

#[test]
fn test_parse_queue_claim() {
    let query = parse("QUEUE CLAIM tasks GROUP workers CONSUMER worker2 MIN_IDLE 60000").unwrap();
    if let QueryExpr::QueueCommand(QueueCommand::Claim {
        queue,
        group,
        consumer,
        min_idle_ms,
    }) = query
    {
        assert_eq!(queue, "tasks");
        assert_eq!(group, "workers");
        assert_eq!(consumer, "worker2");
        assert_eq!(min_idle_ms, 60000);
    } else {
        panic!("Expected QueueCommand::Claim");
    }
}

#[test]
fn test_parse_create_tree() {
    let query = parse(
        "CREATE TREE org IN forest ROOT LABEL company TYPE root PROPERTIES {name: 'Acme'} MAX_CHILDREN 3",
    )
    .unwrap();
    if let QueryExpr::CreateTree(tree) = query {
        assert_eq!(tree.name, "org");
        assert_eq!(tree.collection, "forest");
        assert_eq!(tree.root.label, "company");
        assert_eq!(tree.root.node_type.as_deref(), Some("root"));
        assert_eq!(tree.default_max_children, 3);
        assert_eq!(tree.root.properties.len(), 1);
        assert_eq!(tree.root.properties[0].0, "name");
    } else {
        panic!("Expected CreateTreeQuery");
    }
}

#[test]
fn test_parse_tree_insert() {
    let query = parse(
        "TREE INSERT INTO forest.org PARENT 42 LABEL team TYPE branch PROPERTIES {name: 'A'} METADATA {owner: 'ops'} MAX_CHILDREN 5 POSITION FIRST",
    )
    .unwrap();
    if let QueryExpr::TreeCommand(TreeCommand::Insert {
        collection,
        tree_name,
        parent_id,
        node,
        position,
    }) = query
    {
        assert_eq!(collection, "forest");
        assert_eq!(tree_name, "org");
        assert_eq!(parent_id, 42);
        assert_eq!(node.label, "team");
        assert_eq!(node.node_type.as_deref(), Some("branch"));
        assert_eq!(node.max_children, Some(5));
        assert_eq!(node.properties.len(), 1);
        assert_eq!(node.metadata.len(), 1);
        assert_eq!(position, TreePosition::First);
    } else {
        panic!("Expected TreeCommand::Insert");
    }
}

#[test]
fn test_parse_tree_rebalance_dry_run() {
    let query = parse("TREE REBALANCE forest.org DRY RUN").unwrap();
    if let QueryExpr::TreeCommand(TreeCommand::Rebalance {
        collection,
        tree_name,
        dry_run,
    }) = query
    {
        assert_eq!(collection, "forest");
        assert_eq!(tree_name, "org");
        assert!(dry_run);
    } else {
        panic!("Expected TreeCommand::Rebalance");
    }
}

#[test]
fn test_parse_create_index_hash() {
    let query = parse("CREATE INDEX idx_email ON users (email) USING HASH").unwrap();
    if let QueryExpr::CreateIndex(ci) = query {
        assert_eq!(ci.name, "idx_email");
        assert_eq!(ci.table, "users");
        assert_eq!(ci.columns, vec!["email"]);
        assert_eq!(ci.method, crate::storage::query::ast::IndexMethod::Hash);
        assert!(!ci.unique);
    } else {
        panic!("Expected CreateIndexQuery");
    }
}

#[test]
fn test_parse_create_unique_index() {
    let query = parse("CREATE UNIQUE INDEX idx_pk ON orders (id) USING HASH").unwrap();
    if let QueryExpr::CreateIndex(ci) = query {
        assert!(ci.unique);
        assert_eq!(ci.method, crate::storage::query::ast::IndexMethod::Hash);
    } else {
        panic!("Expected CreateIndexQuery");
    }
}

#[test]
fn test_parse_search_spatial_radius() {
    let query = parse(
        "SEARCH SPATIAL RADIUS 48.8566 2.3522 10.0 COLLECTION sites COLUMN location LIMIT 50",
    )
    .unwrap();
    if let QueryExpr::SearchCommand(crate::storage::query::ast::SearchCommand::SpatialRadius {
        center_lat,
        center_lon,
        radius_km,
        collection,
        limit,
        ..
    }) = query
    {
        assert!((center_lat - 48.8566).abs() < 0.001);
        assert!((center_lon - 2.3522).abs() < 0.001);
        assert!((radius_km - 10.0).abs() < 0.001);
        assert_eq!(collection, "sites");
        assert_eq!(limit, 50);
    } else {
        panic!("Expected SearchCommand::SpatialRadius");
    }
}

#[test]
fn test_parse_hll_commands() {
    let query = parse("CREATE HLL visitors").unwrap();
    assert!(matches!(
        query,
        QueryExpr::ProbabilisticCommand(
            crate::storage::query::ast::ProbabilisticCommand::CreateHll { .. }
        )
    ));

    let query = parse("HLL ADD visitors 'user1' 'user2'").unwrap();
    if let QueryExpr::ProbabilisticCommand(
        crate::storage::query::ast::ProbabilisticCommand::HllAdd { name, elements },
    ) = query
    {
        assert_eq!(name, "visitors");
        assert_eq!(elements, vec!["user1", "user2"]);
    } else {
        panic!("Expected HllAdd");
    }

    let query = parse("HLL COUNT visitors").unwrap();
    assert!(matches!(
        query,
        QueryExpr::ProbabilisticCommand(
            crate::storage::query::ast::ProbabilisticCommand::HllCount { .. }
        )
    ));
}

#[test]
fn test_parse_auth_grant_revoke_and_alter_user_forms() {
    use crate::storage::query::ast::{AlterUserAttribute, GrantObjectKind, GrantPrincipalRef};

    let query =
        parse("GRANT ALL PRIVILEGES ON DATABASE maindb TO PUBLIC WITH GRANT OPTION").unwrap();
    let QueryExpr::Grant(grant) = query else {
        panic!("Expected Grant");
    };
    assert!(grant.all);
    assert_eq!(grant.actions, vec!["ALL"]);
    assert_eq!(grant.object_kind, GrantObjectKind::Database);
    assert_eq!(grant.objects[0].name, "maindb");
    assert!(matches!(grant.principals[0], GrantPrincipalRef::Public));
    assert!(grant.with_grant_option);

    let query =
        parse("GRANT SELECT, UPDATE (name, email) ON TABLE public.users TO tenant1.alice").unwrap();
    let QueryExpr::Grant(grant) = query else {
        panic!("Expected Grant");
    };
    assert_eq!(grant.actions, vec!["SELECT", "UPDATE"]);
    assert_eq!(
        grant.columns.as_deref(),
        Some(&["name".to_string(), "email".to_string()][..])
    );
    assert_eq!(grant.object_kind, GrantObjectKind::Table);
    assert_eq!(grant.objects[0].schema.as_deref(), Some("public"));
    assert_eq!(grant.objects[0].name, "users");
    assert!(matches!(
        &grant.principals[0],
        GrantPrincipalRef::User { tenant: Some(t), name } if t == "tenant1" && name == "alice"
    ));

    let query = parse("REVOKE GRANT OPTION FOR USAGE ON SCHEMA analytics FROM analysts").unwrap();
    let QueryExpr::Revoke(revoke) = query else {
        panic!("Expected Revoke");
    };
    assert!(revoke.grant_option_for);
    assert_eq!(revoke.actions, vec!["USAGE"]);
    assert_eq!(revoke.object_kind, GrantObjectKind::Schema);
    assert!(matches!(
        &revoke.principals[0],
        GrantPrincipalRef::User { tenant: None, name } if name == "analysts"
    ));

    let query = parse(
        "ALTER USER tenant1.alice VALID UNTIL '2030-01-01' CONNECTION LIMIT 5 DISABLE SET search_path = 'public,analytics' ADD GROUP analysts DROP GROUP temp PASSWORD 'newpw'",
    )
    .unwrap();
    let QueryExpr::AlterUser(stmt) = query else {
        panic!("Expected AlterUser");
    };
    assert_eq!(stmt.tenant.as_deref(), Some("tenant1"));
    assert_eq!(stmt.username, "alice");
    assert!(
        matches!(stmt.attributes[0], AlterUserAttribute::ValidUntil(ref s) if s == "2030-01-01")
    );
    assert!(matches!(
        stmt.attributes[1],
        AlterUserAttribute::ConnectionLimit(5)
    ));
    assert!(matches!(stmt.attributes[2], AlterUserAttribute::Disable));
    assert!(
        matches!(stmt.attributes[3], AlterUserAttribute::SetSearchPath(ref s) if s == "public,analytics")
    );
    assert!(matches!(stmt.attributes[4], AlterUserAttribute::AddGroup(ref g) if g == "analysts"));
    assert!(matches!(stmt.attributes[5], AlterUserAttribute::DropGroup(ref g) if g == "temp"));
    assert!(matches!(stmt.attributes[6], AlterUserAttribute::Password(ref p) if p == "newpw"));

    let query = parse(
        "GRANT INSERT, DELETE, TRUNCATE, REFERENCES, EXECUTE ON FUNCTION public.recalc TO GROUP analysts, bob",
    )
    .unwrap();
    let QueryExpr::Grant(grant) = query else {
        panic!("Expected Grant");
    };
    assert_eq!(
        grant.actions,
        vec!["INSERT", "DELETE", "TRUNCATE", "REFERENCES", "EXECUTE"]
    );
    assert_eq!(grant.object_kind, GrantObjectKind::Function);
    assert_eq!(grant.objects[0].schema.as_deref(), Some("public"));
    assert!(matches!(
        &grant.principals[0],
        GrantPrincipalRef::Group(group) if group == "analysts"
    ));
    assert!(matches!(
        &grant.principals[1],
        GrantPrincipalRef::User { tenant: None, name } if name == "bob"
    ));

    let query = parse("REVOKE ALL ON public.users, audit.events FROM GROUP analysts").unwrap();
    let QueryExpr::Revoke(revoke) = query else {
        panic!("Expected Revoke");
    };
    assert!(revoke.all);
    assert_eq!(revoke.object_kind, GrantObjectKind::Table);
    assert_eq!(revoke.objects.len(), 2);
    assert!(matches!(
        &revoke.principals[0],
        GrantPrincipalRef::Group(group) if group == "analysts"
    ));

    let query = parse("ALTER USER bob ENABLE SET search_path TO 'public'").unwrap();
    let QueryExpr::AlterUser(stmt) = query else {
        panic!("Expected AlterUser");
    };
    assert_eq!(stmt.tenant, None);
    assert_eq!(stmt.username, "bob");
    assert!(matches!(stmt.attributes[0], AlterUserAttribute::Enable));
    assert!(
        matches!(stmt.attributes[1], AlterUserAttribute::SetSearchPath(ref s) if s == "public")
    );
}

#[test]
fn test_parse_iam_policy_forms() {
    use crate::storage::query::ast::PolicyPrincipalRef;

    let query = parse("CREATE POLICY 'readonly' AS '{\"Statement\":[]}'").unwrap();
    assert!(matches!(
        query,
        QueryExpr::CreateIamPolicy { ref id, ref json }
            if id == "readonly" && json == "{\"Statement\":[]}"
    ));

    let query = parse("DROP POLICY 'readonly'").unwrap();
    assert!(matches!(query, QueryExpr::DropIamPolicy { ref id } if id == "readonly"));

    let query = parse("ATTACH POLICY 'readonly' TO USER tenant1.alice").unwrap();
    assert!(matches!(
        query,
        QueryExpr::AttachPolicy {
            ref policy_id,
            principal: PolicyPrincipalRef::User(ref user),
        } if policy_id == "readonly"
            && user.tenant.as_deref() == Some("tenant1")
            && user.username == "alice"
    ));

    let query = parse("DETACH POLICY 'readonly' FROM GROUP analysts").unwrap();
    assert!(matches!(
        query,
        QueryExpr::DetachPolicy {
            ref policy_id,
            principal: PolicyPrincipalRef::Group(ref group),
        } if policy_id == "readonly" && group == "analysts"
    ));

    let query = parse("SHOW POLICIES FOR GROUP analysts").unwrap();
    assert!(matches!(
        query,
        QueryExpr::ShowPolicies {
            filter: Some(PolicyPrincipalRef::Group(ref group)),
        } if group == "analysts"
    ));

    let query =
        parse("SHOW EFFECTIVE PERMISSIONS FOR tenant1.alice ON table:public.orders").unwrap();
    assert!(matches!(
        query,
        QueryExpr::ShowEffectivePermissions {
            ref user,
            resource: Some(ref resource),
        } if user.tenant.as_deref() == Some("tenant1")
            && user.username == "alice"
            && resource.kind == "table"
            && resource.name == "public.orders"
    ));

    let query = parse("SIMULATE tenant1.alice ACTION SELECT ON 'table:public.orders'").unwrap();
    assert!(matches!(
        query,
        QueryExpr::SimulatePolicy {
            ref user,
            ref action,
            ref resource,
        } if user.tenant.as_deref() == Some("tenant1")
            && user.username == "alice"
            && action == "select"
            && resource.kind == "table"
            && resource.name == "public.orders"
    ));

    let query = parse("SHOW POLICIES").unwrap();
    assert!(matches!(query, QueryExpr::Table(ref tq) if tq.table == "red.policies"));

    let query = parse("SHOW POLICIES FOR USER alice").unwrap();
    assert!(matches!(
        query,
        QueryExpr::ShowPolicies {
            filter: Some(PolicyPrincipalRef::User(ref user)),
        } if user.tenant.is_none() && user.username == "alice"
    ));

    let query = parse("SHOW EFFECTIVE PERMISSIONS FOR alice").unwrap();
    assert!(matches!(
        query,
        QueryExpr::ShowEffectivePermissions {
            ref user,
            resource: None,
        } if user.tenant.is_none() && user.username == "alice"
    ));

    let query = parse("SIMULATE alice ACTION 'iam:PassRole' ON TABLE:public.orders").unwrap();
    assert!(matches!(
        query,
        QueryExpr::SimulatePolicy {
            ref user,
            ref action,
            ref resource,
        } if user.tenant.is_none()
            && user.username == "alice"
            && action == "iam:PassRole"
            && resource.kind == "table"
            && resource.name == "public.orders"
    ));

    for sql in [
        "ATTACH ROLE 'readonly' TO USER alice",
        "DETACH POLICY 'readonly' TO USER alice",
        "SHOW EFFECTIVE ACTIONS FOR alice",
        "SIMULATE alice ON SELECT ON table:public.orders",
        "SIMULATE alice ACTION SELECT ON 'missing-colon'",
    ] {
        assert!(parse(sql).is_err(), "{sql}");
    }
}

#[test]
fn test_parse_auth_error_forms() {
    for sql in [
        "GRANT UNKNOWN ON TABLE users TO alice",
        "GRANT SELECT users TO alice",
        "GRANT SELECT ON TABLE users TO GROUP",
        "GRANT SELECT ON TABLE users TO alice WITH OPTION",
        "GRANT SELECT ON TABLE users TO alice WITH GRANT",
        "REVOKE GRANT SELECT ON TABLE users FROM alice",
        "REVOKE GRANT OPTION SELECT ON TABLE users FROM alice",
        "ALTER USER alice",
        "ALTER USER alice VALID '2030-01-01'",
        "ALTER USER alice CONNECTION 5",
        "ALTER USER alice SET timezone = 'UTC'",
        "ALTER USER alice SET search_path 'public'",
        "ALTER USER alice ADD ROLE analysts",
        "ALTER USER alice DROP ROLE analysts",
        "ATTACH POLICY 'readonly' TO ROLE analysts",
        "SIMULATE alice ACTION SELECT ON table public.orders",
        "SIMULATE alice ACTION 42 ON table:public.orders",
    ] {
        assert!(parse(sql).is_err(), "{sql}");
    }
}

#[test]
fn test_parse_migration_forms() {
    use crate::storage::query::ast::ApplyMigrationTarget;

    let query = parse(
        "CREATE MIGRATION m2 DEPENDS ON m0, m1 BATCH 500 ROWS NO ROLLBACK AS CREATE TABLE accounts (id INTEGER)",
    )
    .unwrap();
    let QueryExpr::CreateMigration(migration) = query else {
        panic!("Expected CreateMigration");
    };
    assert_eq!(migration.name, "m2");
    assert_eq!(migration.depends_on, vec!["m0", "m1"]);
    assert_eq!(migration.batch_size, Some(500));
    assert!(migration.no_rollback);
    assert_eq!(migration.body, "CREATE TABLE accounts ( id INTEGER )");

    let query = parse("APPLY MIGRATION * FOR TENANT tenant1").unwrap();
    assert!(matches!(
        query,
        QueryExpr::ApplyMigration(apply)
            if matches!(apply.target, ApplyMigrationTarget::All)
                && apply.for_tenant.as_deref() == Some("tenant1")
    ));

    let query = parse("ROLLBACK MIGRATION m2").unwrap();
    assert!(matches!(query, QueryExpr::RollbackMigration(r) if r.name == "m2"));

    let query = parse("EXPLAIN MIGRATION m2").unwrap();
    assert!(matches!(query, QueryExpr::ExplainMigration(e) if e.name == "m2"));

    let query = parse("APPLY MIGRATION m2 FOR TENANT 'tenant-string'").unwrap();
    assert!(matches!(
        query,
        QueryExpr::ApplyMigration(apply)
            if matches!(apply.target, ApplyMigrationTarget::Named(ref name) if name == "m2")
                && apply.for_tenant.as_deref() == Some("tenant-string")
    ));

    let query = parse("CREATE MIGRATION m3 CREATE INDEX idx ON accounts (id)").unwrap();
    assert!(matches!(
        query,
        QueryExpr::CreateMigration(migration)
            if migration.name == "m3"
                && migration.depends_on.is_empty()
                && migration.batch_size.is_none()
                && !migration.no_rollback
                && migration.body == "CREATE INDEX idx ON accounts ( id )"
    ));

    for sql in [
        "APPLY m2",
        "APPLY MIGRATION * FOR m2",
        "APPLY MIGRATION * FOR TENANT 42",
        "CREATE MIGRATION m4 DEPENDS m3 AS SELECT 1",
    ] {
        assert!(parse(sql).is_err(), "{sql}");
    }
}

#[test]
fn test_parse_probabilistic_command_matrix() {
    use crate::storage::query::ast::ProbabilisticCommand;

    let query = parse("CREATE HLL IF NOT EXISTS visitors").unwrap();
    assert!(matches!(
        query,
        QueryExpr::ProbabilisticCommand(ProbabilisticCommand::CreateHll {
            ref name,
            if_not_exists: true,
            ..
        }) if name == "visitors"
    ));

    let query = parse("HLL COUNT visitors signups").unwrap();
    assert!(matches!(
        query,
        QueryExpr::ProbabilisticCommand(ProbabilisticCommand::HllCount { ref names })
            if names == &vec!["visitors".to_string(), "signups".to_string()]
    ));

    let query = parse("HLL MERGE all_visitors visitors signups").unwrap();
    assert!(matches!(
        query,
        QueryExpr::ProbabilisticCommand(ProbabilisticCommand::HllMerge {
            ref dest,
            ref sources,
        }) if dest == "all_visitors"
            && sources == &vec!["visitors".to_string(), "signups".to_string()]
    ));

    let query = parse("HLL INFO visitors").unwrap();
    assert!(matches!(
        query,
        QueryExpr::ProbabilisticCommand(ProbabilisticCommand::HllInfo { ref name })
            if name == "visitors"
    ));

    let query = parse("DROP HLL IF EXISTS visitors").unwrap();
    assert!(matches!(
        query,
        QueryExpr::ProbabilisticCommand(ProbabilisticCommand::DropHll {
            ref name,
            if_exists: true,
        }) if name == "visitors"
    ));

    let query = parse("CREATE SKETCH IF NOT EXISTS freqs WIDTH 2048 DEPTH 7").unwrap();
    assert!(matches!(
        query,
        QueryExpr::ProbabilisticCommand(ProbabilisticCommand::CreateSketch {
            ref name,
            width: 2048,
            depth: 7,
            if_not_exists: true,
        }) if name == "freqs"
    ));

    let query = parse("SKETCH ADD freqs 'red' 3").unwrap();
    assert!(matches!(
        query,
        QueryExpr::ProbabilisticCommand(ProbabilisticCommand::SketchAdd {
            ref name,
            ref element,
            count: 3,
        }) if name == "freqs" && element == "red"
    ));

    let query = parse("SKETCH ADD freqs 'blue'").unwrap();
    assert!(matches!(
        query,
        QueryExpr::ProbabilisticCommand(ProbabilisticCommand::SketchAdd {
            ref name,
            ref element,
            count: 1,
        }) if name == "freqs" && element == "blue"
    ));

    let query = parse("SKETCH COUNT freqs 'red'").unwrap();
    assert!(matches!(
        query,
        QueryExpr::ProbabilisticCommand(ProbabilisticCommand::SketchCount {
            ref name,
            ref element,
        }) if name == "freqs" && element == "red"
    ));

    let query = parse("SKETCH MERGE total freqs other_freqs").unwrap();
    assert!(matches!(
        query,
        QueryExpr::ProbabilisticCommand(ProbabilisticCommand::SketchMerge {
            ref dest,
            ref sources,
        }) if dest == "total" && sources == &vec!["freqs".to_string(), "other_freqs".to_string()]
    ));

    let query = parse("SKETCH INFO freqs").unwrap();
    assert!(matches!(
        query,
        QueryExpr::ProbabilisticCommand(ProbabilisticCommand::SketchInfo { ref name })
            if name == "freqs"
    ));

    let query = parse("DROP SKETCH IF EXISTS freqs").unwrap();
    assert!(matches!(
        query,
        QueryExpr::ProbabilisticCommand(ProbabilisticCommand::DropSketch {
            ref name,
            if_exists: true,
        }) if name == "freqs"
    ));

    let query = parse("CREATE FILTER IF NOT EXISTS seen CAPACITY 4096").unwrap();
    assert!(matches!(
        query,
        QueryExpr::ProbabilisticCommand(ProbabilisticCommand::CreateFilter {
            ref name,
            capacity: 4096,
            if_not_exists: true,
        }) if name == "seen"
    ));

    let query = parse("FILTER ADD seen 'a'").unwrap();
    assert!(matches!(
        query,
        QueryExpr::ProbabilisticCommand(ProbabilisticCommand::FilterAdd {
            ref name,
            ref element,
        }) if name == "seen" && element == "a"
    ));

    let query = parse("FILTER CHECK seen 'a'").unwrap();
    assert!(matches!(
        query,
        QueryExpr::ProbabilisticCommand(ProbabilisticCommand::FilterCheck {
            ref name,
            ref element,
        }) if name == "seen" && element == "a"
    ));

    let query = parse("FILTER DELETE seen 'a'").unwrap();
    assert!(matches!(
        query,
        QueryExpr::ProbabilisticCommand(ProbabilisticCommand::FilterDelete {
            ref name,
            ref element,
        }) if name == "seen" && element == "a"
    ));

    let query = parse("FILTER COUNT seen").unwrap();
    assert!(matches!(
        query,
        QueryExpr::ProbabilisticCommand(ProbabilisticCommand::FilterCount { ref name })
            if name == "seen"
    ));

    let query = parse("FILTER INFO seen").unwrap();
    assert!(matches!(
        query,
        QueryExpr::ProbabilisticCommand(ProbabilisticCommand::FilterInfo { ref name })
            if name == "seen"
    ));

    let query = parse("DROP FILTER IF EXISTS seen").unwrap();
    assert!(matches!(
        query,
        QueryExpr::ProbabilisticCommand(ProbabilisticCommand::DropFilter {
            ref name,
            if_exists: true,
        }) if name == "seen"
    ));

    let query = parse("CREATE HLL visitors2").unwrap();
    assert!(matches!(
        query,
        QueryExpr::ProbabilisticCommand(ProbabilisticCommand::CreateHll {
            ref name,
            if_not_exists: false,
            ..
        }) if name == "visitors2"
    ));

    let query = parse("CREATE SKETCH freqs2 DEPTH 3 WIDTH 512").unwrap();
    assert!(matches!(
        query,
        QueryExpr::ProbabilisticCommand(ProbabilisticCommand::CreateSketch {
            ref name,
            width: 512,
            depth: 3,
            if_not_exists: false,
        }) if name == "freqs2"
    ));

    let query = parse("CREATE FILTER seen2").unwrap();
    assert!(matches!(
        query,
        QueryExpr::ProbabilisticCommand(ProbabilisticCommand::CreateFilter {
            ref name,
            capacity: 100_000,
            if_not_exists: false,
        }) if name == "seen2"
    ));

    let query = parse("DROP FILTER seen2").unwrap();
    assert!(matches!(
        query,
        QueryExpr::ProbabilisticCommand(ProbabilisticCommand::DropFilter {
            ref name,
            if_exists: false,
        }) if name == "seen2"
    ));

    for sql in [
        "HLL DESCRIBE visitors",
        "SKETCH DESCRIBE freqs",
        "FILTER DESCRIBE seen",
        "CREATE BLOOM seen",
        "DROP BLOOM seen",
    ] {
        assert!(parse(sql).is_err(), "{sql}");
    }
}

#[test]
fn test_parse_transaction_control() {
    use crate::storage::query::ast::TxnControl;

    // BEGIN (bare)
    assert!(matches!(
        parse("BEGIN").unwrap(),
        QueryExpr::TransactionControl(TxnControl::Begin)
    ));
    // BEGIN WORK
    assert!(matches!(
        parse("BEGIN WORK").unwrap(),
        QueryExpr::TransactionControl(TxnControl::Begin)
    ));
    // BEGIN TRANSACTION
    assert!(matches!(
        parse("BEGIN TRANSACTION").unwrap(),
        QueryExpr::TransactionControl(TxnControl::Begin)
    ));
    // START TRANSACTION
    assert!(matches!(
        parse("START TRANSACTION").unwrap(),
        QueryExpr::TransactionControl(TxnControl::Begin)
    ));

    // COMMIT + COMMIT WORK + COMMIT TRANSACTION
    for s in ["COMMIT", "COMMIT WORK", "COMMIT TRANSACTION"] {
        assert!(
            matches!(
                parse(s).unwrap(),
                QueryExpr::TransactionControl(TxnControl::Commit)
            ),
            "failed for {s}"
        );
    }

    // ROLLBACK + ROLLBACK WORK + ROLLBACK TRANSACTION
    for s in ["ROLLBACK", "ROLLBACK WORK", "ROLLBACK TRANSACTION"] {
        assert!(
            matches!(
                parse(s).unwrap(),
                QueryExpr::TransactionControl(TxnControl::Rollback)
            ),
            "failed for {s}"
        );
    }

    // SAVEPOINT name
    if let QueryExpr::TransactionControl(TxnControl::Savepoint(name)) =
        parse("SAVEPOINT sp1").unwrap()
    {
        assert_eq!(name, "sp1");
    } else {
        panic!("Expected Savepoint");
    }

    // RELEASE SAVEPOINT name
    if let QueryExpr::TransactionControl(TxnControl::ReleaseSavepoint(name)) =
        parse("RELEASE SAVEPOINT sp1").unwrap()
    {
        assert_eq!(name, "sp1");
    } else {
        panic!("Expected ReleaseSavepoint");
    }
    // RELEASE name (without SAVEPOINT keyword — PG accepts both)
    if let QueryExpr::TransactionControl(TxnControl::ReleaseSavepoint(name)) =
        parse("RELEASE sp2").unwrap()
    {
        assert_eq!(name, "sp2");
    } else {
        panic!("Expected ReleaseSavepoint");
    }

    // ROLLBACK TO SAVEPOINT name
    if let QueryExpr::TransactionControl(TxnControl::RollbackToSavepoint(name)) =
        parse("ROLLBACK TO SAVEPOINT sp1").unwrap()
    {
        assert_eq!(name, "sp1");
    } else {
        panic!("Expected RollbackToSavepoint");
    }
    // ROLLBACK TO name (without SAVEPOINT keyword)
    if let QueryExpr::TransactionControl(TxnControl::RollbackToSavepoint(name)) =
        parse("ROLLBACK TO sp3").unwrap()
    {
        assert_eq!(name, "sp3");
    } else {
        panic!("Expected RollbackToSavepoint");
    }
}

#[test]
fn test_parse_maintenance_commands() {
    use crate::storage::query::ast::MaintenanceCommand as Mc;

    // VACUUM (no target)
    if let QueryExpr::MaintenanceCommand(Mc::Vacuum { target, full }) = parse("VACUUM").unwrap() {
        assert_eq!(target, None);
        assert!(!full);
    } else {
        panic!("Expected Vacuum");
    }

    // VACUUM users (table target)
    if let QueryExpr::MaintenanceCommand(Mc::Vacuum { target, full }) =
        parse("VACUUM users").unwrap()
    {
        assert_eq!(target, Some("users".to_string()));
        assert!(!full);
    } else {
        panic!("Expected Vacuum");
    }

    // VACUUM FULL
    if let QueryExpr::MaintenanceCommand(Mc::Vacuum { target, full }) =
        parse("VACUUM FULL").unwrap()
    {
        assert_eq!(target, None);
        assert!(full);
    } else {
        panic!("Expected Vacuum FULL");
    }

    // VACUUM FULL users
    if let QueryExpr::MaintenanceCommand(Mc::Vacuum { target, full }) =
        parse("VACUUM FULL users").unwrap()
    {
        assert_eq!(target, Some("users".to_string()));
        assert!(full);
    } else {
        panic!("Expected Vacuum FULL users");
    }

    // ANALYZE (no target)
    if let QueryExpr::MaintenanceCommand(Mc::Analyze { target }) = parse("ANALYZE").unwrap() {
        assert_eq!(target, None);
    } else {
        panic!("Expected Analyze");
    }

    // ANALYZE users
    if let QueryExpr::MaintenanceCommand(Mc::Analyze { target }) = parse("ANALYZE users").unwrap() {
        assert_eq!(target, Some("users".to_string()));
    } else {
        panic!("Expected Analyze users");
    }
}

#[test]
fn test_parse_schema_and_sequence_ddl() {
    // CREATE SCHEMA
    if let QueryExpr::CreateSchema(q) = parse("CREATE SCHEMA app").unwrap() {
        assert_eq!(q.name, "app");
        assert!(!q.if_not_exists);
    } else {
        panic!("Expected CreateSchema");
    }
    if let QueryExpr::CreateSchema(q) = parse("CREATE SCHEMA IF NOT EXISTS app").unwrap() {
        assert_eq!(q.name, "app");
        assert!(q.if_not_exists);
    } else {
        panic!("Expected CreateSchema IF NOT EXISTS");
    }

    // DROP SCHEMA
    if let QueryExpr::DropSchema(q) = parse("DROP SCHEMA app").unwrap() {
        assert_eq!(q.name, "app");
        assert!(!q.if_exists);
        assert!(!q.cascade);
    } else {
        panic!("Expected DropSchema");
    }
    if let QueryExpr::DropSchema(q) = parse("DROP SCHEMA IF EXISTS app CASCADE").unwrap() {
        assert_eq!(q.name, "app");
        assert!(q.if_exists);
        assert!(q.cascade);
    } else {
        panic!("Expected DropSchema IF EXISTS CASCADE");
    }

    // CREATE SEQUENCE — bare
    if let QueryExpr::CreateSequence(q) = parse("CREATE SEQUENCE s1").unwrap() {
        assert_eq!(q.name, "s1");
        assert_eq!(q.start, 1);
        assert_eq!(q.increment, 1);
        assert!(!q.if_not_exists);
    } else {
        panic!("Expected CreateSequence");
    }

    // CREATE SEQUENCE with START and INCREMENT
    if let QueryExpr::CreateSequence(q) =
        parse("CREATE SEQUENCE s1 START WITH 100 INCREMENT BY 5").unwrap()
    {
        assert_eq!(q.name, "s1");
        assert_eq!(q.start, 100);
        assert_eq!(q.increment, 5);
    } else {
        panic!("Expected CreateSequence with START/INCREMENT");
    }

    // Order agnostic (INCREMENT before START)
    if let QueryExpr::CreateSequence(q) = parse("CREATE SEQUENCE s1 INCREMENT 3 START 10").unwrap()
    {
        assert_eq!(q.start, 10);
        assert_eq!(q.increment, 3);
    } else {
        panic!("Expected CreateSequence reversed order");
    }

    // IF NOT EXISTS
    if let QueryExpr::CreateSequence(q) = parse("CREATE SEQUENCE IF NOT EXISTS s1").unwrap() {
        assert!(q.if_not_exists);
    } else {
        panic!("Expected CreateSequence IF NOT EXISTS");
    }

    // DROP SEQUENCE
    if let QueryExpr::DropSequence(q) = parse("DROP SEQUENCE s1").unwrap() {
        assert_eq!(q.name, "s1");
        assert!(!q.if_exists);
    } else {
        panic!("Expected DropSequence");
    }
    if let QueryExpr::DropSequence(q) = parse("DROP SEQUENCE IF EXISTS s1").unwrap() {
        assert!(q.if_exists);
    } else {
        panic!("Expected DropSequence IF EXISTS");
    }
}

#[test]
fn test_parse_copy_from_csv() {
    // Basic COPY: no options.
    if let QueryExpr::CopyFrom(q) = parse("COPY users FROM '/tmp/u.csv'").unwrap() {
        assert_eq!(q.table, "users");
        assert_eq!(q.path, "/tmp/u.csv");
        assert!(!q.has_header);
        assert_eq!(q.delimiter, None);
    } else {
        panic!("Expected CopyFrom");
    }

    // Short form with HEADER + DELIMITER outside WITH.
    if let QueryExpr::CopyFrom(q) =
        parse("COPY users FROM '/tmp/u.csv' DELIMITER ';' HEADER").unwrap()
    {
        assert_eq!(q.table, "users");
        assert_eq!(q.delimiter, Some(';'));
        assert!(q.has_header);
    } else {
        panic!("Expected CopyFrom with short options");
    }

    // PG-style WITH block.
    if let QueryExpr::CopyFrom(q) =
        parse("COPY users FROM '/tmp/u.csv' WITH (FORMAT = csv, HEADER = true, DELIMITER = ',')")
            .unwrap()
    {
        assert_eq!(q.delimiter, Some(','));
        assert!(q.has_header);
    } else {
        panic!("Expected CopyFrom with WITH block");
    }
}

#[test]
fn test_parse_view_ddl() {
    // CREATE VIEW
    if let QueryExpr::CreateView(q) =
        parse("CREATE VIEW active_users AS SELECT * FROM users").unwrap()
    {
        assert_eq!(q.name, "active_users");
        assert!(!q.materialized);
        assert!(!q.if_not_exists);
        assert!(!q.or_replace);
        // Body must be a Table query pointing at `users`.
        if let QueryExpr::Table(tq) = *q.query {
            assert_eq!(tq.table, "users");
        } else {
            panic!("Expected Table body");
        }
    } else {
        panic!("Expected CreateView");
    }

    // CREATE OR REPLACE VIEW
    if let QueryExpr::CreateView(q) = parse("CREATE OR REPLACE VIEW v AS SELECT id FROM t").unwrap()
    {
        assert!(q.or_replace);
        assert!(!q.materialized);
    } else {
        panic!("Expected CreateView OR REPLACE");
    }

    // CREATE MATERIALIZED VIEW IF NOT EXISTS
    if let QueryExpr::CreateView(q) =
        parse("CREATE MATERIALIZED VIEW IF NOT EXISTS mv AS SELECT id FROM t").unwrap()
    {
        assert!(q.materialized);
        assert!(q.if_not_exists);
    } else {
        panic!("Expected CreateView MATERIALIZED IF NOT EXISTS");
    }

    // DROP VIEW
    if let QueryExpr::DropView(q) = parse("DROP VIEW v").unwrap() {
        assert_eq!(q.name, "v");
        assert!(!q.materialized);
        assert!(!q.if_exists);
    } else {
        panic!("Expected DropView");
    }

    // DROP MATERIALIZED VIEW IF EXISTS
    if let QueryExpr::DropView(q) = parse("DROP MATERIALIZED VIEW IF EXISTS mv").unwrap() {
        assert!(q.materialized);
        assert!(q.if_exists);
    } else {
        panic!("Expected DropView MATERIALIZED IF EXISTS");
    }

    // REFRESH MATERIALIZED VIEW
    if let QueryExpr::RefreshMaterializedView(q) = parse("REFRESH MATERIALIZED VIEW mv").unwrap() {
        assert_eq!(q.name, "mv");
    } else {
        panic!("Expected RefreshMaterializedView");
    }
}

#[test]
fn test_parse_partitioning_ddl() {
    use crate::storage::query::ast::{AlterOperation, PartitionKind};

    // CREATE TABLE with PARTITION BY RANGE
    if let QueryExpr::CreateTable(t) =
        parse("CREATE TABLE events (id INT, ts INT) PARTITION BY RANGE (ts)").unwrap()
    {
        assert_eq!(t.name, "events");
        let spec = t.partition_by.expect("partition_by should be set");
        assert_eq!(spec.kind, PartitionKind::Range);
        assert_eq!(spec.column, "ts");
    } else {
        panic!("Expected CreateTable with PARTITION BY RANGE");
    }

    // CREATE TABLE with PARTITION BY LIST
    if let QueryExpr::CreateTable(t) =
        parse("CREATE TABLE logs (region TEXT) PARTITION BY LIST (region)").unwrap()
    {
        let spec = t.partition_by.unwrap();
        assert_eq!(spec.kind, PartitionKind::List);
        assert_eq!(spec.column, "region");
    } else {
        panic!("Expected LIST partition");
    }

    // CREATE TABLE with PARTITION BY HASH
    if let QueryExpr::CreateTable(t) =
        parse("CREATE TABLE shards (uid INT) PARTITION BY HASH (uid)").unwrap()
    {
        let spec = t.partition_by.unwrap();
        assert_eq!(spec.kind, PartitionKind::Hash);
    } else {
        panic!("Expected HASH partition");
    }

    // ALTER TABLE ... ATTACH PARTITION
    if let QueryExpr::AlterTable(q) =
        parse("ALTER TABLE events ATTACH PARTITION events_2024 FOR VALUES FROM (2024) TO (2025)")
            .unwrap()
    {
        assert_eq!(q.name, "events");
        match &q.operations[0] {
            AlterOperation::AttachPartition { child, bound } => {
                assert_eq!(child, "events_2024");
                assert!(bound.contains("FROM"));
                assert!(bound.contains("TO"));
            }
            other => panic!("Expected AttachPartition, got {:?}", other),
        }
    } else {
        panic!("Expected AlterTable");
    }

    // ALTER TABLE ... DETACH PARTITION
    if let QueryExpr::AlterTable(q) =
        parse("ALTER TABLE events DETACH PARTITION events_2024").unwrap()
    {
        match &q.operations[0] {
            AlterOperation::DetachPartition { child } => {
                assert_eq!(child, "events_2024");
            }
            other => panic!("Expected DetachPartition, got {:?}", other),
        }
    } else {
        panic!("Expected AlterTable");
    }
}

#[test]
fn test_parse_row_level_security_ddl() {
    use crate::storage::query::ast::{AlterOperation, PolicyAction};

    // CREATE POLICY
    if let QueryExpr::CreatePolicy(q) =
        parse("CREATE POLICY owner_only ON users USING (owner_id = 1)").unwrap()
    {
        assert_eq!(q.name, "owner_only");
        assert_eq!(q.table, "users");
        assert_eq!(q.action, None);
        assert_eq!(q.role, None);
    } else {
        panic!("Expected CreatePolicy");
    }

    // CREATE POLICY with action + role
    if let QueryExpr::CreatePolicy(q) =
        parse("CREATE POLICY readonly ON t FOR SELECT TO analytics USING (public = 1)").unwrap()
    {
        assert_eq!(q.action, Some(PolicyAction::Select));
        assert_eq!(q.role.as_deref(), Some("analytics"));
    } else {
        panic!("Expected CreatePolicy with action + role");
    }

    // DROP POLICY
    if let QueryExpr::DropPolicy(q) = parse("DROP POLICY owner_only ON users").unwrap() {
        assert_eq!(q.name, "owner_only");
        assert_eq!(q.table, "users");
        assert!(!q.if_exists);
    } else {
        panic!("Expected DropPolicy");
    }

    // DROP POLICY IF EXISTS
    if let QueryExpr::DropPolicy(q) = parse("DROP POLICY IF EXISTS p ON t").unwrap() {
        assert!(q.if_exists);
    } else {
        panic!("Expected DropPolicy IF EXISTS");
    }

    // ALTER TABLE ENABLE ROW LEVEL SECURITY
    if let QueryExpr::AlterTable(q) = parse("ALTER TABLE users ENABLE ROW LEVEL SECURITY").unwrap()
    {
        assert!(matches!(
            q.operations[0],
            AlterOperation::EnableRowLevelSecurity
        ));
    } else {
        panic!("Expected ENABLE ROW LEVEL SECURITY");
    }

    // ALTER TABLE DISABLE ROW LEVEL SECURITY
    if let QueryExpr::AlterTable(q) = parse("ALTER TABLE users DISABLE ROW LEVEL SECURITY").unwrap()
    {
        assert!(matches!(
            q.operations[0],
            AlterOperation::DisableRowLevelSecurity
        ));
    } else {
        panic!("Expected DISABLE ROW LEVEL SECURITY");
    }
}

#[test]
fn test_parse_fdw_ddl() {
    // CREATE SERVER
    if let QueryExpr::CreateServer(q) =
        parse("CREATE SERVER mycsv FOREIGN DATA WRAPPER csv OPTIONS (base_path '/data')").unwrap()
    {
        assert_eq!(q.name, "mycsv");
        assert_eq!(q.wrapper, "csv");
        assert_eq!(q.options.len(), 1);
        assert_eq!(q.options[0].0, "base_path");
        assert_eq!(q.options[0].1, "/data");
    } else {
        panic!("Expected CreateServer");
    }

    // CREATE SERVER with IF NOT EXISTS + multiple options
    if let QueryExpr::CreateServer(q) =
        parse("CREATE SERVER IF NOT EXISTS s2 FOREIGN DATA WRAPPER csv OPTIONS (a 'x', b 'y')")
            .unwrap()
    {
        assert!(q.if_not_exists);
        assert_eq!(q.options.len(), 2);
    } else {
        panic!("Expected CreateServer IF NOT EXISTS");
    }

    // DROP SERVER
    if let QueryExpr::DropServer(q) = parse("DROP SERVER mycsv").unwrap() {
        assert_eq!(q.name, "mycsv");
        assert!(!q.if_exists);
        assert!(!q.cascade);
    } else {
        panic!("Expected DropServer");
    }

    // DROP SERVER IF EXISTS ... CASCADE
    if let QueryExpr::DropServer(q) = parse("DROP SERVER IF EXISTS mycsv CASCADE").unwrap() {
        assert!(q.if_exists);
        assert!(q.cascade);
    } else {
        panic!("Expected DropServer IF EXISTS CASCADE");
    }

    // CREATE FOREIGN TABLE
    if let QueryExpr::CreateForeignTable(q) = parse(
        "CREATE FOREIGN TABLE users (id INT, name TEXT) SERVER mycsv OPTIONS (path 'users.csv')",
    )
    .unwrap()
    {
        assert_eq!(q.name, "users");
        assert_eq!(q.server, "mycsv");
        assert_eq!(q.columns.len(), 2);
        assert_eq!(q.columns[0].name, "id");
        assert_eq!(q.columns[1].name, "name");
        assert_eq!(q.options.len(), 1);
        assert_eq!(q.options[0].0, "path");
    } else {
        panic!("Expected CreateForeignTable");
    }

    // DROP FOREIGN TABLE
    if let QueryExpr::DropForeignTable(q) = parse("DROP FOREIGN TABLE IF EXISTS users").unwrap() {
        assert_eq!(q.name, "users");
        assert!(q.if_exists);
    } else {
        panic!("Expected DropForeignTable");
    }
}

// ─────────────────────────────────────────────────────────────────────
// CTE / WITH clause parsing — issue #40.
//
// Top-level `parser::parse` now returns `QueryWithCte`. A leading
// `WITH` is consumed as a CTE prelude; everything else returns the
// `simple` shape with `with_clause: None`. Execution-side wiring is
// out of scope here (#41) — these tests only assert that the parser
// produces the right AST.
// ─────────────────────────────────────────────────────────────────────

#[test]
fn cte_no_with_clause_produces_simple_shape() {
    let parsed = super::parse("SELECT * FROM users").unwrap();
    assert!(parsed.with_clause.is_none());
    assert!(matches!(parsed.query, QueryExpr::Table(_)));
}

#[test]
fn cte_single_with_single_reference() {
    let parsed = super::parse(
        "WITH active AS (SELECT * FROM users WHERE status = 'active') \
         SELECT count(*) FROM active",
    )
    .unwrap();
    let with = parsed
        .with_clause
        .as_ref()
        .expect("with_clause should be Some");
    assert_eq!(with.ctes.len(), 1);
    assert_eq!(with.ctes[0].name, "active");
    assert!(with.ctes[0].columns.is_empty());
    assert!(!with.has_recursive);
    assert!(matches!(parsed.query, QueryExpr::Table(_)));
}

#[test]
fn cte_chained_definitions() {
    let parsed =
        super::parse("WITH a AS (SELECT * FROM t1), b AS (SELECT * FROM a) SELECT * FROM b")
            .unwrap();
    let with = parsed.with_clause.expect("with_clause should be Some");
    assert_eq!(with.ctes.len(), 2);
    assert_eq!(with.ctes[0].name, "a");
    assert_eq!(with.ctes[1].name, "b");
}

#[test]
fn cte_with_column_aliases() {
    let parsed =
        super::parse("WITH x(a, b) AS (SELECT id, name FROM users) SELECT * FROM x").unwrap();
    let with = parsed.with_clause.expect("with_clause should be Some");
    assert_eq!(with.ctes.len(), 1);
    assert_eq!(with.ctes[0].name, "x");
    assert_eq!(with.ctes[0].columns, vec!["a".to_string(), "b".to_string()]);
}

#[test]
fn cte_recursive_marker_propagates() {
    let parsed =
        super::parse("WITH RECURSIVE walk AS (SELECT * FROM nodes) SELECT * FROM walk").unwrap();
    let with = parsed.with_clause.expect("with_clause should be Some");
    assert!(with.has_recursive);
    assert!(with.ctes[0].recursive);
}

// --- Issue #87: hardening / DoS-limit tests --------------------

#[test]
fn dos_limit_input_too_large_is_structured() {
    use super::limits::ParserLimits;
    let limits = ParserLimits {
        max_input_bytes: 16,
        ..ParserLimits::default()
    };
    // The input is well over 16 bytes — must refuse before tokenizing.
    let err = super::Parser::with_limits("SELECT * FROM users WHERE x = 1", limits)
        .err()
        .expect("oversized input must error");
    assert!(matches!(
        err.kind,
        super::ParseErrorKind::InputTooLarge {
            limit_name: "max_input_bytes",
            value: 16,
        }
    ));
}

#[test]
fn dos_limit_identifier_too_long_is_structured() {
    use super::limits::ParserLimits;
    let limits = ParserLimits {
        max_identifier_chars: 8,
        ..ParserLimits::default()
    };
    // `userstable_long_identifier_name` is well over 8 chars; SELECT/FROM
    // are 6 and 4 chars respectively, both ≤ 8.
    let err = super::Parser::with_limits("SELECT * FROM userstable_long_identifier_name", limits)
        .and_then(|mut p| p.parse())
        .err()
        .expect("oversized ident must error");
    assert!(
        matches!(
            err.kind,
            super::ParseErrorKind::IdentifierTooLong {
                limit_name: "max_identifier_chars",
                ..
            }
        ),
        "kind: {:?}",
        err.kind
    );
}

#[test]
fn dos_limit_recursion_depth_is_structured() {
    use super::limits::ParserLimits;
    let limits = ParserLimits {
        max_depth: 8,
        ..ParserLimits::default()
    };
    // 50 nested parens = recursion depth 50, well past the cap of 8.
    let nested = format!("SELECT {}1{} FROM t", "(".repeat(50), ")".repeat(50));
    let mut parser = super::Parser::with_limits(&nested, limits).expect("ctor ok");
    let err = parser.parse().err().expect("deep nesting must error");
    assert!(matches!(
        err.kind,
        super::ParseErrorKind::DepthLimit {
            limit_name: "max_depth",
            value: 8,
        }
    ));
}

#[test]
fn dos_limit_no_panic_on_pathological_input() {
    // Adversarial inputs return Err but never panic / OOM.
    let mut adversarial = "(".repeat(2_000);
    adversarial.push_str("SELECT 1");
    adversarial.push_str(&")".repeat(2_000));
    let _ = super::parse(&adversarial); // must return Err, not panic.

    let big = "x".repeat(10_000); // exceeds default 256 ident cap
    let _ = super::parse(&format!("SELECT {} FROM t", big));

    let huge = "a".repeat(2 * 1024 * 1024); // 2 MiB, exceeds 1 MiB cap
    let err = super::parse(&huge).err().expect("must reject");
    assert!(matches!(
        err.kind,
        super::ParseErrorKind::InputTooLarge { .. }
    ));
}

#[test]
fn dos_limit_chained_not_in_where_does_not_overflow_stack() {
    // Regression test for issue #91. Before the fix,
    // `parse_not_expr` recursed into itself for `NOT NOT NOT … x`
    // without entering the depth counter — only the leaf reached
    // `parse_expr_prec`'s `enter_depth()`, so a 10k-NOT payload
    // overflowed the Rust stack BEFORE `max_depth=128` could fire.
    //
    // We run on a generous-stack thread so that, in the unfixed
    // build, the test reliably reports the overflow as a panic
    // rather than aborting the whole test runner. With the fix,
    // the depth guard fires structurally and the inner thread
    // returns a `DepthLimit` error.
    let handle = std::thread::Builder::new()
        .stack_size(8 * 1024 * 1024)
        .spawn(|| {
            let mut sql = String::from("SELECT * FROM t WHERE ");
            for _ in 0..10_000 {
                sql.push_str("NOT ");
            }
            sql.push_str("x");
            let err = super::parse(&sql).err().expect("must error, not panic");
            assert!(
                matches!(
                    err.kind,
                    super::ParseErrorKind::DepthLimit {
                        limit_name: "max_depth",
                        ..
                    }
                ),
                "expected DepthLimit, got: {:?}",
                err.kind
            );
        })
        .expect("spawn deep-NOT thread");
    handle.join().expect("deep-NOT thread must not panic");
}

// ---------------------------------------------------------------------------
// Documented raw JSON literal forms (audit: cover every example we ship in
// docs and landing page so the docs cannot lie). Each test parses the exact
// string a user would copy from the doc and asserts the resulting AST.
// ---------------------------------------------------------------------------

#[test]
fn doc_form_queue_push_raw_json_literal() {
    // docs/data-models/queues.md:38, README.md:68
    let q = parse(r#"QUEUE PUSH tasks {"job":"process","id":123}"#).unwrap();
    let QueryExpr::QueueCommand(QueueCommand::Push { queue, value, .. }) = q else {
        panic!("expected Push");
    };
    assert_eq!(queue, "tasks");
    let crate::storage::schema::Value::Json(bytes) = value else {
        panic!("expected Value::Json, got {value:?}");
    };
    let v: crate::json::Value = crate::json::from_slice(&bytes).unwrap();
    assert_eq!(v.get("job").and_then(|x| x.as_str()), Some("process"));
    assert_eq!(v.get("id").and_then(|x| x.as_i64()), Some(123));
}

#[test]
fn doc_form_queue_rpush_raw_json_literal() {
    // docs/data-models/queues.md:39
    let q = parse(r#"QUEUE RPUSH tasks {"job":"process","id":456}"#).unwrap();
    assert!(matches!(
        q,
        QueryExpr::QueueCommand(QueueCommand::Push { .. })
    ));
}

#[test]
fn doc_form_queue_lpush_raw_json_literal() {
    // docs/data-models/queues.md:42
    let q = parse(r#"QUEUE LPUSH tasks {"urgent":true}"#).unwrap();
    assert!(matches!(
        q,
        QueryExpr::QueueCommand(QueueCommand::Push { .. })
    ));
}

#[test]
fn doc_form_queue_push_raw_json_with_priority_suffix() {
    // docs/data-models/queues.md:45
    let q = parse(r#"QUEUE PUSH urgent_tasks {"job":"deploy"} PRIORITY 10"#).unwrap();
    let QueryExpr::QueueCommand(QueueCommand::Push {
        priority, value, ..
    }) = q
    else {
        panic!("expected Push");
    };
    assert_eq!(priority, Some(10));
    assert!(matches!(value, crate::storage::schema::Value::Json(_)));
}

#[test]
fn doc_form_insert_document_with_raw_json_literal_in_values() {
    // README.md:44, landing +page.svelte:54/150/492
    let q = parse(r#"INSERT INTO logs DOCUMENT (body) VALUES ({"level":"warn","ip":"10.0.0.1"})"#)
        .unwrap();
    // We don't pin the exact AST shape — just prove it parses to *some* insert.
    match q {
        QueryExpr::Insert(_) => {}
        other => panic!(
            "expected Insert/InsertDocument, got: {:?}",
            std::mem::discriminant(&other)
        ),
    }
}

#[test]
fn doc_form_timeseries_insert_with_raw_json_tags_3_tuple() {
    // landing +page.svelte:59/497, data-types.ts:604, README.md:57
    let q = parse(
        r#"INSERT INTO cpu_metrics (metric, value, tags) VALUES ('cpu.idle', 95.2, {"host":"srv1"})"#,
    )
    .unwrap();
    assert!(matches!(q, QueryExpr::Insert(_)));
}

#[test]
fn doc_form_timeseries_insert_with_raw_json_tags_4_tuple() {
    // docs/data-models/timeseries.md:62
    let q = parse(
        r#"INSERT INTO cpu_metrics (metric, value, tags, timestamp) VALUES ('cpu.idle', 94.8, {"host":"srv1"}, 1704067200000000000)"#,
    )
    .unwrap();
    assert!(matches!(q, QueryExpr::Insert(_)));
}

#[test]
fn doc_form_timeseries_multi_row_insert_with_raw_json_tags() {
    // docs/data-models/timeseries.md:69 — multi-row VALUES with raw JSON
    let q = parse(
        r#"INSERT INTO cpu_metrics (metric, value, tags) VALUES ('cpu.idle', 95.2, {"host":"srv1"}), ('cpu.busy', 4.8, {"host":"srv1"})"#,
    )
    .unwrap();
    assert!(matches!(q, QueryExpr::Insert(_)));
}

// ============================================================================
// KV DSL parser tests
// ============================================================================

#[test]
fn test_parse_kv_put_bare_key() {
    let q = parse("KV PUT name = 'alice'").unwrap();
    if let QueryExpr::KvCommand(KvCommand::Put {
        collection,
        key,
        value,
        ttl_ms,
        if_not_exists,
        ..
    }) = q
    {
        assert_eq!(collection, "kv_default");
        assert_eq!(key, "name");
        assert_eq!(value, crate::storage::schema::Value::text("alice"));
        assert_eq!(ttl_ms, None);
        assert!(!if_not_exists);
    } else {
        panic!("expected KvCommand::Put");
    }
}

#[test]
fn test_parse_kv_put_dotted_key() {
    let q = parse("KV PUT sessions.abc123 = 'data'").unwrap();
    if let QueryExpr::KvCommand(KvCommand::Put {
        collection, key, ..
    }) = q
    {
        assert_eq!(collection, "sessions");
        assert_eq!(key, "abc123");
    } else {
        panic!("expected KvCommand::Put");
    }
}

#[test]
fn test_parse_kv_put_with_expire() {
    let q = parse("KV PUT token = 'jwt-xyz' EXPIRE 30 s").unwrap();
    assert!(matches!(
        q,
        QueryExpr::KvCommand(KvCommand::Put {
            ttl_ms: Some(30_000),
            ..
        })
    ));
}

#[test]
fn test_parse_kv_put_expire_units() {
    for (sql, expected_ms) in [
        ("KV PUT mykey = 1 EXPIRE 100 ms", 100u64),
        ("KV PUT mykey = 1 EXPIRE 2 s", 2_000),
        ("KV PUT mykey = 1 EXPIRE 1 min", 60_000),
        ("KV PUT mykey = 1 EXPIRE 1 hr", 3_600_000),
        ("KV PUT mykey = 1 EXPIRE 1 day", 86_400_000),
    ] {
        let q = parse(sql).unwrap();
        assert!(
            matches!(q, QueryExpr::KvCommand(KvCommand::Put { ttl_ms: Some(ms), .. }) if ms == expected_ms),
            "failed for {sql}: expected {expected_ms} ms"
        );
    }
}

#[test]
fn test_parse_kv_put_if_not_exists() {
    let q = parse("KV PUT lock.deploy = 'free' IF NOT EXISTS").unwrap();
    assert!(matches!(
        q,
        QueryExpr::KvCommand(KvCommand::Put {
            if_not_exists: true,
            ..
        })
    ));
}

#[test]
fn test_parse_kv_put_with_tags() {
    let q = parse("KV PUT sessions.blob = 'data' TAGS [user:42, org:7]").unwrap();
    if let QueryExpr::KvCommand(KvCommand::Put {
        collection,
        key,
        tags,
        ..
    }) = q
    {
        assert_eq!(collection, "sessions");
        assert_eq!(key, "blob");
        assert_eq!(tags, vec!["user:42".to_string(), "org:7".to_string()]);
    } else {
        panic!("expected KvCommand::Put");
    }
}

#[test]
fn test_parse_kv_invalidate_tags() {
    let q = parse("INVALIDATE TAGS [user:42, org:7] FROM sessions").unwrap();
    if let QueryExpr::KvCommand(KvCommand::InvalidateTags { collection, tags }) = q {
        assert_eq!(collection, "sessions");
        assert_eq!(tags, vec!["user:42".to_string(), "org:7".to_string()]);
    } else {
        panic!("expected KvCommand::InvalidateTags");
    }
}

#[test]
fn test_parse_kv_get_bare_key() {
    let q = parse("KV GET name").unwrap();
    if let QueryExpr::KvCommand(KvCommand::Get {
        collection, key, ..
    }) = q
    {
        assert_eq!(collection, "kv_default");
        assert_eq!(key, "name");
    } else {
        panic!("expected KvCommand::Get");
    }
}

#[test]
fn test_parse_kv_get_dotted_key() {
    let q = parse("KV GET sessions.abc123").unwrap();
    if let QueryExpr::KvCommand(KvCommand::Get {
        collection, key, ..
    }) = q
    {
        assert_eq!(collection, "sessions");
        assert_eq!(key, "abc123");
    } else {
        panic!("expected KvCommand::Get");
    }
}

#[test]
fn test_parse_watch_bare_key() {
    let q = parse("WATCH feature_flag").unwrap();
    if let QueryExpr::KvCommand(KvCommand::Watch {
        collection,
        key,
        prefix,
        from_lsn,
        ..
    }) = q
    {
        assert_eq!(collection, "kv_default");
        assert_eq!(key, "feature_flag");
        assert!(!prefix);
        assert_eq!(from_lsn, None);
    } else {
        panic!("expected KvCommand::Watch");
    }
}

#[test]
fn test_parse_kv_watch_dotted_key() {
    let q = parse("KV WATCH sessions.abc123").unwrap();
    if let QueryExpr::KvCommand(KvCommand::Watch {
        collection,
        key,
        prefix,
        from_lsn,
        ..
    }) = q
    {
        assert_eq!(collection, "sessions");
        assert_eq!(key, "abc123");
        assert!(!prefix);
        assert_eq!(from_lsn, None);
    } else {
        panic!("expected KvCommand::Watch");
    }
}

#[test]
fn test_parse_kv_watch_prefix() {
    let q = parse("WATCH account.*").unwrap();
    if let QueryExpr::KvCommand(KvCommand::Watch {
        collection,
        key,
        prefix,
        from_lsn,
        ..
    }) = q
    {
        assert_eq!(collection, "kv_default");
        assert_eq!(key, "account");
        assert!(prefix);
        assert_eq!(from_lsn, None);
    } else {
        panic!("expected KvCommand::Watch");
    }
}

#[test]
fn test_parse_kv_watch_collection_prefix_from_lsn() {
    let q = parse("KV WATCH sessions.account.* FROM LSN 42").unwrap();
    if let QueryExpr::KvCommand(KvCommand::Watch {
        collection,
        key,
        prefix,
        from_lsn,
        ..
    }) = q
    {
        assert_eq!(collection, "sessions");
        assert_eq!(key, "account");
        assert!(prefix);
        assert_eq!(from_lsn, Some(42));
    } else {
        panic!("expected KvCommand::Watch");
    }
}

#[test]
fn test_parse_kv_delete_bare_key() {
    let q = parse("KV DELETE name").unwrap();
    if let QueryExpr::KvCommand(KvCommand::Delete {
        collection, key, ..
    }) = q
    {
        assert_eq!(collection, "kv_default");
        assert_eq!(key, "name");
    } else {
        panic!("expected KvCommand::Delete");
    }
}

#[test]
fn test_parse_kv_delete_dotted_key() {
    let q = parse("KV DELETE sessions.abc123").unwrap();
    if let QueryExpr::KvCommand(KvCommand::Delete {
        collection, key, ..
    }) = q
    {
        assert_eq!(collection, "sessions");
        assert_eq!(key, "abc123");
    } else {
        panic!("expected KvCommand::Delete");
    }
}

#[test]
fn test_parse_kv_put_expire_and_if_not_exists() {
    let q = parse("KV PUT slot = 'v1' EXPIRE 5 s IF NOT EXISTS").unwrap();
    assert!(matches!(
        q,
        QueryExpr::KvCommand(KvCommand::Put {
            ttl_ms: Some(5_000),
            if_not_exists: true,
            ..
        })
    ));
}

#[test]
fn test_parse_kv_unknown_verb_errors() {
    let err = parse("KV SCAN prefix").expect_err("should fail");
    assert!(err.to_string().contains("PUT") || err.to_string().contains("GET"));
}

#[test]
fn test_parse_kv_incr_bare_key_default_by() {
    let q = parse("KV INCR hits").unwrap();
    if let QueryExpr::KvCommand(KvCommand::Incr {
        collection,
        key,
        by,
        ttl_ms,
        ..
    }) = q
    {
        assert_eq!(collection, "kv_default");
        assert_eq!(key, "hits");
        assert_eq!(by, 1);
        assert_eq!(ttl_ms, None);
    } else {
        panic!("expected KvCommand::Incr");
    }
}

#[test]
fn test_parse_kv_incr_dotted_key_with_by() {
    let q = parse("KV INCR counters.page_views BY 5").unwrap();
    if let QueryExpr::KvCommand(KvCommand::Incr {
        collection,
        key,
        by,
        ..
    }) = q
    {
        assert_eq!(collection, "counters");
        assert_eq!(key, "page_views");
        assert_eq!(by, 5);
    } else {
        panic!("expected KvCommand::Incr");
    }
}

#[test]
fn test_parse_kv_incr_with_expire() {
    let q = parse("KV INCR counters.rate BY 1 EXPIRE 60 s").unwrap();
    assert!(matches!(
        q,
        QueryExpr::KvCommand(KvCommand::Incr {
            by: 1,
            ttl_ms: Some(60_000),
            ..
        })
    ));
}

#[test]
fn test_parse_kv_decr_bare_key() {
    let q = parse("KV DECR stock").unwrap();
    if let QueryExpr::KvCommand(KvCommand::Incr { by, .. }) = q {
        assert_eq!(by, -1);
    } else {
        panic!("expected KvCommand::Incr (DECR sugar)");
    }
}

#[test]
fn test_parse_kv_decr_with_by() {
    let q = parse("KV DECR inventory.item BY 3").unwrap();
    if let QueryExpr::KvCommand(KvCommand::Incr { by, .. }) = q {
        assert_eq!(by, -3);
    } else {
        panic!("expected KvCommand::Incr with by=-3");
    }
}

#[test]
fn test_parse_put_config() {
    let q = parse("PUT CONFIG app feature_flag = true").unwrap();
    if let QueryExpr::ConfigCommand(ConfigCommand::Put {
        collection,
        key,
        value,
        value_type,
        ..
    }) = q
    {
        assert_eq!(collection, "app");
        assert_eq!(key, "feature_flag");
        assert_eq!(value, Value::Boolean(true));
        assert_eq!(value_type, None);
    } else {
        panic!("expected ConfigCommand::Put");
    }
}

#[test]
fn test_parse_rotate_config() {
    let q = parse("ROTATE CONFIG app api_key = 'v2' TYPE string").unwrap();
    if let QueryExpr::ConfigCommand(ConfigCommand::Rotate {
        collection,
        key,
        value,
        value_type,
        ..
    }) = q
    {
        assert_eq!(collection, "app");
        assert_eq!(key, "api_key");
        assert_eq!(value, Value::text("v2"));
        assert_eq!(value_type, Some(ConfigValueType::String));
    } else {
        panic!("expected ConfigCommand::Rotate");
    }
}

#[test]
fn test_parse_put_config_with_schema_type() {
    let q = parse("PUT CONFIG app feature_flag = true WITH TYPE bool").unwrap();
    if let QueryExpr::ConfigCommand(ConfigCommand::Put {
        collection,
        key,
        value,
        value_type,
        ..
    }) = q
    {
        assert_eq!(collection, "app");
        assert_eq!(key, "feature_flag");
        assert_eq!(value, Value::Boolean(true));
        assert_eq!(value_type, Some(ConfigValueType::Bool));
    } else {
        panic!("expected ConfigCommand::Put");
    }
}

#[test]
fn test_parse_config_secret_ref_and_resolve() {
    let q = parse("PUT CONFIG app api_key = SECRET_REF(vault, secrets.api_key)").unwrap();
    if let QueryExpr::ConfigCommand(ConfigCommand::Put { value, .. }) = q {
        let Value::Json(bytes) = value else {
            panic!("expected secret ref to parse as structured JSON");
        };
        let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(json["type"], "secret_ref");
        assert_eq!(json["store"], "vault");
        assert_eq!(json["collection"], "secrets");
        assert_eq!(json["key"], "api_key");
    } else {
        panic!("expected ConfigCommand::Put");
    }

    assert!(matches!(
        parse("RESOLVE CONFIG app api_key").unwrap(),
        QueryExpr::ConfigCommand(ConfigCommand::Resolve { .. })
    ));
}

#[test]
fn test_parse_config_list_watch_and_tags() {
    assert!(matches!(
        parse("LIST CONFIG app PREFIX feature LIMIT 10 OFFSET 2").unwrap(),
        QueryExpr::ConfigCommand(ConfigCommand::List {
            collection,
            prefix: Some(prefix),
            limit: Some(10),
            offset: 2,
        }) if collection == "app" && prefix == "feature"
    ));
    assert!(matches!(
        parse("WATCH CONFIG app PREFIX feature FROM LSN 7").unwrap(),
        QueryExpr::ConfigCommand(ConfigCommand::Watch {
            collection,
            key,
            prefix: true,
            from_lsn: Some(7),
        }) if collection == "app" && key == "feature"
    ));
    let q = parse("PUT CONFIG app feature = 'on' TAGS [scope:prod]").unwrap();
    assert!(matches!(
        q,
        QueryExpr::ConfigCommand(ConfigCommand::Put { tags, .. })
            if tags == vec!["scope:prod".to_string()]
    ));
}

#[test]
fn test_parse_get_delete_history_config() {
    assert!(matches!(
        parse("GET CONFIG app feature_flag").unwrap(),
        QueryExpr::ConfigCommand(ConfigCommand::Get { .. })
    ));
    assert!(matches!(
        parse("DELETE CONFIG app feature_flag").unwrap(),
        QueryExpr::ConfigCommand(ConfigCommand::Delete { .. })
    ));
    assert!(matches!(
        parse("HISTORY CONFIG app feature_flag").unwrap(),
        QueryExpr::ConfigCommand(ConfigCommand::History { .. })
    ));
}

#[test]
fn test_parse_config_kv_only_operations_as_invalid_operation() {
    for sql in [
        "PUT CONFIG app ttl_key = 'v' EXPIRE 1 s",
        "ROTATE CONFIG app ttl_key = 'v2' TTL 10",
        "INCR CONFIG app counter",
        "DECR CONFIG app counter",
        "ADD CONFIG app member",
        "INVALIDATE CONFIG app feature_flag",
    ] {
        assert!(
            matches!(
                parse(sql).unwrap(),
                QueryExpr::ConfigCommand(ConfigCommand::InvalidVolatileOperation { .. })
            ),
            "{sql}"
        );
    }
}

#[test]
fn test_parse_vault_put_uses_vault_model() {
    let q = parse("VAULT PUT secrets.api_key = 'sk-test'").unwrap();
    if let QueryExpr::KvCommand(KvCommand::Put {
        model,
        collection,
        key,
        ..
    }) = q
    {
        assert_eq!(model, crate::catalog::CollectionModel::Vault);
        assert_eq!(collection, "secrets");
        assert_eq!(key, "api_key");
    } else {
        panic!("expected Vault KvCommand::Put");
    }
}

#[test]
fn test_parse_unseal_vault_command() {
    let q = parse("UNSEAL VAULT secrets.api_key").unwrap();
    if let QueryExpr::KvCommand(KvCommand::Unseal {
        collection,
        key,
        version,
    }) = q
    {
        assert_eq!(collection, "secrets");
        assert_eq!(key, "api_key");
        assert_eq!(version, None);
    } else {
        panic!("expected Vault KvCommand::Unseal");
    }
}

#[test]
fn test_parse_vault_unseal_command() {
    let q = parse("VAULT UNSEAL secrets.api_key").unwrap();
    assert!(matches!(
        q,
        QueryExpr::KvCommand(KvCommand::Unseal { collection, key, version })
            if collection == "secrets" && key == "api_key" && version.is_none()
    ));
}

#[test]
fn test_parse_vault_lifecycle_commands() {
    assert!(matches!(
        parse("ROTATE VAULT secrets.api_key = 'v2'").unwrap(),
        QueryExpr::KvCommand(KvCommand::Rotate { collection, key, .. })
            if collection == "secrets" && key == "api_key"
    ));
    assert!(matches!(
        parse("HISTORY VAULT secrets.api_key").unwrap(),
        QueryExpr::KvCommand(KvCommand::History { collection, key })
            if collection == "secrets" && key == "api_key"
    ));
    assert!(matches!(
        parse("PURGE VAULT secrets.api_key").unwrap(),
        QueryExpr::KvCommand(KvCommand::Purge { collection, key })
            if collection == "secrets" && key == "api_key"
    ));
    assert!(matches!(
        parse("UNSEAL VAULT secrets.api_key VERSION 1").unwrap(),
        QueryExpr::KvCommand(KvCommand::Unseal { collection, key, version: Some(1) })
            if collection == "secrets" && key == "api_key"
    ));
}

#[test]
fn test_parse_vault_list_and_watch() {
    assert!(matches!(
        parse("LIST VAULT secrets PREFIX api LIMIT 10 OFFSET 2").unwrap(),
        QueryExpr::KvCommand(KvCommand::List {
            model: crate::catalog::CollectionModel::Vault,
            collection,
            prefix: Some(prefix),
            limit: Some(10),
            offset: 2,
        }) if collection == "secrets" && prefix == "api"
    ));
    assert!(matches!(
        parse("WATCH VAULT secrets PREFIX api FROM LSN 7").unwrap(),
        QueryExpr::KvCommand(KvCommand::Watch {
            model: crate::catalog::CollectionModel::Vault,
            collection,
            key,
            prefix: true,
            from_lsn: Some(7),
        }) if collection == "secrets" && key == "api"
    ));
}