migratio-cli 0.4.4

CLI support library for migratio database migrations
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
//! CLI support library for migratio database migrations.
//!
//! This crate provides the runtime support for migration runner binaries
//! generated by `cargo-migratio`. It handles CLI argument parsing and
//! executes migration commands against the database.
//!
//! # Example
//!
//! This crate is typically used by auto-generated runner code, but can
//! also be used directly:
//!
//! ```ignore
//! use migratio_cli::{CliArgs, run_sqlite};
//! use clap::Parser;
//!
//! fn main() -> Result<(), Box<dyn std::error::Error>> {
//!     let database_url = std::env::var("DATABASE_URL")?;
//!     let migrator = my_app::migrations::get_migrator();
//!     let args = CliArgs::parse();
//!     run_sqlite(migrator, &database_url, args)
//! }
//! ```
//!
//! For PostgreSQL:
//!
//! ```ignore
//! use migratio_cli::{CliArgs, run_postgres};
//! use clap::Parser;
//!
//! fn main() -> Result<(), Box<dyn std::error::Error>> {
//!     let database_url = std::env::var("DATABASE_URL")?;
//!     let migrator = my_app::migrations::get_postgres_migrator();
//!     let args = CliArgs::parse();
//!     run_postgres(migrator, &database_url, args)
//! }
//! ```

use clap::{Parser, Subcommand};

/// CLI arguments for the migration runner.
#[derive(Parser, Debug)]
#[command(name = "migratio-runner")]
#[command(about = "Database migration runner")]
pub struct CliArgs {
    #[command(subcommand)]
    pub command: Commands,
}

/// Available migration commands for the runner binary.
#[derive(Subcommand, Debug)]
pub enum Commands {
    /// Show current migration status (requires database)
    Status,
    /// Run pending migrations (requires database)
    Upgrade {
        /// Target version (default: latest)
        #[arg(long)]
        to: Option<u32>,
    },
    /// Rollback migrations (requires database)
    Downgrade {
        /// Target version to rollback to
        #[arg(long)]
        to: u32,
    },
    /// Show migration history (requires database)
    History,
    /// Preview pending migrations without running them (requires database)
    Preview,
    /// List all migrations defined in the migrator (no database required)
    List,
    /// Show the resulting schema after applying all migrations (sqlite only; no database required)
    Schema {
        /// Write the schema to a file instead of stdout
        #[arg(short, long)]
        output: Option<std::path::PathBuf>,
    },
}

#[cfg(feature = "sqlite")]
pub use sqlite::{run_sqlite, schema_sqlite};

#[cfg(feature = "sqlite")]
mod sqlite {
    use super::{CliArgs, Commands};
    use migratio::sqlite::SqliteMigrator;
    use rusqlite::Connection;

    /// Run the CLI with a SQLite migrator.
    ///
    /// This function handles all CLI commands for SQLite databases.
    ///
    /// # Arguments
    ///
    /// * `migrator` - The configured SQLite migrator
    /// * `database_url` - Path to the SQLite database file
    /// * `args` - Parsed CLI arguments
    ///
    /// # Returns
    ///
    /// Returns `Ok(())` on success, or an error if the operation fails.
    pub fn run_sqlite(
        migrator: SqliteMigrator,
        database_url: &str,
        args: CliArgs,
    ) -> Result<(), Box<dyn std::error::Error>> {
        // Schema doesn't need the configured database at all - it runs migrations
        // against a throwaway in-memory database instead.
        let command = match args.command {
            Commands::Schema { output } => return schema_sqlite(migrator, output),
            command => command,
        };

        // Check if the database file exists before opening
        // (SQLite will create a new file if it doesn't exist, which we don't want)
        if !std::path::Path::new(database_url).exists() {
            return Err(format!(
                "Database file not found: {}\n\nTo create a new database, first create the file manually or use your application's initialization logic.",
                database_url
            ).into());
        }

        let mut conn = Connection::open(database_url)?;

        match command {
            Commands::Status => {
                let version = migrator.get_current_version(&mut conn)?;
                let pending = migrator.preview_upgrade(&mut conn)?;
                println!("Current version: {}", version);
                println!("Pending migrations: {}", pending.len());
                for m in pending {
                    println!("  - {} (v{})", m.name(), m.version());
                }
            }
            Commands::Upgrade { to } => {
                let report = match to {
                    Some(target) => migrator.upgrade_to(&mut conn, target)?,
                    None => migrator.upgrade(&mut conn)?,
                };
                if report.migrations_run.is_empty() {
                    println!("No migrations to run.");
                } else {
                    println!("Migrations run: {:?}", report.migrations_run);
                }
            }
            Commands::Downgrade { to } => {
                let report = migrator.downgrade(&mut conn, to)?;
                if report.migrations_run.is_empty() {
                    println!("No migrations to roll back.");
                } else {
                    println!("Migrations rolled back: {:?}", report.migrations_run);
                }
            }
            Commands::History => {
                let history = migrator.get_migration_history(&mut conn)?;
                if history.is_empty() {
                    println!("No migrations have been applied yet.");
                } else {
                    println!("Migration history:");
                    for entry in history {
                        println!(
                            "  v{}: {} [{}] (applied {})",
                            entry.version, entry.name, entry.migration_type, entry.applied_at
                        );
                    }
                }
            }
            Commands::Preview => {
                let pending = migrator.preview_upgrade(&mut conn)?;
                if pending.is_empty() {
                    println!("No pending migrations.");
                } else {
                    println!("Pending migrations:");
                    for m in pending {
                        println!("  - {} (v{})", m.name(), m.version());
                        if let Some(desc) = m.description() {
                            println!("    {}", desc);
                        }
                    }
                }
            }
            Commands::List => {
                // This command is handled before run_sqlite is called.
                // If we get here, something went wrong.
                unreachable!("List command should be handled before run_sqlite");
            }
            Commands::Schema { .. } => {
                unreachable!("Schema command is handled before run_sqlite reaches this match")
            }
        }

        Ok(())
    }

    /// Renders the schema DDL as a string. Pure — no I/O beyond reading the given connection.
    fn render_schema(conn: &Connection, migrations_applied: usize) -> Result<String, rusqlite::Error> {
        let mut stmt = conn.prepare(
            "SELECT sql FROM sqlite_master \
             WHERE sql IS NOT NULL AND name NOT LIKE 'sqlite_%' AND name != '_migratio_version_' \
             ORDER BY CASE type WHEN 'table' THEN 0 WHEN 'index' THEN 1 WHEN 'view' THEN 2 WHEN 'trigger' THEN 3 ELSE 4 END, name",
        )?;
        let statements: Vec<String> = stmt
            .query_map([], |row| row.get(0))?
            .collect::<Result<Vec<_>, _>>()?;

        let mut output = format!(
            "-- Schema generated by migratio ({} migrations applied)\n\
             -- Note: the _migratio_version_ bookkeeping table is excluded.\n\n",
            migrations_applied
        );
        output.push_str(
            &statements
                .iter()
                .map(|sql| format!("{};\n", sql))
                .collect::<Vec<_>>()
                .join("\n"),
        );

        Ok(output)
    }

    /// Runs all migrations against an in-memory sqlite db and outputs the resulting schema.
    pub fn schema_sqlite(
        migrator: SqliteMigrator,
        output: Option<std::path::PathBuf>,
    ) -> Result<(), Box<dyn std::error::Error>> {
        let mut conn = Connection::open_in_memory()?;
        let report = migrator.upgrade(&mut conn)?;
        let schema = render_schema(&conn, report.migrations_run.len())?;
        match output {
            Some(path) => std::fs::write(path, schema)?,
            None => println!("{}", schema),
        }
        Ok(())
    }

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

        #[test]
        fn render_schema_single_migration() {
            sql_migration!(CreateUsers, 1, "Create users",
                up: "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)",
                down: "DROP TABLE users"
            );

            let migrator = SqliteMigrator::new(vec![Box::new(CreateUsers)]);
            let mut conn = Connection::open_in_memory().unwrap();
            let report = migrator.upgrade(&mut conn).unwrap();

            let schema = render_schema(&conn, report.migrations_run.len()).unwrap();

            assert!(schema.contains("CREATE TABLE users"));
            assert!(schema.contains(';'));
        }

        #[test]
        fn render_schema_multiple_migrations() {
            sql_migration!(CreateUsers, 1, "Create users",
                up: "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)",
                down: "DROP TABLE users"
            );
            sql_migration!(CreatePosts, 2, "Create posts",
                up: [
                    "CREATE TABLE posts (id INTEGER PRIMARY KEY, user_id INTEGER, title TEXT)",
                    "CREATE INDEX idx_posts_user ON posts(user_id)"
                ],
                down: [
                    "DROP INDEX idx_posts_user",
                    "DROP TABLE posts"
                ]
            );

            let migrator = SqliteMigrator::new(vec![Box::new(CreateUsers), Box::new(CreatePosts)]);
            let mut conn = Connection::open_in_memory().unwrap();
            let report = migrator.upgrade(&mut conn).unwrap();

            let schema = render_schema(&conn, report.migrations_run.len()).unwrap();

            assert!(schema.contains("CREATE TABLE users"));
            assert!(schema.contains("CREATE TABLE posts"));
            assert!(schema.contains("CREATE INDEX idx_posts_user"));
        }

        #[test]
        fn render_schema_orders_tables_then_index_then_view_then_trigger() {
            sql_migration!(CreateAll, 1, "Create everything, scrambled",
                up: [
                    "CREATE TABLE b (id INTEGER PRIMARY KEY)",
                    "CREATE TABLE a (id INTEGER PRIMARY KEY)",
                    "CREATE VIEW v AS SELECT * FROM a",
                    "CREATE INDEX idx_b ON b(id)",
                    "CREATE TRIGGER trg AFTER INSERT ON a BEGIN SELECT 1; END"
                ],
                down: [
                    "DROP TRIGGER trg",
                    "DROP INDEX idx_b",
                    "DROP VIEW v",
                    "DROP TABLE a",
                    "DROP TABLE b"
                ]
            );

            let migrator = SqliteMigrator::new(vec![Box::new(CreateAll)]);
            let mut conn = Connection::open_in_memory().unwrap();
            let report = migrator.upgrade(&mut conn).unwrap();

            let schema = render_schema(&conn, report.migrations_run.len()).unwrap();

            let a = schema.find("CREATE TABLE a").unwrap();
            let b = schema.find("CREATE TABLE b").unwrap();
            let idx_b = schema.find("CREATE INDEX idx_b").unwrap();
            let v = schema.find("CREATE VIEW v").unwrap();
            let trg = schema.find("CREATE TRIGGER trg").unwrap();

            assert!(a < b, "table a should come before table b");
            assert!(b < idx_b, "tables should come before indexes");
            assert!(idx_b < v, "indexes should come before views");
            assert!(v < trg, "views should come before triggers");
        }

        #[test]
        fn render_schema_excludes_migratio_bookkeeping_table() {
            sql_migration!(CreateUsers, 1, "Create users",
                up: "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)",
                down: "DROP TABLE users"
            );

            let migrator = SqliteMigrator::new(vec![Box::new(CreateUsers)]);
            let mut conn = Connection::open_in_memory().unwrap();
            let report = migrator.upgrade(&mut conn).unwrap();

            let schema = render_schema(&conn, report.migrations_run.len()).unwrap();

            assert!(!schema.contains("CREATE TABLE _migratio_version_"));
        }

        #[test]
        fn render_schema_excludes_sqlite_internal_tables() {
            sql_migration!(CreateUsers, 1, "Create users with autoincrement",
                up: "CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)",
                down: "DROP TABLE users"
            );

            let migrator = SqliteMigrator::new(vec![Box::new(CreateUsers)]);
            let mut conn = Connection::open_in_memory().unwrap();
            let report = migrator.upgrade(&mut conn).unwrap();

            let schema = render_schema(&conn, report.migrations_run.len()).unwrap();

            assert!(!schema.contains("sqlite_sequence"));
        }

        #[test]
        fn render_schema_empty_migrator() {
            let migrator = SqliteMigrator::new(vec![]);
            let mut conn = Connection::open_in_memory().unwrap();
            let report = migrator.upgrade(&mut conn).unwrap();

            let schema = render_schema(&conn, report.migrations_run.len()).unwrap();

            assert!(schema.contains("0 migrations applied"));
            assert!(!schema.contains("CREATE TABLE"));
        }

        #[test]
        fn render_schema_banner_reports_migration_count() {
            sql_migration!(M1, 1, "one", up: "CREATE TABLE t1 (id INTEGER PRIMARY KEY)", down: "DROP TABLE t1");
            sql_migration!(M2, 2, "two", up: "CREATE TABLE t2 (id INTEGER PRIMARY KEY)", down: "DROP TABLE t2");
            sql_migration!(M3, 3, "three", up: "CREATE TABLE t3 (id INTEGER PRIMARY KEY)", down: "DROP TABLE t3");

            let migrator =
                SqliteMigrator::new(vec![Box::new(M1), Box::new(M2), Box::new(M3)]);
            let mut conn = Connection::open_in_memory().unwrap();
            let report = migrator.upgrade(&mut conn).unwrap();

            let schema = render_schema(&conn, report.migrations_run.len()).unwrap();

            assert!(schema.contains("3 migrations applied"));
        }

        #[test]
        fn render_schema_banner_notes_bookkeeping_table_exclusion() {
            let migrator = SqliteMigrator::new(vec![]);
            let mut conn = Connection::open_in_memory().unwrap();
            let report = migrator.upgrade(&mut conn).unwrap();

            let schema = render_schema(&conn, report.migrations_run.len()).unwrap();

            assert!(schema.contains("_migratio_version_"));
        }

        #[test]
        fn schema_sqlite_writes_to_output_file() {
            sql_migration!(CreateUsers, 1, "Create users",
                up: "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)",
                down: "DROP TABLE users"
            );

            let migrator = SqliteMigrator::new(vec![Box::new(CreateUsers)]);
            let path = std::env::temp_dir()
                .join("migratio_cli_test_schema_sqlite_writes_to_output_file.sql");

            let result = schema_sqlite(migrator, Some(path.clone()));

            assert!(result.is_ok());
            let contents = std::fs::read_to_string(&path).unwrap();
            assert!(contents.contains("CREATE TABLE users"));

            std::fs::remove_file(&path).ok();
        }

        #[test]
        fn schema_sqlite_overwrites_existing_file_silently() {
            sql_migration!(CreateUsers, 1, "Create users",
                up: "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)",
                down: "DROP TABLE users"
            );

            let migrator = SqliteMigrator::new(vec![Box::new(CreateUsers)]);
            let path = std::env::temp_dir()
                .join("migratio_cli_test_schema_sqlite_overwrites_existing_file_silently.sql");
            std::fs::write(&path, "old content").unwrap();

            let result = schema_sqlite(migrator, Some(path.clone()));

            assert!(result.is_ok());
            let contents = std::fs::read_to_string(&path).unwrap();
            assert!(!contents.contains("old content"));
            assert!(contents.contains("CREATE TABLE users"));

            std::fs::remove_file(&path).ok();
        }

        #[test]
        fn schema_sqlite_prints_to_stdout_when_no_output_given() {
            sql_migration!(CreateUsers, 1, "Create users",
                up: "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)",
                down: "DROP TABLE users"
            );

            let migrator = SqliteMigrator::new(vec![Box::new(CreateUsers)]);

            let result = schema_sqlite(migrator, None);

            assert!(result.is_ok());
        }
    }
}

#[cfg(feature = "mysql")]
pub use mysql_support::run_mysql;

#[cfg(feature = "postgres")]
pub use postgres_support::run_postgres;

#[cfg(feature = "mysql")]
mod mysql_support {
    use super::{CliArgs, Commands};
    use migratio::mysql::MysqlMigrator;
    use mysql::{Conn, Opts};

    /// Run the CLI with a MySQL migrator.
    ///
    /// This function handles all CLI commands for MySQL databases.
    ///
    /// # Arguments
    ///
    /// * `migrator` - The configured MySQL migrator
    /// * `database_url` - MySQL connection URL
    /// * `args` - Parsed CLI arguments
    ///
    /// # Returns
    ///
    /// Returns `Ok(())` on success, or an error if the operation fails.
    pub fn run_mysql(
        migrator: MysqlMigrator,
        database_url: &str,
        args: CliArgs,
    ) -> Result<(), Box<dyn std::error::Error>> {
        if let Commands::Schema { .. } = &args.command {
            return Err("the `schema` command is only supported for sqlite databases".into());
        }

        let opts = Opts::from_url(database_url)?;
        let mut conn = Conn::new(opts)?;

        match args.command {
            Commands::Status => {
                let version = migrator.get_current_version(&mut conn)?;
                let pending = migrator.preview_upgrade(&mut conn)?;
                println!("Current version: {}", version);
                println!("Pending migrations: {}", pending.len());
                for m in pending {
                    println!("  - {} (v{})", m.name(), m.version());
                }
            }
            Commands::Upgrade { to } => {
                let report = match to {
                    Some(target) => migrator.upgrade_to(&mut conn, target)?,
                    None => migrator.upgrade(&mut conn)?,
                };
                if report.migrations_run.is_empty() {
                    println!("No migrations to run.");
                } else {
                    println!("Migrations run: {:?}", report.migrations_run);
                }
            }
            Commands::Downgrade { to } => {
                let report = migrator.downgrade(&mut conn, to)?;
                if report.migrations_run.is_empty() {
                    println!("No migrations to roll back.");
                } else {
                    println!("Migrations rolled back: {:?}", report.migrations_run);
                }
            }
            Commands::History => {
                let history = migrator.get_migration_history(&mut conn)?;
                if history.is_empty() {
                    println!("No migrations have been applied yet.");
                } else {
                    println!("Migration history:");
                    for entry in history {
                        println!(
                            "  v{}: {} [{}] (applied {})",
                            entry.version, entry.name, entry.migration_type, entry.applied_at
                        );
                    }
                }
            }
            Commands::Preview => {
                let pending = migrator.preview_upgrade(&mut conn)?;
                if pending.is_empty() {
                    println!("No pending migrations.");
                } else {
                    println!("Pending migrations:");
                    for m in pending {
                        println!("  - {} (v{})", m.name(), m.version());
                        if let Some(desc) = m.description() {
                            println!("    {}", desc);
                        }
                    }
                }
            }
            Commands::List => {
                // This command is handled before run_mysql is called.
                // If we get here, something went wrong.
                unreachable!("List command should be handled before run_mysql");
            }
            Commands::Schema { .. } => {
                unreachable!("Schema command is rejected before run_mysql reaches this match")
            }
        }

        Ok(())
    }
}

#[cfg(feature = "postgres")]
mod postgres_support {
    use super::{CliArgs, Commands};
    use migratio::postgres::PostgresMigrator;
    use postgres::{Client, NoTls};

    /// Run the CLI with a PostgreSQL migrator.
    ///
    /// This function handles all CLI commands for PostgreSQL databases.
    ///
    /// # Arguments
    ///
    /// * `migrator` - The configured PostgreSQL migrator
    /// * `database_url` - PostgreSQL connection URL
    /// * `args` - Parsed CLI arguments
    ///
    /// # Returns
    ///
    /// Returns `Ok(())` on success, or an error if the operation fails.
    pub fn run_postgres(
        migrator: PostgresMigrator,
        database_url: &str,
        args: CliArgs,
    ) -> Result<(), Box<dyn std::error::Error>> {
        if let Commands::Schema { .. } = &args.command {
            return Err("the `schema` command is only supported for sqlite databases".into());
        }

        let mut client = Client::connect(database_url, NoTls)?;

        match args.command {
            Commands::Status => {
                let version = migrator.get_current_version(&mut client)?;
                let pending = migrator.preview_upgrade(&mut client)?;
                println!("Current version: {}", version);
                println!("Pending migrations: {}", pending.len());
                for m in pending {
                    println!("  - {} (v{})", m.name(), m.version());
                }
            }
            Commands::Upgrade { to } => {
                let report = match to {
                    Some(target) => migrator.upgrade_to(&mut client, target)?,
                    None => migrator.upgrade(&mut client)?,
                };
                if report.migrations_run.is_empty() {
                    println!("No migrations to run.");
                } else {
                    println!("Migrations run: {:?}", report.migrations_run);
                }
            }
            Commands::Downgrade { to } => {
                let report = migrator.downgrade(&mut client, to)?;
                if report.migrations_run.is_empty() {
                    println!("No migrations to roll back.");
                } else {
                    println!("Migrations rolled back: {:?}", report.migrations_run);
                }
            }
            Commands::History => {
                let history = migrator.get_migration_history(&mut client)?;
                if history.is_empty() {
                    println!("No migrations have been applied yet.");
                } else {
                    println!("Migration history:");
                    for entry in history {
                        println!(
                            "  v{}: {} [{}] (applied {})",
                            entry.version, entry.name, entry.migration_type, entry.applied_at
                        );
                    }
                }
            }
            Commands::Preview => {
                let pending = migrator.preview_upgrade(&mut client)?;
                if pending.is_empty() {
                    println!("No pending migrations.");
                } else {
                    println!("Pending migrations:");
                    for m in pending {
                        println!("  - {} (v{})", m.name(), m.version());
                        if let Some(desc) = m.description() {
                            println!("    {}", desc);
                        }
                    }
                }
            }
            Commands::List => {
                // This command is handled before run_postgres is called.
                // If we get here, something went wrong.
                unreachable!("List command should be handled before run_postgres");
            }
            Commands::Schema { .. } => {
                unreachable!("Schema command is rejected before run_postgres reaches this match")
            }
        }

        Ok(())
    }
}