1use std::path::{
4 Path,
5 PathBuf,
6};
7
8use anyhow::{
9 bail,
10 Context as _,
11 Result,
12};
13use clap::{
14 Arg,
15 ArgAction,
16 ArgMatches,
17 Command,
18};
19use midas::commander::{
20 Migrator,
21 MigratorOptions,
22};
23use midas::config::ProcessEnv;
24use midas::seed::{
25 check_production,
26 run,
27 RunOptions,
28 SeedFile,
29 Summary,
30};
31use midas::{
32 migration,
33 sequel,
34};
35use midas_schema::schema::plan::Plan;
36use midas_schema::schema::{
37 self,
38 state,
39};
40use serde::Serialize;
41
42use crate::commands::{
43 db_lifecycle,
44 seed_meta,
45 source,
46 Context,
47};
48
49pub fn command() -> Command {
51 Command::new("setup")
52 .about("Create the database, apply migrations or schema DDL, and seed it")
53 .arg(
54 Arg::new("schema")
55 .long("schema")
56 .value_name("path")
57 .help("Schema source (defaults to the project schema source)")
58 .num_args(1),
59 )
60 .arg(
61 Arg::new("seed-file")
62 .long("seed-file")
63 .value_name("path")
64 .help("Seed file (defaults to [seed].file or seed.toml)")
65 .num_args(1),
66 )
67 .arg(
68 Arg::new("from")
69 .long("from")
70 .value_name("source")
71 .help("auto, migrations, or schema")
72 .default_value("auto")
73 .num_args(1),
74 )
75 .arg(
76 Arg::new("no-seed")
77 .long("no-seed")
78 .help("Stop after the schema phase")
79 .action(ArgAction::SetTrue),
80 )
81 .arg(
82 Arg::new("state")
83 .long("state")
84 .value_name("path")
85 .help("State snapshot path written after schema-source setup")
86 .num_args(1),
87 )
88 .arg(
89 Arg::new("no-state")
90 .long("no-state")
91 .help("Do not refresh the state snapshot")
92 .action(ArgAction::SetTrue),
93 )
94 .arg(
95 Arg::new("reset")
96 .long("reset")
97 .help("Clear selected tables before seeding")
98 .action(ArgAction::SetTrue),
99 )
100 .arg(
101 Arg::new("seed")
102 .long("seed")
103 .value_name("n")
104 .help("Master seed")
105 .num_args(1)
106 .value_parser(clap::value_parser!(u64)),
107 )
108 .arg(
109 Arg::new("json")
110 .long("json")
111 .help("Emit a machine-readable summary")
112 .action(ArgAction::SetTrue),
113 )
114 .arg(
115 Arg::new("yes")
116 .long("yes")
117 .help("Confirm destructive operations")
118 .action(ArgAction::SetTrue),
119 )
120 .arg(
121 Arg::new("accept-data-loss")
122 .long("accept-data-loss")
123 .help("Allow destructive schema changes")
124 .action(ArgAction::SetTrue),
125 )
126 .arg(
127 Arg::new("allow-production")
128 .long("allow-production")
129 .help("Allow running against production-like environments")
130 .action(ArgAction::SetTrue),
131 )
132}
133
134pub fn register(app: Command) -> Command {
136 app.subcommand(command())
137}
138
139pub fn owns(name: &str) -> bool {
141 name == "setup"
142}
143
144pub fn dispatch(_name: &str, matches: &ArgMatches, context: &Context) -> Result<()> {
146 let json = matches.get_flag("json");
147 match execute(matches, context) {
148 Ok(()) => Ok(()),
149 Err(error) => {
150 if json {
151 println!("{}", serde_json::json!({ "error": error.to_string() }));
152 }
153 Err(error)
154 },
155 }
156}
157
158#[derive(Debug, Clone, Copy, PartialEq, Eq)]
159enum SourceMode {
160 Migrations,
161 Schema,
162}
163
164impl SourceMode {
165 fn as_str(self) -> &'static str {
166 match self {
167 Self::Migrations => "migrations",
168 Self::Schema => "schema",
169 }
170 }
171}
172
173#[derive(Debug, Serialize)]
174struct SetupSummary {
175 command: &'static str,
176 dry_run: bool,
177 source: &'static str,
178 database_created: bool,
179 seed: Option<Summary>,
180 warnings: Vec<String>,
181}
182
183fn execute(matches: &ArgMatches, context: &Context) -> Result<()> {
184 check_production(&ProcessEnv, matches.get_flag("allow-production"), context.dry_run)?;
185
186 let reset = matches.get_flag("reset");
187 if reset && !matches.get_flag("yes") {
188 bail!("--reset requires --yes");
189 }
190 let state_flag = matches.get_one::<String>("state").is_some();
191 if state_flag && matches.get_flag("no-state") {
192 bail!("--state and --no-state are mutually exclusive");
193 }
194 let from = matches
195 .get_one::<String>("from")
196 .map(String::as_str)
197 .unwrap_or("auto");
198 if !matches!(from, "auto" | "migrations" | "schema") {
199 bail!("--from must be auto, migrations, or schema, got `{from}`");
200 }
201 if from == "migrations" && state_flag {
202 bail!("--state cannot be combined with --from migrations");
203 }
204
205 let migrations = migration::discover(&context.config.migrations_dir).unwrap_or_default();
206 let schema_path = source::resolve(matches.get_one::<String>("schema").map(String::as_str)).ok();
207
208 let mode = match from {
209 "migrations" => SourceMode::Migrations,
210 "schema" => SourceMode::Schema,
211 _ => {
212 if !migrations.is_empty() {
213 SourceMode::Migrations
214 } else if schema_path.as_ref().is_some_and(|path| path.exists()) {
215 SourceMode::Schema
216 } else {
217 bail!(
218 "nothing to apply: no migrations in `{}` and no schema source found",
219 context.config.migrations_dir.to_string_lossy()
220 );
221 }
222 },
223 };
224
225 if mode == SourceMode::Schema && !seed_meta::is_postgres(&context.config)? {
226 return Err(midas::Error::unsupported_feature("sqlite", "schema-source setup").into());
227 }
228
229 let mut warnings = Vec::new();
230 let mut database_created = false;
231
232 if context.dry_run {
233 println!(
234 "Would create database `{}` if absent.",
235 sequel::database_name(context.config.require_database_url()?)?
236 );
237 match mode {
238 SourceMode::Migrations => {
239 println!(
240 "Would apply {} migration(s) from `{}`.",
241 migrations.len(),
242 context.config.migrations_dir.to_string_lossy()
243 );
244 },
245 SourceMode::Schema => {
246 let path = schema_path
247 .as_ref()
248 .ok_or_else(|| anyhow::anyhow!("schema source path is required for --from schema"))?;
249 dry_run_schema(context, path)?;
250 },
251 }
252 } else {
253 database_created = db_lifecycle::ensure_database(context)?;
254 match mode {
255 SourceMode::Migrations => apply_migrations(context)?,
256 SourceMode::Schema => {
257 let path = schema_path
258 .as_ref()
259 .ok_or_else(|| anyhow::anyhow!("schema source path is required for --from schema"))?;
260 apply_schema(context, path, matches.get_flag("accept-data-loss"))?;
261 refresh_state(matches, context)?;
262 },
263 }
264 }
265
266 let seed = if matches.get_flag("no-seed") {
267 None
268 } else {
269 seed_after(matches, context, mode, schema_path.as_deref(), &mut warnings)?
270 };
271
272 let summary = SetupSummary {
273 command: "setup",
274 dry_run: context.dry_run,
275 source: mode.as_str(),
276 database_created,
277 seed,
278 warnings,
279 };
280 if matches.get_flag("json") {
281 println!(
282 "{}",
283 serde_json::to_string(&summary).context("failed to serialize setup summary")?
284 );
285 } else {
286 println!("Setup source: {}", mode.as_str());
287 for warning in &summary.warnings {
288 eprintln!("warning: {warning}");
289 }
290 if context.dry_run {
291 println!("Dry run: wrote nothing.");
292 } else {
293 println!("Setup complete.");
294 }
295 }
296 Ok(())
297}
298
299fn apply_migrations(context: &Context) -> Result<()> {
300 let migrations = migration::discover(&context.config.migrations_dir)?;
301 let backend = sequel::connect(&context.config)?;
302 let options = MigratorOptions {
303 dry_run: false,
304 no_lock: context.no_lock,
305 transaction: context.config.transaction,
306 quiet: false,
307 ignore_missing: context.ignore_missing,
308 };
309 Migrator::new(backend, migrations)
310 .with_options(options)
311 .up(None)?;
312 Ok(())
313}
314
315fn apply_schema(context: &Context, path: &Path, accept_data_loss: bool) -> Result<()> {
316 let desired = schema::load_ir(path)?;
317 let live = live_schema(context, &desired)?;
318 let plan = Plan::try_between(&live, &desired)?;
319 if plan.is_empty() {
320 println!("Database already matches the schema.");
321 return Ok(());
322 }
323 if plan.requires_data_loss() && !accept_data_loss {
324 bail!("refusing destructive changes; pass --accept-data-loss");
325 }
326 let sql = schema::emit::alter::up(&plan);
327 let mut backend = sequel::connect(&context.config)?;
328 backend.execute_batch(&sql)?;
329 println!("Applied {} schema change(s).", plan.changes().len());
330 Ok(())
331}
332
333fn dry_run_schema(context: &Context, path: &Path) -> Result<()> {
334 let desired = schema::load_ir(path)?;
335 match live_schema(context, &desired) {
336 Ok(live) => {
337 let plan = Plan::try_between(&live, &desired)?;
338 if plan.is_empty() {
339 println!("Database already matches the schema.");
340 } else {
341 print!("{}", schema::emit::alter::up(&plan));
342 }
343 },
344 Err(_) => {
345 print!("{}", schema::create_sql(&desired)?);
347 },
348 }
349 Ok(())
350}
351
352fn refresh_state(matches: &ArgMatches, context: &Context) -> Result<()> {
353 if matches.get_flag("no-state") {
354 return Ok(());
355 }
356 let path = matches
357 .get_one::<String>("state")
358 .map(PathBuf::from)
359 .unwrap_or_else(state::default_path);
360 let introspection = midas_schema::schema::introspect::introspect_config(&context.config)?;
361 state::write(&path, &introspection.schema)?;
362 println!("Updated state `{}`.", path.to_string_lossy());
363 Ok(())
364}
365
366fn seed_after(
367 matches: &ArgMatches,
368 context: &Context,
369 mode: SourceMode,
370 schema_path: Option<&Path>,
371 warnings: &mut Vec<String>,
372) -> Result<Option<Summary>> {
373 let seed_path: PathBuf = matches
374 .get_one::<String>("seed-file")
375 .map(PathBuf::from)
376 .unwrap_or_else(|| context.config.seed.file.clone());
377 if !seed_path.is_file() {
378 warnings.push(format!(
379 "seed file `{}` not found; skipping seeding",
380 seed_path.to_string_lossy()
381 ));
382 return Ok(None);
383 }
384 let file = SeedFile::load(&seed_path, &context.config.seed).context("failed to load seed file")?;
385 let dialect = seed_meta::dialect(&context.config)?;
386
387 let (resolved, backend) = if context.dry_run {
388 match seed_meta::live(&context.config) {
389 Ok(resolved) => (resolved, None),
390 Err(error) => match (mode, schema_path) {
391 (SourceMode::Schema, Some(path)) => (seed_meta::offline(&context.config, path)?, None),
392 _ => {
393 warnings.push(format!(
394 "cannot resolve seed metadata offline ({error}); skipping seeding"
395 ));
396 return Ok(None);
397 },
398 },
399 }
400 } else {
401 let resolved = seed_meta::live(&context.config)?;
402 let backend = midas::seed::connect(&context.config)?;
403 (resolved, Some(backend))
404 };
405 warnings.extend(resolved.warnings.iter().cloned());
406
407 let mut backend = backend;
408 let options = RunOptions {
409 command: "setup",
410 file: &file,
411 schema: &resolved.schema,
412 settings: &context.config.seed,
413 managed_schemas: &context.config.managed.schemas,
414 default_schema: context.config.search_path.as_deref(),
415 table_filters: &[],
416 rows_override: None,
417 reset: matches.get_flag("reset"),
418 skip_existing: !matches.get_flag("reset"),
419 dry_run: context.dry_run,
420 no_lock: context.no_lock,
421 master_seed: matches.get_one::<u64>("seed").copied(),
422 dialect,
423 warnings: &resolved.warnings,
424 };
425 let summary = match backend.as_deref_mut() {
426 Some(backend) => run(Some(backend), &options)?,
427 None => run(None, &options)?,
428 };
429 Ok(Some(summary))
430}
431
432fn live_schema(
433 context: &Context,
434 desired: &midas_schema::schema::ir::Schema,
435) -> Result<midas_schema::schema::ir::Schema> {
436 let mut schemas = context.config.managed.schemas.clone();
437 if schemas.is_empty() {
438 schemas.extend(desired.schemas.keys().cloned());
439 if !desired.project.default_schema.is_empty() && !schemas.contains(&desired.project.default_schema) {
440 schemas.push(desired.project.default_schema.clone());
441 }
442 if schemas.is_empty() {
443 schemas.push("public".to_string());
444 }
445 }
446 Ok(
447 schema::introspect::introspect_with(
448 &context.config,
449 &schemas,
450 &context.config.managed.ignore_objects,
451 false,
452 )?
453 .schema,
454 )
455}
456
457#[cfg(test)]
458mod tests {
459 use super::*;
460
461 #[test]
462 fn owns_setup_only() {
463 assert!(owns("setup"));
464 assert!(!owns("faker"));
465 }
466
467 #[test]
468 fn command_registers_expected_flags() {
469 let command = command();
470 let names: Vec<&str> = command
471 .get_arguments()
472 .map(|argument| argument.get_id().as_str())
473 .collect();
474 for expected in [
475 "schema",
476 "seed-file",
477 "from",
478 "no-seed",
479 "state",
480 "no-state",
481 "reset",
482 "seed",
483 "json",
484 "yes",
485 "accept-data-loss",
486 "allow-production",
487 ] {
488 assert!(names.contains(&expected), "missing `{expected}`");
489 }
490 }
491}