| | 70 | == Only an available room can be booked |
| | 71 | {{{ |
| | 72 | |
| | 73 | create or replace function trg_room_is_available_for_booking() |
| | 74 | returns trigger |
| | 75 | as $$ |
| | 76 | begin |
| | 77 | if new.check_in_date > new.check_out_date then |
| | 78 | raise exception 'Booking start date cannot be after end date'; |
| | 79 | end if; |
| | 80 | |
| | 81 | |
| | 82 | if not exists( |
| | 83 | select 1 |
| | 84 | from rooms r |
| | 85 | where r.room_id = new.room_id |
| | 86 | and r.status = 'ACTIVE' |
| | 87 | )then |
| | 88 | raise exception 'Room is not active'; |
| | 89 | end if; |
| | 90 | |
| | 91 | if exists( |
| | 92 | select 1 |
| | 93 | from bookings b |
| | 94 | where b.room_id = new.room_id |
| | 95 | and b.booking_status in ('PENDING','CONFIRMED') |
| | 96 | and b.booking_id <> new.booking_id |
| | 97 | and ( |
| | 98 | (new.check_in_date,new.check_out_date) |
| | 99 | overlaps |
| | 100 | (b.check_in_date,b.check_out_date) |
| | 101 | ) |
| | 102 | )then |
| | 103 | raise exception 'Room is already booked'; |
| | 104 | end if; |
| | 105 | |
| | 106 | return new; |
| | 107 | |
| | 108 | end; |
| | 109 | $$ language plpgsql; |
| | 110 | create or replace trigger book_only_available_room |
| | 111 | before insert or update on bookings for each row |
| | 112 | execute function trg_room_is_available_for_booking(); |
| | 113 | }}} |