pgevolve-core 0.3.9

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
//! SQL rendering for publication operations.
//!
//! Each public function corresponds to one DML kind on a Postgres PUBLICATION.
//! All helpers return a complete SQL statement including the trailing semicolon.

use crate::identifier::{Identifier, QualifiedName};
use crate::ir::publication::{Publication, PublicationScope, PublishKinds, PublishedTable};

/// `CREATE PUBLICATION p … WITH (…);`
///
/// Handles all five scope forms:
/// - `FOR ALL TABLES`
/// - `FOR TABLE x [(cols)] [WHERE (filter)], …`
/// - `FOR TABLES IN SCHEMA s, …`
/// - Mixed `FOR TABLE … , TABLES IN SCHEMA …`
///
/// The `WITH (…)` clause is omitted when all options are at their PG defaults.
#[must_use]
pub fn create_publication(p: &Publication) -> String {
    let mut s = format!("CREATE PUBLICATION {}", p.name.render_sql());
    match &p.scope {
        PublicationScope::AllTables => s.push_str(" FOR ALL TABLES"),
        PublicationScope::Selective { schemas, tables } => {
            s.push_str(" FOR ");
            let mut first = true;
            if !tables.is_empty() {
                s.push_str("TABLE ");
                for t in tables {
                    if !first {
                        s.push_str(", ");
                    }
                    s.push_str(&render_published_table(t));
                    first = false;
                }
            }
            if !schemas.is_empty() {
                if !first {
                    s.push_str(", ");
                }
                s.push_str("TABLES IN SCHEMA ");
                let names: Vec<String> = schemas.iter().map(Identifier::render_sql).collect();
                s.push_str(&names.join(", "));
            }
        }
    }
    s.push_str(&render_with_options(p));
    s.push(';');
    s
}

/// `DROP PUBLICATION p;`
#[must_use]
pub fn drop_publication(name: &Identifier) -> String {
    format!("DROP PUBLICATION {};", name.render_sql())
}

/// Two-step replace: `[DROP PUBLICATION old, CREATE PUBLICATION new]`.
///
/// The caller is responsible for joining with a newline when rendering both
/// steps into a single `RawStep` SQL body.
#[must_use]
pub fn replace_publication(from: &Publication, to: &Publication) -> [String; 2] {
    [drop_publication(&from.name), create_publication(to)]
}

/// `ALTER PUBLICATION p ADD TABLE x [(cols)] [WHERE (filter)];`
#[must_use]
pub fn alter_publication_add_table(pname: &Identifier, t: &PublishedTable) -> String {
    format!(
        "ALTER PUBLICATION {} ADD TABLE {};",
        pname.render_sql(),
        render_published_table(t),
    )
}

/// `ALTER PUBLICATION p DROP TABLE x;`
#[must_use]
pub fn alter_publication_drop_table(pname: &Identifier, qname: &QualifiedName) -> String {
    format!(
        "ALTER PUBLICATION {} DROP TABLE {};",
        pname.render_sql(),
        qname.render_sql(),
    )
}

/// `ALTER PUBLICATION p SET TABLE x [(cols)] [WHERE (filter)];`
///
/// Replaces just that one table's specification without affecting other tables
/// in the publication.
#[must_use]
pub fn alter_publication_set_table(pname: &Identifier, t: &PublishedTable) -> String {
    format!(
        "ALTER PUBLICATION {} SET TABLE {};",
        pname.render_sql(),
        render_published_table(t),
    )
}

/// `ALTER PUBLICATION p ADD TABLES IN SCHEMA s;` (PG 15+)
#[must_use]
pub fn alter_publication_add_schema(pname: &Identifier, schema: &Identifier) -> String {
    format!(
        "ALTER PUBLICATION {} ADD TABLES IN SCHEMA {};",
        pname.render_sql(),
        schema.render_sql(),
    )
}

/// `ALTER PUBLICATION p DROP TABLES IN SCHEMA s;` (PG 15+)
#[must_use]
pub fn alter_publication_drop_schema(pname: &Identifier, schema: &Identifier) -> String {
    format!(
        "ALTER PUBLICATION {} DROP TABLES IN SCHEMA {};",
        pname.render_sql(),
        schema.render_sql(),
    )
}

/// `ALTER PUBLICATION p SET (publish = '…');`
#[must_use]
pub fn alter_publication_set_publish(pname: &Identifier, k: PublishKinds) -> String {
    format!(
        "ALTER PUBLICATION {} SET (publish = '{}');",
        pname.render_sql(),
        render_publish_kinds(k),
    )
}

/// `ALTER PUBLICATION p SET (publish_via_partition_root = …);`
#[must_use]
pub fn alter_publication_set_via_root(pname: &Identifier, value: bool) -> String {
    format!(
        "ALTER PUBLICATION {} SET (publish_via_partition_root = {value});",
        pname.render_sql(),
    )
}

/// `COMMENT ON PUBLICATION p IS '…';` or `… IS NULL;` when `comment` is `None`.
///
/// Single quotes inside the comment body are escaped by doubling.
#[must_use]
pub fn comment_on_publication(name: &Identifier, comment: Option<&str>) -> String {
    let body = comment.map_or_else(
        || "NULL".to_string(),
        |c| format!("'{}'", c.replace('\'', "''")),
    );
    format!("COMMENT ON PUBLICATION {} IS {body};", name.render_sql())
}

// ─── private helpers ──────────────────────────────────────────────────────────

/// Render a single table entry (qname, optional column list, optional WHERE filter).
fn render_published_table(t: &PublishedTable) -> String {
    let mut s = t.qname.render_sql();
    if let Some(cols) = &t.columns {
        s.push_str(" (");
        let names: Vec<String> = cols.iter().map(Identifier::render_sql).collect();
        s.push_str(&names.join(", "));
        s.push(')');
    }
    if let Some(filter) = &t.row_filter {
        s.push_str(" WHERE (");
        s.push_str(&filter.canonical_text);
        s.push(')');
    }
    s
}

/// Render the `WITH (…)` clause, omitting it entirely when all values are at
/// their PG defaults (all DML kinds enabled, `publish_via_partition_root = false`).
fn render_with_options(p: &Publication) -> String {
    let mut parts = Vec::new();
    if p.publish != PublishKinds::pg_default() {
        parts.push(format!("publish = '{}'", render_publish_kinds(p.publish)));
    }
    if p.publish_via_partition_root {
        parts.push("publish_via_partition_root = true".to_string());
    }
    if parts.is_empty() {
        String::new()
    } else {
        format!(" WITH ({})", parts.join(", "))
    }
}

/// Render a `PublishKinds` bitset as a comma-separated keyword list.
///
/// The canonical PG ordering is `insert, update, delete, truncate`.
fn render_publish_kinds(k: PublishKinds) -> String {
    let mut parts = Vec::new();
    if k.insert {
        parts.push("insert");
    }
    if k.update {
        parts.push("update");
    }
    if k.delete {
        parts.push("delete");
    }
    if k.truncate {
        parts.push("truncate");
    }
    parts.join(", ")
}

// ─── tests ────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use crate::identifier::Identifier;
    use crate::ir::default_expr::NormalizedExpr;

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

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

    fn all_tables_pub() -> Publication {
        Publication {
            name: id("p"),
            scope: PublicationScope::AllTables,
            publish: PublishKinds::pg_default(),
            publish_via_partition_root: false,
            owner: None,
            comment: None,
        }
    }

    #[test]
    fn renders_create_for_all_tables() {
        let p = all_tables_pub();
        assert_eq!(
            create_publication(&p),
            "CREATE PUBLICATION p FOR ALL TABLES;"
        );
    }

    #[test]
    fn renders_create_for_all_tables_omits_default_with_options() {
        let p = all_tables_pub();
        // With-options empty when everything is at PG defaults.
        assert!(!create_publication(&p).contains("WITH"));
    }

    #[test]
    fn renders_create_for_table_with_columns_and_filter() {
        let filter = NormalizedExpr::from_text("status = 'active'");
        let table = PublishedTable {
            qname: qn("app", "t"),
            row_filter: Some(filter),
            columns: Some(vec![id("id"), id("name")]),
        };
        let p = Publication {
            name: id("p"),
            scope: PublicationScope::Selective {
                schemas: std::collections::BTreeSet::new(),
                tables: vec![table],
            },
            publish: PublishKinds::pg_default(),
            publish_via_partition_root: false,
            owner: None,
            comment: None,
        };
        let sql = create_publication(&p);
        assert!(sql.contains("FOR TABLE app.t (id, name) WHERE ("));
        assert!(sql.contains("status = 'active'"));
    }

    #[test]
    fn renders_publish_kinds_subset() {
        let k = PublishKinds {
            insert: true,
            update: true,
            delete: false,
            truncate: false,
        };
        assert_eq!(render_publish_kinds(k), "insert, update");
    }

    #[test]
    fn renders_publish_kinds_single() {
        let k = PublishKinds {
            insert: true,
            update: false,
            delete: false,
            truncate: false,
        };
        assert_eq!(render_publish_kinds(k), "insert");
    }

    #[test]
    fn with_options_empty_at_pg_defaults() {
        let p = all_tables_pub();
        assert_eq!(render_with_options(&p), "");
    }

    #[test]
    fn with_options_renders_non_default_publish() {
        let mut p = all_tables_pub();
        p.publish = PublishKinds {
            insert: true,
            update: false,
            delete: false,
            truncate: false,
        };
        assert_eq!(render_with_options(&p), " WITH (publish = 'insert')");
    }

    #[test]
    fn with_options_renders_via_root() {
        let mut p = all_tables_pub();
        p.publish_via_partition_root = true;
        assert_eq!(
            render_with_options(&p),
            " WITH (publish_via_partition_root = true)"
        );
    }

    #[test]
    fn renders_alter_set_publish() {
        let k = PublishKinds {
            insert: true,
            update: false,
            delete: false,
            truncate: false,
        };
        assert_eq!(
            alter_publication_set_publish(&id("p"), k),
            "ALTER PUBLICATION p SET (publish = 'insert');",
        );
    }

    #[test]
    fn renders_alter_set_via_root() {
        assert_eq!(
            alter_publication_set_via_root(&id("p"), true),
            "ALTER PUBLICATION p SET (publish_via_partition_root = true);",
        );
        assert_eq!(
            alter_publication_set_via_root(&id("p"), false),
            "ALTER PUBLICATION p SET (publish_via_partition_root = false);",
        );
    }

    #[test]
    fn comment_on_publication_with_null() {
        assert_eq!(
            comment_on_publication(&id("p"), None),
            "COMMENT ON PUBLICATION p IS NULL;",
        );
    }

    #[test]
    fn comment_on_publication_with_value() {
        assert_eq!(
            comment_on_publication(&id("p"), Some("my pub")),
            "COMMENT ON PUBLICATION p IS 'my pub';",
        );
    }

    #[test]
    fn comment_on_publication_escapes_single_quotes() {
        assert_eq!(
            comment_on_publication(&id("p"), Some("it's cool")),
            "COMMENT ON PUBLICATION p IS 'it''s cool';",
        );
    }

    #[test]
    fn replace_publication_returns_drop_then_create() {
        let from = all_tables_pub();
        let mut to = all_tables_pub();
        to.name = id("q");
        let [drop_sql, create_sql] = replace_publication(&from, &to);
        assert_eq!(drop_sql, "DROP PUBLICATION p;");
        assert_eq!(create_sql, "CREATE PUBLICATION q FOR ALL TABLES;");
    }

    #[test]
    fn renders_drop_publication() {
        assert_eq!(drop_publication(&id("p")), "DROP PUBLICATION p;");
    }

    #[test]
    fn renders_alter_add_table() {
        let t = PublishedTable {
            qname: qn("app", "orders"),
            row_filter: None,
            columns: None,
        };
        assert_eq!(
            alter_publication_add_table(&id("p"), &t),
            "ALTER PUBLICATION p ADD TABLE app.orders;",
        );
    }

    #[test]
    fn renders_alter_drop_table() {
        assert_eq!(
            alter_publication_drop_table(&id("p"), &qn("app", "orders")),
            "ALTER PUBLICATION p DROP TABLE app.orders;",
        );
    }

    #[test]
    fn renders_alter_add_schema() {
        assert_eq!(
            alter_publication_add_schema(&id("p"), &id("app")),
            "ALTER PUBLICATION p ADD TABLES IN SCHEMA app;",
        );
    }

    #[test]
    fn renders_alter_drop_schema() {
        assert_eq!(
            alter_publication_drop_schema(&id("p"), &id("app")),
            "ALTER PUBLICATION p DROP TABLES IN SCHEMA app;",
        );
    }

    #[test]
    fn renders_create_for_tables_in_schema() {
        let p = Publication {
            name: id("p"),
            scope: PublicationScope::Selective {
                schemas: std::collections::BTreeSet::from([id("app")]),
                tables: vec![],
            },
            publish: PublishKinds::pg_default(),
            publish_via_partition_root: false,
            owner: None,
            comment: None,
        };
        assert_eq!(
            create_publication(&p),
            "CREATE PUBLICATION p FOR TABLES IN SCHEMA app;",
        );
    }
}