Re: How to keep the last row of a data set?

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: seiliki(at)so-net(dot)net(dot)tw
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: How to keep the last row of a data set?
Date: 2012-12-13 15:56:30
Message-ID: 5508.1355414190@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

seiliki(at)so-net(dot)net(dot)tw writes:
> I am trying to implement a mechanism that prohibits the last row of a data set from being deleted.

> The following trigger protects nothing:

> CREATE OR REPLACE FUNCTION tfd() RETURNS TRIGGER AS $$
> BEGIN
> RAISE NOTICE '%',(SELECT COUNT(*) FROM t1 WHERE c1=OLD.c1);
> IF (SELECT COUNT(*) FROM t1 WHERE c1=OLD.c1) = 1 THEN
> RAISE EXCEPTION 'Must keep at least 1 row for c1="%"',OLD.c1;
> END IF;
> RETURN OLD;
> END $$ LANGUAGE PLPGSQL STABLE;

The reason that doesn't work is you marked it "stable", so it always
sees the starting state of the outer query.

Mind you, even with that oversight fixed, this approach will do little
to save you from concurrent-update situations. That is, transaction A
could delete some of the rows with c1=1, and transaction B could
concurrently delete the rest, and neither transaction will see a reason
why it shouldn't commit.

regards, tom lane

In response to

Browse pgsql-general by date

  From Date Subject
Next Message David Noel 2012-12-13 16:18:58 Re: initdb error
Previous Message Adrian Klaver 2012-12-13 15:55:50 Re: initdb error