Re: Sequences in transaction context

Doug McNaught <doug@wireboard.com>

From: Doug McNaught <doug@wireboard.com>
To: "Erik Pearson" <erik@cariboulake.com>
Cc: pgsql-general@postgresql.org
Date: 2001-06-06T03:14:06Z
Lists: pgsql-general
"Erik Pearson" <erik@cariboulake.com> writes:

> I searched through mailing list archives but was unable to find full
> coverage of this question -- my apologies if this is a reposted question.
> 
> As in the FAQ, I am trying to retrieve the value of a sequence value from a
> newly inserted row.  So, first I call something like:
> 
>     insert into foobar (foo, bar)
>     values (nextval('foobar_foo_seq'), 'whatever');
> 
> Then, I want to retrieve the value that generated from the sequence and
> inserted into the table, so I use a call to currval:
> 
>     insert into foobar_rel_table(foo_fk, baz)
>     values (currval('foobar_foo_seq', 'something else');
> 
> This is (one of the methods that is) prescribed in the FAQ.  However, I'm
> concerned that another transaction attempting to insert into the same table
> might make a call to nextval('foobar_foo_seq') between the two operations
> above.  This would mean that my second statement would use the wrong value
> from the sequence.

This does not happen.  I just tested it:

[doug@shaggy doug]$ createdb foo
CREATE DATABASE
[doug@shaggy doug]$ psql foo
Welcome to psql, the PostgreSQL interactive terminal.

Type:  \copyright for distribution terms
       \h for help with SQL commands
       \? for help on internal slash commands
       \g or terminate with semicolon to execute query
       \q to quit

foo=# create sequence foo_seq;
CREATE
foo=# select nextval('foo_seq');
 nextval 
---------
       1
(1 row)

foo=# select currval('foo_seq');
 currval 
---------
       1
(1 row)

At this point, in another window, I do:

foo=# select nextval('foo_seq');
 nextval 
---------
       2
(1 row)

Back to the first window:

foo=# select currval('foo_seq');
 currval 
---------
       1
(1 row)

Are you not seeing this behavior?  Since you mention the FAQ, question 
4.16.3 addresses this very issue in very clear language.

Welcome to MVCC...

-Doug
-- 
The rain man gave me two cures; he said jump right in,
The first was Texas medicine--the second was just railroad gin,
And like a fool I mixed them, and it strangled up my mind,
Now people just get uglier, and I got no sense of time...          --Dylan