[英]PostgreSQL foreign key violation inside transaction
我有一個 function 里面有幾個查詢,如下所示:
CREATE OR REPLACE FUNCTION public.myfunction(winningid integer, losingid integer)
RETURNS void
LANGUAGE plpgsql
AS $function$
begin
update partecipants set id_be=winningId where id_be=losingId;
...
many other updates and deletes regarding other tables
...
delete from business_entity where id_be=losingId;
end;
$function$
;
參與者和business_entity之間有一個外鍵:
ALTER TABLE partecipants ADD CONSTRAINT partecipants_fk FOREIGN KEY (id_be) REFERENCES business_entity(id_be)
有時(如千分之一)此 function 掛起並出現錯誤:
error: update or delete on table "business_entity" violates foreign key constraint "partecipants_fk" on table "partecipants"
detail:
'Key (id_be)=(315017) is still referenced from table "partecipants".
如果我第二次運行相同的 function ,則結束沒有錯誤。
這怎么可能?
作為背景信息,其他進程在運行時正在使用(通常也帶有鎖)function 中涉及的表。
並發事務可以在您的UPDATE
和您的DELETE
之間添加或修改partecipants
中的行,以便后者失敗。
如果您想避免這種情況,請在一個語句中執行這兩項操作:
WITH dummy AS (
update partecipants set id_be=winningId where id_be=losingId
)
delete from business_entity where id_be=losingId;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.