From: Daniele Varrazzo Date: Tue, 26 Sep 2023 16:27:25 +0000 (+0200) Subject: fix: don't raise spurious errors on cancel if the connection is closed X-Git-Tag: 3.1.12~1^2~2 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=b3e0be9869257cfa9602608caee4ebe96148f63f;p=thirdparty%2Fpsycopg.git fix: don't raise spurious errors on cancel if the connection is closed --- diff --git a/psycopg/psycopg/connection.py b/psycopg/psycopg/connection.py index 0ff3bcf68..82d597cbb 100644 --- a/psycopg/psycopg/connection.py +++ b/psycopg/psycopg/connection.py @@ -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: diff --git a/psycopg/psycopg/connection_async.py b/psycopg/psycopg/connection_async.py index 249048075..34e783488 100644 --- a/psycopg/psycopg/connection_async.py +++ b/psycopg/psycopg/connection_async.py @@ -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: