Postgres - “没有时区的时间”范围并排除约束

时间:2017-11-05 09:46:26

标签: sql postgresql

我有下表:

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。

    < / LI>
  • period(...)错误,但我不知道如何构建time without time zone类型的范围。

1 个答案:

答案 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))