Skip site navigation (1) Skip section navigation (2)

Re: checking update/insert return

From: Andrew McMillan <andrew(at)catalyst(dot)net(dot)nz>
To: "Marcus Andree S(dot) Magalhaes" <marcus(dot)magalhaes(at)vlinfo(dot)com(dot)br>
Cc: pgsql-novice(at)postgresql(dot)org
Subject: Re: checking update/insert return
Date: 2004-01-06 10:30:38
Message-ID: (view raw, whole thread or download thread mbox)
Lists: pgsql-novice
On Tue, 2004-01-06 at 11:40, Marcus Andree S. Magalhaes wrote:
> > Hi,
> >
> > Why do you not use the serial data type : SERIAL ?
> >
> I must guarantee to the client-side that the ID field
> has no holes....

If you _really_ have to do that, then the only way [I have thought of
over the years] to do it in a transaction safe manner is to pre-allocate
numbers, creating records (just the ID number) in a second table.  Like
pulling raffle tickets out of a book.

Then, when you want a number, you:

  SELECT first unused pre-allocated number FOR UPDATE
  DELETE the pre-allocated number
  INSERT empty 'it-didn't-happen-yet' record with pre-allocated number

  do other important stuff

Then, if you roll back the first transaction, the DELETE never happened,
and the INSERT never happened, so the next transaction comes along and
uses that code.

If you roll back the second transaction, then you are still left with an
'empty' record in your table, but there _is_ a record there.  You could
either (a) leave it like that, and be happy, or (b) have a process which
goes along later and removes them while re-pre-allocating the number,
which I would say is probably more pain than it's worth.  Of course the
whole thing is more pain than it's worth, really :-)

Of course something this does not address is _ordering_ of these
records, but you can't guarantee ordering on a multi-user system anyway
unless you make it stop being multi-user for a while.

In the past when people have asked me for this "every code is used"
approach (usually accountants) I've told them "No!", and then baffled
them with justification about how hard it is until their eyes glazed

Then, of course, when I've got them off my back I just can't help
worrying at the problem until I get some sort of half-assed solution
together :-)

					Andrew McMillan.

Andrew @ Catalyst .Net .NZ  Ltd,  PO Box 11-053,  Manners St,  Wellington
WEB:             PHYS: Level 2, 150-154 Willis St
DDI: +64(4)916-7201       MOB: +64(21)635-694      OFFICE: +64(4)499-2267
                     The Killer Ducks are coming!!!


In response to

pgsql-novice by date

Next:From: Martin HamplDate: 2004-01-06 11:30:24
Subject: Disk usage
Previous:From: vhikidaDate: 2004-01-06 00:19:44
Subject: Re: postgresql in windows

Privacy Policy | About PostgreSQL
Copyright © 1996-2017 The PostgreSQL Global Development Group