pgevolve-core 0.4.2

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
//! Column-level diffing inside an `AlterTable`.
//!
//! Pairs columns by name. Logical column order is intentionally **not**
//! enforced in v0.1 — the IR records it, but reordering would require a table
//! rewrite. If the user wants a specific physical order, they must drop and
//! recreate the table.
//!
//! ## Widening whitelist
//!
//! `is_widening` returns true only for type changes Postgres can perform
//! without rewriting data: `int2 → int4 → int8`, `varchar(N) → varchar(M>N)`,
//! `varchar(*) → text`. Everything else is conservative and tagged
//! [`Destructiveness::RequiresApprovalAndDataLossWarning`].

use std::collections::BTreeMap;

use crate::identifier::Identifier;
use crate::ir::canon::filter_pg_defaults::type_default_storage;
use crate::ir::column::Column;
use crate::ir::column_type::ColumnType;
use crate::ir::table::Table;

use super::destructiveness::Destructiveness;
use super::table_op::{TableOp, TableOpEntry};

/// Diff columns in `target` against `source`, appending entries to `out`.
pub fn diff_columns(target: &Table, source: &Table, out: &mut Vec<TableOpEntry>) {
    let target_map: BTreeMap<&Identifier, &Column> =
        target.columns.iter().map(|c| (&c.name, c)).collect();
    let source_map: BTreeMap<&Identifier, &Column> =
        source.columns.iter().map(|c| (&c.name, c)).collect();

    for (name, source_col) in &source_map {
        if !target_map.contains_key(name) {
            out.push(add_column_entry((*source_col).clone()));
        }
    }

    for (name, target_col) in &target_map {
        match source_map.get(name) {
            None => {
                out.push(TableOpEntry {
                    op: TableOp::DropColumn {
                        name: (*name).clone(),
                        is_populated: false,
                    },
                    destructiveness: Destructiveness::RequiresApprovalAndDataLossWarning {
                        reason: format!("drops column {name}"),
                    },
                });
            }
            Some(source_col) => {
                diff_column(target_col, source_col, out);
            }
        }
    }
}

fn add_column_entry(col: Column) -> TableOpEntry {
    let safe = col.nullable || col.default.is_some();
    let destructiveness = if safe {
        Destructiveness::Safe
    } else {
        Destructiveness::RequiresApproval {
            reason: format!(
                "adds NOT NULL column {} with no default — fails on a non-empty table",
                col.name
            ),
        }
    };
    TableOpEntry {
        op: TableOp::AddColumn(col),
        destructiveness,
    }
}

// Each attribute's diff block is a self-contained guard + push; extracting
// them into sub-functions would scatter the logic across many tiny helpers
// without reducing cognitive load.
#[allow(clippy::too_many_lines)] // exhaustive per-column-attribute diff with destructiveness classification.
fn diff_column(target: &Column, source: &Column, out: &mut Vec<TableOpEntry>) {
    if target.ty != source.ty {
        let destructiveness = if is_widening(&target.ty, &source.ty) {
            Destructiveness::Safe
        } else {
            Destructiveness::RequiresApprovalAndDataLossWarning {
                reason: format!(
                    "narrows or changes type family on column {} ({} -> {})",
                    target.name,
                    target.ty.render_sql(),
                    source.ty.render_sql()
                ),
            }
        };
        out.push(TableOpEntry {
            op: TableOp::AlterColumnType {
                name: target.name.clone(),
                from: target.ty.clone(),
                to: source.ty.clone(),
                using: None,
            },
            destructiveness,
        });
    }

    if target.nullable != source.nullable {
        let destructiveness = if source.nullable {
            // Going to nullable is always safe.
            Destructiveness::Safe
        } else {
            Destructiveness::RequiresApproval {
                reason: format!(
                    "SET NOT NULL on {} may fail if column has NULL values",
                    target.name
                ),
            }
        };
        out.push(TableOpEntry {
            op: TableOp::SetColumnNullable {
                name: target.name.clone(),
                nullable: source.nullable,
            },
            destructiveness,
        });
    }

    if target.default != source.default {
        out.push(TableOpEntry {
            op: TableOp::SetColumnDefault {
                name: target.name.clone(),
                default: source.default.clone(),
            },
            destructiveness: Destructiveness::Safe,
        });
    }

    if target.identity != source.identity {
        out.push(TableOpEntry {
            op: TableOp::SetColumnIdentity {
                name: target.name.clone(),
                identity: source.identity.clone(),
            },
            destructiveness: Destructiveness::RequiresApproval {
                reason: "identity changes can fail or rewrite data".into(),
            },
        });
    }

    if target.generated != source.generated {
        out.push(TableOpEntry {
            op: TableOp::SetColumnGenerated {
                name: target.name.clone(),
                generated: source.generated.clone(),
            },
            destructiveness: Destructiveness::RequiresApproval {
                reason: "generated-column changes can fail or rewrite data".into(),
            },
        });
    }

    if target.comment != source.comment {
        out.push(TableOpEntry {
            op: TableOp::SetColumnComment {
                name: target.name.clone(),
                comment: source.comment.clone(),
            },
            destructiveness: Destructiveness::Safe,
        });
    }

    // Storage: resolve None to the type default on both sides so the
    // emitted op is always explicit. Carries both `from` and `to` so the
    // lint rule can detect downgrades.
    {
        let from = target
            .storage
            .unwrap_or_else(|| type_default_storage(&target.ty));
        let to = source
            .storage
            .unwrap_or_else(|| type_default_storage(&source.ty));
        if from != to {
            out.push(TableOpEntry {
                op: TableOp::SetColumnStorage {
                    name: target.name.clone(),
                    from,
                    to,
                },
                destructiveness: Destructiveness::Safe,
            });
        }
    }

    if target.compression != source.compression {
        out.push(TableOpEntry {
            op: TableOp::SetColumnCompression {
                name: target.name.clone(),
                compression: source.compression,
            },
            destructiveness: Destructiveness::Safe,
        });
    }
}

/// Postgres can perform these type changes in place without rewriting data.
///
/// `char(N)` is intentionally absent from the whitelist: char→varchar/text
/// changes semantics (pg right-pads char), and char(N)→char(M) is treated
/// like other length changes — conservative for v0.1.
//
// Each arm is left as a separate case to keep the whitelist readable; the
// extra `match_same_arms` lint hurts readability here without giving us
// anything in return.
#[allow(clippy::match_same_arms)]
fn is_widening(from: &ColumnType, to: &ColumnType) -> bool {
    use ColumnType::{BigInt, Integer, SmallInt, Text, Varchar};
    match (from, to) {
        // Integer family: small → larger only.
        (SmallInt, Integer | BigInt) => true,
        (Integer, BigInt) => true,
        // varchar(N) → varchar(M) when M > N.
        (Varchar { len: Some(n) }, Varchar { len: Some(m) }) => m > n,
        // varchar(N) → unbounded varchar.
        (Varchar { len: Some(_) }, Varchar { len: None }) => true,
        // varchar(N) → text (text is unbounded).
        (Varchar { len: Some(_) }, Text) => true,
        _ => false,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::identifier::QualifiedName;
    use crate::ir::column::{Compression, StorageKind};
    use crate::ir::default_expr::{DefaultExpr, LiteralValue};

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

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

    fn col(name: &str, ty: ColumnType, nullable: bool) -> Column {
        Column {
            name: id(name),
            ty,
            nullable,
            default: None,
            identity: None,
            generated: None,
            collation: None,
            storage: None,
            compression: None,
            comment: None,
        }
    }

    fn tbl(cols: Vec<Column>) -> Table {
        Table {
            qname: qn("users"),
            columns: cols,
            constraints: vec![],
            partition_by: None,
            partition_of: None,
            comment: None,
            owner: None,
            grants: vec![],
            rls_enabled: false,
            rls_forced: false,
            policies: vec![],
            storage: crate::ir::reloptions::TableStorageOptions::default(),
            access_method: None,
        }
    }

    fn diff_one(target: &Table, source: &Table) -> Vec<TableOpEntry> {
        let mut out = Vec::new();
        diff_columns(target, source, &mut out);
        out
    }

    // ---- adds ----

    #[test]
    fn add_nullable_column_is_safe() {
        let target = tbl(vec![col("id", ColumnType::BigInt, false)]);
        let source = tbl(vec![
            col("id", ColumnType::BigInt, false),
            col("email", ColumnType::Text, true),
        ]);
        let ops = diff_one(&target, &source);
        assert_eq!(ops.len(), 1);
        assert!(matches!(ops[0].op, TableOp::AddColumn(_)));
        assert_eq!(ops[0].destructiveness, Destructiveness::Safe);
    }

    #[test]
    fn add_not_null_column_with_default_is_safe() {
        let target = tbl(vec![col("id", ColumnType::BigInt, false)]);
        let mut new_col = col("created", ColumnType::BigInt, false);
        new_col.default = Some(DefaultExpr::Literal(LiteralValue::Integer(0)));
        let source = tbl(vec![col("id", ColumnType::BigInt, false), new_col]);
        let ops = diff_one(&target, &source);
        assert_eq!(ops[0].destructiveness, Destructiveness::Safe);
    }

    #[test]
    fn add_not_null_column_without_default_requires_approval() {
        let target = tbl(vec![col("id", ColumnType::BigInt, false)]);
        let source = tbl(vec![
            col("id", ColumnType::BigInt, false),
            col("email", ColumnType::Text, false),
        ]);
        let ops = diff_one(&target, &source);
        assert_eq!(ops.len(), 1);
        assert!(ops[0].destructiveness.requires_approval());
        assert!(!ops[0].destructiveness.data_loss_risk());
    }

    // ---- drops ----

    #[test]
    fn drop_column_is_data_loss_warning() {
        let target = tbl(vec![
            col("id", ColumnType::BigInt, false),
            col("email", ColumnType::Text, true),
        ]);
        let source = tbl(vec![col("id", ColumnType::BigInt, false)]);
        let ops = diff_one(&target, &source);
        assert_eq!(ops.len(), 1);
        assert!(matches!(ops[0].op, TableOp::DropColumn { .. }));
        assert!(ops[0].destructiveness.data_loss_risk());
    }

    // ---- type changes / widening ----

    #[test]
    fn integer_to_bigint_is_widening_safe() {
        let target = tbl(vec![col("c", ColumnType::Integer, true)]);
        let source = tbl(vec![col("c", ColumnType::BigInt, true)]);
        let ops = diff_one(&target, &source);
        assert_eq!(ops.len(), 1);
        assert!(matches!(ops[0].op, TableOp::AlterColumnType { .. }));
        assert_eq!(ops[0].destructiveness, Destructiveness::Safe);
    }

    #[test]
    fn smallint_to_bigint_is_widening_safe() {
        let target = tbl(vec![col("c", ColumnType::SmallInt, true)]);
        let source = tbl(vec![col("c", ColumnType::BigInt, true)]);
        let ops = diff_one(&target, &source);
        assert_eq!(ops[0].destructiveness, Destructiveness::Safe);
    }

    #[test]
    fn bigint_to_integer_is_data_loss() {
        let target = tbl(vec![col("c", ColumnType::BigInt, true)]);
        let source = tbl(vec![col("c", ColumnType::Integer, true)]);
        let ops = diff_one(&target, &source);
        assert!(ops[0].destructiveness.data_loss_risk());
    }

    #[test]
    fn varchar_widening_is_safe() {
        let target = tbl(vec![col("c", ColumnType::Varchar { len: Some(50) }, true)]);
        let source = tbl(vec![col("c", ColumnType::Varchar { len: Some(100) }, true)]);
        let ops = diff_one(&target, &source);
        assert_eq!(ops[0].destructiveness, Destructiveness::Safe);
    }

    #[test]
    fn varchar_to_unbounded_is_safe() {
        let target = tbl(vec![col("c", ColumnType::Varchar { len: Some(50) }, true)]);
        let source = tbl(vec![col("c", ColumnType::Varchar { len: None }, true)]);
        let ops = diff_one(&target, &source);
        assert_eq!(ops[0].destructiveness, Destructiveness::Safe);
    }

    #[test]
    fn varchar_to_text_is_safe() {
        let target = tbl(vec![col("c", ColumnType::Varchar { len: Some(50) }, true)]);
        let source = tbl(vec![col("c", ColumnType::Text, true)]);
        let ops = diff_one(&target, &source);
        assert_eq!(ops[0].destructiveness, Destructiveness::Safe);
    }

    #[test]
    fn varchar_narrowing_is_data_loss() {
        let target = tbl(vec![col("c", ColumnType::Varchar { len: Some(100) }, true)]);
        let source = tbl(vec![col("c", ColumnType::Varchar { len: Some(50) }, true)]);
        let ops = diff_one(&target, &source);
        assert!(ops[0].destructiveness.data_loss_risk());
    }

    #[test]
    fn cross_family_change_is_data_loss() {
        let target = tbl(vec![col("c", ColumnType::Text, true)]);
        let source = tbl(vec![col("c", ColumnType::Integer, true)]);
        let ops = diff_one(&target, &source);
        assert!(ops[0].destructiveness.data_loss_risk());
    }

    // ---- nullability ----

    #[test]
    fn drop_not_null_is_safe() {
        let target = tbl(vec![col("c", ColumnType::Text, false)]);
        let source = tbl(vec![col("c", ColumnType::Text, true)]);
        let ops = diff_one(&target, &source);
        assert_eq!(ops.len(), 1);
        match &ops[0].op {
            TableOp::SetColumnNullable { nullable, .. } => assert!(*nullable),
            other => panic!("got {other:?}"),
        }
        assert_eq!(ops[0].destructiveness, Destructiveness::Safe);
    }

    #[test]
    fn set_not_null_requires_approval() {
        let target = tbl(vec![col("c", ColumnType::Text, true)]);
        let source = tbl(vec![col("c", ColumnType::Text, false)]);
        let ops = diff_one(&target, &source);
        assert_eq!(ops.len(), 1);
        assert!(ops[0].destructiveness.requires_approval());
        assert!(!ops[0].destructiveness.data_loss_risk());
    }

    // ---- defaults ----

    #[test]
    fn set_default_is_safe() {
        let target = tbl(vec![col("c", ColumnType::Integer, true)]);
        let mut to = col("c", ColumnType::Integer, true);
        to.default = Some(DefaultExpr::Literal(LiteralValue::Integer(0)));
        let source = tbl(vec![to]);
        let ops = diff_one(&target, &source);
        assert_eq!(ops.len(), 1);
        assert!(matches!(ops[0].op, TableOp::SetColumnDefault { .. }));
        assert_eq!(ops[0].destructiveness, Destructiveness::Safe);
    }

    #[test]
    fn drop_default_is_safe() {
        let mut from = col("c", ColumnType::Integer, true);
        from.default = Some(DefaultExpr::Literal(LiteralValue::Integer(0)));
        let target = tbl(vec![from]);
        let source = tbl(vec![col("c", ColumnType::Integer, true)]);
        let ops = diff_one(&target, &source);
        assert_eq!(ops.len(), 1);
        match &ops[0].op {
            TableOp::SetColumnDefault { default, .. } => assert!(default.is_none()),
            other => panic!("got {other:?}"),
        }
    }

    // ---- identity / generated ----

    #[test]
    fn identity_change_requires_approval() {
        use crate::ir::column::{Identity, IdentityKind, SequenceOptions};
        let target = tbl(vec![col("c", ColumnType::BigInt, false)]);
        let mut to = col("c", ColumnType::BigInt, false);
        to.identity = Some(Identity {
            kind: IdentityKind::ByDefault,
            sequence: SequenceOptions {
                start: 1,
                increment: 1,
                min_value: None,
                max_value: None,
                cache: 1,
                cycle: false,
            },
        });
        let source = tbl(vec![to]);
        let ops = diff_one(&target, &source);
        assert_eq!(ops.len(), 1);
        assert!(ops[0].destructiveness.requires_approval());
    }

    // ---- comment ----

    #[test]
    fn column_comment_change_is_safe() {
        let target = tbl(vec![col("c", ColumnType::Integer, true)]);
        let mut to = col("c", ColumnType::Integer, true);
        to.comment = Some("the c column".into());
        let source = tbl(vec![to]);
        let ops = diff_one(&target, &source);
        assert_eq!(ops.len(), 1);
        assert!(matches!(ops[0].op, TableOp::SetColumnComment { .. }));
        assert_eq!(ops[0].destructiveness, Destructiveness::Safe);
    }

    // ---- equality / order ----

    #[test]
    fn equal_columns_emit_nothing() {
        let target = tbl(vec![col("id", ColumnType::BigInt, false)]);
        let source = tbl(vec![col("id", ColumnType::BigInt, false)]);
        let ops = diff_one(&target, &source);
        assert!(ops.is_empty());
    }

    #[test]
    fn column_reorder_is_ignored_in_v0_1() {
        let target = tbl(vec![
            col("a", ColumnType::Integer, true),
            col("b", ColumnType::Integer, true),
        ]);
        let source = tbl(vec![
            col("b", ColumnType::Integer, true),
            col("a", ColumnType::Integer, true),
        ]);
        let ops = diff_one(&target, &source);
        assert!(ops.is_empty(), "v0.1 ignores logical column order");
    }

    // ---- storage ----

    #[test]
    fn storage_change_emits_safe_op() {
        let mut from_col = col("doc", ColumnType::Text, true);
        from_col.storage = Some(StorageKind::Extended); // text default → canon would strip
        let mut to_col = col("doc", ColumnType::Text, true);
        to_col.storage = Some(StorageKind::External);
        let target = tbl(vec![from_col]);
        let source = tbl(vec![to_col]);
        let ops = diff_one(&target, &source);
        assert_eq!(ops.len(), 1);
        assert!(matches!(
            ops[0].op,
            TableOp::SetColumnStorage {
                from: StorageKind::Extended,
                to: StorageKind::External,
                ..
            }
        ));
        assert_eq!(ops[0].destructiveness, Destructiveness::Safe);
    }

    #[test]
    fn storage_none_vs_type_default_is_noop() {
        let from_col = col("doc", ColumnType::Text, true);
        let mut to_col = col("doc", ColumnType::Text, true);
        to_col.storage = Some(StorageKind::Extended); // text default
        let target = tbl(vec![from_col]);
        let source = tbl(vec![to_col]);
        let ops = diff_one(&target, &source);
        assert!(
            ops.is_empty(),
            "None and Some(type_default) must collapse to the same effective storage"
        );
    }

    // ---- compression ----

    #[test]
    fn compression_change_emits_safe_op() {
        let mut from_col = col("blob", ColumnType::Bytea, true);
        from_col.compression = Some(Compression::Pglz);
        let mut to_col = col("blob", ColumnType::Bytea, true);
        to_col.compression = Some(Compression::Lz4);
        let target = tbl(vec![from_col]);
        let source = tbl(vec![to_col]);
        let ops = diff_one(&target, &source);
        assert_eq!(ops.len(), 1);
        assert!(matches!(
            ops[0].op,
            TableOp::SetColumnCompression {
                compression: Some(Compression::Lz4),
                ..
            }
        ));
        assert_eq!(ops[0].destructiveness, Destructiveness::Safe);
    }

    #[test]
    fn compression_to_cluster_default_emits_none() {
        let mut from_col = col("blob", ColumnType::Bytea, true);
        from_col.compression = Some(Compression::Lz4);
        let to_col = col("blob", ColumnType::Bytea, true);
        let target = tbl(vec![from_col]);
        let source = tbl(vec![to_col]);
        let ops = diff_one(&target, &source);
        assert_eq!(ops.len(), 1);
        assert!(matches!(
            ops[0].op,
            TableOp::SetColumnCompression {
                compression: None,
                ..
            }
        ));
    }
}