]> git.ipfire.org Git - thirdparty/psycopg.git/commitdiff
fix: better error on exit of a pipeline with broken connection
authorDaniele Varrazzo <daniele.varrazzo@gmail.com>
Sun, 27 Mar 2022 15:35:06 +0000 (17:35 +0200)
committerDaniele Varrazzo <daniele.varrazzo@gmail.com>
Sat, 2 Apr 2022 23:17:57 +0000 (01:17 +0200)
Raise an OperationalError with a message "the connection is closed" rather
than "connection pointer is NULL". The exception class was right already.

psycopg/psycopg/_pipeline.py
tests/test_pipeline.py
tests/test_pipeline_async.py

index 76b6d7d20d24b4117de14b7cc6953db7cb8a3406..429b2c75dc35bf34709a84929c172d8e5662a7a0 100644 (file)
@@ -9,7 +9,7 @@ from typing import Any, List, Optional, Union, Tuple, Type, TYPE_CHECKING
 
 from . import pq
 from . import errors as e
-from .pq import ExecStatus
+from .pq import ConnStatus, ExecStatus
 from .abc import PipelineCommand, PQGen
 from ._compat import Deque, TypeAlias
 from ._cmodule import _psycopg
@@ -63,7 +63,8 @@ class BasePipeline:
         self.pgconn.enter_pipeline_mode()
 
     def _exit(self) -> None:
-        self.pgconn.exit_pipeline_mode()
+        if self.pgconn.status != ConnStatus.BAD:
+            self.pgconn.exit_pipeline_mode()
 
     def _communicate_gen(self) -> PQGen[None]:
         """Communicate with pipeline to send commands and possibly fetch
index 331db905e75478aa5bb472e8d38174805217cd25..a19e4bdae99711cca91d6332519e450b9264da26 100644 (file)
@@ -30,6 +30,16 @@ def test_pipeline_reenter(conn: psycopg.Connection[Any]) -> None:
     assert p1.status == pq.PipelineStatus.OFF
 
 
+def test_pipeline_broken_conn_exit(conn: psycopg.Connection[Any]) -> None:
+    with pytest.raises(e.OperationalError):
+        with conn.pipeline():
+            conn.execute("select 1")
+            conn.close()
+            closed = True
+
+    assert closed
+
+
 def test_cursor_stream(conn):
     with conn.pipeline(), conn.cursor() as cur:
         with pytest.raises(psycopg.ProgrammingError):
index bb78d08225f01ffc965c8ea410297239fabf3f96..bd079c925203c34643189315c3583ba58598abed 100644 (file)
@@ -33,6 +33,16 @@ async def test_pipeline_reenter(aconn: psycopg.AsyncConnection[Any]) -> None:
     assert p1.status == pq.PipelineStatus.OFF
 
 
+async def test_pipeline_broken_conn_exit(aconn: psycopg.AsyncConnection[Any]) -> None:
+    with pytest.raises(e.OperationalError):
+        async with aconn.pipeline():
+            await aconn.execute("select 1")
+            await aconn.close()
+            closed = True
+
+    assert closed
+
+
 async def test_cursor_stream(aconn):
     async with aconn.pipeline(), aconn.cursor() as cur:
         with pytest.raises(psycopg.ProgrammingError):