midas_cli/commands/
sqlx.rs1use std::path::Path;
4
5use anyhow::{
6 Context as _,
7 Result,
8};
9use clap::{
10 Arg,
11 ArgMatches,
12 Command,
13};
14use midas::{
15 migration,
16 sqlx,
17};
18
19use crate::commands::Context;
20
21pub fn register(app: Command) -> Command {
23 app.subcommand(
24 Command::new("sqlx")
25 .about("SQLx interoperability commands")
26 .arg_required_else_help(true)
27 .subcommand(export_command())
28 .subcommand(import_command()),
29 )
30}
31
32pub fn owns(name: &str) -> bool {
34 name == "sqlx"
35}
36
37pub fn dispatch(name: &str, matches: &ArgMatches, context: &Context) -> Result<()> {
39 let Some((subcommand, sub)) = matches.subcommand() else {
40 anyhow::bail!("`{name}` requires a subcommand");
41 };
42
43 match subcommand {
44 "export" => export(sub, context),
45 "import" => import(sub, context),
46 other => anyhow::bail!("unknown sqlx subcommand `{other}`"),
47 }
48}
49
50fn export_command() -> Command {
51 Command::new("export")
52 .about("Export Midas migrations as SQLx migration files")
53 .arg(
54 Arg::new("out")
55 .long("out")
56 .value_name("dir")
57 .help("Directory to write SQLx migrations into")
58 .required(true)
59 .num_args(1),
60 )
61}
62
63fn import_command() -> Command {
64 Command::new("import")
65 .about("Import SQLx migration files as Midas migrations")
66 .arg(
67 Arg::new("from")
68 .long("from")
69 .value_name("dir")
70 .help("Directory containing SQLx migrations")
71 .required(true)
72 .num_args(1),
73 )
74 .arg(
75 Arg::new("out")
76 .long("out")
77 .value_name("dir")
78 .help("Directory to write Midas migrations into")
79 .required(true)
80 .num_args(1),
81 )
82}
83
84fn export(matches: &ArgMatches, context: &Context) -> Result<()> {
85 let out = matches
86 .get_one::<String>("out")
87 .context("output directory is required")?;
88 let migrations = migration::discover(&context.config.migrations_dir)?;
89 let written = sqlx::export_sqlx(&migrations, Path::new(out))?;
90 println!("Exported {} migration file(s) to `{out}`.", written.len());
91 Ok(())
92}
93
94fn import(matches: &ArgMatches, context: &Context) -> Result<()> {
95 let from = matches
96 .get_one::<String>("from")
97 .context("input directory is required")?;
98 let out = matches
99 .get_one::<String>("out")
100 .context("output directory is required")?;
101 let migrations = sqlx::import_sqlx_with(Path::new(from), &context.config.sqlx)?;
102 let written = sqlx::write_midas(&migrations, Path::new(out))?;
103 println!(
104 "Imported {} migration(s) into `{out}` ({} file(s)).",
105 migrations.len(),
106 written.len()
107 );
108 Ok(())
109}
110
111#[cfg(test)]
112mod tests {
113 use super::*;
114
115 #[test]
116 fn owns_only_sqlx() {
117 assert!(owns("sqlx"));
118 assert!(!owns("generate"));
119 }
120}