Skip to content

Commit

Permalink
feat: database migration
Browse files Browse the repository at this point in the history
  • Loading branch information
zhenyuWang committed Nov 4, 2023
1 parent 5bc87cd commit 8187da0
Show file tree
Hide file tree
Showing 4 changed files with 59 additions and 0 deletions.
26 changes: 26 additions & 0 deletions ormconfig.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// TypeORM configuration file
// database migration

import { DataSource } from 'typeorm';

// 控制台执行 npx typeorm migration:create path-to-migrations-dir/migrationName
// 创建迁移文件
// npx typeorm migration:run -- -d path-to-datasource-config 进行迁移

// 这个迁移太坑了,暴露的对象必须是 DataSource 实例,而不能是 ormconfig.js 中的普通对象
// 因此执行命令是 npx typeorm-ts-node-commonjs migration:run -d ormconfig.ts

// 同理,revert 命令是: npx typeorm-ts-node-commonjs migration:revert -d ormconfig.ts
// px typeorm -ts-node-commonjs migration:generate src/migrations/SchemaSync -d ormconfig.ts

export default new DataSource({
migrationsTableName: 'migrations',
type: 'postgres',
host: 'localhost',
port: 5432,
username: 'postgres',
password: 'pass123',
database: 'postgres',
entities: ['src/**/**.entity{.ts,.js}'],
migrations: ['src/migrations/**/*{.ts,.js}'],
});
3 changes: 3 additions & 0 deletions src/coffees/entities/coffee.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@ export class Coffee {
@Column()
name: string;

@Column({ nullable: true })
description: string;

@Column()
brand: string;

Expand Down
15 changes: 15 additions & 0 deletions src/migrations/1699107959878-CoffeeRefactor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { MigrationInterface, QueryRunner } from 'typeorm';

export class CoffeeRefactor1699107959878 implements MigrationInterface {
public async up(queryRunner: QueryRunner): Promise<any> {
await queryRunner.query(
`ALTER TABLE "coffee" RENAME COLUMN "name" TO "title"`,
);
}

public async down(queryRunner: QueryRunner): Promise<any> {
await queryRunner.query(
`ALTER TABLE "coffee" RENAME COLUMN "title" TO "name"`,
);
}
}
15 changes: 15 additions & 0 deletions src/migrations/1699111223775-SchemaSync.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { MigrationInterface, QueryRunner } from 'typeorm';

export class SchemaSync1699111223775 implements MigrationInterface {
name = 'SchemaSync1699111223775';

public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`ALTER TABLE "coffee" ADD "description" character varying`,
);
}

public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`ALTER TABLE "coffee" DROP COLUMN "description"`);
}
}

0 comments on commit 8187da0

Please # to comment.