Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 37 ยท Migrations

Migrations in TypeORM

Learn TypeORM migrations: the MigrationInterface, QueryRunner, migration:generate, migration:run and revert, plus how to review generated SQL before it ships.

TypeORM migrations are TypeScript classes. Each one implements MigrationInterface with two methods, up and down, and receives a QueryRunner that can run SQL or use schema helpers. The CLI can write a migration for you by comparing your entities with the live database, or you can write it by hand.

Because TypeORM is an npm package, the code in this lesson that imports it is read-only. Alongside it, runnable stand-ins show what the QueryRunner and the CLI do, using real SQLite SQL.

Configuring the data source

The CLI needs a DataSource file that exports your connection. Migrations are listed by a glob pattern, and synchronize stays off.

TypeScript
// data-source.ts
import { DataSource } from 'typeorm';

export default new DataSource({
  type: 'postgres',
  url: process.env.DATABASE_URL,
  entities: ['src/entities/*.ts'],
  migrations: ['src/migrations/*.ts'],
  migrationsTableName: 'migrations',
  synchronize: false,
});

The CLI commands

Command What it does
typeorm migration:create src/migrations/AddEmail Writes an empty migration with a timestamp name
typeorm migration:generate src/migrations/AddEmail -d data-source.ts Diffs entities against the database and writes the SQL
typeorm migration:run -d data-source.ts Applies every pending migration
typeorm migration:revert -d data-source.ts Runs down for the last applied migration
typeorm migration:show -d data-source.ts Lists applied and pending migrations

With TypeScript you usually go through ts-node or tsx, for example npx typeorm-ts-node-commonjs migration:run -d data-source.ts. The exact wrapper depends on your module setup, so check the TypeORM docs for your version.

A hand-written migration

TypeScript
import { MigrationInterface, QueryRunner, Table, TableColumn } from 'typeorm';

export class CreateUsers1730000000000 implements MigrationInterface {
  public async up(q: QueryRunner): Promise<void> {
    await q.createTable(new Table({
      name: 'users',
      columns: [
        { name: 'id', type: 'integer', isPrimary: true, isGenerated: true, generationStrategy: 'increment' },
        { name: 'name', type: 'varchar', length: '120', isNullable: false },
      ],
    }));
    await q.addColumn('users', new TableColumn({ name: 'email', type: 'varchar', isNullable: true }));
  }

  public async down(q: QueryRunner): Promise<void> {
    await q.dropTable('users');
  }
}

The number at the end of the class name is a timestamp. TypeORM sorts by it, which is why the CLI generates it for you. You can also write raw SQL with q.query('...') when the helper API does not cover what you need, such as a partial index or a database-specific feature.

Reviewing generated SQL

migration:generate is a diff tool. It is good at "add this column" and poor at intent. A rename is the classic mistake, so always open the file before you commit it. The stand-in below mimics a diff: it compares what the entity wants with what the table has, and shows how a rename becomes a drop plus an add unless you rewrite it.

Node.js What a generated diff sees (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The generated version would have deleted Ada's name. The hand-written rename column keeps it. In TypeORM you would call q.renameColumn('users', 'name', 'fullName').

Running migrations from code

You can run pending migrations at startup, which suits small apps and tests, though many teams prefer a separate deploy step so a slow migration does not delay the web server.

TypeScript
const ds = await dataSource.initialize();
const ran = await ds.runMigrations({ transaction: 'each' });
console.log(ran.map((m) => m.name));
// ds.undoLastMigration() reverts one

transaction: 'each' wraps each migration in its own transaction, so a failing one leaves the database as it was before that migration. On databases with transactional DDL (PostgreSQL) this is a real safety net. MySQL commits DDL implicitly, so a failed migration can leave half the work applied. Keep MySQL migrations small.

Practical habits

  • Name files by intent (AddEmailToUsers), not by ticket number.
  • Keep schema changes and data changes in separate migrations.
  • Run migration:show in CI to confirm nothing is pending on the test database.
  • Never import entities inside a migration; they change over time but a migration must keep meaning the same thing. Use raw SQL or table names instead.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What two methods does a TypeORM migration implement?

    MigrationInterface requires up to apply and down to undo.
  2. 2. Which command writes SQL by comparing entities to the database?

    migration:create makes an empty file; migration:generate fills it from a schema diff.
  3. 3. Why should you read a generated migration before committing?

    The diff cannot know a rename from a delete and an add. Rewrite it with renameColumn.
  4. 4. Why avoid importing entities inside a migration?

    A migration is frozen history. Using current entity definitions can break it later.

Summary

  • TypeORM migrations are classes with up and down that receive a QueryRunner.
  • Use migration:generate for a first draft and always review the SQL.
  • Renames and data moves need hand-written steps.
  • Keep synchronize off and run migrations in a controlled deploy step.

Next: Migrations in Sequelize