safe-migrate 0.8.0

Check PostgreSQL migrations against a synchronized database baseline
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
use crate::_internal::report::violations::ViolationTier;
use crate::_internal::rules::Rule;
use crate::_internal::rules::conflict::ConflictRule;
use crate::_internal::rules::constraints::BlockingConstraintRule;
use crate::_internal::rules::destructive::{
    CascadingDropRule, CreateTableAsSelectRule, DropDatabaseRule, DropSchemaCascadeRule,
    GeneralCascadeRule, ReversibilityRule, SizeAwareAddColumnRule, TypeChangeRewriteRule,
};
use crate::_internal::rules::drift::DriftDetectionRule;
use crate::_internal::rules::expressions::VolatileDefaultRule;
use crate::_internal::rules::functions::{BrokenComputeRule, FunctionVolatilityRule};
use crate::_internal::rules::idempotency::IdempotencyRule;
use crate::_internal::rules::indexes::ConcurrentIndexRule;
use crate::_internal::rules::opaque::OpaqueDynamicSqlRule;
use crate::_internal::rules::partitions::{PartitionLockRule, PartitionStrategyMismatchRule};
use crate::_internal::rules::policies::RestrictivePolicyRule;
use crate::_internal::rules::security::OverbroadGrantRule;
use crate::_internal::rules::timeouts::{RequireLockTimeoutRule, RequireStatementTimeoutRule};
use crate::_internal::rules::transactions::{
    AlterTypeAddValueRule, ConcurrentInsideTransactionRule, VacuumFullRule,
};
use crate::_internal::rules::triggers::DisableTriggerRule;
use crate::_internal::rules::views::MaterializedViewRefreshRule;

/// Stable user-facing metadata and construction for one primary rule.
///
/// Keep this registry in evaluation order. Discovery, configuration validation,
/// documentation checks, and engine construction all read it. Auxiliary
/// findings emitted by a primary rule are not entries.
pub struct RuleDescriptor {
    pub id: &'static str,
    pub title: &'static str,
    pub summary: &'static str,
    pub impact: &'static str,
    pub supported_configuration_fields: &'static [RuleConfigurationField],
    factory: fn() -> Box<dyn Rule>,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RuleConfigurationField {
    Disabled,
    Tier1ThresholdRows,
    Tier2ThresholdRows,
}

impl RuleConfigurationField {
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Disabled => "disabled",
            Self::Tier1ThresholdRows => "tier1_threshold_rows",
            Self::Tier2ThresholdRows => "tier2_threshold_rows",
        }
    }
}

const DISABLED_ONLY: &[RuleConfigurationField] = &[RuleConfigurationField::Disabled];
const WITH_TIER1_THRESHOLD: &[RuleConfigurationField] = &[
    RuleConfigurationField::Disabled,
    RuleConfigurationField::Tier1ThresholdRows,
];
const WITH_ROW_THRESHOLDS: &[RuleConfigurationField] = &[
    RuleConfigurationField::Disabled,
    RuleConfigurationField::Tier1ThresholdRows,
    RuleConfigurationField::Tier2ThresholdRows,
];

impl RuleDescriptor {
    pub fn build(&self) -> Box<dyn Rule> {
        (self.factory)()
    }

    pub fn default_tier(&self) -> ViolationTier {
        self.build().default_tier()
    }

    pub fn recipe(&self) -> &'static str {
        self.build().recipe()
    }

    pub fn supports(&self, field: RuleConfigurationField) -> bool {
        self.supported_configuration_fields.contains(&field)
    }
}

macro_rules! descriptor {
    ($id:literal, $title:literal, $summary:literal, $impact:literal, $rule:expr) => {
        descriptor!($id, $title, $summary, $impact, $rule, DISABLED_ONLY)
    };
    ($id:literal, $title:literal, $summary:literal, $impact:literal, $rule:expr, $fields:expr) => {
        RuleDescriptor {
            id: $id,
            title: $title,
            summary: $summary,
            impact: $impact,
            supported_configuration_fields: $fields,
            factory: || Box::new($rule),
        }
    };
}

// Marker rules are currently zero-sized; their constructors are kept in this
// registry so future initialized rules can supply a dedicated factory.
pub static PRIMARY_RULES: &[RuleDescriptor] = &[
    descriptor!(
        "irreversible-migration",
        "Irreversible migration",
        "Flags destructive operations that cannot be reversed.",
        "data loss",
        ReversibilityRule,
        WITH_TIER1_THRESHOLD
    ),
    descriptor!(
        "drop-database",
        "Drop database",
        "Flags database deletion.",
        "data loss",
        DropDatabaseRule
    ),
    descriptor!(
        "drop-schema-cascade",
        "Drop schema with cascade",
        "Flags schema-wide cascading deletion.",
        "data loss",
        DropSchemaCascadeRule
    ),
    descriptor!(
        "destructive-general-cascade",
        "Destructive cascade",
        "Flags cascading non-table drops.",
        "data loss",
        GeneralCascadeRule
    ),
    descriptor!(
        "destructive-cascade",
        "Drop table with cascade",
        "Flags table drops that remove dependencies.",
        "data loss",
        CascadingDropRule
    ),
    descriptor!(
        "create-table-as-select",
        "Create table as select",
        "Flags potentially expensive CTAS operations.",
        "rewrite",
        CreateTableAsSelectRule
    ),
    descriptor!(
        "size-aware-add-column",
        "Add column on a large table",
        "Flags column additions that can rewrite large tables.",
        "rewrite",
        SizeAwareAddColumnRule,
        WITH_TIER1_THRESHOLD
    ),
    descriptor!(
        "type-change-rewrite",
        "Type change rewrite",
        "Flags column type changes that rewrite data.",
        "rewrite",
        TypeChangeRewriteRule,
        WITH_TIER1_THRESHOLD
    ),
    descriptor!(
        "blocking-constraint",
        "Blocking constraint",
        "Flags constraint changes that lock or scan tables.",
        "locking",
        BlockingConstraintRule,
        WITH_ROW_THRESHOLDS
    ),
    descriptor!(
        "require-concurrent-index",
        "Require concurrent index",
        "Flags index changes that should use CONCURRENTLY.",
        "locking",
        ConcurrentIndexRule,
        WITH_ROW_THRESHOLDS
    ),
    descriptor!(
        "require-lock-timeout",
        "Require lock timeout",
        "Flags potentially slow statements without an effective lock timeout.",
        "locking",
        RequireLockTimeoutRule
    ),
    descriptor!(
        "require-statement-timeout",
        "Require statement timeout",
        "Flags potentially slow statements without an effective statement timeout.",
        "operability",
        RequireStatementTimeoutRule
    ),
    descriptor!(
        "blocking-mat-view-refresh",
        "Blocking materialized-view refresh",
        "Flags refreshes that block readers.",
        "locking",
        MaterializedViewRefreshRule,
        WITH_ROW_THRESHOLDS
    ),
    descriptor!(
        "blocking-partition-mutation",
        "Blocking partition mutation",
        "Flags partition attach and detach locks.",
        "locking",
        PartitionLockRule,
        WITH_ROW_THRESHOLDS
    ),
    descriptor!(
        "partition-strategy-mismatch",
        "Partition strategy mismatch",
        "Flags incompatible partition attachment.",
        "correctness",
        PartitionStrategyMismatchRule
    ),
    descriptor!(
        "restrictive-policy",
        "Restrictive policy",
        "Flags policies that narrow row visibility.",
        "access control",
        RestrictivePolicyRule
    ),
    descriptor!(
        "disable-trigger",
        "Disable trigger",
        "Flags disabled triggers.",
        "correctness",
        DisableTriggerRule
    ),
    descriptor!(
        "broken-compute",
        "Broken compute dependency",
        "Flags function drops blocked by trigger dependencies.",
        "correctness",
        BrokenComputeRule
    ),
    descriptor!(
        "function-volatility-change",
        "Function volatility change",
        "Flags changed function volatility.",
        "query planning",
        FunctionVolatilityRule
    ),
    descriptor!(
        "missing-idempotency",
        "Missing idempotency",
        "Flags migrations unsafe to rerun.",
        "operability",
        IdempotencyRule
    ),
    descriptor!(
        "concurrent-in-transaction",
        "Concurrent index in transaction",
        "Flags CONCURRENTLY inside a transaction.",
        "correctness",
        ConcurrentInsideTransactionRule
    ),
    descriptor!(
        "alter-type-add-value-txn",
        "Enum value in transaction",
        "Flags enum additions whose new value is unavailable until commit.",
        "correctness",
        AlterTypeAddValueRule
    ),
    descriptor!(
        "vacuum-full",
        "Vacuum full",
        "Flags VACUUM FULL in migrations.",
        "locking",
        VacuumFullRule
    ),
    descriptor!(
        "opaque-dynamic-sql",
        "Opaque dynamic SQL",
        "Flags SQL whose schema effects cannot be modeled.",
        "confidence",
        OpaqueDynamicSqlRule
    ),
    descriptor!(
        "volatile-default",
        "Volatile default",
        "Flags volatile default expressions.",
        "correctness",
        VolatileDefaultRule
    ),
    descriptor!(
        "overbroad-grant",
        "Overbroad grant",
        "Flags broad public privileges.",
        "access control",
        OverbroadGrantRule
    ),
    descriptor!(
        "schema-drift",
        "Schema drift",
        "Flags references missing from the baseline.",
        "correctness",
        DriftDetectionRule
    ),
    descriptor!(
        "chain-conflict",
        "Migration chain conflict",
        "Flags statements that conflict with prior migration state.",
        "correctness",
        ConflictRule
    ),
];

pub fn primary_rule_ids() -> impl Iterator<Item = &'static str> {
    PRIMARY_RULES.iter().map(|rule| rule.id)
}

pub fn find_primary_rule(id: &str) -> Option<&'static RuleDescriptor> {
    PRIMARY_RULES.iter().find(|rule| rule.id == id)
}

pub fn validate_rule_configuration(
    config: &crate::_internal::engine::config::Config,
) -> Result<(), String> {
    if config.tier1_threshold_rows < config.tier2_threshold_rows {
        return Err(format!(
            "tier1_threshold_rows ({}) must be greater than or equal to tier2_threshold_rows ({})",
            config.tier1_threshold_rows, config.tier2_threshold_rows
        ));
    }

    let mut rule_ids: Vec<_> = config.rules.keys().map(String::as_str).collect();
    rule_ids.sort_unstable();
    for rule_id in rule_ids {
        let Some(descriptor) = find_primary_rule(rule_id) else {
            // Config::validate_rule_ids reports unknown IDs with the full list.
            continue;
        };
        let rule = &config.rules[rule_id];
        if rule.tier1_threshold_rows.is_some()
            && !descriptor.supports(RuleConfigurationField::Tier1ThresholdRows)
        {
            return Err(format!(
                "Rule '{rule_id}' does not support 'tier1_threshold_rows'"
            ));
        }
        if rule.tier2_threshold_rows.is_some()
            && !descriptor.supports(RuleConfigurationField::Tier2ThresholdRows)
        {
            return Err(format!(
                "Rule '{rule_id}' does not support 'tier2_threshold_rows'"
            ));
        }
        if descriptor.supports(RuleConfigurationField::Tier1ThresholdRows)
            && descriptor.supports(RuleConfigurationField::Tier2ThresholdRows)
        {
            let tier1 = config.rule_tier1_threshold(rule_id);
            let tier2 = config.rule_tier2_threshold(rule_id);
            if tier1 < tier2 {
                return Err(format!(
                    "Rule '{rule_id}' has tier1_threshold_rows ({tier1}) below tier2_threshold_rows ({tier2})"
                ));
            }
        }
    }
    Ok(())
}

pub fn build_primary_rules() -> Vec<Box<dyn Rule>> {
    PRIMARY_RULES.iter().map(RuleDescriptor::build).collect()
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashSet;

    #[test]
    fn descriptors_have_unique_ids_matching_the_rules_they_construct() {
        let ids: HashSet<_> = PRIMARY_RULES
            .iter()
            .map(|descriptor| descriptor.id)
            .collect();
        assert_eq!(ids.len(), PRIMARY_RULES.len());
        for descriptor in PRIMARY_RULES {
            let rule = descriptor.build();
            assert_eq!(rule.id(), descriptor.id);
            assert_eq!(descriptor.default_tier(), rule.default_tier());
            assert_eq!(descriptor.recipe(), rule.recipe());
        }
    }

    #[test]
    fn descriptors_advertise_only_configuration_the_rules_consume() {
        let tier1_only: HashSet<_> = [
            "irreversible-migration",
            "size-aware-add-column",
            "type-change-rewrite",
        ]
        .into_iter()
        .collect();
        let both_thresholds: HashSet<_> = [
            "blocking-constraint",
            "require-concurrent-index",
            "blocking-mat-view-refresh",
            "blocking-partition-mutation",
        ]
        .into_iter()
        .collect();

        for descriptor in PRIMARY_RULES {
            assert!(descriptor.supports(RuleConfigurationField::Disabled));
            assert_eq!(
                descriptor.supports(RuleConfigurationField::Tier1ThresholdRows),
                tier1_only.contains(descriptor.id) || both_thresholds.contains(descriptor.id),
                "unexpected Tier 1 threshold metadata for {}",
                descriptor.id
            );
            assert_eq!(
                descriptor.supports(RuleConfigurationField::Tier2ThresholdRows),
                both_thresholds.contains(descriptor.id),
                "unexpected Tier 2 threshold metadata for {}",
                descriptor.id
            );
        }
    }

    #[test]
    fn stateful_rules_declare_their_required_capabilities() {
        let expected: HashSet<_> = [
            "destructive-cascade",
            "size-aware-add-column",
            "type-change-rewrite",
            "blocking-constraint",
            "require-concurrent-index",
            "blocking-mat-view-refresh",
            "blocking-partition-mutation",
            "partition-strategy-mismatch",
            "function-volatility-change",
            "broken-compute",
            "concurrent-in-transaction",
            "alter-type-add-value-txn",
            "schema-drift",
        ]
        .into_iter()
        .collect();

        for descriptor in PRIMARY_RULES {
            let rule = descriptor.build();
            assert_eq!(
                !rule.required_capabilities().is_empty(),
                expected.contains(descriptor.id),
                "capability declaration mismatch for {}",
                descriptor.id
            );
        }
    }

    #[test]
    fn threshold_validation_requires_tier1_at_or_above_tier2() {
        let globally_reversed = crate::_internal::engine::config::Config {
            tier1_threshold_rows: 9,
            tier2_threshold_rows: 10,
            ..crate::_internal::engine::config::Config::default()
        };
        assert!(
            validate_rule_configuration(&globally_reversed)
                .unwrap_err()
                .contains("tier1_threshold_rows (9)")
        );

        let mut per_rule_reversed = crate::_internal::engine::config::Config::default();
        per_rule_reversed.rules.insert(
            "blocking-constraint".into(),
            crate::_internal::engine::config::RuleConfig {
                tier1_threshold_rows: Some(5),
                tier2_threshold_rows: Some(6),
                ..crate::_internal::engine::config::RuleConfig::default()
            },
        );
        assert!(
            validate_rule_configuration(&per_rule_reversed)
                .unwrap_err()
                .contains("Rule 'blocking-constraint'")
        );
    }

    #[test]
    fn unsupported_per_rule_thresholds_are_rejected() {
        let mut config = crate::_internal::engine::config::Config::default();
        config.rules.insert(
            "require-lock-timeout".to_string(),
            crate::_internal::engine::config::RuleConfig {
                tier1_threshold_rows: Some(1),
                ..crate::_internal::engine::config::RuleConfig::default()
            },
        );

        assert_eq!(
            validate_rule_configuration(&config).unwrap_err(),
            "Rule 'require-lock-timeout' does not support 'tier1_threshold_rows'"
        );
    }
}