Fix PQport to never return NULL if the connection is valid

From: Daniele Varrazzo <daniele(dot)varrazzo(at)gmail(dot)com>
To: PostgreSQL Hackers <pgsql-hackers(at)postgresql(dot)org>
Subject: Fix PQport to never return NULL if the connection is valid
Date: 2025-05-08 16:58:25
Message-ID: CA+mi_8YTS8WPZPO0PAb2aaGLwHuQ0DEQRF0ZMnvWss4y9FwDYQ@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

The documentation of PQport says that the function will never return
NULL, unless the connection is null:
https://www.postgresql.org/docs/17/libpq-status.html#LIBPQ-PQPORT

However this is not the case: it seems to return null when the port
specified is an empty string:

$ PSYCOPG_IMPL=python python3
>>> import psycopg
>>> conn = psycopg.connect("port=")
>>> from psycopg.pq import _pq_ctypes as libpq
>>> print(libpq.PQport(conn.pgconn._pgconn_ptr))
None

I have prepared a patch, which is attached, to fix the issue. However
the patch returns the default port in case of no info in
'conn->connhost'. Re-reading the docs, I find the behaviour confusing.

if there is an error producing the port information (perhaps if
the connection
has not been fully established or there was an error), it returns
an empty string.

If we have a successful connection but no port information I believe
that returning the default port would be the right answer from this
function (it's the port where the connection was established).

If the connection is unsuccessful, the documentation says that this
function will return an empty string. Is this useful info? If that's
the case, maybe we should finish with an if instead?

if (conn->status == CONNECTION_OK)
return DEF_PGPORT_STR;
else
return "";

Or, alternatively, maybe a better implementation would be to copy the
default port on 'conn->connhost[conn->whichhost].port' if the
connection is successful (or even before attempting connection, as to
be able to return the port we tried)?

Cheers

-- Daniele

Attachment Content-Type Size
0001-Fix-PQport-to-never-return-NULL-unless-the-connectio.patch text/x-patch 1.1 KB

Responses

Browse pgsql-hackers by date

  From Date Subject
Next Message Matthew Gabeler-Lee 2025-05-08 17:14:56 Re: Issue attaching a table to a partitioned table with an auto-referenced foreign key
Previous Message Paul A Jungwirth 2025-05-08 16:20:06 Re: SQL:2011 application time