migratrom 0.2.0

Declarative, self-verifying database migrations (core engine).
Documentation
//! Core data model: migrations, operations, and the values that describe schema changes.
//!
//! These types are intentionally plain data. Builders in [`crate::operations`]
//! assemble [`Operation`]s; the runner in [`crate::runner`] applies [`Migration`]s.

/// A boolean-returning SQL probe. Must yield one row / one column / boolean.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Check {
    /// Human-readable intent, e.g. `ensure table "user" does not exist`.
    pub description: String,
    /// Boolean SQL probe that must yield one row and one boolean column.
    pub sql: String,
}

impl Check {
    /// Create a named boolean SQL probe.
    pub fn new(description: impl Into<String>, sql: impl Into<String>) -> Self {
        Self {
            description: description.into(),
            sql: sql.into(),
        }
    }
}

/// A side-effecting DDL/DML statement.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ExecuteStep {
    /// Human-readable description emitted to the migration logger.
    pub description: String,
    /// Side-effecting DDL or DML statement to execute.
    pub sql: String,
}

impl ExecuteStep {
    /// Create a named side-effecting SQL statement.
    pub fn new(description: impl Into<String>, sql: impl Into<String>) -> Self {
        Self {
            description: description.into(),
            sql: sql.into(),
        }
    }
}

/// A single, named, self-verifying unit of change.
///
/// The runner skips an operation when every [`Operation::postcheck`] already
/// passes, making operations idempotent.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Operation {
    /// Stable logical id, e.g. `table.user`, `fk.post.post_author_id_fkey`.
    pub id: String,
    /// Human-readable label, e.g. `Create table "user"`.
    pub label: String,
    /// Checks that must pass before the execute steps run.
    pub precheck: Vec<Check>,
    /// DDL or DML statements that make the change.
    pub execute: Vec<ExecuteStep>,
    /// Checks that must pass after execution; all passing checks skip the operation.
    pub postcheck: Vec<Check>,
    /// When `true`, run outside the per-migration transaction (required for
    /// `CREATE INDEX CONCURRENTLY`, which cannot run inside a transaction).
    pub outside_transaction: bool,
}

/// Options for `create_index`.
#[derive(Clone, Debug, Default)]
pub struct CreateIndexOptions {
    /// Emit `CREATE INDEX CONCURRENTLY` and run outside the migration transaction.
    pub concurrently: bool,
}

/// A column definition used by `create_table` and `add_column`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ColumnDef {
    /// Unquoted column name.
    pub name: String,
    /// Raw SQL type, authored by the developer. Emitted verbatim, e.g. `"text"`.
    pub type_sql: String,
    /// Defaults to `false` (column rendered `NOT NULL`).
    pub nullable: bool,
    /// Full default clause INCLUDING the `DEFAULT` keyword, e.g. `"DEFAULT (now())"`.
    pub default_sql: Option<String>,
}

impl ColumnDef {
    /// A `NOT NULL` column with no default.
    pub fn new(name: impl Into<String>, type_sql: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            type_sql: type_sql.into(),
            nullable: false,
            default_sql: None,
        }
    }

    /// Set whether the column accepts `NULL` values.
    pub fn nullable(mut self, nullable: bool) -> Self {
        self.nullable = nullable;
        self
    }

    /// Set the full SQL default clause, including the `DEFAULT` keyword.
    pub fn default_sql(mut self, default_sql: impl Into<String>) -> Self {
        self.default_sql = Some(default_sql.into());
        self
    }
}

/// A composite primary key over existing column names.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PrimaryKey {
    /// Column names that form the primary key, in key order.
    pub columns: Vec<String>,
}

/// Referential action for foreign keys.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ReferentialAction {
    /// Propagate the change to rows that reference it.
    Cascade,
    /// Reject the change while referencing rows exist.
    Restrict,
    /// Set referencing columns to `NULL`.
    SetNull,
    /// Use the database's default no-action behavior.
    NoAction,
    /// Set referencing columns to their default values.
    SetDefault,
}

impl ReferentialAction {
    /// Return this action's SQL spelling.
    pub fn as_sql(self) -> &'static str {
        match self {
            ReferentialAction::Cascade => "CASCADE",
            ReferentialAction::Restrict => "RESTRICT",
            ReferentialAction::SetNull => "SET NULL",
            ReferentialAction::NoAction => "NO ACTION",
            ReferentialAction::SetDefault => "SET DEFAULT",
        }
    }
}

/// The relation referenced by a foreign key.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ForeignKeyReference {
    /// Referenced table name in the same schema as the foreign key.
    pub table: String,
    /// Referenced column names, in key order.
    pub columns: Vec<String>,
}

/// A named foreign-key constraint specification.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ForeignKeySpec {
    /// Constraint name.
    pub name: String,
    /// Columns on the table that form the foreign key.
    pub columns: Vec<String>,
    /// Referenced relation and columns.
    pub references: ForeignKeyReference,
    /// Optional action when a referenced row is deleted.
    pub on_delete: Option<ReferentialAction>,
    /// Optional action when a referenced row is updated.
    pub on_update: Option<ReferentialAction>,
}

/// A migration: a node in the dependency DAG carrying ordered operations.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Migration {
    /// Unique, stable migration identifier.
    pub id: i64,
    /// `None` marks a root migration.
    pub parent_id: Option<i64>,
    /// Operations to execute in order when this migration is pending.
    pub operations: Vec<Operation>,
}

impl Migration {
    /// Create a migration with its parent and ordered operations.
    pub fn new(id: i64, parent_id: Option<i64>, operations: Vec<Operation>) -> Self {
        Self {
            id,
            parent_id,
            operations,
        }
    }
}

/// What an SQL dialect can express. Builders gate on these flags.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct DialectCapabilities {
    /// Whether the dialect supports enum types and values.
    pub enum_types: bool,
    /// Whether the dialect supports standalone sequences.
    pub sequences: bool,
    /// Whether the dialect supports materialized views.
    pub materialized_views: bool,
    /// Whether the dialect supports extensions.
    pub extensions: bool,
    /// Whether the dialect supports concurrent index creation.
    pub concurrent_indexes: bool,
    /// Whether the dialect supports named schemas.
    pub schemas: bool,
    /// Whether the dialect supports advisory locking.
    pub advisory_locks: bool,
    /// Whether the dialect supports adding check constraints.
    pub add_check_constraints: bool,
    /// Whether the dialect supports adding primary-key constraints.
    pub add_primary_key_constraints: bool,
    /// Whether the dialect supports adding unique constraints.
    pub add_unique_constraints: bool,
    /// Whether the dialect supports adding foreign-key constraints.
    pub add_foreign_keys: bool,
    /// Whether the dialect supports `ALTER COLUMN SET DEFAULT`.
    pub alter_column_default: bool,
    /// Whether the dialect supports `ALTER COLUMN SET NOT NULL`.
    pub alter_column_not_null: bool,
}

/// The result of applying migrations.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct ApplyResult {
    /// Migration ids applied in this run, in execution order.
    pub applied: Vec<i64>,
    /// Operation ids skipped because their postchecks already passed.
    pub skipped_ops: Vec<String>,
}