Skip to Content
BackendNestJs38-Migrations

1. Migration

  • Migration은 데이터베이스 변경사항을 스크립트로 작성해서 반영한다.
    • 통제된 상황에서 데이터베이스 스키마 변경 및 복구를 진행할 수 있다.
  • Migration이 필요한 이유: 왜 sync 옵션으론 부족한가?
    • Controlled Changes : 원하는 상황에 원하는 형태로 마이그레이션을 자유롭게 실행 할 수 있다
    • Reversible : 진행한 마이그레이션을 쉽게 되돌릴 수 있다.
    • Versioning : 마이그레이션은 스키마 변경에 대한 히스토리를 담고 있다. 디버깅에 매우 유용하다.
    • Consistency : 다양한 환경에서 데이터베이스 스키마가 같게 유지되도록 할 수 있다.
    • Complex Changes : 복잡한 데이터베이스의 변화를 직접 컨트롤 할 수 있다.

2. Migration 파일

shellscript
1
Migration1
2
Migration2 # <------------- Database1
3
Migration3 ## Migration 적용
4
Migration4 ## Migration 적용
5
Migration5 ## Migration 적용
6
Migration6 ## Migration 적용

3. Migration Configuration : ormconfig.json

json
1
{
2
"type": "postgres",
3
"host": "localhost",
4
"port": 5432,
5
"username": "test",
6
"password": "test",
7
"database": "test",
8
"entities": ["src/entities/**/*.ts"],
9
"migrations": ["src/migrations/**/*.ts"], // Migration 파일 경로
10
"cli": {
11
"entitiesDir": "src/entity",
12
"migrationsDir": "src/migrations"
13
}
14
}

4. Migration 테이블 생성

4.1 RAW SQL

typescript
1
import { MigrationInterface, QueryRunner } from 'typeorm'
2
3
export class CreateMovieAndDirectorTables1634567890123 implements MigrationInterface {
4
public async up(queryRunner: QueryRunner): Promise<void> {
5
await queryRunner.query(`
6
CREATE TABLE "director" (
7
"id" SERIAL NOT NULL,
8
"name" VARCHAR NOT NULL,
9
"dob" DATE,
10
"nationality" VARCHAR,
11
PRIMARY KEY ("id")
12
)
13
`)
14
await queryRunner.query(`
15
CREATE TABLE "movie" (
16
"id" SERIAL NOT NULL,
17
"title" VARCHAR NOT NULL,
18
"genre" VARCHAR,
19
"directorId" INTEGER,
20
PRIMARY KEY ("id"),
21
FOREIGN KEY ("directorId") REFERENCES "director" ("id") ON DELETE SET NULL
22
)
23
`)
24
}
25
26
public async down(queryRunner: QueryRunner): Promise<void> {
27
await queryRunner.query(`DROP TABLE "movie"`)
28
await queryRunner.query(`DROP TABLE "director"`)
29
}
30
}

4.2 Migration API

typescript
1
import { MigrationInterface, QueryRunner, Table, TableForeignKey } from 'typeorm'
2
3
export class CreateMovieAndDirectorTables1634567890123 implements MigrationInterface {
4
public async up(queryRunner: QueryRunner): Promise<void> {
5
/// ...생략
6
await queryRunner.createTable(
7
new Table({
8
name: 'movie',
9
columns: [
10
{ name: 'id', type: 'int', isPrimary: true, isGenerated: true, generationStrategy: 'increment' },
11
{ name: 'title', type: 'varchar' },
12
{ name: 'genre', type: 'varchar', isNullable: true },
13
{ name: 'directorId', type: 'int', isNullable: true },
14
],
15
}),
16
true,
17
)
18
await queryRunner.createForeignKey(
19
'movie',
20
new TableForeignKey({
21
columnNames: ['directorId'],
22
referencedColumnNames: ['id'],
23
referencedTableName: 'director',
24
onDelete: 'SET NULL',
25
}),
26
)
27
}
28
29
public async down(queryRunner: QueryRunner): Promise<void> {
30
await queryRunner.dropTable('movie')
31
await queryRunner.dropTable('director')
32
}
33
}

5. Migration 칼럼 추가

5.1 RAW SQL

typescript
1
import { MigrationInterface, QueryRunner } from 'typeorm'
2
3
export class AddDirectorBioColumn1634567890123 implements MigrationInterface {
4
public async up(queryRunner: QueryRunner): Promise<void> {
5
await queryRunner.query(`
6
ALTER TABLE "director"
7
ADD "dateOfBirth" DATE
8
`)
9
}
10
11
public async down(queryRunner: QueryRunner): Promise<void> {
12
await queryRunner.query(`
13
ALTER TABLE "director"
14
DROP COLUMN "dateOfBirth"
15
`)
16
}
17
}

5.2 Migration API

typescript
1
import { MigrationInterface, QueryRunner, TableColumn } from 'typeorm'
2
3
export class AddDateOfBirthColumn1634567890124 implements MigrationInterface {
4
public async up(queryRunner: QueryRunner): Promise<void> {
5
await queryRunner.addColumn(
6
'director',
7
new TableColumn({
8
name: 'dateOfBirth',
9
type: 'date',
10
isNullable: true,
11
}),
12
)
13
}
14
15
public async down(queryRunner: QueryRunner): Promise<void> {
16
await queryRunner.dropColumn('director', 'dateOfBirth')
17
}
18
}

6. Migration 칼럼 이름 변경

6.1 RAW SQL

typescript
1
import { MigrationInterface, QueryRunner } from 'typeorm'
2
3
export class RenameNameToFullName1634567890125 implements MigrationInterface {
4
public async up(queryRunner: QueryRunner): Promise<void> {
5
await queryRunner.query(`
6
ALTER TABLE "director"
7
RENAME COLUMN "name" TO "fullName"
8
`)
9
}
10
11
public async down(queryRunner: QueryRunner): Promise<void> {
12
await queryRunner.query(`
13
ALTER TABLE "director"
14
RENAME COLUMN "fullName" TO "name"
15
`)
16
}
17
}

6.2 Migration API

typescript
1
import { MigrationInterface, QueryRunner } from 'typeorm'
2
3
export class RenameNameToFullNameInDirector1634567890125 implements MigrationInterface {
4
public async up(queryRunner: QueryRunner): Promise<void> {
5
await queryRunner.renameColumn('director', 'name', 'fullName')
6
}
7
8
public async down(queryRunner: QueryRunner): Promise<void> {
9
await queryRunner.renameColumn('director', 'fullName', 'name')
10
}
11
}

7. Migration 칼럼 타입 변경

7.1 RAW SQL

typescript
1
import { MigrationInterface, QueryRunner } from 'typeorm'
2
3
export class ChangeEmailTypeInDirector1634567890126 implements MigrationInterface {
4
public async up(queryRunner: QueryRunner): Promise<void> {
5
await queryRunner.query(`
6
ALTER TABLE "director"
7
ALTER COLUMN "email" TYPE TEXT
8
`)
9
}
10
11
public async down(queryRunner: QueryRunner): Promise<void> {
12
await queryRunner.query(`
13
ALTER TABLE "director"
14
ALTER COLUMN "email" TYPE VARCHAR
15
`)
16
}
17
}

7.2 Migration API

typescript
1
import { MigrationInterface, QueryRunner, TableColumn } from 'typeorm'
2
3
export class ChangeEmailTypeInDirector1634567890126 implements MigrationInterface {
4
public async up(queryRunner: QueryRunner): Promise<void> {
5
await queryRunner.changeColumn(
6
'director',
7
'email',
8
new TableColumn({
9
name: 'email',
10
type: 'text',
11
}),
12
)
13
}
14
15
public async down(queryRunner: QueryRunner): Promise<void> {
16
await queryRunner.changeColumn(
17
'director',
18
'email',
19
new TableColumn({
20
name: 'email',
21
type: 'varchar',
22
}),
23
)
24
}
25
}

8. Migration : Relationship 작업

8.1 RAW SQL

typescript
1
import { MigrationInterface, QueryRunner } from 'typeorm'
2
3
export class CreateGenreAndMovieGenreTables1634567890127 implements MigrationInterface {
4
public async up(queryRunner: QueryRunner): Promise<void> {
5
await queryRunner.query(`
6
CREATE TABLE "genre" (
7
"id" SERIAL NOT NULL,
8
"name" VARCHAR NOT NULL,
9
PRIMARY KEY ("id")
10
)
11
`)
12
await queryRunner.query(`
13
CREATE TABLE "movie_genre" (
14
"movieId" INTEGER NOT NULL,
15
"genreId" INTEGER NOT NULL,
16
PRIMARY KEY ("movieId", "genreId"),
17
FOREIGN KEY ("movieId") REFERENCES "movie" ("id") ON DELETE CASCADE,
18
FOREIGN KEY ("genreId") REFERENCES "genre" ("id") ON DELETE CASCADE
19
)
20
`)
21
}
22
23
public async down(queryRunner: QueryRunner): Promise<void> {
24
await queryRunner.query(`DROP TABLE "movie_genres_genre"`)
25
await queryRunner.query(`DROP TABLE "genre"`)
26
}
27
}

8.2 Migration API

typescript
1
import { MigrationInterface, QueryRunner, Table, TableForeignKey } from 'typeorm'
2
3
export class CreateGenreAndMovieGenreTables1634567890127 implements MigrationInterface {
4
public async up(queryRunner: QueryRunner): Promise<void> {
5
await queryRunner.createTable(
6
new Table({
7
name: 'genre',
8
columns: [
9
{ name: 'id', type: 'int', isPrimary: true, isGenerated: true, generationStrategy: 'increment' },
10
{ name: 'name', type: 'varchar' },
11
],
12
}),
13
true,
14
)
15
//... 생략
16
}
17
18
public async down(queryRunner: QueryRunner): Promise<void> {
19
await queryRunner.dropTable('movie_genres_genre')
20
await queryRunner.dropTable('genre')
21
}
22
}

9. Migration CLI 커맨드

shellscript
1
# Migration 파일 생성
2
npx typeorm migration:generate -n <MigrationName>
3
4
# Migration 실행
5
npx typeorm migration:run
6
7
# Migration 되돌리기
8
npx typeorm migration:revert