From: Federico Caselli Date: Thu, 10 Jul 2025 22:21:54 +0000 (+0200) Subject: Re-raise ``CancelledError`` in asyncpg X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;ds=sidebyside;p=thirdparty%2Fsqlalchemy%2Fsqlalchemy.git 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 --- 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 6b9bb0677d..a5a5dc08fa 100644 --- a/lib/sqlalchemy/dialects/postgresql/asyncpg.py +++ b/lib/sqlalchemy/dialects/postgresql/asyncpg.py @@ -956,13 +956,16 @@ class AsyncAdapt_asyncpg_connection(AsyncAdapt_dbapi_connection): 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()