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/exporting/files.py
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
"""Exclusive export directories and manifest publication."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
import stat
|
|
6
|
+
import sys
|
|
7
|
+
from collections.abc import Iterator
|
|
8
|
+
from contextlib import AbstractContextManager, contextmanager
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import TextIO
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class ExportFileError(Exception):
|
|
14
|
+
"""A filesystem failure safe to report to the caller."""
|
|
15
|
+
|
|
16
|
+
def __init__(self, code: str, message: str) -> None:
|
|
17
|
+
super().__init__(message)
|
|
18
|
+
self.code = code
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _identity(info: os.stat_result) -> tuple[int, int]:
|
|
22
|
+
return info.st_dev, info.st_ino
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class ExportDirectory:
|
|
26
|
+
"""Track directory and file ownership throughout one export."""
|
|
27
|
+
|
|
28
|
+
def __init__(self, path: Path) -> None:
|
|
29
|
+
self.path = path.absolute()
|
|
30
|
+
self._dir_fd: int | None = None
|
|
31
|
+
self._directory = _identity(self.path.lstat())
|
|
32
|
+
self._files: dict[str, tuple[int, int]] = {}
|
|
33
|
+
self._open: set[str] = set()
|
|
34
|
+
self.complete = False
|
|
35
|
+
self._check_directory()
|
|
36
|
+
if sys.platform != "win32":
|
|
37
|
+
self._dir_fd = os.open(self.path, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
|
|
38
|
+
if _identity(os.fstat(self._dir_fd)) != self._directory:
|
|
39
|
+
self.close()
|
|
40
|
+
raise OSError("Export directory changed.")
|
|
41
|
+
|
|
42
|
+
def _check_directory(self) -> None:
|
|
43
|
+
info = self.path.lstat()
|
|
44
|
+
if (
|
|
45
|
+
not stat.S_ISDIR(info.st_mode)
|
|
46
|
+
or getattr(info, "st_file_attributes", 0) & stat.FILE_ATTRIBUTE_REPARSE_POINT
|
|
47
|
+
or _identity(info) != self._directory
|
|
48
|
+
):
|
|
49
|
+
raise OSError("Export directory changed.")
|
|
50
|
+
|
|
51
|
+
def _entry(self, name: str) -> str | Path:
|
|
52
|
+
return name if self._dir_fd is not None else self.path / name
|
|
53
|
+
|
|
54
|
+
def _check_owned(self, name: str) -> None:
|
|
55
|
+
info = os.lstat(self._entry(name), dir_fd=self._dir_fd)
|
|
56
|
+
if not stat.S_ISREG(info.st_mode) or _identity(info) != self._files[name]:
|
|
57
|
+
raise OSError("Export file changed.")
|
|
58
|
+
|
|
59
|
+
def artifact(self, name: str) -> AbstractContextManager[TextIO]:
|
|
60
|
+
"""Open one generated basename exclusively."""
|
|
61
|
+
if name in {"manifest.json", "manifest-pending.json"}:
|
|
62
|
+
raise ValueError("Export manifest names are reserved.")
|
|
63
|
+
return self._artifact(name)
|
|
64
|
+
|
|
65
|
+
@contextmanager
|
|
66
|
+
def _artifact(self, name: str) -> Iterator[TextIO]:
|
|
67
|
+
if (
|
|
68
|
+
not name
|
|
69
|
+
or name.startswith(".")
|
|
70
|
+
or not all(char in "abcdefghijklmnopqrstuvwxyz0123456789-." for char in name)
|
|
71
|
+
or self.complete
|
|
72
|
+
):
|
|
73
|
+
raise ValueError("Invalid export artifact name.")
|
|
74
|
+
self._check_directory()
|
|
75
|
+
flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL
|
|
76
|
+
fd = os.open(self._entry(name), flags, 0o600, dir_fd=self._dir_fd)
|
|
77
|
+
try:
|
|
78
|
+
self._files[name] = _identity(os.fstat(fd))
|
|
79
|
+
self._open.add(name)
|
|
80
|
+
stream = os.fdopen(fd, "w", encoding="utf-8", newline="")
|
|
81
|
+
except BaseException:
|
|
82
|
+
os.close(fd)
|
|
83
|
+
raise
|
|
84
|
+
try:
|
|
85
|
+
with stream:
|
|
86
|
+
yield stream
|
|
87
|
+
finally:
|
|
88
|
+
self._open.remove(name)
|
|
89
|
+
|
|
90
|
+
def publish(self, manifest: dict[str, object]) -> None:
|
|
91
|
+
"""Make the completion marker visible after all artifacts close."""
|
|
92
|
+
if self._open or self.complete or "manifest.json" in self._files:
|
|
93
|
+
raise OSError("Export artifacts are incomplete.")
|
|
94
|
+
for name in self._files:
|
|
95
|
+
self._check_owned(name)
|
|
96
|
+
temporary = "manifest-pending.json"
|
|
97
|
+
with self._artifact(temporary) as stream:
|
|
98
|
+
json.dump(manifest, stream, ensure_ascii=False, separators=(",", ":"))
|
|
99
|
+
stream.write("\n")
|
|
100
|
+
self._check_directory()
|
|
101
|
+
self._check_owned(temporary)
|
|
102
|
+
destination = self._entry("manifest.json")
|
|
103
|
+
try:
|
|
104
|
+
os.lstat(destination, dir_fd=self._dir_fd)
|
|
105
|
+
except FileNotFoundError:
|
|
106
|
+
pass
|
|
107
|
+
else:
|
|
108
|
+
raise FileExistsError("Export manifest already exists.")
|
|
109
|
+
os.replace(
|
|
110
|
+
self._entry(temporary),
|
|
111
|
+
destination,
|
|
112
|
+
src_dir_fd=self._dir_fd,
|
|
113
|
+
dst_dir_fd=self._dir_fd,
|
|
114
|
+
)
|
|
115
|
+
self.complete = True
|
|
116
|
+
|
|
117
|
+
def clean_up(self) -> None:
|
|
118
|
+
"""Remove only owned entries and an empty, still-owned directory."""
|
|
119
|
+
if self._dir_fd is None:
|
|
120
|
+
try:
|
|
121
|
+
self._check_directory()
|
|
122
|
+
except OSError:
|
|
123
|
+
return
|
|
124
|
+
for name in self._files:
|
|
125
|
+
try:
|
|
126
|
+
self._check_owned(name)
|
|
127
|
+
os.unlink(self._entry(name), dir_fd=self._dir_fd)
|
|
128
|
+
except OSError:
|
|
129
|
+
continue
|
|
130
|
+
try:
|
|
131
|
+
self._check_directory()
|
|
132
|
+
self.path.rmdir()
|
|
133
|
+
except OSError:
|
|
134
|
+
pass
|
|
135
|
+
|
|
136
|
+
def close(self) -> None:
|
|
137
|
+
if self._dir_fd is not None:
|
|
138
|
+
os.close(self._dir_fd)
|
|
139
|
+
self._dir_fd = None
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
@contextmanager
|
|
143
|
+
def export_directory(path: Path) -> Iterator[ExportDirectory]:
|
|
144
|
+
"""Create a fresh output directory and clean it up on failure."""
|
|
145
|
+
try:
|
|
146
|
+
path.mkdir(mode=0o700)
|
|
147
|
+
except FileExistsError:
|
|
148
|
+
raise ExportFileError("OUTPUT_EXISTS", "The export destination already exists.") from None
|
|
149
|
+
except OSError:
|
|
150
|
+
raise ExportFileError("EXPORT_FAILED", "Could not create the export directory.") from None
|
|
151
|
+
directory = None
|
|
152
|
+
try:
|
|
153
|
+
directory = ExportDirectory(path)
|
|
154
|
+
yield directory
|
|
155
|
+
if not directory.complete:
|
|
156
|
+
raise OSError("Export did not publish a manifest.")
|
|
157
|
+
except (OSError, UnicodeError):
|
|
158
|
+
raise ExportFileError("EXPORT_FAILED", "Could not finish writing the export.") from None
|
|
159
|
+
finally:
|
|
160
|
+
if directory is not None:
|
|
161
|
+
try:
|
|
162
|
+
if not directory.complete:
|
|
163
|
+
directory.clean_up()
|
|
164
|
+
finally:
|
|
165
|
+
directory.close()
|
seed/exporting/sql.py
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
"""Stream supported PostgreSQL INSERT statements with typed synthetic values."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Iterable
|
|
4
|
+
from typing import TextIO
|
|
5
|
+
|
|
6
|
+
from psycopg.sql import Identifier
|
|
7
|
+
|
|
8
|
+
from seed.generation.streaming import GeneratedRecord, Value
|
|
9
|
+
from seed.metadata import ColumnType, TableSchema
|
|
10
|
+
from seed.reporting.dataset import json_value
|
|
11
|
+
|
|
12
|
+
type SqlRows = tuple[TableSchema, Iterable[GeneratedRecord]]
|
|
13
|
+
|
|
14
|
+
_TYPES = {
|
|
15
|
+
"bigint": "int8",
|
|
16
|
+
"boolean": "bool",
|
|
17
|
+
"date": "date",
|
|
18
|
+
"decimal": "numeric",
|
|
19
|
+
"integer": "int4",
|
|
20
|
+
"numeric": "numeric",
|
|
21
|
+
"smallint": "int2",
|
|
22
|
+
"text": "text",
|
|
23
|
+
"uuid": "uuid",
|
|
24
|
+
"varchar": "varchar",
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _type_name(column: ColumnType) -> str:
|
|
29
|
+
if column.name == "enum" and column.type_schema and column.type_name:
|
|
30
|
+
return Identifier(column.type_schema, column.type_name).as_string()
|
|
31
|
+
if column.name == "timestamp":
|
|
32
|
+
return "pg_catalog.timestamptz" if column.timezone else "pg_catalog.timestamp"
|
|
33
|
+
return "pg_catalog." + _TYPES[column.name]
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _literal(value: Value, column: ColumnType, type_name: str) -> str:
|
|
37
|
+
if value is None:
|
|
38
|
+
return "NULL"
|
|
39
|
+
encoded = json_value(value, column.name)
|
|
40
|
+
if isinstance(encoded, bool):
|
|
41
|
+
text = str(encoded).lower()
|
|
42
|
+
else:
|
|
43
|
+
text = str(encoded)
|
|
44
|
+
# Escape controls so a value cannot introduce a physical psql command line.
|
|
45
|
+
quoted = "".join(
|
|
46
|
+
"''"
|
|
47
|
+
if char == "'"
|
|
48
|
+
else "\\\\"
|
|
49
|
+
if char == "\\"
|
|
50
|
+
else f"\\x{ord(char):02x}"
|
|
51
|
+
if ord(char) < 32 or ord(char) == 127
|
|
52
|
+
else char
|
|
53
|
+
for char in text
|
|
54
|
+
)
|
|
55
|
+
return f"E'{quoted}'::{type_name}"
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def write_sql(output: TextIO, tables: Iterable[SqlRows]) -> None:
|
|
59
|
+
"""Write one transaction for a matching, empty PostgreSQL schema."""
|
|
60
|
+
output.write(
|
|
61
|
+
"BEGIN;\n"
|
|
62
|
+
"SET LOCAL client_encoding TO 'UTF8';\n"
|
|
63
|
+
"SET LOCAL standard_conforming_strings TO on;\n"
|
|
64
|
+
"SET LOCAL search_path TO pg_catalog;\n"
|
|
65
|
+
)
|
|
66
|
+
for table, rows in tables:
|
|
67
|
+
columns = tuple(column for column in table.columns if column.generated is None)
|
|
68
|
+
for row_index, record in enumerate(rows):
|
|
69
|
+
if row_index == 0:
|
|
70
|
+
relation = Identifier(table.id.schema_name, table.id.table).as_string()
|
|
71
|
+
names = ", ".join(Identifier(column.name).as_string() for column in columns)
|
|
72
|
+
types = tuple(_type_name(column.type) for column in columns)
|
|
73
|
+
override = (
|
|
74
|
+
" OVERRIDING SYSTEM VALUE"
|
|
75
|
+
if any(column.identity == "always" for column in columns)
|
|
76
|
+
else ""
|
|
77
|
+
)
|
|
78
|
+
prefix = f"INSERT INTO {relation} ({names}){override} VALUES ("
|
|
79
|
+
values = ", ".join(
|
|
80
|
+
_literal(record.values[column.name], column.type, type_name)
|
|
81
|
+
for column, type_name in zip(columns, types, strict=True)
|
|
82
|
+
)
|
|
83
|
+
output.write(prefix + values + ");\n")
|
|
84
|
+
output.write("COMMIT;\n")
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
"""Stream versioned JSON and PostgreSQL-compatible CSV tabular exports."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
from collections.abc import Iterable
|
|
5
|
+
from typing import TextIO
|
|
6
|
+
|
|
7
|
+
from seed.generation.streaming import GeneratedRecord
|
|
8
|
+
from seed.metadata import TableId
|
|
9
|
+
from seed.reporting.dataset import DatasetColumn, JsonValue, dataset_header, dataset_row
|
|
10
|
+
|
|
11
|
+
type TabularRows = tuple[TableId, tuple[DatasetColumn, ...], Iterable[GeneratedRecord]]
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _csv_field(value: JsonValue) -> str:
|
|
15
|
+
if value is None:
|
|
16
|
+
return ""
|
|
17
|
+
text = str(value).lower() if isinstance(value, bool) else str(value)
|
|
18
|
+
return '"' + text.replace('"', '""') + '"'
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def write_csv(
|
|
22
|
+
output: TextIO,
|
|
23
|
+
columns: tuple[DatasetColumn, ...],
|
|
24
|
+
rows: Iterable[GeneratedRecord],
|
|
25
|
+
) -> None:
|
|
26
|
+
"""Write a header and quote every non-null cell, preserving embedded LF and CR."""
|
|
27
|
+
output.write(",".join(_csv_field(column.name) for column in columns) + "\n")
|
|
28
|
+
for record in rows:
|
|
29
|
+
output.write(",".join(_csv_field(value) for value in dataset_row(record, columns)) + "\n")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def write_json(output: TextIO, tables: Iterable[TabularRows]) -> None:
|
|
33
|
+
"""Write one JSON document with positional rows and no whole-table buffering."""
|
|
34
|
+
encoder = json.JSONEncoder(ensure_ascii=False, separators=(",", ":"))
|
|
35
|
+
output.write('{"version":1,"tables":[')
|
|
36
|
+
for table_index, (table, columns, rows) in enumerate(tables):
|
|
37
|
+
if table_index:
|
|
38
|
+
output.write(",")
|
|
39
|
+
output.write(encoder.encode(dataset_header(table, columns))[:-1])
|
|
40
|
+
output.write(',"rows":[')
|
|
41
|
+
for row_index, record in enumerate(rows):
|
|
42
|
+
if row_index:
|
|
43
|
+
output.write(",")
|
|
44
|
+
output.write(encoder.encode(dataset_row(record, columns)))
|
|
45
|
+
output.write("]}")
|
|
46
|
+
output.write("]}\n")
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Deterministic record generation and constraint checks."""
|
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
"""Stream planned offline records without accessing a database."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Callable, Iterator
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
from functools import partial
|
|
6
|
+
|
|
7
|
+
from seed.config import GeneratorRule, SeedConfig
|
|
8
|
+
from seed.generation.record_checks import UniqueReservations, scalar_domain, value_matches
|
|
9
|
+
from seed.generation.relationships import ExistingKeys, ForeignKeys, ParentPools
|
|
10
|
+
from seed.generation.scalars import scalar_value
|
|
11
|
+
from seed.generation.streaming import (
|
|
12
|
+
GeneratedRecord,
|
|
13
|
+
GenerationError,
|
|
14
|
+
RecordBatch,
|
|
15
|
+
RunContext,
|
|
16
|
+
Value,
|
|
17
|
+
batches,
|
|
18
|
+
retry_row,
|
|
19
|
+
validate_batch_size,
|
|
20
|
+
)
|
|
21
|
+
from seed.metadata import ColumnSchema, DatabaseSchema, NumericBound, TableSchema
|
|
22
|
+
from seed.planning.bindings import Binding, choose_binding
|
|
23
|
+
from seed.planning.plan import GenerationPlan, Mode, PlanIssue, PlannedTable
|
|
24
|
+
from seed.planning.selection import MAX_ROWS
|
|
25
|
+
|
|
26
|
+
type InsertBatch = Callable[[TableSchema, RecordBatch, tuple[str, ...]], RecordBatch]
|
|
27
|
+
type ConflictProbe = Callable[[TableSchema, dict[str, Value]], bool]
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass(frozen=True)
|
|
31
|
+
class LiveInputs:
|
|
32
|
+
insert: InsertBatch
|
|
33
|
+
existing: ExistingKeys | None = None
|
|
34
|
+
conflicts: ConflictProbe | None = None
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@dataclass(frozen=True)
|
|
38
|
+
class _Column:
|
|
39
|
+
binding: Binding
|
|
40
|
+
schema: ColumnSchema
|
|
41
|
+
rule: GeneratorRule | None
|
|
42
|
+
bounds: tuple[NumericBound, ...]
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def generate_batches(
|
|
46
|
+
plan: GenerationPlan,
|
|
47
|
+
schema: DatabaseSchema,
|
|
48
|
+
config: SeedConfig,
|
|
49
|
+
*,
|
|
50
|
+
batch_size: int | None = None,
|
|
51
|
+
) -> Iterator[RecordBatch]:
|
|
52
|
+
"""Generate the planned records in deterministic, bounded single-table batches."""
|
|
53
|
+
yield from _generate(plan, schema, config, "offline", batch_size, None)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def generate_live_batches(
|
|
57
|
+
plan: GenerationPlan,
|
|
58
|
+
schema: DatabaseSchema,
|
|
59
|
+
config: SeedConfig,
|
|
60
|
+
inputs: LiveInputs,
|
|
61
|
+
) -> Iterator[RecordBatch]:
|
|
62
|
+
"""Generate live rows and correlate the committed-to-transaction batch from the adapter."""
|
|
63
|
+
yield from _generate(plan, schema, config, "live", None, inputs)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _generate(
|
|
67
|
+
plan: GenerationPlan,
|
|
68
|
+
schema: DatabaseSchema,
|
|
69
|
+
config: SeedConfig,
|
|
70
|
+
mode: Mode,
|
|
71
|
+
batch_size: int | None,
|
|
72
|
+
inputs: LiveInputs | None,
|
|
73
|
+
) -> Iterator[RecordBatch]:
|
|
74
|
+
if (
|
|
75
|
+
plan.schema_fingerprint != schema.fingerprint
|
|
76
|
+
or plan.target != schema.target
|
|
77
|
+
or not 0 <= plan.total_rows <= MAX_ROWS
|
|
78
|
+
or any(table.rows < 0 for table in plan.tables)
|
|
79
|
+
or sum(table.rows for table in plan.tables) != plan.total_rows
|
|
80
|
+
):
|
|
81
|
+
raise GenerationError(
|
|
82
|
+
PlanIssue(
|
|
83
|
+
code="INVALID_PLAN",
|
|
84
|
+
message="The plan does not match the supplied schema or row limits.",
|
|
85
|
+
)
|
|
86
|
+
)
|
|
87
|
+
compatibility = plan.compatibility.get(mode)
|
|
88
|
+
if compatibility is None or not compatibility.executable:
|
|
89
|
+
raise GenerationError(
|
|
90
|
+
PlanIssue(
|
|
91
|
+
code="PLAN_BLOCKED",
|
|
92
|
+
message=f"This plan cannot generate {mode} records.",
|
|
93
|
+
)
|
|
94
|
+
)
|
|
95
|
+
size = plan.settings.batch_size if batch_size is None else batch_size
|
|
96
|
+
validate_batch_size(size)
|
|
97
|
+
yield from _table_batches(plan, schema, config, size, mode, inputs)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _table_batches(
|
|
101
|
+
plan: GenerationPlan,
|
|
102
|
+
schema: DatabaseSchema,
|
|
103
|
+
config: SeedConfig,
|
|
104
|
+
size: int,
|
|
105
|
+
mode: Mode,
|
|
106
|
+
inputs: LiveInputs | None,
|
|
107
|
+
) -> Iterator[RecordBatch]:
|
|
108
|
+
tables = {table.id: table for table in schema.tables}
|
|
109
|
+
pools = ParentPools(plan, inputs.existing if inputs else None)
|
|
110
|
+
for planned in plan.tables:
|
|
111
|
+
if not planned.rows:
|
|
112
|
+
continue
|
|
113
|
+
table = tables.get(planned.id)
|
|
114
|
+
if table is None:
|
|
115
|
+
raise _binding_error(planned)
|
|
116
|
+
columns = _prepare_columns(planned, table, config, plan.settings.locale, mode)
|
|
117
|
+
identities = tuple(
|
|
118
|
+
item.binding.column for item in columns if item.binding.source == "server_identity"
|
|
119
|
+
)
|
|
120
|
+
identity_columns = {item.binding.column: item.schema for item in columns}
|
|
121
|
+
pending = frozenset(identities)
|
|
122
|
+
writable = tuple(item for item in columns if item.binding.column not in pending)
|
|
123
|
+
context = RunContext(plan.settings, planned.id)
|
|
124
|
+
conflicts = inputs.conflicts if inputs else None
|
|
125
|
+
foreign = ForeignKeys.prepare(planned, table, pools, context)
|
|
126
|
+
uniqueness = UniqueReservations.for_table(
|
|
127
|
+
table,
|
|
128
|
+
config.rules.get(table.id.table, {}),
|
|
129
|
+
pending=pending,
|
|
130
|
+
)
|
|
131
|
+
domains = {
|
|
132
|
+
item.binding.column: scalar_domain(
|
|
133
|
+
item.schema,
|
|
134
|
+
item.binding.source,
|
|
135
|
+
item.binding.generator,
|
|
136
|
+
item.rule,
|
|
137
|
+
item.bounds,
|
|
138
|
+
context.settings.null_rate,
|
|
139
|
+
planned.rows,
|
|
140
|
+
)
|
|
141
|
+
for item in writable
|
|
142
|
+
}
|
|
143
|
+
uniqueness.check_capacity(planned.id, domains, planned.rows)
|
|
144
|
+
|
|
145
|
+
def draw(ordinal: int) -> GeneratedRecord | None:
|
|
146
|
+
keys = foreign.draw()
|
|
147
|
+
if keys is None:
|
|
148
|
+
return None
|
|
149
|
+
values = _candidate(writable, context, ordinal, keys)
|
|
150
|
+
if (
|
|
151
|
+
any(
|
|
152
|
+
not value_matches(
|
|
153
|
+
values[item.binding.column], item.schema, item.bounds, item.rule
|
|
154
|
+
)
|
|
155
|
+
for item in writable
|
|
156
|
+
)
|
|
157
|
+
or not foreign.contains(values)
|
|
158
|
+
or (
|
|
159
|
+
table.primary_key
|
|
160
|
+
and any(
|
|
161
|
+
values[key] is None
|
|
162
|
+
for key in table.primary_key.columns
|
|
163
|
+
if key not in pending
|
|
164
|
+
)
|
|
165
|
+
)
|
|
166
|
+
or (conflicts is not None and conflicts(table, values))
|
|
167
|
+
or not uniqueness.reserve(values)
|
|
168
|
+
):
|
|
169
|
+
return None
|
|
170
|
+
return GeneratedRecord(planned.id, ordinal, values)
|
|
171
|
+
|
|
172
|
+
def accepted_rows() -> Iterator[GeneratedRecord]:
|
|
173
|
+
for ordinal in range(planned.rows):
|
|
174
|
+
record = retry_row(planned.id, ordinal, partial(draw, ordinal))
|
|
175
|
+
foreign.accept(record.values)
|
|
176
|
+
yield record
|
|
177
|
+
|
|
178
|
+
for batch in batches(accepted_rows(), size):
|
|
179
|
+
completed = inputs.insert(table, batch, identities) if inputs is not None else batch
|
|
180
|
+
if len(completed) != len(batch):
|
|
181
|
+
raise _binding_error(planned)
|
|
182
|
+
for original, record in zip(batch, completed, strict=True):
|
|
183
|
+
if (
|
|
184
|
+
record.table != original.table
|
|
185
|
+
or record.ordinal != original.ordinal
|
|
186
|
+
or any(
|
|
187
|
+
name not in record.values
|
|
188
|
+
or record.values[name] is None
|
|
189
|
+
or not value_matches(record.values[name], identity_columns[name], (), None)
|
|
190
|
+
for name in identities
|
|
191
|
+
)
|
|
192
|
+
):
|
|
193
|
+
raise _binding_error(planned)
|
|
194
|
+
pools.accept(record)
|
|
195
|
+
yield completed
|
|
196
|
+
pools.finish(planned)
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def _prepare_columns(
|
|
200
|
+
planned: PlannedTable,
|
|
201
|
+
table: TableSchema,
|
|
202
|
+
config: SeedConfig,
|
|
203
|
+
locale: str,
|
|
204
|
+
mode: Mode,
|
|
205
|
+
) -> tuple[_Column, ...]:
|
|
206
|
+
rules = config.rules.get(table.id.table, {})
|
|
207
|
+
columns = {column.name: column for column in table.columns}
|
|
208
|
+
bindings = planned.bindings.get(mode)
|
|
209
|
+
if bindings is None or tuple(binding.column for binding in bindings) != tuple(columns):
|
|
210
|
+
raise _binding_error(planned)
|
|
211
|
+
if rules.keys() - columns.keys():
|
|
212
|
+
raise _binding_error(planned)
|
|
213
|
+
result: list[_Column] = []
|
|
214
|
+
for binding in bindings:
|
|
215
|
+
column = columns[binding.column]
|
|
216
|
+
rule = rules.get(binding.column)
|
|
217
|
+
bounds = tuple(
|
|
218
|
+
bound for check in table.checks for bound in check.bounds if bound.column == column.name
|
|
219
|
+
)
|
|
220
|
+
if binding.source == "generator":
|
|
221
|
+
expected, compatible = choose_binding(column, rule, locale, bounds)
|
|
222
|
+
if not compatible or binding != expected:
|
|
223
|
+
raise _binding_error(planned, column.name)
|
|
224
|
+
elif rule is not None:
|
|
225
|
+
raise _binding_error(planned, column.name)
|
|
226
|
+
if binding.source != "omit":
|
|
227
|
+
result.append(_Column(binding, column, rule, bounds))
|
|
228
|
+
return tuple(result)
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def _candidate(
|
|
232
|
+
columns: tuple[_Column, ...],
|
|
233
|
+
context: RunContext,
|
|
234
|
+
ordinal: int,
|
|
235
|
+
keys: dict[str, Value],
|
|
236
|
+
) -> dict[str, Value]:
|
|
237
|
+
values: dict[str, Value] = {}
|
|
238
|
+
for item in columns:
|
|
239
|
+
binding = item.binding
|
|
240
|
+
if binding.source in {"foreign_key", "null"}:
|
|
241
|
+
values[binding.column] = keys[binding.column]
|
|
242
|
+
elif binding.source == "explicit_identity":
|
|
243
|
+
values[binding.column] = ordinal + 1
|
|
244
|
+
else:
|
|
245
|
+
assert binding.generator is not None
|
|
246
|
+
values[binding.column] = scalar_value(
|
|
247
|
+
context, item.schema, binding.generator, item.rule, item.bounds
|
|
248
|
+
)
|
|
249
|
+
return values
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def _binding_error(planned: PlannedTable, column: str | None = None) -> GenerationError:
|
|
253
|
+
return GenerationError(
|
|
254
|
+
PlanIssue(
|
|
255
|
+
code="INVALID_PLAN_BINDING",
|
|
256
|
+
message="A planned binding does not match generation inputs.",
|
|
257
|
+
table=planned.id,
|
|
258
|
+
column=column,
|
|
259
|
+
)
|
|
260
|
+
)
|