Support for transactions using 'with' statement

Issue #468 resolved
Former user created an issue

This patch allows SessionTransaction objects to be used with python 2.5's 'with' statement:

with session.create_transaction():
    item1 = sess.query(Item).get(1)
    item2 = sess.query(Item).get(2)
    item1.foo = 'bar'
    item2.bar = 'foo'

If the operations all complete successfully then the transaction is committed, otherwise it is rolled back. It's a bit simpler than:

trans = session.create_transaction()
try:
    item1 = sess.query(Item).get(1)
    item2 = sess.query(Item).get(2)
    item1.foo = 'bar'
    item2.bar = 'foo'
    trans.commit()
except:
    trans.rollback()
    raise

Comments (5)

  1. Mike Bayer repo owner

    beautiful. like in other tickets, i only have web access ATM so ETA on this will be by early next week...if youre bored, an extra patch for the documentation (unitofwork.txt) might be nice.

  2. Former user Account Deleted

    A few things I was thinking about are whether or not {{{enter}}} should return the transaction object, and if {{{exit}}} should check whether the transaction is closed before trying to commit or roll it back.

    As the patch is, this causes an error:

    with sess.create_transaction() as t:
        item1 = sess.query(Item).get(1)
        item2 = sess.query(Item).get(2)
        item1.foo = 'bar'
        item2.bar = 'foo'
        t.commit()
        # other stuff...
    

    since {{{t.exit}}} tries to commit the transaction again.

    It seems to me like it would make the most sense to have {{{exit}}} check if the transaction is closed, and if so, to neither commit nor rollback the transaction.

  3. Former user Account Deleted

    attachment:session.2.patch adds a check in __exit__ to see if the transaction has been closed (it checks self.session.transaction, is that the correct way to do this?)

    I also updated unitofwork.txt

  4. Mike Bayer repo owner

    yeah, i think checking the session is OK for now (its basically an is_closed() check).

  5. Log in to comment