我有下表:
create table booking (
identifier integer not null primary key,
room uuid not null,
start_time time without time zone not null,
end_time time without time zone not null
);
我想创建一个exclude constraint
来强制同一个房间没有重叠的约会。
我尝试了以下内容:
alter table booking add constraint overlapping_times
exclude using gist
(
cast(room as text) with =,
period(start_time, end_time) with &&)
);
这有两个问题:
将room
投放到text
是不够的,它会:ERROR: data type text has no default operator class for access method "gist"
。我知道在v10中有btree_gist
,但我使用的是v9.5和v9.6,因此我必须手动将uuid
转换为text
afaik。
period(...)
错误,但我不知道如何构建time without time zone
类型的范围。
答案 0 :(得分:2)
在installing btree_gist之后,您可以执行以下操作:
create type timerange as range (subtype = time);
alter table booking add constraint overlapping_times
exclude using gist
(
(room::text) with =,
timerange(start_time, end_time) with &&
);
如果您想在约束中使用表达式,则需要将其放入括号中。因此,(room::text)
或(cast(room as text))