Re: Delete trigger and data integrity

From: Albe Laurenz <laurenz(dot)albe(at)wien(dot)gv(dot)at>
To: "Yvonne Zannoun *EXTERN*" <yvonne(dot)zannoun(at)snowflakesoftware(dot)com>, "pgsql-general(at)postgresql(dot)org" <pgsql-general(at)postgresql(dot)org>
Subject: Re: Delete trigger and data integrity
Date: 2014-05-27 10:44:59
Message-ID: A737B7A37273E048B164557ADEF4A58B17CFE566@ntex2010i.host.magwien.gv.at
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Yvonne Zannoun wrote:
> I have this question regarding delete triggers and how it affects data integrity.
> So here goes: I have this trigger which deletes everything before I insert new rows.
>
> CREATE OR REPLACE FUNCTION delete_records()
> RETURNS TRIGGER AS $$
> BEGIN
> delete from "TABLE";
> RETURN NEW;
> END;
> $$
> LANGUAGE plpgsql;
>
> CREATE TRIGGER delete_on_insert
> BEFORE INSERT ON "TABLE"
> FOR EACH ROW EXECUTE PROCEDURE delete_records();
>
> My question is what happens while this function is executed? Is there any chance the table can return
> empty data between the delete and insert commands? Or does a trigger like this block this possibility
> somehow?

Since the trigger has to run in the same transaction as the INSERT, no
concurrent transaction will be able to see the "dirty" state between
the DELETE and the INSERT.

Are you sure that you want the trigger FOR EACH ROW and not FOR EACH STATEMENT?
If the INSERT statement inserts more than one row, the trigger will run multiple
times and you will end up with only one row in the table.

Yours,
Laurenz Albe

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Yvonne Zannoun 2014-05-27 10:54:50 Re: Delete trigger and data integrity
Previous Message Albe Laurenz 2014-05-27 10:35:53 Re: libpq: indefinite block on poll during network problems