MigrateNotWorkingToPreWorking1737260000000.ts 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. import { MigrationInterface, QueryRunner } from 'typeorm';
  2. /**
  3. * TypeORM 迁移:移除 not_working 工作状态
  4. *
  5. * 此迁移执行以下操作:
  6. * 1. 将所有 order_person 表中 work_status = 'not_working' 的记录更新为 'pre_working'
  7. * 2. 重建数据库枚举类型 order_person_work_status_enum,移除 'not_working' 值
  8. *
  9. * 迁移原因:
  10. * - Story 13.29 已从代码中移除 not_working 状态
  11. * - 数据库中仍有 65 条记录使用此状态
  12. * - 需要保持数据库与代码一致
  13. *
  14. * 回滚支持:
  15. * - down() 方法会重新添加 not_working 值到枚举中
  16. */
  17. export class MigrateNotWorkingToPreWorking1737260000000 implements MigrationInterface {
  18. name = 'MigrateNotWorkingToPreWorking1737260000000';
  19. public async up(queryRunner: QueryRunner): Promise<void> {
  20. // 步骤 1: 更新数据 - 将所有 not_working 改为 pre_working
  21. await queryRunner.query(`
  22. UPDATE order_person
  23. SET work_status = 'pre_working'
  24. WHERE work_status = 'not_working'
  25. `);
  26. console.debug('Migration: Updated records from not_working to pre_working');
  27. // 步骤 2: 重建枚举类型(PostgreSQL 不支持直接删除枚举值)
  28. // 2.1 重命名旧枚举
  29. await queryRunner.query(`
  30. ALTER TYPE order_person_work_status_enum
  31. RENAME TO order_person_work_status_enum_old
  32. `);
  33. // 2.2 创建新枚举(不包含 not_working)
  34. await queryRunner.query(`
  35. CREATE TYPE order_person_work_status_enum AS ENUM
  36. ('pre_working', 'working', 'resigned')
  37. `);
  38. // 2.3 修改列类型到新枚举(使用 USING 子句进行类型转换)
  39. await queryRunner.query(`
  40. ALTER TABLE order_person
  41. ALTER COLUMN work_status
  42. TYPE order_person_work_status_enum
  43. USING work_status::text::order_person_work_status_enum
  44. `);
  45. // 2.4 删除旧枚举类型
  46. await queryRunner.query(`
  47. DROP TYPE order_person_work_status_enum_old
  48. `);
  49. console.debug('Migration: Successfully removed not_working from enum');
  50. }
  51. public async down(queryRunner: QueryRunner): Promise<void> {
  52. // 回滚:重新添加 not_working 值到枚举中
  53. // 1. 重命名当前枚举
  54. await queryRunner.query(`
  55. ALTER TYPE order_person_work_status_enum
  56. RENAME TO order_person_work_status_enum_old
  57. `);
  58. // 2. 创建包含 not_working 的新枚举
  59. await queryRunner.query(`
  60. CREATE TYPE order_person_work_status_enum AS ENUM
  61. ('not_working', 'pre_working', 'working', 'resigned')
  62. `);
  63. // 3. 修改列类型到新枚举
  64. await queryRunner.query(`
  65. ALTER TABLE order_person
  66. ALTER COLUMN work_status
  67. TYPE order_person_work_status_enum
  68. USING work_status::text::order_person_work_status_enum
  69. `);
  70. // 4. 删除旧枚举类型
  71. await queryRunner.query(`
  72. DROP TYPE order_person_work_status_enum_old
  73. `);
  74. console.debug('Migration rollback: Added not_working back to enum');
  75. }
  76. }