Re: Abort state on duplicated PKey in transactions

From: Haroldo Stenger <hstenger(at)adinet(dot)com(dot)uy>
To: "Matthew T(dot) O'Connor" <matthew(at)zeut(dot)net>, pgsql-hackers(at)postgresql(dot)org
Subject: Re: Abort state on duplicated PKey in transactions
Date: 2001-09-08 19:22:32
Message-ID: 3B9A6FF8.12ADCEE8@adinet.com.uy
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

"Matthew T. O'Connor" wrote:
>
> > A solution, could be to query for the existance of the PK, just before the
> > insertion. But there is a little span between the test and the
> > insertion, where another insertion from another transaction could void
> > the existance test. Any clever ideas on how to solve this? Using
> > triggers maybe? Other solutions?
> >
>
> All you need to do is use a sequence. If you set the sequence to be the
> primary key with a default value of nextval(seq_name) then you will never
> have a collision. Alternatly if you need to know that number before you
> start inserting you can select next_val(seq_name) before you inser and use
> that. By the way the datatype serial automates exactly what I described.

Yes, but there are situations where a sequenced PK isn't what is needed.
Imagine a DW app, where composed PKs such as (ClientNum, Year, Month,
ArticleNum) in a table which has ArticleQty as a secondary field are
used, in order to consolidate detail record from other tables. There,
the processing cycle goes like checking for the existance of the PK, if
it exists, add ArticleQtyDetail to ArticleQty, and update; and if it
doesn't exist, insert the record with ArticleQtyDetail as the starting
value of ArticleQty. See it? Then, if between the "select from" and the
"insert into", other process in the system (due to parallel processing
for instance) inserts a record with the same key, then the first
transaction would cancel, forcing redoing of all the processing. So,
sort of atomicity of the check?update:insert operation is needed. How
can that be easily implemented using locks and triggers for example?

Regards,
Haroldo.

In response to

Browse pgsql-hackers by date

  From Date Subject
Next Message Ian Lance Taylor 2001-09-08 21:21:04 Problem with new anoncvs server
Previous Message Haroldo Stenger 2001-09-08 17:20:28 Abort state on duplicated PKey in transactions