Re: writing a function to mimic mysql last_insert_id

From: Josh Berkus <josh(at)agliodbs(dot)com>
To: "Beth Gatewood" <beth(at)vizxlabs(dot)com>, <pgsql-sql(at)postgresql(dot)org>
Subject: Re: writing a function to mimic mysql last_insert_id
Date: 2002-09-11 17:53:49
Message-ID: 200209111053.49837.josh@agliodbs.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql


Beth,

> However, we are in the midst of porting a mysql database to pgsql. The perl
> application that is tied to this mysql database heavily utilizes
> last_insert_id. In an effort to save the perl developers the pain of having
> to go in and modify a bunch of their SQL to call out to seq.currval, I
> thought I would attempt to mimic this function.
>
> Perhaps there is another way to approach this than writing this type of
> function?

Not really. CURRVAL requires a sequence name as a parameter because, in
Postgres, one can have more than one sequence for a table. Further, in
Postgres, you can update more than one table at a time using a function,
trigger, or rule; how would any function know which sequence id to return?

While it would be relatively easy for a function to look up what seqeunces
were related to a table in the pg_* tables, you are left with the difficult
task of determining what statement the user last ran. This would, I think,
involve hacking MVCC to some degree.

If you're serious about pursuing this, I suggest posting your question on
PGSQL-HACKERS to get help with hacking MVCC to determine a connection's last
action. I have no idea how easy or difficult this would be.

A second possibility would be writing triggers for all tables that place a
value into a temporary table that can be read back by your custom function.

You may find it less work, however, to do a search-and-replace on calls to
last_inser_id(). But if you do write a replacement function, please post it
on TechDocs!

--
-Josh Berkus
Aglio Database Solutions
San Francisco

In response to

Browse pgsql-sql by date

  From Date Subject
Next Message Ricardo Javier Aranibar León 2002-09-11 20:02:23 reset sequence
Previous Message Beth Gatewood 2002-09-11 17:43:42 Re: writing a function to mimic mysql last_insert_id