Add unique constraint to JourneySegment for seat bookings per schedule

This commit is contained in:
Stephanos A
2026-07-16 21:10:02 +03:00
parent 3726ac8390
commit 17c0123161
2 changed files with 22 additions and 0 deletions

View File

@@ -0,0 +1,18 @@
-- Remove duplicate JourneySegment rows, keeping the one with the lowest id
-- (earliest created) per (scheduleId, seatId, departureStationId) group.
-- This cleans up any existing double-bookings before the unique index is applied.
DELETE FROM passenger."JourneySegment"
WHERE id NOT IN (
SELECT MIN(id)
FROM passenger."JourneySegment"
WHERE "seatId" IS NOT NULL
GROUP BY "scheduleId", "seatId", "departureStationId"
)
AND "seatId" IS NOT NULL;
-- Prevents two confirmed bookings from occupying the same seat on the same
-- schedule hop — the hard DB backstop against application-level race conditions.
-- Partial index: seatId IS NOT NULL excludes free-child rows that have no seat.
CREATE UNIQUE INDEX "JourneySegment_scheduleId_seatId_departureStationId_key"
ON passenger."JourneySegment" ("scheduleId", "seatId", "departureStationId")
WHERE "seatId" IS NOT NULL;

View File

@@ -991,6 +991,10 @@ model JourneySegment {
arrivalStationId String
journey Journey @relation(fields: [journeyId], references: [id])
schedule TrainSchedule @relation(fields: [scheduleId], references: [id])
// Prevents two confirmed bookings from occupying the same seat on the same
// schedule hop — the hard DB backstop against application-level race conditions.
@@unique([scheduleId, seatId, departureStationId])
@@schema("passenger")
}