sqll 0.12.6

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
use core::ffi::CStr;
#[cfg(feature = "alloc")]
use core::ffi::c_void;
use core::ffi::{c_int, c_uint};
use core::fmt;
use core::mem::MaybeUninit;
use core::ops::{BitOr, Deref, DerefMut};
use core::ptr::{NonNull, null_mut};

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

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, Prepare, 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<str>) -> Result<()> {
        self._execute(stmt.as_ref())
    }

    fn _execute(&self, stmt: &str) -> 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.
    ///
    /// This is the same as calling `prepare_with` with `Prepare::EMPTY`.
    ///
    /// 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, Prepare};
    ///
    /// 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<str>) -> Result<Statement> {
        self.prepare_with(stmt, 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, Prepare};
    ///
    /// let c = Connection::open_in_memory()?;
    ///
    /// let e = c.prepare_with("CREATE TABLE test (id INTEGER); INSERT INTO test (id) VALUES (1);", Prepare::PERSISTENT).unwrap_err();
    /// assert_eq!(e.code(), Code::MISUSE);
    /// # Ok::<_, sqll::Error>(())
    /// ```
    ///
    /// [`execute`]: Self::execute
    ///
    /// # Examples
    ///
    /// ```
    /// use sqll::{Connection, Prepare};
    ///
    /// 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 (?)", Prepare::PERSISTENT)?;
    /// let mut query_stmt = c.prepare_with("SELECT id FROM test", Prepare::PERSISTENT)?;
    ///
    /// 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(&self, stmt: impl AsRef<str>, flags: Prepare) -> Result<Statement> {
        let stmt = stmt.as_ref();

        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(())
    }
}

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)
    }
}