8.17.10. Constraints on Ranges

8.17.10. Constraints on Ranges

8.17.10.範圍上的約束

While UNIQUE is a natural constraint for scalar values, it is usually unsuitable for range types. Instead,an exclusion constraint is often more appropriate (see CREATE TABLE ... CONSTRAINT ...EXCLUDE). Exclusion constraints allow the specification of constraints such as “non-overlapping” on a range type. For example:

儘管UNIQUE是標量值的常用約束,但通常不適合範圍類型。 相反,排除約束通常更合適(請參閱 CREATE TABLE ... CONSTRAINT ... EXCLUDE)。 排除約束允許在範圍類型上指定約束,例如“不重疊”。 例如:

 

CREATE TABLE reservation (

during tsrange,

EXCLUDE USING GIST (during WITH &&)

);

That constraint will prevent any overlapping values from existing in the table at the same time:

該約束將防止表中的任何重疊值存在:

 

INSERT INTO reservation VALUES

('[2010-01-01 11:30, 2010-01-01 15:00)');

INSERT 0 1

INSERT INTO reservation VALUES

('[2010-01-01 14:45, 2010-01-01 15:45)');

ERROR: conflicting key value violates exclusion constraint "reservation_during_excl"

DETAIL: Key (during)=(["2010-01-01 14:45:00","2010-01-01 15:45:00")) conflicts

with existing key (during)=(["2010-01-01 11:30:00","2010-01-01 15:00:00")).

You can use the btree_gist extension to define exclusion constraints on plain scalar data types,which can then be combined with range exclusions for maximum flexibility. For example, after btree_gist is installed, the following constraint will reject overlapping ranges only if the meeting room numbers are equal:

可以使用btree_gist擴展來定義普通標量數據類型的排除約束,然後可以將其與範圍排除結合使用,以實現最大的靈活性。 例如,在安裝btree_gist之後,以下約束僅在會議室號相等時才拒絕重疊範圍:

 

CREATE EXTENSION btree_gist;

CREATE TABLE room_reservation (

room text,

during tsrange,

EXCLUDE USING GIST (room WITH =, during WITH &&)

);

INSERT INTO room_reservation VALUES

('123A', '[2010-01-01 14:00, 2010-01-01 15:00)');

INSERT 0 1

INSERT INTO room_reservation VALUES

('123A', '[2010-01-01 14:30, 2010-01-01 15:30)');

ERROR: conflicting key value violates exclusion constraint

"room_reservation_room_during_excl"

DETAIL: Key (room, during)=(123A, ["2010-01-01

14:30:00","2010-01-01 15:30:00")) conflicts

with existing key (room, during)=(123A, ["2010-01-01

14:00:00","2010-01-01 15:00:00")).

INSERT INTO room_reservation VALUES

('123B', '[2010-01-01 14:30, 2010-01-01 15:30)');

INSERT 0 1

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章