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,212 @@
|
|
|
1
|
+
# Copyright (c) 2026- Tight Line LLC
|
|
2
|
+
# SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
"""Turning the core's subset conditions into PostgreSQL queries.
|
|
5
|
+
|
|
6
|
+
Seeds and ``when`` clauses are SQL from the spec, inserted as written, with
|
|
7
|
+
``:as_of`` bound to the plan's anchor time. Strategy B's value sets become
|
|
8
|
+
typed array parameters. Strategy A's references to other tables' selections
|
|
9
|
+
become materialized common table expressions, one per referenced table.
|
|
10
|
+
Every query runs in the database its tables are in, so tables are named by
|
|
11
|
+
schema and table alone.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
import datetime as dt
|
|
15
|
+
import re
|
|
16
|
+
from collections.abc import Mapping, Sequence
|
|
17
|
+
from dataclasses import dataclass, field
|
|
18
|
+
from typing import assert_never
|
|
19
|
+
|
|
20
|
+
from psycopg import sql
|
|
21
|
+
|
|
22
|
+
from datadouble.catalog import Catalog
|
|
23
|
+
from datadouble.engine import EngineError
|
|
24
|
+
from datadouble.names import ColumnName, TableName
|
|
25
|
+
from datadouble.subset import (
|
|
26
|
+
AllOf,
|
|
27
|
+
AllRows,
|
|
28
|
+
AnyNull,
|
|
29
|
+
AnyOf,
|
|
30
|
+
Condition,
|
|
31
|
+
NoRows,
|
|
32
|
+
Predicate,
|
|
33
|
+
SelectedBy,
|
|
34
|
+
ValuesIn,
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
_AS_OF = re.compile(r"(?<![:\w]):as_of\b")
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
type Statement = sql.SQL | sql.Composed
|
|
41
|
+
"""Something psycopg can execute."""
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def trusted(text: str) -> sql.SQL:
|
|
45
|
+
"""SQL from the spec or the catalog, inserted as written.
|
|
46
|
+
|
|
47
|
+
Seeds, ``when`` clauses, expressions, hooks and assertions are written by
|
|
48
|
+
the operator who owns the spec, and type names come from the source's own
|
|
49
|
+
catalog; neither carries data from the source's rows.
|
|
50
|
+
"""
|
|
51
|
+
return sql.SQL(text) # pyright: ignore[reportArgumentType] - operator-written spec SQL, not row data
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def native(text: str) -> sql.SQL:
|
|
55
|
+
"""Spec SQL with ``%`` escaped and ``:as_of`` turned into a bound parameter."""
|
|
56
|
+
return trusted(_AS_OF.sub("%(as_of)s", text.replace("%", "%%")))
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def database_of(table: TableName) -> str:
|
|
60
|
+
"""The database a table is in: its name's first part."""
|
|
61
|
+
return table.namespace[0]
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def unqualified(table: TableName) -> sql.Identifier:
|
|
65
|
+
"""``schema.table``, as a query inside the table's own database names it."""
|
|
66
|
+
return sql.Identifier(*table.parts[1:])
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def columns(names: Sequence[ColumnName]) -> sql.Composed:
|
|
70
|
+
"""A comma-separated list of quoted column names."""
|
|
71
|
+
return sql.SQL(", ").join(sql.Identifier(name) for name in names)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _tuple(names: Sequence[ColumnName]) -> sql.Composable:
|
|
75
|
+
joined = columns(names)
|
|
76
|
+
return joined if len(names) == 1 else sql.SQL("({})").format(joined)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
@dataclass
|
|
80
|
+
class Query:
|
|
81
|
+
"""A rendered statement and its parameters."""
|
|
82
|
+
|
|
83
|
+
text: Statement
|
|
84
|
+
params: dict[str, object]
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
@dataclass
|
|
88
|
+
class Renderer:
|
|
89
|
+
"""Renders conditions against one catalog."""
|
|
90
|
+
|
|
91
|
+
catalog: Catalog
|
|
92
|
+
partitioned: frozenset[TableName]
|
|
93
|
+
as_of: dt.datetime
|
|
94
|
+
selections: Mapping[TableName, Condition] = field(default_factory=dict[TableName, Condition])
|
|
95
|
+
params: dict[str, object] = field(default_factory=dict[str, object])
|
|
96
|
+
_ctes: dict[TableName, sql.Identifier] = field(default_factory=dict[TableName, sql.Identifier])
|
|
97
|
+
_cte_bodies: list[sql.Composable] = field(default_factory=list[sql.Composable])
|
|
98
|
+
|
|
99
|
+
def table(self, name: TableName) -> sql.Composable:
|
|
100
|
+
"""A table reference; ``ONLY`` keeps inheritance children out of plain tables."""
|
|
101
|
+
qualified = unqualified(name)
|
|
102
|
+
if name in self.partitioned:
|
|
103
|
+
return qualified
|
|
104
|
+
return sql.SQL("ONLY {}").format(qualified)
|
|
105
|
+
|
|
106
|
+
def _type(self, table: TableName, column: ColumnName) -> sql.Composable:
|
|
107
|
+
found = self.catalog.table(table)
|
|
108
|
+
spec = found.column(column) if found else None
|
|
109
|
+
if spec is None:
|
|
110
|
+
message = f"{table}.{column} is not in the catalog"
|
|
111
|
+
raise EngineError(message)
|
|
112
|
+
return trusted(spec.type)
|
|
113
|
+
|
|
114
|
+
def _param(self, value: object) -> sql.Composable:
|
|
115
|
+
name = f"p{len(self.params)}"
|
|
116
|
+
self.params[name] = value
|
|
117
|
+
return sql.Placeholder(name)
|
|
118
|
+
|
|
119
|
+
def _values(self, table: TableName, condition: ValuesIn) -> sql.Composable:
|
|
120
|
+
if not condition.values:
|
|
121
|
+
return sql.SQL("FALSE")
|
|
122
|
+
rows = list(condition.values)
|
|
123
|
+
arrays = [
|
|
124
|
+
sql.SQL("{}::{}[]").format(
|
|
125
|
+
self._param([row[i] for row in rows]), self._type(table, column)
|
|
126
|
+
)
|
|
127
|
+
for i, column in enumerate(condition.columns)
|
|
128
|
+
]
|
|
129
|
+
if len(arrays) == 1:
|
|
130
|
+
return sql.SQL("{} = ANY({})").format(sql.Identifier(condition.columns[0]), arrays[0])
|
|
131
|
+
return sql.SQL("{} IN (SELECT * FROM unnest({}))").format(
|
|
132
|
+
_tuple(condition.columns), sql.SQL(", ").join(arrays)
|
|
133
|
+
)
|
|
134
|
+
|
|
135
|
+
def _cte(self, source: TableName) -> sql.Identifier:
|
|
136
|
+
"""The CTE holding ``source``'s selection, defined after those it uses."""
|
|
137
|
+
if source not in self._ctes:
|
|
138
|
+
condition = self.selections.get(source)
|
|
139
|
+
if condition is None:
|
|
140
|
+
message = f"no selection for {source}"
|
|
141
|
+
raise EngineError(message)
|
|
142
|
+
body = self.condition(source, condition)
|
|
143
|
+
name = sql.Identifier(f"dd_selected_{len(self._ctes)}")
|
|
144
|
+
self._ctes[source] = name
|
|
145
|
+
self._cte_bodies.append(
|
|
146
|
+
sql.SQL("{} AS MATERIALIZED (SELECT * FROM {} WHERE {})").format(
|
|
147
|
+
name, self.table(source), body
|
|
148
|
+
)
|
|
149
|
+
)
|
|
150
|
+
return self._ctes[source]
|
|
151
|
+
|
|
152
|
+
def _selected_by(self, condition: SelectedBy) -> sql.Composable:
|
|
153
|
+
if condition.source_condition is None:
|
|
154
|
+
origin: sql.Composable = self._cte(condition.source)
|
|
155
|
+
filters: list[sql.Composable] = []
|
|
156
|
+
else:
|
|
157
|
+
origin = self.table(condition.source)
|
|
158
|
+
filters = [self.condition(condition.source, condition.source_condition)]
|
|
159
|
+
if condition.where:
|
|
160
|
+
filters.append(sql.SQL("({})").format(native(condition.where)))
|
|
161
|
+
where = (
|
|
162
|
+
sql.SQL(" WHERE {}").format(sql.SQL(" AND ").join(filters)) if filters else sql.SQL("")
|
|
163
|
+
)
|
|
164
|
+
return sql.SQL("{} IN (SELECT {} FROM {}{})").format(
|
|
165
|
+
_tuple(condition.columns), columns(condition.source_columns), origin, where
|
|
166
|
+
)
|
|
167
|
+
|
|
168
|
+
def condition(self, table: TableName, condition: Condition) -> sql.Composable:
|
|
169
|
+
"""A boolean expression over the columns of ``table``."""
|
|
170
|
+
match condition:
|
|
171
|
+
case AllRows() | NoRows():
|
|
172
|
+
return sql.SQL("TRUE" if isinstance(condition, AllRows) else "FALSE")
|
|
173
|
+
case Predicate(text):
|
|
174
|
+
self.params["as_of"] = self.as_of
|
|
175
|
+
return sql.SQL("({})").format(native(text))
|
|
176
|
+
case ValuesIn():
|
|
177
|
+
return self._values(table, condition)
|
|
178
|
+
case SelectedBy():
|
|
179
|
+
return self._selected_by(condition)
|
|
180
|
+
case AnyNull(names):
|
|
181
|
+
parts = [sql.SQL("{} IS NULL").format(sql.Identifier(n)) for n in names]
|
|
182
|
+
return sql.SQL("({})").format(sql.SQL(" OR ").join(parts))
|
|
183
|
+
case AnyOf(parts) | AllOf(parts):
|
|
184
|
+
joiner = " OR " if isinstance(condition, AnyOf) else " AND "
|
|
185
|
+
rendered = [self.condition(table, part) for part in parts]
|
|
186
|
+
return sql.SQL("({})").format(sql.SQL(joiner).join(rendered))
|
|
187
|
+
case _:
|
|
188
|
+
assert_never(condition)
|
|
189
|
+
|
|
190
|
+
def select(
|
|
191
|
+
self,
|
|
192
|
+
table: TableName,
|
|
193
|
+
names: Sequence[ColumnName],
|
|
194
|
+
condition: Condition,
|
|
195
|
+
*,
|
|
196
|
+
distinct: bool = False,
|
|
197
|
+
) -> Query:
|
|
198
|
+
"""``SELECT names FROM table WHERE condition``, with the CTEs it needs."""
|
|
199
|
+
where = self.condition(table, condition)
|
|
200
|
+
head = (
|
|
201
|
+
sql.SQL("WITH {} ").format(sql.SQL(", ").join(self._cte_bodies))
|
|
202
|
+
if self._cte_bodies
|
|
203
|
+
else sql.SQL("")
|
|
204
|
+
)
|
|
205
|
+
text = sql.SQL("{}SELECT {}{} FROM {} WHERE {}").format(
|
|
206
|
+
head,
|
|
207
|
+
sql.SQL("DISTINCT ") if distinct else sql.SQL(""),
|
|
208
|
+
columns(names),
|
|
209
|
+
self.table(table),
|
|
210
|
+
where,
|
|
211
|
+
)
|
|
212
|
+
return Query(text=text, params=dict(self.params))
|
|
@@ -0,0 +1,380 @@
|
|
|
1
|
+
# Copyright (c) 2026- Tight Line LLC
|
|
2
|
+
# SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
"""The source side: catalog introspection and consistent snapshots.
|
|
5
|
+
|
|
6
|
+
The source is one or more databases on one server; every table is named
|
|
7
|
+
``database.schema.table``. In each database a coordinator connection opens a
|
|
8
|
+
repeatable-read, read-only transaction and exports its snapshot. Key reads
|
|
9
|
+
(strategy B) and every table's rows are read in their database's transaction,
|
|
10
|
+
and ``pg_dump --snapshot`` writes each database's schema from the same point
|
|
11
|
+
in time. PostgreSQL cannot share a snapshot between databases, so the
|
|
12
|
+
transactions are opened one after another, together; no query reads across
|
|
13
|
+
databases, so each stays consistent on its own. Nothing is written to the
|
|
14
|
+
source.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
import datetime as dt
|
|
18
|
+
import time
|
|
19
|
+
from collections.abc import Generator, Iterable, Mapping
|
|
20
|
+
from contextlib import ExitStack, contextmanager
|
|
21
|
+
from pathlib import Path
|
|
22
|
+
|
|
23
|
+
import psycopg
|
|
24
|
+
from psycopg import sql
|
|
25
|
+
from psycopg.conninfo import make_conninfo
|
|
26
|
+
from pydantic import BaseModel, ConfigDict
|
|
27
|
+
|
|
28
|
+
from datadouble.catalog import Catalog, Requirement, SourceObject, Table
|
|
29
|
+
from datadouble.engine import EngineError, ExtractResult, Snapshot, TableCount, Tooling
|
|
30
|
+
from datadouble.names import ColumnName, TableName
|
|
31
|
+
from datadouble.planner import Plan
|
|
32
|
+
from datadouble.subset import Condition, KeyTuple
|
|
33
|
+
from datadouble_postgres.cluster import Tools, default_image
|
|
34
|
+
from datadouble_postgres.errors import database_error
|
|
35
|
+
from datadouble_postgres.introspect import ENGINE, Extension, Physical, introspect
|
|
36
|
+
from datadouble_postgres.render import Renderer, Statement, database_of, unqualified
|
|
37
|
+
|
|
38
|
+
type Connection = psycopg.Connection[tuple[object, ...]]
|
|
39
|
+
|
|
40
|
+
_DEPENDENT_VIEWS = """
|
|
41
|
+
WITH RECURSIVE dependent(oid) AS (
|
|
42
|
+
SELECT DISTINCT r.ev_class
|
|
43
|
+
FROM pg_catalog.pg_rewrite r
|
|
44
|
+
JOIN pg_catalog.pg_depend d ON d.classid = 'pg_catalog.pg_rewrite'::regclass AND d.objid = r.oid
|
|
45
|
+
WHERE d.refobjid = ANY(%s::regclass[]) AND r.ev_class <> d.refobjid
|
|
46
|
+
UNION
|
|
47
|
+
SELECT r.ev_class
|
|
48
|
+
FROM dependent v
|
|
49
|
+
JOIN pg_catalog.pg_depend d ON d.refobjid = v.oid
|
|
50
|
+
JOIN pg_catalog.pg_rewrite r
|
|
51
|
+
ON d.classid = 'pg_catalog.pg_rewrite'::regclass AND d.objid = r.oid
|
|
52
|
+
WHERE r.ev_class <> v.oid
|
|
53
|
+
)
|
|
54
|
+
SELECT n.nspname, c.relname
|
|
55
|
+
FROM dependent JOIN pg_catalog.pg_class c ON c.oid = dependent.oid
|
|
56
|
+
JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
|
|
57
|
+
ORDER BY 1, 2
|
|
58
|
+
"""
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
_FOREIGN_KEYS = """
|
|
62
|
+
SELECT n.nspname, c.relname, con.conname,
|
|
63
|
+
rn.nspname, rc.relname, tn.nspname, tc.relname
|
|
64
|
+
FROM pg_catalog.pg_constraint con
|
|
65
|
+
JOIN pg_catalog.pg_class c ON c.oid = con.conrelid
|
|
66
|
+
JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
|
|
67
|
+
JOIN pg_catalog.pg_class rc
|
|
68
|
+
ON rc.oid = coalesce(pg_catalog.pg_partition_root(con.conrelid), con.conrelid)
|
|
69
|
+
JOIN pg_catalog.pg_namespace rn ON rn.oid = rc.relnamespace
|
|
70
|
+
JOIN pg_catalog.pg_class tc
|
|
71
|
+
ON tc.oid = coalesce(pg_catalog.pg_partition_root(con.confrelid), con.confrelid)
|
|
72
|
+
JOIN pg_catalog.pg_namespace tn ON tn.oid = tc.relnamespace
|
|
73
|
+
WHERE con.contype = 'f'
|
|
74
|
+
ORDER BY 1, 2, 3
|
|
75
|
+
"""
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
class Constraint(BaseModel):
|
|
79
|
+
"""A foreign-key constraint as ``pg_dump`` writes it, on a table or a partition."""
|
|
80
|
+
|
|
81
|
+
model_config = ConfigDict(strict=True, frozen=True, extra="forbid")
|
|
82
|
+
|
|
83
|
+
namespace: str
|
|
84
|
+
"""The schema of the table it is declared on."""
|
|
85
|
+
table: str
|
|
86
|
+
name: str
|
|
87
|
+
child: TableName
|
|
88
|
+
"""The table it belongs to, or that table's partitioned root."""
|
|
89
|
+
parent: TableName
|
|
90
|
+
"""The table it refers to, or that table's partitioned root."""
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
class ExtractedTable(BaseModel):
|
|
94
|
+
"""One table's data file in an extract."""
|
|
95
|
+
|
|
96
|
+
model_config = ConfigDict(strict=True, frozen=True, extra="forbid")
|
|
97
|
+
|
|
98
|
+
table: TableName
|
|
99
|
+
file: str
|
|
100
|
+
columns: tuple[ColumnName, ...]
|
|
101
|
+
rows: int
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
class ExtractedDatabase(BaseModel):
|
|
105
|
+
"""One database's schema in an extract."""
|
|
106
|
+
|
|
107
|
+
model_config = ConfigDict(strict=True, frozen=True, extra="forbid")
|
|
108
|
+
|
|
109
|
+
name: str
|
|
110
|
+
schema_file: str
|
|
111
|
+
"""Its ``pg_dump`` archive, schema only."""
|
|
112
|
+
omitted_views: tuple[TableName, ...]
|
|
113
|
+
"""Views that depend on excluded tables, left out of every working database."""
|
|
114
|
+
constraints: tuple[Constraint, ...]
|
|
115
|
+
"""Every foreign-key constraint, including those declared only on partitions."""
|
|
116
|
+
extensions: tuple[Extension, ...] = ()
|
|
117
|
+
"""Installed extensions, which ``load`` creates at the source's versions."""
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
class ExtractIndex(BaseModel):
|
|
121
|
+
"""What an extract directory holds, for ``load``."""
|
|
122
|
+
|
|
123
|
+
model_config = ConfigDict(strict=True, frozen=True, extra="forbid")
|
|
124
|
+
|
|
125
|
+
databases: tuple[ExtractedDatabase, ...]
|
|
126
|
+
default: str
|
|
127
|
+
"""The database spec SQL without a table runs in."""
|
|
128
|
+
tables: tuple[ExtractedTable, ...]
|
|
129
|
+
partitioned: tuple[TableName, ...]
|
|
130
|
+
"""Partitioned tables, read without ``ONLY``."""
|
|
131
|
+
|
|
132
|
+
def table(self, name: TableName) -> ExtractedTable | None:
|
|
133
|
+
"""The extracted table called ``name``."""
|
|
134
|
+
return next((t for t in self.tables if t.table == name), None)
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def copied_columns(
|
|
138
|
+
catalog: Catalog, physical: Physical, table: TableName
|
|
139
|
+
) -> tuple[ColumnName, ...]:
|
|
140
|
+
"""The columns COPY reads and writes: all but generated ones."""
|
|
141
|
+
found = catalog.table(table)
|
|
142
|
+
generated = physical.generated.get(table, frozenset())
|
|
143
|
+
return tuple(c.name for c in found.columns if c.name not in generated) if found else ()
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
class PostgresSnapshot:
|
|
147
|
+
"""Each database's coordinator transaction and its exported snapshot."""
|
|
148
|
+
|
|
149
|
+
def __init__(
|
|
150
|
+
self, snapshots: dict[str, str], session: "PostgresSession", as_of: dt.datetime
|
|
151
|
+
) -> None:
|
|
152
|
+
"""Wrap the open coordinator transactions, one per database."""
|
|
153
|
+
self.snapshots = snapshots
|
|
154
|
+
self.session = session
|
|
155
|
+
self.as_of = as_of
|
|
156
|
+
self.opened = time.monotonic()
|
|
157
|
+
self.catalog, self.physical = session.introspect()
|
|
158
|
+
|
|
159
|
+
def project(
|
|
160
|
+
self, table: TableName, condition: Condition, columns: tuple[ColumnName, ...]
|
|
161
|
+
) -> Iterable[KeyTuple]:
|
|
162
|
+
"""Distinct values of ``columns`` for the chosen rows."""
|
|
163
|
+
query = Renderer(self.catalog, self.physical.partitioned, self.as_of).select(
|
|
164
|
+
table, columns, condition, distinct=True
|
|
165
|
+
)
|
|
166
|
+
try:
|
|
167
|
+
with self.session.connections[database_of(table)].cursor() as cursor:
|
|
168
|
+
cursor.execute(query.text, query.params)
|
|
169
|
+
return [tuple(row) for row in cursor.fetchall()]
|
|
170
|
+
except psycopg.Error as error:
|
|
171
|
+
raise database_error(error, f"reading keys of {table}") from None
|
|
172
|
+
|
|
173
|
+
def extract(
|
|
174
|
+
self,
|
|
175
|
+
plan: Plan,
|
|
176
|
+
selections: Mapping[TableName, Condition],
|
|
177
|
+
directory: Path,
|
|
178
|
+
tooling: Tooling,
|
|
179
|
+
) -> ExtractResult:
|
|
180
|
+
"""Write each database's schema and every extracted table's chosen rows."""
|
|
181
|
+
directory.mkdir(parents=True, exist_ok=True)
|
|
182
|
+
catalog, physical = self.catalog, self.physical
|
|
183
|
+
if catalog.fingerprint() != plan.catalog_fingerprint:
|
|
184
|
+
message = (
|
|
185
|
+
"the source schema changed between planning and the snapshot; "
|
|
186
|
+
"plan again (start a new generation)"
|
|
187
|
+
)
|
|
188
|
+
raise EngineError(message)
|
|
189
|
+
excluded = plan.excludes.excluded()
|
|
190
|
+
version = self.session.server_version()
|
|
191
|
+
tools = Tools(
|
|
192
|
+
tooling.runtime, tooling.image or default_image(version), directory.parent / "tools"
|
|
193
|
+
)
|
|
194
|
+
databases: list[ExtractedDatabase] = []
|
|
195
|
+
for position, (database, snapshot) in enumerate(self.snapshots.items()):
|
|
196
|
+
own = frozenset(t for t in excluded if database_of(t) == database)
|
|
197
|
+
schema_file = f"schema-{position:03d}.dump"
|
|
198
|
+
self.session.dump_schema(tools, database, snapshot, own, directory / schema_file)
|
|
199
|
+
connection = self.session.connections[database]
|
|
200
|
+
databases.append(
|
|
201
|
+
ExtractedDatabase(
|
|
202
|
+
name=database,
|
|
203
|
+
schema_file=schema_file,
|
|
204
|
+
omitted_views=_dependent_views(connection, database, own),
|
|
205
|
+
constraints=_constraints(connection, database),
|
|
206
|
+
extensions=physical.extensions.get(database, ()),
|
|
207
|
+
)
|
|
208
|
+
)
|
|
209
|
+
tables: list[ExtractedTable] = []
|
|
210
|
+
for index, table in enumerate(plan.extracted()):
|
|
211
|
+
names = copied_columns(catalog, physical, table)
|
|
212
|
+
renderer = Renderer(catalog, physical.partitioned, plan.as_of, selections)
|
|
213
|
+
query = renderer.select(table, names, selections[table])
|
|
214
|
+
file = f"{index:05d}.copy"
|
|
215
|
+
rows = self._copy_out(table, query.text, query.params, directory / file)
|
|
216
|
+
tables.append(ExtractedTable(table=table, file=file, columns=names, rows=rows))
|
|
217
|
+
index_file = ExtractIndex(
|
|
218
|
+
databases=tuple(databases),
|
|
219
|
+
default=self.session.default,
|
|
220
|
+
tables=tuple(tables),
|
|
221
|
+
partitioned=tuple(sorted(physical.partitioned)),
|
|
222
|
+
)
|
|
223
|
+
(directory / "index.json").write_text(index_file.model_dump_json(indent=2), "utf-8")
|
|
224
|
+
return ExtractResult(
|
|
225
|
+
server_version=version,
|
|
226
|
+
snapshot="",
|
|
227
|
+
snapshots=dict(self.snapshots),
|
|
228
|
+
snapshot_seconds=round(time.monotonic() - self.opened, 3),
|
|
229
|
+
counts=tuple(TableCount(table=t.table, rows=t.rows) for t in tables),
|
|
230
|
+
)
|
|
231
|
+
|
|
232
|
+
def _copy_out(
|
|
233
|
+
self, table: TableName, query: Statement, params: dict[str, object], path: Path
|
|
234
|
+
) -> int:
|
|
235
|
+
statement = sql.SQL("COPY ({}) TO STDOUT").format(query)
|
|
236
|
+
try:
|
|
237
|
+
connection = self.session.connections[database_of(table)]
|
|
238
|
+
with connection.cursor() as cursor, path.open("wb") as out:
|
|
239
|
+
with cursor.copy(statement, params) as copy:
|
|
240
|
+
for chunk in copy:
|
|
241
|
+
out.write(chunk)
|
|
242
|
+
return cursor.rowcount
|
|
243
|
+
except psycopg.Error as error:
|
|
244
|
+
raise database_error(error, f"extracting {table}") from None
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def _constraints(connection: Connection, database: str) -> tuple[Constraint, ...]:
|
|
248
|
+
with connection.cursor() as cursor:
|
|
249
|
+
cursor.execute(_FOREIGN_KEYS)
|
|
250
|
+
return tuple(
|
|
251
|
+
Constraint(
|
|
252
|
+
namespace=str(row[0]),
|
|
253
|
+
table=str(row[1]),
|
|
254
|
+
name=str(row[2]),
|
|
255
|
+
child=TableName.of(database, str(row[3]), str(row[4])),
|
|
256
|
+
parent=TableName.of(database, str(row[5]), str(row[6])),
|
|
257
|
+
)
|
|
258
|
+
for row in cursor.fetchall()
|
|
259
|
+
)
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def _dependent_views(
|
|
263
|
+
connection: Connection, database: str, excluded: frozenset[TableName]
|
|
264
|
+
) -> tuple[TableName, ...]:
|
|
265
|
+
if not excluded:
|
|
266
|
+
return ()
|
|
267
|
+
names = [unqualified(t).as_string(connection) for t in sorted(excluded)]
|
|
268
|
+
with connection.cursor() as cursor:
|
|
269
|
+
cursor.execute(_DEPENDENT_VIEWS, [names])
|
|
270
|
+
return tuple(TableName.of(database, str(nsp), str(rel)) for nsp, rel in cursor.fetchall())
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def _pattern(table: TableName) -> str:
|
|
274
|
+
"""An exact ``pg_dump`` table pattern: schema and table double-quoted, quotes doubled."""
|
|
275
|
+
return ".".join('"' + part.replace('"', '""') + '"' for part in table.parts[1:])
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
class PostgresSession:
|
|
279
|
+
"""Open connections to each database the source reads, on one server."""
|
|
280
|
+
|
|
281
|
+
def __init__(
|
|
282
|
+
self,
|
|
283
|
+
connections: dict[str, Connection],
|
|
284
|
+
conninfo: str,
|
|
285
|
+
password: str | None,
|
|
286
|
+
default: str,
|
|
287
|
+
) -> None:
|
|
288
|
+
"""Wrap a connection per database; ``conninfo`` and ``password`` are for ``pg_dump``.
|
|
289
|
+
|
|
290
|
+
``default`` is the database spec SQL without a table runs in: the
|
|
291
|
+
connection string's, when it is read, or else the first read.
|
|
292
|
+
"""
|
|
293
|
+
self.connections = connections
|
|
294
|
+
self.conninfo = conninfo
|
|
295
|
+
self.password = password
|
|
296
|
+
self.default = default
|
|
297
|
+
|
|
298
|
+
@property
|
|
299
|
+
def connection(self) -> Connection:
|
|
300
|
+
"""The default database's connection."""
|
|
301
|
+
return self.connections[self.default]
|
|
302
|
+
|
|
303
|
+
def server_version(self) -> str:
|
|
304
|
+
"""The source's version, such as ``18.1``."""
|
|
305
|
+
version = str(self.connection.info.parameter_status("server_version") or "")
|
|
306
|
+
return version.split(" ", maxsplit=1)[0]
|
|
307
|
+
|
|
308
|
+
def introspect(self) -> tuple[Catalog, Physical]:
|
|
309
|
+
"""Every database's catalog, merged; requirements are listed once each.
|
|
310
|
+
|
|
311
|
+
Each database's objects are read under its own connection, so under
|
|
312
|
+
its own snapshot, and have edges only within it.
|
|
313
|
+
"""
|
|
314
|
+
tables: list[Table] = []
|
|
315
|
+
objects: list[SourceObject] = []
|
|
316
|
+
requirements: dict[Requirement, None] = {}
|
|
317
|
+
physical = Physical(frozenset(), {}, {})
|
|
318
|
+
for database, connection in self.connections.items():
|
|
319
|
+
catalog, found = introspect(connection, database)
|
|
320
|
+
tables.extend(catalog.tables)
|
|
321
|
+
objects.extend(catalog.objects)
|
|
322
|
+
requirements.update(dict.fromkeys(catalog.requirements))
|
|
323
|
+
physical = physical.merged(found)
|
|
324
|
+
merged = Catalog(
|
|
325
|
+
engine=ENGINE,
|
|
326
|
+
tables=tuple(tables),
|
|
327
|
+
requirements=tuple(requirements),
|
|
328
|
+
objects=tuple(objects),
|
|
329
|
+
)
|
|
330
|
+
return merged, physical
|
|
331
|
+
|
|
332
|
+
def namespaces(self) -> tuple[str, ...]:
|
|
333
|
+
"""Every database read, tables or not."""
|
|
334
|
+
return tuple(self.connections)
|
|
335
|
+
|
|
336
|
+
def catalog(self) -> Catalog:
|
|
337
|
+
"""Introspect the source."""
|
|
338
|
+
try:
|
|
339
|
+
return self.introspect()[0]
|
|
340
|
+
except psycopg.Error as error:
|
|
341
|
+
raise database_error(error, "reading the catalog") from None
|
|
342
|
+
|
|
343
|
+
def dump_schema(
|
|
344
|
+
self,
|
|
345
|
+
tools: Tools,
|
|
346
|
+
database: str,
|
|
347
|
+
snapshot: str,
|
|
348
|
+
excluded: frozenset[TableName],
|
|
349
|
+
path: Path,
|
|
350
|
+
) -> None:
|
|
351
|
+
"""``pg_dump --schema-only`` of one database from its exported snapshot, into ``path``.
|
|
352
|
+
|
|
353
|
+
The source must be reachable from the runtime's containers at the
|
|
354
|
+
address in its connection string.
|
|
355
|
+
"""
|
|
356
|
+
arguments = [
|
|
357
|
+
"--schema-only",
|
|
358
|
+
"--format=custom",
|
|
359
|
+
f"--snapshot={snapshot}",
|
|
360
|
+
f"--file={path}",
|
|
361
|
+
f"--dbname={make_conninfo(self.conninfo, dbname=database)}",
|
|
362
|
+
]
|
|
363
|
+
arguments.extend(f"--exclude-table={_pattern(t)}" for t in sorted(excluded))
|
|
364
|
+
secrets = {"PGPASSWORD": self.password} if self.password else {}
|
|
365
|
+
tools.run("pg_dump", arguments, path.parent.parent, [path.parent], secrets)
|
|
366
|
+
|
|
367
|
+
@contextmanager
|
|
368
|
+
def snapshot(self, as_of: dt.datetime) -> Generator[Snapshot]:
|
|
369
|
+
"""Open every database's coordinator transaction together and export its snapshot."""
|
|
370
|
+
try:
|
|
371
|
+
with ExitStack() as stack:
|
|
372
|
+
snapshots: dict[str, str] = {}
|
|
373
|
+
for database, connection in self.connections.items():
|
|
374
|
+
stack.enter_context(connection.transaction())
|
|
375
|
+
connection.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ, READ ONLY")
|
|
376
|
+
row = connection.execute("SELECT pg_catalog.pg_export_snapshot()").fetchone()
|
|
377
|
+
snapshots[database] = str(row[0]) if row else ""
|
|
378
|
+
yield PostgresSnapshot(snapshots, self, as_of)
|
|
379
|
+
except psycopg.Error as error:
|
|
380
|
+
raise database_error(error, "reading the snapshot") from None
|