lastval() - Mailing list pgsql-patches

From Dennis Bjorklund
Subject lastval()
Date
Msg-id Pine.LNX.4.44.0505081830480.7072-200000@zigo.dhs.org
Whole thread Raw
Responses Re: lastval()
Re: lastval()
Re: lastval()
Re: lastval()
List pgsql-patches
Here is a small patch that implements a function lastval() that
works just like currval() except that it give the current
value of the last sequence used by nextval().

Using this function one can do:

# CREATE TABLE abc (a serial, b int);
CREATE TABLE

# SELECT lastval();
ERROR:  nextval have not been used in the current session

# INSERT INTO abc(b) VALUES (42);
INSERT 0 1

# SELECT lastval();
 lastval
---------
       1


Some comments about the implementetion
--------------------------------------

Each backend keeps a list of all used sequences in the session. This patch
adds a sequence pointer that point out one of the sequences in the list
and which is updated by nextval(). This is a simple pointer assignment so
it's very cheap (almost zero cost).

lastval() works just like currval but use the pointed out sequence
instead of geting a sequence name as an argument.

One can implement this by storing the value instead of the sequence
pointer but I decided it's a good thing that it works just like
currval(), behaving the same with respect to rights, locks and such.

General comments
----------------

I know that some of you might want to name this function the same as the
similar function in mysql (LAST_INSERT_ID), but I prefer to name it
similar to the old sequence functions. It's easy to add a LAST_INSERT_ID()
function that call lastval() if needed. Also, LAST_INSERT_ID() in mysql
will always succeed and it returns 0 if there have not been any row
inserted (at least what I think it will do that based on a quick look in
the mysql doc). The above function does not work like that.

--
/Dennis Björklund

Attachment

pgsql-patches by date:

Previous
From: Tom Lane
Date:
Subject: Re: Dealing with CLUSTER failures
Next
From: Tom Lane
Date:
Subject: Re: lastval()