midas_cli/commands/
migrate_dev.rs1use std::path::{
4 Path,
5 PathBuf,
6};
7
8use anyhow::{
9 Context as _,
10 Result,
11};
12use clap::{
13 Arg,
14 ArgMatches,
15 Command,
16};
17use midas_schema::schema::plan::Plan;
18use midas_schema::schema::{
19 self,
20 ir,
21 state,
22};
23
24use crate::commands::{
25 source,
26 Context,
27};
28
29pub fn dev_command() -> Command {
31 Command::new("dev")
32 .about("Diff the schema source against .midas/state.json and generate a migration")
33 .arg(
34 Arg::new("name")
35 .long("name")
36 .value_name("name")
37 .help("Migration name")
38 .default_value("schema")
39 .num_args(1),
40 )
41 .arg(
42 Arg::new("schema")
43 .long("schema")
44 .value_name("path")
45 .help("Schema file or directory (defaults to the project schema source)")
46 .num_args(1),
47 )
48 .arg(
49 Arg::new("state")
50 .long("state")
51 .value_name("path")
52 .help("State snapshot path")
53 .num_args(1),
54 )
55 .arg(
56 Arg::new("create-only")
57 .long("create-only")
58 .help("Write the migration without applying it or updating state")
59 .action(clap::ArgAction::SetTrue),
60 )
61 .arg(
62 Arg::new("force")
63 .long("force")
64 .help("Ignore drift between the state snapshot and the shadow database")
65 .action(clap::ArgAction::SetTrue),
66 )
67 .arg(
68 Arg::new("accept-data-loss")
69 .long("accept-data-loss")
70 .help("Allow destructive or irreversible changes")
71 .action(clap::ArgAction::SetTrue),
72 )
73 .arg(
74 Arg::new("json")
75 .long("json")
76 .help("Emit a machine-readable plan summary")
77 .action(clap::ArgAction::SetTrue),
78 )
79}
80
81pub fn diff_command() -> Command {
83 Command::new("diff")
84 .about("Diff two schema sources without touching a database")
85 .arg(
86 Arg::new("from")
87 .long("from")
88 .value_name("path")
89 .help("Current schema or state snapshot")
90 .required(true)
91 .num_args(1),
92 )
93 .arg(
94 Arg::new("to")
95 .long("to")
96 .value_name("path")
97 .help("Desired schema or state snapshot")
98 .required(true)
99 .num_args(1),
100 )
101 .arg(
102 Arg::new("script")
103 .long("script")
104 .help("Print UP/DOWN SQL instead of a summary")
105 .action(clap::ArgAction::SetTrue),
106 )
107 .arg(
108 Arg::new("json")
109 .long("json")
110 .help("Emit a machine-readable plan summary")
111 .action(clap::ArgAction::SetTrue),
112 )
113}
114
115pub fn dispatch(name: &str, matches: &ArgMatches, context: &Context) -> Result<()> {
117 match name {
118 "dev" => dev(matches, context),
119 "diff" => diff(matches),
120 other => anyhow::bail!("unknown development migration command `{other}`"),
121 }
122}
123
124fn dev(matches: &ArgMatches, context: &Context) -> Result<()> {
125 let schema_path = source::resolve(matches.get_one::<String>("schema").map(String::as_str))?;
126 let state_path = matches
127 .get_one::<String>("state")
128 .map(PathBuf::from)
129 .unwrap_or_else(state::default_path);
130 let desired = schema::load_ir(&schema_path)?;
131 let snapshot = state::read_optional(&state_path)?;
132 let mut current = snapshot
133 .as_ref()
134 .map(|snapshot| snapshot.schema.clone())
135 .unwrap_or_else(ir::Schema::default);
136 let create_only = matches.get_flag("create-only");
137 let _shadow = if !create_only && !context.dry_run && is_postgres(context)? {
138 let shadow = schema::shadow::ShadowDb::create(&context.config)?;
139 shadow.replay()?;
140 let shadow_schema = schema::introspect::introspect_with(
141 &shadow.config(),
142 &context.config.managed.schemas,
143 &context.config.managed.ignore_objects,
144 false,
145 )?
146 .schema;
147 let live_schema = schema::introspect::introspect_with(
148 &context.config,
149 &context.config.managed.schemas,
150 &context.config.managed.ignore_objects,
151 false,
152 )?
153 .schema;
154 let drift = Plan::between(&live_schema, &shadow_schema);
155 if !drift.is_empty() && !matches.get_flag("force") {
156 let summary = drift
157 .changes()
158 .iter()
159 .map(|change| change.summary())
160 .collect::<Vec<_>>()
161 .join("; ");
162 anyhow::bail!(
163 "drift detected between the live database and the shadow database: {summary}; pass --force to ignore"
164 );
165 }
166 current = shadow_schema;
167 Some(shadow)
168 } else {
169 None
170 };
171 let plan = Plan::try_between(¤t, &desired)?;
172
173 if plan.is_empty() {
174 if matches.get_flag("json") {
175 println!(
176 "{}",
177 serde_json::to_string(&serde_json::json!({
178 "changes": 0,
179 "migration": serde_json::Value::Null,
180 }))?
181 );
182 } else {
183 println!("No schema changes.");
184 }
185 return Ok(());
186 }
187
188 let accept = matches.get_flag("accept-data-loss");
189 if plan.requires_data_loss() && !accept {
190 let mut message = String::from("refusing destructive or irreversible changes:\n");
191 for change in plan.changes() {
192 let meta = change.meta();
193 if meta.destructive || meta.irreversible {
194 message.push_str(&format!(" - {}\n", change.summary()));
195 }
196 }
197 message.push_str("pass --accept-data-loss to continue");
198 anyhow::bail!(message);
199 }
200
201 if context.dry_run {
202 if matches.get_flag("json") {
203 println!("{}", serde_json::to_string(&plan.summary())?);
204 } else {
205 print!("{}", schema::emit::alter::migration(&plan));
206 }
207 return Ok(());
208 }
209
210 let name = matches
211 .get_one::<String>("name")
212 .map(String::as_str)
213 .unwrap_or("schema");
214 let version = midas::migration::create_migration_file(&context.config.migrations_dir, name, false)
215 .context("failed to create migration file")?;
216 let migration_path = find_migration(&context.config.migrations_dir, version)?;
217 std::fs::write(&migration_path, schema::emit::alter::migration(&plan))?;
218
219 if plan.requires_no_transaction() {
220 println!("Migration disables the transaction wrapper.");
221 }
222 println!(
223 "Created migration `{}` with {} change(s).",
224 migration_path.to_string_lossy(),
225 plan.changes().len()
226 );
227
228 if create_only {
229 if matches.get_flag("json") {
230 println!(
231 "{}",
232 serde_json::to_string(&serde_json::json!({
233 "changes": plan.changes().len(),
234 "migration": migration_path.to_string_lossy(),
235 "applied": false,
236 }))?
237 );
238 }
239 return Ok(());
240 }
241
242 crate::commands::migrate::with_migrator(context, false, |migrator| migrator.up(None))
243 .context("failed to apply the generated migration")?;
244 state::write(&state_path, &desired)?;
245
246 if matches.get_flag("json") {
247 println!(
248 "{}",
249 serde_json::to_string(&serde_json::json!({
250 "changes": plan.changes().len(),
251 "migration": migration_path.to_string_lossy(),
252 "applied": true,
253 }))?
254 );
255 } else {
256 println!("Applied migration and updated {}.", state_path.to_string_lossy());
257 }
258 Ok(())
259}
260
261fn diff(matches: &ArgMatches) -> Result<()> {
262 let from = matches.get_one::<String>("from").context("--from is required")?;
263 let to = matches.get_one::<String>("to").context("--to is required")?;
264 let current = load_source(Path::new(from))?;
265 let desired = load_source(Path::new(to))?;
266 let plan = Plan::try_between(¤t, &desired)?;
267
268 if matches.get_flag("script") {
269 print!("{}", schema::emit::alter::migration(&plan));
270 return Ok(());
271 }
272 if matches.get_flag("json") {
273 println!("{}", serde_json::to_string(&plan.summary())?);
274 return Ok(());
275 }
276 if plan.is_empty() {
277 println!("No schema changes.");
278 return Ok(());
279 }
280 for change in plan.changes() {
281 let meta = change.meta();
282 let marker = if meta.irreversible {
283 "irreversible"
284 } else if meta.destructive {
285 "destructive"
286 } else {
287 "safe"
288 };
289 println!("[{marker}] {}", change.summary());
290 }
291 Ok(())
292}
293
294fn load_source(path: &Path) -> Result<ir::Schema> {
295 match path.extension().and_then(|extension| extension.to_str()) {
296 Some("json") => Ok(state::read(path)?.schema),
297 Some("toml") | Some("midas") => Ok(schema::load_ir(path)?),
298 _ => anyhow::bail!(
299 "unsupported schema source `{}`; expected .toml, .midas, or .json",
300 path.to_string_lossy()
301 ),
302 }
303}
304
305fn find_migration(dir: &Path, version: i64) -> Result<PathBuf> {
306 let prefix = format!("{version:013}_");
307 let mut matches = std::fs::read_dir(dir)?
308 .filter_map(|entry| entry.ok())
309 .map(|entry| entry.path())
310 .filter(|path| {
311 path
312 .file_name()
313 .and_then(|name| name.to_str())
314 .is_some_and(|name| name.starts_with(&prefix) && name.ends_with(".sql"))
315 })
316 .collect::<Vec<_>>();
317 matches.sort();
318 matches
319 .into_iter()
320 .next()
321 .ok_or_else(|| anyhow::anyhow!("generated migration not found in `{}`", dir.to_string_lossy()))
322}
323
324fn is_postgres(context: &Context) -> Result<bool> {
325 let url = context.config.require_database_url()?;
326 Ok(matches!(
327 midas::sequel::DatabaseEngine::from_url(url)?,
328 midas::sequel::DatabaseEngine::Postgres | midas::sequel::DatabaseEngine::CockroachDb
329 ))
330}
331
332#[cfg(test)]
333mod tests {
334 use super::*;
335
336 #[test]
337 fn command_group_has_dev_and_diff() {
338 assert_eq!(dev_command().get_name(), "dev");
339 assert_eq!(diff_command().get_name(), "diff");
340 }
341}