velr 0.2.28

Velr embedded property-graph database (Rust driver, beta)
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
//! Rust bindings for the Velr runtime.
//!
//! This crate exposes a high-level API over the Velr runtime ABI (loaded via the `runtime` module),
//! wrapping raw FFI pointers in RAII types with predictable lifetimes.
//!
//! # Threading model
//!
//! Velr uses a *connection-affine* model:
//!
//! 1) [`Velr`] (the connection) is **`Send` + `!Sync`**.
//!    - ✅ You may **move** a connection to another thread.
//!      Example: spawn a worker thread and move the connection into it.
//!    - ❌ Wrapping a connection in `Arc` does not make it safe to share across threads;
//!      `Velr` is `!Sync`, so concurrent shared use is not supported.
//!
//! 2) In-flight / handle-based objects are **`!Send` + `!Sync`** (thread-affine):
//!    [`ExecTables`], [`TableResult`], [`RowIter`], [`VelrTx`], [`ExecTablesTx`],
//!    [`VelrSavepoint`], [`ExplainTrace`].
//!    - ❌ You may not move these to another thread.
//!    - ❌ You may not share these across threads.
//!
//! Practical implications:
//! - ✅ Many connections across many threads is fine (open one connection per thread).
//! - ✅ You can move a connection between threads (e.g., create in main, move into worker).
//! - ❌ You cannot run concurrent operations on the same connection across threads.
//!
//! If you need parallelism, open multiple connections and/or use a pool.
//!
//! # Results and lifetimes
//!
//! Queries can produce **zero or more result tables**:
//! - [`Velr::exec`] / [`VelrTx::exec`] stream tables via [`ExecTables`] / [`ExecTablesTx`].
//! - [`Velr::exec_one`] / [`VelrTx::exec_one`] return a single [`TableResult`].
//!
//! Rows are processed via callbacks. Individual cell values are represented by [`CellRef`], which
//! may borrow bytes from buffers owned by the underlying row cursor. For `Text`/`Json` values, the
//! borrowed bytes remain valid until the next call to [`RowIter::next`] on the same iterator (or
//! until the iterator is dropped). In typical usage this means the borrows are scoped to the row
//! callback invocation.
//!
//! # Bounded result previews
//!
//! Hosts that need projected column names plus a small sample can use [`QueryOptions`] with
//! [`Velr::exec_with_options`], [`Velr::exec_one_with_options`], or [`Velr::run_with_options`].
//! The row cap is enforced by Velr while emitting result rows; the driver does not rewrite the
//! Cypher text.
//!
//! ```
//! # use velr::{QueryOptions, Velr};
//! # fn main() -> velr::Result<()> {
//! let db = Velr::open(None)?;
//! let mut table = db.exec_one_with_options(
//!     "UNWIND [1,2,3,4,5,6] AS x RETURN x ORDER BY x LIMIT 10",
//!     QueryOptions::max_result_rows(5),
//! )?;
//!
//! assert_eq!(table.column_names(), &["x".to_string()]);
//! let rows = table.collect(|row| Ok(format!("{:?}", row[0])))?;
//! assert_eq!(rows.len(), 5);
//! # Ok(())
//! # }
//! ```
//!
//! Existing Cypher `LIMIT` clauses still apply. For example, `LIMIT 3` with
//! `QueryOptions::max_result_rows(5)` emits at most three rows, while `LIMIT 10` with the same
//! option emits at most five rows. Use `QueryOptions::max_result_rows(0)` when you want result
//! table metadata, including column names, without materializing any rows.
//!
//! # Query parameter binding
//!
//! Use [`params!`] or [`QueryParams`] for params-only calls, or combine params with bounded
//! previews through [`QueryOptions`]. Query text uses `$name`; API parameter names omit the
//! leading `$`.
//!
//! ```
//! # use velr::{QueryOptions, Velr};
//! # fn main() -> velr::Result<()> {
//! let db = Velr::open(None)?;
//! db.run_with_params(
//!     "CREATE (:Person {name: $name, age: $age})",
//!     velr::params! {
//!         name: "Alice",
//!         age: 42_i64,
//!     }?,
//! )?;
//!
//! let mut table = db.exec_one_with_options(
//!     "MATCH (p:Person) WHERE p.age >= $min_age RETURN p.name AS name ORDER BY name",
//!     QueryOptions::max_result_rows(20).with_param("min_age", 18_i64)?,
//! )?;
//! assert_eq!(table.column_names(), &["name".to_string()]);
//! # Ok(())
//! # }
//! ```
//!
//! # Errors
//!
//! Most operations return [`Result<T>`]. On failure, you get an [`Error`] containing a numeric
//! code (originating from the runtime ABI) and an optional message.
//!
//! # Schema migration and introspection
//!
//! This runtime's current on-disk schema is version 7. Supported older databases can be opened
//! without automatic migration. Reads remain available on those databases, but writes and
//! features that require the current schema return a query error until the user explicitly
//! migrates. `SHOW CURRENT GRAPH SHAPE` is available once a database has reached schema version 5.
//!
//! Use [`Velr::schema_version`], [`Velr::current_schema_version`], and
//! [`Velr::needs_migration`] to inspect the connection state. Use [`Velr::migrate`] or execute
//! `MIGRATE DATABASE` from maintenance code when upgrading is intended.
//!
//! `SHOW CURRENT GRAPH SHAPE` exposes Velr's observed graph schema: labels, relationship types,
//! properties, observed value types, and counts. Use `YIELD` to compose it with `WHERE` and
//! `RETURN`, or `YIELD *` to inspect the full row shape.
//!
//! Fulltext search is also available through normal Cypher execution. Use `CREATE FULLTEXT INDEX`
//! to define an index and `CALL db.index.fulltext.queryNodes(...)` to search it. Fulltext indexes
//! use a sidecar next to file-backed databases, and no dedicated driver methods are required. The
//! query grammar supports terms, phrases, field scoping, boolean grouping, required/excluded
//! terms, phrase slop, phrase-prefix, boosts, and `*` match-all. `score` is a non-normalized
//! relevance score. Higher scores are better within a single query result set; scores are not
//! guaranteed to be in `0..1` or comparable across different queries.
#![allow(unsafe_code)]

mod api;
mod runtime;
mod sys;

use std::{
    cell::{Cell, RefCell},
    collections::{BTreeMap, HashMap},
    ffi::{CStr, CString},
    fmt,
    hash::BuildHasher,
    marker::PhantomData,
    os::raw::{c_char, c_void},
    panic::{catch_unwind, AssertUnwindSafe},
    ptr::NonNull,
    rc::Rc,
};

use serde_json::Value as JsonValue;
use sys as ffi;
use velr_types::{decode_property_value, StorageValueRef};

pub use velr_types::{
    DateValue, DurationValue, GeographyValue, GeometryShape, GeometryValue, LineStringValue,
    LinearRingValue, ListIter, ListValue, LocalDateTimeValue, LocalTimeValue, PointValue,
    PolygonValue, Position, PropertyValue, PropertyValueRef, VectorElem, VectorIter, VectorStorage,
    VectorType, VectorValue, ZonedDateTimeValue, ZonedTimeValue,
};

/// Convenience result type used throughout the public API.
pub type Result<T> = std::result::Result<T, Error>;

/// Error returned by the Velr API.
///
/// - `code` is an integer error code returned by the runtime ABI. This is subject for change later.
/// - `message` is an optional, human-readable message (may be empty).
///
/// The runtime may or may not provide an error message for a given code.
#[derive(Debug)]
pub struct Error {
    pub code: i32,
    pub message: String,
}

impl Error {
    fn new(code: i32, message: impl Into<String>) -> Self {
        Self {
            code,
            message: message.into(),
        }
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.message.is_empty() {
            write!(f, "velr error (code {})", self.code)
        } else {
            write!(f, "velr error (code {}): {}", self.code, self.message)
        }
    }
}

impl std::error::Error for Error {}

/// A Cypher value supplied out-of-band through [`QueryParams`].
///
/// Values are bound as data and are never parsed as Cypher text. For example,
/// `QueryValue::String("RETURN 1".to_string())` is a Cypher string value, not executable text.
///
/// This covers the openCypher parameter value surface: `null`, booleans, signed 64-bit integers,
/// finite floats, strings, lists, and maps with string keys.
#[derive(Debug, Clone, PartialEq)]
pub enum QueryValue {
    /// The Cypher `null` value.
    Null,
    /// A Cypher `BOOLEAN`.
    Bool(bool),
    /// A Cypher `INTEGER`.
    Integer(i64),
    /// A Cypher `FLOAT`.
    Float(f64),
    /// A Cypher `STRING`.
    String(String),
    /// A Cypher list.
    List(Vec<QueryValue>),
    /// A Cypher map.
    Map(BTreeMap<String, QueryValue>),
}

/// Named parameters supplied to a Cypher query.
///
/// Query text references parameters with `$name`; API callers pass the name without the leading
/// `$`, for example `QueryParams::new().with("name", "Alice")?`. Numeric parameter names are
/// passed the same way, so `$1` in query text is bound with the key `"1"`.
///
/// Parameters are sent to the runtime separately from the Cypher text. They are suitable for user
/// data because strings and other values cannot be interpreted as query fragments.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct QueryParams {
    values: BTreeMap<String, QueryValue>,
}

/// Error returned while constructing or binding query parameters.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct QueryParamError {
    message: String,
}

impl QueryParamError {
    /// Create a parameter-construction error with a human-readable message.
    pub fn new(message: impl Into<String>) -> Self {
        Self {
            message: message.into(),
        }
    }
}

impl fmt::Display for QueryParamError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.message)
    }
}

impl std::error::Error for QueryParamError {}

impl From<QueryParamError> for Error {
    fn from(value: QueryParamError) -> Self {
        Error::new(ffi::velr_code::VELR_EARG as i32, value.to_string())
    }
}

/// Fallible conversion from a Rust value into a Cypher parameter value.
///
/// Implementations are provided for `QueryValue`, `()`, `Option<T>`, booleans, signed and
/// unsigned integer types that fit in Cypher `INTEGER`, `f32`/`f64` finite floats, `String`,
/// `&str`, `Vec<T>`, `BTreeMap<String, T>`, `HashMap<String, T>`, and `serde_json::Value`.
pub trait TryIntoQueryValue {
    /// Convert this Rust value into a Cypher parameter value.
    fn try_into_query_value(self) -> std::result::Result<QueryValue, QueryParamError>;
}

impl QueryParams {
    /// Create an empty parameter map.
    pub fn new() -> Self {
        Self::default()
    }

    /// Return a new parameter map with one additional named value.
    ///
    /// The name must be non-empty and should not include the leading `$` used in Cypher text.
    /// Returns [`QueryParamError`] if the name or value cannot be represented as a Cypher
    /// parameter value.
    pub fn with<V>(
        mut self,
        name: impl Into<String>,
        value: V,
    ) -> std::result::Result<Self, QueryParamError>
    where
        V: TryIntoQueryValue,
    {
        self.insert(name, value)?;
        Ok(self)
    }

    /// Insert or replace one named value.
    ///
    /// The name must be non-empty and should not include the leading `$` used in Cypher text.
    /// Returns [`QueryParamError`] if the name or value cannot be represented as a Cypher
    /// parameter value.
    pub fn insert<V>(
        &mut self,
        name: impl Into<String>,
        value: V,
    ) -> std::result::Result<(), QueryParamError>
    where
        V: TryIntoQueryValue,
    {
        let name = name.into();
        if name.is_empty() {
            return Err(QueryParamError::new("query parameter name cannot be empty"));
        }
        if name.starts_with('$') {
            return Err(QueryParamError::new(
                "query parameter name should not include the leading `$`",
            ));
        }
        let value = value.try_into_query_value()?;
        validate_query_value(&value)?;
        self.values.insert(name, value);
        Ok(())
    }

    /// Get a parameter value by name, without the leading `$`.
    pub fn get(&self, name: &str) -> Option<&QueryValue> {
        self.values.get(name)
    }

    /// Iterate over parameter names and values in stable key order.
    pub fn iter(&self) -> impl Iterator<Item = (&str, &QueryValue)> {
        self.values
            .iter()
            .map(|(name, value)| (name.as_str(), value))
    }

    /// Return true when the parameter map is empty.
    pub fn is_empty(&self) -> bool {
        self.values.is_empty()
    }

    /// Return the number of named parameters.
    pub fn len(&self) -> usize {
        self.values.len()
    }
}

/// Build a [`QueryParams`] map with compact syntax.
///
/// The macro returns `Result<QueryParams, QueryParamError>` so parameter-name and value validation
/// remain explicit at the call site.
///
/// ```
/// # fn main() -> velr::Result<()> {
/// let params = velr::params! {
///     "name" => "Alice",
///     "age" => 42_i64,
/// }?;
/// assert_eq!(params.len(), 2);
/// # Ok(())
/// # }
/// ```
///
/// Identifier keys are also accepted and are stringified, and can be mixed with literal keys:
///
/// ```
/// # fn main() -> velr::Result<()> {
/// let params = velr::params! {
///     name: "Alice",
///     "1" => 42_i64,
/// }?;
/// assert_eq!(params.len(), 2);
/// # Ok(())
/// # }
/// ```
#[macro_export]
macro_rules! params {
    () => {
        ::std::result::Result::<$crate::QueryParams, $crate::QueryParamError>::Ok(
            $crate::QueryParams::new(),
        )
    };
    (@insert $params:ident,) => {};
    (@insert $params:ident) => {};
    (@insert $params:ident, $name:ident : $value:expr, $($rest:tt)*) => {
        $params.insert(::std::stringify!($name), $value)?;
        $crate::params!(@insert $params, $($rest)*);
    };
    (@insert $params:ident, $name:ident : $value:expr) => {
        $params.insert(::std::stringify!($name), $value)?;
    };
    (@insert $params:ident, $name:literal => $value:expr, $($rest:tt)*) => {
        $params.insert($name, $value)?;
        $crate::params!(@insert $params, $($rest)*);
    };
    (@insert $params:ident, $name:literal => $value:expr) => {
        $params.insert($name, $value)?;
    };
    ($($tt:tt)+) => {{
        let mut params = $crate::QueryParams::new();
        let result: ::std::result::Result<$crate::QueryParams, $crate::QueryParamError> = (|| {
            $crate::params!(@insert params, $($tt)+);
            ::std::result::Result::Ok(params)
        })();
        result
    }};
}

impl TryIntoQueryValue for QueryValue {
    fn try_into_query_value(self) -> std::result::Result<QueryValue, QueryParamError> {
        validate_query_value(&self)?;
        Ok(self)
    }
}

impl TryIntoQueryValue for () {
    fn try_into_query_value(self) -> std::result::Result<QueryValue, QueryParamError> {
        Ok(QueryValue::Null)
    }
}

impl<T> TryIntoQueryValue for Option<T>
where
    T: TryIntoQueryValue,
{
    fn try_into_query_value(self) -> std::result::Result<QueryValue, QueryParamError> {
        match self {
            Some(value) => value.try_into_query_value(),
            None => Ok(QueryValue::Null),
        }
    }
}

impl TryIntoQueryValue for bool {
    fn try_into_query_value(self) -> std::result::Result<QueryValue, QueryParamError> {
        Ok(QueryValue::Bool(self))
    }
}

impl TryIntoQueryValue for i64 {
    fn try_into_query_value(self) -> std::result::Result<QueryValue, QueryParamError> {
        Ok(QueryValue::Integer(self))
    }
}

macro_rules! signed_int_value {
    ($($ty:ty),* $(,)?) => {
        $(
            impl TryIntoQueryValue for $ty {
                fn try_into_query_value(self) -> std::result::Result<QueryValue, QueryParamError> {
                    Ok(QueryValue::Integer(i64::from(self)))
                }
            }
        )*
    };
}

signed_int_value!(i8, i16, i32);

impl TryIntoQueryValue for isize {
    fn try_into_query_value(self) -> std::result::Result<QueryValue, QueryParamError> {
        let value = i64::try_from(self)
            .map_err(|_| QueryParamError::new("isize parameter does not fit Cypher INTEGER"))?;
        Ok(QueryValue::Integer(value))
    }
}

macro_rules! unsigned_int_value {
    ($($ty:ty),* $(,)?) => {
        $(
            impl TryIntoQueryValue for $ty {
                fn try_into_query_value(self) -> std::result::Result<QueryValue, QueryParamError> {
                    let value = i64::try_from(self).map_err(|_| {
                        QueryParamError::new(concat!(
                            stringify!($ty),
                            " parameter does not fit Cypher INTEGER"
                        ))
                    })?;
                    Ok(QueryValue::Integer(value))
                }
            }
        )*
    };
}

unsigned_int_value!(u8, u16, u32, u64, usize);

impl TryIntoQueryValue for f64 {
    fn try_into_query_value(self) -> std::result::Result<QueryValue, QueryParamError> {
        if !self.is_finite() {
            return Err(QueryParamError::new(
                "floating point query parameters must be finite",
            ));
        }
        Ok(QueryValue::Float(self))
    }
}

impl TryIntoQueryValue for f32 {
    fn try_into_query_value(self) -> std::result::Result<QueryValue, QueryParamError> {
        if !self.is_finite() {
            return Err(QueryParamError::new(
                "floating point query parameters must be finite",
            ));
        }
        Ok(QueryValue::Float(f64::from(self)))
    }
}

impl TryIntoQueryValue for String {
    fn try_into_query_value(self) -> std::result::Result<QueryValue, QueryParamError> {
        Ok(QueryValue::String(self))
    }
}

impl TryIntoQueryValue for &str {
    fn try_into_query_value(self) -> std::result::Result<QueryValue, QueryParamError> {
        Ok(QueryValue::String(self.to_string()))
    }
}

impl<T> TryIntoQueryValue for Vec<T>
where
    T: TryIntoQueryValue,
{
    fn try_into_query_value(self) -> std::result::Result<QueryValue, QueryParamError> {
        let mut out = Vec::with_capacity(self.len());
        for value in self {
            let value = value.try_into_query_value()?;
            validate_query_value(&value)?;
            out.push(value);
        }
        Ok(QueryValue::List(out))
    }
}

impl<T> TryIntoQueryValue for BTreeMap<String, T>
where
    T: TryIntoQueryValue,
{
    fn try_into_query_value(self) -> std::result::Result<QueryValue, QueryParamError> {
        let mut out = BTreeMap::new();
        for (key, value) in self {
            let value = value.try_into_query_value()?;
            validate_query_value(&value)?;
            out.insert(key, value);
        }
        Ok(QueryValue::Map(out))
    }
}

impl<T, S> TryIntoQueryValue for HashMap<String, T, S>
where
    T: TryIntoQueryValue,
    S: BuildHasher,
{
    fn try_into_query_value(self) -> std::result::Result<QueryValue, QueryParamError> {
        let mut out = BTreeMap::new();
        for (key, value) in self {
            let value = value.try_into_query_value()?;
            validate_query_value(&value)?;
            out.insert(key, value);
        }
        Ok(QueryValue::Map(out))
    }
}

impl TryIntoQueryValue for JsonValue {
    fn try_into_query_value(self) -> std::result::Result<QueryValue, QueryParamError> {
        match self {
            JsonValue::Null => Ok(QueryValue::Null),
            JsonValue::Bool(value) => Ok(QueryValue::Bool(value)),
            JsonValue::Number(value) => {
                if let Some(value) = value.as_i64() {
                    Ok(QueryValue::Integer(value))
                } else if let Some(value) = value.as_u64() {
                    let value = i64::try_from(value).map_err(|_| {
                        QueryParamError::new("JSON integer parameter does not fit Cypher INTEGER")
                    })?;
                    Ok(QueryValue::Integer(value))
                } else if let Some(value) = value.as_f64() {
                    if !value.is_finite() {
                        return Err(QueryParamError::new(
                            "floating point query parameters must be finite",
                        ));
                    }
                    Ok(QueryValue::Float(value))
                } else {
                    Err(QueryParamError::new("unsupported JSON number parameter"))
                }
            }
            JsonValue::String(value) => Ok(QueryValue::String(value)),
            JsonValue::Array(values) => {
                let mut out = Vec::with_capacity(values.len());
                for value in values {
                    out.push(value.try_into_query_value()?);
                }
                Ok(QueryValue::List(out))
            }
            JsonValue::Object(values) => {
                let mut out = BTreeMap::new();
                for (key, value) in values {
                    out.insert(key, value.try_into_query_value()?);
                }
                Ok(QueryValue::Map(out))
            }
        }
    }
}

fn validate_query_value(value: &QueryValue) -> std::result::Result<(), QueryParamError> {
    match value {
        QueryValue::Float(value) if !value.is_finite() => Err(QueryParamError::new(
            "floating point query parameters must be finite",
        )),
        QueryValue::List(values) => {
            for value in values {
                validate_query_value(value)?;
            }
            Ok(())
        }
        QueryValue::Map(values) => {
            for value in values.values() {
                validate_query_value(value)?;
            }
            Ok(())
        }
        _ => Ok(()),
    }
}

fn query_value_to_json(value: &QueryValue) -> JsonValue {
    match value {
        QueryValue::Null => JsonValue::Null,
        QueryValue::Bool(value) => JsonValue::Bool(*value),
        QueryValue::Integer(value) => JsonValue::Number(serde_json::Number::from(*value)),
        QueryValue::Float(value) => JsonValue::Number(
            serde_json::Number::from_f64(*value)
                .expect("QueryValue::Float is validated to be finite"),
        ),
        QueryValue::String(value) => JsonValue::String(value.clone()),
        QueryValue::List(values) => {
            JsonValue::Array(values.iter().map(query_value_to_json).collect())
        }
        QueryValue::Map(values) => JsonValue::Object(
            values
                .iter()
                .map(|(key, value)| (key.clone(), query_value_to_json(value)))
                .collect(),
        ),
    }
}

fn missing_runtime_symbol(name: &str) -> Error {
    Error::new(
        ffi::velr_code::VELR_EERR as i32,
        format!("loaded Velr runtime does not expose {name}"),
    )
}

fn require_runtime_symbol<T: Copy>(symbol: Option<T>, name: &str) -> Result<T> {
    symbol.ok_or_else(|| missing_runtime_symbol(name))
}

/// Out-of-band execution options for query result emission.
///
/// Use this type with [`Velr::exec_with_options`], [`Velr::exec_one_with_options`],
/// [`Velr::run_with_options`], and the matching [`VelrTx`] methods when a host wants to preview
/// a query result without rewriting the Cypher text.
///
/// The options affect result emission only. They do not make a query read-only and they are not a
/// timeout or cancellation mechanism.
#[derive(Debug, Clone, Default, PartialEq)]
#[non_exhaustive]
pub struct QueryOptions {
    /// Maximum number of rows to emit from each result table.
    ///
    /// - `None` preserves the default behavior and emits all rows produced by the query.
    /// - `Some(0)` preserves result table metadata, including column names, but row cursors
    ///   immediately return EOF.
    /// - `Some(n)` emits at most `n` rows from each result table.
    ///
    /// Existing Cypher `LIMIT` clauses still apply. For example, a query with `LIMIT 3` and
    /// `max_result_rows = Some(5)` emits at most three rows, while `LIMIT 10` with
    /// `max_result_rows = Some(5)` emits at most five rows.
    pub max_result_rows: Option<usize>,
    /// Named query parameters bound as Cypher values.
    ///
    /// Query text references these with `$name`; parameter names in this map omit the leading `$`.
    pub params: QueryParams,
}

impl QueryOptions {
    /// Create default query options.
    ///
    /// The default has no row cap and behaves like the non-`_with_options` execution methods.
    pub fn new() -> Self {
        Self::default()
    }

    /// Create query options that cap emitted rows per result table.
    ///
    /// Passing `0` preserves result table metadata, including column names, but emits no rows.
    pub fn max_result_rows(max_result_rows: usize) -> Self {
        Self {
            max_result_rows: Some(max_result_rows),
            params: QueryParams::new(),
        }
    }

    /// Set the maximum emitted row count per result table.
    ///
    /// Passing `0` preserves result table metadata, including column names, but emits no rows.
    pub fn with_max_result_rows(mut self, max_result_rows: usize) -> Self {
        self.max_result_rows = Some(max_result_rows);
        self
    }

    /// Set the full parameter map for this query.
    pub fn with_params(mut self, params: QueryParams) -> Self {
        self.params = params;
        self
    }

    /// Add one named parameter to this query.
    ///
    /// The name should not include the leading `$` used in Cypher text.
    pub fn with_param<V>(
        mut self,
        name: impl Into<String>,
        value: V,
    ) -> std::result::Result<Self, QueryParamError>
    where
        V: TryIntoQueryValue,
    {
        self.params.insert(name, value)?;
        Ok(self)
    }
}

struct RawQueryParams {
    ptr: NonNull<ffi::velr_query_params>,
    free: unsafe extern "C" fn(*mut ffi::velr_query_params),
}

impl RawQueryParams {
    fn from_query_params(params: &QueryParams) -> Result<Option<Self>> {
        if params.is_empty() {
            return Ok(None);
        }

        let a = velr_api()?;
        let ptr = unsafe { (a.velr_query_params_new)() };
        let ptr = NonNull::new(ptr).ok_or_else(|| {
            Error::new(
                ffi::velr_code::VELR_EERR as i32,
                "velr_query_params_new returned null",
            )
        })?;

        let out = Self {
            ptr,
            free: a.velr_query_params_free,
        };
        for (name, value) in params.iter() {
            out.set(name, value)?;
        }
        Ok(Some(out))
    }

    fn set(&self, name: &str, value: &QueryValue) -> Result<()> {
        let a = velr_api()?;
        let name = raw_strview(name.as_bytes());
        let mut err: *mut c_char = std::ptr::null_mut();
        let rc = unsafe {
            match value {
                QueryValue::Null => {
                    (a.velr_query_params_set_null)(self.ptr.as_ptr(), name, &mut err)
                }
                QueryValue::Bool(value) => (a.velr_query_params_set_bool)(
                    self.ptr.as_ptr(),
                    name,
                    i32::from(*value),
                    &mut err,
                ),
                QueryValue::Integer(value) => {
                    (a.velr_query_params_set_i64)(self.ptr.as_ptr(), name, *value, &mut err)
                }
                QueryValue::Float(value) => {
                    (a.velr_query_params_set_f64)(self.ptr.as_ptr(), name, *value, &mut err)
                }
                QueryValue::String(value) => (a.velr_query_params_set_text)(
                    self.ptr.as_ptr(),
                    name,
                    raw_strview(value.as_bytes()),
                    &mut err,
                ),
                QueryValue::List(_) | QueryValue::Map(_) => {
                    let json = serde_json::to_vec(&query_value_to_json(value)).map_err(|e| {
                        Error::new(
                            ffi::velr_code::VELR_EERR as i32,
                            format!("failed to encode query parameter JSON: {e}"),
                        )
                    })?;
                    (a.velr_query_params_set_json)(
                        self.ptr.as_ptr(),
                        name,
                        raw_strview(&json),
                        &mut err,
                    )
                }
            }
        };
        rc_to_result(rc, err)
    }
}

impl Drop for RawQueryParams {
    fn drop(&mut self) {
        unsafe {
            (self.free)(self.ptr.as_ptr());
        }
    }
}

fn raw_strview(bytes: &[u8]) -> ffi::velr_strview {
    ffi::velr_strview {
        ptr: bytes.as_ptr(),
        len: bytes.len(),
    }
}

fn raw_query_options(
    options: &QueryOptions,
) -> Result<(ffi::velr_query_options, Option<RawQueryParams>)> {
    let params = RawQueryParams::from_query_params(&options.params)?;
    let raw = ffi::velr_query_options {
        has_max_result_rows: i32::from(options.max_result_rows.is_some()),
        max_result_rows: options.max_result_rows.unwrap_or(0),
        params: params
            .as_ref()
            .map(|params| params.ptr.as_ptr() as *const ffi::velr_query_params)
            .unwrap_or(std::ptr::null()),
    };
    Ok((raw, params))
}

/// Status returned by [`Velr::migrate`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MigrationStatus {
    /// The database was already at the current runtime schema version.
    AlreadyCurrent,
    /// At least one migration step was applied.
    Migrated,
}

/// Report returned by [`Velr::migrate`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MigrationReport {
    /// Schema version observed before migration.
    pub from_version: i32,
    /// Schema version after migration.
    pub to_version: i32,
    /// Whether migration work was applied.
    pub status: MigrationStatus,
    /// Runtime migration step identifiers applied in order.
    pub steps: Vec<String>,
}

/// Why Velr is asking an embedder to produce vectors.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum VectorEmbeddingPurpose {
    /// Embedding source values from a graph entity for index maintenance.
    IndexEntity,
    /// Embedding a query payload supplied to `db.index.vector.queryNodes`.
    Query,
}

/// Graph entity kind for indexed vector embedding inputs.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum VectorEntityKind {
    Node,
    Relationship,
}

/// One named Velr value passed to a registered vector embedding callback.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct VectorEmbeddingField {
    /// Property name for indexed entity values. Query payloads may be unnamed.
    pub name: Option<String>,
    /// The typed Velr value to embed.
    pub value: PropertyValue,
}

/// One source row passed to a registered vector embedding callback.
///
/// For indexed entities, `fields` follows the `CREATE VECTOR INDEX ... ON EACH [...]`
/// property order. For `n.*`, fields are ordered by property name. For query text,
/// Velr passes one unnamed `PropertyValue::String` field.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct VectorEmbeddingInput {
    pub index_name: String,
    pub dimensions: usize,
    pub purpose: VectorEmbeddingPurpose,
    pub entity_kind: Option<VectorEntityKind>,
    pub entity_id: Option<i64>,
    pub fields: Vec<VectorEmbeddingField>,
}

pub type VectorEmbeddingBatchResult = std::result::Result<Vec<Vec<f32>>, String>;

/// Get a reference to the loaded runtime API.
///
/// This ensures the runtime is initialized (via [`runtime::runtime`]) and then returns the
/// resolved ABI function table.
///
/// # Errors
///
/// Returns an [`Error`] if the runtime cannot be loaded or initialized.
fn velr_api() -> Result<&'static api::Api> {
    Ok(&runtime::runtime()?.api)
}
/*
fn borrowed_bytes<'a>(ptr: *const u8, len: usize, what: &str) -> Result<&'a [u8]> {
    if len == 0 {
        return Ok(&[]);
    }
    if ptr.is_null() {
        return Err(Error::new(
            ffi::velr_code::VELR_EERR as i32,
            format!("{what} is null with non-zero length"),
        ));
    }
    Ok(unsafe { std::slice::from_raw_parts(ptr, len) })
}
*/
/// Convert an ABI-owned error string into a Rust [`String`], freeing it via the runtime.
///
/// # Safety
///
/// `p` must be either null or a pointer to a NUL-terminated C string allocated by the Velr runtime.
/// On success, this function attempts to free the string using `velr_string_free`.
unsafe fn take_err(p: *mut c_char) -> String {
    if p.is_null() {
        return String::new();
    }
    let s = CStr::from_ptr(p).to_string_lossy().into_owned();

    // Free via runtime API (best-effort; if runtime isn't available, leak rather than crash).
    if let Ok(a) = velr_api() {
        (a.velr_string_free)(p);
    }

    s
}

fn free_unexpected_err(err: *mut c_char) {
    if !err.is_null() {
        if let Ok(a) = velr_api() {
            unsafe { (a.velr_string_free)(err) };
        }
    }
}

fn take_owned_bytes(a: &api::Api, ptr: *mut u8, len: usize, what: &str) -> Result<Vec<u8>> {
    if ptr.is_null() {
        return if len == 0 {
            Ok(Vec::new())
        } else {
            Err(Error::new(
                ffi::velr_code::VELR_EERR as i32,
                format!("{what} returned null pointer with non-zero length"),
            ))
        };
    }

    let bytes = unsafe { std::slice::from_raw_parts(ptr, len) }.to_vec();
    unsafe { (a.velr_free)(ptr, len) };
    Ok(bytes)
}

/// Convert a Velr return code plus optional error string into [`Result<()>`].
///
/// On success, frees `err` if it is unexpectedly non-null. On failure, converts `err` into an
/// [`Error`] and frees it via the runtime.
fn rc_to_result(rc: ffi::velr_code, err: *mut c_char) -> Result<()> {
    let code = rc as i32;
    if code == ffi::velr_code::VELR_OK as i32 {
        free_unexpected_err(err);
        Ok(())
    } else {
        let msg = unsafe { take_err(err) };
        Err(Error::new(code, msg))
    }
}

fn rc_to_result_noerr(rc: ffi::velr_code, context: impl Into<String>) -> Result<()> {
    let code = rc as i32;
    if code == ffi::velr_code::VELR_OK as i32 {
        Ok(())
    } else {
        Err(Error::new(code, context.into()))
    }
}

fn strview_to_string(v: ffi::velr_strview, what: &str) -> Result<String> {
    if v.len == 0 {
        return Ok(String::new());
    }
    if v.ptr.is_null() {
        return Err(Error::new(
            ffi::velr_code::VELR_EERR as i32,
            format!("{what} is null with non-zero length"),
        ));
    }

    let bytes = unsafe { std::slice::from_raw_parts(v.ptr, v.len) };
    let s = std::str::from_utf8(bytes).map_err(|_| {
        Error::new(
            ffi::velr_code::VELR_EUTF as i32,
            format!("{what} is not valid UTF-8"),
        )
    })?;
    Ok(s.to_string())
}

fn opt_strview_to_string(v: ffi::velr_strview, what: &str) -> Result<Option<String>> {
    if v.ptr.is_null() && v.len == 0 {
        return Ok(None);
    }
    Ok(Some(strview_to_string(v, what)?))
}

unsafe fn vector_strview_bytes<'a>(
    v: ffi::velr_strview,
    what: &str,
) -> std::result::Result<&'a [u8], String> {
    if v.len == 0 {
        return Ok(&[]);
    }
    if v.ptr.is_null() {
        return Err(format!("{what} is null with non-zero length"));
    }
    Ok(std::slice::from_raw_parts(v.ptr, v.len))
}

unsafe fn vector_strview_to_string(
    v: ffi::velr_strview,
    what: &str,
) -> std::result::Result<String, String> {
    let bytes = vector_strview_bytes(v, what)?;
    std::str::from_utf8(bytes)
        .map(str::to_string)
        .map_err(|_| format!("{what} is not valid UTF-8"))
}

fn vector_purpose_from_raw(value: ffi::velr_vector_embedding_purpose) -> VectorEmbeddingPurpose {
    match value {
        ffi::velr_vector_embedding_purpose::VELR_VECTOR_EMBEDDING_INDEX_ENTITY => {
            VectorEmbeddingPurpose::IndexEntity
        }
        ffi::velr_vector_embedding_purpose::VELR_VECTOR_EMBEDDING_QUERY => {
            VectorEmbeddingPurpose::Query
        }
    }
}

fn vector_entity_kind_from_raw(value: ffi::velr_vector_entity_kind) -> Option<VectorEntityKind> {
    match value {
        ffi::velr_vector_entity_kind::VELR_VECTOR_ENTITY_NODE => Some(VectorEntityKind::Node),
        ffi::velr_vector_entity_kind::VELR_VECTOR_ENTITY_RELATIONSHIP => {
            Some(VectorEntityKind::Relationship)
        }
        ffi::velr_vector_entity_kind::VELR_VECTOR_ENTITY_NONE => None,
    }
}

unsafe fn vector_property_value_from_raw(
    field: &ffi::velr_vector_embedding_field,
) -> std::result::Result<PropertyValue, String> {
    let storage = match field.storage_type {
        ffi::velr_storage_value_type::VELR_STORAGE_NULL => StorageValueRef::Null,
        ffi::velr_storage_value_type::VELR_STORAGE_INT64 => StorageValueRef::Integer(field.i64_),
        ffi::velr_storage_value_type::VELR_STORAGE_DOUBLE => StorageValueRef::Real(field.f64_),
        ffi::velr_storage_value_type::VELR_STORAGE_TEXT => {
            let bytes = vector_strview_bytes(field.bytes, "vector field text storage")?;
            let text = std::str::from_utf8(bytes)
                .map_err(|_| "vector field text storage is not valid UTF-8".to_string())?;
            StorageValueRef::Text(text)
        }
        ffi::velr_storage_value_type::VELR_STORAGE_BLOB => StorageValueRef::Blob(
            vector_strview_bytes(field.bytes, "vector field blob storage")?,
        ),
    };
    decode_property_value(storage).map_err(|err| format!("decode vector field value: {err}"))
}

unsafe fn vector_inputs_from_raw(
    inputs: *const ffi::velr_vector_embedding_input,
    input_count: usize,
) -> std::result::Result<Vec<VectorEmbeddingInput>, String> {
    if input_count == 0 {
        return Ok(Vec::new());
    }
    if inputs.is_null() {
        return Err("vector embedding inputs pointer is null with non-zero count".to_string());
    }

    let raw_inputs = std::slice::from_raw_parts(inputs, input_count);
    let mut out = Vec::with_capacity(input_count);
    for (input_idx, input) in raw_inputs.iter().enumerate() {
        let fields = if input.field_count == 0 {
            &[][..]
        } else {
            if input.fields.is_null() {
                return Err(format!(
                    "vector embedding input {input_idx} fields pointer is null with non-zero count"
                ));
            }
            std::slice::from_raw_parts(input.fields, input.field_count)
        };
        let mut decoded_fields = Vec::with_capacity(fields.len());
        for field in fields {
            let name = if field.has_name != 0 {
                Some(vector_strview_to_string(field.name, "vector field name")?)
            } else {
                None
            };
            decoded_fields.push(VectorEmbeddingField {
                name,
                value: vector_property_value_from_raw(field)?,
            });
        }
        out.push(VectorEmbeddingInput {
            index_name: vector_strview_to_string(input.index_name, "vector index name")?,
            dimensions: input.dimensions,
            purpose: vector_purpose_from_raw(input.purpose),
            entity_kind: vector_entity_kind_from_raw(input.entity_kind),
            entity_id: if input.has_entity_id != 0 {
                Some(input.entity_id)
            } else {
                None
            },
            fields: decoded_fields,
        });
    }
    Ok(out)
}

fn write_vector_callback_error(err_buf: *mut c_char, err_buf_len: usize, msg: &str) {
    if err_buf.is_null() || err_buf_len == 0 {
        return;
    }
    let bytes = msg.as_bytes();
    let copy_len = bytes.len().min(err_buf_len.saturating_sub(1));
    unsafe {
        if copy_len > 0 {
            std::ptr::copy_nonoverlapping(bytes.as_ptr(), err_buf.cast::<u8>(), copy_len);
        }
        *err_buf.add(copy_len) = 0;
    }
}

unsafe extern "C" fn vector_embedder_trampoline<F>(
    user_data: *mut c_void,
    inputs: *const ffi::velr_vector_embedding_input,
    input_count: usize,
    dimensions: usize,
    out_vectors: *mut f32,
    err_buf: *mut c_char,
    err_buf_len: usize,
) -> ffi::velr_code
where
    F: Fn(&[VectorEmbeddingInput]) -> VectorEmbeddingBatchResult + 'static,
{
    let result = catch_unwind(AssertUnwindSafe(|| -> std::result::Result<(), String> {
        if user_data.is_null() {
            return Err("vector embedder user data is null".to_string());
        }
        let output_len = input_count
            .checked_mul(dimensions)
            .ok_or_else(|| "vector embedding output length overflowed".to_string())?;
        if output_len > 0 && out_vectors.is_null() {
            return Err("vector embedding output pointer is null".to_string());
        }

        let embedder = &*(user_data as *const F);
        let decoded = vector_inputs_from_raw(inputs, input_count)?;
        let vectors = embedder(&decoded)?;
        if vectors.len() != input_count {
            return Err(format!(
                "vector embedder returned {} embeddings for {} inputs",
                vectors.len(),
                input_count
            ));
        }

        for (row_idx, vector) in vectors.iter().enumerate() {
            if vector.len() != dimensions {
                return Err(format!(
                    "vector embedder returned {} dimensions for input {} but the index expects {}",
                    vector.len(),
                    row_idx,
                    dimensions
                ));
            }
            for (dim_idx, value) in vector.iter().copied().enumerate() {
                if !value.is_finite() {
                    return Err(format!(
                        "vector embedder returned a non-finite value for input {row_idx} at dimension {dim_idx}: {value}"
                    ));
                }
                if output_len > 0 {
                    *out_vectors.add(row_idx * dimensions + dim_idx) = value;
                }
            }
        }
        Ok(())
    }));

    match result {
        Ok(Ok(())) => ffi::velr_code::VELR_OK,
        Ok(Err(err)) => {
            write_vector_callback_error(err_buf, err_buf_len, &err);
            ffi::velr_code::VELR_EERR
        }
        Err(_) => {
            write_vector_callback_error(err_buf, err_buf_len, "vector embedder callback panicked");
            ffi::velr_code::VELR_EERR
        }
    }
}

unsafe extern "C" fn vector_embedder_free_trampoline<F>(user_data: *mut c_void)
where
    F: Fn(&[VectorEmbeddingInput]) -> VectorEmbeddingBatchResult + 'static,
{
    if !user_data.is_null() {
        drop(Box::from_raw(user_data as *mut F));
    }
}

/// Owned plan metadata returned from an [`ExplainTrace`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ExplainPlanMeta {
    pub plan_id: String,
    pub cypher: String,
    pub step_count: usize,
}

/// Owned step metadata returned from an [`ExplainTrace`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ExplainStepMeta {
    pub step_no: usize,
    pub group_id: String,
    pub op_index: String,
    pub phase: String,
    pub title: String,
    pub source: String,
    pub note: Option<String>,
    pub statement_count: usize,
}

/// Owned statement metadata returned from an [`ExplainTrace`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ExplainStatementMeta {
    pub stmt_id: String,
    pub kind: String,
    pub sql: String,
    pub note: Option<String>,
    pub sqlite_plan_count: usize,
}

/// One explain statement plus its SQLite query-plan detail lines.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ExplainStatement {
    pub meta: ExplainStatementMeta,
    pub sqlite_plan: Vec<String>,
}

/// One explain step plus all statements in it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ExplainStep {
    pub meta: ExplainStepMeta,
    pub statements: Vec<ExplainStatement>,
}

/// One explain plan plus all steps in it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ExplainPlan {
    pub meta: ExplainPlanMeta,
    pub steps: Vec<ExplainStep>,
}

/// EXPLAIN / EXPLAIN ANALYZE trace handle.
///
/// This is an in-flight type and is **`!Send` + `!Sync`** (thread-affine).
/// Dropping it closes the underlying runtime trace handle.
///
/// All strings exposed by this type are copied into owned Rust `String`s before being returned.
pub struct ExplainTrace {
    trace: NonNull<ffi::velr_explain_trace>,
    _nosend: PhantomData<Rc<()>>, // !Send + !Sync
}

impl ExplainTrace {
    fn from_raw(ptr: *mut ffi::velr_explain_trace) -> Result<Self> {
        let trace = NonNull::new(ptr).ok_or_else(|| {
            Error::new(
                ffi::velr_code::VELR_EERR as i32,
                "runtime returned null explain trace",
            )
        })?;

        Ok(Self {
            trace,
            _nosend: PhantomData,
        })
    }

    /// Return the number of top-level plans in this trace.
    ///
    /// # Errors
    ///
    /// Returns an [`Error`] if the runtime API cannot be loaded.
    pub fn plan_count(&self) -> Result<usize> {
        let a = velr_api()?;
        Ok(unsafe { (a.velr_explain_trace_plan_count)(self.trace.as_ptr()) })
    }

    /// Fetch metadata for one plan.
    ///
    /// # Errors
    ///
    /// Returns an [`Error`] if:
    /// - the runtime API cannot be loaded
    /// - `plan_idx` is out of range
    /// - returned string fields are not valid UTF-8
    pub fn plan_meta(&self, plan_idx: usize) -> Result<ExplainPlanMeta> {
        let a = velr_api()?;
        let mut out = std::mem::MaybeUninit::<ffi::velr_explain_plan_meta>::uninit();

        let rc = unsafe {
            (a.velr_explain_trace_plan_meta)(self.trace.as_ptr(), plan_idx, out.as_mut_ptr())
        };
        rc_to_result_noerr(
            rc,
            format!("velr_explain_trace_plan_meta failed at plan_idx={plan_idx}"),
        )?;

        let out = unsafe { out.assume_init() };
        Ok(ExplainPlanMeta {
            plan_id: strview_to_string(out.plan_id, "plan_id")?,
            cypher: strview_to_string(out.cypher, "cypher")?,
            step_count: out.step_count,
        })
    }

    /// Return the number of steps in a plan.
    ///
    /// This is a convenience wrapper over [`ExplainTrace::plan_meta`].
    ///
    /// # Errors
    ///
    /// Returns an [`Error`] if `plan_idx` is out of range or metadata decoding fails.
    pub fn step_count(&self, plan_idx: usize) -> Result<usize> {
        Ok(self.plan_meta(plan_idx)?.step_count)
    }

    /// Fetch metadata for one step.
    ///
    /// # Errors
    ///
    /// Returns an [`Error`] if:
    /// - the runtime API cannot be loaded
    /// - `plan_idx` or `step_idx` is out of range
    /// - returned string fields are not valid UTF-8
    pub fn step_meta(&self, plan_idx: usize, step_idx: usize) -> Result<ExplainStepMeta> {
        let a = velr_api()?;
        let mut out = std::mem::MaybeUninit::<ffi::velr_explain_step_meta>::uninit();

        let rc = unsafe {
            (a.velr_explain_trace_step_meta)(
                self.trace.as_ptr(),
                plan_idx,
                step_idx,
                out.as_mut_ptr(),
            )
        };
        rc_to_result_noerr(
            rc,
            format!(
                "velr_explain_trace_step_meta failed at plan_idx={plan_idx}, step_idx={step_idx}"
            ),
        )?;

        let out = unsafe { out.assume_init() };
        Ok(ExplainStepMeta {
            step_no: out.step_no,
            group_id: strview_to_string(out.group_id, "group_id")?,
            op_index: strview_to_string(out.op_index, "op_index")?,
            phase: strview_to_string(out.phase, "phase")?,
            title: strview_to_string(out.title, "title")?,
            source: strview_to_string(out.source, "source")?,
            note: opt_strview_to_string(out.note, "step.note")?,
            statement_count: out.statement_count,
        })
    }

    /// Return the number of statements in a step.
    ///
    /// This is a convenience wrapper over [`ExplainTrace::step_meta`].
    ///
    /// # Errors
    ///
    /// Returns an [`Error`] if `plan_idx` / `step_idx` are out of range or metadata decoding fails.
    pub fn statement_count(&self, plan_idx: usize, step_idx: usize) -> Result<usize> {
        Ok(self.step_meta(plan_idx, step_idx)?.statement_count)
    }

    /// Fetch metadata for one statement.
    ///
    /// # Errors
    ///
    /// Returns an [`Error`] if:
    /// - the runtime API cannot be loaded
    /// - `plan_idx`, `step_idx`, or `stmt_idx` is out of range
    /// - returned string fields are not valid UTF-8
    pub fn statement_meta(
        &self,
        plan_idx: usize,
        step_idx: usize,
        stmt_idx: usize,
    ) -> Result<ExplainStatementMeta> {
        let a = velr_api()?;
        let mut out = std::mem::MaybeUninit::<ffi::velr_explain_stmt_meta>::uninit();

        let rc = unsafe {
            (a.velr_explain_trace_statement_meta)(
                self.trace.as_ptr(),
                plan_idx,
                step_idx,
                stmt_idx,
                out.as_mut_ptr(),
            )
        };
        rc_to_result_noerr(
            rc,
            format!(
                "velr_explain_trace_statement_meta failed at plan_idx={plan_idx}, step_idx={step_idx}, stmt_idx={stmt_idx}"
            ),
        )?;

        let out = unsafe { out.assume_init() };
        Ok(ExplainStatementMeta {
            stmt_id: strview_to_string(out.stmt_id, "stmt_id")?,
            kind: strview_to_string(out.kind, "kind")?,
            sql: strview_to_string(out.sql, "sql")?,
            note: opt_strview_to_string(out.note, "statement.note")?,
            sqlite_plan_count: out.sqlite_plan_count,
        })
    }

    /// Return the number of SQLite query-plan detail lines for one statement.
    ///
    /// This is a convenience wrapper over [`ExplainTrace::statement_meta`].
    ///
    /// # Errors
    ///
    /// Returns an [`Error`] if indices are out of range or metadata decoding fails.
    pub fn sqlite_plan_count(
        &self,
        plan_idx: usize,
        step_idx: usize,
        stmt_idx: usize,
    ) -> Result<usize> {
        Ok(self
            .statement_meta(plan_idx, step_idx, stmt_idx)?
            .sqlite_plan_count)
    }

    /// Fetch one SQLite query-plan detail line.
    ///
    /// # Errors
    ///
    /// Returns an [`Error`] if:
    /// - the runtime API cannot be loaded
    /// - any index is out of range
    /// - the returned detail line is not valid UTF-8
    pub fn sqlite_plan_detail(
        &self,
        plan_idx: usize,
        step_idx: usize,
        stmt_idx: usize,
        detail_idx: usize,
    ) -> Result<String> {
        let a = velr_api()?;
        let mut out = std::mem::MaybeUninit::<ffi::velr_strview>::uninit();

        let rc = unsafe {
            (a.velr_explain_trace_sqlite_plan_detail)(
                self.trace.as_ptr(),
                plan_idx,
                step_idx,
                stmt_idx,
                detail_idx,
                out.as_mut_ptr(),
            )
        };
        rc_to_result_noerr(
            rc,
            format!(
                "velr_explain_trace_sqlite_plan_detail failed at plan_idx={plan_idx}, step_idx={step_idx}, stmt_idx={stmt_idx}, detail_idx={detail_idx}"
            ),
        )?;

        let out = unsafe { out.assume_init() };
        strview_to_string(out, "sqlite_plan_detail")
    }

    /// Fetch all SQLite query-plan detail lines for one statement.
    ///
    /// # Errors
    ///
    /// Returns an [`Error`] if indices are out of range or any returned detail line
    /// cannot be decoded.
    pub fn sqlite_plan_details(
        &self,
        plan_idx: usize,
        step_idx: usize,
        stmt_idx: usize,
    ) -> Result<Vec<String>> {
        let n = self.sqlite_plan_count(plan_idx, step_idx, stmt_idx)?;
        let mut out = Vec::with_capacity(n);
        for i in 0..n {
            out.push(self.sqlite_plan_detail(plan_idx, step_idx, stmt_idx, i)?);
        }
        Ok(out)
    }

    /// Materialize the entire trace into owned Rust structs.
    ///
    /// This walks all plans, steps, statements, and SQLite plan details and returns
    /// a fully owned snapshot detached from the borrowed runtime string views.
    ///
    /// # Errors
    ///
    /// Returns an [`Error`] if any nested metadata/detail lookup fails.
    pub fn snapshot(&self) -> Result<Vec<ExplainPlan>> {
        let plan_count = self.plan_count()?;
        let mut plans = Vec::with_capacity(plan_count);

        for plan_idx in 0..plan_count {
            let plan_meta = self.plan_meta(plan_idx)?;
            let mut steps = Vec::with_capacity(plan_meta.step_count);

            for step_idx in 0..plan_meta.step_count {
                let step_meta = self.step_meta(plan_idx, step_idx)?;
                let mut statements = Vec::with_capacity(step_meta.statement_count);

                for stmt_idx in 0..step_meta.statement_count {
                    let stmt_meta = self.statement_meta(plan_idx, step_idx, stmt_idx)?;
                    let sqlite_plan = self.sqlite_plan_details(plan_idx, step_idx, stmt_idx)?;
                    statements.push(ExplainStatement {
                        meta: stmt_meta,
                        sqlite_plan,
                    });
                }

                steps.push(ExplainStep {
                    meta: step_meta,
                    statements,
                });
            }

            plans.push(ExplainPlan {
                meta: plan_meta,
                steps,
            });
        }

        Ok(plans)
    }

    /// Return the size in bytes of the compact rendering.
    ///
    /// The compact rendering is UTF-8 text, but this method returns the raw byte count.
    ///
    /// # Errors
    ///
    /// Returns an [`Error`] if the runtime API cannot be loaded or the runtime
    /// fails to render the compact form.
    pub fn compact_len(&self) -> Result<usize> {
        let a = velr_api()?;
        let mut len: usize = 0;
        let mut err: *mut c_char = std::ptr::null_mut();

        let rc =
            unsafe { (a.velr_explain_trace_compact_len)(self.trace.as_ptr(), &mut len, &mut err) };
        rc_to_result(rc, err)?;
        Ok(len)
    }

    /// Render the trace to compact UTF-8 bytes.
    ///
    /// The returned bytes are owned by Rust and independent of the runtime buffer.
    ///
    /// # Errors
    ///
    /// Returns an [`Error`] if:
    /// - the runtime API cannot be loaded
    /// - the runtime fails to render the compact form
    /// - the runtime returns an invalid null/non-null pointer + length combination
    pub fn to_compact_bytes(&self) -> Result<Vec<u8>> {
        let a = velr_api()?;
        let mut ptr: *mut u8 = std::ptr::null_mut();
        let mut len: usize = 0;
        let mut err: *mut c_char = std::ptr::null_mut();

        let rc = unsafe {
            (a.velr_explain_trace_compact_malloc)(self.trace.as_ptr(), &mut ptr, &mut len, &mut err)
        };
        rc_to_result(rc, err)?;
        take_owned_bytes(a, ptr, len, "velr_explain_trace_compact_malloc")
    }

    /// Render the trace to a compact UTF-8 string.
    ///
    /// # Errors
    ///
    /// Returns an [`Error`] if the compact rendering cannot be produced or if the
    /// returned bytes are not valid UTF-8.
    pub fn to_compact_string(&self) -> Result<String> {
        let bytes = self.to_compact_bytes()?;
        let s = String::from_utf8(bytes).map_err(|e| {
            Error::new(
                ffi::velr_code::VELR_EUTF as i32,
                format!("compact explain is not valid UTF-8: {e}"),
            )
        })?;
        Ok(s)
    }

    /// Write the compact rendering into any Rust writer.
    ///
    /// # Errors
    ///
    /// Returns an [`Error`] if rendering fails or if writing to `out` fails.
    pub fn write_compact(&self, mut out: impl std::io::Write) -> Result<()> {
        let bytes = self.to_compact_bytes()?;
        out.write_all(&bytes).map_err(|e| {
            Error::new(
                ffi::velr_code::VELR_EERR as i32,
                format!("failed to write compact explain: {e}"),
            )
        })
    }
}

impl Drop for ExplainTrace {
    fn drop(&mut self) {
        if let Ok(a) = velr_api() {
            unsafe { (a.velr_explain_trace_close)(self.trace.as_ptr()) };
        }
    }
}

// -------------------------- CellRef --------------------------

/// Borrowed view of a single cell value in a result row.
///
/// This is a lightweight, non-owning representation used when iterating rows.
/// Text/JSON values are exposed as raw bytes.
///
/// - For text data, use [`CellRef::as_str_utf8`] if you want a UTF-8 `&str`.
/// - JSON is returned as raw bytes
#[derive(Debug, Copy, Clone)]
pub enum CellRef<'a> {
    Null,
    Bool(bool),
    Integer(i64),
    Float(f64),
    Text(&'a [u8]),
    Json(&'a [u8]),
}

impl<'a> CellRef<'a> {
    /// If this cell is [`CellRef::Text`], attempt to interpret it as UTF-8.
    ///
    /// Returns:
    /// - `Some(Ok(&str))` if the cell is text and valid UTF-8
    /// - `Some(Err(_))` if the cell is text but invalid UTF-8
    /// - `None` if the cell is not text
    pub fn as_str_utf8(&self) -> Option<std::result::Result<&'a str, std::str::Utf8Error>> {
        match self {
            CellRef::Text(b) => Some(std::str::from_utf8(b)),
            _ => None,
        }
    }
}

// -------------------------- Velr (Connection) --------------------------
//
// Velr is Send + !Sync (movable, not shareable).
//

pub struct Velr {
    db: NonNull<ffi::velr_db>,
    _not_sync: PhantomData<Cell<()>>, // Send + !Sync
}

impl Velr {
    /// Open a Velr connection.
    ///
    /// ## Path semantics
    ///
    /// - If `path` is `None`, an **in-memory** database is opened.
    /// - If `path` is `Some(":memory:")`, an **in-memory** database is opened.
    /// - Otherwise, `path` is treated as a filesystem path for a file-backed database.
    ///
    /// # Errors
    ///
    /// Returns an error if `path` contains an interior NUL byte or if the runtime fails to open.
    pub fn open(path: Option<&str>) -> Result<Self> {
        let a = velr_api()?; // ensure runtime is loaded

        let mut out_db: *mut ffi::velr_db = std::ptr::null_mut();
        let mut err: *mut c_char = std::ptr::null_mut();

        let cpath;
        let path_ptr = match path {
            None => std::ptr::null(),
            Some(p) => {
                cpath = CString::new(p).map_err(|_| {
                    Error::new(ffi::velr_code::VELR_EUTF as i32, "path contains NUL")
                })?;
                cpath.as_ptr()
            }
        };

        let rc = unsafe { (a.velr_open)(path_ptr, &mut out_db, &mut err) };
        rc_to_result(rc, err)?;

        let nn = NonNull::new(out_db).ok_or_else(|| {
            Error::new(
                ffi::velr_code::VELR_EERR as i32,
                "velr_open returned null db",
            )
        })?;

        Ok(Self {
            db: nn,
            _not_sync: PhantomData,
        })
    }

    /// Open an existing file-backed Velr database in read-only mode.
    ///
    /// Unlike [`Velr::open`], this does not create, initialize, migrate, or
    /// repair a database. The file must already exist and carry a supported
    /// Velr schema version. Use this for viewers, agents, and other read paths
    /// that should not perform schema DDL.
    ///
    /// Supported older databases remain readable. Mutating queries and features
    /// that require the current schema version are unavailable until the
    /// database is opened read-write and explicitly migrated. `SHOW CURRENT
    /// GRAPH SHAPE` is available once a database has reached schema version 5.
    /// Use [`Velr::migrate`] or `MIGRATE DATABASE` to apply pending migrations.
    ///
    /// If the loaded native runtime is older and does not expose the underlying
    /// C ABI symbol, this returns an error.
    pub fn open_readonly(path: &str) -> Result<Self> {
        let a = velr_api()?;
        let open_readonly = a.velr_open_existing_readonly.ok_or_else(|| {
            Error::new(
                ffi::velr_code::VELR_EERR as i32,
                "loaded Velr runtime does not expose velr_open_existing_readonly",
            )
        })?;

        let mut out_db: *mut ffi::velr_db = std::ptr::null_mut();
        let mut err: *mut c_char = std::ptr::null_mut();
        let cpath = CString::new(path)
            .map_err(|_| Error::new(ffi::velr_code::VELR_EUTF as i32, "path contains NUL"))?;

        let rc = unsafe { open_readonly(cpath.as_ptr(), &mut out_db, &mut err) };
        rc_to_result(rc, err)?;

        let nn = NonNull::new(out_db).ok_or_else(|| {
            Error::new(
                ffi::velr_code::VELR_EERR as i32,
                "velr_open_existing_readonly returned null db",
            )
        })?;

        Ok(Self {
            db: nn,
            _not_sync: PhantomData,
        })
    }

    /// Return the schema version cached by this connection.
    pub fn schema_version(&self) -> Result<i32> {
        let a = velr_api()?;
        let schema_version = require_runtime_symbol(a.velr_schema_version, "velr_schema_version")?;

        let mut out = 0i32;
        let mut err: *mut c_char = std::ptr::null_mut();
        let rc = unsafe { schema_version(self.db.as_ptr(), &mut out, &mut err) };
        rc_to_result(rc, err)?;
        Ok(out)
    }

    /// Return the current schema version supported by this runtime.
    pub fn current_schema_version(&self) -> Result<i32> {
        let a = velr_api()?;
        let current_schema_version =
            require_runtime_symbol(a.velr_current_schema_version, "velr_current_schema_version")?;

        let mut out = 0i32;
        let mut err: *mut c_char = std::ptr::null_mut();
        let rc = unsafe { current_schema_version(self.db.as_ptr(), &mut out, &mut err) };
        rc_to_result(rc, err)?;
        Ok(out)
    }

    /// Return true when this connection is on an older supported schema version.
    ///
    /// Older supported databases can be read, but mutating queries are rejected
    /// until the database is explicitly migrated to the current schema version.
    pub fn needs_migration(&self) -> Result<bool> {
        let a = velr_api()?;
        let needs_migration =
            require_runtime_symbol(a.velr_needs_migration, "velr_needs_migration")?;

        let mut out = 0;
        let mut err: *mut c_char = std::ptr::null_mut();
        let rc = unsafe { needs_migration(self.db.as_ptr(), &mut out, &mut err) };
        rc_to_result(rc, err)?;
        Ok(out != 0)
    }

    /// Explicitly migrate this database to the current schema version.
    ///
    /// Opening a supported older database does not migrate it. Call this method,
    /// or run `MIGRATE DATABASE`, when maintenance code intentionally wants to
    /// apply the pending schema migration.
    ///
    /// Migration must be performed on a read-write connection.
    pub fn migrate(&self) -> Result<MigrationReport> {
        let a = velr_api()?;
        let migrate = require_runtime_symbol(a.velr_migrate, "velr_migrate")?;

        let mut raw = ffi::velr_migration_report {
            from_version: 0,
            to_version: 0,
            status: ffi::velr_migration_status::VELR_MIGRATION_ALREADY_CURRENT,
            step_count: 0,
            steps: std::ptr::null_mut(),
        };
        let mut err: *mut c_char = std::ptr::null_mut();

        let rc = unsafe { migrate(self.db.as_ptr(), &mut raw, &mut err) };
        let result = rc_to_result(rc, err).and_then(|()| {
            let status = match raw.status {
                ffi::velr_migration_status::VELR_MIGRATION_ALREADY_CURRENT => {
                    MigrationStatus::AlreadyCurrent
                }
                ffi::velr_migration_status::VELR_MIGRATION_MIGRATED => MigrationStatus::Migrated,
            };
            let steps = if raw.steps.is_null() || raw.step_count == 0 {
                Vec::new()
            } else {
                let detail = unsafe { CStr::from_ptr(raw.steps) }
                    .to_string_lossy()
                    .into_owned();
                detail
                    .split(',')
                    .filter(|step| !step.is_empty())
                    .map(str::to_string)
                    .collect()
            };

            Ok(MigrationReport {
                from_version: raw.from_version,
                to_version: raw.to_version,
                status,
                steps,
            })
        });

        if !raw.steps.is_null() {
            if let Some(clear) = a.velr_migration_report_clear {
                unsafe { clear(&mut raw) };
            } else {
                unsafe { (a.velr_string_free)(raw.steps) };
            }
        }

        result
    }

    /// Register a named embedding callback for vector indexes.
    ///
    /// Vector indexes refer to this name with
    /// `OPTIONS { indexConfig: { embedder: 'name' } }`. Velr calls the matching
    /// callback when indexed source values change and when embedding query text
    /// supplied to `CALL db.index.vector.queryNodes(...)`.
    ///
    /// The callback receives a batch of [`VectorEmbeddingInput`] values and must
    /// return one vector per input. Each returned vector must contain exactly
    /// `input.dimensions` finite `f32` values.
    ///
    pub fn register_vector_embedder<F>(&self, name: &str, embedder: F) -> Result<()>
    where
        F: Fn(&[VectorEmbeddingInput]) -> VectorEmbeddingBatchResult + 'static,
    {
        if name.trim().is_empty() {
            return Err(Error::new(
                ffi::velr_code::VELR_EARG as i32,
                "vector embedder name cannot be empty",
            ));
        }

        let a = velr_api()?;
        let register = a.velr_register_vector_embedder;

        let name_view = raw_strview(name.as_bytes());
        let boxed = Box::new(embedder);
        let user_data = Box::into_raw(boxed) as *mut c_void;
        let mut err: *mut c_char = std::ptr::null_mut();

        let rc = unsafe {
            register(
                self.db.as_ptr(),
                name_view,
                Some(vector_embedder_trampoline::<F>),
                user_data,
                Some(vector_embedder_free_trampoline::<F>),
                &mut err,
            )
        };
        // Ownership of user_data crosses into the runtime once the ABI call is made.
        rc_to_result(rc, err)
    }

    /// Execute `openCypher` and return a stream of result tables.
    ///
    /// Use [`ExecTables::next_table`] to pull tables until it returns `Ok(None)`.
    ///
    /// # Errors
    ///
    /// Returns an [`Error`] if:
    /// - `openCypher` contains an interior NUL (\0)
    /// - the runtime reports an execution/planning/parsing error
    pub fn exec<'db>(&'db self, cypher: &str) -> Result<ExecTables<'db>> {
        let a = velr_api()?;

        let cy = CString::new(cypher)
            .map_err(|_| Error::new(ffi::velr_code::VELR_EUTF as i32, "openCypher contains NUL"))?;

        let mut out_stream: *mut ffi::velr_stream = std::ptr::null_mut();
        let mut err: *mut c_char = std::ptr::null_mut();

        let rc = unsafe {
            (a.velr_exec_start)(self.db.as_ptr(), cy.as_ptr(), &mut out_stream, &mut err)
        };
        rc_to_result(rc, err)?;

        let nn = NonNull::new(out_stream).ok_or_else(|| {
            Error::new(
                ffi::velr_code::VELR_EERR as i32,
                "velr_exec_start returned null stream",
            )
        })?;

        Ok(ExecTables {
            stream: Some(nn),
            _db: PhantomData,
            _nosend: PhantomData,
        })
    }

    /// Execute `openCypher` with out-of-band result emission options.
    ///
    /// Use this when a host wants result metadata and a bounded row preview without rewriting the
    /// Cypher text. [`QueryOptions::max_result_rows`] caps rows emitted from each result table.
    /// Existing Cypher `LIMIT` clauses still apply, so the effective emitted row count is bounded
    /// by both the query and the option.
    ///
    /// `QueryOptions::max_result_rows(0)` preserves table metadata, including column names, but
    /// row cursors immediately return EOF.
    ///
    /// # Errors
    ///
    /// Returns an [`Error`] if:
    /// - `openCypher` contains an interior NUL (`\0`)
    /// - the runtime reports an execution, planning, or parsing error
    pub fn exec_with_options<'db>(
        &'db self,
        cypher: &str,
        options: QueryOptions,
    ) -> Result<ExecTables<'db>> {
        let a = velr_api()?;

        let cy = CString::new(cypher)
            .map_err(|_| Error::new(ffi::velr_code::VELR_EUTF as i32, "openCypher contains NUL"))?;
        let (raw_options, _raw_params) = raw_query_options(&options)?;

        let mut out_stream: *mut ffi::velr_stream = std::ptr::null_mut();
        let mut err: *mut c_char = std::ptr::null_mut();

        let rc = unsafe {
            (a.velr_exec_start_with_options)(
                self.db.as_ptr(),
                cy.as_ptr(),
                &raw_options,
                &mut out_stream,
                &mut err,
            )
        };
        rc_to_result(rc, err)?;

        let nn = NonNull::new(out_stream).ok_or_else(|| {
            Error::new(
                ffi::velr_code::VELR_EERR as i32,
                "velr_exec_start_with_options returned null stream",
            )
        })?;

        Ok(ExecTables {
            stream: Some(nn),
            _db: PhantomData,
            _nosend: PhantomData,
        })
    }

    /// Execute `openCypher` and return exactly one result table.
    ///
    /// This method succeeds only if executing the provided openCypher text produces exactly one
    /// result table. If execution yields zero tables or more than one table, this returns an error.
    ///
    /// Use [`Velr::exec`] to stream multiple result tables.
    ///
    /// # Errors
    ///
    /// Returns an [`Error`] if:
    /// - `openCypher` contains an interior NUL (\0)
    /// - the runtime reports an execution/planning/parsing error
    /// - the execution yields zero or multiple result tables
    pub fn exec_one(&self, cypher: &str) -> Result<TableResult> {
        let a = velr_api()?;

        let cy = CString::new(cypher)
            .map_err(|_| Error::new(ffi::velr_code::VELR_EUTF as i32, "openCypher contains NUL"))?;

        let mut out_table: *mut ffi::velr_table = std::ptr::null_mut();
        let mut err: *mut c_char = std::ptr::null_mut();

        let rc =
            unsafe { (a.velr_exec_one)(self.db.as_ptr(), cy.as_ptr(), &mut out_table, &mut err) };
        rc_to_result(rc, err)?;
        TableResult::from_raw(out_table)
    }

    /// Execute `openCypher` with options and return exactly one result table.
    ///
    /// This is the options-aware form of [`Velr::exec_one`]. It succeeds only if executing the
    /// provided openCypher text produces exactly one result table. Row emission is controlled by
    /// [`QueryOptions`]; use [`QueryOptions::max_result_rows`] with `0` to inspect column metadata
    /// without emitting rows.
    ///
    /// # Errors
    ///
    /// Returns an [`Error`] if:
    /// - `openCypher` contains an interior NUL (`\0`)
    /// - the runtime reports an execution, planning, or parsing error
    /// - the execution yields zero or multiple result tables
    pub fn exec_one_with_options(
        &self,
        cypher: &str,
        options: QueryOptions,
    ) -> Result<TableResult> {
        let a = velr_api()?;

        let cy = CString::new(cypher)
            .map_err(|_| Error::new(ffi::velr_code::VELR_EUTF as i32, "openCypher contains NUL"))?;
        let (raw_options, _raw_params) = raw_query_options(&options)?;

        let mut out_table: *mut ffi::velr_table = std::ptr::null_mut();
        let mut err: *mut c_char = std::ptr::null_mut();

        let rc = unsafe {
            (a.velr_exec_one_with_options)(
                self.db.as_ptr(),
                cy.as_ptr(),
                &raw_options,
                &mut out_table,
                &mut err,
            )
        };
        rc_to_result(rc, err)?;
        TableResult::from_raw(out_table)
    }

    /// Execute a query and discard all results.
    ///
    /// This is a convenience wrapper around [`Velr::exec`] that drains all tables and rows.
    pub fn run(&self, cypher: &str) -> Result<()> {
        let mut st = self.exec(cypher)?;
        while let Some(mut t) = st.next_table()? {
            t.for_each_row(|_| Ok(()))?;
        }
        Ok(())
    }

    /// Execute a query with options and discard emitted results.
    ///
    /// This drains all result tables like [`Velr::run`]. Query options still affect the rows that
    /// are drained, but they do not skip side effects from write queries. For example, a
    /// read-write query with `max_result_rows = 1` may emit one row while still applying all writes
    /// required by the query.
    ///
    /// # Errors
    ///
    /// Returns an [`Error`] if [`Velr::exec_with_options`] or row draining fails.
    pub fn run_with_options(&self, cypher: &str, options: QueryOptions) -> Result<()> {
        let mut st = self.exec_with_options(cypher, options)?;
        while let Some(mut t) = st.next_table()? {
            t.for_each_row(|_| Ok(()))?;
        }
        Ok(())
    }

    /// Execute `openCypher` with bound parameters and return a stream of result tables.
    ///
    /// This is a convenience wrapper around [`Velr::exec_with_options`] for the common case where
    /// only parameters are needed.
    pub fn exec_with_params<'db>(
        &'db self,
        cypher: &str,
        params: QueryParams,
    ) -> Result<ExecTables<'db>> {
        self.exec_with_options(cypher, QueryOptions::new().with_params(params))
    }

    /// Execute `openCypher` with bound parameters and return exactly one result table.
    ///
    /// This is a convenience wrapper around [`Velr::exec_one_with_options`] for the common case
    /// where only parameters are needed.
    pub fn exec_one_with_params(&self, cypher: &str, params: QueryParams) -> Result<TableResult> {
        self.exec_one_with_options(cypher, QueryOptions::new().with_params(params))
    }

    /// Execute `openCypher` with bound parameters and discard all results.
    ///
    /// This is a convenience wrapper around [`Velr::run_with_options`] for the common case where
    /// only parameters are needed.
    pub fn run_with_params(&self, cypher: &str, params: QueryParams) -> Result<()> {
        self.run_with_options(cypher, QueryOptions::new().with_params(params))
    }

    /// Build an EXPLAIN trace for `openCypher`.
    ///
    /// # Errors
    ///
    /// Returns an [`Error`] if:
    /// - `openCypher` contains an interior NUL (`\0`)
    /// - the runtime reports a planning/explain error
    pub fn explain(&self, cypher: &str) -> Result<ExplainTrace> {
        let a = velr_api()?;

        let cy = CString::new(cypher)
            .map_err(|_| Error::new(ffi::velr_code::VELR_EUTF as i32, "openCypher contains NUL"))?;

        let mut out_trace: *mut ffi::velr_explain_trace = std::ptr::null_mut();
        let mut err: *mut c_char = std::ptr::null_mut();

        let rc =
            unsafe { (a.velr_explain)(self.db.as_ptr(), cy.as_ptr(), &mut out_trace, &mut err) };
        rc_to_result(rc, err)?;
        ExplainTrace::from_raw(out_trace)
    }

    /// Build an EXPLAIN ANALYZE trace for `openCypher`.
    ///
    /// # Errors
    ///
    /// Returns an [`Error`] if:
    /// - `openCypher` contains an interior NUL (`\0`)
    /// - the runtime reports a planning/explain error
    pub fn explain_analyze(&self, cypher: &str) -> Result<ExplainTrace> {
        let a = velr_api()?;

        let cy = CString::new(cypher)
            .map_err(|_| Error::new(ffi::velr_code::VELR_EUTF as i32, "openCypher contains NUL"))?;

        let mut out_trace: *mut ffi::velr_explain_trace = std::ptr::null_mut();
        let mut err: *mut c_char = std::ptr::null_mut();

        let rc = unsafe {
            (a.velr_explain_analyze)(self.db.as_ptr(), cy.as_ptr(), &mut out_trace, &mut err)
        };
        rc_to_result(rc, err)?;
        ExplainTrace::from_raw(out_trace)
    }

    /// Begin a transaction.
    ///
    /// The transaction handle is closed automatically on drop. To explicitly finalize a
    /// transaction, use [`VelrTx::commit`] or [`VelrTx::rollback`].
    /// Begin a transaction.
    ///
    /// The transaction handle is closed automatically on drop. To explicitly finalize a
    /// transaction, use [`VelrTx::commit`] or [`VelrTx::rollback`].
    pub fn begin_tx(&self) -> Result<VelrTx<'_>> {
        let a = velr_api()?;

        let mut out_tx: *mut ffi::velr_tx = std::ptr::null_mut();
        let mut err: *mut c_char = std::ptr::null_mut();

        let rc = unsafe { (a.velr_tx_begin)(self.db.as_ptr(), &mut out_tx, &mut err) };
        rc_to_result(rc, err)?;

        let nn = NonNull::new(out_tx).ok_or_else(|| {
            Error::new(
                ffi::velr_code::VELR_EERR as i32,
                "velr_tx_begin returned null tx",
            )
        })?;

        Ok(VelrTx {
            tx: Some(nn),
            named_savepoints: RefCell::new(Vec::new()),
            _db: PhantomData,
            _nosend: PhantomData,
        })
    }

    /// Bind Arrow arrays (Arrow C Data Interface) to a logical name.
    ///
    /// Available only when built with the `arrow-ipc` feature.
    ///
    /// This transfers ownership of the provided Arrow arrays into Velr for the lifetime of the bind.
    /// (At the ABI level, the ArrowArray structs are consumed during the call.)
    #[cfg(feature = "arrow-ipc")]
    pub fn bind_arrow(
        &self,
        logical: &str,
        col_names: Vec<String>,
        arrays: Vec<Box<dyn arrow2::array::Array>>,
    ) -> Result<()> {
        arrow_bind::bind_arrow_db(self.db.as_ptr(), logical, col_names, arrays)
    }

    /// Bind Arrow IPC file bytes (Feather v2) to a logical name.
    ///
    /// Available only when built with the `arrow-ipc` feature.
    ///
    /// The IPC byte slice is borrowed only for the duration of the call. Velr decodes the IPC file
    /// and owns the resulting Arrow arrays before this returns.
    #[cfg(feature = "arrow-ipc")]
    pub fn bind_arrow_ipc(&self, logical: &str, ipc_file: &[u8]) -> Result<()> {
        arrow_bind::bind_arrow_ipc_db(self.db.as_ptr(), logical, ipc_file)
    }

    /// Bind chunked Arrow arrays per column to a logical name.
    ///
    /// Available only when built with the `arrow-ipc` feature.
    ///
    /// This transfers ownership of the provided Arrow arrays into Velr for the lifetime of the bind.
    /// (At the ABI level, the ArrowArray structs are consumed during the call.)
    ///
    /// All columns must have the same total row count (sum of chunk lengths); otherwise the bind
    /// returns an error.
    #[cfg(feature = "arrow-ipc")]
    pub fn bind_arrow_chunks(
        &self,
        logical: &str,
        col_names: Vec<String>,
        chunks_per_col: Vec<Vec<Box<dyn arrow2::array::Array>>>,
    ) -> Result<()> {
        arrow_bind::bind_arrow_chunks_db(self.db.as_ptr(), logical, col_names, chunks_per_col)
    }
}

impl Drop for Velr {
    /// Close the connection handle.
    fn drop(&mut self) {
        if let Ok(a) = velr_api() {
            unsafe { (a.velr_close)(self.db.as_ptr()) };
        }
    }
}

// -------------------------- ExecTables --------------------------

/// Streaming result of an execution that may yield multiple tables.
///
/// This is an *in-flight* type and is **`!Send` + `!Sync`** (thread-affine).
///
/// Use [`ExecTables::next_table`] to pull result tables sequentially. Dropping this value will
/// close the underlying execution stream
pub struct ExecTables<'db> {
    stream: Option<NonNull<ffi::velr_stream>>,
    _db: PhantomData<&'db Velr>,
    _nosend: PhantomData<Rc<()>>, // !Send + !Sync
}

impl<'db> ExecTables<'db> {
    /// Fetch the next result table from the execution stream.
    ///
    /// Returns:
    /// - `Ok(Some(table))` when a new table is available
    /// - `Ok(None)` when the stream is exhausted (and the runtime stream is closed)
    ///
    /// # Errors
    ///
    /// Returns an [`Error`] if the runtime reports an error while advancing the stream.
    pub fn next_table(&mut self) -> Result<Option<TableResult>> {
        let a = velr_api()?;

        let Some(stream) = self.stream else {
            return Ok(None);
        };

        let mut out_table: *mut ffi::velr_table = std::ptr::null_mut();
        let mut has: i32 = 0;
        let mut err: *mut c_char = std::ptr::null_mut();

        let rc = unsafe {
            (a.velr_stream_next_table)(stream.as_ptr(), &mut out_table, &mut has, &mut err)
        };
        rc_to_result(rc, err)?;

        if has == 0 {
            unsafe { (a.velr_exec_close)(stream.as_ptr()) };
            self.stream = None;
            return Ok(None);
        }

        TableResult::from_raw(out_table).map(Some)
    }
}

impl Drop for ExecTables<'_> {
    /// Close the underlying execution stream if still open.
    fn drop(&mut self) {
        if let Some(st) = self.stream.take() {
            if let Ok(a) = velr_api() {
                unsafe { (a.velr_exec_close)(st.as_ptr()) };
            }
        }
    }
}

// -------------------------- TableResult --------------------------

/// A single result table produced by query execution.
///
/// This is an *in-flight* type and is **`!Send` + `!Sync`** (thread-affine).
///
/// A table exposes:
/// - column metadata (names and count)
/// - row iteration via [`TableResult::rows`], [`TableResult::for_each_row`], or [`TableResult::collect`]
///
pub struct TableResult {
    table: NonNull<ffi::velr_table>,
    col_names: Vec<String>,
    col_count: usize,
    _nosend: PhantomData<Rc<()>>, // !Send + !Sync
}

impl TableResult {
    /// Construct a [`TableResult`] from a raw runtime table pointer.
    ///
    /// # Errors
    ///
    /// Returns an [`Error`] if `ptr` is null, if the runtime fails to retrieve column names,
    /// or if column name bytes are not valid UTF-8.
    fn from_raw(ptr: *mut ffi::velr_table) -> Result<Self> {
        let a = velr_api()?;

        let table = NonNull::new(ptr)
            .ok_or_else(|| Error::new(ffi::velr_code::VELR_EERR as i32, "null table"))?;

        let build = (|| -> Result<(Vec<String>, usize)> {
            let col_count = unsafe { (a.velr_table_column_count)(table.as_ptr()) };

            let mut names = Vec::with_capacity(col_count);
            for i in 0..col_count {
                let mut p: *const u8 = std::ptr::null();
                let mut len: usize = 0;

                let rc = unsafe { (a.velr_table_column_name)(table.as_ptr(), i, &mut p, &mut len) };

                if rc as i32 != ffi::velr_code::VELR_OK as i32 {
                    return Err(Error::new(
                        rc as i32,
                        format!("velr_table_column_name failed at idx={i}"),
                    ));
                }

                let bytes: &[u8] = if len == 0 {
                    &[]
                } else if p.is_null() {
                    return Err(Error::new(
                        ffi::velr_code::VELR_EERR as i32,
                        format!("column name at idx={i} is null with non-zero length"),
                    ));
                } else {
                    unsafe { std::slice::from_raw_parts(p, len) }
                };

                let s = std::str::from_utf8(bytes).map_err(|_| {
                    Error::new(
                        ffi::velr_code::VELR_EUTF as i32,
                        format!("column name at idx={i} is not valid UTF-8"),
                    )
                })?;
                names.push(s.to_string());
            }

            Ok((names, col_count))
        })();

        match build {
            Ok((col_names, col_count)) => Ok(Self {
                table,
                col_names,
                col_count,
                _nosend: PhantomData,
            }),
            Err(e) => {
                unsafe { (a.velr_table_close)(table.as_ptr()) };
                Err(e)
            }
        }
    }

    /// Return the column names for this table.
    pub fn column_names(&self) -> &[String] {
        &self.col_names
    }

    /// Return the number of columns in this table.
    pub fn column_count(&self) -> usize {
        self.col_count
    }

    /// Open a row iterator for this table.
    ///
    /// This requires `&mut self`, so only one active row iterator may exist for a table at a time.
    /// Row iteration is callback-based via [`RowIter::next`], producing a borrowed slice of
    /// [`CellRef`] for each row.
    ///
    /// # Errors
    ///
    /// Returns an [`Error`] if the runtime fails to open the row cursor.
    pub fn rows<'t>(&'t mut self) -> Result<RowIter<'t>> {
        let a = velr_api()?;

        let mut out_rows: *mut ffi::velr_rows = std::ptr::null_mut();
        let mut err: *mut c_char = std::ptr::null_mut();

        let rc = unsafe { (a.velr_table_rows_open)(self.table.as_ptr(), &mut out_rows, &mut err) };
        rc_to_result(rc, err)?;

        let nn = NonNull::new(out_rows).ok_or_else(|| {
            Error::new(ffi::velr_code::VELR_EERR as i32, "rows_open returned null")
        })?;

        Ok(RowIter {
            rows: Some(nn),
            col_count: self.col_count,
            buf: vec![
                ffi::velr_cell {
                    ty: ffi::velr_cell_type::VELR_NULL,
                    i64_: 0,
                    f64_: 0.0,
                    ptr: std::ptr::null(),
                    len: 0,
                };
                self.col_count
            ],
            _table: PhantomData,
            _nosend: PhantomData,
        })
    }

    /// Visit each row in this table.
    ///
    /// The callback receives a slice of [`CellRef`] representing the row’s cells.
    /// The borrow is scoped to the callback invocation (and remains valid until the next row is fetched).
    pub fn for_each_row<F>(&mut self, mut on_row: F) -> Result<()>
    where
        F: for<'row> FnMut(&[CellRef<'row>]) -> Result<()>,
    {
        let mut it = self.rows()?;
        while it.next(|cells| on_row(cells))? {}
        Ok(())
    }

    /// Map each row to a value and collect into a vector.
    ///
    /// This is a convenience wrapper around [`TableResult::for_each_row`].
    pub fn collect<T, F>(&mut self, mut map: F) -> Result<Vec<T>>
    where
        F: for<'row> FnMut(&[CellRef<'row>]) -> Result<T>,
    {
        let mut out = Vec::new();
        self.for_each_row(|cells| {
            out.push(map(cells)?);
            Ok(())
        })?;
        Ok(out)
    }

    /// Encode this table as an Arrow IPC file in memory.
    ///
    /// Available only when built with the `arrow-ipc` feature.
    ///
    /// Returns the IPC file bytes produced by the runtime.
    #[cfg(feature = "arrow-ipc")]
    pub fn to_arrow_ipc_file(&mut self) -> Result<Vec<u8>> {
        let a = velr_api()?;

        let mut ptr: *mut u8 = std::ptr::null_mut();
        let mut len: usize = 0;
        let mut err: *mut c_char = std::ptr::null_mut();

        let rc = unsafe {
            (a.velr_table_ipc_file_malloc)(self.table.as_ptr(), &mut ptr, &mut len, &mut err)
        };
        rc_to_result(rc, err)?;
        take_owned_bytes(a, ptr, len, "velr_table_ipc_file_malloc")
    }
}

impl Drop for TableResult {
    /// Close the table handle.
    fn drop(&mut self) {
        if let Ok(a) = velr_api() {
            unsafe { (a.velr_table_close)(self.table.as_ptr()) };
        }
    }
}

// -------------------------- RowIter --------------------------

/// Iterator over rows of a table.
///
/// This is an *in-flight* type and is **`!Send` + `!Sync`** (thread-affine).
///
/// Rows are produced via [`RowIter::next`], which invokes a callback with a borrowed slice of
/// [`CellRef`].
pub struct RowIter<'t> {
    rows: Option<NonNull<ffi::velr_rows>>,
    col_count: usize,
    buf: Vec<ffi::velr_cell>,
    _table: PhantomData<&'t mut TableResult>,
    _nosend: PhantomData<Rc<()>>, // !Send + !Sync
}

impl<'t> RowIter<'t> {
    /// Advance to the next row and invoke `on_row`.
    ///
    /// Returns:
    /// - `Ok(true)` if a row was produced and `on_row` was called
    /// - `Ok(false)` if the iterator is exhausted
    ///
    /// ## Lifetimes
    ///
    /// For `CellRef::Text` and `CellRef::Json`, the returned byte slices remain valid until the next
    /// call to [`RowIter::next`] on the same iterator (or until the iterator is dropped).
    ///
    /// # Errors
    ///
    /// Returns an [`Error`] if the runtime reports an error while advancing.
    pub fn next<F>(&mut self, on_row: F) -> Result<bool>
    where
        F: for<'row> FnOnce(&[CellRef<'row>]) -> Result<()>,
    {
        let a = velr_api()?;

        let Some(rows) = self.rows else {
            return Ok(false);
        };

        let mut written: usize = 0;
        let mut err: *mut c_char = std::ptr::null_mut();

        let rc = unsafe {
            (a.velr_rows_next)(
                rows.as_ptr(),
                self.buf.as_mut_ptr(),
                self.buf.len(),
                &mut written,
                &mut err,
            )
        };

        if rc == 0 {
            free_unexpected_err(err);
            unsafe { (a.velr_rows_close)(rows.as_ptr()) };
            self.rows = None;
            return Ok(false);
        }
        if rc < 0 {
            let msg = unsafe { take_err(err) };
            return Err(Error::new(rc, msg));
        }

        free_unexpected_err(err);

        if written > self.buf.len() {
            return Err(Error::new(
                ffi::velr_code::VELR_EERR as i32,
                format!(
                    "velr_rows_next reported {} cells, buffer holds {}",
                    written,
                    self.buf.len()
                ),
            ));
        }

        let mut scratch: Vec<CellRef<'_>> = Vec::with_capacity(written);
        for c in self.buf.iter().take(written) {
            let cell = match c.ty {
                ffi::velr_cell_type::VELR_NULL => CellRef::Null,
                ffi::velr_cell_type::VELR_BOOL => CellRef::Bool(c.i64_ != 0),
                ffi::velr_cell_type::VELR_INT64 => CellRef::Integer(c.i64_),
                ffi::velr_cell_type::VELR_DOUBLE => CellRef::Float(c.f64_),

                ffi::velr_cell_type::VELR_TEXT => {
                    let b: &[u8] = if c.len == 0 {
                        &[]
                    } else if c.ptr.is_null() {
                        return Err(Error::new(
                            ffi::velr_code::VELR_EERR as i32,
                            "VELR_TEXT cell had null pointer with non-zero length",
                        ));
                    } else {
                        unsafe { std::slice::from_raw_parts(c.ptr, c.len) }
                    };
                    CellRef::Text(b)
                }

                ffi::velr_cell_type::VELR_JSON => {
                    let b: &[u8] = if c.len == 0 {
                        &[]
                    } else if c.ptr.is_null() {
                        return Err(Error::new(
                            ffi::velr_code::VELR_EERR as i32,
                            "VELR_JSON cell had null pointer with non-zero length",
                        ));
                    } else {
                        unsafe { std::slice::from_raw_parts(c.ptr, c.len) }
                    };
                    CellRef::Json(b)
                }
            };
            scratch.push(cell);
        }

        on_row(&scratch)?;
        Ok(true)
    }
}

impl Drop for RowIter<'_> {
    fn drop(&mut self) {
        if let Some(r) = self.rows.take() {
            if let Ok(a) = velr_api() {
                unsafe { (a.velr_rows_close)(r.as_ptr()) };
            }
        }
    }
}

#[derive(Debug)]
struct NamedSavepoint {
    name: String,
    sp: NonNull<ffi::velr_sp>,
}
// -------------------------- Transactions --------------------------
//

/// A transaction handle (thread-affine).
///
/// Finalization:
/// - [`VelrTx::commit`] consumes `self` and commits.
/// - [`VelrTx::rollback`] consumes `self` and rolls back.
///
/// ## Drop behavior
///
/// If a transaction is dropped without an explicit commit/rollback, the runtime rolls it back.
pub struct VelrTx<'db> {
    tx: Option<NonNull<ffi::velr_tx>>,
    named_savepoints: RefCell<Vec<NamedSavepoint>>,
    _db: PhantomData<&'db Velr>,
    _nosend: PhantomData<Rc<()>>, // !Send + !Sync
}

impl<'db> VelrTx<'db> {
    fn ptr(&self) -> Result<NonNull<ffi::velr_tx>> {
        self.tx
            .ok_or_else(|| Error::new(ffi::velr_code::VELR_ESTATE as i32, "tx already consumed"))
    }

    fn find_named_index(&self, name: &str) -> Option<usize> {
        self.named_savepoints
            .borrow()
            .iter()
            .position(|sp| sp.name == name)
    }

    /// Execute `openCypher` within this transaction and return a stream of result tables.
    ///
    /// See [`Velr::exec`] for general streaming semantics.
    pub fn exec<'tx>(&'tx self, cypher: &str) -> Result<ExecTablesTx<'tx>> {
        let a = velr_api()?;

        let tx = self.ptr()?;
        let cy = CString::new(cypher)
            .map_err(|_| Error::new(ffi::velr_code::VELR_EUTF as i32, "openCypher contains NUL"))?;

        let mut out_stream: *mut ffi::velr_stream_tx = std::ptr::null_mut();
        let mut err: *mut c_char = std::ptr::null_mut();

        let rc =
            unsafe { (a.velr_tx_exec_start)(tx.as_ptr(), cy.as_ptr(), &mut out_stream, &mut err) };
        rc_to_result(rc, err)?;

        let nn = NonNull::new(out_stream).ok_or_else(|| {
            Error::new(
                ffi::velr_code::VELR_EERR as i32,
                "tx_exec_start returned null stream",
            )
        })?;

        Ok(ExecTablesTx {
            stream: Some(nn),
            _tx: PhantomData,
            _nosend: PhantomData,
        })
    }

    /// Execute `openCypher` within this transaction with out-of-band result emission options.
    ///
    /// Transactional semantics match [`VelrTx::exec`]. [`QueryOptions::max_result_rows`] caps
    /// emitted rows per result table without rewriting the Cypher text. Existing Cypher `LIMIT`
    /// clauses still apply.
    ///
    /// # Errors
    ///
    /// Returns an [`Error`] if:
    /// - the transaction is no longer active
    /// - `openCypher` contains an interior NUL (`\0`)
    /// - the runtime reports an execution, planning, or parsing error
    pub fn exec_with_options<'tx>(
        &'tx self,
        cypher: &str,
        options: QueryOptions,
    ) -> Result<ExecTablesTx<'tx>> {
        let a = velr_api()?;

        let tx = self.ptr()?;
        let cy = CString::new(cypher)
            .map_err(|_| Error::new(ffi::velr_code::VELR_EUTF as i32, "openCypher contains NUL"))?;
        let (raw_options, _raw_params) = raw_query_options(&options)?;

        let mut out_stream: *mut ffi::velr_stream_tx = std::ptr::null_mut();
        let mut err: *mut c_char = std::ptr::null_mut();

        let rc = unsafe {
            (a.velr_tx_exec_start_with_options)(
                tx.as_ptr(),
                cy.as_ptr(),
                &raw_options,
                &mut out_stream,
                &mut err,
            )
        };
        rc_to_result(rc, err)?;

        let nn = NonNull::new(out_stream).ok_or_else(|| {
            Error::new(
                ffi::velr_code::VELR_EERR as i32,
                "tx_exec_start_with_options returned null stream",
            )
        })?;

        Ok(ExecTablesTx {
            stream: Some(nn),
            _tx: PhantomData,
            _nosend: PhantomData,
        })
    }

    /// Execute a query expected to produce exactly one table within this transaction.
    ///
    /// This method is implemented by streaming (`exec`) and validating that exactly one table is
    /// produced. If you expect multiple tables, use [`VelrTx::exec`].
    pub fn exec_one(&self, cypher: &str) -> Result<TableResult> {
        let mut st = self.exec(cypher)?;
        let first = match st.next_table()? {
            Some(t) => t,
            None => {
                return Err(Error::new(
                    ffi::velr_code::VELR_EERR as i32,
                    "query produced no result tables",
                ))
            }
        };
        if st.next_table()?.is_some() {
            return Err(Error::new(
                ffi::velr_code::VELR_EERR as i32,
                "query produced multiple tables; use exec()",
            ));
        }
        Ok(first)
    }

    /// Execute a query with options and require exactly one result table.
    ///
    /// This is the options-aware form of [`VelrTx::exec_one`]. It succeeds only if executing the
    /// provided openCypher text produces exactly one result table. Use
    /// [`QueryOptions::max_result_rows`] with `0` to inspect column metadata without emitting rows.
    ///
    /// # Errors
    ///
    /// Returns an [`Error`] if:
    /// - the transaction is no longer active
    /// - `openCypher` contains an interior NUL (`\0`)
    /// - the loaded runtime does not expose the transaction query-options ABI
    /// - the runtime reports an execution, planning, or parsing error
    /// - the execution yields zero or multiple result tables
    pub fn exec_one_with_options(
        &self,
        cypher: &str,
        options: QueryOptions,
    ) -> Result<TableResult> {
        let mut st = self.exec_with_options(cypher, options)?;
        let first = match st.next_table()? {
            Some(t) => t,
            None => {
                return Err(Error::new(
                    ffi::velr_code::VELR_EERR as i32,
                    "query produced no result tables",
                ))
            }
        };
        if st.next_table()?.is_some() {
            return Err(Error::new(
                ffi::velr_code::VELR_EERR as i32,
                "query produced multiple tables; use exec()",
            ));
        }
        Ok(first)
    }

    /// Execute a query within this transaction and discard all results.
    pub fn run(&self, cypher: &str) -> Result<()> {
        let mut st = self.exec(cypher)?;
        while let Some(mut t) = st.next_table()? {
            t.for_each_row(|_| Ok(()))?;
        }
        Ok(())
    }

    /// Execute a query with options inside this transaction and discard results.
    ///
    /// This drains all result tables like [`VelrTx::run`]. Query options cap only emitted rows;
    /// they do not skip query side effects.
    ///
    /// # Errors
    ///
    /// Returns an [`Error`] if [`VelrTx::exec_with_options`] or row draining fails.
    pub fn run_with_options(&self, cypher: &str, options: QueryOptions) -> Result<()> {
        let mut st = self.exec_with_options(cypher, options)?;
        while let Some(mut t) = st.next_table()? {
            t.for_each_row(|_| Ok(()))?;
        }
        Ok(())
    }

    /// Execute `openCypher` with bound parameters inside this transaction.
    ///
    /// This is a convenience wrapper around [`VelrTx::exec_with_options`] for the common case
    /// where only parameters are needed.
    pub fn exec_with_params<'tx>(
        &'tx self,
        cypher: &str,
        params: QueryParams,
    ) -> Result<ExecTablesTx<'tx>> {
        self.exec_with_options(cypher, QueryOptions::new().with_params(params))
    }

    /// Execute `openCypher` with bound parameters inside this transaction and require one table.
    ///
    /// This is a convenience wrapper around [`VelrTx::exec_one_with_options`] for the common case
    /// where only parameters are needed.
    pub fn exec_one_with_params(&self, cypher: &str, params: QueryParams) -> Result<TableResult> {
        self.exec_one_with_options(cypher, QueryOptions::new().with_params(params))
    }

    /// Execute `openCypher` with bound parameters inside this transaction and discard results.
    ///
    /// This is a convenience wrapper around [`VelrTx::run_with_options`] for the common case where
    /// only parameters are needed.
    pub fn run_with_params(&self, cypher: &str, params: QueryParams) -> Result<()> {
        self.run_with_options(cypher, QueryOptions::new().with_params(params))
    }

    /// Build an EXPLAIN trace for `openCypher`.
    ///
    /// # Errors
    ///
    /// Returns an [`Error`] if:
    /// - `openCypher` contains an interior NUL (`\0`)
    /// - the runtime reports a planning/explain error
    pub fn explain(&self, cypher: &str) -> Result<ExplainTrace> {
        let a = velr_api()?;
        let tx = self.ptr()?;

        let cy = CString::new(cypher)
            .map_err(|_| Error::new(ffi::velr_code::VELR_EUTF as i32, "openCypher contains NUL"))?;

        let mut out_trace: *mut ffi::velr_explain_trace = std::ptr::null_mut();
        let mut err: *mut c_char = std::ptr::null_mut();

        let rc = unsafe { (a.velr_tx_explain)(tx.as_ptr(), cy.as_ptr(), &mut out_trace, &mut err) };
        rc_to_result(rc, err)?;
        ExplainTrace::from_raw(out_trace)
    }

    /// Build an EXPLAIN ANALYZE trace for `openCypher`.
    ///
    /// # Errors
    ///
    /// Returns an [`Error`] if:
    /// - `openCypher` contains an interior NUL (`\0`)
    /// - the runtime reports a planning/explain error
    pub fn explain_analyze(&self, cypher: &str) -> Result<ExplainTrace> {
        let a = velr_api()?;
        let tx = self.ptr()?;

        let cy = CString::new(cypher)
            .map_err(|_| Error::new(ffi::velr_code::VELR_EUTF as i32, "openCypher contains NUL"))?;

        let mut out_trace: *mut ffi::velr_explain_trace = std::ptr::null_mut();
        let mut err: *mut c_char = std::ptr::null_mut();

        let rc = unsafe {
            (a.velr_tx_explain_analyze)(tx.as_ptr(), cy.as_ptr(), &mut out_trace, &mut err)
        };
        rc_to_result(rc, err)?;
        ExplainTrace::from_raw(out_trace)
    }

    /// Commit this transaction.
    ///
    /// Consumes the transaction handle. After this call, the transaction is finalized and cannot be
    /// used again.
    ///
    /// Note: the underlying C ABI consumes the transaction handle even if an error is returned.
    pub fn commit(mut self) -> Result<()> {
        let a = velr_api()?;

        // After commit the runtime transaction owns final cleanup of any outstanding named savepoints.
        self.named_savepoints.get_mut().clear();

        let tx = self
            .tx
            .take()
            .ok_or_else(|| Error::new(ffi::velr_code::VELR_ESTATE as i32, "tx already consumed"))?;

        let mut err: *mut c_char = std::ptr::null_mut();
        let rc = unsafe { (a.velr_tx_commit)(tx.as_ptr(), &mut err) };
        rc_to_result(rc, err)
    }

    /// Roll back this transaction.
    ///
    /// Consumes the transaction handle. After this call, the transaction is finalized and cannot be
    /// used again.
    ///
    /// Note: the underlying C ABI consumes the transaction handle even if an error is returned.
    pub fn rollback(mut self) -> Result<()> {
        let a = velr_api()?;

        // After rollback the runtime transaction owns final cleanup of any outstanding named savepoints.
        self.named_savepoints.get_mut().clear();

        let tx = self
            .tx
            .take()
            .ok_or_else(|| Error::new(ffi::velr_code::VELR_ESTATE as i32, "tx already consumed"))?;

        let mut err: *mut c_char = std::ptr::null_mut();
        let rc = unsafe { (a.velr_tx_rollback)(tx.as_ptr(), &mut err) };
        rc_to_result(rc, err)
    }

    fn create_named_savepoint_raw(&self, name: &str) -> Result<NonNull<ffi::velr_sp>> {
        let a = velr_api()?;
        let tx = self.ptr()?;

        let cname = CString::new(name).map_err(|_| {
            Error::new(
                ffi::velr_code::VELR_EUTF as i32,
                "savepoint name contains NUL",
            )
        })?;

        let mut out_sp: *mut ffi::velr_sp = std::ptr::null_mut();
        let mut err: *mut c_char = std::ptr::null_mut();

        let rc = unsafe {
            (a.velr_tx_savepoint_named)(tx.as_ptr(), cname.as_ptr(), &mut out_sp, &mut err)
        };
        rc_to_result(rc, err)?;

        NonNull::new(out_sp).ok_or_else(|| {
            Error::new(
                ffi::velr_code::VELR_EERR as i32,
                "savepoint_named returned null",
            )
        })
    }

    /// Create an unnamed scoped savepoint inside this transaction.
    ///
    /// The returned handle is RAII-managed:
    /// - call [`VelrSavepoint::release`] to keep the work since the savepoint
    /// - call [`VelrSavepoint::rollback`] to undo back to the savepoint
    /// - dropping the handle rolls back to the savepoint and releases it
    pub fn savepoint<'tx>(&'tx self) -> Result<VelrSavepoint<'tx>> {
        let a = velr_api()?;

        let tx = self.ptr()?;
        let mut out_sp: *mut ffi::velr_sp = std::ptr::null_mut();
        let mut err: *mut c_char = std::ptr::null_mut();

        let rc = unsafe { (a.velr_tx_savepoint)(tx.as_ptr(), &mut out_sp, &mut err) };
        rc_to_result(rc, err)?;

        let nn = NonNull::new(out_sp).ok_or_else(|| {
            Error::new(ffi::velr_code::VELR_EERR as i32, "savepoint returned null")
        })?;

        Ok(VelrSavepoint {
            sp: Some(nn),
            _tx: PhantomData,
            _nosend: PhantomData,
        })
    }

    /// Create a detached named savepoint inside this transaction.
    ///
    /// Unlike [`VelrTx::savepoint`], this does not return a guard. The named savepoint remains
    /// active in the transaction until:
    /// - [`VelrTx::rollback_to`] rolls back to it
    /// - [`VelrTx::release_savepoint`] explicitly releases it
    /// - the transaction is committed, rolled back, or dropped
    ///
    /// Active names must be unique within the transaction.
    pub fn savepoint_named(&self, name: &str) -> Result<()> {
        if self.find_named_index(name).is_some() {
            return Err(Error::new(
                ffi::velr_code::VELR_ESTATE as i32,
                format!("named savepoint {name:?} already exists"),
            ));
        }

        let sp = self.create_named_savepoint_raw(name)?;

        self.named_savepoints.borrow_mut().push(NamedSavepoint {
            name: name.to_string(),
            sp,
        });

        Ok(())
    }

    /// Roll back to a previously-created named savepoint.
    ///
    /// Driver semantics:
    /// - all newer named savepoints are discarded
    /// - the target named savepoint remains active after rollback
    ///
    /// This is implemented using the stored savepoint handle, because the runtime's
    /// `velr_tx_rollback_to(...)` is not guaranteed to interoperate with savepoints
    /// created through `velr_tx_savepoint_named(...)`.
    pub fn rollback_to(&self, name: &str) -> Result<()> {
        let idx = self.find_named_index(name).ok_or_else(|| {
            Error::new(
                ffi::velr_code::VELR_ESTATE as i32,
                format!("no such active named savepoint {name:?}"),
            )
        })?;

        let target_name = {
            let named = self.named_savepoints.borrow();
            named[idx].name.clone()
        };

        let target_sp = {
            let named = self.named_savepoints.borrow();
            named[idx].sp
        };

        // Roll back using the savepoint handle itself. This consumes the runtime savepoint
        // and invalidates any newer savepoints as part of the rollback.
        let a = velr_api()?;
        let mut err: *mut c_char = std::ptr::null_mut();
        let rc = unsafe { (a.velr_sp_rollback)(target_sp.as_ptr(), &mut err) };
        rc_to_result(rc, err)?;

        // After a successful rollback:
        // - savepoints before idx are still valid
        // - the target savepoint handle is consumed
        // - newer savepoints are invalid
        {
            let mut named = self.named_savepoints.borrow_mut();
            named.truncate(idx);
        }

        // Recreate the target savepoint so it remains active after rollback.
        // This matches the external API semantics we want.
        let recreated = self.create_named_savepoint_raw(&target_name)?;
        self.named_savepoints.borrow_mut().push(NamedSavepoint {
            name: target_name,
            sp: recreated,
        });

        Ok(())
    }

    /// Release the most recently-created active named savepoint.
    ///
    /// Releasing a non-topmost named savepoint is intentionally rejected here to keep the driver
    /// semantics simple and well-defined.
    pub fn release_savepoint(&self, name: &str) -> Result<()> {
        let a = velr_api()?;

        let mut named = self.named_savepoints.borrow_mut();
        let last_idx = named.len().checked_sub(1).ok_or_else(|| {
            Error::new(
                ffi::velr_code::VELR_ESTATE as i32,
                "no active named savepoints",
            )
        })?;

        if named[last_idx].name != name {
            return Err(Error::new(
                ffi::velr_code::VELR_ESTATE as i32,
                format!(
                    "release_savepoint({name:?}) requires {name:?} to be the most recent active named savepoint"
                ),
            ));
        }

        let entry = named.pop().unwrap();

        let mut err: *mut c_char = std::ptr::null_mut();
        let rc = unsafe { (a.velr_sp_release)(entry.sp.as_ptr(), &mut err) };
        rc_to_result(rc, err)
    }

    /// Bind Arrow arrays (Arrow C Data Interface) to a logical name.
    ///
    /// Available only when built with the `arrow-ipc` feature.
    ///
    /// This consumes the exported ArrowArray values at the ABI boundary.
    /// Callers must not reuse or release those exported ArrowArray values after the call.
    /// (At the ABI level, the ArrowArray structs are consumed during the call.)
    #[cfg(feature = "arrow-ipc")]
    pub fn bind_arrow(
        &self,
        logical: &str,
        col_names: Vec<String>,
        arrays: Vec<Box<dyn arrow2::array::Array>>,
    ) -> Result<()> {
        let tx = self.ptr()?;
        arrow_bind::bind_arrow_tx(tx.as_ptr(), logical, col_names, arrays)
    }

    /// Bind Arrow IPC file bytes (Feather v2) to a logical name inside this transaction.
    ///
    /// Available only when built with the `arrow-ipc` feature.
    ///
    /// The IPC byte slice is borrowed only for the duration of the call. Velr decodes the IPC file
    /// and owns the resulting Arrow arrays before this returns.
    #[cfg(feature = "arrow-ipc")]
    pub fn bind_arrow_ipc(&self, logical: &str, ipc_file: &[u8]) -> Result<()> {
        let tx = self.ptr()?;
        arrow_bind::bind_arrow_ipc_tx(tx.as_ptr(), logical, ipc_file)
    }

    /// Bind chunked Arrow arrays per column to a logical name.
    ///
    /// Available only when built with the `arrow-ipc` feature.
    ///
    /// This transfers ownership of the provided Arrow arrays into Velr for the lifetime of the bind.
    /// (At the ABI level, the ArrowArray structs are consumed during the call.)
    ///
    /// All columns must have the same total row count (sum of chunk lengths); otherwise the bind
    /// returns an error.
    #[cfg(feature = "arrow-ipc")]
    pub fn bind_arrow_chunks(
        &self,
        logical: &str,
        col_names: Vec<String>,
        chunks_per_col: Vec<Vec<Box<dyn arrow2::array::Array>>>,
    ) -> Result<()> {
        let tx = self.ptr()?;
        arrow_bind::bind_arrow_chunks_tx(tx.as_ptr(), logical, col_names, chunks_per_col)
    }
}

impl Drop for VelrTx<'_> {
    /// Close the transaction handle if still open.
    fn drop(&mut self) {
        // Do not attempt to individually close named savepoints here; the transaction finalization
        // owns that cleanup.
        self.named_savepoints.get_mut().clear();

        if let Some(tx) = self.tx.take() {
            if let Ok(a) = velr_api() {
                unsafe { (a.velr_tx_close)(tx.as_ptr()) };
            }
        }
    }
}

// -------------------------- ExecTablesTx --------------------------
//

/// Streaming result of an execution within a transaction.
///
/// This is an *in-flight* type and is **`!Send` + `!Sync`** (thread-affine).
pub struct ExecTablesTx<'tx> {
    stream: Option<NonNull<ffi::velr_stream_tx>>,
    _tx: PhantomData<&'tx VelrTx<'tx>>,
    _nosend: PhantomData<Rc<()>>, // !Send + !Sync
}

impl ExecTablesTx<'_> {
    /// Fetch the next result table from the transaction execution stream.
    ///
    /// Returns `Ok(None)` when exhausted (and closes the underlying stream).
    pub fn next_table(&mut self) -> Result<Option<TableResult>> {
        let a = velr_api()?;

        let Some(stream) = self.stream else {
            return Ok(None);
        };

        let mut out_table: *mut ffi::velr_table = std::ptr::null_mut();
        let mut has: i32 = 0;
        let mut err: *mut c_char = std::ptr::null_mut();

        let rc = unsafe {
            (a.velr_stream_tx_next_table)(stream.as_ptr(), &mut out_table, &mut has, &mut err)
        };
        rc_to_result(rc, err)?;

        if has == 0 {
            unsafe { (a.velr_exec_tx_close)(stream.as_ptr()) };
            self.stream = None;
            return Ok(None);
        }

        TableResult::from_raw(out_table).map(Some)
    }
}

impl Drop for ExecTablesTx<'_> {
    /// Close the underlying transaction execution stream if still open.
    fn drop(&mut self) {
        if let Some(st) = self.stream.take() {
            if let Ok(a) = velr_api() {
                unsafe { (a.velr_exec_tx_close)(st.as_ptr()) };
            }
        }
    }
}
// -------------------------- Savepoints --------------------------
//

/// A scoped savepoint handle within a transaction (thread-affine).
///
/// This is the RAII/scoped savepoint API:
/// - [`VelrTx::savepoint`] creates one
/// - [`VelrSavepoint::release`] keeps the work since the savepoint
/// - [`VelrSavepoint::rollback`] undoes back to the savepoint
///
/// ## Drop behavior
///
/// If dropped without explicit release/rollback, the runtime rolls back to the savepoint and
/// releases it.
#[must_use = "savepoint guards are RAII; bind the returned value to a variable or explicitly call release()/rollback()"]
pub struct VelrSavepoint<'tx> {
    sp: Option<NonNull<ffi::velr_sp>>,
    _tx: PhantomData<&'tx VelrTx<'tx>>,
    _nosend: PhantomData<Rc<()>>, // !Send + !Sync
}

impl VelrSavepoint<'_> {
    /// Release this savepoint.
    ///
    /// Consumes the savepoint handle. After this call, the savepoint is finalized and cannot be used
    /// again.
    ///
    /// Note: the underlying C ABI consumes the savepoint handle even if an error is returned.
    pub fn release(mut self) -> Result<()> {
        let a = velr_api()?;

        let sp = self.sp.take().ok_or_else(|| {
            Error::new(
                ffi::velr_code::VELR_ESTATE as i32,
                "savepoint already consumed",
            )
        })?;

        let mut err: *mut c_char = std::ptr::null_mut();
        let rc = unsafe { (a.velr_sp_release)(sp.as_ptr(), &mut err) };
        rc_to_result(rc, err)
    }

    /// Roll back to this savepoint and release it.
    ///
    /// Consumes the savepoint handle. After this call, the savepoint is finalized and cannot be used
    /// again.
    ///
    /// Note: the underlying C ABI consumes the savepoint handle even if an error is returned.
    pub fn rollback(mut self) -> Result<()> {
        let a = velr_api()?;

        let sp = self.sp.take().ok_or_else(|| {
            Error::new(
                ffi::velr_code::VELR_ESTATE as i32,
                "savepoint already consumed",
            )
        })?;

        let mut err: *mut c_char = std::ptr::null_mut();
        let rc = unsafe { (a.velr_sp_rollback)(sp.as_ptr(), &mut err) };
        rc_to_result(rc, err)
    }
}

impl Drop for VelrSavepoint<'_> {
    /// Close the savepoint handle if still open.
    fn drop(&mut self) {
        if let Some(sp) = self.sp.take() {
            if let Ok(a) = velr_api() {
                unsafe { (a.velr_sp_close)(sp.as_ptr()) };
            }
        }
    }
}

// -------------------------- Arrow binding helpers --------------------------
/// Arrow binding support.
///
/// This module is only compiled with the `arrow-ipc` feature enabled.
///
/// It exports Arrow arrays/schemas using `arrow2`’s Arrow C Data Interface helpers and passes
/// them to the Velr runtime ABI. The code uses `ManuallyDrop` to avoid dropping the exported
/// `ArrowArray` values after the call; this matches an ownership-transfer pattern typical of
/// the Arrow C Data Interface (the runtime is expected to manage release thereafter).

#[cfg(feature = "arrow-ipc")]
mod arrow_bind {
    use super::*;
    use std::mem::ManuallyDrop;

    use arrow2::{
        array::Array,
        datatypes::Field,
        ffi::{export_array_to_c, export_field_to_c, ArrowArray, ArrowSchema},
    };

    fn cstring(s: &str, what: &str) -> Result<CString> {
        CString::new(s).map_err(|_| {
            Error::new(
                ffi::velr_code::VELR_EUTF as i32,
                format!("{what} contains NUL"),
            )
        })
    }

    pub fn bind_arrow_db(
        db: *mut ffi::velr_db,
        logical: &str,
        col_names: Vec<String>,
        arrays: Vec<Box<dyn Array>>,
    ) -> Result<()> {
        let a = super::velr_api()?;
        bind_arrow_common(
            |logical_ptr, schemas_pp, arrays_pp, names_ptr, n, err| unsafe {
                (a.velr_bind_arrow)(db, logical_ptr, schemas_pp, arrays_pp, names_ptr, n, err)
            },
            logical,
            col_names,
            arrays,
        )
    }

    pub fn bind_arrow_tx(
        tx: *mut ffi::velr_tx,
        logical: &str,
        col_names: Vec<String>,
        arrays: Vec<Box<dyn Array>>,
    ) -> Result<()> {
        let a = super::velr_api()?;
        bind_arrow_common(
            |logical_ptr, schemas_pp, arrays_pp, names_ptr, n, err| unsafe {
                (a.velr_tx_bind_arrow)(tx, logical_ptr, schemas_pp, arrays_pp, names_ptr, n, err)
            },
            logical,
            col_names,
            arrays,
        )
    }

    pub fn bind_arrow_ipc_db(db: *mut ffi::velr_db, logical: &str, ipc_file: &[u8]) -> Result<()> {
        let a = super::velr_api()?;
        bind_arrow_ipc_common(
            |logical_ptr, ipc_ptr, ipc_len, err| unsafe {
                (a.velr_bind_arrow_ipc)(db, logical_ptr, ipc_ptr, ipc_len, err)
            },
            logical,
            ipc_file,
        )
    }

    pub fn bind_arrow_ipc_tx(tx: *mut ffi::velr_tx, logical: &str, ipc_file: &[u8]) -> Result<()> {
        let a = super::velr_api()?;
        bind_arrow_ipc_common(
            |logical_ptr, ipc_ptr, ipc_len, err| unsafe {
                (a.velr_tx_bind_arrow_ipc)(tx, logical_ptr, ipc_ptr, ipc_len, err)
            },
            logical,
            ipc_file,
        )
    }

    fn bind_arrow_ipc_common(
        f: impl FnOnce(*const c_char, *const u8, usize, *mut *mut c_char) -> ffi::velr_code,
        logical: &str,
        ipc_file: &[u8],
    ) -> Result<()> {
        if ipc_file.is_empty() {
            return Err(Error::new(
                ffi::velr_code::VELR_EARG as i32,
                "bind_arrow_ipc: empty IPC buffer",
            ));
        }

        let logical_c = cstring(logical, "logical")?;
        let mut err: *mut c_char = std::ptr::null_mut();
        let rc = f(
            logical_c.as_ptr(),
            ipc_file.as_ptr(),
            ipc_file.len(),
            &mut err,
        );
        super::rc_to_result(rc, err)
    }

    fn bind_arrow_common(
        f: impl FnOnce(
            *const c_char,
            *const *const ArrowSchema,
            *const *const ArrowArray,
            *const ffi::velr_strview,
            usize,
            *mut *mut c_char,
        ) -> ffi::velr_code,
        logical: &str,
        col_names: Vec<String>,
        arrays: Vec<Box<dyn Array>>,
    ) -> Result<()> {
        if col_names.is_empty() {
            return Err(Error::new(
                ffi::velr_code::VELR_EARG as i32,
                "bind_arrow: no columns",
            ));
        }
        if arrays.len() != col_names.len() {
            return Err(Error::new(
                ffi::velr_code::VELR_EARG as i32,
                format!(
                    "bind_arrow: arrays len {} != col_names len {}",
                    arrays.len(),
                    col_names.len()
                ),
            ));
        }

        let logical_c = cstring(logical, "logical")?;

        let mut schemas: Vec<ArrowSchema> = Vec::with_capacity(col_names.len());
        let mut array_cs: Vec<ManuallyDrop<ArrowArray>> = Vec::with_capacity(col_names.len());
        let mut schema_ptrs: Vec<*const ArrowSchema> = Vec::with_capacity(col_names.len());
        let mut array_ptrs: Vec<*const ArrowArray> = Vec::with_capacity(col_names.len());
        let mut name_views: Vec<ffi::velr_strview> = Vec::with_capacity(col_names.len());

        for (name, arr) in col_names.iter().zip(arrays.into_iter()) {
            let field = Field::new(name.clone(), arr.data_type().clone(), true);
            let schema = export_field_to_c(&field);
            schemas.push(schema);

            let a = ManuallyDrop::new(export_array_to_c(arr));
            array_cs.push(a);
        }

        for i in 0..col_names.len() {
            schema_ptrs.push(&schemas[i] as *const ArrowSchema);
            array_ptrs.push((&*array_cs[i]) as *const ArrowArray);

            let b = col_names[i].as_bytes();
            name_views.push(ffi::velr_strview {
                ptr: b.as_ptr(),
                len: b.len(),
            });
        }

        let mut err: *mut c_char = std::ptr::null_mut();
        let rc = f(
            logical_c.as_ptr(),
            schema_ptrs.as_ptr(),
            array_ptrs.as_ptr(),
            name_views.as_ptr(),
            col_names.len(),
            &mut err,
        );
        super::rc_to_result(rc, err)
    }

    pub fn bind_arrow_chunks_db(
        db: *mut ffi::velr_db,
        logical: &str,
        col_names: Vec<String>,
        chunks_per_col: Vec<Vec<Box<dyn Array>>>,
    ) -> Result<()> {
        let a = super::velr_api()?;
        bind_chunks_common(
            |logical_ptr, cols_ptr, names_ptr, n, err| unsafe {
                (a.velr_bind_arrow_chunks)(db, logical_ptr, cols_ptr, names_ptr, n, err)
            },
            logical,
            col_names,
            chunks_per_col,
        )
    }

    pub fn bind_arrow_chunks_tx(
        tx: *mut ffi::velr_tx,
        logical: &str,
        col_names: Vec<String>,
        chunks_per_col: Vec<Vec<Box<dyn Array>>>,
    ) -> Result<()> {
        let a = super::velr_api()?;
        bind_chunks_common(
            |logical_ptr, cols_ptr, names_ptr, n, err| unsafe {
                (a.velr_tx_bind_arrow_chunks)(tx, logical_ptr, cols_ptr, names_ptr, n, err)
            },
            logical,
            col_names,
            chunks_per_col,
        )
    }

    fn bind_chunks_common(
        f: impl FnOnce(
            *const c_char,
            *const ffi::velr_arrow_chunks,
            *const ffi::velr_strview,
            usize,
            *mut *mut c_char,
        ) -> ffi::velr_code,
        logical: &str,
        col_names: Vec<String>,
        chunks_per_col: Vec<Vec<Box<dyn Array>>>,
    ) -> Result<()> {
        if col_names.is_empty() {
            return Err(Error::new(
                ffi::velr_code::VELR_EARG as i32,
                "bind_arrow_chunks: no columns",
            ));
        }
        if chunks_per_col.len() != col_names.len() {
            return Err(Error::new(
                ffi::velr_code::VELR_EARG as i32,
                format!(
                    "bind_arrow_chunks: chunks_per_col {} != col_names {}",
                    chunks_per_col.len(),
                    col_names.len()
                ),
            ));
        }

        let logical_c = cstring(logical, "logical")?;

        let mut all_schema_storage: Vec<Vec<ArrowSchema>> = Vec::with_capacity(col_names.len());
        let mut all_array_storage: Vec<Vec<ManuallyDrop<ArrowArray>>> =
            Vec::with_capacity(col_names.len());
        let mut all_schema_ptrs: Vec<Vec<*const ArrowSchema>> = Vec::with_capacity(col_names.len());
        let mut all_array_ptrs: Vec<Vec<*const ArrowArray>> = Vec::with_capacity(col_names.len());

        for (ci, chunks) in chunks_per_col.into_iter().enumerate() {
            if chunks.is_empty() {
                return Err(Error::new(
                    ffi::velr_code::VELR_EARG as i32,
                    format!("bind_arrow_chunks: col {ci} has 0 chunks"),
                ));
            }

            let mut schemas: Vec<ArrowSchema> = Vec::with_capacity(chunks.len());
            let mut arrays: Vec<ManuallyDrop<ArrowArray>> = Vec::with_capacity(chunks.len());

            for arr in chunks.into_iter() {
                let field = Field::new(col_names[ci].clone(), arr.data_type().clone(), true);
                schemas.push(export_field_to_c(&field));
                arrays.push(ManuallyDrop::new(export_array_to_c(arr)));
            }

            let mut sp: Vec<*const ArrowSchema> = Vec::with_capacity(schemas.len());
            let mut ap: Vec<*const ArrowArray> = Vec::with_capacity(arrays.len());
            for i in 0..schemas.len() {
                sp.push(&schemas[i] as *const ArrowSchema);
                ap.push((&*arrays[i]) as *const ArrowArray);
            }

            all_schema_storage.push(schemas);
            all_array_storage.push(arrays);
            all_schema_ptrs.push(sp);
            all_array_ptrs.push(ap);
        }

        let mut cols_desc: Vec<ffi::velr_arrow_chunks> = Vec::with_capacity(col_names.len());
        for i in 0..col_names.len() {
            cols_desc.push(ffi::velr_arrow_chunks {
                schemas: all_schema_ptrs[i].as_ptr(),
                arrays: all_array_ptrs[i].as_ptr(),
                chunk_count: all_schema_ptrs[i].len(),
            });
        }

        let mut name_views: Vec<ffi::velr_strview> = Vec::with_capacity(col_names.len());
        for name in &col_names {
            let b = name.as_bytes();
            name_views.push(ffi::velr_strview {
                ptr: b.as_ptr(),
                len: b.len(),
            });
        }

        let mut err: *mut c_char = std::ptr::null_mut();
        let rc = f(
            logical_c.as_ptr(),
            cols_desc.as_ptr(),
            name_views.as_ptr(),
            col_names.len(),
            &mut err,
        );
        super::rc_to_result(rc, err)
    }
}