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