代码之家  ›  专栏  ›  技术社区  ›  Deviling Master

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

  •  1
  • Deviling Master  · 技术社区  · 4 年前

    我试图理解为什么有些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 &&);
    

    my_constraint_1 有不同的桌子 enter image description here

    为什么叫这个名字 我的约束条件1 可以在不同的表中使用相同的方法,而 my_constraint_2 必须是唯一的,否则我会出错 Errore SQL [42P07]: ERROR: relation "my_constraint_2" already exists

    1 回复  |  直到 4 年前
        1
  •  1
  •   Lukasz Szozda    4 年前

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

    EXCLUDE

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

    db<>fiddle demo