Commits

Mike Bayer committed fc4e7dd

- [bug] If conn.begin() fails when calling
"with engine.begin()", the newly acquired
Connection is closed explicitly before
propagating the exception onward normally.

  • Participants
  • Parent commits d08bb32

Comments (0)

Files changed (3)

     before SQLAlchemy modifies the state 
     of the cursor.
 
+  - [bug] If conn.begin() fails when calling
+    "with engine.begin()", the newly acquired
+    Connection is closed explicitly before 
+    propagating the exception onward normally.
+
 - mssql
   - [feature] Added interim create_engine flag
     supports_unicode_binds to PyODBC dialect,

File lib/sqlalchemy/engine/base.py

 
         """
         conn = self.contextual_connect(close_with_result=close_with_result)
-        trans = conn.begin()
+        try:
+            trans = conn.begin()
+        except:
+            conn.close()
+            raise
         return Engine._trans_ctx(conn, trans, close_with_result)
 
     def transaction(self, callable_, *args, **kwargs):

File test/engine/test_execute.py

         testing.run_as_contextmanager(ctx, fn, 5, value=8)
         self._assert_fn(5, value=8)
 
+    def test_transaction_engine_ctx_begin_fails(self):
+        engine = engines.testing_engine()
+        class MockConnection(Connection):
+            closed = False
+            def begin(self):
+                raise Exception("boom")
+
+            def close(self):
+                MockConnection.closed = True
+        engine._connection_cls = MockConnection
+        fn = self._trans_fn()
+        assert_raises(
+            Exception, 
+            engine.begin
+        )
+        assert MockConnection.closed
+
     def test_transaction_engine_ctx_rollback(self):
         fn = self._trans_rollback_fn()
         ctx = testing.db.begin()