midas_cli/commands/
prepare.rs1use std::path::Path;
4
5use anyhow::{
6 Context as _,
7 Result,
8};
9use clap::{
10 Arg,
11 ArgMatches,
12 Command,
13};
14use midas_schema::{
15 offline,
16 schema,
17};
18
19use crate::commands::{
20 source,
21 Context,
22};
23
24pub fn register(app: Command) -> Command {
26 app.subcommand(
27 Command::new("prepare")
28 .about("Generate offline SQLx metadata from the schema DSL")
29 .arg(
30 Arg::new("schema")
31 .long("schema")
32 .value_name("path")
33 .help("Schema file or directory (defaults to the project schema source)")
34 .num_args(1),
35 )
36 .arg(
37 Arg::new("path")
38 .long("path")
39 .value_name("dir")
40 .help("Project root that contains Rust sources")
41 .default_value(".")
42 .num_args(1),
43 )
44 .arg(
45 Arg::new("check")
46 .long("check")
47 .help("Fail when `.sqlx` metadata is stale")
48 .action(clap::ArgAction::SetTrue),
49 ),
50 )
51}
52
53pub fn owns(name: &str) -> bool {
55 name == "prepare"
56}
57
58pub fn dispatch(name: &str, matches: &ArgMatches, context: &Context) -> Result<()> {
60 let _ = name;
61 let schema_path = source::resolve(matches.get_one::<String>("schema").map(String::as_str))?;
62 let root = Path::new(matches.get_one::<String>("path").expect("path"));
63
64 let loaded = schema::load(&schema_path)
65 .with_context(|| format!("failed to load `{}`", schema_path.to_string_lossy()))?;
66
67 if matches.get_flag("check") {
68 offline::check(&loaded.ir, root)?;
69 println!("offline metadata is up to date");
70 return Ok(());
71 }
72
73 let report = offline::prepare(&loaded.ir, root)?;
74 for warning in &report.warnings {
75 eprintln!("warning: {warning}");
76 }
77 if context.dry_run {
78 for query in &report.queries {
79 print!("{}", String::from_utf8_lossy(&query.to_bytes()?));
80 }
81 return Ok(());
82 }
83
84 offline::write(&report, &root.join(".sqlx"))?;
85 println!("wrote {} offline query file(s)", report.queries.len());
86 Ok(())
87}
88
89#[cfg(test)]
90mod tests {
91 use super::*;
92
93 #[test]
94 fn owns_only_prepare() {
95 assert!(owns("prepare"));
96 assert!(!owns("generate"));
97 }
98}