Re: mysql's last_insert_id - Mailing list pgsql-general

From Dennis Björklund
Subject Re: mysql's last_insert_id
Date
Msg-id Pine.LNX.4.44.0308290900130.4053-100000@zigo.dhs.org
Whole thread Raw
In response to Re: mysql's last_insert_id  (Bo Lorentsen <bl@netgroup.dk>)
Responses Re: mysql's last_insert_id  (Bo Lorentsen <bl@netgroup.dk>)
Re: mysql's last_insert_id  (Dennis Gearon <gearond@fireserve.net>)
List pgsql-general
On 29 Aug 2003, Bo Lorentsen wrote:

> > There are various solutions. Some people use functions to do inserts,
> > I just use the string "currval(whatever)" in the application layer
> > which the database replaces with the appropriate value.
>
> Hmm, but what happends if more than one connection does this at the same
> time ? Then, only one of the concurrent connections will have a insert
> on the returned value, and the rest will get a wrong row reference
> returned.

That is not a problem, it's perfectly safe. It's all described in

http://www.postgresql.org/docs/7.3/static/functions-sequence.html

Basicly, currval() gives the last id for that sequence in that session. So
other sessions does not break anything.

> The only safe methode would be to do a "select nextval(whatever)", and
> aply this number by "hand" to the insert, but that remove the
> possibility to make general code even more, but it will be safe.

It's not needed. The following works fine (if the tables exists of course)
and has no problems with concurrency:

INSERT INTO foo(id,x) VALUES (DEFAULT, 'value');
INSERT INTO bar(id,foo_ref) VALUES (DEFAULT, currval('foo_id_seq'));

--
/Dennis


pgsql-general by date:

Previous
From: "Ivar"
Date:
Subject: Re: Functions have 32 args limt ???
Next
From: Martijn van Oosterhout
Date:
Subject: Re: mysql's last_insert_id