Support for transactions using 'with' statement
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)
-
repo owner -
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.
-
Account Deleted attachment:session.2.patch adds a check in
__exit__
to see if the transaction has been closed (it checksself.session.transaction
, is that the correct way to do this?)I also updated unitofwork.txt
-
repo owner - changed status to resolved
-
repo owner yeah, i think checking the session is OK for now (its basically an is_closed() check).
- Log in to comment
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.