sagitta 0.1.3

Rust framework for building analytical data services on Arrow Flight and DataFusion.
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
//! Flight SQL command handling.

use std::collections::HashMap;
use std::pin::Pin;
use std::sync::{Arc, RwLock};

use crate::DataPath;
use crate::Store;
use arrow_array::RecordBatch;
use arrow_flight::error::FlightError;
use arrow_flight::sql::{
    ActionClosePreparedStatementRequest, ActionCreatePreparedStatementRequest,
    ActionCreatePreparedStatementResult, Any, Command, CommandPreparedStatementQuery,
    CommandPreparedStatementUpdate, CommandStatementQuery, CommandStatementUpdate, EndTransaction,
    TicketStatementQuery,
};
use arrow_ipc::writer::IpcWriteOptions;
use arrow_schema::{ArrowError, Field, Schema, SchemaRef};
use bytes::Bytes;
use datafusion::execution::SendableRecordBatchStream;
use datafusion::logical_expr::{
    CreateCatalogSchema, CreateView, DdlStatement, DmlStatement, DropCatalogSchema, DropTable,
    DropView, LogicalPlan, WriteOp,
};
use datafusion::prelude::{SessionConfig, SessionContext};
use datafusion::sql::TableReference;
use futures::Stream;
use prost::Message;
use tracing::{debug, info, warn};

use crate::catalog::StoreCatalog;

/// Result type for SQL operations.
/// Result type for SQL operations.
pub type SqlResult<T> = std::result::Result<T, SqlError>;

/// Errors that can occur during SQL operations.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum SqlError {
    /// Invalid SQL command format.
    #[error("invalid command: {0}")]
    InvalidCommand(String),

    /// Unsupported SQL command.
    #[error("unsupported command: {0}")]
    UnsupportedCommand(String),

    /// SQL syntax error.
    #[error("sql syntax error: {0}")]
    SyntaxError(String),

    /// Table not found.
    #[error("table not found: {0}")]
    TableNotFound(String),

    /// Table already exists.
    #[error("table already exists: {0}")]
    TableAlreadyExists(String),

    /// Prepared statement not found.
    #[error("prepared statement not found: {0}")]
    PreparedStatementNotFound(String),

    /// Transaction not found.
    #[error("transaction not found: {0}")]
    TransactionNotFound(String),

    /// Savepoint not found.
    #[error("savepoint not found: {0}")]
    SavepointNotFound(String),

    /// Invalid transaction action.
    #[error("invalid transaction action: {0}")]
    InvalidTransactionAction(String),

    /// Internal error.
    #[error("internal error: {0}")]
    Internal(String),

    /// Arrow error.
    #[error("arrow error: {0}")]
    Arrow(#[from] ArrowError),

    /// Query execution error.
    #[error("query execution error: {0}")]
    QueryExecution(String),
}

impl From<SqlError> for tonic::Status {
    fn from(err: SqlError) -> Self {
        match err {
            SqlError::InvalidCommand(msg) => tonic::Status::invalid_argument(msg),
            SqlError::UnsupportedCommand(msg) => tonic::Status::unimplemented(msg),
            SqlError::SyntaxError(msg) => tonic::Status::invalid_argument(msg),
            SqlError::TableNotFound(msg) => tonic::Status::not_found(msg),
            SqlError::TableAlreadyExists(msg) => tonic::Status::already_exists(msg),
            SqlError::PreparedStatementNotFound(msg) => tonic::Status::not_found(msg),
            SqlError::TransactionNotFound(msg) => tonic::Status::not_found(msg),
            SqlError::SavepointNotFound(msg) => tonic::Status::not_found(msg),
            SqlError::InvalidTransactionAction(msg) => tonic::Status::invalid_argument(msg),
            SqlError::Internal(msg) => tonic::Status::internal(msg),
            SqlError::Arrow(e) => tonic::Status::internal(e.to_string()),
            SqlError::QueryExecution(msg) => tonic::Status::internal(msg),
        }
    }
}

/// Result of executing a SQL query via `CommandStatementQuery`.
#[derive(Debug)]
pub struct QueryResult {
    /// Opaque handle for retrieving data via `DoGet`.
    pub handle: Bytes,
    /// Result schema.
    pub schema: SchemaRef,
    /// Total records (-1 if unknown).
    pub total_records: i64,
}

/// Result of executing a SQL update (INSERT, UPDATE, DELETE).
#[derive(Debug)]
pub struct UpdateResult {
    /// Number of records affected.
    pub record_count: i64,
}

/// A streaming source of query data.
///
/// This wraps DataFusion's `SendableRecordBatchStream` to provide streaming
/// access to query results without loading all data into memory.
pub struct QueryDataStream {
    inner: SendableRecordBatchStream,
}

impl QueryDataStream {
    /// Create a new streaming data source.
    pub fn new(stream: SendableRecordBatchStream) -> Self {
        Self { inner: stream }
    }
}

impl Stream for QueryDataStream {
    type Item = Result<RecordBatch, FlightError>;

    fn poll_next(
        mut self: Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Option<Self::Item>> {
        use std::task::Poll;

        match Pin::new(&mut self.inner).poll_next(cx) {
            Poll::Ready(Some(Ok(batch))) => Poll::Ready(Some(Ok(batch))),
            Poll::Ready(Some(Err(e))) => {
                // Convert DataFusionError to FlightError
                Poll::Ready(Some(Err(FlightError::ExternalError(Box::new(e)))))
            }
            Poll::Ready(None) => Poll::Ready(None),
            Poll::Pending => Poll::Pending,
        }
    }
}

/// Result of creating a prepared statement via `CreatePreparedStatement`.
#[derive(Debug)]
pub struct CreatePreparedStatementResult {
    /// Opaque handle identifying the statement.
    pub handle: Bytes,
    /// Schema of the result dataset (for queries).
    pub dataset_schema: Option<SchemaRef>,
    /// Schema of the parameters.
    pub parameter_schema: Option<SchemaRef>,
}

/// Stored prepared statement.
#[derive(Debug, Clone)]
struct PreparedStatement {
    /// Original SQL query.
    query: String,
    /// Whether this is a query (SELECT) or update (INSERT/UPDATE/DELETE).
    is_query: bool,
    /// Result schema for queries.
    #[allow(dead_code)]
    dataset_schema: Option<SchemaRef>,
    /// Parameter schema (returned to clients, not validated internally yet).
    #[allow(dead_code)]
    parameter_schema: Option<SchemaRef>,
    /// Bound parameter values.
    bound_parameters: Option<Vec<Arc<RecordBatch>>>,
}

/// A pending operation within a transaction.
#[derive(Debug, Clone)]
enum PendingOperation {
    /// INSERT operation.
    Insert {
        path: DataPath,
        query: String,
        record_count: i64,
    },
    /// UPDATE operation.
    Update {
        path: DataPath,
        query: String,
        record_count: i64,
    },
    /// DELETE operation.
    Delete {
        path: DataPath,
        query: String,
        record_count: i64,
    },
}

impl PendingOperation {
    fn record_count(&self) -> i64 {
        match self {
            PendingOperation::Insert { record_count, .. } => *record_count,
            PendingOperation::Update { record_count, .. } => *record_count,
            PendingOperation::Delete { record_count, .. } => *record_count,
        }
    }
}

/// Transaction isolation level.
///
/// Defines the degree of isolation between concurrent transactions.
/// Flight SQL supports this via SqlInfo metadata.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum IsolationLevel {
    /// Transactions can read uncommitted data from other transactions.
    ReadUncommitted,
    /// Transactions only read committed data (default).
    #[default]
    ReadCommitted,
    /// Prevents non-repeatable reads within a transaction.
    RepeatableRead,
    /// Full isolation - transactions appear to execute serially.
    Serializable,
}

impl std::fmt::Display for IsolationLevel {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            IsolationLevel::ReadUncommitted => write!(f, "READ UNCOMMITTED"),
            IsolationLevel::ReadCommitted => write!(f, "READ COMMITTED"),
            IsolationLevel::RepeatableRead => write!(f, "REPEATABLE READ"),
            IsolationLevel::Serializable => write!(f, "SERIALIZABLE"),
        }
    }
}

/// Savepoint action for end_savepoint.
///
/// Matches Flight SQL ActionEndSavepointRequest action values.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EndSavepoint {
    /// Unspecified action (invalid).
    Unspecified = 0,
    /// Release the savepoint (commit changes since savepoint).
    Release = 1,
    /// Rollback to the savepoint (discard changes since savepoint).
    Rollback = 2,
}

impl TryFrom<i32> for EndSavepoint {
    type Error = SqlError;

    fn try_from(value: i32) -> Result<Self, Self::Error> {
        match value {
            0 => Ok(EndSavepoint::Unspecified),
            1 => Ok(EndSavepoint::Release),
            2 => Ok(EndSavepoint::Rollback),
            _ => Err(SqlError::InvalidTransactionAction(format!(
                "invalid EndSavepoint value: {value}"
            ))),
        }
    }
}

/// A savepoint within a transaction.
///
/// Savepoints allow partial rollback of a transaction.
#[derive(Debug, Clone)]
struct Savepoint {
    /// User-provided name for the savepoint.
    name: String,
    /// Index into pending_operations where this savepoint was created.
    operation_index: usize,
}

/// Stored transaction.
#[derive(Debug, Clone)]
struct Transaction {
    /// Whether the transaction is still active.
    active: bool,
    /// Transaction isolation level.
    ///
    /// Currently stored for future per-transaction isolation behavior.
    #[allow(dead_code)]
    isolation_level: IsolationLevel,
    /// Pending operations to be committed or rolled back.
    pending_operations: Vec<PendingOperation>,
    /// Named savepoints within this transaction.
    savepoints: HashMap<Bytes, Savepoint>,
}

/// SQL query engine backed by DataFusion.
///
/// Manages query execution, prepared statements, and transactions
/// against tables registered from a [`Store`].
pub struct SqlEngine {
    store: Arc<dyn Store>,
    catalog_name: String,
    default_schema: String,
    ctx: RwLock<SessionContext>,
    prepared_statements: RwLock<HashMap<Bytes, PreparedStatement>>,
    transactions: RwLock<HashMap<Bytes, Transaction>>,
    next_handle_id: RwLock<u64>,
}

impl SqlEngine {
    /// Create a new SQL engine.
    pub async fn new(store: Arc<dyn Store>, catalog_name: &str, default_schema: &str) -> Self {
        let ctx = Self::build_session_context(&store, catalog_name, default_schema).await;
        Self {
            store,
            catalog_name: catalog_name.to_string(),
            default_schema: default_schema.to_string(),
            ctx: RwLock::new(ctx),
            prepared_statements: RwLock::new(HashMap::new()),
            transactions: RwLock::new(HashMap::new()),
            next_handle_id: RwLock::new(1),
        }
    }

    /// Create a new SessionContext with our catalog configured as the default.
    async fn build_session_context(
        store: &Arc<dyn Store>,
        catalog_name: &str,
        default_schema: &str,
    ) -> SessionContext {
        let config = SessionConfig::new()
            .with_default_catalog_and_schema(catalog_name, default_schema)
            .with_information_schema(true);
        let ctx = SessionContext::new_with_config(config);

        // Register our catalog
        let catalog = StoreCatalog::new(store.clone(), catalog_name, default_schema).await;
        ctx.register_catalog(catalog_name, Arc::new(catalog));

        debug!(
            "created SessionContext with default catalog '{catalog_name}' and schema '{default_schema}'"
        );
        ctx
    }

    /// Refresh the SessionContext with current tables from the store.
    ///
    /// Call this after tables are added or removed via DoPut/DoAction.
    pub async fn refresh_tables(&self) {
        let ctx =
            Self::build_session_context(&self.store, &self.catalog_name, &self.default_schema)
                .await;
        *self.ctx.write().unwrap() = ctx;
        debug!("refreshed DataFusion tables from store");
    }

    /// Convert a DataPath to a DataFusion table name.
    ///
    /// Returns the qualified name: `schema.table` or just `table` for default schema.
    #[allow(dead_code)]
    fn path_to_table_name(&self, path: &DataPath) -> String {
        let (_, schema, table) = StoreCatalog::path_to_catalog_schema_table(
            path,
            &self.catalog_name,
            &self.default_schema,
        );
        if schema == self.default_schema {
            table
        } else {
            format!("{schema}.{table}")
        }
    }

    /// Convert a table name back to a DataPath.
    ///
    /// Handles both underscore-separated and dot-separated names.
    #[allow(dead_code)]
    fn table_name_to_path(name: &str) -> DataPath {
        // First try dot-separated (SQL standard)
        if name.contains('.') {
            let segments: Vec<String> = name
                .split('.')
                .map(|s| s.trim_matches('"').to_string())
                .collect();
            return DataPath::new(segments);
        }
        // Fall back to underscore-separated
        let segments: Vec<String> = name.split('_').map(|s| s.to_string()).collect();
        DataPath::new(segments)
    }

    /// Parse a CMD descriptor into a Flight SQL command.
    pub fn parse_command(cmd: &Bytes) -> SqlResult<Command> {
        let any = Any::decode(cmd.as_ref())
            .map_err(|e| SqlError::InvalidCommand(format!("failed to decode Any: {e}")))?;

        Command::try_from(any)
            .map_err(|e| SqlError::InvalidCommand(format!("failed to parse command: {e}")))
    }

    /// Execute a statement query command.
    ///
    /// Returns query metadata for GetFlightInfo.
    /// Uses DataFusion to parse and validate the query.
    pub async fn execute_statement_query(
        &self,
        cmd: &CommandStatementQuery,
    ) -> SqlResult<QueryResult> {
        let query = &cmd.query;
        debug!(query = %query, "executing statement query");

        // Use DataFusion to validate the query and get the logical plan
        let ctx = self.ctx.read().unwrap().clone();
        let df = ctx
            .sql(query)
            .await
            .map_err(|e| SqlError::QueryExecution(e.to_string()))?;

        let schema = df.schema().inner().clone();

        // Create a handle that encodes the query
        let handle = self.create_query_handle(query);

        // Total records is unknown until execution (-1 per Flight SQL spec)
        info!(
            query = %query,
            "query validated with DataFusion"
        );

        Ok(QueryResult {
            handle,
            schema,
            total_records: -1,
        })
    }

    /// Get data for a statement query ticket.
    ///
    /// Executes the query using DataFusion and returns results.
    pub async fn get_statement_query_data(
        &self,
        ticket: &TicketStatementQuery,
    ) -> SqlResult<(SchemaRef, Vec<Arc<RecordBatch>>)> {
        let handle = &ticket.statement_handle;
        let query = String::from_utf8(handle.to_vec())
            .map_err(|_| SqlError::InvalidCommand("invalid query handle".to_string()))?;

        debug!(query = %query, "executing statement query data via DataFusion");

        // Execute the query using DataFusion
        let ctx = self.ctx.read().unwrap().clone();
        let df = ctx
            .sql(&query)
            .await
            .map_err(|e| SqlError::QueryExecution(e.to_string()))?;

        let schema = df.schema().inner().clone();
        let batches = df
            .collect()
            .await
            .map_err(|e| SqlError::QueryExecution(e.to_string()))?;

        // Convert to Arc<RecordBatch>
        let batches: Vec<Arc<RecordBatch>> = batches.into_iter().map(Arc::new).collect();

        let total_rows: usize = batches.iter().map(|b| b.num_rows()).sum();
        info!(
            query = %query,
            total_rows,
            batch_count = batches.len(),
            "query executed via DataFusion"
        );

        Ok((schema, batches))
    }

    /// Get a streaming data source for a statement query ticket.
    ///
    /// Executes the query using DataFusion and returns a stream of record batches.
    /// This avoids loading all data into memory at once for large result sets.
    pub async fn get_statement_query_data_stream(
        &self,
        ticket: &TicketStatementQuery,
    ) -> SqlResult<(SchemaRef, QueryDataStream)> {
        let handle = &ticket.statement_handle;
        let query = String::from_utf8(handle.to_vec())
            .map_err(|_| SqlError::InvalidCommand("invalid query handle".to_string()))?;

        debug!(query = %query, "executing statement query data stream via DataFusion");

        // Execute the query using DataFusion
        let ctx = self.ctx.read().unwrap().clone();
        let df = ctx
            .sql(&query)
            .await
            .map_err(|e| SqlError::QueryExecution(e.to_string()))?;

        let schema = df.schema().inner().clone();

        // Get a streaming result instead of collecting all batches
        let stream = df
            .execute_stream()
            .await
            .map_err(|e| SqlError::QueryExecution(e.to_string()))?;

        info!(
            query = %query,
            "query streaming started via DataFusion"
        );

        Ok((schema, QueryDataStream::new(stream)))
    }

    /// Execute a statement update command.
    ///
    /// Returns the number of affected records.
    /// If a transaction_id is provided, the operation is buffered until commit.
    pub async fn execute_statement_update(
        &self,
        cmd: &CommandStatementUpdate,
    ) -> SqlResult<UpdateResult> {
        let query = &cmd.query;
        debug!(query = %query, transaction_id = ?cmd.transaction_id, "executing statement update");

        let (path, record_count) = self.parse_and_execute_update_async(query).await?;

        // If within a transaction, buffer the operation
        if let Some(ref txn_id) = cmd.transaction_id {
            self.add_pending_operation(txn_id, query, &path, record_count)?;
            info!(
                query = %query,
                path = %path.display(),
                record_count,
                transaction_id = %String::from_utf8_lossy(txn_id),
                "update buffered in transaction"
            );
        } else {
            info!(
                query = %query,
                path = %path.display(),
                record_count,
                "update executed (auto-commit)"
            );
        }

        Ok(UpdateResult { record_count })
    }

    /// Add a pending operation to a transaction.
    fn add_pending_operation(
        &self,
        transaction_id: &Bytes,
        query: &str,
        path: &DataPath,
        record_count: i64,
    ) -> SqlResult<()> {
        let mut transactions = self.transactions.write().unwrap();
        let transaction = transactions.get_mut(transaction_id).ok_or_else(|| {
            SqlError::TransactionNotFound(String::from_utf8_lossy(transaction_id).to_string())
        })?;

        if !transaction.active {
            return Err(SqlError::InvalidTransactionAction(
                "transaction is not active".to_string(),
            ));
        }

        let query_lower = query.trim().to_lowercase();
        let operation = if query_lower.starts_with("insert") {
            PendingOperation::Insert {
                path: path.clone(),
                query: query.to_string(),
                record_count,
            }
        } else if query_lower.starts_with("update") {
            PendingOperation::Update {
                path: path.clone(),
                query: query.to_string(),
                record_count,
            }
        } else {
            PendingOperation::Delete {
                path: path.clone(),
                query: query.to_string(),
                record_count,
            }
        };

        transaction.pending_operations.push(operation);
        Ok(())
    }

    /// Parse and execute an update statement using DataFusion for parsing.
    ///
    /// Uses DataFusion to parse SQL and resolve qualified table names,
    /// then executes the DML operation.
    async fn parse_and_execute_update_async(&self, query: &str) -> SqlResult<(DataPath, i64)> {
        let query_upper = query.trim().to_uppercase();

        // Handle TRUNCATE TABLE (not supported by DataFusion)
        if query_upper.starts_with("TRUNCATE") {
            return self.execute_truncate(query).await;
        }

        // Handle ALTER TABLE (not supported by DataFusion)
        if query_upper.starts_with("ALTER") {
            return self.execute_alter_table(query).await;
        }

        // Handle MERGE / UPSERT (not supported by DataFusion)
        if query_upper.starts_with("MERGE") {
            return self.execute_merge(query).await;
        }

        // Handle INSERT...ON CONFLICT (not supported by DataFusion)
        if query_upper.starts_with("INSERT") && query_upper.contains("ON CONFLICT") {
            return self.execute_upsert(query).await;
        }

        let ctx = self.ctx.read().unwrap().clone();

        // Use DataFusion to create a logical plan - this handles qualified name resolution
        let plan = ctx.state().create_logical_plan(query).await.map_err(|e| {
            let msg = e.to_string();
            // Check if this is a table not found error
            if msg.contains("not found") && msg.contains("table") {
                // Extract table name from message like "table 'catalog.schema.table' not found"
                if let Some(start) = msg.find('\'')
                    && let Some(end) = msg[start + 1..].find('\'')
                {
                    let table_name = &msg[start + 1..start + 1 + end];
                    return SqlError::TableNotFound(table_name.to_string());
                }
                SqlError::TableNotFound(msg)
            } else {
                SqlError::SyntaxError(msg)
            }
        })?;

        // Extract table reference and operation from the plan
        match &plan {
            LogicalPlan::Dml(DmlStatement {
                table_name,
                op,
                input,
                ..
            }) => {
                let path = self.table_reference_to_path(table_name)?;

                match op {
                    WriteOp::Insert(_insert_op) => {
                        // For INSERT...SELECT, execute the input plan to get the data
                        let df = ctx
                            .execute_logical_plan(input.as_ref().clone())
                            .await
                            .map_err(|e| SqlError::QueryExecution(e.to_string()))?;

                        let batches = df
                            .collect()
                            .await
                            .map_err(|e| SqlError::QueryExecution(e.to_string()))?;

                        let record_count: i64 = batches.iter().map(|b| b.num_rows() as i64).sum();

                        // Actually insert the batches into the store
                        if record_count > 0 {
                            self.store
                                .append_batches(&path, batches)
                                .await
                                .map_err(|e| SqlError::Internal(e.to_string()))?;

                            // Refresh the catalog to reflect the new data
                            self.refresh_catalog().await;
                        }

                        info!(
                            path = %path.display(),
                            record_count,
                            "INSERT executed via DataFusion"
                        );

                        Ok((path, record_count))
                    }
                    WriteOp::Ctas => {
                        // CREATE TABLE AS SELECT - execute the input and create a new table
                        let df = ctx
                            .execute_logical_plan(input.as_ref().clone())
                            .await
                            .map_err(|e| SqlError::QueryExecution(e.to_string()))?;

                        let batches = df
                            .collect()
                            .await
                            .map_err(|e| SqlError::QueryExecution(e.to_string()))?;

                        let record_count: i64 = batches.iter().map(|b| b.num_rows() as i64).sum();

                        info!(
                            path = %path.display(),
                            record_count,
                            "CTAS executed via DataFusion"
                        );

                        Ok((path, record_count))
                    }
                    WriteOp::Update => {
                        let info = self
                            .store
                            .get(&path)
                            .await
                            .map_err(|_| SqlError::TableNotFound(path.display()))?;
                        let schema = self
                            .store
                            .get_schema(&path)
                            .await
                            .map_err(|_| SqlError::TableNotFound(path.display()))?;

                        let has_filter = self.plan_has_filter(input);

                        // Execute the DML input plan to get modified rows
                        // (for UPDATE the input contains the SET-transformed rows
                        // that matched the WHERE clause)
                        let modified_df = ctx
                            .execute_logical_plan(input.as_ref().clone())
                            .await
                            .map_err(|e| SqlError::QueryExecution(e.to_string()))?;
                        let modified_batches = modified_df
                            .collect()
                            .await
                            .map_err(|e| SqlError::QueryExecution(e.to_string()))?;
                        let affected_count: i64 =
                            modified_batches.iter().map(|b| b.num_rows() as i64).sum();

                        if !has_filter {
                            // UPDATE without WHERE: all rows replaced by modified data
                            self.store
                                .put(path.clone(), schema, modified_batches)
                                .await
                                .map_err(|e| SqlError::Internal(e.to_string()))?;
                        } else {
                            // UPDATE with WHERE: combine unmodified + modified rows
                            let where_clause = self.extract_top_level_where(query);
                            let qualified = self.qualified_table_sql(&path);

                            let surviving_batches = match where_clause {
                                Some(condition) => {
                                    let surviving_query = format!(
                                        "SELECT * FROM {qualified} WHERE NOT ({condition})"
                                    );
                                    let sdf = ctx
                                        .sql(&surviving_query)
                                        .await
                                        .map_err(|e| SqlError::QueryExecution(e.to_string()))?;
                                    sdf.collect()
                                        .await
                                        .map_err(|e| SqlError::QueryExecution(e.to_string()))?
                                }
                                None => vec![],
                            };

                            let mut all_batches = surviving_batches;
                            all_batches.extend(modified_batches);

                            self.store
                                .put(path.clone(), schema, all_batches)
                                .await
                                .map_err(|e| SqlError::Internal(e.to_string()))?;
                        }

                        self.refresh_catalog().await;

                        let record_count = if has_filter {
                            affected_count
                        } else {
                            info.total_records as i64
                        };

                        info!(
                            path = %path.display(),
                            record_count,
                            "UPDATE executed via DataFusion"
                        );

                        Ok((path, record_count))
                    }
                    WriteOp::Delete => {
                        let info = self
                            .store
                            .get(&path)
                            .await
                            .map_err(|_| SqlError::TableNotFound(path.display()))?;
                        let schema = self
                            .store
                            .get_schema(&path)
                            .await
                            .map_err(|_| SqlError::TableNotFound(path.display()))?;
                        let old_count = info.total_records as i64;

                        let has_filter = self.plan_has_filter(input);

                        if !has_filter {
                            // DELETE without WHERE: remove all rows
                            self.store
                                .truncate(&path)
                                .await
                                .map_err(|e| SqlError::Internal(e.to_string()))?;
                            self.refresh_catalog().await;

                            info!(
                                path = %path.display(),
                                record_count = old_count,
                                "DELETE (all rows) executed via DataFusion"
                            );

                            return Ok((path, old_count));
                        }

                        // DELETE with WHERE: keep only non-matching rows
                        let where_clause =
                            self.extract_top_level_where(query).ok_or_else(|| {
                                SqlError::Internal(
                                    "could not extract WHERE clause from DELETE".to_string(),
                                )
                            })?;
                        let qualified = self.qualified_table_sql(&path);

                        let surviving_query =
                            format!("SELECT * FROM {qualified} WHERE NOT ({where_clause})");
                        let sdf = ctx
                            .sql(&surviving_query)
                            .await
                            .map_err(|e| SqlError::QueryExecution(e.to_string()))?;
                        let surviving_batches = sdf
                            .collect()
                            .await
                            .map_err(|e| SqlError::QueryExecution(e.to_string()))?;
                        let new_count: i64 =
                            surviving_batches.iter().map(|b| b.num_rows() as i64).sum();
                        let deleted_count = old_count - new_count;

                        self.store
                            .put(path.clone(), schema, surviving_batches)
                            .await
                            .map_err(|e| SqlError::Internal(e.to_string()))?;
                        self.refresh_catalog().await;

                        info!(
                            path = %path.display(),
                            record_count = deleted_count,
                            "DELETE executed via DataFusion"
                        );

                        Ok((path, deleted_count))
                    }
                }
            }
            LogicalPlan::Ddl(ddl) => self.execute_ddl(ddl).await,
            _ => {
                // Fall back to manual parsing for non-DML statements
                self.parse_and_execute_update(query).await
            }
        }
    }

    /// Execute a DDL statement (CREATE TABLE, DROP TABLE, etc.).
    async fn execute_ddl(&self, ddl: &DdlStatement) -> SqlResult<(DataPath, i64)> {
        match ddl {
            DdlStatement::CreateMemoryTable(create) => {
                let path = self.table_reference_to_path(&create.name)?;

                // Check if table already exists
                if self.store.contains(&path).await {
                    if create.if_not_exists {
                        info!(
                            path = %path.display(),
                            "CREATE TABLE IF NOT EXISTS: table already exists, skipping"
                        );
                        return Ok((path, 0));
                    }
                    if !create.or_replace {
                        return Err(SqlError::TableAlreadyExists(path.display()));
                    }
                    // Remove existing table for OR REPLACE
                    self.store
                        .remove(&path)
                        .await
                        .map_err(|e| SqlError::Internal(e.to_string()))?;
                }

                // Get schema from the input plan
                let schema = create.input.schema();
                let arrow_schema: SchemaRef = schema.inner().clone();

                // Execute the input plan to get initial data (for CREATE TABLE AS SELECT)
                let ctx = self.ctx.read().unwrap().clone();
                let df = ctx
                    .execute_logical_plan(create.input.as_ref().clone())
                    .await
                    .map_err(|e| SqlError::QueryExecution(e.to_string()))?;

                let batches = df
                    .collect()
                    .await
                    .map_err(|e| SqlError::QueryExecution(e.to_string()))?;

                let record_count: i64 = batches.iter().map(|b| b.num_rows() as i64).sum();

                // Store the table
                self.store
                    .put(path.clone(), arrow_schema, batches)
                    .await
                    .map_err(|e| SqlError::Internal(e.to_string()))?;

                // Refresh the catalog to include the new table
                self.refresh_catalog().await;

                info!(
                    path = %path.display(),
                    record_count,
                    "CREATE TABLE executed"
                );

                Ok((path, record_count))
            }
            DdlStatement::DropTable(DropTable {
                name, if_exists, ..
            }) => {
                let path = self.table_reference_to_path(name)?;

                if !self.store.contains(&path).await {
                    if *if_exists {
                        info!(
                            path = %path.display(),
                            "DROP TABLE IF EXISTS: table does not exist, skipping"
                        );
                        return Ok((path, 0));
                    }
                    return Err(SqlError::TableNotFound(path.display()));
                }

                // Remove the table
                self.store
                    .remove(&path)
                    .await
                    .map_err(|e| SqlError::Internal(e.to_string()))?;

                // Refresh the catalog
                self.refresh_catalog().await;

                info!(path = %path.display(), "DROP TABLE executed");

                Ok((path, 0))
            }
            DdlStatement::CreateView(CreateView {
                name,
                input,
                or_replace,
                ..
            }) => {
                let view_name = name.to_string();

                // Register the view with DataFusion
                let ctx = self.ctx.read().unwrap().clone();

                // Check if view already exists
                if ctx.table_exist(name.clone()).unwrap_or(false) && !*or_replace {
                    return Err(SqlError::TableAlreadyExists(view_name.clone()));
                }

                // Create the view as a logical plan
                let df = ctx
                    .execute_logical_plan(input.as_ref().clone())
                    .await
                    .map_err(|e| SqlError::QueryExecution(e.to_string()))?;

                // Register the view
                ctx.register_table(name.clone(), df.into_view())
                    .map_err(|e| SqlError::Internal(e.to_string()))?;

                info!(view_name = %view_name, "CREATE VIEW executed");

                Ok((DataPath::new(vec![view_name]), 0))
            }
            DdlStatement::DropView(DropView {
                name, if_exists, ..
            }) => {
                let view_name = name.to_string();
                let ctx = self.ctx.read().unwrap().clone();

                // Check if view exists
                if !ctx.table_exist(name.clone()).unwrap_or(false) {
                    if *if_exists {
                        info!(
                            view_name = %view_name,
                            "DROP VIEW IF EXISTS: view does not exist, skipping"
                        );
                        return Ok((DataPath::new(vec![view_name]), 0));
                    }
                    return Err(SqlError::TableNotFound(view_name.clone()));
                }

                // Deregister the view
                ctx.deregister_table(name.clone())
                    .map_err(|e| SqlError::Internal(e.to_string()))?;

                info!(view_name = %view_name, "DROP VIEW executed");

                Ok((DataPath::new(vec![view_name]), 0))
            }
            DdlStatement::CreateCatalogSchema(CreateCatalogSchema {
                schema_name,
                if_not_exists,
                ..
            }) => {
                let schema_name_str = schema_name.to_string();

                if self.store.schema_exists(&schema_name_str).await {
                    if *if_not_exists {
                        info!(
                            schema_name = %schema_name_str,
                            "CREATE SCHEMA IF NOT EXISTS: schema already exists, skipping"
                        );
                        return Ok((DataPath::new(vec![schema_name_str]), 0));
                    }
                    return Err(SqlError::TableAlreadyExists(format!(
                        "schema '{schema_name_str}' already exists"
                    )));
                }

                self.store
                    .create_schema(&schema_name_str)
                    .await
                    .map_err(|e| SqlError::Internal(e.to_string()))?;
                self.refresh_catalog().await;

                info!(
                    schema_name = %schema_name_str,
                    "CREATE SCHEMA executed"
                );

                Ok((DataPath::new(vec![schema_name_str]), 0))
            }
            DdlStatement::DropCatalogSchema(DropCatalogSchema {
                name, if_exists, ..
            }) => {
                let schema_name_str = name.to_string();

                let existed = self
                    .store
                    .drop_schema(&schema_name_str)
                    .await
                    .map_err(|e| SqlError::Internal(e.to_string()))?;

                if !existed && !*if_exists {
                    return Err(SqlError::TableNotFound(format!(
                        "schema '{schema_name_str}' does not exist"
                    )));
                }

                self.refresh_catalog().await;

                info!(
                    schema_name = %schema_name_str,
                    "DROP SCHEMA executed"
                );

                Ok((DataPath::new(vec![schema_name_str]), 0))
            }
            other => Err(SqlError::UnsupportedCommand(format!(
                "DDL statement not yet supported: {}",
                other.name()
            ))),
        }
    }

    /// Refresh the DataFusion catalog to reflect current Store state.
    async fn refresh_catalog(&self) {
        let catalog =
            StoreCatalog::new(self.store.clone(), &self.catalog_name, &self.default_schema).await;
        let ctx = self.ctx.read().unwrap();
        ctx.register_catalog(&self.catalog_name, Arc::new(catalog));
    }

    /// Convert a DataFusion TableReference to a DataPath.
    fn table_reference_to_path(&self, table_ref: &TableReference) -> SqlResult<DataPath> {
        let segments = match table_ref {
            TableReference::Bare { table } => vec![table.to_string()],
            TableReference::Partial { schema, table } => {
                vec![schema.to_string(), table.to_string()]
            }
            TableReference::Full {
                catalog,
                schema,
                table,
            } => vec![catalog.to_string(), schema.to_string(), table.to_string()],
        };

        Ok(DataPath::new(segments))
    }

    /// Build a SQL-safe qualified table name from a DataPath.
    fn qualified_table_sql(&self, path: &DataPath) -> String {
        let (_, schema, table) = StoreCatalog::path_to_catalog_schema_table(
            path,
            &self.catalog_name,
            &self.default_schema,
        );
        if schema == self.default_schema {
            format!("\"{}\".\"{}\"", self.default_schema, table)
        } else {
            format!("\"{}\".\"{}\"", schema, table)
        }
    }

    /// Extract the top-level WHERE clause from a SQL statement.
    ///
    /// Skips WHERE keywords inside parenthesised subqueries.
    fn extract_top_level_where<'a>(&self, query: &'a str) -> Option<&'a str> {
        let lower = query.to_lowercase();
        let bytes = query.as_bytes();
        let lower_bytes = lower.as_bytes();
        let pattern = b" where ";
        let mut depth: i32 = 0;
        let mut last_match: Option<usize> = None;

        let mut i = 0;
        while i < bytes.len() {
            match bytes[i] {
                b'(' => depth += 1,
                b')' => depth = (depth - 1).max(0),
                b'\'' => {
                    // Skip string literals
                    i += 1;
                    while i < bytes.len() {
                        if bytes[i] == b'\'' {
                            break;
                        }
                        i += 1;
                    }
                }
                _ => {}
            }

            if depth == 0
                && i + pattern.len() <= lower_bytes.len()
                && &lower_bytes[i..i + pattern.len()] == pattern
            {
                last_match = Some(i + pattern.len());
            }

            i += 1;
        }

        last_match.map(|pos| query[pos..].trim())
    }

    /// Check if a logical plan contains a filter (WHERE clause).
    fn plan_has_filter(&self, plan: &LogicalPlan) -> bool {
        match plan {
            LogicalPlan::Filter { .. } => true,
            LogicalPlan::Projection(proj) => self.plan_has_filter(proj.input.as_ref()),
            LogicalPlan::SubqueryAlias(alias) => self.plan_has_filter(alias.input.as_ref()),
            _ => false,
        }
    }

    /// Parse and execute an update statement (INSERT, UPDATE, DELETE).
    ///
    /// Returns the table path and affected row count.
    /// This is the synchronous fallback for when DataFusion parsing fails.
    async fn parse_and_execute_update(&self, query: &str) -> SqlResult<(DataPath, i64)> {
        let query_lower = query.trim().to_lowercase();

        if query_lower.starts_with("insert") {
            self.execute_insert(query).await
        } else if query_lower.starts_with("update") {
            self.execute_update(query).await
        } else if query_lower.starts_with("delete") {
            self.execute_delete(query).await
        } else {
            Err(SqlError::SyntaxError(
                "only INSERT, UPDATE, DELETE statements are supported".to_string(),
            ))
        }
    }

    /// Execute an INSERT statement.
    ///
    /// Format: INSERT INTO table_name (cols) VALUES (vals), ...
    /// For now, counts the number of value tuples as affected rows.
    async fn execute_insert(&self, query: &str) -> SqlResult<(DataPath, i64)> {
        let query_lower = query.trim().to_lowercase();

        // Find "into" keyword
        let into_pos = query_lower
            .find(" into ")
            .ok_or_else(|| SqlError::SyntaxError("missing INTO clause".to_string()))?;

        let after_into = &query_lower[into_pos + 6..];
        let table_name = after_into
            .split(|c: char| c.is_whitespace() || c == '(')
            .next()
            .ok_or_else(|| SqlError::SyntaxError("missing table name".to_string()))?;

        let path = self.parse_table_name(table_name)?;

        // Verify table exists
        self.store
            .get_schema(&path)
            .await
            .map_err(|_| SqlError::TableNotFound(path.display()))?;

        // Count value tuples by counting "VALUES" occurrences or parentheses pairs
        // Simple heuristic: count opening parens after VALUES
        let values_pos = query_lower.find(" values ");
        let record_count = match values_pos {
            Some(pos) => {
                let after_values = &query_lower[pos + 8..];
                // Count opening parens that start a value tuple
                after_values.matches('(').count() as i64
            }
            None => 1, // Default to 1 for VALUES-less insert
        };

        Ok((path, record_count))
    }

    /// Execute an UPDATE statement.
    ///
    /// Format: UPDATE table_name SET col=val WHERE condition
    /// Returns count of records that would be affected.
    async fn execute_update(&self, query: &str) -> SqlResult<(DataPath, i64)> {
        let query_lower = query.trim().to_lowercase();

        // Find table name after UPDATE
        let after_update = query_lower
            .strip_prefix("update")
            .ok_or_else(|| SqlError::SyntaxError("invalid UPDATE syntax".to_string()))?
            .trim_start();

        let table_name = after_update
            .split(|c: char| c.is_whitespace())
            .next()
            .ok_or_else(|| SqlError::SyntaxError("missing table name".to_string()))?;

        let path = self.parse_table_name(table_name)?;

        // Get current record count - UPDATE affects existing records
        let info = self
            .store
            .get(&path)
            .await
            .map_err(|_| SqlError::TableNotFound(path.display()))?;

        // If WHERE clause exists, assume partial update (return half for simulation)
        // Otherwise assume all records affected
        let record_count = if query_lower.contains(" where ") {
            // Simulate partial update - return at least 1 if table has records
            (info.total_records as i64).max(1) / 2
        } else {
            info.total_records as i64
        };

        Ok((path, record_count.max(0)))
    }

    /// Execute a DELETE statement.
    ///
    /// Format: DELETE FROM table_name WHERE condition
    /// Returns count of records that would be deleted.
    async fn execute_delete(&self, query: &str) -> SqlResult<(DataPath, i64)> {
        let query_lower = query.trim().to_lowercase();

        // Find "from" keyword
        let from_pos = query_lower
            .find(" from ")
            .ok_or_else(|| SqlError::SyntaxError("missing FROM clause".to_string()))?;

        let after_from = &query_lower[from_pos + 6..];
        let table_name = after_from
            .split_whitespace()
            .next()
            .ok_or_else(|| SqlError::SyntaxError("missing table name".to_string()))?;

        let path = self.parse_table_name(table_name)?;

        // Get current record count
        let info = self
            .store
            .get(&path)
            .await
            .map_err(|_| SqlError::TableNotFound(path.display()))?;

        // If WHERE clause exists, assume partial delete
        // Otherwise assume all records deleted
        let record_count = if query_lower.contains(" where ") {
            // Simulate partial delete - return at least 1 if table has records
            (info.total_records as i64).max(1) / 2
        } else {
            info.total_records as i64
        };

        Ok((path, record_count.max(0)))
    }

    /// Execute a TRUNCATE TABLE statement.
    ///
    /// Format: TRUNCATE [TABLE] table_name
    /// Removes all rows but keeps the table schema.
    async fn execute_truncate(&self, query: &str) -> SqlResult<(DataPath, i64)> {
        let query_lower = query.trim().to_lowercase();

        // Parse: TRUNCATE [TABLE] table_name
        let after_truncate = query_lower
            .strip_prefix("truncate")
            .ok_or_else(|| SqlError::SyntaxError("invalid TRUNCATE syntax".to_string()))?
            .trim_start();

        // Skip optional TABLE keyword
        let table_part = if after_truncate.starts_with("table ") {
            after_truncate.strip_prefix("table ").unwrap().trim_start()
        } else {
            after_truncate
        };

        let table_name = table_part
            .split_whitespace()
            .next()
            .ok_or_else(|| SqlError::SyntaxError("missing table name".to_string()))?;

        let path = self.parse_table_name(table_name)?;

        // Get current record count before truncation
        let info = self
            .store
            .get(&path)
            .await
            .map_err(|_| SqlError::TableNotFound(path.display()))?;

        let record_count = info.total_records as i64;

        // Truncate the table
        self.store
            .truncate(&path)
            .await
            .map_err(|e| SqlError::Internal(e.to_string()))?;

        // Refresh the catalog
        self.refresh_catalog().await;

        info!(
            path = %path.display(),
            record_count,
            "TRUNCATE TABLE executed"
        );

        Ok((path, record_count))
    }

    /// Execute an ALTER TABLE statement.
    ///
    /// Supported operations:
    /// - ALTER TABLE table_name ADD [COLUMN] column_name data_type
    /// - ALTER TABLE table_name DROP [COLUMN] column_name
    /// - ALTER TABLE table_name RENAME [COLUMN] old_name TO new_name
    async fn execute_alter_table(&self, query: &str) -> SqlResult<(DataPath, i64)> {
        let query_lower = query.trim().to_lowercase();

        // Parse: ALTER TABLE table_name ...
        let after_alter = query_lower
            .strip_prefix("alter")
            .ok_or_else(|| SqlError::SyntaxError("invalid ALTER syntax".to_string()))?
            .trim_start();

        let after_table = after_alter
            .strip_prefix("table")
            .ok_or_else(|| SqlError::SyntaxError("expected TABLE after ALTER".to_string()))?
            .trim_start();

        // Extract table name (until ADD, DROP, or RENAME)
        let table_end = after_table
            .find(" add ")
            .or_else(|| after_table.find(" drop "))
            .or_else(|| after_table.find(" rename "))
            .ok_or_else(|| {
                SqlError::SyntaxError("expected ADD, DROP, or RENAME in ALTER TABLE".to_string())
            })?;

        let table_name = after_table[..table_end].trim();
        let operation = &after_table[table_end + 1..].trim();
        let path = self.parse_table_name(table_name)?;

        // Get current schema
        let current_schema = self
            .store
            .get_schema(&path)
            .await
            .map_err(|_| SqlError::TableNotFound(path.display()))?;

        // Get current batches
        let current_batches = self
            .store
            .get_batches(&path)
            .await
            .map_err(|e| SqlError::Internal(e.to_string()))?;

        let (new_schema, new_batches) = if operation.starts_with("add ") {
            self.alter_add_column(operation, &current_schema, &current_batches)?
        } else if operation.starts_with("drop ") {
            self.alter_drop_column(operation, &current_schema, &current_batches)?
        } else if operation.starts_with("rename ") {
            self.alter_rename_column(operation, &current_schema, &current_batches)?
        } else {
            return Err(SqlError::UnsupportedCommand(
                "only ADD, DROP, RENAME operations are supported".to_string(),
            ));
        };

        // Replace the table with the new schema and data
        self.store
            .remove(&path)
            .await
            .map_err(|e| SqlError::Internal(e.to_string()))?;

        let batches: Vec<RecordBatch> = new_batches.into_iter().map(|b| (*b).clone()).collect();
        self.store
            .put(path.clone(), new_schema, batches)
            .await
            .map_err(|e| SqlError::Internal(e.to_string()))?;

        // Refresh the catalog
        self.refresh_catalog().await;

        info!(path = %path.display(), "ALTER TABLE executed");

        Ok((path, 0))
    }

    /// Execute ADD COLUMN operation.
    fn alter_add_column(
        &self,
        operation: &str,
        current_schema: &SchemaRef,
        current_batches: &[Arc<RecordBatch>],
    ) -> SqlResult<(SchemaRef, Vec<Arc<RecordBatch>>)> {
        let after_add = operation.strip_prefix("add ").unwrap().trim_start();

        // Skip optional COLUMN keyword
        let column_part = if after_add.starts_with("column ") {
            after_add.strip_prefix("column ").unwrap().trim_start()
        } else {
            after_add
        };

        // Parse: column_name data_type [NOT NULL] [DEFAULT ...]
        let parts: Vec<&str> = column_part.split_whitespace().collect();
        if parts.len() < 2 {
            return Err(SqlError::SyntaxError(
                "expected column_name data_type".to_string(),
            ));
        }

        let column_name = parts[0];
        let data_type_str = parts[1].to_uppercase();
        let nullable = !column_part.to_uppercase().contains("NOT NULL");

        let data_type = self.parse_data_type(&data_type_str)?;

        // Check if column already exists
        if current_schema.field_with_name(column_name).is_ok() {
            return Err(SqlError::InvalidCommand(format!(
                "column '{column_name}' already exists"
            )));
        }

        // Create new schema with added column
        let mut fields: Vec<Field> = current_schema
            .fields()
            .iter()
            .map(|f| f.as_ref().clone())
            .collect();
        fields.push(Field::new(column_name, data_type.clone(), nullable));
        let new_schema = Arc::new(Schema::new(fields));

        // Create new batches with null values for the new column
        let new_batches = self.add_null_column_to_batches(
            current_batches,
            column_name,
            &data_type,
            nullable,
            &new_schema,
        )?;

        Ok((new_schema, new_batches))
    }

    /// Execute DROP COLUMN operation.
    fn alter_drop_column(
        &self,
        operation: &str,
        current_schema: &SchemaRef,
        current_batches: &[Arc<RecordBatch>],
    ) -> SqlResult<(SchemaRef, Vec<Arc<RecordBatch>>)> {
        let after_drop = operation.strip_prefix("drop ").unwrap().trim_start();

        // Skip optional COLUMN keyword
        let column_name = if after_drop.starts_with("column ") {
            after_drop.strip_prefix("column ").unwrap().trim_start()
        } else {
            after_drop
        };

        let column_name = column_name.split_whitespace().next().unwrap_or(column_name);

        // Check if column exists
        let column_idx = current_schema
            .index_of(column_name)
            .map_err(|_| SqlError::InvalidCommand(format!("column '{column_name}' not found")))?;

        // Can't drop the last column
        if current_schema.fields().len() == 1 {
            return Err(SqlError::InvalidCommand(
                "cannot drop the last column".to_string(),
            ));
        }

        // Create new schema without the column
        let fields: Vec<Field> = current_schema
            .fields()
            .iter()
            .enumerate()
            .filter(|(i, _)| *i != column_idx)
            .map(|(_, f)| f.as_ref().clone())
            .collect();
        let new_schema = Arc::new(Schema::new(fields));

        // Create new batches without the column
        let new_batches =
            self.drop_column_from_batches(current_batches, column_idx, &new_schema)?;

        Ok((new_schema, new_batches))
    }

    /// Execute RENAME COLUMN operation.
    fn alter_rename_column(
        &self,
        operation: &str,
        current_schema: &SchemaRef,
        current_batches: &[Arc<RecordBatch>],
    ) -> SqlResult<(SchemaRef, Vec<Arc<RecordBatch>>)> {
        let after_rename = operation.strip_prefix("rename ").unwrap().trim_start();

        // Skip optional COLUMN keyword
        let column_part = if after_rename.starts_with("column ") {
            after_rename.strip_prefix("column ").unwrap().trim_start()
        } else {
            after_rename
        };

        // Parse: old_name TO new_name
        let parts: Vec<&str> = column_part.split_whitespace().collect();
        let to_idx = parts
            .iter()
            .position(|&p| p == "to")
            .ok_or_else(|| SqlError::SyntaxError("expected old_name TO new_name".to_string()))?;

        if to_idx == 0 || to_idx + 1 >= parts.len() {
            return Err(SqlError::SyntaxError(
                "expected old_name TO new_name".to_string(),
            ));
        }

        let old_name = parts[to_idx - 1];
        let new_name = parts[to_idx + 1];

        // Check if old column exists
        let column_idx = current_schema
            .index_of(old_name)
            .map_err(|_| SqlError::InvalidCommand(format!("column '{old_name}' not found")))?;

        // Check if new name already exists
        if current_schema.field_with_name(new_name).is_ok() {
            return Err(SqlError::InvalidCommand(format!(
                "column '{new_name}' already exists"
            )));
        }

        // Create new schema with renamed column
        let fields: Vec<Field> = current_schema
            .fields()
            .iter()
            .enumerate()
            .map(|(i, f)| {
                if i == column_idx {
                    Field::new(new_name, f.data_type().clone(), f.is_nullable())
                } else {
                    f.as_ref().clone()
                }
            })
            .collect();
        let new_schema = Arc::new(Schema::new(fields));

        // Recreate batches with new schema (data is the same, just schema changes)
        let new_batches = self.rename_column_in_batches(current_batches, &new_schema)?;

        Ok((new_schema, new_batches))
    }

    /// Parse a SQL data type string into an Arrow DataType.
    fn parse_data_type(&self, type_str: &str) -> SqlResult<arrow_schema::DataType> {
        use arrow_schema::DataType;

        let type_upper = type_str.to_uppercase();
        let dt = match type_upper.as_str() {
            "INT" | "INTEGER" | "INT32" => DataType::Int32,
            "BIGINT" | "INT64" => DataType::Int64,
            "SMALLINT" | "INT16" => DataType::Int16,
            "TINYINT" | "INT8" => DataType::Int8,
            "FLOAT" | "FLOAT32" | "REAL" => DataType::Float32,
            "DOUBLE" | "FLOAT64" => DataType::Float64,
            "BOOLEAN" | "BOOL" => DataType::Boolean,
            "VARCHAR" | "TEXT" | "STRING" | "UTF8" => DataType::Utf8,
            "BINARY" | "BYTEA" | "BLOB" => DataType::Binary,
            "DATE" | "DATE32" => DataType::Date32,
            "TIMESTAMP" => DataType::Timestamp(arrow_schema::TimeUnit::Microsecond, None),
            _ => {
                // Check for VARCHAR(n) or similar
                if type_upper.starts_with("VARCHAR") || type_upper.starts_with("CHAR") {
                    DataType::Utf8
                } else {
                    return Err(SqlError::SyntaxError(format!(
                        "unknown data type: {type_str}"
                    )));
                }
            }
        };

        Ok(dt)
    }

    /// Add a null column to all batches.
    fn add_null_column_to_batches(
        &self,
        batches: &[Arc<RecordBatch>],
        _column_name: &str,
        data_type: &arrow_schema::DataType,
        _nullable: bool,
        new_schema: &SchemaRef,
    ) -> SqlResult<Vec<Arc<RecordBatch>>> {
        use arrow_array::{ArrayRef, new_null_array};

        let mut new_batches = Vec::with_capacity(batches.len());

        for batch in batches {
            let num_rows = batch.num_rows();
            let mut columns: Vec<ArrayRef> = batch.columns().to_vec();

            // Create null array for the new column
            let null_array = new_null_array(data_type, num_rows);
            columns.push(null_array);

            let new_batch = RecordBatch::try_new(new_schema.clone(), columns)
                .map_err(|e| SqlError::Internal(e.to_string()))?;
            new_batches.push(Arc::new(new_batch));
        }

        Ok(new_batches)
    }

    /// Drop a column from all batches.
    fn drop_column_from_batches(
        &self,
        batches: &[Arc<RecordBatch>],
        column_idx: usize,
        new_schema: &SchemaRef,
    ) -> SqlResult<Vec<Arc<RecordBatch>>> {
        use arrow_array::ArrayRef;

        let mut new_batches = Vec::with_capacity(batches.len());

        for batch in batches {
            let columns: Vec<ArrayRef> = batch
                .columns()
                .iter()
                .enumerate()
                .filter(|(i, _)| *i != column_idx)
                .map(|(_, col)| col.clone())
                .collect();

            let new_batch = RecordBatch::try_new(new_schema.clone(), columns)
                .map_err(|e| SqlError::Internal(e.to_string()))?;
            new_batches.push(Arc::new(new_batch));
        }

        Ok(new_batches)
    }

    /// Rename a column in all batches (just recreate with new schema).
    fn rename_column_in_batches(
        &self,
        batches: &[Arc<RecordBatch>],
        new_schema: &SchemaRef,
    ) -> SqlResult<Vec<Arc<RecordBatch>>> {
        let mut new_batches = Vec::with_capacity(batches.len());

        for batch in batches {
            let new_batch = RecordBatch::try_new(new_schema.clone(), batch.columns().to_vec())
                .map_err(|e| SqlError::Internal(e.to_string()))?;
            new_batches.push(Arc::new(new_batch));
        }

        Ok(new_batches)
    }

    /// Execute a MERGE statement (SQL:2003 MERGE syntax).
    ///
    /// Executes the merge by building equivalent SQL queries for each WHEN
    /// clause and combining results via UNION ALL.
    async fn execute_merge(&self, query: &str) -> SqlResult<(DataPath, i64)> {
        let lower = query.trim().to_lowercase();
        let original = query.trim();

        // Find keyword positions
        let into_pos = lower
            .find(" into ")
            .ok_or_else(|| SqlError::SyntaxError("missing INTO in MERGE".to_string()))?;
        let using_pos = lower
            .find(" using ")
            .ok_or_else(|| SqlError::SyntaxError("missing USING in MERGE".to_string()))?;
        let on_pos = lower[using_pos + 7..]
            .find(" on ")
            .map(|p| using_pos + 7 + p)
            .ok_or_else(|| SqlError::SyntaxError("missing ON in MERGE".to_string()))?;

        // Extract target and source with optional aliases
        let target_part = original[into_pos + 6..using_pos].trim();
        let source_part = original[using_pos + 7..on_pos].trim();

        let (target_table, target_alias) = self.split_table_alias(target_part);
        let (source_table, source_alias) = self.split_table_alias(source_part);

        let target_path = self.parse_table_name(&target_table.to_lowercase())?;
        let source_path = self.parse_table_name(&source_table.to_lowercase())?;

        // Verify both tables exist
        let target_schema = self
            .store
            .get_schema(&target_path)
            .await
            .map_err(|_| SqlError::TableNotFound(target_path.display()))?;
        self.store
            .get_schema(&source_path)
            .await
            .map_err(|_| SqlError::TableNotFound(source_path.display()))?;

        let target_sql = self.qualified_table_sql(&target_path);
        let source_sql = self.qualified_table_sql(&source_path);
        let t_alias = target_alias.unwrap_or("_t");
        let s_alias = source_alias.unwrap_or("_s");

        // Find WHEN clauses (ensure "when matched" is not "when not matched")
        let when_not_matched_pos = lower.find(" when not matched ");
        let when_matched_pos = lower
            .find(" when matched ")
            .filter(|&p| when_not_matched_pos.is_none_or(|wnm| p != wnm + 4));

        // Extract ON condition (between ON and first WHEN clause)
        let first_when = when_matched_pos
            .into_iter()
            .chain(when_not_matched_pos)
            .min()
            .unwrap_or(original.len());
        let on_condition = original[on_pos + 4..first_when].trim();

        // Parse WHEN MATCHED THEN UPDATE SET ...
        let update_assignments = if let Some(wm_pos) = when_matched_pos {
            let clause_end = when_not_matched_pos
                .filter(|&p| p > wm_pos)
                .unwrap_or(original.len());
            let clause = &original[wm_pos..clause_end];
            let clause_lower = clause.to_lowercase();
            if let Some(set_offset) = clause_lower.find(" set ") {
                let set_str = clause[set_offset + 5..].trim();
                Some(self.parse_set_assignments(set_str)?)
            } else {
                None
            }
        } else {
            None
        };

        // Parse WHEN NOT MATCHED THEN INSERT (cols) VALUES (exprs)
        let insert_clause = if let Some(wnm_pos) = when_not_matched_pos {
            let clause_end = when_matched_pos
                .filter(|&p| p > wnm_pos)
                .unwrap_or(original.len());
            let clause = &original[wnm_pos..clause_end];
            let clause_lower = clause.to_lowercase();
            if let Some(insert_offset) = clause_lower.find(" insert ") {
                let insert_str = clause[insert_offset + 8..].trim();
                Some(self.parse_insert_columns_values(insert_str)?)
            } else {
                None
            }
        } else {
            None
        };

        let target_columns: Vec<&str> = target_schema
            .fields()
            .iter()
            .map(|f| f.name().as_str())
            .collect();

        let ctx = self.ctx.read().unwrap().clone();
        let mut all_batches: Vec<RecordBatch> = Vec::new();
        let mut affected_count: i64 = 0;

        // Part 1: Unchanged target rows (not matched by source)
        {
            let select_cols: Vec<String> = target_columns
                .iter()
                .map(|c| format!("{t_alias}.\"{}\"", c))
                .collect();
            let unchanged_query = format!(
                "SELECT {} FROM {target_sql} {t_alias} \
                 WHERE NOT EXISTS (SELECT 1 FROM {source_sql} {s_alias} WHERE {on_condition})",
                select_cols.join(", ")
            );
            let df = ctx
                .sql(&unchanged_query)
                .await
                .map_err(|e| SqlError::QueryExecution(e.to_string()))?;
            all_batches.extend(
                df.collect()
                    .await
                    .map_err(|e| SqlError::QueryExecution(e.to_string()))?,
            );
        }

        // Part 2: Updated matched rows
        if let Some(ref assignments) = update_assignments {
            let select_cols: Vec<String> = target_columns
                .iter()
                .map(|c| {
                    if let Some(expr) = assignments.get(*c) {
                        format!("{expr} AS \"{c}\"")
                    } else {
                        format!("{t_alias}.\"{}\"", c)
                    }
                })
                .collect();
            let updated_query = format!(
                "SELECT {} FROM {target_sql} {t_alias} \
                 INNER JOIN {source_sql} {s_alias} ON {on_condition}",
                select_cols.join(", ")
            );
            let df = ctx
                .sql(&updated_query)
                .await
                .map_err(|e| SqlError::QueryExecution(e.to_string()))?;
            let updated_batches = df
                .collect()
                .await
                .map_err(|e| SqlError::QueryExecution(e.to_string()))?;
            affected_count += updated_batches
                .iter()
                .map(|b| b.num_rows() as i64)
                .sum::<i64>();
            all_batches.extend(updated_batches);
        }

        // Part 3: Inserted rows from unmatched source
        if let Some((ref cols, ref vals)) = insert_clause {
            let select_cols: Vec<String> = target_columns
                .iter()
                .map(|tc| {
                    if let Some(idx) = cols.iter().position(|c| c == tc) {
                        format!("{} AS \"{}\"", vals[idx], tc)
                    } else {
                        format!("NULL AS \"{}\"", tc)
                    }
                })
                .collect();
            let inserted_query = format!(
                "SELECT {} FROM {source_sql} {s_alias} \
                 WHERE NOT EXISTS (SELECT 1 FROM {target_sql} {t_alias} WHERE {on_condition})",
                select_cols.join(", ")
            );
            let df = ctx
                .sql(&inserted_query)
                .await
                .map_err(|e| SqlError::QueryExecution(e.to_string()))?;
            let inserted_batches = df
                .collect()
                .await
                .map_err(|e| SqlError::QueryExecution(e.to_string()))?;
            affected_count += inserted_batches
                .iter()
                .map(|b| b.num_rows() as i64)
                .sum::<i64>();
            all_batches.extend(inserted_batches);
        }

        // Write back to target
        self.store
            .put(target_path.clone(), target_schema, all_batches)
            .await
            .map_err(|e| SqlError::Internal(e.to_string()))?;
        self.refresh_catalog().await;

        info!(
            target = %target_path.display(),
            record_count = affected_count,
            "MERGE executed"
        );

        Ok((target_path, affected_count))
    }

    /// Execute an INSERT...ON CONFLICT statement (PostgreSQL-style UPSERT).
    ///
    /// For DO NOTHING: inserts only non-conflicting rows.
    /// For DO UPDATE: updates conflicting rows and inserts non-conflicting ones.
    async fn execute_upsert(&self, query: &str) -> SqlResult<(DataPath, i64)> {
        let lower = query.trim().to_lowercase();
        let original = query.trim();

        // Parse table name
        let into_pos = lower
            .find(" into ")
            .ok_or_else(|| SqlError::SyntaxError("missing INTO clause".to_string()))?;
        let after_into = &original[into_pos + 6..];
        let table_end = after_into
            .find(|c: char| c == '(' || c.is_whitespace())
            .unwrap_or(after_into.len());
        let table_name = after_into[..table_end].trim();
        let path = self.parse_table_name(&table_name.to_lowercase())?;

        let target_schema = self
            .store
            .get_schema(&path)
            .await
            .map_err(|_| SqlError::TableNotFound(path.display()))?;
        let target_qualified = self.qualified_table_sql(&path);

        // Parse column list from the original query (after table name)
        let rest = &original[into_pos + 6 + table_end..];
        let cols_start = rest
            .find('(')
            .ok_or_else(|| SqlError::SyntaxError("missing column list".to_string()))?;
        let cols_end = rest
            .find(')')
            .ok_or_else(|| SqlError::SyntaxError("missing closing paren".to_string()))?;
        let columns: Vec<String> = rest[cols_start + 1..cols_end]
            .split(',')
            .map(|c| c.trim().to_lowercase().trim_matches('"').to_string())
            .collect();

        // Parse VALUES section (use original casing for literals)
        let values_pos = lower
            .find(" values ")
            .ok_or_else(|| SqlError::SyntaxError("missing VALUES clause".to_string()))?;
        let on_conflict_pos = lower
            .find(" on conflict ")
            .ok_or_else(|| SqlError::SyntaxError("missing ON CONFLICT clause".to_string()))?;
        let values_section = original[values_pos + 8..on_conflict_pos].trim();

        // Parse ON CONFLICT (key_col)
        let after_conflict = &original[on_conflict_pos + 13..];
        let conflict_start = after_conflict
            .find('(')
            .ok_or_else(|| SqlError::SyntaxError("missing conflict column".to_string()))?;
        let conflict_end = after_conflict.find(')').ok_or_else(|| {
            SqlError::SyntaxError("missing closing paren for conflict column".to_string())
        })?;
        let conflict_col = after_conflict[conflict_start + 1..conflict_end]
            .trim()
            .to_lowercase();

        // Determine action
        let do_update = lower.contains("do update");
        let do_nothing = lower.contains("do nothing");

        if !do_update && !do_nothing {
            return Err(SqlError::SyntaxError(
                "ON CONFLICT requires DO UPDATE or DO NOTHING".to_string(),
            ));
        }

        // Build VALUES subquery with column aliases
        let col_list = columns.join(", ");
        let values_subquery =
            format!("(SELECT * FROM (VALUES {values_section}) AS _nv({col_list}))");

        let target_columns: Vec<&str> = target_schema
            .fields()
            .iter()
            .map(|f| f.name().as_str())
            .collect();

        let ctx = self.ctx.read().unwrap().clone();
        let mut all_batches: Vec<RecordBatch> = Vec::new();
        let mut affected_count: i64 = 0;

        if do_nothing {
            // Keep all existing rows as-is
            let existing_query = format!(
                "SELECT {} FROM {target_qualified}",
                target_columns
                    .iter()
                    .map(|c| format!("\"{}\"", c))
                    .collect::<Vec<_>>()
                    .join(", ")
            );
            let df = ctx
                .sql(&existing_query)
                .await
                .map_err(|e| SqlError::QueryExecution(e.to_string()))?;
            all_batches.extend(
                df.collect()
                    .await
                    .map_err(|e| SqlError::QueryExecution(e.to_string()))?,
            );

            // Insert only non-conflicting new rows
            let insert_cols: Vec<String> = target_columns
                .iter()
                .map(|tc| {
                    if let Some(idx) = columns.iter().position(|c| c == tc) {
                        format!("_nv.\"{}\"", columns[idx])
                    } else {
                        format!("NULL AS \"{}\"", tc)
                    }
                })
                .collect();
            let new_query = format!(
                "SELECT {} FROM {values_subquery} _nv \
                 WHERE _nv.\"{conflict_col}\" NOT IN (SELECT \"{conflict_col}\" FROM {target_qualified})",
                insert_cols.join(", ")
            );
            let df = ctx
                .sql(&new_query)
                .await
                .map_err(|e| SqlError::QueryExecution(e.to_string()))?;
            let new_batches = df
                .collect()
                .await
                .map_err(|e| SqlError::QueryExecution(e.to_string()))?;
            affected_count += new_batches.iter().map(|b| b.num_rows() as i64).sum::<i64>();
            all_batches.extend(new_batches);
        } else {
            // DO UPDATE

            // Parse SET clause (replace EXCLUDED.col with _nv.col)
            let set_pos = lower
                .rfind(" set ")
                .ok_or_else(|| SqlError::SyntaxError("missing SET in DO UPDATE".to_string()))?;
            let set_clause = original[set_pos + 5..].trim();
            let assignments = self.parse_upsert_set_assignments(set_clause)?;

            // Non-conflicting existing rows
            let existing_cols: Vec<String> = target_columns
                .iter()
                .map(|c| format!("\"{}\"", c))
                .collect();
            let existing_query = format!(
                "SELECT {} FROM {target_qualified} \
                 WHERE \"{conflict_col}\" NOT IN (SELECT \"{conflict_col}\" FROM {values_subquery} _nv)",
                existing_cols.join(", ")
            );
            let df = ctx
                .sql(&existing_query)
                .await
                .map_err(|e| SqlError::QueryExecution(e.to_string()))?;
            all_batches.extend(
                df.collect()
                    .await
                    .map_err(|e| SqlError::QueryExecution(e.to_string()))?,
            );

            // Updated conflicting rows
            let update_cols: Vec<String> = target_columns
                .iter()
                .map(|c| {
                    if let Some(expr) = assignments.get(*c) {
                        format!("{expr} AS \"{c}\"")
                    } else {
                        format!("_existing.\"{}\"", c)
                    }
                })
                .collect();
            let updated_query = format!(
                "SELECT {} FROM {target_qualified} _existing \
                 INNER JOIN {values_subquery} _nv ON _existing.\"{conflict_col}\" = _nv.\"{conflict_col}\"",
                update_cols.join(", ")
            );
            let df = ctx
                .sql(&updated_query)
                .await
                .map_err(|e| SqlError::QueryExecution(e.to_string()))?;
            let updated_batches = df
                .collect()
                .await
                .map_err(|e| SqlError::QueryExecution(e.to_string()))?;
            affected_count += updated_batches
                .iter()
                .map(|b| b.num_rows() as i64)
                .sum::<i64>();
            all_batches.extend(updated_batches);

            // Non-conflicting new rows
            let insert_cols: Vec<String> = target_columns
                .iter()
                .map(|tc| {
                    if let Some(idx) = columns.iter().position(|c| c == tc) {
                        format!("_nv.\"{}\"", columns[idx])
                    } else {
                        format!("NULL AS \"{}\"", tc)
                    }
                })
                .collect();
            let new_query = format!(
                "SELECT {} FROM {values_subquery} _nv \
                 WHERE _nv.\"{conflict_col}\" NOT IN (SELECT \"{conflict_col}\" FROM {target_qualified})",
                insert_cols.join(", ")
            );
            let df = ctx
                .sql(&new_query)
                .await
                .map_err(|e| SqlError::QueryExecution(e.to_string()))?;
            let new_batches = df
                .collect()
                .await
                .map_err(|e| SqlError::QueryExecution(e.to_string()))?;
            affected_count += new_batches.iter().map(|b| b.num_rows() as i64).sum::<i64>();
            all_batches.extend(new_batches);
        }

        // Write back to target
        self.store
            .put(path.clone(), target_schema, all_batches)
            .await
            .map_err(|e| SqlError::Internal(e.to_string()))?;
        self.refresh_catalog().await;

        info!(
            path = %path.display(),
            record_count = affected_count,
            "UPSERT executed"
        );

        Ok((path, affected_count))
    }

    /// Split a "table_name AS alias" string into table and optional alias.
    fn split_table_alias<'a>(&self, s: &'a str) -> (&'a str, Option<&'a str>) {
        let lower = s.to_lowercase();
        if let Some(as_pos) = lower.find(" as ") {
            let table = s[..as_pos].trim();
            let alias = s[as_pos + 4..].trim();
            (table, Some(alias))
        } else {
            let parts: Vec<&str> = s.split_whitespace().collect();
            if parts.len() == 2 {
                (parts[0], Some(parts[1]))
            } else {
                (s.trim(), None)
            }
        }
    }

    /// Parse SET assignments: "col1 = expr1, col2 = expr2".
    fn parse_set_assignments(&self, set_clause: &str) -> SqlResult<HashMap<String, String>> {
        let mut assignments = HashMap::new();
        for assign in self.split_top_level(set_clause, ',') {
            let eq_pos = assign
                .find('=')
                .ok_or_else(|| SqlError::SyntaxError("invalid SET assignment".to_string()))?;
            let col = assign[..eq_pos]
                .trim()
                .to_lowercase()
                .trim_matches('"')
                .to_string();
            let expr = assign[eq_pos + 1..].trim().to_string();
            assignments.insert(col, expr);
        }
        Ok(assignments)
    }

    /// Parse UPSERT SET assignments, replacing EXCLUDED references.
    fn parse_upsert_set_assignments(&self, set_clause: &str) -> SqlResult<HashMap<String, String>> {
        let mut assignments = HashMap::new();
        for assign in self.split_top_level(set_clause, ',') {
            let eq_pos = assign
                .find('=')
                .ok_or_else(|| SqlError::SyntaxError("invalid SET assignment".to_string()))?;
            let col = assign[..eq_pos]
                .trim()
                .to_lowercase()
                .trim_matches('"')
                .to_string();
            let expr = assign[eq_pos + 1..].trim().to_string();
            // Replace EXCLUDED.col with _nv."col"
            let expr = expr.replace("EXCLUDED.", "_nv.\"");
            let expr = expr.replace("excluded.", "_nv.\"");
            // Close any opened quotes from the replacement
            let expr = if expr.contains("_nv.\"") && !expr.ends_with('"') {
                // Find each _nv." and close the quote at the next word boundary
                let mut result = String::new();
                let mut chars = expr.chars().peekable();
                while let Some(c) = chars.next() {
                    result.push(c);
                    if result.ends_with("_nv.\"") {
                        // Read until word boundary
                        while let Some(&next) = chars.peek() {
                            if next.is_alphanumeric() || next == '_' {
                                result.push(chars.next().unwrap());
                            } else {
                                break;
                            }
                        }
                        result.push('"');
                    }
                }
                result
            } else {
                expr
            };
            assignments.insert(col, expr);
        }
        Ok(assignments)
    }

    /// Parse INSERT columns and values: "(col1, col2) VALUES (expr1, expr2)".
    fn parse_insert_columns_values(&self, clause: &str) -> SqlResult<(Vec<String>, Vec<String>)> {
        let cols_start = clause
            .find('(')
            .ok_or_else(|| SqlError::SyntaxError("missing column list in INSERT".to_string()))?;
        let cols_end = clause.find(')').ok_or_else(|| {
            SqlError::SyntaxError("missing closing paren in column list".to_string())
        })?;

        let columns: Vec<String> = clause[cols_start + 1..cols_end]
            .split(',')
            .map(|c| c.trim().to_lowercase().trim_matches('"').to_string())
            .collect();

        let rest = &clause[cols_end + 1..];
        let lower_rest = rest.to_lowercase();
        let values_pos = lower_rest
            .find("values")
            .ok_or_else(|| SqlError::SyntaxError("missing VALUES in INSERT".to_string()))?;

        let after_values = &rest[values_pos + 6..];
        let vals_start = after_values
            .find('(')
            .ok_or_else(|| SqlError::SyntaxError("missing values list".to_string()))?;
        let vals_end = after_values
            .rfind(')')
            .ok_or_else(|| SqlError::SyntaxError("missing closing paren in values".to_string()))?;

        let values: Vec<String> = self
            .split_top_level(&after_values[vals_start + 1..vals_end], ',')
            .into_iter()
            .map(|v| v.trim().to_string())
            .collect();

        if columns.len() != values.len() {
            return Err(SqlError::SyntaxError(
                "column count does not match value count in INSERT".to_string(),
            ));
        }

        Ok((columns, values))
    }

    /// Split a string by delimiter, respecting parentheses and string literals.
    fn split_top_level<'a>(&self, s: &'a str, delim: char) -> Vec<&'a str> {
        let mut parts = Vec::new();
        let mut depth = 0i32;
        let mut in_string = false;
        let mut start = 0;

        for (i, c) in s.char_indices() {
            match c {
                '\'' if !in_string => in_string = true,
                '\'' if in_string => in_string = false,
                '(' if !in_string => depth += 1,
                ')' if !in_string => depth -= 1,
                c if c == delim && depth == 0 && !in_string => {
                    parts.push(&s[start..i]);
                    start = i + c.len_utf8();
                }
                _ => {}
            }
        }
        parts.push(&s[start..]);
        parts
    }

    /// Parse a table name into a DataPath.
    fn parse_table_name(&self, table_name: &str) -> SqlResult<DataPath> {
        let segments: Vec<String> = table_name
            .split('.')
            .map(|s| s.trim_matches('"').to_string())
            .collect();

        if segments.is_empty() || segments.iter().any(|s| s.is_empty()) {
            return Err(SqlError::SyntaxError("invalid table name".to_string()));
        }

        Ok(DataPath::new(segments))
    }

    /// Parse a simple SELECT query to extract table path.
    #[cfg(test)]
    fn parse_select_query(&self, query: &str) -> SqlResult<DataPath> {
        let query = query.trim().to_lowercase();

        // Simple parser for: SELECT * FROM table_name
        // or: SELECT * FROM schema.table_name
        if !query.starts_with("select") {
            return Err(SqlError::SyntaxError(
                "only SELECT queries are supported".to_string(),
            ));
        }

        // Find FROM clause
        let from_pos = query
            .find(" from ")
            .ok_or_else(|| SqlError::SyntaxError("missing FROM clause".to_string()))?;

        let after_from = &query[from_pos + 6..];
        let table_name = after_from
            .split_whitespace()
            .next()
            .ok_or_else(|| SqlError::SyntaxError("missing table name".to_string()))?;

        // Handle schema.table format
        let segments: Vec<String> = table_name
            .split('.')
            .map(|s| s.trim_matches('"').to_string())
            .collect();

        if segments.is_empty() {
            return Err(SqlError::SyntaxError("empty table name".to_string()));
        }

        Ok(DataPath::new(segments))
    }

    /// Parse LIMIT clause from a query, returning None if not present.
    #[cfg(test)]
    fn parse_limit(&self, query: &str) -> Option<usize> {
        let query_lower = query.trim().to_lowercase();

        // Find "LIMIT" keyword
        if let Some(limit_pos) = query_lower.find(" limit ") {
            let after_limit = &query_lower[limit_pos + 7..];
            // Take the first token which should be the number
            if let Some(num_str) = after_limit.split_whitespace().next() {
                return num_str.parse::<usize>().ok();
            }
        }
        None
    }

    /// Apply a row limit to record batches.
    #[cfg(test)]
    fn apply_limit(&self, batches: Vec<Arc<RecordBatch>>, limit: usize) -> Vec<Arc<RecordBatch>> {
        let mut result = Vec::new();
        let mut remaining = limit;

        for batch in batches {
            if remaining == 0 {
                break;
            }

            let batch_rows = batch.num_rows();
            if batch_rows <= remaining {
                // Take the whole batch
                result.push(batch);
                remaining -= batch_rows;
            } else {
                // Slice the batch to get only `remaining` rows
                let sliced = batch.slice(0, remaining);
                result.push(Arc::new(sliced));
                remaining = 0;
            }
        }

        result
    }

    /// Create a query handle from a query string.
    fn create_query_handle(&self, query: &str) -> Bytes {
        Bytes::from(query.to_string())
    }

    /// Generate a unique prepared statement handle.
    fn generate_handle(&self) -> Bytes {
        let mut id = self.next_handle_id.write().unwrap();
        let handle = Bytes::from(format!("ps_{}", *id));
        *id += 1;
        handle
    }

    /// Create a prepared statement.
    ///
    /// Uses DataFusion to validate queries and infer result schema.
    pub async fn create_prepared_statement(
        &self,
        request: &ActionCreatePreparedStatementRequest,
    ) -> SqlResult<CreatePreparedStatementResult> {
        let query = &request.query;
        debug!(query = %query, "creating prepared statement");

        let query_lower = query.trim().to_lowercase();
        let is_query = query_lower.starts_with("select");

        // Validate the query and determine schema using DataFusion
        let (dataset_schema, parameter_schema) = if is_query {
            // For SELECT queries, use DataFusion to get the result schema
            let ctx = self.ctx.read().unwrap().clone();
            let df = ctx
                .sql(query)
                .await
                .map_err(|e| SqlError::QueryExecution(e.to_string()))?;

            let schema = df.schema().inner().clone();
            let params = self.extract_parameter_schema(query);
            (Some(schema), params)
        } else if query_lower.starts_with("insert")
            || query_lower.starts_with("update")
            || query_lower.starts_with("delete")
        {
            // For DML statements, validate the table exists
            let path = self.parse_dml_table_name(query)?;
            self.store
                .get_schema(&path)
                .await
                .map_err(|_| SqlError::TableNotFound(path.display()))?;

            let params = self.extract_parameter_schema(query);
            (None, params)
        } else {
            return Err(SqlError::SyntaxError(
                "only SELECT, INSERT, UPDATE, DELETE statements are supported".to_string(),
            ));
        };

        // Generate handle and store the prepared statement
        let handle = self.generate_handle();
        let stmt = PreparedStatement {
            query: query.clone(),
            is_query,
            dataset_schema: dataset_schema.clone(),
            parameter_schema: parameter_schema.clone(),
            bound_parameters: None,
        };

        self.prepared_statements
            .write()
            .unwrap()
            .insert(handle.clone(), stmt);

        info!(
            handle = %String::from_utf8_lossy(&handle),
            query = %query,
            is_query,
            "prepared statement created"
        );

        Ok(CreatePreparedStatementResult {
            handle,
            dataset_schema,
            parameter_schema,
        })
    }

    /// Close a prepared statement.
    pub fn close_prepared_statement(
        &self,
        request: &ActionClosePreparedStatementRequest,
    ) -> SqlResult<()> {
        let handle = &request.prepared_statement_handle;
        debug!(handle = %String::from_utf8_lossy(handle), "closing prepared statement");

        let removed = self.prepared_statements.write().unwrap().remove(handle);

        if removed.is_some() {
            info!(handle = %String::from_utf8_lossy(handle), "prepared statement closed");
            Ok(())
        } else {
            warn!(
                handle = %String::from_utf8_lossy(handle),
                "prepared statement not found for close"
            );
            // Per Flight SQL spec, closing a non-existent statement is not an error
            Ok(())
        }
    }

    /// Bind parameters to a prepared statement.
    ///
    /// Clients send parameter values via DoPut with CommandPreparedStatementQuery.
    /// The parameters are stored and used when the statement is executed.
    pub fn bind_parameters(
        &self,
        handle: &Bytes,
        parameters: Vec<Arc<RecordBatch>>,
    ) -> SqlResult<()> {
        debug!(
            handle = %String::from_utf8_lossy(handle),
            batch_count = parameters.len(),
            "binding parameters to prepared statement"
        );

        let mut statements = self.prepared_statements.write().unwrap();
        let stmt = statements.get_mut(handle).ok_or_else(|| {
            SqlError::PreparedStatementNotFound(String::from_utf8_lossy(handle).to_string())
        })?;

        let total_rows: usize = parameters.iter().map(|b| b.num_rows()).sum();

        stmt.bound_parameters = Some(parameters);

        info!(
            handle = %String::from_utf8_lossy(handle),
            total_rows,
            "parameters bound to prepared statement"
        );

        Ok(())
    }

    /// Get the bound parameters for a prepared statement.
    pub fn get_bound_parameters(&self, handle: &Bytes) -> SqlResult<Option<Vec<Arc<RecordBatch>>>> {
        let statements = self.prepared_statements.read().unwrap();
        let stmt = statements.get(handle).ok_or_else(|| {
            SqlError::PreparedStatementNotFound(String::from_utf8_lossy(handle).to_string())
        })?;

        Ok(stmt.bound_parameters.clone())
    }

    /// Execute a prepared statement query.
    ///
    /// Uses DataFusion to validate and prepare the query.
    pub async fn execute_prepared_statement_query(
        &self,
        cmd: &CommandPreparedStatementQuery,
    ) -> SqlResult<QueryResult> {
        let handle = cmd.prepared_statement_handle.clone();
        debug!(handle = %String::from_utf8_lossy(&handle), "executing prepared statement query");

        let query = {
            let statements = self.prepared_statements.read().unwrap();
            let stmt = statements.get(&handle).ok_or_else(|| {
                SqlError::PreparedStatementNotFound(String::from_utf8_lossy(&handle).to_string())
            })?;

            if !stmt.is_query {
                return Err(SqlError::InvalidCommand(
                    "prepared statement is not a query".to_string(),
                ));
            }

            stmt.query.clone()
        };

        // Use DataFusion to get the schema
        let ctx = self.ctx.read().unwrap().clone();
        let df = ctx
            .sql(&query)
            .await
            .map_err(|e| SqlError::QueryExecution(e.to_string()))?;

        let schema = df.schema().inner().clone();

        info!(
            handle = %String::from_utf8_lossy(&handle),
            "prepared statement query validated"
        );

        Ok(QueryResult {
            handle: handle.clone(),
            schema,
            total_records: -1,
        })
    }

    /// Get data for a prepared statement query.
    ///
    /// Executes the query using DataFusion.
    pub async fn get_prepared_statement_data(
        &self,
        handle: &Bytes,
    ) -> SqlResult<(SchemaRef, Vec<Arc<RecordBatch>>)> {
        debug!(handle = %String::from_utf8_lossy(handle), "getting prepared statement data via DataFusion");

        let query = {
            let statements = self.prepared_statements.read().unwrap();
            let stmt = statements.get(handle).ok_or_else(|| {
                SqlError::PreparedStatementNotFound(String::from_utf8_lossy(handle).to_string())
            })?;
            stmt.query.clone()
        };

        // Execute using DataFusion
        let ctx = self.ctx.read().unwrap().clone();
        let df = ctx
            .sql(&query)
            .await
            .map_err(|e| SqlError::QueryExecution(e.to_string()))?;

        let schema = df.schema().inner().clone();
        let batches = df
            .collect()
            .await
            .map_err(|e| SqlError::QueryExecution(e.to_string()))?;

        // Convert to Arc<RecordBatch>
        let batches: Vec<Arc<RecordBatch>> = batches.into_iter().map(Arc::new).collect();

        Ok((schema, batches))
    }

    /// Get a streaming data source for a prepared statement query.
    ///
    /// Executes the query using DataFusion and returns a stream of record batches.
    /// This avoids loading all data into memory at once for large result sets.
    pub async fn get_prepared_statement_data_stream(
        &self,
        handle: &Bytes,
    ) -> SqlResult<(SchemaRef, QueryDataStream)> {
        debug!(handle = %String::from_utf8_lossy(handle), "getting prepared statement data stream via DataFusion");

        let query = {
            let statements = self.prepared_statements.read().unwrap();
            let stmt = statements.get(handle).ok_or_else(|| {
                SqlError::PreparedStatementNotFound(String::from_utf8_lossy(handle).to_string())
            })?;
            stmt.query.clone()
        };

        // Execute using DataFusion
        let ctx = self.ctx.read().unwrap().clone();
        let df = ctx
            .sql(&query)
            .await
            .map_err(|e| SqlError::QueryExecution(e.to_string()))?;

        let schema = df.schema().inner().clone();

        // Get a streaming result instead of collecting all batches
        let stream = df
            .execute_stream()
            .await
            .map_err(|e| SqlError::QueryExecution(e.to_string()))?;

        info!(
            handle = %String::from_utf8_lossy(handle),
            "prepared statement query streaming started via DataFusion"
        );

        Ok((schema, QueryDataStream::new(stream)))
    }

    /// Execute a prepared statement update.
    pub async fn execute_prepared_statement_update(
        &self,
        cmd: &CommandPreparedStatementUpdate,
    ) -> SqlResult<UpdateResult> {
        let handle = &cmd.prepared_statement_handle;
        debug!(handle = %String::from_utf8_lossy(handle), "executing prepared statement update");

        let query = {
            let statements = self.prepared_statements.read().unwrap();
            let stmt = statements.get(handle).ok_or_else(|| {
                SqlError::PreparedStatementNotFound(String::from_utf8_lossy(handle).to_string())
            })?;

            if stmt.is_query {
                return Err(SqlError::InvalidCommand(
                    "prepared statement is a query, not an update".to_string(),
                ));
            }

            stmt.query.clone()
        };

        // Execute the stored update via DataFusion
        let (path, record_count) = self.parse_and_execute_update_async(&query).await?;

        info!(
            handle = %String::from_utf8_lossy(handle),
            path = %path.display(),
            record_count,
            "prepared statement update executed"
        );

        Ok(UpdateResult { record_count })
    }

    /// Extract parameter schema from a query.
    ///
    /// For now, returns an empty schema - parameter binding is a future enhancement.
    fn extract_parameter_schema(&self, _query: &str) -> Option<SchemaRef> {
        // In a full implementation, we'd parse ? placeholders and infer types
        // For now, return an empty schema indicating no parameters
        Some(Arc::new(Schema::new(Vec::<Field>::new())))
    }

    /// Parse DML statement to extract table name.
    fn parse_dml_table_name(&self, query: &str) -> SqlResult<DataPath> {
        let query_lower = query.trim().to_lowercase();

        if query_lower.starts_with("insert") {
            let into_pos = query_lower
                .find(" into ")
                .ok_or_else(|| SqlError::SyntaxError("missing INTO clause".to_string()))?;
            let after_into = &query_lower[into_pos + 6..];
            let table_name = after_into
                .split(|c: char| c.is_whitespace() || c == '(')
                .next()
                .ok_or_else(|| SqlError::SyntaxError("missing table name".to_string()))?;
            self.parse_table_name(table_name)
        } else if query_lower.starts_with("update") {
            let after_update = query_lower
                .strip_prefix("update")
                .ok_or_else(|| SqlError::SyntaxError("invalid UPDATE syntax".to_string()))?
                .trim_start();
            let table_name = after_update
                .split_whitespace()
                .next()
                .ok_or_else(|| SqlError::SyntaxError("missing table name".to_string()))?;
            self.parse_table_name(table_name)
        } else if query_lower.starts_with("delete") {
            let from_pos = query_lower
                .find(" from ")
                .ok_or_else(|| SqlError::SyntaxError("missing FROM clause".to_string()))?;
            let after_from = &query_lower[from_pos + 6..];
            let table_name = after_from
                .split_whitespace()
                .next()
                .ok_or_else(|| SqlError::SyntaxError("missing table name".to_string()))?;
            self.parse_table_name(table_name)
        } else {
            Err(SqlError::SyntaxError(
                "unknown DML statement type".to_string(),
            ))
        }
    }

    /// Begin a new transaction.
    ///
    /// Returns a unique transaction ID.
    pub fn begin_transaction(&self) -> SqlResult<Bytes> {
        self.begin_transaction_with_isolation(IsolationLevel::default())
    }

    /// Begin a new transaction with a specific isolation level.
    ///
    /// Returns a unique transaction ID.
    pub fn begin_transaction_with_isolation(
        &self,
        isolation_level: IsolationLevel,
    ) -> SqlResult<Bytes> {
        let id = self.generate_handle();
        let transaction = Transaction {
            active: true,
            isolation_level,
            pending_operations: Vec::new(),
            savepoints: HashMap::new(),
        };

        self.transactions
            .write()
            .unwrap()
            .insert(id.clone(), transaction);

        info!(
            transaction_id = %String::from_utf8_lossy(&id),
            isolation_level = %isolation_level,
            "transaction started"
        );

        Ok(id)
    }

    /// End a transaction (commit or rollback).
    pub fn end_transaction(&self, transaction_id: &Bytes, action: EndTransaction) -> SqlResult<()> {
        debug!(
            transaction_id = %String::from_utf8_lossy(transaction_id),
            action = ?action,
            "ending transaction"
        );

        let mut transactions = self.transactions.write().unwrap();
        let transaction = transactions.get_mut(transaction_id).ok_or_else(|| {
            SqlError::TransactionNotFound(String::from_utf8_lossy(transaction_id).to_string())
        })?;

        if !transaction.active {
            return Err(SqlError::InvalidTransactionAction(
                "transaction already ended".to_string(),
            ));
        }

        let pending_count = transaction.pending_operations.len();
        let total_records: i64 = transaction
            .pending_operations
            .iter()
            .map(|op| op.record_count())
            .sum();

        match action {
            EndTransaction::Commit => {
                // Apply all pending operations
                for op in &transaction.pending_operations {
                    match op {
                        PendingOperation::Insert {
                            path,
                            query,
                            record_count,
                        } => {
                            debug!(
                                path = %path.display(),
                                query = %query,
                                record_count,
                                "committing INSERT"
                            );
                            // In a full implementation, this would apply the actual data changes
                        }
                        PendingOperation::Update {
                            path,
                            query,
                            record_count,
                        } => {
                            debug!(
                                path = %path.display(),
                                query = %query,
                                record_count,
                                "committing UPDATE"
                            );
                        }
                        PendingOperation::Delete {
                            path,
                            query,
                            record_count,
                        } => {
                            debug!(
                                path = %path.display(),
                                query = %query,
                                record_count,
                                "committing DELETE"
                            );
                        }
                    }
                }
                info!(
                    transaction_id = %String::from_utf8_lossy(transaction_id),
                    pending_operations = pending_count,
                    total_records_affected = total_records,
                    "transaction committed"
                );
            }
            EndTransaction::Rollback => {
                info!(
                    transaction_id = %String::from_utf8_lossy(transaction_id),
                    pending_operations = pending_count,
                    total_records_discarded = total_records,
                    "transaction rolled back (pending operations discarded)"
                );
                // Simply discard pending operations (done automatically when transaction is removed)
            }
            EndTransaction::Unspecified => {
                return Err(SqlError::InvalidTransactionAction(
                    "unspecified transaction action".to_string(),
                ));
            }
        }

        transaction.active = false;
        // Remove completed transaction from the map (discards pending operations on rollback)
        transactions.remove(transaction_id);

        Ok(())
    }

    /// Get the count of pending operations in a transaction.
    #[cfg(test)]
    pub fn get_pending_operation_count(&self, transaction_id: &Bytes) -> SqlResult<usize> {
        let transactions = self.transactions.read().unwrap();
        let transaction = transactions.get(transaction_id).ok_or_else(|| {
            SqlError::TransactionNotFound(String::from_utf8_lossy(transaction_id).to_string())
        })?;
        Ok(transaction.pending_operations.len())
    }

    /// Begin a savepoint within an existing transaction.
    ///
    /// Returns a unique savepoint ID that can be used to rollback or release.
    pub fn begin_savepoint(&self, transaction_id: &Bytes, name: String) -> SqlResult<Bytes> {
        let mut transactions = self.transactions.write().unwrap();
        let transaction = transactions.get_mut(transaction_id).ok_or_else(|| {
            SqlError::TransactionNotFound(String::from_utf8_lossy(transaction_id).to_string())
        })?;

        if !transaction.active {
            return Err(SqlError::InvalidTransactionAction(
                "cannot create savepoint in inactive transaction".to_string(),
            ));
        }

        // Generate a unique savepoint ID
        let savepoint_id = self.generate_handle();

        // Record the current position in pending operations
        let savepoint = Savepoint {
            name: name.clone(),
            operation_index: transaction.pending_operations.len(),
        };

        transaction
            .savepoints
            .insert(savepoint_id.clone(), savepoint);

        info!(
            transaction_id = %String::from_utf8_lossy(transaction_id),
            savepoint_id = %String::from_utf8_lossy(&savepoint_id),
            savepoint_name = %name,
            operation_index = transaction.pending_operations.len(),
            "savepoint created"
        );

        Ok(savepoint_id)
    }

    /// End a savepoint (release or rollback).
    ///
    /// - Release: Removes the savepoint but keeps all operations since.
    /// - Rollback: Discards all operations since the savepoint was created.
    pub fn end_savepoint(&self, savepoint_id: &Bytes, action: EndSavepoint) -> SqlResult<()> {
        let mut transactions = self.transactions.write().unwrap();

        // Find the transaction containing this savepoint
        let transaction = transactions
            .values_mut()
            .find(|t| t.savepoints.contains_key(savepoint_id))
            .ok_or_else(|| {
                SqlError::SavepointNotFound(String::from_utf8_lossy(savepoint_id).to_string())
            })?;

        if !transaction.active {
            return Err(SqlError::InvalidTransactionAction(
                "cannot end savepoint in inactive transaction".to_string(),
            ));
        }

        let savepoint = transaction.savepoints.remove(savepoint_id).ok_or_else(|| {
            SqlError::SavepointNotFound(String::from_utf8_lossy(savepoint_id).to_string())
        })?;

        match action {
            EndSavepoint::Release => {
                // Simply remove the savepoint marker, keeping all operations
                info!(
                    savepoint_id = %String::from_utf8_lossy(savepoint_id),
                    savepoint_name = %savepoint.name,
                    "savepoint released"
                );
            }
            EndSavepoint::Rollback => {
                // Discard all operations since the savepoint
                let discarded_count =
                    transaction.pending_operations.len() - savepoint.operation_index;
                transaction
                    .pending_operations
                    .truncate(savepoint.operation_index);

                // Also invalidate any savepoints created after this one
                transaction
                    .savepoints
                    .retain(|_, sp| sp.operation_index <= savepoint.operation_index);

                info!(
                    savepoint_id = %String::from_utf8_lossy(savepoint_id),
                    savepoint_name = %savepoint.name,
                    discarded_operations = discarded_count,
                    "savepoint rolled back"
                );
            }
            EndSavepoint::Unspecified => {
                // Re-insert the savepoint since we didn't process it
                transaction
                    .savepoints
                    .insert(savepoint_id.clone(), savepoint);
                return Err(SqlError::InvalidTransactionAction(
                    "unspecified savepoint action".to_string(),
                ));
            }
        }

        Ok(())
    }

    /// Get the isolation level of a transaction.
    #[cfg(test)]
    pub fn get_transaction_isolation_level(
        &self,
        transaction_id: &Bytes,
    ) -> SqlResult<IsolationLevel> {
        let transactions = self.transactions.read().unwrap();
        let transaction = transactions.get(transaction_id).ok_or_else(|| {
            SqlError::TransactionNotFound(String::from_utf8_lossy(transaction_id).to_string())
        })?;
        Ok(transaction.isolation_level)
    }

    /// Get the count of savepoints in a transaction.
    #[cfg(test)]
    pub fn get_savepoint_count(&self, transaction_id: &Bytes) -> SqlResult<usize> {
        let transactions = self.transactions.read().unwrap();
        let transaction = transactions.get(transaction_id).ok_or_else(|| {
            SqlError::TransactionNotFound(String::from_utf8_lossy(transaction_id).to_string())
        })?;
        Ok(transaction.savepoints.len())
    }
}

/// Create a TicketStatementQuery message for a query handle.
pub fn create_statement_ticket(handle: Bytes) -> Bytes {
    let ticket = TicketStatementQuery {
        statement_handle: handle,
    };
    ticket.encode_to_vec().into()
}

/// Create a TicketStatementQuery for a prepared statement handle.
pub fn create_prepared_statement_ticket(handle: Bytes) -> Bytes {
    // Use the same ticket format as regular statement queries
    let ticket = TicketStatementQuery {
        statement_handle: handle,
    };
    ticket.encode_to_vec().into()
}

/// Create a TicketStatementQuery for a metadata query handle.
pub fn create_metadata_ticket(handle: Bytes) -> Bytes {
    // Use the same ticket format - metadata handles are distinguished by prefix
    let ticket = TicketStatementQuery {
        statement_handle: handle,
    };
    ticket.encode_to_vec().into()
}

/// Encode schema to IPC format for ActionCreatePreparedStatementResult.
pub fn encode_schema_to_ipc(schema: &SchemaRef) -> SqlResult<Bytes> {
    use arrow_flight::{IpcMessage, SchemaAsIpc};

    let options = IpcWriteOptions::default();
    let schema_ipc = SchemaAsIpc::new(schema, &options);
    let ipc_message: IpcMessage = schema_ipc
        .try_into()
        .map_err(|e: ArrowError| SqlError::Arrow(e))?;
    Ok(Bytes::copy_from_slice(&ipc_message))
}

/// Create the ActionCreatePreparedStatementResult message.
pub fn create_prepared_statement_result(
    result: &CreatePreparedStatementResult,
) -> SqlResult<ActionCreatePreparedStatementResult> {
    let dataset_schema = match &result.dataset_schema {
        Some(schema) => encode_schema_to_ipc(schema)?,
        None => Bytes::new(),
    };

    let parameter_schema = match &result.parameter_schema {
        Some(schema) => encode_schema_to_ipc(schema)?,
        None => Bytes::new(),
    };

    Ok(ActionCreatePreparedStatementResult {
        prepared_statement_handle: result.handle.clone(),
        dataset_schema,
        parameter_schema,
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::MemoryStore;
    use crate::metadata::{DEFAULT_CATALOG, DEFAULT_SCHEMA};
    use arrow_array::{Int64Array, RecordBatch};
    use arrow_flight::sql::CommandStatementQuery;
    use arrow_schema::{DataType, Field, Schema};

    async fn create_test_store() -> Arc<dyn Store> {
        let store = Arc::new(MemoryStore::new());

        // Add test table
        let schema = Arc::new(Schema::new(vec![
            Field::new("id", DataType::Int64, false),
            Field::new("value", DataType::Int64, false),
        ]));

        let batch = RecordBatch::try_new(
            schema.clone(),
            vec![
                Arc::new(Int64Array::from(vec![1, 2, 3])),
                Arc::new(Int64Array::from(vec![10, 20, 30])),
            ],
        )
        .unwrap();

        store
            .put(
                DataPath::new(vec!["test".to_string(), "table".to_string()]),
                schema,
                vec![batch],
            )
            .await
            .unwrap();

        store
    }

    async fn create_test_engine() -> SqlEngine {
        SqlEngine::new(create_test_store().await, DEFAULT_CATALOG, DEFAULT_SCHEMA).await
    }

    async fn create_fixture_engine() -> SqlEngine {
        let store: Arc<dyn Store> = Arc::new(MemoryStore::with_test_fixtures());
        SqlEngine::new(store, DEFAULT_CATALOG, DEFAULT_SCHEMA).await
    }

    #[tokio::test]
    async fn test_parse_simple_select() {
        let engine = create_test_engine().await;

        let path = engine
            .parse_select_query("SELECT * FROM test.table")
            .unwrap();
        assert_eq!(path.segments(), &["test", "table"]);
    }

    #[tokio::test]
    async fn test_parse_select_single_table() {
        let engine = create_test_engine().await;

        let path = engine.parse_select_query("SELECT * FROM users").unwrap();
        assert_eq!(path.segments(), &["users"]);
    }

    #[tokio::test]
    async fn test_parse_select_with_limit() {
        let engine = create_test_engine().await;

        // LIMIT should not affect table path extraction
        let path = engine
            .parse_select_query("SELECT * FROM test.table LIMIT 5")
            .unwrap();
        assert_eq!(path.segments(), &["test", "table"]);
    }

    #[tokio::test]
    async fn test_parse_limit_clause() {
        let engine = create_test_engine().await;

        assert_eq!(engine.parse_limit("SELECT * FROM users LIMIT 10"), Some(10));
        assert_eq!(engine.parse_limit("SELECT * FROM users LIMIT 5"), Some(5));
        assert_eq!(engine.parse_limit("SELECT * FROM users LIMIT 0"), Some(0));
        assert_eq!(engine.parse_limit("SELECT * FROM users"), None);
        assert_eq!(engine.parse_limit("SELECT * FROM users WHERE id > 5"), None);
    }

    #[tokio::test]
    async fn test_apply_limit() {
        let engine = create_test_engine().await;

        // Create test batches
        let schema = Arc::new(Schema::new(vec![Field::new("id", DataType::Int64, false)]));

        let batch1 = Arc::new(
            RecordBatch::try_new(
                schema.clone(),
                vec![Arc::new(Int64Array::from(vec![1, 2, 3]))],
            )
            .unwrap(),
        );
        let batch2 = Arc::new(
            RecordBatch::try_new(
                schema.clone(),
                vec![Arc::new(Int64Array::from(vec![4, 5, 6]))],
            )
            .unwrap(),
        );

        let batches = vec![batch1, batch2];

        // Limit less than first batch
        let limited = engine.apply_limit(batches.clone(), 2);
        assert_eq!(limited.len(), 1);
        assert_eq!(limited[0].num_rows(), 2);

        // Limit exactly first batch
        let limited = engine.apply_limit(batches.clone(), 3);
        assert_eq!(limited.len(), 1);
        assert_eq!(limited[0].num_rows(), 3);

        // Limit spans both batches
        let limited = engine.apply_limit(batches.clone(), 4);
        assert_eq!(limited.len(), 2);
        assert_eq!(limited[0].num_rows(), 3);
        assert_eq!(limited[1].num_rows(), 1);

        // Limit all rows
        let limited = engine.apply_limit(batches.clone(), 6);
        assert_eq!(limited.len(), 2);
        assert_eq!(limited[0].num_rows(), 3);
        assert_eq!(limited[1].num_rows(), 3);

        // Limit more than available
        let limited = engine.apply_limit(batches.clone(), 100);
        assert_eq!(limited.len(), 2);
    }

    #[tokio::test]
    async fn test_execute_statement_query() {
        let engine = create_test_engine().await;

        let cmd = CommandStatementQuery {
            query: "SELECT * FROM test.\"table\"".to_string(),
            transaction_id: None,
        };

        let result = engine.execute_statement_query(&cmd).await.unwrap();
        // DataFusion returns -1 for total_records until execution
        assert_eq!(result.total_records, -1);
        assert_eq!(result.schema.fields().len(), 2);
    }

    #[tokio::test]
    async fn test_table_not_found() {
        let engine = create_test_engine().await;

        let cmd = CommandStatementQuery {
            query: "SELECT * FROM nonexistent".to_string(),
            transaction_id: None,
        };

        let result = engine.execute_statement_query(&cmd).await;
        assert!(matches!(result, Err(SqlError::QueryExecution(_))));
    }

    #[tokio::test]
    async fn test_inner_join() {
        let engine = create_fixture_engine().await;

        let cmd = CommandStatementQuery {
            query: "SELECT c.name, o.order_id, o.amount FROM test.customers c INNER JOIN test.orders o ON c.customer_id = o.customer_id ORDER BY o.order_id".to_string(),
            transaction_id: None,
        };

        let result = engine.execute_statement_query(&cmd).await.unwrap();
        assert_eq!(result.schema.fields().len(), 3);

        // Execute and verify results
        let ticket = TicketStatementQuery {
            statement_handle: result.handle.clone(),
        };
        let (schema, batches) = engine.get_statement_query_data(&ticket).await.unwrap();
        assert_eq!(schema.fields().len(), 3);

        let total_rows: usize = batches.iter().map(|b| b.num_rows()).sum();
        assert_eq!(total_rows, 25); // All 25 orders should have matching customers
    }

    #[tokio::test]
    async fn test_left_join() {
        let engine = create_fixture_engine().await;

        // LEFT JOIN - all customers, even those without orders
        let cmd = CommandStatementQuery {
            query: "SELECT c.customer_id, c.name, o.order_id FROM test.customers c LEFT JOIN test.orders o ON c.customer_id = o.customer_id ORDER BY c.customer_id, o.order_id".to_string(),
            transaction_id: None,
        };

        let result = engine.execute_statement_query(&cmd).await.unwrap();
        assert_eq!(result.schema.fields().len(), 3);

        let ticket = TicketStatementQuery {
            statement_handle: result.handle.clone(),
        };
        let (_, batches) = engine.get_statement_query_data(&ticket).await.unwrap();

        let total_rows: usize = batches.iter().map(|b| b.num_rows()).sum();
        // All customers have at least one order in our test data
        assert!(total_rows >= 10);
    }

    #[tokio::test]
    async fn test_right_join() {
        let engine = create_fixture_engine().await;

        let cmd = CommandStatementQuery {
            query: "SELECT c.name, o.order_id, o.amount FROM test.customers c RIGHT JOIN test.orders o ON c.customer_id = o.customer_id ORDER BY o.order_id".to_string(),
            transaction_id: None,
        };

        let result = engine.execute_statement_query(&cmd).await.unwrap();
        assert_eq!(result.schema.fields().len(), 3);

        let ticket = TicketStatementQuery {
            statement_handle: result.handle.clone(),
        };
        let (_, batches) = engine.get_statement_query_data(&ticket).await.unwrap();

        let total_rows: usize = batches.iter().map(|b| b.num_rows()).sum();
        assert_eq!(total_rows, 25); // All 25 orders
    }

    #[tokio::test]
    async fn test_full_outer_join() {
        let engine = create_fixture_engine().await;

        let cmd = CommandStatementQuery {
            query: "SELECT c.customer_id, c.name, o.order_id FROM test.customers c FULL OUTER JOIN test.orders o ON c.customer_id = o.customer_id ORDER BY c.customer_id".to_string(),
            transaction_id: None,
        };

        let result = engine.execute_statement_query(&cmd).await.unwrap();
        assert_eq!(result.schema.fields().len(), 3);

        let ticket = TicketStatementQuery {
            statement_handle: result.handle.clone(),
        };
        let (_, batches) = engine.get_statement_query_data(&ticket).await.unwrap();

        let total_rows: usize = batches.iter().map(|b| b.num_rows()).sum();
        // FULL OUTER JOIN includes all rows from both sides
        assert!(total_rows >= 25);
    }

    #[tokio::test]
    async fn test_multi_table_join() {
        let engine = create_fixture_engine().await;

        // Three-way join: customers -> orders -> products
        let cmd = CommandStatementQuery {
            query: "SELECT c.name, o.order_id, p.product_name, p.price FROM test.customers c INNER JOIN test.orders o ON c.customer_id = o.customer_id INNER JOIN test.products p ON o.order_id = p.order_id ORDER BY o.order_id, p.product_id".to_string(),
            transaction_id: None,
        };

        let result = engine.execute_statement_query(&cmd).await.unwrap();
        assert_eq!(result.schema.fields().len(), 4);

        let ticket = TicketStatementQuery {
            statement_handle: result.handle.clone(),
        };
        let (schema, batches) = engine.get_statement_query_data(&ticket).await.unwrap();

        // Verify schema columns
        let field_names: Vec<&str> = schema.fields().iter().map(|f| f.name().as_str()).collect();
        assert_eq!(
            field_names,
            vec!["name", "order_id", "product_name", "price"]
        );

        let total_rows: usize = batches.iter().map(|b| b.num_rows()).sum();
        assert_eq!(total_rows, 15); // 15 products linked to orders
    }

    #[tokio::test]
    async fn test_join_with_aggregate() {
        let engine = create_fixture_engine().await;

        // Join with GROUP BY and aggregation
        let cmd = CommandStatementQuery {
            query: "SELECT c.name, COUNT(o.order_id) as order_count, SUM(o.amount) as total_amount FROM test.customers c INNER JOIN test.orders o ON c.customer_id = o.customer_id GROUP BY c.name ORDER BY total_amount DESC".to_string(),
            transaction_id: None,
        };

        let result = engine.execute_statement_query(&cmd).await.unwrap();
        assert_eq!(result.schema.fields().len(), 3);

        let ticket = TicketStatementQuery {
            statement_handle: result.handle.clone(),
        };
        let (_, batches) = engine.get_statement_query_data(&ticket).await.unwrap();

        let total_rows: usize = batches.iter().map(|b| b.num_rows()).sum();
        assert_eq!(total_rows, 10); // 10 customers, each with aggregated data
    }

    #[tokio::test]
    async fn test_join_with_where_clause() {
        let engine = create_fixture_engine().await;

        let cmd = CommandStatementQuery {
            query: "SELECT c.name, o.order_id, o.amount FROM test.customers c INNER JOIN test.orders o ON c.customer_id = o.customer_id WHERE o.amount > 200 ORDER BY o.amount DESC".to_string(),
            transaction_id: None,
        };

        let result = engine.execute_statement_query(&cmd).await.unwrap();

        let ticket = TicketStatementQuery {
            statement_handle: result.handle.clone(),
        };
        let (_, batches) = engine.get_statement_query_data(&ticket).await.unwrap();

        let total_rows: usize = batches.iter().map(|b| b.num_rows()).sum();
        // Orders with amount > 200: (2, 250), (5, 300), (8, 200 excluded), (9, 500), etc.
        assert!(total_rows > 0);
        assert!(total_rows < 25); // Should filter out some orders
    }

    #[tokio::test]
    async fn test_self_join_existing_tables() {
        let engine = create_fixture_engine().await;

        // Self-join on test.integers to find pairs
        let cmd = CommandStatementQuery {
            query: "SELECT a.id as id1, b.id as id2, a.value + b.value as combined FROM test.integers a INNER JOIN test.integers b ON a.id < b.id WHERE a.id < 5 AND b.id < 5 ORDER BY a.id, b.id".to_string(),
            transaction_id: None,
        };

        let result = engine.execute_statement_query(&cmd).await.unwrap();
        assert_eq!(result.schema.fields().len(), 3);

        let ticket = TicketStatementQuery {
            statement_handle: result.handle.clone(),
        };
        let (_, batches) = engine.get_statement_query_data(&ticket).await.unwrap();

        let total_rows: usize = batches.iter().map(|b| b.num_rows()).sum();
        // Pairs where id1 < id2 and both < 5: (0,1), (0,2), (0,3), (0,4), (1,2), (1,3), (1,4), (2,3), (2,4), (3,4)
        assert_eq!(total_rows, 10);
    }

    // ==================== Subquery Tests ====================

    #[tokio::test]
    async fn test_scalar_subquery_in_select() {
        let engine = create_fixture_engine().await;

        // Scalar subquery in SELECT clause
        let cmd = CommandStatementQuery {
            query: "SELECT customer_id, name, (SELECT COUNT(*) FROM test.orders WHERE test.orders.customer_id = test.customers.customer_id) as order_count FROM test.customers ORDER BY customer_id".to_string(),
            transaction_id: None,
        };

        let result = engine.execute_statement_query(&cmd).await.unwrap();
        assert_eq!(result.schema.fields().len(), 3);

        let ticket = TicketStatementQuery {
            statement_handle: result.handle.clone(),
        };
        let (schema, batches) = engine.get_statement_query_data(&ticket).await.unwrap();

        let field_names: Vec<&str> = schema.fields().iter().map(|f| f.name().as_str()).collect();
        assert_eq!(field_names, vec!["customer_id", "name", "order_count"]);

        let total_rows: usize = batches.iter().map(|b| b.num_rows()).sum();
        assert_eq!(total_rows, 10); // 10 customers
    }

    #[tokio::test]
    async fn test_subquery_in_where_with_in() {
        let engine = create_fixture_engine().await;

        // Subquery in WHERE clause with IN
        let cmd = CommandStatementQuery {
            query: "SELECT customer_id, name FROM test.customers WHERE customer_id IN (SELECT DISTINCT customer_id FROM test.orders WHERE amount > 200) ORDER BY customer_id".to_string(),
            transaction_id: None,
        };

        let result = engine.execute_statement_query(&cmd).await.unwrap();
        assert_eq!(result.schema.fields().len(), 2);

        let ticket = TicketStatementQuery {
            statement_handle: result.handle.clone(),
        };
        let (_, batches) = engine.get_statement_query_data(&ticket).await.unwrap();

        let total_rows: usize = batches.iter().map(|b| b.num_rows()).sum();
        // Customers with orders > 200
        assert!(total_rows > 0);
        assert!(total_rows <= 10);
    }

    #[tokio::test]
    async fn test_subquery_in_where_with_exists() {
        let engine = create_fixture_engine().await;

        // Subquery in WHERE clause with EXISTS
        let cmd = CommandStatementQuery {
            query: "SELECT customer_id, name FROM test.customers WHERE EXISTS (SELECT 1 FROM test.orders WHERE test.orders.customer_id = test.customers.customer_id AND amount > 400) ORDER BY customer_id".to_string(),
            transaction_id: None,
        };

        let result = engine.execute_statement_query(&cmd).await.unwrap();
        assert_eq!(result.schema.fields().len(), 2);

        let ticket = TicketStatementQuery {
            statement_handle: result.handle.clone(),
        };
        let (_, batches) = engine.get_statement_query_data(&ticket).await.unwrap();

        let total_rows: usize = batches.iter().map(|b| b.num_rows()).sum();
        // Customers with orders > 400 (order 9 = 500, order 16 = 425)
        assert!(total_rows > 0);
    }

    #[tokio::test]
    async fn test_subquery_in_where_with_not_exists() {
        let engine = create_fixture_engine().await;

        // NOT EXISTS - but all customers have orders in our test data
        let cmd = CommandStatementQuery {
            query: "SELECT customer_id, name FROM test.customers WHERE NOT EXISTS (SELECT 1 FROM test.orders WHERE test.orders.customer_id = test.customers.customer_id AND amount > 1000) ORDER BY customer_id".to_string(),
            transaction_id: None,
        };

        let result = engine.execute_statement_query(&cmd).await.unwrap();

        let ticket = TicketStatementQuery {
            statement_handle: result.handle.clone(),
        };
        let (_, batches) = engine.get_statement_query_data(&ticket).await.unwrap();

        let total_rows: usize = batches.iter().map(|b| b.num_rows()).sum();
        // No orders > 1000, so all 10 customers should be returned
        assert_eq!(total_rows, 10);
    }

    #[tokio::test]
    async fn test_subquery_in_from_clause() {
        let engine = create_fixture_engine().await;

        // Derived table (subquery in FROM clause)
        let cmd = CommandStatementQuery {
            query: "SELECT sub.customer_id, sub.total_orders FROM (SELECT customer_id, COUNT(*) as total_orders FROM test.orders GROUP BY customer_id) as sub WHERE sub.total_orders > 2 ORDER BY sub.total_orders DESC".to_string(),
            transaction_id: None,
        };

        let result = engine.execute_statement_query(&cmd).await.unwrap();
        assert_eq!(result.schema.fields().len(), 2);

        let ticket = TicketStatementQuery {
            statement_handle: result.handle.clone(),
        };
        let (schema, batches) = engine.get_statement_query_data(&ticket).await.unwrap();

        let field_names: Vec<&str> = schema.fields().iter().map(|f| f.name().as_str()).collect();
        assert_eq!(field_names, vec!["customer_id", "total_orders"]);

        let total_rows: usize = batches.iter().map(|b| b.num_rows()).sum();
        // Customers with more than 2 orders
        assert!(total_rows > 0);
    }

    #[tokio::test]
    async fn test_subquery_with_comparison() {
        let engine = create_fixture_engine().await;

        // Subquery with comparison operator
        let cmd = CommandStatementQuery {
            query: "SELECT order_id, amount FROM test.orders WHERE amount > (SELECT AVG(amount) FROM test.orders) ORDER BY amount DESC".to_string(),
            transaction_id: None,
        };

        let result = engine.execute_statement_query(&cmd).await.unwrap();
        assert_eq!(result.schema.fields().len(), 2);

        let ticket = TicketStatementQuery {
            statement_handle: result.handle.clone(),
        };
        let (_, batches) = engine.get_statement_query_data(&ticket).await.unwrap();

        let total_rows: usize = batches.iter().map(|b| b.num_rows()).sum();
        // Orders above average
        assert!(total_rows > 0);
        assert!(total_rows < 25); // Not all orders
    }

    #[tokio::test]
    async fn test_nested_subquery() {
        let engine = create_fixture_engine().await;

        // Nested subquery
        let cmd = CommandStatementQuery {
            query: "SELECT name FROM test.customers WHERE customer_id IN (SELECT customer_id FROM test.orders WHERE order_id IN (SELECT order_id FROM test.products WHERE price > 100)) ORDER BY name".to_string(),
            transaction_id: None,
        };

        let result = engine.execute_statement_query(&cmd).await.unwrap();
        assert_eq!(result.schema.fields().len(), 1);

        let ticket = TicketStatementQuery {
            statement_handle: result.handle.clone(),
        };
        let (_, batches) = engine.get_statement_query_data(&ticket).await.unwrap();

        let total_rows: usize = batches.iter().map(|b| b.num_rows()).sum();
        // Customers with products priced > 100
        assert!(total_rows > 0);
    }

    // ==================== CTE (WITH clause) Tests ====================

    #[tokio::test]
    async fn test_simple_cte() {
        let engine = create_fixture_engine().await;

        // Simple CTE
        let cmd = CommandStatementQuery {
            query: "WITH high_value_orders AS (SELECT * FROM test.orders WHERE amount > 200) SELECT order_id, amount FROM high_value_orders ORDER BY amount DESC".to_string(),
            transaction_id: None,
        };

        let result = engine.execute_statement_query(&cmd).await.unwrap();
        assert_eq!(result.schema.fields().len(), 2);

        let ticket = TicketStatementQuery {
            statement_handle: result.handle.clone(),
        };
        let (schema, batches) = engine.get_statement_query_data(&ticket).await.unwrap();

        let field_names: Vec<&str> = schema.fields().iter().map(|f| f.name().as_str()).collect();
        assert_eq!(field_names, vec!["order_id", "amount"]);

        let total_rows: usize = batches.iter().map(|b| b.num_rows()).sum();
        // Orders with amount > 200
        assert!(total_rows > 0);
        assert!(total_rows < 25);
    }

    #[tokio::test]
    async fn test_cte_with_join() {
        let engine = create_fixture_engine().await;

        // CTE joined with another table
        let cmd = CommandStatementQuery {
            query: "WITH customer_totals AS (SELECT customer_id, SUM(amount) as total_spent FROM test.orders GROUP BY customer_id) SELECT c.name, ct.total_spent FROM test.customers c INNER JOIN customer_totals ct ON c.customer_id = ct.customer_id ORDER BY ct.total_spent DESC".to_string(),
            transaction_id: None,
        };

        let result = engine.execute_statement_query(&cmd).await.unwrap();
        assert_eq!(result.schema.fields().len(), 2);

        let ticket = TicketStatementQuery {
            statement_handle: result.handle.clone(),
        };
        let (schema, batches) = engine.get_statement_query_data(&ticket).await.unwrap();

        let field_names: Vec<&str> = schema.fields().iter().map(|f| f.name().as_str()).collect();
        assert_eq!(field_names, vec!["name", "total_spent"]);

        let total_rows: usize = batches.iter().map(|b| b.num_rows()).sum();
        assert_eq!(total_rows, 10); // 10 customers
    }

    #[tokio::test]
    async fn test_multiple_ctes() {
        let engine = create_fixture_engine().await;

        // Multiple CTEs
        let cmd = CommandStatementQuery {
            query: "WITH order_counts AS (SELECT customer_id, COUNT(*) as order_count FROM test.orders GROUP BY customer_id), order_totals AS (SELECT customer_id, SUM(amount) as total_amount FROM test.orders GROUP BY customer_id) SELECT c.name, oc.order_count, ot.total_amount FROM test.customers c INNER JOIN order_counts oc ON c.customer_id = oc.customer_id INNER JOIN order_totals ot ON c.customer_id = ot.customer_id ORDER BY ot.total_amount DESC".to_string(),
            transaction_id: None,
        };

        let result = engine.execute_statement_query(&cmd).await.unwrap();
        assert_eq!(result.schema.fields().len(), 3);

        let ticket = TicketStatementQuery {
            statement_handle: result.handle.clone(),
        };
        let (schema, batches) = engine.get_statement_query_data(&ticket).await.unwrap();

        let field_names: Vec<&str> = schema.fields().iter().map(|f| f.name().as_str()).collect();
        assert_eq!(field_names, vec!["name", "order_count", "total_amount"]);

        let total_rows: usize = batches.iter().map(|b| b.num_rows()).sum();
        assert_eq!(total_rows, 10);
    }

    #[tokio::test]
    async fn test_cte_with_aggregation() {
        let engine = create_fixture_engine().await;

        // CTE with aggregation in main query
        let cmd = CommandStatementQuery {
            query: "WITH large_orders AS (SELECT customer_id, amount FROM test.orders WHERE amount > 100) SELECT customer_id, COUNT(*) as large_order_count, AVG(amount) as avg_large_order FROM large_orders GROUP BY customer_id HAVING COUNT(*) > 1 ORDER BY avg_large_order DESC".to_string(),
            transaction_id: None,
        };

        let result = engine.execute_statement_query(&cmd).await.unwrap();
        assert_eq!(result.schema.fields().len(), 3);

        let ticket = TicketStatementQuery {
            statement_handle: result.handle.clone(),
        };
        let (_, batches) = engine.get_statement_query_data(&ticket).await.unwrap();

        let total_rows: usize = batches.iter().map(|b| b.num_rows()).sum();
        // Customers with more than 1 large order
        assert!(total_rows > 0);
    }

    #[tokio::test]
    async fn test_cte_referenced_multiple_times() {
        let engine = create_fixture_engine().await;

        // CTE referenced multiple times in the query
        let cmd = CommandStatementQuery {
            query: "WITH order_stats AS (SELECT customer_id, SUM(amount) as total, AVG(amount) as avg_amount FROM test.orders GROUP BY customer_id) SELECT s1.customer_id, s1.total, s1.avg_amount, (SELECT MAX(total) FROM order_stats) as max_total FROM order_stats s1 ORDER BY s1.total DESC".to_string(),
            transaction_id: None,
        };

        let result = engine.execute_statement_query(&cmd).await.unwrap();
        assert_eq!(result.schema.fields().len(), 4);

        let ticket = TicketStatementQuery {
            statement_handle: result.handle.clone(),
        };
        let (_, batches) = engine.get_statement_query_data(&ticket).await.unwrap();

        let total_rows: usize = batches.iter().map(|b| b.num_rows()).sum();
        assert_eq!(total_rows, 10);
    }

    #[tokio::test]
    async fn test_cte_with_subquery() {
        let engine = create_fixture_engine().await;

        // CTE combined with subquery
        let cmd = CommandStatementQuery {
            query: "WITH top_customers AS (SELECT customer_id FROM test.orders GROUP BY customer_id HAVING SUM(amount) > 300) SELECT name FROM test.customers WHERE customer_id IN (SELECT customer_id FROM top_customers) ORDER BY name".to_string(),
            transaction_id: None,
        };

        let result = engine.execute_statement_query(&cmd).await.unwrap();
        assert_eq!(result.schema.fields().len(), 1);

        let ticket = TicketStatementQuery {
            statement_handle: result.handle.clone(),
        };
        let (_, batches) = engine.get_statement_query_data(&ticket).await.unwrap();

        let total_rows: usize = batches.iter().map(|b| b.num_rows()).sum();
        // Customers with total orders > 300
        assert!(total_rows > 0);
    }

    #[tokio::test]
    async fn test_cte_column_aliasing() {
        let engine = create_fixture_engine().await;

        // CTE with explicit column aliases
        let cmd = CommandStatementQuery {
            query: "WITH customer_summary (cid, order_total) AS (SELECT customer_id, SUM(amount) FROM test.orders GROUP BY customer_id) SELECT cid, order_total FROM customer_summary WHERE order_total > 200 ORDER BY order_total DESC".to_string(),
            transaction_id: None,
        };

        let result = engine.execute_statement_query(&cmd).await.unwrap();
        assert_eq!(result.schema.fields().len(), 2);

        let ticket = TicketStatementQuery {
            statement_handle: result.handle.clone(),
        };
        let (schema, batches) = engine.get_statement_query_data(&ticket).await.unwrap();

        let field_names: Vec<&str> = schema.fields().iter().map(|f| f.name().as_str()).collect();
        assert_eq!(field_names, vec!["cid", "order_total"]);

        let total_rows: usize = batches.iter().map(|b| b.num_rows()).sum();
        assert!(total_rows > 0);
    }

    // Note: DataFusion does not currently support ALL and ANY operators with
    // comparison operators other than '='. Use workarounds with MAX/MIN aggregates
    // or IN/EXISTS clauses instead.

    #[tokio::test]
    async fn test_execute_insert_statement() {
        let engine = create_test_engine().await;

        let cmd = CommandStatementUpdate {
            query: "INSERT INTO test.table (id, value) VALUES (4, 40)".to_string(),
            transaction_id: None,
        };

        let result = engine.execute_statement_update(&cmd).await.unwrap();
        assert_eq!(result.record_count, 1);
    }

    #[tokio::test]
    async fn test_execute_insert_multiple_rows() {
        let engine = create_test_engine().await;

        let cmd = CommandStatementUpdate {
            query: "INSERT INTO test.table (id, value) VALUES (4, 40), (5, 50), (6, 60)"
                .to_string(),
            transaction_id: None,
        };

        let result = engine.execute_statement_update(&cmd).await.unwrap();
        assert_eq!(result.record_count, 3);
    }

    #[tokio::test]
    async fn test_execute_update_all_rows() {
        let engine = create_test_engine().await;

        let cmd = CommandStatementUpdate {
            query: "UPDATE test.table SET value = 100".to_string(),
            transaction_id: None,
        };

        let result = engine.execute_statement_update(&cmd).await.unwrap();
        // All 3 rows should be affected
        assert_eq!(result.record_count, 3);
    }

    #[tokio::test]
    async fn test_execute_update_with_where() {
        let engine = create_test_engine().await;

        let cmd = CommandStatementUpdate {
            query: "UPDATE test.table SET value = 100 WHERE id = 1".to_string(),
            transaction_id: None,
        };

        let result = engine.execute_statement_update(&cmd).await.unwrap();
        // Partial update - simulated as half of 3 rows = 1
        assert_eq!(result.record_count, 1);
    }

    #[tokio::test]
    async fn test_execute_delete_all_rows() {
        let engine = create_test_engine().await;

        let cmd = CommandStatementUpdate {
            query: "DELETE FROM test.table".to_string(),
            transaction_id: None,
        };

        let result = engine.execute_statement_update(&cmd).await.unwrap();
        // All 3 rows would be deleted
        assert_eq!(result.record_count, 3);
    }

    #[tokio::test]
    async fn test_execute_delete_with_where() {
        let engine = create_test_engine().await;

        let cmd = CommandStatementUpdate {
            query: "DELETE FROM test.table WHERE id > 1".to_string(),
            transaction_id: None,
        };

        let result = engine.execute_statement_update(&cmd).await.unwrap();
        // Rows with id 2 and 3 are deleted
        assert_eq!(result.record_count, 2);
    }

    #[tokio::test]
    async fn test_update_table_not_found() {
        let engine = create_test_engine().await;

        let cmd = CommandStatementUpdate {
            query: "UPDATE nonexistent SET value = 1".to_string(),
            transaction_id: None,
        };

        let result = engine.execute_statement_update(&cmd).await;
        assert!(matches!(result, Err(SqlError::TableNotFound(_))));
    }

    #[tokio::test]
    async fn test_invalid_update_syntax() {
        let engine = create_test_engine().await;

        // Test with invalid SQL that doesn't match any known statement type
        let cmd = CommandStatementUpdate {
            query: "INVALID_COMMAND test.table".to_string(),
            transaction_id: None,
        };

        let result = engine.execute_statement_update(&cmd).await;
        assert!(matches!(result, Err(SqlError::SyntaxError(_))));
    }

    #[tokio::test]
    async fn test_create_prepared_statement_select() {
        let engine = create_test_engine().await;

        let request = ActionCreatePreparedStatementRequest {
            query: "SELECT * FROM test.\"table\"".to_string(),
            transaction_id: None,
        };

        let result = engine.create_prepared_statement(&request).await.unwrap();
        assert!(!result.handle.is_empty());
        assert!(result.dataset_schema.is_some());
        assert!(result.parameter_schema.is_some());

        // Schema should have 2 fields
        let schema = result.dataset_schema.unwrap();
        assert_eq!(schema.fields().len(), 2);
    }

    #[tokio::test]
    async fn test_create_prepared_statement_insert() {
        let engine = create_test_engine().await;

        let request = ActionCreatePreparedStatementRequest {
            query: "INSERT INTO test.table (id, value) VALUES (?, ?)".to_string(),
            transaction_id: None,
        };

        let result = engine.create_prepared_statement(&request).await.unwrap();
        assert!(!result.handle.is_empty());
        // INSERT doesn't return result schema
        assert!(result.dataset_schema.is_none());
        assert!(result.parameter_schema.is_some());
    }

    #[tokio::test]
    async fn test_create_prepared_statement_table_not_found() {
        let engine = create_test_engine().await;

        let request = ActionCreatePreparedStatementRequest {
            query: "SELECT * FROM nonexistent".to_string(),
            transaction_id: None,
        };

        let result = engine.create_prepared_statement(&request).await;
        assert!(matches!(result, Err(SqlError::QueryExecution(_))));
    }

    #[tokio::test]
    async fn test_execute_prepared_statement_query() {
        let engine = create_test_engine().await;

        // First create the prepared statement
        let create_request = ActionCreatePreparedStatementRequest {
            query: "SELECT * FROM test.\"table\"".to_string(),
            transaction_id: None,
        };
        let create_result = engine
            .create_prepared_statement(&create_request)
            .await
            .unwrap();

        // Then execute it
        let execute_cmd = CommandPreparedStatementQuery {
            prepared_statement_handle: create_result.handle.clone(),
        };
        let execute_result = engine
            .execute_prepared_statement_query(&execute_cmd)
            .await
            .unwrap();

        // DataFusion returns -1 for total_records until execution
        assert_eq!(execute_result.total_records, -1);
        assert_eq!(execute_result.schema.fields().len(), 2);
    }

    #[tokio::test]
    async fn test_execute_prepared_statement_not_found() {
        let engine = create_test_engine().await;

        let cmd = CommandPreparedStatementQuery {
            prepared_statement_handle: bytes::Bytes::from("nonexistent"),
        };

        let result = engine.execute_prepared_statement_query(&cmd).await;
        assert!(matches!(
            result,
            Err(SqlError::PreparedStatementNotFound(_))
        ));
    }

    #[tokio::test]
    async fn test_close_prepared_statement() {
        let engine = create_test_engine().await;

        // Create a prepared statement
        let create_request = ActionCreatePreparedStatementRequest {
            query: "SELECT * FROM test.\"table\"".to_string(),
            transaction_id: None,
        };
        let create_result = engine
            .create_prepared_statement(&create_request)
            .await
            .unwrap();

        // Close it
        let close_request = ActionClosePreparedStatementRequest {
            prepared_statement_handle: create_result.handle.clone(),
        };
        engine.close_prepared_statement(&close_request).unwrap();

        // Trying to execute should fail
        let execute_cmd = CommandPreparedStatementQuery {
            prepared_statement_handle: create_result.handle,
        };
        let result = engine.execute_prepared_statement_query(&execute_cmd).await;
        assert!(matches!(
            result,
            Err(SqlError::PreparedStatementNotFound(_))
        ));
    }

    #[tokio::test]
    async fn test_close_nonexistent_prepared_statement() {
        let engine = create_test_engine().await;

        // Closing a non-existent statement should succeed (per Flight SQL spec)
        let request = ActionClosePreparedStatementRequest {
            prepared_statement_handle: bytes::Bytes::from("nonexistent"),
        };

        // Should not error
        engine.close_prepared_statement(&request).unwrap();
    }

    #[tokio::test]
    async fn test_get_prepared_statement_data() {
        let engine = create_test_engine().await;

        // Create a prepared statement
        let create_request = ActionCreatePreparedStatementRequest {
            query: "SELECT * FROM test.\"table\"".to_string(),
            transaction_id: None,
        };
        let create_result = engine
            .create_prepared_statement(&create_request)
            .await
            .unwrap();

        // Get the data
        let (schema, batches) = engine
            .get_prepared_statement_data(&create_result.handle)
            .await
            .unwrap();

        assert_eq!(schema.fields().len(), 2);
        assert_eq!(batches.len(), 1);
        assert_eq!(batches[0].num_rows(), 3);
    }

    #[tokio::test]
    async fn test_execute_prepared_statement_update_insert() {
        let engine = create_test_engine().await;

        // Create a prepared INSERT statement
        let create_request = ActionCreatePreparedStatementRequest {
            query: "INSERT INTO test.table (id, value) VALUES (4, 40), (5, 50)".to_string(),
            transaction_id: None,
        };
        let create_result = engine
            .create_prepared_statement(&create_request)
            .await
            .unwrap();

        // Execute the prepared update
        let execute_cmd = CommandPreparedStatementUpdate {
            prepared_statement_handle: create_result.handle,
        };
        let result = engine
            .execute_prepared_statement_update(&execute_cmd)
            .await
            .unwrap();

        assert_eq!(result.record_count, 2);
    }

    #[tokio::test]
    async fn test_execute_prepared_statement_update_update() {
        let engine = create_test_engine().await;

        // Create a prepared UPDATE statement
        let create_request = ActionCreatePreparedStatementRequest {
            query: "UPDATE test.table SET value = 100".to_string(),
            transaction_id: None,
        };
        let create_result = engine
            .create_prepared_statement(&create_request)
            .await
            .unwrap();

        // Execute the prepared update
        let execute_cmd = CommandPreparedStatementUpdate {
            prepared_statement_handle: create_result.handle,
        };
        let result = engine
            .execute_prepared_statement_update(&execute_cmd)
            .await
            .unwrap();

        // Should affect all 3 rows
        assert_eq!(result.record_count, 3);
    }

    #[tokio::test]
    async fn test_execute_prepared_statement_update_delete() {
        let engine = create_test_engine().await;

        // Create a prepared DELETE statement
        let create_request = ActionCreatePreparedStatementRequest {
            query: "DELETE FROM test.table WHERE id > 1".to_string(),
            transaction_id: None,
        };
        let create_result = engine
            .create_prepared_statement(&create_request)
            .await
            .unwrap();

        // Execute the prepared update
        let execute_cmd = CommandPreparedStatementUpdate {
            prepared_statement_handle: create_result.handle,
        };
        let result = engine
            .execute_prepared_statement_update(&execute_cmd)
            .await
            .unwrap();

        // DELETE WHERE id > 1 should remove rows with id 2 and 3
        assert_eq!(result.record_count, 2);
    }

    #[tokio::test]
    async fn test_execute_prepared_statement_update_on_query_fails() {
        let engine = create_test_engine().await;

        // Create a prepared SELECT statement (query, not update)
        let create_request = ActionCreatePreparedStatementRequest {
            query: "SELECT * FROM test.\"table\"".to_string(),
            transaction_id: None,
        };
        let create_result = engine
            .create_prepared_statement(&create_request)
            .await
            .unwrap();

        // Try to execute it as an update
        let execute_cmd = CommandPreparedStatementUpdate {
            prepared_statement_handle: create_result.handle,
        };
        let result = engine.execute_prepared_statement_update(&execute_cmd).await;

        assert!(matches!(result, Err(SqlError::InvalidCommand(_))));
    }

    #[tokio::test]
    async fn test_execute_prepared_statement_update_not_found() {
        let engine = create_test_engine().await;

        let cmd = CommandPreparedStatementUpdate {
            prepared_statement_handle: bytes::Bytes::from("nonexistent"),
        };

        let result = engine.execute_prepared_statement_update(&cmd).await;
        assert!(matches!(
            result,
            Err(SqlError::PreparedStatementNotFound(_))
        ));
    }

    #[tokio::test]
    async fn test_bind_parameters() {
        use arrow_array::Int64Array;
        use arrow_schema::{DataType, Field, Schema};

        let engine = create_test_engine().await;

        // Create a prepared statement
        let create_request = ActionCreatePreparedStatementRequest {
            query: "SELECT * FROM test.\"table\"".to_string(),
            transaction_id: None,
        };
        let create_result = engine
            .create_prepared_statement(&create_request)
            .await
            .unwrap();
        let handle = create_result.handle;

        // Create parameter batch
        let param_schema = Arc::new(Schema::new(vec![Field::new(
            "param1",
            DataType::Int64,
            false,
        )]));
        let param_batch =
            RecordBatch::try_new(param_schema, vec![Arc::new(Int64Array::from(vec![42]))]).unwrap();

        // Bind parameters
        engine
            .bind_parameters(&handle, vec![Arc::new(param_batch)])
            .unwrap();

        // Verify parameters are bound
        let bound = engine.get_bound_parameters(&handle).unwrap();
        assert!(bound.is_some());
        let batches = bound.unwrap();
        assert_eq!(batches.len(), 1);
        assert_eq!(batches[0].num_rows(), 1);
    }

    #[tokio::test]
    async fn test_bind_parameters_not_found() {
        let engine = create_test_engine().await;

        let result = engine.bind_parameters(&bytes::Bytes::from("nonexistent"), vec![]);
        assert!(matches!(
            result,
            Err(SqlError::PreparedStatementNotFound(_))
        ));
    }

    #[tokio::test]
    async fn test_get_bound_parameters_none_initially() {
        let engine = create_test_engine().await;

        // Create a prepared statement
        let create_request = ActionCreatePreparedStatementRequest {
            query: "SELECT * FROM test.\"table\"".to_string(),
            transaction_id: None,
        };
        let create_result = engine
            .create_prepared_statement(&create_request)
            .await
            .unwrap();

        // Initially no parameters bound
        let bound = engine.get_bound_parameters(&create_result.handle).unwrap();
        assert!(bound.is_none());
    }

    #[tokio::test]
    async fn test_begin_transaction() {
        let engine = create_test_engine().await;

        let transaction_id = engine.begin_transaction().unwrap();
        assert!(!transaction_id.is_empty());
        // Transaction IDs should be unique
        let transaction_id2 = engine.begin_transaction().unwrap();
        assert_ne!(transaction_id, transaction_id2);
    }

    #[tokio::test]
    async fn test_end_transaction_commit() {
        let engine = create_test_engine().await;

        let transaction_id = engine.begin_transaction().unwrap();
        engine
            .end_transaction(&transaction_id, EndTransaction::Commit)
            .unwrap();
    }

    #[tokio::test]
    async fn test_end_transaction_rollback() {
        let engine = create_test_engine().await;

        let transaction_id = engine.begin_transaction().unwrap();
        engine
            .end_transaction(&transaction_id, EndTransaction::Rollback)
            .unwrap();
    }

    #[tokio::test]
    async fn test_end_transaction_not_found() {
        let engine = create_test_engine().await;

        let result =
            engine.end_transaction(&bytes::Bytes::from("nonexistent"), EndTransaction::Commit);
        assert!(matches!(result, Err(SqlError::TransactionNotFound(_))));
    }

    #[tokio::test]
    async fn test_end_transaction_unspecified_fails() {
        let engine = create_test_engine().await;

        let transaction_id = engine.begin_transaction().unwrap();
        let result = engine.end_transaction(&transaction_id, EndTransaction::Unspecified);
        assert!(matches!(result, Err(SqlError::InvalidTransactionAction(_))));
    }

    #[tokio::test]
    async fn test_end_transaction_twice_fails() {
        let engine = create_test_engine().await;

        let transaction_id = engine.begin_transaction().unwrap();
        engine
            .end_transaction(&transaction_id, EndTransaction::Commit)
            .unwrap();

        // Ending the same transaction again should fail (transaction removed)
        let result = engine.end_transaction(&transaction_id, EndTransaction::Commit);
        assert!(matches!(result, Err(SqlError::TransactionNotFound(_))));
    }

    #[tokio::test]
    async fn test_transaction_buffers_update() {
        let engine = create_test_engine().await;

        let transaction_id = engine.begin_transaction().unwrap();

        // Execute an update within the transaction
        let cmd = CommandStatementUpdate {
            query: "INSERT INTO test.table (id, value) VALUES (4, 40)".to_string(),
            transaction_id: Some(transaction_id.clone()),
        };
        let result = engine.execute_statement_update(&cmd).await.unwrap();
        assert_eq!(result.record_count, 1);

        // Check pending operations count
        let pending = engine.get_pending_operation_count(&transaction_id).unwrap();
        assert_eq!(pending, 1);

        // Execute another update
        let cmd2 = CommandStatementUpdate {
            query: "UPDATE test.table SET value = 100".to_string(),
            transaction_id: Some(transaction_id.clone()),
        };
        engine.execute_statement_update(&cmd2).await.unwrap();

        // Check pending operations count increased
        let pending = engine.get_pending_operation_count(&transaction_id).unwrap();
        assert_eq!(pending, 2);

        // Commit should succeed
        engine
            .end_transaction(&transaction_id, EndTransaction::Commit)
            .unwrap();
    }

    #[tokio::test]
    async fn test_transaction_rollback_discards_operations() {
        let engine = create_test_engine().await;

        let transaction_id = engine.begin_transaction().unwrap();

        // Execute updates within the transaction
        let cmd1 = CommandStatementUpdate {
            query: "INSERT INTO test.table (id, value) VALUES (5, 50)".to_string(),
            transaction_id: Some(transaction_id.clone()),
        };
        engine.execute_statement_update(&cmd1).await.unwrap();

        let cmd2 = CommandStatementUpdate {
            query: "DELETE FROM test.table WHERE id = 1".to_string(),
            transaction_id: Some(transaction_id.clone()),
        };
        engine.execute_statement_update(&cmd2).await.unwrap();

        // Check pending operations count
        let pending = engine.get_pending_operation_count(&transaction_id).unwrap();
        assert_eq!(pending, 2);

        // Rollback discards operations
        engine
            .end_transaction(&transaction_id, EndTransaction::Rollback)
            .unwrap();

        // Transaction is gone
        let result = engine.get_pending_operation_count(&transaction_id);
        assert!(matches!(result, Err(SqlError::TransactionNotFound(_))));
    }

    #[tokio::test]
    async fn test_transaction_update_fails_for_invalid_transaction() {
        let engine = create_test_engine().await;

        // Try to execute update with non-existent transaction ID
        let cmd = CommandStatementUpdate {
            query: "INSERT INTO test.table (id, value) VALUES (6, 60)".to_string(),
            transaction_id: Some(bytes::Bytes::from("nonexistent_txn")),
        };
        let result = engine.execute_statement_update(&cmd).await;
        assert!(matches!(result, Err(SqlError::TransactionNotFound(_))));
    }

    #[tokio::test]
    async fn test_auto_commit_without_transaction_id() {
        let engine = create_test_engine().await;

        // Execute update without transaction ID (auto-commit mode)
        let cmd = CommandStatementUpdate {
            query: "INSERT INTO test.table (id, value) VALUES (7, 70)".to_string(),
            transaction_id: None,
        };
        let result = engine.execute_statement_update(&cmd).await.unwrap();
        assert_eq!(result.record_count, 1);
        // No transaction to check - this is auto-committed
    }

    // ===== DDL Tests =====

    #[tokio::test]
    async fn test_create_table() {
        let store = create_test_store().await;
        let engine = SqlEngine::new(store.clone(), DEFAULT_CATALOG, DEFAULT_SCHEMA).await;

        let cmd = CommandStatementUpdate {
            query: "CREATE TABLE new_table AS SELECT 1 as id, 'test' as name".to_string(),
            transaction_id: None,
        };
        let result = engine.execute_statement_update(&cmd).await.unwrap();
        assert_eq!(result.record_count, 1);

        // Verify the table was created
        let path = DataPath::new(vec!["new_table".to_string()]);
        assert!(store.contains(&path).await);
    }

    #[tokio::test]
    async fn test_create_table_qualified_name() {
        let store = create_test_store().await;
        let engine = SqlEngine::new(store.clone(), DEFAULT_CATALOG, DEFAULT_SCHEMA).await;

        let cmd = CommandStatementUpdate {
            query: "CREATE TABLE myschema.mytable AS SELECT 1 as id".to_string(),
            transaction_id: None,
        };
        let result = engine.execute_statement_update(&cmd).await.unwrap();
        assert_eq!(result.record_count, 1);

        // Verify the table was created with qualified path
        let path = DataPath::new(vec!["myschema".to_string(), "mytable".to_string()]);
        assert!(store.contains(&path).await);
    }

    #[tokio::test]
    async fn test_create_table_if_not_exists() {
        let store = create_test_store().await;
        let engine = SqlEngine::new(store.clone(), DEFAULT_CATALOG, DEFAULT_SCHEMA).await;

        // First create
        let cmd = CommandStatementUpdate {
            query: "CREATE TABLE new_table AS SELECT 1 as id".to_string(),
            transaction_id: None,
        };
        engine.execute_statement_update(&cmd).await.unwrap();

        // Second create with IF NOT EXISTS should not error
        let cmd = CommandStatementUpdate {
            query: "CREATE TABLE IF NOT EXISTS new_table AS SELECT 1 as id".to_string(),
            transaction_id: None,
        };
        let result = engine.execute_statement_update(&cmd).await.unwrap();
        assert_eq!(result.record_count, 0); // 0 because table already exists
    }

    #[tokio::test]
    async fn test_create_table_already_exists_error() {
        let store = create_test_store().await;
        let engine = SqlEngine::new(store.clone(), DEFAULT_CATALOG, DEFAULT_SCHEMA).await;

        // First create
        let cmd = CommandStatementUpdate {
            query: "CREATE TABLE new_table AS SELECT 1 as id".to_string(),
            transaction_id: None,
        };
        engine.execute_statement_update(&cmd).await.unwrap();

        // Second create without IF NOT EXISTS should error
        let cmd = CommandStatementUpdate {
            query: "CREATE TABLE new_table AS SELECT 2 as id".to_string(),
            transaction_id: None,
        };
        let result = engine.execute_statement_update(&cmd).await;
        assert!(matches!(result, Err(SqlError::TableAlreadyExists(_))));
    }

    #[tokio::test]
    async fn test_create_table_or_replace() {
        let store = create_test_store().await;
        let engine = SqlEngine::new(store.clone(), DEFAULT_CATALOG, DEFAULT_SCHEMA).await;

        // First create
        let cmd = CommandStatementUpdate {
            query: "CREATE TABLE new_table AS SELECT 1 as id".to_string(),
            transaction_id: None,
        };
        engine.execute_statement_update(&cmd).await.unwrap();

        // Create OR REPLACE should succeed
        let cmd = CommandStatementUpdate {
            query: "CREATE OR REPLACE TABLE new_table AS SELECT 2 as id".to_string(),
            transaction_id: None,
        };
        let result = engine.execute_statement_update(&cmd).await.unwrap();
        assert_eq!(result.record_count, 1);
    }

    #[tokio::test]
    async fn test_drop_table() {
        let store = create_test_store().await;
        let engine = SqlEngine::new(store.clone(), DEFAULT_CATALOG, DEFAULT_SCHEMA).await;

        // Create a table first
        let cmd = CommandStatementUpdate {
            query: "CREATE TABLE temp_table AS SELECT 1 as id".to_string(),
            transaction_id: None,
        };
        engine.execute_statement_update(&cmd).await.unwrap();

        let path = DataPath::new(vec!["temp_table".to_string()]);
        assert!(store.contains(&path).await);

        // Drop the table
        let cmd = CommandStatementUpdate {
            query: "DROP TABLE temp_table".to_string(),
            transaction_id: None,
        };
        let result = engine.execute_statement_update(&cmd).await.unwrap();
        assert_eq!(result.record_count, 0);

        // Verify the table is gone
        assert!(!store.contains(&path).await);
    }

    #[tokio::test]
    async fn test_drop_table_qualified_name() {
        let store = create_test_store().await;
        let engine = SqlEngine::new(store.clone(), DEFAULT_CATALOG, DEFAULT_SCHEMA).await;

        // Create a table with qualified name
        let cmd = CommandStatementUpdate {
            query: "CREATE TABLE myschema.temp AS SELECT 1 as id".to_string(),
            transaction_id: None,
        };
        engine.execute_statement_update(&cmd).await.unwrap();

        let path = DataPath::new(vec!["myschema".to_string(), "temp".to_string()]);
        assert!(store.contains(&path).await);

        // Drop the table with qualified name
        let cmd = CommandStatementUpdate {
            query: "DROP TABLE myschema.temp".to_string(),
            transaction_id: None,
        };
        engine.execute_statement_update(&cmd).await.unwrap();

        assert!(!store.contains(&path).await);
    }

    #[tokio::test]
    async fn test_drop_table_if_exists() {
        let engine = create_test_engine().await;

        // Drop non-existent table with IF EXISTS should not error
        let cmd = CommandStatementUpdate {
            query: "DROP TABLE IF EXISTS nonexistent".to_string(),
            transaction_id: None,
        };
        let result = engine.execute_statement_update(&cmd).await.unwrap();
        assert_eq!(result.record_count, 0);
    }

    #[tokio::test]
    async fn test_drop_table_not_found() {
        let engine = create_test_engine().await;

        // Drop non-existent table without IF EXISTS should error
        let cmd = CommandStatementUpdate {
            query: "DROP TABLE nonexistent".to_string(),
            transaction_id: None,
        };
        let result = engine.execute_statement_update(&cmd).await;
        assert!(matches!(result, Err(SqlError::TableNotFound(_))));
    }

    // ===== Introspection Tests =====

    #[tokio::test]
    async fn test_show_tables() {
        let engine = create_test_engine().await;

        let cmd = CommandStatementQuery {
            query: "SHOW TABLES".to_string(),
            transaction_id: None,
        };
        let result = engine.execute_statement_query(&cmd).await.unwrap();
        assert!(!result.schema.fields().is_empty());
    }

    #[tokio::test]
    async fn test_show_tables_returns_data() {
        let engine = create_test_engine().await;

        // Execute SHOW TABLES and get data
        let cmd = CommandStatementQuery {
            query: "SHOW TABLES".to_string(),
            transaction_id: None,
        };
        let query_result = engine.execute_statement_query(&cmd).await.unwrap();

        let ticket = TicketStatementQuery {
            statement_handle: query_result.handle,
        };
        let (schema, batches) = engine.get_statement_query_data(&ticket).await.unwrap();

        // Should have at least the test table
        assert!(!schema.fields().is_empty());
        let total_rows: usize = batches.iter().map(|b| b.num_rows()).sum();
        assert!(total_rows >= 1, "Should have at least one table");
    }

    #[tokio::test]
    async fn test_show_schemas() {
        let engine = create_test_engine().await;

        let cmd = CommandStatementQuery {
            query: "SHOW SCHEMAS".to_string(),
            transaction_id: None,
        };
        let result = engine.execute_statement_query(&cmd).await;
        // DataFusion may not support SHOW SCHEMAS directly - that's okay
        // Check it returns a result (could be error if not supported)
        if let Ok(query_result) = result {
            assert!(!query_result.schema.fields().is_empty());
        }
    }

    #[tokio::test]
    async fn test_information_schema_tables() {
        let engine = create_test_engine().await;

        let cmd = CommandStatementQuery {
            query: "SELECT * FROM information_schema.tables".to_string(),
            transaction_id: None,
        };
        let result = engine.execute_statement_query(&cmd).await.unwrap();
        assert!(!result.schema.fields().is_empty());

        // Get the data
        let ticket = TicketStatementQuery {
            statement_handle: result.handle,
        };
        let (_, batches) = engine.get_statement_query_data(&ticket).await.unwrap();
        let total_rows: usize = batches.iter().map(|b| b.num_rows()).sum();
        assert!(
            total_rows >= 1,
            "Should have at least one table in information_schema.tables"
        );
    }

    #[tokio::test]
    async fn test_information_schema_columns() {
        let engine = create_test_engine().await;

        let cmd = CommandStatementQuery {
            query: "SELECT * FROM information_schema.columns WHERE table_name = 'table'"
                .to_string(),
            transaction_id: None,
        };
        let result = engine.execute_statement_query(&cmd).await.unwrap();
        assert!(!result.schema.fields().is_empty());

        // Get the data
        let ticket = TicketStatementQuery {
            statement_handle: result.handle,
        };
        let (_, batches) = engine.get_statement_query_data(&ticket).await.unwrap();
        let total_rows: usize = batches.iter().map(|b| b.num_rows()).sum();
        // Should have columns from test.table (id and value)
        assert!(total_rows >= 2, "Should have at least 2 columns");
    }

    #[tokio::test]
    async fn test_information_schema_schemata() {
        let engine = create_test_engine().await;

        let cmd = CommandStatementQuery {
            query: "SELECT * FROM information_schema.schemata".to_string(),
            transaction_id: None,
        };
        let result = engine.execute_statement_query(&cmd).await.unwrap();
        assert!(!result.schema.fields().is_empty());
    }

    #[tokio::test]
    async fn test_describe_table() {
        let engine = create_test_engine().await;

        // DESCRIBE is typically implemented via information_schema
        let cmd = CommandStatementQuery {
            query: "SELECT column_name, data_type FROM information_schema.columns WHERE table_schema = 'test' AND table_name = 'table'".to_string(),
            transaction_id: None,
        };
        let result = engine.execute_statement_query(&cmd).await.unwrap();
        assert!(!result.schema.fields().is_empty());

        let ticket = TicketStatementQuery {
            statement_handle: result.handle,
        };
        let (_, batches) = engine.get_statement_query_data(&ticket).await.unwrap();
        let total_rows: usize = batches.iter().map(|b| b.num_rows()).sum();
        assert!(total_rows >= 2, "test.table should have at least 2 columns");
    }

    // ===== Query Features Tests =====

    #[tokio::test]
    async fn test_select_distinct() {
        let engine = create_test_engine().await;

        let cmd = CommandStatementQuery {
            query: "SELECT DISTINCT value FROM test.\"table\"".to_string(),
            transaction_id: None,
        };
        let result = engine.execute_statement_query(&cmd).await.unwrap();
        assert!(!result.schema.fields().is_empty());
    }

    #[tokio::test]
    async fn test_select_limit() {
        let engine = create_test_engine().await;

        let cmd = CommandStatementQuery {
            query: "SELECT * FROM test.\"table\" LIMIT 2".to_string(),
            transaction_id: None,
        };
        let query_result = engine.execute_statement_query(&cmd).await.unwrap();

        let ticket = TicketStatementQuery {
            statement_handle: query_result.handle,
        };
        let (_, batches) = engine.get_statement_query_data(&ticket).await.unwrap();
        let total_rows: usize = batches.iter().map(|b| b.num_rows()).sum();
        assert!(total_rows <= 2, "LIMIT 2 should return at most 2 rows");
    }

    #[tokio::test]
    async fn test_select_limit_offset() {
        let engine = create_test_engine().await;

        let cmd = CommandStatementQuery {
            query: "SELECT * FROM test.\"table\" LIMIT 1 OFFSET 1".to_string(),
            transaction_id: None,
        };
        let query_result = engine.execute_statement_query(&cmd).await.unwrap();

        let ticket = TicketStatementQuery {
            statement_handle: query_result.handle,
        };
        let (_, batches) = engine.get_statement_query_data(&ticket).await.unwrap();
        let total_rows: usize = batches.iter().map(|b| b.num_rows()).sum();
        assert!(
            total_rows <= 1,
            "LIMIT 1 OFFSET 1 should return at most 1 row"
        );
    }

    #[tokio::test]
    async fn test_union() {
        let engine = create_test_engine().await;

        let cmd = CommandStatementQuery {
            query: "SELECT id FROM test.\"table\" WHERE id = 1 UNION SELECT id FROM test.\"table\" WHERE id = 2".to_string(),
            transaction_id: None,
        };
        let result = engine.execute_statement_query(&cmd).await.unwrap();
        assert!(!result.schema.fields().is_empty());
    }

    #[tokio::test]
    async fn test_union_all() {
        let engine = create_test_engine().await;

        let cmd = CommandStatementQuery {
            query: "SELECT id FROM test.\"table\" UNION ALL SELECT id FROM test.\"table\""
                .to_string(),
            transaction_id: None,
        };
        let result = engine.execute_statement_query(&cmd).await.unwrap();
        assert!(!result.schema.fields().is_empty());
    }

    #[tokio::test]
    async fn test_intersect() {
        let engine = create_test_engine().await;

        let cmd = CommandStatementQuery {
            query: "SELECT id FROM test.\"table\" INTERSECT SELECT id FROM test.\"table\""
                .to_string(),
            transaction_id: None,
        };
        let result = engine.execute_statement_query(&cmd).await.unwrap();
        assert!(!result.schema.fields().is_empty());
    }

    #[tokio::test]
    async fn test_except() {
        let engine = create_test_engine().await;

        let cmd = CommandStatementQuery {
            query:
                "SELECT id FROM test.\"table\" EXCEPT SELECT id FROM test.\"table\" WHERE id = 1"
                    .to_string(),
            transaction_id: None,
        };
        let result = engine.execute_statement_query(&cmd).await.unwrap();
        assert!(!result.schema.fields().is_empty());
    }

    #[tokio::test]
    async fn test_case_expression() {
        let engine = create_test_engine().await;

        let cmd = CommandStatementQuery {
            query: "SELECT id, CASE WHEN value > 15 THEN 'high' ELSE 'low' END as category FROM test.\"table\"".to_string(),
            transaction_id: None,
        };
        let result = engine.execute_statement_query(&cmd).await.unwrap();
        assert_eq!(result.schema.fields().len(), 2);
    }

    #[tokio::test]
    async fn test_window_function_row_number() {
        let engine = create_test_engine().await;

        let cmd = CommandStatementQuery {
            query: "SELECT id, ROW_NUMBER() OVER (ORDER BY id) as rn FROM test.\"table\""
                .to_string(),
            transaction_id: None,
        };
        let result = engine.execute_statement_query(&cmd).await.unwrap();
        assert_eq!(result.schema.fields().len(), 2);
    }

    #[tokio::test]
    async fn test_window_function_rank() {
        let engine = create_test_engine().await;

        let cmd = CommandStatementQuery {
            query: "SELECT id, RANK() OVER (ORDER BY value) as rnk FROM test.\"table\"".to_string(),
            transaction_id: None,
        };
        let result = engine.execute_statement_query(&cmd).await.unwrap();
        assert_eq!(result.schema.fields().len(), 2);
    }

    #[tokio::test]
    async fn test_window_function_lag_lead() {
        let engine = create_test_engine().await;

        let cmd = CommandStatementQuery {
            query: "SELECT id, LAG(value, 1) OVER (ORDER BY id) as prev_val, LEAD(value, 1) OVER (ORDER BY id) as next_val FROM test.\"table\"".to_string(),
            transaction_id: None,
        };
        let result = engine.execute_statement_query(&cmd).await.unwrap();
        assert_eq!(result.schema.fields().len(), 3);
    }

    #[tokio::test]
    async fn test_like_pattern() {
        let engine = create_test_engine().await;

        // Create a table with string data for LIKE testing
        let cmd = CommandStatementUpdate {
            query: "CREATE TABLE strings AS SELECT 'hello' as name UNION ALL SELECT 'world' UNION ALL SELECT 'help'".to_string(),
            transaction_id: None,
        };
        engine.execute_statement_update(&cmd).await.unwrap();

        let cmd = CommandStatementQuery {
            query: "SELECT * FROM strings WHERE name LIKE 'hel%'".to_string(),
            transaction_id: None,
        };
        let result = engine.execute_statement_query(&cmd).await.unwrap();
        assert!(!result.schema.fields().is_empty());
    }

    #[tokio::test]
    async fn test_between_operator() {
        let engine = create_test_engine().await;

        let cmd = CommandStatementQuery {
            query: "SELECT * FROM test.\"table\" WHERE value BETWEEN 10 AND 25".to_string(),
            transaction_id: None,
        };
        let result = engine.execute_statement_query(&cmd).await.unwrap();
        assert!(!result.schema.fields().is_empty());
    }

    #[tokio::test]
    async fn test_coalesce() {
        let engine = create_test_engine().await;

        let cmd = CommandStatementQuery {
            query: "SELECT COALESCE(NULL, value, 0) as val FROM test.\"table\"".to_string(),
            transaction_id: None,
        };
        let result = engine.execute_statement_query(&cmd).await.unwrap();
        assert!(!result.schema.fields().is_empty());
    }

    #[tokio::test]
    async fn test_nullif() {
        let engine = create_test_engine().await;

        let cmd = CommandStatementQuery {
            query: "SELECT NULLIF(value, 10) as val FROM test.\"table\"".to_string(),
            transaction_id: None,
        };
        let result = engine.execute_statement_query(&cmd).await.unwrap();
        assert!(!result.schema.fields().is_empty());
    }

    // ===== Function Tests =====

    #[tokio::test]
    async fn test_string_functions() {
        let engine = create_test_engine().await;

        let cmd = CommandStatementQuery {
            query: "SELECT 
                CONCAT('hello', ' ', 'world') as concat_result,
                SUBSTRING('hello world', 1, 5) as substr_result,
                TRIM('  hello  ') as trim_result,
                UPPER('hello') as upper_result,
                LOWER('HELLO') as lower_result
            "
            .to_string(),
            transaction_id: None,
        };
        let result = engine.execute_statement_query(&cmd).await.unwrap();
        assert_eq!(result.schema.fields().len(), 5);
    }

    #[tokio::test]
    async fn test_date_functions() {
        let engine = create_test_engine().await;

        let cmd = CommandStatementQuery {
            query: "SELECT 
                NOW() as now_result,
                CURRENT_DATE as current_date_result
            "
            .to_string(),
            transaction_id: None,
        };
        let result = engine.execute_statement_query(&cmd).await.unwrap();
        assert_eq!(result.schema.fields().len(), 2);
    }

    #[tokio::test]
    async fn test_date_trunc_extract() {
        let engine = create_test_engine().await;

        let cmd = CommandStatementQuery {
            query: "SELECT 
                DATE_TRUNC('month', NOW()) as truncated,
                EXTRACT(YEAR FROM NOW()) as year_val
            "
            .to_string(),
            transaction_id: None,
        };
        let result = engine.execute_statement_query(&cmd).await.unwrap();
        assert_eq!(result.schema.fields().len(), 2);
    }

    #[tokio::test]
    async fn test_math_functions() {
        let engine = create_test_engine().await;

        let cmd = CommandStatementQuery {
            query: "SELECT 
                ABS(-5) as abs_result,
                ROUND(3.7) as round_result,
                FLOOR(3.7) as floor_result,
                CEIL(3.2) as ceil_result,
                10 % 3 as mod_result
            "
            .to_string(),
            transaction_id: None,
        };
        let result = engine.execute_statement_query(&cmd).await.unwrap();
        assert_eq!(result.schema.fields().len(), 5);
    }

    #[tokio::test]
    async fn test_cast_function() {
        let engine = create_test_engine().await;

        let cmd = CommandStatementQuery {
            query: "SELECT 
                CAST(123 AS VARCHAR) as int_to_str,
                CAST('456' AS INT) as str_to_int,
                CAST(1.5 AS INT) as float_to_int
            "
            .to_string(),
            transaction_id: None,
        };
        let result = engine.execute_statement_query(&cmd).await.unwrap();
        assert_eq!(result.schema.fields().len(), 3);
    }

    // ===== EXPLAIN Tests =====

    #[tokio::test]
    async fn test_explain() {
        let engine = create_test_engine().await;

        let cmd = CommandStatementQuery {
            query: "EXPLAIN SELECT * FROM test.\"table\" WHERE id > 1".to_string(),
            transaction_id: None,
        };
        let result = engine.execute_statement_query(&cmd).await.unwrap();
        assert!(!result.schema.fields().is_empty());

        let ticket = TicketStatementQuery {
            statement_handle: result.handle,
        };
        let (_, batches) = engine.get_statement_query_data(&ticket).await.unwrap();
        let total_rows: usize = batches.iter().map(|b| b.num_rows()).sum();
        assert!(total_rows >= 1, "EXPLAIN should return plan rows");
    }

    #[tokio::test]
    async fn test_explain_analyze() {
        let engine = create_test_engine().await;

        let cmd = CommandStatementQuery {
            query: "EXPLAIN ANALYZE SELECT * FROM test.\"table\"".to_string(),
            transaction_id: None,
        };
        let result = engine.execute_statement_query(&cmd).await.unwrap();
        assert!(!result.schema.fields().is_empty());
    }

    // ===== Streaming Tests =====

    #[tokio::test]
    async fn test_streaming_query_data() {
        use futures::TryStreamExt;

        let engine = create_fixture_engine().await;

        // Query the large test fixture which has 10000 rows
        let cmd = CommandStatementQuery {
            query: "SELECT * FROM test.large".to_string(),
            transaction_id: None,
        };
        let result = engine.execute_statement_query(&cmd).await.unwrap();

        let ticket = TicketStatementQuery {
            statement_handle: result.handle,
        };

        // Use streaming to get the data
        let (schema, stream) = engine
            .get_statement_query_data_stream(&ticket)
            .await
            .unwrap();

        // Verify schema
        assert_eq!(schema.fields().len(), 2);
        assert_eq!(schema.field(0).name(), "id");
        assert_eq!(schema.field(1).name(), "data");

        // Consume the stream and count rows
        let batches: Vec<_> = stream.try_collect().await.unwrap();
        let total_rows: usize = batches.iter().map(|b| b.num_rows()).sum();
        assert_eq!(total_rows, 10000);
    }

    #[tokio::test]
    async fn test_streaming_prepared_statement() {
        use futures::TryStreamExt;

        let engine = create_fixture_engine().await;

        // Create a prepared statement
        let create_result = engine
            .create_prepared_statement(&ActionCreatePreparedStatementRequest {
                query: "SELECT * FROM test.large".to_string(),
                transaction_id: None,
            })
            .await
            .unwrap();

        // Use streaming to get the data
        let (schema, stream) = engine
            .get_prepared_statement_data_stream(&create_result.handle)
            .await
            .unwrap();

        // Verify schema
        assert_eq!(schema.fields().len(), 2);

        // Consume the stream and count rows
        let batches: Vec<_> = stream.try_collect().await.unwrap();
        let total_rows: usize = batches.iter().map(|b| b.num_rows()).sum();
        assert_eq!(total_rows, 10000);
    }

    // ===== INSERT...SELECT Tests =====

    #[tokio::test]
    async fn test_insert_select_basic() {
        let store = Arc::new(MemoryStore::with_test_fixtures());
        let engine = SqlEngine::new(store.clone(), DEFAULT_CATALOG, DEFAULT_SCHEMA).await;

        // First, create a destination table
        let create_query = "CREATE TABLE dest_table (id BIGINT, value BIGINT)";
        let cmd = CommandStatementUpdate {
            query: create_query.to_string(),
            transaction_id: None,
        };
        engine.execute_statement_update(&cmd).await.unwrap();

        // Get initial row count
        let info_before = store
            .get(&DataPath::new(vec!["dest_table".to_string()]))
            .await;
        assert!(info_before.is_ok());
        assert_eq!(info_before.unwrap().total_records, 0);

        // INSERT...SELECT from test.integers
        let insert_query =
            "INSERT INTO dest_table SELECT id, value FROM test.integers WHERE id < 10";
        let cmd = CommandStatementUpdate {
            query: insert_query.to_string(),
            transaction_id: None,
        };
        let result = engine.execute_statement_update(&cmd).await.unwrap();

        // Should have inserted 10 rows (ids 0-9)
        assert_eq!(result.record_count, 10);

        // Verify data was actually inserted
        let info_after = store
            .get(&DataPath::new(vec!["dest_table".to_string()]))
            .await
            .unwrap();
        assert_eq!(info_after.total_records, 10);
    }

    #[tokio::test]
    async fn test_insert_select_all_rows() {
        let store = Arc::new(MemoryStore::with_test_fixtures());
        let engine = SqlEngine::new(store.clone(), DEFAULT_CATALOG, DEFAULT_SCHEMA).await;

        // Create destination table
        let create_query = "CREATE TABLE copy_table (id BIGINT, name VARCHAR)";
        let cmd = CommandStatementUpdate {
            query: create_query.to_string(),
            transaction_id: None,
        };
        engine.execute_statement_update(&cmd).await.unwrap();

        // INSERT...SELECT all rows from test.strings
        let insert_query = "INSERT INTO copy_table SELECT * FROM test.strings";
        let cmd = CommandStatementUpdate {
            query: insert_query.to_string(),
            transaction_id: None,
        };
        let result = engine.execute_statement_update(&cmd).await.unwrap();

        // test.strings has 100 rows
        assert_eq!(result.record_count, 100);

        // Verify data
        let info = store
            .get(&DataPath::new(vec!["copy_table".to_string()]))
            .await
            .unwrap();
        assert_eq!(info.total_records, 100);
    }

    // ===== TRUNCATE TABLE Tests =====

    #[tokio::test]
    async fn test_truncate_table_basic() {
        let store = Arc::new(MemoryStore::with_test_fixtures());
        let engine = SqlEngine::new(store.clone(), DEFAULT_CATALOG, DEFAULT_SCHEMA).await;

        // First create a table with some data
        let create_query =
            "CREATE TABLE truncate_test AS SELECT * FROM test.integers WHERE id < 50";
        let cmd = CommandStatementUpdate {
            query: create_query.to_string(),
            transaction_id: None,
        };
        engine.execute_statement_update(&cmd).await.unwrap();

        // Verify table has data
        let path = DataPath::new(vec!["truncate_test".to_string()]);
        let info_before = store.get(&path).await.unwrap();
        assert_eq!(info_before.total_records, 50);

        // Truncate the table
        let cmd = CommandStatementUpdate {
            query: "TRUNCATE TABLE truncate_test".to_string(),
            transaction_id: None,
        };
        let result = engine.execute_statement_update(&cmd).await.unwrap();

        // Should return the number of rows that were removed
        assert_eq!(result.record_count, 50);

        // Verify table is now empty
        let info_after = store.get(&path).await.unwrap();
        assert_eq!(info_after.total_records, 0);

        // Schema should still exist
        let schema = store.get_schema(&path).await.unwrap();
        assert_eq!(schema.fields().len(), 2);
    }

    #[tokio::test]
    async fn test_truncate_without_table_keyword() {
        let store = Arc::new(MemoryStore::with_test_fixtures());
        let engine = SqlEngine::new(store.clone(), DEFAULT_CATALOG, DEFAULT_SCHEMA).await;

        // Create a table
        let create_query =
            "CREATE TABLE truncate_test2 AS SELECT * FROM test.integers WHERE id < 20";
        let cmd = CommandStatementUpdate {
            query: create_query.to_string(),
            transaction_id: None,
        };
        engine.execute_statement_update(&cmd).await.unwrap();

        // Truncate without TABLE keyword
        let cmd = CommandStatementUpdate {
            query: "TRUNCATE truncate_test2".to_string(),
            transaction_id: None,
        };
        let result = engine.execute_statement_update(&cmd).await.unwrap();

        assert_eq!(result.record_count, 20);

        // Verify empty
        let path = DataPath::new(vec!["truncate_test2".to_string()]);
        let info = store.get(&path).await.unwrap();
        assert_eq!(info.total_records, 0);
    }

    #[tokio::test]
    async fn test_truncate_nonexistent_table() {
        let engine = create_test_engine().await;

        let cmd = CommandStatementUpdate {
            query: "TRUNCATE TABLE nonexistent".to_string(),
            transaction_id: None,
        };
        let result = engine.execute_statement_update(&cmd).await;

        assert!(result.is_err());
        assert!(matches!(result.unwrap_err(), SqlError::TableNotFound(_)));
    }

    // ===== ALTER TABLE ADD COLUMN Tests =====

    #[tokio::test]
    async fn test_alter_table_add_column() {
        let store = Arc::new(MemoryStore::with_test_fixtures());
        let engine = SqlEngine::new(store.clone(), DEFAULT_CATALOG, DEFAULT_SCHEMA).await;

        // Create a table
        let create_query =
            "CREATE TABLE alter_test AS SELECT id, value FROM test.integers WHERE id < 5";
        let cmd = CommandStatementUpdate {
            query: create_query.to_string(),
            transaction_id: None,
        };
        engine.execute_statement_update(&cmd).await.unwrap();

        let path = DataPath::new(vec!["alter_test".to_string()]);

        // Verify initial schema
        let schema_before = store.get_schema(&path).await.unwrap();
        assert_eq!(schema_before.fields().len(), 2);

        // Add a new column
        let cmd = CommandStatementUpdate {
            query: "ALTER TABLE alter_test ADD COLUMN new_col VARCHAR".to_string(),
            transaction_id: None,
        };
        engine.execute_statement_update(&cmd).await.unwrap();

        // Verify schema has new column
        let schema_after = store.get_schema(&path).await.unwrap();
        assert_eq!(schema_after.fields().len(), 3);
        assert_eq!(schema_after.field(2).name(), "new_col");
        assert_eq!(schema_after.field(2).data_type(), &DataType::Utf8);

        // Data should still be there with nulls in new column
        let batches = store.get_batches(&path).await.unwrap();
        let total_rows: usize = batches.iter().map(|b| b.num_rows()).sum();
        assert_eq!(total_rows, 5);
    }

    #[tokio::test]
    async fn test_alter_table_add_column_without_keyword() {
        let store = Arc::new(MemoryStore::with_test_fixtures());
        let engine = SqlEngine::new(store.clone(), DEFAULT_CATALOG, DEFAULT_SCHEMA).await;

        // Create a table
        let create_query = "CREATE TABLE alter_test2 AS SELECT id FROM test.integers WHERE id < 3";
        let cmd = CommandStatementUpdate {
            query: create_query.to_string(),
            transaction_id: None,
        };
        engine.execute_statement_update(&cmd).await.unwrap();

        // Add without COLUMN keyword
        let cmd = CommandStatementUpdate {
            query: "ALTER TABLE alter_test2 ADD extra_col BIGINT".to_string(),
            transaction_id: None,
        };
        engine.execute_statement_update(&cmd).await.unwrap();

        let path = DataPath::new(vec!["alter_test2".to_string()]);
        let schema = store.get_schema(&path).await.unwrap();
        assert_eq!(schema.fields().len(), 2);
        assert_eq!(schema.field(1).name(), "extra_col");
    }

    // ===== ALTER TABLE DROP COLUMN Tests =====

    #[tokio::test]
    async fn test_alter_table_drop_column() {
        let store = Arc::new(MemoryStore::with_test_fixtures());
        let engine = SqlEngine::new(store.clone(), DEFAULT_CATALOG, DEFAULT_SCHEMA).await;

        // Create a table with multiple columns
        let create_query =
            "CREATE TABLE drop_test AS SELECT id, value FROM test.integers WHERE id < 5";
        let cmd = CommandStatementUpdate {
            query: create_query.to_string(),
            transaction_id: None,
        };
        engine.execute_statement_update(&cmd).await.unwrap();

        let path = DataPath::new(vec!["drop_test".to_string()]);

        // Verify initial schema
        let schema_before = store.get_schema(&path).await.unwrap();
        assert_eq!(schema_before.fields().len(), 2);

        // Drop a column
        let cmd = CommandStatementUpdate {
            query: "ALTER TABLE drop_test DROP COLUMN value".to_string(),
            transaction_id: None,
        };
        engine.execute_statement_update(&cmd).await.unwrap();

        // Verify schema
        let schema_after = store.get_schema(&path).await.unwrap();
        assert_eq!(schema_after.fields().len(), 1);
        assert_eq!(schema_after.field(0).name(), "id");

        // Data should still be there
        let batches = store.get_batches(&path).await.unwrap();
        let total_rows: usize = batches.iter().map(|b| b.num_rows()).sum();
        assert_eq!(total_rows, 5);
    }

    #[tokio::test]
    async fn test_alter_table_drop_last_column_fails() {
        let store = Arc::new(MemoryStore::with_test_fixtures());
        let engine = SqlEngine::new(store.clone(), DEFAULT_CATALOG, DEFAULT_SCHEMA).await;

        // Create a table with one column
        let create_query = "CREATE TABLE single_col AS SELECT id FROM test.integers WHERE id < 3";
        let cmd = CommandStatementUpdate {
            query: create_query.to_string(),
            transaction_id: None,
        };
        engine.execute_statement_update(&cmd).await.unwrap();

        // Try to drop the only column
        let cmd = CommandStatementUpdate {
            query: "ALTER TABLE single_col DROP COLUMN id".to_string(),
            transaction_id: None,
        };
        let result = engine.execute_statement_update(&cmd).await;

        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(matches!(err, SqlError::InvalidCommand(_)));
    }

    // ===== ALTER TABLE RENAME COLUMN Tests =====

    #[tokio::test]
    async fn test_alter_table_rename_column() {
        let store = Arc::new(MemoryStore::with_test_fixtures());
        let engine = SqlEngine::new(store.clone(), DEFAULT_CATALOG, DEFAULT_SCHEMA).await;

        // Create a table
        let create_query =
            "CREATE TABLE rename_test AS SELECT id, value FROM test.integers WHERE id < 5";
        let cmd = CommandStatementUpdate {
            query: create_query.to_string(),
            transaction_id: None,
        };
        engine.execute_statement_update(&cmd).await.unwrap();

        let path = DataPath::new(vec!["rename_test".to_string()]);

        // Verify initial schema
        let schema_before = store.get_schema(&path).await.unwrap();
        assert_eq!(schema_before.field(1).name(), "value");

        // Rename column
        let cmd = CommandStatementUpdate {
            query: "ALTER TABLE rename_test RENAME COLUMN value TO amount".to_string(),
            transaction_id: None,
        };
        engine.execute_statement_update(&cmd).await.unwrap();

        // Verify schema
        let schema_after = store.get_schema(&path).await.unwrap();
        assert_eq!(schema_after.fields().len(), 2);
        assert_eq!(schema_after.field(0).name(), "id");
        assert_eq!(schema_after.field(1).name(), "amount");

        // Data should still be there
        let batches = store.get_batches(&path).await.unwrap();
        let total_rows: usize = batches.iter().map(|b| b.num_rows()).sum();
        assert_eq!(total_rows, 5);
    }

    #[tokio::test]
    async fn test_alter_table_rename_nonexistent_column() {
        let engine = create_fixture_engine().await;

        // Create a table
        let create_query = "CREATE TABLE rename_test2 AS SELECT id FROM test.integers WHERE id < 3";
        let cmd = CommandStatementUpdate {
            query: create_query.to_string(),
            transaction_id: None,
        };
        engine.execute_statement_update(&cmd).await.unwrap();

        // Try to rename nonexistent column
        let cmd = CommandStatementUpdate {
            query: "ALTER TABLE rename_test2 RENAME COLUMN nonexistent TO newname".to_string(),
            transaction_id: None,
        };
        let result = engine.execute_statement_update(&cmd).await;

        assert!(result.is_err());
        assert!(matches!(result.unwrap_err(), SqlError::InvalidCommand(_)));
    }

    // ===== CREATE/DROP VIEW Tests =====

    #[tokio::test]
    async fn test_create_view_basic() {
        let engine = create_fixture_engine().await;

        // Create a view
        let cmd = CommandStatementUpdate {
            query: "CREATE VIEW test_view AS SELECT id, value FROM test.integers WHERE id < 10"
                .to_string(),
            transaction_id: None,
        };
        let result = engine.execute_statement_update(&cmd).await;
        assert!(result.is_ok());

        // Query the view
        let query_cmd = CommandStatementQuery {
            query: "SELECT * FROM test_view".to_string(),
            transaction_id: None,
        };
        let query_result = engine.execute_statement_query(&query_cmd).await.unwrap();
        assert_eq!(query_result.schema.fields().len(), 2);
    }

    #[tokio::test]
    async fn test_drop_view() {
        let engine = create_fixture_engine().await;

        // Create a view
        let cmd = CommandStatementUpdate {
            query: "CREATE VIEW drop_view_test AS SELECT * FROM test.integers".to_string(),
            transaction_id: None,
        };
        engine.execute_statement_update(&cmd).await.unwrap();

        // Drop the view
        let cmd = CommandStatementUpdate {
            query: "DROP VIEW drop_view_test".to_string(),
            transaction_id: None,
        };
        let result = engine.execute_statement_update(&cmd).await;
        assert!(result.is_ok());

        // Query should fail now
        let query_cmd = CommandStatementQuery {
            query: "SELECT * FROM drop_view_test".to_string(),
            transaction_id: None,
        };
        let query_result = engine.execute_statement_query(&query_cmd).await;
        assert!(query_result.is_err());
    }

    #[tokio::test]
    async fn test_drop_view_if_exists() {
        let engine = create_test_engine().await;

        // Drop non-existent view with IF EXISTS - should succeed
        let cmd = CommandStatementUpdate {
            query: "DROP VIEW IF EXISTS nonexistent_view".to_string(),
            transaction_id: None,
        };
        let result = engine.execute_statement_update(&cmd).await;
        assert!(result.is_ok());
    }

    // ===== CREATE/DROP SCHEMA Tests =====

    #[tokio::test]
    async fn test_create_schema() {
        let engine = create_test_engine().await;

        // Create a schema (virtual for now)
        let cmd = CommandStatementUpdate {
            query: "CREATE SCHEMA new_schema".to_string(),
            transaction_id: None,
        };
        let result = engine.execute_statement_update(&cmd).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_create_schema_if_not_exists() {
        let engine = create_test_engine().await;

        let cmd = CommandStatementUpdate {
            query: "CREATE SCHEMA IF NOT EXISTS another_schema".to_string(),
            transaction_id: None,
        };
        let result = engine.execute_statement_update(&cmd).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_drop_schema() {
        let engine = create_test_engine().await;

        // Create then drop
        let cmd = CommandStatementUpdate {
            query: "CREATE SCHEMA temp_schema".to_string(),
            transaction_id: None,
        };
        engine.execute_statement_update(&cmd).await.unwrap();

        let cmd = CommandStatementUpdate {
            query: "DROP SCHEMA temp_schema".to_string(),
            transaction_id: None,
        };
        let result = engine.execute_statement_update(&cmd).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_drop_schema_if_exists() {
        let engine = create_test_engine().await;

        let cmd = CommandStatementUpdate {
            query: "DROP SCHEMA IF EXISTS nonexistent_schema".to_string(),
            transaction_id: None,
        };
        let result = engine.execute_statement_update(&cmd).await;
        assert!(result.is_ok());
    }

    // ===== MERGE / UPSERT Tests =====

    #[tokio::test]
    async fn test_merge_basic() {
        let engine = create_fixture_engine().await;

        // Execute a MERGE statement
        let cmd = CommandStatementUpdate {
            query: r#"
                MERGE INTO test.integers AS t
                USING test.strings AS s
                ON t.id = s.id
                WHEN MATCHED THEN UPDATE SET value = s.id * 100
                WHEN NOT MATCHED THEN INSERT (id, value) VALUES (s.id, s.id * 100)
            "#
            .to_string(),
            transaction_id: None,
        };
        let result = engine.execute_statement_update(&cmd).await;

        // MERGE is simulated, should succeed
        assert!(result.is_ok());
        assert!(result.unwrap().record_count >= 0);
    }

    #[tokio::test]
    async fn test_merge_target_not_found() {
        let engine = create_test_engine().await;

        let cmd = CommandStatementUpdate {
            query: r#"
                MERGE INTO nonexistent AS t
                USING other_table AS s
                ON t.id = s.id
                WHEN MATCHED THEN UPDATE SET value = s.value
            "#
            .to_string(),
            transaction_id: None,
        };
        let result = engine.execute_statement_update(&cmd).await;

        assert!(result.is_err());
        assert!(matches!(result.unwrap_err(), SqlError::TableNotFound(_)));
    }

    #[tokio::test]
    async fn test_upsert_do_nothing() {
        let store = Arc::new(MemoryStore::with_test_fixtures());
        let engine = SqlEngine::new(store.clone(), DEFAULT_CATALOG, DEFAULT_SCHEMA).await;

        // First, create a table with a key column
        let create_query =
            "CREATE TABLE upsert_test AS SELECT id, value FROM test.integers WHERE id < 5";
        let cmd = CommandStatementUpdate {
            query: create_query.to_string(),
            transaction_id: None,
        };
        engine.execute_statement_update(&cmd).await.unwrap();

        // Execute INSERT...ON CONFLICT DO NOTHING
        let cmd = CommandStatementUpdate {
            query:
                "INSERT INTO upsert_test (id, value) VALUES (1, 999) ON CONFLICT (id) DO NOTHING"
                    .to_string(),
            transaction_id: None,
        };
        let result = engine.execute_statement_update(&cmd).await;

        assert!(result.is_ok());
        // Row id=1 already exists, so DO NOTHING affects zero rows
        assert_eq!(result.unwrap().record_count, 0);
    }

    #[tokio::test]
    async fn test_upsert_do_update() {
        let store = Arc::new(MemoryStore::with_test_fixtures());
        let engine = SqlEngine::new(store.clone(), DEFAULT_CATALOG, DEFAULT_SCHEMA).await;

        // First, create a table
        let create_query =
            "CREATE TABLE upsert_test2 AS SELECT id, value FROM test.integers WHERE id < 5";
        let cmd = CommandStatementUpdate {
            query: create_query.to_string(),
            transaction_id: None,
        };
        engine.execute_statement_update(&cmd).await.unwrap();

        // Execute INSERT...ON CONFLICT DO UPDATE
        let cmd = CommandStatementUpdate {
            query: "INSERT INTO upsert_test2 (id, value) VALUES (1, 999) ON CONFLICT (id) DO UPDATE SET value = EXCLUDED.value".to_string(),
            transaction_id: None,
        };
        let result = engine.execute_statement_update(&cmd).await;

        assert!(result.is_ok());
        assert_eq!(result.unwrap().record_count, 1);
    }

    #[tokio::test]
    async fn test_upsert_multiple_values() {
        let store = Arc::new(MemoryStore::with_test_fixtures());
        let engine = SqlEngine::new(store.clone(), DEFAULT_CATALOG, DEFAULT_SCHEMA).await;

        // Create table
        let create_query =
            "CREATE TABLE upsert_test3 AS SELECT id, value FROM test.integers WHERE id < 3";
        let cmd = CommandStatementUpdate {
            query: create_query.to_string(),
            transaction_id: None,
        };
        engine.execute_statement_update(&cmd).await.unwrap();

        // Upsert multiple rows
        let cmd = CommandStatementUpdate {
            query: "INSERT INTO upsert_test3 (id, value) VALUES (1, 100), (2, 200), (10, 1000) ON CONFLICT (id) DO UPDATE SET value = EXCLUDED.value".to_string(),
            transaction_id: None,
        };
        let result = engine.execute_statement_update(&cmd).await;

        assert!(result.is_ok());
        assert_eq!(result.unwrap().record_count, 3);
    }

    #[tokio::test]
    async fn test_upsert_missing_conflict_action() {
        let engine = create_fixture_engine().await;

        // Create table
        let create_query = "CREATE TABLE upsert_test4 AS SELECT id FROM test.integers WHERE id < 3";
        let cmd = CommandStatementUpdate {
            query: create_query.to_string(),
            transaction_id: None,
        };
        engine.execute_statement_update(&cmd).await.unwrap();

        // Missing DO UPDATE or DO NOTHING
        let cmd = CommandStatementUpdate {
            query: "INSERT INTO upsert_test4 (id) VALUES (1) ON CONFLICT (id)".to_string(),
            transaction_id: None,
        };
        let result = engine.execute_statement_update(&cmd).await;

        assert!(result.is_err());
        assert!(matches!(result.unwrap_err(), SqlError::SyntaxError(_)));
    }

    #[tokio::test]
    async fn test_upsert_table_not_found() {
        let engine = create_test_engine().await;

        let cmd = CommandStatementUpdate {
            query: "INSERT INTO nonexistent (id) VALUES (1) ON CONFLICT (id) DO NOTHING"
                .to_string(),
            transaction_id: None,
        };
        let result = engine.execute_statement_update(&cmd).await;

        assert!(result.is_err());
        assert!(matches!(result.unwrap_err(), SqlError::TableNotFound(_)));
    }

    // ===== Nested Arrow Type Tests =====

    #[tokio::test]
    async fn test_select_nested_list_type() {
        // Use with_test_fixtures to get the nested table
        let engine = create_fixture_engine().await;

        // Query the nested table that contains List<Int64> column
        let cmd = CommandStatementQuery {
            query: "SELECT id, items FROM test.nested LIMIT 5".to_string(),
            transaction_id: None,
        };
        let result = engine.execute_statement_query(&cmd).await.unwrap();

        // Verify schema has List type
        let schema = result.schema;
        assert_eq!(schema.fields().len(), 2);
        assert!(matches!(
            schema.field(1).data_type(),
            arrow_schema::DataType::List(_)
        ));
    }

    #[tokio::test]
    async fn test_nested_list_count() {
        use futures::TryStreamExt;

        // Use with_test_fixtures to get the nested table
        let engine = create_fixture_engine().await;

        // Count rows in nested table
        let cmd = CommandStatementQuery {
            query: "SELECT COUNT(*) as cnt FROM test.nested".to_string(),
            transaction_id: None,
        };
        let result = engine.execute_statement_query(&cmd).await.unwrap();

        // Get the batches using streaming
        let ticket = TicketStatementQuery {
            statement_handle: result.handle,
        };
        let (_schema, stream) = engine
            .get_statement_query_data_stream(&ticket)
            .await
            .unwrap();
        let batches: Vec<_> = stream.try_collect().await.unwrap();
        let batch = &batches[0];
        let count_col = batch
            .column(0)
            .as_any()
            .downcast_ref::<arrow_array::Int64Array>()
            .unwrap();
        assert_eq!(count_col.value(0), 50); // 50 rows created in fixture
    }

    #[tokio::test]
    async fn test_nested_list_filter() {
        use futures::TryStreamExt;

        // Use with_test_fixtures to get the nested table
        let engine = create_fixture_engine().await;

        // Filter nested table by id
        let cmd = CommandStatementQuery {
            query: "SELECT id FROM test.nested WHERE id < 10".to_string(),
            transaction_id: None,
        };
        let result = engine.execute_statement_query(&cmd).await.unwrap();

        // Get the batches using streaming
        let ticket = TicketStatementQuery {
            statement_handle: result.handle,
        };
        let (_schema, stream) = engine
            .get_statement_query_data_stream(&ticket)
            .await
            .unwrap();
        let batches: Vec<_> = stream.try_collect().await.unwrap();
        let total_rows: usize = batches.iter().map(|b| b.num_rows()).sum();
        assert_eq!(total_rows, 10); // ids 0-9
    }

    // ===== Transaction Isolation Level Tests =====

    #[test]
    fn test_isolation_level_default() {
        assert_eq!(IsolationLevel::default(), IsolationLevel::ReadCommitted);
    }

    #[test]
    fn test_isolation_level_display() {
        assert_eq!(
            IsolationLevel::ReadUncommitted.to_string(),
            "READ UNCOMMITTED"
        );
        assert_eq!(IsolationLevel::ReadCommitted.to_string(), "READ COMMITTED");
        assert_eq!(
            IsolationLevel::RepeatableRead.to_string(),
            "REPEATABLE READ"
        );
        assert_eq!(IsolationLevel::Serializable.to_string(), "SERIALIZABLE");
    }

    #[tokio::test]
    async fn test_begin_transaction_with_isolation_level() {
        let engine = create_test_engine().await;

        // Test each isolation level
        let txn1 = engine
            .begin_transaction_with_isolation(IsolationLevel::ReadUncommitted)
            .unwrap();
        assert_eq!(
            engine.get_transaction_isolation_level(&txn1).unwrap(),
            IsolationLevel::ReadUncommitted
        );

        let txn2 = engine
            .begin_transaction_with_isolation(IsolationLevel::Serializable)
            .unwrap();
        assert_eq!(
            engine.get_transaction_isolation_level(&txn2).unwrap(),
            IsolationLevel::Serializable
        );

        // Default transaction uses ReadCommitted
        let txn3 = engine.begin_transaction().unwrap();
        assert_eq!(
            engine.get_transaction_isolation_level(&txn3).unwrap(),
            IsolationLevel::ReadCommitted
        );
    }

    // ===== Savepoint Tests =====

    #[tokio::test]
    async fn test_begin_savepoint() {
        let engine = create_test_engine().await;

        let txn_id = engine.begin_transaction().unwrap();

        // Create a savepoint
        let savepoint_id = engine.begin_savepoint(&txn_id, "sp1".to_string()).unwrap();
        assert!(!savepoint_id.is_empty());

        // Check savepoint count
        assert_eq!(engine.get_savepoint_count(&txn_id).unwrap(), 1);

        // Create another savepoint
        let _savepoint_id2 = engine.begin_savepoint(&txn_id, "sp2".to_string()).unwrap();
        assert_eq!(engine.get_savepoint_count(&txn_id).unwrap(), 2);
    }

    #[tokio::test]
    async fn test_savepoint_in_inactive_transaction() {
        let engine = create_test_engine().await;

        let txn_id = engine.begin_transaction().unwrap();
        engine
            .end_transaction(&txn_id, EndTransaction::Commit)
            .unwrap();

        // Try to create savepoint in ended transaction
        let result = engine.begin_savepoint(&txn_id, "sp1".to_string());
        assert!(matches!(result, Err(SqlError::TransactionNotFound(_))));
    }

    #[tokio::test]
    async fn test_savepoint_release() {
        let engine = create_test_engine().await;

        let txn_id = engine.begin_transaction().unwrap();
        let savepoint_id = engine.begin_savepoint(&txn_id, "sp1".to_string()).unwrap();

        // Release savepoint (keeps operations)
        engine
            .end_savepoint(&savepoint_id, EndSavepoint::Release)
            .unwrap();

        // Savepoint should be removed
        assert_eq!(engine.get_savepoint_count(&txn_id).unwrap(), 0);
    }

    #[tokio::test]
    async fn test_savepoint_rollback() {
        let engine = create_test_engine().await;

        let txn_id = engine.begin_transaction().unwrap();

        // Add an operation
        let cmd = CommandStatementUpdate {
            query: "INSERT INTO test.table (id, value) VALUES (1, 10)".to_string(),
            transaction_id: Some(txn_id.clone()),
        };
        engine.execute_statement_update(&cmd).await.unwrap();
        assert_eq!(engine.get_pending_operation_count(&txn_id).unwrap(), 1);

        // Create savepoint
        let savepoint_id = engine.begin_savepoint(&txn_id, "sp1".to_string()).unwrap();

        // Add more operations
        let cmd = CommandStatementUpdate {
            query: "INSERT INTO test.table (id, value) VALUES (2, 20)".to_string(),
            transaction_id: Some(txn_id.clone()),
        };
        engine.execute_statement_update(&cmd).await.unwrap();
        assert_eq!(engine.get_pending_operation_count(&txn_id).unwrap(), 2);

        // Rollback to savepoint - should discard the second insert
        engine
            .end_savepoint(&savepoint_id, EndSavepoint::Rollback)
            .unwrap();
        assert_eq!(engine.get_pending_operation_count(&txn_id).unwrap(), 1);
    }

    #[tokio::test]
    async fn test_savepoint_rollback_nested() {
        let engine = create_test_engine().await;

        let txn_id = engine.begin_transaction().unwrap();

        // Add operation 1 (using existing table from test fixtures)
        let cmd = CommandStatementUpdate {
            query: "INSERT INTO test.table (id, value) VALUES (100, 1000)".to_string(),
            transaction_id: Some(txn_id.clone()),
        };
        engine.execute_statement_update(&cmd).await.unwrap();

        // Create savepoint 1
        let sp1 = engine.begin_savepoint(&txn_id, "sp1".to_string()).unwrap();

        // Add operation 2
        let cmd = CommandStatementUpdate {
            query: "INSERT INTO test.table (id, value) VALUES (200, 2000)".to_string(),
            transaction_id: Some(txn_id.clone()),
        };
        engine.execute_statement_update(&cmd).await.unwrap();

        // Create savepoint 2
        let sp2 = engine.begin_savepoint(&txn_id, "sp2".to_string()).unwrap();

        // Add operation 3
        let cmd = CommandStatementUpdate {
            query: "INSERT INTO test.table (id, value) VALUES (300, 3000)".to_string(),
            transaction_id: Some(txn_id.clone()),
        };
        engine.execute_statement_update(&cmd).await.unwrap();
        assert_eq!(engine.get_pending_operation_count(&txn_id).unwrap(), 3);
        assert_eq!(engine.get_savepoint_count(&txn_id).unwrap(), 2);

        // Rollback to sp1 - should discard operations 2 and 3, and invalidate sp2
        engine.end_savepoint(&sp1, EndSavepoint::Rollback).unwrap();
        assert_eq!(engine.get_pending_operation_count(&txn_id).unwrap(), 1);
        assert_eq!(engine.get_savepoint_count(&txn_id).unwrap(), 0); // sp1 is gone, sp2 was invalidated

        // sp2 should now be invalid
        let result = engine.end_savepoint(&sp2, EndSavepoint::Release);
        assert!(matches!(result, Err(SqlError::SavepointNotFound(_))));
    }

    #[tokio::test]
    async fn test_end_savepoint_invalid_savepoint() {
        let engine = create_test_engine().await;

        let txn_id = engine.begin_transaction().unwrap();
        let _savepoint_id = engine.begin_savepoint(&txn_id, "sp1".to_string()).unwrap();

        // Try to end a non-existent savepoint
        let result = engine.end_savepoint(&bytes::Bytes::from("invalid"), EndSavepoint::Release);
        assert!(matches!(result, Err(SqlError::SavepointNotFound(_))));
    }

    #[tokio::test]
    async fn test_end_savepoint_unspecified_action() {
        let engine = create_test_engine().await;

        let txn_id = engine.begin_transaction().unwrap();
        let savepoint_id = engine.begin_savepoint(&txn_id, "sp1".to_string()).unwrap();

        // Unspecified action should fail
        let result = engine.end_savepoint(&savepoint_id, EndSavepoint::Unspecified);
        assert!(matches!(result, Err(SqlError::InvalidTransactionAction(_))));

        // Savepoint should still exist after failed action
        assert_eq!(engine.get_savepoint_count(&txn_id).unwrap(), 1);
    }

    #[test]
    fn test_end_savepoint_try_from() {
        assert_eq!(
            EndSavepoint::try_from(0).unwrap(),
            EndSavepoint::Unspecified
        );
        assert_eq!(EndSavepoint::try_from(1).unwrap(), EndSavepoint::Release);
        assert_eq!(EndSavepoint::try_from(2).unwrap(), EndSavepoint::Rollback);
        assert!(EndSavepoint::try_from(3).is_err());
        assert!(EndSavepoint::try_from(-1).is_err());
    }

    #[tokio::test]
    async fn test_transaction_commit_clears_savepoints() {
        let engine = create_test_engine().await;

        let txn_id = engine.begin_transaction().unwrap();
        let _sp1 = engine.begin_savepoint(&txn_id, "sp1".to_string()).unwrap();
        let _sp2 = engine.begin_savepoint(&txn_id, "sp2".to_string()).unwrap();
        assert_eq!(engine.get_savepoint_count(&txn_id).unwrap(), 2);

        // Commit transaction
        engine
            .end_transaction(&txn_id, EndTransaction::Commit)
            .unwrap();

        // Transaction is gone
        let result = engine.get_savepoint_count(&txn_id);
        assert!(matches!(result, Err(SqlError::TransactionNotFound(_))));
    }
}