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.
- datadouble_postgres/__init__.py +192 -0
- datadouble_postgres/cluster.py +229 -0
- datadouble_postgres/errors.py +107 -0
- datadouble_postgres/introspect.py +542 -0
- datadouble_postgres/py.typed +0 -0
- datadouble_postgres/render.py +212 -0
- datadouble_postgres/source.py +380 -0
- datadouble_postgres/working.py +1003 -0
- datadouble_postgres-0.0.3.dist-info/METADATA +249 -0
- datadouble_postgres-0.0.3.dist-info/RECORD +13 -0
- datadouble_postgres-0.0.3.dist-info/WHEEL +4 -0
- datadouble_postgres-0.0.3.dist-info/entry_points.txt +2 -0
- datadouble_postgres-0.0.3.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,1003 @@
|
|
|
1
|
+
# Copyright (c) 2026- Tight Line LLC
|
|
2
|
+
# SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
"""The scratch side: working databases, anonymization, images and restores.
|
|
5
|
+
|
|
6
|
+
``load`` builds a group's working database in a fresh cluster holding every
|
|
7
|
+
database every source read, under its own name: hooks, then in each database the
|
|
8
|
+
source's extensions at the source's versions, the schema's pre-data section,
|
|
9
|
+
the rows (with triggers off), fallbacks for missing parents, the post-data
|
|
10
|
+
section (indexes and constraints, which also check the data), sequences, and
|
|
11
|
+
finally dropping the tables that belong to other groups. A standalone group's
|
|
12
|
+
database holds exactly its closure: the tables it pulls in are kept, with
|
|
13
|
+
the rows of the group's own extract, and every object the closure lacks is
|
|
14
|
+
dropped, dependents first and without ``CASCADE``, so a dependency the
|
|
15
|
+
catalog missed stops the load rather than silently removing something.
|
|
16
|
+
``transform`` copies the stopped cluster and anonymizes the copy in one
|
|
17
|
+
transaction per database. ``package`` writes the data directory (physical) or
|
|
18
|
+
a ``pg_dump`` archive per database (logical); ``restore`` brings either back
|
|
19
|
+
up for verification. Spec SQL that names no table (hooks and assertions) runs
|
|
20
|
+
in the default database.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
import re
|
|
24
|
+
import shutil
|
|
25
|
+
from collections.abc import Callable, Generator, Iterable, Iterator, Sequence
|
|
26
|
+
from contextlib import ExitStack, contextmanager
|
|
27
|
+
from dataclasses import dataclass
|
|
28
|
+
from pathlib import Path
|
|
29
|
+
|
|
30
|
+
import psycopg
|
|
31
|
+
from psycopg import sql
|
|
32
|
+
from psycopg.conninfo import make_conninfo
|
|
33
|
+
from pydantic import BaseModel, ConfigDict
|
|
34
|
+
|
|
35
|
+
from datadouble.catalog import (
|
|
36
|
+
Column,
|
|
37
|
+
ColumnKind,
|
|
38
|
+
ObjectKind,
|
|
39
|
+
ObjectRef,
|
|
40
|
+
Requirement,
|
|
41
|
+
RequirementKind,
|
|
42
|
+
SourceObject,
|
|
43
|
+
)
|
|
44
|
+
from datadouble.closure import ordered
|
|
45
|
+
from datadouble.engine import (
|
|
46
|
+
Account,
|
|
47
|
+
EngineError,
|
|
48
|
+
RestoredImage,
|
|
49
|
+
TableCount,
|
|
50
|
+
Transformation,
|
|
51
|
+
group_extract,
|
|
52
|
+
)
|
|
53
|
+
from datadouble.files import copy_tree
|
|
54
|
+
from datadouble.names import ColumnName, ColumnRef, TableName
|
|
55
|
+
from datadouble.planner import Fixup, Plan, PlannedGroup, PlannedRule
|
|
56
|
+
from datadouble.spec import AccountPrivileges, ExpressionRule, Hook, ImageFormat, NullRule
|
|
57
|
+
from datadouble.subset import Edge, EdgeMode
|
|
58
|
+
from datadouble_postgres.cluster import SUPERUSER, Cluster, Tools
|
|
59
|
+
from datadouble_postgres.errors import database_error, redact
|
|
60
|
+
from datadouble_postgres.render import (
|
|
61
|
+
Statement,
|
|
62
|
+
columns,
|
|
63
|
+
database_of,
|
|
64
|
+
trusted,
|
|
65
|
+
unqualified,
|
|
66
|
+
)
|
|
67
|
+
from datadouble_postgres.source import ExtractedDatabase, ExtractedTable, ExtractIndex
|
|
68
|
+
|
|
69
|
+
type Connection = psycopg.Connection[tuple[object, ...]]
|
|
70
|
+
|
|
71
|
+
_DATADIR = "pgdata"
|
|
72
|
+
_INFO = "database.json"
|
|
73
|
+
# An entry ends with its owner; extensions have none, so their lines end in a space.
|
|
74
|
+
_TOC = re.compile(r"^\d+; \d+ \d+ (.+) \S*$")
|
|
75
|
+
_DESCRIPTIONS = (
|
|
76
|
+
"FK CONSTRAINT",
|
|
77
|
+
"MATERIALIZED VIEW DATA",
|
|
78
|
+
"MATERIALIZED VIEW",
|
|
79
|
+
"VIEW",
|
|
80
|
+
"COMMENT",
|
|
81
|
+
"SCHEMA",
|
|
82
|
+
"EXTENSION",
|
|
83
|
+
)
|
|
84
|
+
_PLACEHOLDERS: dict[ColumnKind, str] = {
|
|
85
|
+
ColumnKind.TEXT: "",
|
|
86
|
+
ColumnKind.INTEGER: "0",
|
|
87
|
+
ColumnKind.DECIMAL: "0",
|
|
88
|
+
ColumnKind.FLOAT: "0",
|
|
89
|
+
ColumnKind.BOOLEAN: "false",
|
|
90
|
+
ColumnKind.DATE: "epoch",
|
|
91
|
+
ColumnKind.TIMESTAMP: "epoch",
|
|
92
|
+
ColumnKind.TIME: "00:00",
|
|
93
|
+
ColumnKind.UUID: "00000000-0000-0000-0000-000000000000",
|
|
94
|
+
ColumnKind.JSON: "{}",
|
|
95
|
+
ColumnKind.ARRAY: "{}",
|
|
96
|
+
ColumnKind.BINARY: "",
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
class DatabaseInfo(BaseModel):
|
|
101
|
+
"""Stored beside a working database and in every image."""
|
|
102
|
+
|
|
103
|
+
model_config = ConfigDict(strict=True, frozen=True, extra="forbid")
|
|
104
|
+
|
|
105
|
+
databases: tuple[str, ...]
|
|
106
|
+
default: str
|
|
107
|
+
"""The database spec SQL without a table runs in, and copies announce."""
|
|
108
|
+
server_version: str
|
|
109
|
+
partitioned: tuple[TableName, ...]
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def dump_name(position: int) -> str:
|
|
113
|
+
"""The file holding the ``position``-th database's archive in a logical image."""
|
|
114
|
+
return f"database-{position:03d}.dump"
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
_qualified = unqualified
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _table(name: TableName, partitioned: frozenset[TableName]) -> sql.Composable:
|
|
121
|
+
return _qualified(name) if name in partitioned else sql.SQL("ONLY {}").format(_qualified(name))
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _and(parts: Iterable[sql.Composable]) -> sql.Composed:
|
|
125
|
+
return sql.SQL(" AND ").join(parts)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _commas(parts: Iterable[sql.Composable]) -> sql.Composed:
|
|
129
|
+
return sql.SQL(", ").join(parts)
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def toc_entry(line: str) -> tuple[str, str, str] | None:
|
|
133
|
+
"""A ``pg_restore --list`` line's ``(description, schema, tag)``, for the kinds handled."""
|
|
134
|
+
match = _TOC.match(line)
|
|
135
|
+
if match is None:
|
|
136
|
+
return None
|
|
137
|
+
description = next((d for d in _DESCRIPTIONS if match.group(1).startswith(d + " ")), None)
|
|
138
|
+
if description is None:
|
|
139
|
+
return None
|
|
140
|
+
schema, _, tag = match.group(1)[len(description) + 1 :].partition(" ")
|
|
141
|
+
return description, schema, tag
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def filter_toc(
|
|
145
|
+
listing: str, drop: frozenset[tuple[str, str, str]], *, comments: bool = True
|
|
146
|
+
) -> str:
|
|
147
|
+
"""Remove ``pg_restore --list`` entries matching ``(description, schema, tag)``.
|
|
148
|
+
|
|
149
|
+
Comments on a removed object are removed with it, unless ``comments`` is false.
|
|
150
|
+
"""
|
|
151
|
+
commented = (
|
|
152
|
+
{(schema, f"{description} {tag}") for description, schema, tag in drop}
|
|
153
|
+
if comments
|
|
154
|
+
else set[tuple[str, str]]()
|
|
155
|
+
)
|
|
156
|
+
kept: list[str] = []
|
|
157
|
+
for line in listing.splitlines():
|
|
158
|
+
entry = toc_entry(line)
|
|
159
|
+
if entry is not None:
|
|
160
|
+
description, schema, tag = entry
|
|
161
|
+
if entry in drop or (description == "COMMENT" and (schema, tag) in commented):
|
|
162
|
+
continue
|
|
163
|
+
kept.append(line)
|
|
164
|
+
return "\n".join(kept) + "\n"
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def only_toc(listing: str, description: str) -> tuple[str, frozenset[tuple[str, str, str]]]:
|
|
168
|
+
"""The listing reduced to entries of one ``description``, and those entries."""
|
|
169
|
+
entries = [(line, toc_entry(line)) for line in listing.splitlines()]
|
|
170
|
+
kept = [(line, e) for line, e in entries if e is not None and e[0] == description]
|
|
171
|
+
return "".join(line + "\n" for line, _ in kept), frozenset(e for _, e in kept)
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def placeholder(table: TableName, column: Column) -> sql.Composable:
|
|
175
|
+
"""A stand-in value for a required column of a stub row."""
|
|
176
|
+
value = _PLACEHOLDERS.get(column.kind)
|
|
177
|
+
if value is None:
|
|
178
|
+
message = (
|
|
179
|
+
f"cannot stub {table}: no placeholder for {column.name} ({column.type}); "
|
|
180
|
+
"make the column nullable, give it a default, or use another fallback"
|
|
181
|
+
)
|
|
182
|
+
raise EngineError(message)
|
|
183
|
+
return sql.SQL("{}::{}").format(sql.Literal(value), trusted(column.type))
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def _execute(connection: Connection, action: str, statement: Statement) -> None:
|
|
187
|
+
try:
|
|
188
|
+
connection.execute(statement)
|
|
189
|
+
except psycopg.Error as error:
|
|
190
|
+
raise database_error(error, action) from None
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
class PostgresRestored:
|
|
194
|
+
"""Databases open for checks: a restored image, or a working database.
|
|
195
|
+
|
|
196
|
+
Each database gets its connection when a check first needs it; checks that
|
|
197
|
+
name no table run in the default database.
|
|
198
|
+
"""
|
|
199
|
+
|
|
200
|
+
def __init__(
|
|
201
|
+
self,
|
|
202
|
+
connect: Callable[[str], Connection],
|
|
203
|
+
default: str,
|
|
204
|
+
partitioned: frozenset[TableName],
|
|
205
|
+
) -> None:
|
|
206
|
+
"""Open connections with ``connect``, by database name."""
|
|
207
|
+
self.connect = connect
|
|
208
|
+
self.default = default
|
|
209
|
+
self.partitioned = partitioned
|
|
210
|
+
self.connections: dict[str, Connection] = {}
|
|
211
|
+
|
|
212
|
+
def close(self) -> None:
|
|
213
|
+
"""Close every connection opened."""
|
|
214
|
+
for connection in self.connections.values():
|
|
215
|
+
connection.close()
|
|
216
|
+
|
|
217
|
+
def _connection(self, database: str) -> Connection:
|
|
218
|
+
if database not in self.connections:
|
|
219
|
+
self.connections[database] = self.connect(database)
|
|
220
|
+
return self.connections[database]
|
|
221
|
+
|
|
222
|
+
def _scalar(self, database: str, action: str, statement: Statement) -> int:
|
|
223
|
+
try:
|
|
224
|
+
row = self._connection(database).execute(statement).fetchone()
|
|
225
|
+
except psycopg.Error as error:
|
|
226
|
+
raise database_error(error, action) from None
|
|
227
|
+
return int(str(row[0])) if row else 0
|
|
228
|
+
|
|
229
|
+
def counts(self, tables: Iterable[TableName]) -> dict[TableName, int]:
|
|
230
|
+
"""Rows per table."""
|
|
231
|
+
return {
|
|
232
|
+
table: self._scalar(
|
|
233
|
+
database_of(table),
|
|
234
|
+
f"counting {table}",
|
|
235
|
+
sql.SQL("SELECT count(*) FROM {}").format(_table(table, self.partitioned)),
|
|
236
|
+
)
|
|
237
|
+
for table in tables
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
def orphans(self, edge: Edge) -> int:
|
|
241
|
+
"""Child rows with a non-null reference and no parent."""
|
|
242
|
+
present = _and(sql.SQL("c.{} IS NOT NULL").format(sql.Identifier(c)) for c in edge.columns)
|
|
243
|
+
matches = _and(
|
|
244
|
+
(
|
|
245
|
+
sql.SQL("p.{} = c.{}").format(sql.Identifier(p), sql.Identifier(c))
|
|
246
|
+
for p, c in zip(edge.parent_columns, edge.columns, strict=True)
|
|
247
|
+
),
|
|
248
|
+
)
|
|
249
|
+
when = sql.SQL(" AND ({})").format(trusted(edge.when)) if edge.when else sql.SQL("")
|
|
250
|
+
return self._scalar(
|
|
251
|
+
database_of(edge.child),
|
|
252
|
+
f"checking {edge.name}",
|
|
253
|
+
sql.SQL(
|
|
254
|
+
"SELECT count(*) FROM {} c WHERE {}{} AND NOT EXISTS (SELECT 1 FROM {} p WHERE {})"
|
|
255
|
+
).format(
|
|
256
|
+
_table(edge.child, self.partitioned),
|
|
257
|
+
present,
|
|
258
|
+
when,
|
|
259
|
+
_table(edge.parent, self.partitioned),
|
|
260
|
+
matches,
|
|
261
|
+
),
|
|
262
|
+
)
|
|
263
|
+
|
|
264
|
+
def text_values(self, column: ColumnRef) -> Iterator[str]:
|
|
265
|
+
"""Distinct non-null values of a column, as text, streamed."""
|
|
266
|
+
statement = sql.SQL("SELECT DISTINCT {}::text FROM {} WHERE {} IS NOT NULL").format(
|
|
267
|
+
sql.Identifier(column.column),
|
|
268
|
+
_table(column.table, self.partitioned),
|
|
269
|
+
sql.Identifier(column.column),
|
|
270
|
+
)
|
|
271
|
+
connection = self._connection(database_of(column.table))
|
|
272
|
+
try:
|
|
273
|
+
with connection.transaction(), connection.cursor(name="dd_values") as cursor:
|
|
274
|
+
cursor.execute(statement)
|
|
275
|
+
for (value,) in cursor:
|
|
276
|
+
yield str(value)
|
|
277
|
+
except psycopg.Error as error:
|
|
278
|
+
raise database_error(error, f"scanning {column}") from None
|
|
279
|
+
|
|
280
|
+
def failing_rows(self, query: str) -> int:
|
|
281
|
+
"""Rows a spec assertion returns."""
|
|
282
|
+
return self._scalar(
|
|
283
|
+
self.default,
|
|
284
|
+
"running an assertion",
|
|
285
|
+
sql.SQL("SELECT count(*) FROM ({}) AS assertion").format(trusted(query)),
|
|
286
|
+
)
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
def _sources(
|
|
290
|
+
group: PlannedGroup, index: ExtractIndex, extract: Path
|
|
291
|
+
) -> Iterator[tuple[Path, ExtractedTable]]:
|
|
292
|
+
"""Each table whose rows the group's database holds, and the folder its file is in.
|
|
293
|
+
|
|
294
|
+
A standalone group's own extract has the rows it pulls in, and its own
|
|
295
|
+
tables' when they gained some; other own tables come from the shared one.
|
|
296
|
+
"""
|
|
297
|
+
own = group_extract(extract, group.name)
|
|
298
|
+
taken: set[TableName] = set()
|
|
299
|
+
if own is not None:
|
|
300
|
+
pulled = ExtractIndex.model_validate_json((own / "index.json").read_bytes())
|
|
301
|
+
for table in pulled.tables:
|
|
302
|
+
taken.add(table.table)
|
|
303
|
+
yield own, table
|
|
304
|
+
members = frozenset(group.tables)
|
|
305
|
+
for table in index.tables:
|
|
306
|
+
if table.table in members and table.table not in taken:
|
|
307
|
+
yield extract, table
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def drop_outside(
|
|
311
|
+
connection: Connection,
|
|
312
|
+
objects: tuple[SourceObject, ...],
|
|
313
|
+
group: PlannedGroup,
|
|
314
|
+
database: str,
|
|
315
|
+
) -> None:
|
|
316
|
+
"""Drop the database's ``objects`` the group's closure lacks, dependents first."""
|
|
317
|
+
wanted = frozenset(group.objects)
|
|
318
|
+
members = frozenset(group.packaged())
|
|
319
|
+
# What needs a table the database lacks went with it.
|
|
320
|
+
found = [
|
|
321
|
+
item.ref
|
|
322
|
+
for item in objects
|
|
323
|
+
if item.ref.namespace[0] == database
|
|
324
|
+
and item.ref not in wanted
|
|
325
|
+
and all(
|
|
326
|
+
edge.table in members
|
|
327
|
+
for edge in item.depends_on
|
|
328
|
+
if edge.table is not None and not edge.inferred
|
|
329
|
+
)
|
|
330
|
+
]
|
|
331
|
+
for ref in reversed(ordered(found, objects)):
|
|
332
|
+
try:
|
|
333
|
+
for statement in _drop(connection, ref):
|
|
334
|
+
connection.execute(statement)
|
|
335
|
+
except psycopg.errors.DependentObjectsStillExist as error:
|
|
336
|
+
# Aggregates, operators, casts and the like are not in the catalog,
|
|
337
|
+
# so PostgreSQL's detail is what names the dependent.
|
|
338
|
+
blocking = redact(error.diag.message_detail or "no detail given")
|
|
339
|
+
message = (
|
|
340
|
+
f"dropping {ref}, which the closure of group {group.name!r} lacks, failed: "
|
|
341
|
+
f"something outside the closure, perhaps not in the catalog, depends on it "
|
|
342
|
+
f"({blocking}); declare {ref.kind} "
|
|
343
|
+
f"{'.'.join((ref.namespace[-1], ref.name))} in the group's `objects` to keep it"
|
|
344
|
+
)
|
|
345
|
+
raise EngineError(message) from None
|
|
346
|
+
except psycopg.Error as error:
|
|
347
|
+
raise database_error(error, f"dropping {ref}") from None
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
_DROPPED: dict[ObjectKind, sql.SQL] = {
|
|
351
|
+
ObjectKind.FUNCTION: sql.SQL("FUNCTION"),
|
|
352
|
+
ObjectKind.PROCEDURE: sql.SQL("PROCEDURE"),
|
|
353
|
+
ObjectKind.VIEW: sql.SQL("VIEW"),
|
|
354
|
+
ObjectKind.MATERIALIZED_VIEW: sql.SQL("MATERIALIZED VIEW"),
|
|
355
|
+
ObjectKind.SEQUENCE: sql.SQL("SEQUENCE"),
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
|
|
359
|
+
_TRIGGER_RELATION = """
|
|
360
|
+
SELECT c.relname, t.tgname
|
|
361
|
+
FROM pg_catalog.pg_trigger t
|
|
362
|
+
JOIN pg_catalog.pg_class c ON c.oid = t.tgrelid
|
|
363
|
+
JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
|
|
364
|
+
WHERE NOT t.tgisinternal AND n.nspname = %s AND c.relname || '.' || t.tgname = %s
|
|
365
|
+
"""
|
|
366
|
+
"""The table or view a trigger is on, found by the name the catalog gives it."""
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
def _drop(connection: Connection, ref: ObjectRef) -> tuple[sql.Composed, ...]:
|
|
370
|
+
"""The statements that drop ``ref``, refusing if anything depends on it; none if it is gone."""
|
|
371
|
+
schema = ref.namespace[-1]
|
|
372
|
+
name = sql.Identifier(schema, ref.name)
|
|
373
|
+
if ref.kind is ObjectKind.TRIGGER:
|
|
374
|
+
# A trigger's catalog name is its table's or view's and its own, joined
|
|
375
|
+
# with a dot; either may hold dots, so the database says which is which.
|
|
376
|
+
# Nothing is found if the trigger went with its table or view.
|
|
377
|
+
relations = connection.execute(_TRIGGER_RELATION, [schema, ref.name]).fetchall()
|
|
378
|
+
return tuple(
|
|
379
|
+
sql.SQL("DROP TRIGGER {} ON {}").format(
|
|
380
|
+
sql.Identifier(str(trigger)), sql.Identifier(schema, str(relation))
|
|
381
|
+
)
|
|
382
|
+
for relation, trigger in relations
|
|
383
|
+
)
|
|
384
|
+
if ref.kind is ObjectKind.TYPE:
|
|
385
|
+
found = connection.execute(
|
|
386
|
+
"SELECT t.typtype FROM pg_catalog.pg_type t"
|
|
387
|
+
" JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace"
|
|
388
|
+
" WHERE n.nspname = %s AND t.typname = %s",
|
|
389
|
+
[schema, ref.name],
|
|
390
|
+
).fetchone()
|
|
391
|
+
kind = sql.SQL("DOMAIN") if found and found[0] == "d" else sql.SQL("TYPE")
|
|
392
|
+
return (sql.SQL("DROP {} IF EXISTS {}").format(kind, name),)
|
|
393
|
+
# The signature is the catalog's own spelling of the argument types.
|
|
394
|
+
arguments = trusted(ref.signature) if ref.signature else sql.SQL("")
|
|
395
|
+
return (sql.SQL("DROP {} IF EXISTS {}{}").format(_DROPPED[ref.kind], name, arguments),)
|
|
396
|
+
|
|
397
|
+
|
|
398
|
+
@dataclass(frozen=True, slots=True)
|
|
399
|
+
class _Loading:
|
|
400
|
+
"""What loading each database of a group's working database needs."""
|
|
401
|
+
|
|
402
|
+
cluster: Cluster
|
|
403
|
+
plan: Plan
|
|
404
|
+
group: PlannedGroup
|
|
405
|
+
index: ExtractIndex
|
|
406
|
+
extract: Path
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
class PostgresWorking:
|
|
410
|
+
"""Working databases and images under one scratch directory."""
|
|
411
|
+
|
|
412
|
+
def __init__(self, tools: Tools, scratch: Path) -> None:
|
|
413
|
+
"""Use ``tools`` for every cluster under ``scratch``."""
|
|
414
|
+
self.tools = tools
|
|
415
|
+
self.scratch = scratch
|
|
416
|
+
self._version: str | None = None
|
|
417
|
+
|
|
418
|
+
def server_version(self) -> str:
|
|
419
|
+
"""The version of the image's server, which images are built for."""
|
|
420
|
+
if self._version is None:
|
|
421
|
+
self._version = self.tools.version()
|
|
422
|
+
return self._version
|
|
423
|
+
|
|
424
|
+
def close(self) -> None:
|
|
425
|
+
"""Nothing to stop: each call starts and stops its own servers."""
|
|
426
|
+
|
|
427
|
+
def available(self) -> tuple[Requirement, ...]:
|
|
428
|
+
"""Every version of every extension the image has, from a throwaway cluster."""
|
|
429
|
+
directory = self.scratch / "available"
|
|
430
|
+
cluster = Cluster(self.tools, directory / _DATADIR, directory)
|
|
431
|
+
try:
|
|
432
|
+
cluster.initialize()
|
|
433
|
+
with cluster.running(), cluster.connect("postgres") as connection:
|
|
434
|
+
rows = connection.execute(
|
|
435
|
+
"SELECT name, version FROM pg_catalog.pg_available_extension_versions"
|
|
436
|
+
).fetchall()
|
|
437
|
+
finally:
|
|
438
|
+
shutil.rmtree(directory, ignore_errors=True)
|
|
439
|
+
return tuple(
|
|
440
|
+
Requirement(kind=RequirementKind.EXTENSION, name=str(name), version=str(version))
|
|
441
|
+
for name, version in rows
|
|
442
|
+
)
|
|
443
|
+
|
|
444
|
+
# load
|
|
445
|
+
|
|
446
|
+
def load(
|
|
447
|
+
self,
|
|
448
|
+
plan: Plan,
|
|
449
|
+
group: PlannedGroup,
|
|
450
|
+
extracts: tuple[Path, ...],
|
|
451
|
+
directory: Path,
|
|
452
|
+
hooks: tuple[Hook, ...],
|
|
453
|
+
) -> tuple[TableCount, ...]:
|
|
454
|
+
"""Build the group's working database, holding every database every source read.
|
|
455
|
+
|
|
456
|
+
Hooks run in the first source's default database.
|
|
457
|
+
"""
|
|
458
|
+
indexes = [
|
|
459
|
+
(extract, ExtractIndex.model_validate_json((extract / "index.json").read_bytes()))
|
|
460
|
+
for extract in extracts
|
|
461
|
+
]
|
|
462
|
+
default = indexes[0][1].default
|
|
463
|
+
partitioned = tuple(sorted({t for _, index in indexes for t in index.partitioned}))
|
|
464
|
+
databases = tuple(database.name for _, index in indexes for database in index.databases)
|
|
465
|
+
cluster = Cluster(self.tools, directory / _DATADIR, directory, extracts)
|
|
466
|
+
cluster.initialize()
|
|
467
|
+
with cluster.running():
|
|
468
|
+
for name in databases:
|
|
469
|
+
cluster.create_database(name)
|
|
470
|
+
with cluster.connect(default) as connection:
|
|
471
|
+
for hook in hooks:
|
|
472
|
+
_execute(connection, "a before_load hook", trusted(hook.sql))
|
|
473
|
+
for extract, index in indexes:
|
|
474
|
+
loading = _Loading(cluster, plan, group, index, extract)
|
|
475
|
+
for database in index.databases:
|
|
476
|
+
self._load_database(loading, database)
|
|
477
|
+
restored = PostgresRestored(cluster.connect, default, frozenset(partitioned))
|
|
478
|
+
try:
|
|
479
|
+
counts = restored.counts(group.packaged())
|
|
480
|
+
finally:
|
|
481
|
+
restored.close()
|
|
482
|
+
info = DatabaseInfo(
|
|
483
|
+
databases=databases,
|
|
484
|
+
default=default,
|
|
485
|
+
server_version=self.server_version(),
|
|
486
|
+
partitioned=partitioned,
|
|
487
|
+
)
|
|
488
|
+
(directory / _INFO).write_text(info.model_dump_json(indent=2), "utf-8")
|
|
489
|
+
return tuple(TableCount(table=t, rows=n) for t, n in counts.items())
|
|
490
|
+
|
|
491
|
+
def _load_database(self, loading: "_Loading", database: ExtractedDatabase) -> None:
|
|
492
|
+
"""Restore one database's schema and load its rows."""
|
|
493
|
+
cluster, plan, group, index, extract = (
|
|
494
|
+
loading.cluster,
|
|
495
|
+
loading.plan,
|
|
496
|
+
loading.group,
|
|
497
|
+
loading.index,
|
|
498
|
+
loading.extract,
|
|
499
|
+
)
|
|
500
|
+
name = database.name
|
|
501
|
+
members = frozenset(group.packaged())
|
|
502
|
+
rowless = group.rowless()
|
|
503
|
+
dump = extract / database.schema_file
|
|
504
|
+
listing = cluster.execute("pg_restore", ["--list", str(dump)])
|
|
505
|
+
views = frozenset(
|
|
506
|
+
(kind, view.namespace[-1], view.name)
|
|
507
|
+
for view in database.omitted_views
|
|
508
|
+
for kind in ("VIEW", "MATERIALIZED VIEW", "MATERIALIZED VIEW DATA")
|
|
509
|
+
)
|
|
510
|
+
# A constraint whose table is in the group but whose target is not (in
|
|
511
|
+
# another group, or excluded) would fail on the rows: leave it out.
|
|
512
|
+
# So would one into a pulled-in table that comes without rows.
|
|
513
|
+
foreign = frozenset(
|
|
514
|
+
("FK CONSTRAINT", constraint.namespace, f"{constraint.table} {constraint.name}")
|
|
515
|
+
for constraint in database.constraints
|
|
516
|
+
if constraint.child in members
|
|
517
|
+
and (
|
|
518
|
+
constraint.parent not in members
|
|
519
|
+
or (constraint.parent in rowless and constraint.child not in rowless)
|
|
520
|
+
)
|
|
521
|
+
)
|
|
522
|
+
listing = self._extensions(cluster, database, plan, dump, listing)
|
|
523
|
+
self._restore(cluster, name, dump, "pre-data", filter_toc(listing, views))
|
|
524
|
+
own = [table for table in index.tables if database_of(table.table) == name]
|
|
525
|
+
with cluster.connect(name) as connection, connection.transaction():
|
|
526
|
+
connection.execute("SET LOCAL session_replication_role = replica")
|
|
527
|
+
for folder, table in _sources(group, index, extract):
|
|
528
|
+
if database_of(table.table) == name:
|
|
529
|
+
self._copy_in(connection, folder / table.file, table.table, table.columns)
|
|
530
|
+
for fixup in group.fixups:
|
|
531
|
+
if database_of(fixup.edge.child) == name:
|
|
532
|
+
self._fixup(connection, plan, index, fixup)
|
|
533
|
+
self._restore(cluster, name, dump, "post-data", filter_toc(listing, views | foreign))
|
|
534
|
+
with cluster.connect(name) as connection:
|
|
535
|
+
self._sequences(connection)
|
|
536
|
+
for table in own:
|
|
537
|
+
if table.table not in members:
|
|
538
|
+
_execute(
|
|
539
|
+
connection,
|
|
540
|
+
f"dropping {table.table}",
|
|
541
|
+
sql.SQL("DROP TABLE IF EXISTS {} CASCADE").format(_qualified(table.table)),
|
|
542
|
+
)
|
|
543
|
+
if group.standalone:
|
|
544
|
+
drop_outside(connection, plan.catalog.objects, group, name)
|
|
545
|
+
|
|
546
|
+
def _extensions(
|
|
547
|
+
self, cluster: Cluster, database: ExtractedDatabase, plan: Plan, dump: Path, listing: str
|
|
548
|
+
) -> str:
|
|
549
|
+
"""Create the kept extensions at the source's versions; the listing left to restore.
|
|
550
|
+
|
|
551
|
+
``pg_dump`` writes ``CREATE EXTENSION`` without a version, which would
|
|
552
|
+
install the image's default. So the schemas are restored first, then
|
|
553
|
+
each extension is created at its version, and the listing returned
|
|
554
|
+
holds neither. Omitted extensions are left out; whatever uses one fails
|
|
555
|
+
to restore.
|
|
556
|
+
"""
|
|
557
|
+
if not database.extensions:
|
|
558
|
+
return listing
|
|
559
|
+
omitted = frozenset(r.name for r in plan.omitted)
|
|
560
|
+
schemas, schema_entries = only_toc(listing, "SCHEMA")
|
|
561
|
+
_, extension_entries = only_toc(listing, "EXTENSION")
|
|
562
|
+
if schema_entries:
|
|
563
|
+
self._restore(cluster, database.name, dump, "pre-data", schemas)
|
|
564
|
+
with cluster.connect(database.name) as connection:
|
|
565
|
+
for extension in database.extensions:
|
|
566
|
+
if extension.name in omitted:
|
|
567
|
+
continue
|
|
568
|
+
_execute(
|
|
569
|
+
connection,
|
|
570
|
+
f"creating extension {extension.name} {extension.version}",
|
|
571
|
+
sql.SQL("CREATE EXTENSION IF NOT EXISTS {} WITH SCHEMA {} VERSION {}").format(
|
|
572
|
+
sql.Identifier(extension.name),
|
|
573
|
+
sql.Identifier(extension.schema_),
|
|
574
|
+
sql.Literal(extension.version),
|
|
575
|
+
),
|
|
576
|
+
)
|
|
577
|
+
rest = filter_toc(listing, extension_entries)
|
|
578
|
+
return filter_toc(rest, schema_entries, comments=False)
|
|
579
|
+
|
|
580
|
+
def _restore(self, cluster: Cluster, database: str, dump: Path, section: str, toc: str) -> None:
|
|
581
|
+
listing = cluster.datadir.parent / f"{section}.list"
|
|
582
|
+
listing.write_text(toc, "utf-8")
|
|
583
|
+
try:
|
|
584
|
+
cluster.execute(
|
|
585
|
+
"pg_restore",
|
|
586
|
+
[
|
|
587
|
+
f"--section={section}",
|
|
588
|
+
f"--use-list={listing}",
|
|
589
|
+
"--no-owner",
|
|
590
|
+
"--no-privileges",
|
|
591
|
+
"--exit-on-error",
|
|
592
|
+
f"--dbname={cluster.local_conninfo(database)}",
|
|
593
|
+
str(dump),
|
|
594
|
+
],
|
|
595
|
+
)
|
|
596
|
+
finally:
|
|
597
|
+
listing.unlink(missing_ok=True)
|
|
598
|
+
|
|
599
|
+
@staticmethod
|
|
600
|
+
def _copy_in(
|
|
601
|
+
connection: Connection, path: Path, table: TableName, names: tuple[ColumnName, ...]
|
|
602
|
+
) -> None:
|
|
603
|
+
statement = sql.SQL("COPY {} ({}) FROM STDIN").format(_qualified(table), columns(names))
|
|
604
|
+
try:
|
|
605
|
+
with (
|
|
606
|
+
connection.cursor() as cursor,
|
|
607
|
+
cursor.copy(statement) as copy,
|
|
608
|
+
path.open("rb") as data,
|
|
609
|
+
):
|
|
610
|
+
while chunk := data.read(1 << 20):
|
|
611
|
+
copy.write(chunk)
|
|
612
|
+
except psycopg.Error as error:
|
|
613
|
+
raise database_error(error, f"loading {table}") from None
|
|
614
|
+
|
|
615
|
+
def _fixup(self, connection: Connection, plan: Plan, index: ExtractIndex, fixup: Fixup) -> None:
|
|
616
|
+
"""Null or stub references whose parent rows are missing."""
|
|
617
|
+
edge = fixup.edge
|
|
618
|
+
conditions = [sql.SQL("c.{} IS NOT NULL").format(sql.Identifier(c)) for c in edge.columns]
|
|
619
|
+
if edge.when:
|
|
620
|
+
conditions.append(sql.SQL("({})").format(trusted(edge.when)))
|
|
621
|
+
if fixup.parent_present:
|
|
622
|
+
conditions.append(
|
|
623
|
+
sql.SQL("NOT EXISTS (SELECT 1 FROM {} p WHERE {})").format(
|
|
624
|
+
_table(edge.parent, frozenset(index.partitioned)),
|
|
625
|
+
_and(
|
|
626
|
+
(
|
|
627
|
+
sql.SQL("p.{} = c.{}").format(sql.Identifier(p), sql.Identifier(c))
|
|
628
|
+
for p, c in zip(edge.parent_columns, edge.columns, strict=True)
|
|
629
|
+
),
|
|
630
|
+
),
|
|
631
|
+
)
|
|
632
|
+
)
|
|
633
|
+
where = _and(conditions)
|
|
634
|
+
child = _qualified(edge.child)
|
|
635
|
+
if fixup.mode is EdgeMode.NULL:
|
|
636
|
+
assignments = _commas(
|
|
637
|
+
sql.SQL("{} = NULL").format(sql.Identifier(c)) for c in edge.columns
|
|
638
|
+
)
|
|
639
|
+
statement: Statement = sql.SQL("UPDATE {} c SET {} WHERE {}").format(
|
|
640
|
+
child, assignments, where
|
|
641
|
+
)
|
|
642
|
+
else:
|
|
643
|
+
statement = self._stub(plan, index, edge, child, where)
|
|
644
|
+
_execute(connection, f"applying the fallback for {edge.name}", statement)
|
|
645
|
+
|
|
646
|
+
@staticmethod
|
|
647
|
+
def _stub(
|
|
648
|
+
plan: Plan, index: ExtractIndex, edge: Edge, child: sql.Composable, where: sql.Composable
|
|
649
|
+
) -> Statement:
|
|
650
|
+
# The planner only allows stubs into tables the image has; if one is
|
|
651
|
+
# missing anyway, the INSERT fails and the database says why.
|
|
652
|
+
parent = plan.catalog.table(edge.parent)
|
|
653
|
+
extracted = index.table(edge.parent)
|
|
654
|
+
columns = parent.columns if parent else ()
|
|
655
|
+
copied = extracted.columns if extracted else ()
|
|
656
|
+
fillers = [
|
|
657
|
+
(column.name, placeholder(edge.parent, column))
|
|
658
|
+
for column in columns
|
|
659
|
+
if column.name not in edge.parent_columns
|
|
660
|
+
and not column.nullable
|
|
661
|
+
and column.name in copied
|
|
662
|
+
]
|
|
663
|
+
return sql.SQL("INSERT INTO {} ({}) SELECT DISTINCT {} FROM {} c WHERE {}").format(
|
|
664
|
+
_qualified(edge.parent),
|
|
665
|
+
_commas(sql.Identifier(n) for n in [*edge.parent_columns, *(n for n, _ in fillers)]),
|
|
666
|
+
_commas(
|
|
667
|
+
[
|
|
668
|
+
*(sql.SQL("c.{}").format(sql.Identifier(c)) for c in edge.columns),
|
|
669
|
+
*(value for _, value in fillers),
|
|
670
|
+
],
|
|
671
|
+
),
|
|
672
|
+
child,
|
|
673
|
+
where,
|
|
674
|
+
)
|
|
675
|
+
|
|
676
|
+
@staticmethod
|
|
677
|
+
def _sequences(connection: Connection) -> None:
|
|
678
|
+
"""Move every column-owned sequence past the loaded rows."""
|
|
679
|
+
rows = connection.execute(
|
|
680
|
+
"""
|
|
681
|
+
SELECT n.nspname, c.relname, a.attname,
|
|
682
|
+
pg_catalog.pg_get_serial_sequence(
|
|
683
|
+
pg_catalog.format('%I.%I', n.nspname, c.relname), a.attname)
|
|
684
|
+
FROM pg_catalog.pg_class c
|
|
685
|
+
JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
|
|
686
|
+
JOIN pg_catalog.pg_attribute a
|
|
687
|
+
ON a.attrelid = c.oid AND a.attnum > 0 AND NOT a.attisdropped
|
|
688
|
+
WHERE c.relkind IN ('r', 'p') AND NOT c.relispartition
|
|
689
|
+
AND n.nspname NOT IN ('pg_catalog', 'information_schema')
|
|
690
|
+
"""
|
|
691
|
+
).fetchall()
|
|
692
|
+
for schema, table, column, sequence in rows:
|
|
693
|
+
if sequence is None:
|
|
694
|
+
continue
|
|
695
|
+
name = sql.Identifier(str(column))
|
|
696
|
+
_execute(
|
|
697
|
+
connection,
|
|
698
|
+
f"setting {sequence}",
|
|
699
|
+
sql.SQL(
|
|
700
|
+
"SELECT pg_catalog.setval({}, coalesce(max({}), 1), max({}) IS NOT NULL) "
|
|
701
|
+
"FROM {}"
|
|
702
|
+
).format(
|
|
703
|
+
sql.Literal(str(sequence)), name, name, sql.Identifier(str(schema), str(table))
|
|
704
|
+
),
|
|
705
|
+
)
|
|
706
|
+
|
|
707
|
+
# transform
|
|
708
|
+
|
|
709
|
+
def transform(
|
|
710
|
+
self,
|
|
711
|
+
group: PlannedGroup,
|
|
712
|
+
source: Path,
|
|
713
|
+
directory: Path,
|
|
714
|
+
transformation: Transformation,
|
|
715
|
+
) -> tuple[TableCount, ...]:
|
|
716
|
+
"""Copy the working database and anonymize the copy, one transaction per database.
|
|
717
|
+
|
|
718
|
+
Hooks run in the default database's transaction, after its rules.
|
|
719
|
+
"""
|
|
720
|
+
directory.parent.mkdir(parents=True, exist_ok=True)
|
|
721
|
+
_copy_tree(source, directory)
|
|
722
|
+
info = DatabaseInfo.model_validate_json((directory / _INFO).read_bytes())
|
|
723
|
+
partitioned = frozenset(info.partitioned)
|
|
724
|
+
by_table: dict[TableName, list[PlannedRule]] = {}
|
|
725
|
+
for rule in transformation.rules:
|
|
726
|
+
by_table.setdefault(rule.column.table, []).append(rule)
|
|
727
|
+
cluster = Cluster(self.tools, directory / _DATADIR, directory)
|
|
728
|
+
last = [name for name in info.databases if name != info.default] + [info.default]
|
|
729
|
+
with cluster.running():
|
|
730
|
+
for database in last:
|
|
731
|
+
with cluster.connect(database) as connection, connection.transaction():
|
|
732
|
+
connection.execute("SET LOCAL session_replication_role = replica")
|
|
733
|
+
for position, (table, rules) in enumerate(by_table.items()):
|
|
734
|
+
if database_of(table) == database:
|
|
735
|
+
self._anonymize(
|
|
736
|
+
connection, (position, table), rules, transformation, partitioned
|
|
737
|
+
)
|
|
738
|
+
if database == info.default:
|
|
739
|
+
for hook in transformation.hooks:
|
|
740
|
+
_execute(connection, "an after_transform hook", trusted(hook.sql))
|
|
741
|
+
restored = PostgresRestored(cluster.connect, info.default, partitioned)
|
|
742
|
+
try:
|
|
743
|
+
counts = restored.counts(group.packaged())
|
|
744
|
+
finally:
|
|
745
|
+
restored.close()
|
|
746
|
+
return tuple(TableCount(table=t, rows=n) for t, n in counts.items())
|
|
747
|
+
|
|
748
|
+
def _anonymize(
|
|
749
|
+
self,
|
|
750
|
+
connection: Connection,
|
|
751
|
+
numbered: tuple[int, TableName],
|
|
752
|
+
rules: list[PlannedRule],
|
|
753
|
+
transformation: Transformation,
|
|
754
|
+
partitioned: frozenset[TableName],
|
|
755
|
+
) -> None:
|
|
756
|
+
"""Apply every rule for one table in a single UPDATE."""
|
|
757
|
+
position, table = numbered
|
|
758
|
+
assignments: list[sql.Composable] = []
|
|
759
|
+
for number, rule in enumerate(rules):
|
|
760
|
+
column = sql.Identifier(rule.column.column)
|
|
761
|
+
match rule.rule:
|
|
762
|
+
case NullRule():
|
|
763
|
+
assignments.append(sql.SQL("{} = NULL").format(column))
|
|
764
|
+
case ExpressionRule(expression=expression, where=where):
|
|
765
|
+
value = sql.SQL("({})").format(trusted(expression))
|
|
766
|
+
if where:
|
|
767
|
+
value = sql.SQL("CASE WHEN ({}) THEN {} ELSE {} END").format(
|
|
768
|
+
trusted(where), value, column
|
|
769
|
+
)
|
|
770
|
+
assignments.append(sql.SQL("{} = {}").format(column, value))
|
|
771
|
+
case _:
|
|
772
|
+
name = sql.Identifier(f"dd_map_{position}_{number}")
|
|
773
|
+
self._replacements(connection, name, rule, transformation, partitioned)
|
|
774
|
+
assignments.append(
|
|
775
|
+
sql.SQL(
|
|
776
|
+
"{} = (SELECT m.new FROM {} m WHERE m.old = t.{}::text)::{}"
|
|
777
|
+
).format(column, name, column, trusted(rule.type))
|
|
778
|
+
)
|
|
779
|
+
update = sql.SQL("UPDATE {} AS t SET {}").format(
|
|
780
|
+
_table(table, partitioned), _commas(assignments)
|
|
781
|
+
)
|
|
782
|
+
_execute(connection, f"anonymizing {table}", update)
|
|
783
|
+
|
|
784
|
+
@staticmethod
|
|
785
|
+
def _replacements(
|
|
786
|
+
connection: Connection,
|
|
787
|
+
name: sql.Identifier,
|
|
788
|
+
rule: PlannedRule,
|
|
789
|
+
transformation: Transformation,
|
|
790
|
+
partitioned: frozenset[TableName],
|
|
791
|
+
) -> None:
|
|
792
|
+
"""Fill a temporary table mapping each original value to its replacement."""
|
|
793
|
+
column = sql.Identifier(rule.column.column)
|
|
794
|
+
distinct = sql.SQL("SELECT DISTINCT {}::text FROM {} WHERE {} IS NOT NULL").format(
|
|
795
|
+
column, _table(rule.column.table, partitioned), column
|
|
796
|
+
)
|
|
797
|
+
try:
|
|
798
|
+
values = [str(row[0]) for row in connection.execute(distinct)]
|
|
799
|
+
except psycopg.Error as error:
|
|
800
|
+
raise database_error(error, f"reading {rule.column}") from None
|
|
801
|
+
mapping = transformation.mapper(rule, values)
|
|
802
|
+
create = sql.SQL(
|
|
803
|
+
"CREATE TEMPORARY TABLE {} (old text PRIMARY KEY, new text) ON COMMIT DROP"
|
|
804
|
+
).format(name)
|
|
805
|
+
_execute(connection, "preparing replacements", create)
|
|
806
|
+
statement = sql.SQL("COPY {} (old, new) FROM STDIN").format(name)
|
|
807
|
+
with connection.cursor() as cursor, cursor.copy(statement) as copy:
|
|
808
|
+
for old, new in mapping.items():
|
|
809
|
+
copy.write_row((old, new))
|
|
810
|
+
|
|
811
|
+
# package and restore
|
|
812
|
+
|
|
813
|
+
def package(self, source: Path, image_format: ImageFormat, directory: Path) -> None:
|
|
814
|
+
"""Write one format of the image into ``directory``."""
|
|
815
|
+
info = DatabaseInfo.model_validate_json((source / _INFO).read_bytes())
|
|
816
|
+
shutil.copyfile(source / _INFO, directory / _INFO)
|
|
817
|
+
if image_format is ImageFormat.PHYSICAL:
|
|
818
|
+
_copy_tree(source / _DATADIR, directory / _DATADIR)
|
|
819
|
+
return
|
|
820
|
+
cluster = Cluster(self.tools, source / _DATADIR, directory, [directory])
|
|
821
|
+
with cluster.running():
|
|
822
|
+
for position, database in enumerate(info.databases):
|
|
823
|
+
cluster.execute(
|
|
824
|
+
"pg_dump",
|
|
825
|
+
[
|
|
826
|
+
"--format=custom",
|
|
827
|
+
"--no-owner",
|
|
828
|
+
"--no-privileges",
|
|
829
|
+
f"--file={directory / dump_name(position)}",
|
|
830
|
+
f"--dbname={cluster.local_conninfo(database)}",
|
|
831
|
+
],
|
|
832
|
+
)
|
|
833
|
+
|
|
834
|
+
def add_accounts(self, image: Path, accounts: Sequence[Account]) -> None:
|
|
835
|
+
"""Give the physical image each account as a role that logs in with a password.
|
|
836
|
+
|
|
837
|
+
A cluster starts on the image's own data directory, so the roles are
|
|
838
|
+
written into it, and its ``pg_hba.conf``, which ``initdb`` wrote for
|
|
839
|
+
local connections only, gains a password rule for every address. An
|
|
840
|
+
``all`` account is a superuser. A ``read`` account gets ``CONNECT`` on
|
|
841
|
+
each database, and ``USAGE`` and ``SELECT`` on every table, view and
|
|
842
|
+
sequence of each schema but the system ones; a copy does not change, so
|
|
843
|
+
no default privileges are needed. Unlike ``pg_read_all_data`` this
|
|
844
|
+
leaves ``pg_authid`` and its password hashes out of reach. Passwords
|
|
845
|
+
reach the server only as SCRAM verifiers computed here, so no statement
|
|
846
|
+
the server could log holds one in plain text.
|
|
847
|
+
"""
|
|
848
|
+
datadir = image / _DATADIR
|
|
849
|
+
cluster = Cluster(self.tools, datadir, image)
|
|
850
|
+
with cluster.running():
|
|
851
|
+
with cluster.connect(SUPERUSER) as connection:
|
|
852
|
+
for account in accounts:
|
|
853
|
+
_create_role(connection, account)
|
|
854
|
+
_check_role(connection, account)
|
|
855
|
+
databases = [
|
|
856
|
+
str(name)
|
|
857
|
+
for (name,) in connection.execute(
|
|
858
|
+
"SELECT datname FROM pg_database"
|
|
859
|
+
" WHERE datallowconn AND NOT datistemplate ORDER BY datname"
|
|
860
|
+
).fetchall()
|
|
861
|
+
]
|
|
862
|
+
readers = [a.user for a in accounts if a.privileges is AccountPrivileges.READ]
|
|
863
|
+
if readers:
|
|
864
|
+
for database in databases:
|
|
865
|
+
with cluster.connect(database) as connection:
|
|
866
|
+
_grant_reading(connection, database, readers)
|
|
867
|
+
endpoint = cluster.server.endpoint
|
|
868
|
+
for account in accounts:
|
|
869
|
+
conninfo = make_conninfo(
|
|
870
|
+
host=endpoint.host,
|
|
871
|
+
port=str(endpoint.port),
|
|
872
|
+
dbname=SUPERUSER,
|
|
873
|
+
user=account.user,
|
|
874
|
+
)
|
|
875
|
+
try:
|
|
876
|
+
psycopg.connect(conninfo, password=account.password, connect_timeout=30).close()
|
|
877
|
+
except psycopg.Error as error:
|
|
878
|
+
action = f"logging in with the image's account {account.user!r}"
|
|
879
|
+
raise database_error(error, action) from None
|
|
880
|
+
hba = datadir / "pg_hba.conf"
|
|
881
|
+
rule = "host all all all scram-sha-256"
|
|
882
|
+
if rule not in hba.read_text("utf-8").splitlines():
|
|
883
|
+
with hba.open("a", encoding="utf-8") as file:
|
|
884
|
+
file.write(f"# package.accounts: password logins from anywhere\n{rule}\n")
|
|
885
|
+
|
|
886
|
+
@contextmanager
|
|
887
|
+
def restore(
|
|
888
|
+
self, image: Path, image_format: ImageFormat, directory: Path
|
|
889
|
+
) -> Generator[RestoredImage]:
|
|
890
|
+
"""Bring an image up in a scratch cluster for checks."""
|
|
891
|
+
info = DatabaseInfo.model_validate_json((image / _INFO).read_bytes())
|
|
892
|
+
datadir = directory / _DATADIR
|
|
893
|
+
directory.mkdir(parents=True, exist_ok=True)
|
|
894
|
+
cluster = Cluster(self.tools, datadir, directory, [image])
|
|
895
|
+
if image_format is ImageFormat.PHYSICAL:
|
|
896
|
+
_copy_tree(image / _DATADIR, datadir)
|
|
897
|
+
datadir.chmod(0o700)
|
|
898
|
+
else:
|
|
899
|
+
cluster.initialize()
|
|
900
|
+
with cluster.running(), ExitStack() as stack:
|
|
901
|
+
if image_format is ImageFormat.LOGICAL:
|
|
902
|
+
for position, database in enumerate(info.databases):
|
|
903
|
+
cluster.create_database(database)
|
|
904
|
+
cluster.execute(
|
|
905
|
+
"pg_restore",
|
|
906
|
+
[
|
|
907
|
+
"--no-owner",
|
|
908
|
+
"--no-privileges",
|
|
909
|
+
"--exit-on-error",
|
|
910
|
+
f"--dbname={cluster.local_conninfo(database)}",
|
|
911
|
+
str(image / dump_name(position)),
|
|
912
|
+
],
|
|
913
|
+
)
|
|
914
|
+
restored = PostgresRestored(cluster.connect, info.default, frozenset(info.partitioned))
|
|
915
|
+
stack.callback(restored.close)
|
|
916
|
+
yield restored
|
|
917
|
+
|
|
918
|
+
|
|
919
|
+
def _copy_tree(source: Path, destination: Path) -> None:
|
|
920
|
+
"""Copy a directory, sharing blocks where the filesystem allows."""
|
|
921
|
+
problem = copy_tree(source, destination)
|
|
922
|
+
if problem:
|
|
923
|
+
message = f"cannot copy {source.name}: {problem}"
|
|
924
|
+
raise EngineError(message)
|
|
925
|
+
|
|
926
|
+
|
|
927
|
+
_SCRAM = "SCRAM-SHA-256$"
|
|
928
|
+
|
|
929
|
+
|
|
930
|
+
def _create_role(connection: Connection, account: Account) -> None:
|
|
931
|
+
"""Create the account's role or reset it, with a SCRAM verifier for its password."""
|
|
932
|
+
action = f"giving the image the account {account.user!r}"
|
|
933
|
+
exists = connection.execute(
|
|
934
|
+
"SELECT 1 FROM pg_roles WHERE rolname = %s", (account.user,)
|
|
935
|
+
).fetchone()
|
|
936
|
+
verifier = connection.pgconn.encrypt_password(
|
|
937
|
+
account.password.encode(), account.user.encode(), b"scram-sha-256"
|
|
938
|
+
).decode()
|
|
939
|
+
read = account.privileges is AccountPrivileges.READ
|
|
940
|
+
attributes = (
|
|
941
|
+
"LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS"
|
|
942
|
+
if read
|
|
943
|
+
else "LOGIN SUPERUSER"
|
|
944
|
+
)
|
|
945
|
+
role = sql.Identifier(account.user)
|
|
946
|
+
_execute(
|
|
947
|
+
connection,
|
|
948
|
+
action,
|
|
949
|
+
sql.SQL("{} ROLE {} WITH {} PASSWORD {}").format(
|
|
950
|
+
sql.SQL("CREATE" if exists is None else "ALTER"),
|
|
951
|
+
role,
|
|
952
|
+
sql.SQL(attributes),
|
|
953
|
+
sql.Literal(verifier),
|
|
954
|
+
),
|
|
955
|
+
)
|
|
956
|
+
|
|
957
|
+
|
|
958
|
+
def _check_role(connection: Connection, account: Account) -> None:
|
|
959
|
+
"""Fail unless the catalog shows the role as declared, with a SCRAM password.
|
|
960
|
+
|
|
961
|
+
The login over the network alone does not prove this: the working
|
|
962
|
+
cluster trusts the loopback address, which is where a port-forward arrives.
|
|
963
|
+
"""
|
|
964
|
+
read = account.privileges is AccountPrivileges.READ
|
|
965
|
+
row = connection.execute(
|
|
966
|
+
sql.SQL(
|
|
967
|
+
"SELECT rolcanlogin, rolsuper, left(rolpassword, {}) = {}"
|
|
968
|
+
" FROM pg_authid WHERE rolname = %s"
|
|
969
|
+
).format(sql.Literal(len(_SCRAM)), sql.Literal(_SCRAM)),
|
|
970
|
+
(account.user,),
|
|
971
|
+
).fetchone()
|
|
972
|
+
if row != (True, not read, True):
|
|
973
|
+
message = (
|
|
974
|
+
f"checking the image's account {account.user!r} failed: the role does not log in"
|
|
975
|
+
f" with a SCRAM password and {account.privileges} privileges"
|
|
976
|
+
)
|
|
977
|
+
raise EngineError(message)
|
|
978
|
+
|
|
979
|
+
|
|
980
|
+
def _grant_reading(connection: Connection, database: str, users: Sequence[str]) -> None:
|
|
981
|
+
"""Let ``users`` connect to ``database`` and read everything in its own schemas."""
|
|
982
|
+
action = "granting read access"
|
|
983
|
+
roles = sql.SQL(", ").join(sql.Identifier(user) for user in users)
|
|
984
|
+
_execute(
|
|
985
|
+
connection,
|
|
986
|
+
action,
|
|
987
|
+
sql.SQL("GRANT CONNECT ON DATABASE {} TO {}").format(sql.Identifier(database), roles),
|
|
988
|
+
)
|
|
989
|
+
schemas = [
|
|
990
|
+
str(name)
|
|
991
|
+
for (name,) in connection.execute(
|
|
992
|
+
"SELECT nspname FROM pg_namespace WHERE left(nspname, 3) <> 'pg_'"
|
|
993
|
+
" AND nspname <> 'information_schema' ORDER BY nspname"
|
|
994
|
+
).fetchall()
|
|
995
|
+
]
|
|
996
|
+
for schema in schemas:
|
|
997
|
+
name = sql.Identifier(schema)
|
|
998
|
+
for statement in (
|
|
999
|
+
"GRANT USAGE ON SCHEMA {} TO {}",
|
|
1000
|
+
"GRANT SELECT ON ALL TABLES IN SCHEMA {} TO {}",
|
|
1001
|
+
"GRANT SELECT ON ALL SEQUENCES IN SCHEMA {} TO {}",
|
|
1002
|
+
):
|
|
1003
|
+
_execute(connection, action, sql.SQL(statement).format(name, roles))
|