]> git.ipfire.org Git - thirdparty/psycopg.git/commitdiff
Add ConnInfo.hostaddr
authorDaniele Varrazzo <daniele.varrazzo@gmail.com>
Thu, 22 Apr 2021 12:28:53 +0000 (13:28 +0100)
committerDaniele Varrazzo <daniele.varrazzo@gmail.com>
Thu, 22 Apr 2021 12:28:53 +0000 (13:28 +0100)
Also add C implementation of PGconn.hostaddr.

psycopg3/psycopg3/conninfo.py
psycopg3_c/psycopg3_c/pq/pgconn.pyx
tests/pq/test_pgconn.py
tests/test_conninfo.py

index a05884f9ea68362e2255fd420ebad8f80a08487a..d6b1a681a76b549781ffafa162f00374802df60a 100644 (file)
@@ -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."""
index 75c918f22fefdf1c62e2bb2f9fb8a3d8091dcb35..6e16fb33f33d4a9c1db608f5db5b92bf96528883 100644 (file)
@@ -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(
+            <long><void *>self.pgconn_ptr, _pq_ctypes.PGconn_ptr)
+        return _pq_ctypes.PQhostaddr(ctypes_ptr)
 
     @property
     def port(self) -> bytes:
index 9587c2b11ef7fe5493204d419698084b99c03bf7..d2f501b1e801704b1f381e4f6a8456dc1b590cc2 100644 (file)
@@ -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
index b5343628465b5565996e92fda07835062fe7824a..64c75ef4583cf5fedbf7d5d7429761d051a4917e 100644 (file)
@@ -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):