Sequences in PostgreSQL and rolling back transactions
12 May 2009
This behavior bit me today and caused me some pain so hopefully by sharing it it can help someone else not ending up in the same pitfall.
Basically, I use Zope to manage a PostgreSQL database and since Zope is 100% transactional it rolls back queries when exception occur. That's great but what I didn't know is that when it rolls back it doesn't roll back the sequences. Makes sense in retrospect I guess. Here's a proof of that:
test_db=# create table "foo" (id serial primary key, name varchar(10)); CREATE TABLE test_db=# insert into foo(name) values('Peter'); INSERT 0 1 test_db=# select * from foo; id | name ----+------- 1 | Peter (1 row) test_db=# select nextval('foo_id_seq'); nextval --------- 2 (1 row) test_db=# begin; BEGIN test_db=# insert into foo(id, name) values(2, 'Sonic'); INSERT 0 1 test_db=# rollback; ROLLBACK test_db=# select nextval('foo_id_seq'); nextval --------- 3 (1 row)
In my application I often use the sequences to predict what the auto generate new ID is going to be for things that the application can use such as redirecting or updating some other tables. As I wasn't expecting this it caused a bug in my web app.