Re: Get block of N numbers from sequence

From: Merlin Moncure <mmoncure(at)gmail(dot)com>
To: Thomas Guettler <hv(at)tbz-pariv(dot)de>
Cc: pgsql-general <pgsql-general(at)postgresql(dot)org>
Subject: Re: Get block of N numbers from sequence
Date: 2009-05-19 18:01:24
Message-ID: b42b73150905191101p57a07e0w362511ba8f950aa7@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On Tue, May 19, 2009 at 9:32 AM, Thomas Guettler <hv(at)tbz-pariv(dot)de> wrote:
>
>
> hubert depesz lubaczewski schrieb:
>> On Tue, May 19, 2009 at 01:45:17PM +0200, Thomas Guettler wrote:
>>> how can you get N numbers (without holes) from a sequence?
>>
>> alter sequence XXX increment by 1000;
>> select nextval('XXX');
>> alter sequence XXX increment by 1;
>
> If other processes run nextval() between "increment by 1000" and "increment by 1",
> they leave big holes in the sequence.

This is only works if everyone does it this way. If anybody throws a
nextval() without locking the sequence first you have a race. Also,
since alter sequence takes a full lock your concurrency is zero.

Probably the best general way to attack this problem is using advisory
locks. note the code below is untested.

create or replace function my_nextval(_seq text, _count int, _v out
bigint) returns bigint as
$$
begin
if _count = 1 then
perform pg_advisory_lock_shared(999);
_v := nextval(_seq);
perform pg_advisory_unlock_shared(999);
else
perform pg_advisory_lock(999);
_v := nextval(_seq);
perform setval(_seq, _v + _count);
perform pg_advisory_unlock(999);
end if;
end;
$$ language plpgsql;

This complexity is worthwhile if you need to intermix standard
nextval() with block allocations. the number 999 has no significance
except as a lock id...see the docs on advisory locks. The advantage
here is that nextval() calls do not block each other and the full lock
is extremely short term, so you can safely call this during longer
running transaction.

merlin

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message James B. Byrne 2009-05-19 18:05:09 Help with join syntax sought
Previous Message Shakil Shaikh 2009-05-19 17:55:25 Locking to restrict rowcounts.