]> git.ipfire.org Git - thirdparty/psycopg.git/commitdiff
fix: avoid a blank "port=" in the repr() of object with connection 1078/head
authorDaniele Varrazzo <daniele.varrazzo@gmail.com>
Thu, 8 May 2025 20:47:50 +0000 (22:47 +0200)
committerDaniele Varrazzo <daniele.varrazzo@gmail.com>
Fri, 9 May 2025 13:09:33 +0000 (15:09 +0200)
psycopg/psycopg/_connection_info.py
psycopg/psycopg/pq/misc.py
tests/test_connection_info.py

index cf6896cf2ff8ac56e7e6f733b8ced0404145c2bb..84554c6f97029aecdd9a29d5e17a8abd8ebce7dd 100644 (file)
@@ -41,19 +41,14 @@ class ConnectionInfo:
     @property
     def port(self) -> int:
         """The port of the active connection. See :pq:`PQport()`."""
-        if sport := self._get_pgconn_attr("port"):
-            return int(sport)
-        return self._get_compiled_port()
+        if port := self._get_pgconn_attr("port"):
+            return int(port)
 
-    def _get_compiled_port(sef) -> int:
         # As per docs: an empty string means the build default, not e.g.
         # something configured by PGPORT
         # https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNECT-PORT
-        for info in pq.Conninfo().get_defaults():
-            if info.keyword == b"port":
-                if info.compiled:
-                    return int(info.compiled)
-                break
+        elif port := pq.misc.get_compiled_port():
+            return int(port)
 
         raise e.InternalError("couldn't find the connection port")
 
index fc223163f015b3aa391f212a2c9d59c4f69519e1..85d8f10823bc338b040980bf8d4e9ffdd1d53977 100644 (file)
@@ -155,8 +155,8 @@ def connection_summary(pgconn: abc.PGconn) -> str:
         # Put together the (CONNECTION)
         if not pgconn.host.startswith(b"/"):
             parts.append(("host", pgconn.host.decode()))
-        if pgconn.port != b"5432":
-            parts.append(("port", pgconn.port.decode()))
+        if (port := pgconn.port.decode() or get_compiled_port()) != "5432":
+            parts.append(("port", port))
         if pgconn.user != pgconn.db:
             parts.append(("user", pgconn.user.decode()))
         parts.append(("database", pgconn.db.decode()))
@@ -186,3 +186,13 @@ def version_pretty(version: int) -> str:
         return f"{major}.{patch}"
     else:
         return f"{major}.{minor}.{patch}"
+
+
+@cache
+def get_compiled_port() -> str:
+    """Return the default port compiled with the libpq."""
+
+    from psycopg._conninfo_utils import get_param_def
+
+    info = get_param_def("port")
+    return info.compiled if info and info.compiled else ""
index ea731ee0edf21f7d494a92a552a8a2a40d9ca3b7..a50237d489880f42a89ae6a52ec0e27e881d7da3 100644 (file)
@@ -54,6 +54,8 @@ def test_blank_port(conn, monkeypatch):
     # assume 5432 is the compiled value
     assert conn.info.port == 5432
 
+    assert "port=" not in repr(conn)
+
 
 def test_get_params(conn, dsn):
     info = conn.info.get_parameters()