ื“ืœื’ ืœืชื•ื›ืŸ ื”ืจืืฉื™

TypeORM Migrations

Create and manage database schema changes with TypeORM migrations.

Overviewโ€‹

Migrations track schema changes in a version-controlled way, allowing safe database evolution.

Creating a Migrationโ€‹

Auto-Generate from Entity Changesโ€‹

yarn typeorm migration:generate -n AddEmployeePhoneColumn

This compares current entities against the database and generates SQL.

Manual Migrationโ€‹

yarn typeorm migration:create -n CustomMigration

Migration File Structureโ€‹

import { MigrationInterface, QueryRunner } from "typeorm";

export class AddEmployeePhoneColumn1709635260000 implements MigrationInterface {
name = "AddEmployeePhoneColumn1709635260000";

public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`
ALTER TABLE "employee"
ADD COLUMN "phoneNumber" varchar(20)
`);
}

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

Running Migrationsโ€‹

# Run pending migrations
yarn typeorm migration:run

# Revert last migration
yarn typeorm migration:revert

# Show migration status
yarn typeorm migration:show

Best Practicesโ€‹

PracticeDescription
Always write down()Enable rollback
Test on staging firstVerify before production
Backup before migrationSafety net
Use transactionsAtomic changes
No data lossAdd columns as nullable first
Sequential namingTimestamps in filenames

Migration Directoryโ€‹

packages/core/src/database/migrations/
โ”œโ”€โ”€ 1700000000001-InitialSchema.ts
โ”œโ”€โ”€ 1700000000002-AddTimeTracking.ts
โ””โ”€โ”€ 1700000000003-AddCRMTables.ts