Look at these two PostgreSQL migrations. They create the exact same helper function and then drop the column it reads.
Migration A uses a traditional dollar-quoted body:
CREATE FUNCTION active_user_emails() RETURNS SETOF text LANGUAGE sql AS $$ SELECT email FROM users WHERE active = true; $$; ALTER TABLE users DROP COLUMN email; Migration B uses the SQL-standard BEGIN ATOMIC body introduced in PostgreSQL 14:
CREATE FUNCTION active_user_emails() RETURNS SETOF text LANGUAGE sql BEGIN ATOMIC SELECT email FROM users WHERE active = true; END; ALTER TABLE users DROP COLUMN email; If you run both migrations against a real PostgreSQL instance:
- Migration A succeeds without a single warning. Even though
check_function_bodiesisonby default and Postgres parsed the SQL inside$$when the function was created, it stores the body as a raw text literal inpg_proc.prosrcand records zero column dependency edges inpg_depend. Your migration passes, CI stays green, andactive_user_emails()only blows up in production the next time a query calls it. - Migration B fails immediately on statement 2 with
ERROR: cannot drop column email of table users because other objects depend on it. Because Postgres storesBEGIN ATOMICas a parsed query tree inpg_proc.prosqlbody, it writes hard dependency edges intopg_depend. And if someone gets clever and runsALTER TABLE users DROP COLUMN email CASCADE;, Postgres happily drops your function along with the column.
Back in July, I wrote an article here on Dev.to about why I built safe-migrate as an in-memory catalog state machine (Parse -> Fact -> Resolve -> Mutation -> Rules) rather than a regex SQL linter.
In the comments on that post, Mads Hansen suggested the one test strategy I had been putting off: spinning up real PostgreSQL containers across multiple major versions, feeding the exact same migration scripts to both the live database and the Rust simulator, and asserting that they agree on every outcome.
I finally built that differential harness across PostgreSQL 14, 15, 16, 17, and 18.
It immediately humbled me.
Why Unit-Testing an Emulator Lies to You
When you build a static analyzer that models an external system, unit tests have a blind spot: the same person who wrote the bug also wrote the assertion.
If I think ALTER TABLE IF EXISTS missing_table ADD COLUMN x int; silently skips validation on every sub-action, I write the simulator to do that, I write a unit test asserting that it returns SAFE, and cargo test prints green. My code matches my mental model. My mental model just happens to be wrong about what PostgreSQL actually does in edge cases.
To fix that, we wired up a differential verification suite (live_tests/) that runs against five real PostgreSQL servers (14 through 18). First, it seeds a baseline schema — tables, partitions, views, domains, composite types, sequences, extensions, casts, extended statistics, and overloaded routines — and runs safe-migrate sync against the live catalog to produce .safe-migrate.cache.
Then it executes 432 migration scenarios against both the live Postgres servers and the offline Rust state machine, checking:
- Does Postgres accept or reject the statement, and does
safe-migrateflag the exact conflict (schema-drift) or dangerous lock/rewrite? - After a chain of renames,
CASCADEdrops, or savepoint rollbacks, does the simulator's in-memory dependency graph matchpg_dependandpg_catalogon the real server?
When a migration tries to drop a column referenced by a SQL function or triggers a table rewrite on a large table, here is what safe-migrate lint actually prints in the terminal:
╭──────────────────────────────────────────────────────────────────────────────╮ │ safe-migrate lint │ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Verdict: HALT Confidence: Exact │ │ HALT: 2 WARN: 0 SAFE: 0 │ ╰──────────────────────────────────────────────────────────────────────────────╯ [HALT] Schema Conflict (schema-drift) object : table public.users reason : Cannot drop column "email" on "public.users" without CASCADE because function "public.active_user_emails()" depends on it. recipe : Update or drop dependent function "public.active_user_emails()" before dropping "public.users.email", or specify CASCADE if dropping dependent objects is intended. sql : ALTER TABLE users DROP COLUMN email; ──────────────────────────────────────────────────────────────── [HALT] Table Rewrite via Column Expression Change (type-change-rewrite) object : table public.orders reason : ALTER COLUMN "total_cents" SET EXPRESSION rewrites stored generated column values across all 12,400,000 rows under an ACCESS EXCLUSIVE lock. recipe : Add a new column, backfill in batches, and swap column names instead of rewriting the stored expression in place on a large table. sql : ALTER TABLE orders ALTER COLUMN total_cents SET EXPRESSION AS (subtotal_cents + tax_cents); ╭──────────────────────────────────────────────────────────────────────────────╮ │ SUMMARY │ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Verdict : HALT │ │ Recommendation : do not deploy │ │ HALT (Tier 1) : 2 │ │ WARN (Tier 2) : 0 │ │ SAFE (Tier 3) : 0 │ ╰──────────────────────────────────────────────────────────────────────────────╯ Getting to the point where all 432 differential scenarios stayed in lockstep across PG 14–18 exposed four classes of bugs in our Rust model.
Bug Class 1: Routine Body Dependencies and check_function_bodies Across Savepoints
At first, modeling CREATE FUNCTION looked simple: parse the signature, register the parameter types and return type in the catalog, and record dependency edges to those types.
Live PostgreSQL broke that assumption in three ways:
- Routine bodies have dependencies too. A
BEGIN ATOMICfunction (or a synced function whose dependencies appear inpg_depend) binds directly to the tables, columns, views, types, and other routines inside its body. If a migration renames a table or drops a column earlier in the file, any laterBEGIN ATOMICfunction referencing the old column fails immediately, and any existingBEGIN ATOMICfunction blocks a non-CASCADEdrop of that column. -
LANGUAGE sqlstring bodies depend oncheck_function_bodies. Whencheck_function_bodiesison(the default), Postgres parses and validates the SQL insideAS $$ ... $$at creation time — so referencing a column that was dropped three lines earlier in the same migration fails right away. -
SET check_function_bodies = offis transactional. Dump files and hand-written migrations frequently toggleSET check_function_bodies = off;orSET LOCAL check_function_bodies = off;so functions can be created before the tables they query.
Watch what happens when you combine SET with a savepoint rollback:
BEGIN; SAVEPOINT sp1; SET check_function_bodies = off; ROLLBACK TO SAVEPOINT sp1; -- Is check_function_bodies 'on' or 'off' right here? CREATE FUNCTION broken_fn() RETURNS int LANGUAGE sql AS $$ SELECT non_existent_column FROM users; $$; COMMIT; In PostgreSQL, SET inside a transaction is rolled back by ROLLBACK TO SAVEPOINT sp1, restoring check_function_bodies to on — which means CREATE FUNCTION broken_fn() fails.
In our simulator, catalog objects (tables, columns, constraints, dependency edges) lived on the transactional undo stack, while session settings like search_path and check_function_bodies lived on a separate struct that wasn't snapshotted per savepoint. When ROLLBACK TO SAVEPOINT sp1 ran, the catalog rewound, but check_function_bodies = off leaked out of the rolled-back savepoint and let broken SQL functions slip through as SAFE.
Bug Class 2: CREATE OR REPLACE FUNCTION Identity Is Weirder Than It Looks
Most Postgres developers know that CREATE OR REPLACE FUNCTION can replace a function's body, but cannot change its parameter types or return type without dropping the function first.
When we tested routine replacements against live PostgreSQL 14–18, we found several rules where naive signature comparison diverges from Postgres:
-
RETURNS TABLEandOUTparameters share the exact same return identity. If a function was originally created with:
CREATE FUNCTION get_pair(id int, OUT a int, OUT b text) RETURNS record ... and a migration runs:
CREATE OR REPLACE FUNCTION get_pair(id int) RETURNS TABLE(a int, b text) ... PostgreSQL considers the return type unchanged (record defined by two output columns int, text), because RETURNS TABLE is syntactic sugar for OUT parameters returning SETOF record (or record when not a set). Treating ReturnType::Record and ReturnType::Table(vec![...]) as distinct enum variants in Rust caused false-positive conflict errors.
- Renaming a parameter via
CREATE OR REPLACEis an explicit error. In Postgres, parameter names are not part of overload resolution, sofoo(user_id int)andfoo(account_id int)have the same call signature(int). Iffoo(user_id int)already exists,CREATE OR REPLACE FUNCTION foo(account_id int)does not create a second overload, and in modern Postgres it refuses to silently rename the argument — it aborts withERROR: cannot change name of input parameter "user_id". -
ALTER ROUTINEandDROP ROUTINEresolve across functions, procedures, and aggregates. You can runALTER ROUTINE my_agg(int) RENAME TO my_agg_v2;even thoughmy_aggwas created withCREATE AGGREGATE. If your lookup table separates functions, procedures, and aggregates into isolated namespaces without unified routine dispatch,ALTER ROUTINEmisses aggregates completely.
Bug Class 3: Multi-Action ALTER TABLE Atomicity and Replacing Full Catalog Clones
In PostgreSQL, a single ALTER TABLE statement can chain multiple sub-actions separated by commas:
ALTER TABLE accounts ADD COLUMN tier text DEFAULT 'free', ADD CONSTRAINT tier_non_empty CHECK (tier <> ''), DROP COLUMN legacy_flag, ALTER COLUMN missing_col SET NOT NULL; Notice what happens here:
- Sub-action 2 (
ADD CONSTRAINT ... CHECK (tier <> '')) referencestier, which was added by sub-action 1 inside the same SQL statement. So sub-actions must mutate the catalog incrementally as the statement executes. - Sub-action 4 (
ALTER COLUMN missing_col SET NOT NULL) fails becausemissing_coldoesn't exist. - Because every individual statement in Postgres is atomic (even in autocommit mode outside a
BEGIN ... COMMITblock), sub-action 4's failure must unwind sub-actions 1, 2, and 3, restoringlegacy_flagand removingtier.
Early versions of safe-migrate handled statement and savepoint rollback by cloning the catalog state before risky operations. Once the catalog model expanded to track domains, composite types, views, triggers, sequences, extensions, user-defined casts, extended statistics (CREATE STATISTICS), and routine body dependency graphs, cloning the world on every multi-action statement became a bottleneck.
In v0.11.0 through v0.14.0, we replaced full state clones with a typed undo journal paired with scoped dependency indexes. Every mutation returns an explicit three-way outcome:
pub enum MutationResult { Applied(UndoEntry), Skipped, Unresolved(EvidenceCode), } Splitting Skipped from Unresolved(EvidenceCode) solved an epistemic honesty bug we hit earlier:
-
Skippedmeans a statement was a provably benign no-op (for example,CREATE TABLE IF NOT EXISTS userswhenusersalready exists, orDROP INDEX IF EXISTSwhen the index is absent). -
Unresolved(EvidenceCode)means the statement ran into an unmodeled boundary (for example, dynamicDO $$ ... $$PL/pgSQL blocks, or an offline check that needs a live catalog snapshot when--cachewasn't provided).
When a migration contains an Unresolved check, safe-migrate refuses to print Verdict: SAFE. Even if violations == 0, an unevaluated safety check downgrades a green SAFE verdict to CAUTIOUS and groups the unevaluated rules by cause so CI never confuses "I couldn't check this" with "I proved this is safe."
And for rollback, each statement and SAVEPOINT simply records an index watermark into the Vec<UndoEntry> journal. If action #4 of a comma-separated ALTER TABLE fails, the simulator pops and applies the inverse UndoEntry items back to the statement watermark in microsecond time.
Bug Class 4: Evolving an Encrypted CI Cache Without Breaking Existing Pipelines
One of the best pieces of feedback we ever got from Reddit (r/rust and r/PostgreSQL) was about CI secret hygiene: an untrusted pull request job needs production table row counts and schema metadata to predict lock impact, but a PR workflow should never have DATABASE_URL for production.
That led to safe-migrate's two-step workflow:
- A scheduled or post-deploy job in a trusted environment runs
safe-migrate syncagainst the database and writes.safe-migrate.cache(containing only catalog metadata, row counts, and dependency edges — never user row data), optionally encrypted withSAFE_MIGRATE_CACHE_KEY. - Untrusted pull requests run
safe-migrate lint-chain --cache .safe-migrate.cachecompletely offline with zero database credentials.
In v0.14.0, we needed to store pg_cast entries and synced routine-body dependency edges in the cache file so offline PR jobs could catch cast conflicts and function-body dependency drops. Normally, changing a binary cache struct forces every user to invalidate and re-sync their cache immediately.
Instead, we structured the versioned cache envelope in Rust so V12_1 wraps the existing V12_0 DbCache alongside an extension payload:
pub enum VersionedCache { // ... V12_0(Box<DbCache>), V12_1(Box<DbCache>, CacheExtensionV12_1), } Older V12.0 caches generated by v0.13.0 still load cleanly into v0.14.0 (with cast and synced routine-body checks explicitly reported if those extension fields are absent), while newly synced V12.1 caches light up the full dependency graph without bloating the base DbCache layout.
Trying It on Your Own Migrations
If you want to test what your migrations actually do against your schema state (or poke at the PG 14–18 differential harness in live_tests/), the repository and prebuilt static binaries are on GitHub:
- GitHub Repository: github.com/dsecurity49/safe-migrate
- Crates.io:
cargo install safe-migrate(crates.io/crates/safe-migrate)
You can lint a migration file or a full directory chain offline in a few seconds:
# 1. In a trusted job (or against a staging/prod read replica), sync catalog metadata: export DATABASE_URL="postgres://readonly@db.example.com:5432/app" safe-migrate sync --output .safe-migrate.cache # 2. In CI / pull requests (no DATABASE_URL needed): safe-migrate lint-chain --dir migrations/ --cache .safe-migrate.cache For folks who have built static analyzers, query planners, or state machines in Rust: what was the weirdest discrepancy you found the first time you ran your model against the real system it was supposed to emulate?


