select for update

From: Craig James <craig_james(at)emolecules(dot)com>
To: "pgsql-admin(at)postgresql(dot)org" <pgsql-admin(at)postgresql(dot)org>
Subject: select for update
Date: 2011-04-22 17:49:54
Message-ID: 4DB1BFC2.7020806@emolecules.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-admin

I thought I understood "select ... for update," but maybe not.

We have a number of separate databases and a unique integer identifier that's supposed to be global across all databases. A single "archive" database is used to issue the next available ID when a process wants to create a new object. The sequence of operations goes like this (pseudo-code):

/* start a transaction *
begin;

/* see if an objectid has been returned for re-use */
select objectid from archive where db_id is null limit 1 for update

/* no ID available? issue a new one */
if (objectid is null)
new_id = select nextval('object_id_sequence')
insert into archive(objectid, db_id) values('new_id', 'new_id')

/* ID available? claim it */
else
update archive set db_id = this_db_id where objectid

commit

The problem is that very occasionally the same ID will be issued twice. I don't see how this can be. Doesn't the "for update" guarantee that no other process can claim that same row?

Thanks,
Craig

Responses

Browse pgsql-admin by date

  From Date Subject
Next Message Mario Splivalo 2011-04-22 18:35:18 Re: Reseting statistics, cluster wide
Previous Message Steve Crawford 2011-04-22 16:54:11 Re: unix timestamp