import { MigrationInterface, QueryRunner } from 'typeorm'; /** * TypeORM 迁移:移除 not_working 工作状态 * * 此迁移执行以下操作: * 1. 将所有 order_person 表中 work_status = 'not_working' 的记录更新为 'pre_working' * 2. 重建数据库枚举类型 order_person_work_status_enum,移除 'not_working' 值 * * 迁移原因: * - Story 13.29 已从代码中移除 not_working 状态 * - 数据库中仍有 65 条记录使用此状态 * - 需要保持数据库与代码一致 * * 回滚支持: * - down() 方法会重新添加 not_working 值到枚举中 */ export class MigrateNotWorkingToPreWorking1737260000000 implements MigrationInterface { name = 'MigrateNotWorkingToPreWorking1737260000000'; public async up(queryRunner: QueryRunner): Promise { // 步骤 1: 更新数据 - 将所有 not_working 改为 pre_working await queryRunner.query(` UPDATE order_person SET work_status = 'pre_working' WHERE work_status = 'not_working' `); console.debug('Migration: Updated records from not_working to pre_working'); // 步骤 2: 重建枚举类型(PostgreSQL 不支持直接删除枚举值) // 2.1 先移除 DEFAULT 约束(因为默认值引用了旧枚举类型) await queryRunner.query(` ALTER TABLE order_person ALTER COLUMN work_status DROP DEFAULT `); // 2.2 重命名旧枚举 await queryRunner.query(` ALTER TYPE order_person_work_status_enum RENAME TO order_person_work_status_enum_old `); // 2.3 创建新枚举(不包含 not_working) await queryRunner.query(` CREATE TYPE order_person_work_status_enum AS ENUM ('pre_working', 'working', 'resigned') `); // 2.4 修改列类型到新枚举(使用 USING 子句进行类型转换) await queryRunner.query(` ALTER TABLE order_person ALTER COLUMN work_status TYPE order_person_work_status_enum USING work_status::text::order_person_work_status_enum `); // 2.5 重新添加 DEFAULT 约束(使用新枚举类型和有效值) await queryRunner.query(` ALTER TABLE order_person ALTER COLUMN work_status SET DEFAULT 'pre_working' `); // 2.6 删除旧枚举类型 await queryRunner.query(` DROP TYPE order_person_work_status_enum_old `); console.debug('Migration: Successfully removed not_working from enum'); } public async down(queryRunner: QueryRunner): Promise { // 回滚:重新添加 not_working 值到枚举中 // 1. 先移除 DEFAULT 约束 await queryRunner.query(` ALTER TABLE order_person ALTER COLUMN work_status DROP DEFAULT `); // 2. 重命名当前枚举 await queryRunner.query(` ALTER TYPE order_person_work_status_enum RENAME TO order_person_work_status_enum_old `); // 3. 创建包含 not_working 的新枚举 await queryRunner.query(` CREATE TYPE order_person_work_status_enum AS ENUM ('not_working', 'pre_working', 'working', 'resigned') `); // 4. 修改列类型到新枚举 await queryRunner.query(` ALTER TABLE order_person ALTER COLUMN work_status TYPE order_person_work_status_enum USING work_status::text::order_person_work_status_enum `); // 5. 重新添加 DEFAULT 约束(使用 not_working 作为默认值) await queryRunner.query(` ALTER TABLE order_person ALTER COLUMN work_status SET DEFAULT 'not_working' `); // 6. 删除旧枚举类型 await queryRunner.query(` DROP TYPE order_person_work_status_enum_old `); console.debug('Migration rollback: Added not_working back to enum'); } }