datadouble 0.0.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
datadouble/planner.py ADDED
@@ -0,0 +1,1492 @@
1
+ # Copyright (c) 2026- Tight Line LLC
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ """The planner: from a spec, a live catalog and a lock to an execution plan.
5
+
6
+ Planning resolves every name in the spec, applies excludes and strict mode,
7
+ builds the reference graph with its fallbacks, assigns tables to image groups,
8
+ works out what each group's image needs (package planning, in
9
+ :mod:`datadouble.closure`), chooses a strategy and checks the anonymization
10
+ rules. It reports every problem it finds, not just the first.
11
+ """
12
+
13
+ import datetime as dt
14
+ import re
15
+ from collections.abc import Callable, Iterable, Mapping, Sequence
16
+ from dataclasses import dataclass, replace
17
+ from typing import assert_never
18
+
19
+ from pydantic import AwareDatetime, BaseModel, ConfigDict, Field
20
+
21
+ from datadouble import jailer
22
+ from datadouble.catalog import (
23
+ Catalog,
24
+ CatalogLock,
25
+ Column,
26
+ ColumnKind,
27
+ ForeignKey,
28
+ ObjectRef,
29
+ Requirement,
30
+ Table,
31
+ )
32
+ from datadouble.closure import Closure, GroupInput, Packaging, Pulled, RowsRule, close
33
+ from datadouble.images import version_line
34
+ from datadouble.names import (
35
+ ColumnName,
36
+ ColumnRef,
37
+ EngineName,
38
+ GroupName,
39
+ SourceName,
40
+ SpecName,
41
+ TableName,
42
+ )
43
+ from datadouble.resolve import Reference, ResolveError, Resolver
44
+ from datadouble.spec import (
45
+ AccountPrivileges,
46
+ Assertion,
47
+ EdgePolicy,
48
+ ExpressionRule,
49
+ FakerKind,
50
+ FakerRule,
51
+ FormatPreservingRule,
52
+ HashRule,
53
+ ImageFormat,
54
+ NullRule,
55
+ ObjectRoot,
56
+ OnMissing,
57
+ PathsFrom,
58
+ PulledRows,
59
+ Rule,
60
+ Spec,
61
+ SpecLayer,
62
+ Strategy,
63
+ Strict,
64
+ StrictLevel,
65
+ StrictOverrides,
66
+ Unselected,
67
+ )
68
+ from datadouble.strict import (
69
+ Difference,
70
+ Excludes,
71
+ Finding,
72
+ PatternMatch,
73
+ StrictReport,
74
+ check_strict,
75
+ resolve_excludes,
76
+ )
77
+ from datadouble.subset import (
78
+ Edge,
79
+ EdgeMode,
80
+ Graph,
81
+ SubsetError,
82
+ TableRule,
83
+ nested_conditions,
84
+ )
85
+
86
+
87
+ class AccountNames(BaseModel):
88
+ """The user names an engine can give copies' accounts (``package.accounts``)."""
89
+
90
+ model_config = ConfigDict(strict=True, frozen=True, extra="forbid")
91
+
92
+ max_characters: int | None = None
93
+ """The longest name, in characters."""
94
+ max_bytes: int | None = None
95
+ """The longest name, in bytes of UTF-8."""
96
+ reserved: tuple[str, ...] = ()
97
+ """Names the engine or Datadouble keeps for itself, such as its build user."""
98
+ reserved_prefixes: tuple[str, ...] = ()
99
+ """Prefixes the engine keeps for its own names."""
100
+ keep_all: tuple[str, ...] = ()
101
+ """Names an account can have only with ``privileges: all``, such as a bootstrap
102
+ superuser that cannot lose its privileges."""
103
+
104
+ def problems(self, engine: str, user: str, privileges: AccountPrivileges) -> list[str]:
105
+ """Why ``engine`` cannot give an account ``user`` these privileges, if it cannot."""
106
+ found: list[str] = []
107
+ if user in self.keep_all and privileges is not AccountPrivileges.ALL:
108
+ found.append(
109
+ f"package.accounts: {user!r} must keep every privilege on {engine}"
110
+ " (privileges: all)"
111
+ )
112
+ if self.max_characters is not None and len(user) > self.max_characters:
113
+ found.append(
114
+ f"package.accounts: {user!r} is longer than the {self.max_characters}"
115
+ f" characters {engine} allows"
116
+ )
117
+ if self.max_bytes is not None and len(user.encode()) > self.max_bytes:
118
+ found.append(
119
+ f"package.accounts: {user!r} is longer than the {self.max_bytes}"
120
+ f" bytes {engine} allows"
121
+ )
122
+ if user in self.reserved:
123
+ found.append(f"package.accounts: {user!r} is a name {engine} keeps for itself")
124
+ found.extend(
125
+ f"package.accounts: {user!r} starts with {prefix!r}, which {engine} keeps for itself"
126
+ for prefix in self.reserved_prefixes
127
+ if user.startswith(prefix)
128
+ )
129
+ return found
130
+
131
+
132
+ class Capabilities(BaseModel):
133
+ """What an engine adapter can do, as far as planning is concerned."""
134
+
135
+ model_config = ConfigDict(strict=True, frozen=True, extra="forbid")
136
+
137
+ formats: tuple[ImageFormat, ...]
138
+ expressions: bool
139
+ """Whether the expression strategy is available (an engine-native language)."""
140
+ nested: bool
141
+ """Whether strategy A is available (the engine evaluates nested selections)."""
142
+ hooks: bool = True
143
+ """Whether ``before_load`` and ``after_transform`` hooks can run."""
144
+ complete: bool = False
145
+ """Whether every table must be seeded or excluded, as a file tree's top-level
146
+ directories must be: nothing in the source goes unconsidered."""
147
+ version_line: int = Field(default=1, ge=1)
148
+ """How many leading numbers of a server version name its compatibility line:
149
+ 1 for PostgreSQL (``17``), 2 for MySQL (``8.4``), whose minor releases change
150
+ what a data directory holds."""
151
+ accounts: AccountNames | None = None
152
+ """The names physical images' accounts (``package.accounts``) can have; None
153
+ when the adapter cannot give images accounts."""
154
+ standalone: bool = False
155
+ """Whether the adapter can build standalone images: load what a closure
156
+ pulls in, and leave out of the image every object the closure lacks."""
157
+ joins_outermost: bool = True
158
+ """Whether one query can join tables in different outermost namespaces.
159
+ PostgreSQL's databases cannot be joined, so a virtual reference between
160
+ two of them fails the plan."""
161
+ several_sources: bool = False
162
+ """Whether one working server can hold several sources' extracts, so a
163
+ spec may name more than one source."""
164
+
165
+
166
+ @dataclass(frozen=True, slots=True)
167
+ class SourceCatalog:
168
+ """What planning needs from one source: its catalog and its server's version."""
169
+
170
+ name: SourceName
171
+ catalog: Catalog
172
+ server_version: str
173
+ namespaces: tuple[str, ...] = ()
174
+ """The databases the source reads, empty ones included (``SourceSession.namespaces``)."""
175
+
176
+ def databases(self) -> tuple[str, ...]:
177
+ """Its outermost namespaces: those it reads, and those its tables are in."""
178
+ found = (*self.namespaces, *(t.name.outermost for t in self.catalog.tables))
179
+ return tuple(dict.fromkeys(found))
180
+
181
+
182
+ class PlanError(Exception):
183
+ """A spec that cannot be planned against the catalog."""
184
+
185
+ def __init__(self, problems: tuple[str, ...], strict: StrictReport | None = None) -> None:
186
+ """Keep every problem, and the strict-mode report if it failed."""
187
+ count = len(problems)
188
+ super().__init__(f"the plan has {count} problem{'s' if count != 1 else ''}")
189
+ self.problems = problems
190
+ self.strict = strict
191
+
192
+
193
+ class _Model(BaseModel):
194
+ model_config = ConfigDict(strict=True, frozen=True, extra="forbid")
195
+
196
+
197
+ class PlannedRule(_Model):
198
+ """An anonymization rule resolved to a column."""
199
+
200
+ column: ColumnRef
201
+ kind: ColumnKind
202
+ type: str
203
+ """The column's type as the engine spells it."""
204
+ rule: Rule
205
+
206
+
207
+ class Fixup(_Model):
208
+ """A fallback applied to a working database at load."""
209
+
210
+ edge: Edge
211
+ mode: EdgeMode
212
+ parent_present: bool
213
+ """Whether the parent table is in the same working database."""
214
+
215
+
216
+ class PlannedGroup(_Model):
217
+ """One image group: its tables, what it needs, and how references leaving it are handled."""
218
+
219
+ name: GroupName
220
+ tables: tuple[TableName, ...]
221
+ requires: tuple[GroupName, ...]
222
+ omitted_references: tuple[str, ...]
223
+ """References whose constraints are left out because the parent is elsewhere."""
224
+ fixups: tuple[Fixup, ...]
225
+ standalone: bool = False
226
+ """Whether the image must work on its own, holding everything in ``pulled``."""
227
+ roots: tuple[ObjectRef, ...] = ()
228
+ """The objects the spec and the group declare in ``objects``."""
229
+ objects: tuple[ObjectRef, ...] = ()
230
+ """Every object the image needs, dependencies first: those that come with
231
+ its tables, its roots, and what they need."""
232
+ pulled: tuple[Pulled, ...] = ()
233
+ """What a standalone group's closure pulled in from outside the group, and from where."""
234
+
235
+ def packaged(self) -> tuple[TableName, ...]:
236
+ """The tables its image holds: its own, then those its closure pulls in."""
237
+ return (*self.tables, *(p.table for p in self.pulled if p.table is not None))
238
+
239
+ def rowless(self) -> frozenset[TableName]:
240
+ """Pulled-in tables that come without rows."""
241
+ return frozenset(
242
+ p.table for p in self.pulled if p.table is not None and p.rows is PulledRows.NONE
243
+ )
244
+
245
+ def rows(self) -> dict[TableName, PulledRows]:
246
+ """Which rows of each pulled-in table its image holds."""
247
+ return {p.table: p.rows for p in self.pulled if p.table is not None and p.rows}
248
+
249
+
250
+ class PiiAllow(_Model):
251
+ """Values the PII scan accepts in one column, as ``LIKE`` patterns."""
252
+
253
+ column: ColumnRef
254
+ patterns: tuple[str, ...]
255
+
256
+
257
+ _PLACEHOLDER = re.compile(r"\{([^{}]+)\}")
258
+
259
+
260
+ class PlannedPaths(_Model):
261
+ """How the chosen rows of one table name files: ``files.paths_from``, resolved."""
262
+
263
+ table: TableName
264
+ columns: tuple[ColumnName, ...]
265
+ """The columns the template names, in the order its placeholders first use them."""
266
+ template: str
267
+ """The path, with ``{column}`` for each column's value."""
268
+ match: str | None = None
269
+ """A regular expression whose first group, where it matches, is the path."""
270
+
271
+ def path(self, values: tuple[object, ...]) -> str | None:
272
+ """The path one row names, given its values of ``columns``; None if it names none."""
273
+ if any(value is None for value in values):
274
+ return None
275
+ by_column = dict(zip(self.columns, (str(value) for value in values), strict=True))
276
+ filled = _PLACEHOLDER.sub(lambda found: by_column[ColumnName(found[1])], self.template)
277
+ if self.match is None:
278
+ return filled
279
+ matched = re.search(self.match, filled)
280
+ return matched[1] if matched else None
281
+
282
+
283
+ class PlannedSource(_Model):
284
+ """One of the spec's sources, as planned."""
285
+
286
+ name: SourceName
287
+ server_version: str
288
+ catalog_fingerprint: str
289
+ """Its live catalog's fingerprint, which its snapshot checks again."""
290
+ namespaces: tuple[str, ...]
291
+ """The outermost namespaces (databases) of its tables, which no other source has."""
292
+ requirements: tuple[Requirement, ...] = ()
293
+ """The requirements it uses that the copies keep, which the working image must provide."""
294
+
295
+
296
+ class SourceReference(_Model):
297
+ """A reference between two sources, read under different snapshots."""
298
+
299
+ edge: str
300
+ """The reference's name, as the plan's edges give it."""
301
+ child: TableName
302
+ child_source: SourceName
303
+ parent: TableName
304
+ parent_source: SourceName
305
+
306
+
307
+ class PlannedSeed(_Model):
308
+ """One ``subset.seeds`` key and the tables it gave a seed to."""
309
+
310
+ pattern: str
311
+ """The key as the spec wrote it: a table name or a glob."""
312
+ tables: tuple[TableName, ...]
313
+ """The tables it gave its condition to; a table's own name wins over a pattern."""
314
+
315
+
316
+ class Plan(_Model):
317
+ """Everything the later stages need, recorded in the plan's manifest."""
318
+
319
+ spec: SpecName
320
+ engine: EngineName
321
+ as_of: AwareDatetime
322
+ strategy: Strategy
323
+ catalog_fingerprint: str
324
+ excludes: Excludes
325
+ strict: StrictReport | None
326
+ tables: tuple[TableRule, ...]
327
+ edges: tuple[Edge, ...]
328
+ groups: tuple[PlannedGroup, ...]
329
+ formats: tuple[ImageFormat, ...]
330
+ anonymization: tuple[PlannedRule, ...]
331
+ rewrites: tuple[ColumnRef, ...]
332
+ pii_allow: tuple[PiiAllow, ...]
333
+ assertions: tuple[Assertion, ...]
334
+ catalog: Catalog
335
+ """The live catalog minus excluded tables and omitted requirements."""
336
+ omitted: tuple[Requirement, ...] = ()
337
+ """The source's requirements that ``sources.<name>.omit`` leaves out."""
338
+ warnings: tuple[str, ...]
339
+ paths_from: PlannedPaths | None = None
340
+ """How the chosen rows name the files to copy too."""
341
+ seeds: tuple[PlannedSeed, ...] = ()
342
+ """Each seed key and the tables it matched."""
343
+ unselected: tuple[TableName, ...] = ()
344
+ """Kept tables no seed or followed reference selected, handled by ``subset.unselected``."""
345
+ sources: tuple[PlannedSource, ...] = ()
346
+ """Every source, in the spec's order, with its version and namespaces."""
347
+ between_sources: tuple[SourceReference, ...] = ()
348
+ """References whose child and parent are in different sources: each side is
349
+ read under its own snapshot, so the pair is not one point in time."""
350
+ spec_layers: tuple[SpecLayer, ...] = ()
351
+ """Every file the spec was read from, with its SHA-256, the spec's own file last."""
352
+
353
+ def graph(self) -> Graph:
354
+ """The selection graph."""
355
+ return Graph({rule.table: rule for rule in self.tables}, self.edges)
356
+
357
+ def extracted(self) -> tuple[TableName, ...]:
358
+ """Tables whose definitions and rows are extracted."""
359
+ excluded = self.excludes.excluded()
360
+ return tuple(rule.table for rule in self.tables if rule.table not in excluded)
361
+
362
+ def source_of(self, table: TableName) -> SourceName:
363
+ """The source a table belongs to."""
364
+ return next(s.name for s in self.sources if table.outermost in s.namespaces)
365
+
366
+ def of_source(self, name: SourceName) -> "Plan":
367
+ """This plan as one source's snapshot sees it: its tables, edges and catalog only.
368
+
369
+ Its ``catalog_fingerprint`` is the source's own, which the snapshot
370
+ checks against its catalog.
371
+ """
372
+ source = next(s for s in self.sources if s.name == name)
373
+ namespaces = frozenset(source.namespaces)
374
+
375
+ def own(table: TableName) -> bool:
376
+ return table.outermost in namespaces
377
+
378
+ def matches(found: tuple[PatternMatch, ...]) -> tuple[PatternMatch, ...]:
379
+ return tuple(
380
+ m.model_copy(update={"tables": tuple(t for t in m.tables if own(t))}) for m in found
381
+ )
382
+
383
+ return self.model_copy(
384
+ update={
385
+ "catalog_fingerprint": source.catalog_fingerprint,
386
+ "catalog": self.catalog.model_copy(
387
+ update={"tables": tuple(t for t in self.catalog.tables if own(t.name))}
388
+ ),
389
+ "tables": tuple(rule for rule in self.tables if own(rule.table)),
390
+ "edges": tuple(e for e in self.edges if own(e.child) and own(e.parent)),
391
+ "excludes": Excludes(
392
+ exclude=matches(self.excludes.exclude),
393
+ structure_only=matches(self.excludes.structure_only),
394
+ ),
395
+ "between_sources": (),
396
+ }
397
+ )
398
+
399
+
400
+ class PlanOptions(_Model):
401
+ """Overrides from the request, applied over the spec."""
402
+
403
+ now: AwareDatetime | None = None
404
+ """The time ``as_of`` defaults to when the spec has none; the current time if omitted."""
405
+ strict: StrictOverrides | None = None
406
+ """Levels set over the spec's ``strict``, for the kinds named."""
407
+ strategy: Strategy | None = None
408
+ formats: tuple[ImageFormat, ...] | None = None
409
+ layers: tuple[SpecLayer, ...] = ()
410
+ """The files the spec was read from, recorded in the plan."""
411
+
412
+
413
+ _FAKER_KINDS: dict[FakerKind, frozenset[ColumnKind]] = {
414
+ FakerKind.DATE_OF_BIRTH: frozenset({ColumnKind.DATE, ColumnKind.TIMESTAMP, ColumnKind.TEXT}),
415
+ }
416
+ _TEXT = frozenset({ColumnKind.TEXT})
417
+ _TEXT_OR_INTEGER = frozenset({ColumnKind.TEXT, ColumnKind.INTEGER})
418
+
419
+
420
+ class _Planner:
421
+ def __init__(
422
+ self,
423
+ spec: Spec,
424
+ catalog: Catalog,
425
+ lock: CatalogLock | None,
426
+ capabilities: Capabilities,
427
+ options: PlanOptions,
428
+ ) -> None:
429
+ self.spec = spec
430
+ self.catalog = catalog
431
+ self.lock = lock
432
+ self.capabilities = capabilities
433
+ self.options = options
434
+ self.resolver = Resolver(catalog, case_sensitive=spec.case_sensitive)
435
+ self.problems: list[str] = []
436
+ self.warnings: list[str] = []
437
+ self.group_roots: dict[GroupName, tuple[ObjectRef, ...]] = {}
438
+ self.closures: dict[GroupName, Closure] = {}
439
+ self.sources: tuple[PlannedSource, ...] = ()
440
+ self.omits: tuple[Requirement, ...] = ()
441
+ self.users: dict[str, tuple[SourceName, ...]] = {}
442
+ """The sources that use each requirement, by its text."""
443
+
444
+ def attempt[**P, T](
445
+ self, action: Callable[P, T], *args: P.args, **kwargs: P.kwargs
446
+ ) -> T | None:
447
+ try:
448
+ return action(*args, **kwargs)
449
+ except ResolveError as error:
450
+ self.problems.append(str(error))
451
+ return None
452
+
453
+ # Excludes and strict mode
454
+
455
+ def levels(self) -> Strict:
456
+ overrides = self.options.strict
457
+ return self.spec.strict if overrides is None else overrides.over(self.spec.strict)
458
+
459
+ def strict_report(self, excluded: frozenset[TableName]) -> StrictReport | None:
460
+ strict = self.levels()
461
+ if self.lock is None:
462
+ if strict.data is StrictLevel.OFF and not strict.failing():
463
+ self.warnings.append("no catalog lock: strict mode cannot compare anything")
464
+ else:
465
+ self.problems.append(
466
+ "strict mode cannot compare the catalog without a catalog lock; "
467
+ "write one with `datadouble lock`"
468
+ )
469
+ return None
470
+ report = check_strict(self.catalog, self.lock, excluded, strict, self.breaks)
471
+ report = report.model_copy(
472
+ update={"findings": tuple(self.named(finding) for finding in report.findings)}
473
+ )
474
+ self.warnings.extend(
475
+ f"strict mode: {finding}" for finding in report.findings if finding.severity == "warn"
476
+ )
477
+ return report
478
+
479
+ def breaks(self, finding: Finding) -> str | None:
480
+ """What a difference from the lock breaks, if anything.
481
+
482
+ A changed column breaks its anonymization rule when the rule no longer
483
+ fits it. A removed object breaks a packaged table or a root that still
484
+ needs it; a new or changed object breaks an image whose closure reaches
485
+ it and then something the image cannot have (package planning).
486
+ """
487
+ if finding.ref is not None:
488
+ return self.object_breaks(finding, finding.ref)
489
+ if finding.difference is not Difference.COLUMN_CHANGED:
490
+ return None
491
+ found = self.rules_by_column().get(finding.object)
492
+ if found is None:
493
+ return None
494
+ column, rule = found
495
+ misfit = _misfit(column, rule)
496
+ return None if misfit is None else f"its anonymization rule no longer fits: {misfit}"
497
+
498
+ def object_breaks(self, finding: Finding, ref: ObjectRef) -> str | None:
499
+ """What a new, changed or removed object breaks in the images, if anything."""
500
+ if finding.difference is not Difference.OBJECT_REMOVED:
501
+ reasons = [c.broken[ref] for c in self.closures.values() if ref in c.broken]
502
+ return "; ".join(dict.fromkeys(reasons)) or None
503
+ # Strict mode compares only with a lock.
504
+ lock = self.lock.catalog if self.lock is not None else self.catalog
505
+ packaged = {t for closure in self.closures.values() for t in closure.tables}
506
+ needing = [
507
+ f"packaged table {table.name} still needs it"
508
+ for table in lock.tables
509
+ if table.name in packaged
510
+ and any(edge.object == ref and not edge.inferred for edge in table.depends_on)
511
+ ]
512
+ locked = Resolver(lock, case_sensitive=self.spec.case_sensitive)
513
+ for name, roots in self.declared():
514
+ for root in roots:
515
+ kind, text = next(iter(root.items()))
516
+ try:
517
+ declared = locked.object(kind, text)
518
+ except ResolveError:
519
+ continue
520
+ if declared.ref == ref:
521
+ needing.append(f"{_declarer(name)} declares it in objects")
522
+ return "; ".join(dict.fromkeys(needing)) or None
523
+
524
+ def declared(self) -> list[tuple[GroupName | None, tuple[ObjectRoot, ...]]]:
525
+ """The spec's roots, and each group's."""
526
+ return [
527
+ (None, self.spec.objects),
528
+ *((name, group.objects) for name, group in self.spec.images.items()),
529
+ ]
530
+
531
+ def roots(self) -> dict[GroupName, tuple[ObjectRef, ...]]:
532
+ """Each group's roots, the spec's first; a root that does not resolve is a problem."""
533
+ resolved: dict[GroupName | None, list[ObjectRef]] = {}
534
+ for name, roots in self.declared():
535
+ found: list[ObjectRef] = []
536
+ for root in roots:
537
+ kind, text = next(iter(root.items()))
538
+ try:
539
+ found.append(self.resolver.object(kind, text).ref)
540
+ except ResolveError as error:
541
+ self.problems.append(f"{_declarer(name)}: objects: {error}")
542
+ resolved[name] = found
543
+ shared = resolved[None]
544
+ return {name: tuple(dict.fromkeys((*shared, *resolved[name]))) for name in self.spec.images}
545
+
546
+ def rules_by_column(self) -> dict[str, tuple[Column, Rule]]:
547
+ """Each anonymized column, by name, with its rule.
548
+
549
+ Names that do not resolve are skipped here and reported by :meth:`anonymization`.
550
+ """
551
+ found: dict[str, tuple[Column, Rule]] = {}
552
+ for table_text, columns in self.spec.anonymize.items():
553
+ try:
554
+ table = self.resolver.table(table_text)
555
+ for column_text, rule in columns.items():
556
+ column = self.resolver.column_of(table, column_text)
557
+ found[str(ColumnRef(table=table.name, column=column.name))] = (column, rule)
558
+ except ResolveError:
559
+ continue
560
+ return found
561
+
562
+ def named(self, finding: Finding) -> Finding:
563
+ """A finding whose resolutions name the sources that use its requirement."""
564
+ users = self.users.get(finding.object)
565
+ if not users:
566
+ return finding
567
+ omits = " or ".join(f"`sources.{name}.omit`" for name in users)
568
+ return finding.model_copy(
569
+ update={
570
+ "resolutions": tuple(
571
+ text.replace("`sources.<name>.omit`", omits) for text in finding.resolutions
572
+ )
573
+ }
574
+ )
575
+
576
+ # References
577
+
578
+ def _declared(self, reference: Reference) -> ForeignKey | None:
579
+ candidates = [
580
+ fk
581
+ for fk in reference.child.foreign_keys
582
+ if fk.target == reference.parent.name
583
+ and (reference.columns is None or fk.columns == reference.columns)
584
+ and (reference.parent_columns is None or fk.target_columns == reference.parent_columns)
585
+ ]
586
+ if len(candidates) > 1:
587
+ names = ", ".join(fk.name for fk in candidates)
588
+ message = (
589
+ f"{reference.child.name} has several references to {reference.parent.name} "
590
+ f"({names}); name the columns, as child.column -> parent"
591
+ )
592
+ raise ResolveError(message)
593
+ return candidates[0] if candidates else None
594
+
595
+ def virtual_edges(self) -> list[Edge]:
596
+ edges: list[Edge] = []
597
+ for text, virtual in self.spec.subset.virtual_fks.items():
598
+ reference = self.attempt(self.resolver.reference, text)
599
+ if reference is None:
600
+ continue
601
+ if reference.columns is None:
602
+ self.problems.append(f"virtual reference {text!r} must name the child columns")
603
+ continue
604
+ child, parent = reference.child.name, reference.parent.name
605
+ if not self.capabilities.joins_outermost and child.outermost != parent.outermost:
606
+ self.problems.append(
607
+ f"virtual reference {text!r} joins {child.outermost} and {parent.outermost},"
608
+ f" which one {self.catalog.engine} query cannot read together"
609
+ )
610
+ continue
611
+ parent_columns = reference.parent_columns or reference.parent.primary_key
612
+ if len(parent_columns) != len(reference.columns):
613
+ self.problems.append(
614
+ f"virtual reference {text!r} has {len(reference.columns)} child column(s) "
615
+ f"and {len(parent_columns)} parent column(s)"
616
+ )
617
+ continue
618
+ edges.append(
619
+ Edge(
620
+ name=f"virtual: {text}",
621
+ child=reference.child.name,
622
+ columns=reference.columns,
623
+ parent=reference.parent.name,
624
+ parent_columns=parent_columns,
625
+ when=virtual.when,
626
+ virtual=True,
627
+ parent_unique=parent_columns == reference.parent.primary_key,
628
+ )
629
+ )
630
+ return edges
631
+
632
+ def find_edge(self, edges: list[Edge], reference: Reference, text: str) -> int | None:
633
+ try:
634
+ declared = self._declared(reference)
635
+ except ResolveError as error:
636
+ self.problems.append(str(error))
637
+ return None
638
+ for index, edge in enumerate(edges):
639
+ if edge.child != reference.child.name or edge.parent != reference.parent.name:
640
+ continue
641
+ if declared is not None and not edge.virtual and edge.name == declared.name:
642
+ return index
643
+ if edge.virtual and (reference.columns is None or edge.columns == reference.columns):
644
+ return index
645
+ self.problems.append(f"{text!r} matches no reference in the catalog or virtual_fks")
646
+ return None
647
+
648
+ def edges(self, tables: Iterable[Table]) -> list[Edge]:
649
+ edges = [
650
+ Edge(
651
+ name=fk.name,
652
+ child=table.name,
653
+ columns=fk.columns,
654
+ parent=fk.target,
655
+ parent_columns=fk.target_columns,
656
+ )
657
+ for table in tables
658
+ for fk in table.foreign_keys
659
+ ]
660
+ edges.extend(self.virtual_edges())
661
+ for text, policy in self.spec.subset.edges.items():
662
+ reference = self.attempt(self.resolver.reference, text)
663
+ index = None if reference is None else self.find_edge(edges, reference, text)
664
+ if index is not None:
665
+ edges[index] = replace(edges[index], mode=_mode(policy))
666
+ for text in self.spec.subset.follow.down:
667
+ reference = self.attempt(self.resolver.downward, text)
668
+ index = None if reference is None else self.find_edge(edges, reference, text)
669
+ if index is not None:
670
+ edges[index] = replace(edges[index], down=True)
671
+ return edges
672
+
673
+ def check_edge(
674
+ self, edge: Edge, rules: dict[TableName, TableRule], excluded: frozenset[TableName]
675
+ ) -> None:
676
+ parent_rule = rules.get(edge.parent)
677
+ parent_keeps_rows = parent_rule is not None and parent_rule.rows_kept
678
+ if edge.mode in {EdgeMode.FOLLOW, EdgeMode.ALL} and not parent_keeps_rows:
679
+ why = "is excluded" if edge.parent in excluded else "keeps no rows"
680
+ self.problems.append(
681
+ f"{edge.child} references {edge.parent} ({edge.name}), which {why}; "
682
+ "give the reference a fallback: on_missing null, stub or drop"
683
+ )
684
+ child = self.catalog.table(edge.child)
685
+ if child is not None and edge.mode is EdgeMode.NULL:
686
+ fixed = [c for c in edge.columns if not (col := child.column(c)) or not col.nullable]
687
+ if fixed:
688
+ self.problems.append(
689
+ f"{edge.name}: on_missing null needs nullable columns, but "
690
+ f"{', '.join(fixed)} cannot be null"
691
+ )
692
+ if edge.mode is EdgeMode.STUB:
693
+ self.check_stub(edge, parent_keeps_rows=parent_keeps_rows)
694
+ if edge.mode is EdgeMode.DROP and edge.when is not None:
695
+ self.problems.append(
696
+ f"{edge.name}: on_missing drop is not supported on a reference with `when`; "
697
+ "use on_missing null"
698
+ )
699
+
700
+ def check_stub(self, edge: Edge, *, parent_keeps_rows: bool) -> None:
701
+ parent = self.catalog.table(edge.parent)
702
+ if parent is None or not parent_keeps_rows:
703
+ self.problems.append(
704
+ f"{edge.name}: on_missing stub needs {edge.parent} in the image, with rows"
705
+ )
706
+ return
707
+ own = {c for fk in parent.foreign_keys for c in fk.columns} - set(edge.parent_columns)
708
+ blocked = [c.name for c in parent.columns if c.name in own and not c.nullable]
709
+ if blocked:
710
+ self.problems.append(
711
+ f"{edge.name}: cannot stub {edge.parent}, whose references "
712
+ f"{', '.join(blocked)} cannot be null"
713
+ )
714
+
715
+ # Groups
716
+
717
+ def placement(self) -> dict[ObjectRef, tuple[GroupName, ...]]:
718
+ """The groups whose ``include`` patterns match each object, from the right."""
719
+ placed: dict[ObjectRef, tuple[GroupName, ...]] = {}
720
+ for item in self.catalog.objects:
721
+ parts = (*item.ref.namespace, item.ref.name)
722
+ groups = tuple(
723
+ name
724
+ for name, group in self.spec.images.items()
725
+ if any(self.resolver.matches_parts(pattern, parts) for pattern in group.include)
726
+ )
727
+ if groups:
728
+ placed[item.ref] = groups
729
+ return placed
730
+
731
+ def rows_rules(self, name: GroupName, edges: list[Edge]) -> tuple[RowsRule, ...]:
732
+ """A group's ``rows`` overrides, resolved: references to edges, tables to names."""
733
+ found: list[RowsRule] = []
734
+ for key, rows in self.spec.images[name].rows.items():
735
+ if "->" in key:
736
+ reference = self.attempt(self.resolver.reference, key)
737
+ index = None if reference is None else self.find_edge(edges, reference, key)
738
+ if index is not None:
739
+ found.append(RowsRule(key=key, rows=rows, edge=edges[index]))
740
+ continue
741
+ if _is_glob(key):
742
+ tables = self.resolver.glob(key.strip())
743
+ else:
744
+ table = self.attempt(self.resolver.table, key)
745
+ tables = () if table is None else (table.name,)
746
+ if tables:
747
+ found.append(RowsRule(key=key, rows=rows, tables=frozenset(tables)))
748
+ elif _is_glob(key):
749
+ self.problems.append(f"group {name!r}: rows: {key!r} matches no table")
750
+ return tuple(found)
751
+
752
+ def check_standalone(self) -> None:
753
+ """Refuse standalone groups the engine adapter cannot build."""
754
+ if self.capabilities.standalone:
755
+ return
756
+ for name, group in self.spec.images.items():
757
+ closure = self.closures[name]
758
+ if group.standalone and (closure.pulled or self.catalog.objects):
759
+ self.problems.append(
760
+ f"group {name!r} is standalone, and the {self.catalog.engine} adapter "
761
+ "cannot build standalone images yet"
762
+ )
763
+
764
+ def members(self, kept: tuple[TableName, ...]) -> dict[GroupName, tuple[TableName, ...]]:
765
+ """The kept tables each group's patterns include."""
766
+ return {
767
+ name: tuple(
768
+ table
769
+ for table in kept
770
+ if any(self.resolver.matches(pattern, table) for pattern in group.include)
771
+ )
772
+ for name, group in self.spec.images.items()
773
+ }
774
+
775
+ def groups(
776
+ self,
777
+ kept: tuple[TableName, ...],
778
+ edges: list[Edge],
779
+ rules: dict[TableName, TableRule],
780
+ members: dict[GroupName, tuple[TableName, ...]],
781
+ ) -> tuple[PlannedGroup, ...]:
782
+ placed = {table for tables in members.values() for table in tables}
783
+ placed |= {t for closure in self.closures.values() for t in closure.tables}
784
+ self.warnings.extend(
785
+ f"{table} is in no image group: its rows are extracted but not packaged"
786
+ for table in kept
787
+ if table not in placed
788
+ )
789
+ planned: list[PlannedGroup] = []
790
+ for name, group in self.spec.images.items():
791
+ closure = self.closures[name]
792
+ # A standalone group holds what its closure pulls in, too; a
793
+ # pulled-in table without rows cannot keep references to it.
794
+ tables = set(closure.tables)
795
+ rowless = {p.table for p in closure.pulled if p.rows is PulledRows.NONE}
796
+ reachable = self.required(name)
797
+ omitted: list[str] = []
798
+ fixups: list[Fixup] = []
799
+ for edge in edges:
800
+ if edge.child not in tables:
801
+ continue
802
+ if edge.parent in rowless and edge.child not in rowless:
803
+ omitted.append(edge.name)
804
+ continue
805
+ parent_here = edge.parent in tables
806
+ parent_rule = rules.get(edge.parent)
807
+ parent_rows = parent_rule is not None and parent_rule.rows_kept
808
+ if not parent_here:
809
+ omitted.append(edge.name)
810
+ self.check_crossing(
811
+ name, edge, parent_rows=parent_rows, members=members, reachable=reachable
812
+ )
813
+ if edge.mode in {EdgeMode.NULL, EdgeMode.STUB}:
814
+ fixups.append(Fixup(edge=edge, mode=edge.mode, parent_present=parent_here))
815
+ planned.append(
816
+ PlannedGroup(
817
+ name=name,
818
+ tables=members[name],
819
+ requires=group.requires,
820
+ omitted_references=tuple(omitted),
821
+ fixups=tuple(fixups),
822
+ standalone=group.standalone,
823
+ roots=self.group_roots[name],
824
+ objects=closure.objects,
825
+ pulled=closure.pulled,
826
+ )
827
+ )
828
+ return tuple(planned)
829
+
830
+ def required(self, name: GroupName) -> frozenset[GroupName]:
831
+ seen: set[GroupName] = set()
832
+ pending = list(self.spec.images[name].requires)
833
+ while pending:
834
+ group = pending.pop()
835
+ if group not in seen:
836
+ seen.add(group)
837
+ pending.extend(self.spec.images[group].requires)
838
+ return frozenset(seen)
839
+
840
+ def check_crossing(
841
+ self,
842
+ name: GroupName,
843
+ edge: Edge,
844
+ *,
845
+ parent_rows: bool,
846
+ members: dict[GroupName, tuple[TableName, ...]],
847
+ reachable: frozenset[GroupName],
848
+ ) -> None:
849
+ if not parent_rows or edge.mode is EdgeMode.NULL:
850
+ return
851
+ if edge.mode in {EdgeMode.STUB, EdgeMode.DROP}:
852
+ self.problems.append(
853
+ f"group {name!r}: {edge.name} leaves the group with on_missing "
854
+ f"{edge.mode}, which version 1 supports only within a group; "
855
+ "use on_missing null or `requires`"
856
+ )
857
+ return
858
+ if not any(edge.parent in members[group] for group in reachable):
859
+ self.problems.append(
860
+ f"group {name!r}: {edge.child} references {edge.parent} ({edge.name}) in "
861
+ "another group; add `requires:` for a group containing it, or give the "
862
+ "reference a fallback"
863
+ )
864
+
865
+ # Anonymization
866
+
867
+ def anonymization(
868
+ self, excluded: frozenset[TableName], key_columns: frozenset[ColumnRef]
869
+ ) -> tuple[PlannedRule, ...]:
870
+ planned: list[PlannedRule] = []
871
+ for table_text, columns in self.spec.anonymize.items():
872
+ table = self.attempt(self.resolver.table, table_text)
873
+ if table is None:
874
+ continue
875
+ if table.name in excluded:
876
+ self.problems.append(f"anonymization rules name {table.name}, which is excluded")
877
+ continue
878
+ for column_text, rule in columns.items():
879
+ column = self.attempt(self.resolver.column_of, table, column_text)
880
+ if column is None:
881
+ continue
882
+ ref = ColumnRef(table=table.name, column=column.name)
883
+ self.check_rule(ref, column, rule, key_columns)
884
+ planned.append(
885
+ PlannedRule(column=ref, kind=column.kind, type=column.type, rule=rule)
886
+ )
887
+ return tuple(planned)
888
+
889
+ def check_rule(
890
+ self,
891
+ ref: ColumnRef,
892
+ column: Column,
893
+ rule: Rule,
894
+ key_columns: frozenset[ColumnRef],
895
+ ) -> None:
896
+ if ref in key_columns:
897
+ self.problems.append(
898
+ f"{ref} is part of a primary or foreign key; anonymizing key columns "
899
+ "is not supported"
900
+ )
901
+ if isinstance(rule, ExpressionRule) and not self.capabilities.expressions:
902
+ self.problems.append(
903
+ f"{ref}: the {self.catalog.engine} adapter has no expression language"
904
+ )
905
+ misfit = _misfit(column, rule)
906
+ if misfit is not None:
907
+ self.problems.append(f"{ref} {misfit}")
908
+
909
+ # The whole plan
910
+
911
+ def formats(self) -> tuple[ImageFormat, ...]:
912
+ wanted = self.options.formats or self.spec.package.formats or self.capabilities.formats
913
+ unsupported = [f for f in wanted if f not in self.capabilities.formats]
914
+ if unsupported:
915
+ supported = ", ".join(self.capabilities.formats)
916
+ self.problems.append(
917
+ f"the {self.catalog.engine} adapter cannot produce "
918
+ f"{', '.join(unsupported)} images; it supports {supported}"
919
+ )
920
+ self.accounts(wanted)
921
+ return tuple(dict.fromkeys(wanted))
922
+
923
+ def accounts(self, wanted: tuple[ImageFormat, ...]) -> None:
924
+ """Check ``package.accounts`` against the adapter and the formats."""
925
+ accounts = self.spec.package.accounts
926
+ if not accounts:
927
+ return
928
+ users = [account.user for account in accounts]
929
+ self.problems.extend(
930
+ f"package.accounts names {user!r} more than once"
931
+ for user in dict.fromkeys(users)
932
+ if users.count(user) > 1
933
+ )
934
+ engine = self.catalog.engine
935
+ names = self.capabilities.accounts
936
+ if names is None:
937
+ self.problems.append(
938
+ f"the {engine} adapter cannot give copies accounts (package.accounts)"
939
+ )
940
+ return
941
+ if ImageFormat.PHYSICAL not in wanted:
942
+ self.problems.append(
943
+ "package.accounts applies to physical images, and this build makes none"
944
+ )
945
+ firsts = {account.user: account for account in reversed(accounts)}
946
+ for user in dict.fromkeys(users):
947
+ self.problems.extend(names.problems(engine, user, firsts[user].privileges))
948
+
949
+ def strategy(self, graph: Graph, between: tuple[SourceReference, ...]) -> Strategy:
950
+ wanted = self.options.strategy or self.spec.subset.strategy
951
+ acyclic = graph.is_acyclic() and self.capabilities.nested
952
+ if wanted is Strategy.AUTO:
953
+ # No query reads two servers, so references between sources need keys.
954
+ return Strategy.NESTED if acyclic and not between else Strategy.KEYS
955
+ if wanted is Strategy.NESTED and between:
956
+ self.problems.extend(
957
+ f"{reference.edge} joins sources {reference.child_source} and"
958
+ f" {reference.parent_source}, which no one query can read; use the keys strategy"
959
+ for reference in between
960
+ )
961
+ elif wanted is Strategy.NESTED:
962
+ if not self.capabilities.nested:
963
+ self.problems.append(
964
+ f"the {self.catalog.engine} adapter cannot run the nested strategy"
965
+ )
966
+ else:
967
+ try:
968
+ nested_conditions(graph)
969
+ except SubsetError as error:
970
+ self.problems.append(f"{error}; the nested strategy cannot run, use keys")
971
+ return wanted
972
+
973
+ def seeds(
974
+ self, rules: dict[TableName, TableRule], excluded: frozenset[TableName]
975
+ ) -> tuple[PlannedSeed, ...]:
976
+ """Give each seeded table its condition; a table's own name wins over a pattern."""
977
+ exact: dict[TableName, tuple[str, str]] = {}
978
+ by_pattern: dict[TableName, list[tuple[str, str]]] = {}
979
+ for text, predicate in self.spec.subset.seeds.items():
980
+ if _is_glob(text):
981
+ for name in self.seed_pattern(text, rules, excluded):
982
+ by_pattern.setdefault(name, []).append((text, predicate))
983
+ elif (seeded := self.seed_table(text, rules, excluded)) is not None:
984
+ if seeded in exact:
985
+ self.problems.append(
986
+ f"seeds {exact[seeded][0]!r} and {text!r} both name {seeded}"
987
+ )
988
+ exact[seeded] = (text, predicate)
989
+ for name, found in by_pattern.items():
990
+ if name in exact:
991
+ continue
992
+ if len(found) > 1:
993
+ patterns = ", ".join(repr(text) for text, _ in found)
994
+ self.problems.append(
995
+ f"{name} matches more than one seed pattern ({patterns}); "
996
+ "give it a seed of its own, or narrow the patterns"
997
+ )
998
+ else:
999
+ exact[name] = found[0]
1000
+ seeded_by: dict[str, list[TableName]] = {text: [] for text in self.spec.subset.seeds}
1001
+ for name, (text, predicate) in exact.items():
1002
+ rules[name] = rules[name].model_copy(update={"seed": predicate})
1003
+ seeded_by[text].append(name)
1004
+ return tuple(
1005
+ PlannedSeed(pattern=text, tables=tuple(sorted(names, key=str)))
1006
+ for text, names in seeded_by.items()
1007
+ )
1008
+
1009
+ def seed_pattern(
1010
+ self, text: str, rules: dict[TableName, TableRule], excluded: frozenset[TableName]
1011
+ ) -> tuple[TableName, ...]:
1012
+ """The tables a seed glob gives rows to: those it matches that keep rows."""
1013
+ matched = tuple(
1014
+ name
1015
+ for name in self.resolver.glob(text.strip())
1016
+ if name not in excluded and rules[name].rows_kept
1017
+ )
1018
+ if not matched:
1019
+ self.problems.append(f"seed pattern {text!r} matches no table that keeps rows")
1020
+ return matched
1021
+
1022
+ def seed_table(
1023
+ self, text: str, rules: dict[TableName, TableRule], excluded: frozenset[TableName]
1024
+ ) -> TableName | None:
1025
+ """The table a seed names, if it can take a seed."""
1026
+ table = self.attempt(self.resolver.table, text)
1027
+ if table is None:
1028
+ return None
1029
+ if table.name in excluded:
1030
+ self.problems.append(f"seed {text!r} names {table.name}, which is excluded")
1031
+ return None
1032
+ if not rules[table.name].rows_kept:
1033
+ self.problems.append(f"seed {text!r} names {table.name}, which is structure-only")
1034
+ return None
1035
+ return table.name
1036
+
1037
+ def unselected(
1038
+ self, rules: dict[TableName, TableRule], edges: list[Edge], kept: tuple[TableName, ...]
1039
+ ) -> tuple[TableName, ...]:
1040
+ """Kept tables nothing selects rows from, handled as ``subset.unselected`` says."""
1041
+ if self.capabilities.complete:
1042
+ return () # Every table must already be seeded or excluded.
1043
+ keeps = frozenset(name for name in kept if rules[name].rows_kept)
1044
+ chosen = _reached(rules, edges, keeps)
1045
+ missing = tuple(name for name in kept if name in keeps and name not in chosen)
1046
+ policy = self.spec.subset.unselected or Unselected.FAIL
1047
+ match policy:
1048
+ case Unselected.FAIL:
1049
+ self.problems.extend(
1050
+ f"no seed or followed reference selects rows of {name}; seed it "
1051
+ "(seed keys take globs), follow a reference to it, make it "
1052
+ "structure_only, exclude it, or set subset.unselected to none or all"
1053
+ for name in missing
1054
+ )
1055
+ case Unselected.NONE:
1056
+ self.warnings.extend(
1057
+ f"no seed or followed reference selects rows of {name}; "
1058
+ "it is copied without rows (subset.unselected: none)"
1059
+ for name in missing
1060
+ )
1061
+ case Unselected.ALL:
1062
+ for name in missing:
1063
+ rules[name] = rules[name].model_copy(update={"every_row": True})
1064
+ case _:
1065
+ assert_never(policy)
1066
+ return missing
1067
+
1068
+ def plan(self) -> Plan:
1069
+ excludes = resolve_excludes(self.resolver, self.spec.exclude, self.spec.structure_only)
1070
+ excluded = excludes.excluded()
1071
+ structure_only = excludes.structure_only_tables()
1072
+ kept_tables = [t for t in self.catalog.tables if t.name not in excluded]
1073
+ kept = tuple(table.name for table in kept_tables)
1074
+ # Package planning comes before strict mode, which asks it what a
1075
+ # difference from the lock breaks.
1076
+ edges = self.edges(kept_tables)
1077
+ members = self.members(kept)
1078
+ self.group_roots = self.roots()
1079
+ packaging = Packaging(
1080
+ self.catalog, excluded, structure_only, tuple(edges), self.placement()
1081
+ )
1082
+ self.closures = {
1083
+ name: close(
1084
+ packaging,
1085
+ GroupInput(
1086
+ name=name,
1087
+ tables=frozenset(members[name]),
1088
+ roots=self.group_roots[name],
1089
+ standalone=group.standalone,
1090
+ allowed=self.required(name) | {name},
1091
+ elsewhere=frozenset(
1092
+ table for other in self.required(name) for table in members[other]
1093
+ ),
1094
+ rows=self.rows_rules(name, edges),
1095
+ ),
1096
+ )
1097
+ for name, group in self.spec.images.items()
1098
+ }
1099
+ self.check_standalone()
1100
+ strict = self.strict_report(excluded)
1101
+ if strict is not None and strict.failed():
1102
+ failures = tuple(f"strict mode: {f}" for f in strict.findings if f.severity == "fail")
1103
+ raise PlanError((*self.problems, *failures), strict)
1104
+ for closure in self.closures.values():
1105
+ self.problems.extend(closure.problems)
1106
+ self.warnings.extend(closure.warnings)
1107
+ rules = {
1108
+ table.name: TableRule(table=table.name, rows_kept=table.name not in structure_only)
1109
+ for table in kept_tables
1110
+ }
1111
+ rules.update({name: TableRule(table=name, rows_kept=False) for name in excluded})
1112
+ seeds = self.seeds(rules, excluded)
1113
+ if self.capabilities.complete:
1114
+ self.problems.extend(
1115
+ f"{rule.table} is neither selected nor excluded"
1116
+ for rule in rules.values()
1117
+ if rule.seed is None and rule.table not in excluded and rule.rows_kept
1118
+ )
1119
+ for edge in edges:
1120
+ self.check_edge(edge, rules, excluded)
1121
+ unselected = self.unselected(rules, edges, kept)
1122
+ graph = Graph(rules, tuple(edges))
1123
+ groups = self.groups(kept, edges, rules, members)
1124
+ key_columns = frozenset(
1125
+ [ColumnRef(table=e.child, column=c) for e in edges for c in e.columns]
1126
+ + [ColumnRef(table=e.parent, column=c) for e in edges for c in e.parent_columns]
1127
+ + [ColumnRef(table=t.name, column=c) for t in kept_tables for c in t.primary_key]
1128
+ )
1129
+ anonymization = self.anonymization(excluded, key_columns)
1130
+ rewrites = tuple(
1131
+ ref
1132
+ for hook in self.spec.hooks.after_transform
1133
+ for text in hook.rewrites
1134
+ if (ref := self.attempt(self.resolver.column, text)) is not None
1135
+ )
1136
+ pii_allow = tuple(
1137
+ PiiAllow(column=ref, patterns=patterns)
1138
+ for text, patterns in self.spec.verify.pii_scan.allow.items()
1139
+ if (ref := self.attempt(self.resolver.column, text)) is not None
1140
+ )
1141
+ if not self.capabilities.hooks and (
1142
+ self.spec.hooks.before_load or self.spec.hooks.after_transform
1143
+ ):
1144
+ self.problems.append(f"the {self.catalog.engine} adapter does not run hooks")
1145
+ omitted = self.omits
1146
+ formats = self.formats()
1147
+ between = self.between_sources(edges)
1148
+ strategy = self.strategy(graph, between)
1149
+ paths_from = self.paths_from(excluded)
1150
+ if self.problems:
1151
+ raise PlanError(tuple(self.problems), strict)
1152
+ now = self.options.now or dt.datetime.now(tz=dt.UTC)
1153
+ as_of = self.spec.subset.as_of or now.replace(microsecond=0)
1154
+ return Plan(
1155
+ spec=self.spec.name,
1156
+ engine=self.catalog.engine,
1157
+ as_of=as_of,
1158
+ strategy=strategy,
1159
+ catalog_fingerprint=self.catalog.fingerprint(),
1160
+ excludes=excludes,
1161
+ strict=strict,
1162
+ tables=tuple(rules[name] for name in (*kept, *sorted(excluded, key=str))),
1163
+ edges=tuple(edges),
1164
+ groups=groups,
1165
+ formats=formats,
1166
+ anonymization=anonymization,
1167
+ rewrites=rewrites,
1168
+ pii_allow=pii_allow,
1169
+ assertions=self.spec.verify.assertions,
1170
+ catalog=self.catalog.without(excluded).model_copy(
1171
+ update={
1172
+ "requirements": tuple(r for r in self.catalog.requirements if r not in omitted)
1173
+ }
1174
+ ),
1175
+ omitted=omitted,
1176
+ warnings=tuple(self.warnings),
1177
+ paths_from=paths_from,
1178
+ seeds=seeds,
1179
+ unselected=unselected,
1180
+ sources=self.sources,
1181
+ between_sources=between,
1182
+ spec_layers=self.options.layers,
1183
+ )
1184
+
1185
+ def between_sources(self, edges: Iterable[Edge]) -> tuple[SourceReference, ...]:
1186
+ """References whose child and parent are in different sources."""
1187
+ owner = {n: s.name for s in self.sources for n in s.namespaces}
1188
+ return tuple(
1189
+ SourceReference(
1190
+ edge=edge.name,
1191
+ child=edge.child,
1192
+ child_source=owner[edge.child.outermost],
1193
+ parent=edge.parent,
1194
+ parent_source=owner[edge.parent.outermost],
1195
+ )
1196
+ for edge in edges
1197
+ if owner.get(edge.child.outermost) != owner.get(edge.parent.outermost)
1198
+ )
1199
+
1200
+ def placeholders(self, table: Table, template: str) -> dict[str, ColumnName]:
1201
+ names: dict[str, ColumnName] = {}
1202
+ for text in _PLACEHOLDER.findall(template):
1203
+ column = self.attempt(self.resolver.column_of, table, text)
1204
+ if column is not None:
1205
+ names[text] = column.name
1206
+ if not names:
1207
+ self.problems.append("files.paths_from.path names no column, as {column}")
1208
+ return names
1209
+
1210
+ def check_match(self, pattern: str) -> None:
1211
+ try:
1212
+ groups = re.compile(pattern).groups
1213
+ except re.error as error:
1214
+ self.problems.append(f"files.paths_from.match is not a regular expression: {error}")
1215
+ return
1216
+ if groups < 1:
1217
+ self.problems.append("files.paths_from.match needs a group for the path")
1218
+
1219
+ def paths_from(self, excluded: frozenset[TableName]) -> PlannedPaths | None:
1220
+ files = self.spec.files
1221
+ if files is None or files.paths_from is None:
1222
+ return None
1223
+ given = files.paths_from
1224
+ if isinstance(given, str):
1225
+ # `table.column` is the template `{column}` over that table.
1226
+ ref = self.attempt(self.resolver.column, given)
1227
+ if ref is None:
1228
+ return None
1229
+ given = PathsFrom(table=str(ref.table), path=f"{{{ref.column}}}")
1230
+ table = self.attempt(self.resolver.table, given.table)
1231
+ if table is None:
1232
+ return None
1233
+ if table.name in excluded:
1234
+ self.problems.append(f"files.paths_from names {table.name}, which is excluded")
1235
+ names = self.placeholders(table, given.path)
1236
+ if given.match is not None:
1237
+ self.check_match(given.match)
1238
+ template = _PLACEHOLDER.sub(
1239
+ lambda found: f"{{{names.get(found[1], found[1])}}}", given.path
1240
+ )
1241
+ return PlannedPaths(
1242
+ table=table.name,
1243
+ columns=tuple(dict.fromkeys(names.values())),
1244
+ template=template,
1245
+ match=given.match,
1246
+ )
1247
+
1248
+
1249
+ def _declarer(group: GroupName | None) -> str:
1250
+ """Who declares roots: ``the spec`` or ``group 'billing'``."""
1251
+ return "the spec" if group is None else f"group {group!r}"
1252
+
1253
+
1254
+ def _misfit(column: Column, rule: Rule) -> str | None:
1255
+ """Why ``rule`` cannot apply to ``column``, if it cannot."""
1256
+ allowed: frozenset[ColumnKind] | None
1257
+ match rule:
1258
+ case FakerRule():
1259
+ allowed = _FAKER_KINDS.get(rule.faker, _TEXT)
1260
+ case HashRule() | FormatPreservingRule():
1261
+ allowed = _TEXT_OR_INTEGER
1262
+ case NullRule():
1263
+ return None if column.nullable else "cannot be null, so the null rule cannot apply"
1264
+ case ExpressionRule():
1265
+ return None
1266
+ case _:
1267
+ assert_never(rule)
1268
+ if column.kind in allowed:
1269
+ return None
1270
+ return f"is a {column.kind} column; this rule needs {', '.join(sorted(allowed))}"
1271
+
1272
+
1273
+ _FALLBACKS: dict[OnMissing, EdgeMode] = {
1274
+ OnMissing.NULL: EdgeMode.NULL,
1275
+ OnMissing.STUB: EdgeMode.STUB,
1276
+ OnMissing.DROP: EdgeMode.DROP,
1277
+ }
1278
+
1279
+
1280
+ _PULLS_PARENTS = frozenset({EdgeMode.FOLLOW, EdgeMode.ALL})
1281
+ """Edge modes under which a chosen child row brings in its parent rows."""
1282
+
1283
+
1284
+ def _is_glob(text: str) -> bool:
1285
+ """Whether a seed key is a pattern rather than a table name."""
1286
+ return any(character in text for character in "*?[")
1287
+
1288
+
1289
+ def _reached(
1290
+ rules: Mapping[TableName, TableRule], edges: Iterable[Edge], keeps: frozenset[TableName]
1291
+ ) -> set[TableName]:
1292
+ """Tables among ``keeps`` that a seed, ``follow: all`` or a followed edge gives rows."""
1293
+ edges = tuple(edges)
1294
+ chosen = {name for name in keeps if rules[name].seed is not None or rules[name].every_row}
1295
+ chosen |= {e.parent for e in edges if e.mode is EdgeMode.ALL and e.parent in keeps}
1296
+ grew = True
1297
+ while grew:
1298
+ grew = False
1299
+ for edge in edges:
1300
+ pulled: list[TableName] = []
1301
+ if edge.child in chosen and edge.mode in _PULLS_PARENTS:
1302
+ pulled.append(edge.parent)
1303
+ if edge.down and edge.parent in chosen:
1304
+ pulled.append(edge.child)
1305
+ for name in pulled:
1306
+ if name in keeps and name not in chosen:
1307
+ chosen.add(name)
1308
+ grew = True
1309
+ return chosen
1310
+
1311
+
1312
+ def _mode(policy: EdgePolicy) -> EdgeMode:
1313
+ # EdgePolicy holds exactly one of `follow: all` and `on_missing`.
1314
+ return EdgeMode.ALL if policy.on_missing is None else _FALLBACKS[policy.on_missing]
1315
+
1316
+
1317
+ def collisions(sources: Sequence[SourceCatalog]) -> list[str]:
1318
+ """Each database (outermost namespace) more than one source reads, named.
1319
+
1320
+ One working server holds every source's databases under their own names,
1321
+ so none may repeat, even one without tables.
1322
+ """
1323
+ holders: dict[str, list[SourceName]] = {}
1324
+ for source in sources:
1325
+ for namespace in source.databases():
1326
+ holders.setdefault(namespace, []).append(source.name)
1327
+ return [
1328
+ f"{namespace} is in sources {' and '.join(names)}; one working server holds every"
1329
+ " source, so database names must not repeat across sources"
1330
+ for namespace, names in holders.items()
1331
+ if len(names) > 1
1332
+ ]
1333
+
1334
+
1335
+ def merge(sources: Sequence[SourceCatalog]) -> Catalog:
1336
+ """Every source's catalog as one, for planning and the lock.
1337
+
1338
+ Requirements are listed once each. A table only the :func:`collisions`
1339
+ already report could repeat; the first source's is kept.
1340
+ """
1341
+ if not sources:
1342
+ message = "a spec needs at least one source"
1343
+ raise ValueError(message)
1344
+ if len(sources) == 1:
1345
+ return sources[0].catalog
1346
+ tables: dict[TableName, Table] = {}
1347
+ requirements: dict[Requirement, None] = {}
1348
+ for source in sources:
1349
+ for table in source.catalog.tables:
1350
+ tables.setdefault(table.name, table)
1351
+ requirements.update(dict.fromkeys(source.catalog.requirements))
1352
+ return Catalog(
1353
+ engine=sources[0].catalog.engine,
1354
+ tables=tuple(tables.values()),
1355
+ requirements=tuple(requirements),
1356
+ )
1357
+
1358
+
1359
+ def _key(requirement: Requirement) -> tuple[str, str]:
1360
+ return (requirement.kind, requirement.name)
1361
+
1362
+
1363
+ def _own_omits(spec: Spec, source: SourceCatalog, problems: list[str]) -> list[Requirement]:
1364
+ """The requirements a source's ``omit`` names; a name it does not use is a problem."""
1365
+ found: list[Requirement] = []
1366
+ for name in spec.sources[source.name].omit:
1367
+ requirement = source.catalog.requirement(name)
1368
+ if requirement is None:
1369
+ problems.append(
1370
+ f"sources.{source.name}.omit names {name!r}, which the source does not use"
1371
+ )
1372
+ else:
1373
+ found.append(requirement)
1374
+ return found
1375
+
1376
+
1377
+ def _requirement_problems(
1378
+ sources: Sequence[SourceCatalog], omits: Mapping[SourceName, list[Requirement]]
1379
+ ) -> list[str]:
1380
+ """Requirements the sources disagree on: at different versions, or omitted by only some.
1381
+
1382
+ One working server provides each requirement once, at one version, or not at all.
1383
+ """
1384
+ problems: list[str] = []
1385
+ users: dict[tuple[str, str], list[tuple[SourceName, Requirement]]] = {}
1386
+ for source in sources:
1387
+ for requirement in source.catalog.requirements:
1388
+ users.setdefault(_key(requirement), []).append((source.name, requirement))
1389
+ for (kind, name), found in users.items():
1390
+ first_source, first = found[0]
1391
+ for other_source, other in found[1:]:
1392
+ if other.version != first.version:
1393
+ problems.append(
1394
+ f"{kind} {name} is at version {first.version} in source {first_source}"
1395
+ f" and {other.version} in source {other_source}; one working server"
1396
+ " provides one version, so the sources must agree"
1397
+ )
1398
+ omitting = [s for s, _ in found if any(_key(r) == (kind, name) for r in omits[s])]
1399
+ if omitting:
1400
+ problems.extend(
1401
+ f"source {omitter} omits {kind} {name}, which source {user} uses; one working"
1402
+ " server holds every source, so omit it in every source that uses it, or in none"
1403
+ for omitter in omitting
1404
+ for user, _ in found
1405
+ if user not in omitting
1406
+ )
1407
+ return problems
1408
+
1409
+
1410
+ def _planned_sources(
1411
+ spec: Spec, sources: Sequence[SourceCatalog], capabilities: Capabilities
1412
+ ) -> tuple[tuple[PlannedSource, ...], tuple[Requirement, ...], list[str]]:
1413
+ """Each source as planned, the requirements the copies leave out, and problems."""
1414
+ problems: list[str] = []
1415
+ if len(sources) > 1 and not capabilities.several_sources:
1416
+ problems.append(
1417
+ f"the {sources[0].catalog.engine} adapter reads one source per spec;"
1418
+ f" this spec has {len(sources)}"
1419
+ )
1420
+ return (), (), problems
1421
+ problems.extend(collisions(sources))
1422
+ lines = {
1423
+ source.name: version_line(source.server_version, capabilities.version_line)
1424
+ for source in sources
1425
+ }
1426
+ if len(set(lines.values())) > 1:
1427
+ listed = ", ".join(f"{s.name} {s.server_version}" for s in sources)
1428
+ problems.append(
1429
+ f"the sources run different version lines ({listed}); one working server"
1430
+ " cannot hold them all, so every source must share a line"
1431
+ )
1432
+ omits = {source.name: _own_omits(spec, source, problems) for source in sources}
1433
+ problems.extend(_requirement_problems(sources, omits))
1434
+ omitted = tuple(dict.fromkeys(r for found in omits.values() for r in found))
1435
+ planned = tuple(
1436
+ PlannedSource(
1437
+ name=source.name,
1438
+ server_version=source.server_version,
1439
+ catalog_fingerprint=source.catalog.fingerprint(),
1440
+ namespaces=source.databases(),
1441
+ requirements=tuple(r for r in source.catalog.requirements if r not in omitted),
1442
+ )
1443
+ for source in sources
1444
+ )
1445
+ return planned, omitted, problems
1446
+
1447
+
1448
+ def plan(
1449
+ spec: Spec,
1450
+ sources: Sequence[SourceCatalog],
1451
+ lock: CatalogLock | None,
1452
+ capabilities: Capabilities,
1453
+ options: PlanOptions | None = None,
1454
+ ) -> Plan:
1455
+ """Plan a build; raises :class:`PlanError` listing every problem found.
1456
+
1457
+ ``sources`` are the spec's sources' live catalogs, in the spec's order;
1458
+ they are planned as one catalog. A subset from Jailer is translated
1459
+ against it first; its excluded tables join the spec's.
1460
+ """
1461
+ planned_sources, omitted, problems = _planned_sources(spec, sources, capabilities)
1462
+ if not planned_sources:
1463
+ raise PlanError(tuple(problems))
1464
+ catalog = merge(sources)
1465
+ warnings: tuple[str, ...] = ()
1466
+ if spec.subset.jailer is not None:
1467
+ try:
1468
+ translated = jailer.load(
1469
+ spec.subset.jailer.model,
1470
+ spec.subset.jailer.datamodel,
1471
+ catalog,
1472
+ case_sensitive=spec.case_sensitive,
1473
+ )
1474
+ except jailer.JailerError as error:
1475
+ raise PlanError((f"the Jailer subset: {error}",)) from None
1476
+ subset = translated.subset.model_copy(
1477
+ update={"as_of": spec.subset.as_of, "strategy": spec.subset.strategy}
1478
+ )
1479
+ exclude = tuple(dict.fromkeys((*spec.exclude, *translated.exclude)))
1480
+ spec = spec.model_copy(update={"subset": subset, "exclude": exclude})
1481
+ warnings = tuple(f"Jailer subset: {line}" for line in translated.report)
1482
+ planner = _Planner(spec, catalog, lock, capabilities, options or PlanOptions())
1483
+ planner.sources = planned_sources
1484
+ users: dict[str, list[SourceName]] = {}
1485
+ for source in sources:
1486
+ for requirement in source.catalog.requirements:
1487
+ users.setdefault(str(requirement), []).append(source.name)
1488
+ planner.users = {text: tuple(names) for text, names in users.items()}
1489
+ planner.omits = omitted
1490
+ planner.problems.extend(problems)
1491
+ planned = planner.plan()
1492
+ return planned.model_copy(update={"warnings": (*warnings, *planned.warnings)})