# Migrations — NestJS: Building Scalable Node.js APIs

Source: https://www.skillbyai.com/en/nestjs/nestjs-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.

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

## Manual migration

Write custom SQL migration for complex schema changes.

```typescript
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

**Quiz:** Why generate a migration instead of editing the database by hand?

- [ ] Migrations make queries faster
- [x] 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.
