sz-orm-cpp 7.6.0

C++ bindings for sz-orm-core via extern C + C ABI
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
//! # SZ-ORM C++ Bindings
//!
//! Provides sz-orm-core's Pool/Query API to C++ via `extern "C"` + C ABI
//! (SQLite backend, real and usable).
//!
//! C++ side wrapper see `cpp/szorm.h` (use `szorm::Pool` after `#include <szorm.h>`).

use std::ffi::{c_char, CStr, CString};

use sz_orm_cabi::{
    PoolConfigC, PoolMetricsC, PoolStatsC, QueryJsonResult, QueryResultC, SzOrmPoolHandle,
    SzOrmQueryBuilderHandle, SzOrmTransactionHandle,
};

/// Create connection pool (real creation, SQLite backend)
///
/// Returns handle, null indicates failure.
///
/// # Safety
///
/// SAFETY: `dsn` must be a valid NUL-terminated C string; `config` may be null.
#[no_mangle]
pub unsafe extern "C" fn sz_orm_cpp_pool_new(
    dsn: *const c_char,
    config: *const PoolConfigC,
) -> SzOrmPoolHandle {
    // SAFETY: 转发到 cabi
    unsafe { sz_orm_cabi::sz_orm_pool_new(dsn, config) }
}

/// Free connection pool
///
/// # Safety
///
/// SAFETY: handle must be a valid handle returned by `sz_orm_cpp_pool_new`.
#[no_mangle]
pub unsafe extern "C" fn sz_orm_cpp_pool_free(handle: SzOrmPoolHandle) {
    // SAFETY: 转发到 cabi
    unsafe { sz_orm_cabi::sz_orm_pool_free(handle) }
}

/// Health check (real acquire + ping)
///
/// # Safety
///
/// SAFETY: handle must be a valid handle returned by `sz_orm_cpp_pool_new`.
#[no_mangle]
pub unsafe extern "C" fn sz_orm_cpp_ping(handle: SzOrmPoolHandle) -> i32 {
    // SAFETY: 转发到 cabi
    unsafe { sz_orm_cabi::sz_orm_ping(handle) }
}

/// Execute query, return JSON row array (caller frees with `sz_orm_cpp_string_free`)
///
/// # Safety
///
/// SAFETY: handle must be a valid handle returned by `sz_orm_cpp_pool_new`;
/// `sql` must be a valid NUL-terminated C string.
#[no_mangle]
pub unsafe extern "C" fn sz_orm_cpp_query(
    handle: SzOrmPoolHandle,
    sql: *const c_char,
) -> *mut c_char {
    if handle.is_null() || sql.is_null() {
        return std::ptr::null_mut();
    }
    // SAFETY: 调用方保证 handle 有效
    let result = unsafe { sz_orm_cabi::sz_orm_query(handle, sql) };
    if result.is_null() {
        return std::ptr::null_mut();
    }
    // SAFETY: result 由 sz_orm_query 分配
    let result_box = unsafe { Box::from_raw(result) };
    let json = if result_box.success != 0 && !result_box.json.is_null() {
        // SAFETY: json 是有效 NUL 结尾 C 字符串
        unsafe { CStr::from_ptr(result_box.json) }
            .to_str()
            .map(|s| s.to_string())
            .unwrap_or_default()
    } else {
        // SAFETY: result_box 配对释放
        unsafe {
            sz_orm_cabi::sz_orm_query_result_free(Box::into_raw(result_box));
        }
        return std::ptr::null_mut();
    };
    // SAFETY: result_box 配对释放
    unsafe {
        sz_orm_cabi::sz_orm_query_result_free(Box::into_raw(result_box));
    }
    match CString::new(json) {
        Ok(c) => c.into_raw(),
        Err(_) => std::ptr::null_mut(),
    }
}

/// Free string returned by `sz_orm_cpp_query`
///
/// # Safety
///
/// SAFETY: `ptr` must be a pointer returned by `sz_orm_cpp_query` (or null).
#[no_mangle]
pub unsafe extern "C" fn sz_orm_cpp_string_free(ptr: *mut c_char) {
    if ptr.is_null() {
        return;
    }
    // SAFETY: ptr 由 CString::into_raw 分配,配对释放
    unsafe {
        drop(CString::from_raw(ptr));
    }
}

/// Execute write statement, return heap-allocated `QueryResultC` (free with `sz_orm_cpp_result_free`)
///
/// # Safety
///
/// SAFETY: handle must be a valid handle returned by `sz_orm_cpp_pool_new`;
/// `sql` must be a valid NUL-terminated C string.
#[no_mangle]
pub unsafe extern "C" fn sz_orm_cpp_execute(
    handle: SzOrmPoolHandle,
    sql: *const c_char,
) -> *mut QueryResultC {
    if handle.is_null() || sql.is_null() {
        return std::ptr::null_mut();
    }
    // SAFETY: 转发到 cabi
    let result = unsafe { sz_orm_cabi::sz_orm_execute(handle, sql) };
    Box::into_raw(Box::new(result))
}

/// Free result returned by `sz_orm_cpp_execute`
///
/// # Safety
///
/// SAFETY: `ptr` must be a pointer returned by `sz_orm_cpp_execute` (or null).
#[no_mangle]
pub unsafe extern "C" fn sz_orm_cpp_result_free(ptr: *mut QueryResultC) {
    if ptr.is_null() {
        return;
    }
    // SAFETY: ptr 由 sz_orm_cpp_execute 分配,配对释放
    unsafe {
        drop(Box::from_raw(ptr));
    }
}

/// Get version number
#[no_mangle]
pub extern "C" fn sz_orm_cpp_version() -> u32 {
    sz_orm_cabi::sz_orm_version()
}

// ============================================================================
// 事务 API 转发(REQ-BND-006)
// ============================================================================

/// Begin transaction, return transaction handle (null indicates failure)
///
/// # Safety
///
/// SAFETY: `handle` must be a valid handle returned by `sz_orm_cpp_pool_new`.
#[no_mangle]
pub unsafe extern "C" fn sz_orm_cpp_transaction_begin(
    handle: SzOrmPoolHandle,
) -> SzOrmTransactionHandle {
    // SAFETY: 转发到 cabi
    unsafe { sz_orm_cabi::sz_orm_transaction_begin(handle) }
}

/// Execute SQL in transaction, return heap-allocated `QueryResultC`
///
/// # Safety
///
/// SAFETY: `tx_handle` must be valid; `sql` must be a valid NUL-terminated C string.
#[no_mangle]
pub unsafe extern "C" fn sz_orm_cpp_transaction_execute(
    tx_handle: SzOrmTransactionHandle,
    sql: *const c_char,
) -> *mut QueryResultC {
    if tx_handle.is_null() || sql.is_null() {
        return std::ptr::null_mut();
    }
    // SAFETY: 转发到 cabi
    let result = unsafe { sz_orm_cabi::sz_orm_transaction_execute(tx_handle, sql) };
    Box::into_raw(Box::new(result))
}

/// Commit transaction, return 1=success 0=failure
///
/// # Safety
///
/// SAFETY: `tx_handle` must be valid.
#[no_mangle]
pub unsafe extern "C" fn sz_orm_cpp_transaction_commit(tx_handle: SzOrmTransactionHandle) -> i32 {
    // SAFETY: 转发到 cabi
    unsafe { sz_orm_cabi::sz_orm_transaction_commit(tx_handle) }
}

/// Rollback transaction, return 1=success 0=failure
///
/// # Safety
///
/// SAFETY: `tx_handle` must be valid.
#[no_mangle]
pub unsafe extern "C" fn sz_orm_cpp_transaction_rollback(tx_handle: SzOrmTransactionHandle) -> i32 {
    // SAFETY: 转发到 cabi
    unsafe { sz_orm_cabi::sz_orm_transaction_rollback(tx_handle) }
}

/// Free transaction handle (auto rollback if still active)
///
/// # Safety
///
/// SAFETY: `tx_handle` must be valid.
#[no_mangle]
pub unsafe extern "C" fn sz_orm_cpp_transaction_free(tx_handle: SzOrmTransactionHandle) {
    // SAFETY: 转发到 cabi
    unsafe { sz_orm_cabi::sz_orm_transaction_free(tx_handle) }
}

// ============================================================================
// 模型级 API 转发(REQ-BND-013)
// ============================================================================

/// Insert row on pool, return heap-allocated `QueryResultC`
///
/// # Safety
///
/// SAFETY: `handle` must be valid; all parameters must be valid NUL-terminated C strings.
#[no_mangle]
pub unsafe extern "C" fn sz_orm_cpp_model_insert(
    handle: SzOrmPoolHandle,
    table: *const c_char,
    fields_json: *const c_char,
    values_json: *const c_char,
) -> *mut QueryResultC {
    if handle.is_null() || table.is_null() || fields_json.is_null() || values_json.is_null() {
        return std::ptr::null_mut();
    }
    // SAFETY: 转发到 cabi
    let result =
        unsafe { sz_orm_cabi::sz_orm_model_insert(handle, table, fields_json, values_json) };
    Box::into_raw(Box::new(result))
}

/// Update row on pool, return heap-allocated `QueryResultC`
///
/// # Safety
///
/// SAFETY: `handle` must be valid; all parameters must be valid NUL-terminated C strings.
#[no_mangle]
pub unsafe extern "C" fn sz_orm_cpp_model_update(
    handle: SzOrmPoolHandle,
    table: *const c_char,
    set_json: *const c_char,
    where_clause: *const c_char,
    where_params_json: *const c_char,
) -> *mut QueryResultC {
    if handle.is_null() || table.is_null() || set_json.is_null() {
        return std::ptr::null_mut();
    }
    // SAFETY: 转发到 cabi
    let result = unsafe {
        sz_orm_cabi::sz_orm_model_update(handle, table, set_json, where_clause, where_params_json)
    };
    Box::into_raw(Box::new(result))
}

/// Delete row on pool, return heap-allocated `QueryResultC`
///
/// # Safety
///
/// SAFETY: `handle` must be valid; all parameters must be valid NUL-terminated C strings.
#[no_mangle]
pub unsafe extern "C" fn sz_orm_cpp_model_delete(
    handle: SzOrmPoolHandle,
    table: *const c_char,
    where_clause: *const c_char,
    where_params_json: *const c_char,
) -> *mut QueryResultC {
    if handle.is_null() || table.is_null() {
        return std::ptr::null_mut();
    }
    // SAFETY: 转发到 cabi
    let result =
        unsafe { sz_orm_cabi::sz_orm_model_delete(handle, table, where_clause, where_params_json) };
    Box::into_raw(Box::new(result))
}

/// Query row on pool, return JSON row array string (free with `sz_orm_cpp_string_free`)
///
/// # Safety
///
/// SAFETY: `handle` must be valid; all parameters must be valid NUL-terminated C strings.
#[no_mangle]
pub unsafe extern "C" fn sz_orm_cpp_model_find(
    handle: SzOrmPoolHandle,
    table: *const c_char,
    where_clause: *const c_char,
    where_params_json: *const c_char,
) -> *mut c_char {
    if handle.is_null() || table.is_null() {
        return std::ptr::null_mut();
    }
    // SAFETY: 转发到 cabi
    unsafe { sz_orm_cabi::sz_orm_model_find(handle, table, where_clause, where_params_json) }
}

/// Insert row in transaction, return heap-allocated `QueryResultC`
///
/// # Safety
///
/// SAFETY: `tx_handle` must be valid; all parameters must be valid NUL-terminated C strings.
#[no_mangle]
pub unsafe extern "C" fn sz_orm_cpp_model_insert_tx(
    tx_handle: SzOrmTransactionHandle,
    table: *const c_char,
    fields_json: *const c_char,
    values_json: *const c_char,
) -> *mut QueryResultC {
    if tx_handle.is_null() || table.is_null() || fields_json.is_null() || values_json.is_null() {
        return std::ptr::null_mut();
    }
    // SAFETY: 转发到 cabi
    let result =
        unsafe { sz_orm_cabi::sz_orm_model_insert_tx(tx_handle, table, fields_json, values_json) };
    Box::into_raw(Box::new(result))
}

/// Update row in transaction, return heap-allocated `QueryResultC`
///
/// # Safety
///
/// SAFETY: `tx_handle` must be valid; all parameters must be valid NUL-terminated C strings.
#[no_mangle]
pub unsafe extern "C" fn sz_orm_cpp_model_update_tx(
    tx_handle: SzOrmTransactionHandle,
    table: *const c_char,
    set_json: *const c_char,
    where_clause: *const c_char,
    where_params_json: *const c_char,
) -> *mut QueryResultC {
    if tx_handle.is_null() || table.is_null() || set_json.is_null() {
        return std::ptr::null_mut();
    }
    // SAFETY: 转发到 cabi
    let result = unsafe {
        sz_orm_cabi::sz_orm_model_update_tx(
            tx_handle,
            table,
            set_json,
            where_clause,
            where_params_json,
        )
    };
    Box::into_raw(Box::new(result))
}

/// Delete row in transaction, return heap-allocated `QueryResultC`
///
/// # Safety
///
/// SAFETY: `tx_handle` must be valid; all parameters must be valid NUL-terminated C strings.
#[no_mangle]
pub unsafe extern "C" fn sz_orm_cpp_model_delete_tx(
    tx_handle: SzOrmTransactionHandle,
    table: *const c_char,
    where_clause: *const c_char,
    where_params_json: *const c_char,
) -> *mut QueryResultC {
    if tx_handle.is_null() || table.is_null() {
        return std::ptr::null_mut();
    }
    // SAFETY: 转发到 cabi
    let result = unsafe {
        sz_orm_cabi::sz_orm_model_delete_tx(tx_handle, table, where_clause, where_params_json)
    };
    Box::into_raw(Box::new(result))
}

/// Query row in transaction, return JSON row array string (free with `sz_orm_cpp_string_free`)
///
/// # Safety
///
/// SAFETY: `tx_handle` must be valid; all parameters must be valid NUL-terminated C strings.
#[no_mangle]
pub unsafe extern "C" fn sz_orm_cpp_model_find_tx(
    tx_handle: SzOrmTransactionHandle,
    table: *const c_char,
    where_clause: *const c_char,
    where_params_json: *const c_char,
) -> *mut c_char {
    if tx_handle.is_null() || table.is_null() {
        return std::ptr::null_mut();
    }
    // SAFETY: 转发到 cabi
    unsafe { sz_orm_cabi::sz_orm_model_find_tx(tx_handle, table, where_clause, where_params_json) }
}

// ============================================================================
// QueryBuilder API 转发(v6.9.0 REQ-BND-QB)
// ============================================================================

/// Create QueryBuilder, return handle (null indicates failure)
///
/// # Safety
///
/// SAFETY: 返回的句柄必须通过 `sz_orm_cpp_qb_free` 释放。
#[no_mangle]
pub unsafe extern "C" fn sz_orm_cpp_qb_new(db_type: u32) -> SzOrmQueryBuilderHandle {
    // SAFETY: 转发到 cabi
    unsafe { sz_orm_cabi::sz_orm_qb_new(db_type) }
}

/// Set table name on QueryBuilder
///
/// # Safety
///
/// SAFETY: `qb` 必须有效;`table` 必须是有效的 NUL 终止 C 字符串。
#[no_mangle]
pub unsafe extern "C" fn sz_orm_cpp_qb_table(
    qb: SzOrmQueryBuilderHandle,
    table: *const c_char,
) -> i32 {
    // SAFETY: 转发到 cabi
    unsafe { sz_orm_cabi::sz_orm_qb_table(qb, table) }
}

/// Add WHERE eq condition
///
/// # Safety
///
/// SAFETY: `qb` 必须有效;`field` 和 `value_json` 必须是有效的 NUL 终止 C 字符串。
#[no_mangle]
pub unsafe extern "C" fn sz_orm_cpp_qb_where_eq(
    qb: SzOrmQueryBuilderHandle,
    field: *const c_char,
    value_json: *const c_char,
) -> i32 {
    // SAFETY: 转发到 cabi
    unsafe { sz_orm_cabi::sz_orm_qb_where_eq(qb, field, value_json) }
}

/// Add ORDER BY clause
///
/// # Safety
///
/// SAFETY: `qb` 必须有效;`field` 必须是有效的 NUL 终止 C 字符串。
#[no_mangle]
pub unsafe extern "C" fn sz_orm_cpp_qb_order_by(
    qb: SzOrmQueryBuilderHandle,
    field: *const c_char,
    desc: i32,
) -> i32 {
    // SAFETY: 转发到 cabi
    unsafe { sz_orm_cabi::sz_orm_qb_order_by(qb, field, desc) }
}

/// Set LIMIT
///
/// # Safety
///
/// SAFETY: `qb` 必须有效。
#[no_mangle]
pub unsafe extern "C" fn sz_orm_cpp_qb_limit(qb: SzOrmQueryBuilderHandle, limit: u64) -> i32 {
    // SAFETY: 转发到 cabi
    unsafe { sz_orm_cabi::sz_orm_qb_limit(qb, limit) }
}

/// Build SQL + params JSON, return C string (free with `sz_orm_cpp_qb_result_free`)
///
/// # Safety
///
/// SAFETY: `qb` 必须有效。
#[no_mangle]
pub unsafe extern "C" fn sz_orm_cpp_qb_build(qb: SzOrmQueryBuilderHandle) -> *mut c_char {
    // SAFETY: 转发到 cabi
    unsafe { sz_orm_cabi::sz_orm_qb_build(qb) }
}

/// Free QueryBuilder handle
///
/// # Safety
///
/// SAFETY: `qb` 必须是 `sz_orm_cpp_qb_new` 返回的句柄(或 null)。
#[no_mangle]
pub unsafe extern "C" fn sz_orm_cpp_qb_free(qb: SzOrmQueryBuilderHandle) {
    // SAFETY: 转发到 cabi
    unsafe { sz_orm_cabi::sz_orm_qb_free(qb) }
}

/// Free build result string
///
/// # Safety
///
/// SAFETY: `result` 必须是 `sz_orm_cpp_qb_build` 返回的指针(或 null)。
#[no_mangle]
pub unsafe extern "C" fn sz_orm_cpp_qb_result_free(result: *mut c_char) {
    // SAFETY: 转发到 cabi
    unsafe { sz_orm_cabi::sz_orm_qb_result_free(result) }
}

// ============================================================================
// ActiveModel API 转发(v6.9.0 REQ-BND-AM)
// ============================================================================

/// ActiveModel create (insert), return heap-allocated `QueryResultC`
///
/// # Safety
///
/// SAFETY: `handle` 必须有效;所有字符串参数必须是有效的 NUL 终止 C 字符串。
#[no_mangle]
pub unsafe extern "C" fn sz_orm_cpp_active_model_create(
    handle: SzOrmPoolHandle,
    table: *const c_char,
    fields_json: *const c_char,
    values_json: *const c_char,
) -> *mut QueryResultC {
    if handle.is_null() || table.is_null() || fields_json.is_null() || values_json.is_null() {
        return std::ptr::null_mut();
    }
    // SAFETY: 转发到 cabi
    let result =
        unsafe { sz_orm_cabi::sz_orm_model_insert(handle, table, fields_json, values_json) };
    Box::into_raw(Box::new(result))
}

/// ActiveModel set (update), return heap-allocated `QueryResultC`
///
/// # Safety
///
/// SAFETY: `handle` 必须有效;所有字符串参数必须是有效的 NUL 终止 C 字符串。
#[no_mangle]
pub unsafe extern "C" fn sz_orm_cpp_active_model_set(
    handle: SzOrmPoolHandle,
    table: *const c_char,
    set_json: *const c_char,
    where_clause: *const c_char,
    where_params_json: *const c_char,
) -> *mut QueryResultC {
    if handle.is_null() || table.is_null() || set_json.is_null() {
        return std::ptr::null_mut();
    }
    // SAFETY: 转发到 cabi
    let result = unsafe {
        sz_orm_cabi::sz_orm_model_update(handle, table, set_json, where_clause, where_params_json)
    };
    Box::into_raw(Box::new(result))
}

/// ActiveModel get (find), return JSON string (free with `sz_orm_cpp_string_free`)
///
/// # Safety
///
/// SAFETY: `handle` 必须有效;所有字符串参数必须是有效的 NUL 终止 C 字符串。
#[no_mangle]
pub unsafe extern "C" fn sz_orm_cpp_active_model_get(
    handle: SzOrmPoolHandle,
    table: *const c_char,
    where_clause: *const c_char,
    where_params_json: *const c_char,
) -> *mut c_char {
    if handle.is_null() || table.is_null() {
        return std::ptr::null_mut();
    }
    // SAFETY: 转发到 cabi
    unsafe { sz_orm_cabi::sz_orm_model_find(handle, table, where_clause, where_params_json) }
}

/// ActiveModel save (insert), return heap-allocated `QueryResultC`
///
/// # Safety
///
/// SAFETY: `handle` 必须有效;所有字符串参数必须是有效的 NUL 终止 C 字符串。
#[no_mangle]
pub unsafe extern "C" fn sz_orm_cpp_active_model_save(
    handle: SzOrmPoolHandle,
    table: *const c_char,
    fields_json: *const c_char,
    values_json: *const c_char,
) -> *mut QueryResultC {
    if handle.is_null() || table.is_null() || fields_json.is_null() || values_json.is_null() {
        return std::ptr::null_mut();
    }
    // SAFETY: 转发到 cabi
    let result =
        unsafe { sz_orm_cabi::sz_orm_model_insert(handle, table, fields_json, values_json) };
    Box::into_raw(Box::new(result))
}

/// ActiveModel delete, return heap-allocated `QueryResultC`
///
/// # Safety
///
/// SAFETY: `handle` 必须有效;所有字符串参数必须是有效的 NUL 终止 C 字符串。
#[no_mangle]
pub unsafe extern "C" fn sz_orm_cpp_active_model_delete(
    handle: SzOrmPoolHandle,
    table: *const c_char,
    where_clause: *const c_char,
    where_params_json: *const c_char,
) -> *mut QueryResultC {
    if handle.is_null() || table.is_null() {
        return std::ptr::null_mut();
    }
    // SAFETY: 转发到 cabi
    let result =
        unsafe { sz_orm_cabi::sz_orm_model_delete(handle, table, where_clause, where_params_json) };
    Box::into_raw(Box::new(result))
}

/// Get pool statistics
///
/// # Safety
///
/// SAFETY: handle must be a valid handle returned by `sz_orm_cpp_pool_new`.
#[no_mangle]
pub unsafe extern "C" fn sz_orm_cpp_pool_stats(handle: SzOrmPoolHandle) -> PoolStatsC {
    // SAFETY: 转发到 cabi,handle 有效性由调用方保证
    unsafe { sz_orm_cabi::sz_orm_pool_stats(handle) }
}

/// Get pool metrics
///
/// # Safety
///
/// SAFETY: handle must be a valid handle returned by `sz_orm_cpp_pool_new`.
#[no_mangle]
pub unsafe extern "C" fn sz_orm_cpp_pool_metrics(handle: SzOrmPoolHandle) -> PoolMetricsC {
    // SAFETY: 转发到 cabi,handle 有效性由调用方保证
    unsafe { sz_orm_cabi::sz_orm_pool_metrics(handle) }
}

/// Query single row as JSON
///
/// # Safety
///
/// SAFETY: handle must be valid; sql must be a valid NUL-terminated C string.
#[no_mangle]
pub unsafe extern "C" fn sz_orm_cpp_query_one(
    handle: SzOrmPoolHandle,
    sql: *const c_char,
) -> *mut QueryJsonResult {
    // SAFETY: 转发到 cabi,参数有效性由调用方保证
    unsafe { sz_orm_cabi::sz_orm_query_one(handle, sql) }
}

/// Execute batch SQL
///
/// # Safety
///
/// SAFETY: handle must be valid; sql must be a valid NUL-terminated C string.
#[no_mangle]
pub unsafe extern "C" fn sz_orm_cpp_execute_batch(
    handle: SzOrmPoolHandle,
    sql: *const c_char,
) -> QueryResultC {
    // SAFETY: 转发到 cabi,参数有效性由调用方保证
    unsafe { sz_orm_cabi::sz_orm_execute_batch(handle, sql) }
}

/// Free query result
///
/// # Safety
///
/// SAFETY: result must be a valid pointer returned by `sz_orm_cpp_query_one`.
#[no_mangle]
pub unsafe extern "C" fn sz_orm_cpp_query_result_free(result: *mut QueryJsonResult) {
    // SAFETY: 转发到 cabi,result 有效性由调用方保证
    unsafe { sz_orm_cabi::sz_orm_query_result_free(result) }
}

/// Get error description string
///
/// # Safety
///
/// SAFETY: Caller must free the returned string with `sz_orm_cpp_string_free`.
#[no_mangle]
pub unsafe extern "C" fn sz_orm_cpp_error_description(code: i32) -> *mut c_char {
    // SAFETY: 转发到 cabi
    unsafe { sz_orm_cabi::sz_orm_error_description(code) }
}

/// Check if table exists
///
/// # Safety
///
/// SAFETY: handle must be valid; table must be a valid NUL-terminated C string.
#[no_mangle]
pub unsafe extern "C" fn sz_orm_cpp_table_exists(
    handle: SzOrmPoolHandle,
    table: *const c_char,
) -> i32 {
    // SAFETY: 转发到 cabi,参数有效性由调用方保证
    unsafe { sz_orm_cabi::sz_orm_table_exists(handle, table) }
}

/// Count rows in table
///
/// # Safety
///
/// SAFETY: handle must be valid; table must be a valid NUL-terminated C string.
#[no_mangle]
pub unsafe extern "C" fn sz_orm_cpp_count(handle: SzOrmPoolHandle, table: *const c_char) -> i64 {
    // SAFETY: 转发到 cabi,参数有效性由调用方保证
    unsafe { sz_orm_cabi::sz_orm_count(handle, table) }
}

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

    fn test_pool() -> SzOrmPoolHandle {
        let dsn = CString::new("sqlite::memory:").unwrap();
        // SAFETY: dsn 有效
        unsafe { sz_orm_cpp_pool_new(dsn.as_ptr(), std::ptr::null()) }
    }

    #[test]
    fn test_cpp_pool_new_creates_real_pool() {
        let pool = test_pool();
        assert!(!pool.is_null(), "pool_new should create a real pool");
        // SAFETY: pool 有效
        unsafe { sz_orm_cpp_pool_free(pool) };
    }

    #[test]
    fn test_cpp_ping_healthy() {
        let pool = test_pool();
        assert!(!pool.is_null());
        // SAFETY: pool 有效
        let healthy = unsafe { sz_orm_cpp_ping(pool) };
        assert_eq!(healthy, 1, "fresh pool should be healthy");
        // SAFETY: pool 有效
        unsafe { sz_orm_cpp_pool_free(pool) };
    }

    #[test]
    fn test_cpp_execute_and_query_roundtrip() {
        let pool = test_pool();
        assert!(!pool.is_null());

        let create =
            CString::new("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)").unwrap();
        // SAFETY: pool/sql 有效
        let rp = unsafe { sz_orm_cpp_execute(pool, create.as_ptr()) };
        assert!(!rp.is_null(), "CREATE should succeed");
        // SAFETY: rp 由 sz_orm_cpp_execute 分配
        let r = unsafe { Box::from_raw(rp) };
        assert_eq!(
            r.success, 1,
            "CREATE should succeed, got code {}",
            r.error_code
        );
        // SAFETY: r 配对释放
        unsafe { sz_orm_cpp_result_free(Box::into_raw(r)) };

        let insert = CString::new("INSERT INTO users (name) VALUES ('Alice'), ('Bob')").unwrap();
        // SAFETY: pool/sql 有效
        let rp = unsafe { sz_orm_cpp_execute(pool, insert.as_ptr()) };
        assert!(!rp.is_null(), "INSERT should succeed");
        // SAFETY: rp 由 sz_orm_cpp_execute 分配
        let r = unsafe { Box::from_raw(rp) };
        assert_eq!(r.success, 1);
        assert_eq!(r.rows_affected, 2, "two rows inserted");
        // SAFETY: r 配对释放
        unsafe { sz_orm_cpp_result_free(Box::into_raw(r)) };

        let q = CString::new("SELECT id, name FROM users ORDER BY id").unwrap();
        // SAFETY: pool/sql 有效
        let json_ptr = unsafe { sz_orm_cpp_query(pool, q.as_ptr()) };
        assert!(!json_ptr.is_null(), "query should return JSON");
        // SAFETY: json_ptr 有效
        let json = unsafe { CStr::from_ptr(json_ptr) }
            .to_string_lossy()
            .into_owned();
        assert!(
            json.contains("Alice"),
            "query rows should contain Alice: {json}"
        );
        assert!(
            json.contains("Bob"),
            "query rows should contain Bob: {json}"
        );
        // SAFETY: json_ptr 由 sz_orm_cpp_query 分配,配对释放
        unsafe { sz_orm_cpp_string_free(json_ptr) };

        // SAFETY: pool 有效
        unsafe { sz_orm_cpp_pool_free(pool) };
    }

    #[test]
    fn test_cpp_query_invalid_sql_returns_null() {
        let pool = test_pool();
        assert!(!pool.is_null());
        let q = CString::new("SELECT * FROM nonexistent").unwrap();
        // SAFETY: pool/sql 有效
        let json_ptr = unsafe { sz_orm_cpp_query(pool, q.as_ptr()) };
        assert!(json_ptr.is_null(), "invalid SQL should return null");
        // SAFETY: pool 有效
        unsafe { sz_orm_cpp_pool_free(pool) };
    }

    #[test]
    fn test_cpp_null_args() {
        // SAFETY: null 参数合法调用
        let pool = unsafe { sz_orm_cpp_pool_new(std::ptr::null(), std::ptr::null()) };
        assert!(pool.is_null());
        // SAFETY: null 参数合法调用
        let r = unsafe { sz_orm_cpp_execute(std::ptr::null_mut(), std::ptr::null()) };
        assert!(r.is_null());
        // SAFETY: null 参数合法调用
        let q = unsafe { sz_orm_cpp_query(std::ptr::null_mut(), std::ptr::null()) };
        assert!(q.is_null());
    }

    #[test]
    fn test_cpp_version() {
        let v = sz_orm_cpp_version();
        assert!(v >= 1, "version should be >= 1, got {v}");
    }

    #[test]
    fn test_cpp_free_null_safe() {
        // SAFETY: null 参数合法调用
        unsafe { sz_orm_cpp_string_free(std::ptr::null_mut()) };
        // SAFETY: null 参数合法调用
        unsafe { sz_orm_cpp_result_free(std::ptr::null_mut()) };
    }

    #[test]
    fn test_cpp_ping_after_free_returns_zero() {
        // 使用 null handle 测试 ping(而非释放后的 UAF)
        // SAFETY: null handle 合法调用
        let healthy = unsafe { sz_orm_cpp_ping(std::ptr::null_mut()) };
        assert_eq!(healthy, 0, "null pool should not be healthy");
    }

    #[test]
    fn test_cpp_multiple_pools_independent() {
        let dsn1 = CString::new("sqlite::memory:").unwrap();
        // SAFETY: dsn1 有效
        let pool1 = unsafe { sz_orm_cpp_pool_new(dsn1.as_ptr(), std::ptr::null()) };
        let dsn2 = CString::new("sqlite::memory:").unwrap();
        // SAFETY: dsn2 有效
        let pool2 = unsafe { sz_orm_cpp_pool_new(dsn2.as_ptr(), std::ptr::null()) };
        assert!(!pool1.is_null());
        assert!(!pool2.is_null());
        assert_ne!(pool1, pool2, "pools should have distinct handles");
        // SAFETY: pools 有效
        unsafe {
            sz_orm_cpp_pool_free(pool1);
            sz_orm_cpp_pool_free(pool2);
        }
    }

    #[test]
    fn test_cpp_execute_empty_sql() {
        let pool = test_pool();
        assert!(!pool.is_null());
        let create = CString::new("CREATE TABLE cpp_e (id INTEGER PRIMARY KEY)").unwrap();
        // SAFETY: pool/sql 有效
        let r = unsafe { sz_orm_cpp_execute(pool, create.as_ptr()) };
        // SAFETY: r 配对释放
        unsafe { sz_orm_cpp_result_free(r) };
        // SAFETY: pool 有效
        unsafe { sz_orm_cpp_pool_free(pool) };
    }

    #[test]
    fn test_cpp_query_empty_table() {
        let pool = test_pool();
        assert!(!pool.is_null());
        let create = CString::new("CREATE TABLE empty_t (id INTEGER PRIMARY KEY)").unwrap();
        // SAFETY: pool/sql 有效
        let r = unsafe { sz_orm_cpp_execute(pool, create.as_ptr()) };
        // SAFETY: r 配对释放
        unsafe { sz_orm_cpp_result_free(r) };
        let q = CString::new("SELECT id FROM empty_t").unwrap();
        // SAFETY: pool/sql 有效
        let json_ptr = unsafe { sz_orm_cpp_query(pool, q.as_ptr()) };
        assert!(
            !json_ptr.is_null(),
            "empty table query should still return JSON"
        );
        // SAFETY: json_ptr 有效
        let json = unsafe { CStr::from_ptr(json_ptr) }
            .to_string_lossy()
            .into_owned();
        assert!(
            json.contains("[]") || json.is_empty() || json.contains("id"),
            "empty result should be empty array: {json}"
        );
        // SAFETY: json_ptr 配对释放
        unsafe { sz_orm_cpp_string_free(json_ptr) };
        // SAFETY: pool 有效
        unsafe { sz_orm_cpp_pool_free(pool) };
    }

    // ===== 新增测试:事务 + 模型级 API 转发(REQ-BND-006/013/014)=====

    fn model_test_pool() -> SzOrmPoolHandle {
        let pool = test_pool();
        assert!(!pool.is_null());
        let create =
            CString::new("CREATE TABLE cm_t (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)")
                .unwrap();
        // SAFETY: pool/sql 有效
        let r = unsafe { sz_orm_cpp_execute(pool, create.as_ptr()) };
        // SAFETY: r 配对释放
        unsafe { sz_orm_cpp_result_free(r) };
        pool
    }

    unsafe fn free_cpp_result(ptr: *mut QueryResultC) -> QueryResultC {
        if ptr.is_null() {
            return QueryResultC {
                success: 0,
                error_code: sz_orm_cabi::SzOrmErrorCode::InvalidArgument.as_i32(),
                rows_affected: 0,
                last_insert_id: 0,
            };
        }
        // SAFETY: ptr 由 sz_orm_cpp_model_* 分配
        let r = unsafe { Box::from_raw(ptr) };
        *r
    }

    unsafe fn free_cpp_str(ptr: *mut c_char) -> String {
        if ptr.is_null() {
            return String::new();
        }
        // SAFETY: ptr 有效
        let s = unsafe { CStr::from_ptr(ptr) }
            .to_string_lossy()
            .into_owned();
        // SAFETY: ptr 配对释放
        unsafe { sz_orm_cpp_string_free(ptr) };
        s
    }

    #[test]
    fn test_cpp_model_insert_find_roundtrip() {
        let pool = model_test_pool();
        let table = CString::new("cm_t").unwrap();
        let fields = CString::new(r#"["name","age"]"#).unwrap();
        let values = CString::new(r#"["Alice",30]"#).unwrap();
        // SAFETY: pool/table/fields/values 有效
        let r = unsafe {
            sz_orm_cpp_model_insert(pool, table.as_ptr(), fields.as_ptr(), values.as_ptr())
        };
        // SAFETY: r 有效
        let r = unsafe { free_cpp_result(r) };
        assert_eq!(
            r.success, 1,
            "cpp model_insert should succeed, code={}",
            r.error_code
        );
        assert_eq!(r.rows_affected, 1);

        let where_clause = CString::new("name = ?").unwrap();
        let where_params = CString::new(r#"["Alice"]"#).unwrap();
        // SAFETY: pool/table/where 有效
        let ptr = unsafe {
            sz_orm_cpp_model_find(
                pool,
                table.as_ptr(),
                where_clause.as_ptr(),
                where_params.as_ptr(),
            )
        };
        assert!(!ptr.is_null());
        // SAFETY: ptr 有效
        let json = unsafe { free_cpp_str(ptr) };
        assert!(
            json.contains("Alice"),
            "cpp model_find should contain Alice: {json}"
        );
        // SAFETY: pool 有效
        unsafe { sz_orm_cpp_pool_free(pool) };
    }

    #[test]
    fn test_cpp_model_update_delete_find() {
        let pool = model_test_pool();
        let table = CString::new("cm_t").unwrap();
        let fields = CString::new(r#"["name","age"]"#).unwrap();
        let values = CString::new(r#"["Bob",25]"#).unwrap();
        // SAFETY: pool/table/fields/values 有效
        let r = unsafe {
            sz_orm_cpp_model_insert(pool, table.as_ptr(), fields.as_ptr(), values.as_ptr())
        };
        // SAFETY: r 有效
        unsafe { free_cpp_result(r) };

        let set_json = CString::new(r#"{"age":26}"#).unwrap();
        let where_clause = CString::new("name = ?").unwrap();
        let where_params = CString::new(r#"["Bob"]"#).unwrap();
        // SAFETY: pool/table/set/where 有效
        let r = unsafe {
            sz_orm_cpp_model_update(
                pool,
                table.as_ptr(),
                set_json.as_ptr(),
                where_clause.as_ptr(),
                where_params.as_ptr(),
            )
        };
        // SAFETY: r 有效
        let r = unsafe { free_cpp_result(r) };
        assert_eq!(
            r.success, 1,
            "cpp model_update should succeed, code={}",
            r.error_code
        );

        // SAFETY: pool/table/where 有效
        let ptr = unsafe {
            sz_orm_cpp_model_find(
                pool,
                table.as_ptr(),
                where_clause.as_ptr(),
                where_params.as_ptr(),
            )
        };
        // SAFETY: ptr 有效
        let json = unsafe { free_cpp_str(ptr) };
        assert!(
            json.contains("26"),
            "cpp find after update should contain age 26: {json}"
        );

        // SAFETY: pool/table/where 有效
        let r = unsafe {
            sz_orm_cpp_model_delete(
                pool,
                table.as_ptr(),
                where_clause.as_ptr(),
                where_params.as_ptr(),
            )
        };
        // SAFETY: r 有效
        let r = unsafe { free_cpp_result(r) };
        assert_eq!(
            r.success, 1,
            "cpp model_delete should succeed, code={}",
            r.error_code
        );

        // SAFETY: pool/table/where 有效
        let ptr = unsafe {
            sz_orm_cpp_model_find(
                pool,
                table.as_ptr(),
                where_clause.as_ptr(),
                where_params.as_ptr(),
            )
        };
        // SAFETY: ptr 有效
        let json = unsafe { free_cpp_str(ptr) };
        assert!(
            json == "[]" || json == "null" || json.is_empty(),
            "cpp find after delete should be empty: {json}"
        );
        // SAFETY: pool 有效
        unsafe { sz_orm_cpp_pool_free(pool) };
    }

    #[test]
    fn test_cpp_model_insert_illegal_table() {
        let pool = model_test_pool();
        let table = CString::new("cm_t; DROP--").unwrap();
        let fields = CString::new(r#"["name"]"#).unwrap();
        let values = CString::new(r#"["X"]"#).unwrap();
        // SAFETY: pool/table/fields/values 有效(table 含注入向量)
        let r = unsafe {
            sz_orm_cpp_model_insert(pool, table.as_ptr(), fields.as_ptr(), values.as_ptr())
        };
        // SAFETY: r 有效
        let r = unsafe { free_cpp_result(r) };
        assert_eq!(r.success, 0, "illegal table should fail");
        assert_eq!(
            r.error_code,
            sz_orm_cabi::SzOrmErrorCode::InvalidArgument.as_i32()
        );
        // SAFETY: pool 有效
        unsafe { sz_orm_cpp_pool_free(pool) };
    }

    #[test]
    fn test_cpp_transaction_model_rollback() {
        let pool = model_test_pool();
        // SAFETY: pool 有效
        let tx = unsafe { sz_orm_cpp_transaction_begin(pool) };
        assert!(!tx.is_null());

        let table = CString::new("cm_t").unwrap();
        let fields = CString::new(r#"["name","age"]"#).unwrap();
        let values = CString::new(r#"["TxUser",99]"#).unwrap();
        // SAFETY: tx/table/fields/values 有效
        let r = unsafe {
            sz_orm_cpp_model_insert_tx(tx, table.as_ptr(), fields.as_ptr(), values.as_ptr())
        };
        // SAFETY: r 有效
        let r = unsafe { free_cpp_result(r) };
        assert_eq!(
            r.success, 1,
            "cpp model_insert_tx should succeed, code={}",
            r.error_code
        );

        // SAFETY: tx 有效
        assert_eq!(unsafe { sz_orm_cpp_transaction_rollback(tx) }, 1);
        // SAFETY: tx 有效
        unsafe { sz_orm_cpp_transaction_free(tx) };

        let where_clause = CString::new("name = ?").unwrap();
        let where_params = CString::new(r#"["TxUser"]"#).unwrap();
        // SAFETY: pool/table/where 有效
        let ptr = unsafe {
            sz_orm_cpp_model_find(
                pool,
                table.as_ptr(),
                where_clause.as_ptr(),
                where_params.as_ptr(),
            )
        };
        // SAFETY: ptr 有效
        let json = unsafe { free_cpp_str(ptr) };
        assert!(
            json == "[]" || json == "null" || json.is_empty(),
            "cpp find after rollback should be empty: {json}"
        );
        // SAFETY: pool 有效
        unsafe { sz_orm_cpp_pool_free(pool) };
    }

    #[test]
    fn test_cpp_transaction_model_commit() {
        let pool = model_test_pool();
        // SAFETY: pool 有效
        let tx = unsafe { sz_orm_cpp_transaction_begin(pool) };
        assert!(!tx.is_null());

        let table = CString::new("cm_t").unwrap();
        let fields = CString::new(r#"["name","age"]"#).unwrap();
        let values = CString::new(r#"["CommitUser",50]"#).unwrap();
        // SAFETY: tx/table/fields/values 有效
        let r = unsafe {
            sz_orm_cpp_model_insert_tx(tx, table.as_ptr(), fields.as_ptr(), values.as_ptr())
        };
        // SAFETY: r 有效
        unsafe { free_cpp_result(r) };

        // SAFETY: tx 有效
        assert_eq!(unsafe { sz_orm_cpp_transaction_commit(tx) }, 1);
        // SAFETY: tx 有效
        unsafe { sz_orm_cpp_transaction_free(tx) };

        let where_clause = CString::new("name = ?").unwrap();
        let where_params = CString::new(r#"["CommitUser"]"#).unwrap();
        // SAFETY: pool/table/where 有效
        let ptr = unsafe {
            sz_orm_cpp_model_find(
                pool,
                table.as_ptr(),
                where_clause.as_ptr(),
                where_params.as_ptr(),
            )
        };
        // SAFETY: ptr 有效
        let json = unsafe { free_cpp_str(ptr) };
        assert!(
            json.contains("CommitUser"),
            "cpp find after commit should contain CommitUser: {json}"
        );
        // SAFETY: pool 有效
        unsafe { sz_orm_cpp_pool_free(pool) };
    }

    // ===== v6.9.0 新增测试:QueryBuilder + ActiveModel 转发 =====

    #[test]
    fn test_cpp_qb_new_and_free() {
        // SAFETY: db_type=0 (MySQL) 合法
        let qb = unsafe { sz_orm_cpp_qb_new(0) };
        assert!(!qb.is_null(), "qb_new should return non-null handle");
        // SAFETY: qb 有效
        unsafe { sz_orm_cpp_qb_free(qb) };
    }

    #[test]
    fn test_cpp_qb_full_chain() {
        // SAFETY: db_type=0 (MySQL) 合法
        let qb = unsafe { sz_orm_cpp_qb_new(0) };
        assert!(!qb.is_null());

        let table = CString::new("users").unwrap();
        // SAFETY: qb 有效
        assert_eq!(
            unsafe { sz_orm_cpp_qb_table(qb, table.as_ptr()) },
            sz_orm_cabi::SzOrmErrorCode::Ok.as_i32()
        );

        let field = CString::new("status").unwrap();
        let value = CString::new(r#""active""#).unwrap();
        // SAFETY: qb 有效
        assert_eq!(
            unsafe { sz_orm_cpp_qb_where_eq(qb, field.as_ptr(), value.as_ptr()) },
            sz_orm_cabi::SzOrmErrorCode::Ok.as_i32()
        );

        let order_field = CString::new("id").unwrap();
        // SAFETY: qb 有效
        assert_eq!(
            unsafe { sz_orm_cpp_qb_order_by(qb, order_field.as_ptr(), 1) },
            sz_orm_cabi::SzOrmErrorCode::Ok.as_i32()
        );

        // SAFETY: qb 有效
        assert_eq!(
            unsafe { sz_orm_cpp_qb_limit(qb, 10) },
            sz_orm_cabi::SzOrmErrorCode::Ok.as_i32()
        );

        // SAFETY: qb 有效
        let result_ptr = unsafe { sz_orm_cpp_qb_build(qb) };
        assert!(!result_ptr.is_null(), "qb_build should return JSON");
        // SAFETY: result_ptr 有效
        let json = unsafe { CStr::from_ptr(result_ptr) }
            .to_string_lossy()
            .into_owned();
        // SAFETY: result_ptr 配对释放
        unsafe { sz_orm_cpp_qb_result_free(result_ptr) };

        assert!(json.contains("users"), "SQL should contain table: {json}");
        assert!(
            json.contains("status"),
            "SQL should contain where field: {json}"
        );

        // SAFETY: qb 有效
        unsafe { sz_orm_cpp_qb_free(qb) };
    }

    #[test]
    fn test_cpp_qb_invalid_db_type() {
        // SAFETY: 无效 db_type 返回 null
        let qb = unsafe { sz_orm_cpp_qb_new(999) };
        assert!(qb.is_null(), "invalid db_type should return null");
    }

    #[test]
    fn test_cpp_qb_free_null_is_noop() {
        // SAFETY: null 指针 free 是安全空操作
        unsafe { sz_orm_cpp_qb_free(std::ptr::null_mut()) };
    }

    #[test]
    fn test_cpp_active_model_create_get_delete() {
        let pool = model_test_pool();

        let table = CString::new("cm_t").unwrap();
        let fields = CString::new(r#"["name","age"]"#).unwrap();
        let values = CString::new(r#"["AMUser",42]"#).unwrap();
        // SAFETY: pool/table/fields/values 有效
        let r = unsafe {
            sz_orm_cpp_active_model_create(pool, table.as_ptr(), fields.as_ptr(), values.as_ptr())
        };
        // SAFETY: r 有效
        let r = unsafe { free_cpp_result(r) };
        assert_eq!(r.success, 1, "active_model create should succeed");

        let where_clause = CString::new("name = ?").unwrap();
        let where_params = CString::new(r#"["AMUser"]"#).unwrap();
        // SAFETY: pool/table/where 有效
        let ptr = unsafe {
            sz_orm_cpp_active_model_get(
                pool,
                table.as_ptr(),
                where_clause.as_ptr(),
                where_params.as_ptr(),
            )
        };
        // SAFETY: ptr 有效
        let json = unsafe { free_cpp_str(ptr) };
        assert!(json.contains("AMUser"), "get should find AMUser: {json}");

        // SAFETY: pool/table/where 有效
        let r = unsafe {
            sz_orm_cpp_active_model_delete(
                pool,
                table.as_ptr(),
                where_clause.as_ptr(),
                where_params.as_ptr(),
            )
        };
        // SAFETY: r 有效
        let r = unsafe { free_cpp_result(r) };
        assert_eq!(r.success, 1, "active_model delete should succeed");

        // SAFETY: pool 有效
        unsafe { sz_orm_cpp_pool_free(pool) };
    }

    #[test]
    fn test_cpp_active_model_set_update() {
        let pool = model_test_pool();

        let table = CString::new("cm_t").unwrap();
        let fields = CString::new(r#"["name","age"]"#).unwrap();
        let values = CString::new(r#"["SetUser",20]"#).unwrap();
        // SAFETY: pool/table/fields/values 有效
        let r = unsafe {
            sz_orm_cpp_active_model_save(pool, table.as_ptr(), fields.as_ptr(), values.as_ptr())
        };
        // SAFETY: r 有效
        unsafe { free_cpp_result(r) };

        let set_json = CString::new(r#"{"age":21}"#).unwrap();
        let where_clause = CString::new("name = ?").unwrap();
        let where_params = CString::new(r#"["SetUser"]"#).unwrap();
        // SAFETY: pool/table/set/where 有效
        let r = unsafe {
            sz_orm_cpp_active_model_set(
                pool,
                table.as_ptr(),
                set_json.as_ptr(),
                where_clause.as_ptr(),
                where_params.as_ptr(),
            )
        };
        // SAFETY: r 有效
        let r = unsafe { free_cpp_result(r) };
        assert_eq!(r.success, 1, "active_model set should succeed");

        // SAFETY: pool/table/where 有效
        let ptr = unsafe {
            sz_orm_cpp_active_model_get(
                pool,
                table.as_ptr(),
                where_clause.as_ptr(),
                where_params.as_ptr(),
            )
        };
        // SAFETY: ptr 有效
        let json = unsafe { free_cpp_str(ptr) };
        assert!(
            json.contains("21"),
            "get after set should contain age 21: {json}"
        );

        // SAFETY: pool 有效
        unsafe { sz_orm_cpp_pool_free(pool) };
    }
}