r/PostgreSQL • u/dsecurity49 • Jun 24 '26
Tools I keep seeing migrations that work fine on staging but lock production. Built a CLI to catch them before deploy.
Had an incident a while back where a migration that ran fine on staging took prod down for like 20 minutes. Same exact SQL. Staging table had a few thousand rows, prod had 80 million. ALTER TABLE ... ADD COLUMN ... DEFAULT NOW() doesn't care that it's "just adding a column" if it has to rewrite 80M rows under an exclusive lock.
Got annoyed enough to build something for it. safe-migrate is a CLI, it's basically two commands.
First you point it at your real db once:
This only reads pg_class/pg_attribute, nothing else, no app data. In CI you'd just do
env:
DATABASE_URL: ${{ secrets.DATABASE_URL }}
run: safe-migrate sync --out prod-stats.json
so the URL never shows up in logs or gets committed anywhere, it just produces a small json file with row counts and column widths that you check into the repo.
Then for every migration:
and it tells you if you're about to do something stupid based on the actual size of the table, not just the SQL text. Same ALTER TABLE statement is fine on a small table and a build-halting error on a huge one. It also knows things like "ADD COLUMN with a constant default is free on PG11+ but rewrites the table on 10 and earlier" so it doesn't cry wolf on stuff that's actually safe on your version.
Things it currently flags: VACUUM FULL, non-concurrent index creation, FK/CHECK constraints added without NOT VALID first, type changes that force a rewrite, CONCURRENTLY inside a transaction (which postgres just errors on anyway), DROP TABLE CASCADE when there's stuff depending on it, dynamic SQL in DO blocks that hides what's actually happening.
repo's at https://github.com/dsecurity49/safe-migrate, MIT/Apache. Still rough in places but it's caught real stuff for me.
3
u/Steveadoo Jun 24 '26
How does it compare to https://squawkhq.com?
2
u/Ecksters Jun 24 '26
Really too bad that they chose
NOW(), if they had gone with a non-volatile value since Postgres 11 columns with default values can be added without a full table rewrite. (Oh, I just finished reading and see you mentioned that)Very cool tool, nice job!
1
u/AutoModerator Jun 24 '26
Youtube Channel
Free Postgres Webinars and Workshops
Discord: People, Postgres, Data
Join us, we have cookies and nice people.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
2
u/[deleted] Jun 24 '26
[removed] — view removed comment