What to check when Claude Code writes a database migration: data loss, locks, deploy order, and the reset commands an agent can run.
Claude Code can write a database migration, and the file is only part of the risk. The rest is what the migration does to data and traffic the agent never saw, plus what the agent runs while it works. Make it show you the exact SQL and a step plan before anything executes, check both against production-sized data, and keep production credentials out of any session that touches migrations.
Disclosure: we build TLM Forge, a process layer for Claude Code, so weigh the product section accordingly. Most of this post is plain database practice that applies with or without us.
Two different failures need two different fixes
People describe two different events. In one, the agent ran a command that reset or emptied a database. In the other, it wrote a migration file that looked fine and misbehaved on real data. The first is a credentials and permissions problem, and the second is a review problem. A better prompt cannot block a reset command, and a deny rule does not catch a bad migration file.
The reports of the first kind are specific, and each is a single account. One user wrote that the agent ran alembic downgrade base and then alembic upgrade head as a "verification step", which dropped all 21 tables in the database. Another reported that in auto-accept mode the agent ran php artisan migrate:fresh as a routine step before tests, on a development database, repeatedly across two days. A third said prisma db push against a production database detected drift, offered a reset, and the agent accepted it. A Hacker News commenter wrote that asking Claude Code to run a database migration led it to delete their production database, and added: "It no longer gets prod credentials." None gives a rate, so read them as symptoms, not statistics. Two of those commands are documented parts of their tools' workflows: Alembic's tutorial shows alembic downgrade base, and the Laravel docs say migrate:fresh drops all tables and then runs the migrate command.
Sources: anthropics/claude-code issue 26913 (alembic downgrade base), anthropics/claude-code issue 69059 (migrate:fresh in auto-accept mode), anthropics/claude-code issue 33183 (prisma db push), Hacker News comment by victorbuilds, Alembic docs: Tutorial (Downgrading), Laravel docs: Migrations
Tool vendors have noticed. Prisma added a guard in version 6.15.0: its release notes say the CLI can recognize agents such as Claude Code and requests explicit confirmation before prisma migrate reset. The CLI reference describes the flow: the command is blocked, the agent is told to ask you, and after you consent it reruns the command with the PRISMA_USER_CONSENT_FOR_DANGEROUS_AI_ACTION environment variable set to the text of your consent. The guard lives in Prisma's CLI, so it does not touch the Alembic or Laravel cases above.
Sources: Prisma blog: ORM 6.15.0, AI Safety Guardrails for Destructive Commands, Prisma docs: CLI reference
First fix: keep production out of the session
Assume that anything the session can reach, it may eventually run a command against. The sandbox documentation says sandboxed commands inherit the environment Claude Code runs in, including any secrets in it, and that there is no built-in credential deny list. So this fix has little to do with prompts. Run migration work against a local or disposable database, keep the production connection string out of your shell, the project directory and the .env your tools load, and let your deploy pipeline apply production migrations with its own credentials.
Sources: Claude Code docs: Sandboxing
A rule in CLAUDE.md does not do this job. The permissions documentation says permission rules are enforced by Claude Code rather than by the model, and that instructions in your prompt or CLAUDE.md shape what Claude tries to do without changing what Claude Code allows. For the reset commands you already know about, add a second layer in .claude/settings.json: deny the resets, and ask before the commands you want to see first.
Sources: Claude Code docs: Configure permissions
{ "permissions": { "deny": ["Bash(prisma migrate reset *)", "Bash(npx prisma migrate reset *)", "Bash(php artisan migrate:fresh *)", "Bash(alembic downgrade *)", "Bash(.venv/bin/python -m alembic downgrade *)"], "ask": ["Bash(prisma db push *)", "Bash(npx prisma db push *)"] } }
Two cautions from the docs. A Bash rule matches the command text Claude writes, so it must match how your project invokes the tool. The Alembic report above ran .venv/bin/python -m alembic downgrade base, which Bash(alembic downgrade *) would not match, and npx is not among the wrappers Claude Code strips. That is why the snippet lists the npx and .venv forms; adjust them to your project. And the docs call a deny or ask rule coverage of the usual invocation, not a security boundary around the program. Claude Code Permissions: What Deny Rules Miss covers those gaps, and Least-Privilege Access for AI Coding Agents covers the credentials side.
Sources: Claude Code docs: Configure permissions
If a credential must exist in your shell, the sandbox can scrub it from the commands Claude runs. This entry unsets the named variable before each sandboxed Bash command; it does not affect commands that run outside the sandbox. Use the name of your own production variable.
Sources: Claude Code docs: Sandboxing
{ "sandbox": { "enabled": true, "credentials": { "envVars": [ { "name": "PROD_DATABASE_URL", "mode": "deny" } ] } } }
Second fix: review the migration as a one-shot program
A migration runs once, against production data, often while the app is serving traffic. Six properties make it unlike ordinary code, and a development database with a handful of rows hides most of them.
1. "Reversible" covers the schema, not the rows
Frameworks call a migration reversible when it can be unapplied, which describes structure. Django's documentation says removing a field is reversible "apart from any data loss, which is irreversible," if the field is nullable or has a default for the recreated column, and irreversible if it has neither. A down migration brings back the column without its old values, so asking the agent to "also write the rollback" buys less than it sounds like. Alembic's tutorial describes alembic downgrade base as a downgrade back to nothing. Where each downgrade drops what its upgrade created, that empties the database, as in the first report above.
Sources: Django docs: Migration Operations, Alembic docs: Tutorial (Downgrading)
2. A development database cannot warn you about production data
Migration tools check the database they are connected to. Prisma's CLI reference says data loss warnings are evaluated against the database the command runs on, and advises reviewing the generated SQL before running against a database that holds data. So the warning you see in development describes development data, not yours. Constraints behave the same way. PostgreSQL's manual says SET NOT NULL is allowed only when no row holds a NULL in the column, and ordinarily checks that by scanning the whole table. A migration that passes on a few seed rows can fail on the first real null.
Sources: Prisma docs: CLI reference, PostgreSQL docs: ALTER TABLE
3. Locks and rewrites depend on the engine and the version
The PostgreSQL manual says ALTER TABLE takes an ACCESS EXCLUSIVE lock unless a form is explicitly noted otherwise, and the locking page says only an ACCESS EXCLUSIVE lock blocks a plain SELECT. Some forms also rewrite the table: changing a column type normally does, and so does a volatile default, while a non-volatile default does not. That last point depends on version, because the PostgreSQL 11 release notes introduced avoiding the rewrite for ADD COLUMN with a non-null default. A plain CREATE INDEX blocks writes while it builds, and CONCURRENTLY avoids that. MySQL differs: its 8.4 online DDL table lists changing a column data type as rebuilding the table and not permitting concurrent DML, and says it is only supported with ALGORITHM=COPY. On a tiny development table, each of these finishes before you notice.
Sources: PostgreSQL docs: ALTER TABLE, PostgreSQL docs: Explicit Locking, PostgreSQL 11 release notes, PostgreSQL docs: CREATE INDEX, MySQL 8.4 manual: Online DDL Operations
Waiting for a lock is its own hazard. PostHog's handbook describes the lock queue: while an ALTER waits behind in-flight queries, every later query on that table queues behind it, and on a busy table that produced request pile-ups and errors until lock_timeout cancelled the ALTER. A migration that is instant once it holds the lock can still stall traffic while it waits for it.
Sources: PostHog handbook: Safe Django migrations
4. A failed migration can leave half the work done
Django runs all operations of a migration in one transaction on PostgreSQL and SQLite by default, and without one on MySQL and Oracle. On MySQL the docs say a failed migration means manually unpicking the changes, because it is impossible to roll back to an earlier point. Even on PostgreSQL, CREATE INDEX CONCURRENTLY cannot run inside a transaction block, so a framework that wraps each migration in a transaction needs that migration marked non-atomic: atomic = False in Django, disable_ddl_transaction! in Rails. Strong Migrations adds that backfilling in the same transaction that alters a table keeps the table locked for the duration of the backfill.
Sources: Django docs: Migrations, PostgreSQL docs: CREATE INDEX, Strong Migrations README
5. The schema and the code deploy at different moments
During a deploy, old and new application code run against the same schema. Strong Migrations says Active Record caches columns at runtime, so dropping a column can cause exceptions until the app reboots, and renaming a column that is in use causes errors. Its safer rename takes six steps: create the new column, write to both, backfill, move reads, stop writing the old one, drop it. PostHog's handbook strongly recommends two things: do not rename columns in production, and do not drop a column at all. If you must drop one, it says to wait until the release that takes the field out of the ORM has been deployed for at least one full deploy cycle. Martin Fowler's site calls the general pattern parallel change, or expand and contract, and says most database refactorings follow it. An agent that writes a rename as one migration has solved the schema and skipped the deploy.
Sources: Strong Migrations README, PostHog handbook: Safe Django migrations, martinfowler.com: Parallel Change
6. Generators guess intent
Alembic autogenerate compares your application's table metadata with the live database, and Django makemigrations writes migrations from the changes you made to your models. Both are guesses about intent. Alembic's docs say a column rename is detected as a column add and drop pair, "which is not at all the same as a name change," and that candidate migrations must always be reviewed by hand. Django's docs say makemigrations is "not perfect, and for complex changes it might not be detecting what you expect." With Alembic, an agent that accepts the generated file lets a rename arrive as a drop plus an add. Treat any DROP COLUMN next to an ADD COLUMN of a similar name as a rename until you prove otherwise.
Sources: Alembic docs: Auto Generating Migrations, Django docs: Migrations
| Risk | Why development hides it | Make the agent show you | You check by hand |
|---|---|---|---|
| Data loss | Down migrations restore structure, not rows, and a small dev database makes a drop look harmless | Which statements delete or rewrite data, and what a down migration cannot restore | Each DROP, type change and backfill, run against a restored copy of production data |
| Data-dependent failure | Few or no rows, so no NULLs, duplicates or orphans | A query that counts existing rows the new constraint would reject | Run that count on production data before the migration, not after |
| Locks and rewrites | Tables are small, so locks are short-lived | Lock level and rewrite behavior per statement, with the manual page it relied on | Open that page for your engine and version; set a lock timeout |
| Partial failure | The migration succeeds on the first try | Whether it is atomic on this engine, and what is left if it stops midway | Whether a concurrent index build or a backfill sits inside a wrapping transaction |
| Deploy order | Code and schema change together on your machine | The steps in order, and what old code does against the new schema | Drops and renames only after the code that stopped using the column is fully deployed |
| Generator guess | The auto-generated diff looks plausible | The SQL the tool will run, not just the model change | Every DROP next to a similarly named ADD |
What to ask the agent before it writes anything
This prompt asks for evidence before code. Paste it at the start of a migration task and fill in the brackets. The answers are claims for you to check, not proof, because a model can state a lock level confidently and be wrong.
- State the database engine and version and the migration tool. If either is unknown, ask me instead of assuming.
- Do not run anything against any database except [the local database in .env.local]. Write the migration file, then stop.
- For each statement, say what it does to existing rows, which lock it takes, and whether it rewrites the table. Name the documentation page you relied on.
- If the change drops, renames or retypes a column, or adds a NOT NULL or unique constraint, split it into steps: add, backfill in batches, switch the code, then remove. Say which steps need a deploy in between.
- Show the exact SQL the tool will execute, not just the migration file.
- Give me a query that counts existing rows the new constraint would reject.
- Say what is lost for good if this runs, and what a down migration can and cannot restore.
What to check by hand
Read the SQL, not the model diff. Most tools print it without applying anything. Django has sqlmigrate, which needs a database connection; its docs say to generate the SQL against a copy of the database you will later migrate. Alembic has --sql on upgrade and downgrade, Laravel has php artisan migrate --pretend, and Prisma has migrate dev --create-only, which creates a migration without applying it. Prisma's docs add that if drift is detected during --create-only, you are prompted to reset your database, so use a disposable one.
Sources: Django docs: django-admin and manage.py, Alembic docs: Generating SQL Scripts (Offline Mode), Laravel docs: Migrations, Prisma docs: CLI reference
Run a linter over the migration. Squawk lints PostgreSQL migrations, with rules such as require-concurrent-index-creation, changing-column-type and require-lock-timeout. Strong Migrations does the same for Rails on PostgreSQL, MySQL and MariaDB. A linter reads the migration, and it does not know your data: Strong Migrations states that it does not detect dangerous backfills, so read those yourself.
Sources: Squawk: Rules overview, Squawk rule: require-concurrent-index-creation, Squawk rule: require-lock-timeout, Strong Migrations README
On PostgreSQL, set a lock timeout at the top of the migration so that a statement that cannot get its lock fails instead of making traffic queue behind it. The manual says lock_timeout aborts any statement that waits longer than the set time to acquire a lock, and Squawk has a rule asking for one. SET lock_timeout = '3s'; is a plausible first line. Pick a value that suits your traffic, and retry at a quieter time if it trips.
Sources: PostgreSQL docs: Client Connection Defaults (lock_timeout), Squawk rule: require-lock-timeout
For adding NOT NULL to a large PostgreSQL table, the manual documents the pieces of a pattern that avoids a long exclusive scan. PostHog's handbook gives the outer shape: add the column as nullable, backfill in batches, then add the constraint. For that last step, add a CHECK constraint with NOT VALID, which skips the scan, validate it, which takes a weaker lock, and finally set NOT NULL, which skips its own scan because a valid CHECK already proves there are no nulls. The PostgreSQL 12 release notes describe that last optimization, so this needs version 12 or later. The first and last statements still take a brief ACCESS EXCLUSIVE lock, since ALTER TABLE takes one unless the manual notes otherwise, which is where the timeout above earns its place.
Sources: PostgreSQL docs: ALTER TABLE, PostgreSQL 12 release notes, PostHog handbook: Safe Django migrations
ALTER TABLE orders ADD CONSTRAINT orders_status_nn CHECK (status IS NOT NULL) NOT VALID;ALTER TABLE orders VALIDATE CONSTRAINT orders_status_nn;ALTER TABLE orders ALTER COLUMN status SET NOT NULL;
Two more checks. Restore a backup, or an anonymized copy, into a scratch database and time the migration there, watching whether it blocks reads and writes. And if CREATE INDEX CONCURRENTLY fails midway, the manual says it leaves an invalid index and recommends dropping it and trying again, so a retry should start with the drop. Then have someone who knows the database read the SQL before production. For which changes deserve a human gate, see Approval Gates for High-Risk AI Code Changes. For what to do after a wipe, see Running a Postmortem on an AI Agent Incident.
Sources: PostgreSQL docs: CREATE INDEX
Where TLM Forge fits
TLM Forge sizes each task Light, Medium or Deep. Medium and Deep tasks show you a design for your OK before building, which gives a migration a pause where you can ask what will be dropped, renamed or retyped before any code is written. Deep tasks get a spec audit and are verified on a real environment.
The limits are real. A task sized Light gets no review agents. The reviewer agents are LLMs that can miss a lock or a data-loss path, a verification environment is not your production data, and TLM Forge does not check your table sizes, traffic or deploy order. It does not make a migration safe. A person who knows the database still reads the SQL.
Frequently asked questions
01Can Claude Code write a database migration safely?
It can write the file, but safety depends on what you check. The risks are data loss, long locks, partial failure and deploy order, and a development database hides most of them. Ask for the exact SQL and a step plan, run it on production-sized data, and have someone who knows the database review it.
02Why did Claude Code drop my database?
In individual user reports, the agent ran a routine reset or downgrade command from its migration tool against whatever database its connection string pointed to. A prompt instruction is guidance, not enforcement. Keep production credentials out of the session, use a disposable database, and deny the reset commands.
03Should I let an AI agent run migrations against production?
No. Let it write the migration against a local or disposable database, then apply it to production through your deploy pipeline with its own credentials, after a person has read the SQL. Writing a good migration does not require the production connection string.
04Does a down migration protect me from data loss?
Not by itself. A down migration usually restores structure, not deleted rows. Django's documentation calls a column removal reversible apart from any data loss, which is irreversible. If a step destroys data, take a backup first and treat that step as one-way.
05How do I add a NOT NULL column to a big PostgreSQL table without a long lock?
Add it as nullable, backfill in batches, add a CHECK constraint with NOT VALID, validate it, then set NOT NULL, which skips the table scan on PostgreSQL 12 and later. The first and last statements still take a brief strong lock, so set a lock timeout.