-
Notifications
You must be signed in to change notification settings - Fork 56
Expand file tree
/
Copy pathlib.rs
More file actions
1403 lines (1280 loc) · 49.1 KB
/
Copy pathlib.rs
File metadata and controls
1403 lines (1280 loc) · 49.1 KB
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
//! C FFI shim around the SQLRite engine (Phase 5b).
//!
//! This crate turns the Rust-native `sqlrite::Connection` / `Statement`
//! / `Rows` API into a C-callable shared library. Every non-Rust SDK
//! (Python via PyO3, Node.js via napi-rs, Go via cgo, plus raw C) binds
//! against the same ABI surface defined here.
//!
//! ## Design
//!
//! - **Opaque pointers.** `SqlriteConnection` and `SqlriteStatement`
//! are opaque to the caller; only the library constructs and
//! destroys them. Callers must pair every `*_open` / `*_prepare`
//! with the matching `*_close` / `*_finalize` or leak memory.
//! - **C-style error codes.** Every mutating call returns an
//! [`SqlriteStatus`] int. On nonzero, the caller can fetch a
//! descriptive message via [`sqlrite_last_error`]. The error string
//! is thread-local so multi-threaded callers don't race.
//! - **Split execute / query.** SQLite's one-size-fits-all
//! `sqlite3_prepare` + `sqlite3_step` collapses statement-that-
//! returns-rows and statement-that-doesn't into one type. We split
//! them: [`sqlrite_execute`] is fire-and-forget for DDL/DML/
//! transactions; [`sqlrite_query`] returns a statement handle that
//! yields rows via [`sqlrite_step`]. Cleaner to bind against.
//! - **Strings.** C strings in (inputs to [`sqlrite_open`],
//! [`sqlrite_execute`], etc.) are NUL-terminated UTF-8 borrows
//! owned by the caller. C strings out (from [`sqlrite_column_text`],
//! [`sqlrite_column_name`], [`sqlrite_last_error`]) are heap-
//! allocated by this library and must be freed with
//! [`sqlrite_free_string`] — *except* `sqlrite_last_error` whose
//! return value is owned by the thread-local and stays valid until
//! the next error on the same thread.
//!
//! ## Memory rules at a glance
//!
//! | API | Ownership of return |
//! |---------------------------|----------------------------------------------|
//! | `sqlrite_open` | caller frees via `sqlrite_close` |
//! | `sqlrite_query` | caller frees via `sqlrite_finalize` |
//! | `sqlrite_column_text` | caller frees via `sqlrite_free_string` |
//! | `sqlrite_column_name` | caller frees via `sqlrite_free_string` |
//! | `sqlrite_last_error` | library-owned thread-local, do *not* free |
//!
//! ## Thread safety
//!
//! A `SqlriteConnection` is `!Sync` — don't share a single connection
//! across threads without external synchronization. The last-error
//! slot is thread-local, so multi-threaded callers can each inspect
//! their own error independently.
use std::cell::RefCell;
use std::ffi::{CStr, CString};
use std::os::raw::{c_char, c_double, c_int};
use std::path::Path;
use std::ptr;
use sqlrite::{Connection, Rows, Value};
// ---------------------------------------------------------------------------
// Status codes
/// Return value of every mutating FFI function. `Ok` is zero; every
/// error is a distinct positive integer so bindings can switch on it.
/// The full error message (with path / SQL / nested causes) is
/// available via [`sqlrite_last_error`].
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SqlriteStatus {
Ok = 0,
/// Generic error — check `sqlrite_last_error` for details.
Error = 1,
/// A required pointer argument was null, or an input string was
/// invalid UTF-8 / not NUL-terminated.
InvalidArgument = 2,
/// Phase 11.7 — a `BEGIN CONCURRENT` commit hit a row-level
/// write-write conflict. The transaction has already been
/// rolled back; the caller should retry the whole
/// transaction with a fresh `BEGIN CONCURRENT`. SDK retry
/// helpers branch on this code (or its `BusySnapshot`
/// sibling) and call their user-provided closure again.
Busy = 5,
/// Phase 11.7 — same retry semantics as [`Self::Busy`], but
/// surfaces the snapshot-isolation specific case (a row in
/// the transaction's read-set changed under us). Reserved
/// for the read-anomaly path Phase 11.5+ wires through
/// `MvStore`; today the engine emits it from the same
/// `BEGIN CONCURRENT` commit path. Distinguished from
/// `Busy` so SDKs can map each to its own
/// per-language exception class without forking on the
/// message string.
BusySnapshot = 6,
/// A SELECT query returned no more rows (returned from `step`).
Done = 101,
/// A SELECT query produced a row (returned from `step`).
Row = 102,
}
impl SqlriteStatus {
/// Phase 11.7 — true for [`Self::Busy`] and
/// [`Self::BusySnapshot`]. Mirrors `SQLRiteError::is_retryable`
/// on the Rust side; SDK retry helpers should branch on this
/// rather than matching specific codes so a future retryable
/// code (e.g. lock-wait timeout) doesn't break callers.
pub fn is_retryable(self) -> bool {
matches!(self, Self::Busy | Self::BusySnapshot)
}
}
// ---------------------------------------------------------------------------
// Thread-local last-error
thread_local! {
static LAST_ERROR: RefCell<Option<CString>> = const { RefCell::new(None) };
}
fn set_last_error(msg: impl Into<String>) {
let s = msg.into();
// Strip NULs just in case — a C string can't contain interior NULs.
let cleaned = s.replace('\0', "\\0");
let cstr = CString::new(cleaned).unwrap_or_else(|_| CString::new("error").unwrap());
LAST_ERROR.with(|slot| *slot.borrow_mut() = Some(cstr));
}
fn clear_last_error() {
LAST_ERROR.with(|slot| *slot.borrow_mut() = None);
}
/// Returns the last error message raised on the current thread, or
/// `NULL` if the most recent call succeeded. The returned pointer is
/// owned by the library (thread-local storage) and stays valid until
/// the next FFI call on the same thread — do *not* pass it to
/// [`sqlrite_free_string`].
///
/// # Safety
///
/// The caller must not mutate or free the returned pointer.
#[unsafe(no_mangle)]
pub extern "C" fn sqlrite_last_error() -> *const c_char {
LAST_ERROR.with(|slot| {
slot.borrow()
.as_ref()
.map(|cstr| cstr.as_ptr())
.unwrap_or(ptr::null())
})
}
// ---------------------------------------------------------------------------
// Opaque handle types
//
// `#[repr(C)]` on a unit struct gives cbindgen a typedef to reference;
// callers only see the pointer, never the contents.
/// Opaque handle to a SQLRite database connection.
#[repr(C)]
pub struct SqlriteConnection {
_private: [u8; 0],
}
/// Opaque handle to a running SELECT query. Yields rows via
/// [`sqlrite_step`] until `SqlriteStatus::Done`.
#[repr(C)]
pub struct SqlriteStatement {
_private: [u8; 0],
}
// Internal wrapper types — never exposed directly; the `SqlriteXxx`
// opaque struct pointers above are pointers to these under the hood.
struct ConnHandle {
conn: Connection,
}
struct StmtHandle {
rows: Rows,
/// The row most recently produced by `step`. Column accessors
/// read from this — `None` before the first `step` call and
/// after the iterator has been exhausted.
current: Option<sqlrite::OwnedRow>,
}
// ---------------------------------------------------------------------------
// Helpers
/// Turns a `Result<_, E>` into a status code + last-error side effect.
/// Callers capture the `Ok` value via an out-parameter before calling this.
///
/// The generic version maps every error to [`SqlriteStatus::Error`].
/// For results carrying an engine-typed `SQLRiteError`, use
/// [`status_of_sqlrite`] instead so retryable variants surface as
/// [`SqlriteStatus::Busy`] / [`SqlriteStatus::BusySnapshot`].
fn status_of<T, E: std::fmt::Display>(r: Result<T, E>) -> (SqlriteStatus, Option<T>) {
match r {
Ok(v) => {
clear_last_error();
(SqlriteStatus::Ok, Some(v))
}
Err(e) => {
set_last_error(e.to_string());
(SqlriteStatus::Error, None)
}
}
}
/// Phase 11.7 — specialised [`status_of`] for engine results.
/// Maps [`sqlrite::SQLRiteError::Busy`] /
/// [`sqlrite::SQLRiteError::BusySnapshot`] to the distinct status
/// codes that SDK retry helpers (Python / Node / Go / WASM)
/// branch on. Every other variant collapses to
/// [`SqlriteStatus::Error`] with the message in
/// [`sqlrite_last_error`].
fn status_of_sqlrite<T>(r: Result<T, sqlrite::SQLRiteError>) -> (SqlriteStatus, Option<T>) {
match r {
Ok(v) => {
clear_last_error();
(SqlriteStatus::Ok, Some(v))
}
Err(e) => {
let status = match e {
sqlrite::SQLRiteError::Busy(_) => SqlriteStatus::Busy,
sqlrite::SQLRiteError::BusySnapshot(_) => SqlriteStatus::BusySnapshot,
_ => SqlriteStatus::Error,
};
set_last_error(e.to_string());
(status, None)
}
}
}
/// Borrows a C string into &str or sets the last-error and returns None.
unsafe fn cstr_to_str<'a>(ptr: *const c_char) -> Option<&'a str> {
if ptr.is_null() {
set_last_error("null pointer passed where a string was required");
return None;
}
// Safety precondition: caller guarantees `ptr` points at a valid
// NUL-terminated UTF-8 sequence for its lifetime. Documented on
// every `*const c_char` input in the generated header.
let cstr = unsafe { CStr::from_ptr(ptr) };
match cstr.to_str() {
Ok(s) => Some(s),
Err(_) => {
set_last_error("input string was not valid UTF-8");
None
}
}
}
// ---------------------------------------------------------------------------
// Connection lifecycle
/// Opens (or creates) a database file for read-write access.
///
/// On success, `*out` is set to a non-null handle and the return value
/// is `SqlriteStatus::Ok`. On failure, `*out` is left null and the
/// return value is an error status; call [`sqlrite_last_error`] for
/// the message.
///
/// # Safety
///
/// `path` must be a valid NUL-terminated UTF-8 string. `out` must be a
/// valid writable pointer. The caller owns the returned connection
/// and must free it with [`sqlrite_close`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn sqlrite_open(
path: *const c_char,
out: *mut *mut SqlriteConnection,
) -> SqlriteStatus {
if out.is_null() {
set_last_error("output pointer is null");
return SqlriteStatus::InvalidArgument;
}
let Some(path_str) = (unsafe { cstr_to_str(path) }) else {
return SqlriteStatus::InvalidArgument;
};
let (status, conn) = status_of(Connection::open(Path::new(path_str)));
if let Some(conn) = conn {
let boxed = Box::new(ConnHandle { conn });
unsafe { *out = Box::into_raw(boxed) as *mut SqlriteConnection };
} else {
unsafe { *out = ptr::null_mut() };
}
status
}
/// Opens an existing database file for read-only access — takes a
/// shared advisory lock so multiple read-only openers coexist.
///
/// # Safety
///
/// Same as [`sqlrite_open`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn sqlrite_open_read_only(
path: *const c_char,
out: *mut *mut SqlriteConnection,
) -> SqlriteStatus {
if out.is_null() {
set_last_error("output pointer is null");
return SqlriteStatus::InvalidArgument;
}
let Some(path_str) = (unsafe { cstr_to_str(path) }) else {
return SqlriteStatus::InvalidArgument;
};
let (status, conn) = status_of(Connection::open_read_only(Path::new(path_str)));
if let Some(conn) = conn {
let boxed = Box::new(ConnHandle { conn });
unsafe { *out = Box::into_raw(boxed) as *mut SqlriteConnection };
} else {
unsafe { *out = ptr::null_mut() };
}
status
}
/// Opens a transient in-memory database — no file, no locks. Useful
/// for tests and short-lived in-process DBs.
///
/// # Safety
///
/// `out` must be a valid writable pointer.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn sqlrite_open_in_memory(out: *mut *mut SqlriteConnection) -> SqlriteStatus {
if out.is_null() {
set_last_error("output pointer is null");
return SqlriteStatus::InvalidArgument;
}
let (status, conn) = status_of(Connection::open_in_memory());
if let Some(conn) = conn {
let boxed = Box::new(ConnHandle { conn });
unsafe { *out = Box::into_raw(boxed) as *mut SqlriteConnection };
} else {
unsafe { *out = ptr::null_mut() };
}
status
}
/// Phase 11.8 — mints a sibling connection that shares the same
/// underlying database state (the in-memory tables, the MVCC
/// store, the pager). Wraps the engine's `Connection::connect`.
///
/// Use this to drive `BEGIN CONCURRENT` from multiple FFI
/// handles: each sibling can hold its own concurrent transaction,
/// and commits validate against the shared MvStore.
///
/// The returned handle is owned by the caller and must be freed
/// with [`sqlrite_close`]; closing one sibling doesn't affect
/// the others.
///
/// # Safety
///
/// `existing` must be a valid pointer returned by one of the
/// `sqlrite_open_*` functions and not yet closed. `out` must be
/// a valid writable pointer. On success the caller owns the
/// returned sibling and must call [`sqlrite_close`] on it when
/// done.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn sqlrite_connect_sibling(
existing: *mut SqlriteConnection,
out: *mut *mut SqlriteConnection,
) -> SqlriteStatus {
if existing.is_null() || out.is_null() {
set_last_error("connection or output pointer is null");
return SqlriteStatus::InvalidArgument;
}
// Safety: caller guarantees `existing` is a valid handle.
let parent = unsafe { &mut *(existing as *mut ConnHandle) };
let sibling = parent.conn.connect();
let boxed = Box::new(ConnHandle { conn: sibling });
unsafe { *out = Box::into_raw(boxed) as *mut SqlriteConnection };
clear_last_error();
SqlriteStatus::Ok
}
/// Closes a connection and releases its file locks. Safe to call with
/// a null pointer (no-op).
///
/// # Safety
///
/// `conn` must be a pointer returned by one of the `sqlrite_open_*`
/// functions and not yet closed. After this call the pointer is
/// invalid.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn sqlrite_close(conn: *mut SqlriteConnection) {
if conn.is_null() {
return;
}
// Safety: caller-provided pointer obtained from Box::into_raw in
// one of the open functions.
unsafe { drop(Box::from_raw(conn as *mut ConnHandle)) };
}
// ---------------------------------------------------------------------------
// Non-query execution — DDL, DML, transactions
/// Parses and executes a single SQL statement that doesn't produce
/// rows (CREATE / INSERT / UPDATE / DELETE / BEGIN / COMMIT /
/// ROLLBACK). Use [`sqlrite_query`] for SELECT.
///
/// # Safety
///
/// `conn` must be a valid open connection handle. `sql` must be a
/// valid NUL-terminated UTF-8 string.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn sqlrite_execute(
conn: *mut SqlriteConnection,
sql: *const c_char,
) -> SqlriteStatus {
if conn.is_null() {
set_last_error("connection handle is null");
return SqlriteStatus::InvalidArgument;
}
let Some(sql_str) = (unsafe { cstr_to_str(sql) }) else {
return SqlriteStatus::InvalidArgument;
};
// Safety: caller guarantees `conn` is a valid handle.
let handle = unsafe { &mut *(conn as *mut ConnHandle) };
// Use the SQLRiteError-aware mapper so `BEGIN CONCURRENT`
// commit conflicts surface as `Busy` / `BusySnapshot` rather
// than the generic `Error`. SDK retry helpers branch on these.
let (status, _) = status_of_sqlrite(handle.conn.execute(sql_str));
status
}
// ---------------------------------------------------------------------------
// Query execution — SELECT
/// Parses and runs a SELECT, returning a statement handle whose rows
/// are iterated via [`sqlrite_step`]. Errors if the SQL isn't a
/// SELECT.
///
/// # Safety
///
/// `conn` must be a valid open connection handle. `sql` must be a
/// valid NUL-terminated UTF-8 string. `out` must be a valid writable
/// pointer. On success the caller owns the returned statement and
/// must call [`sqlrite_finalize`] when done.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn sqlrite_query(
conn: *mut SqlriteConnection,
sql: *const c_char,
out: *mut *mut SqlriteStatement,
) -> SqlriteStatus {
if conn.is_null() || out.is_null() {
set_last_error("connection or output handle is null");
return SqlriteStatus::InvalidArgument;
}
let Some(sql_str) = (unsafe { cstr_to_str(sql) }) else {
return SqlriteStatus::InvalidArgument;
};
let handle = unsafe { &mut *(conn as *mut ConnHandle) };
let stmt_result: Result<Rows, _> = (|| {
let stmt = handle.conn.prepare(sql_str)?;
stmt.query()
})();
let (status, rows) = status_of(stmt_result);
if let Some(rows) = rows {
let boxed = Box::new(StmtHandle {
rows,
current: None,
});
unsafe { *out = Box::into_raw(boxed) as *mut SqlriteStatement };
} else {
unsafe { *out = ptr::null_mut() };
}
status
}
/// Advances the statement to the next row.
///
/// Returns:
/// - `SqlriteStatus::Row` — a row is available; read columns via the
/// `sqlrite_column_*` accessors.
/// - `SqlriteStatus::Done` — the query is exhausted; stop calling step.
/// - any error code — check `sqlrite_last_error`.
///
/// # Safety
///
/// `stmt` must be a valid statement handle returned by
/// [`sqlrite_query`] and not yet finalized.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn sqlrite_step(stmt: *mut SqlriteStatement) -> SqlriteStatus {
if stmt.is_null() {
set_last_error("statement handle is null");
return SqlriteStatus::InvalidArgument;
}
let handle = unsafe { &mut *(stmt as *mut StmtHandle) };
match handle.rows.next() {
Ok(Some(row)) => {
handle.current = Some(row.to_owned_row());
clear_last_error();
SqlriteStatus::Row
}
Ok(None) => {
handle.current = None;
clear_last_error();
SqlriteStatus::Done
}
Err(e) => {
set_last_error(e.to_string());
handle.current = None;
SqlriteStatus::Error
}
}
}
/// Frees a statement handle.
///
/// # Safety
///
/// `stmt` must be a pointer returned by [`sqlrite_query`] and not
/// yet finalized. After this call the pointer is invalid.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn sqlrite_finalize(stmt: *mut SqlriteStatement) {
if stmt.is_null() {
return;
}
unsafe { drop(Box::from_raw(stmt as *mut StmtHandle)) };
}
// ---------------------------------------------------------------------------
// Column accessors
//
// Every accessor reads from the most recent row produced by step(). If
// step() hasn't been called or returned Done, the accessors set an
// error.
/// Number of columns in the current row. Writes the count to `*out`
/// and returns `Ok`, or an error status if no row is active.
///
/// # Safety
///
/// `stmt` must be a valid statement handle. `out` must be a valid
/// writable pointer.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn sqlrite_column_count(
stmt: *mut SqlriteStatement,
out: *mut c_int,
) -> SqlriteStatus {
if stmt.is_null() || out.is_null() {
set_last_error("statement or output pointer is null");
return SqlriteStatus::InvalidArgument;
}
let handle = unsafe { &*(stmt as *const StmtHandle) };
unsafe { *out = handle.rows.columns().len() as c_int };
SqlriteStatus::Ok
}
/// Writes the name of column `idx` into `*out` as a heap-allocated
/// NUL-terminated string. The caller must free it via
/// [`sqlrite_free_string`].
///
/// # Safety
///
/// Same as [`sqlrite_column_count`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn sqlrite_column_name(
stmt: *mut SqlriteStatement,
idx: c_int,
out: *mut *mut c_char,
) -> SqlriteStatus {
if stmt.is_null() || out.is_null() {
set_last_error("statement or output pointer is null");
return SqlriteStatus::InvalidArgument;
}
let handle = unsafe { &*(stmt as *const StmtHandle) };
let columns = handle.rows.columns();
let Some(name) = columns.get(idx as usize) else {
set_last_error(format!(
"column index {idx} out of bounds (statement has {} columns)",
columns.len()
));
return SqlriteStatus::Error;
};
unsafe { *out = alloc_c_string(name) };
SqlriteStatus::Ok
}
/// Reads column `idx` of the current row as a 64-bit integer into `*out`.
/// Errors if no row is active, the column is NULL, or the column's
/// native type can't be losslessly converted to i64.
///
/// # Safety
///
/// Same as [`sqlrite_column_count`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn sqlrite_column_int64(
stmt: *mut SqlriteStatement,
idx: c_int,
out: *mut i64,
) -> SqlriteStatus {
with_current_value(
stmt,
idx,
|v, out_void| match v {
Value::Integer(n) => {
unsafe { *(out_void as *mut i64) = *n };
SqlriteStatus::Ok
}
Value::Null => {
set_last_error("column is NULL (use sqlrite_column_is_null to check first)");
SqlriteStatus::Error
}
other => {
set_last_error(format!("cannot convert {other:?} to int64"));
SqlriteStatus::Error
}
},
out as *mut c_void,
)
}
/// Reads column `idx` as a double.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn sqlrite_column_double(
stmt: *mut SqlriteStatement,
idx: c_int,
out: *mut c_double,
) -> SqlriteStatus {
with_current_value(
stmt,
idx,
|v, out_void| match v {
Value::Real(f) => {
unsafe { *(out_void as *mut c_double) = *f };
SqlriteStatus::Ok
}
Value::Integer(n) => {
unsafe { *(out_void as *mut c_double) = *n as c_double };
SqlriteStatus::Ok
}
Value::Null => {
set_last_error("column is NULL");
SqlriteStatus::Error
}
other => {
set_last_error(format!("cannot convert {other:?} to double"));
SqlriteStatus::Error
}
},
out as *mut c_void,
)
}
/// Reads column `idx` as a newly-allocated NUL-terminated UTF-8
/// string. The caller must free the result via [`sqlrite_free_string`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn sqlrite_column_text(
stmt: *mut SqlriteStatement,
idx: c_int,
out: *mut *mut c_char,
) -> SqlriteStatus {
with_current_value(
stmt,
idx,
|v, out_void| match v {
Value::Text(s) => {
unsafe { *(out_void as *mut *mut c_char) = alloc_c_string(s) };
SqlriteStatus::Ok
}
Value::Null => {
set_last_error("column is NULL");
SqlriteStatus::Error
}
// For Int/Real/Bool we coerce to the display form — matches
// sqlite3_column_text's lenient behavior.
other => {
let rendered = other.to_display_string();
unsafe { *(out_void as *mut *mut c_char) = alloc_c_string(&rendered) };
SqlriteStatus::Ok
}
},
out as *mut c_void,
)
}
/// Writes `1` to `*out` if column `idx` is NULL, `0` otherwise.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn sqlrite_column_is_null(
stmt: *mut SqlriteStatement,
idx: c_int,
out: *mut c_int,
) -> SqlriteStatus {
with_current_value(
stmt,
idx,
|v, out_void| {
unsafe { *(out_void as *mut c_int) = matches!(v, Value::Null) as c_int };
SqlriteStatus::Ok
},
out as *mut c_void,
)
}
// ---------------------------------------------------------------------------
// Introspection
/// Returns 1 if a `BEGIN … COMMIT/ROLLBACK` block is open on this
/// connection, 0 otherwise. -1 on error (null handle).
///
/// # Safety
///
/// `conn` must be a valid open connection handle (or null, in which
/// case this returns -1).
#[unsafe(no_mangle)]
pub unsafe extern "C" fn sqlrite_in_transaction(conn: *mut SqlriteConnection) -> c_int {
if conn.is_null() {
set_last_error("connection handle is null");
return -1;
}
let handle = unsafe { &*(conn as *const ConnHandle) };
handle.conn.in_transaction() as c_int
}
/// Returns 1 if this connection was opened read-only, 0 otherwise.
/// -1 on error.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn sqlrite_is_read_only(conn: *mut SqlriteConnection) -> c_int {
if conn.is_null() {
set_last_error("connection handle is null");
return -1;
}
let handle = unsafe { &*(conn as *const ConnHandle) };
handle.conn.is_read_only() as c_int
}
// ---------------------------------------------------------------------------
// Phase 7g.6 — natural-language → SQL.
//
// One C function: `sqlrite_ask(conn, question, config_json, out)`.
//
// `config_json` is a JSON-encoded AskConfig (or NULL / empty string
// to fall back to AskConfig::from_env). Passing the config as JSON
// rather than 6+ separate FFI parameters keeps the surface tiny and
// extension-friendly: adding a new field later doesn't break the
// C ABI for existing bindings.
//
// Recognized JSON keys (all optional; missing → defaults):
// {"provider": "anthropic", "api_key": "...", "model": "...",
// "max_tokens": 1024, "cache_ttl": "5m", "base_url": "..."}
//
// On success, `*out` is set to a heap-allocated NUL-terminated UTF-8
// JSON string the caller must free via `sqlrite_free_string`. The
// JSON shape is:
//
// {
// "sql": "...",
// "explanation": "...",
// "usage": {
// "input_tokens": 1234,
// "output_tokens": 56,
// "cache_creation_input_tokens": 1000,
// "cache_read_input_tokens": 0
// }
// }
//
// On failure, `*out` is set to NULL and the status code indicates
// the failure mode; details are in `sqlrite_last_error`.
#[derive(serde::Deserialize)]
struct ConfigOverride {
provider: Option<String>,
api_key: Option<String>,
model: Option<String>,
max_tokens: Option<u32>,
cache_ttl: Option<String>,
base_url: Option<String>,
}
#[derive(serde::Serialize)]
struct AskFfiResponse {
sql: String,
explanation: String,
usage: AskFfiUsage,
}
#[derive(serde::Serialize)]
struct AskFfiUsage {
input_tokens: u64,
output_tokens: u64,
cache_creation_input_tokens: u64,
cache_read_input_tokens: u64,
}
fn build_ask_config(config_json: &str) -> Result<sqlrite::ask::AskConfig, String> {
use sqlrite::ask::{AskConfig, CacheTtl, ProviderKind};
// Empty string == "use env defaults" — same shape every other SDK
// ends up at when the caller passes nothing.
let trimmed = config_json.trim();
if trimmed.is_empty() {
return AskConfig::from_env().map_err(|e| e.to_string());
}
// Start from env so any unset keys in the JSON inherit env values.
// Lets a Go caller pass `{"model": "claude-haiku-4-5"}` and still
// pick up `SQLRITE_LLM_API_KEY` from the environment.
let mut cfg = AskConfig::from_env().map_err(|e| e.to_string())?;
let overrides: ConfigOverride =
serde_json::from_str(trimmed).map_err(|e| format!("invalid config JSON: {e}"))?;
if let Some(p) = overrides.provider {
cfg.provider = match p.to_ascii_lowercase().as_str() {
"anthropic" => ProviderKind::Anthropic,
other => return Err(format!("unknown provider: {other} (supported: anthropic)")),
};
}
if let Some(k) = overrides.api_key {
if !k.is_empty() {
cfg.api_key = Some(k);
}
}
if let Some(m) = overrides.model {
if !m.is_empty() {
cfg.model = m;
}
}
if let Some(t) = overrides.max_tokens {
cfg.max_tokens = t;
}
if let Some(c) = overrides.cache_ttl {
cfg.cache_ttl = match c.to_ascii_lowercase().as_str() {
"5m" | "5min" | "5minutes" => CacheTtl::FiveMinutes,
"1h" | "1hr" | "1hour" => CacheTtl::OneHour,
"off" | "none" | "disabled" => CacheTtl::Off,
other => return Err(format!("unknown cache_ttl: {other}")),
};
}
if let Some(u) = overrides.base_url {
if !u.is_empty() {
cfg.base_url = Some(u);
}
}
Ok(cfg)
}
/// Generate SQL from a natural-language question via the configured
/// LLM provider. Returns a JSON string in `*out` (caller frees with
/// `sqlrite_free_string`).
///
/// `config_json` may be NULL or an empty string to use
/// `AskConfig::from_env()`. Otherwise it's a JSON object with any of
/// the documented keys above; unset keys fall back to env values.
///
/// # Safety
///
/// `conn` must be a valid open connection handle. `question` must be
/// a valid NUL-terminated UTF-8 string. `config_json` may be NULL or
/// a valid NUL-terminated UTF-8 JSON string. `out` must be a valid
/// writable pointer.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn sqlrite_ask(
conn: *mut SqlriteConnection,
question: *const c_char,
config_json: *const c_char,
out: *mut *mut c_char,
) -> SqlriteStatus {
clear_last_error();
if out.is_null() {
set_last_error("output pointer is null");
return SqlriteStatus::InvalidArgument;
}
unsafe { *out = ptr::null_mut() };
if conn.is_null() {
set_last_error("connection handle is null");
return SqlriteStatus::InvalidArgument;
}
let Some(question_str) = (unsafe { cstr_to_str(question) }) else {
return SqlriteStatus::InvalidArgument;
};
// config_json: NULL is OK (means "use env defaults"). Non-null
// must be valid UTF-8.
let config_str = if config_json.is_null() {
""
} else {
match unsafe { cstr_to_str(config_json) } {
Some(s) => s,
None => return SqlriteStatus::InvalidArgument,
}
};
let cfg = match build_ask_config(config_str) {
Ok(c) => c,
Err(e) => {
set_last_error(e);
return SqlriteStatus::Error;
}
};
let handle = unsafe { &*(conn as *const ConnHandle) };
let resp = match sqlrite::ask::ask(&handle.conn, question_str, &cfg) {
Ok(r) => r,
Err(e) => {
set_last_error(e.to_string());
return SqlriteStatus::Error;
}
};
let ffi_resp = AskFfiResponse {
sql: resp.sql,
explanation: resp.explanation,
usage: AskFfiUsage {
input_tokens: resp.usage.input_tokens,
output_tokens: resp.usage.output_tokens,
cache_creation_input_tokens: resp.usage.cache_creation_input_tokens,
cache_read_input_tokens: resp.usage.cache_read_input_tokens,
},
};
let json = match serde_json::to_string(&ffi_resp) {
Ok(j) => j,
Err(e) => {
set_last_error(format!("failed to encode response JSON: {e}"));
return SqlriteStatus::Error;
}
};
let cstr = match CString::new(json) {
Ok(c) => c,
Err(e) => {
set_last_error(format!("response JSON contained NUL: {e}"));
return SqlriteStatus::Error;
}
};
unsafe { *out = cstr.into_raw() };
SqlriteStatus::Ok
}
// ---------------------------------------------------------------------------
// Memory freeing
/// Frees a string returned by `sqlrite_column_text` or `sqlrite_column_name`.
/// Safe to call with a null pointer (no-op).
///
/// # Safety
///
/// `ptr` must be a pointer returned by one of those functions and not
/// yet freed.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn sqlrite_free_string(ptr: *mut c_char) {
if ptr.is_null() {
return;
}
unsafe { drop(CString::from_raw(ptr)) };
}
// ---------------------------------------------------------------------------
// Internal helpers
use std::ffi::c_void;
/// Runs `f` against the current row's column value, handling the
/// no-row / out-of-bounds / null-pointer paths centrally. `out` is
/// a type-erased pointer; `f` casts it back to the expected type.
fn with_current_value<F>(
stmt: *mut SqlriteStatement,
idx: c_int,
f: F,
out: *mut c_void,
) -> SqlriteStatus
where
F: FnOnce(&Value, *mut c_void) -> SqlriteStatus,
{
if stmt.is_null() || out.is_null() {
set_last_error("statement or output pointer is null");
return SqlriteStatus::InvalidArgument;
}
let handle = unsafe { &*(stmt as *const StmtHandle) };
let Some(row) = handle.current.as_ref() else {
set_last_error(
"no current row — call sqlrite_step() and check for Row before reading columns",
);
return SqlriteStatus::Error;
};
let Some(val) = row.values.get(idx as usize) else {
set_last_error(format!(
"column index {idx} out of bounds (row has {} columns)",
row.values.len()
));
return SqlriteStatus::Error;
};
clear_last_error();
f(val, out)
}
/// Heap-allocates a C string from a Rust &str. The caller owns the
/// result and must free it via `sqlrite_free_string`. Falls back to
/// an empty string if the input contains interior NULs (shouldn't
/// happen for UTF-8 text from SQLite-style engines but we defend).
fn alloc_c_string(s: &str) -> *mut c_char {
CString::new(s.replace('\0', "\\0"))
.unwrap_or_else(|_| CString::new("").unwrap())
.into_raw()
}
// ---------------------------------------------------------------------------
// Tests