DatabaseProgramming: CheckInTicket.sql

File CheckInTicket.sql, 2.4 KB (added by 231044, 6 days ago)
Line 
1create or replace procedure CheckIn(TicketID_P int) as $$
2declare
3 TicketStatusID_V int;
4 TicketFlightID int;
5 TicketSeatID int;
6 TicketSeatClassID int;
7 FlightDeparture timestamp;
8 ScheduledStatus int;
9 CheckedInStatus int;
10 BoardedStatus int;
11 NewSeatID int;
12begin
13 select id into strict ScheduledStatus
14 from ticketstatus where name = 'Scheduled';
15
16 select id into strict CheckedInStatus
17 from ticketstatus where name = 'Checked In';
18
19 select id into strict BoardedStatus
20 from ticketstatus where name = 'Boarded';
21
22 select t.ticketstatusid, t.flightid, t.seatid, t.seatclassid, f.departure
23 into TicketStatusID_V, TicketFlightID, TicketSeatID, TicketSeatClassID, FlightDeparture
24 from ticket t
25 join flight f on f.id = t.flightid
26 where t.id = TicketID_P
27 for update of t;
28
29 if not found then
30 raise exception 'Ticket not found!';
31 end if;
32
33 if TicketStatusID_V = CheckedInStatus then
34 raise exception 'Ticket already checked in!';
35 end if;
36
37 if TicketStatusID_V = BoardedStatus then
38 raise exception 'Ticket already boarded!';
39 end if;
40
41 if TicketStatusID_V <> ScheduledStatus then
42 raise exception 'Ticket is not in a check-in-eligible state!';
43 end if;
44
45 if exists (select 1 from canceledflight where flightid = TicketFlightID) then
46 raise exception 'Flight has been canceled!';
47 end if;
48
49 if FlightDeparture > now() + interval '8 hours' then
50 raise exception 'Check in not yet open!';
51 end if;
52
53 if FlightDeparture < now() + interval '45 minutes' then
54 raise exception 'Check in closed!';
55 end if;
56
57 if TicketSeatID is null then
58 select s.id
59 into NewSeatID
60 from seat s
61 join seatconfiguration sc on sc.id = s.seatconfigurationid
62 where s.flightid = TicketFlightID
63 and s.reserved = false
64 and sc.seatclassid = TicketSeatClassID
65 order by random()
66 limit 1
67 for update of s skip locked;
68
69 if NewSeatID is null then
70 raise exception 'No available seats matching the ticket class!';
71 end if;
72
73 update ticket
74 set seatid = NewSeatID
75 where id = TicketID_P;
76
77 update seat
78 set reserved = true
79 where id = NewSeatID;
80 end if;
81
82 update ticket
83 set ticketstatusid = CheckedInStatus
84 where id = TicketID_P;
85end;
86$$ language plpgsql;