seed-dev-db 0.1.0__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.
- seed/__init__.py +3 -0
- seed/cli.py +395 -0
- seed/config.py +251 -0
- seed/exporting/__init__.py +1 -0
- seed/exporting/files.py +165 -0
- seed/exporting/sql.py +84 -0
- seed/exporting/tabular.py +46 -0
- seed/generation/__init__.py +1 -0
- seed/generation/engine.py +260 -0
- seed/generation/record_checks.py +180 -0
- seed/generation/relationships.py +213 -0
- seed/generation/scalars.py +112 -0
- seed/generation/streaming.py +124 -0
- seed/metadata.py +126 -0
- seed/planning/__init__.py +1 -0
- seed/planning/bindings.py +138 -0
- seed/planning/dependencies.py +123 -0
- seed/planning/numeric.py +122 -0
- seed/planning/plan.py +305 -0
- seed/planning/selection.py +62 -0
- seed/postgres/__init__.py +1 -0
- seed/postgres/apply_guard.py +268 -0
- seed/postgres/catalog.py +386 -0
- seed/postgres/connection.py +160 -0
- seed/postgres/insertion.py +237 -0
- seed/postgres/inspection.py +76 -0
- seed/postgres/schema.py +234 -0
- seed/reporting/__init__.py +1 -0
- seed/reporting/dataset.py +72 -0
- seed/reporting/inspection.py +65 -0
- seed/reporting/plan.py +64 -0
- seed/workflows/__init__.py +1 -0
- seed/workflows/apply.py +95 -0
- seed/workflows/export.py +168 -0
- seed/workflows/initialize.py +53 -0
- seed/workflows/preview.py +101 -0
- seed/workflows/validate.py +94 -0
- seed_dev_db-0.1.0.dist-info/METADATA +29 -0
- seed_dev_db-0.1.0.dist-info/RECORD +42 -0
- seed_dev_db-0.1.0.dist-info/WHEEL +4 -0
- seed_dev_db-0.1.0.dist-info/entry_points.txt +2 -0
- seed_dev_db-0.1.0.dist-info/licenses/LICENSE +202 -0
seed/planning/plan.py
ADDED
|
@@ -0,0 +1,305 @@
|
|
|
1
|
+
"""Build a read-only generation plan from normalized schema metadata."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from datetime import datetime
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Literal
|
|
7
|
+
|
|
8
|
+
from sqlalchemy import URL
|
|
9
|
+
|
|
10
|
+
from seed.config import SeedConfig, load_config
|
|
11
|
+
from seed.metadata import DatabaseSchema, ForeignKey, Metadata, TableId, TableSchema, Target
|
|
12
|
+
from seed.planning.bindings import Binding, choose_binding
|
|
13
|
+
from seed.planning.dependencies import Dependency, KeySource, resolve_dependencies
|
|
14
|
+
from seed.planning.selection import MAX_ROWS, resolve_selection, validate_row_override
|
|
15
|
+
from seed.postgres.inspection import read_schema, requested_tables
|
|
16
|
+
|
|
17
|
+
type Mode = Literal["live", "offline"]
|
|
18
|
+
_MODES: tuple[Mode, ...] = ("live", "offline")
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class PlanIssue(Metadata):
|
|
22
|
+
code: str
|
|
23
|
+
message: str
|
|
24
|
+
severity: Literal["error", "warning"] = "error"
|
|
25
|
+
table: TableId | None = None
|
|
26
|
+
column: str | None = None
|
|
27
|
+
constraint: str | None = None
|
|
28
|
+
ordinal: int | None = None
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class Compatibility(Metadata):
|
|
32
|
+
executable: bool
|
|
33
|
+
issues: tuple[PlanIssue, ...]
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class PlanSettings(Metadata):
|
|
37
|
+
locale: str
|
|
38
|
+
random_seed: int
|
|
39
|
+
reference_time: datetime
|
|
40
|
+
batch_size: int
|
|
41
|
+
null_rate: float
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class PlannedDependency(Metadata):
|
|
45
|
+
foreign_key: ForeignKey
|
|
46
|
+
source: KeySource
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class PlannedTable(Metadata):
|
|
50
|
+
id: TableId
|
|
51
|
+
requested: bool
|
|
52
|
+
rows: int
|
|
53
|
+
parents: tuple[TableId, ...]
|
|
54
|
+
dependencies: tuple[PlannedDependency, ...]
|
|
55
|
+
key_source: KeySource
|
|
56
|
+
bindings: dict[Mode, tuple[Binding, ...]]
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class GenerationPlan(Metadata):
|
|
60
|
+
target: Target
|
|
61
|
+
schema_fingerprint: str
|
|
62
|
+
settings: PlanSettings
|
|
63
|
+
total_rows: int
|
|
64
|
+
tables: tuple[PlannedTable, ...]
|
|
65
|
+
compatibility: dict[Mode, Compatibility]
|
|
66
|
+
|
|
67
|
+
@property
|
|
68
|
+
def executable(self) -> bool:
|
|
69
|
+
"""Return whether at least one execution mode has a feasible plan."""
|
|
70
|
+
return any(mode.executable for mode in self.compatibility.values())
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
@dataclass(frozen=True)
|
|
74
|
+
class PlanRequest:
|
|
75
|
+
path: Path
|
|
76
|
+
schema: str | None
|
|
77
|
+
filters: list[str]
|
|
78
|
+
rows: int | None
|
|
79
|
+
locale: str | None
|
|
80
|
+
random_seed: int | None
|
|
81
|
+
|
|
82
|
+
def load(self) -> SeedConfig:
|
|
83
|
+
"""Validate invocation overrides and load the effective configuration."""
|
|
84
|
+
validate_row_override(self.filters, self.rows)
|
|
85
|
+
return load_config(
|
|
86
|
+
self.path,
|
|
87
|
+
schema=self.schema,
|
|
88
|
+
locale=self.locale,
|
|
89
|
+
random_seed=self.random_seed,
|
|
90
|
+
)
|
|
91
|
+
|
|
92
|
+
def snapshot(
|
|
93
|
+
self,
|
|
94
|
+
config: SeedConfig,
|
|
95
|
+
*,
|
|
96
|
+
url: URL | None = None,
|
|
97
|
+
) -> tuple[DatabaseSchema, GenerationPlan]:
|
|
98
|
+
"""Read one schema snapshot and build its plan."""
|
|
99
|
+
name = config.database.schema_name
|
|
100
|
+
requested_tables(name, self.filters)
|
|
101
|
+
metadata = read_schema(config, name, url=url)
|
|
102
|
+
return metadata, build_plan(config, metadata, self.filters, self.rows)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def plan_database(
|
|
106
|
+
path: Path,
|
|
107
|
+
*,
|
|
108
|
+
schema: str | None,
|
|
109
|
+
filters: list[str],
|
|
110
|
+
rows: int | None,
|
|
111
|
+
locale: str | None,
|
|
112
|
+
random_seed: int | None,
|
|
113
|
+
) -> GenerationPlan:
|
|
114
|
+
"""Read a schema snapshot and build a plan without reading table data."""
|
|
115
|
+
request = PlanRequest(path, schema, filters, rows, locale, random_seed)
|
|
116
|
+
return request.snapshot(request.load())[1]
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def build_plan(
|
|
120
|
+
config: SeedConfig,
|
|
121
|
+
schema: DatabaseSchema,
|
|
122
|
+
filters: list[str],
|
|
123
|
+
rows: int | None = None,
|
|
124
|
+
) -> GenerationPlan:
|
|
125
|
+
"""Resolve plan compatibility and bindings for live and offline execution."""
|
|
126
|
+
selection = resolve_selection(config, schema, filters, rows)
|
|
127
|
+
graph = resolve_dependencies(selection, config.generation.null_rate)
|
|
128
|
+
total = sum(selection.counts[name] for name in graph.order)
|
|
129
|
+
common = [
|
|
130
|
+
PlanIssue(
|
|
131
|
+
code=issue.code,
|
|
132
|
+
message=issue.message,
|
|
133
|
+
table=selection.tables[issue.table].id,
|
|
134
|
+
constraint=issue.constraint,
|
|
135
|
+
)
|
|
136
|
+
for issue in graph.issues
|
|
137
|
+
]
|
|
138
|
+
if total > MAX_ROWS:
|
|
139
|
+
common.append(PlanIssue(code="ROW_LIMIT_EXCEEDED", message="The plan exceeds 100000 rows."))
|
|
140
|
+
if not graph.order:
|
|
141
|
+
common.append(
|
|
142
|
+
PlanIssue(
|
|
143
|
+
code="NO_TABLES", severity="warning", message="No ordinary tables were selected."
|
|
144
|
+
)
|
|
145
|
+
)
|
|
146
|
+
issues: dict[Mode, list[PlanIssue]] = {mode: list(common) for mode in _MODES}
|
|
147
|
+
planned: list[PlannedTable] = []
|
|
148
|
+
for name in graph.order:
|
|
149
|
+
table = selection.tables[name]
|
|
150
|
+
count = selection.counts[name]
|
|
151
|
+
dependencies = graph.dependencies[name]
|
|
152
|
+
parents = {
|
|
153
|
+
dependency.key.parent for dependency in dependencies if dependency.source != "null"
|
|
154
|
+
}
|
|
155
|
+
if count:
|
|
156
|
+
bindings = _bindings(config, table, count, dependencies, issues)
|
|
157
|
+
source: KeySource = "generated"
|
|
158
|
+
else:
|
|
159
|
+
bindings = {mode: () for mode in _MODES}
|
|
160
|
+
source = "existing" if name in selection.reuse_existing else "none"
|
|
161
|
+
if source == "existing" and any(
|
|
162
|
+
code in {"ROW_LEVEL_SECURITY", "UNSUPPORTED_RELATION_KIND"} for code in table.issues
|
|
163
|
+
):
|
|
164
|
+
issues["live"].append(
|
|
165
|
+
PlanIssue(
|
|
166
|
+
code="UNSUPPORTED_EXISTING_PARENT",
|
|
167
|
+
table=table.id,
|
|
168
|
+
message="This relation cannot be used as an existing parent.",
|
|
169
|
+
)
|
|
170
|
+
)
|
|
171
|
+
planned.append(
|
|
172
|
+
PlannedTable(
|
|
173
|
+
id=table.id,
|
|
174
|
+
requested=name in selection.requested,
|
|
175
|
+
rows=count,
|
|
176
|
+
parents=tuple(sorted(parents, key=lambda item: (item.schema_name, item.table))),
|
|
177
|
+
dependencies=tuple(
|
|
178
|
+
PlannedDependency(foreign_key=dependency.key, source=dependency.source)
|
|
179
|
+
for dependency in dependencies
|
|
180
|
+
),
|
|
181
|
+
key_source=source,
|
|
182
|
+
bindings=bindings,
|
|
183
|
+
)
|
|
184
|
+
)
|
|
185
|
+
settings = config.generation
|
|
186
|
+
return GenerationPlan(
|
|
187
|
+
target=schema.target,
|
|
188
|
+
schema_fingerprint=schema.fingerprint,
|
|
189
|
+
total_rows=total,
|
|
190
|
+
settings=PlanSettings(
|
|
191
|
+
locale=settings.locale,
|
|
192
|
+
random_seed=settings.random_seed,
|
|
193
|
+
reference_time=settings.reference_time,
|
|
194
|
+
batch_size=settings.batch_size,
|
|
195
|
+
null_rate=settings.null_rate,
|
|
196
|
+
),
|
|
197
|
+
tables=tuple(planned),
|
|
198
|
+
compatibility={
|
|
199
|
+
mode: Compatibility(
|
|
200
|
+
executable=not any(issue.severity == "error" for issue in issues[mode]),
|
|
201
|
+
issues=tuple(issues[mode]),
|
|
202
|
+
)
|
|
203
|
+
for mode in _MODES
|
|
204
|
+
},
|
|
205
|
+
)
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def _bindings(
|
|
209
|
+
config: SeedConfig,
|
|
210
|
+
table: TableSchema,
|
|
211
|
+
rows: int,
|
|
212
|
+
dependencies: tuple[Dependency, ...],
|
|
213
|
+
issues: dict[Mode, list[PlanIssue]],
|
|
214
|
+
) -> dict[Mode, tuple[Binding, ...]]:
|
|
215
|
+
def blocked(
|
|
216
|
+
code: str,
|
|
217
|
+
message: str,
|
|
218
|
+
column: str | None = None,
|
|
219
|
+
modes: tuple[Mode, ...] = _MODES,
|
|
220
|
+
) -> None:
|
|
221
|
+
issue = PlanIssue(code=code, message=message, table=table.id, column=column)
|
|
222
|
+
for mode in modes:
|
|
223
|
+
issues[mode].append(issue)
|
|
224
|
+
|
|
225
|
+
for code in table.issues:
|
|
226
|
+
if code != "UNSUPPORTED_FOREIGN_KEY":
|
|
227
|
+
blocked(code, "A reflected feature is outside the supported generation subset.")
|
|
228
|
+
rules = config.rules.get(table.id.table, {})
|
|
229
|
+
for unknown in sorted(rules.keys() - {column.name for column in table.columns}):
|
|
230
|
+
blocked("UNKNOWN_RULE_COLUMN", "A generator rule refers to an unknown column.")
|
|
231
|
+
|
|
232
|
+
sources = {column: edge for edge in dependencies for column in edge.key.columns}
|
|
233
|
+
managed = {column for key in table.foreign_keys for column in key.columns}
|
|
234
|
+
for edge in dependencies:
|
|
235
|
+
if edge.source == "existing":
|
|
236
|
+
blocked(
|
|
237
|
+
"EXISTING_PARENT_OFFLINE",
|
|
238
|
+
"An existing parent key source is available only live.",
|
|
239
|
+
modes=("offline",),
|
|
240
|
+
)
|
|
241
|
+
issues["live"].append(
|
|
242
|
+
PlanIssue(
|
|
243
|
+
code="EXISTING_PARENT_UNVERIFIED",
|
|
244
|
+
severity="warning",
|
|
245
|
+
table=table.id,
|
|
246
|
+
constraint=edge.key.name,
|
|
247
|
+
message="Existing parent keys require live validation.",
|
|
248
|
+
)
|
|
249
|
+
)
|
|
250
|
+
|
|
251
|
+
live, offline = [], []
|
|
252
|
+
for column in table.columns:
|
|
253
|
+
name = column.name
|
|
254
|
+
rule = rules.get(name)
|
|
255
|
+
server_key = column.default_kind in {"identity", "owned_serial"}
|
|
256
|
+
generated = column.generated is not None
|
|
257
|
+
if rule is not None and (name in managed or generated or server_key):
|
|
258
|
+
blocked("MANAGED_COLUMN_RULE", "A managed column cannot have a generator rule.", name)
|
|
259
|
+
if generated:
|
|
260
|
+
choice = Binding(column=name, source="omit")
|
|
261
|
+
elif name in managed:
|
|
262
|
+
managed_edge = sources.get(name)
|
|
263
|
+
choice = Binding(
|
|
264
|
+
column=name,
|
|
265
|
+
source="null" if managed_edge and managed_edge.source == "null" else "foreign_key",
|
|
266
|
+
foreign_key=managed_edge.key.name if managed_edge else None,
|
|
267
|
+
)
|
|
268
|
+
if server_key:
|
|
269
|
+
blocked(
|
|
270
|
+
"MANAGED_KEY_CONFLICT", "A foreign key cannot also allocate an identity.", name
|
|
271
|
+
)
|
|
272
|
+
elif server_key:
|
|
273
|
+
live.append(Binding(column=name, source="server_identity"))
|
|
274
|
+
offline.append(Binding(column=name, source="explicit_identity", generator="integer"))
|
|
275
|
+
if (
|
|
276
|
+
column.sequence_max is None
|
|
277
|
+
or rows > column.sequence_max
|
|
278
|
+
or not any(
|
|
279
|
+
feature.name == f"sequence {name}" and feature.reason == "SERVER_ALLOCATED_KEY"
|
|
280
|
+
for feature in table.features
|
|
281
|
+
)
|
|
282
|
+
):
|
|
283
|
+
blocked(
|
|
284
|
+
"UNSUPPORTED_OFFLINE_SEQUENCE",
|
|
285
|
+
"The sequence cannot allocate the offline IDs.",
|
|
286
|
+
name,
|
|
287
|
+
("offline",),
|
|
288
|
+
)
|
|
289
|
+
continue
|
|
290
|
+
else:
|
|
291
|
+
bounds = tuple(
|
|
292
|
+
bound for check in table.checks for bound in check.bounds if bound.column == name
|
|
293
|
+
)
|
|
294
|
+
choice, compatible = choose_binding(column, rule, config.generation.locale, bounds)
|
|
295
|
+
if not compatible:
|
|
296
|
+
blocked(
|
|
297
|
+
"INCOMPATIBLE_BINDING", "The planned generator cannot satisfy the column.", name
|
|
298
|
+
)
|
|
299
|
+
live.append(choice)
|
|
300
|
+
offline.append(choice)
|
|
301
|
+
if not any(binding.source != "omit" for binding in offline):
|
|
302
|
+
blocked(
|
|
303
|
+
"NO_OFFLINE_COLUMNS", "An offline table needs an output column.", modes=("offline",)
|
|
304
|
+
)
|
|
305
|
+
return {"live": tuple(live), "offline": tuple(offline)}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
"""Resolve the initial table selection and effective row counts."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
|
|
5
|
+
from seed.config import ConfigError, SeedConfig, TableConfig
|
|
6
|
+
from seed.metadata import DatabaseSchema, TableSchema
|
|
7
|
+
from seed.postgres.connection import DatabaseError
|
|
8
|
+
from seed.postgres.inspection import requested_tables
|
|
9
|
+
|
|
10
|
+
MAX_ROWS = 100_000
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@dataclass(frozen=True)
|
|
14
|
+
class Selection:
|
|
15
|
+
requested: tuple[str, ...]
|
|
16
|
+
tables: dict[str, TableSchema]
|
|
17
|
+
counts: dict[str, int]
|
|
18
|
+
reuse_existing: frozenset[str]
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def validate_row_override(filters: list[str], rows: int | None) -> None:
|
|
22
|
+
"""Validate an invocation-level row override before connecting."""
|
|
23
|
+
if rows is not None and (len(filters) != 1 or not 0 <= rows <= MAX_ROWS):
|
|
24
|
+
raise ConfigError("--rows requires one --table and a count from 0 to 100000.")
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def resolve_selection(
|
|
28
|
+
config: SeedConfig,
|
|
29
|
+
schema: DatabaseSchema,
|
|
30
|
+
filters: list[str],
|
|
31
|
+
rows: int | None = None,
|
|
32
|
+
) -> Selection:
|
|
33
|
+
"""Resolve the original request and defaults for possible required parents."""
|
|
34
|
+
validate_row_override(filters, rows)
|
|
35
|
+
tables = {table.id.table: table for table in schema.tables}
|
|
36
|
+
initial = (
|
|
37
|
+
requested_tables(schema.target.schema_name, filters) if filters else set(config.tables)
|
|
38
|
+
)
|
|
39
|
+
if not initial:
|
|
40
|
+
initial = {
|
|
41
|
+
name
|
|
42
|
+
for name, table in tables.items()
|
|
43
|
+
if table.kind == "r" and "UNSUPPORTED_RELATION_KIND" not in table.issues
|
|
44
|
+
}
|
|
45
|
+
if initial - tables.keys():
|
|
46
|
+
raise DatabaseError(
|
|
47
|
+
"TABLE_UNAVAILABLE", "A requested table was not found in the selected schema.", 4
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
counts: dict[str, int] = {}
|
|
51
|
+
reuse: set[str] = set()
|
|
52
|
+
for name in tables:
|
|
53
|
+
settings = config.tables.get(name, TableConfig())
|
|
54
|
+
counts[name] = config.generation.default_rows if settings.rows is None else settings.rows
|
|
55
|
+
if settings.reuse_existing:
|
|
56
|
+
reuse.add(name)
|
|
57
|
+
if rows is not None:
|
|
58
|
+
(selected,) = initial
|
|
59
|
+
if selected in reuse and rows != 0:
|
|
60
|
+
raise ConfigError("A reused parent requires a zero row count.")
|
|
61
|
+
counts[selected] = rows
|
|
62
|
+
return Selection(tuple(sorted(initial)), tables, counts, frozenset(reuse))
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""PostgreSQL connections, catalog inspection, and guarded writes."""
|
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
"""Apply safety checks and write orchestration."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import warnings
|
|
5
|
+
from collections.abc import Callable
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from datetime import datetime
|
|
8
|
+
|
|
9
|
+
from sqlalchemy import URL, Connection, text
|
|
10
|
+
from sqlalchemy.engine import Transaction
|
|
11
|
+
from sqlalchemy.exc import SAWarning, SQLAlchemyError
|
|
12
|
+
|
|
13
|
+
from seed.config import ConfigError, SeedConfig
|
|
14
|
+
from seed.metadata import Inspection, TableId
|
|
15
|
+
from seed.planning.plan import GenerationPlan, PlanRequest, build_plan
|
|
16
|
+
from seed.postgres.connection import DatabaseError, read_snapshot
|
|
17
|
+
from seed.postgres.inspection import requested_tables
|
|
18
|
+
from seed.postgres.schema import reflect_schema
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class ApplyError(DatabaseError):
|
|
22
|
+
"""A safe preflight or transaction refusal."""
|
|
23
|
+
|
|
24
|
+
def __init__(
|
|
25
|
+
self,
|
|
26
|
+
code: str,
|
|
27
|
+
message: str,
|
|
28
|
+
status: int = 5,
|
|
29
|
+
*,
|
|
30
|
+
plan: GenerationPlan | None = None,
|
|
31
|
+
) -> None:
|
|
32
|
+
super().__init__(code, message, status)
|
|
33
|
+
self.plan = plan
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass(frozen=True)
|
|
37
|
+
class ApprovedPlan:
|
|
38
|
+
inspection: Inspection
|
|
39
|
+
plan: GenerationPlan
|
|
40
|
+
backend: tuple[int, datetime, str, str] = field(repr=False)
|
|
41
|
+
|
|
42
|
+
@property
|
|
43
|
+
def targets(self) -> tuple[TableId, ...]:
|
|
44
|
+
return tuple(table.id for table in self.plan.tables if table.rows)
|
|
45
|
+
|
|
46
|
+
@property
|
|
47
|
+
def reused_parents(self) -> tuple[TableId, ...]:
|
|
48
|
+
seen = {
|
|
49
|
+
edge.foreign_key.parent
|
|
50
|
+
for table in self.plan.tables
|
|
51
|
+
for edge in table.dependencies
|
|
52
|
+
if edge.source == "existing"
|
|
53
|
+
}
|
|
54
|
+
return tuple(sorted(seen, key=lambda table: (table.schema_name, table.table)))
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def check_target(config: SeedConfig, url: URL) -> None:
|
|
58
|
+
"""Require an independently configured safe environment and exact URL target."""
|
|
59
|
+
target = config.safety.target
|
|
60
|
+
if config.safety.environment not in {"development", "test"} or target is None:
|
|
61
|
+
raise ApplyError("TARGET_REQUIRED", "Apply requires a development or test target.")
|
|
62
|
+
if (target.host, target.port, target.database, target.schema_name) != (
|
|
63
|
+
url.host,
|
|
64
|
+
url.port,
|
|
65
|
+
url.database,
|
|
66
|
+
config.database.schema_name,
|
|
67
|
+
):
|
|
68
|
+
raise ApplyError(
|
|
69
|
+
"TARGET_MISMATCH", "Connected database does not match the configured write target."
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def apply_preflight(
|
|
74
|
+
connection: Connection,
|
|
75
|
+
url: URL,
|
|
76
|
+
config: SeedConfig,
|
|
77
|
+
request: PlanRequest,
|
|
78
|
+
) -> ApprovedPlan:
|
|
79
|
+
"""Read the authorized target and plan without writing or retaining a transaction."""
|
|
80
|
+
check_target(config, url)
|
|
81
|
+
try:
|
|
82
|
+
with read_snapshot(connection):
|
|
83
|
+
check_server(connection, url)
|
|
84
|
+
backend = backend_identity(connection)
|
|
85
|
+
inspection = inspect_for_apply(connection, url, config)
|
|
86
|
+
requested_tables(config.database.schema_name, request.filters)
|
|
87
|
+
plan = build_plan(config, inspection.schema, request.filters, request.rows)
|
|
88
|
+
if not plan.compatibility["live"].executable:
|
|
89
|
+
raise ApplyError("PLAN_BLOCKED", "This plan cannot be applied.", 4, plan=plan)
|
|
90
|
+
if plan.total_rows <= 0:
|
|
91
|
+
raise ApplyError(
|
|
92
|
+
"NO_ROWS_PLANNED", "Apply requires a positive row count.", plan=plan
|
|
93
|
+
)
|
|
94
|
+
approved = ApprovedPlan(inspection, plan, backend)
|
|
95
|
+
check_empty_targets(connection, config, approved)
|
|
96
|
+
return approved
|
|
97
|
+
except SQLAlchemyError:
|
|
98
|
+
raise ApplyError("PREFLIGHT_FAILED", "Could not verify the target for apply.") from None
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def inspect_for_apply(
|
|
102
|
+
connection: Connection,
|
|
103
|
+
url: URL,
|
|
104
|
+
config: SeedConfig,
|
|
105
|
+
*,
|
|
106
|
+
require_read_only: bool = True,
|
|
107
|
+
) -> Inspection:
|
|
108
|
+
with warnings.catch_warnings():
|
|
109
|
+
warnings.simplefilter("ignore", SAWarning)
|
|
110
|
+
try:
|
|
111
|
+
return reflect_schema(
|
|
112
|
+
connection, url, config.database.schema_name, require_read_only=require_read_only
|
|
113
|
+
)
|
|
114
|
+
except (LookupError, ValueError, NotImplementedError):
|
|
115
|
+
raise ApplyError(
|
|
116
|
+
"SCHEMA_INSPECTION_FAILED", "PostgreSQL metadata could not be normalized.", 4
|
|
117
|
+
) from None
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def backend_identity(connection: Connection) -> tuple[int, datetime, str, str]:
|
|
121
|
+
row = connection.execute(
|
|
122
|
+
text(
|
|
123
|
+
"SELECT pid, backend_start, current_user, session_user "
|
|
124
|
+
"FROM pg_catalog.pg_stat_activity WHERE pid = pg_catalog.pg_backend_pid()"
|
|
125
|
+
)
|
|
126
|
+
).one()
|
|
127
|
+
return int(row[0]), row[1], str(row[2]), str(row[3])
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def check_server(connection: Connection, url: URL) -> None:
|
|
131
|
+
if connection.scalar(text("SELECT pg_catalog.current_database()")) != url.database:
|
|
132
|
+
raise ApplyError(
|
|
133
|
+
"TARGET_MISMATCH", "Connected database does not match the configured write target."
|
|
134
|
+
)
|
|
135
|
+
if connection.scalar(text("SHOW session_replication_role")) != "origin":
|
|
136
|
+
raise ApplyError("UNSAFE_REPLICATION_ROLE", "PostgreSQL must enforce ordinary constraints.")
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def qualified(connection: Connection, table: TableId) -> str:
|
|
140
|
+
"""Compose a schema-qualified identifier from trusted metadata."""
|
|
141
|
+
quote = connection.dialect.identifier_preparer.quote_identifier
|
|
142
|
+
return f"{quote(table.schema_name)}.{quote(table.table)}"
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def check_empty_targets(connection: Connection, config: SeedConfig, approved: ApprovedPlan) -> None:
|
|
146
|
+
for table in approved.targets:
|
|
147
|
+
has_rows = connection.scalar(
|
|
148
|
+
text(f"SELECT EXISTS (SELECT 1 FROM ONLY {qualified(connection, table)})")
|
|
149
|
+
)
|
|
150
|
+
if has_rows and not config.safety.allow_existing_data:
|
|
151
|
+
raise ApplyError(
|
|
152
|
+
"TARGET_NOT_EMPTY",
|
|
153
|
+
"A target table contains rows and append is disabled.",
|
|
154
|
+
plan=approved.plan,
|
|
155
|
+
)
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def preflight_lines(approved: ApprovedPlan) -> list[str]:
|
|
159
|
+
target = approved.plan.target
|
|
160
|
+
lines = [
|
|
161
|
+
f"Apply target {json.dumps(target.host)}:{target.port} "
|
|
162
|
+
f"database {json.dumps(target.database)}, schema {json.dumps(target.schema_name)}",
|
|
163
|
+
f"{approved.plan.total_rows} planned rows",
|
|
164
|
+
]
|
|
165
|
+
for table in approved.plan.tables:
|
|
166
|
+
if table.rows:
|
|
167
|
+
lines.append(f" {json.dumps(table.id.table)} · {table.rows} rows")
|
|
168
|
+
lines.extend(
|
|
169
|
+
f" {json.dumps(parent.table)} · reuse existing keys" for parent in approved.reused_parents
|
|
170
|
+
)
|
|
171
|
+
return lines
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def validate_apply_options(*, yes: bool, dry_run: bool) -> None:
|
|
175
|
+
if yes and dry_run:
|
|
176
|
+
raise ConfigError("Use either --dry-run or --yes.")
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def confirm_apply(*, yes: bool, interactive: bool, prompt: Callable[[], str]) -> None:
|
|
180
|
+
"""Require affirmative approval, including when terminal input ends."""
|
|
181
|
+
if yes:
|
|
182
|
+
return
|
|
183
|
+
if not interactive:
|
|
184
|
+
raise ApplyError("CONFIRMATION_REQUIRED", "Use --yes to approve a non-interactive apply.")
|
|
185
|
+
try:
|
|
186
|
+
answer = prompt()
|
|
187
|
+
except EOFError:
|
|
188
|
+
answer = ""
|
|
189
|
+
if answer.strip().lower() not in {"y", "yes"}:
|
|
190
|
+
raise ApplyError("CANCELLED", "Apply was not confirmed.")
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def begin_guarded_write(
|
|
194
|
+
connection: Connection,
|
|
195
|
+
url: URL,
|
|
196
|
+
config: SeedConfig,
|
|
197
|
+
request: PlanRequest,
|
|
198
|
+
approved: ApprovedPlan,
|
|
199
|
+
) -> Transaction:
|
|
200
|
+
"""Start one transaction and hold each required lock before returning."""
|
|
201
|
+
check_target(config, url)
|
|
202
|
+
if connection.closed or connection.invalidated or connection.in_transaction():
|
|
203
|
+
raise ApplyError("TARGET_CHANGED", "The approved connection is no longer available.")
|
|
204
|
+
try:
|
|
205
|
+
connection.execution_options(isolation_level="READ COMMITTED", postgresql_readonly=False)
|
|
206
|
+
transaction = connection.begin()
|
|
207
|
+
except SQLAlchemyError:
|
|
208
|
+
raise ApplyError(
|
|
209
|
+
"TARGET_CHANGED", "The approved connection is no longer available."
|
|
210
|
+
) from None
|
|
211
|
+
try:
|
|
212
|
+
_lock_and_recheck(connection, url, config, request, approved)
|
|
213
|
+
except (Exception, KeyboardInterrupt):
|
|
214
|
+
rollback(transaction)
|
|
215
|
+
raise
|
|
216
|
+
return transaction
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def _lock_and_recheck(
|
|
220
|
+
connection: Connection,
|
|
221
|
+
url: URL,
|
|
222
|
+
config: SeedConfig,
|
|
223
|
+
request: PlanRequest,
|
|
224
|
+
approved: ApprovedPlan,
|
|
225
|
+
) -> None:
|
|
226
|
+
try:
|
|
227
|
+
connection.execute(text("SET LOCAL search_path TO pg_catalog"))
|
|
228
|
+
connection.execute(text("SET LOCAL lock_timeout TO '5s'"))
|
|
229
|
+
connection.execute(text("SET LOCAL statement_timeout TO '60s'"))
|
|
230
|
+
if backend_identity(connection) != approved.backend:
|
|
231
|
+
raise ApplyError("TARGET_CHANGED", "The approved connection is no longer available.")
|
|
232
|
+
check_server(connection, url)
|
|
233
|
+
if connection.scalar(text("SHOW transaction_read_only")) != "off":
|
|
234
|
+
raise ApplyError("READ_ONLY_TARGET", "The target connection is read-only.")
|
|
235
|
+
except SQLAlchemyError:
|
|
236
|
+
raise ApplyError("TARGET_CHANGED", "Could not recheck the approved connection.") from None
|
|
237
|
+
|
|
238
|
+
locks = dict.fromkeys(approved.reused_parents, "ACCESS SHARE")
|
|
239
|
+
locks.update(dict.fromkeys(approved.targets, "SHARE ROW EXCLUSIVE"))
|
|
240
|
+
try:
|
|
241
|
+
for relation in sorted(locks, key=lambda table: (table.schema_name, table.table)):
|
|
242
|
+
connection.execute(
|
|
243
|
+
text(f"LOCK TABLE ONLY {qualified(connection, relation)} IN {locks[relation]} MODE")
|
|
244
|
+
)
|
|
245
|
+
except SQLAlchemyError:
|
|
246
|
+
raise ApplyError(
|
|
247
|
+
"LOCK_UNAVAILABLE", "Could not acquire all required table locks."
|
|
248
|
+
) from None
|
|
249
|
+
|
|
250
|
+
try:
|
|
251
|
+
check_server(connection, url)
|
|
252
|
+
current = inspect_for_apply(connection, url, config, require_read_only=False)
|
|
253
|
+
if current != approved.inspection:
|
|
254
|
+
raise ApplyError("TARGET_CHANGED", "Schema metadata changed after preflight.")
|
|
255
|
+
plan = build_plan(config, current.schema, request.filters, request.rows)
|
|
256
|
+
if plan != approved.plan:
|
|
257
|
+
raise ApplyError("PLAN_CHANGED", "The generation plan changed after preflight.")
|
|
258
|
+
check_empty_targets(connection, config, approved)
|
|
259
|
+
except SQLAlchemyError:
|
|
260
|
+
raise ApplyError("PREFLIGHT_FAILED", "Could not recheck the locked target.") from None
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def rollback(transaction: Transaction) -> None:
|
|
264
|
+
"""Try to release an uncommitted transaction without exposing driver details."""
|
|
265
|
+
try:
|
|
266
|
+
transaction.rollback()
|
|
267
|
+
except SQLAlchemyError:
|
|
268
|
+
pass
|