migratrom 0.2.0

Declarative, self-verifying database migrations (core engine).
Documentation
//! Constraint builders: unique, check, primary key, foreign key.

use super::helpers::{check, require_capability, step};
use crate::error::Result;
use crate::sql::SqlDialect;
use crate::types::{ForeignKeySpec, Operation};

/// Add a named `UNIQUE` constraint on one or more columns.
pub fn add_unique(
    schema: &str,
    table: &str,
    constraint_name: &str,
    columns: &[String],
    dialect: &dyn SqlDialect,
) -> Result<Operation> {
    require_capability(
        dialect,
        dialect.capabilities().add_unique_constraints,
        "ADD UNIQUE constraints",
    )?;
    let alter_sql = format!(
        "ALTER TABLE {} ADD CONSTRAINT {} UNIQUE ({})",
        dialect.qualified(schema, table),
        dialect.quote_ident(constraint_name),
        dialect.quote_ident_list(columns)
    );

    Ok(Operation {
        id: format!("unique.{table}.{constraint_name}"),
        label: format!("Add unique constraint \"{constraint_name}\" on \"{table}\""),
        precheck: vec![check(
            format!("ensure unique constraint \"{constraint_name}\" does not exist on \"{table}\""),
            dialect.constraint_exists_sql(schema, table, constraint_name, true),
        )],
        execute: vec![step(
            format!("add unique constraint \"{constraint_name}\" on \"{table}\""),
            alter_sql,
        )],
        postcheck: vec![check(
            format!("verify unique constraint \"{constraint_name}\" exists on \"{table}\""),
            dialect.constraint_exists_sql(schema, table, constraint_name, false),
        )],
        outside_transaction: false,
    })
}

/// Add a named `CHECK` constraint to a table.
pub fn add_check(
    schema: &str,
    table: &str,
    constraint_name: &str,
    check_sql: &str,
    dialect: &dyn SqlDialect,
) -> Result<Operation> {
    require_capability(
        dialect,
        dialect.capabilities().add_check_constraints,
        "ADD CHECK constraints",
    )?;
    let alter_sql = format!(
        "ALTER TABLE {} ADD CONSTRAINT {} CHECK ({check_sql})",
        dialect.qualified(schema, table),
        dialect.quote_ident(constraint_name)
    );

    Ok(Operation {
        id: format!("check.{table}.{constraint_name}"),
        label: format!("Add check constraint \"{constraint_name}\" on \"{table}\""),
        precheck: vec![check(
            format!("ensure check constraint \"{constraint_name}\" does not exist on \"{table}\""),
            dialect.check_constraint_exists_sql(schema, table, constraint_name, true),
        )],
        execute: vec![step(
            format!("add check constraint \"{constraint_name}\" on \"{table}\""),
            alter_sql,
        )],
        postcheck: vec![check(
            format!("verify check constraint \"{constraint_name}\" exists on \"{table}\""),
            dialect.check_constraint_exists_sql(schema, table, constraint_name, false),
        )],
        outside_transaction: false,
    })
}

/// Add a named `PRIMARY KEY` constraint on existing columns.
pub fn add_primary_key(
    schema: &str,
    table: &str,
    constraint_name: &str,
    columns: &[String],
    dialect: &dyn SqlDialect,
) -> Result<Operation> {
    require_capability(
        dialect,
        dialect.capabilities().add_primary_key_constraints,
        "ADD PRIMARY KEY constraints",
    )?;
    let alter_sql = format!(
        "ALTER TABLE {} ADD CONSTRAINT {} PRIMARY KEY ({})",
        dialect.qualified(schema, table),
        dialect.quote_ident(constraint_name),
        dialect.quote_ident_list(columns)
    );

    Ok(Operation {
        id: format!("pk.{table}.{constraint_name}"),
        label: format!("Add primary key \"{constraint_name}\" on \"{table}\""),
        precheck: vec![check(
            format!("ensure primary key \"{constraint_name}\" does not exist on \"{table}\""),
            dialect.constraint_exists_sql(schema, table, constraint_name, true),
        )],
        execute: vec![step(
            format!("add primary key \"{constraint_name}\" on \"{table}\""),
            alter_sql,
        )],
        postcheck: vec![check(
            format!("verify primary key \"{constraint_name}\" exists on \"{table}\""),
            dialect.constraint_exists_sql(schema, table, constraint_name, false),
        )],
        outside_transaction: false,
    })
}

/// Add a named foreign-key constraint referencing another table in the same schema.
pub fn add_foreign_key(
    schema: &str,
    table: &str,
    spec: &ForeignKeySpec,
    dialect: &dyn SqlDialect,
) -> Result<Operation> {
    require_capability(
        dialect,
        dialect.capabilities().add_foreign_keys,
        "ADD FOREIGN KEY constraints",
    )?;
    let mut parts = vec![
        format!("ALTER TABLE {}", dialect.qualified(schema, table)),
        format!("  ADD CONSTRAINT {}", dialect.quote_ident(&spec.name)),
        format!(
            "  FOREIGN KEY ({})",
            dialect.quote_ident_list(&spec.columns)
        ),
        format!(
            "  REFERENCES {} ({})",
            dialect.qualified(schema, &spec.references.table),
            dialect.quote_ident_list(&spec.references.columns)
        ),
    ];
    if let Some(on_delete) = spec.on_delete {
        parts.push(format!("  ON DELETE {}", on_delete.as_sql()));
    }
    if let Some(on_update) = spec.on_update {
        parts.push(format!("  ON UPDATE {}", on_update.as_sql()));
    }
    let alter_sql = parts.join("\n");

    Ok(Operation {
        id: format!("fk.{table}.{}", spec.name),
        label: format!("Add foreign key \"{}\" on \"{table}\"", spec.name),
        precheck: vec![check(
            format!(
                "ensure foreign key \"{}\" does not exist on \"{table}\"",
                spec.name
            ),
            dialect.constraint_exists_sql(schema, table, &spec.name, true),
        )],
        execute: vec![step(
            format!("add foreign key \"{}\" on \"{table}\"", spec.name),
            alter_sql,
        )],
        postcheck: vec![check(
            format!("verify foreign key \"{}\" exists on \"{table}\"", spec.name),
            dialect.constraint_exists_sql(schema, table, &spec.name, false),
        )],
        outside_transaction: false,
    })
}