manifoldb 0.1.4

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

use std::path::Path;
use std::sync::Arc;
use std::time::Instant;

use manifoldb_core::encoding::keys::encode_edge_key;
use manifoldb_core::encoding::Encoder;
use manifoldb_core::{Edge, EdgeId, Entity, EntityId};
use manifoldb_storage::backends::redb::{RedbConfig, RedbEngine};
use manifoldb_storage::Transaction;

use crate::cache::{extract_cache_hint, CacheHint, CacheMetrics, QueryCache, QueryCacheKey};
use crate::config::{Config, DatabaseBuilder};
use crate::error::{Error, Result};
use crate::execution::{execute_statement, extract_tables_from_sql};
use crate::index::{IndexInfo, IndexManager, IndexMetadata, IndexStats, IndexType};
use crate::metrics::{CacheMetricsSnapshot, DatabaseMetrics, MetricsSnapshot};
use crate::prepared::{PreparedStatement, PreparedStatementCache};
use crate::schema::SchemaManager;
use crate::transaction::{DatabaseTransaction, TransactionManager};

/// The main `ManifoldDB` database handle.
///
/// `Database` is the primary entry point for interacting with a `ManifoldDB` database.
/// It provides methods for:
///
/// - Opening and configuring databases
/// - Executing SQL statements
/// - Querying data with SQL and graph patterns
/// - Managing transactions
///
/// # Thread Safety
///
/// `Database` is `Send + Sync` and can be safely shared across threads.
/// Multiple concurrent read transactions are supported.
///
/// # Examples
///
/// ## Opening a Database
///
/// ```ignore
/// use manifoldb::Database;
///
/// // Simple open with default options
/// let db = Database::open("mydb.manifold")?;
///
/// // Or use the builder for more options
/// use manifoldb::DatabaseBuilder;
///
/// let db = DatabaseBuilder::new()
///     .path("mydb.manifold")
///     .cache_size(64 * 1024 * 1024)
///     .open()?;
/// ```
///
/// ## Executing Queries
///
/// ```ignore
/// // Execute a statement (INSERT, UPDATE, DELETE)
/// let affected = db.execute("INSERT INTO users (name) VALUES ('Alice')")?;
///
/// // Execute a query (SELECT)
/// let results = db.query("SELECT * FROM users WHERE name = 'Alice'")?;
/// ```
///
/// ## Using Transactions
///
/// ```ignore
/// let mut txn = db.begin()?;
///
/// // Create and store an entity
/// let entity = txn.create_entity()?.with_label("Person");
/// txn.put_entity(&entity)?;
///
/// // Create an edge
/// let edge = txn.create_edge(entity1.id, entity2.id, "FOLLOWS")?;
/// txn.put_edge(&edge)?;
///
/// txn.commit()?;
/// ```
///
/// # Cloning
///
/// `Database` is cheap to clone - it uses `Arc` internally, so cloning only
/// increments a reference count. This makes it easy to share a database handle
/// across threads or async tasks.
///
/// ```ignore
/// let db = Database::open("mydb.manifold")?;
/// let db2 = db.clone(); // Cheap clone, shares underlying data
///
/// // Use in multiple threads
/// std::thread::spawn(move || {
///     db2.query("SELECT * FROM users")?;
/// });
/// ```
#[derive(Clone)]
pub struct Database {
    /// The inner database state, shared via Arc for cheap cloning.
    inner: Arc<DatabaseInner>,
}

/// The internal state of a Database.
///
/// This is wrapped in an `Arc` by `Database` to enable cheap cloning.
struct DatabaseInner {
    /// The transaction manager coordinating storage and indexes.
    manager: TransactionManager<RedbEngine>,
    /// The configuration used to open this database.
    config: Config,
    /// Query result cache.
    query_cache: QueryCache,
    /// Prepared statement cache.
    prepared_cache: PreparedStatementCache,
    /// Database metrics.
    db_metrics: Arc<DatabaseMetrics>,
    /// Payload index manager.
    index_manager: IndexManager,
}

impl Database {
    /// Open or create a database at the given path.
    ///
    /// This is a convenience method that uses default configuration options.
    /// For more control, use [`DatabaseBuilder`].
    ///
    /// # Arguments
    ///
    /// * `path` - The path to the database file
    ///
    /// # Errors
    ///
    /// Returns an error if the database cannot be opened or created.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use manifoldb::Database;
    ///
    /// let db = Database::open("mydb.manifold")?;
    /// ```
    pub fn open(path: impl AsRef<Path>) -> Result<Self> {
        DatabaseBuilder::new().path(path).open()
    }

    /// Open or create an in-memory database.
    ///
    /// In-memory databases are useful for testing and temporary data.
    /// All data is lost when the database is closed.
    ///
    /// # Errors
    ///
    /// Returns an error if the in-memory database cannot be created.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use manifoldb::Database;
    ///
    /// let db = Database::in_memory()?;
    /// ```
    pub fn in_memory() -> Result<Self> {
        DatabaseBuilder::in_memory().open()
    }

    /// Open a database with the given configuration.
    ///
    /// This is typically called through [`DatabaseBuilder::open()`].
    ///
    /// # Errors
    ///
    /// Returns an error if the database cannot be opened.
    pub fn open_with_config(config: Config) -> Result<Self> {
        let engine = if config.in_memory {
            RedbEngine::in_memory().map_err(|e| Error::Open(e.to_string()))?
        } else {
            let mut redb_config = RedbConfig::new();
            if let Some(cache_size) = config.cache_size {
                redb_config = redb_config.cache_size(cache_size);
            }
            if let Some(max_size) = config.max_size {
                redb_config = redb_config.max_size(max_size);
            }
            RedbEngine::open_with_config(&config.path, redb_config)
                .map_err(|e| Error::Open(e.to_string()))?
        };

        let manager = TransactionManager::with_config(engine, config.transaction_config());
        let query_cache = QueryCache::new(config.query_cache_config.clone());
        let prepared_cache = PreparedStatementCache::default();
        let db_metrics = Arc::new(DatabaseMetrics::new());
        let index_manager = IndexManager::new(manager.engine_arc());

        // Initialize prepared cache with current schema version
        let inner = DatabaseInner {
            manager,
            config,
            query_cache,
            prepared_cache,
            db_metrics,
            index_manager,
        };
        let db = Self { inner: Arc::new(inner) };

        // Load initial schema version
        if let Ok(tx) = db.begin_read() {
            if let Ok(version) = SchemaManager::get_version(&tx) {
                db.inner.prepared_cache.set_schema_version(version);
            }
        }

        Ok(db)
    }

    /// Returns a builder for creating a database with custom configuration.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use manifoldb::Database;
    ///
    /// let db = Database::builder()
    ///     .path("mydb.manifold")
    ///     .cache_size(128 * 1024 * 1024)
    ///     .open()?;
    /// ```
    #[must_use]
    pub fn builder() -> DatabaseBuilder {
        DatabaseBuilder::new()
    }

    /// Get the configuration used to open this database.
    #[must_use]
    pub fn config(&self) -> &Config {
        &self.inner.config
    }

    /// Begin a new read-write transaction.
    ///
    /// Write transactions allow both reading and writing data. Only one
    /// write transaction can be active at a time.
    ///
    /// # Errors
    ///
    /// Returns an error if the transaction cannot be started.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// let mut txn = db.begin()?;
    /// let entity = txn.create_entity()?;
    /// txn.put_entity(&entity)?;
    /// txn.commit()?;
    /// ```
    pub fn begin(
        &self,
    ) -> Result<
        DatabaseTransaction<<RedbEngine as manifoldb_storage::StorageEngine>::Transaction<'_>>,
    > {
        self.inner.manager.begin_write().map_err(Error::Transaction)
    }

    /// Begin a new read-only transaction.
    ///
    /// Read transactions provide a consistent snapshot of the database.
    /// Multiple read transactions can run concurrently.
    ///
    /// # Errors
    ///
    /// Returns an error if the transaction cannot be started.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// let txn = db.begin_read()?;
    /// let entity = txn.get_entity(entity_id)?;
    /// // Read transaction doesn't need commit
    /// ```
    pub fn begin_read(
        &self,
    ) -> Result<
        DatabaseTransaction<<RedbEngine as manifoldb_storage::StorageEngine>::Transaction<'_>>,
    > {
        self.inner.manager.begin_read().map_err(Error::Transaction)
    }

    /// Execute a SQL statement that doesn't return results.
    ///
    /// Use this for INSERT, UPDATE, DELETE, and DDL statements.
    /// For SELECT queries, use [`query()`](Self::query) instead.
    ///
    /// # Arguments
    ///
    /// * `sql` - The SQL statement to execute
    ///
    /// # Returns
    ///
    /// The number of rows affected by the statement.
    ///
    /// # Errors
    ///
    /// Returns an error if the statement cannot be parsed or executed.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// let affected = db.execute("INSERT INTO users (name) VALUES ('Alice')")?;
    /// println!("Inserted {} rows", affected);
    /// ```
    pub fn execute(&self, sql: &str) -> Result<u64> {
        self.execute_with_params(sql, &[])
    }

    /// Execute a SQL statement with bound parameters.
    ///
    /// Parameters are specified as `$1`, `$2`, etc. in the SQL string.
    ///
    /// # Arguments
    ///
    /// * `sql` - The SQL statement with parameter placeholders
    /// * `params` - The parameter values to bind
    ///
    /// # Returns
    ///
    /// The number of rows affected by the statement.
    ///
    /// # Errors
    ///
    /// Returns an error if the statement cannot be parsed, parameters are
    /// invalid, or execution fails.
    ///
    /// # Cache Invalidation
    ///
    /// This method automatically invalidates any cached query results that
    /// accessed the tables modified by this statement.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// let affected = db.execute_with_params(
    ///     "INSERT INTO users (name, age) VALUES ($1, $2)",
    ///     &["Alice".into(), 30.into()],
    /// )?;
    /// ```
    pub fn execute_with_params(&self, sql: &str, params: &[manifoldb_core::Value]) -> Result<u64> {
        let start = Instant::now();

        // Extract tables that will be modified for cache invalidation
        let affected_tables = extract_tables_from_sql(sql);

        // Check if this is a DDL statement
        let is_ddl = Self::is_ddl_statement(sql);

        // Start a write transaction
        let mut tx = self.begin()?;
        self.inner.db_metrics.transactions.record_start();

        // Execute the statement
        let result = execute_statement(&mut tx, sql, params);

        match result {
            Ok(count) => {
                // Get schema version before commit if DDL
                let new_schema_version =
                    if is_ddl { SchemaManager::get_version(&tx).ok() } else { None };

                // Commit the transaction
                let commit_start = Instant::now();
                tx.commit().map_err(Error::Transaction)?;
                self.inner.db_metrics.record_commit(commit_start.elapsed());

                // Record successful query
                self.inner.db_metrics.record_query(start.elapsed(), true);

                // Invalidate cache entries for affected tables
                self.inner.query_cache.invalidate_tables(&affected_tables);
                self.inner.prepared_cache.invalidate_tables(&affected_tables)?;

                // Update prepared statement cache schema version if DDL
                if let Some(version) = new_schema_version {
                    self.inner.prepared_cache.set_schema_version(version);
                }

                Ok(count)
            }
            Err(e) => {
                // Record failed query and rollback
                self.inner.db_metrics.record_query(start.elapsed(), false);
                self.inner.db_metrics.record_rollback();
                Err(e)
            }
        }
    }

    /// Check if a SQL statement is a DDL statement.
    fn is_ddl_statement(sql: &str) -> bool {
        let sql_upper = sql.trim().to_uppercase();
        sql_upper.starts_with("CREATE TABLE")
            || sql_upper.starts_with("DROP TABLE")
            || sql_upper.starts_with("CREATE INDEX")
            || sql_upper.starts_with("DROP INDEX")
            || sql_upper.starts_with("ALTER TABLE")
    }

    /// Execute a SQL query and return results.
    ///
    /// Use this for SELECT statements. For INSERT, UPDATE, and DELETE,
    /// use [`execute()`](Self::execute) instead.
    ///
    /// # Arguments
    ///
    /// * `sql` - The SQL query to execute
    ///
    /// # Returns
    ///
    /// A [`QueryResult`] containing the query results.
    ///
    /// # Errors
    ///
    /// Returns an error if the query cannot be parsed or executed.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// let results = db.query("SELECT * FROM users WHERE age > 25")?;
    /// for row in results {
    ///     println!("{:?}", row);
    /// }
    /// ```
    pub fn query(&self, sql: &str) -> Result<QueryResult> {
        self.query_with_params(sql, &[])
    }

    /// Execute a SQL query with bound parameters.
    ///
    /// Parameters are specified as `$1`, `$2`, etc. in the SQL string.
    ///
    /// # Arguments
    ///
    /// * `sql` - The SQL query with parameter placeholders
    /// * `params` - The parameter values to bind
    ///
    /// # Returns
    ///
    /// A [`QueryResult`] containing the query results.
    ///
    /// # Errors
    ///
    /// Returns an error if the query cannot be parsed, parameters are
    /// invalid, or execution fails.
    ///
    /// # Cache Hints
    ///
    /// You can control caching behavior with hints:
    /// - `/*+ CACHE */` - Force caching of this query result
    /// - `/*+ NO_CACHE */` - Skip caching for this query
    ///
    /// # Examples
    ///
    /// ```ignore
    /// let results = db.query_with_params(
    ///     "SELECT * FROM users WHERE name = $1",
    ///     &["Alice".into()],
    /// )?;
    ///
    /// // Force caching
    /// let results = db.query_with_params(
    ///     "/*+ CACHE */ SELECT * FROM users WHERE name = $1",
    ///     &["Alice".into()],
    /// )?;
    ///
    /// // Skip caching
    /// let results = db.query_with_params(
    ///     "/*+ NO_CACHE */ SELECT * FROM users WHERE name = $1",
    ///     &["Alice".into()],
    /// )?;
    /// ```
    pub fn query_with_params(
        &self,
        sql: &str,
        params: &[manifoldb_core::Value],
    ) -> Result<QueryResult> {
        // Extract cache hint and clean SQL
        let (hint, clean_sql) = extract_cache_hint(sql);

        // Determine if we should use caching
        let use_cache = match hint {
            CacheHint::Cache => true,
            CacheHint::NoCache => false,
            CacheHint::Default => self.inner.query_cache.is_enabled(),
        };

        // Try to get from cache if caching is enabled
        if use_cache {
            let cache_key = QueryCacheKey::new(&clean_sql, params);
            if let Some(cached_result) = self.inner.query_cache.get(&cache_key) {
                // Update LRU order
                self.inner.query_cache.touch(&cache_key);
                return Ok(cached_result);
            }
        }

        let start = Instant::now();

        // Start a read transaction
        let tx = self.begin_read()?;

        // Execute the query with the configured row limit
        let result = crate::execution::execute_query_with_limit(
            &tx,
            &clean_sql,
            params,
            self.inner.config.max_rows_in_memory,
        );

        match result {
            Ok(result_set) => {
                // Record successful query
                self.inner.db_metrics.record_query(start.elapsed(), true);

                // Convert the ResultSet to our QueryResult
                let result = QueryResult::from_result_set(result_set);

                // Cache the result if caching is enabled
                if use_cache {
                    let cache_key = QueryCacheKey::new(&clean_sql, params);
                    let accessed_tables = extract_tables_from_sql(&clean_sql);
                    self.inner.query_cache.insert(cache_key, result.clone(), accessed_tables);
                }

                Ok(result)
            }
            Err(e) => {
                // Record failed query
                self.inner.db_metrics.record_query(start.elapsed(), false);
                Err(e)
            }
        }
    }

    /// Flush any buffered data to durable storage.
    ///
    /// This ensures all committed transactions are persisted to disk.
    /// It's typically called automatically on commit, but can be called
    /// explicitly for additional durability guarantees.
    ///
    /// # Errors
    ///
    /// Returns an error if the flush fails.
    pub fn flush(&self) -> Result<()> {
        self.inner.manager.flush().map_err(Error::Transaction)
    }

    /// Get the underlying transaction manager.
    ///
    /// This is useful for advanced use cases that require direct
    /// transaction management.
    #[must_use]
    pub fn transaction_manager(&self) -> &TransactionManager<RedbEngine> {
        &self.inner.manager
    }

    /// Get the query cache.
    ///
    /// Use this to access cache operations like clearing or checking metrics.
    #[must_use]
    pub fn query_cache(&self) -> &QueryCache {
        &self.inner.query_cache
    }

    /// Get the cache metrics.
    ///
    /// Returns metrics about cache hits, misses, and evictions.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let metrics = db.cache_metrics();
    /// println!("Hit rate: {:?}", metrics.hit_rate());
    /// println!("Total lookups: {}", metrics.total_lookups());
    /// ```
    #[must_use]
    pub fn cache_metrics(&self) -> Arc<CacheMetrics> {
        self.inner.query_cache.metrics()
    }

    /// Clear the query cache.
    ///
    /// This removes all cached query results. Useful after bulk data
    /// modifications or when you want to ensure fresh data.
    pub fn clear_cache(&self) {
        self.inner.query_cache.clear();
    }

    /// Invalidate cache entries for specific tables.
    ///
    /// This is automatically called during write operations, but can
    /// be called manually if you modify data outside of the normal
    /// execute methods.
    pub fn invalidate_cache_for_tables(&self, tables: &[String]) {
        self.inner.query_cache.invalidate_tables(tables);
    }

    /// Get a snapshot of all database metrics.
    ///
    /// Returns a point-in-time snapshot of query, transaction, vector search,
    /// storage, and cache metrics.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use manifoldb::Database;
    ///
    /// let db = Database::in_memory()?;
    ///
    /// // Perform some operations
    /// db.execute("INSERT INTO users (name) VALUES ('Alice')")?;
    /// db.query("SELECT * FROM users")?;
    ///
    /// // Get metrics snapshot
    /// let snapshot = db.metrics();
    /// println!("{}", snapshot);  // Pretty-printed summary
    ///
    /// // Access specific metrics
    /// println!("Queries executed: {}", snapshot.queries.total_queries);
    /// println!("Cache hit rate: {:?}", snapshot.cache.as_ref().and_then(|c| c.hit_rate()));
    /// println!("Transactions committed: {}", snapshot.transactions.commits);
    /// ```
    #[must_use]
    pub fn metrics(&self) -> MetricsSnapshot {
        let mut snapshot = self.inner.db_metrics.snapshot();

        // Include cache metrics from the query cache
        let cache_snapshot = self.inner.query_cache.metrics().snapshot();
        snapshot.cache = Some(CacheMetricsSnapshot::from_cache_snapshot(cache_snapshot));

        snapshot
    }

    /// Get access to the raw metrics instance.
    ///
    /// This is useful for custom metric collection or integration with
    /// external monitoring systems.
    #[must_use]
    pub fn raw_metrics(&self) -> Arc<DatabaseMetrics> {
        Arc::clone(&self.inner.db_metrics)
    }

    /// Reset all collected metrics.
    ///
    /// This is useful for benchmarking or when you want to collect
    /// metrics for a specific time window.
    ///
    /// Note: Storage size metrics are not reset as they represent
    /// current state rather than accumulated values.
    pub fn reset_metrics(&self) {
        self.inner.db_metrics.reset();
        self.inner.query_cache.metrics().reset();
    }

    // =========================================================================
    // Payload Indexing
    // =========================================================================

    /// Create an index on a property for entities with the given label.
    ///
    /// Indexes speed up filtered vector searches by allowing the query planner
    /// to narrow down candidates using B-tree lookups instead of scanning all entities.
    ///
    /// # Arguments
    ///
    /// * `label` - The entity label to index (e.g., "Symbol", "Document")
    /// * `property` - The property to index (e.g., "language", "category")
    ///
    /// # Errors
    ///
    /// Returns an error if the index already exists or creation fails.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use manifoldb::Database;
    ///
    /// let db = Database::in_memory()?;
    ///
    /// // Create an index on the "language" property for "Symbol" entities
    /// db.create_index("Symbol", "language")?;
    ///
    /// // Now searches filtering by language will use the index
    /// ```
    pub fn create_index(&self, label: &str, property: &str) -> Result<()> {
        self.create_index_with_type(label, property, IndexType::Equality)
    }

    /// Create an index with a specific type.
    ///
    /// # Arguments
    ///
    /// * `label` - The entity label to index
    /// * `property` - The property to index
    /// * `index_type` - The type of index (Equality, Range, or Prefix)
    ///
    /// # Index Types
    ///
    /// - `Equality`: Best for enum-like fields. Supports `eq`, `ne`, `in` operators.
    /// - `Range`: Best for numeric fields. Supports `gt`, `gte`, `lt`, `lte`, `range`.
    /// - `Prefix`: Best for paths/names. Supports `starts_with`.
    pub fn create_index_with_type(
        &self,
        label: &str,
        property: &str,
        index_type: IndexType,
    ) -> Result<()> {
        self.inner.index_manager.create_index(label, property, index_type)
    }

    /// Drop an index.
    ///
    /// # Arguments
    ///
    /// * `label` - The entity label
    /// * `property` - The indexed property
    ///
    /// # Errors
    ///
    /// Returns an error if the index doesn't exist.
    pub fn drop_index(&self, label: &str, property: &str) -> Result<()> {
        self.inner.index_manager.drop_index(label, property)
    }

    /// List all indexes in the database.
    ///
    /// # Returns
    ///
    /// A vector of index information including label, property, type, and entry count.
    pub fn list_indexes(&self) -> Result<Vec<IndexInfo>> {
        self.inner.index_manager.list_indexes()
    }

    /// Get statistics for a specific index.
    ///
    /// # Arguments
    ///
    /// * `label` - The entity label
    /// * `property` - The indexed property
    ///
    /// # Returns
    ///
    /// Index statistics including entry count, distinct values, and selectivity.
    ///
    /// # Errors
    ///
    /// Returns an error if the index doesn't exist.
    pub fn index_stats(&self, label: &str, property: &str) -> Result<IndexStats> {
        self.inner.index_manager.index_stats(label, property)
    }

    /// Get metadata for an index, or None if it doesn't exist.
    ///
    /// This is useful for checking if an index exists without triggering an error.
    pub fn get_index_metadata(&self, label: &str, property: &str) -> Result<Option<IndexMetadata>> {
        self.inner.index_manager.get_index_metadata(label, property)
    }

    /// Look up entity IDs matching a filter value using an index.
    ///
    /// This is a low-level API primarily used by the query planner.
    /// Returns None if no index exists for the label/property combination.
    ///
    /// # Arguments
    ///
    /// * `label` - The entity label
    /// * `property` - The indexed property
    /// * `value` - The value to match
    pub fn index_lookup(
        &self,
        label: &str,
        property: &str,
        value: &manifoldb_core::Value,
    ) -> Result<Option<Vec<EntityId>>> {
        self.inner.index_manager.lookup_eq(label, property, value)
    }

    /// Build a planner catalog from the current state of the database.
    ///
    /// This creates a snapshot of index metadata that the query planner can use
    /// for index selection and cost estimation.
    ///
    /// # Returns
    ///
    /// A `PlannerCatalog` populated with:
    /// - Payload indexes (as B-tree indexes on label.property)
    /// - Index statistics for selectivity estimation
    ///
    /// # Example
    ///
    /// ```ignore
    /// use manifoldb::Database;
    /// use manifoldb_query::{PhysicalPlanner, PlanBuilder};
    ///
    /// let db = Database::in_memory()?;
    /// db.create_index("Symbol", "language")?;
    ///
    /// // Get catalog with current index info
    /// let catalog = db.build_planner_catalog()?;
    ///
    /// // Use it for query planning
    /// let planner = PhysicalPlanner::new().with_catalog(catalog);
    /// ```
    pub fn build_planner_catalog(&self) -> Result<manifoldb_query::PlannerCatalog> {
        use manifoldb_query::{PlannerCatalog, PlannerIndexInfo, TableStats};

        let mut catalog = PlannerCatalog::new();

        // Add payload indexes
        for idx in self.list_indexes()? {
            // Create index name as "label_property_idx"
            let index_name = format!("{}_{}_idx", idx.label, idx.property);

            // All payload indexes are B-tree style
            let planner_idx = PlannerIndexInfo::btree(
                index_name,
                &idx.label, // Use label as "table" name
                vec![idx.property.clone()],
            );

            catalog = catalog.with_index(planner_idx);

            // Also add table stats based on index entry count
            // This gives the planner row count estimates
            catalog = catalog.with_table(TableStats::new(&idx.label, idx.entry_count as usize));
        }

        Ok(catalog)
    }

    /// Prepare a SQL statement for repeated execution.
    ///
    /// Prepared statements cache the parsed AST and query plan, amortizing
    /// parsing and planning costs over multiple executions.
    ///
    /// # Arguments
    ///
    /// * `sql` - The SQL statement to prepare. Use `$1`, `$2`, etc. for parameters.
    ///
    /// # Returns
    ///
    /// A prepared statement that can be executed multiple times with different parameters.
    ///
    /// # Errors
    ///
    /// Returns an error if the SQL cannot be parsed or planned.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use manifoldb::{Database, Value};
    ///
    /// let db = Database::in_memory()?;
    ///
    /// // Prepare once
    /// let stmt = db.prepare("SELECT * FROM users WHERE age > $1")?;
    ///
    /// // Execute multiple times with different parameters
    /// let young = stmt.query(&db, &[Value::Int(18)])?;
    /// let old = stmt.query(&db, &[Value::Int(65)])?;
    /// ```
    pub fn prepare(&self, sql: &str) -> Result<Arc<PreparedStatement>> {
        self.inner.prepared_cache.prepare(sql)
    }

    /// Get or prepare a SQL statement (uses cache).
    ///
    /// This is like `prepare`, but uses the prepared statement cache.
    /// If the same SQL was previously prepared and the schema hasn't changed,
    /// the cached statement is returned.
    ///
    /// # Arguments
    ///
    /// * `sql` - The SQL statement to prepare. Use `$1`, `$2`, etc. for parameters.
    ///
    /// # Returns
    ///
    /// A prepared statement that can be executed multiple times with different parameters.
    ///
    /// # Errors
    ///
    /// Returns an error if the SQL cannot be parsed or planned.
    pub fn prepare_cached(&self, sql: &str) -> Result<Arc<PreparedStatement>> {
        self.inner.prepared_cache.get_or_prepare(sql)
    }

    /// Execute a prepared statement that returns results (SELECT).
    ///
    /// # Arguments
    ///
    /// * `stmt` - The prepared statement to execute
    /// * `params` - The parameter values to bind
    ///
    /// # Returns
    ///
    /// A [`QueryResult`] containing the query results.
    ///
    /// # Errors
    ///
    /// Returns an error if the statement has been invalidated by schema changes,
    /// or if execution fails.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let stmt = db.prepare("SELECT * FROM users WHERE age > $1")?;
    /// let results = db.query_prepared(&stmt, &[Value::Int(21)])?;
    /// ```
    pub fn query_prepared(
        &self,
        stmt: &PreparedStatement,
        params: &[manifoldb_core::Value],
    ) -> Result<QueryResult> {
        // Check if statement is still valid
        let current_version = self.inner.prepared_cache.schema_version();
        if !stmt.is_valid(current_version) {
            return Err(Error::Execution(
                "Prepared statement is invalid due to schema changes. Please re-prepare."
                    .to_string(),
            ));
        }

        let start = Instant::now();

        // Start a read transaction
        let tx = self.begin_read()?;

        // Execute using the cached plans
        let result = crate::execution::execute_prepared_query(&tx, stmt, params);

        match result {
            Ok(result_set) => {
                // Record successful query
                self.inner.db_metrics.record_query(start.elapsed(), true);

                // Convert the ResultSet to our QueryResult
                Ok(QueryResult::from_result_set(result_set))
            }
            Err(e) => {
                // Record failed query
                self.inner.db_metrics.record_query(start.elapsed(), false);
                Err(e)
            }
        }
    }

    /// Execute a prepared DML statement (INSERT, UPDATE, DELETE).
    ///
    /// # Arguments
    ///
    /// * `stmt` - The prepared statement to execute
    /// * `params` - The parameter values to bind
    ///
    /// # Returns
    ///
    /// The number of rows affected by the statement.
    ///
    /// # Errors
    ///
    /// Returns an error if the statement has been invalidated by schema changes,
    /// or if execution fails.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let stmt = db.prepare("INSERT INTO users (name, age) VALUES ($1, $2)")?;
    /// let count = db.execute_prepared(&stmt, &[Value::from("Alice"), Value::Int(30)])?;
    /// ```
    pub fn execute_prepared(
        &self,
        stmt: &PreparedStatement,
        params: &[manifoldb_core::Value],
    ) -> Result<u64> {
        // Check if statement is still valid
        let current_version = self.inner.prepared_cache.schema_version();
        if !stmt.is_valid(current_version) {
            return Err(Error::Execution(
                "Prepared statement is invalid due to schema changes. Please re-prepare."
                    .to_string(),
            ));
        }

        let start = Instant::now();

        // Start a write transaction
        let mut tx = self.begin()?;
        self.inner.db_metrics.transactions.record_start();

        // Execute using the cached plans
        let result = crate::execution::execute_prepared_statement(&mut tx, stmt, params);

        match result {
            Ok(count) => {
                // Get schema version before commit if DDL
                let new_schema_version =
                    if stmt.is_ddl() { SchemaManager::get_version(&tx).ok() } else { None };

                // Commit the transaction
                let commit_start = Instant::now();
                tx.commit().map_err(Error::Transaction)?;
                self.inner.db_metrics.record_commit(commit_start.elapsed());

                // Record successful query
                self.inner.db_metrics.record_query(start.elapsed(), true);

                // Invalidate cache entries for affected tables
                let affected_tables: Vec<String> = stmt.accessed_tables().iter().cloned().collect();
                self.inner.query_cache.invalidate_tables(&affected_tables);
                self.inner.prepared_cache.invalidate_tables(&affected_tables)?;

                // Update prepared statement cache schema version if DDL
                if let Some(version) = new_schema_version {
                    self.inner.prepared_cache.set_schema_version(version);
                }

                Ok(count)
            }
            Err(e) => {
                // Record failed query and rollback
                self.inner.db_metrics.record_query(start.elapsed(), false);
                self.inner.db_metrics.record_rollback();
                Err(e)
            }
        }
    }

    /// Get the prepared statement cache.
    ///
    /// Use this to access cache operations like clearing or checking metrics.
    #[must_use]
    pub fn prepared_cache(&self) -> &PreparedStatementCache {
        &self.inner.prepared_cache
    }

    /// Clear the prepared statement cache.
    ///
    /// # Errors
    ///
    /// Returns an error if the internal cache lock is poisoned.
    pub fn clear_prepared_cache(&self) -> Result<()> {
        self.inner.prepared_cache.clear()
    }

    /// Bulk insert entities with maximum throughput.
    ///
    /// All entities are inserted in a single transaction, with serialization
    /// parallelized across CPU cores using rayon. This is the most efficient
    /// way to insert many entities.
    ///
    /// # Performance
    ///
    /// This method achieves high throughput by:
    /// 1. **Parallel serialization**: Entities are serialized to binary format in parallel
    /// 2. **Single transaction**: All writes occur within one transaction (one fsync)
    /// 3. **Bulk ID allocation**: Entity IDs are allocated in a single atomic batch
    /// 4. **Index maintenance**: All indexes are updated within the same transaction
    ///
    /// # Arguments
    ///
    /// * `entities` - The entities to insert. All entities should have their labels
    ///   and properties set. The `id` field will be overwritten with auto-generated IDs.
    ///
    /// # Returns
    ///
    /// A vector of [`EntityId`] for the inserted entities, in the same order as the input.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Any entity fails validation (the entire batch is aborted, no entities are inserted)
    /// - Serialization fails for any entity
    /// - The transaction cannot be committed
    ///
    /// # Example
    ///
    /// ```ignore
    /// use manifoldb::{Database, Entity, EntityId};
    ///
    /// let db = Database::in_memory()?;
    ///
    /// // Create many entities (note: IDs will be assigned by bulk_insert_entities)
    /// let entities: Vec<Entity> = (0..10_000)
    ///     .map(|i| {
    ///         Entity::new(EntityId::new(0)) // ID is placeholder, will be overwritten
    ///             .with_label("Document")
    ///             .with_property("index", i as i64)
    ///             .with_property("content", format!("Document {}", i))
    ///     })
    ///     .collect();
    ///
    /// // Insert all at once - much faster than individual inserts
    /// let ids = db.bulk_insert_entities(&entities)?;
    /// assert_eq!(ids.len(), 10_000);
    /// ```
    pub fn bulk_insert_entities(&self, entities: &[Entity]) -> Result<Vec<EntityId>> {
        use crate::execution::EntityIndexMaintenance;
        use rayon::prelude::*;

        if entities.is_empty() {
            return Ok(Vec::new());
        }

        let start = std::time::Instant::now();

        // Phase 1: Parallel serialization
        // Serialize all entities in parallel, storing (original_index, serialized_bytes)
        // We serialize first (before IDs are assigned) to catch serialization errors early
        // The ID field will be updated in phase 3
        let serialized: std::result::Result<Vec<(usize, Vec<u8>)>, Error> = entities
            .par_iter()
            .enumerate()
            .map(|(idx, entity)| {
                // Create a temporary entity with the correct structure for serialization validation
                // Actual ID will be assigned in the write phase
                bincode::serde::encode_to_vec(entity, bincode::config::standard())
                    .map(|bytes| (idx, bytes))
                    .map_err(|e| {
                        Error::Execution(format!(
                            "Failed to serialize entity at index {}: {}",
                            idx, e
                        ))
                    })
            })
            .collect();

        let serialized = serialized?;

        // Phase 2: Begin transaction and allocate IDs
        let mut tx = self.begin()?;
        self.inner.db_metrics.transactions.record_start();

        // Get the starting entity ID and reserve a range
        let entity_count = entities.len() as u64;
        let start_id = {
            // Read current counter
            let current = match tx.get_metadata(b"next_entity_id")? {
                Some(bytes) if bytes.len() == 8 => {
                    let arr: [u8; 8] = bytes
                        .try_into()
                        .map_err(|_| Error::Execution("invalid entity counter".to_string()))?;
                    u64::from_be_bytes(arr)
                }
                _ => 1, // Start from 1 if not set
            };

            // Update counter to reserve the range
            let next = current + entity_count;
            tx.put_metadata(b"next_entity_id", &next.to_be_bytes())?;

            current
        };

        // Phase 3: Re-serialize with correct IDs (in parallel) and write
        // Now we have the IDs, we need to serialize again with the correct IDs
        let entities_with_ids: std::result::Result<Vec<(EntityId, Entity, Vec<u8>)>, Error> =
            entities
                .par_iter()
                .enumerate()
                .map(|(idx, entity)| {
                    let id = EntityId::new(start_id + idx as u64);
                    let mut entity_with_id = entity.clone();
                    entity_with_id.id = id;

                    bincode::serde::encode_to_vec(&entity_with_id, bincode::config::standard())
                        .map(|bytes| (id, entity_with_id, bytes))
                        .map_err(|e| {
                            Error::Execution(format!(
                                "Failed to serialize entity at index {}: {}",
                                idx, e
                            ))
                        })
                })
                .collect();

        let entities_with_ids = entities_with_ids?;

        // Drop the initial serialized results - we only needed them for validation
        drop(serialized);

        // Phase 4: Sequential writes (fast - just memcpy to transaction buffer)
        let ids: Vec<EntityId> = entities_with_ids.iter().map(|(id, _, _)| *id).collect();

        for (id, entity, bytes) in &entities_with_ids {
            let key = id.as_u64().to_be_bytes();
            let storage = tx.storage_mut_ref().map_err(Error::Transaction)?;

            storage
                .put("nodes", &key, bytes)
                .map_err(|e| Error::Execution(format!("Failed to write entity: {}", e)))?;

            // Phase 5a: Label index maintenance
            // Key format: <length:2 bytes><label:N bytes><entity_id:8 bytes>
            for label in &entity.labels {
                let label_bytes = label.as_str().as_bytes();
                let len = label_bytes.len() as u16;
                let mut label_key = Vec::with_capacity(2 + label_bytes.len() + 8);
                label_key.extend_from_slice(&len.to_be_bytes());
                label_key.extend_from_slice(label_bytes);
                label_key.extend_from_slice(&id.as_u64().to_be_bytes());
                storage
                    .put("label_index", &label_key, &[])
                    .map_err(|e| Error::Execution(format!("Failed to write label index: {}", e)))?;
            }

            // Phase 5b: Index maintenance (schema-based indexes)
            EntityIndexMaintenance::on_insert(&mut tx, entity)
                .map_err(|e| Error::Execution(format!("Index maintenance failed: {}", e)))?;

            // Phase 5c: Payload index maintenance
            self.inner.index_manager.on_entity_upsert_tx(
                tx.storage_mut_ref().map_err(Error::Transaction)?,
                entity,
                None, // New entity, no old version
            )?;
        }

        // Phase 6: Commit
        let commit_start = std::time::Instant::now();
        tx.commit().map_err(Error::Transaction)?;
        self.inner.db_metrics.record_commit(commit_start.elapsed());

        // Record successful bulk insert
        self.inner.db_metrics.record_query(start.elapsed(), true);

        Ok(ids)
    }

    /// Bulk insert edges with maximum throughput.
    ///
    /// All edges are inserted in a single transaction, with validation and
    /// serialization parallelized across CPU cores using rayon. This is the
    /// most efficient way to insert many edges.
    ///
    /// # Validation
    ///
    /// Before any edges are inserted, all source and target entity references
    /// are validated to ensure they exist. If any entity reference is invalid,
    /// the entire batch is rejected and no edges are inserted.
    ///
    /// # Performance
    ///
    /// This method achieves high throughput by:
    /// 1. **Parallel validation**: Entity existence checks are parallelized
    /// 2. **Parallel serialization**: Edges are serialized to binary format in parallel
    /// 3. **Single transaction**: All writes occur within one transaction (one fsync)
    /// 4. **Bulk ID allocation**: Edge IDs are allocated in a single atomic batch
    /// 5. **Index maintenance**: All edge indexes are updated within the same transaction
    ///
    /// # Arguments
    ///
    /// * `edges` - The edges to insert. All edges should have their source, target,
    ///   edge_type, and properties set. The `id` field will be overwritten with
    ///   auto-generated IDs.
    ///
    /// # Returns
    ///
    /// A vector of [`EdgeId`] for the inserted edges, in the same order as the input.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Any source entity doesn't exist (the entire batch is aborted)
    /// - Any target entity doesn't exist (the entire batch is aborted)
    /// - Serialization fails for any edge
    /// - The transaction cannot be committed
    ///
    /// # Example
    ///
    /// ```ignore
    /// use manifoldb::{Database, Edge, EdgeId, EntityId};
    ///
    /// let db = Database::in_memory()?;
    ///
    /// // First create some entities
    /// let entity_ids = db.bulk_insert_entities(&entities)?;
    ///
    /// // Create edges between entities (IDs will be assigned by bulk_insert_edges)
    /// let edges: Vec<Edge> = entity_ids.windows(2)
    ///     .map(|pair| {
    ///         Edge::new(EdgeId::new(0), pair[0], pair[1], "FOLLOWS") // ID is placeholder
    ///             .with_property("weight", 1.0f64)
    ///     })
    ///     .collect();
    ///
    /// // Insert all at once - much faster than individual inserts
    /// let edge_ids = db.bulk_insert_edges(&edges)?;
    /// ```
    pub fn bulk_insert_edges(&self, edges: &[Edge]) -> Result<Vec<EdgeId>> {
        use manifoldb_graph::index::IndexMaintenance;
        use rayon::prelude::*;

        // Table names matching transaction handle
        const TABLE_EDGES: &str = "edges";
        const TABLE_EDGES_OUT: &str = "edges_out";
        const TABLE_EDGES_IN: &str = "edges_in";

        // Helper to create adjacency key (same as transaction handle)
        fn make_adjacency_key(entity_id: EntityId, edge_id: EdgeId) -> [u8; 16] {
            let mut key = [0u8; 16];
            key[0..8].copy_from_slice(&entity_id.as_u64().to_be_bytes());
            key[8..16].copy_from_slice(&edge_id.as_u64().to_be_bytes());
            key
        }

        if edges.is_empty() {
            return Ok(Vec::new());
        }

        let start = std::time::Instant::now();

        // Phase 1: Validate all entity references exist
        // We need to check all source and target entities before any writes
        {
            let tx = self.begin_read()?;

            // Collect all unique entity IDs to check
            let mut entity_ids_to_check: Vec<EntityId> =
                edges.iter().flat_map(|e| [e.source, e.target]).collect();
            entity_ids_to_check.sort_unstable();
            entity_ids_to_check.dedup();

            // Check all entities exist
            for entity_id in &entity_ids_to_check {
                if tx.get_entity(*entity_id)?.is_none() {
                    return Err(Error::InvalidEntityReference(*entity_id));
                }
            }
        }

        // Phase 2: Parallel serialization (validation pass)
        // Serialize all edges in parallel to catch encoding errors early
        let serialized: std::result::Result<Vec<(usize, Vec<u8>)>, Error> = edges
            .par_iter()
            .enumerate()
            .map(|(idx, edge)| {
                bincode::serde::encode_to_vec(edge, bincode::config::standard())
                    .map(|bytes| (idx, bytes))
                    .map_err(|e| {
                        Error::Execution(format!(
                            "Failed to serialize edge at index {}: {}",
                            idx, e
                        ))
                    })
            })
            .collect();

        let serialized = serialized?;

        // Phase 3: Begin transaction and allocate IDs
        let mut tx = self.begin()?;
        self.inner.db_metrics.transactions.record_start();

        // Get the starting edge ID and reserve a range
        let edge_count = edges.len() as u64;
        let start_id = {
            // Read current counter
            let current = match tx.get_metadata(b"next_edge_id")? {
                Some(bytes) if bytes.len() == 8 => {
                    let arr: [u8; 8] = bytes
                        .try_into()
                        .map_err(|_| Error::Execution("invalid edge counter".to_string()))?;
                    u64::from_be_bytes(arr)
                }
                _ => 1, // Start from 1 if not set
            };

            // Update counter to reserve the range
            let next = current + edge_count;
            tx.put_metadata(b"next_edge_id", &next.to_be_bytes())?;

            current
        };

        // Phase 4: Re-serialize with correct IDs (in parallel)
        // Now we have the IDs, we need to serialize again with the correct IDs
        // Use Edge::encode() for graph layer compatibility
        let edges_with_ids: std::result::Result<Vec<(EdgeId, Edge, Vec<u8>)>, Error> = edges
            .par_iter()
            .enumerate()
            .map(|(idx, edge)| {
                let id = EdgeId::new(start_id + idx as u64);
                let mut edge_with_id = edge.clone();
                edge_with_id.id = id;

                edge_with_id.encode().map(|bytes| (id, edge_with_id, bytes)).map_err(|e| {
                    Error::Execution(format!("Failed to serialize edge at index {}: {}", idx, e))
                })
            })
            .collect();

        let edges_with_ids = edges_with_ids?;

        // Drop the initial serialized results - we only needed them for validation
        drop(serialized);

        // Phase 5: Sequential writes (fast - just memcpy to transaction buffer)
        let ids: Vec<EdgeId> = edges_with_ids.iter().map(|(id, _, _)| *id).collect();

        for (id, edge, bytes) in &edges_with_ids {
            // Store edge data with key encoding for graph layer compatibility
            let key = encode_edge_key(*id);
            tx.storage_mut_ref()
                .map_err(Error::Transaction)?
                .put(TABLE_EDGES, &key, bytes)
                .map_err(|e| Error::Execution(format!("Failed to write edge: {}", e)))?;

            // Update simple outgoing edge index (source -> edge)
            let out_key = make_adjacency_key(edge.source, *id);
            tx.storage_mut_ref()
                .map_err(Error::Transaction)?
                .put(TABLE_EDGES_OUT, &out_key, &[])
                .map_err(|e| Error::Execution(format!("Failed to write outgoing index: {}", e)))?;

            // Update simple incoming edge index (target -> edge)
            let in_key = make_adjacency_key(edge.target, *id);
            tx.storage_mut_ref()
                .map_err(Error::Transaction)?
                .put(TABLE_EDGES_IN, &in_key, &[])
                .map_err(|e| Error::Execution(format!("Failed to write incoming index: {}", e)))?;

            // Phase 6: Index maintenance - update graph layer indexes
            // (edges_by_source, edges_by_target, edge_types)
            IndexMaintenance::add_edge_indexes(
                tx.storage_mut_ref().map_err(Error::Transaction)?,
                edge,
            )
            .map_err(|e| Error::Execution(format!("Edge index maintenance failed: {}", e)))?;
        }

        // Phase 7: Commit
        let commit_start = std::time::Instant::now();
        tx.commit().map_err(Error::Transaction)?;
        self.inner.db_metrics.record_commit(commit_start.elapsed());

        // Record successful bulk insert
        self.inner.db_metrics.record_query(start.elapsed(), true);

        Ok(ids)
    }

    // ========================================================================
    // Bulk Vector Operations
    // ========================================================================

    /// Bulk insert vectors for entities.
    ///
    /// This method efficiently inserts multiple vectors in a single batch operation.
    /// All vectors are stored atomically. HNSW indexes are updated if they exist
    /// for the specified vector names.
    ///
    /// # Arguments
    ///
    /// * `collection_name` - The name of the collection
    /// * `vectors` - List of (entity_id, vector_name, vector_data) tuples
    ///
    /// # Returns
    ///
    /// The number of vectors successfully inserted.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Any referenced entity doesn't exist
    /// - The storage operation fails
    ///
    /// The operation is all-or-nothing: if any vector fails validation,
    /// no vectors are inserted.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use manifoldb::Database;
    ///
    /// let db = Database::in_memory()?;
    ///
    /// // Create entities first
    /// let mut tx = db.begin()?;
    /// let entity1 = tx.create_entity()?.with_label("documents");
    /// let entity2 = tx.create_entity()?.with_label("documents");
    /// tx.put_entity(&entity1)?;
    /// tx.put_entity(&entity2)?;
    /// tx.commit()?;
    ///
    /// // Bulk insert vectors
    /// let vectors = vec![
    ///     (entity1.id, "text_embedding".to_string(), vec![0.1f32; 384]),
    ///     (entity2.id, "text_embedding".to_string(), vec![0.2f32; 384]),
    /// ];
    ///
    /// let count = db.bulk_insert_vectors("documents", &vectors)?;
    /// assert_eq!(count, 2);
    /// ```
    ///
    /// # Performance
    ///
    /// This method is optimized for high throughput:
    /// - Single transaction for all storage operations
    /// - Batch HNSW index updates
    /// - Target: 100K+ vectors/second for typical workloads
    pub fn bulk_insert_vectors(
        &self,
        collection_name: &str,
        vectors: &[(manifoldb_core::EntityId, String, Vec<f32>)],
    ) -> Result<usize> {
        use crate::collection::{CollectionManager, CollectionName};
        use crate::vector::update_point_vector_in_index;
        use manifoldb_core::PointId;
        use manifoldb_vector::{
            encode_vector_value, encoding::encode_collection_vector_key, VectorData,
            TABLE_COLLECTION_VECTORS,
        };

        if vectors.is_empty() {
            return Ok(0);
        }

        let start = std::time::Instant::now();
        let count = vectors.len();

        // Parse and validate collection name
        let coll_name =
            CollectionName::new(collection_name).map_err(|e| Error::InvalidInput(e.to_string()))?;

        // Phase 1: Validate all entities exist
        {
            let tx = self.begin_read()?;
            for (entity_id, _, _) in vectors {
                if tx.get_entity(*entity_id)?.is_none() {
                    return Err(Error::EntityNotFound(*entity_id));
                }
            }
        }

        // Phase 2: Store vectors in the CollectionVectorStore and update HNSW indexes
        let mut tx = self.begin()?;
        self.inner.db_metrics.transactions.record_start();

        // Get or create collection ID
        let collection_id = match CollectionManager::get(&tx, &coll_name)
            .map_err(|e| Error::Collection(e.to_string()))?
        {
            Some(collection) => collection.id(),
            None => {
                // Create collection on first use with no vector configs
                // (vector configs can be added later if needed for schema validation)
                let collection = CollectionManager::create(&mut tx, &coll_name, std::iter::empty())
                    .map_err(|e| Error::Collection(e.to_string()))?;
                collection.id()
            }
        };

        // Store each vector in the collection_vectors table
        {
            let storage = tx.storage_mut().map_err(Error::Transaction)?;
            for (entity_id, vector_name, data) in vectors {
                // Convert Vec<f32> to VectorData::Dense
                let vector_data = VectorData::Dense(data.clone());

                // Encode key and value
                let key = encode_collection_vector_key(collection_id, *entity_id, vector_name);
                let value = encode_vector_value(&vector_data, vector_name);

                // Store in the collection_vectors table
                storage.put(TABLE_COLLECTION_VECTORS, &key, &value).map_err(Error::Storage)?;
            }
        }

        // Phase 3: Update HNSW indexes for each vector
        for (entity_id, vector_name, data) in vectors {
            let point_id = PointId::new(entity_id.as_u64());
            // update_point_vector_in_index checks if an index exists and only updates if it does
            update_point_vector_in_index(&mut tx, collection_name, vector_name, point_id, data)
                .map_err(|e| Error::Vector(e.to_string()))?;
        }

        // Commit the transaction
        let commit_start = std::time::Instant::now();
        tx.commit().map_err(Error::Transaction)?;
        self.inner.db_metrics.record_commit(commit_start.elapsed());

        // Record successful operation
        self.inner.db_metrics.record_query(start.elapsed(), true);

        Ok(count)
    }

    /// Bulk insert vectors for a single named vector across multiple entities.
    ///
    /// This is a convenience method for the common case where all vectors
    /// have the same name (e.g., all are "text_embedding").
    ///
    /// # Arguments
    ///
    /// * `collection_name` - The name of the collection
    /// * `vector_name` - The name of the vector field
    /// * `vectors` - List of (entity_id, vector_data) tuples
    ///
    /// # Returns
    ///
    /// The number of vectors successfully inserted.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let vectors = vec![
    ///     (entity1.id, vec![0.1f32; 384]),
    ///     (entity2.id, vec![0.2f32; 384]),
    /// ];
    ///
    /// let count = db.bulk_insert_named_vectors("documents", "text_embedding", &vectors)?;
    /// ```
    pub fn bulk_insert_named_vectors(
        &self,
        collection_name: &str,
        vector_name: &str,
        vectors: &[(manifoldb_core::EntityId, Vec<f32>)],
    ) -> Result<usize> {
        let expanded: Vec<(manifoldb_core::EntityId, String, Vec<f32>)> =
            vectors.iter().map(|(id, data)| (*id, vector_name.to_string(), data.clone())).collect();

        self.bulk_insert_vectors(collection_name, &expanded)
    }

    // ========================================================================
    // Bulk Delete Vector Operations
    // ========================================================================

    /// Delete specific vectors by entity ID and vector name.
    ///
    /// This method removes vector properties from entities. Each entry in the
    /// `vectors` slice is a tuple of `(entity_id, vector_name)` specifying which
    /// vector to delete from which entity.
    ///
    /// # Use Cases
    ///
    /// - Remove embeddings when re-embedding with a different model
    /// - Clean up vectors for entities that no longer need them
    /// - Selective vector removal (e.g., delete image embeddings, keep text embeddings)
    ///
    /// # Arguments
    ///
    /// * `vectors` - List of `(entity_id, vector_name)` tuples specifying which
    ///   vectors to delete
    ///
    /// # Returns
    ///
    /// The number of vectors that were actually deleted. This may be less than
    /// the input count if some vectors didn't exist.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - An entity referenced in the input does not exist
    /// - The transaction cannot be committed
    ///
    /// # Example
    ///
    /// ```ignore
    /// use manifoldb::Database;
    /// use manifoldb_core::EntityId;
    ///
    /// let db = Database::in_memory()?;
    ///
    /// // First, insert some vectors
    /// let vectors = vec![
    ///     (entity1.id, "text_embedding".to_string(), vec![0.1f32; 384]),
    ///     (entity1.id, "image_embedding".to_string(), vec![0.2f32; 512]),
    ///     (entity2.id, "text_embedding".to_string(), vec![0.3f32; 384]),
    /// ];
    /// db.bulk_insert_vectors("documents", &vectors)?;
    ///
    /// // Now delete specific vectors
    /// let to_delete = vec![
    ///     (entity1.id, "image_embedding".to_string()),
    ///     (entity2.id, "text_embedding".to_string()),
    /// ];
    /// let deleted = db.bulk_delete_vectors(&to_delete)?;
    /// assert_eq!(deleted, 2);
    /// ```
    pub fn bulk_delete_vectors(
        &self,
        vectors: &[(manifoldb_core::EntityId, String)],
    ) -> Result<usize> {
        use crate::collection::{CollectionManager, CollectionName};
        use crate::vector::remove_point_vector_from_index;
        use manifoldb_core::PointId;
        use manifoldb_vector::{encoding::encode_collection_vector_key, TABLE_COLLECTION_VECTORS};

        if vectors.is_empty() {
            return Ok(0);
        }

        let start = std::time::Instant::now();

        // Phase 1: Validate all entities exist
        {
            let tx = self.begin_read()?;
            for (entity_id, _) in vectors {
                if tx.get_entity(*entity_id)?.is_none() {
                    return Err(Error::EntityNotFound(*entity_id));
                }
            }
        }

        // Phase 2: Delete vectors from all collections
        // Since we don't know which collection the vector belongs to, we need to check all
        let mut tx = self.begin()?;
        self.inner.db_metrics.transactions.record_start();

        let mut deleted_count = 0;

        // Get all collection names and IDs by listing collection names and looking them up
        let collections: Vec<(CollectionName, manifoldb_core::CollectionId)> = {
            let names =
                CollectionManager::list(&tx).map_err(|e| Error::Collection(e.to_string()))?;
            let mut result = Vec::new();
            for name in names {
                if let Some(collection) = CollectionManager::get(&tx, &name)
                    .map_err(|e| Error::Collection(e.to_string()))?
                {
                    result.push((name, collection.id()));
                }
            }
            result
        };

        // Track which vectors were deleted from which collections for HNSW updates
        let mut hnsw_updates: Vec<(&str, manifoldb_core::EntityId, &str)> = Vec::new();

        {
            let storage = tx.storage_mut().map_err(Error::Transaction)?;

            for (entity_id, vector_name) in vectors {
                // Try to delete from each collection
                for (collection_name, collection_id) in &collections {
                    let key = encode_collection_vector_key(*collection_id, *entity_id, vector_name);
                    // Check if key exists and delete it
                    if storage
                        .get(TABLE_COLLECTION_VECTORS, &key)
                        .map_err(Error::Storage)?
                        .is_some()
                    {
                        storage.delete(TABLE_COLLECTION_VECTORS, &key).map_err(Error::Storage)?;
                        deleted_count += 1;
                        // Track for HNSW update
                        hnsw_updates.push((collection_name.as_str(), *entity_id, vector_name));
                        break; // Found and deleted, no need to check other collections
                    }
                }
            }
        }

        // Phase 3: Update HNSW indexes - remove deleted vectors
        for (collection_name, entity_id, vector_name) in hnsw_updates {
            let point_id = PointId::new(entity_id.as_u64());
            remove_point_vector_from_index(&mut tx, collection_name, vector_name, point_id)
                .map_err(|e| Error::Vector(e.to_string()))?;
        }

        // Commit the transaction
        let commit_start = std::time::Instant::now();
        tx.commit().map_err(Error::Transaction)?;
        self.inner.db_metrics.record_commit(commit_start.elapsed());

        // Record successful operation
        self.inner.db_metrics.record_query(start.elapsed(), true);

        Ok(deleted_count)
    }

    /// Delete all vectors with a given name across multiple entities.
    ///
    /// This is a convenience method for the common case where you want to
    /// delete the same named vector from multiple entities.
    ///
    /// # Use Cases
    ///
    /// - Re-embed all documents with a new model (delete old embeddings first)
    /// - Remove a deprecated embedding type across the dataset
    /// - Clean up after changing vector dimension requirements
    ///
    /// # Arguments
    ///
    /// * `vector_name` - The name of the vector field to delete
    /// * `entity_ids` - List of entity IDs from which to delete the vector
    ///
    /// # Returns
    ///
    /// The number of vectors that were actually deleted. This may be less than
    /// the input count if some vectors didn't exist.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use manifoldb::Database;
    /// use manifoldb_core::EntityId;
    ///
    /// let db = Database::in_memory()?;
    ///
    /// // Delete text embeddings from multiple entities
    /// let entity_ids = vec![entity1.id, entity2.id, entity3.id];
    /// let deleted = db.bulk_delete_vectors_by_name("text_embedding", &entity_ids)?;
    /// ```
    pub fn bulk_delete_vectors_by_name(
        &self,
        vector_name: &str,
        entity_ids: &[manifoldb_core::EntityId],
    ) -> Result<usize> {
        let expanded: Vec<(manifoldb_core::EntityId, String)> =
            entity_ids.iter().map(|id| (*id, vector_name.to_string())).collect();

        self.bulk_delete_vectors(&expanded)
    }

    // ========================================================================
    // Bulk Update Vector Operations
    // ========================================================================

    /// Bulk update (replace) vectors for entities.
    ///
    /// This method updates existing vectors with new data. It is optimized for
    /// re-embedding scenarios where you need to replace vectors with a new/better model.
    ///
    /// Unlike `bulk_insert_vectors`, this method:
    /// - Validates that entities already have vectors with the specified names
    /// - Returns an error if any entity is missing the vector to update
    ///
    /// # Arguments
    ///
    /// * `collection_name` - The name of the collection (used for HNSW index lookup)
    /// * `vectors` - List of (entity_id, vector_name, vector_data) tuples
    ///
    /// # Returns
    ///
    /// The number of vectors successfully updated.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Any entity does not exist
    /// - Any entity does not have a vector with the specified name
    /// - The transaction cannot be committed
    ///
    /// The operation is all-or-nothing: if any vector fails validation, no changes are made.
    ///
    /// # Example
    ///
    /// ```ignore
    /// // Re-embed documents with a new model
    /// let new_embeddings = vec![
    ///     (entity1.id, "text_embedding".to_string(), new_model.encode("doc1")),
    ///     (entity2.id, "text_embedding".to_string(), new_model.encode("doc2")),
    /// ];
    ///
    /// let count = db.bulk_update_vectors("documents", &new_embeddings)?;
    /// assert_eq!(count, 2);
    /// ```
    ///
    /// # Performance
    ///
    /// This method is optimized for high throughput:
    /// - Single transaction for all storage operations
    /// - HNSW index updates use efficient delete-then-insert strategy
    /// - Target: 100K+ vectors/second for typical workloads
    pub fn bulk_update_vectors(
        &self,
        collection_name: &str,
        vectors: &[(manifoldb_core::EntityId, String, Vec<f32>)],
    ) -> Result<usize> {
        use crate::collection::{CollectionManager, CollectionName};
        use crate::vector::update_point_vector_in_index;
        use manifoldb_core::PointId;
        use manifoldb_vector::{
            encode_vector_value, encoding::encode_collection_vector_key, VectorData,
            TABLE_COLLECTION_VECTORS,
        };

        if vectors.is_empty() {
            return Ok(0);
        }

        let start = std::time::Instant::now();
        let count = vectors.len();

        // Parse and validate collection name
        let coll_name =
            CollectionName::new(collection_name).map_err(|e| Error::InvalidInput(e.to_string()))?;

        // Phase 1: Validate all entities exist AND have vectors with the specified names in the collection
        {
            let tx = self.begin_read()?;

            // Get collection - must exist for update
            let collection = CollectionManager::get(&tx, &coll_name)
                .map_err(|e| Error::Collection(e.to_string()))?
                .ok_or_else(|| {
                    Error::Collection(format!("Collection '{}' not found", collection_name))
                })?;
            let collection_id = collection.id();

            let storage = tx.storage_ref().map_err(Error::Transaction)?;

            for (entity_id, vector_name, _) in vectors {
                // Entity must exist
                if tx.get_entity(*entity_id)?.is_none() {
                    return Err(Error::EntityNotFound(*entity_id));
                }

                // Check that the vector exists in collection_vectors table
                let key = encode_collection_vector_key(collection_id, *entity_id, vector_name);
                if storage.get(TABLE_COLLECTION_VECTORS, &key).map_err(Error::Storage)?.is_none() {
                    return Err(Error::Vector(format!(
                        "Entity {} does not have vector '{}' to update",
                        entity_id, vector_name
                    )));
                }
            }
        }

        // Phase 2: Update vectors in the collection_vectors table and HNSW indexes
        let mut tx = self.begin()?;
        self.inner.db_metrics.transactions.record_start();

        // Get collection ID again in write transaction
        let collection_id = CollectionManager::get(&tx, &coll_name)
            .map_err(|e| Error::Collection(e.to_string()))?
            .map(|c| c.id())
            .ok_or_else(|| {
                Error::Collection(format!("Collection '{}' not found", collection_name))
            })?;

        {
            let storage = tx.storage_mut().map_err(Error::Transaction)?;

            for (entity_id, vector_name, data) in vectors {
                // Convert Vec<f32> to VectorData::Dense
                let vector_data = VectorData::Dense(data.clone());

                // Encode key and value
                let key = encode_collection_vector_key(collection_id, *entity_id, vector_name);
                let value = encode_vector_value(&vector_data, vector_name);

                // Store in the collection_vectors table (overwrites existing)
                storage.put(TABLE_COLLECTION_VECTORS, &key, &value).map_err(Error::Storage)?;
            }
        }

        // Phase 3: Update HNSW indexes for each vector
        // update_point_vector_in_index handles updating existing entries in HNSW
        for (entity_id, vector_name, data) in vectors {
            let point_id = PointId::new(entity_id.as_u64());
            update_point_vector_in_index(&mut tx, collection_name, vector_name, point_id, data)
                .map_err(|e| Error::Vector(e.to_string()))?;
        }

        // Commit the transaction
        let commit_start = std::time::Instant::now();
        tx.commit().map_err(Error::Transaction)?;
        self.inner.db_metrics.record_commit(commit_start.elapsed());

        // Record successful operation
        self.inner.db_metrics.record_query(start.elapsed(), true);

        Ok(count)
    }

    /// Bulk replace vectors for a single named vector across multiple entities.
    ///
    /// This is a convenience method for the common re-embedding scenario where
    /// all vectors have the same name (e.g., re-embedding all "text_embedding" vectors).
    ///
    /// # Arguments
    ///
    /// * `collection_name` - The name of the collection
    /// * `vector_name` - The name of the vector field to replace
    /// * `vectors` - List of (entity_id, vector_data) tuples
    ///
    /// # Returns
    ///
    /// The number of vectors successfully updated.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Any entity does not exist
    /// - Any entity does not have a vector with the specified name
    ///
    /// # Example
    ///
    /// ```ignore
    /// // Re-embed all documents with a new model
    /// let new_embeddings: Vec<(EntityId, Vec<f32>)> = documents
    ///     .iter()
    ///     .map(|doc| (doc.id, new_model.encode(&doc.text)))
    ///     .collect();
    ///
    /// let count = db.bulk_replace_named_vectors(
    ///     "documents",
    ///     "text_embedding",
    ///     &new_embeddings
    /// )?;
    /// ```
    pub fn bulk_replace_named_vectors(
        &self,
        collection_name: &str,
        vector_name: &str,
        vectors: &[(manifoldb_core::EntityId, Vec<f32>)],
    ) -> Result<usize> {
        let expanded: Vec<(manifoldb_core::EntityId, String, Vec<f32>)> =
            vectors.iter().map(|(id, data)| (*id, vector_name.to_string(), data.clone())).collect();

        self.bulk_update_vectors(collection_name, &expanded)
    }

    // ========================================================================
    // Vector Retrieval Operations
    // ========================================================================

    /// Get a specific named vector for an entity.
    ///
    /// Retrieves a single vector from the collection's vector storage. This is
    /// the primary method for accessing vector data that was stored using
    /// `bulk_insert_vectors` or `bulk_insert_named_vectors`.
    ///
    /// # Arguments
    ///
    /// * `collection_name` - The collection containing the entity
    /// * `entity_id` - The entity ID
    /// * `vector_name` - The name of the vector (e.g., "text_embedding")
    ///
    /// # Returns
    ///
    /// The vector data if it exists, `None` otherwise. The return type is
    /// [`VectorData`](manifoldb_vector::VectorData) which can be dense, sparse,
    /// multi-vector, or binary.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The collection name is invalid
    /// - The collection does not exist
    /// - The storage operation fails
    ///
    /// # Example
    ///
    /// ```ignore
    /// use manifoldb::Database;
    ///
    /// let db = Database::in_memory()?;
    ///
    /// // After inserting vectors...
    /// if let Some(vector) = db.get_vector("documents", entity_id, "text_embedding")? {
    ///     println!("Vector dimension: {}", vector.dimension());
    ///     if let Some(dense) = vector.as_dense() {
    ///         println!("First element: {}", dense[0]);
    ///     }
    /// }
    /// ```
    pub fn get_vector(
        &self,
        collection_name: &str,
        entity_id: manifoldb_core::EntityId,
        vector_name: &str,
    ) -> Result<Option<manifoldb_vector::VectorData>> {
        use crate::collection::{CollectionManager, CollectionName};
        use manifoldb_vector::{encoding::encode_collection_vector_key, TABLE_COLLECTION_VECTORS};

        // Parse and validate collection name
        let coll_name =
            CollectionName::new(collection_name).map_err(|e| Error::InvalidInput(e.to_string()))?;

        // Get collection ID (read-only)
        let tx = self.begin_read()?;
        let collection = CollectionManager::get(&tx, &coll_name)
            .map_err(|e| Error::Collection(e.to_string()))?
            .ok_or_else(|| {
                Error::Collection(format!("collection '{}' not found", collection_name))
            })?;
        let collection_id = collection.id();

        // Access storage directly for vector lookup
        let storage = tx.storage_ref().map_err(Error::Transaction)?;
        let key = encode_collection_vector_key(collection_id, entity_id, vector_name);

        match storage.get(TABLE_COLLECTION_VECTORS, &key).map_err(Error::Storage)? {
            Some(bytes) => {
                let (data, _name) =
                    manifoldb_vector::store::decode_vector_value(&bytes).map_err(|e| {
                        Error::Storage(manifoldb_storage::StorageError::Serialization(
                            e.to_string(),
                        ))
                    })?;
                Ok(Some(data))
            }
            None => Ok(None),
        }
    }

    /// Get all named vectors for an entity.
    ///
    /// Returns a map of vector names to their data. Useful when an entity
    /// has multiple embeddings (text, image, summary, etc.).
    ///
    /// # Arguments
    ///
    /// * `collection_name` - The collection containing the entity
    /// * `entity_id` - The entity ID
    ///
    /// # Returns
    ///
    /// A `HashMap` of vector_name → vector_data. Returns an empty map if the
    /// entity has no vectors.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The collection name is invalid
    /// - The collection does not exist
    /// - The storage operation fails
    ///
    /// # Example
    ///
    /// ```ignore
    /// use manifoldb::Database;
    ///
    /// let db = Database::in_memory()?;
    ///
    /// // After inserting multiple named vectors...
    /// let vectors = db.get_all_vectors("documents", entity_id)?;
    /// for (name, vec) in vectors {
    ///     println!("{}: {} dimensions", name, vec.dimension());
    /// }
    /// ```
    pub fn get_all_vectors(
        &self,
        collection_name: &str,
        entity_id: manifoldb_core::EntityId,
    ) -> Result<std::collections::HashMap<String, manifoldb_vector::VectorData>> {
        use crate::collection::{CollectionManager, CollectionName};
        use manifoldb_storage::Cursor;
        use manifoldb_vector::{encoding::encode_entity_vector_prefix, TABLE_COLLECTION_VECTORS};
        use std::ops::Bound;

        // Parse and validate collection name
        let coll_name =
            CollectionName::new(collection_name).map_err(|e| Error::InvalidInput(e.to_string()))?;

        // Get collection ID (read-only)
        let tx = self.begin_read()?;
        let collection = CollectionManager::get(&tx, &coll_name)
            .map_err(|e| Error::Collection(e.to_string()))?
            .ok_or_else(|| {
                Error::Collection(format!("collection '{}' not found", collection_name))
            })?;
        let collection_id = collection.id();

        // Access storage directly for vector scan
        let storage = tx.storage_ref().map_err(Error::Transaction)?;
        let prefix = encode_entity_vector_prefix(collection_id, entity_id);
        let prefix_end = next_prefix(&prefix);

        let mut cursor = storage
            .range(
                TABLE_COLLECTION_VECTORS,
                Bound::Included(prefix.as_slice()),
                Bound::Excluded(prefix_end.as_slice()),
            )
            .map_err(Error::Storage)?;

        let mut vectors = std::collections::HashMap::new();
        while let Some((_key, value)) = cursor.next().map_err(Error::Storage)? {
            let (data, vector_name) = manifoldb_vector::store::decode_vector_value(&value)
                .map_err(|e| {
                    Error::Storage(manifoldb_storage::StorageError::Serialization(e.to_string()))
                })?;
            vectors.insert(vector_name, data);
        }

        Ok(vectors)
    }

    /// Check if an entity has a specific named vector.
    ///
    /// This is a lightweight existence check that doesn't load the vector data.
    ///
    /// # Arguments
    ///
    /// * `collection_name` - The collection containing the entity
    /// * `entity_id` - The entity ID
    /// * `vector_name` - The name of the vector to check
    ///
    /// # Returns
    ///
    /// `true` if the vector exists, `false` otherwise.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The collection name is invalid
    /// - The collection does not exist
    /// - The storage operation fails
    ///
    /// # Example
    ///
    /// ```ignore
    /// use manifoldb::Database;
    ///
    /// let db = Database::in_memory()?;
    ///
    /// if db.has_vector("documents", entity_id, "text_embedding")? {
    ///     println!("Entity has a text embedding");
    /// } else {
    ///     println!("Entity needs embedding generation");
    /// }
    /// ```
    pub fn has_vector(
        &self,
        collection_name: &str,
        entity_id: manifoldb_core::EntityId,
        vector_name: &str,
    ) -> Result<bool> {
        use crate::collection::{CollectionManager, CollectionName};
        use manifoldb_vector::{encoding::encode_collection_vector_key, TABLE_COLLECTION_VECTORS};

        // Parse and validate collection name
        let coll_name =
            CollectionName::new(collection_name).map_err(|e| Error::InvalidInput(e.to_string()))?;

        // Get collection ID (read-only)
        let tx = self.begin_read()?;
        let collection = CollectionManager::get(&tx, &coll_name)
            .map_err(|e| Error::Collection(e.to_string()))?
            .ok_or_else(|| {
                Error::Collection(format!("collection '{}' not found", collection_name))
            })?;
        let collection_id = collection.id();

        // Access storage directly for existence check
        let storage = tx.storage_ref().map_err(Error::Transaction)?;
        let key = encode_collection_vector_key(collection_id, entity_id, vector_name);

        Ok(storage.get(TABLE_COLLECTION_VECTORS, &key).map_err(Error::Storage)?.is_some())
    }

    // ========================================================================
    // Bulk Upsert Operations
    // ========================================================================

    /// Bulk upsert (insert or update) entities.
    ///
    /// For each entity in the input:
    /// - If an entity with the same ID exists: update it with the new data
    /// - If no entity with that ID exists: insert it as a new entity
    ///
    /// All operations are performed in a single transaction for atomicity.
    ///
    /// # Performance
    ///
    /// This method achieves high throughput by:
    /// 1. **Parallel existence check**: Entity IDs are checked in parallel
    /// 2. **Parallel serialization**: Entities are serialized to binary format in parallel
    /// 3. **Single transaction**: All writes occur within one transaction (one fsync)
    /// 4. **Index maintenance**: All indexes are updated appropriately for inserts and updates
    ///
    /// # Arguments
    ///
    /// * `entities` - The entities to upsert. Each entity must have a valid ID set.
    ///   For inserts, use a placeholder ID (e.g., `EntityId::new(0)`) and the method
    ///   will assign new sequential IDs. For updates, use the existing entity's ID.
    ///
    /// # Returns
    ///
    /// A tuple of `(inserted_count, updated_count)` indicating how many entities
    /// were inserted vs updated.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Serialization fails for any entity
    /// - The transaction cannot be committed
    /// - Index maintenance fails
    ///
    /// The operation is all-or-nothing: if any entity fails, no changes are made.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use manifoldb::{Database, Entity, EntityId};
    ///
    /// let db = Database::in_memory()?;
    ///
    /// // First, insert some entities
    /// let entities: Vec<Entity> = (0..100)
    ///     .map(|i| Entity::new(EntityId::new(0))
    ///         .with_label("Document")
    ///         .with_property("version", 1i64))
    ///     .collect();
    /// let ids = db.bulk_insert_entities(&entities)?;
    ///
    /// // Now upsert: update existing + insert new
    /// let mut upsert_entities: Vec<Entity> = Vec::new();
    ///
    /// // Update first 50 with new version
    /// for id in ids.iter().take(50) {
    ///     upsert_entities.push(
    ///         Entity::new(*id)
    ///             .with_label("Document")
    ///             .with_property("version", 2i64)
    ///     );
    /// }
    ///
    /// // Add 50 new entities
    /// for _ in 0..50 {
    ///     upsert_entities.push(
    ///         Entity::new(EntityId::new(0))
    ///             .with_label("Document")
    ///             .with_property("version", 1i64)
    ///     );
    /// }
    ///
    /// let (inserted, updated) = db.bulk_upsert_entities(&upsert_entities)?;
    /// assert_eq!(inserted, 50);
    /// assert_eq!(updated, 50);
    /// ```
    pub fn bulk_upsert_entities(&self, entities: &[Entity]) -> Result<(usize, usize)> {
        use crate::execution::EntityIndexMaintenance;
        use rayon::prelude::*;

        if entities.is_empty() {
            return Ok((0, 0));
        }

        let start = std::time::Instant::now();

        // Phase 1: Determine which entities exist and which are new
        // Entities with id == 0 are always new inserts
        // Entities with id != 0 need to be checked
        let mut to_insert: Vec<(usize, &Entity)> = Vec::new();
        let mut to_update: Vec<(usize, &Entity, Entity)> = Vec::new(); // (index, new_entity, old_entity)

        {
            let tx = self.begin_read()?;
            for (idx, entity) in entities.iter().enumerate() {
                if entity.id.as_u64() == 0 {
                    // New entity to insert
                    to_insert.push((idx, entity));
                } else {
                    // Check if it exists
                    match tx.get_entity(entity.id)? {
                        Some(old_entity) => {
                            // Entity exists - update
                            to_update.push((idx, entity, old_entity));
                        }
                        None => {
                            // Entity doesn't exist - treat as insert with specified ID
                            // Note: We'll need to handle this carefully since we can't
                            // insert with a specific ID in the normal flow.
                            // For now, we treat non-existent IDs as inserts that will get new IDs.
                            to_insert.push((idx, entity));
                        }
                    }
                }
            }
        }

        let inserted_count = to_insert.len();
        let updated_count = to_update.len();

        // Phase 2: Parallel serialization validation for all entities
        // This catches errors before we start any writes
        let validation_result: std::result::Result<(), Error> =
            entities.par_iter().enumerate().try_for_each(|(idx, entity)| {
                bincode::serde::encode_to_vec(entity, bincode::config::standard())
                    .map(|_| ())
                    .map_err(|e| {
                        Error::Execution(format!(
                            "Failed to serialize entity at index {}: {}",
                            idx, e
                        ))
                    })
            });
        validation_result?;

        // Phase 3: Begin write transaction
        let mut tx = self.begin()?;
        self.inner.db_metrics.transactions.record_start();

        // Phase 4: Handle inserts - allocate new IDs
        let new_entity_ids = if to_insert.is_empty() {
            Vec::new()
        } else {
            let entity_count = to_insert.len() as u64;
            let start_id = {
                // Read current counter
                let current = match tx.get_metadata(b"next_entity_id")? {
                    Some(bytes) if bytes.len() == 8 => {
                        let arr: [u8; 8] = bytes
                            .try_into()
                            .map_err(|_| Error::Execution("invalid entity counter".to_string()))?;
                        u64::from_be_bytes(arr)
                    }
                    _ => 1, // Start from 1 if not set
                };

                // Update counter to reserve the range
                let next = current + entity_count;
                tx.put_metadata(b"next_entity_id", &next.to_be_bytes())?;

                current
            };

            // Assign IDs to entities being inserted
            to_insert
                .iter()
                .enumerate()
                .map(|(i, _)| EntityId::new(start_id + i as u64))
                .collect::<Vec<_>>()
        };

        // Phase 5: Parallel serialization with correct IDs for inserts
        let serialized_inserts: std::result::Result<Vec<(EntityId, Entity, Vec<u8>)>, Error> =
            to_insert
                .par_iter()
                .zip(new_entity_ids.par_iter())
                .map(|((_, entity), &id)| {
                    let mut entity_with_id = (*entity).clone();
                    entity_with_id.id = id;

                    bincode::serde::encode_to_vec(&entity_with_id, bincode::config::standard())
                        .map(|bytes| (id, entity_with_id, bytes))
                        .map_err(|e| {
                            Error::Execution(format!(
                                "Failed to serialize entity for insert: {}",
                                e
                            ))
                        })
                })
                .collect();
        let serialized_inserts = serialized_inserts?;

        // Phase 6: Parallel serialization for updates (keeping original IDs)
        let serialized_updates: std::result::Result<
            Vec<(EntityId, Entity, Entity, Vec<u8>)>,
            Error,
        > = to_update
            .par_iter()
            .map(|(_, new_entity, old_entity)| {
                let entity_with_id = (*new_entity).clone();
                // Note: new_entity should already have the correct ID from the input

                bincode::serde::encode_to_vec(&entity_with_id, bincode::config::standard())
                    .map(|bytes| (entity_with_id.id, entity_with_id, old_entity.clone(), bytes))
                    .map_err(|e| {
                        Error::Execution(format!("Failed to serialize entity for update: {}", e))
                    })
            })
            .collect();
        let serialized_updates = serialized_updates?;

        // Phase 7: Sequential writes for inserts
        for (id, entity, bytes) in &serialized_inserts {
            let key = id.as_u64().to_be_bytes();
            let storage = tx.storage_mut_ref().map_err(Error::Transaction)?;

            storage
                .put("nodes", &key, bytes)
                .map_err(|e| Error::Execution(format!("Failed to write entity: {}", e)))?;

            // Label index maintenance for insert
            for label in &entity.labels {
                let label_bytes = label.as_str().as_bytes();
                let len = label_bytes.len() as u16;
                let mut label_key = Vec::with_capacity(2 + label_bytes.len() + 8);
                label_key.extend_from_slice(&len.to_be_bytes());
                label_key.extend_from_slice(label_bytes);
                label_key.extend_from_slice(&id.as_u64().to_be_bytes());
                storage
                    .put("label_index", &label_key, &[])
                    .map_err(|e| Error::Execution(format!("Failed to write label index: {}", e)))?;
            }

            // Index maintenance for insert (schema-based indexes)
            EntityIndexMaintenance::on_insert(&mut tx, entity)
                .map_err(|e| Error::Execution(format!("Index maintenance failed: {}", e)))?;

            // Payload index maintenance for insert
            self.inner.index_manager.on_entity_upsert_tx(
                tx.storage_mut_ref().map_err(Error::Transaction)?,
                entity,
                None, // New entity, no old version
            )?;
        }

        // Phase 8: Sequential writes for updates
        for (id, new_entity, old_entity, bytes) in &serialized_updates {
            let key = id.as_u64().to_be_bytes();
            let storage = tx.storage_mut_ref().map_err(Error::Transaction)?;

            storage
                .put("nodes", &key, bytes)
                .map_err(|e| Error::Execution(format!("Failed to write entity: {}", e)))?;

            // Label index maintenance for update - remove old labels not in new
            for old_label in &old_entity.labels {
                if !new_entity.labels.contains(old_label) {
                    let label_bytes = old_label.as_str().as_bytes();
                    let len = label_bytes.len() as u16;
                    let mut label_key = Vec::with_capacity(2 + label_bytes.len() + 8);
                    label_key.extend_from_slice(&len.to_be_bytes());
                    label_key.extend_from_slice(label_bytes);
                    label_key.extend_from_slice(&id.as_u64().to_be_bytes());
                    storage.delete("label_index", &label_key).map_err(|e| {
                        Error::Execution(format!("Failed to delete label index: {}", e))
                    })?;
                }
            }
            // Add new labels not in old
            for new_label in &new_entity.labels {
                if !old_entity.labels.contains(new_label) {
                    let label_bytes = new_label.as_str().as_bytes();
                    let len = label_bytes.len() as u16;
                    let mut label_key = Vec::with_capacity(2 + label_bytes.len() + 8);
                    label_key.extend_from_slice(&len.to_be_bytes());
                    label_key.extend_from_slice(label_bytes);
                    label_key.extend_from_slice(&id.as_u64().to_be_bytes());
                    storage.put("label_index", &label_key, &[]).map_err(|e| {
                        Error::Execution(format!("Failed to write label index: {}", e))
                    })?;
                }
            }

            // Index maintenance for update (schema-based indexes)
            EntityIndexMaintenance::on_update(&mut tx, old_entity, new_entity)
                .map_err(|e| Error::Execution(format!("Index maintenance failed: {}", e)))?;

            // Payload index maintenance for update
            self.inner.index_manager.on_entity_upsert_tx(
                tx.storage_mut_ref().map_err(Error::Transaction)?,
                new_entity,
                Some(old_entity),
            )?;
        }

        // Phase 9: Commit
        let commit_start = std::time::Instant::now();
        tx.commit().map_err(Error::Transaction)?;
        self.inner.db_metrics.record_commit(commit_start.elapsed());

        // Record successful bulk upsert
        self.inner.db_metrics.record_query(start.elapsed(), true);

        Ok((inserted_count, updated_count))
    }

    // ========================================================================
    // Bulk Delete Operations
    // ========================================================================

    /// Bulk delete entities by ID.
    ///
    /// All deletions happen in a single transaction. This method properly
    /// cleans up all property indexes and vector indexes for deleted entities.
    ///
    /// By default, this method performs cascade deletion of connected edges.
    /// Use [`bulk_delete_entities_checked`](Self::bulk_delete_entities_checked) if you
    /// want to error when entities have connected edges.
    ///
    /// # Arguments
    ///
    /// * `entity_ids` - The IDs of entities to delete
    ///
    /// # Returns
    ///
    /// The number of entities that were actually deleted. This may be less
    /// than the input size if some entities didn't exist.
    ///
    /// # Performance
    ///
    /// This method achieves high throughput by:
    /// 1. **Single transaction**: All deletes occur within one transaction (one fsync)
    /// 2. **Batch index cleanup**: Property index entries removed efficiently
    /// 3. **Cascade edge deletion**: All connected edges deleted within same transaction
    ///
    /// # Example
    ///
    /// ```ignore
    /// use manifoldb::{Database, EntityId};
    ///
    /// let db = Database::in_memory()?;
    ///
    /// // Create some entities
    /// let ids = db.bulk_insert_entities(&entities)?;
    ///
    /// // Delete half of them
    /// let to_delete: Vec<EntityId> = ids[0..ids.len()/2].to_vec();
    /// let deleted = db.bulk_delete_entities(&to_delete)?;
    /// assert_eq!(deleted, to_delete.len());
    /// ```
    pub fn bulk_delete_entities(&self, entity_ids: &[EntityId]) -> Result<usize> {
        self.bulk_delete_entities_impl(entity_ids, true)
    }

    /// Bulk delete entities by ID, erroring if any entity has connected edges.
    ///
    /// Similar to [`bulk_delete_entities`](Self::bulk_delete_entities), but
    /// returns an error if any entity has connected edges instead of
    /// automatically deleting them.
    ///
    /// # Arguments
    ///
    /// * `entity_ids` - The IDs of entities to delete
    ///
    /// # Returns
    ///
    /// The number of entities that were actually deleted.
    ///
    /// # Errors
    ///
    /// Returns [`Error::BulkOperation`] if any entity has connected edges.
    /// In this case, no entities are deleted (the operation is atomic).
    ///
    /// # Example
    ///
    /// ```ignore
    /// use manifoldb::{Database, EntityId};
    ///
    /// let db = Database::in_memory()?;
    ///
    /// // Delete entities that shouldn't have any edges
    /// match db.bulk_delete_entities_checked(&entity_ids) {
    ///     Ok(count) => println!("Deleted {} entities", count),
    ///     Err(e) => println!("Some entities had edges: {}", e),
    /// }
    /// ```
    pub fn bulk_delete_entities_checked(&self, entity_ids: &[EntityId]) -> Result<usize> {
        self.bulk_delete_entities_impl(entity_ids, false)
    }

    /// Internal implementation of bulk delete with cascade control.
    fn bulk_delete_entities_impl(
        &self,
        entity_ids: &[EntityId],
        cascade_edges: bool,
    ) -> Result<usize> {
        use crate::collection::CollectionManager;
        use crate::execution::EntityIndexMaintenance;
        use manifoldb_storage::Cursor;
        use manifoldb_vector::{encoding::encode_entity_vector_prefix, TABLE_COLLECTION_VECTORS};
        use std::collections::HashSet;
        use std::ops::Bound;

        if entity_ids.is_empty() {
            return Ok(0);
        }

        let start = std::time::Instant::now();

        // Begin a write transaction
        let mut tx = self.begin()?;
        self.inner.db_metrics.transactions.record_start();

        let mut deleted_count = 0;
        let mut affected_tables: HashSet<String> = HashSet::new();

        // Get all collection IDs for vector cascade deletion
        let collection_ids: Vec<_> = {
            let names =
                CollectionManager::list(&tx).map_err(|e| Error::Collection(e.to_string()))?;
            let mut ids = Vec::new();
            for name in names {
                if let Some(collection) = CollectionManager::get(&tx, &name)
                    .map_err(|e| Error::Collection(e.to_string()))?
                {
                    ids.push(collection.id());
                }
            }
            ids
        };

        for &entity_id in entity_ids {
            // Load the entity to get property values for index cleanup
            let entity = match tx.get_entity(entity_id)? {
                Some(e) => e,
                None => continue, // Entity doesn't exist, skip
            };

            // Track affected tables for cache invalidation
            for label in &entity.labels {
                affected_tables.insert(label.as_str().to_string());
            }

            // Handle edges
            if cascade_edges {
                // Cascade delete: delete all connected edges
                let outgoing = tx.get_outgoing_edges(entity_id)?;
                let incoming = tx.get_incoming_edges(entity_id)?;

                // Delete outgoing edges
                for edge in &outgoing {
                    tx.delete_edge(edge.id)?;
                }

                // Delete incoming edges (skip self-loops which appear in both lists)
                for edge in &incoming {
                    if edge.source != edge.target {
                        tx.delete_edge(edge.id)?;
                    }
                }
            } else {
                // Checked delete: error if entity has edges
                if tx.has_edges(entity_id)? {
                    return Err(Error::bulk_operation(format!(
                        "entity {} has connected edges; use bulk_delete_entities for cascade delete",
                        entity_id.as_u64()
                    )));
                }
            }

            // Cascade delete: delete all vectors for this entity from all collections
            {
                let storage = tx.storage_mut().map_err(Error::Transaction)?;
                for &collection_id in &collection_ids {
                    // Create prefix for all vectors of this entity in this collection
                    let prefix = encode_entity_vector_prefix(collection_id, entity_id);

                    // Calculate next prefix for range scan
                    let prefix_end = {
                        let mut result = prefix.clone();
                        for byte in result.iter_mut().rev() {
                            if *byte < 0xFF {
                                *byte += 1;
                                break;
                            }
                        }
                        result
                    };

                    // Collect keys to delete (can't delete while iterating)
                    let mut keys_to_delete: Vec<Vec<u8>> = Vec::new();
                    {
                        let mut cursor = storage
                            .range(
                                TABLE_COLLECTION_VECTORS,
                                Bound::Included(prefix.as_slice()),
                                Bound::Excluded(prefix_end.as_slice()),
                            )
                            .map_err(Error::Storage)?;

                        while let Some((key, _)) = cursor.next().map_err(Error::Storage)? {
                            keys_to_delete.push(key.clone());
                        }
                    }

                    // Delete collected keys
                    for key in keys_to_delete {
                        storage.delete(TABLE_COLLECTION_VECTORS, &key).map_err(Error::Storage)?;
                    }
                }
            }

            // Remove from property indexes before deleting (schema-based indexes)
            EntityIndexMaintenance::on_delete(&mut tx, &entity)
                .map_err(|e| Error::Execution(format!("property index removal failed: {e}")))?;

            // Remove from payload indexes before deleting
            self.inner
                .index_manager
                .on_entity_delete_tx(tx.storage_mut_ref().map_err(Error::Transaction)?, &entity)?;

            // Remove from HNSW/vector indexes
            crate::vector::remove_entity_from_indexes(&mut tx, &entity)
                .map_err(|e| Error::Execution(format!("vector index removal failed: {e}")))?;

            // Delete the entity itself
            if tx.delete_entity(entity_id)? {
                deleted_count += 1;
            }
        }

        // Commit the transaction
        let commit_start = std::time::Instant::now();
        tx.commit().map_err(Error::Transaction)?;
        self.inner.db_metrics.record_commit(commit_start.elapsed());

        // Invalidate cache entries for affected tables
        let table_list: Vec<String> = affected_tables.into_iter().collect();
        self.inner.query_cache.invalidate_tables(&table_list);
        if let Err(e) = self.inner.prepared_cache.invalidate_tables(&table_list) {
            // Log the error but don't fail the operation
            eprintln!("Warning: failed to invalidate prepared cache: {e}");
        }

        // Record successful operation
        self.inner.db_metrics.record_query(start.elapsed(), true);

        Ok(deleted_count)
    }

    /// Bulk delete edges by ID.
    ///
    /// All deletions happen in a single transaction with one fsync for
    /// maximum performance. Edge indexes are properly cleaned up.
    ///
    /// # Arguments
    ///
    /// * `edge_ids` - The IDs of edges to delete
    ///
    /// # Returns
    ///
    /// The number of edges that were actually deleted. This may be less
    /// than the input length if some edges didn't exist.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use manifoldb::{Database, EdgeId};
    ///
    /// let db = Database::in_memory()?;
    ///
    /// // Create some edges...
    /// let edge_ids: Vec<EdgeId> = /* ... */;
    ///
    /// // Delete them all in one transaction
    /// let deleted = db.bulk_delete_edges(&edge_ids)?;
    /// assert_eq!(deleted, edge_ids.len());
    /// ```
    pub fn bulk_delete_edges(&self, edge_ids: &[EdgeId]) -> Result<usize> {
        if edge_ids.is_empty() {
            return Ok(0);
        }

        let start = std::time::Instant::now();

        // Begin a write transaction
        let mut tx = self.begin()?;
        self.inner.db_metrics.transactions.record_start();

        let mut deleted_count = 0;

        for &edge_id in edge_ids {
            // delete_edge handles:
            // - Loading the edge to get source/target
            // - Deleting from main edges table
            // - Removing from EDGES_OUT and EDGES_IN adjacency indexes
            // - Removing from graph layer indexes (edges_by_source, edges_by_target, edge_types)
            if tx.delete_edge(edge_id)? {
                deleted_count += 1;
            }
        }

        // Commit the transaction
        let commit_start = std::time::Instant::now();
        tx.commit().map_err(Error::Transaction)?;
        self.inner.db_metrics.record_commit(commit_start.elapsed());

        // Record successful operation
        self.inner.db_metrics.record_query(start.elapsed(), true);

        Ok(deleted_count)
    }

    // ========================================================================
    // Collection API
    // ========================================================================

    /// Create a new collection with the given name.
    ///
    /// Returns a [`CollectionBuilder`] for configuring the collection's vectors
    /// and indexes. Call `.build()` to finalize the collection creation.
    ///
    /// # Arguments
    ///
    /// * `name` - The name for the collection (e.g., "documents", "products")
    ///
    /// # Errors
    ///
    /// Returns an error if the collection name is invalid.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use manifoldb::{Database, collection::DistanceMetric};
    ///
    /// let db = Database::in_memory()?;
    ///
    /// // Create a collection with a dense vector
    /// let collection = db.create_collection("documents")?
    ///     .with_dense_vector("text_embedding", 768, DistanceMetric::Cosine)
    ///     .build()?;
    ///
    /// // Create a hybrid collection with dense and sparse vectors
    /// let collection = db.create_collection("articles")?
    ///     .with_dense_vector("semantic", 384, DistanceMetric::DotProduct)
    ///     .with_sparse_vector("keywords")
    ///     .build()?;
    /// ```
    pub fn create_collection(
        &self,
        name: &str,
    ) -> Result<
        crate::collection::CollectionBuilder<
            std::sync::Arc<manifoldb_storage::backends::RedbEngine>,
        >,
    > {
        let coll_name = crate::collection::CollectionName::new(name)
            .map_err(|e| Error::Collection(e.to_string()))?;

        Ok(crate::collection::CollectionBuilder::new(self.inner.manager.engine_arc(), coll_name))
    }

    /// Get a handle to an existing collection.
    ///
    /// Returns a [`CollectionHandle`] that can be used to perform point operations
    /// and vector searches on the collection.
    ///
    /// # Arguments
    ///
    /// * `name` - The name of the collection to open
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The collection name is invalid
    /// - The collection doesn't exist
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use manifoldb::Database;
    ///
    /// let db = Database::in_memory()?;
    ///
    /// // Create a collection first
    /// db.create_collection("documents")?
    ///     .with_dense_vector("embedding", 384, DistanceMetric::Cosine)
    ///     .build()?;
    ///
    /// // Later, get a handle to the collection
    /// let collection = db.collection("documents")?;
    ///
    /// // Use the handle for operations
    /// let results = collection.search("embedding")
    ///     .query(query_vector)
    ///     .limit(10)
    ///     .execute()?;
    /// ```
    pub fn collection(
        &self,
        name: &str,
    ) -> Result<
        crate::collection::CollectionHandle<
            std::sync::Arc<manifoldb_storage::backends::RedbEngine>,
        >,
    > {
        let coll_name = crate::collection::CollectionName::new(name)
            .map_err(|e| Error::Collection(e.to_string()))?;

        crate::collection::CollectionHandle::open(self.inner.manager.engine_arc(), coll_name)
            .map_err(|e| Error::Collection(e.to_string()))
    }

    /// Drop a collection and all its data.
    ///
    /// This permanently deletes:
    /// - The collection metadata
    /// - All vectors stored in the collection
    /// - All HNSW indexes for the collection
    ///
    /// # Arguments
    ///
    /// * `name` - The name of the collection to drop
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The collection name is invalid
    /// - The collection doesn't exist
    /// - A storage error occurs
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use manifoldb::Database;
    ///
    /// let db = Database::in_memory()?;
    ///
    /// // Create and then drop a collection
    /// db.create_collection("temp")?
    ///     .with_dense_vector("v", 128, DistanceMetric::Cosine)
    ///     .build()?;
    ///
    /// db.drop_collection("temp")?;
    ///
    /// // Collection no longer exists
    /// assert!(db.collection("temp").is_err());
    /// ```
    pub fn drop_collection(&self, name: &str) -> Result<()> {
        use crate::collection::{CollectionManager, CollectionName};
        use crate::vector::drop_indexes_for_collection;
        use manifoldb_storage::Cursor;
        use manifoldb_vector::{
            encoding::encode_collection_vector_prefix, TABLE_COLLECTION_VECTORS,
        };
        use std::ops::Bound;

        let coll_name = CollectionName::new(name).map_err(|e| Error::Collection(e.to_string()))?;

        let mut tx = self.begin()?;

        // Get the collection to verify it exists and get its ID
        let collection = CollectionManager::get(&tx, &coll_name)
            .map_err(|e| Error::Collection(e.to_string()))?
            .ok_or_else(|| Error::Collection(format!("Collection '{}' not found", name)))?;

        let collection_id = collection.id();

        // Drop all HNSW indexes for this collection
        drop_indexes_for_collection(&mut tx, name).map_err(|e| Error::Vector(e.to_string()))?;

        // Delete all vectors in the collection from collection_vectors table
        {
            let prefix = encode_collection_vector_prefix(collection_id);
            let next_prefix = next_prefix(&prefix);
            let storage = tx.storage_mut().map_err(Error::Transaction)?;

            // Collect all keys to delete using range cursor
            let mut keys_to_delete: Vec<Vec<u8>> = Vec::new();
            let mut cursor = storage
                .range(
                    TABLE_COLLECTION_VECTORS,
                    Bound::Included(prefix.as_slice()),
                    Bound::Excluded(next_prefix.as_slice()),
                )
                .map_err(Error::Storage)?;

            while let Some((key, _)) = cursor.next()? {
                keys_to_delete.push(key.clone());
            }
            drop(cursor);

            // Delete each key
            for key in &keys_to_delete {
                storage.delete(TABLE_COLLECTION_VECTORS, key).map_err(Error::Storage)?;
            }
        }

        // Delete the collection metadata (if_exists = false to error if not found)
        CollectionManager::delete(&mut tx, &coll_name, false)
            .map_err(|e| Error::Collection(e.to_string()))?;

        tx.commit().map_err(Error::Transaction)?;

        Ok(())
    }

    /// List all collections in the database.
    ///
    /// Returns a vector of collection names.
    ///
    /// # Errors
    ///
    /// Returns an error if a storage error occurs.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use manifoldb::Database;
    ///
    /// let db = Database::in_memory()?;
    ///
    /// db.create_collection("users")?
    ///     .with_dense_vector("embedding", 128, DistanceMetric::Cosine)
    ///     .build()?;
    ///
    /// db.create_collection("products")?
    ///     .with_dense_vector("embedding", 256, DistanceMetric::Cosine)
    ///     .build()?;
    ///
    /// let collections = db.list_collections()?;
    /// assert!(collections.contains(&"users".to_string()));
    /// assert!(collections.contains(&"products".to_string()));
    /// ```
    pub fn list_collections(&self) -> Result<Vec<String>> {
        use crate::collection::CollectionManager;

        let tx = self.begin_read()?;
        let collections =
            CollectionManager::list(&tx).map_err(|e| Error::Collection(e.to_string()))?;

        Ok(collections.into_iter().map(|c| c.as_str().to_string()).collect())
    }

    // ========================================================================
    // Unified Entity API
    // ========================================================================

    /// Create a search builder for vector similarity search.
    ///
    /// This is the unified search API that returns [`ScoredEntity`] results
    /// instead of collection-specific point types.
    ///
    /// # Arguments
    ///
    /// * `collection` - The name of the collection to search
    /// * `vector_name` - The name of the vector field to search
    ///
    /// # Returns
    ///
    /// A [`EntitySearchBuilder`] that can be configured with query vector,
    /// filters, and limits before executing the search.
    ///
    /// # Errors
    ///
    /// Returns an error if the collection doesn't exist.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use manifoldb::{Database, Filter, ScoredEntity};
    ///
    /// let db = Database::in_memory()?;
    ///
    /// // Create collection and insert data...
    ///
    /// // Search for similar entities
    /// let results: Vec<ScoredEntity> = db.search("documents", "embedding")
    ///     .query(query_vector)
    ///     .filter(Filter::eq("language", "rust"))
    ///     .limit(10)
    ///     .execute()?;
    ///
    /// for result in results {
    ///     println!("Entity {}: score {:.4}", result.entity.id.as_u64(), result.score);
    /// }
    /// ```
    pub fn search(
        &self,
        collection: &str,
        vector_name: &str,
    ) -> Result<crate::search::EntitySearchBuilder> {
        let handle = self.collection(collection)?;
        let engine = self.inner.manager.engine_arc();
        Ok(crate::search::EntitySearchBuilder::new(handle, engine, vector_name))
    }

    /// Upsert an entity into a collection.
    ///
    /// This is the unified upsert API that handles entities with optional vectors.
    /// The entity's properties are stored as payload, and any vectors attached
    /// to the entity are stored in the appropriate vector indexes.
    ///
    /// # Arguments
    ///
    /// * `collection` - The name of the collection to upsert into
    /// * `entity` - The entity to upsert (may include vectors via `with_vector()`)
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The collection doesn't exist
    /// - Vector dimensions don't match the collection schema
    /// - A storage error occurs
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use manifoldb::{Database, Entity, EntityId, VectorData, DistanceMetric};
    ///
    /// let db = Database::in_memory()?;
    ///
    /// // Create collection with vector configuration
    /// db.create_collection("documents")?
    ///     .with_dense_vector("embedding", 768, DistanceMetric::Cosine)
    ///     .build()?;
    ///
    /// // Create entity with vector
    /// let entity = Entity::new(EntityId::new(1))
    ///     .with_label("Document")
    ///     .with_property("title", "Hello World")
    ///     .with_property("language", "rust")
    ///     .with_vector("embedding", vec![0.1f32; 768]);
    ///
    /// // Upsert entity (stores both properties and vectors)
    /// db.upsert("documents", &entity)?;
    /// ```
    pub fn upsert(&self, collection: &str, entity: &Entity) -> Result<()> {
        use crate::search::entity_to_point_struct;

        let handle = self.collection(collection)?;
        let point = entity_to_point_struct(entity, collection);

        handle.upsert_point(point).map_err(|e| Error::Collection(e.to_string()))
    }

    /// Upsert multiple entities into a collection.
    ///
    /// More efficient than calling `upsert` multiple times.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use manifoldb::{Database, Entity, EntityId};
    ///
    /// let db = Database::in_memory()?;
    ///
    /// let entities: Vec<Entity> = (0..100)
    ///     .map(|i| {
    ///         Entity::new(EntityId::new(i))
    ///             .with_label("Document")
    ///             .with_property("index", i as i64)
    ///             .with_vector("embedding", vec![0.1f32; 768])
    ///     })
    ///     .collect();
    ///
    /// db.upsert_batch("documents", &entities)?;
    /// ```
    pub fn upsert_batch(&self, collection: &str, entities: &[Entity]) -> Result<()> {
        use crate::search::entity_to_point_struct;

        let handle = self.collection(collection)?;

        for entity in entities {
            let point = entity_to_point_struct(entity, collection);
            handle.upsert_point(point).map_err(|e| Error::Collection(e.to_string()))?;
        }

        Ok(())
    }
}

// Note: Database automatically implements Send + Sync through its fields
// TransactionManager<RedbEngine> is Send + Sync, Config is Clone
// No unsafe impls needed - Rust derives these automatically

/// The result of a query execution.
///
/// `QueryResult` contains the rows returned by a SELECT query, along with
/// metadata about the result set.
///
/// # Examples
///
/// Iterate over results:
///
/// ```ignore
/// let results = db.query("SELECT * FROM users")?;
/// for row in &results {
///     let name: &str = row.get("name")?;
///     println!("User: {}", name);
/// }
/// ```
///
/// Access by index:
///
/// ```ignore
/// if let Some(row) = results.get(0) {
///     let name: &str = row.get(0)?;
/// }
/// ```
#[derive(Debug, Clone)]
pub struct QueryResult {
    /// The column names.
    columns: Vec<String>,
    /// The result rows.
    rows: Vec<QueryRow>,
}

impl QueryResult {
    /// Create an empty query result.
    #[must_use]
    pub fn empty() -> Self {
        Self { columns: Vec::new(), rows: Vec::new() }
    }

    /// Create a query result with the given columns and rows.
    #[must_use]
    pub fn new(columns: Vec<String>, rows: Vec<QueryRow>) -> Self {
        Self { columns, rows }
    }

    /// Create a query result from the query engine's result set.
    #[must_use]
    pub fn from_result_set(result_set: manifoldb_query::ResultSet) -> Self {
        let columns = result_set.columns().into_iter().map(|s| s.to_owned()).collect();
        let rows =
            result_set.into_iter().map(|row| QueryRow { values: row.values().to_vec() }).collect();
        Self { columns, rows }
    }

    /// Returns the column names.
    #[must_use]
    pub fn columns(&self) -> &[String] {
        &self.columns
    }

    /// Returns the number of columns.
    #[must_use]
    pub fn num_columns(&self) -> usize {
        self.columns.len()
    }

    /// Returns the rows.
    #[must_use]
    pub fn rows(&self) -> &[QueryRow] {
        &self.rows
    }

    /// Returns the number of rows.
    #[must_use]
    pub fn len(&self) -> usize {
        self.rows.len()
    }

    /// Returns `true` if there are no rows.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.rows.is_empty()
    }

    /// Get a row by index.
    #[must_use]
    pub fn get(&self, index: usize) -> Option<&QueryRow> {
        self.rows.get(index)
    }

    /// Get the first row.
    #[must_use]
    pub fn first(&self) -> Option<&QueryRow> {
        self.rows.first()
    }

    /// Returns an iterator over the rows.
    pub fn iter(&self) -> impl Iterator<Item = &QueryRow> {
        self.rows.iter()
    }

    /// Get the column index for a column name.
    #[must_use]
    pub fn column_index(&self, name: &str) -> Option<usize> {
        self.columns.iter().position(|c| c == name)
    }
}

impl IntoIterator for QueryResult {
    type Item = QueryRow;
    type IntoIter = std::vec::IntoIter<QueryRow>;

    fn into_iter(self) -> Self::IntoIter {
        self.rows.into_iter()
    }
}

impl<'a> IntoIterator for &'a QueryResult {
    type Item = &'a QueryRow;
    type IntoIter = std::slice::Iter<'a, QueryRow>;

    fn into_iter(self) -> Self::IntoIter {
        self.rows.iter()
    }
}

/// A single row in a query result.
///
/// `QueryRow` provides access to the column values in a result row.
///
/// # Examples
///
/// Access values by column index:
///
/// ```ignore
/// let value = row.get(0)?;
/// ```
///
/// Get the raw values:
///
/// ```ignore
/// for value in row.values() {
///     println!("{:?}", value);
/// }
/// ```
#[derive(Debug, Clone)]
pub struct QueryRow {
    values: Vec<manifoldb_core::Value>,
}

impl QueryRow {
    /// Create a new row with the given values.
    #[must_use]
    pub fn new(values: Vec<manifoldb_core::Value>) -> Self {
        Self { values }
    }

    /// Get a value by column index.
    #[must_use]
    pub fn get(&self, index: usize) -> Option<&manifoldb_core::Value> {
        self.values.get(index)
    }

    /// Returns all values in the row.
    #[must_use]
    pub fn values(&self) -> &[manifoldb_core::Value] {
        &self.values
    }

    /// Returns the number of values in the row.
    #[must_use]
    pub fn len(&self) -> usize {
        self.values.len()
    }

    /// Returns `true` if the row has no values.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.values.is_empty()
    }

    /// Try to get a value as a specific type.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// let name: String = row.get_as(0)?;
    /// let age: i64 = row.get_as(1)?;
    /// ```
    pub fn get_as<T: FromValue>(&self, index: usize) -> Result<T> {
        self.values
            .get(index)
            .ok_or_else(|| Error::InvalidParameter(format!("column index {} out of bounds", index)))
            .and_then(T::from_value)
    }
}

/// Trait for converting from a database Value to a Rust type.
pub trait FromValue: Sized {
    /// Convert from a database Value.
    ///
    /// # Errors
    ///
    /// Returns an error if the value cannot be converted to this type.
    fn from_value(value: &manifoldb_core::Value) -> Result<Self>;
}

impl FromValue for String {
    fn from_value(value: &manifoldb_core::Value) -> Result<Self> {
        match value {
            manifoldb_core::Value::String(s) => Ok(s.clone()),
            _ => Err(Error::Type(format!("expected string, got {:?}", value))),
        }
    }
}

impl FromValue for i64 {
    fn from_value(value: &manifoldb_core::Value) -> Result<Self> {
        match value {
            manifoldb_core::Value::Int(n) => Ok(*n),
            _ => Err(Error::Type(format!("expected integer, got {:?}", value))),
        }
    }
}

impl FromValue for f64 {
    fn from_value(value: &manifoldb_core::Value) -> Result<Self> {
        match value {
            manifoldb_core::Value::Float(f) => Ok(*f),
            manifoldb_core::Value::Int(n) => Ok(*n as f64),
            _ => Err(Error::Type(format!("expected float, got {:?}", value))),
        }
    }
}

impl FromValue for bool {
    fn from_value(value: &manifoldb_core::Value) -> Result<Self> {
        match value {
            manifoldb_core::Value::Bool(b) => Ok(*b),
            _ => Err(Error::Type(format!("expected boolean, got {:?}", value))),
        }
    }
}

impl FromValue for Vec<f32> {
    fn from_value(value: &manifoldb_core::Value) -> Result<Self> {
        match value {
            manifoldb_core::Value::Vector(v) => Ok(v.clone()),
            _ => Err(Error::Type(format!("expected vector, got {:?}", value))),
        }
    }
}

impl<T: FromValue> FromValue for Option<T> {
    fn from_value(value: &manifoldb_core::Value) -> Result<Self> {
        match value {
            manifoldb_core::Value::Null => Ok(None),
            _ => T::from_value(value).map(Some),
        }
    }
}

impl FromValue for manifoldb_core::Value {
    fn from_value(value: &manifoldb_core::Value) -> Result<Self> {
        Ok(value.clone())
    }
}

/// Query parameters for parameterized queries.
///
/// This struct holds parameter values that can be bound to a query.
/// Parameters are referenced by position (`$1`, `$2`, etc.) in the SQL string.
///
/// # Examples
///
/// ```ignore
/// use manifoldb::{Database, QueryParams};
///
/// let db = Database::in_memory()?;
///
/// let mut params = QueryParams::new();
/// params.add("Alice");
/// params.add(30i64);
///
/// let results = db.query_with_params(
///     "SELECT * FROM users WHERE name = $1 AND age > $2",
///     params.values(),
/// )?;
/// ```
#[derive(Debug, Clone, Default)]
pub struct QueryParams {
    values: Vec<manifoldb_core::Value>,
}

impl QueryParams {
    /// Create a new empty parameter set.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Add a parameter value.
    pub fn add(&mut self, value: impl Into<manifoldb_core::Value>) -> &mut Self {
        self.values.push(value.into());
        self
    }

    /// Add a parameter value (builder pattern).
    #[must_use]
    pub fn with(mut self, value: impl Into<manifoldb_core::Value>) -> Self {
        self.values.push(value.into());
        self
    }

    /// Returns the parameter values.
    #[must_use]
    pub fn values(&self) -> &[manifoldb_core::Value] {
        &self.values
    }

    /// Returns the number of parameters.
    #[must_use]
    pub fn len(&self) -> usize {
        self.values.len()
    }

    /// Returns `true` if there are no parameters.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.values.is_empty()
    }

    /// Clear all parameters.
    pub fn clear(&mut self) {
        self.values.clear();
    }
}

/// Create query parameters from an array.
///
/// # Examples
///
/// ```ignore
/// use manifoldb::{params, Database};
///
/// let db = Database::in_memory()?;
///
/// let results = db.query_with_params(
///     "SELECT * FROM users WHERE name = $1",
///     &params!["Alice"],
/// )?;
/// ```
#[macro_export]
macro_rules! params {
    () => {
        []
    };
    ($($value:expr),+ $(,)?) => {
        [$($crate::Value::from($value)),+]
    };
}

/// Calculate the next prefix for range scanning.
///
/// Given a prefix byte slice, returns a new slice that serves as an exclusive upper bound
/// for a range scan. This is used to efficiently iterate over all keys with a given prefix.
fn next_prefix(prefix: &[u8]) -> Vec<u8> {
    let mut result = prefix.to_vec();
    for byte in result.iter_mut().rev() {
        if *byte < 0xFF {
            *byte += 1;
            return result;
        }
    }
    // All bytes are 0xFF, append another 0xFF
    result.push(0xFF);
    result
}

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

    #[test]
    fn test_database_in_memory() {
        let db = Database::in_memory().expect("failed to create in-memory db");
        assert!(db.config().in_memory);
    }

    #[test]
    fn test_database_begin_transaction() {
        let db = Database::in_memory().expect("failed to create in-memory db");

        let tx = db.begin().expect("failed to begin transaction");
        assert!(!tx.is_read_only());
        tx.rollback().expect("failed to rollback");
    }

    #[test]
    fn test_database_begin_read_transaction() {
        let db = Database::in_memory().expect("failed to create in-memory db");

        let tx = db.begin_read().expect("failed to begin read transaction");
        assert!(tx.is_read_only());
        tx.rollback().expect("failed to rollback");
    }

    #[test]
    fn test_query_result_empty() {
        let result = QueryResult::empty();
        assert!(result.is_empty());
        assert_eq!(result.len(), 0);
        assert_eq!(result.num_columns(), 0);
    }

    #[test]
    fn test_query_result_with_data() {
        let columns = vec!["id".to_string(), "name".to_string()];
        let rows = vec![
            QueryRow::new(vec![
                manifoldb_core::Value::Int(1),
                manifoldb_core::Value::String("Alice".to_string()),
            ]),
            QueryRow::new(vec![
                manifoldb_core::Value::Int(2),
                manifoldb_core::Value::String("Bob".to_string()),
            ]),
        ];

        let result = QueryResult::new(columns, rows);

        assert_eq!(result.len(), 2);
        assert_eq!(result.num_columns(), 2);
        assert_eq!(result.columns(), &["id", "name"]);
        assert_eq!(result.column_index("name"), Some(1));
    }

    #[test]
    fn test_query_row_get_as() {
        let row = QueryRow::new(vec![
            manifoldb_core::Value::Int(42),
            manifoldb_core::Value::String("test".to_string()),
            manifoldb_core::Value::Bool(true),
            manifoldb_core::Value::Float(2.5),
        ]);

        assert_eq!(row.get_as::<i64>(0).unwrap(), 42);
        assert_eq!(row.get_as::<String>(1).unwrap(), "test");
        assert_eq!(row.get_as::<bool>(2).unwrap(), true);
        assert!((row.get_as::<f64>(3).unwrap() - 2.5).abs() < f64::EPSILON);
    }

    #[test]
    fn test_query_row_get_as_error() {
        let row = QueryRow::new(vec![manifoldb_core::Value::Int(42)]);

        assert!(row.get_as::<String>(0).is_err());
        assert!(row.get_as::<i64>(999).is_err());
    }

    #[test]
    fn test_query_params() {
        let params = QueryParams::new().with("Alice").with(30i64).with(true);

        assert_eq!(params.len(), 3);
        assert_eq!(params.values()[0], manifoldb_core::Value::String("Alice".to_string()));
        assert_eq!(params.values()[1], manifoldb_core::Value::Int(30));
        assert_eq!(params.values()[2], manifoldb_core::Value::Bool(true));
    }

    #[test]
    fn test_query_result_iterator() {
        let columns = vec!["n".to_string()];
        let rows = vec![
            QueryRow::new(vec![manifoldb_core::Value::Int(1)]),
            QueryRow::new(vec![manifoldb_core::Value::Int(2)]),
            QueryRow::new(vec![manifoldb_core::Value::Int(3)]),
        ];

        let result = QueryResult::new(columns, rows);

        let sum: i64 = result.iter().filter_map(|r| r.get_as::<i64>(0).ok()).sum();
        assert_eq!(sum, 6);
    }

    #[test]
    fn test_entity_crud_via_database() {
        let db = Database::in_memory().expect("failed to create in-memory db");

        // Create and store an entity
        let mut tx = db.begin().expect("failed to begin write");
        let entity = tx
            .create_entity()
            .expect("failed to create entity")
            .with_label("Person")
            .with_property("name", "Alice");
        let entity_id = entity.id;
        tx.put_entity(&entity).expect("failed to put entity");
        tx.commit().expect("failed to commit");

        // Read it back
        let tx = db.begin_read().expect("failed to begin read");
        let retrieved =
            tx.get_entity(entity_id).expect("failed to get entity").expect("entity not found");
        assert_eq!(retrieved.id, entity_id);
        assert!(retrieved.has_label("Person"));
    }

    #[test]
    fn test_parse_and_execute_query() {
        let db = Database::in_memory().expect("failed to create in-memory db");

        // Just verify parsing works
        let result = db.query("SELECT * FROM users WHERE id = 1");
        assert!(result.is_ok());
    }

    #[test]
    fn test_parse_invalid_query() {
        let db = Database::in_memory().expect("failed to create in-memory db");

        let result = db.query("INVALID SQL SYNTAX !!!");
        assert!(result.is_err());
    }

    #[test]
    fn test_query_cache_hit() {
        let db = Database::in_memory().expect("failed to create in-memory db");

        // First query - cache miss
        let _result1 = db.query("SELECT * FROM users").expect("query failed");

        // Check metrics
        let metrics = db.cache_metrics();
        assert_eq!(metrics.misses(), 1);
        assert_eq!(metrics.hits(), 0);

        // Second query - cache hit
        let _result2 = db.query("SELECT * FROM users").expect("query failed");

        assert_eq!(metrics.misses(), 1);
        assert_eq!(metrics.hits(), 1);
    }

    #[test]
    fn test_query_cache_invalidation_on_insert() {
        let db = Database::in_memory().expect("failed to create in-memory db");

        // Execute initial query
        let _result1 = db.query("SELECT * FROM users").expect("query failed");
        assert_eq!(db.cache_metrics().misses(), 1);

        // Second query - cache hit
        let _result2 = db.query("SELECT * FROM users").expect("query failed");
        assert_eq!(db.cache_metrics().hits(), 1);

        // Insert invalidates the cache
        db.execute("INSERT INTO users (name) VALUES ('Alice')").expect("insert failed");

        // Query again - should be a miss since cache was invalidated
        let _result3 = db.query("SELECT * FROM users").expect("query failed");
        assert_eq!(db.cache_metrics().misses(), 2);
    }

    #[test]
    fn test_query_cache_no_cache_hint() {
        let db = Database::in_memory().expect("failed to create in-memory db");

        // Query with NO_CACHE hint - should not cache
        let _result1 = db.query("/*+ NO_CACHE */ SELECT * FROM users").expect("query failed");

        // Metrics should show no cache activity (hint bypasses cache)
        // Since NO_CACHE skips caching entirely, we won't see a miss recorded

        // Regular query - cache miss
        let _result2 = db.query("SELECT * FROM users").expect("query failed");
        assert_eq!(db.cache_metrics().misses(), 1);

        // Same query again - cache hit
        let _result3 = db.query("SELECT * FROM users").expect("query failed");
        assert_eq!(db.cache_metrics().hits(), 1);
    }

    #[test]
    fn test_query_cache_with_params() {
        let db = Database::in_memory().expect("failed to create in-memory db");

        let params1 = &[manifoldb_core::Value::Int(1)];
        let params2 = &[manifoldb_core::Value::Int(2)];

        // Query with param 1
        let _result1 = db
            .query_with_params("SELECT * FROM users WHERE id = $1", params1)
            .expect("query failed");
        assert_eq!(db.cache_metrics().misses(), 1);

        // Same query, same params - cache hit
        let _result2 = db
            .query_with_params("SELECT * FROM users WHERE id = $1", params1)
            .expect("query failed");
        assert_eq!(db.cache_metrics().hits(), 1);

        // Same query, different params - cache miss
        let _result3 = db
            .query_with_params("SELECT * FROM users WHERE id = $1", params2)
            .expect("query failed");
        assert_eq!(db.cache_metrics().misses(), 2);
    }

    #[test]
    fn test_query_cache_clear() {
        let db = Database::in_memory().expect("failed to create in-memory db");

        // Populate cache
        let _result1 = db.query("SELECT * FROM users").expect("query failed");
        let _result2 = db.query("SELECT * FROM orders").expect("query failed");

        assert_eq!(db.query_cache().len(), 2);

        // Clear cache
        db.clear_cache();

        assert!(db.query_cache().is_empty());

        // Queries should miss again
        let _result3 = db.query("SELECT * FROM users").expect("query failed");
        assert_eq!(db.cache_metrics().misses(), 3);
    }

    #[test]
    fn test_query_cache_disabled() {
        use crate::cache::CacheConfig;

        let db = DatabaseBuilder::in_memory()
            .query_cache_config(CacheConfig::disabled())
            .open()
            .expect("failed to create db");

        // Queries should not be cached
        let _result1 = db.query("SELECT * FROM users").expect("query failed");
        let _result2 = db.query("SELECT * FROM users").expect("query failed");

        // No hits or misses should be recorded for disabled cache
        assert_eq!(db.cache_metrics().hits(), 0);
        // Misses are not recorded for disabled cache
    }

    #[test]
    fn test_query_cache_metrics() {
        let db = Database::in_memory().expect("failed to create in-memory db");

        // Generate some cache activity
        let _result1 = db.query("SELECT * FROM users").expect("query failed");
        let _result2 = db.query("SELECT * FROM users").expect("query failed");
        let _result3 = db.query("SELECT * FROM orders").expect("query failed");
        let _result4 = db.query("SELECT * FROM users").expect("query failed");

        let metrics = db.cache_metrics();

        assert_eq!(metrics.total_lookups(), 4);
        assert_eq!(metrics.hits(), 2); // users hit twice (after first miss)
        assert_eq!(metrics.misses(), 2); // users first + orders first

        let hit_rate = metrics.hit_rate().expect("should have hit rate");
        assert!((hit_rate - 50.0).abs() < 0.1); // 50% hit rate
    }

    // ========================================================================
    // Bulk Insert Tests
    // ========================================================================

    #[test]
    fn test_bulk_insert_empty() {
        let db = Database::in_memory().expect("failed to create in-memory db");

        let entities: Vec<Entity> = Vec::new();
        let ids = db.bulk_insert_entities(&entities).expect("bulk insert failed");

        assert!(ids.is_empty());
    }

    #[test]
    fn test_bulk_insert_single_entity() {
        let db = Database::in_memory().expect("failed to create in-memory db");

        let entities =
            vec![Entity::new(EntityId::new(0)).with_label("Person").with_property("name", "Alice")];

        let ids = db.bulk_insert_entities(&entities).expect("bulk insert failed");

        assert_eq!(ids.len(), 1);

        // Verify entity was persisted correctly
        let tx = db.begin_read().expect("failed to begin read");
        let retrieved = tx.get_entity(ids[0]).expect("get failed").expect("entity not found");
        assert!(retrieved.has_label("Person"));
        assert_eq!(
            retrieved.get_property("name"),
            Some(&manifoldb_core::Value::String("Alice".to_string()))
        );
    }

    #[test]
    fn test_bulk_insert_multiple_entities() {
        let db = Database::in_memory().expect("failed to create in-memory db");

        let entities: Vec<Entity> = (0..100)
            .map(|i| {
                Entity::new(EntityId::new(0))
                    .with_label("Document")
                    .with_property("index", i as i64)
            })
            .collect();

        let ids = db.bulk_insert_entities(&entities).expect("bulk insert failed");

        assert_eq!(ids.len(), 100);

        // Verify IDs are sequential
        for (i, id) in ids.iter().enumerate() {
            assert_eq!(id.as_u64(), (i + 1) as u64);
        }

        // Verify all entities were persisted correctly
        let tx = db.begin_read().expect("failed to begin read");
        for (i, id) in ids.iter().enumerate() {
            let entity = tx.get_entity(*id).expect("get failed").expect("entity not found");
            assert!(entity.has_label("Document"));
            assert_eq!(entity.get_property("index"), Some(&manifoldb_core::Value::Int(i as i64)));
        }
    }

    #[test]
    fn test_bulk_insert_preserves_existing_id_sequence() {
        let db = Database::in_memory().expect("failed to create in-memory db");

        // Create some entities first using regular inserts
        {
            let mut tx = db.begin().expect("failed to begin");
            for _ in 0..5 {
                let entity = tx.create_entity().expect("failed to create");
                tx.put_entity(&entity).expect("failed to put");
            }
            tx.commit().expect("failed to commit");
        }

        // Now do a bulk insert
        let entities: Vec<Entity> = (0..10)
            .map(|i| Entity::new(EntityId::new(0)).with_property("bulk_index", i as i64))
            .collect();

        let ids = db.bulk_insert_entities(&entities).expect("bulk insert failed");

        // IDs should start from 6 (after the 5 we created)
        assert_eq!(ids[0].as_u64(), 6);
        assert_eq!(ids[9].as_u64(), 15);
    }

    #[test]
    fn test_bulk_insert_with_multiple_labels() {
        let db = Database::in_memory().expect("failed to create in-memory db");

        let entities = vec![Entity::new(EntityId::new(0))
            .with_label("Person")
            .with_label("Employee")
            .with_label("Manager")
            .with_property("name", "Alice")];

        let ids = db.bulk_insert_entities(&entities).expect("bulk insert failed");

        let tx = db.begin_read().expect("failed to begin read");
        let retrieved = tx.get_entity(ids[0]).expect("get failed").expect("entity not found");

        assert!(retrieved.has_label("Person"));
        assert!(retrieved.has_label("Employee"));
        assert!(retrieved.has_label("Manager"));
    }

    #[test]
    fn test_bulk_insert_large_batch() {
        let db = Database::in_memory().expect("failed to create in-memory db");

        // Insert 10,000 entities to test performance characteristics
        let entities: Vec<Entity> = (0..10_000)
            .map(|i| {
                Entity::new(EntityId::new(0))
                    .with_label("Item")
                    .with_property("id", i as i64)
                    .with_property("data", format!("item_{}", i))
            })
            .collect();

        let ids = db.bulk_insert_entities(&entities).expect("bulk insert failed");

        assert_eq!(ids.len(), 10_000);

        // Spot check some entities
        let tx = db.begin_read().expect("failed to begin read");
        for check_idx in [0, 100, 5000, 9999] {
            let entity =
                tx.get_entity(ids[check_idx]).expect("get failed").expect("entity not found");
            assert!(entity.has_label("Item"));
            assert_eq!(
                entity.get_property("id"),
                Some(&manifoldb_core::Value::Int(check_idx as i64))
            );
        }
    }

    #[test]
    fn test_bulk_insert_returns_correct_order() {
        let db = Database::in_memory().expect("failed to create in-memory db");

        // Create entities with unique identifiable properties
        let entities: Vec<Entity> = (0..50)
            .map(|i| Entity::new(EntityId::new(0)).with_property("unique_marker", i * 1000 + 42))
            .collect();

        let ids = db.bulk_insert_entities(&entities).expect("bulk insert failed");

        // Verify each ID corresponds to the correct entity by checking the marker
        let tx = db.begin_read().expect("failed to begin read");
        for (i, id) in ids.iter().enumerate() {
            let entity = tx.get_entity(*id).expect("get failed").expect("entity not found");
            let expected_marker = i as i64 * 1000 + 42;
            assert_eq!(
                entity.get_property("unique_marker"),
                Some(&manifoldb_core::Value::Int(expected_marker)),
                "Entity at position {} has wrong marker",
                i
            );
        }
    }

    // ========================================================================
    // Bulk Upsert Tests
    // ========================================================================

    #[test]
    fn test_bulk_upsert_empty() {
        let db = Database::in_memory().expect("failed to create in-memory db");

        let entities: Vec<Entity> = Vec::new();
        let (inserted, updated) = db.bulk_upsert_entities(&entities).expect("bulk upsert failed");

        assert_eq!(inserted, 0);
        assert_eq!(updated, 0);
    }

    #[test]
    fn test_bulk_upsert_all_inserts() {
        let db = Database::in_memory().expect("failed to create in-memory db");

        // All entities have ID 0, so they're all inserts
        let entities: Vec<Entity> = (0..10)
            .map(|i| {
                Entity::new(EntityId::new(0))
                    .with_label("Document")
                    .with_property("index", i as i64)
            })
            .collect();

        let (inserted, updated) = db.bulk_upsert_entities(&entities).expect("bulk upsert failed");

        assert_eq!(inserted, 10);
        assert_eq!(updated, 0);

        // Verify entities were persisted
        let tx = db.begin_read().expect("failed to begin read");
        for i in 1..=10 {
            let entity =
                tx.get_entity(EntityId::new(i)).expect("get failed").expect("entity not found");
            assert!(entity.has_label("Document"));
            assert_eq!(
                entity.get_property("index"),
                Some(&manifoldb_core::Value::Int((i - 1) as i64))
            );
        }
    }

    #[test]
    fn test_bulk_upsert_all_updates() {
        let db = Database::in_memory().expect("failed to create in-memory db");

        // First, insert some entities
        let initial_entities: Vec<Entity> = (0..10)
            .map(|i| {
                Entity::new(EntityId::new(0))
                    .with_label("Document")
                    .with_property("version", 1i64)
                    .with_property("index", i as i64)
            })
            .collect();

        let ids = db.bulk_insert_entities(&initial_entities).expect("bulk insert failed");

        // Now upsert all of them with updated version
        let update_entities: Vec<Entity> = ids
            .iter()
            .enumerate()
            .map(|(i, id)| {
                Entity::new(*id)
                    .with_label("Document")
                    .with_property("version", 2i64)
                    .with_property("index", i as i64)
            })
            .collect();

        let (inserted, updated) =
            db.bulk_upsert_entities(&update_entities).expect("bulk upsert failed");

        assert_eq!(inserted, 0);
        assert_eq!(updated, 10);

        // Verify entities were updated
        let tx = db.begin_read().expect("failed to begin read");
        for id in &ids {
            let entity = tx.get_entity(*id).expect("get failed").expect("entity not found");
            assert_eq!(entity.get_property("version"), Some(&manifoldb_core::Value::Int(2)));
        }
    }

    #[test]
    fn test_bulk_upsert_mixed_insert_and_update() {
        let db = Database::in_memory().expect("failed to create in-memory db");

        // First, insert some entities
        let initial_entities: Vec<Entity> = (0..50)
            .map(|i| {
                Entity::new(EntityId::new(0))
                    .with_label("Document")
                    .with_property("version", 1i64)
                    .with_property("original_index", i as i64)
            })
            .collect();

        let ids = db.bulk_insert_entities(&initial_entities).expect("bulk insert failed");

        // Now upsert: update first 30, insert 20 new
        let mut upsert_entities: Vec<Entity> = Vec::new();

        // Update first 30 entities
        for (i, id) in ids.iter().take(30).enumerate() {
            upsert_entities.push(
                Entity::new(*id)
                    .with_label("Document")
                    .with_property("version", 2i64)
                    .with_property("original_index", i as i64),
            );
        }

        // Add 20 new entities (ID 0 = insert)
        for i in 0..20 {
            upsert_entities.push(
                Entity::new(EntityId::new(0))
                    .with_label("Document")
                    .with_property("version", 1i64)
                    .with_property("new_index", i as i64),
            );
        }

        let (inserted, updated) =
            db.bulk_upsert_entities(&upsert_entities).expect("bulk upsert failed");

        assert_eq!(inserted, 20);
        assert_eq!(updated, 30);

        // Verify updates
        let tx = db.begin_read().expect("failed to begin read");
        for id in ids.iter().take(30) {
            let entity = tx.get_entity(*id).expect("get failed").expect("entity not found");
            assert_eq!(entity.get_property("version"), Some(&manifoldb_core::Value::Int(2)));
        }

        // Verify inserts (new entities start after the last ID)
        let expected_start_id = ids.len() as u64 + 1;
        for i in 0..20u64 {
            let entity = tx
                .get_entity(EntityId::new(expected_start_id + i))
                .expect("get failed")
                .expect("entity not found");
            assert_eq!(entity.get_property("version"), Some(&manifoldb_core::Value::Int(1)));
            assert_eq!(
                entity.get_property("new_index"),
                Some(&manifoldb_core::Value::Int(i as i64))
            );
        }
    }

    #[test]
    fn test_bulk_upsert_preserves_labels_on_update() {
        let db = Database::in_memory().expect("failed to create in-memory db");

        // Insert entity with multiple labels
        let entities = vec![Entity::new(EntityId::new(0))
            .with_label("Person")
            .with_label("Employee")
            .with_property("name", "Alice")];

        let ids = db.bulk_insert_entities(&entities).expect("bulk insert failed");

        // Upsert with different labels
        let update_entities = vec![Entity::new(ids[0])
            .with_label("Person")
            .with_label("Manager")  // Changed from Employee to Manager
            .with_property("name", "Alice")
            .with_property("promoted", true)];

        let (inserted, updated) =
            db.bulk_upsert_entities(&update_entities).expect("bulk upsert failed");

        assert_eq!(inserted, 0);
        assert_eq!(updated, 1);

        // Verify labels were updated
        let tx = db.begin_read().expect("failed to begin read");
        let entity = tx.get_entity(ids[0]).expect("get failed").expect("entity not found");
        assert!(entity.has_label("Person"));
        assert!(entity.has_label("Manager"));
        assert!(!entity.has_label("Employee")); // Should be removed
        assert_eq!(entity.get_property("promoted"), Some(&manifoldb_core::Value::Bool(true)));
    }

    #[test]
    fn test_bulk_upsert_nonexistent_id_becomes_insert() {
        let db = Database::in_memory().expect("failed to create in-memory db");

        // Entity with a non-zero ID that doesn't exist in the database
        // should be treated as an insert and get a new ID
        let entities = vec![Entity::new(EntityId::new(999))
            .with_label("Ghost")
            .with_property("name", "Phantom")];

        let (inserted, updated) = db.bulk_upsert_entities(&entities).expect("bulk upsert failed");

        // Since ID 999 doesn't exist, it should be treated as an insert
        assert_eq!(inserted, 1);
        assert_eq!(updated, 0);

        // The entity should have gotten ID 1 (first available)
        let tx = db.begin_read().expect("failed to begin read");
        let entity =
            tx.get_entity(EntityId::new(1)).expect("get failed").expect("entity not found");
        assert!(entity.has_label("Ghost"));
        assert_eq!(
            entity.get_property("name"),
            Some(&manifoldb_core::Value::String("Phantom".to_string()))
        );
    }

    #[test]
    fn test_bulk_upsert_large_batch() {
        let db = Database::in_memory().expect("failed to create in-memory db");

        // Insert 5000 entities
        let initial_entities: Vec<Entity> = (0..5000)
            .map(|i| {
                Entity::new(EntityId::new(0))
                    .with_label("Item")
                    .with_property("index", i as i64)
                    .with_property("version", 1i64)
            })
            .collect();

        let ids = db.bulk_insert_entities(&initial_entities).expect("bulk insert failed");

        // Upsert: update 2500, insert 2500 new
        let mut upsert_entities: Vec<Entity> = Vec::new();

        // Update first 2500
        for (i, id) in ids.iter().take(2500).enumerate() {
            upsert_entities.push(
                Entity::new(*id)
                    .with_label("Item")
                    .with_property("index", i as i64)
                    .with_property("version", 2i64),
            );
        }

        // Insert 2500 new
        for i in 0..2500 {
            upsert_entities.push(
                Entity::new(EntityId::new(0))
                    .with_label("Item")
                    .with_property("index", (5000 + i) as i64)
                    .with_property("version", 1i64),
            );
        }

        let (inserted, updated) =
            db.bulk_upsert_entities(&upsert_entities).expect("bulk upsert failed");

        assert_eq!(inserted, 2500);
        assert_eq!(updated, 2500);

        // Spot check some entities
        let tx = db.begin_read().expect("failed to begin read");

        // Check an updated entity
        let updated_entity =
            tx.get_entity(ids[100]).expect("get failed").expect("entity not found");
        assert_eq!(updated_entity.get_property("version"), Some(&manifoldb_core::Value::Int(2)));

        // Check an unchanged entity (not in the upsert batch)
        let unchanged_entity =
            tx.get_entity(ids[4000]).expect("get failed").expect("entity not found");
        assert_eq!(unchanged_entity.get_property("version"), Some(&manifoldb_core::Value::Int(1)));
    }

    #[test]
    fn test_bulk_upsert_update_removes_property() {
        let db = Database::in_memory().expect("failed to create in-memory db");

        // Insert entity with multiple properties
        let entities = vec![Entity::new(EntityId::new(0))
            .with_label("Person")
            .with_property("name", "Alice")
            .with_property("age", 30i64)
            .with_property("email", "alice@example.com")];

        let ids = db.bulk_insert_entities(&entities).expect("bulk insert failed");

        // Upsert without the email property (should remove it)
        let update_entities = vec![Entity::new(ids[0])
            .with_label("Person")
            .with_property("name", "Alice")
            .with_property("age", 31i64)]; // Removed email, updated age

        let (inserted, updated) =
            db.bulk_upsert_entities(&update_entities).expect("bulk upsert failed");

        assert_eq!(inserted, 0);
        assert_eq!(updated, 1);

        // Verify properties
        let tx = db.begin_read().expect("failed to begin read");
        let entity = tx.get_entity(ids[0]).expect("get failed").expect("entity not found");
        assert_eq!(
            entity.get_property("name"),
            Some(&manifoldb_core::Value::String("Alice".to_string()))
        );
        assert_eq!(entity.get_property("age"), Some(&manifoldb_core::Value::Int(31)));
        assert_eq!(entity.get_property("email"), None); // Should be gone
    }

    // ========================================================================
    // Bulk Insert Edge Tests
    // ========================================================================

    #[test]
    fn test_bulk_insert_edges_empty() {
        let db = Database::in_memory().expect("failed to create in-memory db");

        let edges: Vec<Edge> = Vec::new();
        let ids = db.bulk_insert_edges(&edges).expect("bulk insert failed");

        assert!(ids.is_empty());
    }

    #[test]
    fn test_bulk_insert_edges_single() {
        let db = Database::in_memory().expect("failed to create in-memory db");

        // First create two entities
        let entities = vec![
            Entity::new(EntityId::new(0)).with_label("Person"),
            Entity::new(EntityId::new(0)).with_label("Person"),
        ];
        let entity_ids = db.bulk_insert_entities(&entities).expect("entity insert failed");

        // Create one edge between them
        let edges = vec![Edge::new(EdgeId::new(0), entity_ids[0], entity_ids[1], "FOLLOWS")
            .with_property("since", "2024-01-01")];

        let edge_ids = db.bulk_insert_edges(&edges).expect("bulk insert failed");

        assert_eq!(edge_ids.len(), 1);

        // Verify edge was persisted correctly
        let tx = db.begin_read().expect("failed to begin read");
        let retrieved = tx.get_edge(edge_ids[0]).expect("get failed").expect("edge not found");
        assert_eq!(retrieved.source, entity_ids[0]);
        assert_eq!(retrieved.target, entity_ids[1]);
        assert_eq!(retrieved.edge_type.as_str(), "FOLLOWS");
        assert_eq!(
            retrieved.get_property("since"),
            Some(&manifoldb_core::Value::String("2024-01-01".to_string()))
        );
    }

    #[test]
    fn test_bulk_insert_edges_multiple() {
        let db = Database::in_memory().expect("failed to create in-memory db");

        // Create some entities
        let entities: Vec<Entity> = (0..10)
            .map(|i| {
                Entity::new(EntityId::new(0)).with_label("Node").with_property("idx", i as i64)
            })
            .collect();
        let entity_ids = db.bulk_insert_entities(&entities).expect("entity insert failed");

        // Create edges as a chain: 0->1->2->...->9
        let edges: Vec<Edge> = entity_ids
            .windows(2)
            .enumerate()
            .map(|(i, pair)| {
                Edge::new(EdgeId::new(0), pair[0], pair[1], "NEXT").with_property("order", i as i64)
            })
            .collect();

        let edge_ids = db.bulk_insert_edges(&edges).expect("bulk insert failed");

        assert_eq!(edge_ids.len(), 9); // 9 edges for 10 nodes in a chain

        // Verify IDs are sequential
        for (i, id) in edge_ids.iter().enumerate() {
            assert_eq!(id.as_u64(), (i + 1) as u64);
        }

        // Verify all edges were persisted correctly
        let tx = db.begin_read().expect("failed to begin read");
        for (i, edge_id) in edge_ids.iter().enumerate() {
            let edge = tx.get_edge(*edge_id).expect("get failed").expect("edge not found");
            assert_eq!(edge.source, entity_ids[i]);
            assert_eq!(edge.target, entity_ids[i + 1]);
            assert_eq!(edge.edge_type.as_str(), "NEXT");
            assert_eq!(edge.get_property("order"), Some(&manifoldb_core::Value::Int(i as i64)));
        }
    }

    #[test]
    fn test_bulk_insert_edges_invalid_source() {
        let db = Database::in_memory().expect("failed to create in-memory db");

        // Create one entity
        let entities = vec![Entity::new(EntityId::new(0)).with_label("Person")];
        let entity_ids = db.bulk_insert_entities(&entities).expect("entity insert failed");

        // Try to create an edge with a non-existent source
        let edges = vec![Edge::new(
            EdgeId::new(0),
            EntityId::new(999), // Non-existent source
            entity_ids[0],
            "FOLLOWS",
        )];

        let result = db.bulk_insert_edges(&edges);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(matches!(err, Error::InvalidEntityReference(_)));
    }

    #[test]
    fn test_bulk_insert_edges_invalid_target() {
        let db = Database::in_memory().expect("failed to create in-memory db");

        // Create one entity
        let entities = vec![Entity::new(EntityId::new(0)).with_label("Person")];
        let entity_ids = db.bulk_insert_entities(&entities).expect("entity insert failed");

        // Try to create an edge with a non-existent target
        let edges = vec![Edge::new(
            EdgeId::new(0),
            entity_ids[0],
            EntityId::new(999), // Non-existent target
            "FOLLOWS",
        )];

        let result = db.bulk_insert_edges(&edges);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(matches!(err, Error::InvalidEntityReference(_)));
    }

    #[test]
    fn test_bulk_insert_edges_preserves_id_sequence() {
        let db = Database::in_memory().expect("failed to create in-memory db");

        // Create entities
        let entities: Vec<Entity> =
            (0..5).map(|_| Entity::new(EntityId::new(0)).with_label("Node")).collect();
        let entity_ids = db.bulk_insert_entities(&entities).expect("entity insert failed");

        // Create some edges individually first
        {
            let mut tx = db.begin().expect("failed to begin");
            for i in 0..3 {
                let edge = tx
                    .create_edge(entity_ids[i], entity_ids[i + 1], "LINK")
                    .expect("failed to create edge");
                tx.put_edge(&edge).expect("failed to put edge");
            }
            tx.commit().expect("failed to commit");
        }

        // Now do a bulk insert
        let edges: Vec<Edge> =
            vec![Edge::new(EdgeId::new(0), entity_ids[3], entity_ids[4], "LINK")];

        let edge_ids = db.bulk_insert_edges(&edges).expect("bulk insert failed");

        // IDs should start from 4 (after the 3 we created)
        assert_eq!(edge_ids[0].as_u64(), 4);
    }

    #[test]
    fn test_bulk_insert_edges_with_properties() {
        let db = Database::in_memory().expect("failed to create in-memory db");

        // Create entities
        let entities: Vec<Entity> =
            (0..3).map(|_| Entity::new(EntityId::new(0)).with_label("User")).collect();
        let entity_ids = db.bulk_insert_entities(&entities).expect("entity insert failed");

        // Create edges with various properties
        let edges = vec![
            Edge::new(EdgeId::new(0), entity_ids[0], entity_ids[1], "FOLLOWS")
                .with_property("weight", 0.8f64)
                .with_property("since", "2024-01-01")
                .with_property("mutual", true),
            Edge::new(EdgeId::new(0), entity_ids[1], entity_ids[2], "KNOWS")
                .with_property("strength", 5i64)
                .with_property("context", "work"),
        ];

        let edge_ids = db.bulk_insert_edges(&edges).expect("bulk insert failed");

        assert_eq!(edge_ids.len(), 2);

        // Verify properties
        let tx = db.begin_read().expect("failed to begin read");

        let edge1 = tx.get_edge(edge_ids[0]).expect("get failed").expect("edge not found");
        assert_eq!(edge1.get_property("weight"), Some(&manifoldb_core::Value::Float(0.8)));
        assert_eq!(
            edge1.get_property("since"),
            Some(&manifoldb_core::Value::String("2024-01-01".to_string()))
        );
        assert_eq!(edge1.get_property("mutual"), Some(&manifoldb_core::Value::Bool(true)));

        let edge2 = tx.get_edge(edge_ids[1]).expect("get failed").expect("edge not found");
        assert_eq!(edge2.get_property("strength"), Some(&manifoldb_core::Value::Int(5)));
        assert_eq!(
            edge2.get_property("context"),
            Some(&manifoldb_core::Value::String("work".to_string()))
        );
    }

    #[test]
    fn test_bulk_insert_edges_self_referential() {
        let db = Database::in_memory().expect("failed to create in-memory db");

        // Create an entity
        let entities = vec![Entity::new(EntityId::new(0)).with_label("Node")];
        let entity_ids = db.bulk_insert_entities(&entities).expect("entity insert failed");

        // Create a self-referential edge
        let edges = vec![Edge::new(
            EdgeId::new(0),
            entity_ids[0],
            entity_ids[0], // Self-reference
            "SELF_LINK",
        )];

        let edge_ids = db.bulk_insert_edges(&edges).expect("bulk insert failed");

        assert_eq!(edge_ids.len(), 1);

        // Verify the self-referential edge
        let tx = db.begin_read().expect("failed to begin read");
        let edge = tx.get_edge(edge_ids[0]).expect("get failed").expect("edge not found");
        assert_eq!(edge.source, entity_ids[0]);
        assert_eq!(edge.target, entity_ids[0]);
        assert_eq!(edge.edge_type.as_str(), "SELF_LINK");
    }

    #[test]
    fn test_bulk_insert_edges_large_batch() {
        let db = Database::in_memory().expect("failed to create in-memory db");

        // Create 100 entities
        let entities: Vec<Entity> = (0..100)
            .map(|i| {
                Entity::new(EntityId::new(0)).with_label("Node").with_property("idx", i as i64)
            })
            .collect();
        let entity_ids = db.bulk_insert_entities(&entities).expect("entity insert failed");

        // Create 1000 random edges
        let edges: Vec<Edge> = (0..1000)
            .map(|i| {
                let source_idx = i % 100;
                let target_idx = (i * 7 + 13) % 100;
                Edge::new(EdgeId::new(0), entity_ids[source_idx], entity_ids[target_idx], "LINK")
                    .with_property("edge_idx", i as i64)
            })
            .collect();

        let edge_ids = db.bulk_insert_edges(&edges).expect("bulk insert failed");

        assert_eq!(edge_ids.len(), 1000);

        // Spot check some edges
        let tx = db.begin_read().expect("failed to begin read");
        for check_idx in [0, 100, 500, 999] {
            let edge =
                tx.get_edge(edge_ids[check_idx]).expect("get failed").expect("edge not found");
            assert_eq!(
                edge.get_property("edge_idx"),
                Some(&manifoldb_core::Value::Int(check_idx as i64))
            );
        }
    }

    #[test]
    fn test_bulk_insert_edges_returns_correct_order() {
        let db = Database::in_memory().expect("failed to create in-memory db");

        // Create entities
        let entities: Vec<Entity> =
            (0..10).map(|_| Entity::new(EntityId::new(0)).with_label("Node")).collect();
        let entity_ids = db.bulk_insert_entities(&entities).expect("entity insert failed");

        // Create edges with unique markers
        let edges: Vec<Edge> = (0..20)
            .map(|i| {
                let source_idx = i % 10;
                let target_idx = (i + 1) % 10;
                Edge::new(EdgeId::new(0), entity_ids[source_idx], entity_ids[target_idx], "LINK")
                    .with_property("unique_marker", i as i64 * 1000 + 42)
            })
            .collect();

        let edge_ids = db.bulk_insert_edges(&edges).expect("bulk insert failed");

        // Verify each ID corresponds to the correct edge by checking the marker
        let tx = db.begin_read().expect("failed to begin read");
        for (i, id) in edge_ids.iter().enumerate() {
            let edge = tx.get_edge(*id).expect("get failed").expect("edge not found");
            let expected_marker = i as i64 * 1000 + 42;
            assert_eq!(
                edge.get_property("unique_marker"),
                Some(&manifoldb_core::Value::Int(expected_marker)),
                "Edge at position {} has wrong marker",
                i
            );
        }
    }

    #[test]
    fn test_bulk_insert_edges_multiple_types() {
        let db = Database::in_memory().expect("failed to create in-memory db");

        // Create entities
        let entities: Vec<Entity> =
            (0..4).map(|_| Entity::new(EntityId::new(0)).with_label("Node")).collect();
        let entity_ids = db.bulk_insert_entities(&entities).expect("entity insert failed");

        // Create edges with different types
        let edges = vec![
            Edge::new(EdgeId::new(0), entity_ids[0], entity_ids[1], "FOLLOWS"),
            Edge::new(EdgeId::new(0), entity_ids[1], entity_ids[2], "LIKES"),
            Edge::new(EdgeId::new(0), entity_ids[2], entity_ids[3], "KNOWS"),
            Edge::new(EdgeId::new(0), entity_ids[3], entity_ids[0], "WORKS_WITH"),
        ];

        let edge_ids = db.bulk_insert_edges(&edges).expect("bulk insert failed");

        assert_eq!(edge_ids.len(), 4);

        // Verify edge types
        let tx = db.begin_read().expect("failed to begin read");
        let edge_types = ["FOLLOWS", "LIKES", "KNOWS", "WORKS_WITH"];
        for (i, edge_id) in edge_ids.iter().enumerate() {
            let edge = tx.get_edge(*edge_id).expect("get failed").expect("edge not found");
            assert_eq!(edge.edge_type.as_str(), edge_types[i]);
        }
    }

    #[test]
    fn test_bulk_insert_edges_all_invalid_rejected() {
        let db = Database::in_memory().expect("failed to create in-memory db");

        // Create one entity
        let entities = vec![Entity::new(EntityId::new(0)).with_label("Node")];
        let entity_ids = db.bulk_insert_entities(&entities).expect("entity insert failed");

        // Try to create a batch where one edge has an invalid reference
        // The entire batch should be rejected
        let edges = vec![
            Edge::new(EdgeId::new(0), entity_ids[0], entity_ids[0], "VALID"),
            Edge::new(
                EdgeId::new(0),
                entity_ids[0],
                EntityId::new(999), // Invalid target
                "INVALID",
            ),
        ];

        let result = db.bulk_insert_edges(&edges);
        assert!(result.is_err());

        // Verify no edges were created
        let tx = db.begin_read().expect("failed to begin read");
        // Try to get edge with ID 1 (which would be the first edge if any were created)
        let edge = tx.get_edge(EdgeId::new(1)).expect("get failed");
        assert!(edge.is_none(), "No edges should have been created");
    }
}