Generating Safe TypeORM Migrations From Entity Changes
You renamed an entity property from fullName to displayName, ran typeorm migration:generate, and the CLI handed back a migration whose up() opens with DROP COLUMN "fullName" and then ADD COLUMN "displayName". The diff engine did exactly what it was designed to do — it compared the entities against the live catalog and emitted the shortest SQL that makes them match — but “shortest” and “safe” are not the same thing. Applied as written, that migration takes an ACCESS EXCLUSIVE lock, drops a populated column, and discards every value in it, all inside a single migration:run that reviewers waved through because the file looked machine-generated and therefore trustworthy. migration:generate is a draft author, not a release engineer: it cannot see that a drop-plus-add is a rename, it cannot know a column is read by code still in production, and it cheerfully packs an online-hostile statement next to a trivial one. This page is the runbook for reading that generated SQL, splitting a destructive diff into an additive-then-contract sequence, and hardening the result so the deploy is genuinely zero-downtime — the concrete companion to the review discipline the parent TypeORM Migration Workflows guide establishes.
Symptom / Error Signatures
There is rarely an exception at generation time — that is what makes this dangerous. The tell is in the generated file itself. The purest signature of a mis-rendered rename is a drop immediately followed by an add of the same logical column:
// migration/1721800000000-RenameUserName.ts — the up() TypeORM generated for a property rename.
// This is DATA LOSS: the DROP discards every value before the ADD recreates an empty column.
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`ALTER TABLE "users" DROP COLUMN "fullName"`);
await queryRunner.query(`ALTER TABLE "users" ADD "displayName" character varying`);
}
A type change on a large table generates an in-place rewrite that looks harmless but blocks every reader and writer for the duration of the rewrite:
// migration/1721800100000-WidenStatus.ts — an in-place ALTER TYPE on a hot table.
// On a multi-million-row table this holds ACCESS EXCLUSIVE for the whole rewrite.
await queryRunner.query(`ALTER TABLE "orders" ALTER COLUMN "status" TYPE character varying(64)`);
The most under-reviewed signature is the generated down(), which mechanically inverts up() and will DROP a column a backfill has since filled:
// migration/1721800000000-RenameUserName.ts — the down() TypeORM wrote automatically.
// Running this after the new column is populated destroys the migrated data.
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`ALTER TABLE "users" DROP COLUMN "displayName"`);
await queryRunner.query(`ALTER TABLE "users" ADD "fullName" character varying`);
}
At apply time the same generated SQL, re-run after a partial failure, surfaces as QueryFailedError: column "displayName" of relation "users" already exists. If any generated migration contains an unguarded DROP COLUMN, an ALTER COLUMN ... TYPE against a big table, or a down() that drops a column carrying data, you are on the right page.
Root Cause Analysis
TypeORM’s diff engine holds two schema representations: the desired state derived from your @Entity, @Column, and @Index decorators, and the live state reflected from the database catalog. migration:generate computes the set difference and emits the minimal DDL to reconcile them. The engine works at the level of columns and their attributes, not intent — so a property rename presents as one column that vanished and another that appeared, and the only SQL that reconciles “column A gone, column B new” is DROP A; ADD B. There is no rename primitive in the diff because there is no rename signal in the entities. Likewise a widened varchar or a promoted integer is emitted as a single in-place ALTER COLUMN ... TYPE, which on PostgreSQL forces a full table rewrite under an ACCESS EXCLUSIVE lock, exactly the online-DDL hazard the Expand and Contract Methodology exists to avoid.
The generated SQL also diverges sharply by engine, which matters because most teams review the migration on one database and apply it on another. The same entity change produces materially different — and differently dangerous — DDL on PostgreSQL versus MySQL:
| Generated change | PostgreSQL emitted DDL | MySQL 8.0 emitted DDL | Why it bites |
|---|---|---|---|
| Property rename | DROP COLUMN + ADD (data loss) |
DROP COLUMN + ADD (data loss) |
No rename intent in entities on either engine |
| Column type widen | ALTER COLUMN ... TYPE — full rewrite, ACCESS EXCLUSIVE |
ALTER TABLE ... MODIFY — often INPLACE, still locks metadata |
Postgres rewrites the whole table; MySQL varies by algorithm |
| Add non-null column | ADD COLUMN ... NOT NULL DEFAULT (fast, 11+) |
ADD COLUMN ... NOT NULL — can rebuild the table |
Same entity, different lock cost |
| Add index | CREATE INDEX — locks writes |
CREATE INDEX — INPLACE but blocks DDL |
Neither generates CONCURRENTLY / ALGORITHM=INPLACE, LOCK=NONE |
| Failed mid-migration | Rolls back cleanly (transactional DDL) | Each ALTER implicitly commits — half-applied |
The rollback contract differs entirely |
The last row is the deepest trap. Under the default transaction: "all", a failed migration:run on PostgreSQL rolls back and leaves the ledger untouched; on MySQL each ALTER TABLE implicitly commits, so a mid-batch failure can leave a class half-applied and unrecorded — a divergence the Transactional vs Non-Transactional Databases guide treats in depth. The generator is engine-aware in its syntax but never in its safety: it never emits CREATE INDEX CONCURRENTLY, never splits a rename into a copy, and never asks whether the old column is still read. Those judgments are yours.
Immediate Mitigation
The goal is to intercept the destructive diff before it reaches migration:run and reshape it into an online-safe sequence. Work in the generated file and against a scratch database — never hand-edit a migration that has already been applied to a shared environment.
1. Generate against a scratch database and read every statement. Build first so the CLI diffs current compiled entities, then open the file and audit each queryRunner.query(...) call by eye.
# bash · run locally or in CI against a THROWAWAY database · read-only against production.
# migration:generate writes a file; it applies NOTHING. Rebuild first or it diffs stale JS.
npm run build
npx typeorm migration:generate ./src/migration/RenameUserName -d ./dist/data-source.js
grep -nE "DROP COLUMN|ALTER COLUMN .* TYPE|DROP INDEX|NOT NULL" \
./src/migration/*RenameUserName*.ts || echo "no obviously destructive statements"
Verify before proceeding: any line the grep prints is a statement to reshape, not to ship. A clean result still warrants a full read of up() and down().
2. Rewrite a mis-generated rename as a non-destructive copy. Replace the DROP+ADD pair with an additive ADD COLUMN only. The old column stays until the contract phase, so the currently-deployed code keeps reading it.
-- PostgreSQL · migration role · additive and backward compatible · safe under live traffic.
-- Ship ONLY this half now. The old "fullName" column is dropped in a later contract migration.
ALTER TABLE users ADD COLUMN IF NOT EXISTS display_name character varying;
Verify before proceeding: confirm no statement in this migration touches or drops fullName. The backfill and the drop are separate, later steps governed by Backfill Optimization.
3. Split an in-place type change into an expand step. A generated ALTER COLUMN ... TYPE that rewrites the table becomes: add a new column of the target type, backfill it, cut reads over, then drop the old one in a separate deploy.
-- PostgreSQL · migration role · additive · the rewrite is avoided by adding, not altering.
-- The generated single-statement ALTER TYPE is replaced by this additive column.
ALTER TABLE orders ADD COLUMN IF NOT EXISTS status_v2 character varying(64);
Verify before proceeding: the entity should map both the old and new columns during the transition, so the application can dual-write while the backfill runs.
4. Move a generated index into its own non-transactional migration. The generator emits a blocking CREATE INDEX; replace it with CONCURRENTLY and set that migration’s transaction mode to none, because a concurrent index cannot run inside the batch transaction.
// migration/1721800200000-IndexDisplayName.ts · TypeScript · migration role.
// transaction:"none" is REQUIRED — CREATE INDEX CONCURRENTLY cannot run in a transaction.
export class IndexDisplayName1721800200000 implements MigrationInterface {
transaction = "none" as const;
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_users_display_name ON users (display_name)`
);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`DROP INDEX CONCURRENTLY IF EXISTS idx_users_display_name`);
}
}
Verify before proceeding: on PostgreSQL confirm the index built valid — a failed CONCURRENTLY leaves an invalid index that must be dropped and rebuilt.
5. Harden every statement with idempotent guards. Add IF NOT EXISTS / IF EXISTS so a re-run after a partial failure is a no-op rather than a QueryFailedError, following Idempotent Script Design.
# bash · local/CI · confirms the reshaped migration is additive and guarded before you commit.
grep -c "IF NOT EXISTS\|IF EXISTS" ./src/migration/*RenameUserName*.ts
grep -q "DROP COLUMN" ./src/migration/*RenameUserName*.ts \
&& { echo "STILL DESTRUCTIVE — remove the DROP from the expand migration"; exit 1; } \
|| echo "expand migration is additive"
Permanent Fix / Long-Term Pattern
The durable fix is to stop treating a generated migration as a finished artifact and start treating it as a proposal that must clear a review gate before it can be committed. Every migration:generate output passes through the same checklist: is any DROP COLUMN actually a rename in disguise, does any ALTER COLUMN ... TYPE rewrite a large table, does the down() drop a column that will hold migrated data, and does any statement need CONCURRENTLY and its own non-transactional migration. The rename and retype cases are the same additive problem, and the idiomatic solution is always the three-phase sequence the parent TypeORM Migration Workflows guide codifies: an expand migration that only adds, a backfill that populates the new shape while the application dual-writes, and a contract migration — shipped a full deploy later — that finally drops the old column once nothing reads it. The generated SQL supplies the raw DDL for the expand and contract halves; you supply the sequencing.
Make the blind spot impossible to merge by wiring a guard into CI. Fail the build if any migration file added in the diff contains an unguarded DROP COLUMN or an ALTER COLUMN ... TYPE, forcing a human to justify it or split it:
# bash · CI gate on the PR diff · fails the job if a generated migration ships destructive DDL unreviewed.
if git diff --name-only origin/main... | grep '^src/migration/' \
| xargs grep -lE 'DROP COLUMN|ALTER COLUMN .* TYPE' 2>/dev/null | grep .; then
echo "destructive DDL in a migration — split into expand/contract or annotate as reviewed"; exit 1
fi
Close the loop with a drift probe: after the expand deploy, run migration:generate against production with a read-only role and assert it emits no file, proving the entities and the live schema agree — the same parity discipline the Migration Tool Comparison applies across tools. A generated migration is the start of the work, not the end of it; the contract step lands only after the new column is backfilled and the old code is fully drained.
Verification Checklist
Up one level: TypeORM Migration Workflows.
Related
- Disabling TypeORM synchronize in Production
- Resolving TypeORM Out-of-Order Migration Errors
- Expand and Contract Methodology
Frequently Asked Questions
Why does migration:generate turn a column rename into a DROP plus ADD?
Because there is no rename signal in your entities for the diff engine to read. TypeORM compares the desired columns derived from your decorators against the columns reflected from the database; a rename presents as one column that disappeared and another that appeared, and the minimal SQL to reconcile that is DROP the old and ADD the new. The generator has no way to know the two are the same logical field, so it emits data-loss DDL. The fix is to ship only the additive ADD COLUMN now, backfill the new column while the application dual-writes, and drop the old column in a separate contract migration a full deploy later.
Is the generated down() safe to use for rollback?
Treat it as a draft, never a safety net. The generated down() mechanically inverts up(), so if up() added a column it will DROP that column — including after a backfill has populated it, destroying the migrated data on reversal. Under expand-and-contract the correct rollback is almost always to redeploy the previous application image and leave the expanded schema in place, since the old code tolerates the extra column. Run a down() only when the migration added an object nothing reads and you have verified by hand that it drops only that object.
How do I make a generated ALTER COLUMN ... TYPE safe on a large table?
Do not apply it in place. On PostgreSQL that single statement forces a full table rewrite under an ACCESS EXCLUSIVE lock that blocks every reader and writer for the duration. Replace it with the expand sequence: add a new column of the target type, have the entity dual-write both columns, backfill the new one in batches, cut reads over, then drop the old column in a later contract migration. The generator still supplies the raw DDL for the add and the drop — you supply the phasing and the batched backfill that keeps the table online throughout.