midas-migrate-cli 0.8.1

Do painless migration 🦀
Documentation
//! `midas faker` — deterministic seed data for an existing database.

use std::path::PathBuf;

use anyhow::{
  bail,
  Context as _,
  Result,
};
use clap::{
  Arg,
  ArgAction,
  ArgMatches,
  Command,
};
use midas::config::ProcessEnv;
use midas::seed::{
  check_production,
  run,
  RunOptions,
  SeedFile,
};

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

/// Build the `faker` subcommand.
pub fn command() -> Command {
  Command::new("faker")
    .visible_alias("seed")
    .about("Apply deterministic seed data to the configured database")
    .arg(
      Arg::new("seed-file")
        .long("seed-file")
        .value_name("path")
        .help("Seed file (defaults to [seed].file or seed.toml)")
        .num_args(1),
    )
    .arg(
      Arg::new("table")
        .long("table")
        .value_name("name")
        .help("Seed only this table (repeatable)")
        .num_args(1)
        .action(ArgAction::Append),
    )
    .arg(
      Arg::new("rows")
        .long("rows")
        .value_name("n")
        .help("Override generated row counts and row limits")
        .num_args(1)
        .value_parser(clap::value_parser!(u64)),
    )
    .arg(
      Arg::new("seed")
        .long("seed")
        .value_name("n")
        .help("Master seed")
        .num_args(1)
        .value_parser(clap::value_parser!(u64)),
    )
    .arg(
      Arg::new("reset")
        .long("reset")
        .help("Clear selected tables before inserting")
        .action(ArgAction::SetTrue),
    )
    .arg(
      Arg::new("json")
        .long("json")
        .help("Emit a machine-readable summary")
        .action(ArgAction::SetTrue),
    )
    .arg(
      Arg::new("yes")
        .long("yes")
        .help("Confirm destructive operations")
        .action(ArgAction::SetTrue),
    )
    .arg(
      Arg::new("allow-production")
        .long("allow-production")
        .help("Allow running against production-like environments")
        .action(ArgAction::SetTrue),
    )
}

/// Register the command.
pub fn register(app: Command) -> Command {
  app.subcommand(command())
}

/// Whether this module owns the subcommand name.
pub fn owns(name: &str) -> bool {
  matches!(name, "faker" | "seed")
}

/// Dispatch the command.
pub fn dispatch(_name: &str, matches: &ArgMatches, context: &Context) -> Result<()> {
  let json = matches.get_flag("json");
  match execute(matches, context) {
    Ok(()) => Ok(()),
    Err(error) => {
      if json {
        println!("{}", serde_json::json!({ "error": error.to_string() }));
      }
      Err(error)
    },
  }
}

fn execute(matches: &ArgMatches, context: &Context) -> Result<()> {
  let allow_production = matches.get_flag("allow-production");
  check_production(&ProcessEnv, allow_production, context.dry_run)?;

  let reset = matches.get_flag("reset");
  if reset && !matches.get_flag("yes") {
    bail!("--reset requires --yes");
  }

  let seed_path = seed_path(matches, context);
  let seed = SeedFile::load(&seed_path, &context.config.seed)
    .with_context(|| format!("failed to load seed file `{}`", seed_path.to_string_lossy()))?;

  let resolved = seed_meta::live(&context.config)?;
  let dialect = seed_meta::dialect(&context.config)?;

  let tables: Vec<String> = matches
    .get_many::<String>("table")
    .map(|values| values.cloned().collect())
    .unwrap_or_default();
  let rows = matches.get_one::<u64>("rows").copied();
  let master_seed = matches.get_one::<u64>("seed").copied();

  let mut backend = midas::seed::connect(&context.config)?;
  let summary = run(
    Some(backend.as_mut()),
    &RunOptions {
      command: "faker",
      file: &seed,
      schema: &resolved.schema,
      settings: &context.config.seed,
      managed_schemas: &context.config.managed.schemas,
      default_schema: context.config.search_path.as_deref(),
      table_filters: &tables,
      rows_override: rows,
      reset,
      skip_existing: false,
      dry_run: context.dry_run,
      no_lock: context.no_lock,
      master_seed,
      dialect,
      warnings: &resolved.warnings,
    },
  )?;

  if matches.get_flag("json") {
    println!("{}", summary.to_json()?);
  } else {
    print_summary(&summary);
  }
  Ok(())
}

fn seed_path(matches: &ArgMatches, context: &Context) -> PathBuf {
  matches
    .get_one::<String>("seed-file")
    .map(PathBuf::from)
    .unwrap_or_else(|| context.config.seed.file.clone())
}

fn print_summary(summary: &midas::seed::Summary) {
  println!("Seed: {}", summary.seed);
  println!("Reference time: {}", summary.reference_time);
  for table in &summary.tables {
    println!("  {}: {} {} row(s)", table.table, table.rows, table.mode);
  }
  for table in &summary.reset {
    println!("reset {table}");
  }
  for table in &summary.skipped {
    println!("skipped {table}");
  }
  for warning in &summary.warnings {
    eprintln!("warning: {warning}");
  }
  if summary.dry_run {
    if let Some(sql) = &summary.sql {
      print!("{sql}");
    }
    println!("Dry run: wrote nothing.");
  } else {
    println!("Seeded {} row(s).", summary.rows);
  }
}

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

  #[test]
  fn owns_faker_and_seed_alias() {
    assert!(owns("faker"));
    assert!(owns("seed"));
    assert!(!owns("setup"));
  }

  #[test]
  fn command_registers_expected_flags() {
    let command = command();
    let names: Vec<&str> = command
      .get_arguments()
      .map(|argument| argument.get_id().as_str())
      .collect();
    for expected in [
      "seed-file",
      "table",
      "rows",
      "seed",
      "reset",
      "json",
      "yes",
      "allow-production",
    ] {
      assert!(names.contains(&expected), "missing `{expected}`");
    }
  }
}