use std::path::{
Path,
PathBuf,
};
use anyhow::{
bail,
Context as _,
Result,
};
use clap::{
Arg,
ArgAction,
ArgMatches,
Command,
};
use midas::commander::{
Migrator,
MigratorOptions,
};
use midas::config::ProcessEnv;
use midas::seed::{
check_production,
run,
RunOptions,
SeedFile,
Summary,
};
use midas::{
migration,
sequel,
};
use midas_schema::schema::plan::Plan;
use midas_schema::schema::{
self,
state,
};
use serde::Serialize;
use crate::commands::{
db_lifecycle,
seed_meta,
source,
Context,
};
pub fn command() -> Command {
Command::new("setup")
.about("Create the database, apply migrations or schema DDL, and seed it")
.arg(
Arg::new("schema")
.long("schema")
.value_name("path")
.help("Schema source (defaults to the project schema source)")
.num_args(1),
)
.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("from")
.long("from")
.value_name("source")
.help("auto, migrations, or schema")
.default_value("auto")
.num_args(1),
)
.arg(
Arg::new("no-seed")
.long("no-seed")
.help("Stop after the schema phase")
.action(ArgAction::SetTrue),
)
.arg(
Arg::new("state")
.long("state")
.value_name("path")
.help("State snapshot path written after schema-source setup")
.num_args(1),
)
.arg(
Arg::new("no-state")
.long("no-state")
.help("Do not refresh the state snapshot")
.action(ArgAction::SetTrue),
)
.arg(
Arg::new("reset")
.long("reset")
.help("Clear selected tables before seeding")
.action(ArgAction::SetTrue),
)
.arg(
Arg::new("seed")
.long("seed")
.value_name("n")
.help("Master seed")
.num_args(1)
.value_parser(clap::value_parser!(u64)),
)
.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("accept-data-loss")
.long("accept-data-loss")
.help("Allow destructive schema changes")
.action(ArgAction::SetTrue),
)
.arg(
Arg::new("allow-production")
.long("allow-production")
.help("Allow running against production-like environments")
.action(ArgAction::SetTrue),
)
}
pub fn register(app: Command) -> Command {
app.subcommand(command())
}
pub fn owns(name: &str) -> bool {
name == "setup"
}
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)
},
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum SourceMode {
Migrations,
Schema,
}
impl SourceMode {
fn as_str(self) -> &'static str {
match self {
Self::Migrations => "migrations",
Self::Schema => "schema",
}
}
}
#[derive(Debug, Serialize)]
struct SetupSummary {
command: &'static str,
dry_run: bool,
source: &'static str,
database_created: bool,
seed: Option<Summary>,
warnings: Vec<String>,
}
fn execute(matches: &ArgMatches, context: &Context) -> Result<()> {
check_production(&ProcessEnv, matches.get_flag("allow-production"), context.dry_run)?;
let reset = matches.get_flag("reset");
if reset && !matches.get_flag("yes") {
bail!("--reset requires --yes");
}
let state_flag = matches.get_one::<String>("state").is_some();
if state_flag && matches.get_flag("no-state") {
bail!("--state and --no-state are mutually exclusive");
}
let from = matches
.get_one::<String>("from")
.map(String::as_str)
.unwrap_or("auto");
if !matches!(from, "auto" | "migrations" | "schema") {
bail!("--from must be auto, migrations, or schema, got `{from}`");
}
if from == "migrations" && state_flag {
bail!("--state cannot be combined with --from migrations");
}
let migrations = migration::discover(&context.config.migrations_dir).unwrap_or_default();
let schema_path = source::resolve(matches.get_one::<String>("schema").map(String::as_str)).ok();
let mode = match from {
"migrations" => SourceMode::Migrations,
"schema" => SourceMode::Schema,
_ => {
if !migrations.is_empty() {
SourceMode::Migrations
} else if schema_path.as_ref().is_some_and(|path| path.exists()) {
SourceMode::Schema
} else {
bail!(
"nothing to apply: no migrations in `{}` and no schema source found",
context.config.migrations_dir.to_string_lossy()
);
}
},
};
if mode == SourceMode::Schema && !seed_meta::is_postgres(&context.config)? {
return Err(midas::Error::unsupported_feature("sqlite", "schema-source setup").into());
}
let mut warnings = Vec::new();
let mut database_created = false;
if context.dry_run {
println!(
"Would create database `{}` if absent.",
sequel::database_name(context.config.require_database_url()?)?
);
match mode {
SourceMode::Migrations => {
println!(
"Would apply {} migration(s) from `{}`.",
migrations.len(),
context.config.migrations_dir.to_string_lossy()
);
},
SourceMode::Schema => {
let path = schema_path
.as_ref()
.ok_or_else(|| anyhow::anyhow!("schema source path is required for --from schema"))?;
dry_run_schema(context, path)?;
},
}
} else {
database_created = db_lifecycle::ensure_database(context)?;
match mode {
SourceMode::Migrations => apply_migrations(context)?,
SourceMode::Schema => {
let path = schema_path
.as_ref()
.ok_or_else(|| anyhow::anyhow!("schema source path is required for --from schema"))?;
apply_schema(context, path, matches.get_flag("accept-data-loss"))?;
refresh_state(matches, context)?;
},
}
}
let seed = if matches.get_flag("no-seed") {
None
} else {
seed_after(matches, context, mode, schema_path.as_deref(), &mut warnings)?
};
let summary = SetupSummary {
command: "setup",
dry_run: context.dry_run,
source: mode.as_str(),
database_created,
seed,
warnings,
};
if matches.get_flag("json") {
println!(
"{}",
serde_json::to_string(&summary).context("failed to serialize setup summary")?
);
} else {
println!("Setup source: {}", mode.as_str());
for warning in &summary.warnings {
eprintln!("warning: {warning}");
}
if context.dry_run {
println!("Dry run: wrote nothing.");
} else {
println!("Setup complete.");
}
}
Ok(())
}
fn apply_migrations(context: &Context) -> Result<()> {
let migrations = migration::discover(&context.config.migrations_dir)?;
let backend = sequel::connect(&context.config)?;
let options = MigratorOptions {
dry_run: false,
no_lock: context.no_lock,
transaction: context.config.transaction,
quiet: false,
ignore_missing: context.ignore_missing,
};
Migrator::new(backend, migrations)
.with_options(options)
.up(None)?;
Ok(())
}
fn apply_schema(context: &Context, path: &Path, accept_data_loss: bool) -> Result<()> {
let desired = schema::load_ir(path)?;
let live = live_schema(context, &desired)?;
let plan = Plan::try_between(&live, &desired)?;
if plan.is_empty() {
println!("Database already matches the schema.");
return Ok(());
}
if plan.requires_data_loss() && !accept_data_loss {
bail!("refusing destructive changes; pass --accept-data-loss");
}
let sql = schema::emit::alter::up(&plan);
let mut backend = sequel::connect(&context.config)?;
backend.execute_batch(&sql)?;
println!("Applied {} schema change(s).", plan.changes().len());
Ok(())
}
fn dry_run_schema(context: &Context, path: &Path) -> Result<()> {
let desired = schema::load_ir(path)?;
match live_schema(context, &desired) {
Ok(live) => {
let plan = Plan::try_between(&live, &desired)?;
if plan.is_empty() {
println!("Database already matches the schema.");
} else {
print!("{}", schema::emit::alter::up(&plan));
}
},
Err(_) => {
print!("{}", schema::create_sql(&desired)?);
},
}
Ok(())
}
fn refresh_state(matches: &ArgMatches, context: &Context) -> Result<()> {
if matches.get_flag("no-state") {
return Ok(());
}
let path = matches
.get_one::<String>("state")
.map(PathBuf::from)
.unwrap_or_else(state::default_path);
let introspection = midas_schema::schema::introspect::introspect_config(&context.config)?;
state::write(&path, &introspection.schema)?;
println!("Updated state `{}`.", path.to_string_lossy());
Ok(())
}
fn seed_after(
matches: &ArgMatches,
context: &Context,
mode: SourceMode,
schema_path: Option<&Path>,
warnings: &mut Vec<String>,
) -> Result<Option<Summary>> {
let seed_path: PathBuf = matches
.get_one::<String>("seed-file")
.map(PathBuf::from)
.unwrap_or_else(|| context.config.seed.file.clone());
if !seed_path.is_file() {
warnings.push(format!(
"seed file `{}` not found; skipping seeding",
seed_path.to_string_lossy()
));
return Ok(None);
}
let file = SeedFile::load(&seed_path, &context.config.seed).context("failed to load seed file")?;
let dialect = seed_meta::dialect(&context.config)?;
let (resolved, backend) = if context.dry_run {
match seed_meta::live(&context.config) {
Ok(resolved) => (resolved, None),
Err(error) => match (mode, schema_path) {
(SourceMode::Schema, Some(path)) => (seed_meta::offline(&context.config, path)?, None),
_ => {
warnings.push(format!(
"cannot resolve seed metadata offline ({error}); skipping seeding"
));
return Ok(None);
},
},
}
} else {
let resolved = seed_meta::live(&context.config)?;
let backend = midas::seed::connect(&context.config)?;
(resolved, Some(backend))
};
warnings.extend(resolved.warnings.iter().cloned());
let mut backend = backend;
let options = RunOptions {
command: "setup",
file: &file,
schema: &resolved.schema,
settings: &context.config.seed,
managed_schemas: &context.config.managed.schemas,
default_schema: context.config.search_path.as_deref(),
table_filters: &[],
rows_override: None,
reset: matches.get_flag("reset"),
skip_existing: !matches.get_flag("reset"),
dry_run: context.dry_run,
no_lock: context.no_lock,
master_seed: matches.get_one::<u64>("seed").copied(),
dialect,
warnings: &resolved.warnings,
};
let summary = match backend.as_deref_mut() {
Some(backend) => run(Some(backend), &options)?,
None => run(None, &options)?,
};
Ok(Some(summary))
}
fn live_schema(
context: &Context,
desired: &midas_schema::schema::ir::Schema,
) -> Result<midas_schema::schema::ir::Schema> {
let mut schemas = context.config.managed.schemas.clone();
if schemas.is_empty() {
schemas.extend(desired.schemas.keys().cloned());
if !desired.project.default_schema.is_empty() && !schemas.contains(&desired.project.default_schema) {
schemas.push(desired.project.default_schema.clone());
}
if schemas.is_empty() {
schemas.push("public".to_string());
}
}
Ok(
schema::introspect::introspect_with(
&context.config,
&schemas,
&context.config.managed.ignore_objects,
false,
)?
.schema,
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn owns_setup_only() {
assert!(owns("setup"));
assert!(!owns("faker"));
}
#[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 [
"schema",
"seed-file",
"from",
"no-seed",
"state",
"no-state",
"reset",
"seed",
"json",
"yes",
"accept-data-loss",
"allow-production",
] {
assert!(names.contains(&expected), "missing `{expected}`");
}
}
}