From: Daniele Varrazzo Date: Thu, 22 Apr 2021 12:28:53 +0000 (+0100) Subject: Add ConnInfo.hostaddr X-Git-Tag: 3.0.dev0~66^2~5 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=62ae5a680860a74856c1f5f5d45ef265122400c4;p=thirdparty%2Fpsycopg.git Add ConnInfo.hostaddr Also add C implementation of PGconn.hostaddr. --- diff --git a/psycopg3/psycopg3/conninfo.py b/psycopg3/psycopg3/conninfo.py index a05884f9e..d6b1a681a 100644 --- a/psycopg3/psycopg3/conninfo.py +++ b/psycopg3/psycopg3/conninfo.py @@ -106,6 +106,11 @@ class ConnectionInfo: """The host name of the database.""" return self._get_pgconn_attr("host") + @property + def hostaddr(self) -> str: + """The server ip address of the connection.""" + return self._get_pgconn_attr("hostaddr") + @property def port(self) -> int: """The port of the database connection.""" diff --git a/psycopg3_c/psycopg3_c/pq/pgconn.pyx b/psycopg3_c/psycopg3_c/pq/pgconn.pyx index 75c918f22..6e16fb33f 100644 --- a/psycopg3_c/psycopg3_c/pq/pgconn.pyx +++ b/psycopg3_c/psycopg3_c/pq/pgconn.pyx @@ -9,6 +9,7 @@ from cpython.mem cimport PyMem_Malloc, PyMem_Free from cpython.bytes cimport PyBytes_AsString, PyBytes_AsStringAndSize from cpython.memoryview cimport PyMemoryView_FromObject +import ctypes import logging from psycopg3.pq import Format as PqFormat @@ -116,7 +117,13 @@ cdef class PGconn: @property def hostaddr(self) -> bytes: - return b'TODO' + # Available only from PG 12. Use the dynamic ctypes implementation + from psycopg3.pq import _pq_ctypes + + _ensure_pgconn(self) + ctypes_ptr = ctypes.cast( + self.pgconn_ptr, _pq_ctypes.PGconn_ptr) + return _pq_ctypes.PQhostaddr(ctypes_ptr) @property def port(self) -> bytes: diff --git a/tests/pq/test_pgconn.py b/tests/pq/test_pgconn.py index 9587c2b11..d2f501b1e 100644 --- a/tests/pq/test_pgconn.py +++ b/tests/pq/test_pgconn.py @@ -207,15 +207,8 @@ def test_hostaddr(pgconn): # not in info assert isinstance(pgconn.hostaddr, bytes), pgconn.hostaddr pgconn.finish() - if psycopg3.pq.__impl__ == "python": - with pytest.raises(psycopg3.OperationalError): - pgconn.hostaddr - - else: - if pgconn.hostaddr == b"TODO": - pytest.xfail("implement hostaddr in psycopg3_c.pq") - else: - assert False, "you did it! not fix the test" + with pytest.raises(psycopg3.OperationalError): + pgconn.hostaddr @pytest.mark.xfail diff --git a/tests/test_conninfo.py b/tests/test_conninfo.py index b53436284..64c75ef45 100644 --- a/tests/test_conninfo.py +++ b/tests/test_conninfo.py @@ -89,7 +89,8 @@ def test_no_munging(): class TestConnectionInfo: @pytest.mark.parametrize( - "attr", [("dbname", "db"), "host", "user", "password", "options"] + "attr", + [("dbname", "db"), "host", "hostaddr", "user", "password", "options"], ) def test_attrs(self, conn, attr): if isinstance(attr, tuple):