| 1 | create or replace procedure CancelFlight(
|
|---|
| 2 | FlightID_P int,
|
|---|
| 3 | CancellationReason text
|
|---|
| 4 | ) as $$
|
|---|
| 5 | declare
|
|---|
| 6 | FlightDeparture timestamp;
|
|---|
| 7 | CanceledFlightStatus int;
|
|---|
| 8 | CanceledTicketStatus int;
|
|---|
| 9 | begin
|
|---|
| 10 | select id into strict CanceledFlightStatus
|
|---|
| 11 | from flightstatus where name = 'Cancelled';
|
|---|
| 12 |
|
|---|
| 13 | select id into strict CanceledTicketStatus
|
|---|
| 14 | from ticketstatus where name = 'Canceled Flight';
|
|---|
| 15 |
|
|---|
| 16 | select departure
|
|---|
| 17 | into FlightDeparture
|
|---|
| 18 | from flight
|
|---|
| 19 | where id = FlightID_P
|
|---|
| 20 | for update;
|
|---|
| 21 |
|
|---|
| 22 | if not found then
|
|---|
| 23 | raise exception 'Flight does not exist!';
|
|---|
| 24 | end if;
|
|---|
| 25 |
|
|---|
| 26 | if exists (select 1 from canceledflight where flightid = FlightID_P) then
|
|---|
| 27 | raise exception 'Flight is already canceled!';
|
|---|
| 28 | end if;
|
|---|
| 29 |
|
|---|
| 30 | if FlightDeparture < now() + interval '30 minutes' then
|
|---|
| 31 | raise exception 'Flight has already departed (or is too close to departure)!';
|
|---|
| 32 | end if;
|
|---|
| 33 |
|
|---|
| 34 | update flight
|
|---|
| 35 | set statusid = CanceledFlightStatus
|
|---|
| 36 | where id = FlightID_P;
|
|---|
| 37 |
|
|---|
| 38 | insert into canceledflight (flightid, reason, cancellationtime)
|
|---|
| 39 | values (FlightID_P, CancellationReason, now());
|
|---|
| 40 |
|
|---|
| 41 | update ticket
|
|---|
| 42 | set ticketstatusid = CanceledTicketStatus
|
|---|
| 43 | where flightid = FlightID_P;
|
|---|
| 44 | end;
|
|---|
| 45 | $$ language plpgsql; |
|---|