datadouble-postgres 0.0.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,192 @@
1
+ # Copyright (c) 2026- Tight Line LLC
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ """The PostgreSQL engine adapter for Datadouble.
5
+
6
+ Spec settings::
7
+
8
+ sources:
9
+ app:
10
+ engine: postgres
11
+ connection:
12
+ dsn: {env: SHOP_DSN} # a libpq connection string or URI, by reference
13
+ databases: [shop, "billing_*"] # names or globs; by default the DSN's
14
+
15
+ Tables are named ``database.schema.table``; ``databases`` lists the databases
16
+ read (``["*"]`` for every one the user can connect to), each under a snapshot
17
+ of its own, opened together. Working databases, restores and ``pg_dump`` run
18
+ in the official PostgreSQL image of the source's exact version
19
+ (``postgres:<version>-trixie``), or in ``sources.<name>.image``, through the spec's
20
+ container runtime. ``pg_dump`` connects to
21
+ the source from a container, so the source must be reachable from there at the
22
+ address in ``dsn``.
23
+ """
24
+
25
+ from collections.abc import Generator, Mapping
26
+ from contextlib import ExitStack, contextmanager
27
+ from pathlib import Path
28
+ from typing import Annotated
29
+
30
+ import psycopg
31
+ from psycopg.conninfo import conninfo_to_dict, make_conninfo
32
+ from pydantic import BaseModel, ConfigDict, Field, JsonValue
33
+
34
+ from datadouble.engine import (
35
+ ServerPlan,
36
+ SourceSession,
37
+ Tooling,
38
+ WorkingDatabases,
39
+ choose_databases,
40
+ )
41
+ from datadouble.names import EngineName
42
+ from datadouble.planner import AccountNames, Capabilities
43
+ from datadouble.secrets import resolve_secret
44
+ from datadouble.settings import parse_settings
45
+ from datadouble.spec import ImageFormat, SecretRef
46
+ from datadouble_postgres.cluster import SUPERUSER, Tools, default_image
47
+ from datadouble_postgres.errors import database_error
48
+ from datadouble_postgres.introspect import ENGINE
49
+ from datadouble_postgres.source import Connection, PostgresSession
50
+ from datadouble_postgres.working import DatabaseInfo, PostgresWorking
51
+
52
+ MOUNT = "/var/lib/datadouble"
53
+ """Where container servers mount a copy."""
54
+
55
+
56
+ class PostgresConnection(BaseModel):
57
+ """The ``sources.<name>.connection`` settings."""
58
+
59
+ model_config = ConfigDict(strict=True, frozen=True, extra="forbid")
60
+
61
+ dsn: SecretRef
62
+ databases: tuple[Annotated[str, Field(min_length=1)], ...] = ()
63
+ """The databases to read, as names or globs (``["*"]`` for every one the
64
+ user can connect to); the connection string's database when empty."""
65
+
66
+
67
+ _DATABASES = """
68
+ SELECT datname FROM pg_catalog.pg_database
69
+ WHERE NOT datistemplate AND datallowconn
70
+ AND pg_catalog.has_database_privilege(datname, 'CONNECT')
71
+ """
72
+
73
+
74
+ def _open(conninfo: str, password: str | None) -> Connection:
75
+ try:
76
+ return psycopg.connect(conninfo, password=password, autocommit=True)
77
+ except psycopg.Error as error:
78
+ raise database_error(error, "connecting to the source") from None
79
+
80
+
81
+ def list_databases(connection: Connection) -> tuple[str, ...]:
82
+ """Every database the user can connect to, templates aside."""
83
+ try:
84
+ return tuple(str(row[0]) for row in connection.execute(_DATABASES).fetchall())
85
+ except psycopg.Error as error:
86
+ raise database_error(error, "listing the databases") from None
87
+
88
+
89
+ class PostgresServerSettings(BaseModel):
90
+ """The ``sources.<name>.server`` settings."""
91
+
92
+ model_config = ConfigDict(strict=True, frozen=True, extra="forbid")
93
+
94
+ shared_preload_libraries: tuple[Annotated[str, Field(pattern=r"^[A-Za-z0-9_$.-]+$")], ...] = ()
95
+ """Libraries the server loads at start, for extensions that need them
96
+ (``timescaledb``, ``pg_cron``). A physical image keeps the setting, so its
97
+ copies load them too."""
98
+
99
+
100
+ class PostgresEngine:
101
+ """Implements :class:`datadouble.engine.EngineAdapter` for PostgreSQL."""
102
+
103
+ @property
104
+ def name(self) -> EngineName:
105
+ """``postgres``."""
106
+ return ENGINE
107
+
108
+ @property
109
+ def owner(self) -> str:
110
+ """``999:999``, the user the official PostgreSQL image serves as."""
111
+ return "999:999"
112
+
113
+ def capabilities(self) -> Capabilities:
114
+ """Both formats, SQL expressions, accounts and the nested strategy within one database."""
115
+ return Capabilities(
116
+ formats=(ImageFormat.PHYSICAL, ImageFormat.LOGICAL),
117
+ expressions=True,
118
+ nested=True,
119
+ accounts=AccountNames(
120
+ max_bytes=63,
121
+ reserved=("public", "none", "current_user", "session_user", "current_role"),
122
+ reserved_prefixes=("pg_",),
123
+ keep_all=(SUPERUSER,),
124
+ ),
125
+ standalone=True,
126
+ joins_outermost=False,
127
+ several_sources=True,
128
+ )
129
+
130
+ @contextmanager
131
+ def connect(self, connection: Mapping[str, JsonValue]) -> Generator[SourceSession]:
132
+ """Connect to the source; the password never reaches a command line."""
133
+ settings = parse_settings(PostgresConnection, connection, "postgres connection")
134
+ params = conninfo_to_dict(resolve_secret(settings.dsn))
135
+ secret = params.pop("password", None)
136
+ password = None if secret is None else str(secret)
137
+ conninfo = make_conninfo(**{k: str(v) for k, v in params.items()})
138
+ with ExitStack() as stack:
139
+ first = stack.enter_context(_open(conninfo, password))
140
+ home = str(first.info.dbname)
141
+ wanted = settings.databases or (home,)
142
+ databases = choose_databases(list_databases(first), wanted)
143
+ connections = {
144
+ database: first
145
+ if database == home
146
+ else stack.enter_context(_open(make_conninfo(conninfo, dbname=database), password))
147
+ for database in databases
148
+ }
149
+ default = home if home in connections else databases[0]
150
+ yield PostgresSession(connections, conninfo, password, default)
151
+
152
+ def working(self, scratch: Path, tooling: Tooling, source_version: str) -> WorkingDatabases:
153
+ """Clusters under ``scratch``, in the image for the source's version."""
154
+ settings = parse_settings(PostgresServerSettings, tooling.server, "postgres server")
155
+ image = tooling.image or default_image(source_version)
156
+ tools = Tools(tooling.runtime, image, scratch, settings.shared_preload_libraries)
157
+ return PostgresWorking(tools, scratch)
158
+
159
+ def server(self, image: Path, server_image: str | None) -> ServerPlan:
160
+ """The official PostgreSQL image of the image's version, on the copy.
161
+
162
+ At start the data directory gets the permissions PostgreSQL insists on,
163
+ a pg_hba file that allows password logins from anywhere and local trust,
164
+ and the superuser gets the copy's password.
165
+ """
166
+ info = DatabaseInfo.model_validate_json((image / "database.json").read_bytes())
167
+ data = f"{MOUNT}/pgdata"
168
+ hba = f"{data}/pg_hba.datadouble.conf"
169
+ # The password is generated by the replicate adapter (hex), so quoting it is safe.
170
+ start = (
171
+ f"chmod 0700 {data}"
172
+ f" && printf 'local all all trust\\nhost all all all scram-sha-256\\n' > {hba}"
173
+ f' && printf "ALTER ROLE {SUPERUSER} PASSWORD \'%s\'\\n" "$DATADOUBLE_PASSWORD"'
174
+ f" | postgres --single -D {data} postgres > /dev/null"
175
+ f" && exec postgres -D {data} -c listen_addresses='*'"
176
+ f" -c hba_file={hba}"
177
+ )
178
+ return ServerPlan(
179
+ image=server_image or default_image(info.server_version),
180
+ mount=MOUNT,
181
+ owner=self.owner,
182
+ command=("sh", "-c", start),
183
+ ready=("pg_isready", "--host=127.0.0.1", f"--dbname={info.default}"),
184
+ port=5432,
185
+ database=info.default,
186
+ user=SUPERUSER,
187
+ )
188
+
189
+
190
+ def engine() -> PostgresEngine:
191
+ """The entry point named in ``datadouble.engines``."""
192
+ return PostgresEngine()
@@ -0,0 +1,229 @@
1
+ # Copyright (c) 2026- Tight Line LLC
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ """Throwaway PostgreSQL clusters and tools, in the official PostgreSQL image.
5
+
6
+ Every program runs in a container from the image, as Datadouble's own user,
7
+ with the paths it needs mounted at the same absolute path. The image's
8
+ ``nss_wrapper`` gives that user a name, which ``initdb`` and the server
9
+ insist on. Each working database is its own cluster in scratch space; while
10
+ it runs, it accepts the superuser over the network with a password generated
11
+ for that start, and over the loopback address without one, which only
12
+ programs inside its own container (``pg_restore``, ``pg_dump``) can use. It
13
+ has no Unix socket. Server logs and the
14
+ authentication file stay outside the data directory, so a physical image does
15
+ not carry them.
16
+ """
17
+
18
+ import os
19
+ import re
20
+ import secrets
21
+ from collections.abc import Generator, Mapping, Sequence
22
+ from contextlib import contextmanager
23
+ from dataclasses import dataclass, replace
24
+ from pathlib import Path
25
+
26
+ import psycopg
27
+ from psycopg import sql
28
+ from psycopg.conninfo import make_conninfo
29
+
30
+ from datadouble.engine import EngineError
31
+ from datadouble.runtime import Completed, Container, ContainerRuntime, Server
32
+ from datadouble_postgres.errors import tool_error
33
+
34
+ SUPERUSER = "postgres"
35
+ LOOPBACK = "127.0.0.1"
36
+ """How programs inside a server's container reach it: trusted, since only they can."""
37
+ _VERSION = re.compile(r"\(PostgreSQL\) (\d+(?:\.\d+)?)")
38
+ _LOGIN_ENV = "DATADOUBLE_PASSWORD"
39
+
40
+
41
+ def default_image(server_version: str) -> str:
42
+ """The official image of exactly ``server_version``, such as ``postgres:18.4-trixie``.
43
+
44
+ The working server matches the source's minor version: a dump from a newer
45
+ minor release can hold what an older server rejects.
46
+ """
47
+ return f"postgres:{server_version}-trixie"
48
+
49
+
50
+ @dataclass(frozen=True, slots=True)
51
+ class Tools:
52
+ """PostgreSQL programs in containers from one image.
53
+
54
+ ``home`` holds the files every container needs: the user database for
55
+ ``nss_wrapper`` and the servers' authentication file.
56
+ """
57
+
58
+ runtime: ContainerRuntime
59
+ image: str
60
+ home: Path
61
+ preload: tuple[str, ...] = ()
62
+ """``shared_preload_libraries`` for every cluster the tools create."""
63
+
64
+ def _environment(self) -> dict[str, str]:
65
+ passwd = self.home / "passwd"
66
+ if not passwd.is_file():
67
+ self.home.mkdir(parents=True, exist_ok=True)
68
+ uid, gid = os.getuid(), os.getgid()
69
+ passwd.write_text(f"datadouble:x:{uid}:{gid}::/tmp:/bin/sh\n", "utf-8")
70
+ (self.home / "group").write_text(f"datadouble:x:{gid}:\n", "utf-8")
71
+ (self.home / "pg_hba.conf").write_text(
72
+ f"host all all {LOOPBACK}/32 trust\nhost all all all scram-sha-256\n", "utf-8"
73
+ )
74
+ return {
75
+ "LD_PRELOAD": "libnss_wrapper.so",
76
+ "NSS_WRAPPER_PASSWD": str(passwd),
77
+ "NSS_WRAPPER_GROUP": str(self.home / "group"),
78
+ }
79
+
80
+ def container(
81
+ self,
82
+ command: Sequence[str],
83
+ owner: Path,
84
+ mounts: Sequence[Path] = (),
85
+ secrets_: Mapping[str, str] | None = None,
86
+ ) -> Container:
87
+ """A container running ``command`` with ``mounts`` and the tools' home."""
88
+ return Container(
89
+ image=self.image,
90
+ command=tuple(command),
91
+ owner=owner,
92
+ mounts=(self.home, *mounts),
93
+ env=self._environment(),
94
+ secrets=dict(secrets_ or {}),
95
+ )
96
+
97
+ def run(
98
+ self,
99
+ name: str,
100
+ arguments: Sequence[str],
101
+ owner: Path,
102
+ mounts: Sequence[Path] = (),
103
+ secrets_: Mapping[str, str] | None = None,
104
+ ) -> str:
105
+ """Run one program to completion; raise a redacted :class:`EngineError` if it fails."""
106
+ done = self.runtime.run(self.container([name, *arguments], owner, mounts, secrets_))
107
+ return _checked(name, done)
108
+
109
+ def version(self) -> str:
110
+ """The full server version in the image, such as ``18.1``."""
111
+ output = self.run("postgres", ["--version"], self.home)
112
+ match = _VERSION.search(output)
113
+ if match is None:
114
+ message = f"cannot read the PostgreSQL version from {output.strip()!r}"
115
+ raise EngineError(message)
116
+ return match.group(1)
117
+
118
+
119
+ def _checked(name: str, done: Completed) -> str:
120
+ if done.status != 0:
121
+ raise tool_error(name, done.status, done.stderr)
122
+ return done.stdout
123
+
124
+
125
+ class Cluster:
126
+ """One cluster, identified by its data directory."""
127
+
128
+ def __init__(
129
+ self, tools: Tools, datadir: Path, owner: Path, mounts: Sequence[Path] = ()
130
+ ) -> None:
131
+ """Manage the cluster in ``datadir`` for the stage directory ``owner``.
132
+
133
+ ``mounts`` are further paths the server's container sees, for the
134
+ programs run inside it.
135
+ """
136
+ self.tools = tools
137
+ self.datadir = datadir
138
+ self.owner = owner
139
+ self.mounts = (datadir.parent, *mounts)
140
+ self._server: Server | None = None
141
+ self._password = ""
142
+
143
+ def initialize(self) -> None:
144
+ """Create the cluster: UTF-8, C locale."""
145
+ self.datadir.parent.mkdir(parents=True, exist_ok=True)
146
+ self.tools.run(
147
+ "initdb",
148
+ [
149
+ "--pgdata",
150
+ str(self.datadir),
151
+ "--username",
152
+ SUPERUSER,
153
+ "--auth",
154
+ "trust",
155
+ "--encoding",
156
+ "UTF8",
157
+ "--locale",
158
+ "C",
159
+ "--no-instructions",
160
+ ],
161
+ self.owner,
162
+ [self.datadir.parent],
163
+ )
164
+ if self.tools.preload:
165
+ with (self.datadir / "postgresql.conf").open("a", encoding="utf-8") as conf:
166
+ conf.write(f"shared_preload_libraries = '{','.join(self.tools.preload)}'\n")
167
+
168
+ @property
169
+ def server(self) -> Server:
170
+ """The running server's container."""
171
+ if self._server is None:
172
+ message = "the cluster is not running"
173
+ raise EngineError(message)
174
+ return self._server
175
+
176
+ @contextmanager
177
+ def running(self) -> Generator["Cluster"]:
178
+ """Start the cluster for the duration of the block, then stop it cleanly."""
179
+ data = str(self.datadir)
180
+ password = secrets.token_hex(16)
181
+ # The password is hex, so quoting it is safe; it reaches the container
182
+ # through the runtime's secret channel, never a command line.
183
+ start = (
184
+ f'printf "ALTER ROLE {SUPERUSER} PASSWORD \'%s\'\\n" "${_LOGIN_ENV}"'
185
+ f" | postgres --single -D {data} postgres > /dev/null"
186
+ f" && exec postgres -D {data} -c listen_addresses='*'"
187
+ f" -c unix_socket_directories='' -c hba_file={self.tools.home}/pg_hba.conf"
188
+ " -c fsync=off -c max_connections=20 -c logging_collector=off"
189
+ )
190
+ container = replace(
191
+ self.tools.container(
192
+ ["sh", "-c", start], self.owner, self.mounts, {_LOGIN_ENV: password}
193
+ ),
194
+ port=5432,
195
+ ready=("pg_isready", f"--host={LOOPBACK}", f"--username={SUPERUSER}"),
196
+ )
197
+ with self.tools.runtime.serve(container) as server:
198
+ self._server, self._password = server, password
199
+ try:
200
+ yield self
201
+ finally:
202
+ self._server, self._password = None, ""
203
+
204
+ def execute(self, name: str, arguments: Sequence[str]) -> str:
205
+ """Run a client program inside the server's container, over the loopback address."""
206
+ return _checked(name, self.server.execute([name, *arguments]))
207
+
208
+ def local_conninfo(self, dbname: str) -> str:
209
+ """A connection string for programs inside the server's container."""
210
+ return make_conninfo(host=LOOPBACK, dbname=dbname, user=SUPERUSER)
211
+
212
+ def connect(self, dbname: str) -> psycopg.Connection[tuple[object, ...]]:
213
+ """Connect to one database of the running cluster, over the network."""
214
+ endpoint = self.server.endpoint
215
+ conninfo = make_conninfo(
216
+ host=endpoint.host, port=str(endpoint.port), dbname=dbname, user=SUPERUSER
217
+ )
218
+ try:
219
+ return psycopg.connect(conninfo, password=self._password, autocommit=True)
220
+ except psycopg.Error as error:
221
+ message = f"connecting to the working database failed: {type(error).__name__}"
222
+ raise EngineError(message) from None
223
+
224
+ def create_database(self, dbname: str) -> None:
225
+ """Create a database unless it is the default ``postgres`` one."""
226
+ if dbname == SUPERUSER:
227
+ return
228
+ with self.connect(SUPERUSER) as connection:
229
+ connection.execute(sql.SQL("CREATE DATABASE {}").format(sql.Identifier(dbname)))
@@ -0,0 +1,107 @@
1
+ # Copyright (c) 2026- Tight Line LLC
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ """Error messages that are safe to show and log.
5
+
6
+ PostgreSQL messages can quote the data that caused them (a duplicate key, a
7
+ value that does not parse). Messages leaving this adapter keep the SQLSTATE,
8
+ the primary message with data values hidden, and the names of the objects
9
+ involved, which are identifiers rather than data (decisions 54 and 139).
10
+ """
11
+
12
+ import psycopg
13
+
14
+ from datadouble.engine import EngineError
15
+ from datadouble.redaction import Redactor, kinds
16
+ from datadouble.runtime import runtime_failure
17
+
18
+ _NOISE = ("DETAIL:", "CONTEXT:", "HINT:", "LINE ", "QUERY:", "STATEMENT:")
19
+
20
+ # The shapes in which PostgreSQL reports data values; the ``value`` group is
21
+ # hidden. Message texts are from the server's sources (src/backend), named
22
+ # below; a new one is one more line. Values are matched greedily, so one
23
+ # holding a quote mark is hidden whole. Any other quoted string that no kind
24
+ # word names is hidden anyway.
25
+ _VALUES = (
26
+ # utils/adt: numutils.c, int8.c, float.c, uuid.c, bool.c, enum.c, json.c...
27
+ r'invalid input syntax for type [^:]+: "(?P<value>.*)"',
28
+ r'invalid input value for enum [^:]+: "(?P<value>.*)"',
29
+ r'value "(?P<value>.*)" is out of range for type',
30
+ # utils/adt/datetime.c, formatting.c
31
+ r'(?:date/time field value|time zone displacement) out of range: "(?P<value>.*)"',
32
+ r'invalid value "(?P<value>.*)" for',
33
+ # utils/adt/arrayfuncs.c, rowtypes.c, rangetypes.c, multirangetypes.c
34
+ r'malformed (?:array|record|range|multirange) literal: "(?P<value>.*)"',
35
+ # utils/adt/jsonfuncs.c, a DETAIL line
36
+ r'Token "(?P<value>.*)" is invalid',
37
+ # utils/mb/mbutils.c: the bytes are the data's
38
+ r"invalid byte sequence for encoding \"[^\"]*\": (?P<value>.*)",
39
+ r"character with byte sequence (?P<value>.*?) in encoding",
40
+ # access/nbtree/nbtinsert.c, utils/adt/ri_triggers.c, catalog/index.c,
41
+ # executor/execIndexing.c, DETAIL lines naming the key's columns and values
42
+ (
43
+ r"Key \(.*?\)=\((?P<value>.*)\) (?:already exists|is not present in table"
44
+ r"|is still referenced from table|is duplicated|conflicts with existing key)"
45
+ ),
46
+ r"existing key \(.*?\)=\((?P<value>.*)\)",
47
+ # executor/execMain.c, a DETAIL line with the whole row
48
+ r"Failing row contains \((?P<value>.*)\)",
49
+ # commands/copyfrom.c, a CONTEXT line
50
+ r'COPY [^,]+, line \d+, column [^:]+: "(?P<value>.*)"',
51
+ r'COPY [^,]+, line \d+: "(?P<value>.*)"',
52
+ )
53
+ # Words after which a quoted string names an object: ``relation "orders"``.
54
+ _NAMES = (
55
+ kinds(
56
+ "relation table column constraint index sequence view schema database role"
57
+ " user extension type domain function procedure aggregate operator trigger"
58
+ " rule policy collation conversion encoding language tablespace publication"
59
+ " subscription slot server parameter statistics attribute file directory"
60
+ ),
61
+ )
62
+
63
+ # A message a user raised (RAISE in PL/pgSQL, SQLSTATE P0001; plpy.error in
64
+ # PL/Python, XX000; die in PL/Perl, 38000; error in PL/Tcl) can quote any
65
+ # value, so every quoted string in it is hidden. Its context names the
66
+ # language (``PL/Python function "f"``), and psql and pg_restore print it.
67
+ _RAISED = (r"\bP0001\b", r"\bPL/\w+")
68
+
69
+ redact = Redactor(values=_VALUES, names=_NAMES, marks="\"'", raised=_RAISED)
70
+ """Hide the data values in a PostgreSQL message, keeping the objects it names."""
71
+
72
+
73
+ def database_error(error: psycopg.Error, action: str) -> EngineError:
74
+ """An :class:`EngineError` for a failed database operation."""
75
+ diag = error.diag
76
+ raised = diag.sqlstate == "P0001" or redact.raises(diag.context or "")
77
+ primary = redact(diag.message_primary or type(error).__name__, raised=raised)
78
+ names = [
79
+ f"{label} {value}"
80
+ for label, value in (
81
+ ("schema", diag.schema_name),
82
+ ("table", diag.table_name),
83
+ ("column", diag.column_name),
84
+ ("constraint", diag.constraint_name),
85
+ )
86
+ if value
87
+ ]
88
+ where = f" ({', '.join(names)})" if names else ""
89
+ code = f"[{diag.sqlstate}] " if diag.sqlstate else ""
90
+ return EngineError(f"{action} failed: {code}{primary}{where}")
91
+
92
+
93
+ def tool_error(tool: str, status: int, stderr: str) -> EngineError:
94
+ """An :class:`EngineError` for a failed PostgreSQL command-line tool.
95
+
96
+ Its output is redacted, unless the status says the container runtime
97
+ failed before the program ran (:func:`~datadouble.runtime.runtime_failure`).
98
+ """
99
+ keep = runtime_failure(status)
100
+ raised = redact.raises(stderr)
101
+ lines = [
102
+ line.strip() if keep else redact(line.strip(), raised=raised)
103
+ for line in stderr.splitlines()
104
+ if line.strip() and not line.strip().startswith(_NOISE)
105
+ ]
106
+ summary = "; ".join(lines[-3:]) or "no output"
107
+ return EngineError(f"{tool} exited with status {status}: {summary}")