Skip to content

Commit 3221122

Browse files
committed
Fix #136: roll back transactions on exceptions.
1 parent b97ce73 commit 3221122

2 files changed

Lines changed: 12 additions & 16 deletions

File tree

gcloud/datastore/test_transaction.py

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -110,7 +110,6 @@ def test_context_manager_no_raise(self):
110110
self.assertEqual(xact.id(), None)
111111

112112
def test_context_manager_w_raise(self):
113-
# See https://github.com/GoogleCloudPlatform/gcloud-python/issues/136
114113
class Foo(Exception):
115114
pass
116115
_DATASET = 'DATASET'
@@ -125,13 +124,10 @@ class Foo(Exception):
125124
self.assertTrue(connection._xact is xact)
126125
raise Foo()
127126
except Foo:
128-
pass # XXX
129-
#self.assertEqual(xact.id(), None)
130-
#self.assertEqual(connection._rolled_back, (_DATASET, 234))
131-
#self.assertEqual(connection._xact, None)
132-
# XXX should *not* have committed
133-
self.assertEqual(connection._committed, (_DATASET, mutation))
134-
#self.assertEqual(connection._committed, None)
127+
self.assertEqual(xact.id(), None)
128+
self.assertEqual(connection._rolled_back, (_DATASET, 234))
129+
self.assertEqual(connection._xact, None)
130+
self.assertEqual(connection._committed, None)
135131
self.assertTrue(connection._xact is None)
136132
self.assertEqual(xact.id(), None)
137133

gcloud/datastore/transaction.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -21,18 +21,15 @@ class Transaction(object):
2121
... entity1.save()
2222
... entity2.save()
2323
24-
To rollback a transaction if there is an error::
24+
By derault, the transaction is rolled back is an error::
2525
2626
>>> from gcloud import datastore
2727
>>> dataset = datastore.get_dataset('dataset-id', email, key_path)
2828
>>> with dataset.transaction() as t:
29-
... try:
30-
... do_some_work()
31-
... entity1.save()
32-
... except:
33-
... t.rollback()
29+
... do_some_work()
30+
... raise Exception() # rolls back
3431
35-
If the transaction isn't rolled back,
32+
If the transaction block exists without an exception,
3633
it will commit by default.
3734
3835
.. warning::
@@ -249,4 +246,7 @@ def __enter__(self):
249246
return self
250247

251248
def __exit__(self, exc_type, exc_val, exc_tb):
252-
self.commit()
249+
if exc_type is None:
250+
self.commit()
251+
else:
252+
self.rollback()

0 commit comments

Comments
 (0)