diff --git a/apps/edr-freight-api/src/migrations/3080000000000-BackfillDireDawaMilestone.ts b/apps/edr-freight-api/src/migrations/3080000000000-BackfillDireDawaMilestone.ts index ee44e5971..78c44c0ce 100644 --- a/apps/edr-freight-api/src/migrations/3080000000000-BackfillDireDawaMilestone.ts +++ b/apps/edr-freight-api/src/migrations/3080000000000-BackfillDireDawaMilestone.ts @@ -41,9 +41,17 @@ export class BackfillDireDawaMilestone3080000000000 implements MigrationInterfac WHERE m.route_id = rt.id AND m.yard_id = dire AND m.deleted_at IS NULL) LOOP + -- Two-phase shift: uq_route_milestones_route_sequence isn't deferrable, + -- so a direct +1 UPDATE can collide mid-scan (seq 2 -> 3 while seq 3 still live). + -- Route through negative sequence_no first to avoid any interim collision. + -- Soft-deleted rows shift too: the constraint counts them, so a dead row + -- left at a target sequence would still collide. UPDATE freight.route_milestones - SET sequence_no = sequence_no + 1 - WHERE route_id = r.id AND deleted_at IS NULL AND sequence_no >= 2; + SET sequence_no = -sequence_no + WHERE route_id = r.id AND sequence_no >= 2; + UPDATE freight.route_milestones + SET sequence_no = -sequence_no + 1 + WHERE route_id = r.id AND sequence_no < 0; INSERT INTO freight.route_milestones (route_id, yard_id, sequence_no) VALUES (r.id, dire, 2); END LOOP;