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
573
574
575
576
577
578
579
580
581
582
583
584
use anyhow::Result;
use dialoguer::{Confirm, MultiSelect};
use sqlx::PgPool;
use std::collections::BTreeSet;

use crate::catalog::Catalog;

/// Import schema from an existing database with interactive schema selection
pub async fn import_from_database(url: String) -> Result<Catalog> {
    tracing::debug!("Connecting to database...");

    // Connect directly to the source database
    let pool = PgPool::connect(&url)
        .await
        .map_err(|e| anyhow::anyhow!("Failed to connect to database: {}", e))?;

    tracing::debug!("Connected successfully");
    tracing::debug!("Analyzing database schema...");

    // Load full catalog first to analyze available schemas
    // Physical-world load: the interactive schema selection below and
    // init's single filtering point scope the result.
    let full_catalog = Catalog::load_unfiltered(&pool)
        .await
        .map_err(|e| anyhow::anyhow!("Failed to load database catalog: {}", e))?;

    pool.close().await;

    let total_objects = count_catalog_objects(&full_catalog);

    tracing::debug!(
        "Found {} schemas with {} total objects",
        full_catalog.schemas.len(),
        total_objects
    );

    // Show schema analysis and get user selection
    let selected_schemas = prompt_schema_selection(&full_catalog)?;

    tracing::debug!("Filtering catalog for selected schemas...");

    // Filter catalog to only include selected schemas
    let filtered_catalog = filter_catalog_by_schemas(full_catalog, &selected_schemas);

    let filtered_objects = count_catalog_objects(&filtered_catalog);

    tracing::debug!(
        "Filtered to {} objects from {} selected schemas",
        filtered_objects,
        selected_schemas.len()
    );

    Ok(filtered_catalog)
}

/// Count total objects in a catalog
fn count_catalog_objects(catalog: &Catalog) -> usize {
    catalog.tables.len()
        + catalog.views.len()
        + catalog.functions.len()
        + catalog.types.len()
        + catalog.sequences.len()
        + catalog.indexes.len()
        + catalog.constraints.len()
        + catalog.triggers.len()
        + catalog.policies.len()
        + catalog.extensions.len()
        + catalog.grants.len()
}

/// Prompt user to select which schemas to import
fn prompt_schema_selection(catalog: &Catalog) -> Result<Vec<String>> {
    if catalog.schemas.is_empty() {
        println!("📊 No user schemas found in database.");
        return Ok(vec![]);
    }

    // Analyze schema contents
    let mut schema_info = Vec::new();
    for schema in &catalog.schemas {
        let tables_count = catalog
            .tables
            .iter()
            .filter(|t| t.schema == schema.name)
            .count();
        let views_count = catalog
            .views
            .iter()
            .filter(|v| v.schema == schema.name)
            .count();
        let functions_count = catalog
            .functions
            .iter()
            .filter(|f| f.schema == schema.name)
            .count();
        let types_count = catalog
            .types
            .iter()
            .filter(|t| t.schema == schema.name)
            .count();
        let sequences_count = catalog
            .sequences
            .iter()
            .filter(|s| s.schema == schema.name)
            .count();
        let indexes_count = catalog
            .indexes
            .iter()
            .filter(|i| i.schema == schema.name)
            .count();
        let constraints_count = catalog
            .constraints
            .iter()
            .filter(|c| c.schema == schema.name)
            .count();
        let triggers_count = catalog
            .triggers
            .iter()
            .filter(|t| t.schema == schema.name)
            .count();
        let policies_count = catalog
            .policies
            .iter()
            .filter(|p| p.schema == schema.name)
            .count();

        // Extensions are handled separately as they may not have schema association
        let extensions_count = catalog
            .extensions
            .iter()
            .filter(|e| e.schema == schema.name)
            .count();

        // Grants are complex - count those that reference objects in this schema
        let grants_count = catalog
            .grants
            .iter()
            .filter(|g| g.target.schema() == schema.name)
            .count();

        let total_objects = tables_count
            + views_count
            + functions_count
            + types_count
            + sequences_count
            + indexes_count
            + constraints_count
            + triggers_count
            + policies_count
            + extensions_count
            + grants_count;

        schema_info.push((
            schema.name.clone(),
            total_objects,
            tables_count,
            views_count,
            functions_count,
            types_count,
            sequences_count,
            indexes_count,
            constraints_count,
            triggers_count,
            policies_count,
            extensions_count,
            grants_count,
        ));
    }

    // Sort by total object count (most active schemas first)
    schema_info.sort_by(|a, b| b.1.cmp(&a.1));

    display_schema_table(&schema_info);

    // Create selection items with detailed descriptions
    let items: Vec<String> = schema_info
        .iter()
        .map(
            |(
                name,
                total,
                tables,
                views,
                functions,
                types,
                sequences,
                indexes,
                constraints,
                triggers,
                policies,
                extensions,
                grants,
            )| {
                if *total == 0 {
                    format!("{} (empty)", name)
                } else {
                    let mut parts = Vec::new();
                    if *tables > 0 {
                        parts.push(format!(
                            "{} table{}",
                            tables,
                            if *tables == 1 { "" } else { "s" }
                        ));
                    }
                    if *views > 0 {
                        parts.push(format!(
                            "{} view{}",
                            views,
                            if *views == 1 { "" } else { "s" }
                        ));
                    }
                    if *functions > 0 {
                        parts.push(format!(
                            "{} function{}",
                            functions,
                            if *functions == 1 { "" } else { "s" }
                        ));
                    }
                    if *types > 0 {
                        parts.push(format!(
                            "{} type{}",
                            types,
                            if *types == 1 { "" } else { "s" }
                        ));
                    }
                    if *sequences > 0 {
                        parts.push(format!(
                            "{} sequence{}",
                            sequences,
                            if *sequences == 1 { "" } else { "s" }
                        ));
                    }
                    if *indexes > 0 {
                        parts.push(format!(
                            "{} index{}",
                            indexes,
                            if *indexes == 1 { "" } else { "es" }
                        ));
                    }
                    if *constraints > 0 {
                        parts.push(format!(
                            "{} constraint{}",
                            constraints,
                            if *constraints == 1 { "" } else { "s" }
                        ));
                    }
                    if *triggers > 0 {
                        parts.push(format!(
                            "{} trigger{}",
                            triggers,
                            if *triggers == 1 { "" } else { "s" }
                        ));
                    }
                    if *policies > 0 {
                        parts.push(format!(
                            "{} polic{}",
                            policies,
                            if *policies == 1 { "y" } else { "ies" }
                        ));
                    }
                    if *extensions > 0 {
                        parts.push(format!(
                            "{} extension{}",
                            extensions,
                            if *extensions == 1 { "" } else { "s" }
                        ));
                    }
                    if *grants > 0 {
                        parts.push(format!(
                            "{} grant{}",
                            grants,
                            if *grants == 1 { "" } else { "s" }
                        ));
                    }

                    format!("{} ({})", name, parts.join(", "))
                }
            },
        )
        .collect();

    if items.is_empty() {
        return Ok(vec![]);
    }

    // Default to selecting non-empty schemas
    let defaults: Vec<bool> = schema_info
        .iter()
        .map(|(_, total, _, _, _, _, _, _, _, _, _, _, _)| *total > 0)
        .collect();

    println!("\n🎯 Select schemas to import (use Space to toggle, Enter to confirm):");
    let selections = MultiSelect::new()
        .with_prompt("Which schemas would you like to import?")
        .items(&items)
        .defaults(&defaults)
        .interact()?;

    if selections.is_empty() {
        println!("⚠️  No schemas selected for import.");
        let continue_anyway = Confirm::new()
            .with_prompt("Continue with empty schema directory?")
            .default(false)
            .interact()?;

        if !continue_anyway {
            return Err(anyhow::anyhow!("Import cancelled by user"));
        }
        return Ok(vec![]);
    }

    let selected_schemas: Vec<String> = selections
        .iter()
        .map(|&i| schema_info[i].0.clone())
        .collect();

    println!(
        "✅ Selected {} schema{} for import: {}",
        selected_schemas.len(),
        if selected_schemas.len() == 1 { "" } else { "s" },
        selected_schemas.join(", ")
    );

    Ok(selected_schemas)
}

/// Display schema information in a formatted table
#[allow(clippy::type_complexity)]
fn display_schema_table(
    schema_info: &[(
        String,
        usize,
        usize,
        usize,
        usize,
        usize,
        usize,
        usize,
        usize,
        usize,
        usize,
        usize,
        usize,
    )],
) {
    println!("\n📊 Available schemas in database:");
    println!(
        "┌──────────────────────────────────────────────────────────────────────────────────────────────────┐"
    );
    println!(
        "│ Schema            Tables Views Funcs Types Seqs Idxs Cnsts Trigs Pols Exts Grants Total          │"
    );
    println!(
        "├──────────────────────────────────────────────────────────────────────────────────────────────────┤"
    );

    for (
        name,
        total,
        tables,
        views,
        functions,
        types,
        sequences,
        indexes,
        constraints,
        triggers,
        policies,
        extensions,
        grants,
    ) in schema_info
    {
        println!(
            "│ {:16} {:6} {:5} {:5} {:5} {:4} {:4} {:5} {:5} {:4} {:4} {:6} {:5}",
            name,
            tables,
            views,
            functions,
            types,
            sequences,
            indexes,
            constraints,
            triggers,
            policies,
            extensions,
            grants,
            total
        );
    }
    println!(
        "└──────────────────────────────────────────────────────────────────────────────────────────────────┘"
    );
}

/// Filter catalog to only include objects from selected schemas
fn filter_catalog_by_schemas(mut catalog: Catalog, selected_schemas: &[String]) -> Catalog {
    use crate::catalog::id::{DbObjectId, DependsOn};

    if selected_schemas.is_empty() {
        // Return empty catalog if no schemas selected
        return Catalog::empty();
    }

    let schema_set: BTreeSet<String> = selected_schemas.iter().cloned().collect();

    // Filter all object types by schema
    catalog.schemas.retain(|s| schema_set.contains(&s.name));
    catalog.tables.retain(|t| schema_set.contains(&t.schema));
    catalog.views.retain(|v| schema_set.contains(&v.schema));
    catalog.functions.retain(|f| schema_set.contains(&f.schema));
    catalog.types.retain(|t| schema_set.contains(&t.schema));
    catalog.sequences.retain(|s| schema_set.contains(&s.schema));
    catalog.indexes.retain(|i| schema_set.contains(&i.schema));
    catalog
        .constraints
        .retain(|c| schema_set.contains(&c.schema));
    catalog.triggers.retain(|t| schema_set.contains(&t.schema));
    catalog.policies.retain(|p| schema_set.contains(&p.schema));
    catalog
        .extensions
        .retain(|e| schema_set.contains(&e.schema));
    catalog.grants.retain(|g| {
        // Grants reference selected schemas via their target object's schema.
        schema_set.contains(&g.target.schema())
    });

    // Rebuild dependency maps after filtering
    catalog.forward_deps.clear();
    catalog.reverse_deps.clear();

    // Helper for any T: DependsOn (same as in Catalog::load)
    fn insert_deps<T: DependsOn>(
        items: &[T],
        fwd: &mut std::collections::BTreeMap<DbObjectId, Vec<DbObjectId>>,
        rev: &mut std::collections::BTreeMap<DbObjectId, Vec<DbObjectId>>,
    ) {
        for item in items {
            let id = item.id();
            let deps = item.depends_on();
            fwd.insert(id.clone(), deps.to_vec());

            for dep in deps {
                rev.entry(dep.clone()).or_default().push(id.clone());
            }
        }
    }

    insert_deps(
        &catalog.tables,
        &mut catalog.forward_deps,
        &mut catalog.reverse_deps,
    );
    insert_deps(
        &catalog.views,
        &mut catalog.forward_deps,
        &mut catalog.reverse_deps,
    );
    insert_deps(
        &catalog.types,
        &mut catalog.forward_deps,
        &mut catalog.reverse_deps,
    );
    insert_deps(
        &catalog.functions,
        &mut catalog.forward_deps,
        &mut catalog.reverse_deps,
    );
    insert_deps(
        &catalog.sequences,
        &mut catalog.forward_deps,
        &mut catalog.reverse_deps,
    );
    insert_deps(
        &catalog.indexes,
        &mut catalog.forward_deps,
        &mut catalog.reverse_deps,
    );
    insert_deps(
        &catalog.constraints,
        &mut catalog.forward_deps,
        &mut catalog.reverse_deps,
    );
    insert_deps(
        &catalog.triggers,
        &mut catalog.forward_deps,
        &mut catalog.reverse_deps,
    );
    insert_deps(
        &catalog.policies,
        &mut catalog.forward_deps,
        &mut catalog.reverse_deps,
    );
    insert_deps(
        &catalog.extensions,
        &mut catalog.forward_deps,
        &mut catalog.reverse_deps,
    );
    insert_deps(
        &catalog.grants,
        &mut catalog.forward_deps,
        &mut catalog.reverse_deps,
    );

    catalog
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::catalog::{schema::Schema, table::Table};

    #[test]
    fn test_count_catalog_objects() {
        let mut catalog = Catalog::empty();
        assert_eq!(count_catalog_objects(&catalog), 0);

        // Add a table
        catalog.tables.push(Table::new(
            "public".to_string(),
            "users".to_string(),
            vec![],
            None,
            None,
            vec![],
        ));
        assert_eq!(count_catalog_objects(&catalog), 1);
    }

    #[test]
    fn test_filter_catalog_by_schemas() {
        let mut catalog = Catalog::empty();

        // Add schemas
        catalog.schemas.push(Schema {
            name: "public".to_string(),
            comment: None,
        });
        catalog.schemas.push(Schema {
            name: "private".to_string(),
            comment: None,
        });

        // Add tables in different schemas
        catalog.tables.push(Table::new(
            "public".to_string(),
            "users".to_string(),
            vec![],
            None,
            None,
            vec![],
        ));
        catalog.tables.push(Table::new(
            "private".to_string(),
            "secrets".to_string(),
            vec![],
            None,
            None,
            vec![],
        ));

        // Filter to only include public schema
        let selected_schemas = vec!["public".to_string()];
        let filtered_catalog = filter_catalog_by_schemas(catalog, &selected_schemas);

        assert_eq!(filtered_catalog.schemas.len(), 1);
        assert_eq!(filtered_catalog.tables.len(), 1);
        assert_eq!(filtered_catalog.schemas[0].name, "public");
        assert_eq!(filtered_catalog.tables[0].name, "users");
    }

    #[test]
    fn test_filter_catalog_empty_selection() {
        let mut catalog = Catalog::empty();
        catalog.schemas.push(Schema {
            name: "public".to_string(),
            comment: None,
        });

        let selected_schemas: Vec<String> = vec![];
        let filtered_catalog = filter_catalog_by_schemas(catalog, &selected_schemas);

        assert_eq!(filtered_catalog.schemas.len(), 0);
    }
}