diff --git a/apps/edr-freight-api/src/migrations/1791000000004-AddFacilityIdToWarehousesFix.ts b/apps/edr-freight-api/src/migrations/1791000000004-AddFacilityIdToWarehousesFix.ts new file mode 100644 index 000000000..df239a375 --- /dev/null +++ b/apps/edr-freight-api/src/migrations/1791000000004-AddFacilityIdToWarehousesFix.ts @@ -0,0 +1,52 @@ +import { MigrationInterface, QueryRunner, TableColumn, TableForeignKey } from 'typeorm'; + +/** + * Fix: migration 1750000000001 (AddFacilityIdToWarehouses) silently skipped because + * the freight.warehouses table didn't exist yet at that timestamp. The column was + * never added. Add it now with idempotent guards. + */ +export class AddFacilityIdToWarehousesFix1791000000004 implements MigrationInterface { + private readonly table = 'freight.warehouses'; + + public async up(queryRunner: QueryRunner): Promise { + if (!(await queryRunner.hasColumn(this.table, 'facility_id'))) { + await queryRunner.addColumn( + this.table, + new TableColumn({ + name: 'facility_id', + type: 'uuid', + isNullable: true, + }), + ); + } + + const table = await queryRunner.getTable(this.table); + const hasFk = table?.foreignKeys.some((fk) => fk.columnNames.includes('facility_id')); + if (!hasFk) { + await queryRunner.createForeignKey( + this.table, + new TableForeignKey({ + columnNames: ['facility_id'], + referencedColumnNames: ['id'], + referencedTableName: 'facilities', + referencedSchema: 'freight', + onDelete: 'SET NULL', + }), + ); + } + } + + public async down(queryRunner: QueryRunner): Promise { + const table = await queryRunner.getTable(this.table); + if (!table) return; + + const foreignKey = table.foreignKeys.find((fk) => fk.columnNames.includes('facility_id')); + if (foreignKey) { + await queryRunner.dropForeignKey(this.table, foreignKey); + } + + if (await queryRunner.hasColumn(this.table, 'facility_id')) { + await queryRunner.dropColumn(this.table, 'facility_id'); + } + } +}