midas_cli/commands/
db_lifecycle.rs1use anyhow::{
4 Context as _,
5 Result,
6};
7use clap::{
8 Arg,
9 ArgMatches,
10 Command,
11};
12use midas::commander::{
13 Migrator,
14 MigratorOptions,
15};
16use midas::config::Config;
17use midas::{
18 migration,
19 sequel,
20};
21
22use crate::commands::Context;
23
24pub fn subcommands() -> Vec<Command> {
26 vec![
27 Command::new("create")
28 .about("Create the configured database")
29 .arg(
30 Arg::new("from-migrations")
31 .long("from-migrations")
32 .value_name("dir")
33 .help("Apply migrations from this directory after creating the database")
34 .num_args(1),
35 )
36 .arg(
37 Arg::new("from-schema")
38 .long("from-schema")
39 .value_name("path")
40 .help("Apply the schema DSL create-from-empty SQL")
41 .num_args(1),
42 ),
43 Command::new("drop").about("Drop the configured database").arg(
44 Arg::new("force")
45 .long("force")
46 .help("Skip confirmation checks")
47 .action(clap::ArgAction::SetTrue),
48 ),
49 Command::new("reset").about("Drop and recreate the configured database"),
50 Command::new("exists").about("Check whether the configured database exists"),
51 ]
52}
53
54pub fn owns(name: &str) -> bool {
56 matches!(name, "create" | "drop" | "reset" | "exists")
57}
58
59pub fn dispatch(name: &str, matches: &ArgMatches, context: &Context) -> Result<()> {
61 match name {
62 "create" => create(
63 context,
64 matches.get_one::<String>("from-migrations"),
65 matches.get_one::<String>("from-schema"),
66 ),
67 "drop" => drop_database(context),
68 "reset" => {
69 drop_database(context)?;
70 create(context, None, None)
71 },
72 "exists" => exists(context),
73 other => anyhow::bail!("unknown db lifecycle subcommand `{other}`"),
74 }
75}
76
77fn create(context: &Context, from_migrations: Option<&String>, from_schema: Option<&String>) -> Result<()> {
78 ensure_database(context)?;
79
80 if let Some(dir) = from_migrations {
81 let mut config = context.config.clone();
82 config.migrations_dir = dir.into();
83 apply_migrations(&config, context)?;
84 }
85
86 if let Some(path) = from_schema {
87 let desired = midas_schema::schema::load_ir(std::path::Path::new(path))?;
88 let sql = midas_schema::schema::create_sql(&desired)?;
89 if !context.dry_run {
90 let mut backend = sequel::connect(&context.config)?;
91 backend.execute_batch(&sql)?;
92 }
93 println!("Applied schema DSL from `{path}`.");
94 }
95
96 Ok(())
97}
98
99pub(crate) fn ensure_database(context: &Context) -> Result<bool> {
101 let database_url = context.config.require_database_url()?;
102 let name = sequel::database_name(database_url)?;
103 let mut admin = sequel::connect_admin(&context.config)?;
104
105 if admin.database_exists(&name)? {
106 println!("Database `{name}` already exists.");
107 return Ok(false);
108 }
109
110 if context.dry_run {
111 println!("Would create database `{name}`.");
112 return Ok(false);
113 }
114
115 admin
116 .create_database(&name)
117 .with_context(|| format!("failed to create database `{name}`"))?;
118 println!("Created database `{name}`.");
119 Ok(true)
120}
121
122fn drop_database(context: &Context) -> Result<()> {
123 let database_url = context.config.require_database_url()?;
124 let name = sequel::database_name(database_url)?;
125 let mut admin = sequel::connect_admin(&context.config)?;
126
127 if !admin.database_exists(&name)? {
128 println!("Database `{name}` does not exist.");
129 return Ok(());
130 }
131
132 admin
133 .force_drop_database(&name)
134 .with_context(|| format!("failed to drop database `{name}`"))?;
135 println!("Dropped database `{name}`.");
136 Ok(())
137}
138
139fn exists(context: &Context) -> Result<()> {
140 let database_url = context.config.require_database_url()?;
141 let name = sequel::database_name(database_url)?;
142 let mut admin = sequel::connect_admin(&context.config)?;
143 let exists = admin.database_exists(&name)?;
144 if exists {
145 println!("Database `{name}` exists.");
146 } else {
147 println!("Database `{name}` does not exist.");
148 }
149 Ok(())
150}
151
152fn apply_migrations(config: &Config, context: &Context) -> Result<()> {
153 let migrations = migration::discover(&config.migrations_dir)?;
154 let backend = sequel::connect(config)?;
155 let options = MigratorOptions {
156 dry_run: context.dry_run,
157 no_lock: context.no_lock,
158 transaction: config.transaction,
159 quiet: false,
160 ignore_missing: context.ignore_missing,
161 };
162 let mut migrator = Migrator::new(backend, migrations).with_options(options);
163 migrator.up(None)?;
164 Ok(())
165}
166
167#[cfg(test)]
168mod tests {
169 use super::*;
170
171 #[test]
172 fn owns_lifecycle_commands() {
173 for name in ["create", "drop", "reset", "exists"] {
174 assert!(owns(name));
175 }
176 assert!(!owns("pull"));
177 }
178}