]> git.ipfire.org Git - thirdparty/psycopg.git/commitdiff
fix: don't raise spurious errors on cancel if the connection is closed
authorDaniele Varrazzo <daniele.varrazzo@gmail.com>
Tue, 26 Sep 2023 16:27:25 +0000 (18:27 +0200)
committerDaniele Varrazzo <daniele.varrazzo@gmail.com>
Tue, 26 Sep 2023 20:47:35 +0000 (22:47 +0200)
psycopg/psycopg/connection.py
psycopg/psycopg/connection_async.py

index 0ff3bcf6842fae9f1002560f6d5987559e2a18fe..82d597cbb669e250755990f16185d1e1d94d7134 100644 (file)
@@ -311,8 +311,17 @@ class BaseConnection(Generic[Row]):
                 "cancel() cannot be used with a prepared two-phase transaction"
             )
 
-        c = self.pgconn.get_cancel()
-        c.cancel()
+        self._try_cancel(self.pgconn)
+
+    @classmethod
+    def _try_cancel(cls, pgconn: "PGconn") -> None:
+        try:
+            # Can fail if the connection is closed
+            c = pgconn.get_cancel()
+        except Exception as ex:
+            logger.warning("couldn't try to cancel query: %s", ex)
+        else:
+            c.cancel()
 
     def add_notice_handler(self, callback: NoticeHandler) -> None:
         """
@@ -959,8 +968,7 @@ class Connection(BaseConnection[Row]):
         except KeyboardInterrupt:
             # On Ctrl-C, try to cancel the query in the server, otherwise
             # the connection will remain stuck in ACTIVE state.
-            c = self.pgconn.get_cancel()
-            c.cancel()
+            self._try_cancel(self.pgconn)
             try:
                 waiting.wait(gen, self.pgconn.socket, timeout=timeout)
             except e.QueryCanceled:
index 2490480757b02b8cf52e44a03eb0aa9c0a45f2a9..34e7834883dce5f938d5d0bd08b964f7a7872b90 100644 (file)
@@ -349,8 +349,7 @@ class AsyncConnection(BaseConnection[Row]):
         except (asyncio.CancelledError, KeyboardInterrupt):
             # On Ctrl-C, try to cancel the query in the server, otherwise
             # the connection will remain stuck in ACTIVE state.
-            c = self.pgconn.get_cancel()
-            c.cancel()
+            self._try_cancel(self.pgconn)
             try:
                 await waiting.wait_async(gen, self.pgconn.socket)
             except e.QueryCanceled: