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