]> git.ipfire.org Git - thirdparty/psycopg.git/commitdiff
refactor: drop _try_cancel internal method.
authorDaniele Varrazzo <daniele.varrazzo@gmail.com>
Wed, 10 Apr 2024 20:16:47 +0000 (22:16 +0200)
committerDaniele Varrazzo <daniele.varrazzo@gmail.com>
Fri, 12 Apr 2024 22:10:44 +0000 (00:10 +0200)
This method was useful before introducing cancel_safe, which is now the
function of choice for internal cancelling.

Also refactor the exception handling to account for possible errors in
`PGcancel.cancel()`, not only in `PGconn.get_cancel()`, to make sure to
not clobber an exception bubbling up with ours, whatever happens to the
underlying connection.

docs/api/connections.rst
psycopg/psycopg/_connection_base.py

index a6d95d20b22d9f443a77627c680b52f0ce31282e..0f9462ce20aefea6fdfca5cff491e91c62cb825e 100644 (file)
@@ -303,7 +303,9 @@ The `!Connection` class
 
         .. warning::
 
-            The `!cancel()` method has a few shortcomings:
+            The `!cancel()` method is implemented using the :pq:`PQcancel`
+            function, which is deprecated since PostgreSQL 17, and has a few
+            shortcomings:
 
             - it is blocking even on async connections,
             - it `might use an insecure connection`__ even if the original
index 4fdda67b563e625226236cf7908b96cde54ca5cf..4944f1d3157b02626b65ba8d32819cbbff2eba9c 100644 (file)
@@ -293,8 +293,16 @@ class BaseConnection(Generic[Row]):
 
     def cancel(self) -> None:
         """Cancel the current operation on the connection."""
-        if self._should_cancel():
-            self._try_cancel(self.pgconn)
+        if not self._should_cancel():
+            return
+
+        # Don't fail cancelling (which might happen on connection closing) to
+        # avoid clobbering eventual exceptions with ours, which is less important.
+        try:
+            c = self.pgconn.get_cancel()
+            c.cancel()
+        except Exception as ex:
+            logger.warning("couldn't try to cancel query: %s", str(ex))
 
     def _should_cancel(self) -> bool:
         """Check whether the current command should actually be cancelled when
@@ -311,19 +319,6 @@ class BaseConnection(Generic[Row]):
             )
         return True
 
-    @classmethod
-    def _try_cancel(cls, pgconn: "PGconn") -> None:
-        """Try to cancel the current command using a PGcancel object,
-        which is deprecated since libpq 17.
-        """
-        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 _cancel_gen(self) -> PQGenConn[None]:
         try:
             cancel_conn = self.pgconn.cancel_conn()