Skip to main content

toasty_driver_sqlite/
lib.rs

1#![warn(missing_docs)]
2
3//! Toasty driver for [SQLite](https://www.sqlite.org/) using
4//! [`rusqlite`](https://docs.rs/rusqlite).
5//!
6//! Supports both file-backed and in-memory databases.
7//!
8//! # Examples
9//!
10//! ```
11//! use toasty_driver_sqlite::Sqlite;
12//!
13//! // In-memory database
14//! let driver = Sqlite::in_memory();
15//!
16//! // File-backed database
17//! let driver = Sqlite::open("path/to/db.sqlite3");
18//! ```
19
20mod pragma;
21use pragma::Pragmas;
22pub use pragma::{AutoVacuum, JournalMode, LockingMode, Synchronous};
23
24mod value;
25pub(crate) use value::Value;
26
27use async_trait::async_trait;
28use rusqlite::Connection as RusqliteConnection;
29use std::{
30    borrow::Cow,
31    path::{Path, PathBuf},
32    sync::Arc,
33    time::Duration,
34};
35use toasty_core::{
36    Result, Schema,
37    driver::{
38        Capability, ConnectContext, ConnectionUrl, Driver, ExecResponse, QueryLogConfig,
39        log::QueryLog,
40        operation::{IsolationLevel, Operation, RawSqlRet, Transaction, TypedValue},
41    },
42    schema::db::{self, Table},
43    stmt,
44};
45use toasty_sql::{self as sql};
46
47enum SqlReturn {
48    Count,
49    Infer,
50    Types(Vec<stmt::Type>),
51}
52
53/// A SQLite [`Driver`] that opens connections to a file or in-memory database.
54///
55/// # Examples
56///
57/// ```
58/// use toasty_driver_sqlite::Sqlite;
59///
60/// let driver = Sqlite::in_memory();
61/// ```
62#[derive(Debug)]
63pub struct Sqlite {
64    source: Source,
65    busy_timeout: Duration,
66    pragmas: Pragmas,
67}
68
69/// Where a [`Sqlite`] driver's database lives.
70#[derive(Debug)]
71enum Source {
72    /// A database stored at a filesystem path.
73    File(PathBuf),
74    /// An ephemeral in-memory database.
75    InMemory,
76}
77
78impl Sqlite {
79    fn from_source(source: Source) -> Self {
80        Self {
81            source,
82            busy_timeout: Duration::from_secs(5),
83            pragmas: Pragmas::default(),
84        }
85    }
86
87    /// Create a new SQLite driver with an arbitrary connection URL
88    pub fn new(url: impl Into<String>) -> Result<Self> {
89        let url_str = url.into();
90        let url = ConnectionUrl::parse(&url_str)?;
91
92        if !url.has_scheme("sqlite") {
93            return Err(toasty_core::Error::invalid_connection_url(format!(
94                "connection URL does not have a `sqlite` scheme; url={url_str}"
95            )));
96        }
97
98        let path = url.file_path()?;
99        if path == Path::new(":memory:") {
100            return Ok(Self::in_memory());
101        }
102
103        Ok(Self::open(path))
104    }
105
106    /// Create an in-memory SQLite database
107    pub fn in_memory() -> Self {
108        Self::from_source(Source::InMemory)
109    }
110
111    /// Open a SQLite database at the specified file path
112    pub fn open<P: AsRef<Path>>(path: P) -> Self {
113        Self::from_source(Source::File(path.as_ref().to_path_buf()))
114    }
115
116    /// Set the enforcement of
117    /// [foreign key constraints](https://www.sqlite.org/pragma.html#pragma_foreign_keys).
118    ///
119    /// Enabled by default.
120    pub fn foreign_keys(mut self, on: bool) -> Self {
121        self.pragmas
122            .set("foreign_keys", if on { "ON" } else { "OFF" });
123        self
124    }
125
126    /// Set how long a connection waits for a lock held by another
127    /// connection before failing with `database is locked`.
128    ///
129    /// Set through `sqlite3_busy_timeout` as soon as each connection opens,
130    /// before any pragma runs. The default is 5 seconds.
131    pub fn busy_timeout(mut self, timeout: Duration) -> Self {
132        self.busy_timeout = timeout;
133        self
134    }
135
136    /// Set the [journal mode](https://www.sqlite.org/pragma.html#pragma_journal_mode).
137    ///
138    /// Journal modes are per connection, except for
139    /// [WAL](https://www.sqlite.org/wal.html), which the database file
140    /// keeps. Opening a WAL database with a different journal mode takes an
141    /// exclusive lock and converts the file.
142    ///
143    /// Not set by default, so an existing database keeps its mode.
144    ///
145    /// # Examples
146    ///
147    /// ```
148    /// use toasty_driver_sqlite::{JournalMode, Sqlite};
149    ///
150    /// let driver = Sqlite::open("app.db").journal_mode(JournalMode::Wal);
151    /// ```
152    pub fn journal_mode(mut self, mode: JournalMode) -> Self {
153        self.pragmas.set("journal_mode", mode);
154        self
155    }
156
157    /// Set the [synchronous](https://www.sqlite.org/pragma.html#pragma_synchronous)
158    /// setting.
159    ///
160    /// Not set by default; SQLite's default is `FULL`. `NORMAL` is usually
161    /// enough in WAL mode.
162    pub fn synchronous(mut self, synchronous: Synchronous) -> Self {
163        self.pragmas.set("synchronous", synchronous);
164        self
165    }
166
167    /// Set the [locking mode](https://www.sqlite.org/pragma.html#pragma_locking_mode).
168    ///
169    /// Not set by default; SQLite's default is `NORMAL`.
170    pub fn locking_mode(mut self, mode: LockingMode) -> Self {
171        self.pragmas.set("locking_mode", mode);
172        self
173    }
174
175    /// Set the [auto-vacuum](https://www.sqlite.org/pragma.html#pragma_auto_vacuum)
176    /// setting.
177    ///
178    /// Not set by default; SQLite's default is `NONE`. On an existing
179    /// database the change takes effect only after a `VACUUM`.
180    pub fn auto_vacuum(mut self, auto_vacuum: AutoVacuum) -> Self {
181        self.pragmas.set("auto_vacuum", auto_vacuum);
182        self
183    }
184
185    /// Set the [page size](https://www.sqlite.org/pragma.html#pragma_page_size)
186    /// in bytes.
187    ///
188    /// Not set by default; SQLite's default is 4096. On an existing
189    /// database the change takes effect only after a `VACUUM`, and never in
190    /// WAL mode.
191    pub fn page_size(mut self, page_size: u32) -> Self {
192        self.pragmas.set("page_size", page_size.to_string());
193        self
194    }
195
196    /// Set the [SQLCipher](https://www.zetetic.net/sqlcipher/sqlcipher-api/#key)
197    /// passphrase that encrypts the database.
198    ///
199    /// The passphrase is quoted for you, applied before every other pragma,
200    /// and kept out of query logs, error messages, and `Debug` output.
201    /// SQLCipher checks it only when the database is first read, so a wrong
202    /// passphrase fails at the first query rather than on connect.
203    ///
204    /// Available with this crate's `sqlcipher` feature.
205    ///
206    /// # Examples
207    ///
208    /// ```
209    /// use toasty_driver_sqlite::Sqlite;
210    ///
211    /// let driver = Sqlite::open("app.db").key("a passphrase");
212    /// ```
213    #[cfg(feature = "sqlcipher")]
214    pub fn key(mut self, passphrase: impl AsRef<str>) -> Self {
215        let quoted = format!("'{}'", passphrase.as_ref().replace('\'', "''"));
216        self.pragmas.set("key", quoted);
217        self
218    }
219
220    /// Set a `PRAGMA` applied to every connection this driver opens.
221    ///
222    /// Use this for pragmas without a dedicated method. The driver writes
223    /// `PRAGMA {key} = {value}` with both arguments as given, so the caller
224    /// supplies any quoting the value needs. Do not pass untrusted input:
225    /// the value is SQL text.
226    ///
227    /// Pragmas run in a fixed order rather than the order they are set,
228    /// because SQLite and SQLCipher constrain it: `key` and the other
229    /// SQLCipher settings come first, then `page_size`, `locking_mode`,
230    /// `auto_vacuum`, `journal_mode`, `foreign_keys`, `synchronous`, and
231    /// then every other pragma in the order first set. Setting the same
232    /// pragma twice keeps the last value. Names match exactly.
233    ///
234    /// # Examples
235    ///
236    /// ```
237    /// use toasty_driver_sqlite::Sqlite;
238    ///
239    /// let driver = Sqlite::open("app.db")
240    ///     .pragma("cache_size", "-64000")
241    ///     .pragma("temp_store", "MEMORY");
242    /// ```
243    ///
244    /// Values of `key` and other secret SQLCipher pragmas are kept out of
245    /// query logs, error messages, and `Debug` output.
246    pub fn pragma<K, V>(mut self, key: K, value: V) -> Self
247    where
248        K: Into<Cow<'static, str>>,
249        V: Into<Cow<'static, str>>,
250    {
251        self.pragmas.set(key, value);
252        self
253    }
254}
255
256#[async_trait]
257impl Driver for Sqlite {
258    fn url(&self) -> Cow<'_, str> {
259        match &self.source {
260            Source::InMemory => Cow::Borrowed("sqlite::memory:"),
261            Source::File(path) => Cow::Owned(format!("sqlite:{}", path.display())),
262        }
263    }
264
265    fn capability(&self) -> &'static Capability {
266        &Capability::SQLITE
267    }
268
269    async fn connect(
270        &self,
271        cx: &ConnectContext,
272    ) -> toasty_core::Result<Box<dyn toasty_core::Connection>> {
273        let mut connection = match &self.source {
274            Source::File(path) => Connection::open(path)?,
275            Source::InMemory => Connection::in_memory(),
276        };
277        connection.query_log = cx.query_log;
278        connection
279            .connection
280            .busy_timeout(self.busy_timeout)
281            .map_err(toasty_core::Error::driver_operation_failed)?;
282        self.pragmas.apply(&connection.connection, &cx.query_log)?;
283        Ok(Box::new(connection))
284    }
285
286    fn max_connections(&self) -> Option<usize> {
287        matches!(self.source, Source::InMemory).then_some(1)
288    }
289
290    async fn reset_db(&self) -> toasty_core::Result<()> {
291        match &self.source {
292            Source::File(path) => {
293                // Delete the file and recreate it
294                if path.exists() {
295                    std::fs::remove_file(path)
296                        .map_err(toasty_core::Error::driver_operation_failed)?;
297                }
298            }
299            Source::InMemory => {
300                // Nothing to do — each connect() creates a fresh in-memory database
301            }
302        }
303
304        Ok(())
305    }
306}
307
308/// An open connection to a SQLite database.
309#[derive(Debug)]
310pub struct Connection {
311    connection: RusqliteConnection,
312    query_log: QueryLogConfig,
313}
314
315impl Connection {
316    /// Open an in-memory SQLite connection.
317    pub fn in_memory() -> Self {
318        let connection = RusqliteConnection::open_in_memory().unwrap();
319
320        Self {
321            connection,
322            query_log: QueryLogConfig::default(),
323        }
324    }
325
326    /// Open a SQLite connection to a file at `path`.
327    pub fn open<P: AsRef<Path>>(path: P) -> Result<Self> {
328        let connection =
329            RusqliteConnection::open(path).map_err(toasty_core::Error::driver_operation_failed)?;
330        let sqlite = Self {
331            connection,
332            query_log: QueryLogConfig::default(),
333        };
334        Ok(sqlite)
335    }
336
337    fn exec_sql(
338        &mut self,
339        sql_str: &str,
340        typed_params: Vec<TypedValue>,
341        ret: SqlReturn,
342    ) -> Result<ExecResponse> {
343        let mut log = QueryLog::sql(
344            &self.query_log,
345            "sqlite",
346            sql_str,
347            typed_params.iter().map(|tv| &tv.value),
348        );
349        let result = self.exec_sql_inner(sql_str, typed_params, ret, &mut log);
350        log.finish(&result);
351        result
352    }
353
354    fn exec_sql_inner(
355        &mut self,
356        sql_str: &str,
357        typed_params: Vec<TypedValue>,
358        ret: SqlReturn,
359        log: &mut QueryLog<'_>,
360    ) -> Result<ExecResponse> {
361        let mut stmt = self
362            .connection
363            .prepare_cached(sql_str)
364            .map_err(toasty_core::Error::driver_operation_failed)?;
365
366        let params = typed_params
367            .into_iter()
368            .map(|tv| Value::from(tv.value))
369            .collect::<Vec<_>>();
370
371        if matches!(ret, SqlReturn::Count) {
372            let count = stmt
373                .execute(rusqlite::params_from_iter(params.iter()))
374                .map_err(toasty_core::Error::driver_operation_failed)?;
375
376            return Ok(ExecResponse::count(count as _));
377        }
378
379        let mut rows = stmt
380            .query(rusqlite::params_from_iter(params.iter()))
381            .map_err(toasty_core::Error::driver_operation_failed)?;
382
383        let mut values = vec![];
384        let column_count = rows.as_ref().map(|stmt| stmt.column_count()).unwrap_or(0);
385
386        loop {
387            match rows.next() {
388                Ok(Some(row)) => {
389                    let items = match &ret {
390                        SqlReturn::Count => unreachable!(),
391                        SqlReturn::Infer => (0..column_count)
392                            .map(|index| Value::from_sql_infer(row, index).into_inner())
393                            .collect(),
394                        SqlReturn::Types(ret_tys) => ret_tys
395                            .iter()
396                            .enumerate()
397                            .map(|(index, ret_ty)| Value::from_sql(row, index, ret_ty).into_inner())
398                            .collect(),
399                    };
400
401                    values.push(stmt::ValueRecord::from_vec(items).into());
402                }
403                Ok(None) => break,
404                Err(err) => {
405                    return Err(toasty_core::Error::driver_operation_failed(err));
406                }
407            }
408        }
409
410        log.rows(values.len() as u64);
411        Ok(ExecResponse::value_stream(stmt::ValueStream::from_vec(
412            values,
413        )))
414    }
415}
416
417#[async_trait]
418impl toasty_core::driver::Connection for Connection {
419    async fn exec(&mut self, schema: &Arc<Schema>, op: Operation) -> Result<ExecResponse> {
420        tracing::trace!(driver = "sqlite", op = %op.name(), "driver exec");
421
422        let (sql, typed_params, ret_tys) = match op {
423            Operation::Insert(op) => (sql::Statement::from(op.stmt), op.params, op.ret),
424            Operation::QuerySql(op) => (sql::Statement::from(op.stmt), op.params, op.ret),
425            Operation::RawSql(op) => {
426                let ret = match op.ret {
427                    RawSqlRet::None => SqlReturn::Count,
428                    RawSqlRet::Infer => SqlReturn::Infer,
429                    RawSqlRet::Types(types) => SqlReturn::Types(types),
430                };
431                return self.exec_sql(&op.sql, op.params, ret);
432            }
433            Operation::Transaction(mut op) => {
434                if let Transaction::Start { isolation, .. } = &mut op {
435                    if !matches!(isolation, Some(IsolationLevel::Serializable) | None) {
436                        return Err(toasty_core::Error::unsupported_feature(
437                            "SQLite only supports Serializable isolation",
438                        ));
439                    }
440                    *isolation = None;
441                }
442                let sql = sql::Serializer::sqlite(&schema.db).serialize_transaction(&op);
443                self.connection
444                    .execute(&sql, [])
445                    .map_err(toasty_core::Error::driver_operation_failed)?;
446                return Ok(ExecResponse::count(0));
447            }
448            _ => todo!("op={:#?}", op),
449        };
450
451        let ret = match &sql {
452            sql::Statement::Query(stmt) => match &stmt.body {
453                stmt::ExprSet::Select(_) => SqlReturn::Types(ret_tys.unwrap()),
454                _ => todo!(),
455            },
456            sql::Statement::Insert(stmt) => stmt
457                .returning
458                .as_ref()
459                .map(|_| SqlReturn::Types(ret_tys.unwrap()))
460                .unwrap_or(SqlReturn::Count),
461            sql::Statement::Delete(stmt) => stmt
462                .returning
463                .as_ref()
464                .map(|_| SqlReturn::Types(ret_tys.unwrap()))
465                .unwrap_or(SqlReturn::Count),
466            sql::Statement::Update(stmt) => {
467                assert!(stmt.condition.is_none(), "stmt={stmt:#?}");
468                stmt.returning
469                    .as_ref()
470                    .map(|_| SqlReturn::Types(ret_tys.unwrap()))
471                    .unwrap_or(SqlReturn::Count)
472            }
473            _ => SqlReturn::Count,
474        };
475
476        let sql_str = sql::Serializer::sqlite(&schema.db).serialize(&sql);
477        self.exec_sql(&sql_str, typed_params, ret)
478    }
479
480    async fn push_schema(&mut self, schema: &Schema) -> Result<()> {
481        for table in &schema.db.tables {
482            tracing::debug!(table = %table.name, "creating table");
483            self.create_table(&schema.db, table)?;
484        }
485
486        Ok(())
487    }
488
489    async fn applied_migrations(
490        &mut self,
491    ) -> Result<Vec<toasty_core::schema::db::AppliedMigration>> {
492        // Ensure the migrations table exists
493        self.connection
494            .execute(
495                "CREATE TABLE IF NOT EXISTS __toasty_migrations (
496                id INTEGER PRIMARY KEY,
497                name TEXT NOT NULL,
498                applied_at TEXT NOT NULL
499            )",
500                [],
501            )
502            .map_err(toasty_core::Error::driver_operation_failed)?;
503
504        // Query all applied migrations
505        let mut stmt = self
506            .connection
507            .prepare("SELECT id FROM __toasty_migrations ORDER BY applied_at")
508            .map_err(toasty_core::Error::driver_operation_failed)?;
509
510        let rows = stmt
511            .query_map([], |row| {
512                let id: i64 = row.get(0)?;
513                Ok(toasty_core::schema::db::AppliedMigration::new(id as u64))
514            })
515            .map_err(toasty_core::Error::driver_operation_failed)?;
516
517        rows.collect::<rusqlite::Result<Vec<_>>>()
518            .map_err(toasty_core::Error::driver_operation_failed)
519    }
520
521    async fn apply_migration(
522        &mut self,
523        id: u64,
524        name: &str,
525        migration: &toasty_core::schema::db::Migration,
526    ) -> Result<()> {
527        tracing::info!(id = id, name = %name, "applying migration");
528        // Ensure the migrations table exists
529        self.connection
530            .execute(
531                "CREATE TABLE IF NOT EXISTS __toasty_migrations (
532                id INTEGER PRIMARY KEY,
533                name TEXT NOT NULL,
534                applied_at TEXT NOT NULL
535            )",
536                [],
537            )
538            .map_err(toasty_core::Error::driver_operation_failed)?;
539
540        // Start transaction
541        self.connection
542            .execute("BEGIN", [])
543            .map_err(toasty_core::Error::driver_operation_failed)?;
544
545        // Execute each migration statement
546        for statement in migration.statements() {
547            if let Err(e) = self
548                .connection
549                .execute(statement, [])
550                .map_err(toasty_core::Error::driver_operation_failed)
551            {
552                self.connection
553                    .execute("ROLLBACK", [])
554                    .map_err(toasty_core::Error::driver_operation_failed)?;
555                return Err(e);
556            }
557        }
558
559        // Record the migration
560        if let Err(e) = self.connection.execute(
561            "INSERT INTO __toasty_migrations (id, name, applied_at) VALUES (?1, ?2, datetime('now'))",
562            rusqlite::params![id as i64, name],
563        ).map_err(toasty_core::Error::driver_operation_failed) {
564            self.connection.execute("ROLLBACK", []).map_err(toasty_core::Error::driver_operation_failed)?;
565            return Err(e);
566        }
567
568        // Commit transaction
569        self.connection
570            .execute("COMMIT", [])
571            .map_err(toasty_core::Error::driver_operation_failed)?;
572        Ok(())
573    }
574}
575
576impl Connection {
577    fn create_table(&mut self, schema: &db::Schema, table: &Table) -> Result<()> {
578        let serializer = sql::Serializer::sqlite(schema);
579
580        let stmt = serializer.serialize(&sql::Statement::create_table(table, &Capability::SQLITE));
581
582        self.connection
583            .execute(&stmt, [])
584            .map_err(toasty_core::Error::driver_operation_failed)?;
585
586        // Create any indices
587        for index in &table.indices {
588            // The PK has already been created by the table statement
589            if index.primary_key {
590                continue;
591            }
592
593            let stmt = serializer.serialize(&sql::Statement::create_index(index));
594
595            self.connection
596                .execute(&stmt, [])
597                .map_err(toasty_core::Error::driver_operation_failed)?;
598        }
599        Ok(())
600    }
601}