Kwissle

My real-time quiz battle game Kwissle.com

Crosstips.org

My fun Crossword solver project. Crosstips.org & Krysstips.se

Kung Fu

Fujian White Crane Kung Fu

Photos

Photoalbum, both old and new.

Twitter

Follow me on Twitter

Contact me

My contact details and how to contact me.

 

KungFuPeople.com
Do you train Kung Fu?
Or know someone who does?
Then check out KungFuPeople.com


Mobile version of this page Mobile version of this page


 
Linux

Sequences in PostgreSQL and rolling back transactions


12th of 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.



Comment

 
Name:
Email:
hide my email address.

Your email address will be encoded to prevent email-extraction spiders from reading it so you won't get spammed if you decide to show your email address.