powersync_sqlite_nostd 0.5.4

Lightweight, semi-unsafe, nostd bindings to sqlite3
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
extern crate alloc;

use alloc::boxed::Box;
use alloc::ffi::{IntoStringError, NulError};
use alloc::vec::Vec;
use alloc::{ffi::CString, string::String};
use core::array::TryFromSliceError;
use core::cell::{BorrowError, BorrowMutError};
use core::ffi::{CStr, c_char, c_int, c_void};
use core::ptr::null_mut;
use core::{error::Error, slice, str::Utf8Error};

use num_derive::FromPrimitive;
use num_traits::FromPrimitive;

use crate::bindings;
use crate::capi as sqlite3_capi;
pub use crate::capi::*;

// https://www.sqlite.org/c3ref/c_alter_table.html
#[derive(FromPrimitive, PartialEq, Debug, Clone, Copy)]
pub enum ActionCode {
    COPY = 0,
    CREATE_INDEX = 1,
    CREATE_TABLE = 2,
    CREATE_TEMP_INDEX = 3,
    CREATE_TEMP_TABLE = 4,
    CREATE_TEMP_TRIGGER = 5,
    CREATE_TEMP_VIEW = 6,
    CREATE_TRIGGER = 7,
    CREATE_VIEW = 8,
    DELETE = 9,
    DROP_INDEX = 10,
    DROP_TABLE = 11,
    DROP_TEMP_INDEX = 12,
    DROP_TEMP_TABLE = 13,
    DROP_TEMP_TRIGGER = 14,
    DROP_TEMP_VIEW = 15,
    DROP_TRIGGER = 16,
    DROP_VIEW = 17,
    INSERT = 18,
    PRAGMA = 19,
    READ = 20,
    SELECT = 21,
    TRANSACTION = 22,
    UPDATE = 23,
    ATTACH = 24,
    DETACH = 25,
    ALTER_TABLE = 26,
    REINDEX = 27,
    ANALYZE = 28,
    CREATE_VTABLE = 29,
    DROP_VTABLE = 30,
    FUNCTION = 31,
    SAVEPOINT = 32,
    RECURSIVE = 33,
}

#[derive(FromPrimitive, PartialEq, Debug, Clone, Copy)]
pub enum ResultCode {
    OK = 0,
    ERROR = 1,
    INTERNAL = 2,
    PERM = 3,
    ABORT = 4,
    BUSY = 5,
    LOCKED = 6,
    NOMEM = 7,
    READONLY = 8,
    INTERRUPT = 9,
    IOERR = 10,
    CORRUPT = 11,
    NOTFOUND = 12,
    FULL = 13,
    CANTOPEN = 14,
    PROTOCOL = 15,
    EMPTY = 16,
    SCHEMA = 17,
    TOOBIG = 18,
    CONSTRAINT = 19,
    MISMATCH = 20,
    MISUSE = 21,
    NOLFS = 22,
    AUTH = 23,
    FORMAT = 24,
    RANGE = 25,
    NOTADB = 26,
    NOTICE = 27,
    WARNING = 28,
    ROW = 100,
    DONE = 101,
    ERROR_MISSING_COLLSEQ = bindings::SQLITE_ERROR_MISSING_COLLSEQ as isize,
    ERROR_RETRY = bindings::SQLITE_ERROR_RETRY as isize,
    ERROR_SNAPSHOT = bindings::SQLITE_ERROR_SNAPSHOT as isize,
    IOERR_READ = bindings::SQLITE_IOERR_READ as isize,
    IOERR_SHORT_READ = bindings::SQLITE_IOERR_SHORT_READ as isize,
    IOERR_WRITE = bindings::SQLITE_IOERR_WRITE as isize,
    IOERR_FSYNC = bindings::SQLITE_IOERR_FSYNC as isize,
    IOERR_DIR_FSYNC = bindings::SQLITE_IOERR_DIR_FSYNC as isize,
    IOERR_TRUNCATE = bindings::SQLITE_IOERR_TRUNCATE as isize,
    IOERR_FSTAT = bindings::SQLITE_IOERR_FSTAT as isize,
    IOERR_UNLOCK = bindings::SQLITE_IOERR_UNLOCK as isize,
    IOERR_RDLOCK = bindings::SQLITE_IOERR_RDLOCK as isize,
    IOERR_DELETE = bindings::SQLITE_IOERR_DELETE as isize,
    IOERR_BLOCKED = bindings::SQLITE_IOERR_BLOCKED as isize,
    IOERR_NOMEM = bindings::SQLITE_IOERR_NOMEM as isize,
    IOERR_ACCESS = bindings::SQLITE_IOERR_ACCESS as isize,
    IOERR_CHECKRESERVEDLOCK = bindings::SQLITE_IOERR_CHECKRESERVEDLOCK as isize,
    IOERR_LOCK = bindings::SQLITE_IOERR_LOCK as isize,
    IOERR_CLOSE = bindings::SQLITE_IOERR_CLOSE as isize,
    IOERR_DIR_CLOSE = bindings::SQLITE_IOERR_DIR_CLOSE as isize,
    IOERR_SHMOPEN = bindings::SQLITE_IOERR_SHMOPEN as isize,
    IOERR_SHMSIZE = bindings::SQLITE_IOERR_SHMSIZE as isize,
    IOERR_SHMLOCK = bindings::SQLITE_IOERR_SHMLOCK as isize,
    IOERR_SHMMAP = bindings::SQLITE_IOERR_SHMMAP as isize,
    IOERR_SEEK = bindings::SQLITE_IOERR_SEEK as isize,
    IOERR_DELETE_NOENT = bindings::SQLITE_IOERR_DELETE_NOENT as isize,
    IOERR_MMAP = bindings::SQLITE_IOERR_MMAP as isize,
    IOERR_GETTEMPPATH = bindings::SQLITE_IOERR_GETTEMPPATH as isize,
    IOERR_CONVPATH = bindings::SQLITE_IOERR_CONVPATH as isize,
    IOERR_VNODE = bindings::SQLITE_IOERR_VNODE as isize,
    IOERR_AUTH = bindings::SQLITE_IOERR_AUTH as isize,
    IOERR_BEGIN_ATOMIC = bindings::SQLITE_IOERR_BEGIN_ATOMIC as isize,
    IOERR_COMMIT_ATOMIC = bindings::SQLITE_IOERR_COMMIT_ATOMIC as isize,
    IOERR_ROLLBACK_ATOMIC = bindings::SQLITE_IOERR_ROLLBACK_ATOMIC as isize,
    IOERR_DATA = bindings::SQLITE_IOERR_DATA as isize,
    IOERR_CORRUPTFS = bindings::SQLITE_IOERR_CORRUPTFS as isize,
    LOCKED_SHAREDCACHE = bindings::SQLITE_LOCKED_SHAREDCACHE as isize,
    LOCKED_VTAB = bindings::SQLITE_LOCKED_VTAB as isize,
    BUSY_RECOVERY = bindings::SQLITE_BUSY_RECOVERY as isize,
    BUSY_SNAPSHOT = bindings::SQLITE_BUSY_SNAPSHOT as isize,
    BUSY_TIMEOUT = bindings::SQLITE_BUSY_TIMEOUT as isize,
    CANTOPEN_NOTEMPDIR = bindings::SQLITE_CANTOPEN_NOTEMPDIR as isize,
    CANTOPEN_ISDIR = bindings::SQLITE_CANTOPEN_ISDIR as isize,
    CANTOPEN_FULLPATH = bindings::SQLITE_CANTOPEN_FULLPATH as isize,
    CANTOPEN_CONVPATH = bindings::SQLITE_CANTOPEN_CONVPATH as isize,
    CANTOPEN_DIRTYWAL = bindings::SQLITE_CANTOPEN_DIRTYWAL as isize,
    CANTOPEN_SYMLINK = bindings::SQLITE_CANTOPEN_SYMLINK as isize,
    CORRUPT_VTAB = bindings::SQLITE_CORRUPT_VTAB as isize,
    CORRUPT_SEQUENCE = bindings::SQLITE_CORRUPT_SEQUENCE as isize,
    CORRUPT_INDEX = bindings::SQLITE_CORRUPT_INDEX as isize,
    READONLY_RECOVERY = bindings::SQLITE_READONLY_RECOVERY as isize,
    READONLY_CANTLOCK = bindings::SQLITE_READONLY_CANTLOCK as isize,
    READONLY_ROLLBACK = bindings::SQLITE_READONLY_ROLLBACK as isize,
    READONLY_DBMOVED = bindings::SQLITE_READONLY_DBMOVED as isize,
    READONLY_CANTINIT = bindings::SQLITE_READONLY_CANTINIT as isize,
    READONLY_DIRECTORY = bindings::SQLITE_READONLY_DIRECTORY as isize,
    ABORT_ROLLBACK = bindings::SQLITE_ABORT_ROLLBACK as isize,
    CONSTRAINT_CHECK = bindings::SQLITE_CONSTRAINT_CHECK as isize,
    CONSTRAINT_COMMITHOOK = bindings::SQLITE_CONSTRAINT_COMMITHOOK as isize,
    CONSTRAINT_FOREIGNKEY = bindings::SQLITE_CONSTRAINT_FOREIGNKEY as isize,
    CONSTRAINT_FUNCTION = bindings::SQLITE_CONSTRAINT_FUNCTION as isize,
    CONSTRAINT_NOTNULL = bindings::SQLITE_CONSTRAINT_NOTNULL as isize,
    CONSTRAINT_PRIMARYKEY = bindings::SQLITE_CONSTRAINT_PRIMARYKEY as isize,
    CONSTRAINT_TRIGGER = bindings::SQLITE_CONSTRAINT_TRIGGER as isize,
    CONSTRAINT_UNIQUE = bindings::SQLITE_CONSTRAINT_UNIQUE as isize,
    CONSTRAINT_VTAB = bindings::SQLITE_CONSTRAINT_VTAB as isize,
    CONSTRAINT_ROWID = bindings::SQLITE_CONSTRAINT_ROWID as isize,
    CONSTRAINT_PINNED = bindings::SQLITE_CONSTRAINT_PINNED as isize,
    CONSTRAINT_DATATYPE = bindings::SQLITE_CONSTRAINT_DATATYPE as isize,
    NOTICE_RECOVER_WAL = bindings::SQLITE_NOTICE_RECOVER_WAL as isize,
    NOTICE_RECOVER_ROLLBACK = bindings::SQLITE_NOTICE_RECOVER_ROLLBACK as isize,
    WARNING_AUTOINDEX = bindings::SQLITE_WARNING_AUTOINDEX as isize,
    AUTH_USER = bindings::SQLITE_AUTH_USER as isize,
    OK_LOAD_PERMANENTLY = bindings::SQLITE_OK_LOAD_PERMANENTLY as isize,
    OK_SYMLINK = bindings::SQLITE_OK_SYMLINK as isize,

    NULL = 5000,
}

impl core::fmt::Display for ResultCode {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "{:?}", self)
    }
}

impl Error for ResultCode {}

impl From<Utf8Error> for ResultCode {
    fn from(_error: Utf8Error) -> Self {
        ResultCode::FORMAT
    }
}

impl From<TryFromSliceError> for ResultCode {
    fn from(_error: TryFromSliceError) -> Self {
        ResultCode::RANGE
    }
}

impl From<NulError> for ResultCode {
    fn from(_error: NulError) -> Self {
        ResultCode::NOMEM
    }
}

impl From<IntoStringError> for ResultCode {
    fn from(_error: IntoStringError) -> Self {
        ResultCode::FORMAT
    }
}

impl From<BorrowError> for ResultCode {
    fn from(_error: BorrowError) -> Self {
        ResultCode::ERROR
    }
}

impl From<BorrowMutError> for ResultCode {
    fn from(_error: BorrowMutError) -> Self {
        ResultCode::ERROR
    }
}

impl From<String> for ResultCode {
    fn from(_error: String) -> Self {
        ResultCode::ERROR
    }
}

#[derive(FromPrimitive, PartialEq, Debug, Clone, Copy)]
pub enum ColumnType {
    Integer = 1,
    Float = 2,
    Text = 3,
    Blob = 4,
    Null = 5,
}

pub fn libversion() -> &'static str {
    unsafe { CStr::from_ptr(sqlite3_capi::libversion()) }
        .to_str()
        .unwrap()
}

pub fn libversion_number() -> c_int {
    sqlite3_capi::libversion_number()
}

pub fn randomness(blob: &mut [u8]) {
    sqlite3_capi::randomness(blob.len() as c_int, blob.as_mut_ptr() as *mut c_void)
}

pub trait Connection {
    fn commit_hook(&self, callback: Option<xCommitHook>, user_data: *mut c_void) -> *mut c_void;

    fn create_function_v2(
        &self,
        name: &str,
        n_arg: i32,
        flags: u32,
        user_data: Option<*mut c_void>,
        func: Option<xFunc>,
        step: Option<xStep>,
        final_func: Option<xFinal>,
        destroy: Option<xDestroy>,
    ) -> Result<ResultCode, ResultCode>;

    fn create_module_v2(
        &self,
        name: &str,
        module: *const module,
        user_data: Option<*mut c_void>,
        destroy: Option<xDestroy>,
    ) -> Result<ResultCode, ResultCode>;

    fn changes64(&self) -> i64;

    fn errcode(&self) -> ResultCode;
    fn errmsg(&self) -> Result<String, IntoStringError>;
    fn error_offset(&self) -> Option<usize>;

    fn rollback_hook(&self, callback: Option<xRollbackHook>, ctx: *mut c_void) -> *mut c_void;

    fn update_hook(&self, callback: Option<xUpdateHook>, ctx: *mut c_void) -> *mut c_void;
}

impl Connection for *mut sqlite3 {
    fn changes64(&self) -> i64 {
        changes64(*self)
    }

    fn commit_hook(&self, callback: Option<xCommitHook>, user_data: *mut c_void) -> *mut c_void {
        commit_hook(*self, callback, user_data)
    }

    fn create_function_v2(
        &self,
        name: &str,
        n_arg: i32,
        flags: u32,
        user_data: Option<*mut c_void>,
        func: Option<xFunc>,
        step: Option<xStep>,
        final_func: Option<xFinal>,
        destroy: Option<xDestroy>,
    ) -> Result<ResultCode, ResultCode> {
        if let Ok(name) = CString::new(name) {
            convert_rc(create_function_v2(
                *self,
                name.as_ptr(),
                n_arg,
                flags as c_int,
                user_data.unwrap_or(core::ptr::null_mut()),
                func,
                step,
                final_func,
                destroy,
            ))
        } else {
            Err(ResultCode::NOMEM)
        }
    }

    fn create_module_v2(
        &self,
        name: &str,
        module: *const module,
        user_data: Option<*mut c_void>,
        destroy: Option<xDestroy>,
    ) -> Result<ResultCode, ResultCode> {
        if let Ok(name) = CString::new(name) {
            convert_rc(create_module_v2(
                *self,
                name.as_ptr(),
                module,
                user_data.unwrap_or(core::ptr::null_mut()),
                destroy,
            ))
        } else {
            Err(ResultCode::NOMEM)
        }
    }

    fn errmsg(&self) -> Result<String, IntoStringError> {
        errmsg(*self).into_string()
    }

    fn errcode(&self) -> ResultCode {
        ResultCode::from_i32(errcode(*self)).unwrap()
    }

    fn error_offset(&self) -> Option<usize> {
        match error_offset(*self) {
            -1 => None,
            other => Some(other as usize),
        }
    }

    fn rollback_hook(&self, callback: Option<xRollbackHook>, ctx: *mut c_void) -> *mut c_void {
        rollback_hook(*self, callback, ctx)
    }

    fn update_hook(&self, callback: Option<xUpdateHook>, ctx: *mut c_void) -> *mut c_void {
        update_hook(*self, callback, ctx)
    }
}

pub fn convert_rc(rc: i32) -> Result<ResultCode, ResultCode> {
    let rc = ResultCode::from_i32(rc).unwrap_or(ResultCode::ABORT);
    if rc == ResultCode::OK {
        Ok(rc)
    } else {
        Err(rc)
    }
}

pub struct ManagedStmt {
    pub stmt: *mut stmt,
}

impl ManagedStmt {
    pub fn reset(&self) -> Result<ResultCode, ResultCode> {
        convert_rc(reset(self.stmt))
    }

    pub fn step(&self) -> Result<ResultCode, ResultCode> {
        let rc = ResultCode::from_i32(step(self.stmt)).unwrap();
        if (rc == ResultCode::ROW) || (rc == ResultCode::DONE) {
            Ok(rc)
        } else {
            Err(rc)
        }
    }

    pub fn sql(&self) -> Result<&str, ResultCode> {
        let ptr = sql(self.stmt);
        Ok(unsafe { CStr::from_ptr(ptr) }.to_str()?)
    }

    #[inline]
    pub fn column_count(&self) -> i32 {
        column_count(self.stmt)
    }

    /// Calls to `step` or addiitonal calls to `column_name` will invalidate the
    /// returned string. Unclear if there's any way to capture this
    /// behavior in the type system.
    #[inline]
    pub fn column_name(&self, i: i32) -> Result<&str, ResultCode> {
        let ptr = column_name(self.stmt, i);
        if ptr.is_null() {
            Err(ResultCode::NULL)
        } else {
            Ok(
                unsafe {
                    core::str::from_utf8_unchecked(core::ffi::CStr::from_ptr(ptr).to_bytes())
                },
            )
        }
    }

    #[inline]
    pub fn column_type(&self, i: i32) -> ColumnType {
        ColumnType::from_i32(column_type(self.stmt, i)).unwrap_or(ColumnType::Null)
    }

    #[inline]
    pub fn column_text(&self, i: i32) -> Result<&str, ResultCode> {
        let len = column_bytes(self.stmt, i);
        let ptr = column_text_ptr(self.stmt, i);
        if ptr.is_null() {
            Err(ResultCode::NULL)
        } else {
            Ok(unsafe {
                let slice = core::slice::from_raw_parts(ptr as *const u8, len as usize);
                core::str::from_utf8_unchecked(slice)
            })
        }
    }

    #[inline]
    pub fn column_blob(&self, i: i32) -> Result<&[u8], ResultCode> {
        let len = column_bytes(self.stmt, i);
        let ptr = column_blob(self.stmt, i);
        if ptr.is_null() {
            Err(ResultCode::NULL)
        } else {
            Ok(unsafe { core::slice::from_raw_parts(ptr as *const u8, len as usize) })
        }
    }

    #[inline]
    pub fn column_double(&self, i: i32) -> f64 {
        column_double(self.stmt, i)
    }

    #[inline]
    pub fn column_int(&self, i: i32) -> i32 {
        column_int(self.stmt, i)
    }

    #[inline]
    pub fn column_int64(&self, i: i32) -> int64 {
        column_int64(self.stmt, i)
    }

    // TODO: this should return `Option<*mut valu>`
    #[inline]
    pub fn column_value(&self, i: i32) -> Result<*mut value, ResultCode> {
        let ptr = column_value(self.stmt, i);
        if ptr.is_null() {
            Err(ResultCode::NULL)
        } else {
            Ok(ptr)
        }
    }

    pub fn bind_blob(&self, i: i32, val: &[u8], d: Destructor) -> Result<ResultCode, ResultCode> {
        convert_rc(bind_blob(
            self.stmt,
            i,
            val.as_ptr() as *const c_void,
            val.len() as i32,
            d,
        ))
    }

    #[inline]
    pub fn bind_value(&self, i: i32, val: *mut value) -> Result<ResultCode, ResultCode> {
        convert_rc(bind_value(self.stmt, i, val))
    }

    #[inline]
    pub fn bind_text(&self, i: i32, text: &str, d: Destructor) -> Result<ResultCode, ResultCode> {
        convert_rc(bind_text(
            self.stmt,
            i,
            text.as_ptr() as *const c_char,
            text.len() as i32,
            d,
        ))
    }

    #[inline]
    pub fn bind_int64(&self, i: i32, val: int64) -> Result<ResultCode, ResultCode> {
        convert_rc(bind_int64(self.stmt, i, val))
    }

    #[inline]
    pub fn bind_int(&self, i: i32, val: i32) -> Result<ResultCode, ResultCode> {
        convert_rc(bind_int(self.stmt, i, val))
    }

    #[inline]
    pub fn bind_double(&self, i: i32, val: f64) -> Result<ResultCode, ResultCode> {
        convert_rc(bind_double(self.stmt, i, val))
    }

    #[inline]
    pub fn bind_null(&self, i: i32) -> Result<ResultCode, ResultCode> {
        convert_rc(bind_null(self.stmt, i))
    }

    #[inline]
    pub fn clear_bindings(&self) -> Result<ResultCode, ResultCode> {
        convert_rc(clear_bindings(self.stmt))
    }

    #[inline]
    pub fn bind_parameter_count(&self) -> c_int {
        bind_parameter_count(self.stmt)
    }

    pub fn bind_parameter_name(&self, i: i32) -> Result<Option<&str>, Utf8Error> {
        let ptr = bind_parameter_name(self.stmt, i);
        if ptr.is_null() {
            Ok(None)
        } else {
            let name = unsafe { CStr::from_ptr(ptr) };
            Ok(Some(name.to_str()?))
        }
    }

    #[inline]
    pub fn finalize(self) -> Result<ResultCode, ResultCode> {
        self.stmt.finalize()
    }

    pub fn into_raw(self) -> *mut stmt {
        let stmt = self.stmt;
        core::mem::forget(self);
        stmt
    }
}

impl Drop for ManagedStmt {
    fn drop(&mut self) {
        finalize(self.stmt);
    }
}

pub trait Context {
    fn result_text_transient(&self, text: &str);
    fn result_text_static(&self, text: &str);
    fn result_blob_transient(&self, blob: &[u8]);
    fn result_blob_static(&self, blob: &[u8]);
    fn result_error(&self, text: &str);
    fn result_error_code(&self, code: ResultCode);
    fn result_value(&self, value: *mut value);
    fn result_double(&self, value: f64);
    fn result_int(&self, value: i32);
    fn result_int64(&self, value: int64);
    fn result_null(&self);
    fn result_subtype(&self, subtype: u32);
    fn db_handle(&self) -> *mut sqlite3;
    fn user_data(&self) -> *mut c_void;
}

impl Context for *mut context {
    #[inline]
    fn result_null(&self) {
        result_null(*self)
    }

    /// Takes a reference to a string, has SQLite copy the contents
    /// and take ownership of the copy.
    #[inline]
    fn result_text_transient(&self, text: &str) {
        result_text(
            *self,
            text.as_ptr() as *mut c_char,
            text.len() as i32,
            Destructor::TRANSIENT,
        );
    }

    /// Takes a reference to a string that will outlive SQLite's use of the string.
    /// SQLite will not copy this string.
    #[inline]
    fn result_text_static(&self, text: &str) {
        result_text(
            *self,
            text.as_ptr() as *mut c_char,
            text.len() as i32,
            Destructor::STATIC,
        );
    }

    /// SQLite will make a copy of the blob
    #[inline]
    fn result_blob_transient(&self, blob: &[u8]) {
        result_blob(
            *self,
            blob.as_ptr(),
            blob.len() as i32,
            Destructor::TRANSIENT,
        );
    }

    #[inline]
    fn result_blob_static(&self, blob: &[u8]) {
        result_blob(*self, blob.as_ptr(), blob.len() as i32, Destructor::STATIC);
    }

    #[inline]
    fn result_error(&self, text: &str) {
        result_error(*self, text.as_ptr() as *mut c_char, text.len() as c_int);
    }

    #[inline]
    fn result_error_code(&self, code: ResultCode) {
        result_error_code(*self, code as c_int);
    }

    #[inline]
    fn result_value(&self, value: *mut value) {
        result_value(*self, value);
    }

    #[inline]
    fn result_double(&self, value: f64) {
        result_double(*self, value);
    }

    #[inline]
    fn result_int64(&self, value: int64) {
        result_int64(*self, value);
    }

    #[inline]
    fn result_int(&self, value: i32) {
        result_int(*self, value);
    }

    #[inline]
    fn result_subtype(&self, subtype: u32) {
        result_subtype(*self, subtype);
    }

    #[inline]
    fn db_handle(&self) -> *mut sqlite3 {
        context_db_handle(*self)
    }

    #[inline]
    fn user_data(&self) -> *mut c_void {
        user_data(*self)
    }
}

pub trait Stmt {
    fn sql(&self) -> &str;
    fn bind_blob(&self, i: i32, val: &[u8], d: Destructor) -> Result<ResultCode, ResultCode>;
    fn bind_value(&self, i: i32, val: *mut value) -> Result<ResultCode, ResultCode>;
    fn bind_text(&self, i: i32, text: &str, d: Destructor) -> Result<ResultCode, ResultCode>;
    fn bind_int64(&self, i: i32, val: int64) -> Result<ResultCode, ResultCode>;
    fn bind_int(&self, i: i32, val: i32) -> Result<ResultCode, ResultCode>;
    fn bind_double(&self, i: i32, val: f64) -> Result<ResultCode, ResultCode>;
    fn bind_null(&self, i: i32) -> Result<ResultCode, ResultCode>;

    fn clear_bindings(&self) -> Result<ResultCode, ResultCode>;

    fn column_value(&self, i: i32) -> *mut value;
    fn column_int64(&self, i: i32) -> int64;
    fn column_int(&self, i: i32) -> i32;
    fn column_blob(&self, i: i32) -> &[u8];
    fn column_double(&self, i: i32) -> f64;
    fn column_text(&self, i: i32) -> &str;
    fn column_bytes(&self, i: i32) -> i32;

    fn finalize(&self) -> Result<ResultCode, ResultCode>;

    fn reset(&self) -> Result<ResultCode, ResultCode>;
    fn step(&self) -> Result<ResultCode, ResultCode>;
}

impl Stmt for *mut stmt {
    fn sql(&self) -> &str {
        unsafe { core::str::from_utf8_unchecked(core::ffi::CStr::from_ptr(sql(*self)).to_bytes()) }
    }

    #[inline]
    fn bind_blob(&self, i: i32, val: &[u8], d: Destructor) -> Result<ResultCode, ResultCode> {
        convert_rc(bind_blob(
            *self,
            i,
            val.as_ptr() as *const c_void,
            val.len() as i32,
            d,
        ))
    }

    #[inline]
    fn bind_double(&self, i: i32, val: f64) -> Result<ResultCode, ResultCode> {
        convert_rc(bind_double(*self, i, val))
    }

    #[inline]
    fn bind_value(&self, i: i32, val: *mut value) -> Result<ResultCode, ResultCode> {
        convert_rc(bind_value(*self, i, val))
    }

    #[inline]
    fn bind_text(&self, i: i32, text: &str, d: Destructor) -> Result<ResultCode, ResultCode> {
        convert_rc(bind_text(
            *self,
            i,
            text.as_ptr() as *const c_char,
            text.len() as i32,
            d,
        ))
    }

    #[inline]
    fn bind_int64(&self, i: i32, val: int64) -> Result<ResultCode, ResultCode> {
        convert_rc(bind_int64(*self, i, val))
    }

    #[inline]
    fn bind_int(&self, i: i32, val: i32) -> Result<ResultCode, ResultCode> {
        convert_rc(bind_int(*self, i, val))
    }

    #[inline]
    fn bind_null(&self, i: i32) -> Result<ResultCode, ResultCode> {
        convert_rc(bind_null(*self, i))
    }

    #[inline]
    fn clear_bindings(&self) -> Result<ResultCode, ResultCode> {
        convert_rc(clear_bindings(*self))
    }

    #[inline]
    fn column_value(&self, i: i32) -> *mut value {
        column_value(*self, i)
    }

    #[inline]
    fn column_int64(&self, i: i32) -> int64 {
        column_int64(*self, i)
    }

    #[inline]
    fn column_int(&self, i: i32) -> i32 {
        column_int(*self, i)
    }

    #[inline]
    fn column_blob(&self, i: i32) -> &[u8] {
        let len = column_bytes(*self, i);
        let ptr = column_blob(*self, i);
        unsafe { core::slice::from_raw_parts(ptr as *const u8, len as usize) }
    }

    #[inline]
    fn column_double(&self, i: i32) -> f64 {
        column_double(*self, i)
    }

    #[inline]
    fn column_text(&self, i: i32) -> &str {
        column_text(*self, i)
    }

    #[inline]
    fn column_bytes(&self, i: i32) -> i32 {
        column_bytes(*self, i)
    }

    #[inline]
    fn reset(&self) -> Result<ResultCode, ResultCode> {
        convert_rc(reset(*self))
    }

    #[inline]
    fn step(&self) -> Result<ResultCode, ResultCode> {
        match ResultCode::from_i32(step(*self)) {
            Some(ResultCode::ROW) => Ok(ResultCode::ROW),
            Some(ResultCode::DONE) => Ok(ResultCode::DONE),
            Some(rc) => Err(rc),
            None => Err(ResultCode::ERROR),
        }
    }

    #[inline]
    fn finalize(&self) -> Result<ResultCode, ResultCode> {
        match ResultCode::from_i32(finalize(*self)) {
            Some(ResultCode::OK) => Ok(ResultCode::OK),
            Some(rc) => Err(rc),
            None => Err(ResultCode::ABORT),
        }
    }
}

pub trait Value {
    fn blob(&self) -> &[u8];
    fn double(&self) -> f64;
    fn int(&self) -> i32;
    fn int64(&self) -> int64;
    fn text(&self) -> &str;
    fn bytes(&self) -> i32;
    fn value_type(&self) -> ColumnType;
}

impl Value for *mut value {
    #[inline]
    fn value_type(&self) -> ColumnType {
        ColumnType::from_i32(value_type(*self)).unwrap()
    }

    #[inline]
    fn blob(&self) -> &[u8] {
        value_blob(*self)
    }

    #[inline]
    fn double(&self) -> f64 {
        value_double(*self)
    }

    #[inline]
    fn int(&self) -> i32 {
        value_int(*self)
    }

    #[inline]
    fn int64(&self) -> int64 {
        value_int64(*self)
    }

    #[inline]
    fn text(&self) -> &str {
        value_text(*self)
    }

    #[inline]
    fn bytes(&self) -> i32 {
        value_bytes(*self)
    }
}

pub trait StrRef {
    fn set(&self, val: &str);
}

impl StrRef for *mut *mut c_char {
    /**
     * Sets the error message, copying the contents of `val`.
     * If the error has already been set, future calls to `set` are ignored.
     */
    fn set(&self, val: &str) {
        unsafe {
            if **self != null_mut() {
                return;
            }
            if let Ok(cstring) = CString::new(val) {
                **self = cstring.into_raw();
            } else {
                if let Ok(s) = CString::new("Failed setting error message.") {
                    **self = s.into_raw();
                }
            }
        }
    }
}

// TODO: on `T` can I enforce that T has a pointer of name `base` as first item to `vtab`?
pub trait VTabRef {
    fn set<T>(&self, val: Box<T>);
}

impl VTabRef for *mut *mut vtab {
    fn set<T>(&self, val: Box<T>) {
        unsafe {
            let raw_val = Box::into_raw(val);
            **self = raw_val.cast::<sqlite3_capi::vtab>();
        }
    }
}

pub trait CursorRef {
    fn set<T>(&self, val: Box<T>);
}

impl CursorRef for *mut *mut vtab_cursor {
    fn set<T>(&self, val: Box<T>) {
        unsafe {
            let raw_val = Box::into_raw(val);
            **self = raw_val.cast::<sqlite3_capi::vtab_cursor>();
        }
    }
}

pub trait VTab {
    fn set_err(&self, val: &str);
}

impl VTab for *mut vtab {
    /**
     * Sets the error message, copying the contents of `val`.
     * If the error has already been set, future calls to `set` are ignored.
     */
    fn set_err(&self, val: &str) {
        unsafe {
            if (**self).zErrMsg != null_mut() {
                return;
            }
            if let Ok(e) = CString::new(val) {
                (**self).zErrMsg = e.into_raw();
            }
        }
    }
}

// from: https://github.com/asg017/sqlite-loadable-rs/blob/main/src/table.rs#L722
pub struct VTabArgs<'a> {
    /// Name of the module being invoked, the argument in the USING clause.
    /// Example: `"CREATE VIRTUAL TABLE xxx USING custom_vtab"` would have
    /// a `module_name` of `"custom_vtab"`.
    /// Sourced from `argv[0]`
    pub module_name: &'a str,
    /// Name of the database where the virtual table will be created,
    /// typically `"main"` or `"temp"` or another name from an
    /// [`ATTACH`'ed database](https://www.sqlite.org/lang_attach.html).
    /// Sourced from `argv[1]`
    pub database_name: &'a str,

    /// Name of the table being created.
    /// Example: `"CREATE VIRTUAL TABLE xxx USING custom_vtab"` would
    /// have a `table_name` of `"xxx"`.
    /// Sourced from `argv[2]`
    pub table_name: &'a str,
    /// The remaining arguments given in the constructor of the virtual
    /// table, inside `CREATE VIRTUAL TABLE xxx USING custom_vtab(...)`.
    /// Sourced from `argv[3:]`
    pub arguments: Vec<&'a str>,
}

/// Generally do not use this. Does a bunch of copying.
fn c_string_to_str<'a>(c: *const c_char) -> Result<&'a str, Utf8Error> {
    let s = unsafe { CStr::from_ptr(c).to_str()? };
    Ok(s)
}

pub fn parse_vtab_args<'a>(
    argc: c_int,
    argv: *const *const c_char,
) -> Result<VTabArgs<'a>, Utf8Error> {
    let raw_args = unsafe { slice::from_raw_parts(argv, argc as usize) };
    let mut args = Vec::with_capacity(argc as usize);
    for arg in raw_args {
        args.push(c_string_to_str(*arg)?);
    }

    // SQLite guarantees that argv[0-2] will be filled, hence the .expects() -
    // If SQLite is wrong, then may god save our souls
    let module_name = args
        .get(0)
        .expect("argv[0] should be the name of the module");
    let database_name = args
        .get(1)
        .expect("argv[1] should be the name of the database the module is in");
    let table_name = args
        .get(2)
        .expect("argv[2] should be the name of the virtual table");
    let arguments = &args[3..];

    Ok(VTabArgs {
        module_name,
        database_name,
        table_name,
        arguments: arguments.to_vec(),
    })
}

pub fn declare_vtab(db: *mut sqlite3, def: &str) -> Result<ResultCode, ResultCode> {
    let cstring = CString::new(def)?;
    let ret = sqlite3_capi::declare_vtab(db, cstring.as_ptr());
    convert_rc(ret)
}

pub fn vtab_config(db: *mut sqlite3, options: u32) -> Result<ResultCode, ResultCode> {
    let rc = sqlite3_capi::vtab_config(db, options);
    convert_rc(rc)
}

// type xCreateC = extern "C" fn(
//     *mut sqlite3,
//     *mut c_void,
//     c_int,
//     *const *const c_char,
//     *mut *mut vtab,
//     *mut *mut c_char,
// ) -> c_int;

// // return a lambda that invokes f appropriately?
// pub const fn xCreate(
//     f: fn(
//         db: *mut sqlite3,
//         aux: *mut c_void,
//         args: Vec<&str>,
//         tab: *mut *mut vtab,   // declare tab for them?
//         err: *mut *mut c_char, // box?
//     ) -> Result<ResultCode, ResultCode>,
// ) -> xCreateC {
//     move |db, aux, argc, argv, ppvtab, errmsg| match f(db, aux, str_args, ppvtab, errmsg) {
//         Ok(rc) => rc as c_int,
//         Err(rc) => rc as c_int,
//     }
// }

// *mut sqlite3, *mut c_void, Vec<&str>, *mut *mut vtab, *mut *mut c_char