Postgres 约束名称在单个表或整个模式中需要唯一吗?

Dev*_*ter 5 postgresql constraints exclude-constraint

我试图理解为什么一些 Postgres 约束可以在不同的表中命名相同,而有些则不能

这是一个简单的例子:

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 &&);
Run Code Online (Sandbox Code Playgroud)

my_constraint_1正如你所看到的,我可以在不同的表中 使用相同的名称在此输入图像描述

为什么名称my_constraint_1可以在不同的表中使用相同的名称,而my_constraint_2必须是唯一的,否则会出现错误 Errore SQL [42P07]: ERROR: relation "my_constraint_2" already exists

Luk*_*zda 3

为什么名称 my_constraint_1 在不同的表中可以使用相同的名称,而 my_constraint_2 必须是唯一的

约束2具有同名的基础索引,而约束1是表级别的简单检查约束。

EXCLUDE 排除约束是使用索引实现的,因此每个指定的运算符必须与索引访问方法index_method 的适当运算符类(参见第11.10 节)相关联。

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

db<>小提琴演示

  • @DevilingMaster 不,索引必须始终与约束具有相同的名称。 (3认同)