I have a function with several queries inside, like this:
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$
;
There is a foreign key between partecipants and business_entity:
ALTER TABLE partecipants ADD CONSTRAINT partecipants_fk FOREIGN KEY (id_be) REFERENCES business_entity(id_be)
Sometimes (like 1 in 1000 times) this function hangs with error:
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".
If I run the same function a second time, ends without error.
How is this possible?
As a background information, other processes are using (often also with locks) the tables involved in the function while is running.
Concurrent transactions could add or modify rows in partecipants
between your UPDATE
and your DELETE
so that the latter fails.
If you want to avoid that, do both in a single statement:
WITH dummy AS (
update partecipants set id_be=winningId where id_be=losingId
)
delete from business_entity where id_be=losingId;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.