Re: Strange behavior of TRIGGER - Mailing list pgsql-general

From Jeff Davis
Subject Re: Strange behavior of TRIGGER
Date
Msg-id 1191350617.9296.11.camel@dogma.ljc.laika.com
Whole thread Raw
In response to Strange behavior of TRIGGER  ("Nurlan Mukhanov" <nurike@gmail.com>)
List pgsql-general
On Mon, 2007-10-01 at 23:19 +0600, Nurlan Mukhanov wrote:
> There is a table with unique rows. But before insert trigger checks
> data and returns NULL if such record exist and NEW if not.
>
> But from time to time I'm getting an error in my log file
>
> faled query: INSERT INTO viewed_members (member_id, viewed_id) VALUES
> ('93701','41719')
> context: ERROR: duplicate key violates unique constraint "viewed_search_members"
>

The trigger you wrote does not lock the table. A concurrent transaction
might insert a record with the same (member_id, viewed_id) that might
not yet be visible at the time of your trigger's SELECT.

To do this kind of thing safely, your trigger needs to lock the table
against writes before the SELECT operation.

That has a performance penalty, of course. What you should probably do
instead is just rely on the unique index to report an error. If you
don't want an error, you should catch the error in pl/pgsql as described
here:

http://www.postgresql.org/docs/current/static/plpgsql-control-
structures.html#PLPGSQL-ERROR-TRAPPING

That will perform better and allow you to disregard records without a
unique (member_id, viewed_id).

Regards,
    Jeff Davis


pgsql-general by date:

Previous
From: Michael Glaesemann
Date:
Subject: Re: Find min year and min value
Next
From: Jeff Davis
Date:
Subject: Re: It's time to support GRANT SELECT,UPDATE,...,...,... ON database.* to username