Preventing adjacent/overlapping entries with EXCLUDE in PostgreSQL

前提是你 提交于 2019-11-26 18:59:48

Range types consist of a lower and an upper border, which can be included or excluded. The typical use case (and default for range types) is to include the lower and exclude the upper bound.

Excluding overlapping ranges seems clear. There is a nice code example in the manual

In addition, create another exclusion constraint employing the adjacent operator -|- to also exclude adjacent entries. Both must be based on GiST indexes as GIN is currently not supported for this.

To keep it clean, I'd enforce [) bounds (including lower and excluding upper) for all entries with a CHECK constraint using range functions:

CREATE TABLE tbl (
   tbl_id serial PRIMARY KEY
 , tsr tsrange
 , CONSTRAINT tsr_no_overlap  EXCLUDE USING gist (tsr WITH &&)
 , CONSTRAINT tsr_no_adjacent EXCLUDE USING gist (tsr WITH -|-)
 , CONSTRAINT tsr_enforce_bounds CHECK (lower_inc(tsr) AND NOT upper_inc(tsr))
);

db<>fiddle here
(Old SQL Fiddle)

Unfortunately, this creates two identical GiST indexes to implement both exclusion constraints, where one would suffice, logically. That seems to be a shortcoming of the current implementation (up to at least Postgres 11).

You can rewrite the exclude with the range type introduced in 9.2. Better yet, you could replace the two fields with a range. See "Constraints on Ranges" here, with an example that basically amounts to your use case:

http://www.postgresql.org/docs/current/static/rangetypes.html

The problem I am thinking I might have, though, is that this constraint is making the (incorrect) assumption that there are no time increments smaller than one second.

You're OK there, consider:

select 
  extract ('epoch' from now())
  , extract ('epoch' from now()::timestamp(0))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!