Skip to main content

migratrom_turso/
lib.rs

1//! Apply [`migratrom`] migrations through the [`turso`] in-process database.
2//!
3//! [Turso](https://github.com/tursodatabase/turso) is a pure-Rust, SQLite-compatible
4//! engine, so this adapter reuses the core [`SqliteDialect`]. [`apply_migrations`]
5//! opens one connection and pins it for the complete run, ensuring the engine's
6//! transaction statements use one database session. Turso has no advisory locks,
7//! so enabling the core advisory-lock option is a no-op for this adapter.
8//!
9//! # Quick start
10//!
11//! ```no_run
12//! use migratrom::operations::{add_column, create_table};
13//! use migratrom::{ApplyOptions, ColumnDef, Migration, PrimaryKey, SqliteDialect};
14//! use migratrom_turso::apply_migrations;
15//!
16//! # async fn run() -> Result<(), Box<dyn std::error::Error>> {
17//! let db = turso::Builder::new_local("app.db").build().await?;
18//! let dialect = SqliteDialect;
19//!
20//! let create_users = Migration::new(
21//!     1,
22//!     None,
23//!     vec![create_table(
24//!         "main",
25//!         "users",
26//!         &[ColumnDef::new("id", "INTEGER"), ColumnDef::new("email", "TEXT")],
27//!         Some(&PrimaryKey { columns: vec!["id".into()] }),
28//!         &dialect,
29//!     )?],
30//! );
31//! let add_name = Migration::new(
32//!     2,
33//!     Some(1),
34//!     vec![add_column(
35//!         "main",
36//!         "users",
37//!         &ColumnDef::new("name", "TEXT").nullable(true),
38//!         &dialect,
39//!     )?],
40//! );
41//!
42//! let result = apply_migrations(
43//!     &[create_users, add_name],
44//!     &db,
45//!     &ApplyOptions::default(),
46//! ).await?;
47//! println!("applied: {:?}", result.applied);
48//! # Ok(())
49//! # }
50//! ```
51//!
52//! The core [`migratrom::operations`] module documents all available builders.
53//! PostgreSQL-only builders return [`migratrom::MigratromError::Unsupported`] when
54//! used with [`migratrom::SqliteDialect`].
55
56#![deny(missing_docs)]
57
58use async_trait::async_trait;
59use migratrom::{
60    apply_migrations as core_apply, ApplyOptions, ApplyResult, Db, Migration, MigratromError, Row,
61    SqliteDialect,
62};
63use tokio::sync::Mutex;
64use turso::{Connection, Database, Value};
65
66fn db_err(e: turso::Error) -> MigratromError {
67    MigratromError::Db(e.to_string())
68}
69
70struct Inner {
71    conn: Connection,
72    depth: u32,
73}
74
75/// A [`Db`] over one pinned Turso connection.
76pub struct TursoAdapter {
77    inner: Mutex<Inner>,
78}
79
80impl TursoAdapter {
81    /// Wrap an open connection.
82    pub fn new(conn: Connection) -> Self {
83        Self {
84            inner: Mutex::new(Inner { conn, depth: 0 }),
85        }
86    }
87}
88
89struct TursoRowWrap(turso::Row);
90
91impl Row for TursoRowWrap {
92    fn i64_at(&self, idx: usize) -> Option<i64> {
93        match self.0.get_value(idx) {
94            Ok(Value::Integer(i)) => Some(i),
95            _ => None,
96        }
97    }
98    fn str_at(&self, idx: usize) -> Option<String> {
99        match self.0.get_value(idx) {
100            Ok(Value::Text(s)) => Some(s),
101            _ => None,
102        }
103    }
104}
105
106fn read_check(row: &turso::Row) -> Result<bool, MigratromError> {
107    // The SQLite dialect's boolean probes are `SELECT [NOT] EXISTS (...)` /
108    // `SELECT 0|1`, which Turso returns as 0/1 integers.
109    match row.get_value(0) {
110        Ok(Value::Integer(i)) => Ok(i != 0),
111        Ok(other) => Err(MigratromError::CheckShape {
112            message: format!("check must return an integer boolean, got {other:?}"),
113            row_preview: None,
114        }),
115        Err(e) => Err(MigratromError::CheckShape {
116            message: format!("check must return a boolean: {e}"),
117            row_preview: None,
118        }),
119    }
120}
121
122#[async_trait]
123impl Db for TursoAdapter {
124    async fn query_bool(&self, sql: &str) -> Result<bool, MigratromError> {
125        let g = self.inner.lock().await;
126        let mut rows = g.conn.query(sql, ()).await.map_err(db_err)?;
127        let first = rows.next().await.map_err(db_err)?;
128        let row = first.ok_or_else(|| MigratromError::CheckShape {
129            message: "check returned no rows".to_string(),
130            row_preview: None,
131        })?;
132        let value = read_check(&row)?;
133        // Drain so the statement runs to completion; a half-consumed statement
134        // rolls the active transaction back when dropped.
135        while rows.next().await.map_err(db_err)?.is_some() {}
136        Ok(value)
137    }
138
139    async fn execute(&self, sql: &str) -> Result<(), MigratromError> {
140        let g = self.inner.lock().await;
141        g.conn.execute(sql, ()).await.map_err(db_err)?;
142        Ok(())
143    }
144
145    async fn query_rows(&self, sql: &str) -> Result<Vec<Box<dyn Row>>, MigratromError> {
146        let g = self.inner.lock().await;
147        let mut rows = g.conn.query(sql, ()).await.map_err(db_err)?;
148        let mut out: Vec<Box<dyn Row>> = Vec::new();
149        while let Some(row) = rows.next().await.map_err(db_err)? {
150            out.push(Box::new(TursoRowWrap(row)) as Box<dyn Row>);
151        }
152        Ok(out)
153    }
154
155    async fn begin(&self) -> Result<(), MigratromError> {
156        let mut g = self.inner.lock().await;
157        if g.depth == 0 {
158            g.conn.execute("BEGIN", ()).await.map_err(db_err)?;
159        }
160        g.depth += 1;
161        Ok(())
162    }
163
164    async fn commit(&self) -> Result<(), MigratromError> {
165        let mut g = self.inner.lock().await;
166        g.depth -= 1;
167        if g.depth == 0 {
168            g.conn.execute("COMMIT", ()).await.map_err(db_err)?;
169        }
170        Ok(())
171    }
172
173    async fn rollback(&self) -> Result<(), MigratromError> {
174        let mut g = self.inner.lock().await;
175        g.depth -= 1;
176        if g.depth == 0 {
177            g.conn.execute("ROLLBACK", ()).await.map_err(db_err)?;
178        }
179        Ok(())
180    }
181}
182
183/// Apply migrations against a Turso database using [`SqliteDialect`].
184///
185/// One connection is opened from `db` and pinned for the whole run. Callers that
186/// already hold a [`turso::Connection`] can build a [`TursoAdapter`] directly and
187/// call [`migratrom::apply_migrations`].
188pub async fn apply_migrations(
189    migrations: &[Migration],
190    db: &Database,
191    options: &ApplyOptions,
192) -> Result<ApplyResult, MigratromError> {
193    let conn = db.connect().map_err(db_err)?;
194    let adapter = TursoAdapter::new(conn);
195    core_apply(migrations, &adapter, &SqliteDialect, options).await
196}