SkillByAIOpen interactive version →

Lesson 19 / 34

Migrations

Version your database schema with TypeORM migrations: generate, run and write custom SQL changes.

Generate & run migrations

TypeORM CLI generates migrations based on entity changes; run them to update the database.

npx typeorm migration:generate ./src/migrations/CreateUserTable
npx typeorm migration:run

Manual migration

Write custom SQL migration for complex schema changes.

import { MigrationInterface, QueryRunner } from 'typeorm';

export class CreateUserTable123456 implements MigrationInterface {
  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query('CREATE TABLE user (id SERIAL PRIMARY KEY, name VARCHAR NOT NULL)');
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query('DROP TABLE user');
  }
}

Never use synchronize in production

synchronize: true can drop columns to match your entities. Use it only locally; in production run reviewed migrations.

Quick check

Quick check: Why generate a migration instead of editing the database by hand?

  • Migrations make queries faster
  • Changes are versioned, reviewable and repeatable across environments
  • TypeORM refuses manual SQL
Answer

Changes are versioned, reviewable and repeatable across environments — Migration files live in git and run the same way on dev, staging and prod.