如何在 PostgreSQL 中创建条件外键?

Blu*_*gma 2 sql postgresql

我有下表

create table if not exists pgroup (
    id uuid primary key default gen_random_uuid(),
    label varchar not null,
    is_role boolean default false
);
Run Code Online (Sandbox Code Playgroud)

我想创建一个如下所示的表:

create table if not exists grouprole (
    groupId uuid not null references pgroup(id) `where is_role = false`,
    roleId uuid not null references pgroup(id) `where is_role = true`,
    primary key (groupId, roleId)
);
Run Code Online (Sandbox Code Playgroud)

这个想法是,如果一个是角色而另一个不是,则两个 pgroup 可以处于 grouprole 关系中。

我的目标是在插入时执行检查以确保。

编辑:

我不能在两个不同的表中拆分 pgroup,因为其他表引用它并且不关心 is_role 标志。

Ser*_*hov 5

尝试在CHECK约束中使用辅助函数:

create table if not exists pgroup (
    id int primary key,
    label varchar not null,
    is_role boolean default false
);

create table if not exists grouprole (
    groupId int not null references pgroup(id),
    roleId int not null references pgroup(id),
    primary key (groupId, roleId)
);

CREATE FUNCTION check_pgroup(p_id int,p_is_role boolean) RETURNS int AS $$
    SELECT id
    FROM pgroup
    WHERE id=p_id
      AND is_role=p_is_role
$$ LANGUAGE SQL;

alter table grouprole add check(check_pgroup(groupId,false) is not null);
alter table grouprole add check(check_pgroup(roleId,true) is not null);
Run Code Online (Sandbox Code Playgroud)

测试:

INSERT INTO pgroup(id,label,is_role)VALUES(1,'1',true);
INSERT INTO pgroup(id,label,is_role)VALUES(2,'2',false);

INSERT INTO grouprole(groupId,roleId)VALUES(1,2); -- Error
INSERT INTO grouprole(groupId,roleId)VALUES(2,1); -- OK
Run Code Online (Sandbox Code Playgroud)

您还可以创建交叉检查pggroup以防止将错误值设置为is_role

CREATE FUNCTION check_pgroup_is_role(p_id int,p_is_role boolean) RETURNS boolean AS $$
  SELECT true is_exists
  FROM grouprole
  WHERE ((p_is_role=true AND groupId=p_id) OR (p_is_role=false AND roleId=p_id))
$$ LANGUAGE SQL;

ALTER TABLE pgroup ADD CHECK(check_pgroup_is_role(id,is_role) IS NULL);
Run Code Online (Sandbox Code Playgroud)

测试:

UPDATE pgroup SET is_role=false; -- Error

INSERT INTO pgroup(id,label,is_role)VALUES(3,'3',true); -- OK
UPDATE pgroup SET is_role=false WHERE id=3; -- OK
Run Code Online (Sandbox Code Playgroud)

  • @BlueMagma:例如,请注意`UPDATE pgroup SET is_role=not is_role` 将使另一个表违反其约束,而不会发生任何错误。 (2认同)