migratrom 0.2.0

Declarative, self-verifying database migrations (core engine).
Documentation
//! The per-operation execution pipeline: postcheck (skip) → precheck → execute → verify.

use crate::db::Db;
use crate::error::{MigratromError, Result};
use crate::logger::MigrationLogger;
use crate::types::{Check, Operation};

/// Whether an operation ran or was skipped because it was already applied.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum OpOutcome {
    /// The operation's execute steps ran, or would run in a dry run.
    Executed,
    /// The operation was already in its desired postcheck state.
    Skipped,
}

async fn eval_checks(db: &dyn Db, checks: &[Check]) -> Result<Vec<bool>> {
    let mut results = Vec::with_capacity(checks.len());
    for c in checks {
        results.push(db.query_bool(&c.sql).await?);
    }
    Ok(results)
}

/// Run a single operation.
///
/// If every postcheck already passes the operation is skipped (idempotency).
/// Otherwise prechecks must all pass, the execute steps run (unless `dry_run`),
/// and the postchecks must all pass afterwards.
pub async fn run_operation(
    db: &dyn Db,
    op: &Operation,
    log: &dyn MigrationLogger,
    dry_run: bool,
) -> Result<OpOutcome> {
    if op.postcheck.is_empty() {
        return Err(MigratromError::EmptyPostcheck(op.id.clone()));
    }

    let post_results = eval_checks(db, &op.postcheck).await?;
    if post_results.iter().all(|&b| b) {
        log.info(&format!("skip operation {} (already applied)", op.id));
        return Ok(OpOutcome::Skipped);
    }

    let pre_results = eval_checks(db, &op.precheck).await?;
    for (i, &passed) in pre_results.iter().enumerate() {
        if !passed {
            return Err(MigratromError::PrecheckFailed {
                operation: op.id.clone(),
                description: op.precheck[i].description.clone(),
            });
        }
    }

    if dry_run {
        log.info(&format!("dry-run would execute operation {}", op.id));
        return Ok(OpOutcome::Executed);
    }

    for step in &op.execute {
        db.execute(&step.sql).await?;
    }

    let verify_results = eval_checks(db, &op.postcheck).await?;
    for (i, &passed) in verify_results.iter().enumerate() {
        if !passed {
            return Err(MigratromError::PostcheckFailed {
                operation: op.id.clone(),
                description: op.postcheck[i].description.clone(),
            });
        }
    }

    log.info(&format!("executed operation {}", op.id));
    Ok(OpOutcome::Executed)
}