pgevolve-core 0.4.6

Postgres declarative schema management — core library (parser, IR, diff, planner) powering the pgevolve CLI.
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
//! `View` and `MaterializedView` — Postgres view IR records.
//!
//! These types are the flat IR representation of views introduced in v0.2.
//! They reference [`NormalizedBody`] for the canonicalized SELECT body and
//! [`DepEdge`] for body-extracted dependency provenance.

use std::collections::BTreeMap;

use serde::{Deserialize, Serialize};

use crate::identifier::{Identifier, QualifiedName};

/// `WITH [LOCAL | CASCADED] CHECK OPTION` setting on a view.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum CheckOption {
    /// `WITH LOCAL CHECK OPTION` — applies only to this view's predicate.
    Local,
    /// `WITH CASCADED CHECK OPTION` — applies through chained updatable views.
    Cascaded,
}
use crate::ir::column_type::ColumnType;
use crate::ir::difference::Difference;
use crate::ir::eq::{Equiv, field_difference};
use crate::parse::normalize_body::NormalizedBody;
use crate::plan::edges::DepEdge;

/// A single named column in a view or materialized view.
///
/// `column_type` is `None` while unresolved — when `ViewColumn` is built from
/// an explicit alias list during parsing, the type requires resolving the
/// SELECT body against the catalog. The AST-canonicalization pass fills it in.
/// Resolution is enforced by `Catalog::canonicalize`: a `None` that survives
/// to canon is an error, so a serialized catalog never carries an unresolved
/// column type. When built from the live catalog the type is always `Some`.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct ViewColumn {
    /// Column name as it appears in the view definition (or is aliased).
    pub name: Identifier,
    /// Resolved data type of the column, or `None` while unresolved.
    pub column_type: Option<ColumnType>,
    /// Optional `COMMENT ON COLUMN` text.
    pub comment: Option<String>,
}

/// A Postgres `CREATE VIEW`.
///
/// The `body_canonical` is the parsed-and-deparsed SELECT statement in
/// canonical form. `body_dependencies` lists the IR objects the body
/// references, extracted from the AST (v0.2 task 4; initially empty until
/// the AST-walk pass lands).
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct View {
    /// Schema-qualified view name.
    pub qname: QualifiedName,
    /// Explicit column alias list (empty when none was provided).
    pub columns: Vec<ViewColumn>,
    /// Canonical form of the SELECT body.
    pub body_canonical: NormalizedBody,
    /// Dependency edges extracted from the body AST.
    pub body_dependencies: Vec<DepEdge>,
    /// `WITH (security_barrier = ...)` option, if present.
    pub security_barrier: Option<bool>,
    /// `WITH (security_invoker = ...)` option, if present.
    pub security_invoker: Option<bool>,
    /// `WITH [LOCAL | CASCADED] CHECK OPTION`, when set in source.
    /// `None` = unmanaged (lenient — operator may have set it out-of-band;
    /// pgevolve neither sets nor resets unless source declares).
    pub check_option: Option<CheckOption>,
    /// Optional `COMMENT ON VIEW` text.
    pub comment: Option<String>,
    /// Raw SELECT body text from source SQL. Populated by the parser (T3);
    /// consumed by the AST canonicalization pass (T4) to fill
    /// `body_canonical` and `body_dependencies`. Not serialized to plan
    /// output or JSON (T4 produces the canonical form which IS serialized).
    #[serde(skip, default)]
    pub raw_body: String,
    /// Object owner. `None` = unmanaged (the differ ignores ownership).
    /// `Some(role)` = managed: diff emits `ALTER VIEW ... OWNER TO role`.
    pub owner: Option<Identifier>,
    /// Grants on this object. Empty = no grants. Canonicalized.
    pub grants: Vec<crate::ir::grant::Grant>,
}

/// A Postgres `CREATE MATERIALIZED VIEW`.
///
/// Unlike regular views, materialized views are physically stored.
/// They lack the `security_barrier` / `security_invoker` options of regular
/// views but are otherwise structurally similar.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct MaterializedView {
    /// Schema-qualified materialized view name.
    pub qname: QualifiedName,
    /// Explicit column alias list (empty when none was provided).
    pub columns: Vec<ViewColumn>,
    /// Canonical form of the SELECT body.
    pub body_canonical: NormalizedBody,
    /// Dependency edges extracted from the body AST.
    pub body_dependencies: Vec<DepEdge>,
    /// Optional `COMMENT ON MATERIALIZED VIEW` text.
    pub comment: Option<String>,
    /// Raw SELECT body text from source SQL. Populated by the parser (T3);
    /// consumed by the AST canonicalization pass (T4) to fill
    /// `body_canonical` and `body_dependencies`. Not serialized to plan
    /// output or JSON (T4 produces the canonical form which IS serialized).
    #[serde(skip, default)]
    pub raw_body: String,
    /// Object owner. `None` = unmanaged (the differ ignores ownership).
    /// `Some(role)` = managed: diff emits `ALTER MATERIALIZED VIEW ... OWNER TO role`.
    pub owner: Option<Identifier>,
    /// Grants on this object. Empty = no grants. Canonicalized.
    pub grants: Vec<crate::ir::grant::Grant>,
    /// Storage parameters. Same key set as Table.
    pub storage: crate::ir::reloptions::MaterializedViewStorageOptions,
}

/// Render an optional view-column type for diff display. An unresolved
/// (`None`) type renders as `"<unresolved>"`; this should not occur
/// post-canonicalization, but the diff impl must total over both arms.
fn render_column_type(ty: Option<&ColumnType>) -> String {
    ty.map_or_else(|| "<unresolved>".to_string(), ColumnType::render_sql)
}

impl Equiv for View {
    #[allow(clippy::too_many_lines)] // flat field-by-field table plus column pairing — extraction would obscure intent.
    fn differences(&self, other: &Self) -> Vec<Difference> {
        // Field-completeness guard: the compiler errors if a field is added to
        // `View` without being handled below. `raw_body` is a `#[serde(skip)]`
        // parser-transient field consumed by canon (it populates
        // `body_canonical` / `body_dependencies`); it is not part of canonical
        // identity, so it is intentionally not diffed. Bindings are unused
        // (values read via `self`/`other`).
        let Self {
            qname: _,
            columns: _,
            body_canonical: _,
            body_dependencies: _,
            security_barrier: _,
            security_invoker: _,
            check_option: _,
            comment: _,
            raw_body: _, // parser-transient, #[serde(skip)], excluded from equivalence
            owner: _,
            grants: _,
        } = self;
        let mut out = Vec::new();
        out.extend(field_difference("qname", &self.qname, &other.qname));
        out.extend(field_difference(
            "body_canonical",
            &self.body_canonical.canonical_text(),
            &other.body_canonical.canonical_text(),
        ));
        out.extend(field_difference(
            "security_barrier",
            &format!("{:?}", self.security_barrier),
            &format!("{:?}", other.security_barrier),
        ));
        out.extend(field_difference(
            "security_invoker",
            &format!("{:?}", self.security_invoker),
            &format!("{:?}", other.security_invoker),
        ));
        out.extend(field_difference(
            "check_option",
            &format!("{:?}", self.check_option),
            &format!("{:?}", other.check_option),
        ));
        out.extend(field_difference(
            "comment",
            &format!("{:?}", self.comment),
            &format!("{:?}", other.comment),
        ));
        out.extend(field_difference(
            "owner",
            &format!("{:?}", self.owner),
            &format!("{:?}", other.owner),
        ));
        out.extend(field_difference(
            "grants",
            &format!("{:?}", self.grants),
            &format!("{:?}", other.grants),
        ));

        // Column diff: pair by name.
        let lhs: BTreeMap<_, _> = self.columns.iter().map(|c| (c.name.as_str(), c)).collect();
        let rhs: BTreeMap<_, _> = other.columns.iter().map(|c| (c.name.as_str(), c)).collect();
        for (name, l) in &lhs {
            match rhs.get(name) {
                None => out.push(Difference::new(
                    format!("columns.{name}"),
                    "present",
                    "removed",
                )),
                Some(r) => {
                    if l.column_type != r.column_type {
                        out.push(Difference::new(
                            format!("columns.{name}.column_type"),
                            render_column_type(l.column_type.as_ref()),
                            render_column_type(r.column_type.as_ref()),
                        ));
                    }
                    if l.comment != r.comment {
                        out.push(Difference::new(
                            format!("columns.{name}.comment"),
                            format!("{:?}", l.comment),
                            format!("{:?}", r.comment),
                        ));
                    }
                }
            }
        }
        for name in rhs.keys() {
            if !lhs.contains_key(name) {
                out.push(Difference::new(
                    format!("columns.{name}"),
                    "missing",
                    "added",
                ));
            }
        }
        let lhs_order: Vec<&str> = self.columns.iter().map(|c| c.name.as_str()).collect();
        let rhs_order: Vec<&str> = other.columns.iter().map(|c| c.name.as_str()).collect();
        if lhs_order != rhs_order {
            out.push(Difference::new(
                "columns.<order>",
                lhs_order.join(","),
                rhs_order.join(","),
            ));
        }

        // Dependency-edge diff: format vec for comparison.
        out.extend(field_difference(
            "body_dependencies",
            &format!("{:?}", self.body_dependencies),
            &format!("{:?}", other.body_dependencies),
        ));

        out
    }
}

impl Equiv for MaterializedView {
    fn differences(&self, other: &Self) -> Vec<Difference> {
        // Field-completeness guard: the compiler errors if a field is added to
        // `MaterializedView` without being handled below. `raw_body` is a
        // `#[serde(skip)]` parser-transient field consumed by canon and not part
        // of canonical identity, so it is intentionally not diffed. Bindings are
        // unused (values read via `self`/`other`).
        let Self {
            qname: _,
            columns: _,
            body_canonical: _,
            body_dependencies: _,
            comment: _,
            raw_body: _,
            owner: _,
            grants: _,
            storage: _,
        } = self;
        let mut out = Vec::new();
        out.extend(field_difference("qname", &self.qname, &other.qname));
        out.extend(field_difference(
            "body_canonical",
            &self.body_canonical.canonical_text(),
            &other.body_canonical.canonical_text(),
        ));
        out.extend(field_difference(
            "comment",
            &format!("{:?}", self.comment),
            &format!("{:?}", other.comment),
        ));
        out.extend(field_difference(
            "owner",
            &format!("{:?}", self.owner),
            &format!("{:?}", other.owner),
        ));
        out.extend(field_difference(
            "grants",
            &format!("{:?}", self.grants),
            &format!("{:?}", other.grants),
        ));
        out.extend(field_difference(
            "storage",
            &format!("{:?}", self.storage),
            &format!("{:?}", other.storage),
        ));

        // Column diff: pair by name.
        let lhs: BTreeMap<_, _> = self.columns.iter().map(|c| (c.name.as_str(), c)).collect();
        let rhs: BTreeMap<_, _> = other.columns.iter().map(|c| (c.name.as_str(), c)).collect();
        for (name, l) in &lhs {
            match rhs.get(name) {
                None => out.push(Difference::new(
                    format!("columns.{name}"),
                    "present",
                    "removed",
                )),
                Some(r) => {
                    if l.column_type != r.column_type {
                        out.push(Difference::new(
                            format!("columns.{name}.column_type"),
                            render_column_type(l.column_type.as_ref()),
                            render_column_type(r.column_type.as_ref()),
                        ));
                    }
                    if l.comment != r.comment {
                        out.push(Difference::new(
                            format!("columns.{name}.comment"),
                            format!("{:?}", l.comment),
                            format!("{:?}", r.comment),
                        ));
                    }
                }
            }
        }
        for name in rhs.keys() {
            if !lhs.contains_key(name) {
                out.push(Difference::new(
                    format!("columns.{name}"),
                    "missing",
                    "added",
                ));
            }
        }
        let lhs_order: Vec<&str> = self.columns.iter().map(|c| c.name.as_str()).collect();
        let rhs_order: Vec<&str> = other.columns.iter().map(|c| c.name.as_str()).collect();
        if lhs_order != rhs_order {
            out.push(Difference::new(
                "columns.<order>",
                lhs_order.join(","),
                rhs_order.join(","),
            ));
        }

        // Dependency-edge diff: format vec for comparison.
        out.extend(field_difference(
            "body_dependencies",
            &format!("{:?}", self.body_dependencies),
            &format!("{:?}", other.body_dependencies),
        ));

        out
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ir::IrError;
    use crate::ir::catalog::Catalog;
    use crate::ir::column_type::ColumnType;
    use crate::plan::edges::{DepSource, NodeId};

    fn id(s: &str) -> Identifier {
        Identifier::from_unquoted(s).unwrap()
    }

    fn qn(schema: &str, name: &str) -> QualifiedName {
        QualifiedName::new(id(schema), id(name))
    }

    fn body(sql: &str) -> NormalizedBody {
        NormalizedBody::from_sql(sql).unwrap()
    }

    fn simple_view(schema: &str, name: &str) -> View {
        View {
            qname: qn(schema, name),
            columns: vec![ViewColumn {
                name: id("id"),
                column_type: Some(ColumnType::BigInt),
                comment: None,
            }],
            body_canonical: body("SELECT 1"),
            body_dependencies: vec![],
            security_barrier: None,
            security_invoker: None,
            check_option: None,
            comment: None,
            raw_body: String::new(),
            owner: None,
            grants: vec![],
        }
    }

    fn simple_mv(schema: &str, name: &str) -> MaterializedView {
        MaterializedView {
            qname: qn(schema, name),
            columns: vec![],
            body_canonical: body("SELECT 1"),
            body_dependencies: vec![],
            comment: None,
            raw_body: String::new(),
            owner: None,
            grants: vec![],
            storage: crate::ir::reloptions::MaterializedViewStorageOptions::default(),
        }
    }

    #[test]
    fn views_with_equal_fields_compare_equal() {
        let v1 = simple_view("app", "active_users");
        let v2 = View {
            qname: qn("app", "active_users"),
            columns: vec![ViewColumn {
                name: id("id"),
                column_type: Some(ColumnType::BigInt),
                comment: None,
            }],
            body_canonical: body("SELECT 1"),
            body_dependencies: vec![],
            security_barrier: None,
            security_invoker: None,
            check_option: None,
            comment: None,
            raw_body: String::new(),
            owner: None,
            grants: vec![],
        };
        assert_eq!(v1, v2);
    }

    #[test]
    fn materialized_view_round_trips_through_serde() {
        let mv = MaterializedView {
            qname: qn("app", "summary"),
            columns: vec![ViewColumn {
                name: id("total"),
                column_type: Some(ColumnType::BigInt),
                comment: Some("total count".to_string()),
            }],
            body_canonical: body("SELECT count(*) FROM users"),
            body_dependencies: vec![DepEdge {
                from: NodeId::Table(qn("app", "summary")),
                to: NodeId::Table(qn("app", "users")),
                source: DepSource::AstExtracted,
            }],
            comment: Some("materialized summary".to_string()),
            raw_body: String::new(),
            owner: None,
            grants: vec![],
            storage: crate::ir::reloptions::MaterializedViewStorageOptions::default(),
        };
        let json = serde_json::to_string(&mv).expect("serialization must succeed");
        let roundtripped: MaterializedView =
            serde_json::from_str(&json).expect("deserialization must succeed");
        assert_eq!(mv, roundtripped);
    }

    #[test]
    fn catalog_with_views_canonicalizes() {
        let mut c = Catalog::empty();
        c.views.push(simple_view("app", "zzz_view"));
        c.views.push(simple_view("app", "aaa_view"));
        c.materialized_views.push(simple_mv("app", "zzz_mv"));
        c.materialized_views.push(simple_mv("app", "aaa_mv"));

        let result = c.canonicalize();
        assert!(result.is_ok(), "canonicalize should succeed: {result:?}");
        let canonical = result.unwrap();

        assert_eq!(canonical.views[0].qname, qn("app", "aaa_view"));
        assert_eq!(canonical.views[1].qname, qn("app", "zzz_view"));
        assert_eq!(canonical.materialized_views[0].qname, qn("app", "aaa_mv"));
        assert_eq!(canonical.materialized_views[1].qname, qn("app", "zzz_mv"));
    }

    #[test]
    fn unresolved_view_column_rejected_by_canon() {
        let mut c = Catalog::empty();
        let mut v = simple_view("app", "v");
        // Force an unresolved column type — as if ast_canon never ran.
        v.columns[0].column_type = None;
        c.views.push(v);

        let result = c.canonicalize();
        assert!(
            matches!(result, Err(IrError::UnresolvedViewColumn { .. })),
            "expected UnresolvedViewColumn error, got: {result:?}",
        );
    }

    #[test]
    fn catalog_rejects_duplicate_view_qname() {
        let mut c = Catalog::empty();
        c.views.push(simple_view("app", "my_view"));
        c.views.push(simple_view("app", "my_view"));

        let result = c.canonicalize();
        assert!(
            matches!(result, Err(IrError::DuplicateObject { kind: "view", .. })),
            "expected duplicate-view error, got: {result:?}",
        );
    }

    #[test]
    fn catalog_rejects_duplicate_materialized_view_qname() {
        let mut c = Catalog::empty();
        c.materialized_views.push(simple_mv("app", "my_mv"));
        c.materialized_views.push(simple_mv("app", "my_mv"));

        let result = c.canonicalize();
        assert!(
            matches!(
                result,
                Err(IrError::DuplicateObject {
                    kind: "materialized view",
                    ..
                })
            ),
            "expected duplicate-mv error, got: {result:?}",
        );
    }

    #[test]
    fn view_owner_change_diffs() {
        use crate::ir::eq::Equiv;
        let mut b = simple_view("app", "active_users");
        b.owner = Some(id("new_owner"));
        assert!(
            simple_view("app", "active_users")
                .differences(&b)
                .iter()
                .any(|x| x.path == "owner")
        );
    }

    #[test]
    fn view_grants_change_diffs() {
        use crate::ir::eq::Equiv;
        let mut b = simple_view("app", "active_users");
        b.grants.push(crate::ir::grant::Grant {
            grantee: crate::ir::grant::GrantTarget::Public,
            privilege: crate::ir::grant::Privilege::Select,
            with_grant_option: false,
            columns: None,
        });
        assert!(
            simple_view("app", "active_users")
                .differences(&b)
                .iter()
                .any(|x| x.path == "grants")
        );
    }

    #[test]
    fn materialized_view_owner_change_diffs() {
        use crate::ir::eq::Equiv;
        let mut b = simple_mv("app", "my_mv");
        b.owner = Some(id("new_owner"));
        assert!(
            simple_mv("app", "my_mv")
                .differences(&b)
                .iter()
                .any(|x| x.path == "owner")
        );
    }

    #[test]
    fn materialized_view_grants_change_diffs() {
        use crate::ir::eq::Equiv;
        let mut b = simple_mv("app", "my_mv");
        b.grants.push(crate::ir::grant::Grant {
            grantee: crate::ir::grant::GrantTarget::Public,
            privilege: crate::ir::grant::Privilege::Select,
            with_grant_option: false,
            columns: None,
        });
        assert!(
            simple_mv("app", "my_mv")
                .differences(&b)
                .iter()
                .any(|x| x.path == "grants")
        );
    }

    #[test]
    fn materialized_view_storage_change_diffs() {
        use crate::ir::eq::Equiv;
        let mut b = simple_mv("app", "my_mv");
        b.storage = crate::ir::reloptions::MaterializedViewStorageOptions {
            fillfactor: Some(80),
            ..Default::default()
        };
        assert!(
            simple_mv("app", "my_mv")
                .differences(&b)
                .iter()
                .any(|x| x.path == "storage")
        );
    }

    #[test]
    fn view_check_option_change_diffs() {
        use crate::ir::eq::Equiv;
        let a = simple_view("app", "v");
        let mut b = simple_view("app", "v");
        b.check_option = Some(CheckOption::Cascaded);
        let d = a.differences(&b);
        assert!(
            d.iter().any(|x| x.path == "check_option"),
            "check_option change must be reported (was silently ignored before): {d:?}",
        );
    }

    #[test]
    fn check_option_local_does_not_equal_cascaded() {
        assert_ne!(CheckOption::Local, CheckOption::Cascaded);
    }

    #[test]
    fn check_option_implements_copy() {
        let a = CheckOption::Local;
        let b = a; // copies
        let c = a; // still usable
        assert_eq!(b, CheckOption::Local);
        assert_eq!(c, CheckOption::Local);
    }
}