ppoppo_schema_constrained/lib.rs
1//! **NOT a stable public API.** Engine-tier binding primitive — published to
2//! crates.io only because the SDK closure requires it on the registry; 3rd
3//! parties never name this crate. They meet the value-sets it binds through an
4//! SDK product facade or a wire contract, never here.
5//!
6//! # Schema-Constrained Value-Sets (the enum ↔ `CHECK` anchor)
7//!
8//! A *schema-constrained* enum is a domain value-set whose members are also
9//! enumerated by a PostgreSQL `CHECK (col IN (…))` constraint. The enum and the
10//! constraint are two reifications of one fact ("the legal values of this
11//! column"); left unbound they drift independently — a migration widens the
12//! `CHECK`, or a variant is added, and the other side silently goes stale.
13//!
14//! This crate is the single seam that binds them. The same drift class exists
15//! on both sides of the monorepo (PAS `scaccounts`, PCS `scchat`) and neither
16//! core may depend on the other, so the binding primitive is hoisted out of
17//! both — a pure, dependency-free trait + macro (`std::BTreeSet` only), which
18//! both cores (that ban IO/transport crates) can depend on.
19//!
20//! ## Why engine tier and not `crates/shared/`
21//!
22//! It sat in `crates/shared/` (`publish = false`) until `RFC_202607252223`
23//! T-03, which is when the placement was first *tested* rather than assumed:
24//! `ppoppo-identity` needs to enroll its own `EntityType`, and `engine →
25//! shared` is forbidden by the crate lattice (`xtask::policy::rules::taxonomy`)
26//! — so the enrollment was unreachable, and the vocabulary had to keep a
27//! second PAS-local enum alive just to carry it.
28//!
29//! The fix was to notice that the folder was wrong, not the lattice. Engine
30//! tier means *published substrate that no 3rd party names* — a dependency-free
31//! trait + macro consumed by two service cores and one vocabulary crate is
32//! exactly that. The move corrected a misfile that predates the tier; it did
33//! not trade a principle for convenience.
34//!
35//! ## The anchor triple (per `STS_SSOT_GOVERNANCE`)
36//!
37//! - **Owner**: the domain enum in `accounts-core` / `accounts-api` /
38//! `chat-core` (the closest reified form of the value-set decision).
39//! - **Anchor**: domain-specific — these are tuned domain vocabularies with no
40//! external standard, so *this crate doc-comment is the anchor of record*
41//! (governance §4). (Formerly PAS
42//! `ADR_202605242324_schema-constrained-value-sets.md`, folded into
43//! `accounts-core` on its retirement, then hoisted here when PCS adopted the
44//! same gate.)
45//! - **Verification**: [`bindings`](SchemaConstrained::bindings) feeds each
46//! service's `schema_check_drift.rs` DB test
47//! (`accounts-api/tests/` for `scaccounts`, `chat-api/tests/` for `scchat`),
48//! which reads each `CHECK` from the *materialized* schema
49//! (`pg_get_constraintdef`) and asserts set-equality with `ALL`. The
50//! compile-time half lives in the [`impl_schema_constrained!`] macro: it
51//! emits an exhaustive `match`, so adding a variant without listing it fails
52//! to build.
53//!
54//! ## Why a DB test and not a file parse
55//!
56//! The value-sets evolve through `ALTER … DROP/ADD CONSTRAINT` migrations (e.g.
57//! `lifecycle_state` gained `tombstoned`; `oauth_audit_events.event_type`
58//! gained `otp_issue`/`otp_verify`). The authoritative set is therefore the
59//! *result of applying every migration*, which only the database knows —
60//! parsing the baseline `.sql` would report phantom drift. Asking Postgres via
61//! `pg_get_constraintdef` is the only correct anchor (and avoids the brittle
62//! bespoke-parser ops-tax rejected in `STS_RATE_LIMITS_PPOPPO` §Anchor
63//! "Rationale" option A).
64//!
65//! ## Two more rejected alternatives
66//!
67//! - **`#[sqlx::Type]` alone.** Binds the column *type* (text), not the
68//! `CHECK`'s value-set — a typo in the enum still compiles and the set still
69//! drifts. Complementary at the query boundary, not a substitute for the
70//! verification.
71//! - **Accept drift under human review.** Leaves security-adjacent value-sets
72//! (audit taxonomy, lifecycle, step-up purpose) under governance §2's
73//! "aspiration, not enforcement" gate. Rejected.
74//!
75//! ## Caveat — the value-equality half is integration-tier
76//!
77//! The compile-time exhaustiveness guard covers the Rust side on every build.
78//! The `ALL`-vs-`CHECK` set-equality half needs a live database, and there is
79//! no CI job running DB-backed tests — so it bites via each service's
80//! `just test-integration` and the `/deploy-ppoppo` pre-flight, not on a plain
81//! `cargo test`.
82
83#![deny(rust_2018_idioms)]
84#![warn(missing_debug_implementations)]
85
86use std::collections::BTreeSet;
87
88/// One `(constraint, allowed-value-set)` pair, erased of the originating enum
89/// type so the drift test can iterate heterogeneous value-sets.
90#[derive(Debug, Clone)]
91pub struct SchemaBinding {
92 /// The `pg_constraint.conname` (e.g. `"ck_ppnums_entity_type_enum"`).
93 pub constraint: &'static str,
94 /// The DB-text values the owning enum permits — must equal the constraint's
95 /// `IN (…)` set in the materialized schema.
96 pub allowed: BTreeSet<&'static str>,
97}
98
99/// A domain value-set whose members are mirrored by one or more SQL `CHECK`
100/// constraints.
101///
102/// Implemented via [`impl_schema_constrained!`]; never hand-written, so the
103/// compile-time exhaustiveness guard is always emitted alongside.
104pub trait SchemaConstrained: Sized + 'static {
105 /// Every variant, in any order. The macro hand-lists these (no `strum`);
106 /// the exhaustiveness guard makes an omission a build error and the DB test
107 /// makes a stale list a pre-flight failure.
108 const ALL: &'static [Self];
109
110 /// The `CHECK` constraint(s) whose `IN (…)` set must equal
111 /// `{ ALL.map(db_value) }`. More than one when several columns share the
112 /// value-set (e.g. `lifecycle_state` on three columns).
113 const CHECK_CONSTRAINTS: &'static [&'static str];
114
115 /// The DB-text form of a variant — the literal stored in the column and
116 /// named in the `CHECK`. Delegates to the enum's inherent `as_str` /
117 /// `as_wire`.
118 fn db_value(&self) -> &'static str;
119
120 /// Erased `(constraint, allowed)` pairs for the drift test — one per entry
121 /// in [`CHECK_CONSTRAINTS`](Self::CHECK_CONSTRAINTS).
122 fn bindings() -> Vec<SchemaBinding> {
123 let allowed: BTreeSet<&'static str> = Self::ALL.iter().map(Self::db_value).collect();
124 Self::CHECK_CONSTRAINTS
125 .iter()
126 .map(|&constraint| SchemaBinding {
127 constraint,
128 allowed: allowed.clone(),
129 })
130 .collect()
131 }
132}
133
134/// Implement [`SchemaConstrained`] for a unit-variant enum and emit a
135/// compile-time exhaustiveness guard from the same variant list.
136///
137/// ```ignore
138/// ppoppo_schema_constrained::impl_schema_constrained!(EntityType via as_str {
139/// all: [Human, AiAgent, Enterprise, Programmable, Mask],
140/// constraints: ["ck_ppnums_entity_type_enum"],
141/// });
142/// ```
143///
144/// `via $method` is the enum's inherent value accessor (`as_str` for most,
145/// `as_db_str` / `as_wire` for others). Place the invocation next to the enum
146/// so the constraint name lives *on the fact* (governance §6 carrier).
147///
148/// `non_stored` lists render-only variants that exist in the enum but are never
149/// persisted (and so never appear in the `CHECK`) — e.g. `EntityType::Delegated`.
150/// They are excluded from `ALL` yet still covered by the exhaustiveness guard,
151/// so the asymmetry is declared, not hidden.
152#[macro_export]
153macro_rules! impl_schema_constrained {
154 (
155 $ty:ident via $method:ident {
156 all: [ $( $variant:ident ),+ $(,)? ],
157 $( non_stored: [ $( $ns:ident ),+ $(,)? ], )?
158 constraints: [ $( $constraint:literal ),+ $(,)? ] $(,)?
159 }
160 ) => {
161 impl $crate::SchemaConstrained for $ty {
162 const ALL: &'static [Self] = &[ $( $ty::$variant ),+ ];
163 const CHECK_CONSTRAINTS: &'static [&'static str] = &[ $( $constraint ),+ ];
164 fn db_value(&self) -> &'static str {
165 self.$method()
166 }
167 }
168
169 // Compile-time half: if a variant is added to the enum but listed in
170 // neither `all` nor `non_stored`, this match is non-exhaustive and the
171 // build fails — pointing the author at the enrollment.
172 const _: fn($ty) = |x| match x {
173 $( $ty::$variant => () ),+
174 $( , $( $ty::$ns => () ),+ )?
175 };
176 };
177}
178
179/// Finding value-set `CHECK` constraints in migration SQL.
180///
181/// The enrollment registries answer "which enums claim a constraint". This
182/// answers the opposite question — "which constraints exist" — so a service
183/// can assert that every value-set in its schema is either enrolled or
184/// explicitly declared unbound. Both organs need it, and a parser duplicated
185/// per organ is a parser that gets fixed in one of them.
186pub mod migration_scan {
187 use std::collections::BTreeSet;
188
189 /// Names every **single-column value-set** CHECK in one SQL text.
190 ///
191 /// Both spellings count, because both occur: `pg_dump` writes
192 /// `CHECK ((col = ANY (ARRAY['a'::text])))` and a hand-written migration
193 /// writes `CHECK (col IN ('a', 'b'))`. Postgres treats them as the same
194 /// constraint; so does this.
195 ///
196 /// Out of scope, and deliberately so — these are not value-sets and have no
197 /// enum to bind to: range checks, regex checks, `IS NULL` checks, and any
198 /// multi-clause CHECK such as `CHECK ((plan = 'enterprise') = (limit IS
199 /// NULL))`. They are excluded by *structure* (the expression must open on a
200 /// bare column followed immediately by the membership operator), not by a
201 /// blocklist that would need maintaining.
202 pub fn value_set_constraints_in(sql: &str) -> BTreeSet<String> {
203 let flat = flatten(sql);
204 value_set_events(&flat)
205 .into_iter()
206 .map(|(_, name)| name)
207 .collect()
208 }
209
210 /// Every `RENAME CONSTRAINT <old> TO <new>` in one SQL text, in text order.
211 ///
212 /// # Why a text scan of migrations needs this at all
213 ///
214 /// [`value_set_constraints_in`] sees a constraint at the name the migration
215 /// that *created* it used. A later migration is free to rename it, and the
216 /// text of the first file never changes — so a corpus scan without this
217 /// reports a constraint that no longer exists, and the guard demands an
218 /// enum bound to a name nothing will ever match while the enum correctly
219 /// names the new one. That is a false positive on every rename, and it
220 /// reads as a missing enrolment, which sends the reader to the wrong file.
221 ///
222 /// Lives here for the same reason the parser does: both organs need it, and
223 /// a resolver duplicated per organ is a resolver that gets fixed in one.
224 pub fn constraint_renames_in(sql: &str) -> Vec<(String, String)> {
225 let flat = flatten(sql);
226 rename_events(&flat)
227 .into_iter()
228 .map(|(_, rename)| rename)
229 .collect()
230 }
231
232 /// Every value-set CHECK across an ordered migration corpus, **at its final
233 /// name** — the set the materialized schema actually holds.
234 ///
235 /// `sources` must be in chronological order — for this repo's stamped
236 /// filenames that is lexicographic order — and the order is load-bearing:
237 /// this is a **fold over statements**, applied exactly as Postgres applies
238 /// them. An `ADD CONSTRAINT` inserts a name; a `RENAME CONSTRAINT` moves a
239 /// name that exists *at that moment* and is a no-op on one that does not.
240 /// Nothing is resolved after the fact, so a rename never reaches back to a
241 /// constraint that had not been created yet, and never reaches forward to
242 /// one created later under the retired name.
243 ///
244 /// The earlier shape — collect every rename from the whole corpus, then
245 /// resolve every constraint name through all of them — violated exactly
246 /// that (`RFC_202609080357` T-19): a CHECK re-created under a name a
247 /// previous migration had renamed away was resolved through that old
248 /// rename and dropped out of the demanded set, so an unenrolled enum
249 /// escaped `schema_check_coverage`. The fold also makes a rename cycle
250 /// harmless by construction — each statement applies once, and the result
251 /// is whatever name the cycle leaves the constraint on, which is what the
252 /// database ends with too.
253 ///
254 /// This composition lives here rather than in each service's guard on
255 /// purpose: two organs that each assemble "scan, then resolve" for
256 /// themselves are two places for the second half to be forgotten, which is
257 /// exactly how PCS's guard shipped without it.
258 pub fn value_set_constraints_across<'a>(
259 sources: impl IntoIterator<Item = &'a str>,
260 ) -> BTreeSet<String> {
261 let mut live = BTreeSet::new();
262 for sql in sources {
263 let flat = flatten(sql);
264 for event in events_in(&flat) {
265 match event {
266 Event::Add(name) => {
267 live.insert(name);
268 }
269 Event::Rename(from, to) => {
270 if live.remove(&from) {
271 live.insert(to);
272 }
273 }
274 }
275 }
276 }
277 live
278 }
279
280 /// One statement the fold cares about, in the order it appears.
281 enum Event {
282 Add(String),
283 Rename(String, String),
284 }
285
286 /// The value-set adds and the constraint renames of one flattened text,
287 /// merged by text position — the only order in which they mean anything.
288 fn events_in(flat: &str) -> Vec<Event> {
289 let mut events: Vec<(usize, Event)> = value_set_events(flat)
290 .into_iter()
291 .map(|(at, name)| (at, Event::Add(name)))
292 .chain(
293 rename_events(flat)
294 .into_iter()
295 .map(|(at, (from, to))| (at, Event::Rename(from, to))),
296 )
297 .collect();
298 events.sort_by_key(|(at, _)| *at);
299 events.into_iter().map(|(_, event)| event).collect()
300 }
301
302 /// `(position, constraint name)` for every single-column value-set CHECK
303 /// in a flattened text.
304 fn value_set_events(flat: &str) -> Vec<(usize, String)> {
305 let mut found = Vec::new();
306 for (at, _) in flat.match_indices("CONSTRAINT ") {
307 let rest = &flat[at + "CONSTRAINT ".len()..];
308 let Some((name, tail)) = rest.split_once(' ') else {
309 continue;
310 };
311 let Some(body) = tail.strip_prefix("CHECK ") else {
312 continue;
313 };
314 let Some(body) = balanced(body) else {
315 continue;
316 };
317 if is_pure_value_set(body) {
318 found.push((at, name.to_string()));
319 }
320 }
321 found
322 }
323
324 /// `(position, (old, new))` for every `RENAME CONSTRAINT` in a flattened
325 /// text.
326 fn rename_events(flat: &str) -> Vec<(usize, (String, String))> {
327 let mut renames = Vec::new();
328 for (at, _) in flat.match_indices("RENAME CONSTRAINT ") {
329 let rest = &flat[at + "RENAME CONSTRAINT ".len()..];
330 let mut parts = rest.split_whitespace();
331 let (Some(from), Some(to_kw), Some(to)) = (parts.next(), parts.next(), parts.next())
332 else {
333 continue;
334 };
335 if !to_kw.eq_ignore_ascii_case("TO") {
336 continue;
337 }
338 renames.push((
339 at,
340 (
341 from.trim_end_matches(';').to_string(),
342 to.trim_end_matches(';').to_string(),
343 ),
344 ));
345 }
346 renames
347 }
348
349 /// Drops `--` comments and collapses runs of whitespace, so `find` can
350 /// match across the line breaks migrations put between a constraint name
351 /// and its clause — and cannot match a statement the author commented out.
352 ///
353 /// Comments are stripped **per line, before the lines are joined**: a
354 /// `--` runs to the end of its own line and no further, and stripping
355 /// after the join would delete the whole remainder of the file past the
356 /// first comment. A `--` inside a single-quoted literal is text, not a
357 /// comment, and is kept.
358 fn flatten(sql: &str) -> String {
359 let mut out = String::with_capacity(sql.len());
360 let mut in_space = false;
361 for line in sql.lines() {
362 for ch in strip_line_comment(line)
363 .chars()
364 .chain(std::iter::once('\n'))
365 {
366 if ch.is_whitespace() {
367 if !in_space {
368 out.push(' ');
369 }
370 in_space = true;
371 } else {
372 out.push(ch);
373 in_space = false;
374 }
375 }
376 }
377 out
378 }
379
380 /// The part of one line before its `--` comment, if any, ignoring a `--`
381 /// that sits inside a single-quoted literal.
382 fn strip_line_comment(line: &str) -> &str {
383 let mut in_quote = false;
384 let mut prev_dash = false;
385 for (i, ch) in line.char_indices() {
386 match ch {
387 '\'' => {
388 in_quote = !in_quote;
389 prev_dash = false;
390 }
391 '-' if !in_quote => {
392 if prev_dash {
393 return &line[..i - 1];
394 }
395 prev_dash = true;
396 }
397 _ => prev_dash = false,
398 }
399 }
400 line
401 }
402
403 /// The contents of the leading `(...)` group, without its outer parens.
404 fn balanced(s: &str) -> Option<&str> {
405 let s = s.strip_prefix('(')?;
406 let mut depth = 1usize;
407 for (i, ch) in s.char_indices() {
408 match ch {
409 '(' => depth += 1,
410 ')' => {
411 depth -= 1;
412 if depth == 0 {
413 return Some(&s[..i]);
414 }
415 }
416 _ => {}
417 }
418 }
419 None
420 }
421
422 /// Is this expression *nothing but* a membership test on one column?
423 ///
424 /// The "nothing but" is the whole difficulty. An earlier version stripped
425 /// leading parens and checked only that the expression *began* with
426 /// `col IN (` — which accepts
427 /// `((state = ANY (…)) AND (x IS NOT NULL)) OR (…)`, a compound predicate
428 /// whose first clause happens to be a membership test. PAS has exactly one
429 /// of those (`ck_signup_sessions_reservation_pair`) and it was misreported
430 /// as an unbound value-set, i.e. the guard demanded an enum for a
431 /// constraint that can never have one.
432 ///
433 /// So the test is structural on both ends: unwrap redundant parens, then
434 /// require the membership group to consume the entire remainder.
435 fn is_pure_value_set(expr: &str) -> bool {
436 let mut expr = expr.trim();
437 // Unwrap only parens that wrap the *whole* expression.
438 while let Some(inner) = balanced(expr) {
439 if inner.len() + 2 == expr.len() {
440 expr = inner.trim();
441 } else {
442 break;
443 }
444 }
445
446 // The column is either bare (`kind`) or parenthesised, which is how
447 // `pg_dump` writes a cast of a varchar column: `(kind)::text`.
448 let mut after = if expr.starts_with('(') {
449 match balanced(expr) {
450 Some(inner)
451 if !inner.is_empty()
452 && inner.chars().all(|c| c.is_alphanumeric() || c == '_') =>
453 {
454 expr[inner.len() + 2..].trim_start()
455 }
456 _ => return false,
457 }
458 } else {
459 let column_len = expr
460 .find(|c: char| !(c.is_alphanumeric() || c == '_'))
461 .unwrap_or(expr.len());
462 if column_len == 0 {
463 return false;
464 }
465 expr[column_len..].trim_start()
466 };
467 loop {
468 if let Some(r) = after.strip_prefix(')') {
469 after = r.trim_start();
470 continue;
471 }
472 if let Some(r) = after.strip_prefix("::") {
473 after = r
474 .trim_start_matches(|ch: char| ch.is_alphanumeric() || ch == '_')
475 .trim_start();
476 continue;
477 }
478 break;
479 }
480
481 let list = if let Some(r) = after.strip_prefix("IN ") {
482 r.trim_start()
483 } else if let Some(r) = after.strip_prefix("= ANY ") {
484 r.trim_start()
485 } else {
486 return false;
487 };
488 // The membership group must be the last thing in the expression — no
489 // trailing ` AND …`, no ` OR …`.
490 match balanced(list) {
491 Some(inner) => list.len() == inner.len() + 2,
492 None => false,
493 }
494 }
495
496 #[cfg(test)]
497 #[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
498 mod tests {
499 use super::{constraint_renames_in, value_set_constraints_across};
500
501 // ─── rename resolution ────────────────────────────────────────────
502 //
503 // The rename half is half the guard, so it is tested like one: a fold
504 // that silently saw no renames would restore exactly the false
505 // positive it exists to remove, and would do it quietly.
506
507 #[test]
508 fn renames_parse_across_the_line_breaks_migrations_use() {
509 let sql = "ALTER TABLE scchat.t\n RENAME CONSTRAINT one_check\n TO two_check;";
510 assert_eq!(
511 constraint_renames_in(sql),
512 vec![("one_check".to_string(), "two_check".to_string())],
513 );
514 }
515
516 #[test]
517 fn a_rename_chain_lands_on_its_final_name() {
518 let corpus = value_set_constraints_across([
519 "ALTER TABLE t ADD CONSTRAINT a_check CHECK (kind IN ('a')); \
520 ALTER TABLE t ADD CONSTRAINT untouched_check CHECK (mode IN ('m'));",
521 "ALTER TABLE t RENAME CONSTRAINT a_check TO b_check;",
522 "ALTER TABLE t RENAME CONSTRAINT b_check TO c_check;",
523 ]);
524 assert!(corpus.contains("c_check"), "{corpus:?}");
525 assert!(
526 !corpus.contains("a_check") && !corpus.contains("b_check"),
527 "neither retired name is demanded: {corpus:?}"
528 );
529 assert!(
530 corpus.contains("untouched_check"),
531 "a constraint nobody renamed keeps its name: {corpus:?}"
532 );
533 }
534
535 #[test]
536 fn a_cyclic_rename_ends_where_the_database_ends() {
537 // A cycle is a migration bug, but it is one Postgres executes
538 // happily — each statement applies once — so the guard must
539 // terminate AND report the name the schema is actually left with.
540 let corpus = value_set_constraints_across([
541 "ALTER TABLE t ADD CONSTRAINT a_check CHECK (kind IN ('a')); \
542 ALTER TABLE t RENAME CONSTRAINT a_check TO b_check; \
543 ALTER TABLE t RENAME CONSTRAINT b_check TO a_check;",
544 ]);
545 assert_eq!(
546 corpus.into_iter().collect::<Vec<_>>(),
547 vec!["a_check".to_string()]
548 );
549 }
550
551 #[test]
552 fn a_corpus_reports_the_check_at_its_final_name_only() {
553 // The whole point: the creating migration's text never changes, so
554 // without the second pass the guard demands an enum bound to a name
555 // that no longer exists — and that reads as a missing enrolment,
556 // which sends the reader to the wrong file entirely.
557 let created =
558 "ALTER TABLE scchat.t ADD CONSTRAINT old_check CHECK (kind IN ('a', 'b'));";
559 let renamed = "ALTER TABLE scchat.t RENAME CONSTRAINT old_check TO new_check;";
560
561 let one_file = value_set_constraints_across([created]);
562 assert!(
563 one_file.contains("old_check"),
564 "control: the scan finds it before any rename"
565 );
566
567 let corpus = value_set_constraints_across([created, renamed]);
568 assert!(
569 corpus.contains("new_check"),
570 "the final name is what the schema has"
571 );
572 assert!(
573 !corpus.contains("old_check"),
574 "the retired name must not be demanded"
575 );
576 }
577
578 #[test]
579 fn a_check_recreated_under_a_renamed_away_name_is_demanded_again() {
580 // RFC_202609080357 T-19. Three migrations: the first creates
581 // `a_check`, the second renames it to `b_check`, the third creates
582 // a NEW `a_check`. The schema ends with both. A scan that collects
583 // every rename first and only then resolves every name sends the
584 // third file's `a_check` through the second file's rename — so the
585 // new constraint vanishes from the demanded set, and an enum that
586 // forgot to enrol it is never asked to.
587 let first = "ALTER TABLE t ADD CONSTRAINT a_check CHECK (kind IN ('a'));";
588 let second = "ALTER TABLE t RENAME CONSTRAINT a_check TO b_check;";
589 let third = "ALTER TABLE t ADD CONSTRAINT a_check CHECK (mode IN ('x'));";
590
591 let corpus = value_set_constraints_across([first, second, third]);
592 assert!(
593 corpus.contains("b_check"),
594 "the renamed original: {corpus:?}"
595 );
596 assert!(
597 corpus.contains("a_check"),
598 "the re-created constraint must be demanded — a rename that \
599 happened before it existed does not apply to it: {corpus:?}"
600 );
601 }
602
603 #[test]
604 fn a_rename_applies_only_to_what_exists_when_it_runs_within_one_file() {
605 // Same rule inside a single file: statements apply in text order.
606 let sql = "ALTER TABLE t RENAME CONSTRAINT a_check TO b_check; \
607 ALTER TABLE t ADD CONSTRAINT a_check CHECK (kind IN ('a'));";
608 let corpus = value_set_constraints_across([sql]);
609 assert!(corpus.contains("a_check"), "{corpus:?}");
610 assert!(
611 !corpus.contains("b_check"),
612 "nothing named b_check was ever a value-set CHECK: {corpus:?}"
613 );
614 }
615
616 #[test]
617 fn a_rename_inside_a_comment_is_not_a_rename() {
618 // A well-formed statement that happens to be commented out — the
619 // shape a migration author leaves behind when they reconsider —
620 // must mint nothing. The comment-stripping happens before parsing,
621 // per line, so the statement after the comment is still seen.
622 let sql = "-- ALTER TABLE t RENAME CONSTRAINT real_check TO phantom_check;\n\
623 ALTER TABLE t ADD CONSTRAINT real_check CHECK (kind IN ('a'));";
624 assert!(
625 constraint_renames_in(sql).is_empty(),
626 "a commented-out rename was parsed: {:?}",
627 constraint_renames_in(sql)
628 );
629 let corpus = value_set_constraints_across([sql]);
630 assert_eq!(
631 corpus.into_iter().collect::<Vec<_>>(),
632 vec!["real_check".to_string()],
633 "the live statement after the comment is still parsed"
634 );
635 }
636
637 #[test]
638 fn a_commented_out_check_is_not_demanded() {
639 let sql = "-- ADD CONSTRAINT ck_dead CHECK (kind IN ('a'));\n\
640 ADD CONSTRAINT ck_live CHECK (kind IN ('a'));";
641 let found = super::value_set_constraints_in(sql);
642 assert!(!found.contains("ck_dead"), "{found:?}");
643 assert!(found.contains("ck_live"), "{found:?}");
644 }
645
646 #[test]
647 fn a_non_rename_use_of_the_word_is_not_read_as_one() {
648 // `RENAME TO` on a table is not `RENAME CONSTRAINT`, and prose that
649 // merely says the word is not a statement.
650 let renames = constraint_renames_in(
651 "-- we RENAME CONSTRAINT names when a table moves\n\
652 ALTER TABLE scchat.old_t RENAME TO new_t;",
653 );
654 assert!(
655 renames.iter().all(|(from, _)| from != "names"),
656 "a comment must not be parsed as a rename: {renames:?}"
657 );
658 }
659
660 /// The control for every guard built on this parser.
661 ///
662 /// Each input below is a shape a migration in this repo is or could be written
663 /// in. The old matcher found only the last one; the four before it are the
664 /// ones a PR would actually add, and every one of them was invisible.
665 #[test]
666 fn the_parser_sees_the_shapes_a_migration_is_actually_written_in() {
667 let must_find = [
668 (
669 "hand-written ALTER, name and CHECK on separate lines, IN spelling",
670 "ALTER TABLE scchat.t\n ADD CONSTRAINT ck_target\n CHECK (kind IN ('a', 'b'));",
671 ),
672 (
673 "hand-written ALTER, separate lines, pg_dump spelling",
674 "ALTER TABLE scchat.t\n ADD CONSTRAINT ck_target\n CHECK ((kind = ANY (ARRAY['a'::text])));",
675 ),
676 (
677 "inline in CREATE TABLE, IN spelling",
678 "CREATE TABLE scchat.t (\n kind text,\n CONSTRAINT ck_target CHECK (kind IN ('a', 'b'))\n);",
679 ),
680 (
681 "cast between column and operator",
682 "ADD CONSTRAINT ck_target CHECK (((kind)::text = ANY (ARRAY['a'::text])));",
683 ),
684 (
685 "single-line pg_dump form (the only one the first matcher caught)",
686 "ADD CONSTRAINT ck_target CHECK ((kind = ANY (ARRAY['a'::text, 'b'::text])));",
687 ),
688 ];
689 for (label, sql) in must_find {
690 assert!(
691 super::value_set_constraints_in(sql).contains("ck_target"),
692 "parser missed a real value-set CHECK — {label}\n input: {sql}"
693 );
694 }
695
696 // The exclusions must stay exclusions, or the guard starts demanding an
697 // enum for constraints that can never have one.
698 let must_ignore = [
699 (
700 "multi-clause pairing check (this repo has one)",
701 "ADD CONSTRAINT ck_pairing CHECK ((plan = 'enterprise') = (monthly_message_limit IS NULL));",
702 ),
703 (
704 "range check",
705 "ADD CONSTRAINT ck_range CHECK ((retention_days > 0));",
706 ),
707 (
708 "regex check",
709 "ADD CONSTRAINT ck_regex CHECK ((ppnum ~ '^[0-9]{4}$'));",
710 ),
711 (
712 "membership nested inside a compound predicate is not a value-set",
713 "ADD CONSTRAINT ck_compound CHECK ((a IS NULL) OR (kind IN ('a', 'b')));",
714 ),
715 (
716 "membership as the FIRST clause of a compound predicate — PAS has\
717 exactly this shape in ck_signup_sessions_reservation_pair, and a\
718 parser that only checks the start of the expression accepts it",
719 "ADD CONSTRAINT ck_pair CHECK ((((state = ANY (ARRAY['a'::text])) AND\
720 (r IS NOT NULL)) OR ((state = 'b'::text) AND (r IS NULL))));",
721 ),
722 ];
723 for (label, sql) in must_ignore {
724 assert!(
725 super::value_set_constraints_in(sql).is_empty(),
726 "parser claimed a non-value-set CHECK — {label}\n input: {sql}"
727 );
728 }
729 }
730 }
731}