diff --git a/.zed/rules b/.zed/rules index 83fdcec30..d50eef27c 100644 --- a/.zed/rules +++ b/.zed/rules @@ -1123,7 +1123,11 @@ data. The rules: only by core/sources/source_ids.hash_source_id; one built from where the data lives is :, built only by location_source_id: csv:, delta_table:, sqlite_table::main., - postgresql_table:..
, + postgresql_table::/..
(the server the connection + reached, as libpq reports it: a host name lower-cased, an IPv6 address bracketed and + exploded, a socket directory as given, the port always a number; parameters naming several + servers, or a host beside a hostaddr that is not that address, give no default; + developer, November 18, 2026, ITL-1267), spiraldb_table:..
@
(developer, November 16, 2026); a location whose parts hold their separator has no default (source_ids.joined_location). A DBTableSource used directly (a generic connector, no database address) has no default: diff --git a/CLAUDE.md b/CLAUDE.md index 9473e07b7..3a90dd91b 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1167,7 +1167,11 @@ data. The rules: only by `core/sources/source_ids.hash_source_id`; one built from where the data lives is `:`, built only by `location_source_id`: `csv:`, `delta_table:`, `sqlite_table::main.
`, - `postgresql_table:..
`, + `postgresql_table::/..
` (the server the connection + reached, as libpq reports it: a host name lower-cased, an IPv6 address bracketed and + exploded, a socket directory as given, the port always a number; parameters naming several + servers, or a host beside a `hostaddr` that is not that address, give no default; + developer, November 18, 2026, ITL-1267), `spiraldb_table:..
@
` (developer, November 16, 2026); a location whose parts hold their separator has no default (`source_ids.joined_location`). A `DBTableSource` used directly (a generic connector, no database address) has no default: diff --git a/README.md b/README.md index 1f3b6d4b4..e2519ad40 100644 --- a/README.md +++ b/README.md @@ -39,7 +39,7 @@ Optional features are installed as extras, for example `uv add "orcapod[spiraldb |-------|------| | `orcapod[ray]` | Distributed execution with `RayExecutor` | | `orcapod[redis]` | `RedisCacher`, a Redis-backed hash cache | -| `orcapod[postgresql]` | The PostgreSQL connector, table source and file hash cache | +| `orcapod[postgresql]` | The PostgreSQL connector, table source and file hash cache (psycopg 3.1.17 or later) | | `orcapod[spiraldb]` | The SpiralDB connector and table source | | `orcapod[torch]` | PyTorch, for `torch.Tensor` values (any installed `torch` works) | | `orcapod[all]` | All of the above | diff --git a/changelog.d/ITL-1267.md b/changelog.d/ITL-1267.md new file mode 100644 index 000000000..6c041dfac --- /dev/null +++ b/changelog.d/ITL-1267.md @@ -0,0 +1,27 @@ +### Breaking changes and migration + +- The default source id of a `PostgreSQLTableSource` names the server the connection reached + (ITL-1267): `postgresql_table::/..
` (was + `postgresql_table:..
`), so one database, schema and table name on + two servers gives two ids. The host is the name or address as libpq reports it, a host name + in lower case, an IPv6 address in brackets in its exploded form (no `::`), a Unix-domain + socket directory as given (a Windows one with its drive too); the port is always the number used (without one in the DSN, a + service file's, else `PGPORT`, else libpq's compiled default, normally `5432`). + No user name, password or other connection parameter enters the id. The system-tag values + and source-info tokens of rows read from PostgreSQL without a `source_id` change with it; a + `source_id` you give is used as before, and a saved job keeps the id it was saved with. +- A PostgreSQL source whose DSN, `PGHOST` / `PGHOSTADDR` setting or service file names several + servers (`host=a,b`) has no default source id and raises `ValueError` unless it is given a + `source_id`: the server reached can change from one connection to the next. So does one + whose parameters give a host beside a different `hostaddr` (`host=db.example.org + hostaddr=192.0.2.1`), each from the DSN, a service file or the environment, as libpq takes + them: the connection is sent to the address, so the host name does not name the server + (two spellings of one IP address, compared by value, are one address). A host that would put + `::` in the address (a socket directory holding it or ending with `:`) gives no default either. A `hostaddr` given alone names the server by that + address. A database, schema or table name holding `/` has no default either, as one holding + `.` already had. +- `orcapod[postgresql]` requires psycopg 3.1.17 or later (was 3.0). The default PostgreSQL + source id relies on psycopg resolving a single host name of the DSN or `PGHOST` itself and + passing the address to libpq as `hostaddr`, which `Connection.connect` does from 3.1.17 + on; with an earlier psycopg, a service file's `hostaddr` beside a host name would be the + address used while the id named the host. diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index a695bd1b4..8553e3717 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -36,9 +36,17 @@ hashing) and produces the final immutable stream. `orcapod.sources` also provides database-backed sources (`SQLiteTableSource`, `PostgreSQLTableSource`, `SpiralDBTableSource`) and `PollingSource` for data that arrives over time; see the [API reference](../api/sources.md). Their default `source_id` names the table -where it lives (`sqlite_table::main.
`). `DBTableSource`, the base they share, -can also be used directly over any connector; a connector gives no address of its database, -so it then has no default and needs a `source_id`. +where it lives (`sqlite_table::main.
`, +`postgresql_table::/..
`, with the server the connection +reached; the +[hashing reference](../reference/hashing.md#default-source-ids-and-row-identifiers) has +every form). A PostgreSQL DSN that names several servers (`host=a,b`), or gives a host +beside a different `hostaddr` (`host=db.example.org hostaddr=192.0.2.1`; with +`host=127.0.0.1 hostaddr=127.0.0.1` the default stays), has no default; the same holds when +`PGHOST`, `PGHOSTADDR` or a service file gives either value. Give such a source a +`source_id`. `DBTableSource`, the base they share, can also be used directly +over any connector; a connector gives no address of its database, so it then has no default +and needs a `source_id`. Two construction rules apply to every source and are the most common first errors: diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index 25fe352b5..c2dd6917b 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -174,7 +174,7 @@ category, but we should make it totally overridable"; November 16, 2026, ITL-115 | `CSVSource` | `csv` | `csv:` | | `DeltaTableSource` | `delta_table` | `delta_table:` | | `SQLiteTableSource` | `sqlite_table` | `sqlite_table::main.
` (SQLite names a table `.
`; the main database's schema is `main`) | -| `PostgreSQLTableSource` | `postgresql_table` | `postgresql_table:..
` (the three-part name, from `current_database()` and `current_schema()`) | +| `PostgreSQLTableSource` | `postgresql_table` | `postgresql_table::/..
` (the server the connection reached, then the three-part name, from `current_database()` and `current_schema()`; see below) | | `DBTableSource` (any other connector) | `db_table` | none: `source_id` is required. The connector protocol exposes no database address, and the table name alone does not say which database the table is in (developer decision, November 16, 2026) | | `SpiralDBTableSource` | `spiraldb_table` | `spiraldb_table:..
@
` (Spiral's own table identifier, then SpiralDB's table id; `SPIRALDB_SOURCE_ID_HAS_TABLE_ID`) | | `PollingSource` | `polling_source` | `polling_source:semantic_v1:` of `impl.identity()` (never its `repr`) | @@ -185,8 +185,44 @@ A location default names the data where it lives, so two sources of one kind sha when they read the same data. The generic `DBTableSource` knows no database, so it has no default and refuses to be built without a `source_id`. A location whose parts cannot be told apart has no default (`joined_location`): a SQLite table name holding `:`, a PostgreSQL or -SpiralDB name holding `.`, a SpiralDB address or table id holding `@`. Such a source needs a -`source_id`. +SpiralDB name holding `.`, a PostgreSQL name holding `/`, a SpiralDB address or table id +holding `@`, a PostgreSQL address holding `::` (a socket directory holding it or ending with +`:`; `::` separates the parts of a source-info token). Such a source needs a `source_id`. + +A PostgreSQL default names the server the connection reached (developer, November 18, 2026, +ITL-1267), as libpq reports it, so one database, schema and table name on two servers gives +two ids. The host is the name or address as given, or the directory of a Unix-domain socket; +never the address a name resolved to. A `hostaddr` given alone is the host. +A host name is written in lower case (`DB.Example.ORG` and `db.example.org` are one id); an +IPv6 address in brackets and in its exploded form, which holds no `::` +(`[0000:0000:0000:0000:0000:0000:0000:0001]` for `::1`); an IPv4 address and a socket +directory as given (a Windows one with its drive, `C:/PgSockets`, keeps its case too). The port is always the number used: a DSN without one uses the port of +a service file, else `PGPORT`, else libpq's compiled default (normally `5432`), so a DSN that +gives the port the connection would use anyway and one without it give one id. Two spellings of one server are two +ids (`localhost` and `127.0.0.1`), as two spellings of one CSV path are. A DSN, a `PGHOST` +or `PGHOSTADDR` setting or a service file that names several servers (`host=a,b`) gives no +default: the server reached can change from one connection to the next. Neither do +parameters that give a host beside a different `hostaddr` (`host=db.example.org +hostaddr=192.0.2.1`; `host=127.0.0.1 hostaddr=127.0.0.1` keeps a default, as do two spellings of +one IP address, compared by value, an IPv6 zone included: `host=0:0:0:0:0:0:0:1 hostaddr=::1`), wherever each +comes from. libpq takes each parameter from the DSN, else a service file, else the +environment; psycopg (3.1.17 or later, the version `orcapod[postgresql]` requires for this) +resolves a single host name of the DSN or `PGHOST` itself, when neither +gives a `hostaddr`, and passes the address it reached as `hostaddr`, which overrides a service +file's. So a service file's `hostaddr` beside a host name of the DSN or `PGHOST` changes +nothing (the connection goes to the named host, and the default stays), while beside a +Unix-socket directory, which psycopg does not resolve, it is the address used and there is no +default; and a service file's host beside a `PGHOST` that psycopg resolved has no default +(libpq reports the service file's host, the connection went to the `PGHOST` address). libpq +sends the connection to the address, so +the host name does not name the server, and two such DSNs with one host and two addresses +would share an id. A name that DNS, a hosts file or a tunnel sends to another server is not +seen in the parameters: two servers reached under one name that way share a default id and +need a `source_id`. The same holds for a name that means this machine: a socket directory +(`/var/run/postgresql`), `localhost` or a loopback address (`127.0.0.1`, `::1`). Two +machines that each read their own server that way get one default id for one table name +(`postgresql_table:/var/run/postgresql:5432/d.public.t` on both), so when their rows or +provenance are combined, give each source a distinct `source_id`. No user name, password or other connection parameter enters the id. A row's record id is its row identifier (site 5), chosen by `record_id_columns` (a column name or several, in key order; every source accepts it): diff --git a/pyproject.toml b/pyproject.toml index 4011cecca..089125635 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -44,7 +44,7 @@ Issues = "https://github.com/metamorphic-labs/orcapod-python/issues" [project.optional-dependencies] redis = ["redis>=6.2.0"] ray = ["ray[default]==2.48.0", "ipywidgets>=8.1.7"] -postgresql = ["psycopg[binary]>=3.0"] +postgresql = ["psycopg[binary]>=3.1.17"] spiraldb = [ "pyspiral>=0.16.33", ] @@ -97,7 +97,7 @@ dev = [ "pytest-asyncio>=1.3.0", "pytest-cov>=6.1.1", "pytest-xdist>=3.6", - "psycopg[binary]>=3.0", + "psycopg[binary]>=3.1.17", "ray[default]==2.48.0", "redis>=6.2.0", "ruff>=0.14.4", diff --git a/src/orcapod/core/sources/postgresql_table_source.py b/src/orcapod/core/sources/postgresql_table_source.py index 892f227ae..0f12aa372 100644 --- a/src/orcapod/core/sources/postgresql_table_source.py +++ b/src/orcapod/core/sources/postgresql_table_source.py @@ -12,6 +12,8 @@ from __future__ import annotations +import ipaddress +import re from collections.abc import Collection, Iterator from contextlib import contextmanager from typing import TYPE_CHECKING, Any, ClassVar, cast @@ -30,6 +32,99 @@ from orcapod.config import OrcapodConfig +# A drive-qualified Windows socket directory (``C:/PgSockets``, ``c:\\pg``): libpq takes +# it as a path, not a host name, so it keeps its case. +_WINDOWS_DIRECTORY = re.compile(r"[A-Za-z]:[\\/]") + + +def _server_name(host: str) -> str: + """Return the host as it is written in a default source id. + + A host name is lower-cased (DNS names are case-insensitive); an IPv6 address is + bracketed, as in a URI, in its exploded form, so it never holds ``::`` and has one + spelling (a zone, ``%eth0``, is kept as given); an IPv4 address and a socket path + (``/...``, ``@...`` for a Linux abstract socket, or a drive-qualified Windows + directory such as ``C:/PgSockets`` or ``c:\\pg``) are kept as given. + + Args: + host: The host the connection reports (``PQhost``). + + Returns: + The host's name in the id. + """ + address, zone_mark, zone = host.partition("%") + try: + ip = ipaddress.ip_address(address) + except ValueError: + ip = None + if isinstance(ip, ipaddress.IPv6Address): + return f"[{ip.exploded}{zone_mark}{zone}]" + if ip is not None or host.startswith(("/", "@")) or _WINDOWS_DIRECTORY.match(host): + return host + return host.lower() + + +def _one_address(host: str, hostaddr: str) -> bool: + """Return whether a ``host`` and a ``hostaddr`` name one address. + + Equal text, or two IP literals of one parsed value (``0:0:0:0:0:0:0:1`` and + ``::1``; an IPv6 zone such as ``%eth0`` is part of the value). A host name beside + an address is never one address: what the name resolves to is not seen. + """ + if host == hostaddr: + return True + try: + return ipaddress.ip_address(host) == ipaddress.ip_address(hostaddr) + except ValueError: + return False + + +def postgresql_table_address( + host: str, port: int, database: str, schema: str, table: str +) -> str: + """Return ``:/..
``, a PostgreSQL table's address. + + The location of the default source id (``postgresql_table:
``, ITL-1267): + the server the connection reached, then the table's three-part name. The host is + written by ``_server_name``; the port is always the number. The address names one + table only: the parts of the three-part name hold neither ``.`` nor ``/``, so the + last ``/`` ends the server and the last ``:`` before it ends the host. + + Args: + host: The host the connection reports: a host name, an IP address or a + socket directory. + port: The port the connection used. + database: The connection's ``current_database()``. + schema: The connection's ``current_schema()``. + table: The table's name. + + Returns: + The table's address. + + Raises: + ValueError: If the host is empty, the database, schema or table name is + empty or holds ``.`` or ``/``, or the address would contain ``::`` (a + socket directory holding it, or a host ending with ``:``); give the + source a ``source_id``. + """ + if not host: + raise ValueError( + "the PostgreSQL connection reports no host, so the table has no default " + "source id; give the source a source_id" + ) + joined_location("/", database, schema, table) + name = joined_location(".", database, schema, table) + address = f"{_server_name(host)}:{port}/{name}" + if "::" in address: + raise ValueError( + f"the address {address!r} of the PostgreSQL table contains '::' (in the " + "host, such as a socket directory, or in a name), which separates the " + "parts of a source-info token, so the table has no default source id; " + "give the source a source_id" + ) + return address + + class PostgreSQLTableSource(DBTableSource): """A read-only Source backed by a table in a PostgreSQL database. @@ -59,7 +154,9 @@ class PostgreSQLTableSource(DBTableSource): record_id_columns: The key columns that identify a row; ``None``: the primary key (a table without one is refused); ``()``: the position. source_id: Canonical source name. Defaults to - ``postgresql_table:..
``. + ``postgresql_table::/..
`` + (``postgresql_table_address``); connection parameters that name + several servers, or a host beside a ``hostaddr``, give no default. label: Human-readable label for this source node. data_context: Data context governing type conversion and hashing. config: OrcaPod configuration. @@ -115,12 +212,13 @@ def __init__( @override def _table_address(self, connector: DBConnectorProtocol, table_name: str) -> str: - """Return ``..
``, the table's three-part name. + """Return ``:/..
``, the table's address. - The SQL standard's catalog.schema.table, which PostgreSQL documents as - ``database.schema.table``; the database and schema are the connection's - ``current_database()`` and ``current_schema()``, where the connector finds - the table (ITL-1154). + The server the connection reached (host and port as libpq reports them), + then the table's three-part name, ``database.schema.table``, from the + connection's ``current_database()`` and ``current_schema()``, where the + connector finds the table (ITL-1154, ITL-1267). Built by + ``postgresql_table_address``. Args: connector: The connector the source reads through. @@ -128,9 +226,34 @@ def _table_address(self, connector: DBConnectorProtocol, table_name: str) -> str Returns: The table's address. + + Raises: + ValueError: If the connection parameters name several servers (the one + reached can change from one connection to the next), or give a + ``hostaddr`` beside a host that is not that address (the connection + is sent to the address, so the host does not name the server). """ - database, schema = cast("PostgreSQLConnector", connector).current_location() - return joined_location(".", database, schema, table_name) + pg = cast("PostgreSQLConnector", connector) + host, hostaddr = pg.given_server() + if "," in host or "," in hostaddr: + raise ValueError( + f"the connection parameters of the PostgreSQL source over table " + f"{table_name!r} (its DSN, PGHOST or PGHOSTADDR, or a service file) " + "name several servers, and the one reached can change from one " + "connection to the next, so the table has no default source id; give " + "the source a source_id" + ) + if host and hostaddr and not _one_address(host, hostaddr): + raise ValueError( + f"the connection parameters of the PostgreSQL source over table " + f"{table_name!r} (its DSN, PGHOST or PGHOSTADDR, or a service file) " + f"give the host {host!r} and the address {hostaddr!r}: the connection " + "is sent to the address, so the host name alone does not identify " + "the server, and the table has no default source id; give the source " + "a source_id" + ) + host, port, database, schema = pg.current_location() + return postgresql_table_address(host, port, database, schema, table_name) @contextmanager @override diff --git a/src/orcapod/databases/postgresql_connector.py b/src/orcapod/databases/postgresql_connector.py index 39be7f6d2..cd59c4dc4 100644 --- a/src/orcapod/databases/postgresql_connector.py +++ b/src/orcapod/databases/postgresql_connector.py @@ -15,6 +15,7 @@ import itertools import logging +import os import re import threading import uuid @@ -343,6 +344,23 @@ def _field_has_metadata(field: pa.Field) -> bool: return False +def _psycopg_server(dsn: str) -> tuple[str, str]: + """Return the ``host`` and ``hostaddr`` psycopg reads for ``dsn``, now. + + Each from the DSN, else from ``PGHOST`` / ``PGHOSTADDR`` (a service file is + libpq's, and psycopg does not read it), ``""`` when neither gives one. psycopg + decides from these whether it resolves the host itself. + """ + from psycopg.conninfo import conninfo_to_dict + + given = conninfo_to_dict(dsn) + + def supplied(key: str, envvar: str) -> str: + return str((given[key] if key in given else os.environ.get(envvar)) or "") + + return supplied("host", "PGHOST"), supplied("hostaddr", "PGHOSTADDR") + + # --------------------------------------------------------------------------- # PostgreSQLConnector # --------------------------------------------------------------------------- @@ -365,6 +383,10 @@ class PostgreSQLConnector: def __init__(self, dsn: str) -> None: self._dsn = dsn + # The host and hostaddr psycopg reads for this connection (the DSN, else + # PGHOST / PGHOSTADDR), taken when it connects: ``given_server`` must not + # read an environment changed since (ITL-1267). + self._psycopg_server = _psycopg_server(dsn) self._conn: Any = psycopg.connect(dsn, autocommit=False) self._lock = threading.RLock() # RLock required: iter_batches → _resolve_column_type_lookup → get_column_info re-enters the lock self._cursor_seq = itertools.count() @@ -403,23 +425,82 @@ def get_table_names(self) -> list[str]: ) return [row[0] for row in cur.fetchall()] - def current_location(self) -> tuple[str, str]: - """Return ``(current_database(), current_schema())`` of the connection. + def current_location(self) -> tuple[str, int, str, str]: + """Return the server, database and schema the connection reached. - Where the connector finds its tables: the first two parts of a table's - three-part name, ``database.schema.table``. + ``(host, port, current_database(), current_schema())``: where the connector + finds its tables. The host and port are what libpq reports for the live + connection (``PQhost``, ``PQport``): the host name or IP address as given + (with ``host`` and ``hostaddr`` both given, the host; ``given_server`` tells + that case apart), or the directory of a Unix-domain socket; the port is the + one used (when the DSN gives none, a service file's, else ``PGPORT``, else + libpq's compiled default). Never the resolved address, the user, the password + or any other connection parameter (ITL-1267). Returns: - The database and schema names. + The host, the port, the database and the schema. + + Raises: + ValueError: If the connection has no current schema. """ with self._lock: conn = self._require_open() + host, port = conn.info.host, conn.info.port with conn.cursor() as cur: cur.execute("SELECT current_database(), current_schema()") row = cur.fetchone() if row is None or row[0] is None or row[1] is None: raise ValueError("the PostgreSQL connection has no current schema") - return str(row[0]), str(row[1]) + return str(host), int(port), str(row[0]), str(row[1]) + + def given_server(self) -> tuple[str, str]: + """Return the ``host`` and the user's ``hostaddr`` of the connection. + + libpq takes each parameter from the DSN, else from a service file, else from + the environment (``PGHOST``, ``PGHOSTADDR``); the connection reports what it + took (its parameters), so the host and the address returned are the ones the + connection used, wherever they came from. One address is not the user's: + psycopg resolves a single host of the DSN or the environment itself (not a + Unix-socket directory, and only when neither gives a ``hostaddr``) and passes + the address it reached as ``hostaddr``, which overrides a service file's. + That address is dropped (``""``) when the host the connection reports is the + host psycopg resolved; when a service file's host overrode the environment's, + the connection was sent to the environment host's address, which is + returned. A value may be a comma-separated list (``host=a,b``, + ``postgresql://a:5432,b:5433/db``): libpq then connects to the first server + that answers. psycopg splits such a list of the DSN or the environment into + one attempt per server, so that list is returned as given. + + This relies on one psycopg behaviour, that of ``Connection.connect`` in + psycopg 3.1.17 and later (earlier releases passed the DSN to libpq + unchanged): a single host name of the DSN or ``PGHOST``, with no + ``hostaddr`` there, is resolved by psycopg and passed to libpq as + ``hostaddr`` (``TestPsycopgResolvesTheHost`` pins it). + + What psycopg read from the DSN and the environment is taken when the + connector connected, so a later change of ``PGHOST`` or ``PGHOSTADDR`` + changes nothing here; the host and the address are what the connection + reports. + + Returns: + The host and the host address, each ``""`` when there is none. + """ + host, hostaddr = self._psycopg_server + if "," in host or "," in hostaddr: + return host, hostaddr + with self._lock: + reported = self._require_open().info.get_parameters() + used_host = str(reported.get("host", "")) + used_hostaddr = str(reported.get("hostaddr", "")) + resolved_by_psycopg = ( + bool(host) + and not hostaddr + and not host.startswith("/") + and host[1:2] != ":" # a Windows socket directory, as psycopg tests it + ) + if resolved_by_psycopg and used_host == host: + used_hostaddr = "" + return used_host, used_hostaddr def get_pk_columns(self, table_name: str) -> list[str]: """Return primary-key column names in key-sequence order.""" diff --git a/tests/test_core/sources/test_postgresql_table_source.py b/tests/test_core/sources/test_postgresql_table_source.py index e2f79270d..b00d88da7 100644 --- a/tests/test_core/sources/test_postgresql_table_source.py +++ b/tests/test_core/sources/test_postgresql_table_source.py @@ -1,6 +1,7 @@ """Unit tests for PostgreSQLTableSource.""" from __future__ import annotations +from typing import ClassVar from unittest.mock import MagicMock, patch import pyarrow as pa import pytest @@ -73,7 +74,8 @@ def _make_mock_connector( mock.get_table_names.return_value = table_names mock.get_pk_columns.return_value = pk_columns - mock.current_location.return_value = ("orcapod", "public") + mock.current_location.return_value = ("localhost", 5432, "orcapod", "public") + mock.given_server.return_value = ("localhost", "") mock.get_column_info.return_value = [] mock.iter_batches.return_value = iter(batches) return mock @@ -176,13 +178,16 @@ def test_composite_pk_all_columns_are_tags(self): assert "user_id" in tag_schema assert "event_id" in tag_schema - def test_default_source_id_is_table_name(self): + def test_default_source_id_names_server_and_table(self): from orcapod.core.sources import PostgreSQLTableSource with patch(_PATCH) as mock_cls: mock_cls.return_value = _make_mock_connector() src = PostgreSQLTableSource(DSN, "measurements", tag_only_columns=True) - assert src.source_id == "postgresql_table:orcapod.public.measurements" + assert ( + src.source_id + == "postgresql_table:localhost:5432/orcapod.public.measurements" + ) def test_explicit_source_id_overrides_default(self): from orcapod.core.sources import PostgreSQLTableSource @@ -444,7 +449,7 @@ def test_has_tag_columns(self): def test_has_source_id(self): assert ( self._make_src().to_config()["source_id"] - == "postgresql_table:orcapod.public.measurements" + == "postgresql_table:localhost:5432/orcapod.public.measurements" ) def test_has_content_hash(self): @@ -536,3 +541,326 @@ def test_resolve_source_from_config_dispatches_to_postgresql_table_source(): src2 = resolve_source_from_config(config) assert isinstance(src2, PostgreSQLTableSource) + + +# =========================================================================== +# 12. The default source id names the server (ITL-1267) +# =========================================================================== + + +def _server_connector( + host: str, + port: int, + database: str = "orcapod", + schema: str = "public", + *, + given: tuple[str, str] | None = None, +) -> MagicMock: + """A mocked connector whose connection reports ``host``, ``port`` and location. + + ``given`` is the ``host`` and ``hostaddr`` the user gave (``given_server``); + by default the host alone. + """ + mock = _make_mock_connector() + mock.current_location.return_value = (host, port, database, schema) + mock.given_server.return_value = (host, "") if given is None else given + return mock + + +class TestTableAddress: + """``postgresql_table_address``: the location of the default source id.""" + + @pytest.mark.parametrize( + ("host", "port", "expected"), + [ + ("db.example.org", 5432, "db.example.org:5432/orcapod.public.t"), + ("db.example.org", 5433, "db.example.org:5433/orcapod.public.t"), + # A DNS name is case-insensitive: one spelling. + ("DB.Example.ORG", 5432, "db.example.org:5432/orcapod.public.t"), + ("LOCALHOST", 5432, "localhost:5432/orcapod.public.t"), + # An IPv4 address as reported. + ("127.0.0.1", 5432, "127.0.0.1:5432/orcapod.public.t"), + # An IPv6 address: bracketed, in the exploded form (never '::'). + ( + "::1", + 5432, + "[0000:0000:0000:0000:0000:0000:0000:0001]:5432/orcapod.public.t", + ), + ( + "2001:DB8::1", + 5432, + "[2001:0db8:0000:0000:0000:0000:0000:0001]:5432/orcapod.public.t", + ), + ( + "2001:db8:0:0:0:0:0:1", + 5432, + "[2001:0db8:0000:0000:0000:0000:0000:0001]:5432/orcapod.public.t", + ), + ( + "fe80::1%eth0", + 5432, + "[fe80:0000:0000:0000:0000:0000:0000:0001%eth0]:5432/orcapod.public.t", + ), + # A Unix-domain socket directory, as reported, case kept. + ( + "/var/run/postgresql", + 5432, + "/var/run/postgresql:5432/orcapod.public.t", + ), + ("/Tmp/PG", 5433, "/Tmp/PG:5433/orcapod.public.t"), + # A Linux abstract-namespace socket, as reported. + ("@pgsock", 5432, "@pgsock:5432/orcapod.public.t"), + # A drive-qualified Windows socket directory, as reported, case kept. + ("C:/PgSockets", 5432, "C:/PgSockets:5432/orcapod.public.t"), + ("c:\\Pg", 5433, "c:\\Pg:5433/orcapod.public.t"), + ("D:/X/Y", 5432, "D:/X/Y:5432/orcapod.public.t"), + # A one-letter or two-letter DNS name is still a name: lower-cased. + ("C", 5432, "c:5432/orcapod.public.t"), + ("Db", 5433, "db:5433/orcapod.public.t"), + ], + ) + def test_address(self, host: str, port: int, expected: str) -> None: + from orcapod.core.sources.postgresql_table_source import ( + postgresql_table_address, + ) + + assert postgresql_table_address(host, port, "orcapod", "public", "t") == ( + expected + ) + + def test_spellings_of_one_ipv6_address_give_one_address(self) -> None: + from orcapod.core.sources.postgresql_table_source import ( + postgresql_table_address, + ) + + addresses = { + postgresql_table_address(host, 5432, "d", "s", "t") + for host in ("::1", "0::1", "0:0:0:0:0:0:0:1") + } + assert len(addresses) == 1 + + @pytest.mark.parametrize( + ("database", "schema", "table"), + [ + ("a/b", "public", "t"), + ("orcapod", "a/b", "t"), + ("orcapod", "public", "a/b"), + ("a.b", "public", "t"), + ("orcapod", "a.b", "t"), + ("orcapod", "public", "a.b"), + ], + ) + def test_separator_in_a_name_has_no_address( + self, database: str, schema: str, table: str + ) -> None: + from orcapod.core.sources.postgresql_table_source import ( + postgresql_table_address, + ) + + with pytest.raises(ValueError, match="source_id"): + postgresql_table_address("localhost", 5432, database, schema, table) + + @pytest.mark.parametrize( + "host", + ["/tmp/pg::sock", "/a::b/c", "@pg::sock", "/tmp/pg:", "/tmp/a:b:"], + ids=[ + "socket directory holding ::", + ":: in the middle", + "abstract socket holding ::", + "socket directory ending with ':'", + "':' inside and at the end", + ], + ) + def test_a_host_that_would_put_double_colon_in_the_address_has_none( + self, host: str + ) -> None: + """``::`` separates a source-info token: refused, asking for a source_id.""" + from orcapod.core.sources.postgresql_table_source import ( + postgresql_table_address, + ) + + with pytest.raises( + ValueError, match="contains '::'.*give the source a source_id" + ): + postgresql_table_address(host, 5432, "orcapod", "public", "t") + + def test_a_single_colon_in_a_socket_directory_is_kept(self) -> None: + from orcapod.core.sources.postgresql_table_source import ( + postgresql_table_address, + ) + + assert postgresql_table_address("/tmp/a:b", 5432, "d", "s", "t") == ( + "/tmp/a:b:5432/d.s.t" + ) + + def test_empty_host_has_no_address(self) -> None: + from orcapod.core.sources.postgresql_table_source import ( + postgresql_table_address, + ) + + with pytest.raises(ValueError, match="source_id"): + postgresql_table_address("", 5432, "orcapod", "public", "t") + + +class TestDefaultSourceIdNamesServer: + def _source( + self, connector: MagicMock, dsn: str = DSN, source_id: str | None = None + ): + from orcapod.core.sources import PostgreSQLTableSource + + with patch(_PATCH) as mock_cls: + mock_cls.return_value = connector + return PostgreSQLTableSource( + dsn, "measurements", source_id=source_id, tag_only_columns=True + ) + + def test_one_table_name_on_several_servers_gives_several_ids(self) -> None: + servers = [ + ("db.example.org", 5432), + ("db.example.org", 5433), + ("db2.example.org", 5432), + ("/var/run/postgresql", 5432), + ] + ids = [self._source(_server_connector(h, p)).source_id for h, p in servers] + assert ids == [ + "postgresql_table:db.example.org:5432/orcapod.public.measurements", + "postgresql_table:db.example.org:5433/orcapod.public.measurements", + "postgresql_table:db2.example.org:5432/orcapod.public.measurements", + "postgresql_table:/var/run/postgresql:5432/orcapod.public.measurements", + ] + # In the reverse order each source keeps its own id. + reversed_ids = [ + self._source(_server_connector(h, p)).source_id + for h, p in reversed(servers) + ] + assert reversed_ids == list(reversed(ids)) + + def test_one_server_gives_one_id_whatever_the_dsn(self) -> None: + dsns = [ + "postgresql://alice:s3cret@db.example.org:5432/orcapod", + "host=db.example.org port=5432 dbname=orcapod user=alice password=s3cret", + "host=DB.EXAMPLE.ORG dbname=orcapod user=bob", + ] + ids = { + self._source(_server_connector("db.example.org", 5432), dsn).source_id + for dsn in dsns + } + assert ids == { + "postgresql_table:db.example.org:5432/orcapod.public.measurements" + } + + @pytest.mark.parametrize( + "dsn", + [ + "postgresql://alice:s3cret@db.example.org:5432/orcapod", + "host=db.example.org port=5432 dbname=orcapod user=alice password=s3cret", + ], + ) + def test_id_never_holds_user_or_password(self, dsn: str) -> None: + source_id = self._source( + _server_connector("db.example.org", 5432), dsn + ).source_id + assert "alice" not in source_id + assert "s3cret" not in source_id + + SEVERAL_SERVERS: ClassVar[list[tuple[str, str]]] = [ + ("a.example.org,b.example.org", ""), + ("b.example.org,a.example.org", ""), + ("", "192.0.2.1,192.0.2.2"), + ("a.example.org,b.example.org", "192.0.2.1,192.0.2.2"), + ] + # A host beside a hostaddr that is not that address: the connection is sent to + # the address, so the host does not name the server. + HOST_BESIDE_HOSTADDR: ClassVar[list[tuple[str, str]]] = [ + ("db.example.org", "192.0.2.1"), + ("db.example.org", "192.0.2.2"), + ("localhost", "127.0.0.1"), + ("/var/run/postgresql", "192.0.2.1"), + ("192.0.2.1", "192.0.2.2"), + ] + + @pytest.mark.parametrize("given", SEVERAL_SERVERS) + def test_several_servers_have_no_default(self, given: tuple[str, str]) -> None: + connector = _server_connector("db.example.org", 5432, given=given) + with pytest.raises(ValueError, match="several servers.*source_id"): + self._source(connector) + connector.current_location.assert_not_called() + + @pytest.mark.parametrize("given", HOST_BESIDE_HOSTADDR) + def test_host_beside_hostaddr_has_no_default(self, given: tuple[str, str]) -> None: + connector = _server_connector(given[0], 5432, given=given) + with pytest.raises( + ValueError, match="host name alone does not identify.*source_id" + ): + self._source(connector) + connector.current_location.assert_not_called() + + @pytest.mark.parametrize( + ("host", "hostaddr"), + [ + ("0:0:0:0:0:0:0:1", "::1"), + ("::1", "0:0:0:0:0:0:0:1"), + ("2001:DB8::1", "2001:db8:0:0:0:0:0:1"), + ("2001:db8:0:0:0:0:0:1", "2001:DB8::1"), + ("fe80::1%eth0", "fe80:0:0:0:0:0:0:1%eth0"), + ], + ids=[ + "exploded host, short address", + "short host, exploded address", + "upper case host", + "upper case address", + "one zone", + ], + ) + def test_two_spellings_of_one_ip_address_name_it( + self, host: str, hostaddr: str + ) -> None: + connector = _server_connector(host, 5432, given=(host, hostaddr)) + source_id = self._source(connector).source_id + assert source_id.startswith("postgresql_table:[") + assert source_id.endswith("]:5432/orcapod.public.measurements") + + @pytest.mark.parametrize( + ("host", "hostaddr"), + [ + ("fe80::1%eth0", "fe80::1"), + ("fe80::1", "fe80::1%eth0"), + ("fe80::1%eth0", "fe80::1%eth1"), + ("::ffff:127.0.0.1", "127.0.0.1"), + ("::1", "::2"), + ("localhost", "::1"), + ], + ids=[ + "zone only on the host", + "zone only on the address", + "two zones", + "IPv4-mapped against IPv4", + "two IPv6 addresses", + "a name beside an IPv6 address", + ], + ) + def test_different_addresses_or_a_name_still_have_no_default( + self, host: str, hostaddr: str + ) -> None: + connector = _server_connector(host, 5432, given=(host, hostaddr)) + with pytest.raises(ValueError, match="host name alone does not identify"): + self._source(connector) + + def test_hostaddr_alone_or_equal_to_the_host_names_the_address(self) -> None: + # libpq reports the address as the host when no host is given; a host that + # is the address itself names it too. + for given in [("", "192.0.2.1"), ("192.0.2.1", "192.0.2.1")]: + connector = _server_connector("192.0.2.1", 5432, given=given) + assert self._source(connector).source_id == ( + "postgresql_table:192.0.2.1:5432/orcapod.public.measurements" + ) + + @pytest.mark.parametrize( + "given", [("db.example.org", ""), *SEVERAL_SERVERS, *HOST_BESIDE_HOSTADDR] + ) + def test_given_source_id_is_used_as_given(self, given: tuple[str, str]) -> None: + connector = _server_connector("db.example.org", 5432, given=given) + src = self._source(connector, source_id="measurements_v1") + assert src.source_id == "measurements_v1" + connector.current_location.assert_not_called() + connector.given_server.assert_not_called() diff --git a/tests/test_core/sources/test_postgresql_table_source_integration.py b/tests/test_core/sources/test_postgresql_table_source_integration.py index 0a94410b8..46592b213 100644 --- a/tests/test_core/sources/test_postgresql_table_source_integration.py +++ b/tests/test_core/sources/test_postgresql_table_source_integration.py @@ -16,9 +16,12 @@ from __future__ import annotations +import ipaddress import os import uuid -from collections.abc import Iterator +from collections.abc import Iterator, Mapping, Sequence +from types import MappingProxyType +from urllib.parse import quote, urlencode import pytest @@ -260,3 +263,372 @@ def double_response(trial: int, response: float) -> float: tag_values = sorted([tags["session_id"] for tags, _ in fn_outputs[0]]) assert tag_values == ["s1", "s2", "s3"] + + +# --------------------------------------------------------------------------- +# The default source id names the server (ITL-1267) +# --------------------------------------------------------------------------- + + +# The test server's connection parameters, read from the PG* environment once, when +# the module is imported: before any fixture (``no_server_env``) or test changes it. +_SERVER: Mapping[str, str] = MappingProxyType( + { + "host": os.environ.get("PGHOST", "localhost"), + "port": os.environ.get("PGPORT", "5432"), + "dbname": os.environ.get("PGDATABASE", "testdb"), + "user": os.environ.get("PGUSER", "postgres"), + "password": os.environ.get("PGPASSWORD", "postgres"), + } +) + + +def _keyword_dsn(schema: str, **params: str | None) -> str: + """A keyword DSN for the test server; a parameter given as None is left out. + + The parameters given come after the server's others, in the order given. + """ + merged: dict[str, str | None] = { + **{key: value for key, value in _SERVER.items() if key not in params}, + **params, + } + parts = [f"{key}={value}" for key, value in merged.items() if value is not None] + return " ".join([*parts, f"options=-csearch_path={schema}"]) + + +@pytest.fixture +def server_table(pg_schema: str) -> str: + """A one-row table ``t`` in the test schema; returns the schema.""" + with psycopg.connect(_keyword_dsn(pg_schema)) as conn: + with conn.cursor() as cur: + cur.execute('CREATE TABLE "t" (k TEXT PRIMARY KEY, x INTEGER)') + cur.execute("INSERT INTO \"t\" VALUES ('a', 1)") + conn.commit() + return pg_schema + + +@pytest.fixture +def no_server_env(monkeypatch: pytest.MonkeyPatch) -> None: + """Keep the PG* host, port and service variables out of the DSNs a test builds.""" + for envvar in ("PGHOST", "PGHOSTADDR", "PGPORT", "PGSERVICE"): + monkeypatch.delenv(envvar, raising=False) + + +def _source_id(dsn: str) -> str: + from orcapod.core.sources import PostgreSQLTableSource + + return PostgreSQLTableSource(dsn, "t", tag_only_columns=True).source_id + + +def _expected(host: str, schema: str, port: str | None = None) -> str: + return ( + f"postgresql_table:{host}:{port or _SERVER['port']}/" + f"{_SERVER['dbname']}.{schema}.t" + ) + + +def _id_host(host: str) -> str: + """How the default id writes the test server's host: an IPv6 address bracketed + and exploded, an IPv4 address as given, a name in lower case.""" + try: + ip = ipaddress.ip_address(host) + except ValueError: + return host.lower() + return f"[{ip.exploded}]" if ip.version == 6 else host + + +def _uri( + schema: str, *, host: str | None = None, query: Sequence[tuple[str, str]] = () +) -> str: + """A URI DSN for the test server, every component percent-encoded. + + ``host`` defaults to the test server's; ``""`` leaves it out (the query then + names the server). An IPv6 literal is bracketed, its zone's ``%`` encoded. + """ + server = _SERVER["host"] if host is None else host + if ":" in server: + netloc_host = "[" + server.replace("%", "%25") + "]" + else: + netloc_host = quote(server, safe="") + params = [*query, ("options", f"-csearch_path={schema}")] + return ( + f"postgresql://{quote(_SERVER['user'], safe='')}:" + f"{quote(_SERVER['password'], safe='')}@{netloc_host}:{_SERVER['port']}/" + f"{quote(_SERVER['dbname'], safe='')}?{urlencode(params, quote_via=quote)}" + ) + + +def _requires_localhost() -> None: + if _SERVER["host"] != "localhost": + pytest.skip("needs the test server at PGHOST=localhost, as in CI") + + +@pytest.mark.postgres +class TestDefaultSourceIdOnTheServer: + """What the connection reports, measured on the test server. + + The CI server is reached as ``localhost:5432`` over TCP; Unix sockets are covered + by unit tests only (the CI server runs in a container and has no local socket). + """ + + def test_uri_and_keyword_dsn_give_one_id(self, server_table: str) -> None: + uri = _uri(server_table) + ids = [_source_id(uri), _source_id(_keyword_dsn(server_table))] + assert ids == [_expected(_id_host(_SERVER["host"]), server_table)] * 2 + + def test_id_never_holds_user_or_password(self, server_table: str) -> None: + # Both DSNs carry the user and the password; the id is exactly the host, the + # port and the three-part name, with room for nothing else. (A substring + # check would fail a correct id whenever the user's name is also the + # database's, as with PGUSER=postgres PGDATABASE=postgres.) + uri = _uri(server_table) + for dsn in (uri, _keyword_dsn(server_table)): + assert _source_id(dsn) == _expected(_id_host(_SERVER["host"]), server_table) + + def test_upper_case_host_name_gives_the_lower_case_id( + self, server_table: str + ) -> None: + _requires_localhost() + ids = [ + _source_id(_keyword_dsn(server_table, host=host)) + for host in ("LOCALHOST", "localhost", "LocalHost") + ] + assert ids == [_expected("localhost", server_table)] * 3 + + def test_omitted_port_is_written_as_the_port_used( + self, server_table: str, no_server_env: None + ) -> None: + _requires_localhost() + if _SERVER["port"] != "5432": + pytest.skip("needs the test server on the default port 5432") + omitted = _source_id(_keyword_dsn(server_table, host="localhost", port=None)) + given = _source_id(_keyword_dsn(server_table, host="localhost", port="5432")) + assert omitted == given == _expected("localhost", server_table, "5432") + + def test_two_spellings_of_one_server_give_two_ids(self, server_table: str) -> None: + _requires_localhost() + ids = [ + _source_id(_keyword_dsn(server_table, host=host)) + for host in ("localhost", "127.0.0.1") + ] + assert ids == [ + _expected("localhost", server_table), + _expected("127.0.0.1", server_table), + ] + + def test_hostaddr_alone_names_the_address( + self, server_table: str, no_server_env: None + ) -> None: + _requires_localhost() + dsn = _keyword_dsn(server_table, host=None, hostaddr="127.0.0.1") + assert _source_id(dsn) == _expected("127.0.0.1", server_table) + + def test_host_equal_to_hostaddr_names_the_address( + self, server_table: str, no_server_env: None + ) -> None: + _requires_localhost() + dsn = _keyword_dsn(server_table, host="127.0.0.1", hostaddr="127.0.0.1") + assert _source_id(dsn) == _expected("127.0.0.1", server_table) + + @pytest.mark.parametrize( + "order", + [("host", "hostaddr"), ("hostaddr", "host")], + ids=["host-first", "hostaddr-first"], + ) + @pytest.mark.parametrize("form", ["keyword", "uri"]) + def test_host_beside_hostaddr_in_the_dsn_has_no_default( + self, + server_table: str, + no_server_env: None, + form: str, + order: tuple[str, str], + ) -> None: + _requires_localhost() + from orcapod.core.sources import PostgreSQLTableSource + + server = {"host": "LocalHost", "hostaddr": "127.0.0.1"} + if form == "keyword": + dsn = _keyword_dsn(server_table, **{key: server[key] for key in order}) + else: + dsn = _uri( + server_table, host="", query=[(key, server[key]) for key in order] + ) + with pytest.raises(ValueError, match="host name alone does not identify"): + _source_id(dsn) + given = PostgreSQLTableSource( + dsn, "t", source_id="t_by_address", tag_only_columns=True + ) + assert given.source_id == "t_by_address" + + @pytest.mark.parametrize( + ("dsn_params", "env"), + [ + ({"host": "localhost"}, {"PGHOSTADDR": "127.0.0.1"}), + ({"hostaddr": "127.0.0.1"}, {"PGHOST": "localhost"}), + ({}, {"PGHOST": "localhost", "PGHOSTADDR": "127.0.0.1"}), + ({}, {"PGHOSTADDR": "127.0.0.1", "PGHOST": "localhost"}), + ], + ids=["dsn-host-env-addr", "env-host-dsn-addr", "env-both", "env-both-reversed"], + ) + def test_host_beside_hostaddr_from_the_environment_has_no_default( + self, + server_table: str, + no_server_env: None, + monkeypatch: pytest.MonkeyPatch, + dsn_params: dict[str, str], + env: dict[str, str], + ) -> None: + _requires_localhost() + for envvar, value in env.items(): + monkeypatch.setenv(envvar, value) + dsn = _keyword_dsn(server_table, **{"host": None, **dsn_params}) + with pytest.raises(ValueError, match="host name alone does not identify"): + _source_id(dsn) + + @pytest.mark.parametrize( + ("service", "dsn_params"), + [ + ("host=localhost\nhostaddr=127.0.0.1", {}), + ("hostaddr=127.0.0.1\nhost=localhost", {}), + ("host=localhost", {"hostaddr": "127.0.0.1"}), + ], + ids=["service-both", "service-both-reversed", "service-host-dsn-addr"], + ) + def test_host_beside_hostaddr_from_a_service_file_has_no_default( + self, + server_table: str, + no_server_env: None, + monkeypatch: pytest.MonkeyPatch, + tmp_path, + service: str, + dsn_params: dict[str, str], + ) -> None: + _requires_localhost() + service_file = tmp_path / "pg_service.conf" + service_file.write_text(f"[one]\n{service}\nport={_SERVER['port']}\n") + monkeypatch.setenv("PGSERVICEFILE", str(service_file)) + dsn = _keyword_dsn( + server_table, **{"host": None, "port": None, "service": "one", **dsn_params} + ) + with pytest.raises(ValueError, match="host name alone does not identify"): + _source_id(dsn) + + @pytest.mark.parametrize( + ("dsn_host", "env_host"), + [("localhost", None), (None, "localhost")], + ids=["dsn-host", "pghost"], + ) + def test_host_name_beside_a_service_file_hostaddr_keeps_the_default( + self, + server_table: str, + no_server_env: None, + monkeypatch: pytest.MonkeyPatch, + tmp_path, + dsn_host: str | None, + env_host: str | None, + ) -> None: + # psycopg resolves a host name of the DSN or PGHOST and passes the address it + # reached as hostaddr, which overrides the service file's: the connection goes + # to the named host, not to the service file's unreachable address (a wrong + # claim would fail at connect_timeout). + _requires_localhost() + service_file = tmp_path / "pg_service.conf" + service_file.write_text(f"[one]\nhostaddr=192.0.2.1\nport={_SERVER['port']}\n") + monkeypatch.setenv("PGSERVICEFILE", str(service_file)) + if env_host is not None: + monkeypatch.setenv("PGHOST", env_host) + dsn = _keyword_dsn( + server_table, host=dsn_host, port=None, service="one", connect_timeout="5" + ) + assert _source_id(dsn) == _expected("localhost", server_table) + + @pytest.mark.parametrize( + ("service_host", "env_host"), + [("localhost", "127.0.0.1"), ("127.0.0.1", "localhost")], + ids=["service-name-env-address", "service-address-env-name"], + ) + def test_service_file_host_beside_a_resolved_pghost_has_no_default( + self, + server_table: str, + no_server_env: None, + monkeypatch: pytest.MonkeyPatch, + tmp_path, + service_host: str, + env_host: str, + ) -> None: + # libpq takes the service file's host over PGHOST, while psycopg resolved + # PGHOST and sent the connection to that address: the reported host does not + # name the server reached. + _requires_localhost() + service_file = tmp_path / "pg_service.conf" + service_file.write_text(f"[one]\nhost={service_host}\nport={_SERVER['port']}\n") + monkeypatch.setenv("PGSERVICEFILE", str(service_file)) + monkeypatch.setenv("PGHOST", env_host) + dsn = _keyword_dsn(server_table, host=None, port=None, service="one") + with pytest.raises(ValueError, match="host name alone does not identify"): + _source_id(dsn) + + def test_host_from_a_service_file_names_the_host( + self, + server_table: str, + no_server_env: None, + monkeypatch: pytest.MonkeyPatch, + tmp_path, + ) -> None: + _requires_localhost() + service_file = tmp_path / "pg_service.conf" + service_file.write_text(f"[one]\nhost=LocalHost\nport={_SERVER['port']}\n") + monkeypatch.setenv("PGSERVICEFILE", str(service_file)) + dsn = _keyword_dsn(server_table, host=None, port=None, service="one") + assert _source_id(dsn) == _expected("localhost", server_table) + + def test_ipv6_host_is_bracketed_and_exploded(self, server_table: str) -> None: + _requires_localhost() + dsn = _keyword_dsn(server_table, host="::1") + try: + psycopg.connect(dsn).close() + except psycopg.OperationalError: + pytest.skip("the test server is not reachable over IPv6") + assert _source_id(dsn) == _expected( + "[0000:0000:0000:0000:0000:0000:0000:0001]", server_table + ) + + @pytest.mark.parametrize("hosts", ["localhost,127.0.0.1", "127.0.0.1,localhost"]) + def test_several_hosts_in_the_dsn_have_no_default( + self, server_table: str, hosts: str + ) -> None: + _requires_localhost() + from orcapod.core.sources import PostgreSQLTableSource + + dsn = _keyword_dsn(server_table, host=hosts) + with pytest.raises(ValueError, match="several servers"): + _source_id(dsn) + given = PostgreSQLTableSource( + dsn, "t", source_id="t_on_the_pool", tag_only_columns=True + ) + assert given.source_id == "t_on_the_pool" + + def test_several_hosts_from_pghost_have_no_default( + self, server_table: str, no_server_env: None, monkeypatch: pytest.MonkeyPatch + ) -> None: + _requires_localhost() + monkeypatch.setenv("PGHOST", "localhost,127.0.0.1") + with pytest.raises(ValueError, match="several servers"): + _source_id(_keyword_dsn(server_table, host=None)) + + def test_several_hosts_from_a_service_file_have_no_default( + self, + server_table: str, + no_server_env: None, + monkeypatch: pytest.MonkeyPatch, + tmp_path, + ) -> None: + _requires_localhost() + service_file = tmp_path / "pg_service.conf" + service_file.write_text( + f"[pool]\nhost=localhost,127.0.0.1\nport={_SERVER['port']}\n" + ) + monkeypatch.setenv("PGSERVICEFILE", str(service_file)) + dsn = _keyword_dsn(server_table, host=None, port=None, service="pool") + with pytest.raises(ValueError, match="several servers"): + _source_id(dsn) diff --git a/tests/test_core/sources/test_source_check_for_new_data.py b/tests/test_core/sources/test_source_check_for_new_data.py index 385b7e7fa..8c4d14d6a 100644 --- a/tests/test_core/sources/test_source_check_for_new_data.py +++ b/tests/test_core/sources/test_source_check_for_new_data.py @@ -482,7 +482,8 @@ def _pg_connector(keys: list[int]) -> MagicMock: connector = MagicMock() connector.get_table_names.return_value = ["t"] connector.get_pk_columns.return_value = ["k"] - connector.current_location.return_value = ("orcapod", "public") + connector.current_location.return_value = ("localhost", 5432, "orcapod", "public") + connector.given_server.return_value = ("localhost", "") connector.get_column_info.return_value = [ ColumnInfo("k", pa.int64(), False), ColumnInfo("x", pa.int64(), False), @@ -756,7 +757,8 @@ def _connector_without_column_info(x: list[int | None]) -> MagicMock: connector = MagicMock() connector.get_table_names.return_value = ["t"] connector.get_pk_columns.return_value = ["k"] - connector.current_location.return_value = ("orcapod", "public") + connector.current_location.return_value = ("localhost", 5432, "orcapod", "public") + connector.given_server.return_value = ("localhost", "") connector.get_column_info.return_value = [] table = pa.table( {"k": pa.array(range(len(x)), pa.int64()), "x": pa.array(x, pa.int64())} diff --git a/tests/test_databases/test_postgresql_connector.py b/tests/test_databases/test_postgresql_connector.py index 545d7b096..b73c7fcc2 100644 --- a/tests/test_databases/test_postgresql_connector.py +++ b/tests/test_databases/test_postgresql_connector.py @@ -3,8 +3,12 @@ from __future__ import annotations +import pathlib +import socket +from typing import Any from unittest.mock import MagicMock, patch +import psycopg import pyarrow as pa import pytest @@ -309,3 +313,462 @@ def test_get_pk_columns_no_pk(self) -> None: result = connector.get_pk_columns("my_table") assert result == [] connector._conn = None + + +class TestServerLocationUnit: + """``current_location`` and ``given_server`` (ITL-1267), mocked connection. + + The values a live server reports are asserted by the postgres-marked tests in + ``tests/test_core/sources/test_postgresql_table_source_integration.py``. + """ + + @staticmethod + def _connector( + dsn: str = "postgresql://localhost/test", + *, + host: str = "localhost", + port: int = 5432, + parameters: dict[str, str] | None = None, + ) -> PostgreSQLConnector: + with patch("psycopg.connect") as mock_connect: + conn = MagicMock() + conn.info.host = host + conn.info.port = port + conn.info.get_parameters.return_value = ( + {"host": host} if parameters is None else parameters + ) + cursor = MagicMock() + cursor.__enter__ = lambda s: s + cursor.__exit__ = MagicMock(return_value=False) + cursor.fetchone.return_value = ("testdb", "public") + conn.cursor.return_value = cursor + mock_connect.return_value = conn + return PostgreSQLConnector(dsn) + + @pytest.mark.parametrize( + ("host", "port"), + [("db.example.org", 5433), ("/var/run/postgresql", 5432), ("::1", 6543)], + ) + def test_current_location_reports_the_connection( + self, host: str, port: int + ) -> None: + connector = self._connector(host=host, port=port) + assert connector.current_location() == (host, port, "testdb", "public") + connector._conn = None + + # ── given_server: what libpq takes, from the DSN, a service file, the environment + # + # Each case hands psycopg's own first connection attempt for the DSN (its host + # resolution included, every host name resolving to PSYCOPG_ADDRESS) to libpq's + # PQconnectStart, which applies the DSN, then the service file, then the + # environment, before it connects; nothing listens at any address used, and the + # attempt is abandoned once its parameters are read. So the precedence tested is + # libpq's own, not a model of it. + + PSYCOPG_ADDRESS = "203.0.113.9" + SOCKET = "/var/run/postgresql" + SERVER_ENV = ("PGHOST", "PGHOSTADDR", "PGSERVICE", "PGSERVICEFILE", "PGSYSCONFDIR") + + @pytest.fixture + def isolated_env( + self, monkeypatch: pytest.MonkeyPatch, tmp_path: pathlib.Path + ) -> pathlib.Path: + """No server variable of the caller's; no service file but the test's.""" + for envvar in self.SERVER_ENV: + monkeypatch.delenv(envvar, raising=False) + monkeypatch.setenv("PGSYSCONFDIR", str(tmp_path)) + monkeypatch.setenv("PGSERVICEFILE", str(tmp_path / "pg_service.conf")) + return tmp_path + + def _as_libpq_takes(self, dsn: str) -> PostgreSQLConnector: + """A connector whose connection reports the parameters libpq takes for dsn.""" + from psycopg import pq + from psycopg.conninfo import conninfo_attempts, conninfo_to_dict, make_conninfo + + resolved = [ + (socket.AF_INET, socket.SOCK_STREAM, 6, "", (self.PSYCOPG_ADDRESS, 5432)) + ] + with patch("socket.getaddrinfo", return_value=resolved): + attempt = conninfo_attempts(conninfo_to_dict(dsn))[0] + pgconn = pq.PGconn.connect_start(make_conninfo("", **attempt).encode()) + try: + reported = { + option.keyword.decode(): option.val.decode() + for option in pgconn.info + if option.val and option.keyword in (b"host", b"hostaddr") + } + finally: + pgconn.finish() + return self._connector(dsn, parameters=reported) + + def _given( + self, + isolated_env: pathlib.Path, + monkeypatch: pytest.MonkeyPatch, + dsn: list[str], + env: dict[str, str], + service: list[str] | None, + reverse: bool, + ) -> tuple[str, str]: + """``given_server`` for the DSN keywords, environment and service file lines. + + ``reverse`` writes the DSN keywords, the variables and the service file lines + in the other order. + """ + + def ordered(items: list[str]) -> list[str]: + return items[::-1] if reverse else items + + if service is not None: + lines = ordered(service) + (isolated_env / "pg_service.conf").write_text( + "\n".join(["[one]", *lines]) + "\n" + ) + dsn = [*dsn, "service=one"] + for envvar in ordered(list(env)): + monkeypatch.setenv(envvar, env[envvar]) + connector = self._as_libpq_takes(" ".join(ordered([*dsn, "dbname=x"]))) + try: + return connector.given_server() + finally: + connector._conn = None + + @pytest.mark.parametrize("reverse", [False, True], ids=["in-order", "reversed"]) + @pytest.mark.parametrize( + ("dsn", "expected"), + [ + (["host=db.example.org"], ("db.example.org", "")), + ([f"host={SOCKET}"], (SOCKET, "")), + (["host=192.0.2.1"], ("192.0.2.1", "")), + (["hostaddr=192.0.2.1"], ("", "192.0.2.1")), + (["host=192.0.2.1", "hostaddr=192.0.2.1"], ("192.0.2.1", "192.0.2.1")), + ( + ["host=db.example.org", "hostaddr=192.0.2.1"], + ("db.example.org", "192.0.2.1"), + ), + ([f"host={SOCKET}", "hostaddr=192.0.2.1"], (SOCKET, "192.0.2.1")), + ( + ["host=a.example.org,b.example.org", "port=5432"], + ("a.example.org,b.example.org", ""), + ), + (["hostaddr=192.0.2.1,192.0.2.2"], ("", "192.0.2.1,192.0.2.2")), + ], + ) + def test_given_in_the_dsn( + self, + isolated_env: pathlib.Path, + monkeypatch: pytest.MonkeyPatch, + dsn: list[str], + expected: tuple[str, str], + reverse: bool, + ) -> None: + given = self._given(isolated_env, monkeypatch, dsn, {}, None, reverse) + assert given == expected + + @pytest.mark.parametrize( + ("dsn", "expected"), + [ + ("postgresql://u:p@db.example.org:5432/x", ("db.example.org", "")), + ( + "postgresql://u@db.example.org/x?hostaddr=192.0.2.1", + ("db.example.org", "192.0.2.1"), + ), + ( + "postgresql:///x?hostaddr=192.0.2.1&host=db.example.org", + ("db.example.org", "192.0.2.1"), + ), + ( + "postgresql://u:p@b.example.org:5433,a.example.org:5432/x", + ("b.example.org,a.example.org", ""), + ), + ("postgresql:///x?hostaddr=192.0.2.1", ("", "192.0.2.1")), + ], + ) + def test_given_in_a_uri( + self, isolated_env: pathlib.Path, dsn: str, expected: tuple[str, str] + ) -> None: + connector = self._as_libpq_takes(dsn) + assert connector.given_server() == expected + connector._conn = None + + @pytest.mark.parametrize("reverse", [False, True], ids=["in-order", "reversed"]) + @pytest.mark.parametrize( + ("dsn", "env", "expected"), + [ + ([], {"PGHOST": "db.example.org"}, ("db.example.org", "")), + ([], {"PGHOSTADDR": "192.0.2.1"}, ("", "192.0.2.1")), + ( + [], + {"PGHOST": "db.example.org", "PGHOSTADDR": "192.0.2.1"}, + ("db.example.org", "192.0.2.1"), + ), + ( + ["host=db.example.org"], + {"PGHOSTADDR": "192.0.2.1"}, + ("db.example.org", "192.0.2.1"), + ), + ( + ["hostaddr=192.0.2.1"], + {"PGHOST": "db.example.org"}, + ("db.example.org", "192.0.2.1"), + ), + ([], {"PGHOST": SOCKET, "PGHOSTADDR": "192.0.2.1"}, (SOCKET, "192.0.2.1")), + # The DSN overrides the environment, key by key. + ( + ["host=db.example.org"], + {"PGHOST": "a.example.org,b.example.org"}, + ("db.example.org", ""), + ), + ( + ["host=db.example.org", "hostaddr=192.0.2.1"], + {"PGHOSTADDR": "192.0.2.7,192.0.2.8"}, + ("db.example.org", "192.0.2.1"), + ), + ( + [], + {"PGHOST": "a.example.org,b.example.org"}, + ("a.example.org,b.example.org", ""), + ), + ([], {"PGHOSTADDR": "192.0.2.1,192.0.2.2"}, ("", "192.0.2.1,192.0.2.2")), + ], + ) + def test_given_in_the_environment( + self, + isolated_env: pathlib.Path, + monkeypatch: pytest.MonkeyPatch, + dsn: list[str], + env: dict[str, str], + expected: tuple[str, str], + reverse: bool, + ) -> None: + given = self._given(isolated_env, monkeypatch, dsn, env, None, reverse) + assert given == expected + + @pytest.mark.parametrize("reverse", [False, True], ids=["in-order", "reversed"]) + @pytest.mark.parametrize( + ("service", "dsn", "env", "expected"), + [ + # Host and address from the service file alone. + (["host=svc.invalid"], [], {}, ("svc.invalid", "")), + ( + ["host=svc.invalid", "hostaddr=192.0.2.50"], + [], + {}, + ("svc.invalid", "192.0.2.50"), + ), + ( + ["host=192.0.2.50", "hostaddr=192.0.2.50"], + [], + {}, + ("192.0.2.50", "192.0.2.50"), + ), + (["hostaddr=192.0.2.50"], [], {}, ("", "192.0.2.50")), + ( + ["host=a.invalid,b.invalid"], + [], + {}, + ("a.invalid,b.invalid", ""), + ), + # The service file's address beside a host of the DSN or the environment: + # psycopg resolves a host name and passes its address, which overrides the + # service file's; it does not resolve a socket directory, so the service + # file's address is the one used. + ( + ["hostaddr=192.0.2.50"], + ["host=db.example.org"], + {}, + ("db.example.org", ""), + ), + (["hostaddr=192.0.2.50"], [f"host={SOCKET}"], {}, (SOCKET, "192.0.2.50")), + ( + ["hostaddr=192.0.2.50"], + [], + {"PGHOST": "db.example.org"}, + ("db.example.org", ""), + ), + (["hostaddr=192.0.2.50"], [], {"PGHOST": SOCKET}, (SOCKET, "192.0.2.50")), + # The service file overrides the environment, key by key. + ( + ["hostaddr=192.0.2.50"], + [], + {"PGHOSTADDR": "192.0.2.60"}, + ("", "192.0.2.50"), + ), + ( + ["host=svc.invalid"], + [], + {"PGHOST": "db.example.org"}, + ("svc.invalid", PSYCOPG_ADDRESS), + ), + (["host=svc.invalid"], [], {"PGHOST": SOCKET}, ("svc.invalid", "")), + ( + ["host=svc.invalid"], + [], + {"PGHOST": "db.example.org", "PGHOSTADDR": "192.0.2.60"}, + ("svc.invalid", "192.0.2.60"), + ), + # The service file's host beside an address of the DSN or the environment. + ( + ["host=svc.invalid"], + ["hostaddr=192.0.2.1"], + {}, + ("svc.invalid", "192.0.2.1"), + ), + ( + ["host=svc.invalid"], + [], + {"PGHOSTADDR": "192.0.2.60"}, + ("svc.invalid", "192.0.2.60"), + ), + # The DSN overrides the service file. + ( + ["host=svc.invalid", "hostaddr=192.0.2.50"], + ["host=db.example.org"], + {}, + ("db.example.org", ""), + ), + ( + ["host=svc.invalid", "hostaddr=192.0.2.50"], + ["hostaddr=192.0.2.1"], + {}, + ("svc.invalid", "192.0.2.1"), + ), + ], + ) + def test_given_in_a_service_file( + self, + isolated_env: pathlib.Path, + monkeypatch: pytest.MonkeyPatch, + service: list[str], + dsn: list[str], + env: dict[str, str], + expected: tuple[str, str], + reverse: bool, + ) -> None: + given = self._given(isolated_env, monkeypatch, dsn, env, service, reverse) + assert given == expected + + @pytest.mark.parametrize( + ("at_connect", "later", "expected"), + [ + # psycopg resolved PGHOST: a PGHOSTADDR set later does not make its + # address the user's. + ( + {"PGHOST": "db.example.org"}, + {"PGHOSTADDR": "192.0.2.7"}, + ("db.example.org", ""), + ), + # Another host later, in place of the one connected to. + ( + {"PGHOST": "db.example.org"}, + {"PGHOST": "other.example.org"}, + ("db.example.org", ""), + ), + # Several servers at connect time stay several when PGHOST is unset. + ( + {"PGHOST": "a.example.org,b.example.org"}, + {"PGHOST": None}, + ("a.example.org,b.example.org", ""), + ), + # One server at connect time stays one when PGHOST becomes a list. + ( + {"PGHOST": "db.example.org"}, + {"PGHOST": "a.example.org,b.example.org"}, + ("db.example.org", ""), + ), + ], + ) + def test_the_environment_is_read_when_the_connector_connects( + self, + isolated_env: pathlib.Path, + monkeypatch: pytest.MonkeyPatch, + at_connect: dict[str, str], + later: dict[str, str | None], + expected: tuple[str, str], + ) -> None: + for envvar, value in at_connect.items(): + monkeypatch.setenv(envvar, value) + connector = self._as_libpq_takes("dbname=x") + for envvar, value in later.items(): + if value is None: + monkeypatch.delenv(envvar) + else: + monkeypatch.setenv(envvar, value) + try: + assert connector.given_server() == expected + finally: + connector._conn = None + + +class TestPsycopgResolvesTheHost: + """The psycopg behaviour ``given_server`` relies on, pinned (ITL-1267). + + psycopg's ``Connection.connect`` resolves a single host name of the DSN or + ``PGHOST`` itself, when neither gives a ``hostaddr``, and passes the address to + libpq as ``hostaddr`` (psycopg 3.1.17 and later; earlier releases passed the DSN + unchanged). Real name resolution of ``localhost`` and psycopg's own connect + loop: only the step that would open the connection is replaced, to record the + connection string psycopg hands to libpq. If a future psycopg stops doing this + (or renames that step), these tests fail. + """ + + @staticmethod + def _passed_to_libpq(dsn: str) -> list[dict[str, Any]]: + from psycopg.conninfo import conninfo_to_dict + + passed: list[str] = [] + + def refuse(conninfo: str, **_: Any) -> Any: + passed.append(conninfo) + raise psycopg.OperationalError("not connecting in a unit test") + + with patch.object(psycopg.Connection, "_connect_gen", side_effect=refuse): + with pytest.raises(psycopg.OperationalError): + psycopg.connect(dsn) + assert passed, "psycopg did not reach the step that opens the connection" + return [conninfo_to_dict(conninfo) for conninfo in passed] + + @staticmethod + def _addresses(name: str) -> set[str]: + return { + str(info[4][0]) + for info in socket.getaddrinfo( + name, 5432, proto=socket.IPPROTO_TCP, type=socket.SOCK_STREAM + ) + } + + @pytest.fixture(autouse=True) + def _no_server_env(self, monkeypatch: pytest.MonkeyPatch) -> None: + for envvar in ("PGHOST", "PGHOSTADDR", "PGSERVICE"): + monkeypatch.delenv(envvar, raising=False) + + @pytest.mark.parametrize("via", ["dsn", "PGHOST"]) + def test_a_host_name_is_passed_with_the_address_psycopg_resolved( + self, monkeypatch: pytest.MonkeyPatch, via: str + ) -> None: + if via == "PGHOST": + monkeypatch.setenv("PGHOST", "localhost") + dsn = "host=localhost dbname=x" if via == "dsn" else "dbname=x" + attempts = self._passed_to_libpq(dsn) + addresses = self._addresses("localhost") + assert {attempt["hostaddr"] for attempt in attempts} <= addresses + assert all( + attempt.get("host", "localhost") == "localhost" for attempt in attempts + ) + + @pytest.mark.parametrize( + ("dsn", "hostaddr"), + [ + ("host=127.0.0.1 dbname=x", "127.0.0.1"), + ("host=localhost hostaddr=192.0.2.1 dbname=x", "192.0.2.1"), + ("hostaddr=192.0.2.1 host=localhost dbname=x", "192.0.2.1"), + ], + ) + def test_an_address_is_passed_as_given(self, dsn: str, hostaddr: str) -> None: + assert [attempt["hostaddr"] for attempt in self._passed_to_libpq(dsn)] == [ + hostaddr + ] + + def test_a_socket_directory_is_not_resolved(self) -> None: + attempts = self._passed_to_libpq("host=/var/run/postgresql dbname=x") + assert [attempt.get("hostaddr") for attempt in attempts] == [None] diff --git a/uv.lock b/uv.lock index 17ad21c4a..ef85340f8 100644 --- a/uv.lock +++ b/uv.lock @@ -2132,8 +2132,8 @@ requires-dist = [ { name = "numpy", specifier = ">=1.26.4" }, { name = "pandas", specifier = ">=2.2.3,<3" }, { name = "polars", specifier = ">=1.36.0" }, - { name = "psycopg", extras = ["binary"], marker = "extra == 'all'", specifier = ">=3.0" }, - { name = "psycopg", extras = ["binary"], marker = "extra == 'postgresql'", specifier = ">=3.0" }, + { name = "psycopg", extras = ["binary"], marker = "extra == 'all'", specifier = ">=3.1.17" }, + { name = "psycopg", extras = ["binary"], marker = "extra == 'postgresql'", specifier = ">=3.1.17" }, { name = "pyarrow", specifier = ">=22.0.0" }, { name = "pydantic", specifier = ">=2.0" }, { name = "pyspiral", marker = "extra == 'all'", specifier = ">=0.16.33" }, @@ -2173,7 +2173,7 @@ dev = [ { name = "pip-licenses", specifier = ">=5.0.0" }, { name = "pre-commit", specifier = ">=4.4.0" }, { name = "pre-commit-hooks", specifier = ">=6.0.0" }, - { name = "psycopg", extras = ["binary"], specifier = ">=3.0" }, + { name = "psycopg", extras = ["binary"], specifier = ">=3.1.17" }, { name = "pyarrow-stubs", specifier = ">=20.0.0.20250716" }, { name = "pyiceberg", specifier = ">=0.9.1" }, { name = "pyright", specifier = ">=1.1.404" },