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/strict.py ADDED
@@ -0,0 +1,498 @@
1
+ # Copyright (c) 2026- Tight Line LLC
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ """Excludes and strict mode.
5
+
6
+ Excludes are resolved first, against the live catalog. Strict mode then
7
+ compares what is left with the catalog lock. ``strict.data`` sets how tables,
8
+ columns and requirements are treated:
9
+
10
+ ========================================= ======= ======== ===========
11
+ Difference from the lock off tables columns
12
+ ========================================= ======= ======== ===========
13
+ Known table or column removed fail fail fail
14
+ Known table's keys changed fail fail fail
15
+ Known column's type or nullability changed warn warn fail
16
+ New table matching an exclude pattern ignored ignored ignored
17
+ New table, not excluded warn fail fail
18
+ New column in a known table warn warn fail
19
+ Requirement removed or at another version fail fail fail
20
+ New requirement warn fail fail
21
+ ========================================= ======= ======== ===========
22
+
23
+ A difference that breaks something fails whatever the level. The caller says
24
+ which do through a :data:`Breaks` function, since only planning knows what a
25
+ difference breaks: a changed column whose anonymization rule no longer fits
26
+ it, for one.
27
+
28
+ Requirements are the extensions, plugins and modules the source uses; see
29
+ :class:`~datadouble.catalog.Requirement`.
30
+
31
+ Each kind of object (functions and procedures, views, triggers, types,
32
+ sequences, events) has its own level: ``off`` compares nothing, ``warn``
33
+ names each new, changed or removed object, and ``fail`` fails on any
34
+ difference. A removed object that a remaining object still depends on breaks
35
+ that object, so it fails at every level, naming both. Everything else an
36
+ object difference might break (a packaged table needing a changed function, a
37
+ new trigger needing what an image cannot have) is for the planner's
38
+ :data:`Breaks` function to say.
39
+ """
40
+
41
+ from collections.abc import Callable
42
+ from enum import StrEnum
43
+
44
+ from pydantic import BaseModel, ConfigDict
45
+
46
+ from datadouble.catalog import (
47
+ Catalog,
48
+ CatalogLock,
49
+ Dependency,
50
+ ObjectKind,
51
+ ObjectRef,
52
+ Requirement,
53
+ SourceObject,
54
+ Table,
55
+ )
56
+ from datadouble.names import TableName
57
+ from datadouble.resolve import Resolver
58
+ from datadouble.spec import ObjectLevel, Strict, StrictKind, StrictLevel
59
+
60
+
61
+ class _Model(BaseModel):
62
+ model_config = ConfigDict(strict=True, frozen=True, extra="forbid")
63
+
64
+
65
+ class PatternMatch(_Model):
66
+ """The tables one exclude or structure-only pattern matched."""
67
+
68
+ pattern: str
69
+ tables: tuple[TableName, ...]
70
+
71
+
72
+ class Excludes(_Model):
73
+ """Excludes and structure-only patterns, resolved once at plan time."""
74
+
75
+ exclude: tuple[PatternMatch, ...]
76
+ structure_only: tuple[PatternMatch, ...]
77
+
78
+ def excluded(self) -> frozenset[TableName]:
79
+ """Every excluded table."""
80
+ return frozenset(name for match in self.exclude for name in match.tables)
81
+
82
+ def structure_only_tables(self) -> frozenset[TableName]:
83
+ """Every table kept without rows."""
84
+ return frozenset(name for match in self.structure_only for name in match.tables)
85
+
86
+
87
+ def resolve_excludes(
88
+ resolver: Resolver, exclude: tuple[str, ...], structure_only: tuple[str, ...]
89
+ ) -> Excludes:
90
+ """Match exclude and structure-only patterns against the catalog."""
91
+ return Excludes(
92
+ exclude=tuple(PatternMatch(pattern=p, tables=resolver.glob(p)) for p in exclude),
93
+ structure_only=tuple(
94
+ PatternMatch(pattern=p, tables=resolver.glob(p)) for p in structure_only
95
+ ),
96
+ )
97
+
98
+
99
+ class Difference(StrEnum):
100
+ """Ways the live catalog can differ from the lock."""
101
+
102
+ TABLE_REMOVED = "table-removed"
103
+ TABLE_CHANGED = "table-changed"
104
+ COLUMN_REMOVED = "column-removed"
105
+ COLUMN_CHANGED = "column-changed"
106
+ NEW_TABLE = "new-table"
107
+ NEW_COLUMN = "new-column"
108
+ REQUIREMENT_REMOVED = "requirement-removed"
109
+ REQUIREMENT_CHANGED = "requirement-changed"
110
+ NEW_REQUIREMENT = "new-requirement"
111
+ OBJECT_REMOVED = "object-removed"
112
+ OBJECT_CHANGED = "object-changed"
113
+ NEW_OBJECT = "new-object"
114
+
115
+
116
+ class Severity(StrEnum):
117
+ """What a difference does to the run."""
118
+
119
+ FAIL = "fail"
120
+ WARN = "warn"
121
+
122
+
123
+ TABLE_RESOLUTIONS = (
124
+ "exclude it",
125
+ "list it in `structure_only`, then re-lock with `datadouble lock`",
126
+ "add anonymization rules for any personal data it holds, then re-lock with `datadouble lock`",
127
+ )
128
+ """The ways to resolve a new table, in the order to consider them."""
129
+
130
+ COLUMN_RESOLUTIONS = (
131
+ (
132
+ "add an anonymization rule for it if it holds personal data, "
133
+ "then re-lock with `datadouble lock`"
134
+ ),
135
+ )
136
+ """The way to resolve a new column: columns can't be excluded, only their tables."""
137
+
138
+ REQUIREMENT_RESOLUTIONS = (
139
+ "check that the working image provides it, then re-lock with `datadouble lock`",
140
+ "leave it out with `sources.<name>.omit`, then re-lock with `datadouble lock`",
141
+ )
142
+ """The ways to resolve a new requirement."""
143
+
144
+ CHANGE_RESOLUTIONS = (
145
+ (
146
+ "check that the copies and the anonymization rules still suit it, "
147
+ "then re-lock with `datadouble lock`"
148
+ ),
149
+ )
150
+ """The way to resolve a changed column or object."""
151
+
152
+ OBJECT_RESOLUTIONS = (
153
+ (
154
+ "check what it does to the copies (a trigger or function can change what they "
155
+ "hold), then re-lock with `datadouble lock`"
156
+ ),
157
+ )
158
+ """The way to resolve a new, changed or removed object."""
159
+
160
+ SETTINGS: dict[ObjectKind, StrictKind] = {
161
+ ObjectKind.FUNCTION: StrictKind.FUNCTIONS,
162
+ ObjectKind.PROCEDURE: StrictKind.FUNCTIONS,
163
+ ObjectKind.PACKAGE: StrictKind.FUNCTIONS,
164
+ ObjectKind.VIEW: StrictKind.VIEWS,
165
+ ObjectKind.MATERIALIZED_VIEW: StrictKind.VIEWS,
166
+ ObjectKind.TRIGGER: StrictKind.TRIGGERS,
167
+ ObjectKind.TYPE: StrictKind.TYPES,
168
+ ObjectKind.SEQUENCE: StrictKind.SEQUENCES,
169
+ ObjectKind.EVENT: StrictKind.EVENTS,
170
+ }
171
+ """The ``strict`` setting each kind of object falls under."""
172
+
173
+
174
+ class Finding(_Model):
175
+ """One difference between the live catalog and the lock."""
176
+
177
+ difference: Difference
178
+ severity: Severity
179
+ object: str
180
+ detail: str
181
+ resolutions: tuple[str, ...] = ()
182
+ breaks: str | None = None
183
+ """What the difference breaks, when it does; such a difference always fails."""
184
+ kind: StrictKind = StrictKind.DATA
185
+ """The ``strict`` setting the difference falls under."""
186
+ ref: ObjectRef | None = None
187
+ """The object that differs, for differences in objects."""
188
+
189
+ def __str__(self) -> str:
190
+ """``new-column public.users.phone: detail``, and what it breaks, if anything."""
191
+ text = f"{self.difference} {self.object}: {self.detail}"
192
+ return text if self.breaks is None else f"{text}; {self.breaks}"
193
+
194
+
195
+ type Breaks = Callable[[Finding], str | None]
196
+ """What a difference breaks, if anything: planning's judgement, given to strict mode."""
197
+
198
+
199
+ def _breaks_nothing(_finding: Finding) -> str | None:
200
+ return None
201
+
202
+
203
+ class StrictReport(_Model):
204
+ """Strict mode's verdict on a plan."""
205
+
206
+ strict: Strict
207
+ """The levels the catalog was compared at."""
208
+ lock_fingerprint: str
209
+ findings: tuple[Finding, ...]
210
+
211
+ def failed(self) -> bool:
212
+ """Whether any finding stops the run."""
213
+ return any(finding.severity is Severity.FAIL for finding in self.findings)
214
+
215
+
216
+ def _severity_new_table(level: StrictLevel) -> Severity:
217
+ return Severity.WARN if level is StrictLevel.OFF else Severity.FAIL
218
+
219
+
220
+ def _severity_new_column(level: StrictLevel) -> Severity:
221
+ return Severity.FAIL if level is StrictLevel.COLUMNS else Severity.WARN
222
+
223
+
224
+ def _compare_table(live: Table, locked: Table, level: StrictLevel) -> list[Finding]:
225
+ findings: list[Finding] = []
226
+ live_columns = {column.name: column for column in live.columns}
227
+ for column in locked.columns:
228
+ found = live_columns.pop(column.name, None)
229
+ name = f"{live.name}.{column.name}"
230
+ if found is None:
231
+ findings.append(
232
+ Finding(
233
+ difference=Difference.COLUMN_REMOVED,
234
+ severity=Severity.FAIL,
235
+ object=name,
236
+ detail="the column is in the lock but not in the live catalog",
237
+ )
238
+ )
239
+ elif found != column:
240
+ findings.append(
241
+ Finding(
242
+ difference=Difference.COLUMN_CHANGED,
243
+ severity=_severity_new_column(level),
244
+ object=name,
245
+ detail=(
246
+ f"locked as {column.type} ({'null' if column.nullable else 'not null'}),"
247
+ f" now {found.type} ({'null' if found.nullable else 'not null'})"
248
+ ),
249
+ resolutions=CHANGE_RESOLUTIONS,
250
+ )
251
+ )
252
+ findings.extend(
253
+ Finding(
254
+ difference=Difference.NEW_COLUMN,
255
+ severity=_severity_new_column(level),
256
+ object=f"{live.name}.{name}",
257
+ detail="the column is not in the lock",
258
+ resolutions=COLUMN_RESOLUTIONS,
259
+ )
260
+ for name in live_columns
261
+ )
262
+ if live.primary_key != locked.primary_key or set(live.foreign_keys) != set(locked.foreign_keys):
263
+ findings.append(
264
+ Finding(
265
+ difference=Difference.TABLE_CHANGED,
266
+ severity=Severity.FAIL,
267
+ object=str(live.name),
268
+ detail="its primary key or foreign keys differ from the lock; re-lock",
269
+ )
270
+ )
271
+ return findings
272
+
273
+
274
+ def _compare_requirements(
275
+ live: tuple[Requirement, ...], locked: tuple[Requirement, ...], level: StrictLevel
276
+ ) -> list[Finding]:
277
+ findings: list[Finding] = []
278
+ current = {(r.kind, r.name): r for r in live}
279
+ for requirement in locked:
280
+ found = current.pop((requirement.kind, requirement.name), None)
281
+ if found is None:
282
+ findings.append(
283
+ Finding(
284
+ difference=Difference.REQUIREMENT_REMOVED,
285
+ severity=Severity.FAIL,
286
+ object=str(requirement),
287
+ detail="the source no longer uses it; re-lock",
288
+ )
289
+ )
290
+ elif found.version != requirement.version:
291
+ findings.append(
292
+ Finding(
293
+ difference=Difference.REQUIREMENT_CHANGED,
294
+ severity=Severity.FAIL,
295
+ object=str(found),
296
+ detail=f"locked at version {requirement.version}; re-lock",
297
+ )
298
+ )
299
+ findings.extend(
300
+ Finding(
301
+ difference=Difference.NEW_REQUIREMENT,
302
+ severity=_severity_new_table(level),
303
+ object=str(requirement),
304
+ detail="the source uses it, and the lock does not",
305
+ resolutions=REQUIREMENT_RESOLUTIONS,
306
+ )
307
+ for requirement in current.values()
308
+ )
309
+ return findings
310
+
311
+
312
+ def _same_name(ref: ObjectRef) -> tuple[StrictKind, tuple[str, ...], str]:
313
+ """What an inferred edge can tell: the kind of setting, namespace and name, no signature."""
314
+ return (SETTINGS[ref.kind], ref.namespace, ref.name)
315
+
316
+
317
+ def _names(edge: Dependency, ref: ObjectRef, *, by_name: bool) -> bool:
318
+ """Whether ``edge`` names ``ref``: exactly, or by kind of setting, namespace and name."""
319
+ if edge.object is None:
320
+ return False
321
+ return _same_name(edge.object) == _same_name(ref) if by_name else edge.object == ref
322
+
323
+
324
+ class _Objects:
325
+ """The objects of the lock and the live catalog, compared under each kind's level.
326
+
327
+ Objects whose exact edges name only excluded tables are left out of copies,
328
+ so they are ignored, as excluded tables are.
329
+ """
330
+
331
+ def __init__(self, live: Catalog, lock: Catalog, excluded: frozenset[TableName]) -> None:
332
+ self.live = {o.ref: o for o in live.objects if not o.needs_only(excluded)}
333
+ self.locked = {o.ref: o for o in lock.objects if not o.needs_only(excluded)}
334
+ self.excluded = excluded
335
+ self.names = {_same_name(ref) for ref in self.live}
336
+
337
+ def findings(self, strict: Strict) -> list[tuple[Finding, bool]]:
338
+ """Each difference, and whether its kind's level ignores it unless it breaks something."""
339
+ found: list[tuple[Finding, bool]] = []
340
+ for ref, locked in self.locked.items():
341
+ current = self.live.get(ref)
342
+ if current is None:
343
+ found.append(self.removed(ref, strict))
344
+ elif current.fingerprint != locked.fingerprint:
345
+ found.append(
346
+ self.finding(
347
+ Difference.OBJECT_CHANGED,
348
+ ref,
349
+ strict,
350
+ "its definition differs from the lock",
351
+ )
352
+ )
353
+ found.extend(
354
+ self.finding(Difference.NEW_OBJECT, ref, strict, "the object is not in the lock")
355
+ for ref in self.live
356
+ if ref not in self.locked
357
+ )
358
+ return found
359
+
360
+ def removed(self, ref: ObjectRef, strict: Strict) -> tuple[Finding, bool]:
361
+ """A removed object, naming what may still need it by an inferred edge.
362
+
363
+ Inferred edges never fail the plan, but a removal they rest on warns
364
+ even at ``off``, and fails at ``fail``.
365
+ """
366
+ detail = "the object is in the lock but not in the live catalog"
367
+ maybe = self.needing(ref, inferred=True)
368
+ if maybe is None:
369
+ return self.finding(Difference.OBJECT_REMOVED, ref, strict, detail)
370
+ finding, _ = self.finding(Difference.OBJECT_REMOVED, ref, strict, f"{detail}; {maybe}")
371
+ return finding, False
372
+
373
+ def finding(
374
+ self, difference: Difference, ref: ObjectRef, strict: Strict, detail: str
375
+ ) -> tuple[Finding, bool]:
376
+ kind = SETTINGS[ref.kind]
377
+ level = strict.level(kind)
378
+ finding = Finding(
379
+ difference=difference,
380
+ severity=Severity.FAIL if level is ObjectLevel.FAIL else Severity.WARN,
381
+ object=str(ref),
382
+ detail=detail,
383
+ resolutions=OBJECT_RESOLUTIONS,
384
+ kind=kind,
385
+ ref=ref,
386
+ )
387
+ return finding, level is ObjectLevel.OFF
388
+
389
+ def breaks(self, finding: Finding) -> str | None:
390
+ """For a removed object, the remaining objects whose exact edges still name it."""
391
+ if finding.difference is not Difference.OBJECT_REMOVED or finding.ref is None:
392
+ return None
393
+ return self.needing(finding.ref, inferred=False)
394
+
395
+ def needing(self, ref: ObjectRef, *, inferred: bool) -> str | None:
396
+ """The remaining objects that need ``ref`` by exact, or by inferred, edges.
397
+
398
+ A remaining object's edges are its live ones, and its locked ones when
399
+ its definition is unchanged. Objects that need an excluded table are
400
+ left out of copies, so they need nothing. An inferred edge knows a name,
401
+ not a signature, so it needs ``ref`` only when nothing of that name is
402
+ left.
403
+ """
404
+ if inferred and _same_name(ref) in self.names:
405
+ return None
406
+ how = "may still need it (an inferred dependency)" if inferred else "still needs it"
407
+ needing = [
408
+ f"{item.ref} {how}"
409
+ for item in self.live.values()
410
+ if not item.needs_table(self.excluded)
411
+ for edge in self.edges(item)
412
+ if edge.inferred == inferred and _names(edge, ref, by_name=inferred)
413
+ ]
414
+ return "; ".join(dict.fromkeys(needing)) or None
415
+
416
+ def edges(self, item: SourceObject) -> tuple[Dependency, ...]:
417
+ locked = self.locked.get(item.ref)
418
+ if locked is None or locked.fingerprint != item.fingerprint:
419
+ return item.depends_on
420
+ return (*item.depends_on, *locked.depends_on)
421
+
422
+
423
+ def _judged(finding: Finding, breaks: Breaks) -> Finding:
424
+ """``finding``, failing with the reason when it breaks something."""
425
+ if finding.severity is Severity.FAIL and finding.difference in _ALWAYS_FAIL:
426
+ return finding
427
+ reason = breaks(finding)
428
+ if reason is None:
429
+ return finding
430
+ return finding.model_copy(update={"severity": Severity.FAIL, "breaks": reason})
431
+
432
+
433
+ _ALWAYS_FAIL = frozenset(
434
+ {
435
+ Difference.TABLE_REMOVED,
436
+ Difference.TABLE_CHANGED,
437
+ Difference.COLUMN_REMOVED,
438
+ Difference.REQUIREMENT_REMOVED,
439
+ Difference.REQUIREMENT_CHANGED,
440
+ }
441
+ )
442
+ """Differences that fail at every level, whatever they break."""
443
+
444
+
445
+ def check_strict(
446
+ live: Catalog,
447
+ locked: CatalogLock,
448
+ excluded: frozenset[TableName],
449
+ strict: Strict,
450
+ breaks: Breaks = _breaks_nothing,
451
+ ) -> StrictReport:
452
+ """Compare the live catalog, minus excluded tables, with the lock.
453
+
454
+ ``breaks`` says what a difference breaks, if anything; one that breaks
455
+ something fails whatever the levels.
456
+ """
457
+ level = strict.data
458
+ lock = locked.catalog
459
+ findings: list[Finding] = []
460
+ for locked_table in lock.tables:
461
+ if locked_table.name in excluded:
462
+ continue
463
+ current = live.table(locked_table.name)
464
+ if current is None:
465
+ findings.append(
466
+ Finding(
467
+ difference=Difference.TABLE_REMOVED,
468
+ severity=Severity.FAIL,
469
+ object=str(locked_table.name),
470
+ detail="the table is in the lock but not in the live catalog",
471
+ )
472
+ )
473
+ else:
474
+ findings.extend(_compare_table(current, locked_table, level))
475
+ locked_names = set(lock.names())
476
+ findings.extend(
477
+ Finding(
478
+ difference=Difference.NEW_TABLE,
479
+ severity=_severity_new_table(level),
480
+ object=str(table.name),
481
+ detail="the table is not in the lock and matches no exclude pattern",
482
+ resolutions=TABLE_RESOLUTIONS,
483
+ )
484
+ for table in live.tables
485
+ if table.name not in locked_names and table.name not in excluded
486
+ )
487
+ findings.extend(_compare_requirements(live.requirements, lock.requirements, level))
488
+ judged = [_judged(finding, breaks) for finding in findings]
489
+ objects = _Objects(live, lock, excluded)
490
+
491
+ def object_breaks(finding: Finding) -> str | None:
492
+ return objects.breaks(finding) or breaks(finding)
493
+
494
+ for finding, ignored in objects.findings(strict):
495
+ result = _judged(finding, object_breaks)
496
+ if not ignored or result.breaks is not None:
497
+ judged.append(result)
498
+ return StrictReport(strict=strict, lock_fingerprint=locked.fingerprint, findings=tuple(judged))