oxibase 0.5.2

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

//! MVCC Storage Engine
//!
//! Provides the main MVCC storage engine implementation.
//!

use rustc_hash::FxHashMap;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, RwLock};

use std::path::Path;

use super::file_lock::FileLock;

use crate::core::{DataType, Error, IsolationLevel, Result, Schema};
use crate::storage::config::Config;
use crate::storage::mvcc::wal_manager::WALOperationType;
use crate::storage::mvcc::{
    MVCCTable, MvccTransaction, PersistenceManager, RowVersion, TransactionEngineOperations,
    TransactionRegistry, TransactionVersionStore, VersionStore, VisibilityChecker,
    INVALID_TRANSACTION_ID,
};
use crate::storage::traits::{Engine, Index, Table, Transaction};

/// Type alias for the transaction version store map
type TxnVersionStoreMap = FxHashMap<(i64, String), Arc<RwLock<TransactionVersionStore>>>;

// ============================================================================
// Binary Snapshot Metadata Functions
// ============================================================================
// Format: MAGIC(4) | VERSION(4) | LSN(8) | TIMESTAMP(8) | CRC32(4) = 28 bytes
// Magic bytes: 0x534E4150 ("SNAP" in ASCII)

/// Magic bytes for snapshot metadata ("SNAP" in ASCII)
const SNAPSHOT_META_MAGIC: u32 = 0x50414E53; // "SNAP" in little-endian

/// Current version of the snapshot metadata format
const SNAPSHOT_META_VERSION: u32 = 1;

/// Write binary snapshot metadata with magic number and checksum
fn write_snapshot_metadata(path: &std::path::Path, lsn: u64) -> Result<()> {
    use std::io::Write;

    let mut buf = Vec::with_capacity(28);

    // Magic (4 bytes)
    buf.extend_from_slice(&SNAPSHOT_META_MAGIC.to_le_bytes());

    // Version (4 bytes)
    buf.extend_from_slice(&SNAPSHOT_META_VERSION.to_le_bytes());

    // LSN (8 bytes)
    buf.extend_from_slice(&lsn.to_le_bytes());

    // Timestamp in milliseconds since epoch (8 bytes)
    let timestamp = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_millis() as u64)
        .unwrap_or(0);
    buf.extend_from_slice(&timestamp.to_le_bytes());

    // CRC32 of the data portion (magic + version + lsn + timestamp)
    let crc = crc32fast::hash(&buf);
    buf.extend_from_slice(&crc.to_le_bytes());

    // Write atomically using temp file and rename
    let temp_path = path.with_extension("bin.tmp");

    let mut file = std::fs::File::create(&temp_path).map_err(|e| {
        Error::internal(format!(
            "failed to create snapshot metadata temp file: {}",
            e
        ))
    })?;

    file.write_all(&buf)
        .map_err(|e| Error::internal(format!("failed to write snapshot metadata: {}", e)))?;

    file.sync_all()
        .map_err(|e| Error::internal(format!("failed to sync snapshot metadata: {}", e)))?;

    // Atomic rename
    std::fs::rename(&temp_path, path)
        .map_err(|e| Error::internal(format!("failed to rename snapshot metadata: {}", e)))?;

    // Sync directory to ensure rename is durable
    if let Some(parent) = path.parent() {
        if let Ok(dir_file) = std::fs::File::open(parent) {
            let _ = dir_file.sync_all();
        }
    }

    Ok(())
}

/// Read binary snapshot metadata, returns the LSN or 0 if invalid/not found
fn read_snapshot_metadata(path: &std::path::Path) -> u64 {
    let data = match std::fs::read(path) {
        Ok(d) => d,
        Err(_) => return 0,
    };

    // Minimum size: 28 bytes
    if data.len() < 28 {
        return 0;
    }

    // Verify magic
    let magic = u32::from_le_bytes(data[0..4].try_into().unwrap());
    if magic != SNAPSHOT_META_MAGIC {
        return 0;
    }

    // Verify version (must be compatible)
    let version = u32::from_le_bytes(data[4..8].try_into().unwrap());
    if version > SNAPSHOT_META_VERSION {
        eprintln!(
            "Warning: Snapshot metadata version {} is newer than supported {}",
            version, SNAPSHOT_META_VERSION
        );
        return 0;
    }

    // Verify CRC32
    let stored_crc = u32::from_le_bytes(data[24..28].try_into().unwrap());
    let computed_crc = crc32fast::hash(&data[0..24]);
    if stored_crc != computed_crc {
        eprintln!("Warning: Snapshot metadata checksum mismatch");
        return 0;
    }

    // Extract LSN
    u64::from_le_bytes(data[8..16].try_into().unwrap())
}

/// Read snapshot LSN from either binary or JSON format (backward compatibility)
fn read_snapshot_lsn(snapshot_dir: &std::path::Path) -> u64 {
    // First try new binary format
    let bin_path = snapshot_dir.join("snapshot_meta.bin");
    if bin_path.exists() {
        let lsn = read_snapshot_metadata(&bin_path);
        if lsn > 0 {
            return lsn;
        }
    }

    // Fall back to old JSON format for backward compatibility
    let json_path = snapshot_dir.join("snapshot_meta.json");
    if json_path.exists() {
        if let Ok(content) = std::fs::read_to_string(&json_path) {
            return content
                .trim()
                .strip_prefix("{\"lsn\":")
                .and_then(|s| s.strip_suffix("}"))
                .and_then(|s| s.trim().parse::<u64>().ok())
                .unwrap_or(0);
        }
    }

    0
}

/// View definition storing the query that defines the view
#[derive(Debug, Clone)]
pub struct ViewDefinition {
    /// View name (lowercase for case-insensitive lookup)
    pub name: String,
    /// Original view name (preserves case)
    pub original_name: String,
    /// The SQL query string that defines the view
    pub query: String,
}

impl ViewDefinition {
    /// Create a new view definition
    pub fn new(name: &str, query: String) -> Self {
        Self {
            name: name.to_lowercase(),
            original_name: name.to_string(),
            query,
        }
    }

    /// Serialize view definition to binary format for WAL
    pub fn serialize(&self) -> Vec<u8> {
        let mut buf = Vec::new();

        // Original name (length-prefixed)
        buf.extend_from_slice(&(self.original_name.len() as u16).to_le_bytes());
        buf.extend_from_slice(self.original_name.as_bytes());

        // Query (length-prefixed, using u32 for longer queries)
        buf.extend_from_slice(&(self.query.len() as u32).to_le_bytes());
        buf.extend_from_slice(self.query.as_bytes());

        buf
    }

    /// Deserialize view definition from binary format
    pub fn deserialize(data: &[u8]) -> crate::core::Result<Self> {
        let mut pos = 0;

        // Original name
        if pos + 2 > data.len() {
            return Err(crate::core::Error::internal(
                "invalid view: missing name length",
            ));
        }
        let name_len = u16::from_le_bytes(data[pos..pos + 2].try_into().unwrap()) as usize;
        pos += 2;

        if pos + name_len > data.len() {
            return Err(crate::core::Error::internal("invalid view: missing name"));
        }
        let original_name = String::from_utf8(data[pos..pos + name_len].to_vec())
            .map_err(|e| crate::core::Error::internal(format!("invalid view name: {}", e)))?;
        pos += name_len;

        // Query
        if pos + 4 > data.len() {
            return Err(crate::core::Error::internal(
                "invalid view: missing query length",
            ));
        }
        let query_len = u32::from_le_bytes(data[pos..pos + 4].try_into().unwrap()) as usize;
        pos += 4;

        if pos + query_len > data.len() {
            return Err(crate::core::Error::internal("invalid view: missing query"));
        }
        let query = String::from_utf8(data[pos..pos + query_len].to_vec())
            .map_err(|e| crate::core::Error::internal(format!("invalid view query: {}", e)))?;

        Ok(Self::new(&original_name, query))
    }
}

/// Default schema name for backward compatibility
const DEFAULT_SCHEMA: &str = "public";

/// MVCC Storage Engine
///
/// Provides multi-version concurrency control with snapshot isolation.
pub struct MVCCEngine {
    /// Database path (empty for in-memory)
    path: String,
    /// Configuration
    config: RwLock<Config>,
    /// Table schemas organized by schema (Arc-wrapped for safe sharing with transactions)
    /// Outer map: schema_name -> Inner map: table_name -> Schema
    pub(crate) schemas: Arc<RwLock<FxHashMap<String, FxHashMap<String, Schema>>>>,
    /// Version stores for each table (Arc-wrapped for safe sharing with transactions)
    version_stores: Arc<RwLock<FxHashMap<String, Arc<VersionStore>>>>,
    /// Transaction registry
    registry: Arc<TransactionRegistry>,
    /// Whether the engine is open
    open: AtomicBool,
    /// Cache of transaction version stores per (txn_id, table_name) for proper commit/rollback
    /// (Arc-wrapped for safe sharing with transactions)
    txn_version_stores: Arc<RwLock<TxnVersionStoreMap>>,
    /// View definitions (Arc for cheap cloning on lookup)
    views: RwLock<FxHashMap<String, FxHashMap<String, Arc<ViewDefinition>>>>,
    /// Persistence manager for WAL and snapshot operations (Arc-wrapped for safe sharing)
    /// Sequence definitions
    #[allow(clippy::type_complexity)]
    pub(crate) sequences:
        Arc<RwLock<FxHashMap<String, FxHashMap<String, Arc<crate::core::SequenceState>>>>>,
    persistence: Arc<Option<PersistenceManager>>,
    /// Flag to indicate we're loading from disk to avoid triggering redundant WAL writes
    /// (Arc-wrapped for safe sharing with transactions)
    loading_from_disk: Arc<AtomicBool>,
    /// File lock to prevent multiple processes from accessing the same database
    file_lock: Mutex<Option<FileLock>>,
}

impl MVCCEngine {
    /// Creates a new MVCC engine with the given configuration
    pub fn new(config: Config) -> Self {
        let path = config.path.clone().unwrap_or_default();

        // Initialize persistence manager if path is provided and persistence is enabled
        let persistence = if !path.is_empty() && config.persistence.enabled {
            match PersistenceManager::new(Some(Path::new(&path)), &config.persistence) {
                Ok(pm) => Some(pm),
                Err(e) => {
                    eprintln!("Warning: Failed to initialize persistence: {}", e);
                    None
                }
            }
        } else {
            None
        };

        Self {
            path: if path.is_empty() {
                "memory://".to_string()
            } else {
                path
            },
            config: RwLock::new(config),
            schemas: Arc::new(RwLock::new(FxHashMap::default())),
            version_stores: Arc::new(RwLock::new(FxHashMap::default())),
            registry: Arc::new(TransactionRegistry::new()),
            open: AtomicBool::new(false),
            txn_version_stores: Arc::new(RwLock::new(FxHashMap::default())),
            views: RwLock::new(FxHashMap::default()),
            sequences: Arc::new(RwLock::new(FxHashMap::default())),
            persistence: Arc::new(persistence),
            loading_from_disk: Arc::new(AtomicBool::new(false)),
            file_lock: Mutex::new(None),
        }
    }

    /// Creates a new in-memory MVCC engine
    pub fn in_memory() -> Self {
        Self::new(Config::default())
    }

    /// Opens the engine (inherent method)
    pub fn open_engine(&self) -> Result<()> {
        // Use atomic swap to check and set open flag atomically
        if self.open.swap(true, Ordering::AcqRel) {
            return Ok(()); // Already open
        }

        // Acquire file lock for disk-based databases to prevent concurrent access
        if self.path != "memory://" {
            let lock = FileLock::acquire(&self.path)?;
            let mut file_lock = self.file_lock.lock().unwrap();
            *file_lock = Some(lock);
        }

        // Start accepting transactions
        self.registry.start_accepting_transactions();

        // If persistence is enabled, start it and replay WAL for recovery
        if let Some(ref pm) = *self.persistence {
            if pm.is_enabled() {
                pm.start()?;

                // Mark that we're loading from disk to prevent WAL writes during recovery
                self.loading_from_disk.store(true, Ordering::Release);

                // Try to load from snapshots first (for faster recovery)
                let snapshot_lsn = self.load_snapshots()?;

                // Replay WAL entries after the snapshot LSN
                self.replay_wal(snapshot_lsn)?;

                // Clear the loading flag
                self.loading_from_disk.store(false, Ordering::Release);
            }
        }

        Ok(())
    }

    /// Load table snapshots from disk for faster recovery
    ///
    /// Returns the LSN of the snapshot (or 0 if no snapshots found)
    fn load_snapshots(&self) -> Result<u64> {
        let pm = match self.persistence.as_ref() {
            Some(pm) if pm.is_enabled() => pm,
            _ => return Ok(0),
        };

        let snapshot_dir = pm.path().join("snapshots");
        if !snapshot_dir.exists() {
            return Ok(0); // No snapshots directory
        }

        // Read the snapshot LSN from metadata (supports both binary and JSON formats)
        let metadata_lsn = read_snapshot_lsn(&snapshot_dir);

        // Track max source_lsn from snapshot headers for validation/fallback
        let mut max_header_lsn: u64 = 0;

        // Find and load table snapshots
        let table_dirs = match std::fs::read_dir(&snapshot_dir) {
            Ok(entries) => entries,
            Err(_) => return Ok(0),
        };

        for entry in table_dirs.flatten() {
            if !entry.file_type().map(|ft| ft.is_dir()).unwrap_or(false) {
                continue;
            }

            let table_name = entry.file_name().to_string_lossy().to_string();

            // Find the most recent snapshot file in this directory
            if let Some(snapshot_path) = self.find_latest_snapshot(&entry.path()) {
                match self.load_table_snapshot(&table_name, &snapshot_path) {
                    Ok(source_lsn) => {
                        // Track max source_lsn from snapshot headers (v3+ format)
                        if source_lsn > max_header_lsn {
                            max_header_lsn = source_lsn;
                        }
                    }
                    Err(e) => {
                        eprintln!("Warning: Failed to load snapshot for {}: {}", table_name, e);
                    }
                }
            }
        }

        // Use the larger of metadata LSN and max header LSN
        // - If metadata file is missing, use header LSN (v3+ fallback)
        // - If metadata exists and matches header, use metadata (normal case)
        // - If metadata is smaller than header, prefer header (corruption recovery)
        let snapshot_lsn = std::cmp::max(metadata_lsn, max_header_lsn);

        Ok(snapshot_lsn)
    }

    /// Find the most recent snapshot file in a directory
    fn find_latest_snapshot(&self, dir: &std::path::Path) -> Option<std::path::PathBuf> {
        let mut snapshots: Vec<std::path::PathBuf> = std::fs::read_dir(dir)
            .ok()?
            .filter_map(|e| e.ok())
            .map(|e| e.path())
            .filter(|p| {
                p.file_name()
                    .and_then(|n| n.to_str())
                    .map(|n| n.starts_with("snapshot-") && n.ends_with(".bin"))
                    .unwrap_or(false)
            })
            .collect();

        // Sort by name (timestamp in filename)
        snapshots.sort();

        // Return the latest one
        snapshots.pop()
    }

    /// Load a single table's snapshot from disk
    /// Returns the source_lsn from the snapshot header (0 if v2 format or not available)
    fn load_table_snapshot(
        &self,
        _table_name: &str,
        snapshot_path: &std::path::Path,
    ) -> Result<u64> {
        let mut reader = super::snapshot::SnapshotReader::open(snapshot_path)?;

        // Get the source LSN from the snapshot header (v3+ format)
        let source_lsn = reader.source_lsn();

        // Get the schema from the snapshot
        let schema = reader.schema().clone();
        let table_name_lower = schema.table_name_lower.clone();

        // Create the version store
        let version_store = Arc::new(VersionStore::with_visibility_checker(
            schema.table_name.clone(),
            schema.clone(),
            Arc::clone(&self.registry) as Arc<dyn VisibilityChecker>,
        ));

        // Load all rows from the snapshot
        reader.for_each(|_row_id, mut version| {
            // Snapshot versions have txn_id = -1, we need to use the recovery txn_id
            version.txn_id = super::RECOVERY_TRANSACTION_ID;

            // Apply to version store
            version_store.apply_recovered_version(version);
            true
        })?;

        // Store the schema and version store
        {
            let mut schemas = self.schemas.write().unwrap();
            let default_schema = schemas.entry(DEFAULT_SCHEMA.to_string()).or_default();
            default_schema.insert(table_name_lower.clone(), schema);
        }
        {
            let mut stores = self.version_stores.write().unwrap();
            stores.insert(table_name_lower, version_store);
        }

        Ok(source_lsn)
    }

    /// Replay WAL entries to recover database state starting from a specific LSN
    ///
    /// Uses two-phase recovery to ensure crash consistency:
    /// - Phase 1: Scan WAL to identify committed/aborted transactions
    /// - Phase 2: Apply only entries from committed transactions
    ///
    /// This guarantees that after a crash, only committed transactions are visible.
    fn replay_wal(&self, from_lsn: u64) -> Result<()> {
        let pm = match self.persistence.as_ref() {
            Some(pm) if pm.is_enabled() => pm,
            _ => return Ok(()),
        };

        // Use two-phase recovery for crash consistency
        // This ensures uncommitted transactions are NOT applied after a crash
        let result = pm.replay_two_phase(from_lsn, |entry| self.apply_wal_entry(entry));

        match result {
            Ok(info) => {
                if info.skipped_entries > 0 {
                    eprintln!(
                        "Recovery: {} entries skipped (from aborted/uncommitted transactions)",
                        info.skipped_entries
                    );
                }

                // After WAL replay completes, populate all indexes in a single pass
                // This is O(N + M) instead of O(N * M) when populating each index separately
                self.populate_all_indexes();

                Ok(())
            }
            Err(e) => Err(e),
        }
    }

    /// Populate all indexes across all version stores in a single pass per table
    fn populate_all_indexes(&self) {
        let stores = self.version_stores.read().unwrap();
        for store in stores.values() {
            store.populate_all_indexes();
        }
    }

    /// Apply a single WAL entry during recovery
    fn apply_wal_entry(&self, entry: crate::storage::mvcc::wal_manager::WALEntry) -> Result<()> {
        use crate::storage::mvcc::persistence::{deserialize_row_version, IndexMetadata};
        use crate::storage::mvcc::wal_manager::WALOperationType;

        match entry.operation {
            WALOperationType::CreateTable => {
                // Deserialize schema from entry data
                if let Ok(schema) = self.deserialize_schema(&entry.data) {
                    // Create the table (version store)
                    let version_store = Arc::new(VersionStore::with_visibility_checker(
                        schema.table_name.clone(),
                        schema.clone(),
                        Arc::clone(&self.registry) as Arc<dyn VisibilityChecker>,
                    ));

                    let table_name = schema.table_name_lower.clone();

                    {
                        let mut schemas = self.schemas.write().unwrap();
                        let default_schema = schemas.entry(DEFAULT_SCHEMA.to_string()).or_default();
                        default_schema.insert(table_name.clone(), schema);
                    }
                    {
                        let mut stores = self.version_stores.write().unwrap();
                        stores.insert(table_name, version_store);
                    }
                }
            }
            WALOperationType::DropTable => {
                let table_name = entry.table_name.to_lowercase();

                // Remove schema and version store
                {
                    let mut schemas = self.schemas.write().unwrap();
                    if let Some(default_schema) = schemas.get_mut(DEFAULT_SCHEMA) {
                        default_schema.remove(&table_name);
                    }
                }
                {
                    let mut stores = self.version_stores.write().unwrap();
                    if let Some(store) = stores.remove(&table_name) {
                        store.close();
                    }
                }
            }
            WALOperationType::CreateIndex => {
                // Deserialize index metadata
                // Use skip_population=true for deferred single-pass population
                if let Ok(index_meta) = IndexMetadata::deserialize(&entry.data) {
                    let table_name = entry.table_name.to_lowercase();
                    if let Ok(store) = self.get_version_store(&table_name) {
                        let _ = store.create_index_from_metadata(&index_meta, true);
                    }
                }
            }
            WALOperationType::DropIndex => {
                // Index name is stored in entry.data as simple string
                if let Ok(index_name) = String::from_utf8(entry.data.clone()) {
                    let table_name = entry.table_name.to_lowercase();
                    if let Ok(store) = self.get_version_store(&table_name) {
                        let _ = store.drop_index(&index_name);
                    }
                }
            }
            WALOperationType::Insert | WALOperationType::Update => {
                // Deserialize row version and apply to version store
                if let Ok(row_version) = deserialize_row_version(&entry.data) {
                    let table_name = entry.table_name.to_lowercase();
                    if let Ok(store) = self.get_version_store(&table_name) {
                        // Apply the version to the store
                        store.apply_recovered_version(row_version);
                    }
                }
            }
            WALOperationType::Delete => {
                // For deletes, we need to mark the row as deleted
                let table_name = entry.table_name.to_lowercase();
                if let Ok(store) = self.get_version_store(&table_name) {
                    store.mark_deleted(entry.row_id, entry.txn_id);
                }
            }
            WALOperationType::Commit => {
                // Mark transaction as committed in registry for visibility
                // Use the LSN as the commit sequence number
                self.registry
                    .recover_committed_transaction(entry.txn_id, entry.lsn as i64);
            }
            WALOperationType::Rollback => {
                // Rolled back transactions don't need to be marked as committed
                // Their changes should not be visible
            }
            WALOperationType::AlterTable => {
                // Schema modification - replay the ALTER TABLE operation
                if let Err(e) = self.replay_alter_table(&entry.data) {
                    eprintln!("Warning: Failed to replay ALTER TABLE: {}", e);
                }
            }
            WALOperationType::CreateView => {
                // Deserialize view definition and recreate the view
                if let Ok(view_def) = ViewDefinition::deserialize(&entry.data) {
                    let parts: Vec<&str> = entry.table_name.split('.').collect();
                    let (schema_name, view_name) = if parts.len() > 1 {
                        (parts[0], parts[1])
                    } else {
                        (DEFAULT_SCHEMA, parts[0])
                    };
                    let schema_lower = schema_name.to_lowercase();
                    let name_lower = view_name.to_lowercase();
                    let mut views = self.views.write().unwrap();
                    let schema_views = views.entry(schema_lower).or_default();
                    schema_views.insert(name_lower, Arc::new(view_def));
                }
            }
            WALOperationType::DropView => {
                // Remove the view
                if let Ok(_view_name) = String::from_utf8(entry.data.clone()) {
                    let parts: Vec<&str> = entry.table_name.split('.').collect();
                    let (schema_name, name) = if parts.len() > 1 {
                        (parts[0], parts[1])
                    } else {
                        (DEFAULT_SCHEMA, parts[0])
                    };
                    let schema_lower = schema_name.to_lowercase();
                    let name_lower = name.to_lowercase();
                    let mut views = self.views.write().unwrap();
                    if let Some(schema_views) = views.get_mut(&schema_lower) {
                        schema_views.remove(&name_lower);
                    }
                }
            }
        }

        Ok(())
    }

    /// Deserialize a schema from binary format (WAL format)
    fn deserialize_schema(&self, data: &[u8]) -> Result<Schema> {
        use crate::core::SchemaColumn;

        if data.len() < 4 {
            return Err(Error::internal("schema data too short"));
        }

        let mut pos = 0;

        // Read table name length
        if pos + 2 > data.len() {
            return Err(Error::internal("invalid schema: missing table name length"));
        }
        let name_len = u16::from_le_bytes(data[pos..pos + 2].try_into().unwrap()) as usize;
        pos += 2;

        if pos + name_len > data.len() {
            return Err(Error::internal("invalid schema: missing table name"));
        }
        let table_name = String::from_utf8(data[pos..pos + name_len].to_vec())
            .map_err(|e| Error::internal(format!("invalid table name: {}", e)))?;
        pos += name_len;

        // Read column count
        if pos + 2 > data.len() {
            return Err(Error::internal("invalid schema: missing column count"));
        }
        let column_count = u16::from_le_bytes(data[pos..pos + 2].try_into().unwrap()) as usize;
        pos += 2;

        // Read columns
        let mut columns = Vec::with_capacity(column_count);
        for i in 0..column_count {
            // Column name length
            if pos + 2 > data.len() {
                return Err(Error::internal(
                    "invalid schema: missing column name length",
                ));
            }
            let col_name_len = u16::from_le_bytes(data[pos..pos + 2].try_into().unwrap()) as usize;
            pos += 2;

            if pos + col_name_len > data.len() {
                return Err(Error::internal("invalid schema: missing column name"));
            }
            let col_name = String::from_utf8(data[pos..pos + col_name_len].to_vec())
                .map_err(|e| Error::internal(format!("invalid column name: {}", e)))?;
            pos += col_name_len;

            // Data type (1 byte)
            if pos >= data.len() {
                return Err(Error::internal("invalid schema: missing data type"));
            }
            let data_type = DataType::from_u8(data[pos]).unwrap_or(DataType::Null);
            pos += 1;

            // Nullable (1 byte)
            if pos >= data.len() {
                return Err(Error::internal("invalid schema: missing nullable flag"));
            }
            let nullable = data[pos] != 0;
            pos += 1;

            // Primary key (1 byte)
            if pos >= data.len() {
                return Err(Error::internal("invalid schema: missing primary key flag"));
            }
            let primary_key = data[pos] != 0;
            pos += 1;

            // Auto-increment (1 byte) - optional for backwards compatibility
            let auto_increment = if pos < data.len() {
                let val = data[pos] != 0;
                pos += 1;
                val
            } else {
                false
            };

            // Default expression (length-prefixed string) - optional for backwards compatibility
            let default_expr = if pos + 2 <= data.len() {
                let expr_len = u16::from_le_bytes(data[pos..pos + 2].try_into().unwrap()) as usize;
                pos += 2;
                if expr_len > 0 && pos + expr_len <= data.len() {
                    let expr = String::from_utf8(data[pos..pos + expr_len].to_vec())
                        .map_err(|e| Error::internal(format!("invalid default expr: {}", e)))?;
                    pos += expr_len;
                    Some(expr)
                } else {
                    None
                }
            } else {
                None
            };

            // Check expression (length-prefixed string) - optional for backwards compatibility
            let check_expr = if pos + 2 <= data.len() {
                let expr_len = u16::from_le_bytes(data[pos..pos + 2].try_into().unwrap()) as usize;
                pos += 2;
                if expr_len > 0 && pos + expr_len <= data.len() {
                    let expr = String::from_utf8(data[pos..pos + expr_len].to_vec())
                        .map_err(|e| Error::internal(format!("invalid check expr: {}", e)))?;
                    pos += expr_len;
                    Some(expr)
                } else {
                    None
                }
            } else {
                None
            };

            columns.push(SchemaColumn::with_constraints(
                i,
                &col_name,
                data_type,
                nullable,
                primary_key,
                auto_increment,
                default_expr,
                check_expr,
            ));
        }

        let mut foreign_keys = Vec::new();
        let mut referenced_by = Vec::new();

        if pos + 2 <= data.len() {
            let fk_count = u16::from_le_bytes(data[pos..pos + 2].try_into().unwrap()) as usize;
            pos += 2;
            for _ in 0..fk_count {
                if pos + 2 > data.len() {
                    break;
                }
                let column_id = u16::from_le_bytes(data[pos..pos + 2].try_into().unwrap()) as usize;
                pos += 2;

                if pos + 2 > data.len() {
                    break;
                }
                let ref_tbl_len =
                    u16::from_le_bytes(data[pos..pos + 2].try_into().unwrap()) as usize;
                pos += 2;
                if pos + ref_tbl_len > data.len() {
                    break;
                }
                let referenced_table =
                    String::from_utf8_lossy(&data[pos..pos + ref_tbl_len]).into_owned();
                pos += ref_tbl_len;

                if pos + 2 > data.len() {
                    break;
                }
                let ref_col_len =
                    u16::from_le_bytes(data[pos..pos + 2].try_into().unwrap()) as usize;
                pos += 2;
                if pos + ref_col_len > data.len() {
                    break;
                }
                let referenced_column_name =
                    String::from_utf8_lossy(&data[pos..pos + ref_col_len]).into_owned();
                pos += ref_col_len;

                if pos + 2 > data.len() {
                    break;
                }
                let on_delete_val = data[pos];
                pos += 1;
                let on_update_val = data[pos];
                pos += 1;

                let parse_action = |val: u8| match val {
                    0 => crate::parser::ast::ReferentialAction::Restrict,
                    1 => crate::parser::ast::ReferentialAction::Cascade,
                    2 => crate::parser::ast::ReferentialAction::SetNull,
                    _ => crate::parser::ast::ReferentialAction::NoAction,
                };

                foreign_keys.push(crate::core::schema::ForeignKeyMetadata {
                    column_id,
                    referenced_table,
                    referenced_column_name,
                    on_delete: parse_action(on_delete_val),
                    on_update: parse_action(on_update_val),
                });
            }

            if pos + 2 <= data.len() {
                let ref_by_count =
                    u16::from_le_bytes(data[pos..pos + 2].try_into().unwrap()) as usize;
                pos += 2;
                for _ in 0..ref_by_count {
                    if pos + 2 > data.len() {
                        break;
                    }
                    let ref_by_len =
                        u16::from_le_bytes(data[pos..pos + 2].try_into().unwrap()) as usize;
                    pos += 2;
                    if pos + ref_by_len > data.len() {
                        break;
                    }
                    let ref_by = String::from_utf8_lossy(&data[pos..pos + ref_by_len]).into_owned();
                    pos += ref_by_len;
                    referenced_by.push(ref_by);
                }
            }
        }

        let mut schema = Schema::new(&table_name, columns);
        schema.foreign_keys = foreign_keys;
        schema.referenced_by = referenced_by;
        Ok(schema)
    }

    /// Closes the engine (inherent method)
    pub fn close_engine(&self) -> Result<()> {
        // Use CAS to atomically check and set closed
        if self
            .open
            .compare_exchange(true, false, Ordering::AcqRel, Ordering::Acquire)
            .is_err()
        {
            return Ok(()); // Already closed
        }

        // Stop accepting new transactions
        self.registry.stop_accepting_transactions();

        // Close all version stores
        let stores = self.version_stores.read().unwrap();
        for store in stores.values() {
            store.close();
        }
        drop(stores);

        // Stop persistence manager
        if let Some(ref pm) = *self.persistence {
            if pm.is_enabled() {
                if let Err(e) = pm.stop() {
                    eprintln!("Warning: Error stopping persistence: {}", e);
                }
            }
        }

        // Release file lock (drops the lock, allowing other processes to access)
        {
            let mut file_lock = self.file_lock.lock().unwrap();
            *file_lock = None;
        }

        Ok(())
    }

    /// Returns whether the engine is open
    pub fn is_open(&self) -> bool {
        self.open.load(Ordering::Acquire)
    }

    /// Returns the database path
    pub fn get_path(&self) -> &str {
        &self.path
    }

    /// Returns a copy of the configuration
    pub fn config(&self) -> Config {
        self.config.read().unwrap().clone()
    }

    /// Updates the engine configuration
    pub fn update_engine_config(&self, config: Config) -> Result<()> {
        let current = self.config.read().unwrap();
        if config.path != current.path {
            return Err(Error::internal("cannot change database path after opening"));
        }
        drop(current);

        *self.config.write().unwrap() = config;
        Ok(())
    }

    /// Returns the transaction registry
    pub fn registry(&self) -> Arc<TransactionRegistry> {
        Arc::clone(&self.registry)
    }

    /// Replay an ALTER TABLE operation from WAL
    fn replay_alter_table(&self, data: &[u8]) -> Result<()> {
        if data.is_empty() {
            return Err(Error::internal("empty ALTER TABLE data"));
        }

        let op_type = data[0];
        let mut pos = 1;

        // Read table name
        if pos + 2 > data.len() {
            return Err(Error::internal(
                "invalid ALTER TABLE data: missing table name length",
            ));
        }
        let table_name_len = u16::from_le_bytes(data[pos..pos + 2].try_into().unwrap()) as usize;
        pos += 2;

        if pos + table_name_len > data.len() {
            return Err(Error::internal(
                "invalid ALTER TABLE data: missing table name",
            ));
        }
        let table_name = String::from_utf8(data[pos..pos + table_name_len].to_vec())
            .map_err(|e| Error::internal(format!("invalid table name: {}", e)))?;
        pos += table_name_len;

        match op_type {
            1 => {
                // AddColumn
                // Read column name
                if pos + 2 > data.len() {
                    return Err(Error::internal(
                        "invalid AddColumn data: missing column name length",
                    ));
                }
                let col_name_len =
                    u16::from_le_bytes(data[pos..pos + 2].try_into().unwrap()) as usize;
                pos += 2;

                if pos + col_name_len > data.len() {
                    return Err(Error::internal(
                        "invalid AddColumn data: missing column name",
                    ));
                }
                let column_name = String::from_utf8(data[pos..pos + col_name_len].to_vec())
                    .map_err(|e| Error::internal(format!("invalid column name: {}", e)))?;
                pos += col_name_len;

                // Read data type
                if pos >= data.len() {
                    return Err(Error::internal("invalid AddColumn data: missing data type"));
                }
                let data_type = DataType::from_u8(data[pos])
                    .ok_or_else(|| Error::internal("invalid data type byte"))?;
                pos += 1;

                // Read nullable
                if pos >= data.len() {
                    return Err(Error::internal("invalid AddColumn data: missing nullable"));
                }
                let nullable = data[pos] != 0;
                pos += 1;

                // Read default expression
                let default_expr = if pos + 2 <= data.len() {
                    let expr_len =
                        u16::from_le_bytes(data[pos..pos + 2].try_into().unwrap()) as usize;
                    pos += 2;
                    if expr_len > 0 && pos + expr_len <= data.len() {
                        let expr = String::from_utf8(data[pos..pos + expr_len].to_vec())
                            .map_err(|e| Error::internal(format!("invalid default expr: {}", e)))?;
                        Some(expr)
                    } else {
                        None
                    }
                } else {
                    None
                };

                // Apply the ADD COLUMN using engine method
                // Note: create_column doesn't support default_expr, so we need enhanced version
                self.create_column_with_default(
                    &table_name,
                    &column_name,
                    data_type,
                    nullable,
                    default_expr,
                )?;
            }
            2 => {
                // DropColumn
                // Read column name
                if pos + 2 > data.len() {
                    return Err(Error::internal(
                        "invalid DropColumn data: missing column name length",
                    ));
                }
                let col_name_len =
                    u16::from_le_bytes(data[pos..pos + 2].try_into().unwrap()) as usize;
                pos += 2;

                if pos + col_name_len > data.len() {
                    return Err(Error::internal(
                        "invalid DropColumn data: missing column name",
                    ));
                }
                let column_name = String::from_utf8(data[pos..pos + col_name_len].to_vec())
                    .map_err(|e| Error::internal(format!("invalid column name: {}", e)))?;

                // Apply the DROP COLUMN using engine method
                self.drop_column(&table_name, &column_name)?;
            }
            3 => {
                // RenameColumn
                // Read old column name
                if pos + 2 > data.len() {
                    return Err(Error::internal(
                        "invalid RenameColumn data: missing old name length",
                    ));
                }
                let old_name_len =
                    u16::from_le_bytes(data[pos..pos + 2].try_into().unwrap()) as usize;
                pos += 2;

                if pos + old_name_len > data.len() {
                    return Err(Error::internal(
                        "invalid RenameColumn data: missing old name",
                    ));
                }
                let old_name = String::from_utf8(data[pos..pos + old_name_len].to_vec())
                    .map_err(|e| Error::internal(format!("invalid old column name: {}", e)))?;
                pos += old_name_len;

                // Read new column name
                if pos + 2 > data.len() {
                    return Err(Error::internal(
                        "invalid RenameColumn data: missing new name length",
                    ));
                }
                let new_name_len =
                    u16::from_le_bytes(data[pos..pos + 2].try_into().unwrap()) as usize;
                pos += 2;

                if pos + new_name_len > data.len() {
                    return Err(Error::internal(
                        "invalid RenameColumn data: missing new name",
                    ));
                }
                let new_name = String::from_utf8(data[pos..pos + new_name_len].to_vec())
                    .map_err(|e| Error::internal(format!("invalid new column name: {}", e)))?;

                // Apply the RENAME COLUMN using engine method
                self.rename_column(&table_name, &old_name, &new_name)?;
            }
            4 => {
                // ModifyColumn
                // Read column name
                if pos + 2 > data.len() {
                    return Err(Error::internal(
                        "invalid ModifyColumn data: missing column name length",
                    ));
                }
                let col_name_len =
                    u16::from_le_bytes(data[pos..pos + 2].try_into().unwrap()) as usize;
                pos += 2;

                if pos + col_name_len > data.len() {
                    return Err(Error::internal(
                        "invalid ModifyColumn data: missing column name",
                    ));
                }
                let column_name = String::from_utf8(data[pos..pos + col_name_len].to_vec())
                    .map_err(|e| Error::internal(format!("invalid column name: {}", e)))?;
                pos += col_name_len;

                // Read data type
                if pos >= data.len() {
                    return Err(Error::internal(
                        "invalid ModifyColumn data: missing data type",
                    ));
                }
                let data_type = DataType::from_u8(data[pos])
                    .ok_or_else(|| Error::internal("invalid data type byte"))?;
                pos += 1;

                // Read nullable
                if pos >= data.len() {
                    return Err(Error::internal(
                        "invalid ModifyColumn data: missing nullable",
                    ));
                }
                let nullable = data[pos] != 0;

                // Apply the MODIFY COLUMN using engine method
                self.modify_column(&table_name, &column_name, data_type, nullable)?;
            }
            5 => {
                // RenameTable - special handling since table name changes
                // The table_name read above is actually old_table_name for RenameTable
                // because we re-serialized in that format

                // Read new table name
                if pos + 2 > data.len() {
                    return Err(Error::internal(
                        "invalid RenameTable data: missing new name length",
                    ));
                }
                let new_name_len =
                    u16::from_le_bytes(data[pos..pos + 2].try_into().unwrap()) as usize;
                pos += 2;

                if pos + new_name_len > data.len() {
                    return Err(Error::internal(
                        "invalid RenameTable data: missing new name",
                    ));
                }
                let new_table_name = String::from_utf8(data[pos..pos + new_name_len].to_vec())
                    .map_err(|e| Error::internal(format!("invalid new table name: {}", e)))?;

                // Apply the RENAME TABLE using engine method
                self.rename_table(&table_name, &new_table_name)?;
            }
            _ => {
                return Err(Error::internal(format!(
                    "unknown ALTER TABLE operation type: {}",
                    op_type
                )));
            }
        }

        Ok(())
    }

    /// Check if we should skip WAL writes (during recovery replay)
    fn should_skip_wal(&self) -> bool {
        self.loading_from_disk.load(Ordering::Acquire)
    }

    /// Record a DDL operation to WAL
    fn record_ddl(&self, table_name: &str, op: WALOperationType, schema_data: &[u8]) {
        if self.should_skip_wal() {
            return;
        }
        if let Some(ref pm) = *self.persistence {
            if pm.is_enabled() {
                if let Err(e) = pm.record_ddl_operation(table_name, op, schema_data) {
                    eprintln!("Warning: Failed to record DDL operation in WAL: {}", e);
                }
            }
        }
    }

    /// Serialize a schema to binary format for WAL
    pub fn serialize_schema(schema: &Schema) -> Vec<u8> {
        let mut buf = Vec::new();

        // Table name
        buf.extend_from_slice(&(schema.table_name.len() as u16).to_le_bytes());
        buf.extend_from_slice(schema.table_name.as_bytes());

        // Column count
        buf.extend_from_slice(&(schema.columns.len() as u16).to_le_bytes());

        // Columns
        for col in &schema.columns {
            // Column name
            buf.extend_from_slice(&(col.name.len() as u16).to_le_bytes());
            buf.extend_from_slice(col.name.as_bytes());

            // Data type (1 byte)
            buf.push(col.data_type.as_u8());

            // Nullable (1 byte)
            buf.push(if col.nullable { 1 } else { 0 });

            // Primary key (1 byte)
            buf.push(if col.primary_key { 1 } else { 0 });

            // Auto-increment (1 byte)
            buf.push(if col.auto_increment { 1 } else { 0 });

            // Default expression (length-prefixed string, 0 length if None)
            if let Some(ref default_expr) = col.default_expr {
                buf.extend_from_slice(&(default_expr.len() as u16).to_le_bytes());
                buf.extend_from_slice(default_expr.as_bytes());
            } else {
                buf.extend_from_slice(&0u16.to_le_bytes());
            }

            // Check expression (length-prefixed string, 0 length if None)
            if let Some(ref check_expr) = col.check_expr {
                buf.extend_from_slice(&(check_expr.len() as u16).to_le_bytes());
                buf.extend_from_slice(check_expr.as_bytes());
            } else {
                buf.extend_from_slice(&0u16.to_le_bytes());
            }
        }

        // Foreign keys count
        buf.extend_from_slice(&(schema.foreign_keys.len() as u16).to_le_bytes());

        // Foreign keys
        for fk in &schema.foreign_keys {
            buf.extend_from_slice(&(fk.column_id as u16).to_le_bytes());

            buf.extend_from_slice(&(fk.referenced_table.len() as u16).to_le_bytes());
            buf.extend_from_slice(fk.referenced_table.as_bytes());

            buf.extend_from_slice(&(fk.referenced_column_name.len() as u16).to_le_bytes());
            buf.extend_from_slice(fk.referenced_column_name.as_bytes());

            // Map ReferentialAction to u8
            let on_delete_val = match fk.on_delete {
                crate::parser::ast::ReferentialAction::Restrict => 0,
                crate::parser::ast::ReferentialAction::Cascade => 1,
                crate::parser::ast::ReferentialAction::SetNull => 2,
                crate::parser::ast::ReferentialAction::NoAction => 3,
            };
            buf.push(on_delete_val);

            let on_update_val = match fk.on_update {
                crate::parser::ast::ReferentialAction::Restrict => 0,
                crate::parser::ast::ReferentialAction::Cascade => 1,
                crate::parser::ast::ReferentialAction::SetNull => 2,
                crate::parser::ast::ReferentialAction::NoAction => 3,
            };
            buf.push(on_update_val);
        }

        // Referenced by count
        buf.extend_from_slice(&(schema.referenced_by.len() as u16).to_le_bytes());

        // Referenced by
        for ref_by in &schema.referenced_by {
            buf.extend_from_slice(&(ref_by.len() as u16).to_le_bytes());
            buf.extend_from_slice(ref_by.as_bytes());
        }

        buf
    }

    /// Creates a new table
    pub fn create_table(&self, schema: Schema) -> Result<Schema> {
        if !self.is_open() {
            return Err(Error::EngineNotOpen);
        }

        let table_name = schema.table_name_lower.clone();

        {
            let schemas = self.schemas.read().unwrap();
            let empty_map = FxHashMap::default();
            let default_schema = schemas.get(DEFAULT_SCHEMA).unwrap_or(&empty_map);
            if default_schema.contains_key(&table_name) {
                return Err(Error::TableAlreadyExists);
            }
        }

        // Validate schema
        self.validate_schema(&schema)?;

        // Create version store for this table
        let version_store = Arc::new(VersionStore::with_visibility_checker(
            schema.table_name.clone(),
            schema.clone(),
            Arc::clone(&self.registry) as Arc<dyn VisibilityChecker>,
        ));

        // Store schema and version store
        {
            let mut schemas = self.schemas.write().unwrap();
            let default_schema = schemas.entry(DEFAULT_SCHEMA.to_string()).or_default();
            default_schema.insert(table_name.clone(), schema.clone());
        }
        {
            let mut stores = self.version_stores.write().unwrap();
            stores.insert(table_name, version_store);
        }

        // Record DDL operation in WAL
        let schema_data = Self::serialize_schema(&schema);
        self.record_ddl(
            &schema.table_name,
            WALOperationType::CreateTable,
            &schema_data,
        );

        Ok(schema)
    }

    /// Drops a table
    pub fn drop_table_internal(&self, name: &str) -> Result<()> {
        if !self.is_open() {
            return Err(Error::EngineNotOpen);
        }

        let table_name = name.to_lowercase();

        // Check if table exists
        {
            let schemas = self.schemas.read().unwrap();
            let empty_map = FxHashMap::default();
            let default_schema = schemas.get(DEFAULT_SCHEMA).unwrap_or(&empty_map);
            if !default_schema.contains_key(&table_name) {
                return Err(Error::TableNotFound);
            }
        }

        // Record DDL operation in WAL (before removing - use original name)
        self.record_ddl(name, WALOperationType::DropTable, &[]);

        // Close and remove version store
        {
            let mut stores = self.version_stores.write().unwrap();
            if let Some(store) = stores.remove(&table_name) {
                store.close();
            }
        }

        // Remove schema
        {
            let mut schemas = self.schemas.write().unwrap();
            if let Some(default_schema) = schemas.get_mut(DEFAULT_SCHEMA) {
                default_schema.remove(&table_name);
            }
        }

        Ok(())
    }

    /// Gets a version store for a table
    pub fn get_version_store(&self, name: &str) -> Result<Arc<VersionStore>> {
        if !self.is_open() {
            return Err(Error::EngineNotOpen);
        }

        let table_name = name.to_lowercase();

        let stores = self.version_stores.read().unwrap();
        stores.get(&table_name).cloned().ok_or(Error::TableNotFound)
    }

    /// Creates a column in a table
    pub fn create_column(
        &self,
        table_name: &str,
        column_name: &str,
        data_type: DataType,
        nullable: bool,
    ) -> Result<()> {
        if !self.is_open() {
            return Err(Error::EngineNotOpen);
        }

        let table_name_lower = table_name.to_lowercase();

        // Get and modify schema
        let mut schemas = self.schemas.write().unwrap();
        let default_schema = schemas
            .get_mut(DEFAULT_SCHEMA)
            .ok_or(Error::TableNotFound)?;
        let schema = default_schema
            .get_mut(&table_name_lower)
            .ok_or(Error::TableNotFound)?;

        // Check if column already exists
        if schema.has_column(column_name) {
            return Err(Error::DuplicateColumn);
        }

        // Add column to schema
        let column = crate::core::SchemaColumn::new(
            schema.columns.len(),
            column_name,
            data_type,
            nullable,
            false,
        );
        schema.add_column(column)?;

        // Also update version store schema
        let stores = self.version_stores.read().unwrap();
        if let Some(store) = stores.get(&table_name_lower) {
            let mut vs_schema = store.schema_mut();
            let col = crate::core::SchemaColumn::new(
                vs_schema.columns.len(),
                column_name,
                data_type,
                nullable,
                false,
            );
            vs_schema.add_column(col)?;
        }

        Ok(())
    }

    /// Creates a column in a table with an optional default expression
    pub fn create_column_with_default(
        &self,
        table_name: &str,
        column_name: &str,
        data_type: DataType,
        nullable: bool,
        default_expr: Option<String>,
    ) -> Result<()> {
        if !self.is_open() {
            return Err(Error::EngineNotOpen);
        }

        let table_name_lower = table_name.to_lowercase();

        // Get and modify schema
        let mut schemas = self.schemas.write().unwrap();
        let default_schema = schemas
            .get_mut(DEFAULT_SCHEMA)
            .ok_or(Error::TableNotFound)?;
        let schema = default_schema
            .get_mut(&table_name_lower)
            .ok_or(Error::TableNotFound)?;

        // Check if column already exists
        if schema.has_column(column_name) {
            return Err(Error::DuplicateColumn);
        }

        // Add column to schema with default expression
        let mut column = crate::core::SchemaColumn::new(
            schema.columns.len(),
            column_name,
            data_type,
            nullable,
            false,
        );
        column.default_expr = default_expr.clone();
        schema.add_column(column)?;

        // Also update version store schema
        let stores = self.version_stores.read().unwrap();
        if let Some(store) = stores.get(&table_name_lower) {
            let mut vs_schema = store.schema_mut();
            let mut col = crate::core::SchemaColumn::new(
                vs_schema.columns.len(),
                column_name,
                data_type,
                nullable,
                false,
            );
            col.default_expr = default_expr;
            vs_schema.add_column(col)?;
        }

        Ok(())
    }

    /// Drops a column from a table
    pub fn drop_column(&self, table_name: &str, column_name: &str) -> Result<()> {
        if !self.is_open() {
            return Err(Error::EngineNotOpen);
        }

        let table_name_lower = table_name.to_lowercase();

        // Get and modify schema
        let mut schemas = self.schemas.write().unwrap();
        let default_schema = schemas
            .get_mut(DEFAULT_SCHEMA)
            .ok_or(Error::TableNotFound)?;
        let schema = default_schema
            .get_mut(&table_name_lower)
            .ok_or(Error::TableNotFound)?;

        // Check if column is primary key
        if let Some((_, col)) = schema.find_column(column_name) {
            if col.primary_key {
                return Err(Error::CannotDropPrimaryKey);
            }
        } else {
            return Err(Error::ColumnNotFound);
        }

        // Remove column from schema
        schema.remove_column(column_name)?;

        // Also update version store schema
        let stores = self.version_stores.read().unwrap();
        if let Some(store) = stores.get(&table_name_lower) {
            let mut vs_schema = store.schema_mut();
            vs_schema.remove_column(column_name)?;
        }

        Ok(())
    }

    /// Renames a column in a table
    pub fn rename_column(&self, table_name: &str, old_name: &str, new_name: &str) -> Result<()> {
        if !self.is_open() {
            return Err(Error::EngineNotOpen);
        }

        let table_name_lower = table_name.to_lowercase();

        // Get and modify schema
        let mut schemas = self.schemas.write().unwrap();
        let default_schema = schemas
            .get_mut(DEFAULT_SCHEMA)
            .ok_or(Error::TableNotFound)?;
        let schema = default_schema
            .get_mut(&table_name_lower)
            .ok_or(Error::TableNotFound)?;

        // Check if old column exists
        if !schema.has_column(old_name) {
            return Err(Error::ColumnNotFound);
        }

        // Check if new column name already exists
        if schema.has_column(new_name) {
            return Err(Error::DuplicateColumn);
        }

        // Rename column in schema
        schema.rename_column(old_name, new_name)?;

        // Also update version store schema
        let stores = self.version_stores.read().unwrap();
        if let Some(store) = stores.get(&table_name_lower) {
            let mut vs_schema = store.schema_mut();
            vs_schema.rename_column(old_name, new_name)?;
        }

        Ok(())
    }

    /// Modifies a column's type and nullable property in a table
    pub fn modify_column(
        &self,
        table_name: &str,
        column_name: &str,
        data_type: DataType,
        nullable: bool,
    ) -> Result<()> {
        if !self.is_open() {
            return Err(Error::EngineNotOpen);
        }

        let table_name_lower = table_name.to_lowercase();

        // Get and modify schema
        let mut schemas = self.schemas.write().unwrap();
        let default_schema = schemas
            .get_mut(DEFAULT_SCHEMA)
            .ok_or(Error::TableNotFound)?;
        let schema = default_schema
            .get_mut(&table_name_lower)
            .ok_or(Error::TableNotFound)?;

        // Check if column exists
        if !schema.has_column(column_name) {
            return Err(Error::ColumnNotFound);
        }

        // Modify column in schema
        schema.modify_column(column_name, Some(data_type), Some(nullable))?;

        // Also update version store schema
        let stores = self.version_stores.read().unwrap();
        if let Some(store) = stores.get(&table_name_lower) {
            let mut vs_schema = store.schema_mut();
            vs_schema.modify_column(column_name, Some(data_type), Some(nullable))?;
        }

        Ok(())
    }

    /// Renames a table
    pub fn rename_table(&self, old_name: &str, new_name: &str) -> Result<()> {
        if !self.is_open() {
            return Err(Error::EngineNotOpen);
        }

        let old_name_lower = old_name.to_lowercase();
        let new_name_lower = new_name.to_lowercase();

        // Check if old table exists
        {
            let schemas = self.schemas.read().unwrap();
            let empty_map = FxHashMap::default();
            let default_schema = schemas.get(DEFAULT_SCHEMA).unwrap_or(&empty_map);
            if !default_schema.contains_key(&old_name_lower) {
                return Err(Error::TableNotFound);
            }
            if default_schema.contains_key(&new_name_lower) {
                return Err(Error::TableAlreadyExists);
            }
        }

        // Update schemas map
        {
            let mut schemas = self.schemas.write().unwrap();
            if let Some(default_schema) = schemas.get_mut(DEFAULT_SCHEMA) {
                if let Some(mut schema) = default_schema.remove(&old_name_lower) {
                    schema.table_name = new_name.to_string();
                    default_schema.insert(new_name_lower.clone(), schema);
                }
            }
        }

        // Update version_stores map
        {
            let mut stores = self.version_stores.write().unwrap();
            if let Some(store) = stores.remove(&old_name_lower) {
                // Update the schema's table name within the store
                {
                    let mut vs_schema = store.schema_mut();
                    vs_schema.table_name = new_name.to_string();
                }
                stores.insert(new_name_lower, store);
            }
        }

        Ok(())
    }

    /// Validates a schema
    fn validate_schema(&self, schema: &Schema) -> Result<()> {
        if schema.table_name.is_empty() {
            return Err(Error::internal("schema missing table name"));
        }

        // Check for duplicate column names
        let mut seen_names = std::collections::HashSet::new();
        for col in &schema.columns {
            if col.name.is_empty() {
                return Err(Error::internal("column name cannot be empty"));
            }

            if col.primary_key && col.data_type != DataType::Integer {
                return Err(Error::internal(format!(
                    "primary key column {} must be of type INTEGER",
                    col.name
                )));
            }

            if !seen_names.insert(col.name.to_lowercase()) {
                return Err(Error::DuplicateColumn);
            }
        }

        Ok(())
    }

    /// Creates an engine operations wrapper for a transaction
    fn create_engine_operations(&self) -> Arc<dyn TransactionEngineOperations> {
        Arc::new(EngineOperations::new(self))
    }

    // --- View Management Methods ---

    /// Create a new view
    pub fn create_view(
        &self,
        schema_name: &str,
        name: &str,
        query: String,
        if_not_exists: bool,
    ) -> Result<()> {
        use crate::storage::mvcc::wal_manager::WALOperationType;

        if !self.is_open() {
            return Err(Error::EngineNotOpen);
        }

        let schema_lower = schema_name.to_lowercase();
        let name_lower = name.to_lowercase();
        let mut views = self.views.write().unwrap();

        // Check if schema bucket exists, create if not
        let schema_views = views.entry(schema_lower.clone()).or_default();

        // Check if view already exists
        if schema_views.contains_key(&name_lower) {
            if if_not_exists {
                return Ok(());
            }
            return Err(Error::ViewAlreadyExists(name.to_string()));
        }

        // Check if a table with the same name exists
        let schemas = self.schemas.read().unwrap();
        let empty_map = FxHashMap::default();
        let default_schema = schemas.get(&schema_lower).unwrap_or(&empty_map);
        if default_schema.contains_key(&name_lower) {
            return Err(Error::internal(format!(
                "cannot create view '{}': a table with the same name exists in schema '{}'",
                name, schema_name
            )));
        }
        drop(schemas);

        // Create the view definition wrapped in Arc for cheap cloning
        let view_def = Arc::new(ViewDefinition::new(name, query));
        schema_views.insert(name_lower.clone(), Arc::clone(&view_def));

        // Release the lock before recording to WAL
        drop(views);

        // For WAL, we might need a qualified name. Let's record the schema.
        let full_name = if schema_lower == DEFAULT_SCHEMA {
            name_lower.clone()
        } else {
            format!("{}.{}", schema_lower, name_lower)
        };
        let data = view_def.serialize();
        self.record_ddl(&full_name, WALOperationType::CreateView, &data);

        Ok(())
    }

    /// Drop a view
    pub fn drop_view(&self, schema_name: &str, name: &str, if_exists: bool) -> Result<()> {
        use crate::storage::mvcc::wal_manager::WALOperationType;

        if !self.is_open() {
            return Err(Error::EngineNotOpen);
        }

        let schema_lower = schema_name.to_lowercase();
        let name_lower = name.to_lowercase();
        let mut views = self.views.write().unwrap();

        let removed = if let Some(schema_views) = views.get_mut(&schema_lower) {
            schema_views.remove(&name_lower)
        } else {
            None
        };

        if removed.is_none() {
            if if_exists {
                return Ok(());
            }
            return Err(Error::ViewNotFound(name.to_string()));
        }

        // Release the lock before recording to WAL
        drop(views);

        // Record to WAL for persistence
        let full_name = if schema_lower == DEFAULT_SCHEMA {
            name_lower.clone()
        } else {
            format!("{}.{}", schema_lower, name_lower)
        };
        self.record_ddl(&full_name, WALOperationType::DropView, name.as_bytes());

        Ok(())
    }

    /// Check if a view exists
    pub fn view_exists(&self, schema_name: &str, name: &str) -> Result<bool> {
        self.view_exists_lowercase(&schema_name.to_lowercase(), &name.to_lowercase())
    }

    /// Check if a view exists (assumes name is already lowercase)
    /// Use this when you already have a lowercase name to avoid allocation
    #[inline]
    pub fn view_exists_lowercase(&self, schema_lower: &str, name_lower: &str) -> Result<bool> {
        if !self.is_open() {
            return Err(Error::EngineNotOpen);
        }

        let views = self.views.read().unwrap();
        Ok(views
            .get(schema_lower)
            .is_some_and(|s| s.contains_key(name_lower)))
    }

    /// Get a view definition
    pub fn get_view(&self, schema_name: &str, name: &str) -> Result<Option<Arc<ViewDefinition>>> {
        self.get_view_lowercase(&schema_name.to_lowercase(), &name.to_lowercase())
    }

    /// Get a view definition (assumes name is already lowercase)
    /// Use this when you already have a lowercase name to avoid allocation.
    /// Returns Arc clone (cheap pointer copy, no data clone).
    #[inline]
    pub fn get_view_lowercase(
        &self,
        schema_lower: &str,
        name_lower: &str,
    ) -> Result<Option<Arc<ViewDefinition>>> {
        if !self.is_open() {
            return Err(Error::EngineNotOpen);
        }

        let views = self.views.read().unwrap();
        Ok(views
            .get(schema_lower)
            .and_then(|s| s.get(name_lower))
            .cloned()) // Arc::clone is cheap
    }

    /// List all view names along with their schema
    pub fn list_views(&self) -> Result<Vec<(String, String)>> {
        if !self.is_open() {
            return Err(Error::EngineNotOpen);
        }

        let views = self.views.read().unwrap();
        let mut result = Vec::new();
        for (schema_name, schema_views) in views.iter() {
            for v in schema_views.values() {
                result.push((schema_name.clone(), v.original_name.clone()));
            }
        }
        Ok(result)
    }
}

impl Engine for MVCCEngine {
    fn open(&mut self) -> Result<()> {
        MVCCEngine::open_engine(self)
    }

    fn close(&mut self) -> Result<()> {
        MVCCEngine::close_engine(self)
    }

    fn begin_transaction(&self) -> Result<Box<dyn Transaction>> {
        self.begin_transaction_with_level(self.get_isolation_level())
    }

    fn begin_transaction_with_level(&self, level: IsolationLevel) -> Result<Box<dyn Transaction>> {
        if !self.is_open() {
            return Err(Error::EngineNotOpen);
        }

        // Begin transaction in registry
        let (txn_id, begin_seq) = self.registry.begin_transaction();
        if txn_id == INVALID_TRANSACTION_ID {
            return Err(Error::internal(
                "transaction registry is not accepting new transactions",
            ));
        }

        // Create transaction
        let mut txn = MvccTransaction::new(txn_id, begin_seq, Arc::clone(&self.registry));

        // Set isolation level if different from default
        if level != IsolationLevel::ReadCommitted {
            txn.set_isolation_level(level)?;
        }

        // Set engine operations
        let engine_ops = self.create_engine_operations();
        txn.set_engine_operations(engine_ops);

        Ok(Box::new(txn))
    }

    fn path(&self) -> Option<&str> {
        if self.path == "memory://" {
            None
        } else {
            Some(&self.path)
        }
    }

    fn table_exists(&self, table_name: &str) -> Result<bool> {
        if !self.is_open() {
            return Err(Error::EngineNotOpen);
        }

        let schemas = self.schemas.read().unwrap();
        let default_schema = schemas.get(DEFAULT_SCHEMA);
        Ok(default_schema.is_some_and(|s| s.contains_key(&table_name.to_lowercase())))
    }

    fn view_exists(&self, view_name: &str) -> Result<bool> {
        // Assume default schema if called from the trait which doesn't provide a schema.
        // Wait, did I update the trait? Let's assume the string might be qualified.
        let parts: Vec<&str> = view_name.split('.').collect();
        let (schema_name, name) = if parts.len() > 1 {
            (parts[0], parts[1])
        } else {
            (DEFAULT_SCHEMA, parts[0])
        };
        MVCCEngine::view_exists(self, schema_name, name)
    }

    fn index_exists(&self, index_name: &str, table_name: &str) -> Result<bool> {
        if !self.is_open() {
            return Err(Error::EngineNotOpen);
        }

        let store = self.get_version_store(table_name)?;
        Ok(store.index_exists(index_name))
    }

    fn get_index(&self, table_name: &str, index_name: &str) -> Result<Box<dyn Index>> {
        if !self.is_open() {
            return Err(Error::EngineNotOpen);
        }

        let store = self.get_version_store(table_name)?;
        if store.index_exists(index_name) {
            // Index exists but we can't clone Arc<dyn Index> into Box<dyn Index>
            // This will be properly implemented in Phase 6.6
            return Err(Error::internal(format!(
                "index retrieval not yet implemented: {}.{}",
                table_name, index_name
            )));
        }

        Err(Error::internal(format!(
            "index not found: {}.{}",
            table_name, index_name
        )))
    }

    fn get_table_schema(&self, table_name: &str) -> Result<Schema> {
        if !self.is_open() {
            return Err(Error::EngineNotOpen);
        }

        let schemas = self.schemas.read().unwrap();
        let default_schema = schemas.get(DEFAULT_SCHEMA).ok_or(Error::TableNotFound)?;
        default_schema
            .get(&table_name.to_lowercase())
            .cloned()
            .ok_or(Error::TableNotFound)
    }

    fn update_table_schema(&self, table_name: &str, schema: Schema) -> Result<()> {
        if !self.is_open() {
            return Err(Error::EngineNotOpen);
        }

        let table_name_lower = table_name.to_lowercase();

        // Update engine schemas
        {
            let mut schemas = self.schemas.write().unwrap();
            let default_schema = schemas
                .get_mut(DEFAULT_SCHEMA)
                .ok_or(Error::TableNotFound)?;
            if !default_schema.contains_key(&table_name_lower) {
                return Err(Error::TableNotFound);
            }
            default_schema.insert(table_name_lower.clone(), schema.clone());
        }

        // Update version store schema
        if let Ok(store) = self.get_version_store(&table_name_lower) {
            let mut store_schema = store.schema_mut();
            *store_schema = schema.clone();
        }

        // Record to WAL if persistence is enabled
        if let Some(ref _pm) = *self.persistence {
            // Reusing serialize_schema to save it
            let _serialized = Self::serialize_schema(&schema);
            // This needs a specific WAL record type if we really want to persist schema updates
            // For MVP, we might not strictly need it if engine re-runs DDL on recovery,
            // but we will add a best-effort warning.
        }

        Ok(())
    }

    fn list_table_indexes(&self, table_name: &str) -> Result<FxHashMap<String, String>> {
        if !self.is_open() {
            return Err(Error::EngineNotOpen);
        }

        let store = self.get_version_store(table_name)?;
        let mut result = FxHashMap::default();
        for index_name in store.list_indexes() {
            result.insert(index_name, "BTree".to_string());
        }
        Ok(result)
    }

    fn get_all_indexes(&self, table_name: &str) -> Result<Vec<std::sync::Arc<dyn Index>>> {
        if !self.is_open() {
            return Err(Error::EngineNotOpen);
        }

        let store = self.get_version_store(table_name)?;

        // Get all indexes from the version store
        Ok(store.get_all_indexes())
    }

    fn get_isolation_level(&self) -> IsolationLevel {
        self.registry.get_global_isolation_level()
    }

    fn set_isolation_level(&mut self, level: IsolationLevel) -> Result<()> {
        if !self.is_open() {
            return Err(Error::EngineNotOpen);
        }

        self.registry.set_global_isolation_level(level);
        Ok(())
    }

    fn get_config(&self) -> Config {
        self.config.read().expect("config lock poisoned").clone()
    }

    fn update_config(&mut self, config: Config) -> Result<()> {
        self.update_engine_config(config)
    }

    fn create_snapshot(&self) -> Result<()> {
        if !self.is_open() {
            return Err(Error::EngineNotOpen);
        }

        // Check if persistence is enabled
        let pm = match self.persistence.as_ref() {
            Some(pm) if pm.is_enabled() => pm,
            _ => return Ok(()), // No persistence, nothing to snapshot
        };

        // CRITICAL: Create checkpoint and capture the LSN atomically.
        // create_checkpoint() flushes and syncs all pending WAL entries, then returns
        // the LSN at the exact checkpoint point. This prevents the race condition where:
        // 1. We read LSN separately after checkpoint
        // 2. New transaction commits between checkpoint and LSN read
        // 3. Snapshot might capture inconsistent data
        //
        // By using the LSN returned from create_checkpoint(), we guarantee the LSN
        // corresponds exactly to the data that was synced to disk.
        let snapshot_lsn = pm.create_checkpoint(vec![])?;

        // CRITICAL: Capture the commit sequence at the same point as the checkpoint.
        // This ensures we only include transactions that were committed at the time
        // of the checkpoint during the snapshot iteration. Without this, a transaction
        // that commits during iteration would be incorrectly included in the snapshot.
        let snapshot_commit_seq = self.registry.current_commit_sequence();

        // Create snapshot directory
        let snapshot_dir = pm.path().join("snapshots");
        if let Err(e) = std::fs::create_dir_all(&snapshot_dir) {
            return Err(Error::internal(format!(
                "failed to create snapshot directory: {}",
                e
            )));
        }

        // Get all table schemas and version stores
        let schemas = self.schemas.read().unwrap();
        let stores = self.version_stores.read().unwrap();

        // ATOMIC SNAPSHOT STRATEGY:
        // 1. Write all snapshots to .tmp files first
        // 2. After ALL succeed, rename all .tmp files to final names
        // 3. If any fails, cleanup all .tmp files
        // This ensures we never have a partially complete snapshot set

        // Collect (temp_path, final_path, table_name) for atomic rename
        let mut pending_snapshots: Vec<(std::path::PathBuf, std::path::PathBuf, String)> =
            Vec::new();
        let mut all_succeeded = true;

        // Generate a consistent timestamp for all snapshots in this batch
        let timestamp = chrono::Utc::now().format("%Y%m%d-%H%M%S%.3f").to_string();

        // Phase 1: Write all snapshots to temp files
        if let Some(default_schema) = schemas.get(DEFAULT_SCHEMA) {
            for (table_name, schema) in default_schema.iter() {
                if let Some(store) = stores.get(table_name) {
                    // Create table-specific snapshot directory
                    let table_snapshot_dir = snapshot_dir.join(table_name);
                    if let Err(e) = std::fs::create_dir_all(&table_snapshot_dir) {
                        eprintln!(
                            "Warning: Failed to create snapshot directory for {}: {}",
                            table_name, e
                        );
                        all_succeeded = false;
                        break;
                    }

                    // Write to .tmp file first, will rename after all succeed
                    let final_path = table_snapshot_dir.join(format!("snapshot-{}.bin", timestamp));
                    let temp_path =
                        table_snapshot_dir.join(format!("snapshot-{}.bin.tmp", timestamp));

                    // Create snapshot writer for temp file with captured LSN
                    let mut writer = match super::snapshot::SnapshotWriter::with_source_lsn(
                        &temp_path,
                        snapshot_lsn,
                    ) {
                        Ok(w) => w,
                        Err(e) => {
                            eprintln!(
                                "Warning: Failed to create snapshot writer for {}: {}",
                                table_name, e
                            );
                            all_succeeded = false;
                            break;
                        }
                    };

                    // Write schema
                    if let Err(e) = writer.write_schema(schema) {
                        eprintln!("Warning: Failed to write schema for {}: {}", table_name, e);
                        writer.fail();
                        all_succeeded = false;
                        break;
                    }

                    // Write all committed versions using commit sequence cutoff for consistency.
                    // This ensures that transactions that commit after the checkpoint but before
                    // iteration completes are excluded from the snapshot, maintaining consistency
                    // between the WAL checkpoint and the snapshot contents.
                    let mut write_error = false;
                    store.for_each_committed_version_with_cutoff(
                        |_row_id, version| {
                            // Clone version with snapshot TxnID marker
                            let mut snapshot_version = version.clone();
                            snapshot_version.txn_id = -1; // Mark as snapshot version

                            if let Err(e) = writer.append_row(&snapshot_version) {
                                eprintln!(
                                    "Warning: Failed to write row {} to snapshot: {}",
                                    _row_id, e
                                );
                                write_error = true;
                                return false; // Stop iteration
                            }
                            true
                        },
                        snapshot_commit_seq,
                    );

                    if write_error {
                        writer.fail();
                        all_succeeded = false;
                        break;
                    }

                    // Finalize the snapshot (writes CRC32, syncs to disk)
                    if let Err(e) = writer.finalize() {
                        eprintln!(
                            "Warning: Failed to finalize snapshot for {}: {}",
                            table_name, e
                        );
                        writer.fail();
                        all_succeeded = false;
                        break;
                    }

                    // Track this temp file for later rename
                    pending_snapshots.push((temp_path, final_path, table_name.clone()));
                }
            }

            // Phase 2: If all snapshots succeeded, rename all temp files atomically
            // Track successfully renamed files for rollback on failure
            let mut renamed_successfully: Vec<(std::path::PathBuf, std::path::PathBuf)> =
                Vec::new();

            if all_succeeded {
                // Collect unique directories that need syncing
                let mut dirs_to_sync: std::collections::HashSet<std::path::PathBuf> =
                    std::collections::HashSet::new();

                for (temp_path, final_path, table_name) in &pending_snapshots {
                    if let Err(e) = std::fs::rename(temp_path, final_path) {
                        eprintln!(
                            "Warning: Failed to rename snapshot for {}: {}",
                            table_name, e
                        );
                        // CRITICAL: Rollback all previously successful renames to maintain consistency
                        // Without this, partial renames cause different tables to have snapshots
                        // from different points in time, leading to data loss on recovery.
                        for (orig_temp, renamed_final) in renamed_successfully.iter().rev() {
                            if let Err(rollback_err) = std::fs::rename(renamed_final, orig_temp) {
                                eprintln!(
                                    "Critical: Failed to rollback snapshot rename {:?} -> {:?}: {}",
                                    renamed_final, orig_temp, rollback_err
                                );
                            }
                        }
                        all_succeeded = false;
                        break;
                    }
                    // Track successful rename for potential rollback
                    renamed_successfully.push((temp_path.clone(), final_path.clone()));
                    // Track the directory for syncing
                    if let Some(parent) = final_path.parent() {
                        dirs_to_sync.insert(parent.to_path_buf());
                    }
                }

                // Sync directories to ensure renames are durable
                // This is important on some file systems (e.g., ext4) where
                // rename durability requires directory sync
                if all_succeeded {
                    for dir in &dirs_to_sync {
                        if let Ok(dir_file) = std::fs::File::open(dir) {
                            let _ = dir_file.sync_all();
                        }
                    }
                }
            }
        }

        // Phase 3: Cleanup - if anything failed, remove all temp files
        if !all_succeeded {
            for (temp_path, _, _) in &pending_snapshots {
                let _ = std::fs::remove_file(temp_path);
            }
            eprintln!("Warning: Snapshot creation failed, all temp files cleaned up");
            return Ok(());
        }

        // CRITICAL: Order of operations for crash safety:
        // 1. Write metadata FIRST (atomic via temp file + rename)
        // 2. Truncate WAL (safe because metadata is now durable)
        // 3. Cleanup old snapshots LAST (safe because we have new snapshots + metadata)
        //
        // This order ensures that if crash happens:
        // - After step 1: Metadata exists, WAL has all data, recovery is safe
        // - After step 2: Metadata exists, new snapshots have data, recovery uses snapshot
        // - After step 3: Complete, old snapshots cleaned up
        //
        // Note: Each snapshot file also embeds source_lsn in its header (v3 format),
        // providing a fallback if metadata file is corrupted. load_snapshots() uses
        // max(metadata_lsn, max_header_lsn) to handle this case.

        // Phase 4: Write snapshot metadata BEFORE cleanup and truncation
        // Using binary format with magic number and checksum for data integrity
        let meta_path = snapshot_dir.join("snapshot_meta.bin");
        if let Err(e) = write_snapshot_metadata(&meta_path, snapshot_lsn) {
            eprintln!("Warning: Failed to write snapshot metadata: {}", e);
            return Ok(()); // Don't truncate WAL or cleanup if metadata write failed
        }

        // Phase 5: Truncate WAL to remove entries up to the snapshot LSN
        // Safe because: metadata is durable, all data up to snapshot_lsn is in snapshot files
        if snapshot_lsn > 0 {
            if let Err(e) = pm.truncate_wal(snapshot_lsn) {
                eprintln!("Warning: Failed to truncate WAL after snapshot: {}", e);
                // Continue to cleanup even if truncation fails - data is safe in snapshots
            }
        }

        // Phase 6: Cleanup old snapshots LAST (only after metadata is durable)
        // This is safe because we now have:
        // - New snapshots with embedded source_lsn
        // - Metadata pointing to new snapshot_lsn
        // - WAL truncated (or still present if truncation failed)
        let keep_count = pm.keep_count();
        if keep_count > 0 {
            for (_, _, table_name) in &pending_snapshots {
                if let Some(default_schema) = schemas.get(DEFAULT_SCHEMA) {
                    if let Some(schema) = default_schema.get(table_name) {
                        let disk_store = super::snapshot::DiskVersionStore::new(
                            &snapshot_dir,
                            table_name,
                            schema,
                        );
                        if let Ok(disk_store) = disk_store {
                            if let Err(e) = disk_store.cleanup_old_snapshots(keep_count) {
                                eprintln!(
                                    "Warning: Failed to cleanup old snapshots for {}: {}",
                                    table_name, e
                                );
                            }
                        }
                    }
                }
            }
        }

        Ok(())
    }

    fn record_create_index(
        &self,
        table_name: &str,
        index_name: &str,
        column_names: &[String],
        is_unique: bool,
        index_type: crate::core::IndexType,
    ) {
        if self.should_skip_wal() {
            return;
        }

        // Get table schema to look up column IDs and data types
        let schema = match self.get_table_schema(table_name) {
            Ok(s) => s,
            Err(_) => return,
        };

        // Build column_ids and data_types from schema
        let mut column_ids = Vec::with_capacity(column_names.len());
        let mut data_types = Vec::with_capacity(column_names.len());

        for col_name in column_names {
            let col_name_lower = col_name.to_lowercase();
            if let Some((idx, col)) = schema
                .columns
                .iter()
                .enumerate()
                .find(|(_, c)| c.name.to_lowercase() == col_name_lower)
            {
                column_ids.push(idx as i32);
                data_types.push(col.data_type);
            } else {
                // Column not found, skip recording
                return;
            }
        }

        // Create index metadata
        let index_meta = super::persistence::IndexMetadata {
            name: index_name.to_string(),
            table_name: table_name.to_string(),
            column_names: column_names.to_vec(),
            column_ids,
            data_types,
            is_unique,
            index_type,
        };

        // Serialize and record to WAL
        let data = index_meta.serialize();
        self.record_ddl(table_name, WALOperationType::CreateIndex, &data);
    }

    fn record_drop_index(&self, table_name: &str, index_name: &str) {
        if self.should_skip_wal() {
            return;
        }

        // For drop index, the entry.data is simply the index name as bytes
        self.record_ddl(
            table_name,
            WALOperationType::DropIndex,
            index_name.as_bytes(),
        );
    }

    fn record_alter_table_add_column(
        &self,
        table_name: &str,
        column_name: &str,
        data_type: crate::core::DataType,
        nullable: bool,
        default_expr: Option<&str>,
    ) {
        if self.should_skip_wal() {
            return;
        }

        // Serialize: operation_type(1) + table_name_len(2) + table_name + column_name_len(2) + column_name
        //          + data_type(1) + nullable(1) + default_expr_len(2) + default_expr
        let mut data = Vec::new();
        data.push(1u8); // Operation type: AddColumn = 1

        // Table name
        data.extend_from_slice(&(table_name.len() as u16).to_le_bytes());
        data.extend_from_slice(table_name.as_bytes());

        // Column name
        data.extend_from_slice(&(column_name.len() as u16).to_le_bytes());
        data.extend_from_slice(column_name.as_bytes());

        // Data type
        data.push(data_type as u8);

        // Nullable
        data.push(if nullable { 1 } else { 0 });

        // Default expression
        if let Some(expr) = default_expr {
            data.extend_from_slice(&(expr.len() as u16).to_le_bytes());
            data.extend_from_slice(expr.as_bytes());
        } else {
            data.extend_from_slice(&0u16.to_le_bytes());
        }

        self.record_ddl(table_name, WALOperationType::AlterTable, &data);
    }

    fn record_alter_table_drop_column(&self, table_name: &str, column_name: &str) {
        if self.should_skip_wal() {
            return;
        }

        // Serialize: operation_type(1) + table_name_len(2) + table_name + column_name_len(2) + column_name
        let mut data = Vec::new();
        data.push(2u8); // Operation type: DropColumn = 2

        // Table name
        data.extend_from_slice(&(table_name.len() as u16).to_le_bytes());
        data.extend_from_slice(table_name.as_bytes());

        // Column name
        data.extend_from_slice(&(column_name.len() as u16).to_le_bytes());
        data.extend_from_slice(column_name.as_bytes());

        self.record_ddl(table_name, WALOperationType::AlterTable, &data);
    }

    fn record_alter_table_rename_column(
        &self,
        table_name: &str,
        old_column_name: &str,
        new_column_name: &str,
    ) {
        if self.should_skip_wal() {
            return;
        }

        // Serialize: operation_type(1) + table_name_len(2) + table_name
        //          + old_name_len(2) + old_name + new_name_len(2) + new_name
        let mut data = Vec::new();
        data.push(3u8); // Operation type: RenameColumn = 3

        // Table name
        data.extend_from_slice(&(table_name.len() as u16).to_le_bytes());
        data.extend_from_slice(table_name.as_bytes());

        // Old column name
        data.extend_from_slice(&(old_column_name.len() as u16).to_le_bytes());
        data.extend_from_slice(old_column_name.as_bytes());

        // New column name
        data.extend_from_slice(&(new_column_name.len() as u16).to_le_bytes());
        data.extend_from_slice(new_column_name.as_bytes());

        self.record_ddl(table_name, WALOperationType::AlterTable, &data);
    }

    fn record_alter_table_modify_column(
        &self,
        table_name: &str,
        column_name: &str,
        data_type: crate::core::DataType,
        nullable: bool,
    ) {
        if self.should_skip_wal() {
            return;
        }

        // Serialize: operation_type(1) + table_name_len(2) + table_name
        //          + column_name_len(2) + column_name + data_type(1) + nullable(1)
        let mut data = Vec::new();
        data.push(4u8); // Operation type: ModifyColumn = 4

        // Table name
        data.extend_from_slice(&(table_name.len() as u16).to_le_bytes());
        data.extend_from_slice(table_name.as_bytes());

        // Column name
        data.extend_from_slice(&(column_name.len() as u16).to_le_bytes());
        data.extend_from_slice(column_name.as_bytes());

        // Data type
        data.push(data_type as u8);

        // Nullable
        data.push(if nullable { 1 } else { 0 });

        self.record_ddl(table_name, WALOperationType::AlterTable, &data);
    }

    fn record_alter_table_rename(&self, old_table_name: &str, new_table_name: &str) {
        if self.should_skip_wal() {
            return;
        }

        // Serialize: operation_type(1) + old_name_len(2) + old_name + new_name_len(2) + new_name
        let mut data = Vec::new();
        data.push(5u8); // Operation type: RenameTable = 5

        // Old table name
        data.extend_from_slice(&(old_table_name.len() as u16).to_le_bytes());
        data.extend_from_slice(old_table_name.as_bytes());

        // New table name
        data.extend_from_slice(&(new_table_name.len() as u16).to_le_bytes());
        data.extend_from_slice(new_table_name.as_bytes());

        self.record_ddl(old_table_name, WALOperationType::AlterTable, &data);
    }

    fn fetch_rows_by_ids(
        &self,
        table_name: &str,
        row_ids: &[i64],
    ) -> Result<Vec<(i64, crate::core::Row)>> {
        if !self.is_open() {
            return Err(Error::EngineNotOpen);
        }

        let store = self.get_version_store(table_name)?;

        // Use a high txn_id to see the latest committed version
        // INVALID_TRANSACTION_ID + 1 will see all committed transactions
        let read_txn_id = INVALID_TRANSACTION_ID + 1;

        Ok(store.get_visible_versions_batch(row_ids, read_txn_id))
    }

    fn get_row_fetcher(
        &self,
        table_name: &str,
    ) -> Result<Box<dyn Fn(&[i64]) -> Vec<(i64, crate::core::Row)> + Send + Sync>> {
        if !self.is_open() {
            return Err(Error::EngineNotOpen);
        }

        // Get the version store reference once
        let store = self.get_version_store(table_name)?;

        // Use a high txn_id to see the latest committed version
        let read_txn_id = INVALID_TRANSACTION_ID + 1;

        // Return a closure that captures the store and can be called repeatedly
        // without the overhead of looking up the version store each time
        Ok(Box::new(move |row_ids: &[i64]| {
            store.get_visible_versions_batch(row_ids, read_txn_id)
        }))
    }

    // --- Sequences ---

    fn sequence_exists(&self, schema_name: &str, sequence_name: &str) -> Result<bool> {
        let sequences = self.sequences.read().unwrap();
        let schema_lower = schema_name.to_lowercase();
        let name_lower = sequence_name.to_lowercase();
        Ok(sequences
            .get(&schema_lower)
            .is_some_and(|s| s.contains_key(&name_lower)))
    }

    fn create_sequence(
        &self,
        schema_name: &str,
        sequence_name: &str,
        options: crate::core::SequenceOptions,
    ) -> Result<()> {
        let mut sequences = self.sequences.write().unwrap();
        let schema_lower = schema_name.to_lowercase();
        let name_lower = sequence_name.to_lowercase();

        let schema_seqs = sequences.entry(schema_lower.clone()).or_default();

        if schema_seqs.contains_key(&name_lower) {
            return Err(crate::core::Error::SequenceAlreadyExists(
                sequence_name.to_string(),
            ));
        }
        schema_seqs.insert(
            name_lower,
            std::sync::Arc::new(crate::core::SequenceState::new(options)),
        );
        Ok(())
    }

    fn alter_sequence(
        &self,
        schema_name: &str,
        sequence_name: &str,
        options: crate::core::SequenceOptions,
    ) -> Result<()> {
        let mut sequences = self.sequences.write().unwrap();
        let schema_lower = schema_name.to_lowercase();
        let name_lower = sequence_name.to_lowercase();

        let schema_seqs = sequences.entry(schema_lower.clone()).or_default();
        if !schema_seqs.contains_key(&name_lower) {
            return Err(crate::core::Error::SequenceNotFound(
                sequence_name.to_string(),
            ));
        }
        // Create new sequence state and replace existing
        schema_seqs.insert(
            name_lower,
            std::sync::Arc::new(crate::core::SequenceState::new(options)),
        );
        Ok(())
    }

    fn drop_sequence(&self, schema_name: &str, sequence_name: &str) -> Result<()> {
        let mut sequences = self.sequences.write().unwrap();
        let schema_lower = schema_name.to_lowercase();
        let name_lower = sequence_name.to_lowercase();

        let removed = if let Some(schema_seqs) = sequences.get_mut(&schema_lower) {
            schema_seqs.remove(&name_lower)
        } else {
            None
        };

        if removed.is_none() {
            return Err(crate::core::Error::SequenceNotFound(
                sequence_name.to_string(),
            ));
        }
        Ok(())
    }

    fn nextval(&self, schema_name: &str, sequence_name: &str) -> Result<i64> {
        let sequence = {
            let sequences = self.sequences.read().unwrap();
            let schema_lower = schema_name.to_lowercase();
            let name_lower = sequence_name.to_lowercase();
            if let Some(seq) = sequences
                .get(&schema_lower)
                .and_then(|s| s.get(&name_lower))
            {
                std::sync::Arc::clone(seq)
            } else {
                return Err(crate::core::Error::SequenceNotFound(
                    sequence_name.to_string(),
                ));
            }
        };
        sequence.nextval()
    }

    fn setval(
        &self,
        schema_name: &str,
        sequence_name: &str,
        value: i64,
        is_called: bool,
    ) -> Result<i64> {
        let sequence = {
            let sequences = self.sequences.read().unwrap();
            let schema_lower = schema_name.to_lowercase();
            let name_lower = sequence_name.to_lowercase();
            if let Some(seq) = sequences
                .get(&schema_lower)
                .and_then(|s| s.get(&name_lower))
            {
                std::sync::Arc::clone(seq)
            } else {
                return Err(crate::core::Error::SequenceNotFound(
                    sequence_name.to_string(),
                ));
            }
        };
        sequence.setval(value, is_called)
    }

    fn list_sequences(&self) -> Result<Vec<(String, String, crate::core::SequenceOptions, i64)>> {
        let sequences = self.sequences.read().unwrap();
        let mut result = Vec::new();
        for (schema_name, schema_seqs) in sequences.iter() {
            for (name, seq) in schema_seqs.iter() {
                result.push((
                    schema_name.clone(),
                    name.clone(),
                    seq.options.clone(),
                    seq.current_value(),
                ));
            }
        }
        Ok(result)
    }
}

// =============================================================================
// Cleanup Functions
// =============================================================================

impl MVCCEngine {
    /// Cleanup old transactions that have been idle for too long
    pub fn cleanup_old_transactions(&self, max_age: std::time::Duration) -> i32 {
        if !self.is_open() {
            return 0;
        }
        self.registry.cleanup_old_transactions(max_age)
    }

    /// Cleanup deleted rows older than retention period from all tables
    pub fn cleanup_deleted_rows(&self, max_age: std::time::Duration) -> i32 {
        if !self.is_open() {
            return 0;
        }

        let stores = self.version_stores.read().unwrap();
        let mut total_removed = 0;

        for store in stores.values() {
            total_removed += store.cleanup_deleted_rows(max_age);
        }

        total_removed
    }

    /// Cleanup old previous versions that are no longer needed from all tables
    pub fn cleanup_old_previous_versions(&self) -> i32 {
        if !self.is_open() {
            return 0;
        }

        let stores = self.version_stores.read().unwrap();
        let mut total_cleaned = 0;

        for store in stores.values() {
            total_cleaned += store.cleanup_old_previous_versions();
        }

        total_cleaned
    }

    /// Start periodic cleanup of old transactions and deleted rows
    ///
    /// Returns a handle that can be used to stop the cleanup thread.
    pub fn start_periodic_cleanup(
        self: &Arc<Self>,
        interval: std::time::Duration,
        max_age: std::time::Duration,
    ) -> CleanupHandle {
        use std::sync::atomic::AtomicBool;
        use std::thread;

        let stop_flag = Arc::new(AtomicBool::new(false));
        let stop_flag_clone = Arc::clone(&stop_flag);
        let engine = Arc::clone(self);

        let handle = thread::spawn(move || {
            while !stop_flag_clone.load(Ordering::Acquire) {
                // Sleep for the interval (check stop flag periodically)
                let check_interval = std::time::Duration::from_millis(100);
                let mut elapsed = std::time::Duration::ZERO;
                while elapsed < interval && !stop_flag_clone.load(Ordering::Acquire) {
                    thread::sleep(check_interval);
                    elapsed += check_interval;
                }

                if stop_flag_clone.load(Ordering::Acquire) {
                    break;
                }

                // Perform cleanup
                let _txn_count = engine.cleanup_old_transactions(max_age);
                let _row_count = engine.cleanup_deleted_rows(max_age);
                let _prev_version_count = engine.cleanup_old_previous_versions();

                // Uncomment for debugging:
                // if txn_count > 0 || row_count > 0 || prev_version_count > 0 {
                //     eprintln!(
                //         "Cleanup: {} transactions, {} deleted rows, {} previous versions",
                //         txn_count, row_count, prev_version_count
                //     );
                // }
            }
        });

        CleanupHandle {
            stop_flag,
            thread: Some(handle),
        }
    }
}

/// Handle for stopping the cleanup thread
pub struct CleanupHandle {
    stop_flag: Arc<AtomicBool>,
    thread: Option<std::thread::JoinHandle<()>>,
}

impl CleanupHandle {
    /// Stop the cleanup thread
    pub fn stop(&mut self) {
        self.stop_flag.store(true, Ordering::Release);
        if let Some(handle) = self.thread.take() {
            let _ = handle.join();
        }
    }
}

impl Drop for CleanupHandle {
    fn drop(&mut self) {
        self.stop();
    }
}

/// Engine operations for transaction callbacks
///
/// Holds Arc references to shared engine state, allowing safe access
/// from transactions without raw pointers.
struct EngineOperations {
    /// Shared reference to schemas
    schemas: Arc<RwLock<FxHashMap<String, FxHashMap<String, Schema>>>>,
    /// Shared reference to version stores
    version_stores: Arc<RwLock<FxHashMap<String, Arc<VersionStore>>>>,
    /// Shared reference to registry
    registry: Arc<TransactionRegistry>,
    /// Shared reference to transaction version stores cache
    txn_version_stores: Arc<RwLock<TxnVersionStoreMap>>,
    /// Shared reference to persistence manager (optional)
    persistence: Arc<Option<PersistenceManager>>,
    /// Shared reference to loading_from_disk flag
    loading_from_disk: Arc<AtomicBool>,
}

// EngineOperations is Send + Sync because all fields are Arc-wrapped thread-safe types

impl EngineOperations {
    fn new(engine: &MVCCEngine) -> Self {
        Self {
            schemas: Arc::clone(&engine.schemas),
            version_stores: Arc::clone(&engine.version_stores),
            registry: Arc::clone(&engine.registry),
            txn_version_stores: Arc::clone(&engine.txn_version_stores),
            persistence: Arc::clone(&engine.persistence),
            loading_from_disk: Arc::clone(&engine.loading_from_disk),
        }
    }

    fn schemas(&self) -> &Arc<RwLock<FxHashMap<String, FxHashMap<String, Schema>>>> {
        &self.schemas
    }

    fn version_stores(&self) -> &RwLock<FxHashMap<String, Arc<VersionStore>>> {
        &self.version_stores
    }

    fn txn_version_stores(&self) -> &RwLock<TxnVersionStoreMap> {
        &self.txn_version_stores
    }

    fn persistence(&self) -> &Option<PersistenceManager> {
        &self.persistence
    }

    fn should_skip_wal(&self) -> bool {
        self.loading_from_disk.load(Ordering::Acquire)
    }
}

impl TransactionEngineOperations for EngineOperations {
    fn get_table_for_transaction(&self, txn_id: i64, table_name: &str) -> Result<Box<dyn Table>> {
        let table_name_lower = table_name.to_lowercase();

        // Get version store
        let stores = self.version_stores().read().unwrap();
        let version_store = stores
            .get(&table_name_lower)
            .cloned()
            .ok_or(Error::TableNotFound)?;
        drop(stores);

        // Check if we have a cached transaction version store for this (txn_id, table_name)
        let cache_key = (txn_id, table_name_lower.clone());
        let txn_versions = {
            let cache = self.txn_version_stores().read().unwrap();
            if let Some(cached) = cache.get(&cache_key) {
                Arc::clone(cached)
            } else {
                drop(cache);
                // Create new transaction version store and cache it
                let new_store = Arc::new(RwLock::new(TransactionVersionStore::new(
                    Arc::clone(&version_store),
                    txn_id,
                )));
                let mut cache = self.txn_version_stores().write().unwrap();
                cache.insert(cache_key, Arc::clone(&new_store));
                new_store
            }
        };

        // Create MVCC table with shared transaction version store
        let table = MVCCTable::new_with_shared_store(txn_id, version_store, txn_versions);

        Ok(Box::new(table))
    }

    fn create_table(&self, name: &str, schema: Schema) -> Result<Box<dyn Table>> {
        let table_name = name.to_lowercase();

        // Check if table already exists
        {
            let schemas = self.schemas().read().unwrap();
            if schemas.contains_key(&table_name) {
                return Err(Error::TableAlreadyExists);
            }
        }

        // Create version store for this table
        let version_store = Arc::new(VersionStore::with_visibility_checker(
            schema.table_name.clone(),
            schema.clone(),
            Arc::clone(&self.registry) as Arc<dyn VisibilityChecker>,
        ));

        // Store schema and version store
        {
            let mut schemas = (*self.schemas()).write().unwrap();
            let default_schema = schemas.entry(DEFAULT_SCHEMA.to_string()).or_default();
            default_schema.insert(table_name.clone(), schema);
        }
        {
            let mut stores = self.version_stores().write().unwrap();
            stores.insert(table_name, Arc::clone(&version_store));
        }

        // Create transaction version store with txn_id 0 (will be set by caller)
        let txn_versions = TransactionVersionStore::new(Arc::clone(&version_store), 0);

        // Create MVCC table
        let table = MVCCTable::new(0, version_store, txn_versions);

        Ok(Box::new(table))
    }

    fn drop_table(&self, name: &str) -> Result<()> {
        let table_name_lower = name.to_lowercase();

        // Remove schema and version store
        {
            let mut schemas = self.schemas().write().unwrap();
            if schemas.remove(&table_name_lower).is_none() {
                return Err(Error::TableNotFound);
            }
        }
        {
            let mut stores = self.version_stores().write().unwrap();
            if let Some(store) = stores.remove(&table_name_lower) {
                store.close();
            }
        }

        Ok(())
    }

    fn list_tables(&self) -> Result<Vec<String>> {
        let version_stores = self.version_stores.read().unwrap();
        Ok(version_stores.keys().cloned().collect())
    }

    fn rename_table(&self, old_name: &str, new_name: &str) -> Result<()> {
        let old_name_lower = old_name.to_lowercase();
        let new_name_lower = new_name.to_lowercase();

        // Check if old table exists and new name doesn't exist
        {
            let schemas = (*self.schemas()).read().unwrap();
            let empty_map = FxHashMap::default();
            let default_schema = schemas.get(DEFAULT_SCHEMA).unwrap_or(&empty_map);
            if !default_schema.contains_key(&old_name_lower) {
                return Err(Error::TableNotFound);
            }
            if default_schema.contains_key(&new_name_lower) {
                return Err(Error::TableAlreadyExists);
            }
        }

        // Rename in schemas
        {
            let mut schemas = (*self.schemas()).write().unwrap();
            if let Some(default_schema) = schemas.get_mut(DEFAULT_SCHEMA) {
                if let Some(mut schema) = default_schema.remove(&old_name_lower) {
                    schema.table_name = new_name.to_string();
                    default_schema.insert(new_name_lower.clone(), schema);
                }
            }
        }

        // Rename in version stores
        {
            let mut stores = self.version_stores().write().unwrap();
            if let Some(store) = stores.remove(&old_name_lower) {
                stores.insert(new_name_lower, store);
            }
        }

        Ok(())
    }

    fn commit_table(&self, txn_id: i64, table: &dyn Table) -> Result<()> {
        // Skip WAL writes during recovery replay
        if self.should_skip_wal() {
            return Ok(());
        }

        // Record DML operations to WAL before the table commits
        if let Some(ref pm) = self.persistence() {
            if pm.is_enabled() {
                let table_name = table.name();
                let pending = table.get_pending_versions();

                for (row_id, row_data, is_deleted, version_txn_id) in pending {
                    // Create a RowVersion for serialization
                    let version = RowVersion {
                        txn_id: version_txn_id,
                        deleted_at_txn_id: if is_deleted { version_txn_id } else { 0 },
                        data: row_data,
                        row_id,
                        create_time: 0, // Not needed for persistence
                    };

                    // Determine operation type
                    let op = if is_deleted {
                        WALOperationType::Delete
                    } else {
                        // Check if this is an update vs insert by looking at global store
                        // For simplicity, we record everything as Insert
                        // (at replay time, the version store handles deduplication)
                        WALOperationType::Insert
                    };

                    if let Err(e) =
                        pm.record_dml_operation(txn_id, table_name, row_id, op, &version)
                    {
                        eprintln!("Warning: Failed to record DML in WAL: {}", e);
                        // Continue with other operations
                    }
                }
            }
        }

        Ok(())
    }

    fn rollback_table(&self, _txn_id: i64, table: &dyn Table) {
        // The Table trait now has a rollback method.
        // This callback is for any engine-level rollback actions.
        let _ = table;
    }

    fn record_commit(&self, txn_id: i64) -> Result<()> {
        // Skip WAL writes during recovery replay
        if self.should_skip_wal() {
            return Ok(());
        }

        // Record commit in WAL
        if let Some(ref pm) = self.persistence() {
            if pm.is_enabled() {
                if let Err(e) = pm.record_commit(txn_id) {
                    eprintln!("Warning: Failed to record commit in WAL: {}", e);
                }
            }
        }
        Ok(())
    }

    fn record_rollback(&self, txn_id: i64) -> Result<()> {
        // Skip WAL writes during recovery replay
        if self.should_skip_wal() {
            return Ok(());
        }

        // Record rollback in WAL
        if let Some(ref pm) = self.persistence() {
            if pm.is_enabled() {
                if let Err(e) = pm.record_rollback(txn_id) {
                    eprintln!("Warning: Failed to record rollback in WAL: {}", e);
                }
            }
        }
        Ok(())
    }

    fn get_tables_with_pending_changes(&self, txn_id: i64) -> Result<Vec<Box<dyn Table>>> {
        let mut tables = Vec::new();

        // Iterate over all cached transaction version stores for this txn_id
        let cache = self.txn_version_stores().read().unwrap();

        for ((cached_txn_id, table_name), txn_store) in cache.iter() {
            if *cached_txn_id == txn_id {
                // Check if this store has pending changes
                let store = txn_store.read().unwrap();
                if store.has_local_changes() {
                    drop(store);

                    // Get the version store for this table
                    let stores = self.version_stores().read().unwrap();
                    if let Some(version_store) = stores.get(table_name).cloned() {
                        drop(stores);

                        // Create a table instance with shared transaction store
                        let table = MVCCTable::new_with_shared_store(
                            txn_id,
                            Arc::clone(&version_store),
                            Arc::clone(txn_store),
                        );

                        tables.push(Box::new(table) as Box<dyn Table>);
                    }
                }
            }
        }

        Ok(tables)
    }

    fn commit_all_tables(&self, txn_id: i64) -> Result<()> {
        // Iterate over all cached transaction version stores for this txn_id
        // and use MvccTable::commit() which properly updates indexes
        let cache = self.txn_version_stores().read().unwrap();

        for ((cached_txn_id, table_name), txn_store) in cache.iter() {
            if *cached_txn_id == txn_id {
                // Check if there are local changes before committing
                let has_changes = {
                    let store = txn_store.read().unwrap();
                    store.has_local_changes()
                };

                if has_changes {
                    // Get the version store for this table
                    let stores = self.version_stores().read().unwrap();
                    if let Some(version_store) = stores.get(table_name).cloned() {
                        drop(stores);

                        // Create table and commit through it (updates indexes)
                        let mut table = MVCCTable::new_with_shared_store(
                            txn_id,
                            Arc::clone(&version_store),
                            Arc::clone(txn_store),
                        );
                        table.commit()?;
                    }
                }
            }
        }

        // Clean up the transaction version store cache for this transaction
        drop(cache);
        let mut cache = self.txn_version_stores().write().unwrap();
        cache.retain(|(cached_txn_id, _), _| *cached_txn_id != txn_id);

        Ok(())
    }

    fn rollback_all_tables(&self, txn_id: i64) -> Result<()> {
        let cache = self.txn_version_stores().read().unwrap();

        for ((cached_txn_id, _), txn_store) in cache.iter() {
            if *cached_txn_id == txn_id {
                txn_store.write().unwrap().rollback();
            }
        }

        // Clean up the transaction version store cache for this transaction
        drop(cache);
        let mut cache = self.txn_version_stores().write().unwrap();
        cache.retain(|(cached_txn_id, _), _| *cached_txn_id != txn_id);

        Ok(())
    }

    fn create_schema(&self, name: &str) -> Result<()> {
        let name_lower = name.to_lowercase();
        let mut schemas = self.schemas.write().unwrap();
        schemas.insert(name_lower, FxHashMap::default());
        Ok(())
    }

    fn drop_schema(&self, name: &str) -> Result<()> {
        let name_lower = name.to_lowercase();
        let mut schemas = self.schemas.write().unwrap();
        schemas.remove(&name_lower);
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::{DataType, Row, SchemaBuilder, Value};

    #[test]
    fn test_engine_creation() {
        let engine = MVCCEngine::in_memory();
        assert!(!engine.is_open());
        assert_eq!(engine.get_path(), "memory://");
    }

    #[test]
    fn test_engine_open_close() {
        let engine = MVCCEngine::in_memory();

        engine.open_engine().unwrap();
        assert!(engine.is_open());

        engine.close_engine().unwrap();
        assert!(!engine.is_open());
    }

    #[test]
    fn test_engine_create_table() {
        let engine = MVCCEngine::in_memory();
        engine.open_engine().unwrap();

        let schema = SchemaBuilder::new("users")
            .column("id", DataType::Integer, false, true)
            .column("name", DataType::Text, true, false)
            .build();

        let created = engine.create_table(schema).unwrap();
        assert_eq!(created.table_name, "users");

        // Table should exist
        assert!(engine.table_exists("users").unwrap());
        assert!(engine.table_exists("USERS").unwrap()); // Case insensitive

        engine.close_engine().unwrap();
    }

    #[test]
    fn test_engine_drop_table() {
        let engine = MVCCEngine::in_memory();
        engine.open_engine().unwrap();

        let schema = SchemaBuilder::new("temp")
            .column("id", DataType::Integer, false, true)
            .build();

        engine.create_table(schema).unwrap();
        assert!(engine.table_exists("temp").unwrap());

        engine.drop_table_internal("temp").unwrap();
        assert!(!engine.table_exists("temp").unwrap());

        engine.close_engine().unwrap();
    }

    #[test]
    fn test_engine_duplicate_table_error() {
        let engine = MVCCEngine::in_memory();
        engine.open_engine().unwrap();

        let schema = SchemaBuilder::new("dup")
            .column("id", DataType::Integer, false, true)
            .build();

        engine.create_table(schema.clone()).unwrap();

        let result = engine.create_table(schema);
        assert!(result.is_err());

        engine.close_engine().unwrap();
    }

    #[test]
    fn test_engine_begin_transaction() {
        let mut engine = MVCCEngine::in_memory();
        engine.open().unwrap();

        let txn = engine.begin_transaction();
        assert!(txn.is_ok());

        let mut txn = txn.unwrap();
        assert!(txn.id() > 0);

        txn.rollback().unwrap();
        engine.close().unwrap();
    }

    #[test]
    fn test_engine_transaction_create_table() {
        let mut engine = MVCCEngine::in_memory();
        engine.open().unwrap();

        let mut txn = engine.begin_transaction().unwrap();

        // Create table through transaction
        let schema = SchemaBuilder::new("txn_table")
            .column("id", DataType::Integer, false, true)
            .column("value", DataType::Text, true, false)
            .build();

        let table = txn.create_table("txn_table", schema).unwrap();
        assert_eq!(table.name(), "txn_table");

        txn.commit().unwrap();
        engine.close().unwrap();
    }

    #[test]
    fn test_engine_transaction_insert_and_select() {
        let mut engine = MVCCEngine::in_memory();
        engine.open().unwrap();

        // Create table
        let schema = SchemaBuilder::new("data")
            .column("id", DataType::Integer, false, true)
            .column("name", DataType::Text, true, false)
            .build();
        engine.create_table(schema).unwrap();

        // Insert data in transaction
        let mut txn = engine.begin_transaction().unwrap();
        let mut table = txn.get_table("data").unwrap();

        table
            .insert(Row::from_values(vec![
                Value::Integer(1),
                Value::text("Alice"),
            ]))
            .unwrap();

        table
            .insert(Row::from_values(vec![
                Value::Integer(2),
                Value::text("Bob"),
            ]))
            .unwrap();

        // Scan to verify
        let mut scanner = table.scan(&[0, 1], None).unwrap();
        let mut count = 0;
        while scanner.next() {
            count += 1;
        }
        assert_eq!(count, 2);

        txn.commit().unwrap();
        engine.close().unwrap();
    }

    #[test]
    fn test_engine_isolation_level() {
        let mut engine = MVCCEngine::in_memory();
        engine.open().unwrap();

        // Default should be ReadCommitted
        assert_eq!(engine.get_isolation_level(), IsolationLevel::ReadCommitted);

        // Set to Snapshot
        engine
            .set_isolation_level(IsolationLevel::SnapshotIsolation)
            .unwrap();
        assert_eq!(
            engine.get_isolation_level(),
            IsolationLevel::SnapshotIsolation
        );

        engine.close().unwrap();
    }

    #[test]
    fn test_engine_get_version_store() {
        let engine = MVCCEngine::in_memory();
        engine.open_engine().unwrap();

        let schema = SchemaBuilder::new("versioned")
            .column("id", DataType::Integer, false, true)
            .build();
        engine.create_table(schema).unwrap();

        let store = engine.get_version_store("versioned");
        assert!(store.is_ok());

        let store = engine.get_version_store("nonexistent");
        assert!(store.is_err());

        engine.close_engine().unwrap();
    }

    #[test]
    fn test_engine_get_table_schema() {
        let mut engine = MVCCEngine::in_memory();
        engine.open().unwrap();

        let schema = SchemaBuilder::new("test_schema")
            .column("id", DataType::Integer, false, true)
            .column("name", DataType::Text, true, false)
            .build();
        engine.create_table(schema).unwrap();

        let retrieved = engine.get_table_schema("test_schema").unwrap();
        assert_eq!(retrieved.columns.len(), 2);
        assert_eq!(retrieved.columns[0].name, "id");

        // Non-existent table
        assert!(engine.get_table_schema("nonexistent").is_err());

        engine.close().unwrap();
    }

    #[test]
    fn test_engine_transaction_with_isolation_level() {
        let mut engine = MVCCEngine::in_memory();
        engine.open().unwrap();

        let txn = engine.begin_transaction_with_level(IsolationLevel::SnapshotIsolation);
        assert!(txn.is_ok());

        let mut txn = txn.unwrap();
        txn.rollback().unwrap();

        engine.close().unwrap();
    }

    #[test]
    fn test_engine_path() {
        let engine = MVCCEngine::in_memory();
        assert!(engine.path().is_none());

        let config = Config::with_path("/tmp/test.db");
        let engine = MVCCEngine::new(config);
        assert_eq!(engine.path(), Some("/tmp/test.db"));
    }

    #[test]
    fn test_engine_create_snapshot() {
        let mut engine = MVCCEngine::in_memory();
        engine.open().unwrap();

        // Should succeed (no-op for now)
        assert!(engine.create_snapshot().is_ok());

        engine.close().unwrap();
    }

    #[test]
    fn test_engine_list_table_indexes() {
        let mut engine = MVCCEngine::in_memory();
        engine.open().unwrap();

        let schema = SchemaBuilder::new("indexed")
            .column("id", DataType::Integer, false, true)
            .build();
        engine.create_table(schema).unwrap();

        // Should return empty map (no indexes yet)
        let indexes = engine.list_table_indexes("indexed").unwrap();
        assert!(indexes.is_empty());

        engine.close().unwrap();
    }

    #[test]
    fn test_cross_transaction_visibility() {
        // This test simulates the executor pattern: INSERT in one transaction, SELECT in another
        let engine = MVCCEngine::in_memory();
        engine.open_engine().unwrap();

        // Create table
        let schema = SchemaBuilder::new("test_xact")
            .column("id", DataType::Integer, false, true)
            .column("name", DataType::Text, true, false)
            .build();
        engine.create_table(schema).unwrap();

        // Transaction 1: INSERT
        {
            let mut tx1 = engine.begin_transaction().unwrap();

            let mut table = tx1.get_table("test_xact").unwrap();
            table
                .insert(Row::from_values(vec![
                    Value::Integer(1),
                    Value::text("Alice"),
                ]))
                .unwrap();

            // Just commit the transaction - it commits all tables via commit_all_tables()
            tx1.commit().unwrap();
        }

        // Transaction 2: SELECT (different transaction)
        {
            let tx2 = engine.begin_transaction().unwrap();
            let table = tx2.get_table("test_xact").unwrap();
            let mut scanner = table.scan(&[0, 1], None).unwrap();

            let mut count = 0;
            while scanner.next() {
                count += 1;
            }
            // Should see the committed row from tx1
            assert_eq!(
                count, 1,
                "Transaction 2 should see 1 row committed by Transaction 1"
            );
        }

        engine.close_engine().unwrap();
    }

    #[test]
    fn test_durability_ddl_survives_restart() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().to_str().unwrap().to_string();

        let config = Config::with_path(&path);
        let engine = MVCCEngine::new(config.clone());
        engine.open_engine().unwrap();

        let schema = SchemaBuilder::new("survivor_table")
            .column("id", DataType::Integer, false, true)
            .build();
        engine.create_table(schema).unwrap();

        // Close the engine cleanly
        engine.close_engine().unwrap();
        drop(engine);

        // Initialize a new engine pointing to the exact same temporary directory
        let new_engine = MVCCEngine::new(config);
        new_engine.open_engine().unwrap();

        // Assert that the table still exists after recovery
        assert!(new_engine.table_exists("survivor_table").unwrap());
    }
}