migratrom-sqlite 0.2.0

SQLite (sqlx) adapter for migratrom.
Documentation
//! Apply [`migratrom`] migrations through a `sqlx::SqlitePool`.
//!
//! This is the normal application entry point for SQLite. [`apply_migrations`]
//! acquires one pooled connection and pins it for the complete run, ensuring the
//! engine's transaction statements use one SQLite session. SQLite has no advisory
//! locks, so enabling the core advisory-lock option is a no-op for this adapter.
//!
//! # Quick start
//!
//! ```no_run
//! use migratrom::operations::{add_column, create_table};
//! use migratrom::{ApplyOptions, ColumnDef, Migration, PrimaryKey, SqliteDialect};
//! use migratrom_sqlite::apply_migrations;
//! use sqlx::sqlite::SqlitePoolOptions;
//!
//! # async fn run() -> Result<(), Box<dyn std::error::Error>> {
//! let pool = SqlitePoolOptions::new()
//!     .max_connections(1)
//!     .connect("sqlite:app.db")
//!     .await?;
//! let dialect = SqliteDialect;
//!
//! let create_users = Migration::new(
//!     1,
//!     None,
//!     vec![create_table(
//!         "main",
//!         "users",
//!         &[ColumnDef::new("id", "INTEGER"), ColumnDef::new("email", "TEXT")],
//!         Some(&PrimaryKey { columns: vec!["id".into()] }),
//!         &dialect,
//!     )?],
//! );
//! let add_name = Migration::new(
//!     2,
//!     Some(1),
//!     vec![add_column(
//!         "main",
//!         "users",
//!         &ColumnDef::new("name", "TEXT").nullable(true),
//!         &dialect,
//!     )?],
//! );
//!
//! let result = apply_migrations(
//!     &[create_users, add_name],
//!     &pool,
//!     &ApplyOptions::default(),
//! ).await?;
//! println!("applied: {:?}", result.applied);
//! # Ok(())
//! # }
//! ```
//!
//! The core [`migratrom::operations`] module documents all available builders.
//! PostgreSQL-only builders return [`migratrom::MigratromError::Unsupported`] when
//! used with [`migratrom::SqliteDialect`].

#![deny(missing_docs)]

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
}