Skip to main content

midas_cli/commands/
schema.rs

1//! Schema DSL commands.
2
3use std::fs;
4
5use anyhow::{
6  Context as _,
7  Result,
8};
9use clap::{
10  Arg,
11  ArgMatches,
12  Command,
13};
14use midas_schema::schema;
15
16use crate::commands::{
17  source,
18  Context,
19};
20
21/// Register the `schema` command group.
22pub fn register(app: Command) -> Command {
23  app.subcommand(
24    Command::new("schema")
25      .about("Validate, format, and emit the schema DSL")
26      .arg_required_else_help(true)
27      .subcommand(
28        Command::new("validate")
29          .about("Parse and validate the schema DSL")
30          .arg(path_arg())
31          .arg(
32            Arg::new("json")
33              .long("json")
34              .help("Emit machine-readable diagnostics")
35              .action(clap::ArgAction::SetTrue),
36          ),
37      )
38      .subcommand(
39        Command::new("lint")
40          .about("Warn about unknown table and column references in view SQL")
41          .arg(path_arg())
42          .arg(
43            Arg::new("json")
44              .long("json")
45              .help("Emit machine-readable warnings")
46              .action(clap::ArgAction::SetTrue),
47          ),
48      )
49      .subcommand(
50        Command::new("sql")
51          .about("Emit create-from-empty Postgres SQL")
52          .arg(path_arg())
53          .arg(
54            Arg::new("output")
55              .long("output")
56              .short('o')
57              .value_name("file")
58              .help("Write SQL to a file instead of stdout")
59              .num_args(1),
60          )
61          .arg(
62            Arg::new("dialect")
63              .long("dialect")
64              .value_name("dialect")
65              .help("Target SQL dialect")
66              .value_parser(["postgres", "sqlite", "mysql"])
67              .default_value("postgres")
68              .num_args(1),
69          ),
70      )
71      .subcommand(
72        Command::new("format")
73          .visible_alias("fmt")
74          .about("Write canonical TOML or schema.midas")
75          .arg(path_arg())
76          .arg(
77            Arg::new("check")
78              .long("check")
79              .help("Fail when the file is not already canonical")
80              .action(clap::ArgAction::SetTrue),
81          ),
82      )
83      .subcommand(
84        Command::new("convert")
85          .about("Convert between TOML and schema.midas")
86          .arg(path_arg())
87          .arg(
88            Arg::new("from")
89              .long("from")
90              .value_name("format")
91              .help("Source format; inferred from the extension when omitted")
92              .value_parser(["toml", "midas"])
93              .num_args(1),
94          )
95          .arg(
96            Arg::new("to")
97              .long("to")
98              .value_name("format")
99              .help("Target format")
100              .value_parser(["toml", "midas"])
101              .required(true)
102              .num_args(1),
103          )
104          .arg(
105            Arg::new("output")
106              .long("output")
107              .short('o')
108              .value_name("file")
109              .help("Write the converted schema to a file instead of stdout")
110              .num_args(1),
111          ),
112      )
113      .subcommand(
114        Command::new("json-schema")
115          .about("Print the JSON Schema for the TOML DSL")
116          .arg(
117            Arg::new("output")
118              .long("output")
119              .short('o')
120              .value_name("file")
121              .help("Write the schema to a file instead of stdout")
122              .num_args(1),
123          ),
124      ),
125  )
126}
127
128fn path_arg() -> Arg {
129  Arg::new("path")
130    .value_name("path")
131    .help("Schema file or directory (defaults to the project schema source)")
132    .num_args(1)
133}
134
135/// Whether this module owns the given subcommand name.
136pub fn owns(name: &str) -> bool {
137  name == "schema"
138}
139
140/// Dispatch the command.
141pub fn dispatch(name: &str, matches: &ArgMatches, _: &Context) -> Result<()> {
142  let Some((subcommand, sub)) = matches.subcommand() else {
143    anyhow::bail!("`{name}` requires a subcommand");
144  };
145  match subcommand {
146    "validate" => validate(sub),
147    "lint" => lint(sub),
148    "sql" => sql(sub),
149    "format" | "fmt" => format(sub),
150    "convert" => convert(sub),
151    "json-schema" => json_schema(sub),
152    other => anyhow::bail!("unknown schema subcommand `{other}`"),
153  }
154}
155
156fn validate(matches: &ArgMatches) -> Result<()> {
157  let path = source::resolve(matches.get_one::<String>("path").map(String::as_str))?;
158  let json = matches.get_flag("json");
159  match schema::load(&path) {
160    Ok(loaded) => {
161      if json {
162        let output = serde_json::json!({
163          "valid": true,
164          "warnings": loaded.diagnostics.warnings,
165          "objects": object_counts(&loaded.ir),
166        });
167        println!("{}", serde_json::to_string(&output)?);
168      } else {
169        for warning in &loaded.diagnostics.warnings {
170          eprintln!("warning: {warning}");
171        }
172        println!(
173          "schema valid: {} table(s), {} type(s), {} function(s)",
174          loaded.ir.tables.len(),
175          loaded.ir.enums.len()
176            + loaded.ir.domains.len()
177            + loaded.ir.composites.len()
178            + loaded.ir.ranges.len(),
179          loaded.ir.functions.len() + loaded.ir.procedures.len()
180        );
181      }
182      Ok(())
183    },
184    Err(error) => {
185      if json {
186        let output = serde_json::json!({
187          "valid": false,
188          "error": error.to_string(),
189        });
190        println!("{}", serde_json::to_string(&output)?);
191      }
192      Err(error.into())
193    },
194  }
195}
196
197fn lint(matches: &ArgMatches) -> Result<()> {
198  let path = source::resolve(matches.get_one::<String>("path").map(String::as_str))?;
199  anyhow::ensure!(path.is_file(), "`schema lint` expects a file");
200  let warnings = schema::lint::lint_path(&path)?;
201  if matches.get_flag("json") {
202    println!(
203      "{}",
204      serde_json::to_string(&serde_json::json!({
205        "valid": true,
206        "warnings": warnings,
207      }))?
208    );
209  } else {
210    for warning in &warnings {
211      eprintln!(
212        "warning: {}:{}:{}: {}",
213        warning.file, warning.line, warning.column, warning.message
214      );
215    }
216    println!("lint complete: {} warning(s)", warnings.len());
217  }
218  Ok(())
219}
220
221fn sql(matches: &ArgMatches) -> Result<()> {
222  let path = source::resolve(matches.get_one::<String>("path").map(String::as_str))?;
223  let dialect = matches.get_one::<String>("dialect").expect("dialect");
224  let loaded = schema::load(&path)?;
225  for warning in &loaded.diagnostics.warnings {
226    eprintln!("warning: {warning}");
227  }
228  let sql = schema::create_sql_for(dialect, &loaded.ir)?;
229  write_or_print(matches.get_one::<String>("output"), &sql)
230}
231
232fn format(matches: &ArgMatches) -> Result<()> {
233  let path = source::resolve(matches.get_one::<String>("path").map(String::as_str))?;
234  anyhow::ensure!(path.is_file(), "`schema format` expects a file");
235  let raw =
236    fs::read_to_string(&path).with_context(|| format!("failed to read `{}`", path.to_string_lossy()))?;
237  let formatted = if path.extension().and_then(|extension| extension.to_str()) == Some("midas") {
238    schema::midas::format_str(&raw, &path)?
239  } else {
240    schema::format::format_str(&raw)?
241  };
242  if matches.get_flag("check") {
243    anyhow::ensure!(
244      raw == formatted,
245      "`{}` is not canonically formatted",
246      path.to_string_lossy()
247    );
248    return Ok(());
249  }
250  print!("{formatted}");
251  Ok(())
252}
253
254fn convert(matches: &ArgMatches) -> Result<()> {
255  let path = source::resolve(matches.get_one::<String>("path").map(String::as_str))?;
256  anyhow::ensure!(path.is_file(), "`schema convert` expects a file");
257  let from = match matches.get_one::<String>("from").map(String::as_str) {
258    Some(value) => value.to_string(),
259    None => match path.extension().and_then(|extension| extension.to_str()) {
260      Some("midas") => "midas".to_string(),
261      Some("toml") => "toml".to_string(),
262      _ => anyhow::bail!("cannot infer `--from`; pass `--from toml|midas`"),
263    },
264  };
265  let to = matches.get_one::<String>("to").context("--to is required")?;
266  let text = match (from.as_str(), to.as_str()) {
267    ("toml", "midas") => {
268      let ast = schema::parse::parse_file(&path)?;
269      schema::midas::write_ast(&ast, &schema::midas::Comments::default())
270    },
271    ("midas", "midas") => {
272      let raw = fs::read_to_string(&path)?;
273      schema::midas::format_str(&raw, &path)?
274    },
275    ("toml", "toml") => {
276      let raw = fs::read_to_string(&path)?;
277      schema::format::format_str(&raw)?
278    },
279    ("midas", "toml") => {
280      let ast = schema::midas::parse_file(&path)?.ast;
281      let ir = schema::resolve::resolve(ast)?;
282      schema::to_toml(&ir)?
283    },
284    _ => anyhow::bail!("unsupported conversion `{from}` -> `{to}`"),
285  };
286  write_or_print(matches.get_one::<String>("output"), &text)
287}
288
289fn json_schema(matches: &ArgMatches) -> Result<()> {
290  let schema = schema::json_schema()?;
291  let mut text = serde_json::to_string_pretty(&schema)?;
292  text.push('\n');
293  write_or_print(matches.get_one::<String>("output"), &text)
294}
295
296fn write_or_print(output: Option<&String>, text: &str) -> Result<()> {
297  match output {
298    Some(path) => fs::write(path, text).with_context(|| format!("failed to write `{path}`"))?,
299    None => print!("{text}"),
300  }
301  Ok(())
302}
303
304fn object_counts(schema: &schema::ir::Schema) -> serde_json::Value {
305  serde_json::json!({
306    "schemas": schema.schemas.len(),
307    "extensions": schema.extensions.len(),
308    "enums": schema.enums.len(),
309    "domains": schema.domains.len(),
310    "composites": schema.composites.len(),
311    "ranges": schema.ranges.len(),
312    "collations": schema.collations.len(),
313    "sequences": schema.sequences.len(),
314    "tables": schema.tables.len(),
315    "views": schema.views.len(),
316    "functions": schema.functions.len(),
317    "procedures": schema.procedures.len(),
318    "triggers": schema.triggers.len(),
319    "policies": schema.policies.len(),
320    "roles": schema.roles.len(),
321    "grants": schema.grants.len(),
322    "default_privileges": schema.default_privileges.len(),
323    "publications": schema.publications.len(),
324    "subscriptions": schema.subscriptions.len(),
325    "statistics": schema.statistics.len(),
326    "raw": schema.raw.len(),
327    "ignores": schema.ignores.len(),
328  })
329}
330
331#[cfg(test)]
332mod tests {
333  use super::*;
334
335  #[test]
336  fn owns_only_schema() {
337    assert!(owns("schema"));
338    assert!(!owns("generate"));
339  }
340
341  #[test]
342  fn command_group_has_expected_subcommands() {
343    let app = register(Command::new("midas"));
344    let schema = app
345      .get_subcommands()
346      .find(|command| command.get_name() == "schema")
347      .expect("schema command");
348    let names = schema
349      .get_subcommands()
350      .map(|command| command.get_name())
351      .collect::<Vec<_>>();
352    for expected in ["validate", "lint", "sql", "format", "convert", "json-schema"] {
353      assert!(names.contains(&expected), "missing `{expected}`");
354    }
355  }
356}