migratrom 0.2.0

Declarative, self-verifying database migrations (core engine).
Documentation
//! Table and column shape operation builders.
//!
//! This file covers table creation, column addition, and renames, wrapping each
//! DDL statement with catalog prechecks and postchecks.

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

/// Create a table with the given columns and an optional inline primary key.
///
/// Columns default to `NOT NULL` unless [`ColumnDef::nullable`] is set.
pub fn create_table(
    schema: &str,
    table: &str,
    columns: &[ColumnDef],
    primary_key: Option<&PrimaryKey>,
    dialect: &dyn SqlDialect,
) -> Result<Operation> {
    let mut lines = vec![dialect.render_column_list(columns)];
    if let Some(pk) = primary_key {
        lines.push(format!(
            "PRIMARY KEY ({})",
            dialect.quote_ident_list(&pk.columns)
        ));
    }
    let create_sql = format!(
        "CREATE TABLE {} (\n  {}\n)",
        dialect.qualified(schema, table),
        lines.join(",\n  ")
    );

    Ok(Operation {
        id: format!("table.{table}"),
        label: format!("Create table \"{table}\""),
        precheck: vec![check(
            format!("ensure table \"{table}\" does not exist"),
            dialect.table_exists_sql(schema, table, true),
        )],
        execute: vec![step(format!("create table \"{table}\""), create_sql)],
        postcheck: vec![check(
            format!("verify table \"{table}\" exists"),
            dialect.table_exists_sql(schema, table, false),
        )],
        outside_transaction: false,
    })
}

/// Add a column to an existing table.
pub fn add_column(
    schema: &str,
    table: &str,
    col: &ColumnDef,
    dialect: &dyn SqlDialect,
) -> Result<Operation> {
    let alter_sql = format!(
        "ALTER TABLE {} ADD COLUMN {}",
        dialect.qualified(schema, table),
        dialect.render_column_def(col)
    );

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

/// Rename a table within a schema.
pub fn rename_table(
    schema: &str,
    from: &str,
    to: &str,
    dialect: &dyn SqlDialect,
) -> Result<Operation> {
    let alter_sql = format!(
        "ALTER TABLE {} RENAME TO {}",
        dialect.qualified(schema, from),
        dialect.quote_ident(to)
    );

    Ok(Operation {
        id: format!("rename_table.{from}_to_{to}"),
        label: format!("Rename table \"{from}\" to \"{to}\""),
        precheck: vec![
            check(
                format!("ensure table \"{from}\" exists"),
                dialect.table_exists_sql(schema, from, false),
            ),
            check(
                format!("ensure table \"{to}\" does not exist"),
                dialect.table_exists_sql(schema, to, true),
            ),
        ],
        execute: vec![step(
            format!("rename table \"{from}\" to \"{to}\""),
            alter_sql,
        )],
        postcheck: vec![check(
            format!("verify table \"{to}\" exists"),
            dialect.table_exists_sql(schema, to, false),
        )],
        outside_transaction: false,
    })
}

/// Rename a column within a table.
pub fn rename_column(
    schema: &str,
    table: &str,
    from: &str,
    to: &str,
    dialect: &dyn SqlDialect,
) -> Result<Operation> {
    let alter_sql = format!(
        "ALTER TABLE {} RENAME COLUMN {} TO {}",
        dialect.qualified(schema, table),
        dialect.quote_ident(from),
        dialect.quote_ident(to)
    );

    Ok(Operation {
        id: format!("rename_column.{table}.{from}_to_{to}"),
        label: format!("Rename column \"{from}\" to \"{to}\" on \"{table}\""),
        precheck: vec![
            check(
                format!("ensure column \"{from}\" exists on \"{table}\""),
                dialect.column_exists_sql(schema, table, from, false),
            ),
            check(
                format!("ensure column \"{to}\" does not exist on \"{table}\""),
                dialect.column_exists_sql(schema, table, to, true),
            ),
        ],
        execute: vec![step(
            format!("rename column \"{from}\" to \"{to}\" on \"{table}\""),
            alter_sql,
        )],
        postcheck: vec![check(
            format!("verify column \"{to}\" exists on \"{table}\""),
            dialect.column_exists_sql(schema, table, to, false),
        )],
        outside_transaction: false,
    })
}