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/__init__.py
ADDED
seed/cli.py
ADDED
|
@@ -0,0 +1,395 @@
|
|
|
1
|
+
"""Terminal entry point for Seed."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import sys
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Annotated
|
|
7
|
+
|
|
8
|
+
import typer
|
|
9
|
+
from rich.console import Console
|
|
10
|
+
from rich.text import Text
|
|
11
|
+
from typer._click.exceptions import UsageError
|
|
12
|
+
|
|
13
|
+
from seed import __version__
|
|
14
|
+
from seed.config import ConfigError
|
|
15
|
+
from seed.planning.plan import PlanRequest, plan_database
|
|
16
|
+
from seed.postgres.connection import DatabaseError
|
|
17
|
+
from seed.postgres.inspection import inspect_database
|
|
18
|
+
from seed.reporting.inspection import inspection_lines
|
|
19
|
+
from seed.reporting.plan import plan_issues, plan_lines
|
|
20
|
+
from seed.workflows.apply import run_apply
|
|
21
|
+
from seed.workflows.export import ExportFormat, run_export
|
|
22
|
+
from seed.workflows.initialize import initialize_config
|
|
23
|
+
from seed.workflows.preview import preview as preview_request
|
|
24
|
+
from seed.workflows.validate import validate as validate_request
|
|
25
|
+
|
|
26
|
+
app = typer.Typer(
|
|
27
|
+
help="Generate synthetic data for development and testing.",
|
|
28
|
+
no_args_is_help=True,
|
|
29
|
+
invoke_without_command=True,
|
|
30
|
+
add_completion=False,
|
|
31
|
+
pretty_exceptions_enable=False,
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def result(message: str) -> None:
|
|
36
|
+
"""Write a result to stdout."""
|
|
37
|
+
Console().print(Text(message))
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def diagnostic(message: str) -> None:
|
|
41
|
+
"""Write a diagnostic to stderr."""
|
|
42
|
+
Console(stderr=True).print(Text(message))
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@app.callback()
|
|
46
|
+
def root(
|
|
47
|
+
version: bool = typer.Option(
|
|
48
|
+
False, "--version", is_eager=True, help="Show the package version."
|
|
49
|
+
),
|
|
50
|
+
) -> None:
|
|
51
|
+
"""Work with Seed configurations and datasets."""
|
|
52
|
+
if version:
|
|
53
|
+
result(__version__)
|
|
54
|
+
raise typer.Exit()
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
@app.command()
|
|
58
|
+
def init(
|
|
59
|
+
config: Annotated[Path, typer.Option("--config", help="Starter configuration path.")] = Path(
|
|
60
|
+
"./seed.toml"
|
|
61
|
+
),
|
|
62
|
+
as_json: Annotated[bool, typer.Option("--json", help="Emit a JSON result.")] = False,
|
|
63
|
+
verbose: Annotated[
|
|
64
|
+
bool, typer.Option("--verbose", help="Show additional diagnostics.")
|
|
65
|
+
] = False,
|
|
66
|
+
) -> None:
|
|
67
|
+
"""Create a starter configuration."""
|
|
68
|
+
try:
|
|
69
|
+
created = initialize_config(config)
|
|
70
|
+
except (OSError, ConfigError) as error:
|
|
71
|
+
code = "CONFIG_INVALID" if isinstance(error, ConfigError) else "INIT_FAILED"
|
|
72
|
+
status = 2 if isinstance(error, ConfigError) else 6
|
|
73
|
+
if as_json:
|
|
74
|
+
_json_response(
|
|
75
|
+
"init",
|
|
76
|
+
status,
|
|
77
|
+
None,
|
|
78
|
+
[
|
|
79
|
+
{"code": code, "severity": "error", "message": str(error)},
|
|
80
|
+
],
|
|
81
|
+
)
|
|
82
|
+
else:
|
|
83
|
+
diagnostic(str(error))
|
|
84
|
+
raise typer.Exit(status) from None
|
|
85
|
+
|
|
86
|
+
if verbose:
|
|
87
|
+
diagnostic("Created a starter configuration." if created else "Existing file preserved.")
|
|
88
|
+
if as_json:
|
|
89
|
+
_json_response("init", 0, {"path": str(config), "created": created}, [])
|
|
90
|
+
else:
|
|
91
|
+
result("Created seed configuration." if created else "Seed configuration already exists.")
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
@app.command()
|
|
95
|
+
def inspect(
|
|
96
|
+
config: Annotated[Path, typer.Option("--config", help="Configuration path.")] = Path(
|
|
97
|
+
"./seed.toml"
|
|
98
|
+
),
|
|
99
|
+
schema: Annotated[str | None, typer.Option("--schema", help="Exact schema name.")] = None,
|
|
100
|
+
table: Annotated[
|
|
101
|
+
list[str] | None, typer.Option("--table", help="Limit displayed tables.")
|
|
102
|
+
] = None,
|
|
103
|
+
as_json: Annotated[bool, typer.Option("--json", help="Emit a JSON result.")] = False,
|
|
104
|
+
verbose: Annotated[
|
|
105
|
+
bool, typer.Option("--verbose", help="Show additional diagnostics.")
|
|
106
|
+
] = False,
|
|
107
|
+
) -> None:
|
|
108
|
+
"""Inspect one PostgreSQL schema in a read-only transaction."""
|
|
109
|
+
try:
|
|
110
|
+
report = inspect_database(config, schema, table or [])
|
|
111
|
+
except (ConfigError, DatabaseError) as error:
|
|
112
|
+
code = error.code if isinstance(error, DatabaseError) else "CONFIG_INVALID"
|
|
113
|
+
status = error.status if isinstance(error, DatabaseError) else 2
|
|
114
|
+
if as_json:
|
|
115
|
+
_json_response(
|
|
116
|
+
"inspect",
|
|
117
|
+
status,
|
|
118
|
+
None,
|
|
119
|
+
[
|
|
120
|
+
{"code": code, "severity": "error", "message": str(error)},
|
|
121
|
+
],
|
|
122
|
+
)
|
|
123
|
+
else:
|
|
124
|
+
diagnostic(str(error))
|
|
125
|
+
raise typer.Exit(status) from None
|
|
126
|
+
|
|
127
|
+
if verbose:
|
|
128
|
+
diagnostic("Completed schema inspection in a read-only transaction.")
|
|
129
|
+
if as_json:
|
|
130
|
+
issues: list[dict[str, object]] = [
|
|
131
|
+
{
|
|
132
|
+
"code": code,
|
|
133
|
+
"severity": "warning",
|
|
134
|
+
"message": "A schema feature is outside the supported generation subset.",
|
|
135
|
+
"scope": {"table": item.id.model_dump(by_alias=True)},
|
|
136
|
+
}
|
|
137
|
+
for item in report.tables
|
|
138
|
+
for code in item.issues
|
|
139
|
+
]
|
|
140
|
+
_json_response(
|
|
141
|
+
"inspect",
|
|
142
|
+
0,
|
|
143
|
+
{
|
|
144
|
+
"schema": report.model_dump(mode="json", by_alias=True),
|
|
145
|
+
},
|
|
146
|
+
issues,
|
|
147
|
+
)
|
|
148
|
+
else:
|
|
149
|
+
result("\n".join(inspection_lines(report)))
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
@app.command()
|
|
153
|
+
def plan(
|
|
154
|
+
config: Annotated[Path, typer.Option("--config", help="Configuration path.")] = Path(
|
|
155
|
+
"./seed.toml"
|
|
156
|
+
),
|
|
157
|
+
schema: Annotated[str | None, typer.Option("--schema", help="Exact schema name.")] = None,
|
|
158
|
+
table: Annotated[list[str] | None, typer.Option("--table", help="Select tables.")] = None,
|
|
159
|
+
rows: Annotated[int | None, typer.Option("--rows", help="Override one table's count.")] = None,
|
|
160
|
+
random_seed: Annotated[int | None, typer.Option("--random-seed")] = None,
|
|
161
|
+
locale: Annotated[str | None, typer.Option("--locale")] = None,
|
|
162
|
+
as_json: Annotated[bool, typer.Option("--json", help="Emit a JSON result.")] = False,
|
|
163
|
+
verbose: Annotated[bool, typer.Option("--verbose")] = False,
|
|
164
|
+
) -> None:
|
|
165
|
+
"""Plan generation from a read-only schema snapshot."""
|
|
166
|
+
try:
|
|
167
|
+
report = plan_database(
|
|
168
|
+
config,
|
|
169
|
+
schema=schema,
|
|
170
|
+
filters=table or [],
|
|
171
|
+
rows=rows,
|
|
172
|
+
locale=locale,
|
|
173
|
+
random_seed=random_seed,
|
|
174
|
+
)
|
|
175
|
+
except (ConfigError, DatabaseError) as error:
|
|
176
|
+
code = error.code if isinstance(error, DatabaseError) else "CONFIG_INVALID"
|
|
177
|
+
status = error.status if isinstance(error, DatabaseError) else 2
|
|
178
|
+
if as_json:
|
|
179
|
+
_json_response(
|
|
180
|
+
"plan",
|
|
181
|
+
status,
|
|
182
|
+
None,
|
|
183
|
+
[
|
|
184
|
+
{"code": code, "severity": "error", "message": str(error)},
|
|
185
|
+
],
|
|
186
|
+
)
|
|
187
|
+
else:
|
|
188
|
+
diagnostic(str(error))
|
|
189
|
+
raise typer.Exit(status) from None
|
|
190
|
+
|
|
191
|
+
if verbose:
|
|
192
|
+
diagnostic("Built the plan from a read-only schema snapshot.")
|
|
193
|
+
if as_json:
|
|
194
|
+
_json_response(
|
|
195
|
+
"plan",
|
|
196
|
+
0 if report.executable else 4,
|
|
197
|
+
{
|
|
198
|
+
"plan": report.model_dump(mode="json", by_alias=True),
|
|
199
|
+
},
|
|
200
|
+
plan_issues(report),
|
|
201
|
+
)
|
|
202
|
+
else:
|
|
203
|
+
result("\n".join(plan_lines(report)))
|
|
204
|
+
if not report.executable:
|
|
205
|
+
raise typer.Exit(4)
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def _json_response(
|
|
209
|
+
command: str,
|
|
210
|
+
status: int,
|
|
211
|
+
data: dict[str, object] | None,
|
|
212
|
+
issues: list[dict[str, object]],
|
|
213
|
+
) -> None:
|
|
214
|
+
typer.echo(
|
|
215
|
+
json.dumps(
|
|
216
|
+
{
|
|
217
|
+
"version": 1,
|
|
218
|
+
"command": command,
|
|
219
|
+
"ok": status == 0,
|
|
220
|
+
"data": data,
|
|
221
|
+
"issues": issues,
|
|
222
|
+
}
|
|
223
|
+
)
|
|
224
|
+
)
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def _render_issue(issue: dict[str, object]) -> None:
|
|
228
|
+
scope = " · " + json.dumps(issue["scope"]) if "scope" in issue else ""
|
|
229
|
+
diagnostic(f"{issue['code']} · {issue['message']}{scope}")
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
@app.command()
|
|
233
|
+
def validate(
|
|
234
|
+
config: Annotated[Path, typer.Option("--config", help="Configuration path.")] = Path(
|
|
235
|
+
"./seed.toml"
|
|
236
|
+
),
|
|
237
|
+
schema: Annotated[str | None, typer.Option("--schema", help="Exact schema name.")] = None,
|
|
238
|
+
table: Annotated[list[str] | None, typer.Option("--table", help="Select tables.")] = None,
|
|
239
|
+
rows: Annotated[int | None, typer.Option("--rows", help="Override one table's count.")] = None,
|
|
240
|
+
random_seed: Annotated[int | None, typer.Option("--random-seed")] = None,
|
|
241
|
+
locale: Annotated[str | None, typer.Option("--locale")] = None,
|
|
242
|
+
as_json: Annotated[bool, typer.Option("--json", help="Emit a JSON result.")] = False,
|
|
243
|
+
verbose: Annotated[bool, typer.Option("--verbose")] = False,
|
|
244
|
+
dataset: Annotated[bool, typer.Option("--dataset", help="Validate all offline rows.")] = False,
|
|
245
|
+
) -> None:
|
|
246
|
+
"""Validate configuration, schema compatibility, and optional offline rows."""
|
|
247
|
+
report = validate_request(
|
|
248
|
+
PlanRequest(config, schema, table or [], rows, locale, random_seed),
|
|
249
|
+
dataset=dataset,
|
|
250
|
+
)
|
|
251
|
+
if verbose:
|
|
252
|
+
diagnostic("Completed staged validation.")
|
|
253
|
+
if as_json:
|
|
254
|
+
_json_response("validate", report.status, report.payload(), report.issues())
|
|
255
|
+
else:
|
|
256
|
+
for name, stage in report.stages().items():
|
|
257
|
+
count = (
|
|
258
|
+
f" · {stage.rows_checked} rows checked" if stage.rows_checked is not None else ""
|
|
259
|
+
)
|
|
260
|
+
result(f"{name} · {stage.status}{count}")
|
|
261
|
+
for issue in report.issues():
|
|
262
|
+
_render_issue(issue)
|
|
263
|
+
if report.status:
|
|
264
|
+
raise typer.Exit(report.status)
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
@app.command()
|
|
268
|
+
def preview(
|
|
269
|
+
config: Annotated[Path, typer.Option("--config", help="Configuration path.")] = Path(
|
|
270
|
+
"./seed.toml"
|
|
271
|
+
),
|
|
272
|
+
schema: Annotated[str | None, typer.Option("--schema", help="Exact schema name.")] = None,
|
|
273
|
+
table: Annotated[list[str] | None, typer.Option("--table", help="Select tables.")] = None,
|
|
274
|
+
rows: Annotated[int | None, typer.Option("--rows", help="Override one table's count.")] = None,
|
|
275
|
+
random_seed: Annotated[int | None, typer.Option("--random-seed")] = None,
|
|
276
|
+
locale: Annotated[str | None, typer.Option("--locale")] = None,
|
|
277
|
+
as_json: Annotated[bool, typer.Option("--json", help="Emit a JSON result.")] = False,
|
|
278
|
+
verbose: Annotated[bool, typer.Option("--verbose")] = False,
|
|
279
|
+
limit: Annotated[int, typer.Option("--limit", help="Rows to show per requested table.")] = 5,
|
|
280
|
+
) -> None:
|
|
281
|
+
"""Show an offline sample from a read-only schema snapshot."""
|
|
282
|
+
report = preview_request(
|
|
283
|
+
PlanRequest(config, schema, table or [], rows, locale, random_seed), limit
|
|
284
|
+
)
|
|
285
|
+
if verbose:
|
|
286
|
+
diagnostic("Completed offline preview.")
|
|
287
|
+
if as_json:
|
|
288
|
+
_json_response("preview", report.status, report.payload(), list(report.issues))
|
|
289
|
+
else:
|
|
290
|
+
lines = plan_lines(report.plan) if report.plan is not None else []
|
|
291
|
+
for sample in report.tables:
|
|
292
|
+
name = json.dumps(sample.table.table)
|
|
293
|
+
lines.append(f"{name} · {len(sample.rows)} sampled rows")
|
|
294
|
+
lines.append(" " + " | ".join(json.dumps(column.name) for column in sample.columns))
|
|
295
|
+
lines.extend(" " + json.dumps(row) for row in sample.rows)
|
|
296
|
+
if lines:
|
|
297
|
+
result("\n".join(lines))
|
|
298
|
+
if report.status:
|
|
299
|
+
for issue in report.issues:
|
|
300
|
+
_render_issue(issue)
|
|
301
|
+
if report.status:
|
|
302
|
+
raise typer.Exit(report.status)
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
def _apply_prompt() -> str:
|
|
306
|
+
sys.stderr.write("Apply the planned rows? [y/N] ")
|
|
307
|
+
sys.stderr.flush()
|
|
308
|
+
return sys.stdin.readline()
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
@app.command()
|
|
312
|
+
def apply(
|
|
313
|
+
config: Annotated[Path, typer.Option("--config", help="Configuration path.")] = Path(
|
|
314
|
+
"./seed.toml"
|
|
315
|
+
),
|
|
316
|
+
schema: Annotated[str | None, typer.Option("--schema", help="Exact schema name.")] = None,
|
|
317
|
+
table: Annotated[list[str] | None, typer.Option("--table", help="Select tables.")] = None,
|
|
318
|
+
rows: Annotated[int | None, typer.Option("--rows", help="Override one table's count.")] = None,
|
|
319
|
+
random_seed: Annotated[int | None, typer.Option("--random-seed")] = None,
|
|
320
|
+
locale: Annotated[str | None, typer.Option("--locale")] = None,
|
|
321
|
+
as_json: Annotated[bool, typer.Option("--json", help="Emit a JSON result.")] = False,
|
|
322
|
+
verbose: Annotated[bool, typer.Option("--verbose")] = False,
|
|
323
|
+
dry_run: Annotated[bool, typer.Option("--dry-run", help="Run read-only preflight.")] = False,
|
|
324
|
+
yes: Annotated[bool, typer.Option("--yes", help="Skip the confirmation prompt.")] = False,
|
|
325
|
+
) -> None:
|
|
326
|
+
"""Insert planned rows into an explicitly authorized development or test target."""
|
|
327
|
+
report = run_apply(
|
|
328
|
+
PlanRequest(config, schema, table or [], rows, locale, random_seed),
|
|
329
|
+
yes=yes,
|
|
330
|
+
dry_run=dry_run,
|
|
331
|
+
interactive=sys.stdin.isatty() and sys.stderr.isatty(),
|
|
332
|
+
prompt=_apply_prompt,
|
|
333
|
+
show_target=diagnostic,
|
|
334
|
+
)
|
|
335
|
+
if verbose:
|
|
336
|
+
diagnostic("Completed apply workflow.")
|
|
337
|
+
if as_json:
|
|
338
|
+
_json_response("apply", report.status, report.payload(), report.issues)
|
|
339
|
+
else:
|
|
340
|
+
for issue in report.issues:
|
|
341
|
+
_render_issue(issue)
|
|
342
|
+
if report.status == 0 and dry_run:
|
|
343
|
+
result("Read-only preflight passed.")
|
|
344
|
+
elif report.insertion is not None and report.insertion.counts is not None:
|
|
345
|
+
for count in report.insertion.counts:
|
|
346
|
+
result(f"Committed {count.rows} rows to {json.dumps(count.table.table)}.")
|
|
347
|
+
if report.status:
|
|
348
|
+
raise typer.Exit(report.status)
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
@app.command()
|
|
352
|
+
def export(
|
|
353
|
+
format: Annotated[ExportFormat, typer.Option("--format", help="Artifact format.")],
|
|
354
|
+
config: Annotated[Path, typer.Option("--config", help="Configuration path.")] = Path(
|
|
355
|
+
"./seed.toml"
|
|
356
|
+
),
|
|
357
|
+
schema: Annotated[str | None, typer.Option("--schema", help="Exact schema name.")] = None,
|
|
358
|
+
table: Annotated[list[str] | None, typer.Option("--table", help="Select tables.")] = None,
|
|
359
|
+
rows: Annotated[int | None, typer.Option("--rows", help="Override one table’s count.")] = None,
|
|
360
|
+
random_seed: Annotated[int | None, typer.Option("--random-seed")] = None,
|
|
361
|
+
locale: Annotated[str | None, typer.Option("--locale")] = None,
|
|
362
|
+
as_json: Annotated[bool, typer.Option("--json", help="Emit a JSON result.")] = False,
|
|
363
|
+
verbose: Annotated[bool, typer.Option("--verbose")] = False,
|
|
364
|
+
output: Annotated[Path, typer.Option("--output", help="New export directory.")] = Path(
|
|
365
|
+
"./seed-export"
|
|
366
|
+
),
|
|
367
|
+
) -> None:
|
|
368
|
+
"""Export a relational dataset from a read-only schema snapshot."""
|
|
369
|
+
report = run_export(
|
|
370
|
+
PlanRequest(config, schema, table or [], rows, locale, random_seed), format, output
|
|
371
|
+
)
|
|
372
|
+
if verbose and report.result is not None:
|
|
373
|
+
diagnostic("Published the export manifest.")
|
|
374
|
+
if as_json:
|
|
375
|
+
data: dict[str, object] | None = (
|
|
376
|
+
{"export": report.result.payload()} if report.result is not None else None
|
|
377
|
+
)
|
|
378
|
+
_json_response("export", report.status, data, list(report.issues))
|
|
379
|
+
else:
|
|
380
|
+
for issue in report.issues:
|
|
381
|
+
_render_issue(issue)
|
|
382
|
+
if report.result is not None:
|
|
383
|
+
result(f"Exported to {json.dumps(str(report.result.directory))}.")
|
|
384
|
+
if report.status:
|
|
385
|
+
raise typer.Exit(report.status)
|
|
386
|
+
|
|
387
|
+
|
|
388
|
+
def main() -> int:
|
|
389
|
+
"""Run the installed CLI and keep parser diagnostics free of arguments."""
|
|
390
|
+
try:
|
|
391
|
+
status = app(standalone_mode=False)
|
|
392
|
+
except UsageError:
|
|
393
|
+
diagnostic("Invalid command or options. Run seed --help for usage.")
|
|
394
|
+
return 2
|
|
395
|
+
return status if isinstance(status, int) else 0
|
seed/config.py
ADDED
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
"""Read and validate Seed configuration without connecting to a database."""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import re
|
|
5
|
+
import tomllib
|
|
6
|
+
from collections.abc import Mapping
|
|
7
|
+
from datetime import UTC, date, datetime, timedelta
|
|
8
|
+
from decimal import Decimal, InvalidOperation
|
|
9
|
+
from ipaddress import ip_address
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Annotated, Literal, Self
|
|
12
|
+
|
|
13
|
+
from faker.config import AVAILABLE_LOCALES
|
|
14
|
+
from pydantic import BaseModel, ConfigDict, Field, ValidationError, field_validator, model_validator
|
|
15
|
+
|
|
16
|
+
type Identifier = Annotated[str, Field(min_length=1, pattern=r"^[^\x00]+$")]
|
|
17
|
+
type Rows = Annotated[int, Field(ge=0, le=100_000)]
|
|
18
|
+
type Probability = Annotated[float, Field(ge=0, le=1, allow_inf_nan=False)]
|
|
19
|
+
type Scalar = str | bool | int | date | datetime
|
|
20
|
+
type Generator = Literal[
|
|
21
|
+
"integer",
|
|
22
|
+
"decimal",
|
|
23
|
+
"boolean",
|
|
24
|
+
"text",
|
|
25
|
+
"date",
|
|
26
|
+
"datetime",
|
|
27
|
+
"uuid",
|
|
28
|
+
"choice",
|
|
29
|
+
"constant",
|
|
30
|
+
"email",
|
|
31
|
+
"phone",
|
|
32
|
+
"first_name",
|
|
33
|
+
"last_name",
|
|
34
|
+
"name",
|
|
35
|
+
"address",
|
|
36
|
+
"city",
|
|
37
|
+
"country",
|
|
38
|
+
"description",
|
|
39
|
+
]
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class ConfigError(Exception):
|
|
43
|
+
"""A configuration failure with a message safe to render."""
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class ConfigModel(BaseModel):
|
|
47
|
+
model_config = ConfigDict(strict=True, extra="forbid", hide_input_in_errors=True)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class DatabaseConfig(ConfigModel):
|
|
51
|
+
driver: Literal["postgresql"] = "postgresql"
|
|
52
|
+
url_env: Annotated[str, Field(pattern=r"^[A-Za-z_][A-Za-z0-9_]*$")]
|
|
53
|
+
schema_name: Identifier = Field(default="public", alias="schema")
|
|
54
|
+
connect_timeout: Annotated[int, Field(ge=2, le=60)] = 5
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class GenerationConfig(ConfigModel):
|
|
58
|
+
locale: str = "en_US"
|
|
59
|
+
random_seed: Annotated[int, Field(ge=0, le=2**64 - 1)] = 0
|
|
60
|
+
default_rows: Rows = 100
|
|
61
|
+
batch_size: Annotated[int, Field(ge=1, le=10_000)] = 1000
|
|
62
|
+
reference_time: datetime = datetime(2025, 1, 1, tzinfo=UTC)
|
|
63
|
+
null_rate: Probability = 0.05
|
|
64
|
+
|
|
65
|
+
@field_validator("locale")
|
|
66
|
+
@classmethod
|
|
67
|
+
def check_locale(cls, value: str) -> str:
|
|
68
|
+
if value not in AVAILABLE_LOCALES:
|
|
69
|
+
raise ValueError("Expected a supported Faker locale")
|
|
70
|
+
return value
|
|
71
|
+
|
|
72
|
+
@field_validator("reference_time")
|
|
73
|
+
@classmethod
|
|
74
|
+
def normalize_time(cls, value: datetime) -> datetime:
|
|
75
|
+
if value.utcoffset() is None:
|
|
76
|
+
raise ValueError("Expected an offset datetime")
|
|
77
|
+
try:
|
|
78
|
+
utc_value = value.astimezone(UTC)
|
|
79
|
+
utc_value - timedelta(days=365)
|
|
80
|
+
except OverflowError:
|
|
81
|
+
raise ValueError("Expected a reference time with a preceding 365-day window") from None
|
|
82
|
+
return utc_value
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class WriteTarget(ConfigModel):
|
|
86
|
+
host: str
|
|
87
|
+
port: Annotated[int, Field(ge=1, le=65_535)]
|
|
88
|
+
database: Identifier
|
|
89
|
+
schema_name: Identifier = Field(alias="schema")
|
|
90
|
+
|
|
91
|
+
@field_validator("host")
|
|
92
|
+
@classmethod
|
|
93
|
+
def check_host(cls, value: str) -> str:
|
|
94
|
+
try:
|
|
95
|
+
return str(ip_address(value))
|
|
96
|
+
except ValueError:
|
|
97
|
+
host = value.lower().removesuffix(".")
|
|
98
|
+
label = r"[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?"
|
|
99
|
+
if len(host) > 253 or not re.fullmatch(rf"{label}(?:\.{label})*", host):
|
|
100
|
+
raise ValueError("Expected one DNS name or IP address") from None
|
|
101
|
+
return host
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
class SafetyConfig(ConfigModel):
|
|
105
|
+
environment: Literal["development", "test"] | None = None
|
|
106
|
+
allow_existing_data: bool = False
|
|
107
|
+
target: WriteTarget | None = None
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
class TableConfig(ConfigModel):
|
|
111
|
+
rows: Rows | None = None
|
|
112
|
+
reuse_existing: bool = False
|
|
113
|
+
|
|
114
|
+
@model_validator(mode="after")
|
|
115
|
+
def check_reuse(self) -> Self:
|
|
116
|
+
if self.reuse_existing and self.rows != 0:
|
|
117
|
+
raise ValueError("Existing parent reuse requires an explicit zero row count")
|
|
118
|
+
return self
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
class GeneratorRule(ConfigModel):
|
|
122
|
+
generator: Generator | None = None
|
|
123
|
+
min: int | str | None = None
|
|
124
|
+
max: int | str | None = None
|
|
125
|
+
value: Scalar | None = None
|
|
126
|
+
values: list[Scalar] | None = None
|
|
127
|
+
unique: bool = False
|
|
128
|
+
null_rate: Probability | None = None
|
|
129
|
+
|
|
130
|
+
@model_validator(mode="after")
|
|
131
|
+
def check_parameters(self) -> Self:
|
|
132
|
+
if (self.value is not None) != (self.generator == "constant"):
|
|
133
|
+
raise ValueError("The constant generator requires a value")
|
|
134
|
+
if self.generator == "choice":
|
|
135
|
+
if not self.values or len({(type(value), value) for value in self.values}) != len(
|
|
136
|
+
self.values
|
|
137
|
+
):
|
|
138
|
+
raise ValueError("The choice generator requires distinct values")
|
|
139
|
+
elif self.values is not None:
|
|
140
|
+
raise ValueError("Values are only valid with the choice generator")
|
|
141
|
+
|
|
142
|
+
bounds = [bound for bound in (self.min, self.max) if bound is not None]
|
|
143
|
+
if bounds:
|
|
144
|
+
if self.generator == "integer" and all(isinstance(bound, int) for bound in bounds):
|
|
145
|
+
numeric = [Decimal(bound) for bound in bounds]
|
|
146
|
+
elif self.generator == "decimal":
|
|
147
|
+
try:
|
|
148
|
+
numeric = [Decimal(bound) for bound in bounds]
|
|
149
|
+
except InvalidOperation:
|
|
150
|
+
raise ValueError("Expected exact decimal bounds") from None
|
|
151
|
+
else:
|
|
152
|
+
raise ValueError("Expected bounds for a compatible numeric generator")
|
|
153
|
+
if not all(bound.is_finite() for bound in numeric) or (
|
|
154
|
+
len(numeric) == 2 and numeric[0] > numeric[1]
|
|
155
|
+
):
|
|
156
|
+
raise ValueError("Expected finite bounds in ascending order")
|
|
157
|
+
return self
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
class SeedConfig(ConfigModel):
|
|
161
|
+
version: Literal[1]
|
|
162
|
+
database: DatabaseConfig
|
|
163
|
+
generation: GenerationConfig = Field(default_factory=GenerationConfig)
|
|
164
|
+
safety: SafetyConfig = Field(default_factory=SafetyConfig)
|
|
165
|
+
tables: dict[Identifier, TableConfig] = Field(default_factory=dict)
|
|
166
|
+
rules: dict[Identifier, dict[Identifier, GeneratorRule]] = Field(default_factory=dict)
|
|
167
|
+
|
|
168
|
+
@field_validator("version", mode="before")
|
|
169
|
+
@classmethod
|
|
170
|
+
def check_version(cls, value: object) -> object:
|
|
171
|
+
if type(value) is not int:
|
|
172
|
+
raise ValueError("Expected an integer configuration version")
|
|
173
|
+
return value
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def parse_config(
|
|
177
|
+
text: str,
|
|
178
|
+
*,
|
|
179
|
+
schema: str | None = None,
|
|
180
|
+
locale: str | None = None,
|
|
181
|
+
random_seed: int | None = None,
|
|
182
|
+
) -> SeedConfig:
|
|
183
|
+
"""Parse TOML and validate both the file and requested overrides."""
|
|
184
|
+
try:
|
|
185
|
+
data = tomllib.loads(text)
|
|
186
|
+
except tomllib.TOMLDecodeError:
|
|
187
|
+
raise ConfigError("Configuration is not valid TOML.") from None
|
|
188
|
+
config = _validate(data)
|
|
189
|
+
try:
|
|
190
|
+
return SeedConfig(
|
|
191
|
+
version=config.version,
|
|
192
|
+
database=DatabaseConfig.model_validate(
|
|
193
|
+
{
|
|
194
|
+
**config.database.model_dump(by_alias=True),
|
|
195
|
+
**({"schema": schema} if schema is not None else {}),
|
|
196
|
+
}
|
|
197
|
+
),
|
|
198
|
+
generation=GenerationConfig.model_validate(
|
|
199
|
+
{
|
|
200
|
+
**config.generation.model_dump(),
|
|
201
|
+
**({"locale": locale} if locale is not None else {}),
|
|
202
|
+
**({"random_seed": random_seed} if random_seed is not None else {}),
|
|
203
|
+
}
|
|
204
|
+
),
|
|
205
|
+
safety=config.safety,
|
|
206
|
+
tables=config.tables,
|
|
207
|
+
rules=config.rules,
|
|
208
|
+
)
|
|
209
|
+
except ValidationError as error:
|
|
210
|
+
raise _safe_validation_error(error) from None
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def load_config(
|
|
214
|
+
path: Path,
|
|
215
|
+
*,
|
|
216
|
+
schema: str | None = None,
|
|
217
|
+
locale: str | None = None,
|
|
218
|
+
random_seed: int | None = None,
|
|
219
|
+
) -> SeedConfig:
|
|
220
|
+
"""Read and validate a UTF-8 configuration file."""
|
|
221
|
+
try:
|
|
222
|
+
text = path.read_text(encoding="utf-8")
|
|
223
|
+
except (OSError, UnicodeError):
|
|
224
|
+
raise ConfigError("Could not read the UTF-8 configuration file.") from None
|
|
225
|
+
return parse_config(text, schema=schema, locale=locale, random_seed=random_seed)
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def resolve_database_url(config: SeedConfig, environ: Mapping[str, str] | None = None) -> str:
|
|
229
|
+
"""Resolve the explicitly named environment variable without displaying its value."""
|
|
230
|
+
values = os.environ if environ is None else environ
|
|
231
|
+
url = values.get(config.database.url_env, "")
|
|
232
|
+
if not url.strip():
|
|
233
|
+
raise ConfigError(
|
|
234
|
+
"The environment variable configured by database.url_env is missing or empty."
|
|
235
|
+
)
|
|
236
|
+
return url
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def _validate(data: object) -> SeedConfig:
|
|
240
|
+
try:
|
|
241
|
+
return SeedConfig.model_validate(data)
|
|
242
|
+
except ValidationError as error:
|
|
243
|
+
raise _safe_validation_error(error) from None
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def _safe_validation_error(error: ValidationError) -> ConfigError:
|
|
247
|
+
first = error.errors(include_input=False, include_context=False, include_url=False)[0]
|
|
248
|
+
root = first["loc"][0] if first["loc"] else ""
|
|
249
|
+
known_sections = {"version", "database", "generation", "safety", "tables", "rules"}
|
|
250
|
+
scope = f" in {root}" if isinstance(root, str) and root in known_sections else ""
|
|
251
|
+
return ConfigError(f"Invalid configuration field{scope}.")
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Dataset serializers and export file publication."""
|