実際にデータベースに制約を設定する正しい方法はありませんか?それは厳密に何のためのものかと思われます。外部キー制約とnullでないものを追加すると、ビジネスに参加する必要があるように見えます。
禁断の
drop table foousers cascade;
drop table foogroups cascade;
drop table foousergrps cascade;
create table foousers (id int primary key, name text);
create table foogroups (id int primary key, name text);
create table foousergrps (user_id int unique references foousers not null, group_id int unique references foogroups not null);
alter table foogroups add foreign key (id) references foousergrps (group_id) deferrable initially deferred;
alter table foousers add foreign key (id) references foousergrps (user_id) deferrable initially deferred;
begin;
insert into foousers values (0, 'root');
insert into foousers values (1, 'daemon');
insert into foogroups values (0, 'wheel');
insert into foogroups values (1, 'daemon');
insert into foousergrps values (0,0);
insert into foousergrps values (1,1);
commit;
:(非遅延可能、BOO)チェック機能の
insert into foousers values (2, 'bad');
insert into foousergrps values (2,2);
例:
create table foousergrps (user_id int unique references foousers not null, group_id int not null);
create function fooorphangroupcheck(int) returns boolean as $$
declare
gid alias for $1;
begin
perform 1 from foousergrps where group_id = gid limit 1;
if NOT FOUND then return false;
end if;
return true;
end;
$$
LANGUAGE 'plpgsql';
alter table foogroups add check (fooorphangroupcheck(id));
私が知っています。このタイプのトリガーを使用して質問に記載されたシナリオを実行することはできません。それが私が間接的な方法を探していた理由です。あなたは一人知っていますか? –