Skip to content

Commit b3e0be9

Browse files
committed
fix: don't raise spurious errors on cancel if the connection is closed
1 parent 125f93c commit b3e0be9

2 files changed

Lines changed: 13 additions & 6 deletions

File tree

‎psycopg/psycopg/connection.py‎

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -311,8 +311,17 @@ def cancel(self) -> None:
311311
"cancel() cannot be used with a prepared two-phase transaction"
312312
)
313313

314-
c = self.pgconn.get_cancel()
315-
c.cancel()
314+
self._try_cancel(self.pgconn)
315+
316+
@classmethod
317+
def _try_cancel(cls, pgconn: "PGconn") -> None:
318+
try:
319+
# Can fail if the connection is closed
320+
c = pgconn.get_cancel()
321+
except Exception as ex:
322+
logger.warning("couldn't try to cancel query: %s", ex)
323+
else:
324+
c.cancel()
316325

317326
def add_notice_handler(self, callback: NoticeHandler) -> None:
318327
"""
@@ -959,8 +968,7 @@ def wait(self, gen: PQGen[RV], timeout: Optional[float] = 0.1) -> RV:
959968
except KeyboardInterrupt:
960969
# On Ctrl-C, try to cancel the query in the server, otherwise
961970
# the connection will remain stuck in ACTIVE state.
962-
c = self.pgconn.get_cancel()
963-
c.cancel()
971+
self._try_cancel(self.pgconn)
964972
try:
965973
waiting.wait(gen, self.pgconn.socket, timeout=timeout)
966974
except e.QueryCanceled:

‎psycopg/psycopg/connection_async.py‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -349,8 +349,7 @@ async def wait(self, gen: PQGen[RV]) -> RV:
349349
except (asyncio.CancelledError, KeyboardInterrupt):
350350
# On Ctrl-C, try to cancel the query in the server, otherwise
351351
# the connection will remain stuck in ACTIVE state.
352-
c = self.pgconn.get_cancel()
353-
c.cancel()
352+
self._try_cancel(self.pgconn)
354353
try:
355354
await waiting.wait_async(gen, self.pgconn.socket)
356355
except e.QueryCanceled:

0 commit comments

Comments
 (0)