migratrom 0.2.0

Declarative, self-verifying database migrations (core engine).
Documentation
//! History-table management: schema, applied-id/record reads, and recording.

use std::collections::{HashMap, HashSet};

use crate::checksum::{canonical_encode, checksum};
use crate::db::Db;
use crate::error::Result;
use crate::sql::SqlDialect;
use crate::types::Migration;

/// Default history table name, shared with the Swift and TypeScript siblings.
pub const DEFAULT_HISTORY_TABLE: &str = "__migratron_history__";

/// A stored history row, used to checksum-verify already-applied migrations.
#[derive(Clone, Debug)]
pub struct AppliedRecord {
    /// Digest of the operation list recorded when the migration was applied.
    pub checksum: String,
    /// Canonical operation-encoding hex stored at apply time.
    pub operations: Option<String>,
}

/// Create the history table if it does not already exist.
pub async fn ensure_history_table(db: &dyn Db, name: &str, dialect: &dyn SqlDialect) -> Result<()> {
    db.execute(&dialect.create_history_table_sql(name)).await
}

/// Read the set of already-applied migration ids.
pub async fn read_applied_ids(
    db: &dyn Db,
    name: &str,
    dialect: &dyn SqlDialect,
) -> Result<HashSet<i64>> {
    let rows = db
        .query_rows(&format!("SELECT id FROM {}", dialect.quote_ident(name)))
        .await?;
    Ok(rows.iter().filter_map(|r| r.i64_at(0)).collect())
}

/// Read the full applied records keyed by id (id, checksum, operations).
pub async fn read_applied_records(
    db: &dyn Db,
    name: &str,
    dialect: &dyn SqlDialect,
) -> Result<HashMap<i64, AppliedRecord>> {
    let rows = db
        .query_rows(&format!(
            "SELECT id, checksum, operations FROM {}",
            dialect.quote_ident(name)
        ))
        .await?;
    let mut map = HashMap::with_capacity(rows.len());
    for row in rows {
        if let Some(id) = row.i64_at(0) {
            map.insert(
                id,
                AppliedRecord {
                    checksum: row.str_at(1).unwrap_or_default(),
                    operations: row.str_at(2),
                },
            );
        }
    }
    Ok(map)
}

/// Insert a history row recording an applied migration.
pub async fn record_migration(
    db: &dyn Db,
    name: &str,
    migration: &Migration,
    dialect: &dyn SqlDialect,
) -> Result<()> {
    let operations_hex = hex::encode(canonical_encode(&migration.operations));
    let digest = checksum(&migration.operations);
    let parent = match migration.parent_id {
        Some(p) => p.to_string(),
        None => "NULL".to_string(),
    };
    let sql = format!(
        "INSERT INTO {} (id, parent_id, checksum, operations) VALUES ({}, {}, {}, {})",
        dialect.quote_ident(name),
        migration.id,
        parent,
        dialect.quote_literal(&digest),
        dialect.quote_literal(&operations_hex),
    );
    db.execute(&sql).await
}