]> git.ipfire.org Git - thirdparty/psycopg.git/commitdiff
Fix return error without exception on PQsocket call of broken connection
authorDaniele Varrazzo <daniele.varrazzo@gmail.com>
Sun, 21 Feb 2021 01:16:28 +0000 (02:16 +0100)
committerDaniele Varrazzo <daniele.varrazzo@gmail.com>
Sun, 28 Feb 2021 13:05:08 +0000 (14:05 +0100)
Still some weirdness here around: the method raises an exception on my
box (both with unix and tcp socket) but it seems to raise still a valid
number on certain databases on Travis. Make sure, in the test, at least
that it is a reasonable value.

psycopg3/psycopg3/pq/pq_ctypes.py
psycopg3_c/psycopg3_c/pq/pgconn.pyx
tests/pq/test_pgconn.py

index f017beb425425c666dd534a366c8e142a08916ee..1a58bc98baa568569d3e7cd2de5697ba867fd1a6 100644 (file)
@@ -207,7 +207,10 @@ class PGconn:
 
     @property
     def socket(self) -> int:
-        return self._call_int(impl.PQsocket)
+        rv = self._call_int(impl.PQsocket)
+        if rv == -1:
+            raise e.OperationalError("the connection is lost")
+        return rv
 
     @property
     def backend_pid(self) -> int:
index f277d13eff98e25fc7397ebba4a7109d2850f070..ccd431c1cfcef714dd8d58bf869e7362dbedf15d 100644 (file)
@@ -160,7 +160,10 @@ cdef class PGconn:
 
     @property
     def socket(self) -> int:
-        return _call_int(self, libpq.PQsocket)
+        rv = _call_int(self, libpq.PQsocket)
+        if rv == -1:
+            raise PQerror("the connection is lost")
+        return rv
 
     @property
     def backend_pid(self) -> int:
@@ -506,12 +509,12 @@ cdef char *_call_bytes(PGconn pgconn, conn_bytes_f func) except NULL:
     return rv
 
 
-cdef int _call_int(PGconn pgconn, conn_int_f func) except -1:
+cdef int _call_int(PGconn pgconn, conn_int_f func) except -2:
     """
     Call one of the pgconn libpq functions returning an int.
     """
     if not _ensure_pgconn(pgconn):
-        return -1
+        return -2
     return func(pgconn.pgconn_ptr)
 
 
index e122cd0922feef35341dc220f45bf5ff9714977f..c45fbfcc18abb1834172be1ebf4b4c0a7fc719e8 100644 (file)
@@ -295,6 +295,20 @@ def test_server_version(pgconn):
         pgconn.server_version
 
 
+def test_socket(pgconn):
+    socket = pgconn.socket
+    assert socket > 0
+    pgconn.exec_(
+        f"select pg_terminate_backend({pgconn.backend_pid})".encode("utf8")
+    )
+    # TODO: on my box it raises OperationalError as it should. Not on Travis,
+    # so let's see if at least an ok value comes out of it.
+    try:
+        assert pgconn.socket == socket
+    except psycopg3.OperationalError:
+        pass
+
+
 def test_error_message(pgconn):
     assert pgconn.error_message == b""
     res = pgconn.exec_(b"wat")