diff --git a/apps/edr-freight-api/src/migrations/1718549600000-FixOrphanedBookings.ts b/apps/edr-freight-api/src/migrations/1718549600000-FixOrphanedBookings.ts new file mode 100644 index 000000000..9599db72c --- /dev/null +++ b/apps/edr-freight-api/src/migrations/1718549600000-FixOrphanedBookings.ts @@ -0,0 +1,25 @@ +import { MigrationInterface, QueryRunner } from 'typeorm'; + +export class FixOrphanedBookings1718549600000 implements MigrationInterface { + public async up(queryRunner: QueryRunner): Promise { + // Delete orphaned bookings records with invalid origin_yard_id + await queryRunner.query(` + DELETE FROM "freight"."bookings" + WHERE "origin_yard_id" IS NOT NULL + AND "origin_yard_id" NOT IN (SELECT "id" FROM "freight"."yards") + `); + + // Also clean up destination_yard_id if it exists and has the same issue + await queryRunner.query(` + DELETE FROM "freight"."bookings" + WHERE "destination_yard_id" IS NOT NULL + AND "destination_yard_id" NOT IN (SELECT "id" FROM "freight"."yards") + `); + + console.log('✅ Deleted orphaned bookings records'); + } + + public async down(_queryRunner: QueryRunner): Promise { + // No rollback needed for data cleanup + } +}