Skip to main content

rusqlite/
lib.rs

1//! Rusqlite is an ergonomic wrapper for using SQLite from Rust.
2//!
3//! Historically, the API was based on the one from
4//! [`rust-postgres`](https://github.com/sfackler/rust-postgres). However, the
5//! two have diverged in many ways, and no compatibility between the two is
6//! intended.
7//!
8//! ```rust
9//! use rusqlite::{params, Connection, Result};
10//!
11//! #[derive(Debug)]
12//! struct Person {
13//!     id: i32,
14//!     name: String,
15//!     data: Option<Vec<u8>>,
16//! }
17//!
18//! fn main() -> Result<()> {
19//!     let conn = Connection::open_in_memory()?;
20//!
21//!     conn.execute(
22//!         "CREATE TABLE person (
23//!             id   INTEGER PRIMARY KEY,
24//!             name TEXT NOT NULL,
25//!             data BLOB
26//!         )",
27//!         (), // empty list of parameters.
28//!     )?;
29//!     let me = Person {
30//!         id: 0,
31//!         name: "Steven".to_string(),
32//!         data: None,
33//!     };
34//!     conn.execute(
35//!         "INSERT INTO person (name, data) VALUES (?1, ?2)",
36//!         (&me.name, &me.data),
37//!     )?;
38//!
39//!     let mut stmt = conn.prepare("SELECT id, name, data FROM person")?;
40//!     let person_iter = stmt.query_map([], |row| {
41//!         Ok(Person {
42//!             id: row.get(0)?,
43//!             name: row.get(1)?,
44//!             data: row.get(2)?,
45//!         })
46//!     })?;
47//!
48//!     for person in person_iter {
49//!         println!("Found person {:?}", person?);
50//!     }
51//!     Ok(())
52//! }
53//! ```
54#![warn(missing_docs)]
55#![cfg_attr(docsrs, feature(doc_cfg))]
56
57pub use fallible_iterator;
58pub use fallible_streaming_iterator;
59
60#[cfg(not(all(
61    target_family = "wasm",
62    target_os = "unknown",
63    any(test, feature = "ffi-sqlite-wasm-rs")
64)))]
65pub use libdoltlite_sys as ffi;
66#[cfg(all(
67    target_family = "wasm",
68    target_os = "unknown",
69    any(test, feature = "ffi-sqlite-wasm-rs")
70))]
71pub use sqlite_wasm_rs as ffi;
72
73use std::cell::RefCell;
74use std::default::Default;
75use std::ffi::{c_char, c_int, c_uint, CStr, CString};
76use std::fmt;
77
78use std::path::Path;
79use std::result;
80use std::str;
81use std::sync::{Arc, Mutex};
82
83#[cfg(feature = "cache")]
84use crate::cache::StatementCache;
85use crate::inner_connection::InnerConnection;
86use crate::raw_statement::RawStatement;
87use crate::types::ValueRef;
88
89pub use crate::bind::BindIndex;
90#[cfg(feature = "cache")]
91pub use crate::cache::CachedStatement;
92#[cfg(feature = "column_decltype")]
93pub use crate::column::Column;
94#[cfg(feature = "column_metadata")]
95pub use crate::column::ColumnMetadata;
96pub use crate::error::{to_sqlite_error, Error};
97pub use crate::ffi::ErrorCode;
98#[cfg(feature = "load_extension")]
99pub use crate::load_extension_guard::LoadExtensionGuard;
100pub use crate::params::{params_from_iter, Params, ParamsFromIter};
101#[cfg(all(feature = "remote", not(target_arch = "wasm32")))]
102pub use crate::remote_server::{RemoteAuthenticator, RemoteServer, RemoteServerOptions};
103pub use crate::row::{AndThenRows, Map, MappedRows, Row, RowIndex, Rows};
104pub use crate::statement::{Statement, StatementStatus};
105#[cfg(feature = "modern_sqlite")]
106pub use crate::transaction::TransactionState;
107pub use crate::transaction::{DropBehavior, Savepoint, Transaction, TransactionBehavior};
108pub use crate::types::ToSql;
109pub use crate::util::Name;
110pub use crate::version::*;
111#[cfg(feature = "rusqlite-macros")]
112#[doc(hidden)]
113pub use rusqlite_macros::__bind;
114
115#[macro_use]
116mod error;
117
118#[cfg(not(feature = "loadable_extension"))]
119pub mod auto_extension;
120#[cfg(feature = "backup")]
121pub mod backup;
122mod bind;
123#[cfg(feature = "blob")]
124pub mod blob;
125mod busy;
126#[cfg(feature = "cache")]
127mod cache;
128#[cfg(feature = "collation")]
129mod collation;
130mod column;
131pub mod config;
132#[cfg(any(feature = "functions", feature = "vtab"))]
133mod context;
134#[cfg(feature = "functions")]
135pub mod functions;
136#[cfg(feature = "hooks")]
137pub mod hooks;
138mod inner_connection;
139#[cfg(feature = "limits")]
140pub mod limits;
141#[cfg(feature = "load_extension")]
142mod load_extension_guard;
143mod params;
144mod pragma;
145mod raw_statement;
146#[cfg(all(feature = "remote", not(target_arch = "wasm32")))]
147pub mod remote_server;
148mod row;
149#[cfg(feature = "serialize")]
150pub mod serialize;
151#[cfg(feature = "session")]
152pub mod session;
153mod statement;
154#[cfg(feature = "trace")]
155pub mod trace;
156mod transaction;
157pub mod types;
158#[cfg(feature = "unlock_notify")]
159mod unlock_notify;
160mod version;
161#[cfg(feature = "vtab")]
162pub mod vtab;
163
164pub(crate) mod util;
165
166// Actually, only sqlite3_enable_load_extension is disabled (not sqlite3_load_extension)
167#[cfg(all(feature = "loadable_extension", feature = "load_extension"))]
168compile_error!("feature \"loadable_extension\" and feature \"load_extension\" cannot be enabled at the same time");
169
170// Number of cached prepared statements we'll hold on to.
171#[cfg(feature = "cache")]
172const STATEMENT_CACHE_DEFAULT_CAPACITY: usize = 16;
173
174/// A macro making it more convenient to pass longer lists of
175/// parameters as a `&[&dyn ToSql]`.
176///
177/// # Example
178///
179/// ```rust,no_run
180/// # use rusqlite::{Result, Connection, params};
181///
182/// struct Person {
183///     name: String,
184///     age_in_years: u8,
185///     data: Option<Vec<u8>>,
186/// }
187///
188/// fn add_person(conn: &Connection, person: &Person) -> Result<()> {
189///     conn.execute(
190///         "INSERT INTO person(name, age_in_years, data) VALUES (?1, ?2, ?3)",
191///         params![person.name, person.age_in_years, person.data],
192///     )?;
193///     Ok(())
194/// }
195/// ```
196#[macro_export]
197macro_rules! params {
198    () => {
199        &[] as &[&dyn $crate::ToSql]
200    };
201    ($($param:expr),+ $(,)?) => {
202        &[$(&$param as &dyn $crate::ToSql),+] as &[&dyn $crate::ToSql]
203    };
204}
205
206/// A macro making it more convenient to pass lists of named parameters
207/// as a `&[(&str, &dyn ToSql)]`.
208///
209/// # Example
210///
211/// ```rust,no_run
212/// # use rusqlite::{Result, Connection, named_params};
213///
214/// struct Person {
215///     name: String,
216///     age_in_years: u8,
217///     data: Option<Vec<u8>>,
218/// }
219///
220/// fn add_person(conn: &Connection, person: &Person) -> Result<()> {
221///     conn.execute(
222///         "INSERT INTO person (name, age_in_years, data)
223///          VALUES (:name, :age, :data)",
224///         named_params! {
225///             ":name": person.name,
226///             ":age": person.age_in_years,
227///             ":data": person.data,
228///         },
229///     )?;
230///     Ok(())
231/// }
232/// ```
233#[macro_export]
234macro_rules! named_params {
235    () => {
236        &[] as &[(&str, &dyn $crate::ToSql)]
237    };
238    // Note: It's a lot more work to support this as part of the same macro as
239    // `params!`, unfortunately.
240    ($($param_name:literal: $param_val:expr),+ $(,)?) => {
241        &[$(($param_name, &$param_val as &dyn $crate::ToSql)),+] as &[(&str, &dyn $crate::ToSql)]
242    };
243}
244
245/// Captured identifiers in SQL
246///
247/// * only SQLite `$x` / `@x` / `:x` syntax works (Rust `&x` syntax does not
248///   work).
249/// * `$x.y` expression does not work.
250///
251/// # Example
252///
253/// ```rust, no_run
254/// # use rusqlite::{prepare_and_bind, Connection, Result, Statement};
255///
256/// fn misc(db: &Connection) -> Result<Statement> {
257///     let name = "Lisa";
258///     let age = 8;
259///     let smart = true;
260///     Ok(prepare_and_bind!(db, "SELECT $name, @age, :smart;"))
261/// }
262/// ```
263#[cfg(feature = "rusqlite-macros")]
264#[macro_export]
265macro_rules! prepare_and_bind {
266    ($conn:expr, $sql:literal) => {{
267        let mut stmt = $conn.prepare($sql)?;
268        $crate::__bind!(stmt $sql);
269        stmt
270    }};
271}
272
273/// Captured identifiers in SQL
274///
275/// * only SQLite `$x` / `@x` / `:x` syntax works (Rust `&x` syntax does not
276///   work).
277/// * `$x.y` expression does not work.
278#[cfg(feature = "rusqlite-macros")]
279#[macro_export]
280macro_rules! prepare_cached_and_bind {
281    ($conn:expr, $sql:literal) => {{
282        let mut stmt = $conn.prepare_cached($sql)?;
283        $crate::__bind!(stmt $sql);
284        stmt
285    }};
286}
287
288/// A typedef of the result returned by many methods.
289pub type Result<T, E = Error> = result::Result<T, E>;
290
291/// See the [method documentation](#tymethod.optional).
292pub trait OptionalExtension<T> {
293    /// Converts a `Result<T>` into a `Result<Option<T>>`.
294    ///
295    /// By default, Rusqlite treats 0 rows being returned from a query that is
296    /// expected to return 1 row as an error. This method will
297    /// handle that error, and give you back an `Option<T>` instead.
298    fn optional(self) -> Result<Option<T>>;
299}
300
301impl<T> OptionalExtension<T> for Result<T> {
302    fn optional(self) -> Result<Option<T>> {
303        match self {
304            Ok(value) => Ok(Some(value)),
305            Err(Error::QueryReturnedNoRows) => Ok(None),
306            Err(e) => Err(e),
307        }
308    }
309}
310
311unsafe fn errmsg_to_string(errmsg: *const c_char) -> String {
312    CStr::from_ptr(errmsg).to_string_lossy().into_owned()
313}
314
315#[cfg(any(feature = "functions", feature = "vtab", test))]
316fn str_to_cstring(s: &str) -> Result<util::SmallCString> {
317    Ok(util::SmallCString::new(s)?)
318}
319
320/// Returns `(string ptr, len as c_int, SQLITE_STATIC | SQLITE_TRANSIENT)`
321/// normally.
322/// The `sqlite3_destructor_type` item is always `SQLITE_TRANSIENT` unless
323/// the string was empty (in which case it's `SQLITE_STATIC`, and the ptr is
324/// static).
325fn str_for_sqlite(
326    s: &[u8],
327) -> (
328    *const c_char,
329    ffi::sqlite3_uint64,
330    ffi::sqlite3_destructor_type,
331) {
332    let len = s.len();
333    let (ptr, dtor_info) = if len != 0 {
334        (s.as_ptr().cast::<c_char>(), ffi::SQLITE_TRANSIENT())
335    } else {
336        // Return a pointer guaranteed to live forever
337        ("".as_ptr().cast::<c_char>(), ffi::SQLITE_STATIC())
338    };
339    (ptr, len as ffi::sqlite3_uint64, dtor_info)
340}
341
342fn path_to_cstring(p: &Path) -> Result<CString> {
343    cfg_select! {
344        unix => {
345            use std::os::unix::ffi::OsStrExt as _;
346            Ok(CString::new(p.as_os_str().as_bytes())?)
347        }
348        _ => {
349            let s = p.to_str().ok_or_else(|| Error::InvalidPath(p.to_owned()))?;
350            Ok(CString::new(s)?)
351        }
352    }
353}
354
355/// Shorthand for `Main` database.
356pub const MAIN_DB: &CStr = c"main";
357/// Shorthand for `Temp` database.
358pub const TEMP_DB: &CStr = c"temp";
359
360/// A connection to a SQLite database.
361pub struct Connection {
362    db: RefCell<InnerConnection>,
363    #[cfg(feature = "cache")]
364    cache: StatementCache,
365    transaction_behavior: TransactionBehavior,
366}
367
368unsafe impl Send for Connection {}
369
370impl Drop for Connection {
371    #[inline]
372    fn drop(&mut self) {
373        #[cfg(feature = "cache")]
374        self.flush_prepared_statement_cache();
375    }
376}
377
378impl Connection {
379    /// Open a new connection to a SQLite database. If a database does not exist
380    /// at the path, one is created.
381    ///
382    /// ```rust,no_run
383    /// # use rusqlite::{Connection, Result};
384    /// fn open_my_db() -> Result<()> {
385    ///     let path = "./my_db.db3";
386    ///     let db = Connection::open(path)?;
387    ///     // Use the database somehow...
388    ///     println!("{}", db.is_autocommit());
389    ///     Ok(())
390    /// }
391    /// ```
392    ///
393    /// # Flags
394    ///
395    /// `Connection::open(path)` is equivalent to using
396    /// [`Connection::open_with_flags`] with the default [`OpenFlags`]. That is,
397    /// it's equivalent to:
398    ///
399    /// ```ignore
400    /// Connection::open_with_flags(
401    ///     path,
402    ///     OpenFlags::SQLITE_OPEN_READ_WRITE
403    ///         | OpenFlags::SQLITE_OPEN_CREATE
404    ///         | OpenFlags::SQLITE_OPEN_URI
405    ///         | OpenFlags::SQLITE_OPEN_NO_MUTEX,
406    /// )
407    /// ```
408    ///
409    /// These flags have the following effects:
410    ///
411    /// - Open the database for both reading or writing.
412    /// - Create the database if one does not exist at the path.
413    /// - Allow the filename to be interpreted as a URI (see <https://www.sqlite.org/uri.html#uri_filenames_in_sqlite>
414    ///   for details).
415    /// - Disables the use of a per-connection mutex.
416    ///
417    ///   Rusqlite enforces thread-safety at compile time, so additional
418    ///   locking is not needed and provides no benefit. (See the
419    ///   documentation on [`OpenFlags::SQLITE_OPEN_FULL_MUTEX`] for some
420    ///   additional discussion about this).
421    ///
422    /// Most of these are also the default settings for the C API, although
423    /// technically the default locking behavior is controlled by the flags used
424    /// when compiling SQLite -- rather than let it vary, we choose `NO_MUTEX`
425    /// because it's a fairly clearly the best choice for users of this library.
426    ///
427    /// # Failure
428    ///
429    /// Will return `Err` if `path` cannot be converted to a C-compatible string
430    /// or if the underlying SQLite open call fails.
431    ///
432    /// # WASM support
433    ///
434    /// If you plan to use this connection type on the `wasm32-unknown-unknown` target please
435    /// make sure to read the following notes:
436    ///
437    /// - The database is stored in memory by default.
438    /// - Persistent VFS (Virtual File Systems) is optional,
439    ///   see <https://github.com/Spxg/sqlite-wasm-rs> for details
440    #[inline]
441    pub fn open<P: AsRef<Path>>(path: P) -> Result<Self> {
442        let flags = OpenFlags::default();
443        Self::open_with_flags(path, flags)
444    }
445
446    /// Open a new connection to an in-memory SQLite database.
447    ///
448    /// # Failure
449    ///
450    /// Will return `Err` if the underlying SQLite open call fails.
451    #[inline]
452    pub fn open_in_memory() -> Result<Self> {
453        let flags = OpenFlags::default();
454        Self::open_in_memory_with_flags(flags)
455    }
456
457    /// Open a new connection to a SQLite database.
458    ///
459    /// [Database Connection](http://www.sqlite.org/c3ref/open.html) for a description of valid
460    /// flag combinations.
461    ///
462    /// # Failure
463    ///
464    /// Will return `Err` if `path` cannot be converted to a C-compatible
465    /// string or if the underlying SQLite open call fails.
466    #[inline]
467    pub fn open_with_flags<P: AsRef<Path>>(path: P, flags: OpenFlags) -> Result<Self> {
468        let c_path = path_to_cstring(path.as_ref())?;
469        InnerConnection::open_with_flags(&c_path, flags, None).map(|db| Self {
470            db: RefCell::new(db),
471            #[cfg(feature = "cache")]
472            cache: StatementCache::with_capacity(STATEMENT_CACHE_DEFAULT_CAPACITY),
473            transaction_behavior: TransactionBehavior::Deferred,
474        })
475    }
476
477    /// Open a new connection to a SQLite database using the specific flags and
478    /// vfs name.
479    ///
480    /// [Database Connection](http://www.sqlite.org/c3ref/open.html) for a description of valid
481    /// flag combinations.
482    ///
483    /// # Failure
484    ///
485    /// Will return `Err` if either `path` or `vfs` cannot be converted to a
486    /// C-compatible string or if the underlying SQLite open call fails.
487    #[inline]
488    pub fn open_with_flags_and_vfs<P: AsRef<Path>, V: Name>(
489        path: P,
490        flags: OpenFlags,
491        vfs: V,
492    ) -> Result<Self> {
493        let c_path = path_to_cstring(path.as_ref())?;
494        let c_vfs = vfs.as_cstr()?;
495        InnerConnection::open_with_flags(&c_path, flags, Some(&c_vfs)).map(|db| Self {
496            db: RefCell::new(db),
497            #[cfg(feature = "cache")]
498            cache: StatementCache::with_capacity(STATEMENT_CACHE_DEFAULT_CAPACITY),
499            transaction_behavior: TransactionBehavior::Deferred,
500        })
501    }
502
503    /// Open a new connection to an in-memory SQLite database.
504    ///
505    /// [Database Connection](http://www.sqlite.org/c3ref/open.html) for a description of valid
506    /// flag combinations.
507    ///
508    /// # Failure
509    ///
510    /// Will return `Err` if the underlying SQLite open call fails.
511    #[inline]
512    pub fn open_in_memory_with_flags(flags: OpenFlags) -> Result<Self> {
513        Self::open_with_flags(":memory:", flags)
514    }
515
516    /// Open a new connection to an in-memory SQLite database using the specific
517    /// flags and vfs name.
518    ///
519    /// [Database Connection](http://www.sqlite.org/c3ref/open.html) for a description of valid
520    /// flag combinations.
521    ///
522    /// # Failure
523    ///
524    /// Will return `Err` if `vfs` cannot be converted to a C-compatible
525    /// string or if the underlying SQLite open call fails.
526    #[inline]
527    pub fn open_in_memory_with_flags_and_vfs<V: Name>(flags: OpenFlags, vfs: V) -> Result<Self> {
528        Self::open_with_flags_and_vfs(":memory:", flags, vfs)
529    }
530
531    /// Convenience method to run multiple SQL statements (that cannot take any
532    /// parameters).
533    ///
534    /// ## Example
535    ///
536    /// ```rust,no_run
537    /// # use rusqlite::{Connection, Result};
538    /// fn create_tables(conn: &Connection) -> Result<()> {
539    ///     conn.execute_batch(
540    ///         "BEGIN;
541    ///          CREATE TABLE foo(x INTEGER);
542    ///          CREATE TABLE bar(y TEXT);
543    ///          COMMIT;",
544    ///     )
545    /// }
546    /// ```
547    ///
548    /// # Failure
549    ///
550    /// Will return `Err` if `sql` cannot be converted to a C-compatible string
551    /// or if the underlying SQLite call fails.
552    pub fn execute_batch(&self, sql: &str) -> Result<()> {
553        let mut sql = sql;
554        while !sql.is_empty() {
555            let (stmt, tail) = self
556                .db
557                .borrow_mut()
558                .prepare(self, sql, PrepFlags::default())?;
559            if !stmt.stmt.is_null() && stmt.step()? {
560                // Some PRAGMA may return rows
561                if false {
562                    return Err(Error::ExecuteReturnedResults);
563                }
564            }
565            if tail == 0 || tail >= sql.len() {
566                break;
567            }
568            sql = &sql[tail..];
569        }
570        Ok(())
571    }
572
573    /// Convenience method to prepare and execute a single SQL statement.
574    ///
575    /// On success, returns the number of rows that were changed or inserted or
576    /// deleted (via `sqlite3_changes`).
577    ///
578    /// ## Example
579    ///
580    /// ### With positional params
581    ///
582    /// ```rust,no_run
583    /// # use rusqlite::{Connection};
584    /// fn update_rows(conn: &Connection) {
585    ///     match conn.execute("UPDATE foo SET bar = 'baz' WHERE qux = ?1", [1i32]) {
586    ///         Ok(updated) => println!("{} rows were updated", updated),
587    ///         Err(err) => println!("update failed: {}", err),
588    ///     }
589    /// }
590    /// ```
591    ///
592    /// ### With positional params of varying types
593    ///
594    /// ```rust,no_run
595    /// # use rusqlite::{params, Connection};
596    /// fn update_rows(conn: &Connection) {
597    ///     match conn.execute(
598    ///         "UPDATE foo SET bar = 'baz' WHERE qux = ?1 AND quux = ?2",
599    ///         params![1i32, 1.5f64],
600    ///     ) {
601    ///         Ok(updated) => println!("{} rows were updated", updated),
602    ///         Err(err) => println!("update failed: {}", err),
603    ///     }
604    /// }
605    /// ```
606    ///
607    /// ### With named params
608    ///
609    /// ```rust,no_run
610    /// # use rusqlite::{Connection, Result};
611    /// fn insert(conn: &Connection) -> Result<usize> {
612    ///     conn.execute(
613    ///         "INSERT INTO test (name) VALUES (:name)",
614    ///         &[(":name", "one")],
615    ///     )
616    /// }
617    /// ```
618    ///
619    /// # Failure
620    ///
621    /// Will return `Err` if `sql` cannot be converted to a C-compatible string
622    /// or if the underlying SQLite call fails.
623    #[inline]
624    pub fn execute<P: Params>(&self, sql: &str, params: P) -> Result<usize> {
625        self.prepare(sql).and_then(|mut stmt| stmt.execute(params))
626    }
627
628    /// Returns the path to the database file, if one exists and is known.
629    ///
630    /// Returns `Some("")` for a temporary or in-memory database.
631    ///
632    /// Note that in some cases [PRAGMA
633    /// database_list](https://sqlite.org/pragma.html#pragma_database_list) is
634    /// likely to be more robust.
635    #[inline]
636    pub fn path(&self) -> Option<&str> {
637        unsafe { inner_connection::db_filename(std::marker::PhantomData, self.handle(), MAIN_DB) }
638    }
639
640    /// Attempts to free as much heap memory as possible from the database
641    /// connection.
642    ///
643    /// This calls [`sqlite3_db_release_memory`](https://www.sqlite.org/c3ref/db_release_memory.html).
644    #[inline]
645    pub fn release_memory(&self) -> Result<()> {
646        self.db.borrow_mut().release_memory()
647    }
648
649    /// Get the SQLite rowid of the most recent successful INSERT.
650    ///
651    /// Uses [sqlite3_last_insert_rowid](https://www.sqlite.org/c3ref/last_insert_rowid.html) under
652    /// the hood.
653    #[inline]
654    pub fn last_insert_rowid(&self) -> i64 {
655        self.db.borrow_mut().last_insert_rowid()
656    }
657
658    /// Convenience method to execute a query that is expected to return a
659    /// single row.
660    ///
661    /// ## Example
662    ///
663    /// ```rust,no_run
664    /// # use rusqlite::{Result, Connection};
665    /// fn preferred_locale(conn: &Connection) -> Result<String> {
666    ///     conn.query_row(
667    ///         "SELECT value FROM preferences WHERE name='locale'",
668    ///         [],
669    ///         |row| row.get(0),
670    ///     )
671    /// }
672    /// ```
673    ///
674    /// If the query returns more than one row, all rows except the first are
675    /// ignored.
676    ///
677    /// Returns `Err(QueryReturnedNoRows)` if no results are returned. If the
678    /// query truly is optional, you can call `.optional()` on the result of
679    /// this to get a `Result<Option<T>>`.
680    ///
681    /// # Failure
682    ///
683    /// Will return `Err` if `sql` cannot be converted to a C-compatible string
684    /// or if the underlying SQLite call fails.
685    #[inline]
686    pub fn query_row<T, P, F>(&self, sql: &str, params: P, f: F) -> Result<T>
687    where
688        P: Params,
689        F: FnOnce(&Row<'_>) -> Result<T>,
690    {
691        let mut stmt = self.prepare(sql)?;
692        stmt.query_row(params, f)
693    }
694
695    /// Convenience method to execute a query that is expected to return exactly
696    /// one row.
697    ///
698    /// Returns `Err(QueryReturnedMoreThanOneRow)` if the query returns more than one row.
699    ///
700    /// Returns `Err(QueryReturnedNoRows)` if no results are returned. If the
701    /// query truly is optional, you can call
702    /// [`.optional()`](crate::OptionalExtension::optional) on the result of
703    /// this to get a `Result<Option<T>>` (requires that the trait
704    /// `rusqlite::OptionalExtension` is imported).
705    ///
706    /// # Failure
707    ///
708    /// Will return `Err` if the underlying SQLite call fails.
709    pub fn query_one<T, P, F>(&self, sql: &str, params: P, f: F) -> Result<T>
710    where
711        P: Params,
712        F: FnOnce(&Row<'_>) -> Result<T>,
713    {
714        let mut stmt = self.prepare(sql)?;
715        stmt.query_one(params, f)
716    }
717
718    // https://sqlite.org/tclsqlite.html#onecolumn
719    #[cfg(test)]
720    pub(crate) fn one_column<T, P>(&self, sql: &str, params: P) -> Result<T>
721    where
722        T: types::FromSql,
723        P: Params,
724    {
725        self.query_one(sql, params, |r| r.get(0))
726    }
727
728    /// Convenience method to execute a query that is expected to return a
729    /// single row, and execute a mapping via `f` on that returned row with
730    /// the possibility of failure. The `Result` type of `f` must implement
731    /// `std::convert::From<Error>`.
732    ///
733    /// ## Example
734    ///
735    /// ```rust,no_run
736    /// # use rusqlite::{Result, Connection};
737    /// fn preferred_locale(conn: &Connection) -> Result<String> {
738    ///     conn.query_row_and_then(
739    ///         "SELECT value FROM preferences WHERE name='locale'",
740    ///         [],
741    ///         |row| row.get(0),
742    ///     )
743    /// }
744    /// ```
745    ///
746    /// If the query returns more than one row, all rows except the first are
747    /// ignored.
748    ///
749    /// # Failure
750    ///
751    /// Will return `Err` if `sql` cannot be converted to a C-compatible string
752    /// or if the underlying SQLite call fails.
753    #[inline]
754    pub fn query_row_and_then<T, E, P, F>(&self, sql: &str, params: P, f: F) -> Result<T, E>
755    where
756        P: Params,
757        F: FnOnce(&Row<'_>) -> Result<T, E>,
758        E: From<Error>,
759    {
760        let mut stmt = self.prepare(sql)?;
761        let mut rows = stmt.query(params)?;
762
763        rows.get_expected_row().map_err(E::from).and_then(f)
764    }
765
766    /// Prepare a SQL statement for execution.
767    ///
768    /// ## Example
769    ///
770    /// ```rust,no_run
771    /// # use rusqlite::{Connection, Result};
772    /// fn insert_new_people(conn: &Connection) -> Result<()> {
773    ///     let mut stmt = conn.prepare("INSERT INTO People (name) VALUES (?1)")?;
774    ///     stmt.execute(["Joe Smith"])?;
775    ///     stmt.execute(["Bob Jones"])?;
776    ///     Ok(())
777    /// }
778    /// ```
779    ///
780    /// # Failure
781    ///
782    /// Will return `Err` if `sql` cannot be converted to a C-compatible string
783    /// or if the underlying SQLite call fails.
784    #[inline]
785    pub fn prepare(&self, sql: &str) -> Result<Statement<'_>> {
786        self.prepare_with_flags(sql, PrepFlags::default())
787    }
788
789    /// Prepare a SQL statement for execution.
790    ///
791    /// # Failure
792    ///
793    /// Will return `Err` if `sql` cannot be converted to a C-compatible string
794    /// or if the underlying SQLite call fails.
795    #[inline]
796    pub fn prepare_with_flags(&self, sql: &str, flags: PrepFlags) -> Result<Statement<'_>> {
797        let (stmt, tail) = self.db.borrow_mut().prepare(self, sql, flags)?;
798        if tail != 0 && !self.prepare(&sql[tail..])?.stmt.is_null() {
799            Err(Error::MultipleStatement)
800        } else {
801            Ok(stmt)
802        }
803    }
804
805    /// Close the SQLite connection.
806    ///
807    /// This is functionally equivalent to the `Drop` implementation for
808    /// `Connection` except that on failure, it returns an error and the
809    /// connection itself (presumably so closing can be attempted again).
810    ///
811    /// # Failure
812    ///
813    /// Will return `Err` if the underlying SQLite call fails.
814    #[expect(clippy::result_large_err)]
815    #[inline]
816    pub fn close(self) -> Result<(), (Self, Error)> {
817        #[cfg(feature = "cache")]
818        self.flush_prepared_statement_cache();
819        let r = self.db.borrow_mut().close();
820        r.map_err(move |err| (self, err))
821    }
822
823    /// Enable loading of SQLite extensions from both SQL queries and Rust.
824    ///
825    /// You must call [`Connection::load_extension_disable`] when you're
826    /// finished loading extensions (failure to call it can lead to bad things,
827    /// see "Safety"), so you should strongly consider using
828    /// [`LoadExtensionGuard`] instead of this function, automatically disables
829    /// extension loading when it goes out of scope.
830    ///
831    /// # Example
832    ///
833    /// ```rust,no_run
834    /// # use rusqlite::{Connection, Result};
835    /// fn load_my_extension(conn: &Connection) -> Result<()> {
836    ///     // Safety: We fully trust the loaded extension and execute no untrusted SQL
837    ///     // while extension loading is enabled.
838    ///     unsafe {
839    ///         conn.load_extension_enable()?;
840    ///         let r = conn.load_extension("my/trusted/extension", None::<&str>);
841    ///         conn.load_extension_disable()?;
842    ///         r
843    ///     }
844    /// }
845    /// ```
846    ///
847    /// # Failure
848    ///
849    /// Will return `Err` if the underlying SQLite call fails.
850    ///
851    /// # Safety
852    ///
853    /// TLDR: Don't execute any untrusted queries between this call and
854    /// [`Connection::load_extension_disable`].
855    ///
856    /// Perhaps surprisingly, this function does not only allow the use of
857    /// [`Connection::load_extension`] from Rust, but it also allows SQL queries
858    /// to perform [the same operation][loadext]. For example, in the period
859    /// between `load_extension_enable` and `load_extension_disable`, the
860    /// following operation will load and call some function in some dynamic
861    /// library:
862    ///
863    /// ```sql
864    /// SELECT load_extension('why_is_this_possible.dll', 'dubious_func');
865    /// ```
866    ///
867    /// This means that while this is enabled a carefully crafted SQL query can
868    /// be used to escalate a SQL injection attack into code execution.
869    ///
870    /// Safely using this function requires that you trust all SQL queries run
871    /// between when it is called, and when loading is disabled (by
872    /// [`Connection::load_extension_disable`]).
873    ///
874    /// [loadext]: https://www.sqlite.org/lang_corefunc.html#load_extension
875    #[cfg(feature = "load_extension")]
876    #[inline]
877    pub unsafe fn load_extension_enable(&self) -> Result<()> {
878        self.db.borrow_mut().enable_load_extension(1)
879    }
880
881    /// Disable loading of SQLite extensions.
882    ///
883    /// See [`Connection::load_extension_enable`] for an example.
884    ///
885    /// # Failure
886    ///
887    /// Will return `Err` if the underlying SQLite call fails.
888    #[cfg(feature = "load_extension")]
889    #[inline]
890    pub fn load_extension_disable(&self) -> Result<()> {
891        // It's always safe to turn off extension loading.
892        unsafe { self.db.borrow_mut().enable_load_extension(0) }
893    }
894
895    /// Load the SQLite extension at `dylib_path`. `dylib_path` is passed
896    /// through to `sqlite3_load_extension`, which may attempt OS-specific
897    /// modifications if the file cannot be loaded directly (for example
898    /// converting `"some/ext"` to `"some/ext.so"`, `"some\\ext.dll"`, ...).
899    ///
900    /// If `entry_point` is `None`, SQLite will attempt to find the entry point.
901    /// If it is not `None`, the entry point will be passed through to
902    /// `sqlite3_load_extension`.
903    ///
904    /// ## Example
905    ///
906    /// ```rust,no_run
907    /// # use rusqlite::{Connection, Result, LoadExtensionGuard};
908    /// fn load_my_extension(conn: &Connection) -> Result<()> {
909    ///     // Safety: we don't execute any SQL statements while
910    ///     // extension loading is enabled.
911    ///     let _guard = unsafe { LoadExtensionGuard::new(conn)? };
912    ///     // Safety: `my_sqlite_extension` is highly trustworthy.
913    ///     unsafe { conn.load_extension("my_sqlite_extension", None::<&str>) }
914    /// }
915    /// ```
916    ///
917    /// # Failure
918    ///
919    /// Will return `Err` if the underlying SQLite call fails.
920    ///
921    /// # Safety
922    ///
923    /// This is equivalent to performing a `dlopen`/`LoadLibrary` on a shared
924    /// library, and calling a function inside, and thus requires that you trust
925    /// the library that you're loading.
926    ///
927    /// That is to say: to safely use this, the code in the extension must be
928    /// sound, trusted, correctly use the SQLite APIs, and not contain any
929    /// memory or thread safety errors.
930    #[cfg(feature = "load_extension")]
931    #[inline]
932    pub unsafe fn load_extension<P: AsRef<Path>, N: Name>(
933        &self,
934        dylib_path: P,
935        entry_point: Option<N>,
936    ) -> Result<()> {
937        self.db
938            .borrow_mut()
939            .load_extension(dylib_path.as_ref(), entry_point)
940    }
941
942    /// Get access to the underlying SQLite database connection handle.
943    ///
944    /// # Warning
945    ///
946    /// You should not need to use this function. If you do need to, please
947    /// [open an issue on the rusqlite repository](https://github.com/rusqlite/rusqlite/issues) and describe
948    /// your use case.
949    ///
950    /// # Safety
951    ///
952    /// This function is unsafe because it gives you raw access
953    /// to the SQLite connection, and what you do with it could impact the
954    /// safety of this `Connection`.
955    #[inline]
956    pub unsafe fn handle(&self) -> *mut ffi::sqlite3 {
957        self.db.borrow().db()
958    }
959
960    /// Create a `Connection` from a raw handle.
961    ///
962    /// The underlying SQLite database connection handle will not be closed when
963    /// the returned connection is dropped/closed.
964    ///
965    /// # Safety
966    ///
967    /// This function is unsafe because improper use may impact the Connection.
968    #[inline]
969    pub unsafe fn from_handle(db: *mut ffi::sqlite3) -> Result<Self> {
970        let db = InnerConnection::new(db, false);
971        Ok(Self {
972            db: RefCell::new(db),
973            #[cfg(feature = "cache")]
974            cache: StatementCache::with_capacity(STATEMENT_CACHE_DEFAULT_CAPACITY),
975            transaction_behavior: TransactionBehavior::Deferred,
976        })
977    }
978
979    /// Helper to register an SQLite extension written in Rust.
980    /// For [persistent](https://sqlite.org/loadext.html#persistent_loadable_extensions) extension,
981    /// `init` should return `Ok(true)`.
982    /// # Safety
983    /// * Results are undefined if `init` does not just register features.
984    #[cfg(feature = "loadable_extension")]
985    pub unsafe fn extension_init2(
986        db: *mut ffi::sqlite3,
987        pz_err_msg: *mut *mut c_char,
988        p_api: *mut ffi::sqlite3_api_routines,
989        init: fn(Self) -> Result<bool>,
990    ) -> c_int {
991        if p_api.is_null() {
992            return ffi::SQLITE_ERROR;
993        }
994        match ffi::rusqlite_extension_init2(p_api)
995            .map_err(Error::from)
996            .and(Self::from_handle(db))
997            .and_then(init)
998        {
999            Err(err) => to_sqlite_error(&err, pz_err_msg),
1000            Ok(true) => ffi::SQLITE_OK_LOAD_PERMANENTLY,
1001            _ => ffi::SQLITE_OK,
1002        }
1003    }
1004
1005    /// Create a `Connection` from a raw owned handle.
1006    ///
1007    /// The returned connection will attempt to close the inner connection
1008    /// when dropped/closed. This function should only be called on connections
1009    /// owned by the caller.
1010    ///
1011    /// # Safety
1012    ///
1013    /// This function is unsafe because improper use may impact the Connection.
1014    /// In particular, it should only be called on connections created
1015    /// and owned by the caller, e.g. as a result of calling
1016    /// `ffi::sqlite3_open`().
1017    #[inline]
1018    pub unsafe fn from_handle_owned(db: *mut ffi::sqlite3) -> Result<Self> {
1019        let db = InnerConnection::new(db, true);
1020        Ok(Self {
1021            db: RefCell::new(db),
1022            #[cfg(feature = "cache")]
1023            cache: StatementCache::with_capacity(STATEMENT_CACHE_DEFAULT_CAPACITY),
1024            transaction_behavior: TransactionBehavior::Deferred,
1025        })
1026    }
1027
1028    /// Get access to a handle that can be used to interrupt long-running
1029    /// queries from another thread.
1030    #[inline]
1031    pub fn get_interrupt_handle(&self) -> InterruptHandle {
1032        self.db.borrow().get_interrupt_handle()
1033    }
1034
1035    #[inline]
1036    fn decode_result(&self, code: c_int) -> Result<()> {
1037        self.db.borrow().decode_result(code)
1038    }
1039
1040    /// Return the number of rows modified, inserted or deleted by the most
1041    /// recently completed INSERT, UPDATE or DELETE statement on the database
1042    /// connection.
1043    ///
1044    /// See <https://www.sqlite.org/c3ref/changes.html>
1045    #[inline]
1046    pub fn changes(&self) -> u64 {
1047        self.db.borrow().changes()
1048    }
1049
1050    /// Return the total number of rows modified, inserted or deleted by all
1051    /// completed INSERT, UPDATE or DELETE statements since the database
1052    /// connection was opened, including those executed as part of trigger programs.
1053    ///
1054    /// See <https://www.sqlite.org/c3ref/total_changes.html>
1055    #[inline]
1056    pub fn total_changes(&self) -> u64 {
1057        self.db.borrow().total_changes()
1058    }
1059
1060    /// Test for auto-commit mode.
1061    /// Autocommit mode is on by default.
1062    #[inline]
1063    pub fn is_autocommit(&self) -> bool {
1064        self.db.borrow().is_autocommit()
1065    }
1066
1067    /// Determine if all associated prepared statements have been reset.
1068    #[inline]
1069    pub fn is_busy(&self) -> bool {
1070        self.db.borrow().is_busy()
1071    }
1072
1073    /// Flush caches to disk mid-transaction
1074    pub fn cache_flush(&self) -> Result<()> {
1075        self.db.borrow_mut().cache_flush()
1076    }
1077
1078    /// Determine if a database is read-only
1079    pub fn is_readonly<N: Name>(&self, db_name: N) -> Result<bool> {
1080        self.db.borrow().db_readonly(db_name)
1081    }
1082
1083    /// Return the schema name for a database connection
1084    ///
1085    /// ## Failure
1086    ///
1087    /// Return an `Error::InvalidDatabaseIndex` if `index` is out of range.
1088    #[cfg(feature = "modern_sqlite")] // 3.39.0
1089    pub fn db_name(&self, index: usize) -> Result<String> {
1090        unsafe {
1091            let db = self.handle();
1092            let name = ffi::sqlite3_db_name(db, index as c_int);
1093            if name.is_null() {
1094                Err(Error::InvalidDatabaseIndex(index))
1095            } else {
1096                Ok(CStr::from_ptr(name).to_str()?.to_owned())
1097            }
1098        }
1099    }
1100
1101    /// Determine whether an interrupt is currently in effect
1102    #[cfg(feature = "modern_sqlite")] // 3.41.0
1103    pub fn is_interrupted(&self) -> bool {
1104        self.db.borrow().is_interrupted()
1105    }
1106
1107    /// Set error code and message
1108    #[cfg(feature = "modern_sqlite")] // 3.51.0
1109    pub fn set_errmsg(&self, code: c_int, msg: Option<&std::ffi::CStr>) -> Result<()> {
1110        unsafe { error::set_errmsg(self.handle(), code, msg) }
1111    }
1112}
1113
1114impl fmt::Debug for Connection {
1115    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1116        f.debug_struct("Connection")
1117            .field("path", &self.path())
1118            .finish()
1119    }
1120}
1121
1122/// Batch fallible iterator
1123///
1124/// # Warning
1125///
1126/// There is no recovery on parsing error, when an invalid statement is found in `sql`, SQLite cannot jump to the next statement.
1127/// So you should break the loop when an error is raised by the `next` method.
1128///
1129/// ```rust
1130/// use fallible_iterator::FallibleIterator;
1131/// use rusqlite::{Batch, Connection, Result};
1132///
1133/// fn main() -> Result<()> {
1134///     let conn = Connection::open_in_memory()?;
1135///     let sql = r"
1136///     CREATE TABLE tbl1 (col);
1137///     CREATE TABLE tbl2 (col);
1138///     ";
1139///     let mut batch = Batch::new(&conn, sql);
1140///     while let Some(mut stmt) = batch.next()? {
1141///         stmt.execute([])?;
1142///     }
1143///     Ok(())
1144/// }
1145/// ```
1146#[derive(Debug)]
1147pub struct Batch<'conn, 'sql> {
1148    conn: &'conn Connection,
1149    sql: &'sql str,
1150    tail: usize,
1151}
1152
1153impl<'conn, 'sql> Batch<'conn, 'sql> {
1154    /// Constructor
1155    pub fn new(conn: &'conn Connection, sql: &'sql str) -> Self {
1156        Batch { conn, sql, tail: 0 }
1157    }
1158}
1159impl<'conn> fallible_iterator::FallibleIterator for Batch<'conn, '_> {
1160    type Item = Statement<'conn>;
1161    type Error = Error;
1162
1163    /// Iterates on each batch statements.
1164    ///
1165    /// Returns `Ok(None)` when batch is completed.
1166    fn next(&mut self) -> Result<Option<Statement<'conn>>> {
1167        while self.tail < self.sql.len() {
1168            let sql = &self.sql[self.tail..];
1169            let (next, tail) =
1170                self.conn
1171                    .db
1172                    .borrow_mut()
1173                    .prepare(self.conn, sql, PrepFlags::default())?;
1174            if tail == 0 {
1175                self.tail = self.sql.len();
1176            } else {
1177                self.tail += tail;
1178            }
1179            if next.stmt.is_null() {
1180                continue;
1181            }
1182            return Ok(Some(next));
1183        }
1184        Ok(None)
1185    }
1186}
1187
1188bitflags::bitflags! {
1189    /// Flags for opening SQLite database connections. See
1190    /// [sqlite3_open_v2](https://www.sqlite.org/c3ref/open.html) for details.
1191    ///
1192    /// The default open flags are `SQLITE_OPEN_READ_WRITE | SQLITE_OPEN_CREATE
1193    /// | SQLITE_OPEN_URI | SQLITE_OPEN_NO_MUTEX`. See [`Connection::open`] for
1194    /// some discussion about these flags.
1195    #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
1196    #[repr(C)]
1197    pub struct OpenFlags: c_int {
1198        /// The database is opened in read-only mode.
1199        /// If the database does not already exist, an error is returned.
1200        const SQLITE_OPEN_READ_ONLY = ffi::SQLITE_OPEN_READONLY;
1201        /// The database is opened for reading and writing if possible,
1202        /// or reading only if the file is write-protected by the operating system.
1203        /// In either case the database must already exist, otherwise an error is returned.
1204        const SQLITE_OPEN_READ_WRITE = ffi::SQLITE_OPEN_READWRITE;
1205        /// The database is created if it does not already exist
1206        const SQLITE_OPEN_CREATE = ffi::SQLITE_OPEN_CREATE;
1207        /// The filename can be interpreted as a URI if this flag is set.
1208        const SQLITE_OPEN_URI = ffi::SQLITE_OPEN_URI;
1209        /// The database will be opened as an in-memory database.
1210        const SQLITE_OPEN_MEMORY = ffi::SQLITE_OPEN_MEMORY;
1211        /// The new database connection will not use a per-connection mutex (the
1212        /// connection will use the "multi-thread" threading mode, in SQLite
1213        /// parlance).
1214        ///
1215        /// This is used by default, as proper `Send`/`Sync` usage (in
1216        /// particular, the fact that [`Connection`] does not implement `Sync`)
1217        /// ensures thread-safety without the need to perform locking around all
1218        /// calls.
1219        const SQLITE_OPEN_NO_MUTEX = ffi::SQLITE_OPEN_NOMUTEX;
1220        /// The new database connection will use a per-connection mutex -- the
1221        /// "serialized" threading mode, in SQLite parlance.
1222        ///
1223        /// # Caveats
1224        ///
1225        /// This flag should probably never be used with `rusqlite`, as we
1226        /// ensure thread-safety statically (we implement [`Send`] and not
1227        /// [`Sync`]).
1228        ///
1229        /// Critically, even if this flag is used, the [`Connection`] is not
1230        /// safe to use across multiple threads simultaneously. To access a
1231        /// database from multiple threads, you should either create multiple
1232        /// connections, one for each thread (if you have very many threads,
1233        /// wrapping the `rusqlite::Connection` in a mutex is also reasonable).
1234        ///
1235        /// This is both because of the additional per-connection state stored
1236        /// by `rusqlite` (for example, the prepared statement cache), and
1237        /// because not all of SQLites functions are fully thread safe, even in
1238        /// serialized/`SQLITE_OPEN_FULLMUTEX` mode.
1239        ///
1240        /// All that said, it's fairly harmless to enable this flag with
1241        /// `rusqlite`, it will just slow things down while providing no
1242        /// benefit.
1243        const SQLITE_OPEN_FULL_MUTEX = ffi::SQLITE_OPEN_FULLMUTEX;
1244        /// The database is opened with shared cache enabled.
1245        ///
1246        /// This is frequently useful for in-memory connections, but note that
1247        /// broadly speaking it's discouraged by SQLite itself, which states
1248        /// "Any use of shared cache is discouraged" in the official
1249        /// [documentation](https://www.sqlite.org/c3ref/enable_shared_cache.html).
1250        const SQLITE_OPEN_SHARED_CACHE = 0x0002_0000;
1251        /// The database is opened shared cache disabled.
1252        const SQLITE_OPEN_PRIVATE_CACHE = 0x0004_0000;
1253        /// The database filename is not allowed to be a symbolic link. (3.31.0)
1254        const SQLITE_OPEN_NOFOLLOW = 0x0100_0000;
1255        /// Extended result codes. (3.37.0)
1256        const SQLITE_OPEN_EXRESCODE = 0x0200_0000;
1257    }
1258}
1259
1260impl Default for OpenFlags {
1261    #[inline]
1262    fn default() -> Self {
1263        // Note: update the `Connection::open` and top-level `OpenFlags` docs if
1264        // you change these.
1265        Self::SQLITE_OPEN_READ_WRITE
1266            | Self::SQLITE_OPEN_CREATE
1267            | Self::SQLITE_OPEN_NO_MUTEX
1268            | Self::SQLITE_OPEN_URI
1269    }
1270}
1271
1272bitflags::bitflags! {
1273    /// Prepare flags. See
1274    /// [sqlite3_prepare_v3](https://sqlite.org/c3ref/c_prepare_dont_log.html) for details.
1275    #[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
1276    #[repr(C)]
1277    pub struct PrepFlags: c_uint {
1278        /// A hint to the query planner that the prepared statement will be retained for a long time and probably reused many times.
1279        const SQLITE_PREPARE_PERSISTENT = 0x01;
1280        /// Causes the SQL compiler to return an error (error code SQLITE_ERROR) if the statement uses any virtual tables.
1281        const SQLITE_PREPARE_NO_VTAB = 0x04;
1282        /// Prevents SQL compiler errors from being sent to the error log.
1283        const SQLITE_PREPARE_DONT_LOG = 0x10;
1284        /// Causes the SQL compiler to enforce security constraints that would otherwise only be enforced when parsing
1285        /// the database schema.
1286        const SQLITE_PREPARE_FROM_DDL = 0x20; // 3.53.0
1287    }
1288}
1289
1290/// Allows interrupting a long-running computation.
1291pub struct InterruptHandle {
1292    db_lock: Arc<Mutex<*mut ffi::sqlite3>>,
1293}
1294
1295unsafe impl Send for InterruptHandle {}
1296unsafe impl Sync for InterruptHandle {}
1297
1298impl InterruptHandle {
1299    /// Interrupt the query currently executing on another thread. This will
1300    /// cause that query to fail with a `SQLITE3_INTERRUPT` error.
1301    pub fn interrupt(&self) {
1302        let db_handle = self.db_lock.lock().unwrap();
1303        if !db_handle.is_null() {
1304            unsafe { ffi::sqlite3_interrupt(*db_handle) }
1305        }
1306    }
1307}
1308
1309// The README example uses `RemoteServer`, which is available only with the
1310// optional `remote` feature.
1311#[cfg(all(doctest, feature = "remote"))]
1312doc_comment::doctest!("../README.md");
1313
1314#[cfg(all(test, not(miri)))]
1315mod test {
1316    #[cfg(all(target_family = "wasm", target_os = "unknown"))]
1317    use wasm_bindgen_test::wasm_bindgen_test as test;
1318
1319    use super::*;
1320    use fallible_iterator::FallibleIterator as _;
1321    use std::error::Error as StdError;
1322    use std::fmt;
1323
1324    // this function is never called, but is still type checked; in
1325    // particular, calls with specific instantiations will require
1326    // that those types are `Send`.
1327    #[allow(dead_code)]
1328    #[expect(unconditional_recursion, clippy::extra_unused_type_parameters)]
1329    fn ensure_send<T: Send>() {
1330        ensure_send::<Connection>();
1331        ensure_send::<InterruptHandle>();
1332    }
1333
1334    #[allow(dead_code)]
1335    #[expect(unconditional_recursion, clippy::extra_unused_type_parameters)]
1336    fn ensure_sync<T: Sync>() {
1337        ensure_sync::<InterruptHandle>();
1338    }
1339
1340    fn checked_memory_handle() -> Connection {
1341        Connection::open_in_memory().unwrap()
1342    }
1343
1344    #[cfg_attr(
1345        any(
1346            target_os = "windows",
1347            all(target_family = "wasm", target_os = "unknown")
1348        ),
1349        ignore = "DoltLite file-backed concurrency is not supported on this platform"
1350    )]
1351    #[test]
1352    fn test_concurrent_transactions_busy_commit() -> Result<()> {
1353        use std::time::Duration;
1354        let tmp = tempfile::tempdir().unwrap();
1355        let path = tmp.path().join("transactions.db3");
1356
1357        Connection::open(&path)?.execute_batch(
1358            "
1359            BEGIN; CREATE TABLE foo(x INTEGER);
1360            INSERT INTO foo VALUES(42); END;",
1361        )?;
1362
1363        let mut db1 = Connection::open_with_flags(&path, OpenFlags::SQLITE_OPEN_READ_WRITE)?;
1364        let mut db2 = Connection::open_with_flags(&path, OpenFlags::SQLITE_OPEN_READ_ONLY)?;
1365
1366        db1.busy_timeout(Duration::from_millis(0))?;
1367        db2.busy_timeout(Duration::from_millis(0))?;
1368
1369        {
1370            let tx1 = db1.transaction()?;
1371            let tx2 = db2.transaction()?;
1372
1373            // SELECT first makes sqlite lock with a shared lock
1374            tx1.query_row("SELECT x FROM foo LIMIT 1", [], |_| Ok(()))?;
1375            tx2.query_row("SELECT x FROM foo LIMIT 1", [], |_| Ok(()))?;
1376
1377            tx1.execute("INSERT INTO foo VALUES(?1)", [1])?;
1378            let _ = tx2.execute("INSERT INTO foo VALUES(?1)", [2]);
1379
1380            let _ = tx1.commit();
1381            let _ = tx2.commit();
1382        }
1383
1384        let _ = db1
1385            .transaction()
1386            .expect("commit should have closed transaction");
1387        let _ = db2
1388            .transaction()
1389            .expect("commit should have closed transaction");
1390        Ok(())
1391    }
1392
1393    #[cfg_attr(
1394        all(target_family = "wasm", target_os = "unknown"),
1395        ignore = "no filesystem on this platform"
1396    )]
1397    #[test]
1398    fn test_persistence() -> Result<()> {
1399        let temp_dir = tempfile::tempdir().unwrap();
1400        let path = temp_dir.path().join("test.db3");
1401
1402        {
1403            let db = Connection::open(&path)?;
1404            let sql = "BEGIN;
1405                   CREATE TABLE foo(x INTEGER);
1406                   INSERT INTO foo VALUES(42);
1407                   END;";
1408            db.execute_batch(sql)?;
1409        }
1410
1411        let path_string = path.to_str().unwrap();
1412        let db = Connection::open(path_string)?;
1413
1414        assert_eq!(42, db.one_column::<i64, _>("SELECT x FROM foo", [])?);
1415        Ok(())
1416    }
1417
1418    #[test]
1419    fn test_open() {
1420        Connection::open_in_memory().unwrap();
1421
1422        let db = checked_memory_handle();
1423        db.close().unwrap();
1424    }
1425
1426    #[cfg_attr(
1427        all(target_family = "wasm", target_os = "unknown"),
1428        ignore = "no filesystem on this platform"
1429    )]
1430    #[test]
1431    fn test_path() -> Result<()> {
1432        let tmp = tempfile::tempdir().unwrap();
1433        let db = Connection::open("")?;
1434        assert_eq!(Some(""), db.path());
1435        let db = Connection::open_in_memory()?;
1436        if cfg!(feature = "bundled") {
1437            assert_eq!(Some(":memory:"), db.path());
1438        } else {
1439            assert_eq!(Some(""), db.path());
1440        }
1441        let db = Connection::open("file:dummy.db?mode=memory&cache=shared")?;
1442        if cfg!(feature = "bundled") {
1443            assert_eq!(Some("/dummy.db"), db.path());
1444        } else {
1445            assert_eq!(Some(""), db.path());
1446        }
1447        let path = tmp.path().join("file.db");
1448        let db = Connection::open(path)?;
1449        assert!(db.path().is_some_and(|p| p.ends_with("file.db")));
1450        Ok(())
1451    }
1452
1453    #[test]
1454    fn test_open_failure() {
1455        let filename = "no_such_file.db";
1456        let result = Connection::open_with_flags(filename, OpenFlags::SQLITE_OPEN_READ_ONLY);
1457        let err = result.unwrap_err();
1458        if let Error::SqliteFailure(e, Some(msg)) = err {
1459            assert_eq!(ErrorCode::CannotOpen, e.code);
1460            assert_eq!(ffi::SQLITE_CANTOPEN, e.extended_code);
1461            assert!(
1462                msg.contains(filename),
1463                "error message '{msg}' does not contain '{filename}'"
1464            );
1465        } else {
1466            panic!("SqliteFailure expected");
1467        }
1468    }
1469
1470    #[cfg(unix)]
1471    #[test]
1472    fn test_invalid_unicode_file_names() -> Result<()> {
1473        use std::ffi::OsStr;
1474        use std::fs::File;
1475        use std::os::unix::ffi::OsStrExt as _;
1476        let temp_dir = tempfile::tempdir().unwrap();
1477
1478        let path = temp_dir.path();
1479        if File::create(path.join(OsStr::from_bytes(&[0xFE]))).is_err() {
1480            // Skip test, filesystem doesn't support invalid Unicode
1481            return Ok(());
1482        }
1483        let db_path = path.join(OsStr::from_bytes(&[0xFF]));
1484        {
1485            let db = Connection::open(&db_path)?;
1486            let sql = "BEGIN;
1487                   CREATE TABLE foo(x INTEGER);
1488                   INSERT INTO foo VALUES(42);
1489                   END;";
1490            db.execute_batch(sql)?;
1491        }
1492
1493        let db = Connection::open(&db_path)?;
1494
1495        assert_eq!(42, db.one_column::<i64, _>("SELECT x FROM foo", [])?);
1496        Ok(())
1497    }
1498
1499    #[test]
1500    fn test_close_retry() -> Result<()> {
1501        let db = Connection::open_in_memory()?;
1502
1503        // force the DB to be busy by preparing a statement; this must be done at the
1504        // FFI level to allow us to call .close() without dropping the prepared
1505        // statement first.
1506        let raw_stmt = {
1507            use super::str_to_cstring;
1508            use std::ffi::c_int;
1509            use std::ptr;
1510
1511            let raw_db = db.db.borrow_mut().db;
1512            let sql = "SELECT 1";
1513            let mut raw_stmt: *mut ffi::sqlite3_stmt = ptr::null_mut();
1514            let cstring = str_to_cstring(sql)?;
1515            let rc = unsafe {
1516                ffi::sqlite3_prepare_v2(
1517                    raw_db,
1518                    cstring.as_ptr(),
1519                    (sql.len() + 1) as c_int,
1520                    &mut raw_stmt,
1521                    ptr::null_mut(),
1522                )
1523            };
1524            assert_eq!(rc, ffi::SQLITE_OK);
1525            raw_stmt
1526        };
1527
1528        // now that we have an open statement, trying (and retrying) to close should
1529        // fail.
1530        let (db, _) = db.close().unwrap_err();
1531        let (db, _) = db.close().unwrap_err();
1532        let (db, _) = db.close().unwrap_err();
1533
1534        // finalize the open statement so a final close will succeed
1535        assert_eq!(ffi::SQLITE_OK, unsafe { ffi::sqlite3_finalize(raw_stmt) });
1536
1537        db.close().unwrap();
1538        Ok(())
1539    }
1540
1541    #[test]
1542    fn test_open_with_flags() {
1543        for bad_flags in &[
1544            OpenFlags::empty(),
1545            OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_READ_WRITE,
1546            OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_CREATE,
1547        ] {
1548            Connection::open_in_memory_with_flags(*bad_flags).unwrap_err();
1549        }
1550    }
1551
1552    #[test]
1553    fn test_execute_batch() -> Result<()> {
1554        let db = Connection::open_in_memory()?;
1555        let sql = "BEGIN;
1556                   CREATE TABLE foo(x INTEGER);
1557                   INSERT INTO foo VALUES(1);
1558                   INSERT INTO foo VALUES(2);
1559                   INSERT INTO foo VALUES(3);
1560                   INSERT INTO foo VALUES(4);
1561                   END;";
1562        db.execute_batch(sql)?;
1563
1564        db.execute_batch("UPDATE foo SET x = 3 WHERE x < 3")?;
1565
1566        db.execute_batch("INVALID SQL").unwrap_err();
1567
1568        db.execute_batch("PRAGMA locking_mode = EXCLUSIVE")?;
1569        Ok(())
1570    }
1571
1572    #[test]
1573    fn test_execute() -> Result<()> {
1574        let db = Connection::open_in_memory()?;
1575        db.execute_batch("CREATE TABLE foo(x INTEGER)")?;
1576
1577        assert_eq!(1, db.execute("INSERT INTO foo(x) VALUES (?1)", [1i32])?);
1578        assert_eq!(1, db.execute("INSERT INTO foo(x) VALUES (?1)", [2i32])?);
1579
1580        assert_eq!(3, db.one_column::<i32, _>("SELECT SUM(x) FROM foo", [])?);
1581        Ok(())
1582    }
1583
1584    #[test]
1585    #[cfg(feature = "extra_check")]
1586    fn test_execute_select_with_no_row() {
1587        let db = checked_memory_handle();
1588        let err = db.execute("SELECT 1 WHERE 1 < ?1", [1i32]).unwrap_err();
1589        assert_eq!(
1590            err,
1591            Error::ExecuteReturnedResults,
1592            "Unexpected error: {err}"
1593        );
1594    }
1595
1596    #[test]
1597    fn test_execute_select_with_row() {
1598        let db = checked_memory_handle();
1599        let err = db.execute("SELECT 1", []).unwrap_err();
1600        assert_eq!(err, Error::ExecuteReturnedResults);
1601    }
1602
1603    #[test]
1604    fn test_execute_multiple() {
1605        let db = checked_memory_handle();
1606        let err = db
1607            .execute(
1608                "CREATE TABLE foo(x INTEGER); CREATE TABLE foo(x INTEGER)",
1609                [],
1610            )
1611            .unwrap_err();
1612        match err {
1613            Error::MultipleStatement => (),
1614            _ => panic!("Unexpected error: {err}"),
1615        }
1616        db.execute("CREATE TABLE t(c); -- bim", [])
1617            .expect("Tail comment should be ignored");
1618    }
1619
1620    #[test]
1621    fn test_prepare_column_names() -> Result<()> {
1622        let db = Connection::open_in_memory()?;
1623        db.execute_batch("CREATE TABLE foo(x INTEGER);")?;
1624
1625        let stmt = db.prepare("SELECT * FROM foo")?;
1626        assert_eq!(stmt.column_count(), 1);
1627        assert_eq!(stmt.column_names(), vec!["x"]);
1628
1629        let stmt = db.prepare("SELECT x AS a, x AS b FROM foo")?;
1630        assert_eq!(stmt.column_count(), 2);
1631        assert_eq!(stmt.column_names(), vec!["a", "b"]);
1632        Ok(())
1633    }
1634
1635    #[test]
1636    fn test_prepare_execute() -> Result<()> {
1637        let db = Connection::open_in_memory()?;
1638        db.execute_batch("CREATE TABLE foo(x INTEGER);")?;
1639
1640        let mut insert_stmt = db.prepare("INSERT INTO foo(x) VALUES(?1)")?;
1641        assert_eq!(insert_stmt.execute([1i32])?, 1);
1642        assert_eq!(insert_stmt.execute([2i32])?, 1);
1643        assert_eq!(insert_stmt.execute([3i32])?, 1);
1644
1645        assert_eq!(insert_stmt.execute(["hello"])?, 1);
1646        assert_eq!(insert_stmt.execute(["goodbye"])?, 1);
1647        assert_eq!(insert_stmt.execute([types::Null])?, 1);
1648
1649        let mut update_stmt = db.prepare("UPDATE foo SET x=?1 WHERE x<?2")?;
1650        assert_eq!(update_stmt.execute([3i32, 3i32])?, 2);
1651        assert_eq!(update_stmt.execute([3i32, 3i32])?, 0);
1652        assert_eq!(update_stmt.execute([8i32, 8i32])?, 3);
1653        Ok(())
1654    }
1655
1656    #[test]
1657    fn test_prepare_query() -> Result<()> {
1658        let db = Connection::open_in_memory()?;
1659        db.execute_batch("CREATE TABLE foo(x INTEGER);")?;
1660
1661        let mut insert_stmt = db.prepare("INSERT INTO foo(x) VALUES(?1)")?;
1662        assert_eq!(insert_stmt.execute([1i32])?, 1);
1663        assert_eq!(insert_stmt.execute([2i32])?, 1);
1664        assert_eq!(insert_stmt.execute([3i32])?, 1);
1665
1666        let mut query = db.prepare("SELECT x FROM foo WHERE x < ?1 ORDER BY x DESC")?;
1667        {
1668            let mut rows = query.query([4i32])?;
1669            let mut v = Vec::<i32>::new();
1670
1671            while let Some(row) = rows.next()? {
1672                v.push(row.get(0)?);
1673            }
1674
1675            assert_eq!(v, [3i32, 2, 1]);
1676        }
1677
1678        {
1679            let mut rows = query.query([3i32])?;
1680            let mut v = Vec::<i32>::new();
1681
1682            while let Some(row) = rows.next()? {
1683                v.push(row.get(0)?);
1684            }
1685
1686            assert_eq!(v, [2i32, 1]);
1687        }
1688        Ok(())
1689    }
1690
1691    #[test]
1692    fn test_query_map() -> Result<()> {
1693        let db = Connection::open_in_memory()?;
1694        let sql = "BEGIN;
1695                   CREATE TABLE foo(x INTEGER, y TEXT);
1696                   INSERT INTO foo VALUES(4, \"hello\");
1697                   INSERT INTO foo VALUES(3, \", \");
1698                   INSERT INTO foo VALUES(2, \"world\");
1699                   INSERT INTO foo VALUES(1, \"!\");
1700                   END;";
1701        db.execute_batch(sql)?;
1702
1703        let mut query = db.prepare("SELECT x, y FROM foo ORDER BY x DESC")?;
1704        let results: Result<Vec<String>> = query.query([])?.map(|row| row.get(1)).collect();
1705
1706        assert_eq!(results?.concat(), "hello, world!");
1707        Ok(())
1708    }
1709
1710    #[test]
1711    fn test_query_row() -> Result<()> {
1712        let db = Connection::open_in_memory()?;
1713        let sql = "BEGIN;
1714                   CREATE TABLE foo(x INTEGER);
1715                   INSERT INTO foo VALUES(1);
1716                   INSERT INTO foo VALUES(2);
1717                   INSERT INTO foo VALUES(3);
1718                   INSERT INTO foo VALUES(4);
1719                   END;";
1720        db.execute_batch(sql)?;
1721
1722        assert_eq!(10, db.one_column::<i64, _>("SELECT SUM(x) FROM foo", [])?);
1723
1724        let result: Result<i64> = db.one_column("SELECT x FROM foo WHERE x > 5", []);
1725        match result.unwrap_err() {
1726            Error::QueryReturnedNoRows => (),
1727            err => panic!("Unexpected error {err}"),
1728        }
1729
1730        db.query_row("NOT A PROPER QUERY; test123", [], |_| Ok(()))
1731            .unwrap_err();
1732
1733        db.query_row("SELECT 1; SELECT 2;", [], |_| Ok(()))
1734            .unwrap_err();
1735
1736        Ok(())
1737    }
1738
1739    #[test]
1740    fn test_optional() -> Result<()> {
1741        let db = Connection::open_in_memory()?;
1742
1743        let result: Result<i64> = db.one_column("SELECT 1 WHERE 0 <> 0", []);
1744        let result = result.optional();
1745        match result? {
1746            None => (),
1747            _ => panic!("Unexpected result"),
1748        }
1749
1750        let result: Result<i64> = db.one_column("SELECT 1 WHERE 0 == 0", []);
1751        let result = result.optional();
1752        match result? {
1753            Some(1) => (),
1754            _ => panic!("Unexpected result"),
1755        }
1756
1757        let bad_query_result: Result<i64> = db.one_column("NOT A PROPER QUERY", []);
1758        let bad_query_result = bad_query_result.optional();
1759        bad_query_result.unwrap_err();
1760        Ok(())
1761    }
1762
1763    #[test]
1764    fn test_pragma_query_row() -> Result<()> {
1765        let db = Connection::open_in_memory()?;
1766        assert_eq!(
1767            "memory",
1768            db.one_column::<String, _>("PRAGMA journal_mode", [])?
1769        );
1770        if cfg!(feature = "bundled") {
1771            return Ok(());
1772        }
1773        let mode = db.one_column::<String, _>("PRAGMA journal_mode=off", [])?;
1774        if cfg!(feature = "bundled") {
1775            assert_eq!(mode, "off");
1776        } else {
1777            // Note: system SQLite on macOS defaults to "off" rather than
1778            // "memory" for the journal mode (which cannot be changed for
1779            // in-memory connections). This seems like it's *probably* legal
1780            // according to the docs below, so we relax this test when not
1781            // bundling:
1782            //
1783            // From https://www.sqlite.org/pragma.html#pragma_journal_mode
1784            // > Note that the journal_mode for an in-memory database is either
1785            // > MEMORY or OFF and can not be changed to a different value. An
1786            // > attempt to change the journal_mode of an in-memory database to
1787            // > any setting other than MEMORY or OFF is ignored.
1788            assert!(mode == "memory" || mode == "off", "Got mode {mode:?}");
1789        }
1790
1791        Ok(())
1792    }
1793
1794    #[test]
1795    fn test_prepare_failures() -> Result<()> {
1796        let db = Connection::open_in_memory()?;
1797        db.execute_batch("CREATE TABLE foo(x INTEGER);")?;
1798
1799        let err = db.prepare("SELECT * FROM does_not_exist").unwrap_err();
1800        assert!(format!("{err}").contains("does_not_exist"));
1801        Ok(())
1802    }
1803
1804    #[test]
1805    fn test_last_insert_rowid() -> Result<()> {
1806        let db = Connection::open_in_memory()?;
1807        db.execute_batch("CREATE TABLE foo(x INTEGER PRIMARY KEY)")?;
1808        db.execute_batch("INSERT INTO foo DEFAULT VALUES")?;
1809
1810        assert_eq!(db.last_insert_rowid(), 1);
1811
1812        let mut stmt = db.prepare("INSERT INTO foo DEFAULT VALUES")?;
1813        for _ in 0i32..9 {
1814            stmt.execute([])?;
1815        }
1816        assert_eq!(db.last_insert_rowid(), 10);
1817        Ok(())
1818    }
1819
1820    #[test]
1821    fn test_total_changes() -> Result<()> {
1822        let db = Connection::open_in_memory()?;
1823        let sql = "CREATE TABLE foo(x INTEGER PRIMARY KEY, value TEXT default '' NOT NULL,
1824                                    desc TEXT default '');
1825                   CREATE VIEW foo_bar AS SELECT x, desc FROM foo WHERE value = 'bar';
1826                   CREATE TRIGGER INSERT_FOOBAR
1827                   INSTEAD OF INSERT
1828                   ON foo_bar
1829                   BEGIN
1830                       INSERT INTO foo VALUES(new.x, 'bar', new.desc);
1831                   END;";
1832        db.execute_batch(sql)?;
1833        let total_changes_before = db.total_changes();
1834        let changes = db
1835            .prepare("INSERT INTO foo_bar VALUES(null, 'baz');")?
1836            .execute([])?;
1837        let total_changes_after = db.total_changes();
1838        assert_eq!(changes, 0);
1839        assert_eq!(total_changes_after - total_changes_before, 1);
1840        Ok(())
1841    }
1842
1843    #[test]
1844    fn test_is_autocommit() -> Result<()> {
1845        let db = Connection::open_in_memory()?;
1846        assert!(
1847            db.is_autocommit(),
1848            "autocommit expected to be active by default"
1849        );
1850        Ok(())
1851    }
1852
1853    #[test]
1854    fn test_is_busy() -> Result<()> {
1855        let db = Connection::open_in_memory()?;
1856        assert!(!db.is_busy());
1857        let mut stmt = db.prepare("PRAGMA schema_version")?;
1858        assert!(!db.is_busy());
1859        {
1860            let mut rows = stmt.query([])?;
1861            assert!(!db.is_busy());
1862            let row = rows.next()?;
1863            assert!(db.is_busy());
1864            assert!(row.is_some());
1865        }
1866        assert!(!db.is_busy());
1867        Ok(())
1868    }
1869
1870    #[test]
1871    fn test_statement_debugging() -> Result<()> {
1872        let db = Connection::open_in_memory()?;
1873        let query = "SELECT 12345";
1874        let stmt = db.prepare(query)?;
1875
1876        assert!(format!("{stmt:?}").contains(query));
1877        Ok(())
1878    }
1879
1880    #[test]
1881    fn test_notnull_constraint_error() -> Result<()> {
1882        let db = Connection::open_in_memory()?;
1883        db.execute_batch("CREATE TABLE foo(x NOT NULL)")?;
1884
1885        let result = db.execute("INSERT INTO foo (x) VALUES (NULL)", []);
1886
1887        match result.unwrap_err() {
1888            Error::SqliteFailure(err, _) => {
1889                assert_eq!(err.code, ErrorCode::ConstraintViolation);
1890                assert_eq!(err.extended_code, ffi::SQLITE_CONSTRAINT_NOTNULL);
1891            }
1892            err => panic!("Unexpected error {err}"),
1893        }
1894        Ok(())
1895    }
1896
1897    #[test]
1898    fn test_version_string() {
1899        let n = version_number();
1900        let major = n / 1_000_000;
1901        let minor = (n % 1_000_000) / 1_000;
1902        let patch = n % 1_000;
1903
1904        assert!(version().contains(&format!("{major}.{minor}.{patch}")));
1905    }
1906
1907    #[test]
1908    #[cfg(feature = "functions")]
1909    fn test_interrupt() -> Result<()> {
1910        let db = Connection::open_in_memory()?;
1911
1912        let interrupt_handle = db.get_interrupt_handle();
1913
1914        db.create_scalar_function(
1915            "interrupt",
1916            0,
1917            functions::FunctionFlags::default(),
1918            move |_| {
1919                interrupt_handle.interrupt();
1920                Ok(0)
1921            },
1922        )?;
1923
1924        let mut stmt =
1925            db.prepare("SELECT interrupt() FROM (SELECT 1 UNION SELECT 2 UNION SELECT 3)")?;
1926
1927        let result: Result<Vec<i32>> = stmt.query([])?.map(|r| r.get(0)).collect();
1928
1929        assert_eq!(
1930            result.unwrap_err().sqlite_error_code(),
1931            Some(ErrorCode::OperationInterrupted)
1932        );
1933        Ok(())
1934    }
1935
1936    #[test]
1937    fn test_interrupt_close() {
1938        let db = checked_memory_handle();
1939        let handle = db.get_interrupt_handle();
1940        handle.interrupt();
1941        db.close().unwrap();
1942        handle.interrupt();
1943
1944        // Look at its internals to see if we cleared it out properly.
1945        let db_guard = handle.db_lock.lock().unwrap();
1946        assert!(db_guard.is_null());
1947        // It would be nice to test that we properly handle close/interrupt
1948        // running at the same time, but it seems impossible to do with any
1949        // degree of reliability.
1950    }
1951
1952    #[test]
1953    fn test_get_raw() -> Result<()> {
1954        let db = Connection::open_in_memory()?;
1955        db.execute_batch("CREATE TABLE foo(i, x);")?;
1956        let vals = ["foobar", "1234", "qwerty"];
1957        let mut insert_stmt = db.prepare("INSERT INTO foo(i, x) VALUES(?1, ?2)")?;
1958        for (i, v) in vals.iter().enumerate() {
1959            let i_to_insert = i as i64;
1960            assert_eq!(insert_stmt.execute(params![i_to_insert, v])?, 1);
1961        }
1962
1963        let mut query = db.prepare("SELECT i, x FROM foo")?;
1964        let mut rows = query.query([])?;
1965
1966        while let Some(row) = rows.next()? {
1967            let i = row.get_ref(0)?.as_i64()?;
1968            let expect = vals[i as usize];
1969            let x = row.get_ref("x")?.as_str()?;
1970            assert_eq!(x, expect);
1971        }
1972
1973        let mut query = db.prepare("SELECT x FROM foo")?;
1974        let rows = query.query_map([], |row| {
1975            let x = row.get_ref(0)?.as_str()?; // check From<FromSqlError> for Error
1976            Ok(x[..].to_owned())
1977        })?;
1978
1979        for (i, row) in rows.enumerate() {
1980            assert_eq!(row?, vals[i]);
1981        }
1982        Ok(())
1983    }
1984
1985    #[test]
1986    fn test_from_handle() -> Result<()> {
1987        let db = Connection::open_in_memory()?;
1988        let handle = unsafe { db.handle() };
1989        {
1990            let db = unsafe { Connection::from_handle(handle) }?;
1991            db.execute_batch("PRAGMA VACUUM")?;
1992        }
1993        db.close().unwrap();
1994        Ok(())
1995    }
1996
1997    #[test]
1998    fn test_from_handle_owned() -> Result<()> {
1999        let mut handle: *mut ffi::sqlite3 = std::ptr::null_mut();
2000        let r = unsafe { ffi::sqlite3_open(c":memory:".as_ptr(), &mut handle) };
2001        assert_eq!(r, ffi::SQLITE_OK);
2002        let db = unsafe { Connection::from_handle_owned(handle) }?;
2003        db.execute_batch("PRAGMA VACUUM")?;
2004        Ok(())
2005    }
2006
2007    mod query_and_then_tests {
2008        #[cfg(all(target_family = "wasm", target_os = "unknown"))]
2009        use wasm_bindgen_test::wasm_bindgen_test as test;
2010
2011        use super::*;
2012
2013        #[derive(Debug)]
2014        enum CustomError {
2015            SomeError,
2016            Sqlite(Error),
2017        }
2018
2019        impl fmt::Display for CustomError {
2020            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
2021                match *self {
2022                    Self::SomeError => write!(f, "my custom error"),
2023                    Self::Sqlite(ref se) => write!(f, "my custom error: {se}"),
2024                }
2025            }
2026        }
2027
2028        impl StdError for CustomError {
2029            fn description(&self) -> &str {
2030                "my custom error"
2031            }
2032
2033            fn cause(&self) -> Option<&dyn StdError> {
2034                match *self {
2035                    Self::SomeError => None,
2036                    Self::Sqlite(ref se) => Some(se),
2037                }
2038            }
2039        }
2040
2041        impl From<Error> for CustomError {
2042            fn from(se: Error) -> Self {
2043                Self::Sqlite(se)
2044            }
2045        }
2046
2047        type CustomResult<T> = Result<T, CustomError>;
2048
2049        #[test]
2050        fn test_query_and_then() -> Result<()> {
2051            let db = Connection::open_in_memory()?;
2052            let sql = "BEGIN;
2053                       CREATE TABLE foo(x INTEGER, y TEXT);
2054                       INSERT INTO foo VALUES(4, \"hello\");
2055                       INSERT INTO foo VALUES(3, \", \");
2056                       INSERT INTO foo VALUES(2, \"world\");
2057                       INSERT INTO foo VALUES(1, \"!\");
2058                       END;";
2059            db.execute_batch(sql)?;
2060
2061            let mut query = db.prepare("SELECT x, y FROM foo ORDER BY x DESC")?;
2062            let results: Result<Vec<String>> =
2063                query.query_and_then([], |row| row.get(1))?.collect();
2064
2065            assert_eq!(results?.concat(), "hello, world!");
2066            Ok(())
2067        }
2068
2069        #[test]
2070        fn test_query_and_then_fails() -> Result<()> {
2071            let db = Connection::open_in_memory()?;
2072            let sql = "BEGIN;
2073                       CREATE TABLE foo(x INTEGER, y TEXT);
2074                       INSERT INTO foo VALUES(4, \"hello\");
2075                       INSERT INTO foo VALUES(3, \", \");
2076                       INSERT INTO foo VALUES(2, \"world\");
2077                       INSERT INTO foo VALUES(1, \"!\");
2078                       END;";
2079            db.execute_batch(sql)?;
2080
2081            let mut query = db.prepare("SELECT x, y FROM foo ORDER BY x DESC")?;
2082            let bad_type: Result<Vec<f64>> = query.query_and_then([], |row| row.get(1))?.collect();
2083
2084            match bad_type.unwrap_err() {
2085                Error::InvalidColumnType(..) => (),
2086                err => panic!("Unexpected error {err}"),
2087            }
2088
2089            let bad_idx: Result<Vec<String>> =
2090                query.query_and_then([], |row| row.get(3))?.collect();
2091
2092            match bad_idx.unwrap_err() {
2093                Error::InvalidColumnIndex(_) => (),
2094                err => panic!("Unexpected error {err}"),
2095            }
2096            Ok(())
2097        }
2098
2099        #[test]
2100        fn test_query_and_then_custom_error() -> CustomResult<()> {
2101            let db = Connection::open_in_memory()?;
2102            let sql = "BEGIN;
2103                       CREATE TABLE foo(x INTEGER, y TEXT);
2104                       INSERT INTO foo VALUES(4, \"hello\");
2105                       INSERT INTO foo VALUES(3, \", \");
2106                       INSERT INTO foo VALUES(2, \"world\");
2107                       INSERT INTO foo VALUES(1, \"!\");
2108                       END;";
2109            db.execute_batch(sql)?;
2110
2111            let mut query = db.prepare("SELECT x, y FROM foo ORDER BY x DESC")?;
2112            let results: CustomResult<Vec<String>> = query
2113                .query_and_then([], |row| row.get(1).map_err(CustomError::Sqlite))?
2114                .collect();
2115
2116            assert_eq!(results?.concat(), "hello, world!");
2117            Ok(())
2118        }
2119
2120        #[test]
2121        fn test_query_and_then_custom_error_fails() -> Result<()> {
2122            let db = Connection::open_in_memory()?;
2123            let sql = "BEGIN;
2124                       CREATE TABLE foo(x INTEGER, y TEXT);
2125                       INSERT INTO foo VALUES(4, \"hello\");
2126                       INSERT INTO foo VALUES(3, \", \");
2127                       INSERT INTO foo VALUES(2, \"world\");
2128                       INSERT INTO foo VALUES(1, \"!\");
2129                       END;";
2130            db.execute_batch(sql)?;
2131
2132            let mut query = db.prepare("SELECT x, y FROM foo ORDER BY x DESC")?;
2133            let bad_type: CustomResult<Vec<f64>> = query
2134                .query_and_then([], |row| row.get(1).map_err(CustomError::Sqlite))?
2135                .collect();
2136
2137            match bad_type.unwrap_err() {
2138                CustomError::Sqlite(Error::InvalidColumnType(..)) => (),
2139                err => panic!("Unexpected error {err}"),
2140            }
2141
2142            let bad_idx: CustomResult<Vec<String>> = query
2143                .query_and_then([], |row| row.get(3).map_err(CustomError::Sqlite))?
2144                .collect();
2145
2146            match bad_idx.unwrap_err() {
2147                CustomError::Sqlite(Error::InvalidColumnIndex(_)) => (),
2148                err => panic!("Unexpected error {err}"),
2149            }
2150
2151            let non_sqlite_err: CustomResult<Vec<String>> = query
2152                .query_and_then([], |_| Err(CustomError::SomeError))?
2153                .collect();
2154
2155            match non_sqlite_err.unwrap_err() {
2156                CustomError::SomeError => (),
2157                err => panic!("Unexpected error {err}"),
2158            }
2159            Ok(())
2160        }
2161
2162        #[test]
2163        fn test_query_row_and_then_custom_error() -> CustomResult<()> {
2164            let db = Connection::open_in_memory()?;
2165            let sql = "BEGIN;
2166                       CREATE TABLE foo(x INTEGER, y TEXT);
2167                       INSERT INTO foo VALUES(4, \"hello\");
2168                       END;";
2169            db.execute_batch(sql)?;
2170
2171            let query = "SELECT x, y FROM foo ORDER BY x DESC";
2172            let results: CustomResult<String> =
2173                db.query_row_and_then(query, [], |row| row.get(1).map_err(CustomError::Sqlite));
2174
2175            assert_eq!(results?, "hello");
2176            Ok(())
2177        }
2178
2179        #[test]
2180        fn test_query_row_and_then_custom_error_fails() -> Result<()> {
2181            let db = Connection::open_in_memory()?;
2182            let sql = "BEGIN;
2183                       CREATE TABLE foo(x INTEGER, y TEXT);
2184                       INSERT INTO foo VALUES(4, \"hello\");
2185                       END;";
2186            db.execute_batch(sql)?;
2187
2188            let query = "SELECT x, y FROM foo ORDER BY x DESC";
2189            let bad_type: CustomResult<f64> =
2190                db.query_row_and_then(query, [], |row| row.get(1).map_err(CustomError::Sqlite));
2191
2192            match bad_type.unwrap_err() {
2193                CustomError::Sqlite(Error::InvalidColumnType(..)) => (),
2194                err => panic!("Unexpected error {err}"),
2195            }
2196
2197            let bad_idx: CustomResult<String> =
2198                db.query_row_and_then(query, [], |row| row.get(3).map_err(CustomError::Sqlite));
2199
2200            match bad_idx.unwrap_err() {
2201                CustomError::Sqlite(Error::InvalidColumnIndex(_)) => (),
2202                err => panic!("Unexpected error {err}"),
2203            }
2204
2205            let non_sqlite_err: CustomResult<String> =
2206                db.query_row_and_then(query, [], |_| Err(CustomError::SomeError));
2207
2208            match non_sqlite_err.unwrap_err() {
2209                CustomError::SomeError => (),
2210                err => panic!("Unexpected error {err}"),
2211            }
2212            Ok(())
2213        }
2214    }
2215
2216    #[test]
2217    fn test_dynamic() -> Result<()> {
2218        let db = Connection::open_in_memory()?;
2219        let sql = "BEGIN;
2220                       CREATE TABLE foo(x INTEGER, y TEXT);
2221                       INSERT INTO foo VALUES(4, \"hello\");
2222                       END;";
2223        db.execute_batch(sql)?;
2224
2225        db.query_row("SELECT * FROM foo", [], |r| {
2226            assert_eq!(2, r.as_ref().column_count());
2227            Ok(())
2228        })
2229    }
2230    #[test]
2231    fn test_dyn_box() -> Result<()> {
2232        let db = Connection::open_in_memory()?;
2233        db.execute_batch("CREATE TABLE foo(x INTEGER);")?;
2234        let b: Box<dyn ToSql> = Box::new(5);
2235        db.execute("INSERT INTO foo VALUES(?1)", [b])?;
2236        db.query_row("SELECT x FROM foo", [], |r| {
2237            assert_eq!(5, r.get_unwrap::<_, i32>(0));
2238            Ok(())
2239        })
2240    }
2241
2242    #[test]
2243    fn test_params() -> Result<()> {
2244        let db = Connection::open_in_memory()?;
2245        db.query_row(
2246            "SELECT
2247            ?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10,
2248            ?11, ?12, ?13, ?14, ?15, ?16, ?17, ?18, ?19, ?20,
2249            ?21, ?22, ?23, ?24, ?25, ?26, ?27, ?28, ?29, ?30,
2250            ?31, ?32, ?33, ?34;",
2251            params![
2252                1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2253                1, 1, 1, 1, 1, 1,
2254            ],
2255            |r| {
2256                assert_eq!(1, r.get_unwrap::<_, i32>(0));
2257                Ok(())
2258            },
2259        )
2260    }
2261
2262    #[test]
2263    fn test_alter_table() -> Result<()> {
2264        let db = Connection::open_in_memory()?;
2265        db.execute_batch("CREATE TABLE x(t);")?;
2266        // `execute_batch` should be used but `execute` should also work
2267        db.execute("ALTER TABLE x RENAME TO y;", [])?;
2268        Ok(())
2269    }
2270
2271    #[test]
2272    fn test_batch() -> Result<()> {
2273        let db = Connection::open_in_memory()?;
2274        let sql = r"
2275             CREATE TABLE tbl1 (col);
2276             CREATE TABLE tbl2 (col);
2277             ";
2278        let mut batch = Batch::new(&db, sql);
2279        while let Some(mut stmt) = batch.next()? {
2280            stmt.execute([])?;
2281        }
2282        Ok(())
2283    }
2284
2285    #[test]
2286    fn test_invalid_batch() -> Result<()> {
2287        let db = Connection::open_in_memory()?;
2288        let sql = r"
2289            PRAGMA test1;
2290            PRAGMA test2=?;
2291            PRAGMA test3;
2292            ";
2293        let mut batch = Batch::new(&db, sql);
2294        assert!(batch.next().is_ok());
2295        assert!(batch.next().is_err());
2296        assert!(batch.next().is_err());
2297        assert!(Batch::new(&db, sql).count().is_err());
2298        Ok(())
2299    }
2300
2301    #[test]
2302    #[cfg(feature = "modern_sqlite")]
2303    fn test_returning() -> Result<()> {
2304        let db = Connection::open_in_memory()?;
2305        db.execute_batch("CREATE TABLE foo(x INTEGER PRIMARY KEY)")?;
2306        let row_id =
2307            db.one_column::<i64, _>("INSERT INTO foo DEFAULT VALUES RETURNING ROWID", [])?;
2308        assert_eq!(row_id, 1);
2309        Ok(())
2310    }
2311
2312    #[test]
2313    fn test_cache_flush() -> Result<()> {
2314        let db = Connection::open_in_memory()?;
2315        db.cache_flush()
2316    }
2317
2318    #[test]
2319    fn db_readonly() -> Result<()> {
2320        let db = Connection::open_in_memory()?;
2321        assert!(!db.is_readonly(MAIN_DB)?);
2322        Ok(())
2323    }
2324
2325    #[test]
2326    #[cfg(feature = "rusqlite-macros")]
2327    fn prepare_and_bind() -> Result<()> {
2328        let db = Connection::open_in_memory()?;
2329        let name = "Lisa";
2330        let age = 8;
2331        let mut stmt = prepare_and_bind!(db, "SELECT $name, $age;");
2332        let (v1, v2) = stmt
2333            .raw_query()
2334            .next()
2335            .and_then(|o| o.ok_or(Error::QueryReturnedNoRows))
2336            .and_then(|r| Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)?)))?;
2337        assert_eq!((v1.as_str(), v2), (name, age));
2338        Ok(())
2339    }
2340
2341    #[test]
2342    #[cfg(feature = "modern_sqlite")]
2343    fn test_db_name() -> Result<()> {
2344        let db = Connection::open_in_memory()?;
2345        assert_eq!(db.db_name(0)?, "main");
2346        assert_eq!(db.db_name(1)?, "temp");
2347        assert_eq!(db.db_name(2), Err(Error::InvalidDatabaseIndex(2)));
2348        db.execute_batch("ATTACH DATABASE ':memory:' AS xyz;")?;
2349        assert_eq!(db.db_name(2)?, "xyz");
2350        Ok(())
2351    }
2352
2353    #[test]
2354    #[cfg(feature = "modern_sqlite")]
2355    fn test_is_interrupted() -> Result<()> {
2356        let db = Connection::open_in_memory()?;
2357        assert!(!db.is_interrupted());
2358        db.get_interrupt_handle().interrupt();
2359        assert!(db.is_interrupted());
2360        Ok(())
2361    }
2362
2363    #[test]
2364    fn release_memory() -> Result<()> {
2365        let db = Connection::open_in_memory()?;
2366        db.release_memory()
2367    }
2368
2369    #[test]
2370    #[cfg(feature = "modern_sqlite")] // 3.51.0
2371    fn set_errmsg() -> Result<()> {
2372        let db = Connection::open_in_memory()?;
2373        let code: i32 = ffi::SQLITE_MISUSE;
2374        let msg = c"Oops";
2375        db.set_errmsg(code, Some(msg))?;
2376        let ptr = unsafe { db.handle() };
2377        assert_eq!(unsafe { ffi::sqlite3_errcode(ptr) }, code);
2378        assert_eq!(
2379            unsafe { std::ffi::CStr::from_ptr(ffi::sqlite3_errmsg(ptr)) },
2380            msg
2381        );
2382        Ok(())
2383    }
2384}