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/catalog.py ADDED
@@ -0,0 +1,677 @@
1
+ # Copyright (c) 2026- Tight Line LLC
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ """Catalogs and catalog locks.
5
+
6
+ An engine adapter introspects a source into a :class:`Catalog`: its tables,
7
+ columns, primary keys and foreign keys, the add-ons the source depends on
8
+ (its :class:`Requirement` list), and its other objects (functions, views,
9
+ triggers and the like, as :class:`SourceObject`), each with a fingerprint of
10
+ its definition and the tables and objects it depends on. A table lists what
11
+ it needs too, such as the sequence a column's default draws from.
12
+ ``datadouble lock`` writes the catalog to the spec's lock next to it (``shop.lock``
13
+ for ``shop.yml``), listing what changed since the lock it replaces (:func:`changes`), and strict
14
+ mode compares the live catalog against it at plan time.
15
+
16
+ A lock holds names, engine type names, keys, requirement versions and
17
+ fingerprints of object definitions, never data values, so it may be published
18
+ where data may not (decision 123). An engine's type name can carry schema
19
+ literals, such as a MySQL ``enum`` or ``set`` column's labels; they are part
20
+ of the schema, already in the committed lock, so publishing the lock exposes
21
+ nothing more.
22
+ """
23
+
24
+ import hashlib
25
+ import json
26
+ from enum import StrEnum
27
+ from pathlib import Path
28
+ from typing import Literal
29
+
30
+ from pydantic import BaseModel, ConfigDict, ValidationError, model_validator
31
+
32
+ from datadouble.names import ColumnName, EngineName, TableName
33
+
34
+
35
+ class CatalogError(Exception):
36
+ """A catalog or lock that cannot be used."""
37
+
38
+
39
+ class _Model(BaseModel):
40
+ model_config = ConfigDict(strict=True, frozen=True, extra="forbid")
41
+
42
+
43
+ class ColumnKind(StrEnum):
44
+ """The engine-neutral family of a column's type.
45
+
46
+ Anonymization strategies and the PII scan work by kind; the engine's own
47
+ type name is kept alongside it.
48
+ """
49
+
50
+ TEXT = "text"
51
+ INTEGER = "integer"
52
+ DECIMAL = "decimal"
53
+ FLOAT = "float"
54
+ BOOLEAN = "boolean"
55
+ DATE = "date"
56
+ TIMESTAMP = "timestamp"
57
+ TIME = "time"
58
+ BINARY = "binary"
59
+ JSON = "json"
60
+ UUID = "uuid"
61
+ ARRAY = "array"
62
+ OTHER = "other"
63
+
64
+
65
+ class Column(_Model):
66
+ """A column, with its type as the engine spells it and its kind."""
67
+
68
+ name: ColumnName
69
+ type: str
70
+ kind: ColumnKind
71
+ nullable: bool
72
+
73
+
74
+ class ForeignKey(_Model):
75
+ """A declared foreign key from some of a table's columns to another table."""
76
+
77
+ name: str
78
+ columns: tuple[ColumnName, ...]
79
+ target: TableName
80
+ target_columns: tuple[ColumnName, ...]
81
+
82
+
83
+ class RequirementKind(StrEnum):
84
+ """The engine-neutral family of something a source needs beyond the server itself."""
85
+
86
+ EXTENSION = "extension"
87
+ PLUGIN = "plugin"
88
+ MODULE = "module"
89
+ PACKAGE = "package"
90
+ OPTION = "option"
91
+
92
+
93
+ class Requirement(_Model):
94
+ """An add-on the source uses, which the working image must provide.
95
+
96
+ ``version`` is the version the source runs, when the engine has one; the
97
+ working image must provide exactly that version.
98
+ """
99
+
100
+ kind: RequirementKind
101
+ name: str
102
+ version: str | None = None
103
+
104
+ def __str__(self) -> str:
105
+ """``extension vector 0.8.2``."""
106
+ return " ".join(part for part in (self.kind.value, self.name, self.version) if part)
107
+
108
+
109
+ class ObjectKind(StrEnum):
110
+ """The engine-neutral kinds of object besides tables.
111
+
112
+ A ``package`` is a package of routines, such as Oracle's: its
113
+ specification and body together.
114
+ """
115
+
116
+ FUNCTION = "function"
117
+ PROCEDURE = "procedure"
118
+ PACKAGE = "package"
119
+ VIEW = "view"
120
+ MATERIALIZED_VIEW = "materialized-view"
121
+ TRIGGER = "trigger"
122
+ TYPE = "type"
123
+ SEQUENCE = "sequence"
124
+ EVENT = "event"
125
+
126
+
127
+ class ObjectRef(_Model):
128
+ """Which object: its kind, namespaces and name, and a routine's argument types.
129
+
130
+ ``namespace`` is the path of namespaces holding it, outermost first, as a
131
+ table's is (:class:`~datadouble.names.TableName`): ``(database, schema)``
132
+ for PostgreSQL. ``signature`` tells overloaded routines apart, as
133
+ ``(integer, text)``.
134
+ """
135
+
136
+ kind: ObjectKind
137
+ namespace: tuple[str, ...]
138
+ name: str
139
+ signature: str | None = None
140
+
141
+ def __str__(self) -> str:
142
+ """``function shop.public.total(integer)``."""
143
+ return f"{self.kind} {'.'.join((*self.namespace, self.name))}{self.signature or ''}"
144
+
145
+
146
+ class Dependency(_Model):
147
+ """A table or object another object needs.
148
+
149
+ ``inferred`` marks an edge found by parsing a definition's text rather
150
+ than read from the engine's own dependency records, so a person knows to
151
+ check it.
152
+ """
153
+
154
+ table: TableName | None = None
155
+ object: ObjectRef | None = None
156
+ inferred: bool = False
157
+
158
+ @model_validator(mode="after")
159
+ def _one_target(self) -> "Dependency":
160
+ if (self.table is None) == (self.object is None):
161
+ message = "a dependency names either a table or an object"
162
+ raise ValueError(message)
163
+ return self
164
+
165
+ @property
166
+ def target(self) -> "TableName | ObjectRef":
167
+ """The table or object it names."""
168
+ # Exactly one is set, as the model checks.
169
+ return next(node for node in (self.object, self.table) if node is not None)
170
+
171
+ def __str__(self) -> str:
172
+ """``table public.users``, or the object, with ``(inferred)`` when it is."""
173
+ target = f"table {self.table}" if self.object is None else str(self.object)
174
+ return f"{target} (inferred)" if self.inferred else target
175
+
176
+
177
+ class Table(_Model):
178
+ """A table, the keys the subset planner follows, and the objects it needs."""
179
+
180
+ name: TableName
181
+ columns: tuple[Column, ...]
182
+ primary_key: tuple[ColumnName, ...] = ()
183
+ foreign_keys: tuple[ForeignKey, ...] = ()
184
+ depends_on: tuple[Dependency, ...] = ()
185
+ """What its definition uses besides its foreign keys: a sequence or function
186
+ in a column's default, a column's user-defined type, a function in a check
187
+ constraint, or a table a row-level security policy reads."""
188
+
189
+ def column(self, name: ColumnName) -> Column | None:
190
+ """The column called ``name``, if there is one."""
191
+ return next((column for column in self.columns if column.name == name), None)
192
+
193
+
194
+ class SourceObject(_Model):
195
+ """An object besides a table: a routine, view, trigger, type, sequence or event."""
196
+
197
+ ref: ObjectRef
198
+ fingerprint: str
199
+ """A SHA-256 over the definition, as :func:`definition_fingerprint` computes it."""
200
+ depends_on: tuple[Dependency, ...] = ()
201
+ """The tables and objects it needs, such as a trigger's table and function."""
202
+
203
+ def needs_table(self, names: frozenset[TableName]) -> bool:
204
+ """Whether an exact edge says it depends on any of the tables in ``names``."""
205
+ return any(edge.table in names for edge in self.depends_on if not edge.inferred)
206
+
207
+ def needs_only(self, names: frozenset[TableName]) -> bool:
208
+ """Whether its exact edges name tables, all of them in ``names``."""
209
+ tables = {edge.table for edge in self.depends_on if edge.table and not edge.inferred}
210
+ return bool(tables) and tables <= names
211
+
212
+
213
+ def definition_fingerprint(definition: str) -> str:
214
+ """A SHA-256 over an object's definition as written.
215
+
216
+ Only line endings and whitespace at the ends of lines are normalized:
217
+ elsewhere whitespace can matter, inside a string literal or in an
218
+ indentation-sensitive body such as PL/Python's.
219
+ """
220
+ lines = definition.replace("\r\n", "\n").replace("\r", "\n").split("\n")
221
+ text = "\n".join(line.rstrip() for line in lines).strip("\n")
222
+ return "sha256:" + hashlib.sha256(text.encode()).hexdigest()
223
+
224
+
225
+ def _edge_key(edge: Dependency) -> tuple[str, str, bool]:
226
+ if edge.object is None:
227
+ return ("table", str(edge.table), edge.inferred)
228
+ return ("object", str(edge.object), edge.inferred)
229
+
230
+
231
+ class Catalog(_Model):
232
+ """Everything strict mode and the planner need to know about a source."""
233
+
234
+ engine: EngineName
235
+ tables: tuple[Table, ...]
236
+ requirements: tuple[Requirement, ...] = ()
237
+ """What the source needs beyond the server: extensions, plugins, modules."""
238
+ objects: tuple[SourceObject, ...] = ()
239
+ """Routines, views, triggers, types, sequences and events, for engines that have them."""
240
+
241
+ def object(self, ref: ObjectRef) -> SourceObject | None:
242
+ """The object ``ref`` names, if there is one."""
243
+ return next((found for found in self.objects if found.ref == ref), None)
244
+
245
+ def requirement(self, name: str) -> Requirement | None:
246
+ """The requirement called ``name``, if there is one."""
247
+ return next((r for r in self.requirements if r.name == name), None)
248
+
249
+ def table(self, name: TableName) -> Table | None:
250
+ """The table called ``name``, if there is one."""
251
+ return next((table for table in self.tables if table.name == name), None)
252
+
253
+ def names(self) -> tuple[TableName, ...]:
254
+ """Every table name, in catalog order."""
255
+ return tuple(table.name for table in self.tables)
256
+
257
+ def without(self, names: frozenset[TableName]) -> "Catalog":
258
+ """The catalog minus the tables in ``names``."""
259
+ return self.model_copy(
260
+ update={"tables": tuple(table for table in self.tables if table.name not in names)}
261
+ )
262
+
263
+ def fingerprint(self) -> str:
264
+ """A SHA-256 over the catalog's canonical JSON form."""
265
+ return "sha256:" + hashlib.sha256(_canonical(self).encode()).hexdigest()
266
+
267
+
268
+ def normalize(catalog: Catalog) -> Catalog:
269
+ """Sort tables, foreign keys, requirements and objects, so equal catalogs compare equal.
270
+
271
+ Column order is kept: it is part of a table's definition.
272
+ """
273
+ tables = sorted(catalog.tables, key=lambda table: table.name.parts)
274
+ return Catalog(
275
+ engine=catalog.engine,
276
+ tables=tuple(
277
+ table.model_copy(
278
+ update={
279
+ "foreign_keys": tuple(sorted(table.foreign_keys, key=lambda fk: fk.name)),
280
+ "depends_on": tuple(sorted(set(table.depends_on), key=_edge_key)),
281
+ }
282
+ )
283
+ for table in tables
284
+ ),
285
+ requirements=tuple(sorted(catalog.requirements, key=lambda r: (r.kind, r.name))),
286
+ objects=tuple(
287
+ item.model_copy(
288
+ update={"depends_on": tuple(sorted(set(item.depends_on), key=_edge_key))}
289
+ )
290
+ for item in sorted(catalog.objects, key=lambda item: str(item.ref))
291
+ ),
292
+ )
293
+
294
+
295
+ def _canonical(catalog: Catalog) -> str:
296
+ normal = normalize(catalog)
297
+ form = normal.model_dump(mode="json", exclude=_empty_needs(normal))
298
+ # A catalog without requirements hashes as it did before they existed, so
299
+ # locks written then stay valid.
300
+ if not catalog.requirements:
301
+ del form["requirements"]
302
+ # Likewise objects, for engines that report none.
303
+ if not catalog.objects:
304
+ del form["objects"]
305
+ return json.dumps(form, sort_keys=True, separators=(",", ":"))
306
+
307
+
308
+ def _empty_needs(catalog: Catalog) -> dict[str, dict[int, set[str]]]:
309
+ """What to leave out of a dump: tables' empty ``depends_on``.
310
+
311
+ Catalogs from before tables listed what they need then hash as they did.
312
+ """
313
+ return {
314
+ "tables": {
315
+ index: {"depends_on"}
316
+ for index, table in enumerate(catalog.tables)
317
+ if not table.depends_on
318
+ }
319
+ }
320
+
321
+
322
+ class CatalogLock(_Model):
323
+ """The catalog as it was when the subset model was built."""
324
+
325
+ format: Literal[1] = 1
326
+ fingerprint: str
327
+ catalog: Catalog
328
+
329
+ @classmethod
330
+ def of(cls, catalog: Catalog) -> "CatalogLock":
331
+ """Lock ``catalog``."""
332
+ normal = normalize(catalog)
333
+ return cls(fingerprint=normal.fingerprint(), catalog=normal)
334
+
335
+
336
+ def write_lock(lock: CatalogLock, path: Path) -> None:
337
+ """Write a lock file: indented JSON with sorted keys, so diffs are readable."""
338
+ form = lock.model_dump(mode="json", exclude={"catalog": _empty_needs(lock.catalog)})
339
+ if not lock.catalog.requirements:
340
+ del form["catalog"]["requirements"]
341
+ if not lock.catalog.objects:
342
+ del form["catalog"]["objects"]
343
+ text = json.dumps(form, indent=2, sort_keys=True)
344
+ try:
345
+ path.write_text(text + "\n", encoding="utf-8")
346
+ except OSError as error:
347
+ message = f"cannot write the catalog lock {path}: {error.strerror}"
348
+ raise CatalogError(message) from None
349
+
350
+
351
+ def read_lock(path: Path) -> CatalogLock:
352
+ """Read and check a lock file."""
353
+ try:
354
+ lock = CatalogLock.model_validate_json(path.read_bytes())
355
+ except FileNotFoundError:
356
+ message = f"{path} does not exist; write one with `datadouble lock`"
357
+ raise CatalogError(message) from None
358
+ except ValidationError as error:
359
+ message = f"{path} is not a valid catalog lock: {error.error_count()} problem(s)"
360
+ raise CatalogError(message) from error
361
+ if lock.catalog.fingerprint() != lock.fingerprint:
362
+ message = f"{path} has been edited by hand: its fingerprint does not match its contents"
363
+ raise CatalogError(message)
364
+ return lock
365
+
366
+
367
+ class Change(StrEnum):
368
+ """How an object differs between two locks."""
369
+
370
+ ADDED = "added"
371
+ REMOVED = "removed"
372
+ CHANGED = "changed"
373
+
374
+
375
+ class ChangeKind(StrEnum):
376
+ """What a lock change is about, besides the objects of :class:`ObjectKind`."""
377
+
378
+ TABLE = "table"
379
+ COLUMN = "column"
380
+ PRIMARY_KEY = "primary-key"
381
+ FOREIGN_KEY = "foreign-key"
382
+ REQUIREMENT = "requirement"
383
+ CATALOG = "catalog"
384
+ """The catalog as a whole: its engine, or a difference nothing else names."""
385
+
386
+
387
+ class LockChange(_Model):
388
+ """One difference between an earlier lock and a new one: names and types, never values."""
389
+
390
+ change: Change
391
+ kind: ChangeKind | ObjectKind
392
+ object: str
393
+ """``public.customer``, ``public.customer.email``, ``public.orders fk_customer``..."""
394
+ detail: str = ""
395
+ """The type, key or version, and what it was for a change."""
396
+
397
+ def __str__(self) -> str:
398
+ """``added column public.customer.phone: text null``."""
399
+ text = f"{self.change} {self.kind} {self.object}"
400
+ return f"{text}: {self.detail}" if self.detail else text
401
+
402
+
403
+ def _column(column: Column) -> str:
404
+ return f"{column.type} ({column.kind}) {'null' if column.nullable else 'not null'}"
405
+
406
+
407
+ def _key(columns: tuple[ColumnName, ...]) -> str:
408
+ return f"({', '.join(columns)})"
409
+
410
+
411
+ def _reference(key: ForeignKey) -> str:
412
+ return f"{_key(key.columns)} -> {key.target}{_key(key.target_columns)}"
413
+
414
+
415
+ def _was(old: str, new: str) -> str:
416
+ return f"{new}, was {old}"
417
+
418
+
419
+ def _added_table(table: Table) -> list[LockChange]:
420
+ """A new table, each of its columns and its keys: every new column is someone's to check."""
421
+ found = [LockChange(change=Change.ADDED, kind=ChangeKind.TABLE, object=str(table.name))]
422
+ found.extend(
423
+ LockChange(
424
+ change=Change.ADDED,
425
+ kind=ChangeKind.COLUMN,
426
+ object=f"{table.name}.{column.name}",
427
+ detail=_column(column),
428
+ )
429
+ for column in table.columns
430
+ )
431
+ if table.primary_key:
432
+ found.append(
433
+ LockChange(
434
+ change=Change.ADDED,
435
+ kind=ChangeKind.PRIMARY_KEY,
436
+ object=str(table.name),
437
+ detail=_key(table.primary_key),
438
+ )
439
+ )
440
+ found.extend(
441
+ LockChange(
442
+ change=Change.ADDED,
443
+ kind=ChangeKind.FOREIGN_KEY,
444
+ object=f"{table.name} {key.name}",
445
+ detail=_reference(key),
446
+ )
447
+ for key in sorted(table.foreign_keys, key=lambda key: key.name)
448
+ )
449
+ return found
450
+
451
+
452
+ def _order(old: Table, new: Table) -> list[LockChange]:
453
+ """The order of the columns both locks have, which is part of a table's definition."""
454
+ kept = {column.name for column in old.columns} & {column.name for column in new.columns}
455
+ before = tuple(column.name for column in old.columns if column.name in kept)
456
+ after = tuple(column.name for column in new.columns if column.name in kept)
457
+ if before == after:
458
+ return []
459
+ return [
460
+ LockChange(
461
+ change=Change.CHANGED,
462
+ kind=ChangeKind.TABLE,
463
+ object=str(new.name),
464
+ detail=f"column order {_was(_key(before), _key(after))}",
465
+ )
466
+ ]
467
+
468
+
469
+ def _columns(old: Table, new: Table) -> list[LockChange]:
470
+ found: list[LockChange] = []
471
+ before = {column.name: column for column in old.columns}
472
+ after = {column.name: column for column in new.columns}
473
+ for column in old.columns:
474
+ name = f"{new.name}.{column.name}"
475
+ current = after.get(column.name)
476
+ if current is None:
477
+ found.append(LockChange(change=Change.REMOVED, kind=ChangeKind.COLUMN, object=name))
478
+ elif current != column:
479
+ detail = _was(_column(column), _column(current))
480
+ found.append(
481
+ LockChange(
482
+ change=Change.CHANGED, kind=ChangeKind.COLUMN, object=name, detail=detail
483
+ )
484
+ )
485
+ found.extend(
486
+ LockChange(
487
+ change=Change.ADDED,
488
+ kind=ChangeKind.COLUMN,
489
+ object=f"{new.name}.{column.name}",
490
+ detail=_column(column),
491
+ )
492
+ for column in new.columns
493
+ if column.name not in before
494
+ )
495
+ return found
496
+
497
+
498
+ def _keys(old: Table, new: Table) -> list[LockChange]:
499
+ found: list[LockChange] = []
500
+ if old.primary_key != new.primary_key:
501
+ found.append(
502
+ LockChange(
503
+ change=Change.CHANGED,
504
+ kind=ChangeKind.PRIMARY_KEY,
505
+ object=str(new.name),
506
+ detail=_was(_key(old.primary_key), _key(new.primary_key)),
507
+ )
508
+ )
509
+ before = {key.name: key for key in old.foreign_keys}
510
+ after = {key.name: key for key in new.foreign_keys}
511
+ for name in sorted(before.keys() | after.keys()):
512
+ old_key, new_key = before.get(name), after.get(name)
513
+ what = f"{new.name} {name}"
514
+ if new_key is None:
515
+ found.append(
516
+ LockChange(change=Change.REMOVED, kind=ChangeKind.FOREIGN_KEY, object=what)
517
+ )
518
+ elif old_key is None:
519
+ found.append(
520
+ LockChange(
521
+ change=Change.ADDED,
522
+ kind=ChangeKind.FOREIGN_KEY,
523
+ object=what,
524
+ detail=_reference(new_key),
525
+ )
526
+ )
527
+ elif old_key != new_key:
528
+ found.append(
529
+ LockChange(
530
+ change=Change.CHANGED,
531
+ kind=ChangeKind.FOREIGN_KEY,
532
+ object=what,
533
+ detail=_was(_reference(old_key), _reference(new_key)),
534
+ )
535
+ )
536
+ return found
537
+
538
+
539
+ def _requirements(old: Catalog, new: Catalog) -> list[LockChange]:
540
+ found: list[LockChange] = []
541
+ before = {(r.kind, r.name): r for r in old.requirements}
542
+ after = {(r.kind, r.name): r for r in new.requirements}
543
+ for key in sorted(before.keys() | after.keys()):
544
+ earlier, current = before.get(key), after.get(key)
545
+ what = f"{key[0]} {key[1]}"
546
+ if current is None:
547
+ found.append(
548
+ LockChange(change=Change.REMOVED, kind=ChangeKind.REQUIREMENT, object=what)
549
+ )
550
+ elif earlier is None:
551
+ found.append(
552
+ LockChange(
553
+ change=Change.ADDED,
554
+ kind=ChangeKind.REQUIREMENT,
555
+ object=what,
556
+ detail=current.version or "",
557
+ )
558
+ )
559
+ elif earlier.version != current.version:
560
+ found.append(
561
+ LockChange(
562
+ change=Change.CHANGED,
563
+ kind=ChangeKind.REQUIREMENT,
564
+ object=what,
565
+ detail=_was(earlier.version or "no version", current.version or "no version"),
566
+ )
567
+ )
568
+ return found
569
+
570
+
571
+ def _objects(old: Catalog, new: Catalog) -> list[LockChange]:
572
+ """Objects added, removed, or changed in definition or in what they depend on."""
573
+ found: list[LockChange] = []
574
+ before = {str(o.ref): o for o in old.objects}
575
+ after = {str(o.ref): o for o in new.objects}
576
+ refs = {str(o.ref): o.ref for o in (*old.objects, *new.objects)}
577
+ for key in sorted(refs):
578
+ earlier, current, ref = before.get(key), after.get(key), refs[key]
579
+ what = f"{'.'.join((*ref.namespace, ref.name))}{ref.signature or ''}"
580
+ if current is None:
581
+ found.append(LockChange(change=Change.REMOVED, kind=ref.kind, object=what))
582
+ elif earlier is None:
583
+ found.append(LockChange(change=Change.ADDED, kind=ref.kind, object=what))
584
+ elif earlier.fingerprint != current.fingerprint:
585
+ found.append(
586
+ LockChange(
587
+ change=Change.CHANGED, kind=ref.kind, object=what, detail="its definition"
588
+ )
589
+ )
590
+ elif sorted(map(_edge_key, earlier.depends_on)) != sorted(
591
+ map(_edge_key, current.depends_on)
592
+ ):
593
+ found.append(
594
+ LockChange(
595
+ change=Change.CHANGED, kind=ref.kind, object=what, detail="what it depends on"
596
+ )
597
+ )
598
+ return found
599
+
600
+
601
+ def changes(old: Catalog, new: Catalog) -> tuple[LockChange, ...]:
602
+ """What ``new`` adds, removes and changes against ``old``, table by table."""
603
+ found: list[LockChange] = []
604
+ old_tables = {table.name: table for table in old.tables}
605
+ new_tables = {table.name: table for table in new.tables}
606
+ for name in sorted(old_tables.keys() | new_tables.keys()):
607
+ before, after = old_tables.get(name), new_tables.get(name)
608
+ if after is None:
609
+ found.append(LockChange(change=Change.REMOVED, kind=ChangeKind.TABLE, object=str(name)))
610
+ elif before is None:
611
+ found.extend(_added_table(after))
612
+ else:
613
+ found.extend(_columns(before, after))
614
+ found.extend(_order(before, after))
615
+ found.extend(_keys(before, after))
616
+ if sorted(map(_edge_key, before.depends_on)) != sorted(
617
+ map(_edge_key, after.depends_on)
618
+ ):
619
+ found.append(
620
+ LockChange(
621
+ change=Change.CHANGED,
622
+ kind=ChangeKind.TABLE,
623
+ object=str(name),
624
+ detail="the objects it needs",
625
+ )
626
+ )
627
+ found.extend(_requirements(old, new))
628
+ found.extend(_objects(old, new))
629
+ if old.engine != new.engine:
630
+ found.append(
631
+ LockChange(
632
+ change=Change.CHANGED,
633
+ kind=ChangeKind.CATALOG,
634
+ object="engine",
635
+ detail=_was(old.engine, new.engine),
636
+ )
637
+ )
638
+ if not found and old.fingerprint() != new.fingerprint():
639
+ found.append(
640
+ LockChange(
641
+ change=Change.CHANGED,
642
+ kind=ChangeKind.CATALOG,
643
+ object="fingerprint",
644
+ detail=(
645
+ "the locks differ, though in no table, column, key, requirement or object;"
646
+ " compare the two files"
647
+ ),
648
+ )
649
+ )
650
+ return tuple(found)
651
+
652
+
653
+ def describe_changes(
654
+ changes: tuple[LockChange, ...] | None, unreadable: str | None = None
655
+ ) -> tuple[str, ...]:
656
+ """The changes as lines for people: the CLI summary and the lock job's ``changes.txt``.
657
+
658
+ ``unreadable`` is why an earlier lock could not be read, when that is why
659
+ there are no changes to list.
660
+ """
661
+ if unreadable is not None:
662
+ problem = (
663
+ f"the earlier lock could not be read ({unreadable}): check every table and column"
664
+ " in the new one for personal data"
665
+ )
666
+ return (problem,)
667
+ if changes is None:
668
+ return (
669
+ "no earlier lock to compare with: check every table and column in it for personal data",
670
+ )
671
+ if not changes:
672
+ return ("no changes from the earlier lock",)
673
+ heading = (
674
+ f"{len(changes)} change(s) from the earlier lock; check new and changed columns"
675
+ " for personal data:"
676
+ )
677
+ return (heading, *(f" {change}" for change in changes))