migratrom-sqlite 0.1.0

SQLite (sqlx) adapter for migratrom.
Documentation
//! SQLite adapter for [`migratrom`], built on `sqlx`.
//!
//! Pins a single pooled connection so the manual `BEGIN`/`COMMIT`/`ROLLBACK`
//! statements act on one session. SQLite has no advisory locks, so the dialect
//! reports `advisory_locks: false` and locking is a no-op.

use async_trait::async_trait;
use migratrom::{
    apply_migrations as core_apply, ApplyOptions, ApplyResult, Db, Migration, MigratromError, Row,
    SqliteDialect,
};
use sqlx::pool::PoolConnection;
use sqlx::sqlite::SqliteRow;
use sqlx::{Row as SqlxRow, Sqlite, SqlitePool};
use tokio::sync::Mutex;

fn db_err(e: sqlx::Error) -> MigratromError {
    MigratromError::Db(e.to_string())
}

struct Inner {
    conn: PoolConnection<Sqlite>,
    depth: u32,
}

/// A [`Db`] over one pinned SQLite connection.
pub struct SqliteAdapter {
    inner: Mutex<Inner>,
}

impl SqliteAdapter {
    /// Wrap an acquired pooled connection.
    pub fn new(conn: PoolConnection<Sqlite>) -> Self {
        Self {
            inner: Mutex::new(Inner { conn, depth: 0 }),
        }
    }
}

struct SqliteRowWrap(SqliteRow);

impl Row for SqliteRowWrap {
    fn i64_at(&self, idx: usize) -> Option<i64> {
        self.0.try_get::<i64, _>(idx).ok()
    }
    fn str_at(&self, idx: usize) -> Option<String> {
        self.0.try_get::<String, _>(idx).ok()
    }
}

fn read_check(row: &SqliteRow) -> Result<bool, MigratromError> {
    // SQLite returns 0/1 integers for our boolean probes.
    if let Ok(i) = row.try_get::<i64, _>(0) {
        return Ok(i != 0);
    }
    match row.try_get::<bool, _>(0) {
        Ok(b) => Ok(b),
        Err(e) => Err(MigratromError::CheckShape {
            message: format!("check must return a boolean: {e}"),
            row_preview: None,
        }),
    }
}

#[async_trait]
impl Db for SqliteAdapter {
    async fn query_bool(&self, sql: &str) -> Result<bool, MigratromError> {
        let mut g = self.inner.lock().await;
        let row = sqlx::query(sql)
            .fetch_one(&mut *g.conn)
            .await
            .map_err(db_err)?;
        read_check(&row)
    }

    async fn execute(&self, sql: &str) -> Result<(), MigratromError> {
        let mut g = self.inner.lock().await;
        sqlx::query(sql)
            .execute(&mut *g.conn)
            .await
            .map_err(db_err)?;
        Ok(())
    }

    async fn query_rows(&self, sql: &str) -> Result<Vec<Box<dyn Row>>, MigratromError> {
        let mut g = self.inner.lock().await;
        let rows = sqlx::query(sql)
            .fetch_all(&mut *g.conn)
            .await
            .map_err(db_err)?;
        Ok(rows
            .into_iter()
            .map(|r| Box::new(SqliteRowWrap(r)) as Box<dyn Row>)
            .collect())
    }

    async fn begin(&self) -> Result<(), MigratromError> {
        let mut g = self.inner.lock().await;
        if g.depth == 0 {
            sqlx::query("BEGIN")
                .execute(&mut *g.conn)
                .await
                .map_err(db_err)?;
        }
        g.depth += 1;
        Ok(())
    }

    async fn commit(&self) -> Result<(), MigratromError> {
        let mut g = self.inner.lock().await;
        g.depth -= 1;
        if g.depth == 0 {
            sqlx::query("COMMIT")
                .execute(&mut *g.conn)
                .await
                .map_err(db_err)?;
        }
        Ok(())
    }

    async fn rollback(&self) -> Result<(), MigratromError> {
        let mut g = self.inner.lock().await;
        g.depth -= 1;
        if g.depth == 0 {
            sqlx::query("ROLLBACK")
                .execute(&mut *g.conn)
                .await
                .map_err(db_err)?;
        }
        Ok(())
    }
}

/// Apply migrations against a SQLite pool using [`SqliteDialect`].
pub async fn apply_migrations(
    migrations: &[Migration],
    pool: &SqlitePool,
    options: &ApplyOptions,
) -> Result<ApplyResult, MigratromError> {
    let conn = pool.acquire().await.map_err(db_err)?;
    let adapter = SqliteAdapter::new(conn);
    core_apply(migrations, &adapter, &SqliteDialect, options).await
}