# TypeORM Migrations {#typeorm-migrations}


Create and manage database schema changes with TypeORM migrations.


## Overview {#overview}


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


## Creating a Migration {#creating-a-migration}



### Auto-Generate from Entity Changes {#auto-generate-from-entity-changes}


```bash
yarn typeorm migration:generate -n AddEmployeePhoneColumn
```

This compares current entities against the database and generates SQL.


### Manual Migration {#manual-migration}


```bash
yarn typeorm migration:create -n CustomMigration
```


## Migration File Structure {#migration-file-structure}


```typescript
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 {#running-migrations}


```bash
# Run pending migrations
yarn typeorm migration:run

# Revert last migration
yarn typeorm migration:revert

# Show migration status
yarn typeorm migration:show
```


## Best Practices {#best-practices}


| Practice                | Description                   |
| ----------------------- | ----------------------------- |
| Always write `down()`   | Enable rollback               |
| Test on staging first   | Verify before production      |
| Backup before migration | Safety net                    |
| Use transactions        | Atomic changes                |
| No data loss            | Add columns as nullable first |
| Sequential naming       | Timestamps in filenames       |


## Migration Directory {#migration-directory}


```
packages/core/src/database/migrations/
├── 1700000000001-InitialSchema.ts
├── 1700000000002-AddTimeTracking.ts
└── 1700000000003-AddCRMTables.ts
```


## Related Pages {#related-pages}


- [Database Schema](https://sourcey-gauzy.pages.dev/database/schema-overview/index.md) — schema overview
- [MikroORM Migrations](https://sourcey-gauzy.pages.dev/database/mikroorm-migrations/index.md) — MikroORM alternative
- [SQLite to PostgreSQL](https://sourcey-gauzy.pages.dev/migration/sqlite-to-postgresql/index.md) — DB migration
