]> git.ipfire.org Git - thirdparty/psycopg.git/commitdiff
Make sure transaction blocks cannot be used more than once
authorDaniele Varrazzo <daniele.varrazzo@gmail.com>
Tue, 24 Nov 2020 12:26:18 +0000 (12:26 +0000)
committerDaniele Varrazzo <daniele.varrazzo@gmail.com>
Tue, 24 Nov 2020 12:26:18 +0000 (12:26 +0000)
See #12

psycopg3/psycopg3/transaction.py
tests/test_transaction.py
tests/test_transaction_async.py

index 8130e44acd01c1c3d4c6a21478864c0616d0f4b3..14c6adaba707c146d98d4f1a47a751732fab7374 100644 (file)
@@ -75,8 +75,10 @@ class BaseTransaction(Generic[ConnectionType]):
         return f"{self.__class__.__qualname__}({', '.join(args)})"
 
     def _enter_commands(self) -> List[str]:
-        assert self._yolo
-        self._yolo = False
+        if not self._yolo:
+            raise TypeError("transaction blocks cannot be use more than once")
+        else:
+            self._yolo = False
 
         self._outer_transaction = (
             self._conn.pgconn.transaction_status == TransactionStatus.IDLE
index 86652b9545217e6908f5adfb46a84734dca1a60e..1caa2c289c4d6ad2ef06a1d943af7a1f53f073e6 100644 (file)
@@ -106,6 +106,15 @@ def test_exposes_savepoint_name(conn):
             tx.savepoint_name = "bar"
 
 
+def test_cant_reenter(conn):
+    with conn.transaction() as tx:
+        pass
+
+    with pytest.raises(TypeError):
+        with tx:
+            pass
+
+
 def test_begins_on_enter(conn):
     """Transaction does not begin until __enter__() is called."""
     tx = conn.transaction()
index 8cae48e70f7e4f48e64048bc89f9dec241377e07..f9cbd420dff66d73b6bb70fef6ac8d830f37545c 100644 (file)
@@ -50,6 +50,15 @@ async def test_exposes_savepoint_name(aconn):
             tx.savepoint_name = "bar"
 
 
+async def test_cant_reenter(aconn):
+    async with aconn.transaction() as tx:
+        pass
+
+    with pytest.raises(TypeError):
+        async with tx:
+            pass
+
+
 async def test_begins_on_enter(aconn):
     """Transaction does not begin until __enter__() is called."""
     tx = aconn.transaction()