migratrom 0.2.0

Declarative, self-verifying database migrations (core engine).
Documentation
//! Escape hatch for fully authored SQL operations.
//!
//! Raw operations still participate in Migratrom's normal self-verifying
//! pipeline: optional prechecks, required execute steps, and required postchecks.

use crate::error::{MigratromError, Result};
use crate::types::{Check, ExecuteStep, Operation};

/// A precheck/postcheck for [`raw_sql`]; `description` defaults to the SQL text.
#[derive(Clone, Debug)]
pub struct RawCheck {
    /// Optional human-readable description; defaults to [`RawCheck::sql`].
    pub description: Option<String>,
    /// Boolean SQL probe that must return one row and one boolean column.
    pub sql: String,
}

impl RawCheck {
    /// Create a raw boolean check whose description defaults to its SQL.
    pub fn new(sql: impl Into<String>) -> Self {
        Self {
            description: None,
            sql: sql.into(),
        }
    }
}

/// An execute step for [`raw_sql`]; `description` defaults to the SQL text.
#[derive(Clone, Debug)]
pub struct RawStep {
    /// Optional human-readable description; defaults to [`RawStep::sql`].
    pub description: Option<String>,
    /// Side-effecting SQL statement to execute.
    pub sql: String,
}

impl RawStep {
    /// Create a raw execute step whose description defaults to its SQL.
    pub fn new(sql: impl Into<String>) -> Self {
        Self {
            description: None,
            sql: sql.into(),
        }
    }
}

/// Input for [`raw_sql`].
#[derive(Clone, Debug, Default)]
pub struct RawSqlInput {
    /// Human-readable label, also the default id slug source.
    pub label: String,
    /// Optional boolean probes run before execute.
    pub precheck: Vec<RawCheck>,
    /// One or more side-effecting statements (at least one required).
    pub execute: Vec<RawStep>,
    /// Boolean probes that must pass after execute (at least one required).
    pub postcheck: Vec<RawCheck>,
    /// Stable operation id; defaults to a slug of [`RawSqlInput::label`].
    pub id: Option<String>,
}

/// Build a fully specified [`Operation`] from raw SQL using the same
/// precheck → execute → postcheck pipeline as built-in builders.
///
/// Requires at least one execute step and one postcheck.
pub fn raw_sql(input: RawSqlInput) -> Result<Operation> {
    if input.execute.is_empty() {
        return Err(MigratromError::Config(
            "rawSql requires at least one execute step".to_string(),
        ));
    }
    if input.postcheck.is_empty() {
        return Err(MigratromError::Config(
            "rawSql requires at least one postcheck step".to_string(),
        ));
    }

    let id = input.id.unwrap_or_else(|| slugify(&input.label));
    Ok(Operation {
        id,
        label: input.label,
        precheck: input.precheck.into_iter().map(normalize_check).collect(),
        execute: input.execute.into_iter().map(normalize_step).collect(),
        postcheck: input.postcheck.into_iter().map(normalize_check).collect(),
        outside_transaction: false,
    })
}

fn normalize_check(c: RawCheck) -> Check {
    Check {
        description: c.description.unwrap_or_else(|| c.sql.clone()),
        sql: c.sql,
    }
}

fn normalize_step(s: RawStep) -> ExecuteStep {
    ExecuteStep {
        description: s.description.unwrap_or_else(|| s.sql.clone()),
        sql: s.sql,
    }
}

/// Lowercase, collapse runs of non-alphanumerics to `.`, trim leading/trailing `.`.
fn slugify(label: &str) -> String {
    let mut out = String::with_capacity(label.len());
    let mut prev_dot = false;
    for ch in label.chars() {
        if ch.is_ascii_alphanumeric() {
            out.push(ch.to_ascii_lowercase());
            prev_dot = false;
        } else if !prev_dot {
            out.push('.');
            prev_dot = true;
        }
    }
    out.trim_matches('.').to_string()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn slugifies_label_into_id() {
        let op = raw_sql(RawSqlInput {
            label: "Create Sequence raw_seq!".to_string(),
            execute: vec![RawStep::new("CREATE SEQUENCE public.raw_seq")],
            postcheck: vec![RawCheck::new(
                "SELECT to_regclass('\"public\".\"raw_seq\"') IS NOT NULL",
            )],
            ..Default::default()
        })
        .unwrap();
        assert_eq!(op.id, "create.sequence.raw.seq");
        assert_eq!(op.execute[0].description, op.execute[0].sql);
    }

    #[test]
    fn requires_execute_and_postcheck() {
        assert!(raw_sql(RawSqlInput {
            label: "noop".to_string(),
            ..Default::default()
        })
        .is_err());
    }
}