Re: Check before insert - Mailing list pgsql-interfaces

From Michael Fuhr
Subject Re: Check before insert
Date
Msg-id 20050315222329.GA67743@winnie.fuhr.org
Whole thread Raw
In response to Re: Check before insert  (Robert Perry <rlperry@lodestonetechnologies.com>)
List pgsql-interfaces
On Tue, Mar 15, 2005 at 04:51:20PM -0500, Robert Perry wrote:

> Insert (protein_id, name)
> select 'P04667', 'Albumin'
> where
>     not exists(select * from protein_table_name where protein_id = 
> 'P04667')

This should work if concurrency isn't an issue.  But if two concurrent
transactions execute the same statement, then they might both find
no existing row and thus both attempt the insert.  In that case,
in the presence of a unique index, one of the inserts will succeed
and the other transaction will block pending the first transaction's
completion.  If the first transaction rolls back then the second's
insert will succeed, but if the first transaction commits then the
second will fail with a duplicate key violation.  A program should
therefore be prepared to handle this situation.  In 8.0 and later
you could use a savepoint or a PL/pgSQL exception handler to recover
from the error without aborting the entire transaction.

-- 
Michael Fuhr
http://www.fuhr.org/~mfuhr/


pgsql-interfaces by date:

Previous
From: Robert Perry
Date:
Subject: Re: Check before insert
Next
From: Christof Petig
Date:
Subject: libecpg (8.0 and CVS) hits a gcc bug on powerpc and amd64 (crash)