使用函数和检查约束或约束触发器到多个表的外键?

时间:2019-04-23 12:20:44

标签: postgresql

我有一个简单的问题。请不要问为什么。

我有两个表data1和data2。它们都有主键ID列。每个表中的值都保证在两个表中都是唯一的。这是由检查约束强制执行的。

我有第三个表(data3),该表的一列应仅包含data1.id或data2.id中存在的值。我不能使用常规外键来强制执行此操作。因此,我编写了一个通过检查约束来执行此操作的函数。

是否有使用触发约束来执行此操作的更好方法?

drop schema if exists test cascade;
create schema test;

CREATE FUNCTION test.right_bit_shift()
    RETURNS bigint IMMUTABLE LANGUAGE SQL AS
'SELECT 2::bigint';

create or replace function test.ufn_get_type_id(id bigint) returns bigint as $$
select id >> 2;
$$ language sql
;

create table test.data1(name text);
alter table test.data1 add column id bigint primary key constraint id_chk check(test.ufn_get_type_id(id) =1) no inherit ;

create table test.data2(name text);
alter table test.data2 add column id bigint primary key constraint id_chk check(test.ufn_get_type_id(id) =0) no inherit ;

insert into test.data1(id, name) values(5,'101');
insert into test.data2(id, name) values(1,'001');

create table test.table_lookup(type_id bigint, table_name text);

insert into test.table_lookup(type_id, table_name)
values
(1, 'test.data1'),
(0, 'test.data2');    


create or replace function test.ufn_get_existence_sql(_id bigint) returns text as $$
    select
            'select exists(select 1 from '||table_name||' where id = '||_id||');'
    from test.table_lookup where type_id = test.ufn_get_type_id(_id);
    $$
language sql;


create or replace function test.ufn_id_exists (id_to_check bigint) returns boolean as $$
    declare res bool;
begin
    execute test.ufn_get_existence_sql(id_to_check) into res;
    return res;
end;
$$
    language plpgsql;

create table test.data3(name text, fk_id bigint constraint fk_id check ( test.ufn_id_exists(fk_id) ));

2 个答案:

答案 0 :(得分:0)

您绝对可以使用触发器来执行此操作。定义一个触发器,该触发器在对表data3进行插入或更新之前触发,并检查data1.id或data2.id中是否存在data3中的引用列。如果没有,您可以提出例外。

一种更简单的方法是使用与引用表一样多的列和尽可能多的外键添加外来约束。在表3中,您可以添加对data2.id具有外键引用的data2_id列,以及对data3.id具有外键引用的另一列data3_id。这些列必须为空,因为data2_id不为空,而data3_id为空。

答案 1 :(得分:0)

所以我找到了

https://dba.stackexchange.com/questions/75613/disable-all-constraints-and-table-checks-while-restoring-a-dump/75635#75635

它指出检查约束应该是不可变的,而我的检查约束当然不是。可能会导致恢复转储等问题。

因此,似乎最好的方法是插入和更新触发器。

相关问题