diff --git a/ormconfig.ts b/ormconfig.ts new file mode 100644 index 0000000..6c1911c --- /dev/null +++ b/ormconfig.ts @@ -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}'], +}); diff --git a/src/coffees/entities/coffee.entity.ts b/src/coffees/entities/coffee.entity.ts index 64d274c..4c7638b 100644 --- a/src/coffees/entities/coffee.entity.ts +++ b/src/coffees/entities/coffee.entity.ts @@ -16,6 +16,9 @@ export class Coffee { @Column() name: string; + @Column({ nullable: true }) + description: string; + @Column() brand: string; diff --git a/src/migrations/1699107959878-CoffeeRefactor.ts b/src/migrations/1699107959878-CoffeeRefactor.ts new file mode 100644 index 0000000..971b84d --- /dev/null +++ b/src/migrations/1699107959878-CoffeeRefactor.ts @@ -0,0 +1,15 @@ +import { MigrationInterface, QueryRunner } from 'typeorm'; + +export class CoffeeRefactor1699107959878 implements MigrationInterface { + public async up(queryRunner: QueryRunner): Promise { + await queryRunner.query( + `ALTER TABLE "coffee" RENAME COLUMN "name" TO "title"`, + ); + } + + public async down(queryRunner: QueryRunner): Promise { + await queryRunner.query( + `ALTER TABLE "coffee" RENAME COLUMN "title" TO "name"`, + ); + } +} diff --git a/src/migrations/1699111223775-SchemaSync.ts b/src/migrations/1699111223775-SchemaSync.ts new file mode 100644 index 0000000..2c66dc8 --- /dev/null +++ b/src/migrations/1699111223775-SchemaSync.ts @@ -0,0 +1,15 @@ +import { MigrationInterface, QueryRunner } from 'typeorm'; + +export class SchemaSync1699111223775 implements MigrationInterface { + name = 'SchemaSync1699111223775'; + + public async up(queryRunner: QueryRunner): Promise { + await queryRunner.query( + `ALTER TABLE "coffee" ADD "description" character varying`, + ); + } + + public async down(queryRunner: QueryRunner): Promise { + await queryRunner.query(`ALTER TABLE "coffee" DROP COLUMN "description"`); + } +}