简体   繁体   English

Postgres 约束名称需要在单个表或整个架构中是唯一的?

[英]Postgres constraint name need to be unique across single table or entire schema?

I'm trying to understand why some Postgres constraints can be named the same within different tables, and some don't我试图理解为什么一些 Postgres 约束可以在不同的表中命名相同,而有些则不能

Here a simple example:这里有一个简单的例子:

drop table if exists public.table_1;
drop table if exists public.table_2;

CREATE TABLE public.table_1 (
    id serial NOT NULL,
    date_start date NOT NULL,
    date_end date NULL
);

CREATE TABLE public.table_2 (
    id serial NOT NULL,
    date_start date NOT NULL,
    date_end date NULL
);


alter table public.table_1 add constraint my_constraint_1 check (date_start > now());
alter table public.table_2 add constraint my_constraint_1 check (date_start > now());


alter table public.table_1 add constraint my_constraint_2 EXCLUDE USING gist (daterange(date_start, coalesce(date_end, 'infinity'),  '[]') WITH &&);
alter table public.table_2 add constraint my_constraint_2 EXCLUDE USING gist (daterange(date_start, coalesce(date_end, 'infinity'),  '[]') WITH &&);

As you can see I can use the same name my_constraint_1 with different tables如您所见,我可以对不同的表使用相同的名称my_constraint_1 在此处输入图像描述

Why the name my_constraint_1 can be used as the same in different tables, while my_constraint_2 must be unique otherwise I get the error Errore SQL [42P07]: ERROR: relation "my_constraint_2" already exists ?为什么名称my_constraint_1可以在不同的表中使用相同的名称,而my_constraint_2必须是唯一的,否则我会收到错误Errore SQL [42P07]: ERROR: relation "my_constraint_2" already exists

Why the name my_constraint_1 can be used as the same in different tables, while my_constraint_2 must be unique为什么名称 my_constraint_1 可以在不同的表中使用相同的名称,而 my_constraint_2 必须是唯一的

Constraint 2 has underlying index with the same name, while constraint 1 is simple check contraint on table level.约束 2 具有同名的基础索引,而约束 1 是表级别的简单检查约束。

EXCLUDE Exclusion constraints are implemented using an index, so each specified operator must be associated with an appropriate operator class (see Section 11.10) for the index access method index_method. EXCLUDE排除约束是使用索引实现的,因此每个指定的运算符都必须与索引访问方法 index_method 的适当运算符 class(参见第 11.10 节)相关联。

CREATE INDEX my_constraint_2 ON public.table_1 USING gist (daterange(date_start, COALESCE(date_end, 'infinity'::date), '[]'::text))

db<>fiddle demo db<>小提琴演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM