pgmt 0.4.9

PostgreSQL migration tool that keeps your schema files as the source of truth
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
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
mod baseline;
mod catalog;
mod commands;
mod config;
mod constants;
mod db;
mod diff;
mod docker;
mod migrate;
mod migration;
mod migration_tracking;
mod progress;
mod prompts;
mod render;
mod schema_generator;
mod schema_loader;
mod schema_ops;
mod validation;
mod validation_output;

use crate::commands::apply::ExecutionMode;
use crate::commands::diff_output::DiffFormat;
use anyhow::Result;
use clap::{Parser, Subcommand};
use dotenv::dotenv;
use tracing::info;
use tracing_subscriber::{EnvFilter, fmt};

#[derive(Parser)]
#[command(author, version, about, long_about = None)]
struct Cli {
    #[arg(long, default_value = "pgmt.yaml", global = true)]
    config_file: String,

    /// Enable verbose output (info level)
    #[arg(long, short = 'v', global = true)]
    verbose: bool,

    /// Suppress all non-essential output (error level only)
    #[arg(long, short = 'q', global = true)]
    quiet: bool,

    /// Enable debug output (debug level)
    #[arg(long, global = true)]
    debug: bool,

    #[command(subcommand)]
    command: Commands,
}

#[derive(Parser)]
struct ApplyArgs {
    /// Show what would be applied without making any changes
    #[arg(long, group = "mode")]
    dry_run: bool,

    /// Apply all changes without confirmation prompts
    #[arg(long, group = "mode")]
    force: bool,

    /// Apply only safe operations, skip destructive changes
    #[arg(long, group = "mode")]
    safe_only: bool,

    /// Fail if destructive operations exist (default in non-interactive mode)
    #[arg(long, group = "mode")]
    require_approval: bool,

    /// Watch for schema file changes and continuously apply them
    #[arg(long)]
    watch: bool,

    #[command(flatten)]
    database_args: config::DatabaseArgs,

    #[command(flatten)]
    directory_args: config::DirectoryArgs,

    #[command(flatten)]
    object_filter_args: config::ObjectFilterArgs,
}

/// Arguments for pgmt diff (schema vs dev)
#[derive(Parser, Debug)]
pub struct DiffArgs {
    /// Output format
    #[arg(long, value_enum, default_value = "detailed")]
    pub format: DiffFormat,

    /// Save SQL output to file
    #[arg(long)]
    pub output_sql: Option<String>,

    #[command(flatten)]
    pub database_args: config::DatabaseArgs,

    #[command(flatten)]
    pub directory_args: config::DirectoryArgs,
}

/// Arguments for pgmt migrate diff (schema vs target)
#[derive(Parser, Debug)]
pub struct MigrateDiffArgs {
    /// Output format
    #[arg(long, value_enum, default_value = "detailed")]
    pub format: DiffFormat,

    /// Save SQL output to file
    #[arg(long)]
    pub output_sql: Option<String>,

    #[command(flatten)]
    pub database_args: config::DatabaseArgs,

    #[command(flatten)]
    pub directory_args: config::DirectoryArgs,
}

#[derive(Subcommand)]
enum Commands {
    /// Initialize project
    Init(commands::init::InitArgs),

    /// Apply modular schema files to development database
    Apply(ApplyArgs),

    /// Migration commands
    Migrate {
        #[command(subcommand)]
        command: MigrateCommands,
    },

    /// Compare schema files with dev database (preview what apply would do)
    Diff(DiffArgs),

    /// Validate schema consistency
    Validate,

    /// Manage configuration
    Config {
        #[command(subcommand)]
        command: Option<commands::config::ConfigCommands>,
    },

    /// Debug commands for troubleshooting
    Debug {
        #[command(subcommand)]
        command: DebugCommands,
    },
}

#[derive(Subcommand)]
enum MigrateCommands {
    /// Check target database for schema drift
    Diff(MigrateDiffArgs),

    /// Generate migration from diff
    New {
        /// Description for the migration
        description: Option<String>,

        /// Create a baseline file alongside the migration
        #[arg(long)]
        create_baseline: bool,

        #[command(flatten)]
        database_args: config::DatabaseArgs,

        #[command(flatten)]
        directory_args: config::DirectoryArgs,
    },

    /// Update the latest migration with current changes
    Update {
        /// Migration version to update (e.g., V1734567890). If not provided, updates latest migration.
        migration_version: Option<String>,

        /// Create backup of original migration before updating
        #[arg(long)]
        backup: bool,

        /// Preview changes without applying them
        #[arg(long)]
        dry_run: bool,

        #[command(flatten)]
        database_args: config::DatabaseArgs,

        #[command(flatten)]
        directory_args: config::DirectoryArgs,
    },

    /// Apply explicit migrations
    Apply {
        #[command(flatten)]
        database_args: config::DatabaseArgs,

        #[command(flatten)]
        directory_args: config::DirectoryArgs,
    },

    /// Check migration status
    Status {
        #[command(flatten)]
        database_args: config::DatabaseArgs,
    },

    /// Validate migration consistency (for CI)
    Validate {
        #[command(flatten)]
        database_args: config::DatabaseArgs,

        #[command(flatten)]
        directory_args: config::DirectoryArgs,

        /// Output format: human (default), json
        #[arg(long, default_value = "human")]
        format: String,

        /// Suppress verbose output (useful with --format=json)
        #[arg(long)]
        quiet: bool,

        /// Show detailed validation information
        #[arg(long)]
        verbose: bool,

        /// Ignore specific migrations during validation
        #[arg(long, value_delimiter = ',')]
        ignore_migrations: Vec<String>,
    },

    /// Create a baseline and optionally consolidate old migrations
    Baseline(MigrateBaselineArgs),
}

#[derive(clap::Args)]
struct MigrateBaselineArgs {
    #[command(subcommand)]
    command: Option<MigrateBaselineSubcommands>,

    /// Skip safety checks and force baseline creation
    #[arg(long)]
    force: bool,

    /// Don't delete old migrations after creating the baseline
    #[arg(long)]
    keep_migrations: bool,

    /// Preview what would happen without making changes
    #[arg(long)]
    dry_run: bool,

    #[command(flatten)]
    database_args: config::DatabaseArgs,

    #[command(flatten)]
    directory_args: config::DirectoryArgs,
}

#[derive(Subcommand)]
enum MigrateBaselineSubcommands {
    /// List existing baselines
    List,
}

#[derive(Subcommand)]
enum DebugCommands {
    /// Show object dependencies (intrinsic from PostgreSQL + augmented from -- require:)
    Dependencies {
        /// Output format
        #[arg(long, value_enum, default_value = "json")]
        format: DebugOutputFormat,

        /// Filter to specific object (e.g., "public.users" or "Table:public.users")
        #[arg(long)]
        object: Option<String>,

        #[command(flatten)]
        directory_args: config::DirectoryArgs,
    },
}

#[derive(clap::ValueEnum, Clone, Debug, PartialEq)]
pub enum DebugOutputFormat {
    /// JSON output for piping to jq
    Json,
    /// Human-readable text format
    Text,
}

#[tokio::main]
async fn main() -> Result<()> {
    dotenv().ok();
    let cli = Cli::parse();
    initialize_logging(&cli);
    let result = tokio::select! {
        result = run_main(cli) => result,
        _ = wait_for_shutdown_signal() => {
            info!("Received shutdown signal, cleaning up...");
            Ok(())
        }
    };

    if let Err(e) = docker::cleanup_all_containers().await {
        eprintln!("Warning: Failed to cleanup Docker containers: {}", e);
    }

    result
}

async fn wait_for_shutdown_signal() {
    use tokio::signal;

    let ctrl_c = async {
        signal::ctrl_c()
            .await
            .expect("failed to install Ctrl+C handler");
    };

    #[cfg(unix)]
    let terminate = async {
        signal::unix::signal(signal::unix::SignalKind::terminate())
            .expect("failed to install signal handler")
            .recv()
            .await;
    };

    #[cfg(not(unix))]
    let terminate = std::future::pending::<()>();

    tokio::select! {
        _ = ctrl_c => {},
        _ = terminate => {},
    }
}

fn initialize_logging(cli: &Cli) {
    let level = if cli.debug {
        "debug"
    } else if cli.verbose {
        "info"
    } else if cli.quiet {
        "error"
    } else {
        "warn" // default level
    };

    let filter = if std::env::var("RUST_LOG").is_ok() {
        EnvFilter::from_default_env()
    } else {
        EnvFilter::new(level)
    };

    fmt().with_env_filter(filter).with_target(false).init();
}

async fn run_main(cli: Cli) -> Result<()> {
    match &cli.command {
        Commands::Init(args) => commands::cmd_init_with_args(args).await,
        _ => {
            let (file_config, root_dir) = config::load_config(&cli.config_file)?;

            match &cli.command {
                Commands::Init(_) => unreachable!(),
                Commands::Apply(args) => {
                    let cli_config = config::ConfigInput {
                        databases: Some(args.database_args.clone().into()),
                        directories: Some(args.directory_args.clone().into()),
                        objects: Some(args.object_filter_args.clone().into()),
                        migration: None,
                        schema: None,
                        docker: None,
                    };

                    let config = config::ConfigBuilder::new()
                        .with_file(file_config.clone())
                        .with_cli_args(cli_config)
                        .resolve()?;

                    use commands::apply::ApplyOutcome;
                    use std::io::IsTerminal;

                    let execution_mode = if args.dry_run {
                        ExecutionMode::DryRun
                    } else if args.force {
                        ExecutionMode::Force
                    } else if args.safe_only {
                        ExecutionMode::SafeOnly
                    } else if args.require_approval {
                        ExecutionMode::RequireApproval
                    } else if std::io::stdin().is_terminal() {
                        // Interactive: auto-apply safe, prompt for destructive
                        ExecutionMode::Interactive
                    } else {
                        // Non-interactive: fail if destructive
                        ExecutionMode::RequireApproval
                    };

                    info!("Applying modular schema to dev");
                    let outcome = if args.watch {
                        commands::cmd_apply_watch(&config, &root_dir, execution_mode).await?
                    } else {
                        commands::cmd_apply(&config, &root_dir, execution_mode).await?
                    };

                    // Return appropriate exit code based on outcome
                    match outcome {
                        ApplyOutcome::DestructiveRequired => {
                            std::process::exit(2);
                        }
                        _ => Ok(()),
                    }
                }
                Commands::Migrate { command } => match command {
                    MigrateCommands::Diff(args) => {
                        let cli_config = config::ConfigInput {
                            databases: Some(args.database_args.clone().into()),
                            directories: Some(args.directory_args.clone().into()),
                            objects: None,
                            migration: None,
                            schema: None,
                            docker: None,
                        };

                        let config = config::ConfigBuilder::new()
                            .with_file(file_config.clone())
                            .with_cli_args(cli_config)
                            .resolve()?;

                        let diff_args = commands::MigrateDiffArgs {
                            format: args.format.clone(),
                            output_sql: args.output_sql.clone(),
                        };

                        info!("Checking target database for drift");
                        commands::cmd_migrate_diff(&config, &root_dir, diff_args).await
                    }
                    MigrateCommands::New {
                        description,
                        create_baseline,
                        database_args,
                        directory_args,
                    } => {
                        let cli_config = config::ConfigInput {
                            databases: Some(database_args.clone().into()),
                            directories: Some(directory_args.clone().into()),
                            objects: None,
                            migration: Some(config::MigrationInput {
                                default_mode: None,
                                validate_baseline_consistency: None,
                                create_baselines_by_default: Some(*create_baseline),
                                tracking_table: None,
                                column_order: None,
                                filename_prefix: None,
                            }),
                            schema: None,
                            docker: None,
                        };

                        let config = config::ConfigBuilder::new()
                            .with_file(file_config.clone())
                            .with_cli_args(cli_config)
                            .resolve()?;

                        info!("Generating migration from diff");
                        commands::cmd_migrate_new(&config, &root_dir, description.as_deref()).await
                    }
                    MigrateCommands::Update {
                        migration_version,
                        backup,
                        dry_run,
                        database_args,
                        directory_args,
                    } => {
                        let cli_config = config::ConfigInput {
                            databases: Some(database_args.clone().into()),
                            directories: Some(directory_args.clone().into()),
                            objects: None,
                            migration: None,
                            schema: None,
                            docker: None,
                        };

                        let config = config::ConfigBuilder::new()
                            .with_file(file_config.clone())
                            .with_cli_args(cli_config)
                            .resolve()?;

                        if let Some(version) = migration_version {
                            info!("Updating migration: {}", version);
                            commands::cmd_migrate_update_specific(
                                &config, &root_dir, version, *backup, *dry_run,
                            )
                            .await
                        } else {
                            info!("Updating latest migration");
                            commands::cmd_migrate_update_with_options(&config, &root_dir, *dry_run)
                                .await
                        }
                    }
                    MigrateCommands::Apply {
                        database_args,
                        directory_args,
                    } => {
                        let cli_config = config::ConfigInput {
                            databases: Some(database_args.clone().into()),
                            directories: Some(directory_args.clone().into()),
                            objects: None,
                            migration: None,
                            schema: None,
                            docker: None,
                        };

                        let config = config::ConfigBuilder::new()
                            .with_file(file_config.clone())
                            .with_cli_args(cli_config)
                            .resolve()?;

                        info!("Applying explicit migrations");
                        commands::cmd_migrate_apply(&config, &root_dir).await
                    }
                    MigrateCommands::Status { database_args } => {
                        let cli_config = config::ConfigInput {
                            databases: Some(database_args.clone().into()),
                            directories: None,
                            objects: None,
                            migration: None,
                            schema: None,
                            docker: None,
                        };

                        let config = config::ConfigBuilder::new()
                            .with_file(file_config.clone())
                            .with_cli_args(cli_config)
                            .resolve()?;

                        info!("Checking migration status");
                        commands::cmd_migrate_status(&config).await
                    }
                    MigrateCommands::Validate {
                        database_args,
                        directory_args,
                        format,
                        quiet,
                        verbose,
                        ignore_migrations,
                    } => {
                        let cli_config = config::ConfigInput {
                            databases: Some(database_args.clone().into()),
                            directories: Some(directory_args.clone().into()),
                            objects: None,
                            migration: None,
                            schema: None,
                            docker: None,
                        };

                        let config = config::ConfigBuilder::new()
                            .with_file(file_config.clone())
                            .with_cli_args(cli_config)
                            .resolve()?;

                        info!("Validating migration consistency");

                        let validation_options = validation_output::ValidationOutputOptions {
                            format: format.clone(),
                            quiet: *quiet,
                            verbose: *verbose,
                            ignore_migrations: ignore_migrations.clone(),
                        };

                        commands::cmd_migrate_validate(&config, &root_dir, &validation_options)
                            .await
                    }
                    MigrateCommands::Baseline(args) => {
                        let cli_config = config::ConfigInput {
                            databases: Some(args.database_args.clone().into()),
                            directories: Some(args.directory_args.clone().into()),
                            objects: None,
                            migration: None,
                            schema: None,
                            docker: None,
                        };

                        let config = config::ConfigBuilder::new()
                            .with_file(file_config.clone())
                            .with_cli_args(cli_config)
                            .resolve()?;

                        match &args.command {
                            Some(MigrateBaselineSubcommands::List) => {
                                info!("Listing existing baselines");
                                commands::cmd_baseline_list(&config, &root_dir).await
                            }
                            None => {
                                info!("Creating baseline");
                                commands::cmd_migrate_baseline(
                                    &config,
                                    &root_dir,
                                    args.force,
                                    args.keep_migrations,
                                    args.dry_run,
                                )
                                .await
                            }
                        }
                    }
                },
                Commands::Diff(args) => {
                    let cli_config = config::ConfigInput {
                        databases: Some(args.database_args.clone().into()),
                        directories: Some(args.directory_args.clone().into()),
                        objects: None,
                        migration: None,
                        schema: None,
                        docker: None,
                    };

                    let config = config::ConfigBuilder::new()
                        .with_file(file_config.clone())
                        .with_cli_args(cli_config)
                        .resolve()?;

                    let diff_args = commands::diff::DiffArgs {
                        format: args.format.clone(),
                        output_sql: args.output_sql.clone(),
                    };

                    info!("Comparing schema files with dev database");
                    commands::cmd_diff(&config, &root_dir, diff_args).await
                }
                Commands::Validate => {
                    let config = config::ConfigBuilder::new()
                        .with_file(file_config.clone())
                        .resolve()?;

                    info!("Validating schema consistency");
                    commands::cmd_validate(&config).await
                }
                Commands::Config { command } => {
                    match &command {
                        Some(_) => {
                            // Don't load config file for config commands, use the raw file path
                            let (file_config, _) = config::load_config(&cli.config_file)?;
                            let config = config::ConfigBuilder::new()
                                .with_file(file_config.clone())
                                .resolve()?;

                            info!("Managing configuration");
                            commands::cmd_config(&config, command.clone()).await
                        }
                        None => {
                            // Just show help for config command
                            let config = config::ConfigBuilder::new()
                                .with_file(file_config.clone())
                                .resolve()?;
                            commands::cmd_config(&config, None).await
                        }
                    }
                }
                Commands::Debug { command } => match command {
                    DebugCommands::Dependencies {
                        format,
                        object,
                        directory_args,
                    } => {
                        let cli_config = config::ConfigInput {
                            databases: None,
                            directories: Some(directory_args.clone().into()),
                            objects: None,
                            migration: None,
                            schema: None,
                            docker: None,
                        };

                        let config = config::ConfigBuilder::new()
                            .with_file(file_config.clone())
                            .with_cli_args(cli_config)
                            .resolve()?;

                        info!("Analyzing dependencies");
                        let output_format = match format {
                            DebugOutputFormat::Json => commands::debug::OutputFormat::Json,
                            DebugOutputFormat::Text => commands::debug::OutputFormat::Text,
                        };
                        commands::cmd_debug_dependencies(
                            &config,
                            &root_dir,
                            output_format,
                            object.as_deref(),
                        )
                        .await
                    }
                },
            }
        }
    }
}