Re: Enforcing serial uniqueness?

From: Tino Wildenhain <tino(at)wildenhain(dot)de>
To: Steven Brown <swbrown(at)ucsd(dot)edu>
Cc: kleptog(at)svana(dot)org, pgsql-general(at)postgresql(dot)org
Subject: Re: Enforcing serial uniqueness?
Date: 2006-03-22 13:31:46
Message-ID: 442151C2.3030507@wildenhain.de
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Steven Brown schrieb:
> Martijn van Oosterhout wrote:
>
...
>> Secondly, if you don't want people to be able to stuff with your ID
>> column, you could set a BEFORE INSERT trigger to overwrite whatever
>> they provide and a BEFORE UPDATE trigger to cancel any changes...
>
>
> The problem is that to get the last inserted id, as far as I know, you
> need to select a value ahead of time via nextval, then insert with it.
> If I simply block/change all forced entries, I'll wind up blocking that,
> and won't know what id the row I just inserted got.

Just turn it around (which has the advantage you dont have to
transfer to and fro the database in 2 steps):

INSERT INTO thetable (col1,col2,col3) VALUES ( ... );
SELECT currval('thetable_id_seq');

since your insert above would call nextval() per default,
its save to use currval() in the same transaction.

For sequences (instead of just an int column with default)
there is even a function to find the sequence for that
column.

> I believe there's a way to get the last row oid and use that to figure
> out what id was used, but I think that would require all clients to be
> PostgreSQL-specific, so isn't too useful if you don't control all the
> clients.

No, you dont mess around with oids.

Regards
Tino

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Steven Brown 2006-03-22 13:44:06 Re: Enforcing serial uniqueness?
Previous Message Andrus 2006-03-22 13:24:46 Re: How to release locks