]> git.ipfire.org Git - thirdparty/sqlalchemy/sqlalchemy.git/commitdiff
- Context manager provided by Connection.begin()
authorMike Bayer <mike_mp@zzzcomputing.com>
Tue, 12 Jul 2011 23:34:25 +0000 (19:34 -0400)
committerMike Bayer <mike_mp@zzzcomputing.com>
Tue, 12 Jul 2011 23:34:25 +0000 (19:34 -0400)
will issue rollback() if the commit() fails,
not just if an exception occurs.

CHANGES
lib/sqlalchemy/engine/base.py
test/engine/test_transaction.py

diff --git a/CHANGES b/CHANGES
index cd2577fe9420a6a4ca6f3837b61523bb6d0ad4c3..5734405523d251002f189b46410351606abe8c08 100644 (file)
--- a/CHANGES
+++ b/CHANGES
@@ -69,6 +69,10 @@ CHANGES
     from the default.  [ticket:2209]
 
 - engine
+  - Context manager provided by Connection.begin()
+    will issue rollback() if the commit() fails,
+    not just if an exception occurs.
+
   - Use urllib.parse_qsl() in Python 2.6 and above,
     no deprecation warning about cgi.parse_qsl()
     [ticket:1682]
index 3cfe800814d699f82a488c8c65a628c55c5cc2ab..04c14c2b7e77ef058ad776dcc6feadb751b1c46d 100644 (file)
@@ -1979,11 +1979,14 @@ class Transaction(object):
 
     def __exit__(self, type, value, traceback):
         if type is None and self.is_active:
-            self.commit()
+            try:
+                self.commit()
+            except:
+                self.rollback()
+                raise
         else:
             self.rollback()
 
-
 class RootTransaction(Transaction):
     def __init__(self, connection):
         super(RootTransaction, self).__init__(connection, None)
index 1184befda9507ab68d797fec8318f86a970e720d..344a30734bc0b323a1cf52d3a4f8dba0fadf80ce 100644 (file)
@@ -159,6 +159,28 @@ class TransactionTest(fixtures.TestBase):
         assert len(result.fetchall()) == 0
         connection.close()
 
+    def test_with_interface(self):
+        connection = testing.db.connect()
+        trans = connection.begin()
+        connection.execute(users.insert(), user_id=1, user_name='user1')
+        connection.execute(users.insert(), user_id=2, user_name='user2')
+        try:
+            connection.execute(users.insert(), user_id=2, user_name='user2.5')
+        except Exception, e:
+            trans.__exit__(*sys.exc_info())
+
+        assert not trans.is_active
+        self.assert_(connection.scalar('select count(*) from '
+                     'query_users') == 0)
+
+        trans = connection.begin()
+        connection.execute(users.insert(), user_id=1, user_name='user1')
+        trans.__exit__(None, None, None)
+        assert not trans.is_active
+        self.assert_(connection.scalar('select count(*) from '
+                     'query_users') == 1)
+        connection.close()
+
     def test_close(self):
         connection = testing.db.connect()
         transaction = connection.begin()