|
| 1 | +# TypeORM을 이용한 DB Migration |
| 2 | + |
| 3 | +## typerom-config.service.ts |
| 4 | + |
| 5 | +```typescript |
| 6 | +import { Injectable } from '@nestjs/common'; |
| 7 | +import { ConfigService } from '@nestjs/config'; |
| 8 | +import { TypeOrmModuleOptions, TypeOrmOptionsFactory } from '@nestjs/typeorm'; |
| 9 | +import { Collection } from '../collections/entities/collection.entity'; |
| 10 | +import { NestedContent } from '../collections/entities/nested-content.entity'; |
| 11 | +import { Category } from '../contents/entities/category.entity'; |
| 12 | +import { Content } from '../contents/entities/content.entity'; |
| 13 | +import { User } from '../users/entities/user.entity'; |
| 14 | + |
| 15 | +@Injectable() |
| 16 | +export class TypeOrmConfigService implements TypeOrmOptionsFactory { |
| 17 | + constructor(private configService: ConfigService) {} |
| 18 | + |
| 19 | + createTypeOrmOptions(): TypeOrmModuleOptions { |
| 20 | + return { |
| 21 | + type: 'postgres', |
| 22 | + ...(this.configService.get('POSTGRES_DB') |
| 23 | + ? { |
| 24 | + host: this.configService.get('POSTGRES_DB'), |
| 25 | + port: +this.configService.get('DB_PORT'), |
| 26 | + username: this.configService.get('POSTGRES_USER'), |
| 27 | + password: this.configService.get('POSTGRES_PASSWORD'), |
| 28 | + database: this.configService.get('POSTGRES_DB_NAME'), |
| 29 | + } |
| 30 | + : { |
| 31 | + host: this.configService.get('DB_HOST'), |
| 32 | + port: +this.configService.get('DB_PORT'), |
| 33 | + username: this.configService.get('DB_USERNAME'), |
| 34 | + password: this.configService.get('DB_PW'), |
| 35 | + database: this.configService.get('DB_NAME'), |
| 36 | + }), |
| 37 | + maxQueryExecutionTime: 10000, // If query execution time exceed this given max execution time (in milliseconds) then logger will log this query. |
| 38 | + extra: { |
| 39 | + statement_timeout: 10000, // timeout in milliseconds |
| 40 | + }, |
| 41 | + synchronize: this.configService.get('NODE_ENV') !== 'prod', |
| 42 | + logging: |
| 43 | + this.configService.get('NODE_ENV') !== 'prod' && |
| 44 | + this.configService.get('NODE_ENV') !== 'test', |
| 45 | + entities: [User, Content, Category, Collection, NestedContent], |
| 46 | + migrations: [__dirname + '/migrations/**/*{.ts,.js}'], |
| 47 | + } as TypeOrmModuleOptions; |
| 48 | + } |
| 49 | +} |
| 50 | +``` |
| 51 | + |
| 52 | +기본적인 typeorm 설정 |
| 53 | + |
| 54 | +## ormconfig(data source) |
| 55 | + |
| 56 | +```typescript |
| 57 | +import { DataSource, DataSourceOptions } from 'typeorm'; |
| 58 | +import * as dotenv from 'dotenv'; |
| 59 | + |
| 60 | +dotenv.config({ path: __dirname + '/../../.env.dev' }); |
| 61 | + |
| 62 | +export const AppDataSource = new DataSource({ |
| 63 | + type: 'postgres', |
| 64 | + ...(process.env.POSTGRES_DB |
| 65 | + ? { |
| 66 | + host: process.env.POSTGRES_DB, |
| 67 | + port: +process.env.DB_PORT, |
| 68 | + username: process.env.POSTGRES_USER, |
| 69 | + password: process.env.POSTGRES_PASSWORD, |
| 70 | + database: process.env.POSTGRES_DB_NAME, |
| 71 | + } |
| 72 | + : { |
| 73 | + host: process.env.DB_HOST, |
| 74 | + port: +process.env.DB_PORT, |
| 75 | + username: process.env.DB_USERNAME, |
| 76 | + password: process.env.DB_PW, |
| 77 | + database: process.env.DB_NAME, |
| 78 | + }), |
| 79 | + maxQueryExecutionTime: 10000, // If query execution time exceed this given max execution time (in milliseconds) then logger will log this query. |
| 80 | + extra: { |
| 81 | + statement_timeout: 10000, // timeout in milliseconds |
| 82 | + }, |
| 83 | + synchronize: false, |
| 84 | + logging: process.env.NODE_ENV !== 'prod' && process.env.NODE_ENV !== 'test', |
| 85 | + entities: [__dirname + '/../**/*.entity{.ts,.js}'], |
| 86 | + migrations: [__dirname + '/migrations/**/*{.ts,.js}'], |
| 87 | + cli: { |
| 88 | + entitiesDir: 'src/**/**', |
| 89 | + migrationsDir: 'src/database/migrations', |
| 90 | + }, |
| 91 | +} as DataSourceOptions); |
| 92 | +``` |
| 93 | + |
| 94 | +typeorm cli를 사용하기 위한 설정 |
| 95 | + |
| 96 | +## package.json |
| 97 | + |
| 98 | +```json |
| 99 | +{ |
| 100 | + ... |
| 101 | + "scripts": { |
| 102 | + ... |
| 103 | + "typeorm": "typeorm-ts-node-commonjs", |
| 104 | + "migration:generate": "npm run typeorm -- -d src/database/ormconfig.ts migration:generate", |
| 105 | + "migration:create": "npm run typeorm -- migration:create", |
| 106 | + "migration:run": "npm run typeorm -- -d src/database/ormconfig.ts migration:run" |
| 107 | + }, |
| 108 | + ... |
| 109 | +``` |
| 110 | + |
| 111 | +script를 통해 typeorm cli를 사용할 수 있도록 설정 |
| 112 | + |
| 113 | +<br/> |
| 114 | + |
| 115 | +# 주의점 |
| 116 | + |
| 117 | +## generate |
| 118 | + |
| 119 | +create랑 generate 모두 마이그레이션 파일을 생성하지만 둘 사이에는 큰 차이가 있다. |
| 120 | +create는 그냥 빈 파일만을 생성시켜 줄 뿐이지만 |
| 121 | +generate는 db와 entity 사이의 차이점이 있다면 이를 파악하고 sql구문을 작성한다. |
| 122 | +그러나 컬럼의 길이 또는 타입 변경 시 해당 테이블의 컬럼을 DROP한 후 재생성하는 방식이기 때문에 기존 컬럼에 있던 데이터가 모두 삭제된다. |
| 123 | + |
| 124 | +```bash |
| 125 | +EX) |
| 126 | +npm run migration:generate src/database/migrations/migration_test |
| 127 | +``` |
0 commit comments