migratrom 0.2.0

Declarative, self-verifying database migrations (core engine).
Documentation
//! Database adapter contract used by the migration engine.
//!
//! Adapter crates implement [`Db`] and [`Row`] to expose a tiny async surface:
//! boolean probes, side-effecting statements, positional history reads, and
//! transaction boundaries.

use async_trait::async_trait;

use crate::error::Result;

/// Positional row decode for the fixed-order `SELECT`s used by history reads.
pub trait Row: Send {
    /// Read column `idx` as an `i64`, or `None` if absent / not an integer.
    fn i64_at(&self, idx: usize) -> Option<i64>;
    /// Read column `idx` as a `String`, or `None` if absent / not text.
    fn str_at(&self, idx: usize) -> Option<String>;
}

/// The only contract the engine has with a database.
#[async_trait]
pub trait Db: Send + Sync {
    /// Run a boolean check. Implementations must return exactly one row, one
    /// column, boolean; otherwise return [`crate::MigratromError::CheckShape`].
    async fn query_bool(&self, sql: &str) -> Result<bool>;

    /// Run a side-effecting statement (DDL/DML).
    async fn execute(&self, sql: &str) -> Result<()>;

    /// Run a query and return its rows for positional decoding (history reads).
    async fn query_rows(&self, sql: &str) -> Result<Vec<Box<dyn Row>>>;

    /// Open a transaction. A no-op when one is already active (nesting reuse).
    async fn begin(&self) -> Result<()>;

    /// Commit the active transaction (only the outermost begin commits).
    async fn commit(&self) -> Result<()>;

    /// Roll back the active transaction (only the outermost begin rolls back).
    async fn rollback(&self) -> Result<()>;
}

/// Run `body` inside a transaction, committing on success and rolling back on
/// error.
pub async fn with_transaction<F, Fut, T>(db: &dyn Db, body: F) -> Result<T>
where
    F: FnOnce() -> Fut,
    Fut: std::future::Future<Output = Result<T>>,
{
    db.begin().await?;
    match body().await {
        Ok(value) => {
            db.commit().await?;
            Ok(value)
        }
        Err(err) => {
            // Preserve the original failure even if rollback also fails.
            let _ = db.rollback().await;
            Err(err)
        }
    }
}