TypeORM database migrations in NestJS apps

1.git clone https://github.com/nestjs/typescript-starter.git nestjs-typeorm-migration-demo2.cd nestjs-typeorm-migration-demo3.npm install4.npm install --save @nestjs/typeorm typeorm pg
[
{
"name": "default",
"type": "postgres",
"host": "localhost",
"port": 5432,
"username": <username>,
"password": <password>,
"database": "demo",
"entities": ["dist/**/*.entity{ .ts,.js}"],
"synchronize": false,
"migrations": ["dist/migrations/*{.ts,.js}"],
"migrationsTableName": "migrations_typeorm",
"migrationsRun": true
}
]
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AppController } from './app.controller';
import { AppService } from './app.service';
@Module({
imports: [TypeOrmModule.forRoot()],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';
@Entity()
export class Article {
@PrimaryGeneratedColumn()
id: number;
@Column()
title: string;
@Column()
content: string;
}
npx typeorm migration:create -n ArticleTable -d src/migrations
import { MigrationInterface, QueryRunner, Table } from 'typeorm';
export class ArticleTable1586653096209 implements MigrationInterface {
public async up(queryRunner: QueryRunner): Promise<any> {
await queryRunner.createTable(
new Table({
name: 'article',
columns: [
{
name: 'id',
type: 'int4',
isPrimary: true,
isGenerated: true,
generationStrategy: 'increment',
},
{
name: 'title',
type: 'varchar',
isNullable: false,
},
{
name: 'content',
type: 'varchar',
isNullable: false,
},
],
}),
false,
);
}
public async down(queryRunner: QueryRunner): Promise<any> {
queryRunner.query(`DROP TABLE article`);
}
}
1.npm run build
2.npm start
import { MigrationInterface, QueryRunner } from 'typeorm';
export class AddColToArticleTable1586666091775 implements MigrationInterface {
public async up(queryRunner: QueryRunner): Promise<any> {
queryRunner.query(`ALTER TABLE article ADD author VARCHAR(30)`);
}
public async down(queryRunner: QueryRunner): Promise<any> {
queryRunner.dropColumn('article', 'author');
}
}
1.npx typeorm migration:generate -n ArticleTable -d src/migrations
2.npm run build
3.npm run start
1.npm run build
2.npx typeorm migration:generate -n RenameColInArticleTable -d src/migrations
1.typeorm migration:run
2.typeorm migration:revert

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store