Re: translating this SQL query from a different dialect

From: Michael Fuhr <mike(at)fuhr(dot)org>
To: "A(dot) Kretschmer" <andreas(dot)kretschmer(at)schollglas(dot)com>, pgsql-novice(at)postgresql(dot)org
Subject: Re: translating this SQL query from a different dialect
Date: 2006-01-10 17:38:59
Message-ID: 20060110173859.GA98683@winnie.fuhr.org
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-novice

On Tue, Jan 10, 2006 at 03:53:00PM +0100, A. Kretschmer wrote:
> create function max8() returns trigger as $$
> declare
> c int;
> begin
> select into c count(*) from foo;
> -- the name of the table is foo
>
> if (c = 8) then
> -- 8 is the maximum
> raise exception 'max count reached';
> end if;
> return NEW;
> end;
> $$ language plpgsql;
>
> create trigger max8 before insert on foo for each row execute procedure max8();

Beware that as written this doesn't handle concurrency. For example:

Transaction A: BEGIN;
Transaction B: BEGIN;
Transaction A: INSERT INTO foo ... -- 7 times
Transaction B: INSERT INTO foo ... -- 7 times
Transaction A: COMMIT;
Transaction B: COMMIT;

The table now has 14 records. You'll need to add some extra locking
for it to work in a concurrent environment.

--
Michael Fuhr

In response to

Responses

Browse pgsql-novice by date

  From Date Subject
Next Message A. Kretschmer 2006-01-10 18:28:36 Re: translating this SQL query from a different dialect
Previous Message Joao Miguel Ferreira 2006-01-10 17:01:02 Preventing access of user1 to user2's database