| | 1 | = Database Programming |
| | 2 | == Prevention of double booking the same room |
| | 3 | {{{ |
| | 4 | create or replace function trg_prevent_double_booking() |
| | 5 | returns trigger |
| | 6 | as $$ |
| | 7 | begin |
| | 8 | if NEW.booking_status in ('PENDING','CONFIRMED') then |
| | 9 | if exists( |
| | 10 | select 1 |
| | 11 | from bookings b |
| | 12 | where b.room_id = NEW.room_id |
| | 13 | and b.booking_status in ('PENDING','CONFIRMED') |
| | 14 | and daterange(b.check_in_date, b.check_out_date, '[)') |
| | 15 | && daterange(NEW.check_in_date, NEW.check_out_date, '[)') |
| | 16 | )then |
| | 17 | raise exception 'Room % is already booked',NEW.room_id; |
| | 18 | end if; |
| | 19 | end if; |
| | 20 | return new; |
| | 21 | end; |
| | 22 | $$ language plpgsql; |
| | 23 | |
| | 24 | create trigger prevent_double_booking |
| | 25 | before insert on bookings for each row execute function trg_prevent_double_booking(); |
| | 26 | }}} |
| | 27 | == Validate the dates of a booking |
| | 28 | {{{ |
| | 29 | |
| | 30 | create or replace function trg_validate_booking_dates() |
| | 31 | returns trigger as $$ |
| | 32 | begin |
| | 33 | if new.check_in_date >= new.check_out_date then |
| | 34 | raise exception 'Check out date must be after check in date'; |
| | 35 | end if; |
| | 36 | if new.check_in_date < now() then |
| | 37 | raise exception 'Check in date cannot be in the past'; |
| | 38 | end if; |
| | 39 | return new; |
| | 40 | end; |
| | 41 | $$ language plpgsql; |
| | 42 | |
| | 43 | create trigger validate_booking_dates |
| | 44 | before insert or update on bookings for each row |
| | 45 | execute function trg_validate_booking_dates(); |
| | 46 | }}} |
| | 47 | == A review can be made only for a complete booking |
| | 48 | {{{ |
| | 49 | create or replace function trg_review_only_completed_booking() |
| | 50 | returns trigger |
| | 51 | as $$ |
| | 52 | declare v_status varchar; |
| | 53 | begin |
| | 54 | select booking_status |
| | 55 | into v_status |
| | 56 | from bookings |
| | 57 | where booking_id = new.booking_id; |
| | 58 | |
| | 59 | if v_status <> 'COMPLETED' then |
| | 60 | raise exception 'Can only review completed bookings'; |
| | 61 | end if; |
| | 62 | return new; |
| | 63 | end; |
| | 64 | $$ language plpgsql; |
| | 65 | |
| | 66 | create trigger review_only_completed_booking |
| | 67 | before insert or update on reviews for each row |
| | 68 | execute function trg_review_only_completed_booking(); |
| | 69 | }}} |