考慮下面的代碼:有沒有辦法在pgsql中捕獲延遲約束的異常?
drop table if exists demo cascade;
drop table if exists child cascade;
create table demo
(
id bigint not null
constraint demo_pk primary key
);
create table child
(
id bigint not null
constraint child_pk primary key,
pid bigint,
constraint child_pid_fk
foreign key (pid)
references demo (id)
deferrable initially deferred -- remove this line and exceptions get caught
);
insert into demo values (1);
insert into child values (11, 1);
do language plpgsql $$
begin
delete from demo where id = 1;
exception
when others then
raise notice 'exception caught';
end;
$$;
我想趕通過限制拋出的任何異常,但由於性能原因我推遲檢查的約束,直到提交(deferrable initially deferred
)。有沒有辦法在不啓用immediate
模式的情況下捕捉異常?
不,你不能,因爲根據定義,延遲約束直到你提交後纔會被檢查。您需要在運行SQL –
的代碼中處理異常您可以在觸發約束檢查的SQL上下文中嘗試在'DELETE'語句之後運行'SET CONSTRAINTS child_pid_fk IMMEDIATE;';但是我不確定在plpgsql上下文中是否也是如此。 - 編輯:只是看到你寫道,你尋求其他選擇。我不認爲有其他選擇。 – pozs
@pozs:我認爲你畢竟是在正確的軌道上。我認爲OP只是不想改變表定義,'SET CONSTRAINTS'是他需要的。 –