Skip to main content

midas_cli/commands/
db_schema.rs

1//! Database schema commands composed under `midas db`.
2
3use std::fs;
4use std::path::Path;
5
6use anyhow::{
7  Context as _,
8  Result,
9};
10use clap::{
11  Arg,
12  ArgMatches,
13  Command,
14};
15use midas_schema::schema::plan::Plan;
16use midas_schema::schema::{
17  self,
18  ir,
19};
20
21use crate::commands::{
22  source,
23  Context,
24};
25
26/// Subcommands owned by the schema module.
27pub fn subcommands() -> Vec<Command> {
28  vec![
29    Command::new("pull")
30      .about("Introspect the database into the schema DSL")
31      .arg(
32        Arg::new("schema")
33          .long("schema")
34          .value_name("name")
35          .help("Schema to inspect; repeat for multiple")
36          .action(clap::ArgAction::Append)
37          .num_args(1),
38      )
39      .arg(
40        Arg::new("output")
41          .long("output")
42          .short('o')
43          .value_name("path")
44          .help("Output TOML path")
45          .default_value("schema.toml")
46          .num_args(1),
47      )
48      .arg(
49        Arg::new("force")
50          .long("force")
51          .help("Overwrite an existing schema file")
52          .action(clap::ArgAction::SetTrue),
53      )
54      .arg(
55        Arg::new("include-raw")
56          .long("include-raw")
57          .help("Emit unsupported event triggers as raw blocks")
58          .action(clap::ArgAction::SetTrue),
59      ),
60    Command::new("push")
61      .about("Apply the schema DSL to the database")
62      .arg(
63        Arg::new("schema")
64          .value_name("path")
65          .help("Schema file or directory (defaults to the project schema source)")
66          .num_args(1),
67      )
68      .arg(
69        Arg::new("accept-data-loss")
70          .long("accept-data-loss")
71          .help("Allow destructive or irreversible changes")
72          .action(clap::ArgAction::SetTrue),
73      )
74      .arg(
75        Arg::new("force")
76          .long("force")
77          .help("Ignore drift checks")
78          .action(clap::ArgAction::SetTrue),
79      ),
80    Command::new("diff")
81      .about("Report drift between the database and the schema DSL")
82      .arg(
83        Arg::new("schema")
84          .value_name("path")
85          .help("Schema file or directory (defaults to the project schema source)")
86          .num_args(1),
87      )
88      .arg(
89        Arg::new("script")
90          .long("script")
91          .help("Print UP/DOWN SQL")
92          .action(clap::ArgAction::SetTrue),
93      )
94      .arg(
95        Arg::new("json")
96          .long("json")
97          .help("Emit a machine-readable plan summary")
98          .action(clap::ArgAction::SetTrue),
99      ),
100  ]
101}
102
103/// Whether this module owns the given subcommand name.
104pub fn owns(name: &str) -> bool {
105  matches!(name, "pull" | "push" | "diff")
106}
107
108/// Dispatch a schema subcommand.
109pub fn dispatch(name: &str, matches: &ArgMatches, context: &Context) -> Result<()> {
110  match name {
111    "pull" => pull(matches, context),
112    "push" => push(matches, context),
113    "diff" => diff(matches, context),
114    other => anyhow::bail!("unknown db schema subcommand `{other}`"),
115  }
116}
117
118fn pull(matches: &ArgMatches, context: &Context) -> Result<()> {
119  let schemas = matches
120    .get_many::<String>("schema")
121    .map(|values| values.cloned().collect::<Vec<_>>())
122    .unwrap_or_default();
123  let output = matches
124    .get_one::<String>("output")
125    .map(Path::new)
126    .unwrap_or_else(|| Path::new("schema.toml"));
127  let introspection = schema::introspect::introspect_with(
128    &context.config,
129    &schemas,
130    &context.config.managed.ignore_objects,
131    matches.get_flag("include-raw"),
132  )?;
133  for warning in &introspection.warnings {
134    eprintln!("warning: {warning}");
135  }
136  let text = schema::to_toml(&introspection.schema)?;
137
138  if output.is_file() && !matches.get_flag("force") {
139    let existing = fs::read_to_string(output)?;
140    if existing != text {
141      print_diff(&existing, &text);
142    }
143    anyhow::bail!(
144      "`{}` already exists; pass --force to overwrite",
145      output.to_string_lossy()
146    );
147  }
148
149  if let Some(parent) = output.parent() {
150    fs::create_dir_all(parent)?;
151  }
152  fs::write(output, &text).with_context(|| format!("failed to write `{}`", output.to_string_lossy()))?;
153  println!(
154    "Wrote {} table(s) to `{}`.",
155    introspection.schema.tables.len(),
156    output.to_string_lossy()
157  );
158  Ok(())
159}
160
161fn push(matches: &ArgMatches, context: &Context) -> Result<()> {
162  let path = source::resolve(matches.get_one::<String>("schema").map(String::as_str))?;
163  let desired = schema::load_ir(&path)?;
164  let live = live_schema(context, &desired)?;
165  let plan = Plan::try_between(&live, &desired)?;
166  if plan.is_empty() {
167    println!("Database already matches the schema.");
168    return Ok(());
169  }
170  if plan.requires_data_loss() && !matches.get_flag("accept-data-loss") {
171    anyhow::bail!("refusing destructive changes; pass --accept-data-loss");
172  }
173  let sql = schema::emit::alter::up(&plan);
174  if context.dry_run {
175    print!("{sql}");
176    return Ok(());
177  }
178  let mut backend = midas::sequel::connect(&context.config)?;
179  backend.execute_batch(&sql)?;
180  println!("Applied {} change(s).", plan.changes().len());
181  Ok(())
182}
183
184fn diff(matches: &ArgMatches, context: &Context) -> Result<()> {
185  let path = source::resolve(matches.get_one::<String>("schema").map(String::as_str))?;
186  let desired = schema::load_ir(&path)?;
187  let live = live_schema(context, &desired)?;
188  let plan = Plan::try_between(&live, &desired)?;
189  if matches.get_flag("script") {
190    print!("{}", schema::emit::alter::migration(&plan));
191  } else if matches.get_flag("json") {
192    println!("{}", serde_json::to_string(&plan.summary())?);
193  } else if plan.is_empty() {
194    println!("No drift detected.");
195  } else {
196    for change in plan.changes() {
197      let meta = change.meta();
198      let marker = if meta.irreversible {
199        "irreversible"
200      } else if meta.destructive {
201        "destructive"
202      } else {
203        "safe"
204      };
205      println!("[{marker}] {}", change.summary());
206    }
207  }
208  Ok(())
209}
210
211fn live_schema(context: &Context, desired: &ir::Schema) -> Result<ir::Schema> {
212  let mut schemas = context.config.managed.schemas.clone();
213  if schemas.is_empty() {
214    schemas.extend(desired.schemas.keys().cloned());
215    if !desired.project.default_schema.is_empty() && !schemas.contains(&desired.project.default_schema) {
216      schemas.push(desired.project.default_schema.clone());
217    }
218    if schemas.is_empty() {
219      schemas.push("public".to_string());
220    }
221  }
222  Ok(
223    schema::introspect::introspect_with(
224      &context.config,
225      &schemas,
226      &context.config.managed.ignore_objects,
227      false,
228    )?
229    .schema,
230  )
231}
232
233fn print_diff(old: &str, new: &str) {
234  println!("--- existing");
235  println!("+++ generated");
236  for line in old.lines() {
237    if !new.lines().any(|candidate| candidate == line) {
238      println!("-{line}");
239    }
240  }
241  for line in new.lines() {
242    if !old.lines().any(|candidate| candidate == line) {
243      println!("+{line}");
244    }
245  }
246}
247
248#[cfg(test)]
249mod tests {
250  use super::*;
251
252  #[test]
253  fn owns_schema_commands() {
254    for name in ["pull", "push", "diff"] {
255      assert!(owns(name));
256    }
257    assert!(!owns("create"));
258  }
259}