Search code examples
sqlalchemyatomic

sqlalchemy, atomicity, and getting inserted id


I needed the answer in this article about how to get the id of a newly inserted database entry : sqlalchemy flush() and get inserted id?

I am wondering about atomicity of commits. For instance, suppose that I have commited a new item to the db and then gotten the id back. I now want to do some further processing and maybe add the item id as a foreign key to another table. This breaks atomicity, as I would like to commit to the db only after I have done this extra processing. Doesn't this sound like a problem? I am facing this problem in my project.


Solution

  • .flush() does not commit anything. The only effect of .flush() (and a later .rollback()) is that the AUTO_INCREMENT of the table is increased (e.g., if the last committed record had ID 13 and then you .add(), .flush() and .rollback() your new record, the next inserted record will receive ID 15 instead of ID 14.