Debian Codegraph @

third_party/rust/rusqlite/src/lib.rs

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