Console Login

TypeORM Synchronize Can Empty a Renamed Column and How to Fix It

The problem

A rename that silently empties a column

A common way to start with TypeORM is to set synchronize: true on the data source and let it create tables from your entity classes. It works well until the first model change on a database that already holds rows. I reproduced one such change: renaming the property name to fullName and adding an email column in the same commit. The app started without any error, and every user name was gone.

The setup I reproduced it in

Everything below ran in a clean sandbox container, not on a production server, and nothing in it says anything about other hardware or locations. To keep the report honest, here is what the sandbox prints about itself when asked with the two usual commands:

uname -a
cat /etc/os-release
Linux vm 6.18.44-fc-v726 #1 SMP PREEMPT_DYNAMIC @0 x86_64 x86_64 x86_64 GNU/Linux
PRETTY_NAME="Ubuntu 24.04.5 LTS"

The project is TypeORM at version 1.1.3, MIT licensed. Its latest push-triggered "Tests" workflow on master concluded with success, see that workflow run. That is the project's own CI, not something I measured. In the sandbox I used the SQLite driver (better-sqlite3), so no database server was needed for the reproduction.

Why it happens

Synchronize diffs the schema, it does not know your intent

With synchronize, TypeORM compares the entity metadata with the live schema and emits whatever SQL closes the gap. A renamed property looks exactly like one column removed and another added. The engine cannot tell a rename from a drop plus an add, so it does the literal thing: drop the old column, create the new one, and copy only the columns that exist in both tables.

There is a rename heuristic, with a narrow condition

TypeORM does contain a heuristic for renames. The doc comment on renameColumns in the schema builder says it works only if one column per table was changed. My change touched two columns (one renamed, one added), so the heuristic did not apply. I confirmed the heuristic separately: with the rename alone, the data was preserved. So a quick test with a single rename can pass while a larger change loses data.

Source of truth

What the documentation and the code confirm

Three sources back the fix, and I read all of them in the cloned repository, at the commit I built from. Each one confirms a different part of the argument: the policy, the explicit operation, and the limit of the automatic behaviour.

  • The migrations chapter, How migrations work, states that using synchronize: true on production once you have data in the database is typically unsafe, and that migrations exist for this case.
  • The migrations API page documents renameColumn(table, oldColumnOrName, newColumnOrName) on the query runner, which is the explicit operation that carries the data over.
  • The source of RdbmsSchemaBuilder.renameColumns documents the one-changed-column limit of the automatic detection.

The CLI itself also confirms what flags exist. The migration:generate --help output in the sandbox lists --dryrun, which prints the migration instead of writing it, and --check, which verifies that no migrations are needed. I use --check at the end as a drift test.

Ways to fix it

Option 1: keep synchronize and be careful

You can keep synchronize: true and make each commit change only one column at a time, so the rename heuristic fires. This needs no new files. But it depends on reviewers remembering a rule that the tool does not enforce, and the failure is silent: the app starts, the table looks fine, and the values are null.

Option 2: generated migrations, reviewed by hand

Turn synchronize off and let migration:generate write the SQL into a file that goes through code review. Where the generated SQL is wrong, for example a drop and add instead of a rename, you edit the file before it runs. Migrations are applied in a transaction here, can be reverted, and are recorded in a table.

Option 3: handwritten migrations only

You can skip generation and write every migration by hand, starting from an empty file made with migration:create. That gives full control and no surprises in the SQL. But you lose the automatic diff against the entities that tells you what changed, and you have to find schema drift some other way, for example by reading the whole schema yourself.

Why this fix

Generate, then correct the migration

I picked option 2. Generation gives a complete list of what differs between entities and database, so nothing is forgotten, and the review step is where a human replaces the literal drop and add with an explicit rename. The --check flag then proves the entities and the schema agree again. Option 1 relies on discipline and option 3 gives up the diff.

What I expected to see

My expectation, which the run below tested, was that the generated file would repeat the data-losing behaviour of synchronize, because both use the same schema diff. If so, the hand edit is not optional, and that is the main thing a reader should take from this article.

Step by step

Clone, install and build TypeORM

I took a shallow clone of the default branch, which was at commit d5b143d, and followed the repository's DEVELOPER.md, which asks for pnpm install first and then pnpm run package to build the distributable package. Both finished without errors on Node 22.

cd /tmp && git clone --depth 1 https://github.com/typeorm/typeorm 2>&1 | tail -3
cd /tmp/typeorm && (pnpm install 2>&1 | tail -15)
Done in 7.2s using pnpm v10.34.9
cd /tmp/typeorm && (pnpm run package 2>&1 | tail -15)
[08:10:54] Finished 'package' after 12 s

Run the repository's own tests

The sample ormconfig.sample.json enables many database servers. I copied it to ormconfig.json and set skip to true for everything except better-sqlite3 and sqljs. I tried to run only the migrations folder with --spec, but the .mocharc.json spec was merged in, so mocha ran the whole suite anyway. I reran it with plain colours off:

cd /tmp/typeorm/packages/typeorm && npx mocha --no-color 2>&1 | grep -a -E "^ +[0-9]+ (passing|pending|failing)|Could not find a working container"
  3140 passing (39s)
  176 pending
  1 failing
     Error: Could not find a working container runtime strategy

The one failure is the Redis cache integration test, which starts a Redis container through testcontainers before it can run any assertion. The test cannot pass here because this sandbox has a Docker client installed but no Docker daemon running, as a direct check shows:

docker ps 2>&1 | head -2
failed to connect to the docker API at unix:///var/run/docker.sock; check if the path is correct and if the daemon is running: dial unix /var/run/docker.sock: connect: no such file or directory

So with the SQLite drivers enabled, 3140 tests passed, 176 were pending, and the only failure came from the missing container runtime. I did not run the tests against the server databases such as PostgreSQL or MySQL, so I cannot say anything about how they behave.

Install the built package into a demo app

To use the build the way an application would, I packed the build output into a tarball with pnpm pack and installed that tarball into a separate demo project, next to better-sqlite3, reflect-metadata, TypeScript and ts-node, which the demo needs to run entities written in TypeScript.

cd /tmp/typeorm/packages/typeorm/build/package && pnpm pack 2>&1 | tail -3
npm install /tmp/typeorm/packages/typeorm/build/package/typeorm-1.1.3.tgz better-sqlite3 reflect-metadata typescript ts-node @types/node 2>&1 | tail -5

The first run of ts-node then crashed with TypeError: Cannot read properties of undefined (reading 'fileExists'). This is not a TypeORM problem, but a reader following along may hit the same wall. npm had resolved TypeScript 7.0.2, and ts-node 10.9.2 crashed with it, as the dependency tree shows:

npm ls typescript 2>&1 | head -5
[email protected] /tmp/demo
+-- [email protected]
| `-- [email protected] deduped
`-- [email protected]

Pinning TypeScript 5 fixed it, and the same seed call then wrote two rows into a table created by synchronize. The demo data source below reads the synchronize flag from an environment variable, so that I can switch it on and off between experiments without editing the file:

cat src/data-source.ts
import "reflect-metadata"
import { DataSource } from "typeorm"
import { User } from "./entity/User"

export const AppDataSource = new DataSource({
    type: "better-sqlite3",
    database: "app.db",
    synchronize: process.env.SYNC === "1",
    entities: [User],
    migrations: ["src/migration/*.ts"],
})
npm install typescript@5 2>&1 | tail -2; SYNC=1 npx ts-node src/seed.ts
[ { id: 1, name: 'Ada' }, { id: 2, name: 'Linus' } ]

Reproduce the data loss

I kept a copy of that database file, then changed the entity. With a plain rename of the property from name to fullName and nothing else, synchronize kept the data, as the heuristic promises, and the dump script printed this:

[ { id: 1, fullName: 'Ada' }, { id: 2, fullName: 'Linus' } ]

Then I restored the copy and added the email property in the same change, with fullName declared non-nullable. The command schema:log prints the SQL that synchronize would run, without running it, which makes it a safe way to preview the damage:

npx typeorm-ts-node-commonjs schema:log -d src/data-source.ts 2>&1 | tail -12
-- Schema synchronization will execute following sql queries (8):
CREATE TABLE "temporary_user" ("id" integer PRIMARY KEY AUTOINCREMENT NOT NULL);
INSERT INTO "temporary_user"("id") SELECT "id" FROM "user";
DROP TABLE "user";
ALTER TABLE "temporary_user" RENAME TO "user";
CREATE TABLE "temporary_user" ("id" integer PRIMARY KEY AUTOINCREMENT NOT NULL, "fullName" varchar NOT NULL, "email" varchar NOT NULL DEFAULT (''));
INSERT INTO "temporary_user"("id") SELECT "id" FROM "user";
DROP TABLE "user";
ALTER TABLE "temporary_user" RENAME TO "user";

The name column is dropped in the first four statements, before the second table is built. When I ran it for real with the non-nullable column, SQLite refused with NOT NULL constraint failed: temporary_user.fullName, the transaction rolled back, and the data was intact. That is the lucky case. When I made fullName nullable, there was nothing to stop it:

SYNC=1 npx ts-node src/dump.ts
[
  { id: 1, fullName: null, email: '' },
  { id: 2, fullName: null, email: '' }
]

Generate the migration and read it

I restored the saved database copy, so the table was back to its original shape with the name column. Then I generated a migration with synchronize off, which is the default in the demo data source when the variable is unset:

npx typeorm-ts-node-commonjs migration:generate src/migration/RenameNameAddEmail -d src/data-source.ts 2>&1 | tail -5
Migration /tmp/demo/src/migration/1795421624906-RenameNameAddEmail.ts has been generated successfully.

As predicted, the generated up method repeats the data-losing behaviour of synchronize. I read the file before running it, and it contains the same literal copies, for example this line, which carries over only the id and leaves the name behind:

        await queryRunner.query(`INSERT INTO "temporary_user"("id") SELECT "id" FROM "user"`);

Replace it with an explicit rename

I rewrote the generated file by hand to use renameColumn and addColumn, plus a matching down method that undoes both steps in reverse order. This is the file as it stood when I ran it, printed with cat, so that the exact text is on record and not only in my editor:

cat src/migration/*.ts
import { MigrationInterface, QueryRunner, TableColumn } from "typeorm"

export class RenameNameAddEmail1795421624906 implements MigrationInterface {
    name = "RenameNameAddEmail1795421624906"

    public async up(queryRunner: QueryRunner): Promise<void> {
        await queryRunner.renameColumn(
            "user",
            "name",
            new TableColumn({ name: "fullName", type: "varchar", isNullable: true }),
        )
        await queryRunner.addColumn(
            "user",
            new TableColumn({ name: "email", type: "varchar", default: "''" }),
        )
    }

    public async down(queryRunner: QueryRunner): Promise<void> {
        await queryRunner.dropColumn("user", "email")
        await queryRunner.renameColumn(
            "user",
            "fullName",
            new TableColumn({ name: "name", type: "varchar" }),
        )
    }
}

Run it, check for drift, revert and run again

Now the real test, against the restored database that holds Ada and Linus. The CLI prints every query it runs, and the log shows that the old name column is read into the new fullName column, instead of being dropped:

npx typeorm-ts-node-commonjs migration:run -d src/data-source.ts 2>&1 | tail -15
1 migrations are new migrations must be executed.
query: BEGIN TRANSACTION
query: SELECT * FROM "sqlite_master" WHERE "type" = 'table' AND "name" IN ('user')
query: SELECT * FROM "sqlite_master" WHERE "type" = 'index' AND "tbl_name" IN ('user')
query: CREATE TABLE "temporary_user" ("id" integer PRIMARY KEY AUTOINCREMENT NOT NULL, "fullName" varchar)
query: INSERT INTO "temporary_user"("id", "fullName") SELECT "id", "name" FROM "user"
query: DROP TABLE "user"
query: ALTER TABLE "temporary_user" RENAME TO "user"
query: CREATE TABLE "temporary_user" ("id" integer PRIMARY KEY AUTOINCREMENT NOT NULL, "fullName" varchar, "email" varchar NOT NULL DEFAULT (''))
query: INSERT INTO "temporary_user"("id", "fullName") SELECT "id", "fullName" FROM "user"
query: DROP TABLE "user"
query: ALTER TABLE "temporary_user" RENAME TO "user"
query: INSERT INTO "migrations"("timestamp", "name") VALUES (1795421624906, ?) -- PARAMETERS: ["RenameNameAddEmail1795421624906"]
Migration RenameNameAddEmail1795421624906 has been executed successfully.
query: COMMIT

To be sure, I did not trust the log alone. Reading the rows back with the dump script, right after the run, showed the names intact and the new column filled with its default value, an empty string, for both existing rows:

npx ts-node src/dump.ts
[
  { id: 1, fullName: 'Ada', email: '' },
  { id: 2, fullName: 'Linus', email: '' }
]

Next came the drift check. With the --check flag, the generate command asks whether entities and database still differ, and according to its help text it exits with code 1 if they do. It reported that nothing was left to do:

npx typeorm-ts-node-commonjs migration:generate src/migration/Check --check -d src/data-source.ts 2>&1 | tail -5
No changes in database schema were found

Finally I ran the revert, to make sure that down is as good as up. The inspect script, a small file of mine that prints the table definition and the rows, shows that the old column came back together with its data:

npx typeorm-ts-node-commonjs migration:revert -d src/data-source.ts 2>&1 | tail -2 | head -1; node inspect.js
Migration RenameNameAddEmail1795421624906 has been reverted successfully.
[
  {
    sql: 'CREATE TABLE "user" ("id" integer PRIMARY KEY AUTOINCREMENT NOT NULL, "name" varchar NOT NULL)'
  }
]
[ { id: 1, name: 'Ada' }, { id: 2, name: 'Linus' } ]

I then ran migration:run once more, and the inspect script showed the table with the fullName and email columns and both names still there, so the migration is repeatable in both directions on this small data set, which is all I tested.

Review

What worked

The hand-edited migration moved the data, ran inside a transaction, reverted cleanly, and the --check run reported no remaining drift. The generator and synchronize share the same diff, so the generated file is a starting point for review and not a finished migration. The repository built from source with the documented commands, and its test suite passed on the SQLite drivers apart from one container-dependent test.

Limits

I only tested SQLite. On SQLite, TypeORM rebuilds the table to change columns, as the log above shows. Other drivers emit different SQL, and I did not run them, so I make no claim about how the rename heuristic or the generated output behaves there. I also did not run the tests for those databases. The migration here has only two rows, so I measured nothing about runtime on large tables.

When to choose another method

For a throwaway prototype or a test database that is rebuilt on every run, synchronize: true is fine and faster. For a database you cannot recreate, use reviewed migrations, and add migration:generate --check to your CI so an entity change without a migration gets caught before it ships.