remdb 0.3.1

嵌入式内存数据库
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
#![allow(non_snake_case)]

use crate::config::DbConfig;
use crate::transaction::{IsolationLevel, TransactionType};
use crate::types::{DataType, FieldDef, TableDef, Value};

#[cfg(feature = "log")]
use crate::log::debug;

/// C API: 数据类型枚举
#[repr(u8)]
#[derive(Copy, Clone, PartialEq)]
pub enum RemDbDataType {
    UInt8 = 0,
    UInt16 = 1,
    UInt32 = 2,
    UInt64 = 3,
    Float32 = 4,
    Float64 = 5,
    Bool = 6,
    Timestamp = 7,
    String = 8,
    Json = 9,
    Vector = 10,
}

impl From<RemDbDataType> for DataType {
    fn from(c_type: RemDbDataType) -> Self {
        match c_type {
            RemDbDataType::UInt8 => DataType::UInt8,
            RemDbDataType::UInt16 => DataType::UInt16,
            RemDbDataType::UInt32 => DataType::UInt32,
            RemDbDataType::UInt64 => DataType::UInt64,
            RemDbDataType::Float32 => DataType::Float32,
            RemDbDataType::Float64 => DataType::Float64,
            RemDbDataType::Bool => DataType::Bool,
            RemDbDataType::Timestamp => DataType::Timestamp,
            RemDbDataType::String => DataType::VarChar,
            RemDbDataType::Json => DataType::Json,
            RemDbDataType::Vector => DataType::Vector,
        }
    }
}

/// C API: 最大字符串长度
pub const REMDB_MAX_STRING_LEN: usize = 64;

/// 当前全局数据库中的用户表数量(不包含 db.init() 自动创建的系统表)。
/// C API 的 table_id 只引用用户表,系统表属于数据库内部实现细节。
static mut C_API_USER_TABLE_COUNT: usize = 0;

/// 获取当前全局数据库中的用户表数量
///
/// # Safety
///
/// 访问全局静态变量,要求外部同步(C API 使用场景为单线程初始化)
unsafe fn c_api_user_table_count() -> usize {
    C_API_USER_TABLE_COUNT
}

/// C API: 通用值类型
#[repr(C)]
pub union RemDbValue {
    pub u8: u8,
    pub u16: u16,
    pub u32: u32,
    pub u64: u64,
    pub float32: f32,
    pub float64: f64,
    pub boolean: u8,
    pub timestamp: u64,
    pub string: [u8; REMDB_MAX_STRING_LEN],
    pub json: RemDbJsonValue,
    pub vector: RemDbVectorValue,
}

/// C API: JSON值类型
#[repr(C)]
#[derive(Copy, Clone)]
pub struct RemDbJsonValue {
    pub pool_id: u8,
    pub offset: u32,
    pub length: u32,
}

/// C API: Vector值类型
#[repr(C)]
#[derive(Copy, Clone)]
pub struct RemDbVectorValue {
    pub pool_id: u8,
    pub offset: u32,
    pub length: u32,
}

impl From<Value> for RemDbValue {
    fn from(rust_value: Value) -> Self {
        unsafe {
            // 注意:Value是union,直接访问第一个字段作为默认值
            // 实际使用中,应该根据字段的数据类型来访问正确的union字段
            RemDbValue {
                u32: rust_value.u32,
            }
        }
    }
}

impl From<RemDbValue> for Value {
    fn from(c_value: RemDbValue) -> Self {
        // 注意:这个转换需要知道具体的数据类型才能安全进行
        // 在实际使用中,应该根据字段的数据类型来选择合适的变体
        // 这里提供一个默认实现,实际使用时需要根据上下文调整
        unsafe { Value { u32: c_value.u32 } }
    }
}

/// C API: 字段定义
#[repr(C)]
pub struct RemDbFieldDef {
    pub name: *const u8,
    pub data_type: RemDbDataType,
    pub size: usize,
    pub offset: usize,
}

impl From<&FieldDef> for RemDbFieldDef {
    fn from(rust_field: &FieldDef) -> Self {
        RemDbFieldDef {
            name: rust_field.name.as_ptr(),
            data_type: match rust_field.data_type {
                DataType::UInt8 => RemDbDataType::UInt8,
                DataType::UInt16 => RemDbDataType::UInt16,
                DataType::UInt32 => RemDbDataType::UInt32,
                DataType::UInt64 => RemDbDataType::UInt64,
                DataType::Int8 => RemDbDataType::UInt8, // 映射为无符号类型
                DataType::Int16 => RemDbDataType::UInt16, // 映射为无符号类型
                DataType::Int32 => RemDbDataType::UInt32, // 映射为无符号类型
                DataType::Int64 => RemDbDataType::UInt64, // 映射为无符号类型
                DataType::Float32 => RemDbDataType::Float32,
                DataType::Float64 => RemDbDataType::Float64,
                DataType::Bool => RemDbDataType::Bool,
                DataType::Timestamp => RemDbDataType::Timestamp,
                DataType::TimestampTZ => RemDbDataType::Timestamp, // 映射为Timestamp
                DataType::VarChar | DataType::Char | DataType::Text => RemDbDataType::String,
                DataType::Interval => RemDbDataType::UInt64, // 映射为UInt64
                DataType::Vector => RemDbDataType::Vector,   // 映射为Vector类型
                DataType::Json => RemDbDataType::Json,       // 映射为Json类型
            },
            size: rust_field.size,
            offset: rust_field.offset,
        }
    }
}

/// C API: 表定义
#[repr(C)]
pub struct RemDbTableDef {
    pub id: u8,
    pub name: *const u8,
    pub fields: *const RemDbFieldDef,
    pub fields_count: usize,
    pub primary_key: usize,
    pub secondary_index: i32,
    pub record_size: usize,
    pub max_records: usize,
}

/// C API: HA角色枚举
#[cfg(feature = "ha")]
#[repr(u8)]
#[derive(Copy, Clone)]
pub enum RemDbHARole {
    Master = 0,
    Slave = 1,
    Auto = 2,
}

#[cfg(feature = "ha")]
impl From<RemDbHARole> for crate::ha::HARole {
    fn from(c_role: RemDbHARole) -> Self {
        match c_role {
            RemDbHARole::Master => crate::ha::HARole::Master,
            RemDbHARole::Slave => crate::ha::HARole::Slave,
            RemDbHARole::Auto => crate::ha::HARole::Auto,
        }
    }
}

/// C API: 复制模式枚举
#[cfg(feature = "ha")]
#[repr(u8)]
#[derive(Copy, Clone)]
pub enum RemDbReplicationMode {
    Async = 0,
    Sync = 1,
}

#[cfg(feature = "ha")]
impl From<RemDbReplicationMode> for crate::ha::ReplicationMode {
    fn from(c_mode: RemDbReplicationMode) -> Self {
        match c_mode {
            RemDbReplicationMode::Async => crate::ha::ReplicationMode::Async,
            RemDbReplicationMode::Sync => crate::ha::ReplicationMode::Sync,
        }
    }
}

/// C API: HA配置
#[cfg(feature = "ha")]
#[repr(C)]
pub struct RemDbHAConfig {
    pub ha_role: RemDbHARole,
    pub replication_mode: RemDbReplicationMode,
    pub heartbeat_interval_ms: u32,
    pub failure_detection_ms: u32,
    pub sync_timeout_ms: u32,
    pub master_address: *const u8, // 字符串形式的IP地址
    pub master_port: u16,
    pub replication_port: u16,
    pub heartbeat_port: u16,
    pub node_id: u32,
}

/// C API: 数据库配置
#[repr(C)]
pub struct RemDbConfig {
    pub tables: *const RemDbTableDef,
    pub tables_count: usize,
    pub time_series_tables: *const RemDbTimeSeriesTableDef,
    pub time_series_tables_count: usize,
    pub total_memory: usize,
    pub low_power_mode_supported: u8,
    pub low_power_max_records: i32,
    pub ha_config: *const core::ffi::c_void, // 可选的HA配置,使用void*以避免依赖特定特性
}

/// C API: 数据库句柄类型别名
pub type RemDbHandle = *mut crate::RemDb;

/// C API: 事务类型
#[repr(u8)]
pub enum RemDbTransactionType {
    ReadOnly = 0,
    ReadWrite = 1,
}

impl From<RemDbTransactionType> for TransactionType {
    fn from(c_type: RemDbTransactionType) -> Self {
        match c_type {
            RemDbTransactionType::ReadOnly => TransactionType::ReadOnly,
            RemDbTransactionType::ReadWrite => TransactionType::ReadWrite,
        }
    }
}

/// C API: 隔离级别
#[repr(u8)]
pub enum RemDbIsolationLevel {
    ReadUncommitted = 0,
    ReadCommitted = 1,
    RepeatableRead = 2,
    Serializable = 3,
}

impl From<RemDbIsolationLevel> for IsolationLevel {
    fn from(c_level: RemDbIsolationLevel) -> Self {
        match c_level {
            RemDbIsolationLevel::ReadUncommitted => IsolationLevel::ReadUncommitted,
            RemDbIsolationLevel::ReadCommitted => IsolationLevel::ReadCommitted,
            RemDbIsolationLevel::RepeatableRead => IsolationLevel::RepeatableRead,
            RemDbIsolationLevel::Serializable => IsolationLevel::Serializable,
        }
    }
}

/// C API: 数据库指标快照
#[repr(C)]
pub struct RemDbMetricsSnapshot {
    pub total_memory: usize,
    pub used_memory: usize,
    pub read_ops: u64,
    pub write_ops: u64,
    pub delete_ops: u64,
    pub update_ops: u64,
    pub cache_hits: u64,
    pub cache_misses: u64,
    pub index_lookups: u64,
    pub index_inserts: u64,
    pub index_deletes: u64,
    pub transactions: u64,
    pub committed_transactions: u64,
    pub rolled_back_transactions: u64,
    pub start_time: u64,
}

impl From<crate::DbMetricsSnapshot> for RemDbMetricsSnapshot {
    fn from(rust_snapshot: crate::DbMetricsSnapshot) -> Self {
        RemDbMetricsSnapshot {
            total_memory: rust_snapshot.total_memory,
            used_memory: rust_snapshot.used_memory,
            read_ops: rust_snapshot.read_ops as u64,
            write_ops: rust_snapshot.write_ops as u64,
            delete_ops: rust_snapshot.delete_ops as u64,
            update_ops: rust_snapshot.update_ops as u64,
            cache_hits: rust_snapshot.cache_hits as u64,
            cache_misses: rust_snapshot.cache_misses as u64,
            index_lookups: rust_snapshot.index_lookups as u64,
            index_inserts: rust_snapshot.index_inserts as u64,
            index_deletes: rust_snapshot.index_deletes as u64,
            transactions: rust_snapshot.transactions as u64,
            committed_transactions: rust_snapshot.committed_transactions as u64,
            rolled_back_transactions: rust_snapshot.rolled_back_transactions as u64,
            start_time: 0, // 占位符,实际值需要根据DbMetricsSnapshot结构体调整
        }
    }
}

/// C API: 健康状态
#[repr(u8)]
pub enum RemDbHealthStatus {
    Healthy = 0,
    Warning = 1,
    Unhealthy = 2,
}

impl From<crate::HealthStatus> for RemDbHealthStatus {
    fn from(rust_status: crate::HealthStatus) -> Self {
        match rust_status {
            crate::HealthStatus::Healthy => RemDbHealthStatus::Healthy,
            crate::HealthStatus::Warning => RemDbHealthStatus::Warning,
            crate::HealthStatus::Unhealthy => RemDbHealthStatus::Unhealthy,
        }
    }
}

/// C API: 健康检查结果
#[repr(C)]
pub struct RemDbHealthCheckResult {
    pub status: RemDbHealthStatus,
    pub metrics: RemDbMetricsSnapshot,
    pub details: *const u8,
}

impl From<crate::HealthCheckResult> for RemDbHealthCheckResult {
    fn from(rust_result: crate::HealthCheckResult) -> Self {
        RemDbHealthCheckResult {
            status: rust_result.status.into(),
            metrics: rust_result.metrics.into(),
            details: rust_result.details.as_ptr(),
        }
    }
}

/// C API: 数据库状态枚举
#[repr(u8)]
pub enum RemDbDatabaseStatus {
    Created = 0,
    Open = 1,
    Closed = 2,
    Dropped = 3,
}

impl From<crate::DatabaseStatus> for RemDbDatabaseStatus {
    fn from(rust_status: crate::DatabaseStatus) -> Self {
        match rust_status {
            crate::DatabaseStatus::Created => RemDbDatabaseStatus::Created,
            crate::DatabaseStatus::Open => RemDbDatabaseStatus::Open,
            crate::DatabaseStatus::Closed => RemDbDatabaseStatus::Closed,
            crate::DatabaseStatus::Dropped => RemDbDatabaseStatus::Dropped,
        }
    }
}

/// C API: 数据库信息结构体
#[repr(C)]
pub struct RemDbDatabaseInfo {
    pub name: *const u8,
    pub database_type: *const u8,
    pub status: RemDbDatabaseStatus,
    pub table_count: usize,
    pub memory_usage: usize,
}

impl From<crate::DatabaseInfo> for RemDbDatabaseInfo {
    fn from(rust_info: crate::DatabaseInfo) -> Self {
        RemDbDatabaseInfo {
            name: rust_info.name.as_ptr(),
            database_type: rust_info.database_type.as_ptr(),
            status: rust_info.status.into(),
            table_count: rust_info.table_count,
            memory_usage: rust_info.memory_usage,
        }
    }
}

/// C API: 数据库配置结构体
#[repr(C)]
pub struct RemDbDatabaseConfig {
    pub name: *const u8,
    pub memory_limit: *const usize,
    pub max_tables: *const usize,
    pub wal_mode: *const u8,
    pub default_index_type: *const u8,
    pub temp_store: *const u8,
}

/// C API: 类型化值
#[repr(C)]
pub struct RemDbTypedValue {
    pub data_type: RemDbDataType,
    pub value: RemDbValue,
}

impl From<crate::types::TypedValue> for RemDbTypedValue {
    fn from(rust_value: crate::types::TypedValue) -> Self {
        use crate::DataType;

        let data_type = match rust_value.value_type {
            DataType::UInt8 => RemDbDataType::UInt8,
            DataType::UInt16 => RemDbDataType::UInt16,
            DataType::UInt32 => RemDbDataType::UInt32,
            DataType::UInt64 => RemDbDataType::UInt64,
            DataType::Int8 => RemDbDataType::UInt8, // 映射为无符号类型
            DataType::Int16 => RemDbDataType::UInt16, // 映射为无符号类型
            DataType::Int32 => RemDbDataType::UInt32, // 映射为无符号类型
            DataType::Int64 => RemDbDataType::UInt64, // 映射为无符号类型
            DataType::Float32 => RemDbDataType::Float32,
            DataType::Float64 => RemDbDataType::Float64,
            DataType::Bool => RemDbDataType::Bool,
            DataType::Timestamp => RemDbDataType::Timestamp,
            DataType::TimestampTZ => RemDbDataType::Timestamp, // 映射为Timestamp
            DataType::VarChar | DataType::Char | DataType::Text => RemDbDataType::String,
            DataType::Interval => RemDbDataType::UInt64, // 映射为UInt64
            DataType::Vector => RemDbDataType::Vector,   // 映射为Vector类型
            DataType::Json => {
                // 内联JSON存储为String类型,以便C API直接读取
                // 外部JSON仍使用Json类型,通过pool管理器访问
                unsafe {
                    match rust_value.value.json_storage {
                        crate::types::JsonStorage::Inline(_) | crate::types::JsonStorage::Null => {
                            RemDbDataType::String
                        }
                        crate::types::JsonStorage::External { .. } => RemDbDataType::Json,
                    }
                }
            }
        };

        let value = unsafe {
            match rust_value.value_type {
                DataType::UInt8 => RemDbValue {
                    u8: rust_value.value.u8,
                },
                DataType::UInt16 => RemDbValue {
                    u16: rust_value.value.u16,
                },
                DataType::UInt32 => RemDbValue {
                    u32: rust_value.value.u32,
                },
                DataType::UInt64 => RemDbValue {
                    u64: rust_value.value.u64,
                },
                DataType::Int8 => RemDbValue {
                    u8: rust_value.value.i8 as u8,
                },
                DataType::Int16 => RemDbValue {
                    u16: rust_value.value.i16 as u16,
                },
                DataType::Int32 => RemDbValue {
                    u32: rust_value.value.i32 as u32,
                },
                DataType::Int64 => RemDbValue {
                    u64: rust_value.value.i64 as u64,
                },
                DataType::Float32 => RemDbValue {
                    float32: rust_value.value.float32,
                },
                DataType::Float64 => RemDbValue {
                    float64: rust_value.value.float64,
                },
                DataType::Bool => RemDbValue {
                    boolean: rust_value.value.bool as u8,
                },
                DataType::Timestamp => RemDbValue {
                    timestamp: rust_value.value.timestamp,
                },
                DataType::TimestampTZ => RemDbValue {
                    timestamp: rust_value.value.timestamp,
                },
                DataType::Interval => RemDbValue {
                    u64: rust_value.value.interval.value as u64,
                },
                DataType::VarChar | DataType::Char | DataType::Text => {
                    let mut string = [0u8; REMDB_MAX_STRING_LEN];
                    let src = &rust_value.value.string;
                    let len = core::cmp::min(src.len(), REMDB_MAX_STRING_LEN);
                    string[..len].copy_from_slice(&src[..len]);
                    RemDbValue { string }
                }
                DataType::Vector => {
                    // Vector storage mapping to RemDbVectorValue
                    RemDbValue {
                        vector: RemDbVectorValue {
                            pool_id: 0,
                            offset: 0,
                            length: 0,
                        },
                    }
                }
                DataType::Json => {
                    // JSON storage mapping to C API value
                    let json_storage = rust_value.value.json_storage;
                    match json_storage {
                        crate::types::JsonStorage::Inline(data) => {
                            // Inline JSON: store as string for direct C API access
                            let mut string = [0u8; REMDB_MAX_STRING_LEN];
                            let actual_len = match data.iter().position(|&b| b == 0) {
                                Some(pos) => pos,
                                None => data.len(),
                            };
                            let copy_len = core::cmp::min(actual_len, REMDB_MAX_STRING_LEN);
                            string[..copy_len].copy_from_slice(&data[..copy_len]);
                            RemDbValue { string }
                        }
                        crate::types::JsonStorage::External {
                            pool_id,
                            offset,
                            length,
                        } => RemDbValue {
                            json: RemDbJsonValue {
                                pool_id,
                                offset,
                                length,
                            },
                        },
                        crate::types::JsonStorage::Null => {
                            // Null JSON: store as empty string
                            RemDbValue {
                                string: [0u8; REMDB_MAX_STRING_LEN],
                            }
                        }
                    }
                }
            }
        };

        RemDbTypedValue { data_type, value }
    }
}

/// C API: 结果行
#[repr(C)]
pub struct RemDbResultRow {
    pub values: *const RemDbTypedValue,
    pub values_count: usize,
}

/// C API: 结果集
#[repr(C)]
pub struct RemDbResultSet {
    pub columns: *const *const u8,
    pub columns_count: usize,
    pub rows: *const RemDbResultRow,
    pub rows_count: usize,
}

/// C API: UDP模式枚举
#[repr(u8)]
#[derive(Copy, Clone)]
pub enum RemDbUdpMode {
    Unicast = 0,
    Broadcast = 1,
    Multicast = 2,
}

impl From<RemDbUdpMode> for crate::pubsub::UdpMode {
    fn from(c_mode: RemDbUdpMode) -> Self {
        match c_mode {
            RemDbUdpMode::Unicast => crate::pubsub::UdpMode::Unicast,
            RemDbUdpMode::Broadcast => crate::pubsub::UdpMode::Broadcast,
            RemDbUdpMode::Multicast => crate::pubsub::UdpMode::Multicast,
        }
    }
}

/// C API: 压缩类型枚举
#[repr(u8)]
#[derive(Copy, Clone)]
pub enum RemDbCompressionType {
    None = 0,
    DeltaRunLength = 1,
    Snappy = 2,
}

impl From<RemDbCompressionType> for crate::time_series::CompressionType {
    fn from(c_type: RemDbCompressionType) -> Self {
        match c_type {
            RemDbCompressionType::None => crate::time_series::CompressionType::None,
            RemDbCompressionType::DeltaRunLength => {
                crate::time_series::CompressionType::DeltaRunLength
            }
            RemDbCompressionType::Snappy => crate::time_series::CompressionType::DeltaRunLength, // 不支持Snappy,使用DeltaRunLength替代
        }
    }
}

/// C API: 时序数据记录
#[repr(C)]
#[derive(Clone, Copy)]
pub struct RemDbTimeSeriesRecord {
    pub timestamp: u64,
    pub value: f64,
    pub tag_count: u8,
    pub tags: [u64; 8],
}

impl From<RemDbTimeSeriesRecord> for crate::time_series::TimeSeriesRecord {
    fn from(c_record: RemDbTimeSeriesRecord) -> Self {
        crate::time_series::TimeSeriesRecord {
            timestamp: c_record.timestamp,
            value: c_record.value,
            tag_count: c_record.tag_count,
            tags: c_record.tags,
        }
    }
}

impl From<crate::time_series::TimeSeriesRecord> for RemDbTimeSeriesRecord {
    fn from(rust_record: crate::time_series::TimeSeriesRecord) -> Self {
        RemDbTimeSeriesRecord {
            timestamp: rust_record.timestamp,
            value: rust_record.value,
            tag_count: rust_record.tag_count,
            tags: rust_record.tags,
        }
    }
}

/// C API: 时序数据配置
#[repr(C)]
#[derive(Clone, Copy)]
pub struct RemDbTimeSeriesConfig {
    pub partition_duration_secs: u64,
    pub retention_period_secs: u64,
    pub compression: RemDbCompressionType,
    pub max_partitions: usize,
}

impl From<RemDbTimeSeriesConfig> for crate::time_series::TimeSeriesConfig {
    fn from(c_config: RemDbTimeSeriesConfig) -> Self {
        crate::time_series::TimeSeriesConfig {
            partition_duration_secs: c_config.partition_duration_secs,
            retention_period_secs: c_config.retention_period_secs,
            compression: c_config.compression.into(),
            max_partitions: c_config.max_partitions,
        }
    }
}

/// C API: 时序表定义
#[repr(C)]
pub struct RemDbTimeSeriesTableDef {
    pub id: u8,
    pub name: *const u8,
    pub fields: *const RemDbFieldDef,
    pub fields_count: usize,
    pub primary_key: usize,
    pub secondary_index: i32,
    pub record_size: usize,
    pub max_records: usize,
    pub time_field: usize,
    pub value_field: usize,
    pub tag_fields: *const usize,
    pub tag_fields_count: usize,
    pub config: RemDbTimeSeriesConfig,
}

/// C API: 发布/订阅配置
#[repr(C)]
pub struct RemDbPubSubConfig {
    pub udp_mode: RemDbUdpMode,
    pub multicast_addr: *const u8, // 字符串形式的IP地址
    pub port: u16,
    pub max_topics: usize,
    pub max_subscribers_per_topic: usize,
    pub buffer_size: usize,
    pub enable_nack: u8,
    pub retransmit_timeout_ms: u32,
    pub max_retransmits: usize,
    pub heartbeat_interval_secs: u32,
    pub frame_pool_size: usize,
}

/// C API: 订阅回调函数类型
type RemDbPubSubCallback = extern "C" fn(topic_id: u16, data: *const u8, data_len: usize) -> u8;

/// 内部: 保存C回调的全局存储
static mut C_CALLBACK_STORAGE: Option<RemDbPubSubCallback> = None;

/// C API: 错误码
#[repr(u32)]
pub enum RemDbError {
    Success = 0,
    OutOfMemory = 1,
    RecordNotFound = 2,
    DuplicateKey = 3,
    FieldNotFound = 4,
    TypeMismatch = 5,
    TransactionError = 6,
    ConfigError = 7,
    UnsupportedOperation = 8,
    FileIoError = 9,
    SnapshotFormatError = 10,
    Crc32Error = 11,
    LogFormatError = 12,
    LogRecordNotFound = 13,
    LogChecksumError = 14,
    LockConflict = 15,
    LockTimeout = 16,
    TableNotFound = 17,
    InvalidRecordSize = 18,
    /// 参数错误
    InvalidParameter = 19,
    // PubSub相关错误
    PubSubInitFailed = 20,
    PubSubNetworkError = 21,
    PubSubInvalidParameter = 22,
    PubSubResourceExhausted = 23,
    PubSubInvalidFrameFormat = 24,
    PubSubCrcCheckFailed = 25,
    PubSubTopicNotFound = 26,
    PubSubSubscriptionNotFound = 27,
    /// 操作不允许
    NotAllowed = 28,
}

impl From<crate::RemDbError> for RemDbError {
    fn from(rust_error: crate::RemDbError) -> Self {
        match rust_error {
            crate::RemDbError::OutOfMemory => RemDbError::OutOfMemory,
            crate::RemDbError::RecordNotFound => RemDbError::RecordNotFound,
            crate::RemDbError::DuplicateKey => RemDbError::DuplicateKey,
            crate::RemDbError::FieldNotFound => RemDbError::FieldNotFound,
            crate::RemDbError::TypeMismatch => RemDbError::TypeMismatch,
            crate::RemDbError::NotNullViolation => RemDbError::TypeMismatch, // 映射为TypeMismatch
            crate::RemDbError::TransactionError => RemDbError::TransactionError,
            crate::RemDbError::ConfigError => RemDbError::ConfigError,
            crate::RemDbError::NotAllowed => RemDbError::NotAllowed,
            crate::RemDbError::UnsupportedOperation => RemDbError::UnsupportedOperation,
            crate::RemDbError::FileIoError => RemDbError::FileIoError,
            crate::RemDbError::SnapshotFormatError => RemDbError::SnapshotFormatError,
            crate::RemDbError::Crc32Error => RemDbError::Crc32Error,
            crate::RemDbError::LogFormatError => RemDbError::LogFormatError,
            crate::RemDbError::LogRecordNotFound => RemDbError::LogRecordNotFound,
            crate::RemDbError::LogChecksumError => RemDbError::LogChecksumError,
            crate::RemDbError::LockConflict => RemDbError::LockConflict,
            crate::RemDbError::LockTimeout => RemDbError::LockTimeout,
            crate::RemDbError::TableNotFound => RemDbError::TableNotFound,
            crate::RemDbError::InvalidRecordSize => RemDbError::InvalidRecordSize,
            crate::RemDbError::InvalidSqlQuery => RemDbError::UnsupportedOperation,
            crate::RemDbError::InternalError => RemDbError::UnsupportedOperation,
            crate::RemDbError::NoRecordsToOverwrite => RemDbError::RecordNotFound,
            crate::RemDbError::TwoMoreIndexNotSupported => RemDbError::ConfigError, // 映射为ConfigError
            crate::RemDbError::DatabaseNotFound => RemDbError::ConfigError, // 映射为ConfigError
            crate::RemDbError::DatabaseExists => RemDbError::DuplicateKey,  // 映射为DuplicateKey
            crate::RemDbError::DatabaseClosed => RemDbError::ConfigError,   // 映射为ConfigError
            crate::RemDbError::MaxDatabasesReached => RemDbError::ConfigError, // 映射为ConfigError
            crate::RemDbError::InvalidConfig(_) => RemDbError::ConfigError,
            crate::RemDbError::CompressionError => RemDbError::ConfigError,
            crate::RemDbError::InvalidArgument => RemDbError::InvalidParameter,
            crate::RemDbError::InvalidState => RemDbError::InvalidParameter,
            crate::RemDbError::PlatformNotInitialized => RemDbError::UnsupportedOperation,
            crate::RemDbError::LockError => RemDbError::LockConflict,
            crate::RemDbError::InvalidPointer => RemDbError::InvalidParameter,
            crate::RemDbError::InvalidData(_) => RemDbError::InvalidParameter,
            crate::RemDbError::VariableSizeType => RemDbError::UnsupportedOperation,
            crate::RemDbError::ProtocolError(_) => RemDbError::UnsupportedOperation,
            crate::RemDbError::UnexpectedNone(_) => RemDbError::UnsupportedOperation,
        }
    }
}

impl From<crate::pubsub::PubSubError> for RemDbError {
    fn from(rust_error: crate::pubsub::PubSubError) -> Self {
        match rust_error {
            crate::pubsub::PubSubError::InitFailed => RemDbError::PubSubInitFailed,
            crate::pubsub::PubSubError::NetworkError => RemDbError::PubSubNetworkError,
            crate::pubsub::PubSubError::InvalidParameter => RemDbError::PubSubInvalidParameter,
            crate::pubsub::PubSubError::ResourceExhausted => RemDbError::PubSubResourceExhausted,
            crate::pubsub::PubSubError::InvalidFrameFormat => RemDbError::PubSubInvalidFrameFormat,
            crate::pubsub::PubSubError::CrcCheckFailed => RemDbError::PubSubCrcCheckFailed,
            crate::pubsub::PubSubError::TopicNotFound => RemDbError::PubSubTopicNotFound,
            crate::pubsub::PubSubError::SubscriptionNotFound => {
                RemDbError::PubSubSubscriptionNotFound
            }
            crate::pubsub::PubSubError::UnsupportedOperation => RemDbError::UnsupportedOperation,
        }
    }
}

/// 从HA错误转换为C API错误
#[cfg(feature = "ha")]
impl From<crate::ha::HAError> for RemDbError {
    fn from(ha_error: crate::ha::HAError) -> Self {
        match ha_error {
            crate::ha::HAError::InitFailed => RemDbError::PubSubInitFailed,
            crate::ha::HAError::NetworkError => RemDbError::PubSubNetworkError,
            crate::ha::HAError::InvalidParameter => RemDbError::ConfigError,
            crate::ha::HAError::RoleConflict => RemDbError::UnsupportedOperation,
            crate::ha::HAError::SyncFailed => RemDbError::UnsupportedOperation,
            crate::ha::HAError::HeartbeatTimeout => RemDbError::UnsupportedOperation,
            crate::ha::HAError::ReplicationError => RemDbError::UnsupportedOperation,
            crate::ha::HAError::UnsupportedOperation => RemDbError::UnsupportedOperation,
        }
    }
}

/// C API: 从C字符串创建Rust字符串
unsafe fn c_str_to_rust(c_str: *const u8) -> alloc::string::String {
    let mut len = 0;
    while *c_str.offset(len) != 0 {
        len += 1;
    }
    let slice = core::slice::from_raw_parts(c_str, len as usize);
    alloc::string::String::from_utf8_lossy(slice).into_owned()
}

/// C API: 获取C字符串长度
unsafe fn _c_strlen(s: *const u8) -> usize {
    let mut len = 0;
    while *s.offset(len) != 0 {
        len += 1;
    }
    len as usize
}

/// C API: 初始化全局数据库实例
#[no_mangle]
pub unsafe extern "C" fn remdb_init_global(
    config: *const RemDbConfig,
    handle: *mut RemDbHandle,
) -> RemDbError {
    if config.is_null() || handle.is_null() {
        return RemDbError::ConfigError;
    }

    // 将C配置转换为Rust配置
    let c_config = &*config;

    // 初始化内存分配器
    // 分配内存用于内存池
    let total_memory = c_config.total_memory;

    // 检查内存大小是否足够
    if total_memory < 1024 * 1024 {
        // 最小1MB
        return RemDbError::OutOfMemory;
    }

    // 分配内存缓冲区
    let mut memory_buffer = alloc::vec::Vec::with_capacity(total_memory);

    // 尝试调整内存缓冲区大小
    if let Err(_) = memory_buffer.try_reserve(total_memory) {
        return RemDbError::OutOfMemory;
    }

    // 调整大小并初始化
    memory_buffer.resize(total_memory, 0);
    let memory_ptr = memory_buffer.as_mut_ptr();

    // 泄漏内存,使其成为静态内存
    core::mem::forget(memory_buffer);

    // 初始化全局内存分配器
    if let Err(e) = crate::memory::allocator::init_global_allocator(memory_ptr, total_memory) {
        return e.into();
    }

    // 检查内存分配器是否初始化成功
    let stats = crate::memory::allocator::get_memory_stats();
    if stats.total < total_memory / 2 {
        // 至少应该有一半的内存可用
        return RemDbError::OutOfMemory;
    }

    // 转换表定义
    let mut rust_tables = Vec::new();
    for i in 0..c_config.tables_count {
        let c_table = &*c_config.tables.offset(i as isize);

        // 转换字段定义
        let mut rust_fields = Vec::new();
        for j in 0..c_table.fields_count {
            let c_field = &*c_table.fields.offset(j as isize);
            rust_fields.push(FieldDef {
                name: core::str::from_utf8_unchecked(core::slice::from_raw_parts(
                    c_field.name,
                    _c_strlen(c_field.name),
                ))
                .to_string(),
                data_type: c_field.data_type.into(),
                size: c_field.size,
                string_length: None,
                offset: c_field.offset,
                primary_key: j == c_table.primary_key,
                not_null: j == c_table.primary_key, // 主键默认非空
                unique: j == c_table.primary_key,   // 主键默认唯一
                auto_increment: false,              // 默认不自增
                default_value: None,                // 默认无默认值
                vector_metadata: None,              // 默认无向量元数据
                json_metadata: None,                // 默认无JSON元数据
            });
        }

        rust_tables.push(TableDef {
            id: c_table.id,
            name: core::str::from_utf8_unchecked(core::slice::from_raw_parts(
                c_table.name,
                _c_strlen(c_table.name),
            ))
            .to_string(),
            fields: rust_fields,
            primary_key: vec![c_table.primary_key],
            secondary_index: if c_table.secondary_index == -1 {
                None
            } else {
                Some(vec![c_table.secondary_index as usize])
            },
            secondary_index_type: crate::types::IndexType::Hash,
            record_size: c_table.record_size,
            max_records: c_table.max_records,
            version: 1,
            created_at: 0,
            updated_at: 0,
        });
    }

    // 解析HA配置
    let ha_config = if !c_config.ha_config.is_null() {
        #[cfg(feature = "ha")]
        {
            let c_ha_config = &*(c_config.ha_config as *const RemDbHAConfig);

            // 解析主节点地址
            let master_address = if !c_ha_config.master_address.is_null() {
                Some(c_str_to_rust(c_ha_config.master_address))
            } else {
                None
            };

            Some(crate::ha::HAConfig {
                node_id: c_ha_config.node_id,
                ha_role: c_ha_config.ha_role.into(),
                replication_mode: c_ha_config.replication_mode.into(),
                heartbeat_interval_ms: c_ha_config.heartbeat_interval_ms as u64,
                failure_detection_ms: c_ha_config.failure_detection_ms as u64,
                sync_timeout_ms: c_ha_config.sync_timeout_ms as u64,
                master_address: master_address
                    .map(|s| Box::<str>::leak(s.into_boxed_str()) as &'static str),
                master_port: if c_ha_config.master_port == 0 {
                    None
                } else {
                    Some(c_ha_config.master_port)
                },
                replication_port: c_ha_config.replication_port,
            })
        }
        #[cfg(not(feature = "ha"))]
        {
            // HA特性未启用,忽略HA配置
            None
        }
    } else {
        None
    };

    // 创建Rust配置
    let rust_config = DbConfig {
        tables: rust_tables,
        total_memory: c_config.total_memory,
        low_power_mode_supported: c_config.low_power_mode_supported != 0,
        low_power_max_records: if c_config.low_power_max_records == -1 {
            None
        } else {
            Some(c_config.low_power_max_records as usize)
        },
        default_max_records: 1000, // 默认值
        memory_allocator: &crate::config::DefaultMemoryAllocator,
        wal_config: crate::config::WALConfig {
            log_path: "remdb.wal",
            log_mode: crate::config::LogMode::Sync,
            checkpoint_interval_ms: 60000,
            log_file_size_limit: 16 * 1024 * 1024,
            log_prealloc_size: 16 * 1024 * 1024,
            log_segment_size: 16 * 1024 * 1024,
            retained_checkpoints: 2,
            max_consecutive_invalid: 100,
            skip_threshold: 20,
            skip_block_size: 4096,
            max_skip_attempts: 10,
            compression_type: crate::config::WALCompressionType::None,
            compression_level: 3,
        },
        time_series_defaults: crate::time_series::TimeSeriesConfig::DEFAULT,
        #[cfg(feature = "pubsub")]
        pubsub_config: None,
        ha_config,

        model_worker_config: crate::config::ModelWorkerConfig::default(),
    };

    // 初始化全局数据库
    // 注意:这里需要根据实际情况调整,不能直接使用固定大小的数组
    // 实际使用中应该根据配置动态创建表、主键索引和辅助索引
    match crate::init_global_db(core::mem::transmute(&rust_config)) {
        Ok(db) => {
            *handle = db as *mut _;

            // 记录用户表数量:C API 的 table_id 只引用用户表,
            // db.init() 内部追加创建的系统表对 C API 不可见
            C_API_USER_TABLE_COUNT = c_config.tables_count;

            // 如果有时序表定义,需要初始化时序表
            let db_mut = &mut *(*handle);

            for i in 0..c_config.time_series_tables_count {
                let c_time_series_table = &*c_config.time_series_tables.offset(i as isize);

                // 转换字段定义
                let mut rust_fields = Vec::new();
                for j in 0..c_time_series_table.fields_count {
                    let c_field = &*c_time_series_table.fields.offset(j as isize);
                    rust_fields.push(FieldDef {
                        name: core::str::from_utf8_unchecked(core::slice::from_raw_parts(
                            c_field.name,
                            _c_strlen(c_field.name),
                        ))
                        .to_string(),
                        data_type: c_field.data_type.into(),
                        size: c_field.size,
                        string_length: None,
                        offset: c_field.offset,
                        primary_key: j == c_time_series_table.primary_key,
                        not_null: j == c_time_series_table.primary_key, // 主键默认非空
                        unique: j == c_time_series_table.primary_key,   // 主键默认唯一
                        auto_increment: false,                          // 默认不自增
                        default_value: None,                            // 默认无默认值
                        vector_metadata: None,                          // 默认无向量元数据
                        json_metadata: None,                            // 默认无JSON元数据
                    });
                }

                // 转换标签字段索引
                let mut rust_tag_fields = Vec::new();
                for j in 0..c_time_series_table.tag_fields_count {
                    let tag_field = *c_time_series_table.tag_fields.offset(j as isize);
                    rust_tag_fields.push(tag_field);
                }

                // 创建基础表定义
                let base_table_def = TableDef {
                    id: c_time_series_table.id,
                    name: core::str::from_utf8_unchecked(core::slice::from_raw_parts(
                        c_time_series_table.name,
                        _c_strlen(c_time_series_table.name),
                    ))
                    .to_string(),
                    fields: rust_fields,
                    primary_key: vec![c_time_series_table.primary_key],
                    secondary_index: if c_time_series_table.secondary_index == -1 {
                        None
                    } else {
                        Some(vec![c_time_series_table.secondary_index as usize])
                    },
                    secondary_index_type: crate::types::IndexType::Hash,
                    record_size: c_time_series_table.record_size,
                    max_records: c_time_series_table.max_records,
                    version: 1,
                    created_at: 0,
                    updated_at: 0,
                };

                // 创建时序表定义
                let time_series_table_def = crate::time_series::TimeSeriesTableDef {
                    base: base_table_def,
                    time_field: c_time_series_table.time_field,
                    value_field: c_time_series_table.value_field,
                    tag_fields: rust_tag_fields.into_boxed_slice(),
                    config: c_time_series_table.config.into(),
                };

                // 创建时序索引
                let time_series_index = crate::time_series::TimeSeriesIndex::new();

                // 创建时序表
                match crate::time_series::TimeSeriesTable::new(
                    alloc::sync::Arc::new(time_series_table_def),
                    time_series_index,
                ) {
                    Ok(time_series_table) => {
                        // 将时序表添加到数据库
                        while db_mut.time_series_tables.len() <= i {
                            db_mut.time_series_tables.push(None);
                        }
                        db_mut.time_series_tables[i] = Some(time_series_table);
                    }
                    Err(e) => {
                        return e.into();
                    }
                }
            }

            RemDbError::Success
        }
        Err(e) => e.into(),
    }
}

/// C API: 获取全局数据库实例(需先调用 remdb_init_global)
#[no_mangle]
pub unsafe extern "C" fn remdb_get_global(handle: *mut RemDbHandle) -> RemDbError {
    if handle.is_null() {
        return RemDbError::ConfigError;
    }

    // 尝试获取已存在的全局数据库实例
    match crate::get_global_db() {
        Some(db) => {
            *handle = db as *mut _;
            RemDbError::Success
        }
        None => RemDbError::ConfigError,
    }
}

/// C API: 进入低功耗模式
#[no_mangle]
pub unsafe extern "C" fn remdb_enter_low_power_mode(handle: RemDbHandle) -> RemDbError {
    if handle.is_null() {
        return RemDbError::ConfigError;
    }

    let db = &mut *handle;
    match db.enter_low_power_mode() {
        Ok(_) => RemDbError::Success,
        Err(e) => e.into(),
    }
}

/// C API: 退出低功耗模式
#[no_mangle]
pub unsafe extern "C" fn remdb_exit_low_power_mode(handle: RemDbHandle) -> RemDbError {
    if handle.is_null() {
        return RemDbError::ConfigError;
    }

    let db = &mut *handle;
    match db.exit_low_power_mode() {
        Ok(_) => RemDbError::Success,
        Err(e) => e.into(),
    }
}

/// C API: 检查是否处于低功耗模式
#[no_mangle]
pub unsafe extern "C" fn remdb_is_low_power_mode(
    handle: RemDbHandle,
    is_enabled: *mut u8,
) -> RemDbError {
    if handle.is_null() || is_enabled.is_null() {
        return RemDbError::ConfigError;
    }

    let db = &*handle;
    *is_enabled = db.is_low_power_mode() as u8;
    RemDbError::Success
}

/// C API: 开始事务
#[no_mangle]
pub unsafe extern "C" fn remdb_begin_transaction(
    handle: RemDbHandle,
    tx_type: RemDbTransactionType,
    isolation_level: RemDbIsolationLevel,
) -> RemDbError {
    if handle.is_null() {
        return RemDbError::ConfigError;
    }

    let db = &mut *handle;

    // 事务缓冲区必须比本次调用活得更久:全局 TX_MANAGER 会持有指向它们的指针
    // 直到 commit/rollback。若使用本函数的栈局部变量或局部 Vec,函数返回后
    // TX_MANAGER 将持有悬垂指针(栈帧被复用、Vec 被释放),后续任何
    // 事务操作都会访问已释放/被复用的内存。因此使用静态缓冲区。
    static mut TX_BUFFER: Option<Box<crate::transaction::Transaction>> = None;
    static mut LOG_BUFFER: Option<Box<[crate::transaction::VariableSizeLogItem]>> = None;

    if TX_BUFFER.is_none() {
        TX_BUFFER = Some(Box::new(crate::transaction::Transaction::default()));
    }
    if LOG_BUFFER.is_none() {
        LOG_BUFFER =
            Some(vec![crate::transaction::VariableSizeLogItem::default(); 1024].into_boxed_slice());
    }

    let tx_ptr = match TX_BUFFER.as_mut() {
        Some(buf) => &mut **buf as *mut crate::transaction::Transaction,
        None => return RemDbError::OutOfMemory,
    };
    let log_ptr = match LOG_BUFFER.as_mut() {
        Some(buf) => buf.as_mut_ptr(),
        None => return RemDbError::OutOfMemory,
    };

    match db.begin_transaction(
        tx_type.into(),
        isolation_level.into(),
        tx_ptr,
        log_ptr,
        1024,
    ) {
        Ok(_) => RemDbError::Success,
        Err(e) => e.into(),
    }
}

/// C API: 提交事务
#[no_mangle]
pub unsafe extern "C" fn remdb_commit_transaction(handle: RemDbHandle) -> RemDbError {
    if handle.is_null() {
        return RemDbError::ConfigError;
    }

    let db = &mut *handle;
    match db.commit_transaction() {
        Ok(_) => RemDbError::Success,
        Err(e) => e.into(),
    }
}

/// C API: 回滚事务
#[no_mangle]
pub unsafe extern "C" fn remdb_rollback_transaction(handle: RemDbHandle) -> RemDbError {
    if handle.is_null() {
        return RemDbError::ConfigError;
    }

    let db = &mut *handle;
    match db.rollback_transaction() {
        Ok(_) => RemDbError::Success,
        Err(e) => e.into(),
    }
}

/// C API: 保存快照到文件
#[no_mangle]
pub unsafe extern "C" fn remdb_save_snapshot(handle: RemDbHandle, path: *const u8) -> RemDbError {
    if handle.is_null() || path.is_null() {
        return RemDbError::ConfigError;
    }

    let db = &mut *handle;
    let rust_path = c_str_to_rust(path);
    match db.save_snapshot(&rust_path) {
        Ok(_) => RemDbError::Success,
        Err(e) => e.into(),
    }
}

/// C API: 从文件恢复快照
#[no_mangle]
pub unsafe extern "C" fn remdb_restore_snapshot(
    handle: RemDbHandle,
    path: *const u8,
) -> RemDbError {
    if handle.is_null() || path.is_null() {
        return RemDbError::ConfigError;
    }

    let db = &mut *handle;
    let rust_path = c_str_to_rust(path);
    match db.restore_snapshot(&rust_path) {
        Ok(_) => RemDbError::Success,
        Err(e) => e.into(),
    }
}

/// C API: 保存增量快照到文件
#[no_mangle]
pub unsafe extern "C" fn remdb_save_incremental_snapshot(
    handle: RemDbHandle,
    path: *const u8,
) -> RemDbError {
    if handle.is_null() || path.is_null() {
        return RemDbError::ConfigError;
    }

    let db = &mut *handle;
    let rust_path = c_str_to_rust(path);
    match db.save_incremental_snapshot(&rust_path) {
        Ok(_) => RemDbError::Success,
        Err(e) => e.into(),
    }
}

/// C API: 获取指标快照
#[no_mangle]
pub unsafe extern "C" fn remdb_get_metrics_snapshot(
    handle: RemDbHandle,
    snapshot: *mut RemDbMetricsSnapshot,
) -> RemDbError {
    if handle.is_null() || snapshot.is_null() {
        return RemDbError::ConfigError;
    }

    let db = &*handle;
    let rust_snapshot = db.metrics_snapshot();
    *snapshot = rust_snapshot.into();
    RemDbError::Success
}

/// C API: 重置所有指标
#[no_mangle]
pub unsafe extern "C" fn remdb_reset_metrics(handle: RemDbHandle) -> RemDbError {
    if handle.is_null() {
        return RemDbError::ConfigError;
    }

    let db = &*handle;
    db.reset_metrics();
    RemDbError::Success
}

/// C API: 执行健康检查
#[no_mangle]
pub unsafe extern "C" fn remdb_health_check(
    handle: RemDbHandle,
    result: *mut RemDbHealthCheckResult,
) -> RemDbError {
    if handle.is_null() || result.is_null() {
        return RemDbError::ConfigError;
    }

    let db = &*handle;
    let rust_result = db.health_check();
    *result = rust_result.into();
    RemDbError::Success
}

/// C API: 将指标输出到字符串
#[no_mangle]
pub unsafe extern "C" fn remdb_dump_metrics(
    handle: RemDbHandle,
    buffer: *mut u8,
    buffer_size: usize,
    written: *mut usize,
) -> RemDbError {
    if handle.is_null() || buffer.is_null() || written.is_null() {
        return RemDbError::ConfigError;
    }

    let db = &*handle;
    let metrics_str = db.dump_metrics();
    let metrics_bytes = metrics_str.as_bytes();

    let copy_len = core::cmp::min(metrics_bytes.len(), buffer_size - 1);
    core::ptr::copy_nonoverlapping(metrics_bytes.as_ptr(), buffer, copy_len);
    *buffer.offset(copy_len as isize) = 0;
    *written = copy_len;

    RemDbError::Success
}

/// C API: 获取快照版本
#[no_mangle]
pub unsafe extern "C" fn remdb_get_snapshot_version(
    handle: RemDbHandle,
    version: *mut u32,
) -> RemDbError {
    if handle.is_null() || version.is_null() {
        return RemDbError::ConfigError;
    }

    let db = &*handle;
    *version = db.snapshot_version;
    RemDbError::Success
}

/// C API: 向表中插入记录
#[no_mangle]
pub unsafe extern "C" fn remdb_table_insert(
    handle: RemDbHandle,
    table_id: usize,
    record: *const u8,
) -> RemDbError {
    if handle.is_null() || record.is_null() {
        return RemDbError::ConfigError;
    }

    // C API 的 table_id 只引用用户表;越界(含指向内部系统表的 ID)返回 TableNotFound
    if table_id >= c_api_user_table_count() {
        return RemDbError::TableNotFound;
    }

    let db = &mut *handle;

    // 1. 向表中插入记录,获取记录ID
    let record_id = match db.get_table_mut(table_id) {
        Ok(table) => match table.insert(record) {
            Ok(id) => id,
            Err(e) => return e.into(),
        },
        Err(e) => return e.into(),
    };

    // 2. 更新主键索引(table引用已释放,可重新借用db)
    if let Ok(index) = db.get_primary_index_mut(table_id) {
        if let Err(e) = index.insert_composite(record, record_id as u16) {
            return e.into();
        }
    }

    RemDbError::Success
}

/// C API: 从表中获取记录
#[no_mangle]
pub unsafe extern "C" fn remdb_table_get(
    handle: RemDbHandle,
    table_id: usize,
    key: *const RemDbValue,
    record: *mut u8,
) -> RemDbError {
    if handle.is_null() || key.is_null() || record.is_null() {
        return RemDbError::ConfigError;
    }

    let db = &mut *handle;

    // 1. 获取表定义以确定主键字段大小
    let key_size = match db.get_table(table_id) {
        Ok(table) => {
            let def = &table.def;
            let pk_idx = match def.primary_key.get(0) {
                Some(idx) => *idx,
                None => return RemDbError::ConfigError,
            };
            let pk_field = match def.fields.get(pk_idx) {
                Some(f) => f,
                None => return RemDbError::ConfigError,
            };
            pk_field.size
        }
        Err(e) => return e.into(),
    };

    // 2. 获取主键索引
    let primary_index = match db.get_primary_index_mut(table_id) {
        Ok(index) => index,
        Err(e) => return e.into(),
    };

    // 3. 使用主键索引查找记录ID
    let key_ptr = key as *const u8;
    let record_id = match primary_index.find(key_ptr, key_size) {
        Ok(id) => id as usize,
        Err(e) => return e.into(),
    };

    // 4. 获取表并读取记录
    let table = match db.get_table(table_id) {
        Ok(table) => table,
        Err(e) => return e.into(),
    };

    match table.get_by_id(record_id, record) {
        Ok(_) => RemDbError::Success,
        Err(e) => e.into(),
    }
}

/// C API: 更新表中的记录
#[no_mangle]
pub unsafe extern "C" fn remdb_table_update(
    handle: RemDbHandle,
    table_id: usize,
    key: *const RemDbValue,
    record: *const u8,
) -> RemDbError {
    if handle.is_null() || key.is_null() || record.is_null() {
        return RemDbError::ConfigError;
    }

    // C API 的 table_id 只引用用户表;越界(含指向内部系统表的 ID)返回 TableNotFound
    if table_id >= c_api_user_table_count() {
        return RemDbError::TableNotFound;
    }

    let db = &mut *handle;

    // 1. 获取表定义以确定主键字段大小
    let key_size = match db.get_table(table_id) {
        Ok(table) => {
            let def = &table.def;
            let pk_idx = match def.primary_key.get(0) {
                Some(idx) => *idx,
                None => return RemDbError::ConfigError,
            };
            let pk_field = match def.fields.get(pk_idx) {
                Some(f) => f,
                None => return RemDbError::ConfigError,
            };
            pk_field.size
        }
        Err(e) => return e.into(),
    };

    // 2. 获取主键索引
    let primary_index = match db.get_primary_index_mut(table_id) {
        Ok(index) => index,
        Err(e) => return e.into(),
    };

    // 3. 使用主键索引查找记录ID
    let key_ptr = key as *const u8;
    let record_id = match primary_index.find(key_ptr, key_size) {
        Ok(id) => id as usize,
        Err(e) => return e.into(),
    };

    // 4. 获取表并更新记录
    let table = match db.get_table_mut(table_id) {
        Ok(table) => table,
        Err(e) => return e.into(),
    };

    match table.update(record_id, record) {
        Ok(_) => RemDbError::Success,
        Err(e) => e.into(),
    }
}

/// C API: 从表中删除记录
#[no_mangle]
pub unsafe extern "C" fn remdb_table_delete(
    handle: RemDbHandle,
    table_id: usize,
    key: *const RemDbValue,
) -> RemDbError {
    if handle.is_null() || key.is_null() {
        return RemDbError::ConfigError;
    }

    // C API 的 table_id 只引用用户表;越界(含指向内部系统表的 ID)返回 TableNotFound
    if table_id >= c_api_user_table_count() {
        return RemDbError::TableNotFound;
    }

    let db = &mut *handle;

    // 1. 获取表定义以确定主键字段大小
    let key_size = match db.get_table(table_id) {
        Ok(table) => {
            let def = &table.def;
            let pk_idx = match def.primary_key.get(0) {
                Some(idx) => *idx,
                None => return RemDbError::ConfigError,
            };
            let pk_field = match def.fields.get(pk_idx) {
                Some(f) => f,
                None => return RemDbError::ConfigError,
            };
            pk_field.size
        }
        Err(e) => return e.into(),
    };

    let key_ptr = key as *const u8;

    // 2. 使用主键索引查找记录ID
    let record_id = match db.get_primary_index_mut(table_id) {
        Ok(index) => match index.find(key_ptr, key_size) {
            Ok(id) => id as usize,
            Err(e) => return e.into(),
        },
        Err(e) => return e.into(),
    };

    // 3. 从主键索引中删除(index引用已释放,可重新借用db)
    if let Ok(index) = db.get_primary_index_mut(table_id) {
        let _ = index.delete(key_ptr, key_size);
    }

    // 4. 从表中删除记录
    let table = match db.get_table_mut(table_id) {
        Ok(table) => table,
        Err(e) => return e.into(),
    };

    match table.delete(record_id) {
        Ok(_) => RemDbError::Success,
        Err(e) => e.into(),
    }
}

/// C API: 获取表的记录数
#[no_mangle]
pub unsafe extern "C" fn remdb_table_get_record_count(
    handle: RemDbHandle,
    table_id: usize,
    count: *mut usize,
) -> RemDbError {
    if handle.is_null() || count.is_null() {
        return RemDbError::ConfigError;
    }

    let db = &*handle;
    match db.get_table(table_id) {
        Ok(table) => {
            *count = table.record_count;
            RemDbError::Success
        }
        Err(e) => e.into(),
    }
}

/// C API: 通过名称获取表
#[no_mangle]
pub unsafe extern "C" fn remdb_table_get_by_name(
    handle: RemDbHandle,
    name: *const u8,
    table_id: *mut usize,
) -> RemDbError {
    if handle.is_null() || name.is_null() || table_id.is_null() {
        return RemDbError::ConfigError;
    }

    let db = &*handle;
    let rust_name = c_str_to_rust(name);

    for (i, table_opt) in db.tables.iter().enumerate() {
        if let Some(table) = table_opt {
            if table.def.name == rust_name {
                *table_id = i;
                return RemDbError::Success;
            }
        }
    }

    RemDbError::TableNotFound
}

/// C API: 初始化发布/订阅系统
#[no_mangle]
pub unsafe extern "C" fn remdb_pubsub_init(config: *const RemDbPubSubConfig) -> RemDbError {
    if config.is_null() {
        return RemDbError::ConfigError;
    }

    let c_config = &*config;

    // 解析组播地址
    let multicast_addr = if !c_config.multicast_addr.is_null() {
        let addr_str = c_str_to_rust(c_config.multicast_addr);
        match addr_str.parse() {
            Ok(addr) => Some(addr),
            Err(_) => None,
        }
    } else {
        None
    };

    // 创建Rust配置
    let rust_config = crate::pubsub::PubSubConfig {
        udp_mode: c_config.udp_mode.into(),
        multicast_addr,
        port: c_config.port,
        max_topics: c_config.max_topics,
        max_subscribers_per_topic: c_config.max_subscribers_per_topic,
        buffer_size: c_config.buffer_size,
        enable_nack: c_config.enable_nack != 0,
        retransmit_timeout: core::time::Duration::from_millis(
            c_config.retransmit_timeout_ms as u64,
        ),
        max_retransmits: c_config.max_retransmits,
        heartbeat_interval: core::time::Duration::from_secs(
            c_config.heartbeat_interval_secs as u64,
        ),
        frame_pool_size: c_config.frame_pool_size,
    };

    // 初始化pubsub
    match crate::pubsub::init(rust_config) {
        Ok(_) => RemDbError::Success,
        Err(e) => e.into(),
    }
}

/// 内部: 静态回调函数,调用保存的C回调
fn static_pubsub_callback(topic_id: u16, data: &[u8]) -> bool {
    unsafe {
        if let Some(callback) = C_CALLBACK_STORAGE {
            callback(topic_id, data.as_ptr(), data.len()) != 0
        } else {
            false
        }
    }
}

/// C API: 订阅主题
#[no_mangle]
pub unsafe extern "C" fn remdb_pubsub_subscribe(
    topic_id: u16,
    callback: RemDbPubSubCallback,
    subscription_id: *mut usize,
) -> RemDbError {
    if subscription_id.is_null() {
        return RemDbError::ConfigError;
    }

    // 保存C回调到全局存储
    C_CALLBACK_STORAGE = Some(callback);

    // 订阅主题使用静态回调
    match crate::pubsub::subscribe(topic_id, static_pubsub_callback) {
        Ok(id) => {
            *subscription_id = id;
            RemDbError::Success
        }
        Err(e) => e.into(),
    }
}

/// C API: 取消订阅
#[no_mangle]
pub unsafe extern "C" fn remdb_pubsub_unsubscribe(subscription_id: usize) -> RemDbError {
    match crate::pubsub::unsubscribe(subscription_id) {
        Ok(_) => RemDbError::Success,
        Err(e) => e.into(),
    }
}

/// C API: 发布数据
#[no_mangle]
pub unsafe extern "C" fn remdb_pubsub_publish(
    topic_id: u16,
    data: *const u8,
    data_len: usize,
) -> RemDbError {
    if data.is_null() || data_len == 0 {
        return RemDbError::ConfigError;
    }

    let data_slice = core::slice::from_raw_parts(data, data_len);

    match crate::pubsub::publish(topic_id, data_slice) {
        Ok(_) => RemDbError::Success,
        Err(e) => e.into(),
    }
}

/// C API: 启动接收线程
#[no_mangle]
pub unsafe extern "C" fn remdb_pubsub_start_receiver() -> RemDbError {
    match crate::pubsub::start_receiver() {
        Ok(_) => RemDbError::Success,
        Err(e) => e.into(),
    }
}

/// C API: 停止发布/订阅系统
#[no_mangle]
pub unsafe extern "C" fn remdb_pubsub_shutdown() -> RemDbError {
    match crate::pubsub::shutdown() {
        Ok(_) => RemDbError::Success,
        Err(e) => e.into(),
    }
}

/// C API: 批量写入时序数据
#[no_mangle]
pub unsafe extern "C" fn remdb_time_series_batch_write(
    handle: RemDbHandle,
    table_id: usize,
    records: *const RemDbTimeSeriesRecord,
    count: usize,
    written: *mut usize,
) -> RemDbError {
    if handle.is_null() || records.is_null() || written.is_null() {
        return RemDbError::ConfigError;
    }

    let db = &mut *handle;

    // 1. 获取时序表
    match db.get_time_series_table_mut(table_id) {
        Ok(time_series_table) => {
            // 2. 将C记录转换为Rust记录
            let mut rust_records = Vec::with_capacity(count);
            for i in 0..count {
                let c_record = unsafe { *records.offset(i as isize) };
                rust_records.push(c_record.into());
            }

            // 3. 执行批量写入
            match time_series_table.write_timeseries_batch(&rust_records) {
                Ok(inserted) => {
                    *written = inserted;
                    RemDbError::Success
                }
                Err(e) => e.into(),
            }
        }
        Err(e) => e.into(),
    }
}

/// C API: 根据时间范围查询时序数据
#[no_mangle]
pub unsafe extern "C" fn remdb_time_series_query(
    handle: RemDbHandle,
    table_id: usize,
    start_time: u64,
    end_time: u64,
    buffer: *mut RemDbTimeSeriesRecord,
    buffer_size: usize,
    result_count: *mut usize,
) -> RemDbError {
    if handle.is_null() || buffer.is_null() || result_count.is_null() {
        return RemDbError::ConfigError;
    }

    let db = &*handle;

    // 1. 获取时序表
    match db.get_time_series_table(table_id) {
        Ok(time_series_table) => {
            // 2. 执行查询
            match time_series_table.query_time_range(start_time, end_time) {
                Ok(results) => {
                    // 3. 将结果转换为C格式并复制到输出缓冲区
                    let actual_count = core::cmp::min(results.len(), buffer_size);
                    for i in 0..actual_count {
                        *buffer.add(i) = results[i].into();
                    }

                    *result_count = actual_count;
                    RemDbError::Success
                }
                Err(e) => e.into(),
            }
        }
        Err(e) => e.into(),
    }
}

/// C API: 根据名称获取时序表
#[no_mangle]
pub unsafe extern "C" fn remdb_time_series_table_get_by_name(
    handle: RemDbHandle,
    name: *const u8,
    table_id: *mut usize,
) -> RemDbError {
    if handle.is_null() || name.is_null() || table_id.is_null() {
        return RemDbError::ConfigError;
    }

    let db = &*handle;
    let rust_name = c_str_to_rust(name);

    // 查找时序表
    for (i, table_opt) in db.time_series_tables.iter().enumerate() {
        if let Some(table) = table_opt {
            if table.def.base.name == rust_name {
                *table_id = i;
                return RemDbError::Success;
            }
        }
    }

    RemDbError::TableNotFound
}

/// C API: 获取可变时序表引用(内部使用)
pub unsafe fn get_time_series_table_mut(
    db: &mut crate::RemDb,
    table_id: usize,
) -> Result<&mut crate::time_series::TimeSeriesTable, crate::RemDbError> {
    if table_id >= db.time_series_tables.len() {
        return Err(crate::RemDbError::TableNotFound);
    }

    match &mut db.time_series_tables[table_id] {
        Some(table) => Ok(table),
        None => Err(crate::RemDbError::TableNotFound),
    }
}

/// C API: 将Rust结果集转换为C结果集
/// 注意:返回的结果集需要通过remdb_free_result_set释放内存
#[no_mangle]
pub unsafe extern "C" fn remdb_sql_query(
    handle: RemDbHandle,
    sql: *const u8,
    result_set: *mut *mut RemDbResultSet,
) -> RemDbError {
    if handle.is_null() || sql.is_null() || result_set.is_null() {
        return RemDbError::ConfigError;
    }

    let db = &mut *handle;
    let rust_sql = c_str_to_rust(sql);

    match db.sql_query(&rust_sql) {
        Ok(rust_result_set) => {
            #[cfg(feature = "log")]
            debug!(
                "sql_query succeeded, columns: {:?}, rows_count: {}",
                rust_result_set.columns,
                rust_result_set.rows.len()
            );

            // 分配内存存储结果集
            let c_result_set = alloc::alloc::alloc(alloc::alloc::Layout::new::<RemDbResultSet>())
                as *mut RemDbResultSet;
            if c_result_set.is_null() {
                return RemDbError::OutOfMemory;
            }

            // 分配内存存储列名
            let columns = alloc::alloc::alloc(
                alloc::alloc::Layout::array::<*const u8>(rust_result_set.columns.len())
                    .expect("failed to allocate memory"),
            ) as *mut *const u8;
            if columns.is_null() {
                alloc::alloc::dealloc(
                    c_result_set as *mut u8,
                    alloc::alloc::Layout::new::<RemDbResultSet>(),
                );
                return RemDbError::OutOfMemory;
            }

            // 转换列名
            for (i, column) in rust_result_set.columns.iter().enumerate() {
                let column_str = alloc::alloc::alloc(
                    alloc::alloc::Layout::array::<u8>(column.len() + 1)
                        .expect("failed to allocate memory"),
                ) as *mut u8;
                if column_str.is_null() {
                    // 释放已分配的内存
                    for j in 0..i {
                        let col = *columns.offset(j as isize);
                        alloc::alloc::dealloc(
                            col as *mut u8,
                            alloc::alloc::Layout::array::<u8>(_c_strlen(col) + 1)
                                .expect("failed to allocate memory"),
                        );
                    }
                    alloc::alloc::dealloc(
                        columns as *mut u8,
                        alloc::alloc::Layout::array::<*const u8>(rust_result_set.columns.len())
                            .expect("failed to allocate memory"),
                    );
                    alloc::alloc::dealloc(
                        c_result_set as *mut u8,
                        alloc::alloc::Layout::new::<RemDbResultSet>(),
                    );
                    return RemDbError::OutOfMemory;
                }

                // 复制列名字符串
                core::ptr::copy_nonoverlapping(column.as_ptr(), column_str, column.len());
                *column_str.offset(column.len() as isize) = 0; // 添加终止符
                *columns.offset(i as isize) = column_str as *const u8;
            }

            // 分配内存存储行
            let rows = alloc::alloc::alloc(
                alloc::alloc::Layout::array::<RemDbResultRow>(rust_result_set.rows.len())
                    .expect("failed to allocate memory"),
            ) as *mut RemDbResultRow;
            if rows.is_null() {
                // 释放已分配的内存
                for i in 0..rust_result_set.columns.len() {
                    let col = *columns.offset(i as isize);
                    alloc::alloc::dealloc(
                        col as *mut u8,
                        alloc::alloc::Layout::array::<u8>(_c_strlen(col) + 1)
                            .expect("failed to allocate memory"),
                    );
                }
                alloc::alloc::dealloc(
                    columns as *mut u8,
                    alloc::alloc::Layout::array::<*const u8>(rust_result_set.columns.len())
                        .expect("failed to allocate memory"),
                );
                alloc::alloc::dealloc(
                    c_result_set as *mut u8,
                    alloc::alloc::Layout::new::<RemDbResultSet>(),
                );
                return RemDbError::OutOfMemory;
            }

            // 转换行数据
            for (i, row) in rust_result_set.rows.iter().enumerate() {
                // 分配内存存储值
                let values = alloc::alloc::alloc(
                    alloc::alloc::Layout::array::<RemDbTypedValue>(row.values.len())
                        .expect("failed to allocate memory"),
                ) as *mut RemDbTypedValue;
                if values.is_null() {
                    // 释放已分配的内存
                    for j in 0..i {
                        let r = &*rows.offset(j as isize);
                        alloc::alloc::dealloc(
                            r.values as *mut u8,
                            alloc::alloc::Layout::array::<RemDbTypedValue>(r.values_count)
                                .expect("failed to allocate memory"),
                        );
                    }
                    alloc::alloc::dealloc(
                        rows as *mut u8,
                        alloc::alloc::Layout::array::<RemDbResultRow>(rust_result_set.rows.len())
                            .expect("failed to allocate memory"),
                    );
                    for j in 0..rust_result_set.columns.len() {
                        let col = *columns.offset(j as isize);
                        alloc::alloc::dealloc(
                            col as *mut u8,
                            alloc::alloc::Layout::array::<u8>(_c_strlen(col) + 1)
                                .expect("failed to allocate memory"),
                        );
                    }
                    alloc::alloc::dealloc(
                        columns as *mut u8,
                        alloc::alloc::Layout::array::<*const u8>(rust_result_set.columns.len())
                            .expect("failed to allocate memory"),
                    );
                    alloc::alloc::dealloc(
                        c_result_set as *mut u8,
                        alloc::alloc::Layout::new::<RemDbResultSet>(),
                    );
                    return RemDbError::OutOfMemory;
                }

                // 转换值
                for (j, value) in row.values.iter().enumerate() {
                    #[cfg(feature = "log")]
                    debug!("row {}, value {}: type={:?}", i, j, value.value_type);
                    *values.offset(j as isize) = value.clone().into();
                }

                // 设置行数据
                let row_ptr = rows.offset(i as isize);
                (*row_ptr).values = values;
                (*row_ptr).values_count = row.values.len();
            }

            // 设置结果集数据
            (*c_result_set).columns = columns;
            (*c_result_set).columns_count = rust_result_set.columns.len();
            (*c_result_set).rows = rows;
            (*c_result_set).rows_count = rust_result_set.rows.len();

            *result_set = c_result_set;
            RemDbError::Success
        }
        Err(e) => e.into(),
    }
}

/// C API: 释放结果集内存
#[no_mangle]
pub unsafe extern "C" fn remdb_free_result_set(result_set: *mut RemDbResultSet) -> RemDbError {
    if result_set.is_null() {
        return RemDbError::Success;
    }

    let rs = &mut *result_set;

    // 释放列名
    for i in 0..rs.columns_count {
        let col = *rs.columns.offset(i as isize);
        if !col.is_null() {
            alloc::alloc::dealloc(
                col as *mut u8,
                alloc::alloc::Layout::array::<u8>(_c_strlen(col) + 1)
                    .expect("failed to allocate memory"),
            );
        }
    }
    alloc::alloc::dealloc(
        rs.columns as *mut u8,
        alloc::alloc::Layout::array::<*const u8>(rs.columns_count)
            .expect("failed to allocate memory"),
    );

    // 释放行数据
    for i in 0..rs.rows_count {
        let row = &*rs.rows.offset(i as isize);
        if !row.values.is_null() {
            alloc::alloc::dealloc(
                row.values as *mut u8,
                alloc::alloc::Layout::array::<RemDbTypedValue>(row.values_count)
                    .expect("failed to allocate memory"),
            );
        }
    }
    alloc::alloc::dealloc(
        rs.rows as *mut u8,
        alloc::alloc::Layout::array::<RemDbResultRow>(rs.rows_count)
            .expect("failed to allocate memory"),
    );

    // 释放结果集本身
    alloc::alloc::dealloc(
        result_set as *mut u8,
        alloc::alloc::Layout::new::<RemDbResultSet>(),
    );

    RemDbError::Success
}

/// C API: 获取JSON字符串
/// 注意:返回的字符串需要通过remdb_free_string释放内存
#[no_mangle]
pub unsafe extern "C" fn remdb_get_json_string(
    value: *const RemDbTypedValue,
    json_string: *mut *const u8,
    length: *mut usize,
) -> RemDbError {
    if value.is_null() || json_string.is_null() || length.is_null() {
        return RemDbError::ConfigError;
    }

    let typed_value = &*value;

    // Support both Json and String data types (inline JSON is stored as String)
    if typed_value.data_type != RemDbDataType::Json
        && typed_value.data_type != RemDbDataType::String
    {
        return RemDbError::TypeMismatch;
    }

    // Helper function to copy a string from a byte array to allocated memory
    let copy_string_from_bytes = |bytes: &[u8]| -> Result<(*const u8, usize), RemDbError> {
        let actual_len = match bytes.iter().position(|&b| b == 0) {
            Some(pos) => pos,
            None => bytes.len(),
        };

        let layout = match alloc::alloc::Layout::array::<u8>(actual_len + 1) {
            Ok(l) => l,
            Err(_) => return Err(RemDbError::OutOfMemory),
        };
        let json_c_str = alloc::alloc::alloc(layout) as *mut u8;

        if json_c_str.is_null() {
            return Err(RemDbError::OutOfMemory);
        }

        if actual_len > 0 {
            core::ptr::copy_nonoverlapping(bytes.as_ptr(), json_c_str, actual_len);
        }
        *json_c_str.offset(actual_len as isize) = 0; // null terminator

        Ok((json_c_str as *const u8, actual_len))
    };

    // If stored as String (inline JSON), read directly from the string field
    if typed_value.data_type == RemDbDataType::String {
        match copy_string_from_bytes(&typed_value.value.string) {
            Ok((ptr, len)) => {
                *json_string = ptr;
                *length = len;
                RemDbError::Success
            }
            Err(e) => e,
        }
    } else {
        // data_type is Json - use pool-based or inline detection
        let json_value = typed_value.value.json;

        // Check for inline JSON (pool_id == 0, offset == 0, length == 0)
        // Read from the string field directly since the union overlaps
        if json_value.pool_id == 0 && json_value.offset == 0 && json_value.length == 0 {
            match copy_string_from_bytes(&typed_value.value.string) {
                Ok((ptr, len)) => {
                    *json_string = ptr;
                    *length = len;
                    RemDbError::Success
                }
                Err(e) => e,
            }
        } else {
            // 获取全局JSON池管理器
            let pool_manager = match crate::json::memory_pool::get_global_json_pool_manager() {
                Some(manager) => manager,
                None => return RemDbError::UnsupportedOperation,
            };

            // 获取JSON池
            let pool = match pool_manager.get_pool(json_value.pool_id) {
                Some(p) => p,
                None => return RemDbError::UnsupportedOperation,
            };

            // 获取JSON数据
            if let Some(data_ptr) = pool.get_block_data(json_value.offset as usize, 0) {
                let data_slice = core::slice::from_raw_parts(data_ptr, json_value.length as usize);

                // 尝试解析JSON数据并转换为字符串
                match crate::json::JsonDocument::from_binary(data_slice, json_value.length as usize)
                {
                    Ok(json_doc) => {
                        // 转换为JSON字符串
                        let json_str = match json_doc.to_json() {
                            Ok(s) => s,
                            Err(_) => return RemDbError::TypeMismatch,
                        };

                        // 分配内存存储JSON字符串
                        let json_c_str = alloc::alloc::alloc(
                            alloc::alloc::Layout::array::<u8>(json_str.len() + 1)
                                .expect("failed to allocate memory"),
                        ) as *mut u8;

                        if json_c_str.is_null() {
                            return RemDbError::OutOfMemory;
                        }

                        // 复制JSON字符串
                        core::ptr::copy_nonoverlapping(
                            json_str.as_ptr(),
                            json_c_str,
                            json_str.len(),
                        );
                        *json_c_str.offset(json_str.len() as isize) = 0; // 添加终止符

                        *json_string = json_c_str as *const u8;
                        *length = json_str.len();

                        RemDbError::Success
                    }
                    Err(_) => RemDbError::TypeMismatch,
                }
            } else {
                RemDbError::UnsupportedOperation
            }
        }
    }
}

/// C API: 释放字符串内存
#[no_mangle]
pub unsafe extern "C" fn remdb_free_string(s: *const u8) -> RemDbError {
    if s.is_null() {
        return RemDbError::Success;
    }

    alloc::alloc::dealloc(
        s as *mut u8,
        alloc::alloc::Layout::array::<u8>(_c_strlen(s) + 1).expect("failed to allocate memory"),
    );

    RemDbError::Success
}

/// C API: 执行查询操作
#[no_mangle]
pub unsafe extern "C" fn remdb_execute_query(
    handle: RemDbHandle,
    table_name: *const u8,
    columns: *const *const u8,
    columns_count: usize,
    where_clause: *const u8,
    limit: i32,
    result_set: *mut *mut RemDbResultSet,
) -> RemDbError {
    if handle.is_null() || table_name.is_null() || result_set.is_null() {
        return RemDbError::ConfigError;
    }

    let db = &mut *handle;
    let rust_table_name = c_str_to_rust(table_name);

    // 转换列名
    let mut rust_columns = Vec::with_capacity(columns_count);
    for i in 0..columns_count {
        let col = *columns.offset(i as isize);
        if !col.is_null() {
            rust_columns.push(c_str_to_rust(col));
        }
    }

    // 转换where子句
    let rust_where_clause = if !where_clause.is_null() {
        Some(c_str_to_rust(where_clause))
    } else {
        None
    };

    // 转换limit
    let rust_limit = if limit > 0 {
        Some(limit as usize)
    } else {
        None
    };

    match db.execute_query(
        &rust_table_name,
        &rust_columns
            .iter()
            .map(|s| s.as_str())
            .collect::<Vec<&str>>(),
        rust_where_clause.as_deref(),
        rust_limit,
    ) {
        Ok(rust_result_set) => {
            // 分配内存存储结果集
            let c_result_set = alloc::alloc::alloc(alloc::alloc::Layout::new::<RemDbResultSet>())
                as *mut RemDbResultSet;
            if c_result_set.is_null() {
                return RemDbError::OutOfMemory;
            }

            // 分配内存存储列名
            let columns_ptr = alloc::alloc::alloc(
                alloc::alloc::Layout::array::<*const u8>(rust_result_set.columns.len())
                    .expect("failed to allocate memory"),
            ) as *mut *const u8;
            if columns_ptr.is_null() {
                alloc::alloc::dealloc(
                    c_result_set as *mut u8,
                    alloc::alloc::Layout::new::<RemDbResultSet>(),
                );
                return RemDbError::OutOfMemory;
            }

            // 转换列名
            for (i, column) in rust_result_set.columns.iter().enumerate() {
                let column_str = alloc::alloc::alloc(
                    alloc::alloc::Layout::array::<u8>(column.len() + 1)
                        .expect("failed to allocate memory"),
                ) as *mut u8;
                if column_str.is_null() {
                    // 释放已分配的内存
                    for j in 0..i {
                        let col = *columns_ptr.offset(j as isize);
                        alloc::alloc::dealloc(
                            col as *mut u8,
                            alloc::alloc::Layout::array::<u8>(_c_strlen(col) + 1)
                                .expect("failed to allocate memory"),
                        );
                    }
                    alloc::alloc::dealloc(
                        columns_ptr as *mut u8,
                        alloc::alloc::Layout::array::<*const u8>(rust_result_set.columns.len())
                            .expect("failed to allocate memory"),
                    );
                    alloc::alloc::dealloc(
                        c_result_set as *mut u8,
                        alloc::alloc::Layout::new::<RemDbResultSet>(),
                    );
                    return RemDbError::OutOfMemory;
                }

                // 复制列名字符串
                core::ptr::copy_nonoverlapping(column.as_ptr(), column_str, column.len());
                *column_str.offset(column.len() as isize) = 0; // 添加终止符
                *columns_ptr.offset(i as isize) = column_str as *const u8;
            }

            // 分配内存存储行
            let rows_ptr = alloc::alloc::alloc(
                alloc::alloc::Layout::array::<RemDbResultRow>(rust_result_set.rows.len())
                    .expect("failed to allocate memory"),
            ) as *mut RemDbResultRow;
            if rows_ptr.is_null() {
                // 释放已分配的内存
                for i in 0..rust_result_set.columns.len() {
                    let col = *columns_ptr.offset(i as isize);
                    alloc::alloc::dealloc(
                        col as *mut u8,
                        alloc::alloc::Layout::array::<u8>(_c_strlen(col) + 1)
                            .expect("failed to allocate memory"),
                    );
                }
                alloc::alloc::dealloc(
                    columns_ptr as *mut u8,
                    alloc::alloc::Layout::array::<*const u8>(rust_result_set.columns.len())
                        .expect("failed to allocate memory"),
                );
                alloc::alloc::dealloc(
                    c_result_set as *mut u8,
                    alloc::alloc::Layout::new::<RemDbResultSet>(),
                );
                return RemDbError::OutOfMemory;
            }

            // 转换行数据
            for (i, row) in rust_result_set.rows.iter().enumerate() {
                // 分配内存存储值
                let values_ptr = alloc::alloc::alloc(
                    alloc::alloc::Layout::array::<RemDbTypedValue>(row.values.len())
                        .expect("failed to allocate memory"),
                ) as *mut RemDbTypedValue;
                if values_ptr.is_null() {
                    // 释放已分配的内存
                    for j in 0..i {
                        let r = &*rows_ptr.offset(j as isize);
                        if !r.values.is_null() {
                            alloc::alloc::dealloc(
                                r.values as *mut u8,
                                alloc::alloc::Layout::array::<RemDbTypedValue>(r.values_count)
                                    .expect("failed to allocate memory"),
                            );
                        }
                    }
                    alloc::alloc::dealloc(
                        rows_ptr as *mut u8,
                        alloc::alloc::Layout::array::<RemDbResultRow>(rust_result_set.rows.len())
                            .expect("failed to allocate memory"),
                    );
                    for j in 0..rust_result_set.columns.len() {
                        let col = *columns_ptr.offset(j as isize);
                        alloc::alloc::dealloc(
                            col as *mut u8,
                            alloc::alloc::Layout::array::<u8>(_c_strlen(col) + 1)
                                .expect("failed to allocate memory"),
                        );
                    }
                    alloc::alloc::dealloc(
                        columns_ptr as *mut u8,
                        alloc::alloc::Layout::array::<*const u8>(rust_result_set.columns.len())
                            .expect("failed to allocate memory"),
                    );
                    alloc::alloc::dealloc(
                        c_result_set as *mut u8,
                        alloc::alloc::Layout::new::<RemDbResultSet>(),
                    );
                    return RemDbError::OutOfMemory;
                }

                // 转换值
                for (j, value) in row.values.iter().enumerate() {
                    *values_ptr.offset(j as isize) = value.clone().into();
                }

                // 设置行数据
                let row_ptr = rows_ptr.offset(i as isize);
                (*row_ptr).values = values_ptr;
                (*row_ptr).values_count = row.values.len();
            }

            // 设置结果集数据
            (*c_result_set).columns = columns_ptr;
            (*c_result_set).columns_count = rust_result_set.columns.len();
            (*c_result_set).rows = rows_ptr;
            (*c_result_set).rows_count = rust_result_set.rows.len();

            *result_set = c_result_set;
            RemDbError::Success
        }
        Err(e) => e.into(),
    }
}

// 向量索引相关C API函数声明

/// C API: 向量索引类型枚举
#[repr(u8)]
#[derive(Copy, Clone)]
pub enum RemDbVectorIndexType {
    HNSW = 0,
    HNSW_SQ = 1,
    HNSW_BQ = 2,
    IVF = 3, // IVF_FLAT
    IVF_PQ = 4,
}

/// C API: 向量距离度量类型枚举
#[repr(u8)]
#[derive(Copy, Clone)]
pub enum RemDbDistanceType {
    L2 = 0,
    InnerProduct = 1,
    Cosine = 2,
}

/// C API: 向量元数据配置
#[repr(C)]
pub struct RemDbVectorMetadata {
    pub dimension: u16,
    pub distance_type: RemDbDistanceType,
    pub index_type: RemDbVectorIndexType,
    pub compression_enabled: u8,
    pub compression_scheme: u8,
    pub compression_level: u8,
    pub hnsw_m: u8,
    pub hnsw_ef_construction: u32,
    pub hnsw_ef_search: u32,
    pub ivf_nlist: u32,
    pub ivf_nprobe: u32,
}

/// C API: 初始化索引构建线程池
#[no_mangle]
pub unsafe extern "C" fn remdb_init_index_build_thread_pool(thread_count: u32) -> RemDbError {
    crate::index::builder::init_index_build_thread_pool(thread_count as usize);
    RemDbError::Success
}

/// C API: 创建向量索引
#[no_mangle]
pub unsafe extern "C" fn remdb_create_vector_index(
    handle: RemDbHandle,
    table_name: *const u8,
    field_name: *const u8,
    metadata: *const RemDbVectorMetadata,
) -> RemDbError {
    if handle.is_null() || table_name.is_null() || field_name.is_null() || metadata.is_null() {
        return RemDbError::ConfigError;
    }

    let db = &mut *handle;
    let table_name_str = c_str_to_rust(table_name);
    let field_name_str = c_str_to_rust(field_name);
    let c_meta = &*metadata;

    // 转换为Rust向量元数据
    let rust_meta = crate::types::VectorMetadata {
        dimension: c_meta.dimension,
        distance_type: match c_meta.distance_type {
            RemDbDistanceType::L2 => crate::types::DistanceType::L2,
            RemDbDistanceType::InnerProduct => crate::types::DistanceType::InnerProduct,
            RemDbDistanceType::Cosine => crate::types::DistanceType::Cosine,
        },
        index_type: match c_meta.index_type {
            RemDbVectorIndexType::HNSW => crate::types::VectorIndexType::HNSW,
            RemDbVectorIndexType::HNSW_SQ => crate::types::VectorIndexType::HNSW_SQ,
            RemDbVectorIndexType::HNSW_BQ => crate::types::VectorIndexType::HNSW_BQ,
            RemDbVectorIndexType::IVF => crate::types::VectorIndexType::IVF, // IVF_FLAT
            RemDbVectorIndexType::IVF_PQ => crate::types::VectorIndexType::IVF_PQ,
        },
        compression_enabled: c_meta.compression_enabled != 0,
        compression_scheme: c_meta.compression_scheme,
        compression_level: c_meta.compression_level,
        hnsw_m: c_meta.hnsw_m,
        hnsw_ef_construction: c_meta.hnsw_ef_construction,
        hnsw_ef_search: c_meta.hnsw_ef_search,
        ivf_nlist: c_meta.ivf_nlist,
        ivf_nprobe: c_meta.ivf_nprobe,
    };

    // 使用SQL API创建向量索引
    let sql = alloc::format!(
        "CREATE INDEX ON {} ({}) WITH DIMENSION={}, DISTANCE={:?}, INDEX_TYPE={:?}",
        table_name_str,
        field_name_str,
        rust_meta.dimension,
        rust_meta.distance_type,
        rust_meta.index_type
    );

    match db.sql_query(&sql) {
        Ok(_) => RemDbError::Success,
        Err(e) => e.into(),
    }
}

/// C API: 向量相似度搜索
#[no_mangle]
pub unsafe extern "C" fn remdb_vector_search(
    handle: RemDbHandle,
    table_name: *const u8,
    field_name: *const u8,
    query_vector: *const f32,
    _vector_dim: u16,
    k: u32,
    results: *mut *mut u32,   // 返回匹配的记录ID数组
    distances: *mut *mut f32, // 返回距离数组
    result_count: *mut u32,   // 实际返回的结果数量
) -> RemDbError {
    if handle.is_null()
        || table_name.is_null()
        || field_name.is_null()
        || query_vector.is_null()
        || results.is_null()
        || distances.is_null()
        || result_count.is_null()
    {
        return RemDbError::ConfigError;
    }

    let db = &mut *handle;
    let table_name_str = c_str_to_rust(table_name);
    let field_name_str = c_str_to_rust(field_name);

    // 使用SQL API执行向量搜索
    let sql = alloc::format!(
        "SELECT id, VECTOR_DISTANCE({}, ?) as distance FROM {} ORDER BY distance LIMIT {}",
        field_name_str,
        table_name_str,
        k
    );

    // 注意:此处简化实现,实际应该支持参数化查询
    match db.sql_query(&sql) {
        Ok(rust_result_set) => {
            let actual_count = rust_result_set.rows.len();
            *result_count = actual_count as u32;

            if actual_count > 0 {
                // 分配内存存储结果
                let result_ids = alloc::alloc::alloc(
                    alloc::alloc::Layout::array::<u32>(actual_count)
                        .expect("failed to allocate memory"),
                ) as *mut u32;
                let result_distances = alloc::alloc::alloc(
                    alloc::alloc::Layout::array::<f32>(actual_count)
                        .expect("failed to allocate memory"),
                ) as *mut f32;

                if result_ids.is_null() || result_distances.is_null() {
                    if !result_ids.is_null() {
                        alloc::alloc::dealloc(
                            result_ids as *mut u8,
                            alloc::alloc::Layout::array::<u32>(actual_count)
                                .expect("failed to allocate memory"),
                        );
                    }
                    if !result_distances.is_null() {
                        alloc::alloc::dealloc(
                            result_distances as *mut u8,
                            alloc::alloc::Layout::array::<f32>(actual_count)
                                .expect("failed to allocate memory"),
                        );
                    }
                    return RemDbError::OutOfMemory;
                }

                // 提取结果
                for i in 0..actual_count {
                    let row = &rust_result_set.rows[i];
                    if row.values.len() >= 2 {
                        // 假设第一列为id,第二列为distance
                        let id_value = &row.values[0];
                        let distance_value = &row.values[1];

                        // 提取id值
                        if let crate::types::DataType::UInt32
                        | crate::types::DataType::Int32
                        | crate::types::DataType::UInt64
                        | crate::types::DataType::Int64 = id_value.value_type
                        {
                            *result_ids.offset(i as isize) = unsafe { id_value.value.u32 };
                        } else {
                            *result_ids.offset(i as isize) = 0;
                        }

                        // 提取distance值
                        if let crate::types::DataType::Float32 | crate::types::DataType::Float64 =
                            distance_value.value_type
                        {
                            *result_distances.offset(i as isize) =
                                unsafe { distance_value.value.float32 };
                        } else {
                            *result_distances.offset(i as isize) = 0.0;
                        }
                    }
                }

                *results = result_ids;
                *distances = result_distances;
            }

            RemDbError::Success
        }
        Err(e) => e.into(),
    }
}

/// C API: 释放向量搜索结果内存
#[no_mangle]
pub unsafe extern "C" fn remdb_free_vector_search_results(
    results: *mut u32,
    distances: *mut f32,
    count: u32,
) -> RemDbError {
    if !results.is_null() {
        alloc::alloc::dealloc(
            results as *mut u8,
            alloc::alloc::Layout::array::<u32>(count as usize).expect("failed to allocate memory"),
        );
    }

    if !distances.is_null() {
        alloc::alloc::dealloc(
            distances as *mut u8,
            alloc::alloc::Layout::array::<f32>(count as usize).expect("failed to allocate memory"),
        );
    }

    RemDbError::Success
}

/// C API: 获取索引构建状态
#[no_mangle]
pub unsafe extern "C" fn remdb_get_index_build_status(
    handle: RemDbHandle,
    table_name: *const u8,
    field_name: *const u8,
    is_building: *mut u8,
    progress: *mut u32, // 0-100
) -> RemDbError {
    if handle.is_null()
        || table_name.is_null()
        || field_name.is_null()
        || is_building.is_null()
        || progress.is_null()
    {
        return RemDbError::ConfigError;
    }

    let db = &mut *handle;
    let table_name_str = c_str_to_rust(table_name);
    let field_name_str = c_str_to_rust(field_name);

    // 使用SQL API查询索引构建状态
    let sql = alloc::format!(
        "SHOW INDEX BUILD STATUS ON {} FOR {}",
        table_name_str,
        field_name_str
    );

    match db.sql_query(&sql) {
        Ok(rust_result_set) => {
            if rust_result_set.rows.len() > 0 {
                let row = &rust_result_set.rows[0];
                if row.values.len() >= 2 {
                    // 假设第一列为is_building,第二列为progress
                    let building_value = &row.values[0];
                    let progress_value = &row.values[1];

                    // 提取is_building值
                    if let crate::types::DataType::Bool = building_value.value_type {
                        *is_building = unsafe { building_value.value.bool as u8 };
                    } else {
                        *is_building = 0;
                    }

                    // 提取progress值
                    if let crate::types::DataType::UInt32 | crate::types::DataType::Int32 =
                        progress_value.value_type
                    {
                        *progress = unsafe { progress_value.value.u32 };
                    } else {
                        *progress = 0;
                    }
                }
            }

            RemDbError::Success
        }
        Err(e) => e.into(),
    }
}

/// C API: 创建表
#[no_mangle]
pub unsafe extern "C" fn remdb_create_table(
    handle: RemDbHandle,
    table_name: *const u8,
    fields: *const RemDbFieldDef,
    fields_count: usize,
    primary_key: i32,
) -> RemDbError {
    if handle.is_null() || table_name.is_null() {
        return RemDbError::ConfigError;
    }

    let db = &mut *handle;
    let rust_table_name = c_str_to_rust(table_name);

    // 转换字段定义
    let mut field_name_strings = Vec::with_capacity(fields_count);
    let mut rust_fields = Vec::with_capacity(fields_count);

    for i in 0..fields_count {
        let c_field = &*fields.offset(i as isize);
        let field_name = c_str_to_rust(c_field.name);
        field_name_strings.push(field_name);
    }

    // 现在创建字段定义向量
    for (i, field_name) in field_name_strings.iter().enumerate() {
        let c_field = &*fields.offset(i as isize);
        rust_fields.push((
            field_name.as_str(),
            c_field.data_type.into(),
            c_field.size as u16,
            None, // 不支持向量距离类型
            None, // 不支持默认值
        ));
    }

    // 转换主键索引
    let rust_primary_key = if primary_key >= 0 {
        Some(vec![primary_key as usize])
    } else {
        None
    };

    match db.create_table(&rust_table_name, &rust_fields, rust_primary_key) {
        Ok(_) => RemDbError::Success,
        Err(e) => e.into(),
    }
}

/// C API: 批量插入记录
#[no_mangle]
pub unsafe extern "C" fn remdb_batch_insert_record(
    handle: RemDbHandle,
    table_name: *const u8,
    column_names: *const *const u8,
    column_names_count: usize,
    records: *const *const *const u8,
    records_count: usize,
    values_per_record: usize,
    affected_rows: *mut usize,
) -> RemDbError {
    if handle.is_null() || table_name.is_null() || records.is_null() || affected_rows.is_null() {
        return RemDbError::ConfigError;
    }

    let db = &mut *handle;
    let rust_table_name = c_str_to_rust(table_name);

    // 转换列名
    let mut col_name_vec = Vec::with_capacity(column_names_count);
    for i in 0..column_names_count {
        let col = *column_names.offset(i as isize);
        if !col.is_null() {
            let col_str = c_str_to_rust(col);
            col_name_vec.push(col_str);
        }
    }

    // 转换列名向量为&str切片
    let col_names: Vec<&str> = col_name_vec.iter().map(|s| s.as_str()).collect();

    // 转换并插入每条记录
    let mut total_inserted = 0;

    for i in 0..records_count {
        let record = *records.offset(i as isize);

        // 转换单条记录的字段值
        let mut field_value_vec = Vec::with_capacity(values_per_record);
        for j in 0..values_per_record {
            let value = *record.offset(j as isize);
            if !value.is_null() {
                let val_str = c_str_to_rust(value);
                field_value_vec.push(val_str);
            } else {
                field_value_vec.push("".to_string());
            }
        }

        // 转换字段值向量为&str切片
        let field_values: Vec<&str> = field_value_vec.iter().map(|s| s.as_str()).collect();

        // 单条插入记录
        match db.insert_record(&rust_table_name, &col_names, &field_values) {
            Ok(inserted) => {
                total_inserted += inserted;
            }
            Err(e) => {
                return e.into();
            }
        }
    }

    *affected_rows = total_inserted;
    RemDbError::Success
}

/// C API: 更新记录
#[no_mangle]
pub unsafe extern "C" fn remdb_update_record(
    handle: RemDbHandle,
    table_name: *const u8,
    set_clause: *const u8,
    where_clause: *const u8,
    affected_rows: *mut usize,
) -> RemDbError {
    if handle.is_null() || table_name.is_null() || set_clause.is_null() || affected_rows.is_null() {
        return RemDbError::ConfigError;
    }

    let db = &mut *handle;
    let rust_table_name = c_str_to_rust(table_name);
    let rust_set_clause = c_str_to_rust(set_clause);

    // 转换where子句
    let where_clause_str = if !where_clause.is_null() {
        Some(c_str_to_rust(where_clause))
    } else {
        None
    };
    let rust_where_clause = where_clause_str.as_deref();

    match db.update_record(&rust_table_name, &rust_set_clause, rust_where_clause) {
        Ok(updated) => {
            *affected_rows = updated;
            RemDbError::Success
        }
        Err(e) => e.into(),
    }
}

/// C API: 删除记录
#[no_mangle]
pub unsafe extern "C" fn remdb_delete_record(
    handle: RemDbHandle,
    table_name: *const u8,
    where_clause: *const u8,
    affected_rows: *mut usize,
) -> RemDbError {
    if handle.is_null() || table_name.is_null() || affected_rows.is_null() {
        return RemDbError::ConfigError;
    }

    let db = &mut *handle;
    let rust_table_name = c_str_to_rust(table_name);

    // 转换where子句
    let where_clause_str = if !where_clause.is_null() {
        Some(c_str_to_rust(where_clause))
    } else {
        None
    };
    let rust_where_clause = where_clause_str.as_deref();

    match db.delete_record(&rust_table_name, rust_where_clause) {
        Ok(deleted) => {
            *affected_rows = deleted;
            RemDbError::Success
        }
        Err(e) => e.into(),
    }
}

/// C API: 导出DDL
#[no_mangle]
pub unsafe extern "C" fn remdb_export_ddl(handle: RemDbHandle, path: *const u8) -> RemDbError {
    if handle.is_null() || path.is_null() {
        return RemDbError::ConfigError;
    }

    let db = &*handle;
    let rust_path = c_str_to_rust(path);

    match db.export_ddl(&rust_path) {
        Ok(_) => RemDbError::Success,
        Err(e) => e.into(),
    }
}

/// C API: 导出数据
#[no_mangle]
pub unsafe extern "C" fn remdb_export_data(handle: RemDbHandle, path: *const u8) -> RemDbError {
    if handle.is_null() || path.is_null() {
        return RemDbError::ConfigError;
    }

    let db = &*handle;
    let rust_path = c_str_to_rust(path);

    match db.export_data(&rust_path) {
        Ok(_) => RemDbError::Success,
        Err(e) => e.into(),
    }
}

/// C API: 获取当前HA角色
#[cfg(feature = "ha")]
#[no_mangle]
pub unsafe extern "C" fn remdb_ha_get_role(role: *mut RemDbHARole) -> RemDbError {
    if role.is_null() {
        return RemDbError::ConfigError;
    }

    match crate::ha::get_role() {
        Ok(ha_role) => {
            *role = match ha_role {
                crate::ha::HARole::Master => RemDbHARole::Master,
                crate::ha::HARole::Slave => RemDbHARole::Slave,
                crate::ha::HARole::Auto => RemDbHARole::Auto,
            };
            RemDbError::Success
        }
        Err(e) => e.into(),
    }
}

/// C API: 提升为Master节点
#[cfg(feature = "ha")]
#[no_mangle]
pub unsafe extern "C" fn remdb_ha_promote_to_master() -> RemDbError {
    match crate::ha::promote_to_master() {
        Ok(_) => RemDbError::Success,
        Err(e) => e.into(),
    }
}

/// C API: 降级为Slave节点
#[cfg(feature = "ha")]
#[no_mangle]
pub unsafe extern "C" fn remdb_ha_demote_to_slave() -> RemDbError {
    match crate::ha::demote_to_slave() {
        Ok(_) => RemDbError::Success,
        Err(e) => e.into(),
    }
}

/// C API: 检查HA状态
#[cfg(feature = "ha")]
#[no_mangle]
pub unsafe extern "C" fn remdb_ha_check_status() -> RemDbError {
    match crate::ha::check_status() {
        Ok(_) => RemDbError::Success,
        Err(e) => e.into(),
    }
}

/// C API: 获取复制模式
#[cfg(feature = "ha")]
#[no_mangle]
pub unsafe extern "C" fn remdb_ha_get_replication_mode(
    mode: *mut RemDbReplicationMode,
) -> RemDbError {
    if mode.is_null() {
        return RemDbError::ConfigError;
    }

    match crate::ha::get_replication_mode() {
        Ok(replication_mode) => {
            *mode = match replication_mode {
                crate::ha::ReplicationMode::Async => RemDbReplicationMode::Async,
                crate::ha::ReplicationMode::Sync => RemDbReplicationMode::Sync,
            };
            RemDbError::Success
        }
        Err(e) => e.into(),
    }
}

/// C API: 创建数据库
#[no_mangle]
pub unsafe extern "C" fn remdb_create_database(
    name: *const u8,
    schema: *const u8,
    config: *const RemDbDatabaseConfig,
) -> RemDbError {
    if name.is_null() {
        return RemDbError::ConfigError;
    }

    // 检查数据库名称长度
    let name_len = _c_strlen(name);
    if name_len == 0 || name_len > 128 {
        // 限制数据库名称长度为128个字符
        return RemDbError::ConfigError;
    }

    let rust_name = c_str_to_rust(name);
    let rust_schema = if schema.is_null() {
        ""
    } else {
        &*Box::leak(Box::new(c_str_to_rust(schema)))
    };

    // 转换数据库配置
    let rust_config = if config.is_null() {
        None
    } else {
        let c_config = &*config;
        Some(crate::DatabaseConfig {
            name: if c_config.name.is_null() {
                rust_name.clone()
            } else {
                c_str_to_rust(c_config.name)
            },
            memory_limit: if c_config.memory_limit.is_null() {
                None
            } else {
                Some(*c_config.memory_limit)
            },
            max_tables: if c_config.max_tables.is_null() {
                None
            } else {
                Some(*c_config.max_tables)
            },
            wal_mode: if c_config.wal_mode.is_null() {
                None
            } else {
                Some(c_str_to_rust(c_config.wal_mode))
            },
            default_index_type: if c_config.default_index_type.is_null() {
                None
            } else {
                Some(crate::types::IndexType::Hash)
            },
            temp_store: if c_config.temp_store.is_null() {
                None
            } else {
                Some(c_str_to_rust(c_config.temp_store))
            },
        })
    };

    // 创建数据库管理器
    let mut db_manager = crate::DatabaseManager::new(10); // 默认最大10个数据库

    match db_manager.create_database(&rust_name, rust_schema, rust_config) {
        Ok(_) => RemDbError::Success,
        Err(e) => e.into(),
    }
}

/// C API: 使用指定数据库
#[no_mangle]
pub unsafe extern "C" fn remdb_use_database(handle: RemDbHandle, name: *const u8) -> RemDbError {
    if handle.is_null() || name.is_null() {
        return RemDbError::ConfigError;
    }

    // 检查数据库名称长度
    let name_len = _c_strlen(name);
    if name_len == 0 || name_len > 128 {
        // 限制数据库名称长度为128个字符
        return RemDbError::ConfigError;
    }

    let db = &mut *handle;
    let rust_name = c_str_to_rust(name);

    match db.use_database(&rust_name) {
        Ok(_) => RemDbError::Success,
        Err(e) => e.into(),
    }
}

/// C API: 关闭指定数据库
#[no_mangle]
pub unsafe extern "C" fn remdb_close_database(handle: RemDbHandle, name: *const u8) -> RemDbError {
    if handle.is_null() || name.is_null() {
        return RemDbError::ConfigError;
    }

    // 检查数据库名称长度
    let name_len = _c_strlen(name);
    if name_len == 0 || name_len > 128 {
        // 限制数据库名称长度为128个字符
        return RemDbError::ConfigError;
    }

    let db = &mut *handle;
    let rust_name = c_str_to_rust(name);

    match db.close_database(&rust_name) {
        Ok(_) => RemDbError::Success,
        Err(e) => e.into(),
    }
}

/// C API: 删除指定数据库
#[no_mangle]
pub unsafe extern "C" fn remdb_drop_database(handle: RemDbHandle, name: *const u8) -> RemDbError {
    if handle.is_null() || name.is_null() {
        return RemDbError::ConfigError;
    }

    // 检查数据库名称长度
    let name_len = _c_strlen(name);
    if name_len == 0 || name_len > 128 {
        // 限制数据库名称长度为128个字符
        return RemDbError::ConfigError;
    }

    let db = &mut *handle;
    let rust_name = c_str_to_rust(name);

    match db.drop_database(&rust_name) {
        Ok(_) => RemDbError::Success,
        Err(e) => e.into(),
    }
}

/// C API: 获取数据库列表
#[no_mangle]
pub unsafe extern "C" fn remdb_get_databases(
    handle: RemDbHandle,
    databases: *mut *mut RemDbDatabaseInfo,
    count: *mut usize,
) -> RemDbError {
    if handle.is_null() || databases.is_null() || count.is_null() {
        return RemDbError::ConfigError;
    }

    let db = &*handle;

    match db.databases() {
        Ok(rust_databases) => {
            // 分配内存存储数据库信息
            let c_databases = alloc::alloc::alloc(
                alloc::alloc::Layout::array::<RemDbDatabaseInfo>(rust_databases.len())
                    .expect("failed to allocate memory"),
            ) as *mut RemDbDatabaseInfo;

            if c_databases.is_null() {
                return RemDbError::OutOfMemory;
            }

            // 转换数据库信息
            for (i, rust_db) in rust_databases.iter().enumerate() {
                let c_db = &mut *c_databases.offset(i as isize);
                *c_db = rust_db.clone().into();
            }

            *databases = c_databases;
            *count = rust_databases.len();
            RemDbError::Success
        }
        Err(e) => e.into(),
    }
}

/// C API: 释放数据库列表内存
#[no_mangle]
pub unsafe extern "C" fn remdb_free_databases(
    databases: *mut RemDbDatabaseInfo,
    count: usize,
) -> RemDbError {
    if !databases.is_null() {
        alloc::alloc::dealloc(
            databases as *mut u8,
            alloc::alloc::Layout::array::<RemDbDatabaseInfo>(count)
                .expect("failed to allocate memory"),
        );
    }
    RemDbError::Success
}