midas-migrate-cli 0.8.2

Do painless migration 🦀
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
//! `midas setup` — one-command development bootstrap.

use std::path::{
  Path,
  PathBuf,
};

use anyhow::{
  bail,
  Context as _,
  Result,
};
use clap::{
  Arg,
  ArgAction,
  ArgMatches,
  Command,
};
use midas::commander::{
  Migrator,
  MigratorOptions,
};
use midas::config::ProcessEnv;
use midas::seed::{
  check_production,
  run,
  RunOptions,
  SeedFile,
  Summary,
};
use midas::{
  migration,
  sequel,
};
use midas_schema::schema::plan::Plan;
use midas_schema::schema::{
  self,
  state,
};
use serde::Serialize;

use crate::commands::{
  db_lifecycle,
  seed_meta,
  source,
  Context,
};

/// Build the `setup` subcommand.
pub fn command() -> Command {
  Command::new("setup")
    .about("Create the database, apply migrations or schema DDL, and seed it")
    .arg(
      Arg::new("schema")
        .long("schema")
        .value_name("path")
        .help("Schema source (defaults to the project schema source)")
        .num_args(1),
    )
    .arg(
      Arg::new("seed-file")
        .long("seed-file")
        .value_name("path")
        .help("Seed file (defaults to [seed].file or seed.toml)")
        .num_args(1),
    )
    .arg(
      Arg::new("from")
        .long("from")
        .value_name("source")
        .help("auto, migrations, or schema")
        .default_value("auto")
        .num_args(1),
    )
    .arg(
      Arg::new("no-seed")
        .long("no-seed")
        .help("Stop after the schema phase")
        .action(ArgAction::SetTrue),
    )
    .arg(
      Arg::new("state")
        .long("state")
        .value_name("path")
        .help("State snapshot path written after schema-source setup")
        .num_args(1),
    )
    .arg(
      Arg::new("no-state")
        .long("no-state")
        .help("Do not refresh the state snapshot")
        .action(ArgAction::SetTrue),
    )
    .arg(
      Arg::new("reset")
        .long("reset")
        .help("Clear selected tables before seeding")
        .action(ArgAction::SetTrue),
    )
    .arg(
      Arg::new("seed")
        .long("seed")
        .value_name("n")
        .help("Master seed")
        .num_args(1)
        .value_parser(clap::value_parser!(u64)),
    )
    .arg(
      Arg::new("json")
        .long("json")
        .help("Emit a machine-readable summary")
        .action(ArgAction::SetTrue),
    )
    .arg(
      Arg::new("yes")
        .long("yes")
        .help("Confirm destructive operations")
        .action(ArgAction::SetTrue),
    )
    .arg(
      Arg::new("accept-data-loss")
        .long("accept-data-loss")
        .help("Allow destructive schema changes")
        .action(ArgAction::SetTrue),
    )
    .arg(
      Arg::new("allow-production")
        .long("allow-production")
        .help("Allow running against production-like environments")
        .action(ArgAction::SetTrue),
    )
}

/// Register the command.
pub fn register(app: Command) -> Command {
  app.subcommand(command())
}

/// Whether this module owns the subcommand name.
pub fn owns(name: &str) -> bool {
  name == "setup"
}

/// Dispatch the command.
pub fn dispatch(_name: &str, matches: &ArgMatches, context: &Context) -> Result<()> {
  let json = matches.get_flag("json");
  match execute(matches, context) {
    Ok(()) => Ok(()),
    Err(error) => {
      if json {
        println!("{}", serde_json::json!({ "error": error.to_string() }));
      }
      Err(error)
    },
  }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum SourceMode {
  Migrations,
  Schema,
}

impl SourceMode {
  fn as_str(self) -> &'static str {
    match self {
      Self::Migrations => "migrations",
      Self::Schema => "schema",
    }
  }
}

#[derive(Debug, Serialize)]
struct SetupSummary {
  command: &'static str,
  dry_run: bool,
  source: &'static str,
  database_created: bool,
  seed: Option<Summary>,
  warnings: Vec<String>,
}

fn execute(matches: &ArgMatches, context: &Context) -> Result<()> {
  check_production(&ProcessEnv, matches.get_flag("allow-production"), context.dry_run)?;

  let reset = matches.get_flag("reset");
  if reset && !matches.get_flag("yes") {
    bail!("--reset requires --yes");
  }
  let state_flag = matches.get_one::<String>("state").is_some();
  if state_flag && matches.get_flag("no-state") {
    bail!("--state and --no-state are mutually exclusive");
  }
  let from = matches
    .get_one::<String>("from")
    .map(String::as_str)
    .unwrap_or("auto");
  if !matches!(from, "auto" | "migrations" | "schema") {
    bail!("--from must be auto, migrations, or schema, got `{from}`");
  }
  if from == "migrations" && state_flag {
    bail!("--state cannot be combined with --from migrations");
  }

  let migrations = migration::discover(&context.config.migrations_dir).unwrap_or_default();
  let schema_path = source::resolve(matches.get_one::<String>("schema").map(String::as_str)).ok();

  let mode = match from {
    "migrations" => SourceMode::Migrations,
    "schema" => SourceMode::Schema,
    _ => {
      if !migrations.is_empty() {
        SourceMode::Migrations
      } else if schema_path.as_ref().is_some_and(|path| path.exists()) {
        SourceMode::Schema
      } else {
        bail!(
          "nothing to apply: no migrations in `{}` and no schema source found",
          context.config.migrations_dir.to_string_lossy()
        );
      }
    },
  };

  if mode == SourceMode::Schema && !seed_meta::is_postgres(&context.config)? {
    return Err(midas::Error::unsupported_feature("sqlite", "schema-source setup").into());
  }

  let mut warnings = Vec::new();
  let mut database_created = false;

  if context.dry_run {
    println!(
      "Would create database `{}` if absent.",
      sequel::database_name(context.config.require_database_url()?)?
    );
    match mode {
      SourceMode::Migrations => {
        println!(
          "Would apply {} migration(s) from `{}`.",
          migrations.len(),
          context.config.migrations_dir.to_string_lossy()
        );
      },
      SourceMode::Schema => {
        let path = schema_path
          .as_ref()
          .ok_or_else(|| anyhow::anyhow!("schema source path is required for --from schema"))?;
        dry_run_schema(context, path)?;
      },
    }
  } else {
    database_created = db_lifecycle::ensure_database(context)?;
    match mode {
      SourceMode::Migrations => apply_migrations(context)?,
      SourceMode::Schema => {
        let path = schema_path
          .as_ref()
          .ok_or_else(|| anyhow::anyhow!("schema source path is required for --from schema"))?;
        apply_schema(context, path, matches.get_flag("accept-data-loss"))?;
        refresh_state(matches, context)?;
      },
    }
  }

  let seed = if matches.get_flag("no-seed") {
    None
  } else {
    seed_after(matches, context, mode, schema_path.as_deref(), &mut warnings)?
  };

  let summary = SetupSummary {
    command: "setup",
    dry_run: context.dry_run,
    source: mode.as_str(),
    database_created,
    seed,
    warnings,
  };
  if matches.get_flag("json") {
    println!(
      "{}",
      serde_json::to_string(&summary).context("failed to serialize setup summary")?
    );
  } else {
    println!("Setup source: {}", mode.as_str());
    for warning in &summary.warnings {
      eprintln!("warning: {warning}");
    }
    if context.dry_run {
      println!("Dry run: wrote nothing.");
    } else {
      println!("Setup complete.");
    }
  }
  Ok(())
}

fn apply_migrations(context: &Context) -> Result<()> {
  let migrations = migration::discover(&context.config.migrations_dir)?;
  let backend = sequel::connect(&context.config)?;
  let options = MigratorOptions {
    dry_run: false,
    no_lock: context.no_lock,
    transaction: context.config.transaction,
    quiet: false,
    ignore_missing: context.ignore_missing,
  };
  Migrator::new(backend, migrations)
    .with_options(options)
    .up(None)?;
  Ok(())
}

fn apply_schema(context: &Context, path: &Path, accept_data_loss: bool) -> Result<()> {
  let desired = schema::load_ir(path)?;
  let live = live_schema(context, &desired)?;
  let plan = Plan::try_between(&live, &desired)?;
  if plan.is_empty() {
    println!("Database already matches the schema.");
    return Ok(());
  }
  if plan.requires_data_loss() && !accept_data_loss {
    bail!("refusing destructive changes; pass --accept-data-loss");
  }
  let sql = schema::emit::alter::up(&plan);
  let mut backend = sequel::connect(&context.config)?;
  backend.execute_batch(&sql)?;
  println!("Applied {} schema change(s).", plan.changes().len());
  Ok(())
}

fn dry_run_schema(context: &Context, path: &Path) -> Result<()> {
  let desired = schema::load_ir(path)?;
  match live_schema(context, &desired) {
    Ok(live) => {
      let plan = Plan::try_between(&live, &desired)?;
      if plan.is_empty() {
        println!("Database already matches the schema.");
      } else {
        print!("{}", schema::emit::alter::up(&plan));
      }
    },
    Err(_) => {
      // The database is absent or unreachable; show the create-from-empty DDL.
      print!("{}", schema::create_sql(&desired)?);
    },
  }
  Ok(())
}

fn refresh_state(matches: &ArgMatches, context: &Context) -> Result<()> {
  if matches.get_flag("no-state") {
    return Ok(());
  }
  let path = matches
    .get_one::<String>("state")
    .map(PathBuf::from)
    .unwrap_or_else(state::default_path);
  let introspection = midas_schema::schema::introspect::introspect_config(&context.config)?;
  state::write(&path, &introspection.schema)?;
  println!("Updated state `{}`.", path.to_string_lossy());
  Ok(())
}

fn seed_after(
  matches: &ArgMatches,
  context: &Context,
  mode: SourceMode,
  schema_path: Option<&Path>,
  warnings: &mut Vec<String>,
) -> Result<Option<Summary>> {
  let seed_path: PathBuf = matches
    .get_one::<String>("seed-file")
    .map(PathBuf::from)
    .unwrap_or_else(|| context.config.seed.file.clone());
  if !seed_path.is_file() {
    warnings.push(format!(
      "seed file `{}` not found; skipping seeding",
      seed_path.to_string_lossy()
    ));
    return Ok(None);
  }
  let file = SeedFile::load(&seed_path, &context.config.seed).context("failed to load seed file")?;
  let dialect = seed_meta::dialect(&context.config)?;

  let (resolved, backend) = if context.dry_run {
    match seed_meta::live(&context.config) {
      Ok(resolved) => (resolved, None),
      Err(error) => match (mode, schema_path) {
        (SourceMode::Schema, Some(path)) => (seed_meta::offline(&context.config, path)?, None),
        _ => {
          warnings.push(format!(
            "cannot resolve seed metadata offline ({error}); skipping seeding"
          ));
          return Ok(None);
        },
      },
    }
  } else {
    let resolved = seed_meta::live(&context.config)?;
    let backend = midas::seed::connect(&context.config)?;
    (resolved, Some(backend))
  };
  warnings.extend(resolved.warnings.iter().cloned());

  let mut backend = backend;
  let options = RunOptions {
    command: "setup",
    file: &file,
    schema: &resolved.schema,
    settings: &context.config.seed,
    managed_schemas: &context.config.managed.schemas,
    default_schema: context.config.search_path.as_deref(),
    table_filters: &[],
    rows_override: None,
    reset: matches.get_flag("reset"),
    skip_existing: !matches.get_flag("reset"),
    dry_run: context.dry_run,
    no_lock: context.no_lock,
    master_seed: matches.get_one::<u64>("seed").copied(),
    dialect,
    warnings: &resolved.warnings,
  };
  let summary = match backend.as_deref_mut() {
    Some(backend) => run(Some(backend), &options)?,
    None => run(None, &options)?,
  };
  Ok(Some(summary))
}

fn live_schema(
  context: &Context,
  desired: &midas_schema::schema::ir::Schema,
) -> Result<midas_schema::schema::ir::Schema> {
  let mut schemas = context.config.managed.schemas.clone();
  if schemas.is_empty() {
    schemas.extend(desired.schemas.keys().cloned());
    if !desired.project.default_schema.is_empty() && !schemas.contains(&desired.project.default_schema) {
      schemas.push(desired.project.default_schema.clone());
    }
    if schemas.is_empty() {
      schemas.push("public".to_string());
    }
  }
  Ok(
    schema::introspect::introspect_with(
      &context.config,
      &schemas,
      &context.config.managed.ignore_objects,
      false,
    )?
    .schema,
  )
}

#[cfg(test)]
mod tests {
  use super::*;

  #[test]
  fn owns_setup_only() {
    assert!(owns("setup"));
    assert!(!owns("faker"));
  }

  #[test]
  fn command_registers_expected_flags() {
    let command = command();
    let names: Vec<&str> = command
      .get_arguments()
      .map(|argument| argument.get_id().as_str())
      .collect();
    for expected in [
      "schema",
      "seed-file",
      "from",
      "no-seed",
      "state",
      "no-state",
      "reset",
      "seed",
      "json",
      "yes",
      "accept-data-loss",
      "allow-production",
    ] {
      assert!(names.contains(&expected), "missing `{expected}`");
    }
  }
}