lastval()

From: Dennis Bjorklund <db(at)zigo(dot)dhs(dot)org>
To: pgsql-patches(at)postgresql(dot)org
Subject: lastval()
Date: 2005-05-08 17:00:15
Message-ID: Pine.LNX.4.44.0505081830480.7072-200000@zigo.dhs.org
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-hackers 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 Content-Type Size
pg-lastval.txt text/plain 8.2 KB

Responses

Browse pgsql-hackers by date

  From Date Subject
Next Message Jim C. Nasby 2005-05-08 17:04:44 Re: Race conditions, race conditions!
Previous Message Tom Lane 2005-05-08 16:46:47 Re: Patch for collation using ICU

Browse pgsql-patches by date

  From Date Subject
Next Message Tom Lane 2005-05-08 22:36:49 Re: lastval()
Previous Message Tom Lane 2005-05-08 16:35:22 Re: [PATCHES] Cleaning up unreferenced table files