use std::fs;
use std::path::Path;
use anyhow::{
Context as _,
Result,
};
use clap::{
Arg,
ArgMatches,
Command,
};
use midas_schema::schema::plan::Plan;
use midas_schema::schema::{
self,
ir,
};
use crate::commands::{
source,
Context,
};
pub fn subcommands() -> Vec<Command> {
vec![
Command::new("pull")
.about("Introspect the database into the schema DSL")
.arg(
Arg::new("schema")
.long("schema")
.value_name("name")
.help("Schema to inspect; repeat for multiple")
.action(clap::ArgAction::Append)
.num_args(1),
)
.arg(
Arg::new("output")
.long("output")
.short('o')
.value_name("path")
.help("Output TOML path")
.default_value("schema.toml")
.num_args(1),
)
.arg(
Arg::new("force")
.long("force")
.help("Overwrite an existing schema file")
.action(clap::ArgAction::SetTrue),
)
.arg(
Arg::new("include-raw")
.long("include-raw")
.help("Emit unsupported event triggers as raw blocks")
.action(clap::ArgAction::SetTrue),
),
Command::new("push")
.about("Apply the schema DSL to the database")
.arg(
Arg::new("schema")
.value_name("path")
.help("Schema file or directory (defaults to the project schema source)")
.num_args(1),
)
.arg(
Arg::new("accept-data-loss")
.long("accept-data-loss")
.help("Allow destructive or irreversible changes")
.action(clap::ArgAction::SetTrue),
)
.arg(
Arg::new("force")
.long("force")
.help("Ignore drift checks")
.action(clap::ArgAction::SetTrue),
),
Command::new("diff")
.about("Report drift between the database and the schema DSL")
.arg(
Arg::new("schema")
.value_name("path")
.help("Schema file or directory (defaults to the project schema source)")
.num_args(1),
)
.arg(
Arg::new("script")
.long("script")
.help("Print UP/DOWN SQL")
.action(clap::ArgAction::SetTrue),
)
.arg(
Arg::new("json")
.long("json")
.help("Emit a machine-readable plan summary")
.action(clap::ArgAction::SetTrue),
),
]
}
pub fn owns(name: &str) -> bool {
matches!(name, "pull" | "push" | "diff")
}
pub fn dispatch(name: &str, matches: &ArgMatches, context: &Context) -> Result<()> {
match name {
"pull" => pull(matches, context),
"push" => push(matches, context),
"diff" => diff(matches, context),
other => anyhow::bail!("unknown db schema subcommand `{other}`"),
}
}
fn pull(matches: &ArgMatches, context: &Context) -> Result<()> {
let schemas = matches
.get_many::<String>("schema")
.map(|values| values.cloned().collect::<Vec<_>>())
.unwrap_or_default();
let output = matches
.get_one::<String>("output")
.map(Path::new)
.unwrap_or_else(|| Path::new("schema.toml"));
let introspection = schema::introspect::introspect_with(
&context.config,
&schemas,
&context.config.managed.ignore_objects,
matches.get_flag("include-raw"),
)?;
for warning in &introspection.warnings {
eprintln!("warning: {warning}");
}
let text = schema::to_toml(&introspection.schema)?;
if output.is_file() && !matches.get_flag("force") {
let existing = fs::read_to_string(output)?;
if existing != text {
print_diff(&existing, &text);
}
anyhow::bail!(
"`{}` already exists; pass --force to overwrite",
output.to_string_lossy()
);
}
if let Some(parent) = output.parent() {
fs::create_dir_all(parent)?;
}
fs::write(output, &text).with_context(|| format!("failed to write `{}`", output.to_string_lossy()))?;
println!(
"Wrote {} table(s) to `{}`.",
introspection.schema.tables.len(),
output.to_string_lossy()
);
Ok(())
}
fn push(matches: &ArgMatches, context: &Context) -> Result<()> {
let path = source::resolve(matches.get_one::<String>("schema").map(String::as_str))?;
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() && !matches.get_flag("accept-data-loss") {
anyhow::bail!("refusing destructive changes; pass --accept-data-loss");
}
let sql = schema::emit::alter::up(&plan);
if context.dry_run {
print!("{sql}");
return Ok(());
}
let mut backend = midas::sequel::connect(&context.config)?;
backend.execute_batch(&sql)?;
println!("Applied {} change(s).", plan.changes().len());
Ok(())
}
fn diff(matches: &ArgMatches, context: &Context) -> Result<()> {
let path = source::resolve(matches.get_one::<String>("schema").map(String::as_str))?;
let desired = schema::load_ir(&path)?;
let live = live_schema(context, &desired)?;
let plan = Plan::try_between(&live, &desired)?;
if matches.get_flag("script") {
print!("{}", schema::emit::alter::migration(&plan));
} else if matches.get_flag("json") {
println!("{}", serde_json::to_string(&plan.summary())?);
} else if plan.is_empty() {
println!("No drift detected.");
} else {
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 live_schema(context: &Context, desired: &ir::Schema) -> Result<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,
)
}
fn print_diff(old: &str, new: &str) {
println!("--- existing");
println!("+++ generated");
for line in old.lines() {
if !new.lines().any(|candidate| candidate == line) {
println!("-{line}");
}
}
for line in new.lines() {
if !old.lines().any(|candidate| candidate == line) {
println!("+{line}");
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn owns_schema_commands() {
for name in ["pull", "push", "diff"] {
assert!(owns(name));
}
assert!(!owns("create"));
}
}