Lesson 20 / 35

TypeORM Migrations

Generate a TypeORM migration from entity changes, read its up and down methods, and run or revert it with the CLI.

By · 15 years in web development

Generated classes with up and down

A TypeORM migration is a TypeScript class implementing MigrationInterface with two methods. up applies the change and down undoes it, both receiving a QueryRunner you use to run SQL. You can write one by hand with migration:create, or let TypeORM compare your entities with the database and write it for you with migration:generate. The CLI needs to know where your DataSource is, passed with -d, and if your project is TypeScript you run the CLI through a ts-node wrapper such as typeorm-ts-node-commonjs (or compile first and point at the JavaScript output). migration:run applies pending migrations in order and records them in the migrations table; migration:revert undoes only the most recent one by calling its down. You can also set migrationsRun: true on the DataSource to run migrations at startup, though many teams prefer an explicit pipeline step so a failed migration stops the deploy rather than the running app.

Generate, inspect, run

The class name ends with a timestamp so migrations sort in creation order.

// terminal:
// npx typeorm-ts-node-commonjs migration:generate src/migrations/AddBio -d src/data-source.ts
// npx typeorm-ts-node-commonjs migration:run -d src/data-source.ts

import { MigrationInterface, QueryRunner } from 'typeorm';

export class AddBio1712345678901 implements MigrationInterface {
  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`ALTER TABLE "user" ADD "bio" text`);
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`ALTER TABLE "user" DROP COLUMN "bio"`);
  }
}

Read generated migrations line by line

If you rename a property, TypeORM's generator may emit DROP COLUMN followed by ADD, losing the data. Replace it with ALTER TABLE ... RENAME COLUMN ... before committing. Generated code is a draft, not a decision.

Quick check: What does typeorm migration:revert do?

  • Rolls back every migration ever applied
  • Deletes the migration files from disk
  • Regenerates the latest migration from entities
  • Runs the down method of the most recently applied migration
Answer

Runs the down method of the most recently applied migration — revert undoes one migration at a time, the last one recorded in the migrations table, by calling its down method.