PostgreSql 9.2 Reservation table is defined as
CREATE EXTENSION btree_gist;
CREATE TABLE schedule (
id serial primary key,
during tsrange not null,
EXCLUDE USING gist (during WITH &&)
);
Holidays are listed in table
CREATE TABLE holiday ( day primary key );
Work hours are from 8 to 18:00 in work days and reservatons can be done by 30 minute intervals only. How to add constraints to during values so that it allows only reservations during work time:
- Start and end dates in tsrange are always same.
- Start and end dates cannot be saturday and sunday
- Start and end dates cannot appear in public holiday table
- Start time can be only 8:00 , 8:30, 9:00, 9:30, ... 16:00, 16:30, 17:00 or 17:30 inclusive
- End time can be only 8:30, 9:00, 9:30, ... 16:00, 16:30, 17:00, 17:30 or 18:00 exclusive
Is it reasonable to add those or some of those constraints to this table ? If yes, how to add ? schedule table structure can changed if this helps.
You can solve everything except item 3. with plain
CHECK
constraints:Use dedicated range functions
lower(anysrange)
andupper(anyrange)
to access lower / upper border of the range.1.) Start and end dates in tsrange are always same.
2.) Start and end dates cannot be saturday and sunday
Use
isodow
, notdow
for a simpler expression.3.) Start and end dates cannot appear in public holiday table
The only exception: for this you'd need a trigger like:
4.) Start time can be only 8:00 , 8:30, 9:00, 9:30, ... 16:00, 16:30, 17:00 or 17:30 inclusive
5.) End time can be only 8:30, 9:00, 9:30, ... 16:00, 16:30, 17:00, 17:30 or 18:00 exclusive
Additional question in comment
Simplest way: Cast to
timestamp(0)
ortimestamptz(0)
or use this data type for the column to begin with. I quote the manual here:You need to change you table definition and add some
check
constraints:The checks are in this order
We need something in
holiday
table: insert into holiday values ('2012-11-28');check
can not reference other table hence we need trigger function (it might be better to put all check into this function i.e. have them at one place):Then we need to create triggers before
insert
/update
:Finally, some tests: