Re: Sequential non unique IDs

From: Craig Ringer <craig(at)postnewspapers(dot)com(dot)au>
To: John Reeve <jreeve(at)pelagodesign(dot)com>
Cc: pgsql-sql(at)postgresql(dot)org
Subject: Re: Sequential non unique IDs
Date: 2008-04-02 04:24:16
Message-ID: 47F30A70.3090507@postnewspapers.com.au
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

John Reeve wrote:

> I've already considered:
> 1. I can't lock the table, because there are too many inserts happening
> and it will slow down the app.

In a locking approach you may not need to lock the whole table. You
should only need to lock the entry for the customer being altered, eg:

BEGIN;

SELECT 1 FROM task WHERE customerid = 92 FOR UPDATE;

INSERT INTO task (id, customerid, localid) VALUES (nextval('task_id'),
92, (SELECT MAX(localid) + 1 FROM task WHERE customerid = 92));

If I'm not mistaken, that should ensure that for any given customer ID
there's only one transaction holding the locks on that customer.

It won't prevent SELECTs from reading the customer's records, but you
don't mind that so long as they're not using the customer's records to
determine the least free localid. That'll help reduce the hit on your
app's performance, too. If you do mind the , use SELECT ... FOR SHARE
and you'll wait on the FOR UPDATE lock if one is active (however, it
might prove hard to obtain a FOR UPDATE lock if there are lots of FOR
SHARE operations active).

I *think* that'll work, but you should of course test and investigate
before doing anything as crazy as taking my word for it.

> Anyone know a solution for this? This can't be the first time anyone has
> ever tried to do this. Thanks!

If I'm not mistaken about the similarity, you might want to search the
archives for the thread "Primary Key with serial". It might be informative.

--
Craig Ringer

In response to

Responses

Browse pgsql-sql by date

  From Date Subject
Next Message Volkan YAZICI 2008-04-02 05:48:03 Re: Sequential non unique IDs
Previous Message John Reeve 2008-04-01 22:49:46 Sequential non unique IDs