pgmt 0.6.4

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
use crate::baseline::operations::{BaselineCreationRequest, create_baseline};
use crate::catalog::Catalog;
use crate::config::Config;
use crate::migrate::{MigrationGenerationInput, generate_migration};
use crate::migration::{
    BaselineConfig, find_latest_migration, generate_baseline_filename,
    get_migration_update_starting_state, should_manage_baseline_for_migration,
    validate_baseline_against_catalog,
};
use crate::modules::{
    HistoricalAttribution, evaluate_module_generation, render_generated_migration,
    section_baseline_if_moduled,
};
use anyhow::{Result, anyhow};
use std::path::Path;
use std::time::{SystemTime, UNIX_EPOCH};
use tracing::debug;

pub async fn cmd_migrate_update_with_options(
    config: &Config,
    root_dir: &Path,
    dry_run: bool,
    shadow: &crate::config::ShadowDatabase,
) -> Result<()> {
    if dry_run {
        println!("🔍 Dry-run mode: previewing changes without applying them");
    }

    println!("Updating latest migration with current changes");

    // Create necessary directories
    let migrations_dir = root_dir.join(&config.directories.migrations);
    let baselines_dir = root_dir.join(&config.directories.baselines);
    std::fs::create_dir_all(&migrations_dir)?;
    std::fs::create_dir_all(&baselines_dir)?;

    // Find the latest migration
    let latest_migration = find_latest_migration(&migrations_dir)?;
    if latest_migration.is_none() {
        return Err(anyhow::anyhow!(
            "No migrations found. Use 'pgmt migrate new <description>' to create the first migration."
        ));
    }

    let latest_migration = latest_migration.unwrap();
    println!("Updating migration: {}", latest_migration.path.display());

    // Step 1: Load the baseline that corresponds to the previous migration
    let baseline_config = BaselineConfig {
        validate_consistency: config.migration.validate_baseline_consistency,
        verbose: true,
    };
    let roles_file = root_dir.join(&config.directories.roles);

    // Each pristine-start phase gets its own fresh branch — the replay dirties
    // the shadow and `clean_shadow_db` is a no-op on branches, so a shared
    // branch would make the schema-file apply collide. See `migrate new`.
    let starting_pool = shadow.connect_fresh().await?;
    let mut historical = HistoricalAttribution::default();
    let attribution = config.modules.is_enabled().then_some(&mut historical);
    let old_catalog = get_migration_update_starting_state(
        &starting_pool,
        &baselines_dir,
        &migrations_dir,
        latest_migration.version,
        &roles_file,
        &baseline_config,
        config,
        attribution,
    )
    .await?;
    crate::db::branch::drop_branch(starting_pool).await?;

    // Step 2: Reset shadow database and apply current schema
    debug!("Applying current schema to shadow database");
    let (new_catalog, file_mapping) =
        crate::schema_ops::apply_current_schema_to_shadow_with_mapping(config, root_dir, shadow)
            .await?;

    // Validate column ordering before generating migration
    crate::validation::apply_column_order_validation(
        &old_catalog,
        &new_catalog,
        config.migration.column_order,
    )?;

    // Step 3: Generate migration using pure logic
    debug!("Generating updated migration steps");
    let migration_result = generate_migration(MigrationGenerationInput {
        old_catalog: old_catalog.clone(),
        new_catalog: new_catalog.clone(),
        description: latest_migration.description.clone(), // We keep the original description
        version: latest_migration.version,
        filename_prefix: config.migration.filename_prefix.clone(),
    })?;

    // Whether a paired baseline will be (re)generated below — that baseline is
    // also what a partition re-anchor requires.
    let baseline_filename = generate_baseline_filename(latest_migration.version);
    let baseline_path = baselines_dir.join(&baseline_filename);
    let should_update_baseline = should_manage_baseline_for_migration(
        config,
        &baseline_path,
        config.migration.create_baselines_by_default,
    );

    let module_gen = evaluate_module_generation(
        config,
        &old_catalog,
        &new_catalog,
        &file_mapping,
        &historical,
        should_update_baseline,
        // `migrate update` has no --create-baseline flag; re-anchoring is owned
        // by `migrate new`, so point the user there rather than at a flag this
        // subcommand would reject as unknown.
        "run 'pgmt migrate new <description> --create-baseline' to emit a re-anchoring baseline.",
    )?;
    let partition_diverged = module_gen.as_ref().is_some_and(|m| m.diverged);

    if !migration_result.has_changes && !partition_diverged {
        println!("No changes detected - updating migration to be empty");

        // Update the migration file to be empty since no changes are needed
        let empty_migration_sql = "-- No changes detected\n";
        std::fs::write(&latest_migration.path, empty_migration_sql)?;
        println!(
            "Updated migration: {} (now empty)",
            latest_migration.path.display()
        );

        return Ok(());
    }

    // Step 5 runs before step 4 for module projects so the baseline is
    // sectioned first. The migration's acquisition sections render the
    // moved objects from the STARTING catalog, not the baseline, so they do
    // not consume the baseline's sections — but the ordering is still natural.
    if should_update_baseline {
        let result = create_baseline(BaselineCreationRequest {
            catalog: new_catalog.clone(),
            base_catalog: Catalog::empty(),
            version: latest_migration.version,
            description: "baseline".to_string(),
            baselines_dir: baselines_dir.clone(),
            verbose: baseline_config.verbose,
        })
        .await?;
        section_baseline_if_moduled(
            module_gen.as_ref(),
            &result.path,
            &new_catalog,
            &file_mapping,
            &historical,
        )?;
        println!("Updated baseline: {}", result.path.display());

        // Step 6: Validate that the baseline matches the intended schema using pure logic
        if baseline_config.validate_consistency {
            let validate_pool = shadow.connect_fresh().await?;
            validate_baseline_against_catalog(
                &validate_pool,
                &result.path,
                &new_catalog,
                &baseline_config,
                &roles_file,
                config,
            )
            .await?;
            crate::db::branch::drop_branch(validate_pool).await?;
        }
    } else {
        println!(
            "Skipping baseline update (baseline does not exist and create_baselines_by_default is false)"
        );
    }

    // Step 4 (after 5 by design): update the migration file — ordinary diff
    // sections plus, at a re-anchor, the acquisition sections.
    let migration_sql: String = render_generated_migration(
        module_gen.as_ref(),
        migration_result.has_changes,
        &migration_result.migration_sql,
        &old_catalog,
        &new_catalog,
        &file_mapping,
        &historical,
    )?
    .unwrap_or_else(|| "-- No changes detected\n".to_string());
    std::fs::write(&latest_migration.path, &migration_sql)?;
    println!("Updated migration: {}", latest_migration.path.display());

    println!("Migration update complete!");
    Ok(())
}

/// Update a specific migration with current changes (renumbers if not latest)
pub async fn cmd_migrate_update_specific(
    config: &Config,
    root_dir: &Path,
    version_str: &str,
    backup: bool,
    dry_run: bool,
    shadow: &crate::config::ShadowDatabase,
) -> Result<()> {
    use crate::migration::parsing::find_migration_by_version;

    if dry_run {
        println!(
            "🔍 Dry-run mode: previewing migration update for: {}",
            version_str
        );
    } else {
        println!("Updating migration: {}", version_str);
    }

    // Create necessary directories
    let migrations_dir = root_dir.join(&config.directories.migrations);
    let baselines_dir = root_dir.join(&config.directories.baselines);
    std::fs::create_dir_all(&migrations_dir)?;
    std::fs::create_dir_all(&baselines_dir)?;

    // Find the target migration
    let target_migration = find_migration_by_version(&migrations_dir, version_str)?;
    let target_migration = match target_migration {
        Some(migration) => migration,
        None => {
            return Err(anyhow!(
                "Migration '{}' not found. Use 'pgmt migrate status' to see available migrations.",
                version_str
            ));
        }
    };

    println!(
        "Found migration: {} ({})",
        target_migration.path.display(),
        target_migration.description
    );

    // Create backup if requested
    if backup && !dry_run {
        let backup_path = target_migration.path.with_extension("sql.bak");
        std::fs::copy(&target_migration.path, &backup_path)?;
        println!("💾 Backup created: {}", backup_path.display());
    } else if backup && dry_run {
        let backup_path = target_migration.path.with_extension("sql.bak");
        println!("💾 Would create backup: {}", backup_path.display());
    }

    // Check if this is the latest migration
    let latest_migration = find_latest_migration(&migrations_dir)?;
    let is_latest = latest_migration
        .map(|latest| latest.version == target_migration.version)
        .unwrap_or(false);

    // Get the baseline state before this migration
    let baseline_config = BaselineConfig {
        validate_consistency: config.migration.validate_baseline_consistency,
        verbose: true,
    };
    let roles_file = root_dir.join(&config.directories.roles);

    // Fresh branch per pristine-start phase (see `migrate new`): the replay
    // dirties the shadow and branch cleans are no-ops, so reuse would collide.
    let starting_pool = shadow.connect_fresh().await?;
    let mut historical = HistoricalAttribution::default();
    let attribution = config.modules.is_enabled().then_some(&mut historical);
    let old_catalog = get_migration_update_starting_state(
        &starting_pool,
        &baselines_dir,
        &migrations_dir,
        target_migration.version,
        &roles_file,
        &baseline_config,
        config,
        attribution,
    )
    .await?;
    crate::db::branch::drop_branch(starting_pool).await?;

    // Apply current schema to shadow database
    debug!("Applying current schema to shadow database");
    let (new_catalog, file_mapping) =
        crate::schema_ops::apply_current_schema_to_shadow_with_mapping(config, root_dir, shadow)
            .await?;

    // Validate column ordering before generating migration
    crate::validation::apply_column_order_validation(
        &old_catalog,
        &new_catalog,
        config.migration.column_order,
    )?;

    // Determine version and description for the new migration
    let (new_version, new_description) = if is_latest {
        // For latest migration, keep same version and description
        (
            target_migration.version,
            target_migration.description.clone(),
        )
    } else {
        // For older migration, generate new timestamp
        let new_version = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map_err(|e| anyhow!("System time is before Unix epoch: {}", e))?
            .as_secs();
        (new_version, target_migration.description.clone())
    };

    // Generate migration content
    debug!("Generating updated migration steps");
    let migration_result = generate_migration(MigrationGenerationInput {
        old_catalog: old_catalog.clone(),
        new_catalog: new_catalog.clone(),
        description: new_description.clone(),
        version: new_version,
        filename_prefix: config.migration.filename_prefix.clone(),
    })?;

    // Whether a paired baseline will be (re)generated below — required for a
    // partition re-anchor.
    let baseline_filename = generate_baseline_filename(new_version);
    let baseline_path = baselines_dir.join(&baseline_filename);
    let should_update_baseline = should_manage_baseline_for_migration(
        config,
        &baseline_path,
        config.migration.create_baselines_by_default,
    );

    let module_gen = evaluate_module_generation(
        config,
        &old_catalog,
        &new_catalog,
        &file_mapping,
        &historical,
        should_update_baseline,
        // `migrate update` has no --create-baseline flag; re-anchoring is owned
        // by `migrate new`, so point the user there rather than at a flag this
        // subcommand would reject as unknown.
        "run 'pgmt migrate new <description> --create-baseline' to emit a re-anchoring baseline.",
    )?;
    let partition_diverged = module_gen.as_ref().is_some_and(|m| m.diverged);

    if !migration_result.has_changes {
        if is_latest {
            println!("No changes detected - updating migration to be empty");
            let empty_migration_sql = "-- No changes detected\n";
            std::fs::write(&target_migration.path, empty_migration_sql)?;
            println!(
                "Updated migration: {} (now empty)",
                target_migration.path.display()
            );
        } else {
            println!("No changes detected - conflicts resolved by other migrations");
            // For older migrations with no changes, still create/update the file with a comment
            let empty_migration_content = format!(
                "-- Migration: {}\n-- Version: {}{}\n-- Generated by pgmt migrate update (renumbered from {}{})\n-- No changes needed - conflicts resolved by intervening migrations\n",
                new_description,
                config.migration.filename_prefix,
                new_version,
                config.migration.filename_prefix,
                target_migration.version
            );

            if is_latest {
                // Overwrite existing file
                std::fs::write(&target_migration.path, &empty_migration_content)?;
                println!(
                    "Updated migration: {} (no changes needed)",
                    target_migration.path.display()
                );
            } else {
                // Delete old file and create new one
                std::fs::remove_file(&target_migration.path)?;
                let new_filename = format!(
                    "{}{}_{}.sql",
                    config.migration.filename_prefix,
                    new_version,
                    new_description.replace(' ', "_")
                );
                let new_path = migrations_dir.join(&new_filename);
                std::fs::write(&new_path, &empty_migration_content)?;
                println!(
                    "Migration {} updated to {} (no changes needed)",
                    target_migration.version, new_version
                );
                println!("Created: {}", new_path.display());
            }
        }
        if !partition_diverged {
            return Ok(());
        }
        // Pure re-tag: fall through so the re-anchoring baseline regenerates.
    }

    // Handle baseline updates FIRST for module projects so the baseline is
    // sectioned first. The migration's acquisition sections render the
    // moved objects from the STARTING catalog rather than the baseline.
    if should_update_baseline {
        let result = create_baseline(BaselineCreationRequest {
            catalog: new_catalog.clone(),
            base_catalog: Catalog::empty(),
            version: new_version,
            description: "baseline".to_string(),
            baselines_dir: baselines_dir.clone(),
            verbose: baseline_config.verbose,
        })
        .await?;
        section_baseline_if_moduled(
            module_gen.as_ref(),
            &result.path,
            &new_catalog,
            &file_mapping,
            &historical,
        )?;
        if is_latest {
            println!("Updated baseline: {}", result.path.display());
        } else {
            println!("Created baseline: {}", result.path.display());
        }

        if baseline_config.validate_consistency {
            let validate_pool = shadow.connect_fresh().await?;
            validate_baseline_against_catalog(
                &validate_pool,
                &result.path,
                &new_catalog,
                &baseline_config,
                &roles_file,
                config,
            )
            .await?;
            crate::db::branch::drop_branch(validate_pool).await?;
        }
    } else if is_latest {
        println!(
            "Skipping baseline update (baseline does not exist and create_baselines_by_default is false)"
        );
    } else {
        println!("Skipping baseline creation (create_baselines_by_default is false)");
    }

    // The migration content: ordinary diff sections plus, at a re-anchor, the
    // acquisition sections. `None` = nothing to write (the
    // no-changes handling above already produced the file).
    let migration_sql: Option<String> = render_generated_migration(
        module_gen.as_ref(),
        migration_result.has_changes,
        &migration_result.migration_sql,
        &old_catalog,
        &new_catalog,
        &file_mapping,
        &historical,
    )?;

    // Write the migration file
    if let Some(migration_sql) = &migration_sql {
        if dry_run {
            println!(
                "📝 Preview: Generated migration content ({} chars)",
                migration_sql.len()
            );
            if is_latest {
                println!("🔄 Would update: {}", target_migration.path.display());
            } else {
                let new_filename = format!(
                    "{}{}_{}.sql",
                    config.migration.filename_prefix,
                    new_version,
                    new_description.replace(' ', "_")
                );
                let new_path = migrations_dir.join(&new_filename);
                println!(
                    "🔄 Would rename {} → {}",
                    target_migration.version, new_version
                );
                println!("   Delete: {}", target_migration.path.display());
                println!("   Create: {}", new_path.display());
            }
            println!("\n📋 Migration preview:\n{}", migration_sql);
        } else if is_latest {
            // For latest migration, overwrite the existing file (current behavior)
            std::fs::write(&target_migration.path, migration_sql)?;
            println!("Updated migration: {}", target_migration.path.display());
        } else {
            // For older migration, delete old file and create new one with a
            // fresh timestamp. The no-changes fall-through (a pure re-tag with
            // acquisitions) already moved the file; only delete what exists.
            if target_migration.path.exists() {
                std::fs::remove_file(&target_migration.path)?;
                println!("Deleted: {}", target_migration.path.display());
            }
            let new_filename = format!(
                "{}{}_{}.sql",
                config.migration.filename_prefix,
                new_version,
                new_description.replace(' ', "_")
            );
            let new_path = migrations_dir.join(&new_filename);
            std::fs::write(&new_path, migration_sql)?;
            println!(
                "Migration {} updated to {} (renumbered)",
                target_migration.version, new_version
            );
            println!("Created: {}", new_path.display());
        }
    }

    if dry_run {
        println!("🔍 Dry-run complete! No changes were made.");
    } else {
        println!("Migration update complete!");
    }
    Ok(())
}