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

3
我有以下表格:
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
);

我想创建一个“排除约束”来强制确保同一房间没有重叠的约会。
我尝试了以下方法:
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

  • period(...)是错误的,但我不知道如何构建一个time without time zone类型的范围。

1个回答

4

安装 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))

谢谢,这个可行!在v10中,您可以删除那个转换,因为btree_gist支持uuid类型。 - Franz They
我没有意识到你可以构建自定义范围。太酷了! - Franz They

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接