|
| 1 | +//! PGM021 — `ADD UNIQUE` on existing table without `USING INDEX` |
| 2 | +//! |
| 3 | +//! Detects `ALTER TABLE ... ADD CONSTRAINT ... UNIQUE (columns)` on tables that |
| 4 | +//! already exist where the target columns don't already have a covering unique |
| 5 | +//! index. The safe pattern is to first create a unique index CONCURRENTLY, then |
| 6 | +//! add the constraint using that index. |
| 7 | +
|
| 8 | +use crate::parser::ir::{AlterTableAction, IrNode, Located, TableConstraint}; |
| 9 | +use crate::rules::{Finding, LintContext, Rule, Severity, alter_table_check}; |
| 10 | + |
| 11 | +/// Rule that flags adding a UNIQUE constraint to an existing table without a |
| 12 | +/// pre-existing unique index on the constraint columns. |
| 13 | +pub struct Pgm021; |
| 14 | + |
| 15 | +impl Rule for Pgm021 { |
| 16 | + fn id(&self) -> &'static str { |
| 17 | + "PGM021" |
| 18 | + } |
| 19 | + |
| 20 | + fn default_severity(&self) -> Severity { |
| 21 | + Severity::Critical |
| 22 | + } |
| 23 | + |
| 24 | + fn description(&self) -> &'static str { |
| 25 | + "ADD UNIQUE on existing table without USING INDEX" |
| 26 | + } |
| 27 | + |
| 28 | + fn explain(&self) -> &'static str { |
| 29 | + "PGM021 — ADD UNIQUE on existing table without USING INDEX\n\ |
| 30 | + \n\ |
| 31 | + What it detects:\n\ |
| 32 | + ALTER TABLE ... ADD CONSTRAINT ... UNIQUE (columns) where the table\n\ |
| 33 | + already exists and the target columns don't have a pre-existing unique\n\ |
| 34 | + index.\n\ |
| 35 | + \n\ |
| 36 | + Why it's dangerous:\n\ |
| 37 | + Adding a UNIQUE constraint inline builds a unique index under an ACCESS\n\ |
| 38 | + EXCLUSIVE lock, blocking all reads and writes for the duration. For\n\ |
| 39 | + large tables this can cause extended downtime. Unlike CHECK and FOREIGN\n\ |
| 40 | + KEY constraints, NOT VALID does NOT apply to UNIQUE constraints, so\n\ |
| 41 | + there is no NOT VALID escape hatch.\n\ |
| 42 | + \n\ |
| 43 | + Example (bad):\n\ |
| 44 | + ALTER TABLE orders ADD CONSTRAINT uq_email UNIQUE (email);\n\ |
| 45 | + \n\ |
| 46 | + Fix (safe pattern — build unique index concurrently first):\n\ |
| 47 | + CREATE UNIQUE INDEX CONCURRENTLY idx_orders_email ON orders (email);\n\ |
| 48 | + ALTER TABLE orders ADD CONSTRAINT uq_email UNIQUE USING INDEX idx_orders_email;" |
| 49 | + } |
| 50 | + |
| 51 | + fn check(&self, statements: &[Located<IrNode>], ctx: &LintContext<'_>) -> Vec<Finding> { |
| 52 | + alter_table_check::check_alter_actions(statements, ctx, |at, action, stmt, ctx| { |
| 53 | + let AlterTableAction::AddConstraint(TableConstraint::Unique { columns, .. }) = action |
| 54 | + else { |
| 55 | + return vec![]; |
| 56 | + }; |
| 57 | + |
| 58 | + let table_key = at.name.catalog_key(); |
| 59 | + let Some(table) = ctx.catalog_before.get_table(table_key) else { |
| 60 | + return vec![]; |
| 61 | + }; |
| 62 | + |
| 63 | + if table.has_unique_covering(columns) { |
| 64 | + return vec![]; |
| 65 | + } |
| 66 | + |
| 67 | + vec![self.make_finding( |
| 68 | + format!( |
| 69 | + "ADD UNIQUE on existing table '{table}' without a \ |
| 70 | + pre-existing unique index on column(s) [{columns}]. \ |
| 71 | + Create a unique index CONCURRENTLY first, then use \ |
| 72 | + ADD CONSTRAINT ... UNIQUE USING INDEX.", |
| 73 | + table = at.name.display_name(), |
| 74 | + columns = columns.join(", "), |
| 75 | + ), |
| 76 | + ctx.file, |
| 77 | + &stmt.span, |
| 78 | + )] |
| 79 | + }) |
| 80 | + } |
| 81 | +} |
| 82 | + |
| 83 | +#[cfg(test)] |
| 84 | +mod tests { |
| 85 | + use super::*; |
| 86 | + use crate::catalog::Catalog; |
| 87 | + use crate::catalog::builder::CatalogBuilder; |
| 88 | + use crate::parser::ir::*; |
| 89 | + use crate::rules::test_helpers::{located, make_ctx}; |
| 90 | + use std::collections::HashSet; |
| 91 | + use std::path::PathBuf; |
| 92 | + |
| 93 | + fn add_unique_stmt(table: &str, columns: &[&str]) -> Located<IrNode> { |
| 94 | + located(IrNode::AlterTable(AlterTable { |
| 95 | + name: QualifiedName::unqualified(table), |
| 96 | + actions: vec![AlterTableAction::AddConstraint(TableConstraint::Unique { |
| 97 | + name: Some(format!("uq_{}", columns.join("_"))), |
| 98 | + columns: columns.iter().map(|s| s.to_string()).collect(), |
| 99 | + })], |
| 100 | + })) |
| 101 | + } |
| 102 | + |
| 103 | + #[test] |
| 104 | + fn test_add_unique_no_existing_index_fires() { |
| 105 | + let before = CatalogBuilder::new() |
| 106 | + .table("orders", |t| { |
| 107 | + t.column("id", "bigint", false) |
| 108 | + .column("email", "text", false); |
| 109 | + }) |
| 110 | + .build(); |
| 111 | + let after = before.clone(); |
| 112 | + let file = PathBuf::from("migrations/002.sql"); |
| 113 | + let created = HashSet::new(); |
| 114 | + let ctx = make_ctx(&before, &after, &file, &created); |
| 115 | + |
| 116 | + let stmts = vec![add_unique_stmt("orders", &["email"])]; |
| 117 | + |
| 118 | + let findings = Pgm021.check(&stmts, &ctx); |
| 119 | + insta::assert_yaml_snapshot!(findings); |
| 120 | + } |
| 121 | + |
| 122 | + #[test] |
| 123 | + fn test_add_unique_with_existing_unique_index_no_finding() { |
| 124 | + let before = CatalogBuilder::new() |
| 125 | + .table("orders", |t| { |
| 126 | + t.column("id", "bigint", false) |
| 127 | + .column("email", "text", false) |
| 128 | + .index("idx_orders_email", &["email"], true); |
| 129 | + }) |
| 130 | + .build(); |
| 131 | + let after = before.clone(); |
| 132 | + let file = PathBuf::from("migrations/002.sql"); |
| 133 | + let created = HashSet::new(); |
| 134 | + let ctx = make_ctx(&before, &after, &file, &created); |
| 135 | + |
| 136 | + let stmts = vec![add_unique_stmt("orders", &["email"])]; |
| 137 | + |
| 138 | + let findings = Pgm021.check(&stmts, &ctx); |
| 139 | + assert!(findings.is_empty()); |
| 140 | + } |
| 141 | + |
| 142 | + #[test] |
| 143 | + fn test_add_unique_on_new_table_no_finding() { |
| 144 | + let before = Catalog::new(); |
| 145 | + let after = CatalogBuilder::new() |
| 146 | + .table("orders", |t| { |
| 147 | + t.column("id", "bigint", false) |
| 148 | + .column("email", "text", false); |
| 149 | + }) |
| 150 | + .build(); |
| 151 | + let file = PathBuf::from("migrations/001.sql"); |
| 152 | + let mut created = HashSet::new(); |
| 153 | + created.insert("orders".to_string()); |
| 154 | + let ctx = make_ctx(&before, &after, &file, &created); |
| 155 | + |
| 156 | + let stmts = vec![add_unique_stmt("orders", &["email"])]; |
| 157 | + |
| 158 | + let findings = Pgm021.check(&stmts, &ctx); |
| 159 | + assert!(findings.is_empty()); |
| 160 | + } |
| 161 | + |
| 162 | + #[test] |
| 163 | + fn test_table_not_in_catalog_no_finding() { |
| 164 | + let before = Catalog::new(); |
| 165 | + let after = before.clone(); |
| 166 | + let file = PathBuf::from("migrations/002.sql"); |
| 167 | + let created = HashSet::new(); |
| 168 | + let ctx = make_ctx(&before, &after, &file, &created); |
| 169 | + |
| 170 | + let stmts = vec![add_unique_stmt("nonexistent", &["email"])]; |
| 171 | + |
| 172 | + let findings = Pgm021.check(&stmts, &ctx); |
| 173 | + assert!(findings.is_empty()); |
| 174 | + } |
| 175 | + |
| 176 | + #[test] |
| 177 | + fn test_non_unique_index_still_fires() { |
| 178 | + let before = CatalogBuilder::new() |
| 179 | + .table("orders", |t| { |
| 180 | + t.column("id", "bigint", false) |
| 181 | + .column("email", "text", false) |
| 182 | + .index("idx_orders_email", &["email"], false); // NOT unique |
| 183 | + }) |
| 184 | + .build(); |
| 185 | + let after = before.clone(); |
| 186 | + let file = PathBuf::from("migrations/002.sql"); |
| 187 | + let created = HashSet::new(); |
| 188 | + let ctx = make_ctx(&before, &after, &file, &created); |
| 189 | + |
| 190 | + let stmts = vec![add_unique_stmt("orders", &["email"])]; |
| 191 | + |
| 192 | + let findings = Pgm021.check(&stmts, &ctx); |
| 193 | + insta::assert_yaml_snapshot!(findings); |
| 194 | + } |
| 195 | + |
| 196 | + #[test] |
| 197 | + fn test_add_unique_with_existing_unique_constraint_no_finding() { |
| 198 | + let before = CatalogBuilder::new() |
| 199 | + .table("orders", |t| { |
| 200 | + t.column("id", "bigint", false) |
| 201 | + .column("email", "text", false) |
| 202 | + .unique("uq_orders_email", &["email"]); |
| 203 | + }) |
| 204 | + .build(); |
| 205 | + let after = before.clone(); |
| 206 | + let file = PathBuf::from("migrations/002.sql"); |
| 207 | + let created = HashSet::new(); |
| 208 | + let ctx = make_ctx(&before, &after, &file, &created); |
| 209 | + |
| 210 | + let stmts = vec![add_unique_stmt("orders", &["email"])]; |
| 211 | + |
| 212 | + let findings = Pgm021.check(&stmts, &ctx); |
| 213 | + assert!(findings.is_empty()); |
| 214 | + } |
| 215 | +} |
0 commit comments