Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLAlchemy session commit exception handing with rollback

I am trying to figure out the preferred way to manage session if exceptiion occurs while doing operation or committing the session. But a few examples in the document confuses me a little bit.

The doc says to frame out a commit/rollback block, you can do something like this:

# verbose version of what a context manager will do
with Session(engine) as session:
    session.begin()
    try:
        session.add(some_object)
        session.add(some_other_object)
    except:
        session.rollback()
        raise
    else:
        session.commit()

While this example includes the commit() call in the try block:

Session = sessionmaker(bind=engine)
session = Session()
session.begin()
try:
    item1 = session.query(Item).get(1)
    item2 = session.query(Item).get(2)
    item1.foo = 'bar'
    item2.bar = 'foo'
    session.commit()
except:
    session.rollback()
    raise

I wonder:

  1. what's the difference between these two patterns?
  2. which is the preferred way for managing transaction?
  3. The doc says both example above can be succinctly illustrated with session.begin() context manager, so does it handle the exception occurs while commit() ?

Possible related answes:

Here is a answer that exludes commit() from the try block, but the explanation in the comments doesn't seem sufficient to me. And this answer mentions about why including commit() in try block.

like image 305
oeter Avatar asked Sep 10 '25 12:09

oeter


1 Answers

Both examples accomplish nearly the same thing. The transaction will be committed if there is no error, and rolled back if there is an error.

The difference is that if there is an exception on the commit itself, the second example will roll back. It's uncommon to get an exception on the commit, but it's possible.

like image 78
Bill Karwin Avatar answered Sep 13 '25 01:09

Bill Karwin