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
//! src/catalog/view.rs
//! Fetch views and their dependencies via pg_depend + pg_rewrite
use super::id::{DbObjectId, DependsOn};
use super::utils::{is_system_schema, resolve_type_dependency};
use anyhow::Result;
use sqlx::postgres::PgConnection;
use sqlx::postgres::types::Oid;
use std::collections::{HashMap, HashSet};
use tracing::info;

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ViewColumn {
    pub name: String,
    pub type_: Option<String>, // PostgreSQL doesn't always expose this directly
    pub comment: Option<String>,
}

#[derive(Debug, Clone)]
pub struct View {
    pub schema: String,
    pub name: String,
    pub definition: String, // raw `SELECT …`
    pub columns: Vec<ViewColumn>,
    pub comment: Option<String>,     // comment on the view
    pub security_invoker: bool,      // PG 15+: execute with invoker's permissions (default: false)
    pub security_barrier: bool,      // prevent predicate pushdown for security (default: false)
    pub depends_on: Vec<DbObjectId>, // populated from pg_depend
}

impl View {
    pub fn id(&self) -> DbObjectId {
        DbObjectId::View {
            schema: self.schema.clone(),
            name: self.name.clone(),
        }
    }
}

impl DependsOn for View {
    fn id(&self) -> DbObjectId {
        DbObjectId::View {
            schema: self.schema.clone(),
            name: self.name.clone(),
        }
    }

    fn depends_on(&self) -> &[DbObjectId] {
        &self.depends_on
    }
}

#[derive(sqlx::FromRow)]
struct RawView {
    view_oid: Oid,
    schema: String,
    name: String,
    definition: String,
    comment: Option<String>,
    reloptions: Option<Vec<String>>,
}

/// Build column type string, schema-qualifying custom types and preserving array brackets
fn build_column_type(
    formatted_type: &str,
    type_schema: &Option<String>,
    type_name: &Option<String>,
    attndims: i32,
    is_extension_type: bool,
) -> String {
    // Extension and system types use format_type directly
    if is_extension_type {
        return formatted_type.to_string();
    }
    if type_schema.as_ref().is_some_and(|s| is_system_schema(s)) || type_schema.is_none() {
        return formatted_type.to_string();
    }

    // Custom types need schema qualification
    if let (Some(schema), Some(name)) = (type_schema, type_name) {
        if attndims > 0 {
            format!(
                "\"{}\".\"{}\"{}",
                schema,
                name,
                "[]".repeat(attndims as usize)
            )
        } else if formatted_type.ends_with("[]") {
            format!("\"{}\".\"{}\"{}", schema, name, "[]")
        } else {
            format!("\"{}\".\"{}\"", schema, name)
        }
    } else {
        formatted_type.to_string()
    }
}

/// Parse reloptions to extract security_invoker and security_barrier
fn parse_view_options(reloptions: &Option<Vec<String>>) -> (bool, bool) {
    let mut security_invoker = false;
    let mut security_barrier = false;

    if let Some(opts) = reloptions {
        for opt in opts {
            if opt == "security_invoker=true" || opt == "security_invoker=on" {
                security_invoker = true;
            } else if opt == "security_barrier=true" || opt == "security_barrier=on" {
                security_barrier = true;
            }
        }
    }

    (security_invoker, security_barrier)
}

/// Fetch all non-system views, then populate `depends_on` via pg_depend.
pub async fn fetch(conn: &mut PgConnection) -> Result<Vec<View>> {
    // 1. Fetch view OIDs + definitions
    info!("Fetching views...");
    let raw: Vec<RawView> = sqlx::query_as!(
        RawView,
        r#"
        SELECT
          c.oid                    AS "view_oid!",
          n.nspname                AS "schema!",
          c.relname                AS "name!",
          pg_catalog.pg_get_viewdef(c.oid, true) AS "definition!",
          d.description            AS "comment?",
          c.reloptions             AS "reloptions?"
        FROM pg_class c
        JOIN pg_namespace n
          ON c.relnamespace = n.oid
        LEFT JOIN pg_description d ON d.objoid = c.oid AND d.objsubid = 0
        WHERE c.relkind = 'v'                             -- only views
          AND n.nspname NOT IN ('pg_catalog','information_schema', 'pg_toast')
          -- Exclude views that belong to extensions
          AND NOT EXISTS (
              SELECT 1 FROM pg_depend dep
              WHERE dep.objid = c.oid
              AND dep.deptype = 'e'
          )
        ORDER BY n.nspname, c.relname
        "#
    )
    .fetch_all(&mut *conn)
    .await?;

    info!("Fetching view columns...");
    // Use pg_attribute + pg_type for consistent array handling with other catalog types
    let column_rows = sqlx::query!(
        r#"
        SELECT
            n.nspname AS "schema!",
            c.relname AS "view_name!",
            a.attname AS "column_name!",
            pg_catalog.format_type(a.atttypid, a.atttypmod) AS "data_type!",
            COALESCE(a.attndims, 0)::int AS "attndims!: i32",
            -- Resolve array element type schema/name for custom type handling
            CASE
                WHEN t.typelem != 0 THEN elem_tn.nspname
                ELSE tn.nspname
            END AS "type_schema?",
            CASE
                WHEN t.typelem != 0 THEN elem_t.typname
                ELSE t.typname
            END AS "type_name?",
            -- Check if type (or element type for arrays) is from an extension
            ext_types.extname IS NOT NULL AS "is_extension_type!: bool",
            d.description AS "comment?"
        FROM pg_attribute a
        JOIN pg_class c ON a.attrelid = c.oid
        JOIN pg_namespace n ON c.relnamespace = n.oid
        LEFT JOIN pg_type t ON a.atttypid = t.oid
        LEFT JOIN pg_namespace tn ON t.typnamespace = tn.oid
        -- Element type for array attributes
        LEFT JOIN pg_type elem_t ON t.typelem = elem_t.oid AND t.typelem != 0
        LEFT JOIN pg_namespace elem_tn ON elem_t.typnamespace = elem_tn.oid
        -- Extension type lookup
        LEFT JOIN (
            SELECT DISTINCT dep.objid AS type_oid, e.extname
            FROM pg_depend dep
            JOIN pg_extension e ON dep.refobjid = e.oid
            WHERE dep.deptype = 'e'
        ) ext_types ON ext_types.type_oid = COALESCE(NULLIF(t.typelem, 0::oid), t.oid)
        -- Per-column comment (objsubid = attnum)
        LEFT JOIN pg_description d ON d.objoid = a.attrelid AND d.objsubid = a.attnum
        WHERE c.relkind = 'v'
          AND a.attnum > 0
          AND NOT a.attisdropped
          AND n.nspname NOT IN ('pg_catalog', 'information_schema', 'pg_toast')
        ORDER BY n.nspname, c.relname, a.attnum
        "#
    )
    .fetch_all(&mut *conn)
    .await?;

    let mut columns_by_view: HashMap<(String, String), Vec<ViewColumn>> = HashMap::new();
    for col in column_rows {
        let key = (col.schema.clone(), col.view_name.clone());
        let type_str = build_column_type(
            &col.data_type,
            &col.type_schema,
            &col.type_name,
            col.attndims,
            col.is_extension_type,
        );
        columns_by_view.entry(key).or_default().push(ViewColumn {
            name: col.column_name,
            type_: Some(type_str),
            comment: col.comment,
        });
    }

    // Build initial View structs (empty depends_on) and index map
    let mut views: Vec<View> = raw
        .iter()
        .map(|r| {
            let key = (r.schema.clone(), r.name.clone());
            let columns = columns_by_view.remove(&key).unwrap_or_default();
            let (security_invoker, security_barrier) = parse_view_options(&r.reloptions);

            View {
                schema: r.schema.clone(),
                name: r.name.clone(),
                definition: r.definition.clone(),
                columns,
                comment: r.comment.clone(),
                security_invoker,
                security_barrier,
                depends_on: Vec::new(),
            }
        })
        .collect();

    let mut oid_to_idx: HashMap<Oid, usize> = HashMap::with_capacity(raw.len());
    let view_oids: Vec<Oid> = raw
        .into_iter()
        .enumerate()
        .map(|(i, r)| {
            oid_to_idx.insert(r.view_oid, i);
            r.view_oid
        })
        .collect();

    info!("Fetching view dependencies...");
    let deps = sqlx::query!(
        r#"
        SELECT
          r.ev_class                     AS "view_oid!",         -- the view itself
          d.refclassid                   AS "refclassid!",       -- kind of object
          d.refobjid                     AS "refobjid!",


          -- Table or view reference
          cls.relkind::text             AS "cls_relkind",
          cls_n.nspname                 AS "cls_schema",
          cls.relname                   AS "cls_name",

          -- Type reference (resolve array element type)
          CASE
            WHEN typ.typelem != 0 THEN elem_typ.typname
            ELSE typ.typname
          END AS "typ_name",
          CASE
            WHEN typ.typelem != 0 THEN elem_typ_n.nspname
            ELSE typ_n.nspname
          END AS "typ_schema",
          ext_types.extname AS "typ_extension_name?",
          -- Get typtype to distinguish domains ('d') from other types
          CASE
            WHEN typ.typelem != 0 THEN elem_typ.typtype::text
            ELSE typ.typtype::text
          END AS "typ_typtype?",
          -- Get relkind for composite types (to distinguish table/view from explicit composite)
          CASE
            WHEN typ.typelem != 0 THEN elem_typ_rel.relkind::text
            ELSE typ_rel.relkind::text
          END AS "typ_relkind?",

          -- Function reference
          proc.proname                  AS "proc_name",
          proc_n.nspname                AS "proc_schema",
          pg_catalog.pg_get_function_identity_arguments(proc.oid) AS "proc_args?",
          ext_procs.extname AS "proc_extension_name?",

          -- Operator reference (custom operators used in the view body; PostgreSQL
          -- records these in pg_depend via the OpExpr's opno).
          op.oprname                    AS "op_name?",
          op_n.nspname                  AS "op_schema?",
          CASE WHEN op.oprleft = 0 THEN NULL ELSE format_type(op.oprleft, NULL) END AS "op_left_type?",
          CASE WHEN op.oprright = 0 THEN NULL ELSE format_type(op.oprright, NULL) END AS "op_right_type?",
          ext_ops.extname AS "op_extension_name?"

        FROM pg_rewrite r
        JOIN pg_depend d
          ON d.classid = 'pg_rewrite'::regclass::oid
         AND d.objid    = r.oid

        -- Table/view reference
        LEFT JOIN pg_class cls
          ON d.refclassid = 'pg_class'::regclass::oid
         AND d.refobjid   = cls.oid

        LEFT JOIN pg_namespace cls_n
          ON cls.relnamespace = cls_n.oid

        -- Type reference
        LEFT JOIN pg_type typ
          ON d.refclassid = 'pg_type'::regclass::oid
         AND d.refobjid   = typ.oid

        LEFT JOIN pg_namespace typ_n
          ON typ.typnamespace = typ_n.oid

        -- Element type for array types
        LEFT JOIN pg_type elem_typ
          ON typ.typelem = elem_typ.oid AND typ.typelem != 0

        LEFT JOIN pg_namespace elem_typ_n
          ON elem_typ.typnamespace = elem_typ_n.oid

        -- Get relkind for composite types (to distinguish table/view from explicit composite)
        LEFT JOIN pg_class typ_rel
          ON typ.typrelid = typ_rel.oid AND typ.typrelid != 0
        LEFT JOIN pg_class elem_typ_rel
          ON elem_typ.typrelid = elem_typ_rel.oid AND elem_typ.typrelid != 0

        -- Extension type lookup: compute once as derived table, then hash join
        LEFT JOIN (
            SELECT DISTINCT dep.objid AS type_oid, e.extname
            FROM pg_depend dep
            JOIN pg_extension e ON dep.refobjid = e.oid
            WHERE dep.deptype = 'e'
        ) ext_types ON ext_types.type_oid = COALESCE(NULLIF(typ.typelem, 0::oid), typ.oid)

        -- Function reference
        LEFT JOIN pg_proc proc
          ON d.refclassid = 'pg_proc'::regclass::oid
         AND d.refobjid   = proc.oid

        LEFT JOIN pg_namespace proc_n
          ON proc.pronamespace = proc_n.oid

        -- Extension function lookup: compute once as derived table, then hash join
        LEFT JOIN (
            SELECT DISTINCT dep.objid AS proc_oid, e.extname
            FROM pg_depend dep
            JOIN pg_extension e ON dep.refobjid = e.oid
            WHERE dep.deptype = 'e'
        ) ext_procs ON ext_procs.proc_oid = proc.oid

        -- Operator reference
        LEFT JOIN pg_operator op
          ON d.refclassid = 'pg_operator'::regclass::oid
         AND d.refobjid   = op.oid

        LEFT JOIN pg_namespace op_n
          ON op.oprnamespace = op_n.oid

        -- Extension operator lookup
        LEFT JOIN (
            SELECT DISTINCT dep.objid AS op_oid, e.extname
            FROM pg_depend dep
            JOIN pg_extension e ON dep.refobjid = e.oid
            WHERE dep.deptype = 'e'
        ) ext_ops ON ext_ops.op_oid = op.oid

        WHERE r.ev_class = ANY($1)
        "#,
        &view_oids,
    )
    .fetch_all(&mut *conn)
    .await?;

    // 3. Map each dependency row into the corresponding View.depends_on
    for d in deps {
        if let Some(&idx) = oid_to_idx.get(&d.view_oid) {
            let view_id = views[idx].id();
            let v = &mut views[idx].depends_on;

            // Table or nested view?
            if let Some(relkind) = d.cls_relkind.as_deref() {
                let dep = match relkind {
                    "r" | "p" => DbObjectId::Table {
                        schema: d.cls_schema.unwrap(),
                        name: d.cls_name.unwrap(),
                    },
                    "v" | "m" => DbObjectId::View {
                        schema: d.cls_schema.unwrap(),
                        name: d.cls_name.unwrap(),
                    },
                    _ => continue, // skip other relkinds
                };
                if dep != view_id {
                    v.push(dep);
                }
                continue;
            }

            // Custom type, domain, or extension type?
            // Use resolve_type_dependency for consistent handling of extension types,
            // domains, composite types from tables/views, and other custom types
            if let Some(dep_id) = resolve_type_dependency(
                d.typ_schema.as_deref(),
                d.typ_name.as_deref(),
                d.typ_typtype.as_deref(),
                d.typ_relkind.as_deref(),
                d.typ_extension_name.is_some(),
                d.typ_extension_name.as_deref(),
            ) {
                v.push(dep_id);
                continue;
            }

            // Function or extension function?
            if let (Some(name), Some(ns), Some(args)) = (&d.proc_name, &d.proc_schema, &d.proc_args)
                && !is_system_schema(ns)
            {
                // If function is from an extension, depend on the extension instead
                if let Some(ext_name) = &d.proc_extension_name {
                    v.push(DbObjectId::Extension {
                        name: ext_name.clone(),
                    });
                } else {
                    v.push(DbObjectId::Function {
                        schema: ns.to_string(),
                        name: name.to_string(),
                        arguments: args.to_string(),
                    });
                }
                continue;
            }

            // Custom operator used in the view body? (Built-in operators live in
            // pg_catalog and are skipped; extension operators depend on the extension.)
            if let (Some(name), Some(ns)) = (&d.op_name, &d.op_schema)
                && !is_system_schema(ns)
            {
                if let Some(ext_name) = &d.op_extension_name {
                    v.push(DbObjectId::Extension {
                        name: ext_name.clone(),
                    });
                } else {
                    let arguments = format!(
                        "{}, {}",
                        d.op_left_type.as_deref().unwrap_or("NONE"),
                        d.op_right_type.as_deref().unwrap_or("NONE")
                    );
                    v.push(DbObjectId::Operator {
                        schema: ns.to_string(),
                        name: name.to_string(),
                        arguments,
                    });
                }
            }
        }
    }

    // Deduplicate dependencies for each view
    for view in &mut views {
        let unique_deps: HashSet<_> = view.depends_on.drain(..).collect();
        view.depends_on.extend(unique_deps);

        // Add implicit schema dependency (every view depends on its schema existing)
        // Only add if it's not the default 'public' schema
        if view.schema != "public" {
            view.depends_on.push(DbObjectId::Schema {
                name: view.schema.clone(),
            });
        }
    }

    Ok(views)
}