picovolt 2.2.0

Embedded SQL database with MVCC history and single-file deployment
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
// Modified for PicoVolt 2.2.0 encryption/hybrid retrieval; see legal/COMPONENT-SCOPE-2.2.md.
// Modified for PicoVolt 2.1.0 retrieval, 2026-09-11. See legal/COMPONENT-SCOPE-2.1.md.
//! C ABI (enabled by the `capi` feature).
//!
//! A thin, stable, panic-safe C-callable surface over the in-process engine, so
//! PicoVolt can be embedded from C, Go (cgo), Python (ctypes), and any language
//! with a C FFI. Build a shared library with:
//!
//! ```sh
//! cargo build --release --features capi
//! ```
//!
//! which produces `target/release/{libpicovolt.so | picovolt.dll |
//! libpicovolt.dylib}`. The matching header is [`include/picovolt.h`](https://github.com/MiniJe/picovolt/blob/main/include/picovolt.h).
//!
//! ## Contract
//!
//! - A [`crate::ffi::PvDb`] handle is created by `pv_open_*` and must be released
//!   with `pv_close`. A [`crate::ffi::PvStmt`] comes from `pv_prepare` and must be
//!   released with `pv_stmt_close`. Handles are **not** thread-safe: do not use
//!   one handle from multiple threads without external synchronization.
//! - `pv_query` returns a newly allocated, NUL-terminated JSON string the caller
//!   frees with `pv_string_free`; `pv_export` returns a byte buffer freed with
//!   `pv_bytes_free`. Mixing up the free functions is undefined behavior.
//! - On error, fallible functions return NULL (or `0`) and record a message
//!   retrievable on the same thread with `pv_last_error`.
//! - Panics never cross the FFI boundary: every entry point catches them and
//!   reports them through `pv_last_error`.

use std::cell::RefCell;
use std::ffi::{CStr, CString};
use std::os::raw::c_char;
use std::panic::{catch_unwind, AssertUnwindSafe};
use std::ptr;

use crate::{Database, PreparedStatement};

/// Native encrypted vault handles (2.2+).
#[cfg(all(feature = "encryption", not(target_arch = "wasm32")))]
pub mod vault;

/// Opaque handle to a PicoVolt database. Allocate with `pv_open_*`, free with
/// `pv_close`.
pub struct PvDb {
    inner: Database,
}

/// Opaque reusable prepared statement. Allocate with [`pv_prepare`], execute
/// with [`pv_stmt_execute`], and release with [`pv_stmt_close`].
pub struct PvStmt {
    inner: PreparedStatement,
}

thread_local! {
    static LAST_ERROR: RefCell<Option<CString>> = const { RefCell::new(None) };
}

fn set_last_error(msg: impl Into<Vec<u8>>) {
    // Strip any interior NUL bytes so the message is always a valid C string.
    let bytes: Vec<u8> = msg
        .into()
        .into_iter()
        .map(|b| if b == 0 { b'?' } else { b })
        .collect();
    let cstr = CString::new(bytes).unwrap_or_else(|_| CString::new("error").unwrap());
    LAST_ERROR.with(|e| *e.borrow_mut() = Some(cstr));
}

fn clear_last_error() {
    LAST_ERROR.with(|e| *e.borrow_mut() = None);
}

/// Run `f`, converting any panic into a recorded error and the `on_panic`
/// sentinel, so a panic never unwinds across the C boundary.
fn guard<T>(on_panic: T, f: impl FnOnce() -> T) -> T {
    match catch_unwind(AssertUnwindSafe(f)) {
        Ok(v) => v,
        Err(_) => {
            set_last_error("panic in a PicoVolt FFI call");
            on_panic
        }
    }
}

/// Borrow a C string as `&str`, or `None` if it is NULL or not valid UTF-8.
///
/// # Safety
/// `p` must be NULL or a valid pointer to a NUL-terminated string that stays
/// alive for the duration of the call.
unsafe fn cstr_to_str<'a>(p: *const c_char) -> Option<&'a str> {
    if p.is_null() {
        return None;
    }
    CStr::from_ptr(p).to_str().ok()
}

/// Allocate a NUL-terminated C string owning `s`, or NULL if `s` contained an
/// interior NUL (it never does for our JSON output).
fn string_to_c(s: String) -> *mut c_char {
    match CString::new(s) {
        Ok(c) => c.into_raw(),
        Err(_) => {
            set_last_error("result contained an interior NUL byte");
            ptr::null_mut()
        }
    }
}

/// The PicoVolt semantic version as a static NUL-terminated string. Never NULL;
/// do not free.
#[no_mangle]
pub extern "C" fn pv_version() -> *const c_char {
    concat!(env!("CARGO_PKG_VERSION"), "\0").as_ptr() as *const c_char
}

/// The most recent error message recorded on the calling thread, or NULL if
/// there is none.
///
/// The returned pointer is owned by PicoVolt and remains valid only until the
/// next PicoVolt call on this thread. Copy it if you need to keep it; do not
/// free it.
#[no_mangle]
pub extern "C" fn pv_last_error() -> *const c_char {
    LAST_ERROR.with(|e| match &*e.borrow() {
        Some(s) => s.as_ptr(),
        None => ptr::null(),
    })
}

/// Open a new, empty in-memory database. Returns NULL only on allocation
/// failure or panic (see `pv_last_error`).
#[no_mangle]
pub extern "C" fn pv_open_memory() -> *mut PvDb {
    guard(ptr::null_mut(), || {
        clear_last_error();
        Box::into_raw(Box::new(PvDb {
            inner: Database::open_memory(),
        }))
    })
}

/// Open a development workspace at `path` (UTF-8). Returns NULL on error (see
/// `pv_last_error`).
///
/// # Safety
/// `path` must be NULL or a valid pointer to a NUL-terminated UTF-8 string.
#[no_mangle]
pub unsafe extern "C" fn pv_open_dev(path: *const c_char) -> *mut PvDb {
    guard(ptr::null_mut(), || {
        clear_last_error();
        let Some(path) = (unsafe { cstr_to_str(path) }) else {
            set_last_error("pv_open_dev: path is NULL or not valid UTF-8");
            return ptr::null_mut();
        };
        match Database::open_dev(path) {
            Ok(inner) => Box::into_raw(Box::new(PvDb { inner })),
            Err(e) => {
                set_last_error(e.to_string());
                ptr::null_mut()
            }
        }
    })
}

/// Open a baked `.pvdb` production monolith at `path` (UTF-8), read-only.
/// Returns NULL on error (see `pv_last_error`).
///
/// # Safety
/// `path` must be NULL or a valid pointer to a NUL-terminated UTF-8 string.
#[no_mangle]
pub unsafe extern "C" fn pv_open_prod(path: *const c_char) -> *mut PvDb {
    guard(ptr::null_mut(), || {
        clear_last_error();
        let Some(path) = (unsafe { cstr_to_str(path) }) else {
            set_last_error("pv_open_prod: path is NULL or not valid UTF-8");
            return ptr::null_mut();
        };
        match Database::open_prod(path) {
            Ok(inner) => Box::into_raw(Box::new(PvDb { inner })),
            Err(e) => {
                set_last_error(e.to_string());
                ptr::null_mut()
            }
        }
    })
}

/// Run one SQL statement. Returns a newly allocated, NUL-terminated JSON string
/// the caller must free with `pv_string_free`, or NULL on error (see
/// `pv_last_error`). The JSON shape matches the JavaScript binding:
/// `{"columns":[...],"rows":[[...]]}` | `{"mutated":n}` | `{"done":true}`.
///
/// # Safety
/// `db` must be a live handle from `pv_open_*` (not yet closed), and `sql` a
/// valid pointer to a NUL-terminated UTF-8 string.
#[no_mangle]
pub unsafe extern "C" fn pv_query(db: *mut PvDb, sql: *const c_char) -> *mut c_char {
    guard(ptr::null_mut(), || {
        clear_last_error();
        let Some(db) = (unsafe { db.as_mut() }) else {
            set_last_error("pv_query: db handle is NULL");
            return ptr::null_mut();
        };
        let Some(sql) = (unsafe { cstr_to_str(sql) }) else {
            set_last_error("pv_query: sql is NULL or not valid UTF-8");
            return ptr::null_mut();
        };
        match db.inner.query(sql) {
            Ok(result) => match crate::json::result_to_string(&result) {
                Ok(s) => string_to_c(s),
                Err(e) => {
                    set_last_error(e.to_string());
                    ptr::null_mut()
                }
            },
            Err(e) => {
                set_last_error(e.to_string());
                ptr::null_mut()
            }
        }
    })
}

/// Like [`pv_query`] but binds `?` placeholders to a JSON array of parameters,
/// e.g. `[1, "alice", null]`. Each element maps to a PicoVolt value (null, a
/// boolean as 0/1, an integer, a fractional number as a decimal, or a string)
/// and is substituted as a safely-escaped SQL literal. Returns the same JSON
/// result string (free with `pv_string_free`), or NULL on error.
///
/// # Safety
/// `db` must be a live handle, and `sql` / `params_json` valid pointers to
/// NUL-terminated UTF-8 strings.
#[no_mangle]
pub unsafe extern "C" fn pv_query_params(
    db: *mut PvDb,
    sql: *const c_char,
    params_json: *const c_char,
) -> *mut c_char {
    guard(ptr::null_mut(), || {
        clear_last_error();
        let Some(db) = (unsafe { db.as_mut() }) else {
            set_last_error("pv_query_params: db handle is NULL");
            return ptr::null_mut();
        };
        let Some(sql) = (unsafe { cstr_to_str(sql) }) else {
            set_last_error("pv_query_params: sql is NULL or not valid UTF-8");
            return ptr::null_mut();
        };
        let Some(pj) = (unsafe { cstr_to_str(params_json) }) else {
            set_last_error("pv_query_params: params is NULL or not valid UTF-8");
            return ptr::null_mut();
        };
        let values = match json_params_to_values("pv_query_params", pj) {
            Ok(values) => values,
            Err(error) => {
                set_last_error(error);
                return ptr::null_mut();
            }
        };
        match db.inner.query_with(sql, &values) {
            Ok(result) => match crate::json::result_to_string(&result) {
                Ok(s) => string_to_c(s),
                Err(e) => {
                    set_last_error(e.to_string());
                    ptr::null_mut()
                }
            },
            Err(e) => {
                set_last_error(e.to_string());
                ptr::null_mut()
            }
        }
    })
}

#[cfg(any(feature = "full-text", feature = "vector-search"))]
/// Execute a bounded SELECT retrieval request. Free the result with pv_string_free.
///
/// # Safety
/// `db` is a live handle and `request` points to a NUL-terminated UTF-8 string.
#[no_mangle]
pub unsafe extern "C" fn pv_retrieve(db: *mut PvDb, request: *const c_char) -> *mut c_char {
    guard(ptr::null_mut(), || {
        clear_last_error();
        let (Some(db), Some(request)) = (unsafe { db.as_mut() }, unsafe { cstr_to_str(request) })
        else {
            set_last_error("pv_retrieve: invalid handle or request");
            return ptr::null_mut();
        };
        match db.inner.retrieve_json(request) {
            Ok(result) => string_to_c(result),
            Err(error) => {
                set_last_error(error.to_string());
                ptr::null_mut()
            }
        }
    })
}

/// Validate and retain a reusable SQL template. The returned statement is not
/// tied to `db` and may be executed against another compatible PicoVolt handle.
/// Returns NULL on error (see [`pv_last_error`]).
///
/// # Safety
/// `db` must be a live handle and `sql` a valid pointer to a NUL-terminated
/// UTF-8 string.
#[no_mangle]
pub unsafe extern "C" fn pv_prepare(db: *const PvDb, sql: *const c_char) -> *mut PvStmt {
    guard(ptr::null_mut(), || {
        clear_last_error();
        let Some(db) = (unsafe { db.as_ref() }) else {
            set_last_error("pv_prepare: db handle is NULL");
            return ptr::null_mut();
        };
        let Some(sql) = (unsafe { cstr_to_str(sql) }) else {
            set_last_error("pv_prepare: sql is NULL or not valid UTF-8");
            return ptr::null_mut();
        };
        match db.inner.prepare(sql) {
            Ok(inner) => Box::into_raw(Box::new(PvStmt { inner })),
            Err(error) => {
                set_last_error(error.to_string());
                ptr::null_mut()
            }
        }
    })
}

/// Return the number of positional `?` values required by `stmt`. Returns zero
/// for a NULL handle and records an error; a valid zero-parameter statement also
/// returns zero without setting an error.
///
/// # Safety
/// `stmt` must be NULL or a live handle returned by [`pv_prepare`].
#[no_mangle]
pub unsafe extern "C" fn pv_stmt_parameter_count(stmt: *const PvStmt) -> usize {
    guard(0, || {
        clear_last_error();
        match unsafe { stmt.as_ref() } {
            Some(stmt) => stmt.inner.parameter_count(),
            None => {
                set_last_error("pv_stmt_parameter_count: statement handle is NULL");
                0
            }
        }
    })
}

/// Execute a prepared statement with a JSON array of positional parameters.
/// Returns the same newly allocated JSON result as [`pv_query_params`], or NULL
/// on error. Free the result with [`pv_string_free`].
///
/// # Safety
/// `stmt` and `db` must be live PicoVolt handles and `params_json` must be a
/// valid pointer to a NUL-terminated UTF-8 JSON array.
#[no_mangle]
pub unsafe extern "C" fn pv_stmt_execute(
    stmt: *const PvStmt,
    db: *mut PvDb,
    params_json: *const c_char,
) -> *mut c_char {
    guard(ptr::null_mut(), || {
        clear_last_error();
        let Some(stmt) = (unsafe { stmt.as_ref() }) else {
            set_last_error("pv_stmt_execute: statement handle is NULL");
            return ptr::null_mut();
        };
        let Some(db) = (unsafe { db.as_mut() }) else {
            set_last_error("pv_stmt_execute: db handle is NULL");
            return ptr::null_mut();
        };
        let Some(pj) = (unsafe { cstr_to_str(params_json) }) else {
            set_last_error("pv_stmt_execute: params is NULL or not valid UTF-8");
            return ptr::null_mut();
        };
        let values = match json_params_to_values("pv_stmt_execute", pj) {
            Ok(values) => values,
            Err(error) => {
                set_last_error(error);
                return ptr::null_mut();
            }
        };
        match stmt.inner.execute(&mut db.inner, &values) {
            Ok(result) => match crate::json::result_to_string(&result) {
                Ok(json) => string_to_c(json),
                Err(error) => {
                    set_last_error(error.to_string());
                    ptr::null_mut()
                }
            },
            Err(error) => {
                set_last_error(error.to_string());
                ptr::null_mut()
            }
        }
    })
}

/// Free a prepared-statement handle. NULL is ignored.
///
/// # Safety
/// `stmt` must be NULL or a handle returned by [`pv_prepare`] that has not
/// already been freed.
#[no_mangle]
pub unsafe extern "C" fn pv_stmt_close(stmt: *mut PvStmt) {
    guard((), || {
        if !stmt.is_null() {
            drop(unsafe { Box::from_raw(stmt) });
        }
    });
}

fn json_params_to_values(function: &str, params_json: &str) -> Result<Vec<crate::Value>, String> {
    let parsed: serde_json::Value = serde_json::from_str(params_json)
        .map_err(|error| format!("{function}: invalid params JSON: {error}"))?;
    let serde_json::Value::Array(array) = parsed else {
        return Err(format!("{function}: params must be a JSON array"));
    };
    array
        .into_iter()
        .map(|value| json_to_value(value).map_err(|error| format!("{function}: {error}")))
        .collect()
}

/// Map one JSON parameter to a PicoVolt value.
fn json_to_value(v: serde_json::Value) -> Result<crate::Value, String> {
    use crate::Value;
    use serde_json::Value as J;
    match v {
        J::Null => Ok(Value::Null),
        J::Bool(b) => Ok(Value::Int(if b { 1 } else { 0 })),
        J::Number(n) => {
            if let Some(i) = n.as_i64() {
                Ok(Value::Int(i))
            } else if n.as_u64().is_some() {
                Err("integer parameter exceeds the i64 range".into())
            } else if let Some(f) = n.as_f64() {
                let scaled = f * 1_000_000.0;
                if !scaled.is_finite() || scaled.abs() >= 1.7e38 {
                    Err("numeric parameter out of range".into())
                } else {
                    Ok(Value::Decimal(scaled.round() as i128))
                }
            } else {
                Err("numeric parameter out of range".into())
            }
        }
        J::String(s) => Ok(Value::Text(s)),
        J::Array(_) | J::Object(_) => Err("array and object parameters are not supported".into()),
    }
}

/// Import a SQL dump (such as the output of `sqlite3 db .dump`). Returns a JSON
/// report `{"executed":n,"skipped":[...],"errors":[...]}` (free with
/// `pv_string_free`), or NULL on error.
///
/// # Safety
/// `db` must be a live handle and `dump` a valid NUL-terminated UTF-8 string.
#[no_mangle]
pub unsafe extern "C" fn pv_import_sql(db: *mut PvDb, dump: *const c_char) -> *mut c_char {
    guard(ptr::null_mut(), || {
        clear_last_error();
        let Some(db) = (unsafe { db.as_mut() }) else {
            set_last_error("pv_import_sql: db handle is NULL");
            return ptr::null_mut();
        };
        let Some(dump) = (unsafe { cstr_to_str(dump) }) else {
            set_last_error("pv_import_sql: dump is NULL or not valid UTF-8");
            return ptr::null_mut();
        };
        let report = db.inner.import_sql(dump);
        let json = serde_json::json!({
            "executed": report.executed,
            "skipped": report.skipped,
            "errors": report.errors,
        });
        match serde_json::to_string(&json) {
            Ok(s) => string_to_c(s),
            Err(e) => {
                set_last_error(e.to_string());
                ptr::null_mut()
            }
        }
    })
}

/// The most recently committed transaction id (the upper bound for a
/// `... BEFORE tx` time-travel query). Returns `0` if `db` is NULL.
///
/// # Safety
/// `db` must be NULL or a live handle from `pv_open_*`.
#[no_mangle]
pub unsafe extern "C" fn pv_current_tx(db: *const PvDb) -> u64 {
    guard(0, || {
        // Clear first, like every other error-recording entry point, so a
        // successful call never leaves a stale message in `pv_last_error`.
        clear_last_error();
        match unsafe { db.as_ref() } {
            Some(db) => db.inner.current_tx(),
            None => {
                set_last_error("pv_current_tx: db handle is NULL");
                0
            }
        }
    })
}

fn transaction_control(
    db: *mut PvDb,
    function: &str,
    operation: impl FnOnce(&mut Database) -> crate::Result<()>,
) -> i32 {
    clear_last_error();
    let Some(db) = (unsafe { db.as_mut() }) else {
        set_last_error(format!("{function}: db handle is NULL"));
        return 0;
    };
    match operation(&mut db.inner) {
        Ok(()) => 1,
        Err(error) => {
            set_last_error(error.to_string());
            0
        }
    }
}

fn json_result<T: serde::Serialize>(result: crate::Result<T>) -> *mut c_char {
    match result.and_then(|v| serde_json::to_string(&v).map_err(Into::into)) {
        Ok(s) => string_to_c(s),
        Err(error) => {
            set_last_error(error.to_string());
            ptr::null_mut()
        }
    }
}

/// Atomic repeated INSERT/UPDATE/DELETE. Parameters are a JSON array of arrays;
/// returns `{"mutated":n}` owned by the caller, or NULL on any failure.
/// # Safety
/// `db` must be live; strings must be valid NUL-terminated UTF-8 or NULL.
#[no_mangle]
pub unsafe extern "C" fn pv_execute_many(
    db: *mut PvDb,
    sql: *const c_char,
    rows_json: *const c_char,
) -> *mut c_char {
    guard(ptr::null_mut(), || {
        clear_last_error();
        let (Some(db), Some(sql), Some(rows)) = (
            unsafe { db.as_mut() },
            unsafe { cstr_to_str(sql) },
            unsafe { cstr_to_str(rows_json) },
        ) else {
            set_last_error("pv_execute_many: null handle or invalid UTF-8 input");
            return ptr::null_mut();
        };
        let result = (|| -> crate::Result<_> {
            let rows: Vec<Vec<serde_json::Value>> = serde_json::from_str(rows)?;
            let rows: Vec<Vec<crate::Value>> = rows
                .into_iter()
                .map(|row| {
                    row.into_iter()
                        .map(|v| json_to_value(v).map_err(crate::PvError::Query))
                        .collect()
                })
                .collect::<crate::Result<_>>()?;
            Ok(serde_json::json!({"mutated":db.inner.execute_many(sql,&rows)?}))
        })();
        json_result(result)
    })
}

/// Enable filesystem commit logging. Zero limits select the default per field.
/// # Safety
/// `db` must be a live handle or NULL.
#[no_mangle]
pub unsafe extern "C" fn pv_enable_commit_log(
    db: *mut PvDb,
    transaction_bytes: u64,
    retained_bytes: u64,
    retained_commits: usize,
) -> i32 {
    guard(0, || {
        transaction_control(db, "pv_enable_commit_log", |db| {
            let mut options = crate::CommitLogOptions::default();
            if transaction_bytes != 0 {
                options.max_transaction_bytes = transaction_bytes;
            }
            if retained_bytes != 0 {
                options.max_retained_bytes = retained_bytes;
            }
            if retained_commits != 0 {
                options.max_retained_commits = retained_commits;
            }
            db.enable_commit_log(options)
        })
    })
}

/// Return JSON retention diagnostics. Free the result with pv_string_free.
/// # Safety
/// `db` must be a live handle or NULL.
#[no_mangle]
pub unsafe extern "C" fn pv_commit_log_status(db: *const PvDb) -> *mut c_char {
    guard(ptr::null_mut(), || {
        clear_last_error();
        let Some(db) = (unsafe { db.as_ref() }) else {
            set_last_error("pv_commit_log_status: null handle");
            return ptr::null_mut();
        };
        json_result(db.inner.commit_log_status())
    })
}

/// Return a JSON array of physical changes strictly after the sequence cursor.
/// Free the result with pv_string_free. At most 4096 commits per call.
/// # Safety
/// `db` must be a live handle or NULL.
#[no_mangle]
pub unsafe extern "C" fn pv_changes_since(
    db: *const PvDb,
    after: u64,
    limit: usize,
) -> *mut c_char {
    guard(ptr::null_mut(), || {
        clear_last_error();
        let Some(db) = (unsafe { db.as_ref() }) else {
            set_last_error("pv_changes_since: null handle");
            return ptr::null_mut();
        };
        json_result(db.inner.changes_since(after, limit))
    })
}

/// Prune through an acknowledged sequence; never automatically acknowledges data.
/// # Safety
/// `db` must be a live handle or NULL.
#[no_mangle]
pub unsafe extern "C" fn pv_prune_changes(db: *mut PvDb, through: u64) -> i32 {
    guard(0, || {
        transaction_control(db, "pv_prune_changes", |db| db.prune_changes(through))
    })
}

/// Begin an explicit multi-statement transaction. Returns 1 on success and 0 on
/// error. A development workspace creates a crash-recovery point before return.
///
/// # Safety
/// `db` must be a live handle from `pv_open_*`.
#[no_mangle]
pub unsafe extern "C" fn pv_begin_transaction(db: *mut PvDb) -> i32 {
    guard(0, || {
        transaction_control(db, "pv_begin_transaction", Database::begin_transaction)
    })
}

/// Commit an explicit transaction. Returns 1 on success and 0 on error.
///
/// # Safety
/// `db` must be a live handle from `pv_open_*`.
#[no_mangle]
pub unsafe extern "C" fn pv_commit_transaction(db: *mut PvDb) -> i32 {
    guard(0, || {
        transaction_control(db, "pv_commit_transaction", Database::commit_transaction)
    })
}

/// Roll back an explicit transaction. Returns 1 on success and 0 on error.
///
/// # Safety
/// `db` must be a live handle from `pv_open_*`.
#[no_mangle]
pub unsafe extern "C" fn pv_rollback_transaction(db: *mut PvDb) -> i32 {
    guard(0, || {
        transaction_control(
            db,
            "pv_rollback_transaction",
            Database::rollback_transaction,
        )
    })
}

/// Return 1 when an explicit transaction is active, otherwise 0.
///
/// # Safety
/// `db` must be a live handle from `pv_open_*`.
#[no_mangle]
pub unsafe extern "C" fn pv_in_transaction(db: *const PvDb) -> i32 {
    guard(0, || {
        clear_last_error();
        match unsafe { db.as_ref() } {
            Some(db) => i32::from(db.inner.in_transaction()),
            None => {
                set_last_error("pv_in_transaction: db handle is NULL");
                0
            }
        }
    })
}

/// Export the whole database as a `.pvdb` byte image. On success returns a
/// buffer of `*out_len` bytes (free it with `pv_bytes_free`) and writes the
/// length through `out_len`; returns NULL on error (see `pv_last_error`).
///
/// # Safety
/// `db` must be a live handle and `out_len` a valid, writable `size_t*`.
#[no_mangle]
pub unsafe extern "C" fn pv_export(db: *mut PvDb, out_len: *mut usize) -> *mut u8 {
    guard(ptr::null_mut(), || {
        clear_last_error();
        if out_len.is_null() {
            set_last_error("pv_export: out_len is NULL");
            return ptr::null_mut();
        }
        let Some(db) = (unsafe { db.as_mut() }) else {
            set_last_error("pv_export: db handle is NULL");
            unsafe { *out_len = 0 };
            return ptr::null_mut();
        };
        match db.inner.bake_to_bytes() {
            Ok(bytes) => {
                let len = bytes.len();
                let mut boxed = bytes.into_boxed_slice();
                let ptr = boxed.as_mut_ptr();
                std::mem::forget(boxed);
                unsafe { *out_len = len };
                ptr
            }
            Err(e) => {
                set_last_error(e.to_string());
                unsafe { *out_len = 0 };
                ptr::null_mut()
            }
        }
    })
}

/// Import a database from a `.pvdb` byte image (e.g. one from `pv_export`).
/// Returns NULL on error (see `pv_last_error`).
///
/// # Safety
/// `bytes` must point to at least `len` readable bytes (or be NULL, which is an
/// error).
#[no_mangle]
pub unsafe extern "C" fn pv_import(bytes: *const u8, len: usize) -> *mut PvDb {
    guard(ptr::null_mut(), || {
        clear_last_error();
        if bytes.is_null() {
            set_last_error("pv_import: bytes is NULL");
            return ptr::null_mut();
        }
        let slice = unsafe { std::slice::from_raw_parts(bytes, len) };
        match Database::import_bytes(slice) {
            Ok(inner) => Box::into_raw(Box::new(PvDb { inner })),
            Err(e) => {
                set_last_error(e.to_string());
                ptr::null_mut()
            }
        }
    })
}

/// Free a string returned by `pv_query`. NULL is ignored.
///
/// # Safety
/// `s` must be NULL or a pointer returned by `pv_query` and not already freed.
#[no_mangle]
pub unsafe extern "C" fn pv_string_free(s: *mut c_char) {
    if !s.is_null() {
        drop(unsafe { CString::from_raw(s) });
    }
}

/// Free a buffer returned by `pv_export`. `len` must be the same length that
/// `pv_export` reported. NULL is ignored.
///
/// # Safety
/// `ptr`/`len` must be a buffer returned by `pv_export`, with its exact length,
/// not already freed.
#[no_mangle]
pub unsafe extern "C" fn pv_bytes_free(ptr: *mut u8, len: usize) {
    if !ptr.is_null() {
        drop(unsafe { Box::from_raw(std::ptr::slice_from_raw_parts_mut(ptr, len)) });
    }
}

/// Close a database handle and free its resources. NULL is ignored. Using the
/// handle after this call is undefined behavior.
///
/// # Safety
/// `db` must be NULL or a handle from `pv_open_*` that has not already been
/// closed.
#[no_mangle]
pub unsafe extern "C" fn pv_close(db: *mut PvDb) {
    guard((), || {
        if !db.is_null() {
            let mut db = unsafe { Box::from_raw(db) };
            if db.inner.in_transaction() {
                let _ = db.inner.rollback_transaction();
            }
            drop(db);
        }
    });
}

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

    unsafe fn run(db: *mut PvDb, sql: &str) -> Option<String> {
        let c = CString::new(sql).unwrap();
        let res = pv_query(db, c.as_ptr());
        if res.is_null() {
            return None;
        }
        let s = CStr::from_ptr(res).to_str().unwrap().to_owned();
        pv_string_free(res);
        Some(s)
    }

    #[test]
    fn roundtrip_memory() {
        unsafe {
            let db = pv_open_memory();
            assert!(!db.is_null());
            assert!(run(db, "CREATE TABLE t (id, name)")
                .unwrap()
                .contains("\"done\":true"));
            assert!(run(db, "INSERT INTO t VALUES (1, 'alice')")
                .unwrap()
                .contains("\"mutated\":1"));
            let sel = run(db, "SELECT * FROM t").unwrap();
            assert!(sel.contains("\"columns\"") && sel.contains("alice"));
            assert!(pv_current_tx(db) > 0);
            pv_close(db);
        }
    }

    #[test]
    fn params_bind_and_escape() {
        unsafe {
            let db = pv_open_memory();
            run(db, "CREATE TABLE u (id, name)").unwrap();
            let sql = CString::new("INSERT INTO u VALUES (?, ?)").unwrap();
            let p1 = CString::new(r#"[1, "o'brien"]"#).unwrap();
            let r1 = pv_query_params(db, sql.as_ptr(), p1.as_ptr());
            assert!(!r1.is_null());
            pv_string_free(r1);
            // An injection attempt is escaped into one string value, not executed.
            let p2 = CString::new(r#"[2, "x'); DROP TABLE u; --"]"#).unwrap();
            let r2 = pv_query_params(db, sql.as_ptr(), p2.as_ptr());
            assert!(!r2.is_null());
            pv_string_free(r2);
            assert!(run(db, "SELECT COUNT(*) FROM u").unwrap().contains("[[2]]"));
            pv_close(db);
        }
    }

    #[test]
    fn error_path_sets_last_error() {
        unsafe {
            let db = pv_open_memory();
            clear_last_error();
            let bad = pv_query(db, CString::new("SELECT FROM").unwrap().as_ptr());
            assert!(bad.is_null());
            let err = pv_last_error();
            assert!(!err.is_null());
            assert!(!CStr::from_ptr(err).to_bytes().is_empty());
            pv_close(db);
        }
    }

    #[test]
    fn export_import_roundtrip() {
        unsafe {
            let db = pv_open_memory();
            run(db, "CREATE TABLE t (id)").unwrap();
            run(db, "INSERT INTO t VALUES (42)").unwrap();
            let mut len: usize = 0;
            let bytes = pv_export(db, &mut len as *mut usize);
            assert!(!bytes.is_null() && len > 0);
            let db2 = pv_import(bytes, len);
            assert!(!db2.is_null());
            assert!(run(db2, "SELECT * FROM t").unwrap().contains("42"));
            pv_bytes_free(bytes, len);
            pv_close(db);
            pv_close(db2);
        }
    }

    #[test]
    fn prepared_statement_reuses_validated_template() {
        unsafe {
            let db = pv_open_memory();
            run(db, "CREATE TABLE t (id, name)").unwrap();
            let sql = CString::new("INSERT INTO t VALUES (?, ?)").unwrap();
            let stmt = pv_prepare(db, sql.as_ptr());
            assert!(!stmt.is_null());
            assert_eq!(pv_stmt_parameter_count(stmt), 2);

            for params in ["[1,\"alice\"]", "[2,\"bob\"]"] {
                let params = CString::new(params).unwrap();
                let result = pv_stmt_execute(stmt, db, params.as_ptr());
                assert!(!result.is_null());
                assert!(CStr::from_ptr(result).to_str().unwrap().contains("mutated"));
                pv_string_free(result);
            }
            let wrong_arity = CString::new("[3]").unwrap();
            assert!(pv_stmt_execute(stmt, db, wrong_arity.as_ptr()).is_null());
            assert!(CStr::from_ptr(pv_last_error())
                .to_str()
                .unwrap()
                .contains("expects 2 parameters"));

            pv_stmt_close(stmt);
            assert!(run(db, "SELECT COUNT(*) FROM t").unwrap().contains("[[2]]"));
            pv_close(db);
        }
    }

    #[test]
    fn prepared_statement_rejects_invalid_inputs_without_unwinding() {
        unsafe {
            let db = pv_open_memory();
            let invalid = CString::new("SELECT FROM").unwrap();
            assert!(pv_prepare(db, invalid.as_ptr()).is_null());
            assert!(!pv_last_error().is_null());
            assert!(pv_prepare(ptr::null(), invalid.as_ptr()).is_null());
            assert_eq!(pv_stmt_parameter_count(ptr::null()), 0);
            let empty = CString::new("[]").unwrap();
            assert!(pv_stmt_execute(ptr::null(), db, empty.as_ptr()).is_null());
            pv_stmt_close(ptr::null_mut());
            pv_close(db);
        }
    }

    #[test]
    fn explicit_transaction_round_trips_through_c_abi() {
        unsafe {
            let db = pv_open_memory();
            run(db, "CREATE TABLE t (id)").unwrap();
            assert_eq!(pv_begin_transaction(db), 1);
            assert_eq!(pv_in_transaction(db), 1);
            run(db, "INSERT INTO t VALUES (1)").unwrap();
            assert_eq!(pv_rollback_transaction(db), 1);
            assert_eq!(pv_in_transaction(db), 0);
            assert!(run(db, "SELECT COUNT(*) FROM t").unwrap().contains("[[0]]"));

            assert_eq!(pv_begin_transaction(db), 1);
            run(db, "INSERT INTO t VALUES (2)").unwrap();
            assert_eq!(pv_commit_transaction(db), 1);
            assert!(run(db, "SELECT COUNT(*) FROM t").unwrap().contains("[[1]]"));
            pv_close(db);
        }
    }

    #[test]
    fn null_arguments_are_safe() {
        unsafe {
            let sql = CString::new("SELECT 1").unwrap();
            assert!(pv_query(ptr::null_mut(), sql.as_ptr()).is_null());
            assert_eq!(pv_current_tx(ptr::null()), 0);
            pv_close(ptr::null_mut());
            pv_string_free(ptr::null_mut());
            pv_bytes_free(ptr::null_mut(), 0);
            let v = CStr::from_ptr(pv_version()).to_str().unwrap();
            assert!(v.chars().next().unwrap().is_ascii_digit());
        }
    }
}