PostgreSQL check constraint for foreign key condition

前端 未结 4 1434
無奈伤痛
無奈伤痛 2020-12-13 10:45

I have a table of users eg:

create table \"user\" (
    id serial primary key,
    name text not null,
    superuser boolean not null default false
);
         


        
4条回答
  •  心在旅途
    2020-12-13 11:14

    This would work for INSERTS:

    create or replace function is_superuser(int) returns boolean as $$
    select exists (
        select 1
        from "user"
        where id   = $1
          and superuser = true
    );
    $$ language sql;
    

    And then a check contraint on the user_has_job table:

    create table user_has_job (
        user_id integer references "user"(id),
        job_id integer references job(id),
        constraint user_has_job_pk PRIMARY KEY (user_id, job_id),
        constraint chk_is_superuser check (is_superuser(user_id))
    );
    

    Works for inserts:

    postgres=# insert into "user" (name,superuser) values ('name1',false);
    INSERT 0 1
    postgres=# insert into "user" (name,superuser) values ('name2',true);
    INSERT 0 1
    
    postgres=# insert into job (description) values ('test');
    INSERT 0 1
    postgres=# insert into user_has_job (user_id,job_id) values (1,1);
    ERROR:  new row for relation "user_has_job" violates check constraint "chk_is_superuser"
    DETAIL:  Failing row contains (1, 1).
    postgres=# insert into user_has_job (user_id,job_id) values (2,1);
    INSERT 0 1
    

    However this is possible:

    postgres=# update "user" set superuser=false;
    UPDATE 2
    

    So if you allow updating users you need to create an update trigger on the users table to prevent that if the user has jobs.

提交回复
热议问题