midas-migrate-cli 0.8.1

Do painless migration 🦀
Documentation
//! Schema-driven development migrations and offline diffs.

use std::path::{
  Path,
  PathBuf,
};

use anyhow::{
  Context as _,
  Result,
};
use clap::{
  Arg,
  ArgMatches,
  Command,
};
use midas_schema::schema::plan::Plan;
use midas_schema::schema::{
  self,
  ir,
  state,
};

use crate::commands::{
  source,
  Context,
};

/// Build the `migrate dev` subcommand.
pub fn dev_command() -> Command {
  Command::new("dev")
    .about("Diff the schema source against .midas/state.json and generate a migration")
    .arg(
      Arg::new("name")
        .long("name")
        .value_name("name")
        .help("Migration name")
        .default_value("schema")
        .num_args(1),
    )
    .arg(
      Arg::new("schema")
        .long("schema")
        .value_name("path")
        .help("Schema file or directory (defaults to the project schema source)")
        .num_args(1),
    )
    .arg(
      Arg::new("state")
        .long("state")
        .value_name("path")
        .help("State snapshot path")
        .num_args(1),
    )
    .arg(
      Arg::new("create-only")
        .long("create-only")
        .help("Write the migration without applying it or updating state")
        .action(clap::ArgAction::SetTrue),
    )
    .arg(
      Arg::new("force")
        .long("force")
        .help("Ignore drift between the state snapshot and the shadow database")
        .action(clap::ArgAction::SetTrue),
    )
    .arg(
      Arg::new("accept-data-loss")
        .long("accept-data-loss")
        .help("Allow destructive or irreversible changes")
        .action(clap::ArgAction::SetTrue),
    )
    .arg(
      Arg::new("json")
        .long("json")
        .help("Emit a machine-readable plan summary")
        .action(clap::ArgAction::SetTrue),
    )
}

/// Build the `migrate diff` subcommand.
pub fn diff_command() -> Command {
  Command::new("diff")
    .about("Diff two schema sources without touching a database")
    .arg(
      Arg::new("from")
        .long("from")
        .value_name("path")
        .help("Current schema or state snapshot")
        .required(true)
        .num_args(1),
    )
    .arg(
      Arg::new("to")
        .long("to")
        .value_name("path")
        .help("Desired schema or state snapshot")
        .required(true)
        .num_args(1),
    )
    .arg(
      Arg::new("script")
        .long("script")
        .help("Print UP/DOWN SQL instead of a summary")
        .action(clap::ArgAction::SetTrue),
    )
    .arg(
      Arg::new("json")
        .long("json")
        .help("Emit a machine-readable plan summary")
        .action(clap::ArgAction::SetTrue),
    )
}

/// Dispatch `dev` and `diff`.
pub fn dispatch(name: &str, matches: &ArgMatches, context: &Context) -> Result<()> {
  match name {
    "dev" => dev(matches, context),
    "diff" => diff(matches),
    other => anyhow::bail!("unknown development migration command `{other}`"),
  }
}

fn dev(matches: &ArgMatches, context: &Context) -> Result<()> {
  let schema_path = source::resolve(matches.get_one::<String>("schema").map(String::as_str))?;
  let state_path = matches
    .get_one::<String>("state")
    .map(PathBuf::from)
    .unwrap_or_else(state::default_path);
  let desired = schema::load_ir(&schema_path)?;
  let snapshot = state::read_optional(&state_path)?;
  let mut current = snapshot
    .as_ref()
    .map(|snapshot| snapshot.schema.clone())
    .unwrap_or_else(ir::Schema::default);
  let create_only = matches.get_flag("create-only");
  let _shadow = if !create_only && !context.dry_run && is_postgres(context)? {
    let shadow = schema::shadow::ShadowDb::create(&context.config)?;
    shadow.replay()?;
    let shadow_schema = schema::introspect::introspect_with(
      &shadow.config(),
      &context.config.managed.schemas,
      &context.config.managed.ignore_objects,
      false,
    )?
    .schema;
    let live_schema = schema::introspect::introspect_with(
      &context.config,
      &context.config.managed.schemas,
      &context.config.managed.ignore_objects,
      false,
    )?
    .schema;
    let drift = Plan::between(&live_schema, &shadow_schema);
    if !drift.is_empty() && !matches.get_flag("force") {
      let summary = drift
        .changes()
        .iter()
        .map(|change| change.summary())
        .collect::<Vec<_>>()
        .join("; ");
      anyhow::bail!(
        "drift detected between the live database and the shadow database: {summary}; pass --force to ignore"
      );
    }
    current = shadow_schema;
    Some(shadow)
  } else {
    None
  };
  let plan = Plan::try_between(&current, &desired)?;

  if plan.is_empty() {
    if matches.get_flag("json") {
      println!(
        "{}",
        serde_json::to_string(&serde_json::json!({
          "changes": 0,
          "migration": serde_json::Value::Null,
        }))?
      );
    } else {
      println!("No schema changes.");
    }
    return Ok(());
  }

  let accept = matches.get_flag("accept-data-loss");
  if plan.requires_data_loss() && !accept {
    let mut message = String::from("refusing destructive or irreversible changes:\n");
    for change in plan.changes() {
      let meta = change.meta();
      if meta.destructive || meta.irreversible {
        message.push_str(&format!("  - {}\n", change.summary()));
      }
    }
    message.push_str("pass --accept-data-loss to continue");
    anyhow::bail!(message);
  }

  if context.dry_run {
    if matches.get_flag("json") {
      println!("{}", serde_json::to_string(&plan.summary())?);
    } else {
      print!("{}", schema::emit::alter::migration(&plan));
    }
    return Ok(());
  }

  let name = matches
    .get_one::<String>("name")
    .map(String::as_str)
    .unwrap_or("schema");
  let version = midas::migration::create_migration_file(&context.config.migrations_dir, name, false)
    .context("failed to create migration file")?;
  let migration_path = find_migration(&context.config.migrations_dir, version)?;
  std::fs::write(&migration_path, schema::emit::alter::migration(&plan))?;

  if plan.requires_no_transaction() {
    println!("Migration disables the transaction wrapper.");
  }
  println!(
    "Created migration `{}` with {} change(s).",
    migration_path.to_string_lossy(),
    plan.changes().len()
  );

  if create_only {
    if matches.get_flag("json") {
      println!(
        "{}",
        serde_json::to_string(&serde_json::json!({
          "changes": plan.changes().len(),
          "migration": migration_path.to_string_lossy(),
          "applied": false,
        }))?
      );
    }
    return Ok(());
  }

  crate::commands::migrate::with_migrator(context, false, |migrator| migrator.up(None))
    .context("failed to apply the generated migration")?;
  state::write(&state_path, &desired)?;

  if matches.get_flag("json") {
    println!(
      "{}",
      serde_json::to_string(&serde_json::json!({
        "changes": plan.changes().len(),
        "migration": migration_path.to_string_lossy(),
        "applied": true,
      }))?
    );
  } else {
    println!("Applied migration and updated {}.", state_path.to_string_lossy());
  }
  Ok(())
}

fn diff(matches: &ArgMatches) -> Result<()> {
  let from = matches.get_one::<String>("from").context("--from is required")?;
  let to = matches.get_one::<String>("to").context("--to is required")?;
  let current = load_source(Path::new(from))?;
  let desired = load_source(Path::new(to))?;
  let plan = Plan::try_between(&current, &desired)?;

  if matches.get_flag("script") {
    print!("{}", schema::emit::alter::migration(&plan));
    return Ok(());
  }
  if matches.get_flag("json") {
    println!("{}", serde_json::to_string(&plan.summary())?);
    return Ok(());
  }
  if plan.is_empty() {
    println!("No schema changes.");
    return Ok(());
  }
  for change in plan.changes() {
    let meta = change.meta();
    let marker = if meta.irreversible {
      "irreversible"
    } else if meta.destructive {
      "destructive"
    } else {
      "safe"
    };
    println!("[{marker}] {}", change.summary());
  }
  Ok(())
}

fn load_source(path: &Path) -> Result<ir::Schema> {
  match path.extension().and_then(|extension| extension.to_str()) {
    Some("json") => Ok(state::read(path)?.schema),
    Some("toml") | Some("midas") => Ok(schema::load_ir(path)?),
    _ => anyhow::bail!(
      "unsupported schema source `{}`; expected .toml, .midas, or .json",
      path.to_string_lossy()
    ),
  }
}

fn find_migration(dir: &Path, version: i64) -> Result<PathBuf> {
  let prefix = format!("{version:013}_");
  let mut matches = std::fs::read_dir(dir)?
    .filter_map(|entry| entry.ok())
    .map(|entry| entry.path())
    .filter(|path| {
      path
        .file_name()
        .and_then(|name| name.to_str())
        .is_some_and(|name| name.starts_with(&prefix) && name.ends_with(".sql"))
    })
    .collect::<Vec<_>>();
  matches.sort();
  matches
    .into_iter()
    .next()
    .ok_or_else(|| anyhow::anyhow!("generated migration not found in `{}`", dir.to_string_lossy()))
}

fn is_postgres(context: &Context) -> Result<bool> {
  let url = context.config.require_database_url()?;
  Ok(matches!(
    midas::sequel::DatabaseEngine::from_url(url)?,
    midas::sequel::DatabaseEngine::Postgres | midas::sequel::DatabaseEngine::CockroachDb
  ))
}

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

  #[test]
  fn command_group_has_dev_and_diff() {
    assert_eq!(dev_command().get_name(), "dev");
    assert_eq!(diff_command().get_name(), "diff");
  }
}