Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion .zed/rules
Original file line number Diff line number Diff line change
Expand Up @@ -1123,7 +1123,11 @@ data. The rules:
only by core/sources/source_ids.hash_source_id; one built from where the data lives is
<kind>:<location>, built only by location_source_id: csv:<path as passed>,
delta_table:<path or URI as passed>, sqlite_table:<db path as passed>:main.<table>,
postgresql_table:<database>.<schema>.<table>,
postgresql_table:<host>:<port>/<database>.<schema>.<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:<project>.<dataset>.<table>@<table id> (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:
Expand Down
6 changes: 5 additions & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -1167,7 +1167,11 @@ data. The rules:
only by `core/sources/source_ids.hash_source_id`; one built from where the data lives is
`<kind>:<location>`, built only by `location_source_id`: `csv:<path as passed>`,
`delta_table:<path or URI as passed>`, `sqlite_table:<db path as passed>:main.<table>`,
`postgresql_table:<database>.<schema>.<table>`,
`postgresql_table:<host>:<port>/<database>.<schema>.<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:<project>.<dataset>.<table>@<table id>` (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:
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
27 changes: 27 additions & 0 deletions changelog.d/ITL-1267.md
Original file line number Diff line number Diff line change
@@ -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:<host>:<port>/<database>.<schema>.<table>` (was
`postgresql_table:<database>.<schema>.<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.
14 changes: 11 additions & 3 deletions docs/concepts/sources.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:<db path>:main.<table>`). `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:<db path>:main.<table>`,
`postgresql_table:<host>:<port>/<database>.<schema>.<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:

Expand Down
42 changes: 39 additions & 3 deletions docs/reference/hashing.md
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ category, but we should make it totally overridable"; November 16, 2026, ITL-115
| `CSVSource` | `csv` | `csv:<file path as passed>` |
| `DeltaTableSource` | `delta_table` | `delta_table:<path or URI of the table folder as passed>` |
| `SQLiteTableSource` | `sqlite_table` | `sqlite_table:<db path as passed>:main.<table>` (SQLite names a table `<schema>.<table>`; the main database's schema is `main`) |
| `PostgreSQLTableSource` | `postgresql_table` | `postgresql_table:<database>.<schema>.<table>` (the three-part name, from `current_database()` and `current_schema()`) |
| `PostgreSQLTableSource` | `postgresql_table` | `postgresql_table:<host>:<port>/<database>.<schema>.<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:<project>.<dataset>.<table>@<table id>` (Spiral's own table identifier, then SpiralDB's table id; `SPIRALDB_SOURCE_ID_HAS_TABLE_ID`) |
| `PollingSource` | `polling_source` | `polling_source:semantic_v1:<hex>` of `impl.identity()` (never its `repr`) |
Expand All @@ -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.
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
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):
Expand Down
4 changes: 2 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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",
]
Expand Down Expand Up @@ -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",
Expand Down
139 changes: 131 additions & 8 deletions src/orcapod/core/sources/postgresql_table_source.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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 ``<host>:<port>/<database>.<schema>.<table>``, a PostgreSQL table's address.

The location of the default source id (``postgresql_table:<address>``, 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.

Expand Down Expand Up @@ -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:<database>.<schema>.<table>``.
``postgresql_table:<host>:<port>/<database>.<schema>.<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.
Expand Down Expand Up @@ -115,22 +212,48 @@ def __init__(

@override
def _table_address(self, connector: DBConnectorProtocol, table_name: str) -> str:
"""Return ``<database>.<schema>.<table>``, the table's three-part name.
"""Return ``<host>:<port>/<database>.<schema>.<table>``, 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.
table_name: The table's name.

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
Expand Down
Loading
Loading