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
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
"""Validate candidate values and reserve uniqueness only for accepted rows."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass, field
|
|
4
|
+
from decimal import Decimal
|
|
5
|
+
from math import prod
|
|
6
|
+
from uuid import UUID
|
|
7
|
+
|
|
8
|
+
from seed.config import GeneratorRule, Scalar
|
|
9
|
+
from seed.generation.relationships import KeyTuple
|
|
10
|
+
from seed.generation.streaming import GenerationError, Value
|
|
11
|
+
from seed.metadata import ColumnSchema, NumericBound, TableId, TableSchema
|
|
12
|
+
from seed.planning.bindings import compatible_value
|
|
13
|
+
from seed.planning.numeric import numeric_grid
|
|
14
|
+
from seed.planning.plan import PlanIssue
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass(frozen=True)
|
|
18
|
+
class UniqueRule:
|
|
19
|
+
name: str
|
|
20
|
+
columns: tuple[str, ...]
|
|
21
|
+
nulls_distinct: bool
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass(frozen=True)
|
|
25
|
+
class Domain:
|
|
26
|
+
"""An upper bound on non-null candidates and whether null can be emitted."""
|
|
27
|
+
|
|
28
|
+
capacity: int | None
|
|
29
|
+
nullable: bool
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def value_matches(
|
|
33
|
+
value: Value,
|
|
34
|
+
column: ColumnSchema,
|
|
35
|
+
bounds: tuple[NumericBound, ...],
|
|
36
|
+
rule: GeneratorRule | None,
|
|
37
|
+
) -> bool:
|
|
38
|
+
"""Check the typed value and configured numeric interval."""
|
|
39
|
+
if value is None:
|
|
40
|
+
return column.nullable
|
|
41
|
+
kind = column.type.name
|
|
42
|
+
converted: Scalar
|
|
43
|
+
if isinstance(value, Decimal):
|
|
44
|
+
if kind != "numeric" or not value.is_finite():
|
|
45
|
+
return False
|
|
46
|
+
converted = str(value)
|
|
47
|
+
elif isinstance(value, UUID):
|
|
48
|
+
if kind != "uuid":
|
|
49
|
+
return False
|
|
50
|
+
converted = str(value)
|
|
51
|
+
else:
|
|
52
|
+
if kind in {"numeric", "uuid"}:
|
|
53
|
+
return False
|
|
54
|
+
converted = value
|
|
55
|
+
if not compatible_value(converted, column, bounds):
|
|
56
|
+
return False
|
|
57
|
+
if rule and (rule.min is not None or rule.max is not None):
|
|
58
|
+
number = Decimal(str(value))
|
|
59
|
+
return not (
|
|
60
|
+
(rule.min is not None and number < Decimal(rule.min))
|
|
61
|
+
or (rule.max is not None and number > Decimal(rule.max))
|
|
62
|
+
)
|
|
63
|
+
return True
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def scalar_domain(
|
|
67
|
+
column: ColumnSchema,
|
|
68
|
+
source: str,
|
|
69
|
+
generator: str | None,
|
|
70
|
+
rule: GeneratorRule | None,
|
|
71
|
+
bounds: tuple[NumericBound, ...],
|
|
72
|
+
null_rate: float,
|
|
73
|
+
rows: int,
|
|
74
|
+
) -> Domain:
|
|
75
|
+
"""Bound common finite generator domains for early exhaustion checks."""
|
|
76
|
+
if source == "explicit_identity":
|
|
77
|
+
return Domain(rows, False)
|
|
78
|
+
if source == "null":
|
|
79
|
+
return Domain(0, True)
|
|
80
|
+
if source != "generator":
|
|
81
|
+
return Domain(None, column.nullable)
|
|
82
|
+
if rule and rule.null_rate is not None:
|
|
83
|
+
null_rate = rule.null_rate
|
|
84
|
+
emits_null = column.nullable and null_rate > 0
|
|
85
|
+
if emits_null and null_rate == 1:
|
|
86
|
+
return Domain(0, True)
|
|
87
|
+
capacity: int | None = None
|
|
88
|
+
if rule and rule.generator in {"constant", "choice"}:
|
|
89
|
+
capacity = len(rule.values) if rule.values is not None else 1
|
|
90
|
+
elif generator == "choice":
|
|
91
|
+
capacity = len(column.type.enum_labels)
|
|
92
|
+
elif generator == "boolean":
|
|
93
|
+
capacity = 2
|
|
94
|
+
elif generator == "phone":
|
|
95
|
+
capacity = 100
|
|
96
|
+
elif generator in {"integer", "decimal"}:
|
|
97
|
+
grid = numeric_grid(column, rule, bounds)
|
|
98
|
+
capacity = 0 if grid is None else grid.last - grid.first + 1
|
|
99
|
+
elif generator == "date":
|
|
100
|
+
capacity = 366
|
|
101
|
+
elif column.type.length is not None:
|
|
102
|
+
width = column.type.length
|
|
103
|
+
if generator == "email":
|
|
104
|
+
capacity = 36 ** min(16, width - len("@example.com"))
|
|
105
|
+
elif generator == "text":
|
|
106
|
+
capacity = 36 ** min(24, width)
|
|
107
|
+
return Domain(capacity, emits_null)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
@dataclass
|
|
111
|
+
class UniqueReservations:
|
|
112
|
+
"""Record keys from accepted rows, with PostgreSQL null semantics."""
|
|
113
|
+
|
|
114
|
+
rules: tuple[UniqueRule, ...]
|
|
115
|
+
seen: tuple[set[KeyTuple], ...] = field(init=False, repr=False)
|
|
116
|
+
|
|
117
|
+
def __post_init__(self) -> None:
|
|
118
|
+
self.seen = tuple(set() for _ in self.rules)
|
|
119
|
+
|
|
120
|
+
@classmethod
|
|
121
|
+
def for_table(
|
|
122
|
+
cls,
|
|
123
|
+
table: TableSchema,
|
|
124
|
+
configured: dict[str, GeneratorRule],
|
|
125
|
+
*,
|
|
126
|
+
pending: frozenset[str] = frozenset(),
|
|
127
|
+
) -> "UniqueReservations":
|
|
128
|
+
rules: list[UniqueRule] = []
|
|
129
|
+
if table.primary_key is not None:
|
|
130
|
+
key = table.primary_key
|
|
131
|
+
rules.append(UniqueRule(key.name, key.columns, False))
|
|
132
|
+
rules.extend(
|
|
133
|
+
UniqueRule(key.name, key.columns, bool(key.nulls_distinct))
|
|
134
|
+
for key in table.unique_keys
|
|
135
|
+
if key.supported is True
|
|
136
|
+
)
|
|
137
|
+
rules.extend(
|
|
138
|
+
UniqueRule(column, (column,), True)
|
|
139
|
+
for column, rule in configured.items()
|
|
140
|
+
if rule.unique
|
|
141
|
+
)
|
|
142
|
+
return cls(tuple(rule for rule in rules if pending.isdisjoint(rule.columns)))
|
|
143
|
+
|
|
144
|
+
def check_capacity(self, table: TableId, domains: dict[str, Domain], rows: int) -> None:
|
|
145
|
+
"""Refuse a finite unique domain that provably cannot satisfy the request."""
|
|
146
|
+
for rule in self.rules:
|
|
147
|
+
sizes: list[int] = []
|
|
148
|
+
for name in rule.columns:
|
|
149
|
+
domain = domains.get(name)
|
|
150
|
+
if (
|
|
151
|
+
domain is None
|
|
152
|
+
or domain.capacity is None
|
|
153
|
+
or (domain.nullable and rule.nulls_distinct)
|
|
154
|
+
):
|
|
155
|
+
break
|
|
156
|
+
sizes.append(min(rows, domain.capacity + int(domain.nullable)))
|
|
157
|
+
else:
|
|
158
|
+
if prod(sizes) < rows:
|
|
159
|
+
raise GenerationError(
|
|
160
|
+
PlanIssue(
|
|
161
|
+
code="DOMAIN_EXHAUSTED",
|
|
162
|
+
message="A unique key domain cannot satisfy the planned row count.",
|
|
163
|
+
table=table,
|
|
164
|
+
constraint=rule.name,
|
|
165
|
+
)
|
|
166
|
+
)
|
|
167
|
+
|
|
168
|
+
def reserve(self, values: dict[str, Value]) -> bool:
|
|
169
|
+
"""Reserve every participating tuple together after checking for collisions."""
|
|
170
|
+
candidates: list[tuple[set[KeyTuple], KeyTuple]] = []
|
|
171
|
+
for rule, seen in zip(self.rules, self.seen, strict=True):
|
|
172
|
+
key = tuple(values[name] for name in rule.columns)
|
|
173
|
+
if rule.nulls_distinct and None in key:
|
|
174
|
+
continue
|
|
175
|
+
if key in seen:
|
|
176
|
+
return False
|
|
177
|
+
candidates.append((seen, key))
|
|
178
|
+
for seen, key in candidates:
|
|
179
|
+
seen.add(key)
|
|
180
|
+
return True
|
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
"""Retain and consume only the parent keys required by the plan."""
|
|
2
|
+
|
|
3
|
+
from collections import Counter, defaultdict
|
|
4
|
+
from collections.abc import Callable, Iterable
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
from itertools import islice
|
|
7
|
+
|
|
8
|
+
from seed.generation.streaming import GeneratedRecord, GenerationError, RunContext, Value
|
|
9
|
+
from seed.metadata import TableId, TableSchema
|
|
10
|
+
from seed.planning.plan import GenerationPlan, PlanIssue, PlannedDependency, PlannedTable
|
|
11
|
+
|
|
12
|
+
type KeyTuple = tuple[Value, ...]
|
|
13
|
+
type PoolId = tuple[TableId, tuple[str, ...]]
|
|
14
|
+
type ExistingKeys = Callable[[PlannedDependency], Iterable[KeyTuple]]
|
|
15
|
+
MAX_EXISTING_KEYS = 10_000
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _pool_id(edge: PlannedDependency) -> PoolId:
|
|
19
|
+
return edge.foreign_key.parent, edge.foreign_key.parent_columns
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass
|
|
23
|
+
class KeyPool:
|
|
24
|
+
values: list[KeyTuple] = field(default_factory=list)
|
|
25
|
+
members: set[KeyTuple] = field(default_factory=set)
|
|
26
|
+
|
|
27
|
+
def add(self, values: KeyTuple) -> None:
|
|
28
|
+
if None not in values and values not in self.members:
|
|
29
|
+
self.values.append(values)
|
|
30
|
+
self.members.add(values)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class ParentPools:
|
|
34
|
+
"""Own referenced key tuples for an entire run."""
|
|
35
|
+
|
|
36
|
+
def __init__(self, plan: GenerationPlan, existing: ExistingKeys | None = None) -> None:
|
|
37
|
+
edges = [
|
|
38
|
+
edge
|
|
39
|
+
for table in plan.tables
|
|
40
|
+
if table.rows
|
|
41
|
+
for edge in table.dependencies
|
|
42
|
+
if edge.source in {"generated", "existing"}
|
|
43
|
+
]
|
|
44
|
+
self._remaining = Counter(_pool_id(edge) for edge in edges)
|
|
45
|
+
self._retained: dict[TableId, dict[tuple[str, ...], KeyPool]] = defaultdict(dict)
|
|
46
|
+
for edge in edges:
|
|
47
|
+
parent, columns = _pool_id(edge)
|
|
48
|
+
if columns in self._retained[parent]:
|
|
49
|
+
continue
|
|
50
|
+
pool = KeyPool()
|
|
51
|
+
if edge.source == "existing":
|
|
52
|
+
if existing is None:
|
|
53
|
+
raise GenerationError(
|
|
54
|
+
PlanIssue(
|
|
55
|
+
code="PARENT_KEYS_EXHAUSTED",
|
|
56
|
+
message="No existing parent key source is available.",
|
|
57
|
+
table=parent,
|
|
58
|
+
)
|
|
59
|
+
)
|
|
60
|
+
for values in islice(existing(edge), MAX_EXISTING_KEYS):
|
|
61
|
+
pool.add(values)
|
|
62
|
+
if not pool.values:
|
|
63
|
+
raise GenerationError(
|
|
64
|
+
PlanIssue(
|
|
65
|
+
code="PARENT_KEYS_EXHAUSTED",
|
|
66
|
+
message="The existing parent key pool is empty.",
|
|
67
|
+
table=parent,
|
|
68
|
+
constraint=edge.foreign_key.name,
|
|
69
|
+
)
|
|
70
|
+
)
|
|
71
|
+
self._retained[parent][columns] = pool
|
|
72
|
+
|
|
73
|
+
def accept(self, record: GeneratedRecord) -> None:
|
|
74
|
+
"""Register the accepted record's non-null referenced tuples."""
|
|
75
|
+
for columns, pool in self._retained.get(record.table, {}).items():
|
|
76
|
+
pool.add(tuple(record.values.get(column) for column in columns))
|
|
77
|
+
|
|
78
|
+
def for_edge(self, edge: PlannedDependency) -> KeyPool:
|
|
79
|
+
table, columns = _pool_id(edge)
|
|
80
|
+
return self._retained[table][columns]
|
|
81
|
+
|
|
82
|
+
def finish(self, table: PlannedTable) -> None:
|
|
83
|
+
"""Release pools whose last consumer has finished."""
|
|
84
|
+
for edge in table.dependencies:
|
|
85
|
+
if edge.source in {"generated", "existing"}:
|
|
86
|
+
key = _pool_id(edge)
|
|
87
|
+
self._remaining[key] -= 1
|
|
88
|
+
if self._remaining[key] == 0:
|
|
89
|
+
del self._retained[key[0]][key[1]]
|
|
90
|
+
del self._remaining[key]
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
@dataclass
|
|
94
|
+
class _Available:
|
|
95
|
+
values: list[KeyTuple]
|
|
96
|
+
positions: dict[KeyTuple, int]
|
|
97
|
+
|
|
98
|
+
@classmethod
|
|
99
|
+
def from_pool(cls, pool: KeyPool) -> "_Available":
|
|
100
|
+
return cls(list(pool.values), {value: index for index, value in enumerate(pool.values)})
|
|
101
|
+
|
|
102
|
+
def take(self, key: KeyTuple) -> None:
|
|
103
|
+
index = self.positions.pop(key)
|
|
104
|
+
last = self.values.pop()
|
|
105
|
+
if index < len(self.values):
|
|
106
|
+
self.values[index] = last
|
|
107
|
+
self.positions[last] = index
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
@dataclass
|
|
111
|
+
class ForeignKeys:
|
|
112
|
+
"""Draw complete tuples and reserve one-to-one keys only after row acceptance."""
|
|
113
|
+
|
|
114
|
+
context: RunContext
|
|
115
|
+
dependencies: tuple[PlannedDependency, ...]
|
|
116
|
+
nullable: frozenset[str]
|
|
117
|
+
pools: ParentPools
|
|
118
|
+
available: dict[str, _Available] = field(default_factory=dict)
|
|
119
|
+
|
|
120
|
+
@classmethod
|
|
121
|
+
def prepare(
|
|
122
|
+
cls,
|
|
123
|
+
table: PlannedTable,
|
|
124
|
+
metadata: TableSchema,
|
|
125
|
+
pools: ParentPools,
|
|
126
|
+
context: RunContext,
|
|
127
|
+
) -> "ForeignKeys":
|
|
128
|
+
nullable = frozenset(column.name for column in metadata.columns if column.nullable)
|
|
129
|
+
state = cls(context, table.dependencies, nullable, pools)
|
|
130
|
+
unique_keys: dict[frozenset[str], bool] = {}
|
|
131
|
+
for unique_key in metadata.unique_keys:
|
|
132
|
+
if unique_key.supported is True:
|
|
133
|
+
columns = frozenset(unique_key.columns)
|
|
134
|
+
unique_keys[columns] = unique_keys.get(columns, True) and bool(
|
|
135
|
+
unique_key.nulls_distinct
|
|
136
|
+
)
|
|
137
|
+
if metadata.primary_key:
|
|
138
|
+
unique_keys[frozenset(metadata.primary_key.columns)] = False
|
|
139
|
+
for edge in table.dependencies:
|
|
140
|
+
key = edge.foreign_key
|
|
141
|
+
if edge.source == "null":
|
|
142
|
+
continue
|
|
143
|
+
if edge.source not in {"generated", "existing"}:
|
|
144
|
+
raise state._error(key.name, "No parent key source is available.")
|
|
145
|
+
pool = pools.for_edge(edge)
|
|
146
|
+
if not pool.values:
|
|
147
|
+
raise state._error(key.name, "The parent key pool is empty.")
|
|
148
|
+
columns = frozenset(key.columns)
|
|
149
|
+
if columns in unique_keys:
|
|
150
|
+
null_allowed = state._allows_null(edge)
|
|
151
|
+
if not (null_allowed and unique_keys[columns]):
|
|
152
|
+
capacity = len(pool.values) + int(null_allowed)
|
|
153
|
+
if table.rows > capacity:
|
|
154
|
+
raise state._error(
|
|
155
|
+
key.name, "The unique foreign key capacity is exhausted."
|
|
156
|
+
)
|
|
157
|
+
state.available[key.name] = _Available.from_pool(pool)
|
|
158
|
+
return state
|
|
159
|
+
|
|
160
|
+
def _allows_null(self, edge: PlannedDependency) -> bool:
|
|
161
|
+
return bool(self.context.settings.null_rate) and self.nullable.issuperset(
|
|
162
|
+
edge.foreign_key.columns
|
|
163
|
+
)
|
|
164
|
+
|
|
165
|
+
def draw(self) -> dict[str, Value] | None:
|
|
166
|
+
"""Draw candidate foreign key values; return None on depleted non-null keys."""
|
|
167
|
+
result: dict[str, Value] = {}
|
|
168
|
+
for edge in self.dependencies:
|
|
169
|
+
foreign = edge.foreign_key
|
|
170
|
+
rng = self.context.random(foreign.name, "foreign_key")
|
|
171
|
+
if edge.source == "null" or (
|
|
172
|
+
self._allows_null(edge) and rng.random() < self.context.settings.null_rate
|
|
173
|
+
):
|
|
174
|
+
result.update(dict.fromkeys(foreign.columns))
|
|
175
|
+
continue
|
|
176
|
+
unique = self.available.get(foreign.name)
|
|
177
|
+
values = unique.values if unique is not None else self.pools.for_edge(edge).values
|
|
178
|
+
if not values:
|
|
179
|
+
return None
|
|
180
|
+
result.update(zip(foreign.columns, rng.choice(values), strict=True))
|
|
181
|
+
return result
|
|
182
|
+
|
|
183
|
+
def contains(self, values: dict[str, Value]) -> bool:
|
|
184
|
+
"""Check the generated tuples against their parent pools."""
|
|
185
|
+
for edge in self.dependencies:
|
|
186
|
+
key = tuple(values[column] for column in edge.foreign_key.columns)
|
|
187
|
+
if all(value is None for value in key):
|
|
188
|
+
if edge.source != "null" and not self._allows_null(edge):
|
|
189
|
+
return False
|
|
190
|
+
elif (
|
|
191
|
+
edge.source not in {"generated", "existing"}
|
|
192
|
+
or key not in self.pools.for_edge(edge).members
|
|
193
|
+
):
|
|
194
|
+
return False
|
|
195
|
+
return True
|
|
196
|
+
|
|
197
|
+
def accept(self, values: dict[str, Value]) -> None:
|
|
198
|
+
for edge in self.dependencies:
|
|
199
|
+
available = self.available.get(edge.foreign_key.name)
|
|
200
|
+
if available is not None:
|
|
201
|
+
key = tuple(values[column] for column in edge.foreign_key.columns)
|
|
202
|
+
if None not in key:
|
|
203
|
+
available.take(key)
|
|
204
|
+
|
|
205
|
+
def _error(self, constraint: str, message: str) -> GenerationError:
|
|
206
|
+
return GenerationError(
|
|
207
|
+
PlanIssue(
|
|
208
|
+
code="PARENT_KEYS_EXHAUSTED",
|
|
209
|
+
message=message,
|
|
210
|
+
constraint=constraint,
|
|
211
|
+
table=self.context.table,
|
|
212
|
+
)
|
|
213
|
+
)
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
"""Generate typed scalar values from executable column bindings."""
|
|
2
|
+
|
|
3
|
+
from datetime import UTC, datetime, timedelta
|
|
4
|
+
from decimal import Decimal
|
|
5
|
+
from random import Random
|
|
6
|
+
from string import ascii_lowercase, digits
|
|
7
|
+
from uuid import UUID
|
|
8
|
+
|
|
9
|
+
from seed.config import GeneratorRule, Scalar
|
|
10
|
+
from seed.generation.streaming import GenerationError, RunContext, Value
|
|
11
|
+
from seed.metadata import ColumnSchema, NumericBound
|
|
12
|
+
from seed.planning.numeric import numeric_grid
|
|
13
|
+
from seed.planning.plan import PlanIssue
|
|
14
|
+
|
|
15
|
+
_TEXT_ALPHABET = ascii_lowercase + digits
|
|
16
|
+
_MICROSECONDS_PER_DAY = 86_400_000_000
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def scalar_value(
|
|
20
|
+
context: RunContext,
|
|
21
|
+
column: ColumnSchema,
|
|
22
|
+
generator: str,
|
|
23
|
+
rule: GeneratorRule | None,
|
|
24
|
+
bounds: tuple[NumericBound, ...] = (),
|
|
25
|
+
) -> Value:
|
|
26
|
+
"""Draw one scalar in the binding's domain."""
|
|
27
|
+
name = column.name
|
|
28
|
+
null_rate = (
|
|
29
|
+
rule.null_rate if rule and rule.null_rate is not None else context.settings.null_rate
|
|
30
|
+
)
|
|
31
|
+
if column.nullable and null_rate and context.random(name, "null").random() < null_rate:
|
|
32
|
+
return None
|
|
33
|
+
rng = context.random(name)
|
|
34
|
+
kind = column.type
|
|
35
|
+
if rule and rule.generator == "constant" and rule.value is not None:
|
|
36
|
+
return _configured_value(rule.value, column)
|
|
37
|
+
if rule and rule.generator == "choice" and rule.values:
|
|
38
|
+
return _configured_value(rng.choice(rule.values), column)
|
|
39
|
+
if generator == "email":
|
|
40
|
+
suffix = "@example.com"
|
|
41
|
+
width = min(16, kind.length - len(suffix)) if kind.length is not None else 16
|
|
42
|
+
if width > 0:
|
|
43
|
+
return random_text(rng, width) + suffix
|
|
44
|
+
if generator == "phone":
|
|
45
|
+
if context.settings.locale == "en_US" and (kind.length is None or kind.length >= 15):
|
|
46
|
+
return f"+1-202-555-01{rng.randrange(100):02}"
|
|
47
|
+
if generator in {
|
|
48
|
+
"first_name",
|
|
49
|
+
"last_name",
|
|
50
|
+
"name",
|
|
51
|
+
"address",
|
|
52
|
+
"city",
|
|
53
|
+
"country",
|
|
54
|
+
"description",
|
|
55
|
+
}:
|
|
56
|
+
provider = context.faker(name)
|
|
57
|
+
value = (
|
|
58
|
+
provider.text() if generator == "description" else str(getattr(provider, generator)())
|
|
59
|
+
)
|
|
60
|
+
return value[: kind.length] if kind.length is not None else value
|
|
61
|
+
if generator in {"integer", "decimal"}:
|
|
62
|
+
grid = numeric_grid(column, rule, bounds)
|
|
63
|
+
if grid is not None:
|
|
64
|
+
units = rng.randint(grid.first, grid.last)
|
|
65
|
+
return units if generator == "integer" else grid.decimal(units)
|
|
66
|
+
elif generator == "boolean":
|
|
67
|
+
return bool(rng.getrandbits(1))
|
|
68
|
+
elif generator == "uuid":
|
|
69
|
+
return UUID(int=rng.getrandbits(128), version=4)
|
|
70
|
+
elif generator == "text":
|
|
71
|
+
return random_text(rng, min(24, kind.length) if kind.length is not None else 24)
|
|
72
|
+
elif generator == "choice" and kind.enum_labels:
|
|
73
|
+
return rng.choice(kind.enum_labels)
|
|
74
|
+
elif generator in {"date", "datetime"}:
|
|
75
|
+
reference = context.settings.reference_time.astimezone(UTC)
|
|
76
|
+
start = reference - timedelta(days=365)
|
|
77
|
+
if generator == "date":
|
|
78
|
+
return start.date() + timedelta(days=rng.randrange(366))
|
|
79
|
+
precision = kind.precision if kind.precision is not None else 6
|
|
80
|
+
quantum = 10 ** (6 - precision)
|
|
81
|
+
offset = (-start.microsecond) % quantum
|
|
82
|
+
count = (365 * _MICROSECONDS_PER_DAY - offset) // quantum
|
|
83
|
+
sample = start + timedelta(microseconds=offset + rng.randint(0, count) * quantum)
|
|
84
|
+
return sample if kind.timezone else sample.replace(tzinfo=None)
|
|
85
|
+
raise GenerationError(
|
|
86
|
+
PlanIssue(
|
|
87
|
+
code="INCOMPATIBLE_BINDING",
|
|
88
|
+
message="The planned generator has no compatible values.",
|
|
89
|
+
table=context.table,
|
|
90
|
+
column=name,
|
|
91
|
+
)
|
|
92
|
+
)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def random_text(rng: Random, width: int) -> str:
|
|
96
|
+
"""Return bounded ASCII text using the supplied private stream."""
|
|
97
|
+
return "".join(rng.choices(_TEXT_ALPHABET, k=width))
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _configured_value(value: Scalar, column: ColumnSchema) -> Value:
|
|
101
|
+
"""Convert a validated config literal to the matching database scalar."""
|
|
102
|
+
if column.type.name == "numeric" and isinstance(value, (int, str)):
|
|
103
|
+
number = Decimal(value)
|
|
104
|
+
grid = numeric_grid(column, None, (), number)
|
|
105
|
+
if grid is not None and column.type.scale is not None:
|
|
106
|
+
return grid.decimal(grid.first)
|
|
107
|
+
return number
|
|
108
|
+
if column.type.name == "uuid" and isinstance(value, str):
|
|
109
|
+
return UUID(value)
|
|
110
|
+
if isinstance(value, datetime) and value.utcoffset() is not None:
|
|
111
|
+
return value.astimezone(UTC)
|
|
112
|
+
return value
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
"""Deterministic record and batching primitives for generation runs."""
|
|
2
|
+
|
|
3
|
+
import hashlib
|
|
4
|
+
import json
|
|
5
|
+
from collections.abc import Callable, Iterable, Iterator
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from datetime import date, datetime
|
|
8
|
+
from decimal import Decimal
|
|
9
|
+
from random import Random
|
|
10
|
+
from uuid import UUID
|
|
11
|
+
|
|
12
|
+
from faker import Faker
|
|
13
|
+
|
|
14
|
+
from seed.metadata import TableId
|
|
15
|
+
from seed.planning.plan import PlanIssue, PlanSettings
|
|
16
|
+
|
|
17
|
+
type Value = None | bool | int | str | Decimal | date | datetime | UUID
|
|
18
|
+
type RecordBatch = tuple[GeneratedRecord, ...]
|
|
19
|
+
MAX_BATCH = 10_000
|
|
20
|
+
MAX_ATTEMPTS = 100
|
|
21
|
+
_ALGORITHM = "seed-offline-v1"
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass(frozen=True)
|
|
25
|
+
class GeneratedRecord:
|
|
26
|
+
"""A record with a stable table-local ordinal and insertion-ordered columns."""
|
|
27
|
+
|
|
28
|
+
table: TableId
|
|
29
|
+
ordinal: int
|
|
30
|
+
values: dict[str, Value] = field(repr=False)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class GenerationError(Exception):
|
|
34
|
+
"""A scoped failure without candidate values."""
|
|
35
|
+
|
|
36
|
+
def __init__(self, issue: PlanIssue) -> None:
|
|
37
|
+
super().__init__(issue.message)
|
|
38
|
+
self.issue = issue
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class RunContext:
|
|
42
|
+
"""Keep each binding's independent RNG and Faker stream local to the run."""
|
|
43
|
+
|
|
44
|
+
def __init__(self, settings: PlanSettings, table: TableId) -> None:
|
|
45
|
+
self.settings = settings
|
|
46
|
+
self.table = table
|
|
47
|
+
self._streams: dict[tuple[str, str], Random] = {}
|
|
48
|
+
self._providers: dict[str, Faker] = {}
|
|
49
|
+
|
|
50
|
+
def _seed(self, binding: str, purpose: str) -> int:
|
|
51
|
+
encoded = json.dumps(
|
|
52
|
+
[
|
|
53
|
+
_ALGORITHM,
|
|
54
|
+
self.settings.random_seed,
|
|
55
|
+
self.table.schema_name,
|
|
56
|
+
self.table.table,
|
|
57
|
+
binding,
|
|
58
|
+
purpose,
|
|
59
|
+
],
|
|
60
|
+
separators=(",", ":"),
|
|
61
|
+
).encode("utf-8")
|
|
62
|
+
return int.from_bytes(hashlib.sha256(encoded).digest(), "big")
|
|
63
|
+
|
|
64
|
+
def random(self, binding: str, purpose: str = "scalar") -> Random:
|
|
65
|
+
"""Return the stable stream for one binding and purpose."""
|
|
66
|
+
key = (binding, purpose)
|
|
67
|
+
stream = self._streams.get(key)
|
|
68
|
+
if stream is None:
|
|
69
|
+
stream = Random(self._seed(binding, purpose))
|
|
70
|
+
self._streams[key] = stream
|
|
71
|
+
return stream
|
|
72
|
+
|
|
73
|
+
def faker(self, binding: str) -> Faker:
|
|
74
|
+
"""Return a seeded Faker instance without changing global RNG state."""
|
|
75
|
+
provider = self._providers.get(binding)
|
|
76
|
+
if provider is None:
|
|
77
|
+
provider = Faker(self.settings.locale)
|
|
78
|
+
provider.seed_instance(self._seed(binding, "faker"))
|
|
79
|
+
self._providers[binding] = provider
|
|
80
|
+
return provider
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def validate_batch_size(size: int) -> None:
|
|
84
|
+
"""Check the batch bound independently of record availability."""
|
|
85
|
+
if not 1 <= size <= MAX_BATCH:
|
|
86
|
+
raise GenerationError(
|
|
87
|
+
PlanIssue(code="INVALID_BATCH_SIZE", message="Batch size must be from 1 to 10000.")
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def batches(records: Iterable[GeneratedRecord], size: int) -> Iterator[RecordBatch]:
|
|
92
|
+
"""Yield nonempty bounded batches containing records from one table."""
|
|
93
|
+
validate_batch_size(size)
|
|
94
|
+
pending: list[GeneratedRecord] = []
|
|
95
|
+
for record in records:
|
|
96
|
+
if pending and record.table != pending[0].table:
|
|
97
|
+
yield tuple(pending)
|
|
98
|
+
pending.clear()
|
|
99
|
+
pending.append(record)
|
|
100
|
+
if len(pending) == size:
|
|
101
|
+
yield tuple(pending)
|
|
102
|
+
pending.clear()
|
|
103
|
+
if pending:
|
|
104
|
+
yield tuple(pending)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def retry_row(
|
|
108
|
+
table: TableId,
|
|
109
|
+
ordinal: int,
|
|
110
|
+
attempt: Callable[[], GeneratedRecord | None],
|
|
111
|
+
) -> GeneratedRecord:
|
|
112
|
+
"""Stop after a bounded number of attempts to accept a row."""
|
|
113
|
+
for _ in range(MAX_ATTEMPTS):
|
|
114
|
+
record = attempt()
|
|
115
|
+
if record is not None:
|
|
116
|
+
return record
|
|
117
|
+
raise GenerationError(
|
|
118
|
+
PlanIssue(
|
|
119
|
+
code="RETRY_EXHAUSTED",
|
|
120
|
+
message="Could not generate a valid record within 100 attempts.",
|
|
121
|
+
table=table,
|
|
122
|
+
ordinal=ordinal,
|
|
123
|
+
)
|
|
124
|
+
)
|