Re: DELETE trigger, direct or indirect? - Mailing list pgsql-general

From Erik Wienhold
Subject Re: DELETE trigger, direct or indirect?
Date
Msg-id 1955533673.226407.1676563761989@office.mailbox.org
Whole thread Raw
In response to DELETE trigger, direct or indirect?  (Dominique Devienne <ddevienne@gmail.com>)
List pgsql-general
> On 16/02/2023 14:23 CET Dominique Devienne <ddevienne@gmail.com> wrote:
>
> Hi. This is a bit unusual. We have a foreign key between two tables, with
> ON DELETE CASCADE, to preserve referential integrity. But we apparently
> also need to preserve the severed reference (by natural key, i.e. its name),
> to later on reconnect the two entities after-the-fact, should the parent
> row re-appear later on (in the same transaction or not it still unclear).
>
> To achieve this weird requirement, I'd like to know if it is possible in an
> ON DELETE trigger to know whether the deletion is coming from a direct-DELETE
> in the "child table", or whether the deletion is coming from the "parent
> table" CASCADEd to the child table.

Not to my knowledge.  ON DELETE CASCADE behaves like a manual DELETE on the
child table that happens before the DELETE on the parent table.

The process you describe shows that it's not known until the end of the
transaction which parent rows can be deleted.  You can instead track the
parent rows as candidates for deletion in a temp table.  Insert the primary
key of parent rows if you deem them deletable and delete the primary key if
you detect the opposite.  At the end the temp table only contains IDs of
parent rows that can be deleted for sure.

--
Erik



pgsql-general by date:

Previous
From: "David G. Johnston"
Date:
Subject: Re: Postgres undeterministically uses a bad plan, how to convince it otherwise?
Next
From: Ron
Date:
Subject: Re: Postgres undeterministically uses a bad plan, how to convince it otherwise?