LLM Postgres Migrations: How to Validate Before Merge
In this article
To validate LLM-generated PostgreSQL migrations before merging, you must run them against a copy of your production schema in an isolated environment, verify both the forward and rollback paths, and check for destructive or locking operations using EXPLAIN and pg_dump comparisons. This process is non-negotiable because LLMs can produce syntactically valid SQL that still drops data, locks tables for hours, or breaks replication.
Why LLM-Generated Migrations Are Risky
LLMs generate SQL by predicting patterns from training data, not by understanding your specific database state. They have no awareness of your existing indexes, foreign key constraints, row counts, or the version of PostgreSQL you run. A migration that works on a toy database can fail catastrophically on a production table with 50 million rows. Common failure modes include:
- Missing WHERE clauses in UPDATE or DELETE statements, affecting every row.
- Adding a NOT NULL column without a DEFAULT, which fails on existing rows.
- Using ALTER TABLE ... TYPE that rewrites the entire table, locking it for the duration.
- Creating indexes without CONCURRENTLY, blocking writes on large tables.
- Dropping columns or tables that are still referenced by application code or views.
Pre-Merge Validation Checklist
Before you even open a pull request, run through this checklist in a staging environment that mirrors production as closely as possible:
- Restore a recent production backup into a separate database. This gives you real data volumes and distribution.
- Run the migration using the same migration tool you use in production (e.g., Flyway, Liquibase, Alembic, or plain psql).
- Verify the schema with
\d table_nameor queryinformation_schemato confirm columns, types, defaults, and constraints match expectations. - Test the rollback (down migration) if one exists. If the LLM didn't generate one, write it manually and test it.
- Run a smoke test of your application's core queries against the migrated database to catch broken assumptions.
- Check for locks by running the migration on a copy of production while monitoring
pg_locksandpg_stat_activity.
Automated Checks You Can Run in CI
Manual validation is necessary but not sufficient. Add automated checks to your CI pipeline to catch common issues before a human even looks at the migration:
- SQL linting with tools like
sqlflufforpgrollto catch syntax errors and style issues. - Schema diffing – after running the migration, compare the resulting schema against a known-good reference using
pg_dump --schema-onlyand a diff tool. - Lock analysis – use
pg_repackor a custom script to detect statements that acquire ACCESS EXCLUSIVE locks on large tables. - Data integrity checks – run queries to ensure row counts, foreign key integrity, and NOT NULL constraints are still valid.
- Replay the migration on a fresh database from an empty schema to ensure it's repeatable.
Common LLM Mistakes and How to Catch Them
LLMs often produce migrations that look plausible but have subtle flaws. Here are the most frequent ones and how to spot them:
- Non-idempotent statements – running the migration twice fails. Test by running it twice in a row; it should be a no-op the second time.
- Missing down migrations – the LLM only gives you the up migration. Always ask for the reverse, or write it yourself.
- Using
SERIALinstead ofIDENTITY– both work, but IDENTITY is the modern PostgreSQL standard. Not a bug, but a style issue. - Adding an index on a huge table without CONCURRENTLY – this locks writes. Catch it with a regex that looks for
CREATE INDEXwithoutCONCURRENTLY. - Changing a column type that requires a table rewrite – e.g.,
VARCHARtoTEXTis fine, butTEXTtoINTEGERwill fail if there's non-numeric data. Test with real data.
Tools That Help Validate Migrations
Several tools can automate part of the validation process. Use them in combination with manual review:
- pgTAP – write unit tests for your database schema and data. You can assert that a column exists, a constraint is present, or a trigger fires correctly.
- Flyway or Liquibase – these tools track applied migrations and can validate checksums, ensuring the migration file hasn't changed after being applied.
- pg_dump and diff – the classic approach: dump the schema before and after, then diff. This catches unintended changes.
- pg_verify_checksums – not for migrations, but for data integrity after a migration that rewrites files.
- Custom scripts – write a script that parses the migration SQL and flags dangerous patterns (e.g.,
DROP TABLEwithout a backup,TRUNCATE, orALTER TABLE ... SET NOT NULLwithout a DEFAULT).
How to Test Rollbacks Effectively
Rollbacks are often an afterthought, but they're critical. If a migration fails halfway, you need to get back to a working state. Test the rollback by:
- Applying the up migration to a copy of production.
- Inserting some test data that uses the new schema.
- Running the down migration.
- Verifying that the schema and data are exactly as they were before the up migration (use a diff of
pg_dumpoutput).
If the LLM didn't generate a down migration, write one manually. It's often easier to write the down migration first, then the up migration, because you know what you need to revert.
Performance and Locking Considerations
Even if a migration is correct, it can still cause downtime. PostgreSQL locks tables during DDL operations. For large tables, an ALTER TABLE that rewrites the table can lock it for minutes or hours. To validate performance:
- Run the migration on a staging copy that has similar row counts to production.
- Use
EXPLAIN ANALYZEon the migration's queries to estimate execution time. - Check for
ACCESS EXCLUSIVElocks inpg_lockswhile the migration runs. - Consider using
pg_repackor online schema change tools if the migration rewrites a large table.
Frequently Asked Questions
Can I trust an LLM-generated migration if it passes a syntax check?
No. Syntax validity only means the SQL is parseable. It says nothing about whether the migration matches your schema, preserves data, or avoids locking. Always test against a real copy of your data.
How do I know if a migration is safe to run on a large table?
Check the execution plan and lock behavior. If the migration involves ALTER TABLE ... TYPE, ADD COLUMN with a volatile DEFAULT, or CREATE INDEX without CONCURRENTLY, it will likely lock the table. Test on a staging copy with similar row counts and monitor pg_locks.
What if the LLM gives me a migration that drops a column I need?
Review the migration manually. LLMs don't know your application's dependencies. Use pg_dump to capture the schema before running, and after running, diff to see what changed. If a column is dropped, you can restore from backup.
Should I always write a down migration?
Yes, for any migration that changes the schema in a non-additive way (e.g., dropping a column, changing a type, or adding a NOT NULL constraint). Without a down migration, you can't roll back without restoring a backup, which may lose recent data.
Can I use a temporary database for validation?
Yes, but it must be a copy of production, not a small toy schema. A temporary database with a few rows won't reveal locking issues or data conversion errors. Use pg_dump and pg_restore to create a realistic copy.