pg.ddx.io  pgsql-performance@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: Tom Lane <tgl@sss.pgh.pa.us>
To: Craig James <cjames@emolecules.com>
Cc: pgsql-performance@postgresql.org
Subject: Re: Does setval(nextval()+N) generate unique blocks of IDs?
Date: Mon, 20 Aug 2012 20:10:00 -0400
Message-ID: <13192.1345507800@sss.pgh.pa.us> (raw)
In-Reply-To: <CAFwQ8re6hFodxhfRcsrpywegFfRAVd9a3fe=9BOXL2dtezMEAQ@mail.gmail.com>
References: <CAFwQ8re6hFodxhfRcsrpywegFfRAVd9a3fe=9BOXL2dtezMEAQ@mail.gmail.com>

Craig James <cjames@emolecules.com> writes:
> I want to do this:

>     select setval('object_id_seq', nextval('object_id_seq') + 1000, false);

> Now suppose two processes do this simultaneously.  Maybe they're in
> transactions, maybe they're not.  Are they guaranteed to get distinct
> blocks of IDs?

No, because the setval and the nextval are not indivisible.

> Or is it possible that each will execute nextval() and
> get N and N+1 respectively, and then do setval() to N+1000 and N+1001,
> resulting in two overlapping blocks.

Exactly.

> If the answer is, "This won't work," then what's a better way to do this?

AFAIK the only way at the moment is

* acquire some advisory lock that by convention you use for this sequence
* advance the sequence
* release advisory lock

There have been previous discussions of this type of problem, eg
http://archives.postgresql.org/pgsql-hackers/2011-09/msg01031.php
but the topic doesn't seem to have come up quite often enough to
motivate anybody to do anything about it.  Your particular case could be
handled by a variant of nextval() with a number-of-times-to-advance
argument, but I'm not sure if that's enough for other scenarios.

			regards, tom lane




view thread (14+ messages)  latest in thread

Message-ID: <13192.1345507800@sss.pgh.pa.us>
Permalink:  ../13192.1345507800@sss.pgh.pa.us/
Also on:    postgresql.org/message-id/13192.1345507800@sss.pgh.pa.us

 · 

reply

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Reply to all the recipients using the --to and --cc options:
  reply via email

  To: pgsql-performance@postgresql.org
  Cc: tgl@sss.pgh.pa.us, cjames@emolecules.com
  Subject: Re: Does setval(nextval()+N) generate unique blocks of IDs?
  In-Reply-To: <13192.1345507800@sss.pgh.pa.us>

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox