migratrom 0.2.0

Declarative, self-verifying database migrations (core engine).
Documentation
//! Index operation builders.
//!
//! Builders in this file construct self-verifying [`Operation`] values for
//! index DDL, including the PostgreSQL-specific concurrent-index path.

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

/// Create a btree index on one or more table columns.
///
/// With [`CreateIndexOptions::concurrently`], emits `CREATE INDEX CONCURRENTLY`
/// and marks the operation [`Operation::outside_transaction`].
pub fn create_index(
    schema: &str,
    table: &str,
    index_name: &str,
    columns: &[String],
    options: &CreateIndexOptions,
    dialect: &dyn SqlDialect,
) -> Result<Operation> {
    let concurrently = options.concurrently;
    if concurrently {
        require_capability(
            dialect,
            dialect.capabilities().concurrent_indexes,
            "CREATE INDEX CONCURRENTLY",
        )?;
    }
    let create_sql = dialect.create_index_sql(schema, table, index_name, columns, concurrently);
    let label_suffix = if concurrently { " concurrently" } else { "" };

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