1use std::fs;
4use std::path::Path;
5
6use anyhow::{
7 Context as _,
8 Result,
9};
10use clap::{
11 value_parser,
12 Arg,
13 ArgMatches,
14 Command,
15};
16use console::style;
17use midas::commander::{
18 MigrationInfo,
19 Migrator,
20 MigratorOptions,
21};
22use midas::config::Config;
23use midas::sqlx::{
24 qualified_table_name,
25 SqlxMigrationType,
26 SqlxVersioning,
27};
28use midas::{
29 migration,
30 sequel,
31};
32use prettytable::format::consts;
33use prettytable::{
34 row,
35 Table,
36};
37
38use crate::commands::Context;
39
40const PROJECT_FILE: &str = "midas.toml";
41const SCHEMA_FILE: &str = "schema.toml";
42
43pub fn register(app: Command) -> Command {
45 let mut app = app
46 .subcommand(
47 Command::new("init")
48 .about("Set up a midas project (midas.toml, schema.toml, migrations/)")
49 .arg(
50 Arg::new("force")
51 .long("force")
52 .help("Overwrite existing configuration files")
53 .action(clap::ArgAction::SetTrue),
54 ),
55 )
56 .subcommand(
57 Command::new("add")
58 .visible_alias("create")
59 .visible_alias("c")
60 .about("Create a timestamped migration file")
61 .arg(Arg::new("name").help("The migration action name").required(true))
62 .arg(
63 Arg::new("reversible")
64 .long("reversible")
65 .help("Create a .up.sql/.down.sql pair")
66 .action(clap::ArgAction::SetTrue),
67 ),
68 );
69
70 for command in migration_commands() {
71 app = app.subcommand(command.clone());
72 }
73
74 app.subcommand(
75 Command::new("migrate")
76 .about("Migration commands")
77 .arg_required_else_help(true)
78 .subcommands(migration_commands()),
79 )
80}
81
82fn migration_commands() -> Vec<Command> {
83 vec![
84 Command::new("run")
85 .visible_alias("up")
86 .visible_alias("u")
87 .about("Apply pending migrations")
88 .arg(
89 Arg::new("target")
90 .long("target")
91 .value_name("version")
92 .help("Apply only migrations up to this version")
93 .num_args(1)
94 .value_parser(value_parser!(i64)),
95 )
96 .arg(json_flag()),
97 Command::new("info")
98 .visible_alias("status")
99 .visible_alias("s")
100 .about("Show applied, pending, and dirty migrations")
101 .arg(json_flag()),
102 Command::new("list")
103 .visible_alias("ls")
104 .about("List migration files without a database"),
105 Command::new("revert")
106 .visible_alias("r")
107 .about("Revert applied migrations")
108 .arg(
109 Arg::new("to")
110 .long("to")
111 .value_name("version")
112 .help("Revert every migration above this version")
113 .num_args(1)
114 .value_parser(value_parser!(i64)),
115 ),
116 Command::new("redo").about("Revert and re-apply the last migration"),
117 Command::new("baseline")
118 .about("Mark migrations as applied without running SQL")
119 .arg(
120 Arg::new("to")
121 .long("to")
122 .value_name("version")
123 .help("Highest version to mark as applied")
124 .num_args(1)
125 .value_parser(value_parser!(i64))
126 .required_unless_present("from"),
127 )
128 .arg(
129 Arg::new("from")
130 .long("from")
131 .value_name("format")
132 .help("Read applied versions from another migration engine")
133 .value_parser(["sqlx"])
134 .num_args(1),
135 ),
136 Command::new("repair").about("Recompute checksums for applied migrations"),
137 Command::new("resolve")
138 .about("Resolve a dirty migration")
139 .disable_version_flag(true)
140 .arg(
141 Arg::new("applied")
142 .long("applied")
143 .help("Mark the dirty migration as applied")
144 .action(clap::ArgAction::SetTrue),
145 )
146 .arg(
147 Arg::new("rolled-back")
148 .long("rolled-back")
149 .help("Remove the dirty migration record")
150 .action(clap::ArgAction::SetTrue),
151 )
152 .arg(
153 Arg::new("migration_version")
154 .long("version")
155 .value_name("version")
156 .help("Version to resolve (defaults to the lowest dirty version)")
157 .num_args(1)
158 .value_parser(value_parser!(i64)),
159 ),
160 Command::new("reset").about("Drop metadata and replay every migration"),
161 Command::new("down")
162 .visible_alias("d")
163 .about("Revert every applied migration")
164 .arg(
165 Arg::new("force")
166 .long("force")
167 .help("Required confirmation for reverting everything")
168 .action(clap::ArgAction::SetTrue),
169 ),
170 crate::commands::migrate_dev::dev_command(),
171 crate::commands::migrate_dev::diff_command(),
172 export_command(),
173 import_command(),
174 Command::new("adopt")
175 .about("Verify that an existing SQLx metadata table can be adopted")
176 .arg(
177 Arg::new("table")
178 .long("table")
179 .value_name("name")
180 .help("SQLx metadata table, optionally schema-qualified")
181 .default_value("_sqlx_migrations")
182 .num_args(1),
183 ),
184 ]
185}
186
187fn export_command() -> Command {
188 Command::new("export")
189 .about("Export migrations for another migration tool")
190 .arg(
191 Arg::new("format")
192 .long("format")
193 .value_name("format")
194 .help("Output format")
195 .value_parser(["sqlx"])
196 .default_value("sqlx")
197 .num_args(1),
198 )
199 .arg(
200 Arg::new("out")
201 .long("out")
202 .value_name("dir")
203 .help("Directory to write exported migrations into")
204 .required(true)
205 .num_args(1),
206 )
207}
208
209fn import_command() -> Command {
210 Command::new("import")
211 .about("Import migrations from another migration tool")
212 .arg(
213 Arg::new("format")
214 .long("format")
215 .value_name("format")
216 .help("Input format")
217 .value_parser(["sqlx"])
218 .default_value("sqlx")
219 .num_args(1),
220 )
221 .arg(
222 Arg::new("from")
223 .long("from")
224 .value_name("dir")
225 .help("Directory to read migrations from")
226 .required(true)
227 .num_args(1),
228 )
229 .arg(
230 Arg::new("out")
231 .long("out")
232 .value_name("dir")
233 .help("Directory to write Midas migrations into")
234 .required(true)
235 .num_args(1),
236 )
237}
238
239fn json_flag() -> Arg {
240 Arg::new("json")
241 .long("json")
242 .help("Emit machine-readable JSON")
243 .action(clap::ArgAction::SetTrue)
244}
245
246pub fn owns(name: &str) -> bool {
248 matches!(
249 name,
250 "init"
251 | "add"
252 | "create"
253 | "c"
254 | "run"
255 | "up"
256 | "u"
257 | "info"
258 | "status"
259 | "s"
260 | "list"
261 | "ls"
262 | "revert"
263 | "r"
264 | "redo"
265 | "baseline"
266 | "repair"
267 | "resolve"
268 | "reset"
269 | "down"
270 | "d"
271 | "migrate"
272 | "export"
273 | "import"
274 | "adopt"
275 )
276}
277
278pub fn dispatch(name: &str, matches: &ArgMatches, context: &Context) -> Result<()> {
280 if name == "migrate" {
281 let Some((nested, sub)) = matches.subcommand() else {
282 return Ok(());
283 };
284 return dispatch(nested, sub, context);
285 }
286
287 match name {
288 "init" => init(&context.config, matches.get_flag("force")),
289 "add" | "create" | "c" => add(matches, context),
290 "run" | "up" | "u" => run(matches, context),
291 "info" | "status" | "s" => info(matches, context),
292 "list" | "ls" => list(&context.config),
293 "revert" | "r" => revert(matches, context),
294 "redo" => with_migrator(context, false, |migrator| migrator.redo()).map(drop),
295 "baseline" => baseline(matches, context),
296 "repair" => with_migrator(context, false, |migrator| migrator.repair()).map(drop),
297 "resolve" => resolve(matches, context),
298 "reset" => with_migrator(context, false, |migrator| migrator.reset()).map(drop),
299 "down" | "d" => with_migrator(context, false, |migrator| {
300 migrator.down(matches.get_flag("force"))
301 })
302 .map(drop),
303 "dev" | "diff" => crate::commands::migrate_dev::dispatch(name, matches, context),
304 "export" => export(matches, context),
305 "import" => import(matches, context),
306 "adopt" => adopt(matches, context),
307 other => anyhow::bail!("unknown migration subcommand `{other}`"),
308 }
309}
310
311fn init(config: &Config, force: bool) -> Result<()> {
312 let project_file = Path::new(PROJECT_FILE);
313 let schema_file = Path::new(SCHEMA_FILE);
314
315 if !force {
316 for path in [project_file, schema_file] {
317 if path.exists() {
318 return Err(
319 midas::Error::config(format!(
320 "{} already exists; rerun with --force to overwrite",
321 path.to_string_lossy()
322 ))
323 .into(),
324 );
325 }
326 }
327 }
328
329 fs::create_dir_all(&config.migrations_dir).with_context(|| {
330 format!(
331 "failed to create migrations directory `{}`",
332 config.migrations_dir.to_string_lossy()
333 )
334 })?;
335
336 if !project_file.exists() || force {
337 fs::write(project_file, project_template(config)).context("failed to write midas.toml")?;
338 }
339 if !schema_file.exists() || force {
340 fs::write(schema_file, schema_template()).context("failed to write schema.toml")?;
341 }
342
343 println!("Initialized midas project.");
344 Ok(())
345}
346
347fn add(matches: &ArgMatches, context: &Context) -> Result<()> {
348 let slug = matches
349 .get_one::<String>("name")
350 .context("migration name is required")?;
351 let existing = migration::discover(&context.config.migrations_dir)?;
352 let reversible = matches.get_flag("reversible")
353 || match context.config.sqlx.default_migration_type {
354 SqlxMigrationType::Reversible => true,
355 SqlxMigrationType::Simple => false,
356 SqlxMigrationType::Inferred => existing
357 .values()
358 .next_back()
359 .is_some_and(|migration| migration.down.is_some()),
360 };
361 let versioning = match context.config.sqlx.default_versioning {
362 SqlxVersioning::Sequential => migration::Versioning::Sequential,
363 SqlxVersioning::Timestamp => migration::Versioning::Timestamp,
364 SqlxVersioning::Inferred => infer_versioning(&existing),
365 };
366 let version =
367 migration::create_migration_file_with(&context.config.migrations_dir, slug, reversible, versioning)?;
368 println!("Created migration {version:013}.");
369 Ok(())
370}
371
372fn infer_versioning(existing: &migration::MigrationList) -> migration::Versioning {
373 let versions = existing.keys().copied().collect::<Vec<_>>();
374 let sequential = match versions.as_slice() {
375 [only] => *only == 1,
376 [.., previous, latest] => latest - previous == 1,
377 [] => false,
378 };
379 if sequential {
380 migration::Versioning::Sequential
381 } else {
382 migration::Versioning::Timestamp
383 }
384}
385
386fn run(matches: &ArgMatches, context: &Context) -> Result<()> {
387 let target = matches.get_one::<i64>("target").copied();
388 if target.is_some_and(|target| target < 0) {
389 anyhow::bail!("target version must be non-negative");
390 }
391 let info = with_migrator(context, matches.get_flag("json"), |migrator| migrator.up(target))?;
392 output(matches, &info)
393}
394
395fn info(matches: &ArgMatches, context: &Context) -> Result<()> {
396 let info = if matches.get_flag("json") {
397 with_migrator(context, true, |migrator| migrator.info())?
398 } else {
399 with_migrator(context, false, |migrator| migrator.status())?
400 };
401 output(matches, &info)
402}
403
404fn list(config: &Config) -> Result<()> {
405 let migrations = migration::discover(&config.migrations_dir)?;
406 if migrations.is_empty() {
407 println!("There are no available migration files.");
408 return Ok(());
409 }
410
411 let mut table = Table::new();
412 table.set_titles(row![Fbb->"Migration No.", Fbb->"Filename", Fbb->"Description"]);
413 table.set_format(*consts::FORMAT_CLEAN);
414
415 for migration in migrations.values() {
416 let filename = migration
417 .source_path
418 .file_name()
419 .map(|name| name.to_string_lossy().into_owned())
420 .unwrap_or_default();
421 table.add_row(row![
422 b->&format!("{:013}", migration.version),
423 Fgb->&filename,
424 &migration.description
425 ]);
426 }
427
428 let msg = style("Available migrations:").bold().cyan();
429 println!();
430 println!("{msg}");
431 println!();
432 table.printstd();
433 println!();
434
435 Ok(())
436}
437
438fn revert(matches: &ArgMatches, context: &Context) -> Result<()> {
439 let target = matches.get_one::<i64>("to").copied();
440 if target.is_some_and(|target| target < 0) {
441 anyhow::bail!("revert target must be non-negative");
442 }
443 with_migrator(context, false, |migrator| migrator.revert_to(target)).map(drop)
444}
445
446fn baseline(matches: &ArgMatches, context: &Context) -> Result<()> {
447 if matches.get_one::<String>("from").is_some() {
448 let options = migrator_options(context, false);
449 let report = midas::sqlx::baseline_from_sqlx(&context.config, &options)?;
450 if report.inserted.is_empty() {
451 println!("No SQLx metadata needed to be baselined.");
452 } else {
453 println!(
454 "Baselined {} migration(s) from SQLx metadata.",
455 report.inserted.len()
456 );
457 }
458 if !report.skipped.is_empty() {
459 println!("Skipped {} already-applied migration(s).", report.skipped.len());
460 }
461 return Ok(());
462 }
463
464 let target = *matches
465 .get_one::<i64>("to")
466 .context("baseline version is required")?;
467 if target < 0 {
468 anyhow::bail!("baseline version must be non-negative");
469 }
470 with_migrator(context, false, |migrator| migrator.baseline(target)).map(drop)
471}
472
473fn export(matches: &ArgMatches, context: &Context) -> Result<()> {
474 let out = matches
475 .get_one::<String>("out")
476 .context("export directory is required")?;
477 let migrations = migration::discover(&context.config.migrations_dir)?;
478 let written = midas::sqlx::export_sqlx(&migrations, Path::new(out))?;
479 println!("Exported {} migration file(s) to `{out}`.", written.len());
480 Ok(())
481}
482
483fn import(matches: &ArgMatches, context: &Context) -> Result<()> {
484 let from = matches
485 .get_one::<String>("from")
486 .context("import directory is required")?;
487 let out = matches
488 .get_one::<String>("out")
489 .context("output directory is required")?;
490 let migrations = midas::sqlx::import_sqlx_with(Path::new(from), &context.config.sqlx)?;
491 let written = midas::sqlx::write_midas(&migrations, Path::new(out))?;
492 println!(
493 "Imported {} migration(s) into `{out}` ({} file(s)).",
494 migrations.len(),
495 written.len()
496 );
497 Ok(())
498}
499
500fn adopt(matches: &ArgMatches, context: &Context) -> Result<()> {
501 let table = matches
502 .get_one::<String>("table")
503 .map(String::as_str)
504 .unwrap_or("_sqlx_migrations");
505 let report = midas::sqlx::verify_adoption(&context.config, table)?;
506
507 println!(
508 "SQLx metadata table `{}` is adoptable ({} applied migration(s)).",
509 qualified_table_name(report.schema.as_deref(), &report.table),
510 report.applied.len()
511 );
512 if report.has_down_checksum {
513 println!("The table stores DOWN checksums.");
514 } else {
515 println!("No `down_checksum` column; DOWN checksums are validated from migration files on revert.");
516 }
517 println!("To keep using it, add to `midas.toml` [database]:");
518 if let Some(schema) = &report.schema {
519 println!(" metadata_schema = \"{schema}\"");
520 }
521 println!(" metadata_table = \"{}\"", report.table);
522 Ok(())
523}
524
525fn resolve(matches: &ArgMatches, context: &Context) -> Result<()> {
526 let applied = matches.get_flag("applied");
527 let rolled_back = matches.get_flag("rolled-back");
528 if applied == rolled_back {
529 anyhow::bail!("pass exactly one of --applied or --rolled-back");
530 }
531 let version = matches.get_one::<i64>("migration_version").copied();
532 if applied {
533 with_migrator(context, false, |migrator| migrator.resolve_applied(version)).map(drop)
534 } else {
535 with_migrator(context, false, |migrator| migrator.resolve_rolled_back(version)).map(drop)
536 }
537}
538
539fn output(matches: &ArgMatches, info: &MigrationInfo) -> Result<()> {
540 if matches.get_flag("json") {
541 println!("{}", serde_json::to_string(info)?);
542 }
543 Ok(())
544}
545
546pub(crate) fn with_migrator<F, T>(context: &Context, quiet: bool, action: F) -> Result<T>
547where
548 F: FnOnce(&mut Migrator) -> midas::Result<T>,
549{
550 context.config.require_database_url()?;
551 let migrations = migration::discover(&context.config.migrations_dir)?;
552 let backend = sequel::connect(&context.config)?;
553 let options = migrator_options(context, quiet);
554 let mut migrator = Migrator::new(backend, migrations).with_options(options);
555 Ok(action(&mut migrator)?)
556}
557
558fn migrator_options(context: &Context, quiet: bool) -> MigratorOptions {
559 MigratorOptions {
560 dry_run: context.dry_run,
561 no_lock: context.no_lock,
562 transaction: context.config.transaction,
563 quiet,
564 ignore_missing: context.ignore_missing,
565 }
566}
567
568fn project_template(config: &Config) -> String {
569 let dir = config.migrations_dir.to_string_lossy();
570 let dialect = configured_dialect(config);
571 let (default_schema, metadata_schema) = match dialect {
572 "sqlite" => ("default_schema = \"main\"\n".to_string(), String::new()),
573 _ => (
574 "default_schema = \"public\"\n".to_string(),
575 "metadata_schema = \"midas\"\n".to_string(),
576 ),
577 };
578 let managed_schema = if dialect == "sqlite" { "main" } else { "public" };
579
580 format!(
581 r#"# midas project configuration
582[project]
583dialect = "{dialect}"
584{default_schema}
585[database]
586url_env = "DATABASE_URL"
587{metadata_schema}metadata_table = "__schema_migrations"
588shadow_url_env = "SHADOW_DATABASE_URL"
589
590[migrations]
591dir = "{dir}"
592transaction = "per-migration"
593
594[managed]
595schemas = ["{managed_schema}"]
596ignore_objects = []
597"#
598 )
599}
600
601fn configured_dialect(config: &Config) -> &'static str {
602 config
603 .database_url
604 .as_deref()
605 .and_then(|url| midas::sequel::DatabaseEngine::from_url(url).ok())
606 .map(midas::sequel::DatabaseEngine::dialect_name)
607 .unwrap_or("postgres")
608}
609
610fn schema_template() -> &'static str {
611 "# midas schema DSL file.\n\
612 # Define tables, enums, and other schema objects here.\n"
613}
614
615#[cfg(test)]
616mod tests {
617 use super::*;
618
619 #[test]
620 fn owners_are_explicit() {
621 for name in [
622 "init", "add", "create", "run", "up", "info", "status", "list", "revert", "redo", "baseline", "repair",
623 "resolve", "reset", "down",
624 ] {
625 assert!(owns(name), "expected owner for `{name}`");
626 }
627 assert!(!owns("db"));
628 assert!(!owns("schema"));
629 }
630
631 #[test]
632 fn project_template_contains_migrations_dir() {
633 let config = Config {
634 migrations_dir: "custom_migrations".into(),
635 ..Config::default()
636 };
637 let template = project_template(&config);
638 assert!(template.contains("dir = \"custom_migrations\""));
639 assert!(template.contains("metadata_table = \"__schema_migrations\""));
640 }
641
642 #[test]
643 fn project_template_follows_the_configured_dialect() {
644 let sqlite = Config {
645 database_url: Some("sqlite://./app.db3".to_string()),
646 ..Config::default()
647 };
648 let template = project_template(&sqlite);
649 assert!(template.contains("dialect = \"sqlite\""));
650 assert!(!template.contains("metadata_schema"));
651
652 let cockroach = Config {
653 database_url: Some("cockroachdb://root@localhost:26257/app".to_string()),
654 ..Config::default()
655 };
656 let template = project_template(&cockroach);
657 assert!(template.contains("dialect = \"postgres\""));
658 assert!(template.contains("metadata_schema = \"midas\""));
659 }
660
661 #[test]
662 fn schema_template_is_comment_only() {
663 assert!(schema_template().lines().all(|line| line.starts_with('#')));
664 }
665}