From 7b9365cf9098ec17011a898d93ada7bd6d011e88 Mon Sep 17 00:00:00 2001 From: Federico Caselli Date: Fri, 11 Jul 2025 00:21:54 +0200 Subject: [PATCH] Re-raise ``CancelledError`` in asyncpg Re-raise catched ``CancelledError`` in the terminate method of the asyncpg dialect to avoid possible hangs of the code execution. Fixes: #12728 Change-Id: Ia9a353ac7504592be00355001ef40b13ab51375c (cherry picked from commit 36da2eaf3e23269f2cf28420ae73674beafd0661) --- doc/build/changelog/unreleased_20/12728.rst | 7 +++++++ lib/sqlalchemy/dialects/postgresql/asyncpg.py | 5 ++++- 2 files changed, 11 insertions(+), 1 deletion(-) create mode 100644 doc/build/changelog/unreleased_20/12728.rst diff --git a/doc/build/changelog/unreleased_20/12728.rst b/doc/build/changelog/unreleased_20/12728.rst new file mode 100644 index 0000000000..f710370b64 --- /dev/null +++ b/doc/build/changelog/unreleased_20/12728.rst @@ -0,0 +1,7 @@ +.. change:: + :tags: bug, postgresql + :tickets: 12728 + + Re-raise catched ``CancelledError`` in the terminate method of the + asyncpg dialect to avoid possible hangs of the code execution. + diff --git a/lib/sqlalchemy/dialects/postgresql/asyncpg.py b/lib/sqlalchemy/dialects/postgresql/asyncpg.py index 096892127b..36566b6740 100644 --- a/lib/sqlalchemy/dialects/postgresql/asyncpg.py +++ b/lib/sqlalchemy/dialects/postgresql/asyncpg.py @@ -910,13 +910,16 @@ class AsyncAdapt_asyncpg_connection(AdaptedConnection): asyncio.CancelledError, OSError, self.dbapi.asyncpg.PostgresError, - ): + ) as e: # in the case where we are recycling an old connection # that may have already been disconnected, close() will # fail with the above timeout. in this case, terminate # the connection without any further waiting. # see issue #8419 self._connection.terminate() + if isinstance(e, asyncio.CancelledError): + # re-raise CancelledError if we were cancelled + raise else: # not in a greenlet; this is the gc cleanup case self._connection.terminate() -- 2.47.2