sqll 0.13.2

Efficient interface to SQLite that doesn't get in your way
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
use core::ffi::CStr;
#[cfg(feature = "alloc")]
use core::ffi::c_void;
use core::ffi::{c_int, c_uint};
use core::fmt;
#[cfg(feature = "alloc")]
use core::mem::ManuallyDrop;
use core::mem::MaybeUninit;
use core::ops::{BitOr, Deref, DerefMut};
use core::ptr::{NonNull, null_mut};
use core::slice;

#[cfg(feature = "std")]
use std::path::Path;

#[cfg(feature = "alloc")]
use crate::OwnedBytes;
use crate::ffi;
#[cfg(feature = "alloc")]
use crate::owned::Owned;
use crate::utils::{c_to_error_text, sqlite3_try};
use crate::{Code, DatabaseNotFound, Error, NotThreadSafe, OpenOptions, Result, Statement, Text};

/// A collection of flags use to prepare a statement.
pub struct Prepare(c_uint);

impl Prepare {
    /// No flags.
    ///
    /// This provides the default behavior when preparing a statement.
    pub const EMPTY: Self = Self(0);

    /// The PERSISTENT flag is a hint to the query planner that the prepared
    /// statement will be retained for a long time and probably reused many
    /// times. Without this flag, [`Connection::prepare`] assume that the
    /// prepared statement will be used just once or at most a few times and
    /// then destroyed relatively soon.
    ///
    /// The current implementation acts on this hint by avoiding the use of
    /// lookaside memory so as not to deplete the limited store of lookaside
    /// memory. Future versions of SQLite may act on this hint differently.
    pub const PERSISTENT: Self = Self(ffi::SQLITE_PREPARE_PERSISTENT as c_uint);

    /// The NORMALIZE flag is a no-op. This flag used to be required for any
    /// prepared statement that wanted to use the normalized sql interface.
    /// However, the normalized sql interface is now available to all prepared
    /// statements, regardless of whether or not they use this flag.
    pub const NORMALIZE: Self = Self(ffi::SQLITE_PREPARE_NORMALIZE as c_uint);

    /// The NO_VTAB flag causes the SQL compiler to return an error if the
    /// statement uses any virtual tables.
    pub const NO_VTAB: Self = Self(ffi::SQLITE_PREPARE_NO_VTAB as c_uint);
}

impl BitOr for Prepare {
    type Output = Self;

    fn bitor(self, rhs: Self) -> Self::Output {
        Self(self.0 | rhs.0)
    }
}

/// A SQLite database connection.
///
/// For detailed information on how to safetly use a connection, including
/// complex topics such as *Thread Safety* and asynchronous use, see
/// [`OpenOptions`].
///
/// # Examples
///
/// Opening a connection to a filesystem path:
///
/// ```no_run
/// use sqll::Connection;
///
/// let c = Connection::open("database.db")?;
///
/// c.execute(r#"
///     CREATE TABLE test (id INTEGER);
/// "#)?;
/// # Ok::<_, sqll::Error>(())
/// ```
///
/// Opening an in-memory database:
///
/// ```
/// use sqll::Connection;
///
/// let c = Connection::open_in_memory()?;
///
/// c.execute(r#"
///     CREATE TABLE test (id INTEGER);
/// "#)?;
/// # Ok::<_, sqll::Error>(())
/// ```
pub struct Connection {
    raw: NonNull<ffi::sqlite3>,
    #[cfg(feature = "alloc")]
    busy_callback: Option<Owned>,
    is_thread_safe: bool,
}

/// Connection is `Send`.
#[cfg(feature = "threadsafe")]
unsafe impl Send for Connection {}

impl Connection {
    /// Construct a connection from a raw pointer.
    #[inline]
    pub(crate) fn from_raw(raw: NonNull<ffi::sqlite3>, is_thread_safe: bool) -> Self {
        Self {
            raw,
            #[cfg(feature = "alloc")]
            busy_callback: None,
            is_thread_safe,
        }
    }

    /// Coerce this statement into a [`SendConnection`] which can be sent across
    /// threads.
    ///
    /// # Errors
    ///
    /// This return an error if neither [`full_mutex`] or [`no_mutex`] are set,
    /// or if the sqlite library is not configured to be thread safe.
    ///
    /// ```
    /// use sqll::OpenOptions;
    ///
    /// let mut c = OpenOptions::new()
    ///     .create()
    ///     .read_write()
    ///     .open_in_memory()?;
    ///
    /// let e = unsafe { c.into_send().unwrap_err() };
    /// assert!(matches!(e, sqll::NotThreadSafe { .. }));
    /// # Ok::<_, sqll::Error>(())
    /// ```
    ///
    /// [`full_mutex`]: crate::OpenOptions::full_mutex
    /// [`no_mutex`]: crate::OpenOptions::no_mutex
    ///
    /// # Safety
    ///
    /// This is unsafe because it required that the caller ensures that any
    /// database objects are synchronized. The exact level of synchronization
    /// depends on how the connection was opened:
    /// * If [`full_mutex`] was set and [`no_mutex`] was not set, no external
    ///   synchronization is necessary, but calls to the statement might block
    ///   if it's busy.
    /// * If [`no_mutex`] was set, the caller must ensure that the [`Statement`]
    ///   is fully synchronized with respect to the connection that constructed
    ///   it. One way to achieve this is to wrap all the statements behind a
    ///   single mutex.
    ///
    /// [`full_mutex`]: crate::OpenOptions::full_mutex
    /// [`no_mutex`]: crate::OpenOptions::no_mutex
    ///
    /// # Examples
    ///
    /// The following example showcases how you can share a single connection in
    /// a multi-threaded asynchronous application.
    ///
    /// > In this example, statements are compiled and executed on-the-fly. See
    /// > [`Statement::into_send`] for an example which is more idiomatic and
    /// > uses prepared statement.
    ///
    /// ```
    /// use std::sync::Arc;
    /// use sqll::{OpenOptions, SendConnection};
    /// use anyhow::Result;
    /// use tokio::task;
    /// use tokio::sync::Mutex;
    ///
    /// #[derive(Clone)]
    /// struct Database {
    ///     c: Arc<Mutex<SendConnection>>,
    /// }
    ///
    /// fn setup_database() -> Result<Database> {
    ///     let c = OpenOptions::new()
    ///         .create()
    ///         .read_write()
    ///         .no_mutex()
    ///         .open_in_memory()?;
    ///
    ///     c.execute(
    ///         r#"
    ///         CREATE TABLE users (name TEXT PRIMARY KEY NOT NULL, age INTEGER);
    ///
    ///         INSERT INTO users VALUES ('Alice', 60), ('Bob', 70), ('Charlie', 20);
    ///         "#,
    ///     )?;
    ///
    ///     // SAFETY: We serialize all accesses to the connection behind a mutex.
    ///     let c = unsafe {
    ///         c.into_send()?
    ///     };
    ///
    ///     Ok(Database {
    ///         c: Arc::new(Mutex::new(c)),
    ///     })
    /// }
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<()> {
    ///     let db = setup_database()?;
    ///
    ///     let mut tasks = Vec::new();
    ///
    ///     for _ in 0..10 {
    ///         _ = task::spawn({
    ///             let db = db.clone();
    ///
    ///             async move {
    ///                 let mut c = db.c.lock_owned().await;
    ///
    ///                 let task = task::spawn_blocking(move || {
    ///                     let mut update = c.prepare("UPDATE users SET age = age + ?")?;
    ///                     update.execute(2)
    ///                 });
    ///
    ///                 Ok::<_, anyhow::Error>(task.await??)
    ///             }
    ///         });
    ///
    ///         let t = task::spawn({
    ///             let db = db.clone();
    ///
    ///             async move {
    ///                 let mut c = db.c.lock_owned().await;
    ///
    ///                 let task = task::spawn_blocking(move || -> Result<Option<i64>> {
    ///                     let mut select = c.prepare("SELECT age FROM users ORDER BY age")?;
    ///                     Ok(select.next::<i64>()?)
    ///                 });
    ///
    ///                 task.await?
    ///             }
    ///         });
    ///
    ///         tasks.push(t);
    ///     }
    ///
    ///     for t in tasks {
    ///         let first = t.await??;
    ///         assert!(matches!(first, Some(20..=40)));
    ///     }
    ///
    ///     Ok(())
    /// }
    /// ```
    pub unsafe fn into_send(self) -> Result<SendConnection, NotThreadSafe> {
        if !self.is_thread_safe {
            return Err(NotThreadSafe::connection());
        }

        Ok(SendConnection { inner: self })
    }

    /// Open a database to the given path.
    ///
    /// Note that it is possible to open an in-memory database by passing
    /// `":memory:"` here, this call might require allocating depending on the
    /// platform, so it should be avoided in favor of using [`open_in_memory`]. To avoid
    /// allocating for regular paths, you can use [`open_c_str`], however you
    /// are responsible for ensuring the c-string is a valid path.
    ///
    /// This is the same as calling:
    ///
    /// ```
    /// use sqll::OpenOptions;
    /// # let path = ":memory:";
    ///
    /// let c = OpenOptions::new()
    ///     .extended_result_codes()
    ///     .read_write()
    ///     .create()
    ///     .open(path)?;
    ///
    /// # Ok::<_, sqll::Error>(())
    /// ```
    ///
    /// [`open_in_memory`]: Self::open_in_memory
    /// [`open_c_str`]: Self::open_c_str
    #[cfg(feature = "std")]
    #[cfg_attr(docsrs, cfg(feature = "std"))]
    #[inline]
    pub fn open(path: impl AsRef<Path>) -> Result<Connection> {
        OpenOptions::new()
            .extended_result_codes()
            .read_write()
            .create()
            .open(path)
    }

    /// Open a database connection with a raw c-string.
    ///
    /// This can be used to open in-memory databases by passing `c":memory:"` or
    /// a regular open call with a filesystem path like
    /// `c"/path/to/database.sql"`.
    ///
    /// This is the same as calling:
    ///
    /// ```
    /// use sqll::OpenOptions;
    /// # let name = c":memory:";
    ///
    /// let c = OpenOptions::new()
    ///     .extended_result_codes()
    ///     .read_write()
    ///     .create()
    ///     .open_c_str(name)?;
    ///
    /// # Ok::<_, sqll::Error>(())
    /// ```
    #[inline]
    pub fn open_c_str(name: &CStr) -> Result<Connection> {
        OpenOptions::new()
            .extended_result_codes()
            .read_write()
            .create()
            .open_c_str(name)
    }

    /// Open an in-memory database.
    ///
    /// This is the same as calling
    ///
    /// This is the same as calling:
    ///
    /// ```
    /// use sqll::OpenOptions;
    ///
    /// let c = OpenOptions::new()
    ///     .extended_result_codes()
    ///     .read_write()
    ///     .create()
    ///     .open_in_memory()?;
    ///
    /// # Ok::<_, sqll::Error>(())
    /// ```
    #[inline]
    pub fn open_in_memory() -> Result<Connection> {
        OpenOptions::new()
            .extended_result_codes()
            .read_write()
            .create()
            .open_in_memory()
    }

    /// Check if the database connection is read-only.
    ///
    /// # Examples
    ///
    /// ```
    /// use sqll::{Connection, Code, OpenOptions, DatabaseNotFound};
    ///
    /// let c = OpenOptions::new().read_write().open_in_memory()?;
    ///
    /// assert!(!c.database_read_only(c"main")?);
    /// let e = c.database_read_only(c"not a db").unwrap_err();
    /// assert!(matches!(e, DatabaseNotFound { .. }));
    ///
    /// let c = OpenOptions::new().read_only().open_in_memory()?;
    ///
    /// assert!(c.database_read_only(c"main")?);
    /// let e = c.database_read_only(c"not a db").unwrap_err();
    /// assert!(matches!(e, DatabaseNotFound { .. }));
    /// # Ok::<_, Box<dyn std::error::Error>>(())
    /// ```
    pub fn database_read_only(&self, name: &CStr) -> Result<bool, DatabaseNotFound> {
        unsafe {
            match ffi::sqlite3_db_readonly(self.raw.as_ptr(), name.as_ptr()) {
                1 => Ok(true),
                0 => Ok(false),
                _ => Err(DatabaseNotFound),
            }
        }
    }

    /// Execute a batch of statements.
    ///
    /// Unlike [`prepare`], this can be used to execute multiple statements
    /// separated by a semi-colon `;` and is internally optimized for one-off
    /// queries.
    ///
    /// [`prepare`]: Self::prepare
    ///
    /// # Errors
    ///
    /// If any of the statements fail, an error is returned.
    ///
    /// ```
    /// use sqll::{Code, Connection};
    ///
    /// let c = Connection::open_in_memory()?;
    ///
    /// let e = c.execute(":)").unwrap_err();
    /// assert_eq!(e.code(), Code::ERROR);
    /// # Ok::<_, sqll::Error>(())
    /// ```
    ///
    /// # Examples
    ///
    /// ```
    /// use sqll::{Connection, Result};
    ///
    /// let c = Connection::open_in_memory()?;
    ///
    /// c.execute(r#"
    ///     CREATE TABLE users (name TEXT, age INTEGER);
    ///
    ///     INSERT INTO users VALUES ('Alice', 42);
    ///     INSERT INTO users VALUES ('Bob', 72);
    /// "#)?;
    ///
    /// let results = c.prepare("SELECT name, age FROM users")?
    ///     .iter::<(String, u32)>()
    ///     .collect::<Result<Vec<_>>>()?;
    ///
    /// assert_eq!(results, [("Alice".to_string(), 42), ("Bob".to_string(), 72)]);
    /// # Ok::<_, sqll::Error>(())
    /// ```
    #[inline]
    pub fn execute(&self, stmt: impl AsRef<[u8]>) -> Result<()> {
        self.execute_raw(stmt.as_ref())
    }

    fn execute_raw(&self, stmt: &[u8]) -> Result<()> {
        unsafe {
            let mut ptr = stmt.as_ptr().cast();
            let mut len = stmt.len();

            while len > 0 {
                let mut raw = MaybeUninit::uninit();
                let mut rest = MaybeUninit::uninit();

                let l = i32::try_from(len).unwrap_or(i32::MAX);

                sqlite3_try!(
                    self,
                    ffi::sqlite3_prepare_v3(
                        self.raw.as_ptr(),
                        ptr,
                        l,
                        0,
                        raw.as_mut_ptr(),
                        rest.as_mut_ptr(),
                    )
                );

                let rest = rest.assume_init();

                // If statement is null then it's simply empty, so we can safely
                // skip it, otherwise iterate over all rows.
                if let Some(raw) = NonNull::new(raw.assume_init()) {
                    let mut statement = Statement::from_raw(raw, self.is_thread_safe);
                    while statement.step()?.is_row() {}
                }

                // Skip over empty statements.
                let o = rest.offset_from_unsigned(ptr);
                len -= o;
                ptr = rest;
            }

            Ok(())
        }
    }

    /// Enable or disable extended result codes.
    ///
    /// This can also be set during construction with
    /// [`OpenOptions::extended_result_codes`].
    ///
    /// # Examples
    ///
    /// ```
    /// use sqll::{OpenOptions, Code};
    ///
    /// let mut c = OpenOptions::new().create().read_write().open_in_memory()?;
    ///
    /// let e = c.execute("
    ///     CREATE TABLE users (name TEXT);
    ///     CREATE UNIQUE INDEX idx_users_name ON users (name);
    ///
    ///     INSERT INTO users VALUES ('Bob');
    /// ");
    ///
    /// let e = c.execute("INSERT INTO users VALUES ('Bob')").unwrap_err();
    /// assert_eq!(e.code(), Code::CONSTRAINT_UNIQUE);
    /// assert_eq!(c.error_message(), "UNIQUE constraint failed: users.name");
    ///
    /// c.extended_result_codes(false)?;
    /// let e = c.execute("INSERT INTO users VALUES ('Bob')").unwrap_err();
    /// assert_eq!(e.code(), Code::CONSTRAINT);
    /// assert_eq!(c.error_message(), "UNIQUE constraint failed: users.name");
    /// # Ok::<_, sqll::Error>(())
    /// ```
    pub fn extended_result_codes(&mut self, enabled: bool) -> Result<()> {
        unsafe {
            let onoff = i32::from(enabled);
            sqlite3_try!(
                self,
                ffi::sqlite3_extended_result_codes(self.raw.as_ptr(), onoff)
            );
        }

        Ok(())
    }

    /// Get the last error message for this connection.
    ///
    /// When operating in multi-threaded environment, the error message seen
    /// here might not correspond to the query that failed unless some kind of
    /// external synchronization is in use which is the recommended way to use
    /// sqlite.
    ///
    /// This is only meaningful if an error has occured. If no errors have
    /// occured, this returns a non-erronous message like `"not an error"`
    /// (default for sqlite3).
    ///
    /// # Examples
    ///
    /// ```
    /// use sqll::{Connection, Code};
    ///
    /// let c = Connection::open_in_memory()?;
    ///
    /// let e = c.execute("
    ///     CREATE TABLE users (name TEXT);
    ///     CREATE UNIQUE INDEX idx_users_name ON users (name);
    ///
    ///     INSERT INTO users VALUES ('Bob');
    /// ");
    ///
    /// let e = c.execute("INSERT INTO users VALUES ('Bob')").unwrap_err();
    /// assert_eq!(e.code(), Code::CONSTRAINT_UNIQUE);
    /// assert_eq!(c.error_message(), "UNIQUE constraint failed: users.name");
    /// # Ok::<_, sqll::Error>(())
    /// ```
    pub fn error_message(&self) -> &Text {
        unsafe { c_to_error_text(ffi::sqlite3_errmsg(self.raw.as_ptr())) }
    }

    /// Build a prepared statement with default options.
    ///
    /// This is the same as calling `prepare_with` with without setting any
    /// options.
    ///
    /// The database connection will be kept open for the lifetime of this
    /// statement.
    ///
    /// # Errors
    ///
    /// If the prepare call contains multiple statements, it will error. To
    /// execute multiple statements, use [`execute`] instead.
    ///
    /// ```
    /// use sqll::{Connection, Code};
    ///
    /// let c = Connection::open_in_memory()?;
    ///
    /// let e = c.prepare("CREATE TABLE test (id INTEGER) /* test */; INSERT INTO test (id) VALUES (1);").unwrap_err();
    ///
    /// assert_eq!(e.code(), Code::MISUSE);
    /// # Ok::<_, sqll::Error>(())
    /// ```
    ///
    /// [`execute`]: Self::execute
    ///
    /// # Examples
    ///
    /// ```
    /// use sqll::Connection;
    ///
    /// let c = Connection::open_in_memory()?;
    ///
    /// c.execute(r#"
    ///     CREATE TABLE test (id INTEGER);
    /// "#)?;
    ///
    /// let mut insert_stmt = c.prepare("INSERT INTO test (id) VALUES (?);")?;
    /// let mut query_stmt = c.prepare("SELECT id FROM test;")?;
    ///
    /// drop(c);
    ///
    /// insert_stmt.execute(42)?;
    ///
    /// query_stmt.bind(())?;
    /// assert_eq!(query_stmt.iter::<i64>().collect::<Vec<_>>(), [Ok(42)]);
    /// # Ok::<_, sqll::Error>(())
    /// ```
    #[inline]
    pub fn prepare(&self, stmt: impl AsRef<[u8]>) -> Result<Statement> {
        self.prepare_raw(stmt.as_ref(), Prepare::EMPTY)
    }

    /// Build a prepared statement with custom flags.
    ///
    /// For long-running statements it is recommended that they have the
    /// [`Prepare::PERSISTENT`] flag set.
    ///
    /// The database connection will be kept open for the lifetime of this
    /// statement.
    ///
    /// # Errors
    ///
    /// If the prepare call contains multiple statements, it will error. To
    /// execute multiple statements, use [`execute`] instead.
    ///
    /// ```
    /// use sqll::{Connection, Code};
    ///
    /// let c = Connection::open_in_memory()?;
    ///
    /// let e = c.prepare_with("CREATE TABLE test (id INTEGER); INSERT INTO test (id) VALUES (1);")
    ///     .persistent()
    ///     .build()
    ///     .unwrap_err();
    ///
    /// assert_eq!(e.code(), Code::MISUSE);
    /// # Ok::<_, sqll::Error>(())
    /// ```
    ///
    /// [`execute`]: Self::execute
    ///
    /// # Examples
    ///
    /// ```
    /// use sqll::Connection;
    ///
    /// let c = Connection::open_in_memory()?;
    ///
    /// c.execute(r#"
    ///     CREATE TABLE test (id INTEGER);
    /// "#)?;
    ///
    /// let mut insert_stmt = c.prepare_with("INSERT INTO test (id) VALUES (?)")
    ///     .persistent()
    ///     .build()?;
    ///
    /// let mut query_stmt = c.prepare_with("SELECT id FROM test")
    ///     .persistent()
    ///     .build()?;
    ///
    /// drop(c);
    ///
    /// /* .. */
    ///
    /// insert_stmt.bind(42)?;
    /// assert!(insert_stmt.step()?.is_done());
    ///
    /// query_stmt.bind(())?;
    /// assert_eq!(query_stmt.iter::<i64>().collect::<Vec<_>>(), [Ok(42)]);
    /// # Ok::<_, sqll::Error>(())
    /// ```
    pub fn prepare_with<S>(&self, stmt: S) -> PrepareWith<'_, S>
    where
        S: AsRef<[u8]>,
    {
        PrepareWith {
            conn: self,
            stmt,
            flags: Prepare::EMPTY,
        }
    }

    fn prepare_raw(&self, stmt: &[u8], flags: Prepare) -> Result<Statement> {
        unsafe {
            let mut raw = MaybeUninit::uninit();
            let mut rest = MaybeUninit::uninit();

            let ptr = stmt.as_ptr().cast();
            let len = i32::try_from(stmt.len()).unwrap_or(i32::MAX);

            sqlite3_try! {
                self,
                ffi::sqlite3_prepare_v3(
                    self.raw.as_ptr(),
                    ptr,
                    len,
                    flags.0,
                    raw.as_mut_ptr(),
                    rest.as_mut_ptr(),
                )
            };

            let rest = rest.assume_init();

            let o = rest.offset_from_unsigned(ptr);

            if o != stmt.len() {
                return Err(Error::new(
                    Code::MISUSE,
                    "multiple statements in a single prepare are not allowed",
                ));
            }

            let raw = NonNull::new_unchecked(raw.assume_init());
            Ok(Statement::from_raw(raw, self.is_thread_safe))
        }
    }

    /// Return the number of rows inserted, updated, or deleted by the most
    /// recent INSERT, UPDATE, or DELETE statement.
    ///
    /// # Examples
    ///
    /// ```
    /// use sqll::Connection;
    ///
    /// let c = Connection::open_in_memory()?;
    ///
    /// c.execute(r#"
    ///     CREATE TABLE users (name TEXT, age INTEGER);
    ///
    ///     INSERT INTO users VALUES ('Alice', 42);
    ///     INSERT INTO users VALUES ('Bob', 72);
    /// "#)?;
    ///
    /// assert_eq!(c.changes(), 1);
    /// # Ok::<_, sqll::Error>(())
    /// ```
    #[inline]
    pub fn changes(&self) -> usize {
        unsafe { ffi::sqlite3_changes(self.raw.as_ptr()) as usize }
    }

    /// Return the total number of rows inserted, updated, and deleted by all
    /// INSERT, UPDATE, and DELETE statements since the connection was opened.
    ///
    /// # Examples
    ///
    /// ```
    /// use sqll::Connection;
    ///
    /// let c = Connection::open_in_memory()?;
    ///
    /// c.execute(r#"
    ///     CREATE TABLE users (name TEXT, age INTEGER);
    ///
    ///     INSERT INTO users VALUES ('Alice', 42);
    ///     INSERT INTO users VALUES ('Bob', 72);
    /// "#)?;
    ///
    /// assert_eq!(c.total_changes(), 2);
    /// # Ok::<_, sqll::Error>(())
    /// ```
    #[inline]
    pub fn total_changes(&self) -> usize {
        unsafe { ffi::sqlite3_total_changes(self.raw.as_ptr()) as usize }
    }

    /// Return the rowid of the most recent successful INSERT into a rowid table
    /// or virtual table.
    ///
    /// # Examples
    ///
    /// If there is no primary key, the last inserted row id is an internal
    /// identifier for the row:
    ///
    /// ```
    /// use sqll::Connection;
    ///
    /// let c = Connection::open_in_memory()?;
    ///
    /// c.execute(r#"
    ///     CREATE TABLE users (name TEXT);
    ///
    ///     INSERT INTO users VALUES ('Alice');
    ///     INSERT INTO users VALUES ('Bob');
    /// "#)?;
    /// assert_eq!(c.last_insert_rowid(), 2);
    ///
    /// c.execute(r#"
    ///     INSERT INTO users VALUES ('Charlie');
    /// "#)?;
    /// assert_eq!(c.last_insert_rowid(), 3);
    ///
    /// let mut stmt = c.prepare("INSERT INTO users VALUES (?)")?;
    /// stmt.execute("Dave")?;
    ///
    /// assert_eq!(c.last_insert_rowid(), 4);
    /// # Ok::<_, sqll::Error>(())
    /// ```
    ///
    /// If there is a primary key, the last inserted row id corresponds to it:
    ///
    /// ```
    /// use sqll::Connection;
    ///
    /// let c = Connection::open_in_memory()?;
    ///
    /// c.execute(r#"
    ///     CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT);
    ///
    ///     INSERT INTO users (name) VALUES ('Alice');
    ///     INSERT INTO users (name) VALUES ('Bob');
    /// "#)?;
    /// assert_eq!(c.last_insert_rowid(), 2);
    ///
    /// c.execute("INSERT INTO users (name) VALUES ('Charlie')")?;
    /// assert_eq!(c.last_insert_rowid(), 3);
    ///
    /// c.execute("INSERT INTO users (name) VALUES ('Dave')")?;
    /// assert_eq!(c.last_insert_rowid(), 4);
    ///
    /// let mut select = c.prepare("SELECT id FROM users WHERE name = ?")?;
    /// select.bind("Dave")?;
    ///
    /// for id in select.iter::<i64>() {
    ///     assert_eq!(id?, 4);
    /// }
    ///
    /// c.execute("DELETE FROM users WHERE id = 3")?;
    /// assert_eq!(c.last_insert_rowid(), 4);
    ///
    /// c.execute("INSERT INTO users (name) VALUES ('Charlie')")?;
    /// assert_eq!(c.last_insert_rowid(), 5);
    ///
    /// select.bind("Charlie")?;
    ///
    /// while let Some(id) = select.next::<i64>()? {
    ///     assert_eq!(id, 5);
    /// }
    /// # Ok::<_, sqll::Error>(())
    /// ```
    #[inline]
    pub fn last_insert_rowid(&self) -> i64 {
        unsafe { ffi::sqlite3_last_insert_rowid(self.raw.as_ptr()) }
    }

    /// Set a callback for handling busy events.
    ///
    /// The callback is triggered when the database cannot perform an operation
    /// due to processing of some other request. If the callback returns `true`,
    /// the operation will be repeated.
    ///
    /// The busy callback should not take any actions which modify the database
    /// connection that invoked the busy handler. In other words, the busy
    /// handler is not reentrant. Any such actions result in undefined behavior.
    ///
    /// Since this needs to allocate space to store the closure the `alloc`
    /// feature has to be enabled.
    ///
    /// # Examples
    ///
    /// ```
    /// use sqll::Connection;
    ///
    /// let mut c = Connection::open_in_memory()?;
    ///
    /// c.busy_handler(|attempts| {
    ///     println!("busy attempt: {attempts}");
    ///     attempts < 5
    /// })?;
    /// # Ok::<_, sqll::Error>(())
    /// ```
    #[cfg(feature = "alloc")]
    #[cfg_attr(docsrs, cfg(feature = "alloc"))]
    pub fn busy_handler<F>(&mut self, callback: F) -> Result<()>
    where
        F: FnMut(usize) -> bool + Send + 'static,
    {
        extern "C" fn glue<F>(callback: *mut c_void, attempts: c_int) -> c_int
        where
            F: FnMut(usize) -> bool,
        {
            unsafe {
                if (*(callback as *mut F))(attempts as usize) {
                    1
                } else {
                    0
                }
            }
        }

        unsafe {
            let callback = Owned::new(callback)?;

            let result = ffi::sqlite3_busy_handler(
                self.raw.as_ptr(),
                Some(glue::<F>),
                callback.as_ptr().cast(),
            );

            // NB: Old callback will be dropped and freed when we set the new
            // one here.
            self.busy_callback = Some(callback);
            sqlite3_try!(self, result);
        }

        Ok(())
    }

    /// Clear any previously registered busy handler.
    ///
    /// # Examples
    ///
    /// ```
    /// use sqll::Connection;
    ///
    /// let mut c = Connection::open_in_memory()?;
    ///
    /// c.busy_handler(|attempts| {
    ///     println!("busy attempt: {attempts}");
    ///     attempts < 5
    /// })?;
    ///
    /// c.clear_busy_handler()?;
    /// # Ok::<_, sqll::Error>(())
    /// ```
    #[inline]
    pub fn clear_busy_handler(&mut self) -> Result<()> {
        unsafe {
            sqlite3_try! {
                self,
                ffi::sqlite3_busy_handler(
                    self.raw.as_ptr(),
                    None,
                    null_mut()
                )
            };
        }

        #[cfg(feature = "alloc")]
        {
            self.busy_callback = None;
        }

        Ok(())
    }

    /// Set an implicit callback for handling busy events that tries to repeat
    /// rejected operations until a timeout expires.
    ///
    /// # Examples
    ///
    /// ```
    /// use sqll::Connection;
    ///
    /// let mut c = Connection::open_in_memory()?;
    ///
    /// c.busy_timeout(5000)?;
    /// # Ok::<_, sqll::Error>(())
    /// ```
    #[inline]
    pub fn busy_timeout(&mut self, ms: c_int) -> Result<()> {
        unsafe {
            sqlite3_try! {
                self,
                ffi::sqlite3_busy_timeout(
                    self.raw.as_ptr(),
                    ms
                )
            };
        }

        Ok(())
    }

    /// Serialize the database to a byte buffer.
    ///
    /// The returned buffer is allocated by sqlite and will be freed when
    /// dropped.
    ///
    /// The `name` parameter specifies the name of the database to serialize,
    /// which is typically `c"main"` for the main database.
    ///
    /// # Examples
    ///
    /// ```
    /// use sqll::{Connection, Result};
    ///
    /// let c = Connection::open_in_memory()?;
    ///
    /// c.execute(r#"
    ///     CREATE TABLE users (name TEXT, age INTEGER);
    ///     INSERT INTO users VALUES ('Alice', 42);
    ///     INSERT INTO users VALUES ('Bob', 72);
    /// "#)?;
    ///
    /// let data = c.serialize(c"main")?;
    /// assert!(!data.is_empty());
    ///
    /// let c2 = Connection::open_in_memory()?;
    /// c2.deserialize(c"main", data)?;
    ///
    /// let results = c2.prepare("SELECT name, age FROM users")?
    ///     .iter::<(String, u32)>()
    ///     .collect::<Result<Vec<_>>>()?;
    ///
    /// assert_eq!(results, [("Alice".to_string(), 42), ("Bob".to_string(), 72)]);
    /// # Ok::<_, sqll::Error>(())
    /// ```
    #[cfg(feature = "alloc")]
    #[cfg_attr(docsrs, cfg(feature = "alloc"))]
    pub fn serialize(&self, name: &CStr) -> Result<OwnedBytes, Error> {
        unsafe {
            let mut len = MaybeUninit::uninit();

            match ffi::sqlite3_serialize(self.raw.as_ptr(), name.as_ptr(), len.as_mut_ptr(), 0) {
                ptr if ptr.is_null() => {
                    Err(Error::new(Code::NOMEM, "failed to serialize database"))
                }
                ptr => {
                    let ptr = NonNull::new_unchecked(ptr);
                    let len = len.assume_init();

                    let Ok(len) = usize::try_from(len) else {
                        ffi::sqlite3_free(ptr.as_ptr().cast());

                        return Err(Error::new(
                            Code::ERROR,
                            format_args!(
                                "failed to serialize database, returned size {len} is non-sensical"
                            ),
                        ));
                    };

                    Ok(OwnedBytes::from_raw(ptr, len))
                }
            }
        }
    }

    /// Serialize the database to a byte buffer without copying.
    ///
    /// This requires that database storage is contiguous in memory which might
    /// be difficult to satisfy. One way to do so is if the current database is
    /// [`deserialize`] from a previously serialized database (without having
    /// been modified).
    ///
    /// The `name` parameter specifies the name of the database to serialize,
    /// which is typically `c"main"` for the main database.
    ///
    /// [`deserialize`]: Self::deserialize
    ///
    /// # Safety
    ///
    /// The returned buffer is valid until the next call to `serialize` or
    /// `deserialize`, or until the connection is dropped. Modifying the
    /// database in any way might invalidate the returned buffer, so it should
    /// be used with care.
    ///
    /// For a safe variant of this method, see [`serialize`].
    ///
    /// [`serialize`]: Self::serialize
    ///
    /// # Examples
    ///
    /// ```
    /// use sqll::{Connection, Result};
    ///
    /// let c = Connection::open_in_memory()?;
    ///
    /// c.execute(r#"
    ///     CREATE TABLE users (name TEXT, age INTEGER);
    ///     INSERT INTO users VALUES ('Alice', 42);
    ///     INSERT INTO users VALUES ('Bob', 72);
    /// "#)?;
    ///
    /// let data = c.serialize(c"main")?;
    /// assert!(!data.is_empty());
    ///
    /// let c2 = Connection::open_in_memory()?;
    /// c2.deserialize(c"main", data.clone())?;
    ///
    /// let results = c2.prepare("SELECT name, age FROM users")?
    ///     .iter::<(String, u32)>()
    ///     .collect::<Result<Vec<_>>>()?;
    ///
    /// assert_eq!(results, [("Alice".to_string(), 42), ("Bob".to_string(), 72)]);
    ///
    /// let data2 = unsafe { c2.serialize_no_copy(c"main")? };
    /// assert_eq!(data, *data2);
    /// # Ok::<_, sqll::Error>(())
    /// ```
    pub unsafe fn serialize_no_copy(&self, name: &CStr) -> Result<&[u8], Error> {
        unsafe {
            let mut len = MaybeUninit::uninit();

            match ffi::sqlite3_serialize(
                self.raw.as_ptr(),
                name.as_ptr(),
                len.as_mut_ptr(),
                ffi::SQLITE_SERIALIZE_NOCOPY as u32,
            ) {
                ptr if ptr.is_null() => Err(Error::new(
                    Code::MISUSE,
                    "database is not contiguous and cannot be serialized without copying",
                )),
                ptr => {
                    let len = len.assume_init();

                    let Ok(len) = usize::try_from(len) else {
                        return Err(Error::new(
                            Code::ERROR,
                            format_args!(
                                "failed to serialize database, returned size {len} is non-sensical"
                            ),
                        ));
                    };

                    Ok(slice::from_raw_parts(ptr.cast(), len))
                }
            }
        }
    }

    /// Deserialize and take ownership of the specified byte buffer into the
    /// database.
    ///
    /// The `name` parameter specifies the name of the database to deserialize
    /// into, which is typically `c"main"` for the main database.
    ///
    /// The `data` parameter is the byte buffer containing the serialized
    /// database, which should be obtained from a previous call to `serialize`
    /// or read from a file.
    ///
    /// # Examples
    ///
    /// ```
    /// use sqll::{Connection, Result};
    ///
    /// let c = Connection::open_in_memory()?;
    ///
    /// c.execute(r#"
    ///     CREATE TABLE users (name TEXT, age INTEGER);
    ///     INSERT INTO users VALUES ('Alice', 42);
    ///     INSERT INTO users VALUES ('Bob', 72);
    /// "#)?;
    ///
    /// let data = c.serialize(c"main")?;
    /// assert!(!data.is_empty());
    ///
    /// let c2 = Connection::open_in_memory()?;
    /// c2.deserialize(c"main", data)?;
    ///
    /// let results = c2.prepare("SELECT name, age FROM users")?
    ///     .iter::<(String, u32)>()
    ///     .collect::<Result<Vec<_>>>()?;
    ///
    /// assert_eq!(results, [("Alice".to_string(), 42), ("Bob".to_string(), 72)]);
    /// # Ok::<_, sqll::Error>(())
    /// ```
    #[cfg(feature = "alloc")]
    #[cfg_attr(docsrs, cfg(feature = "alloc"))]
    pub fn deserialize(&self, name: &CStr, data: OwnedBytes) -> Result<()> {
        let data = ManuallyDrop::new(data);

        let Ok(len) = i64::try_from(data.len()) else {
            return Err(Error::new(
                Code::MISUSE,
                "length of owned buffer is too large",
            ));
        };

        let Ok(capacity) = i64::try_from(data.capacity()) else {
            return Err(Error::new(
                Code::MISUSE,
                "capacity of owned buffer is too large",
            ));
        };

        unsafe {
            sqlite3_try! {
                self,
                ffi::sqlite3_deserialize(
                    self.raw.as_ptr(),
                    name.as_ptr(),
                    data.as_ptr().cast_mut(),
                    len,
                    capacity,
                    (ffi::SQLITE_DESERIALIZE_FREEONCLOSE | ffi::SQLITE_DESERIALIZE_RESIZEABLE) as u32,
                )
            };
        }

        Ok(())
    }
}

impl fmt::Debug for Connection {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Connection")
            .field("is_thread_safe", &self.is_thread_safe)
            .finish_non_exhaustive()
    }
}

impl Drop for Connection {
    #[inline]
    #[allow(unused_must_use)]
    fn drop(&mut self) {
        self.clear_busy_handler();

        // Will close the connection unconditionally. The database will stay
        // alive until all associated prepared statements have been closed since
        // we're using v2.
        let code = unsafe { ffi::sqlite3_close_v2(self.raw.as_ptr()) };
        debug_assert_eq!(code, ffi::SQLITE_OK);
    }
}

/// A [`Connection`] that can be sent between threads.
///
/// Constructed using [`Connection::into_send`].
pub struct SendConnection {
    inner: Connection,
}

unsafe impl Send for SendConnection {}

impl Deref for SendConnection {
    type Target = Connection;

    #[inline]
    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

impl DerefMut for SendConnection {
    #[inline]
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.inner
    }
}

impl fmt::Debug for SendConnection {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.inner.fmt(f)
    }
}

/// A builder for customizing a prepared [`Statement`].
///
/// See [`Connection::prepare_with`] for more details.
pub struct PrepareWith<'a, S>
where
    S: AsRef<[u8]>,
{
    conn: &'a Connection,
    stmt: S,
    flags: Prepare,
}

impl<S> PrepareWith<'_, S>
where
    S: AsRef<[u8]>,
{
    /// Set custom flags for the prepared statement.
    ///
    /// When setting [`Prepare::PERSISTENT`] it is recommended to use
    /// [`PrepareWith::persistent`] instead for improved readability.
    ///
    /// # Examples
    ///
    /// ```
    /// use sqll::{Connection, Prepare};
    ///
    /// let c = Connection::open_in_memory()?;
    ///
    /// c.execute(r#"
    ///     CREATE TABLE test (id INTEGER);
    /// "#)?;
    ///
    /// let mut stmt = c.prepare_with("SELECT id FROM test")
    ///     .with_flags(Prepare::PERSISTENT | Prepare::NO_VTAB)
    ///     .build()?;
    ///
    /// stmt.bind(())?;
    /// assert_eq!(stmt.iter::<i64>().collect::<Vec<_>>(), []);
    /// # Ok::<_, sqll::Error>(())
    /// ```
    #[inline]
    pub fn with_flags(mut self, flags: Prepare) -> Self {
        self.flags = flags;
        self
    }

    /// Set the [`Prepare::PERSISTENT`] flag for the built prepared
    /// [`Statement`].
    ///
    /// # Examples
    ///
    /// ```
    /// use sqll::Connection;
    ///
    /// let c = Connection::open_in_memory()?;
    ///
    /// c.execute(r#"
    ///     CREATE TABLE test (id INTEGER);
    /// "#)?;
    ///
    /// let mut insert_stmt = c.prepare_with("INSERT INTO test (id) VALUES (?)")
    ///     .persistent()
    ///     .build()?;
    ///
    /// let mut query_stmt = c.prepare_with("SELECT id FROM test")
    ///     .persistent()
    ///     .build()?;
    ///
    /// drop(c);
    ///
    /// /* .. */
    ///
    /// insert_stmt.bind(42)?;
    /// assert!(insert_stmt.step()?.is_done());
    ///
    /// query_stmt.bind(())?;
    /// assert_eq!(query_stmt.iter::<i64>().collect::<Vec<_>>(), [Ok(42)]);
    /// # Ok::<_, sqll::Error>(())
    /// ```
    #[inline]
    pub fn persistent(self) -> Self {
        self.with_flags(Prepare::PERSISTENT)
    }

    /// Build the prepared statement.
    #[inline]
    pub fn build(self) -> Result<Statement> {
        self.conn.prepare_raw(self.stmt.as_ref(), self.flags)
    }
}