pgevolve-core 0.3.4

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
//! Differ for publications. Pair by name; per-publication granular diff.
//!
//! Key behaviors:
//! - Source has it, target doesn't → `CreatePublication` (Safe).
//! - Target has it, source doesn't → no auto-drop (lenient); surfaces via
//!   `unmanaged-publication` lint in Stage 9.
//! - Both have it, mode mismatch (`AllTables` ↔ `Selective`) → `ReplacePublication`
//!   (`RequiresApproval`). No per-field diffs — replace handles everything.
//! - Both have it, same `Selective` mode → per-table add/drop/set, per-schema
//!   add/drop, per-publication scalar diffs, owner (v0.3.1 lenient pattern).
//!
//! Spec: `docs/superpowers/specs/2026-05-26-publications-design.md`.

use std::collections::BTreeMap;

use crate::diff::change::Change;
use crate::diff::changeset::ChangeSet;
use crate::diff::destructiveness::Destructiveness;
use crate::diff::owner_op::{AlterObjectOwner, OwnerObjectKind};
use crate::identifier::Identifier;
use crate::ir::catalog::Catalog;
use crate::ir::publication::{Publication, PublicationScope, PublishedTable};

/// Compute granular publication changes needed to converge `target` toward
/// `source`. Appends all emitted changes to `out`.
pub fn diff_publications(target: &Catalog, source: &Catalog, out: &mut ChangeSet) {
    let target_map: BTreeMap<&Identifier, &Publication> =
        target.publications.iter().map(|p| (&p.name, p)).collect();
    let source_map: BTreeMap<&Identifier, &Publication> =
        source.publications.iter().map(|p| (&p.name, p)).collect();

    // Creates: in source but not in target.
    for (name, src) in &source_map {
        if !target_map.contains_key(name) {
            out.push(
                Change::CreatePublication((*src).clone()),
                Destructiveness::Safe,
            );
        }
    }

    // Target-only: lenient — no auto-drop. Surfaces via unmanaged-publication lint.
    // Intentionally no-op loop; Stage 9 adds the unmanaged-publication lint rule.
    for _name in target_map.keys() {
        // unmanaged-publication lint (Stage 9) handles publications absent from source.
    }

    // Modifies: in both.
    for (name, src) in &source_map {
        let Some(tgt) = target_map.get(name) else {
            continue;
        };
        diff_one_publication(tgt, src, out);
    }
}

fn diff_one_publication(target: &Publication, source: &Publication, out: &mut ChangeSet) {
    // Mode mismatch → ReplacePublication (RequiresApproval).
    // A mode swap stops replication for the old set of tables, so it needs
    // explicit approval. No data is destroyed (WAL is not deleted), but
    // subscribers will see an interruption.
    let target_mode = std::mem::discriminant(&target.scope);
    let source_mode = std::mem::discriminant(&source.scope);
    if target_mode != source_mode {
        out.push(
            Change::ReplacePublication {
                from: target.clone(),
                to: source.clone(),
            },
            Destructiveness::RequiresApproval {
                reason: format!(
                    "publication {} mode swap (AllTables ↔ Selective)",
                    source.name
                ),
            },
        );
        // Do not emit per-field diffs — the replace handles everything.
        return;
    }

    // Same mode. For Selective, diff tables and schemas granularly.
    if let (
        PublicationScope::Selective {
            schemas: t_schemas,
            tables: t_tables,
        },
        PublicationScope::Selective {
            schemas: s_schemas,
            tables: s_tables,
        },
    ) = (&target.scope, &source.scope)
    {
        diff_selective_tables(&source.name, t_tables, s_tables, out);
        diff_selective_schemas(&source.name, t_schemas, s_schemas, out);
    }
    // AllTables mode has no per-table or per-schema granular diffs.

    // Per-publication scalar diffs.
    if target.publish != source.publish {
        out.push(
            Change::AlterPublicationSetPublish {
                publication: source.name.clone(),
                kinds: source.publish,
            },
            Destructiveness::Safe,
        );
    }
    if target.publish_via_partition_root != source.publish_via_partition_root {
        out.push(
            Change::AlterPublicationSetViaRoot {
                publication: source.name.clone(),
                value: source.publish_via_partition_root,
            },
            Destructiveness::Safe,
        );
    }
    if target.comment != source.comment {
        out.push(
            Change::CommentOnPublication {
                name: source.name.clone(),
                comment: source.comment.clone(),
            },
            Destructiveness::Safe,
        );
    }

    // Owner: v0.3.1 lenient pattern — only emit when source declares an owner
    // and it differs from target. Source `None` = unmanaged, no change emitted.
    if let Some(s_owner) = &source.owner
        && target.owner.as_ref() != Some(s_owner)
    {
        let from = target.owner.clone().unwrap_or_else(|| {
            Identifier::from_unquoted("__unknown_owner__")
                .expect("literal is always a valid unquoted identifier")
        });
        out.push(
            Change::AlterObjectOwner(AlterObjectOwner {
                kind: OwnerObjectKind::Publication,
                // Publications are not schema-qualified. We use a synthetic
                // QualifiedName with `__cluster__` as the schema component to
                // satisfy the `QualifiedName` type (same convention as cluster
                // ops in plan/cluster_rewrite/emit.rs).
                qname: crate::identifier::QualifiedName::new(
                    Identifier::from_unquoted("__cluster__")
                        .expect("literal is always a valid unquoted identifier"),
                    source.name.clone(),
                ),
                signature: String::new(),
                from,
                to: s_owner.clone(),
            }),
            Destructiveness::Safe,
        );
    }
}

fn diff_selective_tables(
    pub_name: &Identifier,
    target_tables: &[PublishedTable],
    source_tables: &[PublishedTable],
    out: &mut ChangeSet,
) {
    let t_map: BTreeMap<_, _> = target_tables.iter().map(|t| (&t.qname, t)).collect();
    let s_map: BTreeMap<_, _> = source_tables.iter().map(|t| (&t.qname, t)).collect();

    // Added tables: in source but not in target.
    for (qname, t) in &s_map {
        if !t_map.contains_key(qname) {
            out.push(
                Change::AlterPublicationAddTable {
                    publication: pub_name.clone(),
                    table: (*t).clone(),
                },
                Destructiveness::Safe,
            );
        }
    }

    // Dropped tables: in target but not in source.
    for qname in t_map.keys() {
        if !s_map.contains_key(qname) {
            out.push(
                Change::AlterPublicationDropTable {
                    publication: pub_name.clone(),
                    qname: (*qname).clone(),
                },
                Destructiveness::Safe,
            );
        }
    }

    // Changed tables: in both, but row_filter or columns differ.
    for (qname, src_table) in &s_map {
        let Some(tgt_table) = t_map.get(qname) else {
            continue;
        };
        if tgt_table.row_filter != src_table.row_filter || tgt_table.columns != src_table.columns {
            out.push(
                Change::AlterPublicationSetTable {
                    publication: pub_name.clone(),
                    table: (*src_table).clone(),
                },
                Destructiveness::Safe,
            );
        }
    }
}

fn diff_selective_schemas(
    pub_name: &Identifier,
    target_schemas: &std::collections::BTreeSet<Identifier>,
    source_schemas: &std::collections::BTreeSet<Identifier>,
    out: &mut ChangeSet,
) {
    // Added schemas: in source but not in target.
    for s in source_schemas.difference(target_schemas) {
        out.push(
            Change::AlterPublicationAddSchema {
                publication: pub_name.clone(),
                schema: s.clone(),
            },
            Destructiveness::Safe,
        );
    }

    // Dropped schemas: in target but not in source.
    for s in target_schemas.difference(source_schemas) {
        out.push(
            Change::AlterPublicationDropSchema {
                publication: pub_name.clone(),
                schema: s.clone(),
            },
            Destructiveness::Safe,
        );
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::identifier::{Identifier, QualifiedName};
    use crate::ir::catalog::Catalog;
    use crate::ir::publication::{Publication, PublicationScope, PublishKinds, PublishedTable};
    use std::collections::BTreeSet;

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

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

    fn pub_all_tables(name: &str) -> Publication {
        Publication {
            name: id(name),
            scope: PublicationScope::AllTables,
            publish: PublishKinds::pg_default(),
            publish_via_partition_root: false,
            owner: None,
            comment: None,
        }
    }

    fn pub_selective(name: &str, tables: Vec<PublishedTable>) -> Publication {
        Publication {
            name: id(name),
            scope: PublicationScope::Selective {
                schemas: BTreeSet::new(),
                tables,
            },
            publish: PublishKinds::pg_default(),
            publish_via_partition_root: false,
            owner: None,
            comment: None,
        }
    }

    fn table_entry(schema: &str, name: &str) -> PublishedTable {
        PublishedTable {
            qname: qn(schema, name),
            row_filter: None,
            columns: None,
        }
    }

    fn catalog_with(pubs: Vec<Publication>) -> Catalog {
        let mut c = Catalog::empty();
        c.publications = pubs;
        c
    }

    fn run_diff(target: &Catalog, source: &Catalog) -> ChangeSet {
        let mut out = ChangeSet::new();
        diff_publications(target, source, &mut out);
        out
    }

    // ---- creates ----

    #[test]
    fn create_pub_when_source_has_it_and_target_doesnt() {
        let target = Catalog::empty();
        let source = catalog_with(vec![pub_all_tables("p")]);
        let changes = run_diff(&target, &source);
        assert_eq!(changes.len(), 1);
        assert!(matches!(
            changes.iter().next().unwrap().change,
            Change::CreatePublication(_)
        ));
    }

    // ---- lenient: no auto-drop ----

    #[test]
    fn no_drop_when_target_has_pub_but_source_doesnt() {
        let target = catalog_with(vec![pub_all_tables("p")]);
        let source = Catalog::empty();
        let changes = run_diff(&target, &source);
        assert!(
            changes.is_empty(),
            "expected no changes (lenient), got {changes:?}"
        );
    }

    // ---- mode mismatch ----

    #[test]
    fn mode_mismatch_emits_replace_publication() {
        let target = catalog_with(vec![pub_all_tables("p")]);
        let source = catalog_with(vec![pub_selective("p", vec![table_entry("app", "t")])]);
        let changes = run_diff(&target, &source);
        assert_eq!(changes.len(), 1);
        let entry = changes.iter().next().unwrap();
        assert!(
            matches!(entry.change, Change::ReplacePublication { .. }),
            "expected ReplacePublication, got {:?}",
            entry.change
        );
        assert!(
            entry.destructiveness.requires_approval(),
            "mode swap must be RequiresApproval"
        );
    }

    #[test]
    fn mode_mismatch_emits_no_per_field_diffs() {
        // Even if publish differs, only ReplacePublication is emitted on mode mismatch.
        let target = catalog_with(vec![pub_all_tables("p")]);
        let mut src_pub = pub_selective("p", vec![table_entry("app", "t")]);
        src_pub.publish = PublishKinds {
            insert: true,
            update: false,
            delete: false,
            truncate: false,
        };
        let source = catalog_with(vec![src_pub]);
        let changes = run_diff(&target, &source);
        assert_eq!(changes.len(), 1, "only ReplacePublication, no scalar diffs");
    }

    // ---- same-Selective: per-table diffs ----

    #[test]
    fn add_table_when_source_has_it_and_target_doesnt() {
        let target = catalog_with(vec![pub_selective("p", vec![])]);
        let source = catalog_with(vec![pub_selective("p", vec![table_entry("app", "t")])]);
        let changes = run_diff(&target, &source);
        assert_eq!(changes.len(), 1);
        assert!(matches!(
            changes.iter().next().unwrap().change,
            Change::AlterPublicationAddTable { .. }
        ));
    }

    #[test]
    fn drop_table_when_target_has_it_and_source_doesnt() {
        let target = catalog_with(vec![pub_selective("p", vec![table_entry("app", "t")])]);
        let source = catalog_with(vec![pub_selective("p", vec![])]);
        let changes = run_diff(&target, &source);
        assert_eq!(changes.len(), 1);
        assert!(matches!(
            changes.iter().next().unwrap().change,
            Change::AlterPublicationDropTable { .. }
        ));
    }

    #[test]
    fn set_table_when_columns_differ() {
        let mut src_table = table_entry("app", "t");
        src_table.columns = Some(vec![id("id"), id("name")]);
        let target = catalog_with(vec![pub_selective("p", vec![table_entry("app", "t")])]);
        let source = catalog_with(vec![pub_selective("p", vec![src_table])]);
        let changes = run_diff(&target, &source);
        assert_eq!(changes.len(), 1);
        assert!(matches!(
            changes.iter().next().unwrap().change,
            Change::AlterPublicationSetTable { .. }
        ));
    }

    #[test]
    fn no_change_when_table_identical() {
        let t = table_entry("app", "orders");
        let target = catalog_with(vec![pub_selective("p", vec![t.clone()])]);
        let source = catalog_with(vec![pub_selective("p", vec![t])]);
        let changes = run_diff(&target, &source);
        assert!(changes.is_empty());
    }

    // ---- per-schema diffs ----

    #[test]
    fn add_schema_when_source_has_it_and_target_doesnt() {
        let tgt_pub = Publication {
            name: id("p"),
            scope: PublicationScope::Selective {
                schemas: BTreeSet::new(),
                tables: vec![table_entry("app", "t")],
            },
            publish: PublishKinds::pg_default(),
            publish_via_partition_root: false,
            owner: None,
            comment: None,
        };
        let src_pub = Publication {
            name: id("p"),
            scope: PublicationScope::Selective {
                schemas: BTreeSet::from([id("app")]),
                tables: vec![table_entry("app", "t")],
            },
            publish: PublishKinds::pg_default(),
            publish_via_partition_root: false,
            owner: None,
            comment: None,
        };
        let target = catalog_with(vec![tgt_pub]);
        let source = catalog_with(vec![src_pub]);
        let changes = run_diff(&target, &source);
        assert_eq!(changes.len(), 1);
        assert!(matches!(
            changes.iter().next().unwrap().change,
            Change::AlterPublicationAddSchema { .. }
        ));
    }

    #[test]
    fn drop_schema_when_target_has_it_and_source_doesnt() {
        let tgt_pub = Publication {
            name: id("p"),
            scope: PublicationScope::Selective {
                schemas: BTreeSet::from([id("app")]),
                tables: vec![table_entry("app", "t")],
            },
            publish: PublishKinds::pg_default(),
            publish_via_partition_root: false,
            owner: None,
            comment: None,
        };
        let src_pub = Publication {
            name: id("p"),
            scope: PublicationScope::Selective {
                schemas: BTreeSet::new(),
                tables: vec![table_entry("app", "t")],
            },
            publish: PublishKinds::pg_default(),
            publish_via_partition_root: false,
            owner: None,
            comment: None,
        };
        let target = catalog_with(vec![tgt_pub]);
        let source = catalog_with(vec![src_pub]);
        let changes = run_diff(&target, &source);
        assert_eq!(changes.len(), 1);
        assert!(matches!(
            changes.iter().next().unwrap().change,
            Change::AlterPublicationDropSchema { .. }
        ));
    }

    // ---- scalar diffs ----

    #[test]
    fn set_publish_when_publish_kinds_differ() {
        let target = catalog_with(vec![pub_all_tables("p")]);
        let mut src_pub = pub_all_tables("p");
        src_pub.publish = PublishKinds {
            insert: true,
            update: false,
            delete: false,
            truncate: false,
        };
        let source = catalog_with(vec![src_pub]);
        let changes = run_diff(&target, &source);
        assert_eq!(changes.len(), 1);
        assert!(matches!(
            changes.iter().next().unwrap().change,
            Change::AlterPublicationSetPublish { .. }
        ));
    }

    #[test]
    fn set_via_root_when_differs() {
        let target = catalog_with(vec![pub_all_tables("p")]);
        let mut src_pub = pub_all_tables("p");
        src_pub.publish_via_partition_root = true;
        let source = catalog_with(vec![src_pub]);
        let changes = run_diff(&target, &source);
        assert_eq!(changes.len(), 1);
        assert!(matches!(
            changes.iter().next().unwrap().change,
            Change::AlterPublicationSetViaRoot { value: true, .. }
        ));
    }

    #[test]
    fn comment_on_publication_when_comment_differs() {
        let target = catalog_with(vec![pub_all_tables("p")]);
        let mut src_pub = pub_all_tables("p");
        src_pub.comment = Some("my pub".into());
        let source = catalog_with(vec![src_pub]);
        let changes = run_diff(&target, &source);
        assert_eq!(changes.len(), 1);
        assert!(matches!(
            changes.iter().next().unwrap().change,
            Change::CommentOnPublication { .. }
        ));
    }

    // ---- owner: lenient pattern ----

    #[test]
    fn owner_change_emits_alter_object_owner() {
        let mut tgt_pub = pub_all_tables("p");
        tgt_pub.owner = Some(id("alice"));
        let mut src_pub = pub_all_tables("p");
        src_pub.owner = Some(id("bob"));
        let target = catalog_with(vec![tgt_pub]);
        let source = catalog_with(vec![src_pub]);
        let changes = run_diff(&target, &source);
        assert_eq!(changes.len(), 1);
        assert!(matches!(
            changes.iter().next().unwrap().change,
            Change::AlterObjectOwner(_)
        ));
    }

    #[test]
    fn no_owner_change_when_source_owner_is_none() {
        // Source `None` = unmanaged ownership; no change emitted.
        let mut tgt_pub = pub_all_tables("p");
        tgt_pub.owner = Some(id("alice"));
        let src_pub = pub_all_tables("p"); // owner = None
        let target = catalog_with(vec![tgt_pub]);
        let source = catalog_with(vec![src_pub]);
        let changes = run_diff(&target, &source);
        assert!(
            changes.is_empty(),
            "source owner None = unmanaged, no change expected"
        );
    }

    // ---- identity (diff against self) ----

    #[test]
    fn diff_against_self_is_empty_all_tables() {
        let c = catalog_with(vec![pub_all_tables("p")]);
        let changes = run_diff(&c, &c);
        assert!(changes.is_empty());
    }

    #[test]
    fn diff_against_self_is_empty_selective() {
        let c = catalog_with(vec![pub_selective("p", vec![table_entry("app", "users")])]);
        let changes = run_diff(&c, &c);
        assert!(changes.is_empty());
    }
}