Skip to main content

migratrom_sqlite/
lib.rs

1//! Apply [`migratrom`] migrations through a `sqlx::SqlitePool`.
2//!
3//! This is the normal application entry point for SQLite. [`apply_migrations`]
4//! acquires one pooled connection and pins it for the complete run, ensuring the
5//! engine's transaction statements use one SQLite session. SQLite has no advisory
6//! locks, so enabling the core advisory-lock option is a no-op for this adapter.
7//!
8//! # Quick start
9//!
10//! ```no_run
11//! use migratrom::operations::{add_column, create_table};
12//! use migratrom::{ApplyOptions, ColumnDef, Migration, PrimaryKey, SqliteDialect};
13//! use migratrom_sqlite::apply_migrations;
14//! use sqlx::sqlite::SqlitePoolOptions;
15//!
16//! # async fn run() -> Result<(), Box<dyn std::error::Error>> {
17//! let pool = SqlitePoolOptions::new()
18//!     .max_connections(1)
19//!     .connect("sqlite:app.db")
20//!     .await?;
21//! let dialect = SqliteDialect;
22//!
23//! let create_users = Migration::new(
24//!     1,
25//!     None,
26//!     vec![create_table(
27//!         "main",
28//!         "users",
29//!         &[ColumnDef::new("id", "INTEGER"), ColumnDef::new("email", "TEXT")],
30//!         Some(&PrimaryKey { columns: vec!["id".into()] }),
31//!         &dialect,
32//!     )?],
33//! );
34//! let add_name = Migration::new(
35//!     2,
36//!     Some(1),
37//!     vec![add_column(
38//!         "main",
39//!         "users",
40//!         &ColumnDef::new("name", "TEXT").nullable(true),
41//!         &dialect,
42//!     )?],
43//! );
44//!
45//! let result = apply_migrations(
46//!     &[create_users, add_name],
47//!     &pool,
48//!     &ApplyOptions::default(),
49//! ).await?;
50//! println!("applied: {:?}", result.applied);
51//! # Ok(())
52//! # }
53//! ```
54//!
55//! The core [`migratrom::operations`] module documents all available builders.
56//! PostgreSQL-only builders return [`migratrom::MigratromError::Unsupported`] when
57//! used with [`migratrom::SqliteDialect`].
58
59#![deny(missing_docs)]
60
61use async_trait::async_trait;
62use migratrom::{
63    apply_migrations as core_apply, ApplyOptions, ApplyResult, Db, Migration, MigratromError, Row,
64    SqliteDialect,
65};
66use sqlx::pool::PoolConnection;
67use sqlx::sqlite::SqliteRow;
68use sqlx::{Row as SqlxRow, Sqlite, SqlitePool};
69use tokio::sync::Mutex;
70
71fn db_err(e: sqlx::Error) -> MigratromError {
72    MigratromError::Db(e.to_string())
73}
74
75struct Inner {
76    conn: PoolConnection<Sqlite>,
77    depth: u32,
78}
79
80/// A [`Db`] over one pinned SQLite connection.
81pub struct SqliteAdapter {
82    inner: Mutex<Inner>,
83}
84
85impl SqliteAdapter {
86    /// Wrap an acquired pooled connection.
87    pub fn new(conn: PoolConnection<Sqlite>) -> Self {
88        Self {
89            inner: Mutex::new(Inner { conn, depth: 0 }),
90        }
91    }
92}
93
94struct SqliteRowWrap(SqliteRow);
95
96impl Row for SqliteRowWrap {
97    fn i64_at(&self, idx: usize) -> Option<i64> {
98        self.0.try_get::<i64, _>(idx).ok()
99    }
100    fn str_at(&self, idx: usize) -> Option<String> {
101        self.0.try_get::<String, _>(idx).ok()
102    }
103}
104
105fn read_check(row: &SqliteRow) -> Result<bool, MigratromError> {
106    // SQLite returns 0/1 integers for our boolean probes.
107    if let Ok(i) = row.try_get::<i64, _>(0) {
108        return Ok(i != 0);
109    }
110    match row.try_get::<bool, _>(0) {
111        Ok(b) => Ok(b),
112        Err(e) => Err(MigratromError::CheckShape {
113            message: format!("check must return a boolean: {e}"),
114            row_preview: None,
115        }),
116    }
117}
118
119#[async_trait]
120impl Db for SqliteAdapter {
121    async fn query_bool(&self, sql: &str) -> Result<bool, MigratromError> {
122        let mut g = self.inner.lock().await;
123        let row = sqlx::query(sql)
124            .fetch_one(&mut *g.conn)
125            .await
126            .map_err(db_err)?;
127        read_check(&row)
128    }
129
130    async fn execute(&self, sql: &str) -> Result<(), MigratromError> {
131        let mut g = self.inner.lock().await;
132        sqlx::query(sql)
133            .execute(&mut *g.conn)
134            .await
135            .map_err(db_err)?;
136        Ok(())
137    }
138
139    async fn query_rows(&self, sql: &str) -> Result<Vec<Box<dyn Row>>, MigratromError> {
140        let mut g = self.inner.lock().await;
141        let rows = sqlx::query(sql)
142            .fetch_all(&mut *g.conn)
143            .await
144            .map_err(db_err)?;
145        Ok(rows
146            .into_iter()
147            .map(|r| Box::new(SqliteRowWrap(r)) as Box<dyn Row>)
148            .collect())
149    }
150
151    async fn begin(&self) -> Result<(), MigratromError> {
152        let mut g = self.inner.lock().await;
153        if g.depth == 0 {
154            sqlx::query("BEGIN")
155                .execute(&mut *g.conn)
156                .await
157                .map_err(db_err)?;
158        }
159        g.depth += 1;
160        Ok(())
161    }
162
163    async fn commit(&self) -> Result<(), MigratromError> {
164        let mut g = self.inner.lock().await;
165        g.depth -= 1;
166        if g.depth == 0 {
167            sqlx::query("COMMIT")
168                .execute(&mut *g.conn)
169                .await
170                .map_err(db_err)?;
171        }
172        Ok(())
173    }
174
175    async fn rollback(&self) -> Result<(), MigratromError> {
176        let mut g = self.inner.lock().await;
177        g.depth -= 1;
178        if g.depth == 0 {
179            sqlx::query("ROLLBACK")
180                .execute(&mut *g.conn)
181                .await
182                .map_err(db_err)?;
183        }
184        Ok(())
185    }
186}
187
188/// Apply migrations against a SQLite pool using [`SqliteDialect`].
189pub async fn apply_migrations(
190    migrations: &[Migration],
191    pool: &SqlitePool,
192    options: &ApplyOptions,
193) -> Result<ApplyResult, MigratromError> {
194    let conn = pool.acquire().await.map_err(db_err)?;
195    let adapter = SqliteAdapter::new(conn);
196    core_apply(migrations, &adapter, &SqliteDialect, options).await
197}