From: Daniele Varrazzo Date: Thu, 8 May 2025 20:47:50 +0000 (+0200) Subject: fix: avoid a blank "port=" in the repr() of object with connection X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=refs%2Fpull%2F1078%2Fhead;p=thirdparty%2Fpsycopg.git fix: avoid a blank "port=" in the repr() of object with connection --- diff --git a/psycopg/psycopg/_connection_info.py b/psycopg/psycopg/_connection_info.py index cf6896cf2..84554c6f9 100644 --- a/psycopg/psycopg/_connection_info.py +++ b/psycopg/psycopg/_connection_info.py @@ -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") diff --git a/psycopg/psycopg/pq/misc.py b/psycopg/psycopg/pq/misc.py index fc223163f..85d8f1082 100644 --- a/psycopg/psycopg/pq/misc.py +++ b/psycopg/psycopg/pq/misc.py @@ -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 "" diff --git a/tests/test_connection_info.py b/tests/test_connection_info.py index ea731ee0e..a50237d48 100644 --- a/tests/test_connection_info.py +++ b/tests/test_connection_info.py @@ -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()