lang2
lang2

Reputation: 11966

sqlalchemy: is rollback required on every commit?

I'm using SQLAlchemy for my web app. I've seen a lot of code like this:

try:
   session.commit()
except:
   session.rollback()

I'm wondering if it's necessary for each commit() operation. If it is, then why isn't it part of the commit() operation? How to decide when to rollback() and when not?

Upvotes: 7

Views: 3238

Answers (1)

szym
szym

Reputation: 5846

When commit fails it just means that the transaction cannot complete without breaking some constraints. So in principle, instead of rolling back you could make some updates and try committing again.

In practice, such error recovery logic is non-trivial to reason about, so most people just roll back (undo any changes made for the transaction) to keep data in consistent state, and communicate the problem to the user.

Upvotes: 5

Related Questions