pgmt 0.5.0

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
use anyhow::Result;
use std::fs;
use std::path::Path;

use crate::constants::{
    CONFIG_FILENAME, FUNCTIONS_SUBDIR, SCHEMAS_SUBDIR, TABLES_SUBDIR, TYPES_SUBDIR, VIEWS_SUBDIR,
};

/// Create the basic project structure for a pgmt project
pub fn create_project_structure(options: &super::InitOptions) -> Result<()> {
    fs::create_dir_all(&options.project_dir)?;

    let migrations_dir = options.project_dir.join(&options.migrations_dir);
    let baselines_dir = options.project_dir.join(&options.baselines_dir);
    let full_schema_dir = options.project_dir.join(&options.schema_dir);

    fs::create_dir_all(&migrations_dir)?;
    fs::create_dir_all(&baselines_dir)?;
    fs::create_dir_all(&full_schema_dir)?;

    // Create schema subdirectories
    fs::create_dir_all(full_schema_dir.join(SCHEMAS_SUBDIR))?;
    fs::create_dir_all(full_schema_dir.join(TYPES_SUBDIR))?;
    fs::create_dir_all(full_schema_dir.join(TABLES_SUBDIR))?;
    fs::create_dir_all(full_schema_dir.join(VIEWS_SUBDIR))?;
    fs::create_dir_all(full_schema_dir.join(FUNCTIONS_SUBDIR))?;

    Ok(())
}

/// Header prepended to the generated pgmt.yaml. The body is serialized from
/// `ConfigInput`, so it always round-trips through the parser; human guidance
/// lives up here where serde can't lose it.
const CONFIG_HEADER: &str = r#"# pgmt Configuration File
# Generated by pgmt init — reference: https://docs.pgmt.dev/docs/reference/configuration
#
# Common options to add:
#   databases.shadow.docker.image     custom shadow image (e.g. PostGIS, Supabase)
#   databases.shadow.docker.platform  e.g. linux/amd64 for single-arch images
#   objects.include.schemas           limit pgmt to the schemas you manage
"#;

/// Generate pgmt.yaml configuration file
///
/// Init's gathered answers are overlaid on `existing` (the config loaded on
/// re-init): fields init didn't gather — `objects`, `migration`, a shadow
/// docker `environment`, … — survive instead of being overwritten.
pub fn generate_config_file(
    options: &super::InitOptions,
    existing: Option<&crate::config::types::ConfigInput>,
    project_dir: &Path,
) -> Result<()> {
    use crate::config::merge::Merge;

    let gathered = gathered_config_input(options);
    let mut merged = match existing {
        Some(base) => base.clone().merge(gathered),
        None => gathered,
    };

    // Substrate schemas excluded during import are appended to whatever
    // exclude list the config already carries.
    if !options.substrate_exclusions.is_empty() {
        let objects = merged.objects.get_or_insert_with(Default::default);
        let exclude = objects.exclude.get_or_insert_with(Default::default);
        let schemas = exclude.schemas.get_or_insert_with(Vec::new);
        for schema in &options.substrate_exclusions {
            if !schemas.contains(schema) {
                schemas.push(schema.clone());
            }
        }
    }

    let yaml = serde_yaml::to_string(&merged)?;
    let config_path = project_dir.join(CONFIG_FILENAME);
    std::fs::write(config_path, format!("{CONFIG_HEADER}\n{yaml}"))?;

    Ok(())
}

/// The config-shaped subset of init's gathered answers, as a `ConfigInput`
/// layer (the same type pgmt.yaml parses into, so output can't desync from
/// the parser).
fn gathered_config_input(options: &super::InitOptions) -> crate::config::types::ConfigInput {
    use crate::config::types::{ConfigInput, DatabasesInput, DirectoriesInput, ShadowDockerInput};

    // For shadow config, prefer explicit CLI version, then detected version from dev DB
    let effective_version = options
        .shadow_pg_version
        .as_ref()
        .or(options.detected_pg_version.as_ref())
        .map(|v| crate::prompts::extract_major_version(v));

    let shadow = match &options.shadow_config {
        crate::prompts::ShadowDatabaseInput::Auto => match effective_version {
            Some(version) => crate::config::types::ShadowDatabaseInput {
                docker: Some(ShadowDockerInput {
                    version: Some(version),
                    ..Default::default()
                }),
                ..Default::default()
            },
            None => crate::config::types::ShadowDatabaseInput {
                auto: Some(true),
                ..Default::default()
            },
        },
        crate::prompts::ShadowDatabaseInput::Docker { image, platform } => {
            crate::config::types::ShadowDatabaseInput {
                docker: Some(ShadowDockerInput {
                    image: Some(image.clone()),
                    platform: platform.clone(),
                    ..Default::default()
                }),
                ..Default::default()
            }
        }
        crate::prompts::ShadowDatabaseInput::Manual(url) => {
            crate::config::types::ShadowDatabaseInput {
                auto: Some(false),
                url: Some(url.clone()),
                ..Default::default()
            }
        }
    };

    ConfigInput {
        databases: Some(DatabasesInput {
            dev_url: Some(options.dev_database_url.clone()),
            shadow: Some(shadow),
            ..Default::default()
        }),
        directories: Some(DirectoriesInput {
            schema_dir: Some(options.schema_dir.display().to_string()),
            migrations_dir: Some(options.migrations_dir.clone()),
            baselines_dir: Some(options.baselines_dir.clone()),
            roles_file: options.roles_file.clone(),
        }),
        ..Default::default()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::commands::init::{BaselineCreationConfig, InitOptions, ObjectManagementConfig};
    use crate::config::types::Directories;
    use std::env;
    use std::path::{Path, PathBuf};

    fn test_options(temp_dir: &Path) -> InitOptions {
        let dir_defaults = Directories::default();
        InitOptions {
            project_dir: temp_dir.to_path_buf(),
            dev_database_url: "postgres://localhost/test_db".to_string(),
            shadow_config: crate::prompts::ShadowDatabaseInput::Auto,
            shadow_pg_version: None,
            detected_pg_version: None,
            schema_dir: PathBuf::from("schema"),
            migrations_dir: dir_defaults.migrations,
            baselines_dir: dir_defaults.baselines,
            import_source: None,
            object_config: ObjectManagementConfig::default(),
            baseline_config: BaselineCreationConfig::default(),
            tracking_table: crate::config::types::TrackingTable::default(),
            roles_file: None,
            objects: Default::default(),
            substrate_exclusions: Vec::new(),
        }
    }

    #[test]
    fn test_create_project_structure() {
        let temp_dir = env::temp_dir().join("pgmt_test_project_structure");
        let _ = std::fs::remove_dir_all(&temp_dir);

        let options = test_options(&temp_dir);
        create_project_structure(&options).unwrap();

        let dir_defaults = Directories::default();

        // Check that directories were created
        assert!(temp_dir.join(&dir_defaults.migrations).exists());
        assert!(temp_dir.join(&dir_defaults.baselines).exists());
        assert!(temp_dir.join("schema").exists());
        assert!(temp_dir.join("schema/tables").exists());
        assert!(temp_dir.join("schema/views").exists());
        assert!(temp_dir.join("schema/functions").exists());
        assert!(temp_dir.join("schema/types").exists());
        assert!(temp_dir.join("schema/schemas").exists());

        // Cleanup
        let _ = std::fs::remove_dir_all(&temp_dir);
    }

    #[test]
    fn test_create_project_structure_custom_directories() {
        let temp_dir = env::temp_dir().join("pgmt_test_project_structure_custom");
        let _ = std::fs::remove_dir_all(&temp_dir);

        let mut options = test_options(&temp_dir);
        options.migrations_dir = "db/migrations".to_string();
        options.baselines_dir = "db/baselines".to_string();

        create_project_structure(&options).unwrap();

        // Check that custom directories were created
        assert!(temp_dir.join("db/migrations").exists());
        assert!(temp_dir.join("db/baselines").exists());
        assert!(temp_dir.join("schema").exists());

        // Cleanup
        let _ = std::fs::remove_dir_all(&temp_dir);
    }

    #[test]
    fn test_generate_config_file() {
        let temp_dir = env::temp_dir().join("pgmt_test_config");
        let _ = std::fs::remove_dir_all(&temp_dir);
        std::fs::create_dir_all(&temp_dir).unwrap();

        let mut options = test_options(&temp_dir);
        options.schema_dir = PathBuf::from("custom_schema");

        generate_config_file(&options, None, &temp_dir).unwrap();

        let config_path = temp_dir.join("pgmt.yaml");
        assert!(config_path.exists());

        let content = std::fs::read_to_string(&config_path).unwrap();
        let dir_defaults = Directories::default();

        assert!(content.contains("postgres://localhost/test_db"));
        assert!(content.contains("custom_schema"));
        assert!(content.contains("auto: true"));
        assert!(content.contains(&format!("migrations_dir: {}", dir_defaults.migrations)));
        assert!(content.contains(&format!("baselines_dir: {}", dir_defaults.baselines)));

        // Cleanup
        let _ = std::fs::remove_dir_all(&temp_dir);
    }

    #[test]
    fn test_generate_config_file_custom_directories() {
        let temp_dir = env::temp_dir().join("pgmt_test_config_custom_dirs");
        let _ = std::fs::remove_dir_all(&temp_dir);
        std::fs::create_dir_all(&temp_dir).unwrap();

        let mut options = test_options(&temp_dir);
        options.migrations_dir = "db/migrations".to_string();
        options.baselines_dir = "db/baselines".to_string();

        generate_config_file(&options, None, &temp_dir).unwrap();

        let config_path = temp_dir.join("pgmt.yaml");
        let content = std::fs::read_to_string(&config_path).unwrap();

        assert!(
            content.contains("migrations_dir: db/migrations"),
            "Expected custom migrations_dir, got:\n{}",
            content
        );
        assert!(
            content.contains("baselines_dir: db/baselines"),
            "Expected custom baselines_dir, got:\n{}",
            content
        );

        // Cleanup
        let _ = std::fs::remove_dir_all(&temp_dir);
    }

    #[test]
    fn test_generate_config_file_with_detected_version() {
        let temp_dir = env::temp_dir().join("pgmt_test_config_detected_version");
        let _ = std::fs::remove_dir_all(&temp_dir);
        std::fs::create_dir_all(&temp_dir).unwrap();

        // Test that detected_pg_version is persisted when shadow_pg_version is None
        let mut options = test_options(&temp_dir);
        options.detected_pg_version = Some("15.4".to_string()); // Detected from dev DB

        generate_config_file(&options, None, &temp_dir).unwrap();

        let config_path = temp_dir.join("pgmt.yaml");
        let content = std::fs::read_to_string(&config_path).unwrap();

        // Should use detected version, NOT auto: true
        let parsed: crate::config::types::ConfigInput =
            serde_yaml::from_str(&content).expect("generated pgmt.yaml should parse");
        let docker = parsed
            .databases
            .and_then(|d| d.shadow)
            .and_then(|s| s.docker)
            .expect("shadow.docker should be present");
        assert_eq!(
            docker.version.as_deref(),
            Some("15"),
            "Expected detected version to be persisted, got:\n{}",
            content
        );
        assert!(
            !content.contains("auto: true"),
            "Should not have auto: true when version is detected"
        );

        // Cleanup
        let _ = std::fs::remove_dir_all(&temp_dir);
    }

    #[test]
    fn test_generate_config_file_explicit_version_takes_precedence() {
        let temp_dir = env::temp_dir().join("pgmt_test_config_explicit_version");
        let _ = std::fs::remove_dir_all(&temp_dir);
        std::fs::create_dir_all(&temp_dir).unwrap();

        // Test that explicit shadow_pg_version takes precedence over detected_pg_version
        let mut options = test_options(&temp_dir);
        options.shadow_pg_version = Some("16".to_string()); // Explicit from CLI
        options.detected_pg_version = Some("15.4".to_string()); // Detected from dev DB

        generate_config_file(&options, None, &temp_dir).unwrap();

        let config_path = temp_dir.join("pgmt.yaml");
        let content = std::fs::read_to_string(&config_path).unwrap();

        // Should use explicit version (16), not detected version (15)
        let parsed: crate::config::types::ConfigInput =
            serde_yaml::from_str(&content).expect("generated pgmt.yaml should parse");
        let docker = parsed
            .databases
            .and_then(|d| d.shadow)
            .and_then(|s| s.docker)
            .expect("shadow.docker should be present");
        assert_eq!(
            docker.version.as_deref(),
            Some("16"),
            "Expected explicit version to take precedence, got:\n{}",
            content
        );

        // Cleanup
        let _ = std::fs::remove_dir_all(&temp_dir);
    }

    #[test]
    fn test_generate_config_file_docker_image_and_platform() {
        let temp_dir = env::temp_dir().join("pgmt_test_config_docker_image");
        let _ = std::fs::remove_dir_all(&temp_dir);
        std::fs::create_dir_all(&temp_dir).unwrap();

        // A custom shadow image with a pinned platform (e.g. PostGIS on arm64).
        let mut options = test_options(&temp_dir);
        options.shadow_config = crate::prompts::ShadowDatabaseInput::Docker {
            image: "postgis/postgis:16-3.5".to_string(),
            platform: Some("linux/amd64".to_string()),
        };

        generate_config_file(&options, None, &temp_dir).unwrap();

        let config_path = temp_dir.join("pgmt.yaml");
        let content = std::fs::read_to_string(&config_path).unwrap();

        assert!(
            !content.contains("auto: true"),
            "Should not emit auto mode for a custom image"
        );

        // The generated YAML must parse back into a Docker shadow config.
        let parsed: crate::config::types::ConfigInput =
            serde_yaml::from_str(&content).expect("generated pgmt.yaml should parse");
        let docker = parsed
            .databases
            .and_then(|d| d.shadow)
            .and_then(|s| s.docker)
            .expect("shadow.docker should be present");
        assert_eq!(docker.image.as_deref(), Some("postgis/postgis:16-3.5"));
        assert_eq!(docker.platform.as_deref(), Some("linux/amd64"));

        // Cleanup
        let _ = std::fs::remove_dir_all(&temp_dir);
    }

    /// The generated file is serialized from ConfigInput, so parsing it back
    /// must reproduce the exact input — one assertion that covers every
    /// current and future field.
    #[test]
    fn test_generate_config_file_round_trips_exactly() {
        let temp_dir = env::temp_dir().join("pgmt_test_config_round_trip");
        let _ = std::fs::remove_dir_all(&temp_dir);
        std::fs::create_dir_all(&temp_dir).unwrap();

        let mut options = test_options(&temp_dir);
        options.shadow_config = crate::prompts::ShadowDatabaseInput::Docker {
            image: "postgis/postgis:16-3.5".to_string(),
            platform: Some("linux/amd64".to_string()),
        };
        options.roles_file = Some("roles.sql".to_string());

        generate_config_file(&options, None, &temp_dir).unwrap();

        let content = std::fs::read_to_string(temp_dir.join("pgmt.yaml")).unwrap();
        let parsed: crate::config::types::ConfigInput =
            serde_yaml::from_str(&content).expect("generated pgmt.yaml should parse");

        assert_eq!(
            parsed,
            gathered_config_input(&options),
            "parse(serialize(x)) must equal x, got:\n{}",
            content
        );

        let _ = std::fs::remove_dir_all(&temp_dir);
    }

    /// Re-init must not destroy config the user added by hand: fields init
    /// doesn't gather (shadow docker environment/container_name, objects,
    /// migration settings) survive, while re-answered fields are updated.
    #[test]
    fn test_generate_config_file_preserves_hand_edits_on_reinit() {
        let temp_dir = env::temp_dir().join("pgmt_test_config_reinit_preserve");
        let _ = std::fs::remove_dir_all(&temp_dir);
        std::fs::create_dir_all(&temp_dir).unwrap();

        // An existing pgmt.yaml with hand-maintained additions.
        let existing: crate::config::types::ConfigInput = serde_yaml::from_str(
            r#"
databases:
  dev_url: postgres://localhost/old_db
  shadow:
    docker:
      image: postgis/postgis:16-3.4
      container_name: pgmt_shadow_bluebox
      auto_cleanup: false
      environment:
        POSTGRES_PASSWORD: hand-edited
objects:
  include:
    schemas: [public, bluebox]
migration:
  filename_prefix: "V"
"#,
        )
        .unwrap();

        // Re-init: user re-answers with a new dev URL and a newer image.
        let mut options = test_options(&temp_dir);
        options.dev_database_url = "postgres://localhost/new_db".to_string();
        options.shadow_config = crate::prompts::ShadowDatabaseInput::Docker {
            image: "postgis/postgis:17-3.5".to_string(),
            platform: None,
        };

        generate_config_file(&options, Some(&existing), &temp_dir).unwrap();

        let content = std::fs::read_to_string(temp_dir.join("pgmt.yaml")).unwrap();
        let parsed: crate::config::types::ConfigInput = serde_yaml::from_str(&content).unwrap();

        // Re-answered fields updated
        let databases = parsed.databases.expect("databases");
        assert_eq!(
            databases.dev_url.as_deref(),
            Some("postgres://localhost/new_db")
        );
        let docker = databases
            .shadow
            .and_then(|s| s.docker)
            .expect("shadow.docker");
        assert_eq!(docker.image.as_deref(), Some("postgis/postgis:17-3.5"));

        // Hand-maintained fields survived
        assert_eq!(
            docker.container_name.as_deref(),
            Some("pgmt_shadow_bluebox"),
            "hand-added container_name must survive re-init, got:\n{}",
            content
        );
        assert_eq!(docker.auto_cleanup, Some(false));
        assert_eq!(
            docker
                .environment
                .as_ref()
                .and_then(|e| e.get("POSTGRES_PASSWORD"))
                .map(String::as_str),
            Some("hand-edited")
        );
        let objects = parsed.objects.expect("objects section must survive");
        assert_eq!(
            objects.include.and_then(|i| i.schemas),
            Some(vec!["public".to_string(), "bluebox".to_string()])
        );
        assert_eq!(
            parsed.migration.and_then(|m| m.filename_prefix).as_deref(),
            Some("V"),
            "migration section must survive re-init"
        );

        let _ = std::fs::remove_dir_all(&temp_dir);
    }
}

#[cfg(test)]
mod substrate_tests {
    use super::*;
    use std::env;
    use std::path::Path;

    fn options_with_exclusions(
        temp_dir: &Path,
        exclusions: Vec<String>,
    ) -> crate::commands::init::InitOptions {
        let dir_defaults = crate::config::types::Directories::default();
        crate::commands::init::InitOptions {
            project_dir: temp_dir.to_path_buf(),
            dev_database_url: "postgres://localhost/test_db".to_string(),
            shadow_config: crate::prompts::ShadowDatabaseInput::Auto,
            shadow_pg_version: None,
            detected_pg_version: None,
            schema_dir: std::path::PathBuf::from("schema"),
            migrations_dir: dir_defaults.migrations,
            baselines_dir: dir_defaults.baselines,
            import_source: None,
            object_config: crate::commands::init::ObjectManagementConfig::default(),
            baseline_config: crate::commands::init::BaselineCreationConfig::default(),
            tracking_table: crate::config::types::TrackingTable::default(),
            roles_file: None,
            objects: Default::default(),
            substrate_exclusions: exclusions,
        }
    }

    /// Substrate exclusions chosen during import land in the generated
    /// config's exclude list, unioned with any hand-written exclusions.
    #[test]
    fn test_substrate_exclusions_written_to_config() {
        let temp_dir = env::temp_dir().join("pgmt_test_substrate_exclusions");
        let _ = std::fs::remove_dir_all(&temp_dir);
        std::fs::create_dir_all(&temp_dir).unwrap();

        let existing: crate::config::types::ConfigInput = serde_yaml::from_str(
            "objects:\n  exclude:\n    schemas: [flyway_schema_history, tiger]\n",
        )
        .unwrap();

        let options = options_with_exclusions(
            &temp_dir,
            vec![
                "tiger".to_string(),
                "tiger_data".to_string(),
                "topology".to_string(),
            ],
        );

        generate_config_file(&options, Some(&existing), &temp_dir).unwrap();

        let content = std::fs::read_to_string(temp_dir.join("pgmt.yaml")).unwrap();
        let parsed: crate::config::types::ConfigInput = serde_yaml::from_str(&content).unwrap();
        let schemas = parsed
            .objects
            .and_then(|o| o.exclude)
            .and_then(|e| e.schemas)
            .expect("exclude.schemas should be present");

        assert_eq!(
            schemas,
            vec!["flyway_schema_history", "tiger", "tiger_data", "topology"],
            "hand-written exclusions kept, substrate appended, no duplicates"
        );

        let _ = std::fs::remove_dir_all(&temp_dir);
    }
}