| 1 | create or replace procedure SetSeat(
|
|---|
| 2 | TicketID_P int,
|
|---|
| 3 | SeatID_P int
|
|---|
| 4 | ) as $$
|
|---|
| 5 | declare
|
|---|
| 6 | TicketFlightID int;
|
|---|
| 7 | TicketSeatID int;
|
|---|
| 8 | TicketSeatClassID int;
|
|---|
| 9 | TicketStatusID_V int;
|
|---|
| 10 | SeatFlightID int;
|
|---|
| 11 | SeatReserved bool;
|
|---|
| 12 | SeatClassID_V int;
|
|---|
| 13 | BoardedStatus int;
|
|---|
| 14 | begin
|
|---|
| 15 | select id
|
|---|
| 16 | into strict BoardedStatus
|
|---|
| 17 | from ticketstatus
|
|---|
| 18 | where name = 'Boarded';
|
|---|
| 19 |
|
|---|
| 20 | select flightid, seatid, seatclassid, ticketstatusid
|
|---|
| 21 | into TicketFlightID, TicketSeatID, TicketSeatClassID, TicketStatusID_V
|
|---|
| 22 | from ticket
|
|---|
| 23 | where id = TicketID_P
|
|---|
| 24 | for update;
|
|---|
| 25 |
|
|---|
| 26 | if not found then
|
|---|
| 27 | raise exception 'Ticket not found!';
|
|---|
| 28 | end if;
|
|---|
| 29 |
|
|---|
| 30 | if TicketStatusID_V = BoardedStatus then
|
|---|
| 31 | raise exception 'Ticket is already boarded!';
|
|---|
| 32 | end if;
|
|---|
| 33 |
|
|---|
| 34 | if TicketSeatID = SeatID_P then
|
|---|
| 35 | raise exception 'Ticket already has that seat!';
|
|---|
| 36 | end if;
|
|---|
| 37 |
|
|---|
| 38 | select s.flightid, s.reserved, sc.seatclassid
|
|---|
| 39 | into SeatFlightID, SeatReserved, SeatClassID_V
|
|---|
| 40 | from seat s
|
|---|
| 41 | join seatconfiguration sc on sc.id = s.seatconfigurationid
|
|---|
| 42 | where s.id = SeatID_P
|
|---|
| 43 | for update of s;
|
|---|
| 44 |
|
|---|
| 45 | if not found then
|
|---|
| 46 | raise exception 'Seat not found!';
|
|---|
| 47 | end if;
|
|---|
| 48 |
|
|---|
| 49 | if SeatFlightID <> TicketFlightID then
|
|---|
| 50 | raise exception 'Seat is not on the ticket''s flight!';
|
|---|
| 51 | end if;
|
|---|
| 52 |
|
|---|
| 53 | if SeatReserved then
|
|---|
| 54 | raise exception 'Seat is already reserved!';
|
|---|
| 55 | end if;
|
|---|
| 56 |
|
|---|
| 57 | if SeatClassID_V <> TicketSeatClassID then
|
|---|
| 58 | raise exception 'Seat class does not match the ticket''s class!';
|
|---|
| 59 | end if;
|
|---|
| 60 |
|
|---|
| 61 | if TicketSeatID is not null then
|
|---|
| 62 | update seat
|
|---|
| 63 | set reserved = false
|
|---|
| 64 | where id = TicketSeatID;
|
|---|
| 65 | end if;
|
|---|
| 66 |
|
|---|
| 67 | update ticket
|
|---|
| 68 | set seatid = SeatID_P
|
|---|
| 69 | where id = TicketID_P;
|
|---|
| 70 |
|
|---|
| 71 | update seat
|
|---|
| 72 | set reserved = true
|
|---|
| 73 | where id = SeatID_P;
|
|---|
| 74 | end;
|
|---|
| 75 | $$ language plpgsql; |
|---|