Wednesday, July 27, 2011

web.py: get auto-increment value after db.insert

This is probably too simple, so no one ever bothered to write about it. (Or I couldn't come up with the proper keywords for Google).

The situation is simple. I have a table where the primary key is some auto-incrementing ID number (in the case of postgresql, with the primary key called nid, the definition is nid serial primary key). After inserting a record into the table, I want to know what ID it has got.

Turns out it's very simple. I need only to pass a custom seqname to db.insert().

nid = db.insert("tablename", seqname="tablename_nid_seq",...)

For the serial column, postgresql creates a sequence automatically and assigns it a particularly constructed name. More details at FAQ: Using Sequences in PostgreSQL.

This is probably not the best style (I'm hard-coding the seqname in the source code), and I'm not even sure if it's the right way. But at least I can proceed with my prototyping and hacking now :)