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/images.py ADDED
@@ -0,0 +1,265 @@
1
+ # Copyright (c) 2026- Tight Line LLC
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ """Golden images: identity, packing, and the image summary stored beside each one.
5
+
6
+ An image is identified by spec, group, engine, engine version and generation.
7
+ Each requested format is packed as its own compressed tar archive holding the
8
+ engine's files under ``image/`` and the build manifest as ``manifest.json``.
9
+ The image summary, a few kilobytes of JSON, sits next to the archives so it
10
+ can be read without downloading them:
11
+
12
+ shop/all/postgres-18/
13
+ 0193a7c21b4e9f30.logical.tar.gz
14
+ 0193a7c21b4e9f30.physical.tar.gz
15
+ 0193a7c21b4e9f30.summary.json
16
+
17
+ Stores that cannot list keys, such as a web server, are read through an index
18
+ ``promote`` writes under each ``<spec>/<group>/`` (``index.json``), naming
19
+ the group's image lines and the generations with a summary in each.
20
+ """
21
+
22
+ import hashlib
23
+ import secrets
24
+ import tarfile
25
+ import time
26
+ from pathlib import Path
27
+ from typing import Literal
28
+
29
+ from pydantic import AwareDatetime, BaseModel, ConfigDict, ValidationError
30
+
31
+ from datadouble.names import EngineName, Generation, GroupName, SpecName
32
+ from datadouble.spec import ImageFormat, Strict
33
+ from datadouble.storage import ListingUnsupportedError, Store
34
+
35
+ CODEC: Literal["gz"] = "gz"
36
+ """Compression for image archives (gzip, from the standard library)."""
37
+ _CHUNK = 1 << 20
38
+
39
+
40
+ class ImageError(Exception):
41
+ """An image archive that cannot be written or read."""
42
+
43
+
44
+ class _Model(BaseModel):
45
+ model_config = ConfigDict(strict=True, frozen=True, extra="forbid")
46
+
47
+
48
+ def new_generation(now_ms: int | None = None) -> Generation:
49
+ """A generation ID: 12 hex digits of milliseconds since 1970, then 4 random ones.
50
+
51
+ IDs sort by build time.
52
+ """
53
+ millis = time.time_ns() // 1_000_000 if now_ms is None else now_ms
54
+ return Generation(f"{millis:012x}{secrets.token_hex(2)}")
55
+
56
+
57
+ class ImageIdentity(_Model):
58
+ """What an image is: the parts consumers select by."""
59
+
60
+ spec: SpecName
61
+ group: GroupName
62
+ engine: EngineName
63
+ engine_version: str
64
+ """The major version of the server that restores the image."""
65
+ generation: Generation
66
+
67
+ def prefix(self) -> str:
68
+ """The store directory holding this image's generations."""
69
+ return f"{self.spec}/{self.group}/{self.engine}-{self.engine_version}"
70
+
71
+ def archive_key(self, image_format: ImageFormat) -> str:
72
+ """The store key of one format's archive."""
73
+ return f"{self.prefix()}/{self.generation}.{image_format}.tar.{CODEC}"
74
+
75
+ def summary_key(self) -> str:
76
+ """The store key of the image summary."""
77
+ return f"{self.prefix()}/{self.generation}.summary.json"
78
+
79
+
80
+ class Digest(_Model):
81
+ """A file's SHA-256 and size."""
82
+
83
+ sha256: str
84
+ size: int
85
+
86
+
87
+ def digest(path: Path) -> Digest:
88
+ """Hash a file."""
89
+ sha = hashlib.sha256()
90
+ with path.open("rb") as handle:
91
+ while chunk := handle.read(_CHUNK):
92
+ sha.update(chunk)
93
+ return Digest(sha256=sha.hexdigest(), size=path.stat().st_size)
94
+
95
+
96
+ class ImageArchive(_Model):
97
+ """One format of an image."""
98
+
99
+ format: ImageFormat
100
+ key: str
101
+ codec: Literal["gz"] = CODEC
102
+ digest: Digest
103
+
104
+
105
+ class Verification(_Model):
106
+ """The outcome of ``verify``, as summarized for consumers."""
107
+
108
+ passed: bool
109
+ checks: int
110
+ failed: int
111
+
112
+
113
+ class ImageSummary(_Model):
114
+ """The small file stored beside each image, readable without downloading it."""
115
+
116
+ summary_format: Literal[1] = 1
117
+ identity: ImageIdentity
118
+ built_at: AwareDatetime
119
+ archives: tuple[ImageArchive, ...]
120
+ manifest_sha256: str
121
+ verification: Verification
122
+ strict: Strict
123
+ """The strict-mode levels the image was built with."""
124
+ server_version: str | None = None
125
+ """The exact version of the server that wrote the image; the identity names its line."""
126
+ accounts: tuple[str, ...] = ()
127
+ """The users of the accounts physical copies carry (``package.accounts``)."""
128
+ signature: str | None = None
129
+ """The store key of the signature bundle, if the image is signed."""
130
+
131
+
132
+ def pack(source: Path, manifest: bytes, destination: Path) -> Digest:
133
+ """Write ``source``'s contents and ``manifest`` into a compressed tar archive."""
134
+ manifest_file = destination.with_name(destination.name + ".manifest.json")
135
+ manifest_file.write_bytes(manifest)
136
+ try:
137
+ with tarfile.open(destination, "w:gz", compresslevel=6) as archive:
138
+ archive.add(manifest_file, arcname="manifest.json")
139
+ archive.add(source, arcname="image")
140
+ finally:
141
+ manifest_file.unlink(missing_ok=True)
142
+ return digest(destination)
143
+
144
+
145
+ def unpack(archive: Path, destination: Path) -> tuple[Path, bytes]:
146
+ """Extract an archive safely; return the image directory and the manifest."""
147
+ destination.mkdir(parents=True, exist_ok=True)
148
+ try:
149
+ with tarfile.open(archive, "r:gz") as opened:
150
+ opened.extractall(destination, filter="data")
151
+ except (tarfile.TarError, OSError) as error:
152
+ message = f"cannot unpack {archive.name}: {error}"
153
+ raise ImageError(message) from None
154
+ manifest = destination / "manifest.json"
155
+ image = destination / "image"
156
+ if not manifest.is_file() or not image.is_dir():
157
+ message = f"{archive.name} is not a Datadouble image"
158
+ raise ImageError(message)
159
+ return image, manifest.read_bytes()
160
+
161
+
162
+ _SUMMARY = ".summary.json"
163
+ _LINE_DEPTH = 3 # spec/group/engine-version/file
164
+ INDEX = "index.json"
165
+ """The name of the index under each ``<spec>/<group>/``."""
166
+
167
+
168
+ class ImageIndex(_Model):
169
+ """A group's image lines and generations, for stores that cannot list keys."""
170
+
171
+ index_format: Literal[1] = 1
172
+ lines: dict[str, tuple[Generation, ...]]
173
+ """Each image line (``<engine>-<version>``) and its generations with a summary, oldest
174
+ first."""
175
+
176
+
177
+ def index_key(spec: str, group: str) -> str:
178
+ """The store key of a group's index."""
179
+ return f"{spec}/{group}/{INDEX}"
180
+
181
+
182
+ def read_index(store: Store, spec: str, group: str) -> ImageIndex:
183
+ """A group's index; empty if the store has none."""
184
+ key = index_key(spec, group)
185
+ data = store.get_bytes(key)
186
+ if data is None:
187
+ return ImageIndex(lines={})
188
+ try:
189
+ return ImageIndex.model_validate_json(data)
190
+ except ValidationError:
191
+ message = f"{key} in {store.describe()} is not a valid image index"
192
+ raise ImageError(message) from None
193
+
194
+
195
+ def write_index(store: Store, spec: str, group: str) -> ImageIndex:
196
+ """List a group's image lines and generations and write them as its index."""
197
+ index = ImageIndex(
198
+ lines={
199
+ prefix.rsplit("/", 1)[1]: tuple(generations(store, prefix))
200
+ for prefix in image_lines(store, spec, group)
201
+ }
202
+ )
203
+ store.put_bytes(index_key(spec, group), index.model_dump_json(indent=2).encode())
204
+ return index
205
+
206
+
207
+ def image_lines(store: Store, spec: str, group: str) -> list[str]:
208
+ """The ``<spec>/<group>/<engine>-<version>`` prefixes a store holds images under.
209
+
210
+ A store that cannot list keys is read through the group's index.
211
+ """
212
+ try:
213
+ found = {
214
+ "/".join(key.split("/")[:3])
215
+ for key in store.list(f"{spec}/{group}/")
216
+ if key.endswith(_SUMMARY) and key.count("/") == _LINE_DEPTH
217
+ }
218
+ except ListingUnsupportedError:
219
+ found = {f"{spec}/{group}/{line}" for line in read_index(store, spec, group).lines}
220
+ return sorted(found, key=_version_order)
221
+
222
+
223
+ def _version_order(prefix: str) -> tuple[int, ...]:
224
+ version = prefix.rsplit("-", 1)[-1]
225
+ return tuple(int(part) for part in version.split(".") if part.isdigit())
226
+
227
+
228
+ def line_engine(prefix: str) -> str:
229
+ """The engine of an image line, from its ``<spec>/<group>/<engine>-<version>`` prefix."""
230
+ return prefix.rsplit("/", 1)[-1].rpartition("-")[0]
231
+
232
+
233
+ def current_lines(prefixes: list[str], keep: int) -> set[str]:
234
+ """Each engine's newest ``keep`` lines; a files line is never older than a database's."""
235
+ by_engine: dict[str, list[str]] = {}
236
+ for prefix in sorted(prefixes, key=_version_order):
237
+ by_engine.setdefault(line_engine(prefix), []).append(prefix)
238
+ return {prefix for lines in by_engine.values() for prefix in lines[-keep:]}
239
+
240
+
241
+ def generations(store: Store, prefix: str) -> list[Generation]:
242
+ """The generations with a summary under an image line, oldest first.
243
+
244
+ A store that cannot list keys is read through the group's index.
245
+ """
246
+ try:
247
+ return sorted(
248
+ Generation(key.rsplit("/", 1)[1].removesuffix(_SUMMARY))
249
+ for key in store.list(f"{prefix}/")
250
+ if key.endswith(_SUMMARY) and key.count("/") == prefix.count("/") + 1
251
+ )
252
+ except ListingUnsupportedError:
253
+ spec, group, line = prefix.split("/")
254
+ return sorted(read_index(store, spec, group).lines.get(line, ()))
255
+
256
+
257
+ def read_summary(store: Store, prefix: str, generation: Generation) -> ImageSummary | None:
258
+ """A generation's image summary, if the store has it."""
259
+ data = store.get_bytes(f"{prefix}/{generation}{_SUMMARY}")
260
+ return None if data is None else ImageSummary.model_validate_json(data)
261
+
262
+
263
+ def version_line(version: str, parts: int) -> str:
264
+ """The compatibility line of a server version: its first ``parts`` numbers."""
265
+ return ".".join(version.split(".")[:parts])
datadouble/jailer.py ADDED
@@ -0,0 +1,403 @@
1
+ # Copyright (c) 2026- Tight Line LLC
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ """Reading Jailer subsets: a data model folder and an extraction model (``.jm``).
5
+
6
+ Both compile to the native subset model, so a subset designed in Jailer runs in
7
+ Datadouble unchanged, on every run (decision 81):
8
+
9
+ - each **subject** becomes a seed, its ``T.`` alias removed;
10
+ - each **association** is an equality join between two tables; one the
11
+ catalog declares stays a foreign key, any other becomes a virtual one;
12
+ - Jailer follows every association in both directions unless restricted, so
13
+ every child direction without a restriction becomes a followed child edge;
14
+ - ``ignore`` on a child direction leaves it unfollowed, and on a parent
15
+ direction becomes ``on_missing: null`` (Jailer exports such rows with the
16
+ reference dangling; the key sets agree);
17
+ - excluded tables and associations are excluded and ignored.
18
+
19
+ Anything that would change which rows are chosen and has no native
20
+ equivalent fails, naming it: non-equality joins, restriction conditions,
21
+ subject limits, column filters and ``${param}`` placeholders. Layout, XML and
22
+ export settings do not affect the rows and are listed in the report.
23
+ """
24
+
25
+ import csv
26
+ import re
27
+ from collections.abc import Iterable
28
+ from dataclasses import dataclass, field
29
+ from pathlib import Path
30
+
31
+ from pydantic import BaseModel, ConfigDict
32
+
33
+ from datadouble.catalog import Catalog, Table
34
+ from datadouble.resolve import ends_with
35
+ from datadouble.spec import EdgePolicy, Follow, OnMissing, Subset, Unselected, VirtualForeignKey
36
+
37
+ _ALIAS_T = re.compile(r"(?<![\w.\"`])T\.(?=[\w\"`])", re.IGNORECASE)
38
+ _PAIR = re.compile(r"^\s*(A|B)\.([\w$]+)\s*=\s*(A|B)\.([\w$]+)\s*$", re.IGNORECASE)
39
+ _AND = re.compile(r"\s+AND\s+", re.IGNORECASE)
40
+ _PARAMETER = re.compile(r"\$\{\w+\}")
41
+ _ASSOCIATION_CELLS = 6
42
+ """A, B, first insert, cardinality, join condition, name."""
43
+ _LIMIT = 2
44
+ """Where a subject's limit is: subject; condition; limit."""
45
+ _RESTRICTION = 2
46
+ """Where an association's restriction is: association; ; restriction."""
47
+ _ROW_BLOCKS = frozenset({"", "additional subjects"})
48
+ _IGNORED_BLOCKS = frozenset(
49
+ {
50
+ "xml-mapping",
51
+ "datamodelfolder",
52
+ "export modus",
53
+ "xml settings",
54
+ "xml column mapping",
55
+ "upserts",
56
+ "exclude from deletion",
57
+ "filter templates",
58
+ "layout",
59
+ "known",
60
+ "version",
61
+ }
62
+ )
63
+
64
+
65
+ class JailerError(Exception):
66
+ """A Jailer model that cannot be read, or uses what Datadouble cannot run."""
67
+
68
+
69
+ @dataclass(frozen=True, slots=True)
70
+ class Association:
71
+ """One row of ``association.csv``."""
72
+
73
+ a: str
74
+ b: str
75
+ first_insert: str
76
+ cardinality: str
77
+ join: str
78
+ name: str
79
+
80
+
81
+ @dataclass(frozen=True, slots=True)
82
+ class DataModel:
83
+ """A Jailer data model folder."""
84
+
85
+ tables: dict[str, tuple[str, ...]]
86
+ """Table name to primary-key columns."""
87
+ associations: tuple[Association, ...]
88
+ excluded_tables: frozenset[str]
89
+ excluded_associations: frozenset[str]
90
+
91
+
92
+ @dataclass(frozen=True, slots=True)
93
+ class Subject:
94
+ """A starting table, its condition and optional limit."""
95
+
96
+ table: str
97
+ condition: str
98
+ limit: str
99
+
100
+
101
+ @dataclass
102
+ class ExtractionModel:
103
+ """The parts of a ``.jm`` file that choose rows."""
104
+
105
+ subjects: list[Subject] = field(default_factory=list[Subject])
106
+ restrictions: dict[str, str] = field(default_factory=dict[str, str])
107
+ filters: list[str] = field(default_factory=list[str])
108
+ ignored: list[str] = field(default_factory=list[str])
109
+
110
+
111
+ class Translation(BaseModel):
112
+ """A Jailer subset in native terms, and what was left out on purpose."""
113
+
114
+ model_config = ConfigDict(strict=True, frozen=True, extra="forbid")
115
+
116
+ subset: Subset
117
+ exclude: tuple[str, ...]
118
+ report: tuple[str, ...]
119
+ """Settings that do not choose rows and were ignored."""
120
+
121
+
122
+ def _rows(path: Path) -> list[list[str]]:
123
+ """The semicolon-separated rows of a Jailer file, comments and blanks removed."""
124
+ if not path.is_file():
125
+ return []
126
+ with path.open(encoding="utf-8", newline="") as stream:
127
+ return [
128
+ [cell.strip() for cell in row]
129
+ for row in csv.reader(stream, delimiter=";")
130
+ if row and row[0].strip() and not row[0].lstrip().startswith("#")
131
+ ]
132
+
133
+
134
+ def read_datamodel(folder: Path) -> DataModel:
135
+ """Read a data model folder's tables, associations and exclusions."""
136
+ if not (folder / "table.csv").is_file():
137
+ message = f"{folder} is not a Jailer data model folder (it has no table.csv)"
138
+ raise JailerError(message)
139
+ tables: dict[str, tuple[str, ...]] = {}
140
+ for row in _rows(folder / "table.csv"):
141
+ keys: list[str] = []
142
+ for cell in row[2:]:
143
+ if not cell:
144
+ break
145
+ keys.append(cell.split()[0])
146
+ tables[row[0]] = tuple(keys)
147
+ associations = tuple(
148
+ Association(
149
+ a=row[0], b=row[1], first_insert=row[2], cardinality=row[3], join=row[4], name=row[5]
150
+ )
151
+ for row in _rows(folder / "association.csv")
152
+ if len(row) >= _ASSOCIATION_CELLS
153
+ )
154
+ return DataModel(
155
+ tables=tables,
156
+ associations=associations,
157
+ excluded_tables=frozenset(row[0] for row in _rows(folder / "exclude-tables.csv")),
158
+ excluded_associations=frozenset(
159
+ row[0] for row in _rows(folder / "exclude-associations.csv")
160
+ ),
161
+ )
162
+
163
+
164
+ def read_extraction_model(path: Path) -> ExtractionModel:
165
+ """Read a ``.jm`` file's subjects, restrictions and filters."""
166
+ if not path.is_file():
167
+ message = f"there is no Jailer extraction model at {path}"
168
+ raise JailerError(message)
169
+ model = ExtractionModel()
170
+ block = ""
171
+ section = 0
172
+ for raw in path.read_text("utf-8").splitlines():
173
+ line = raw.strip()
174
+ if line.startswith("#!"):
175
+ block = line[2:].strip().removeprefix("block").strip().lower()
176
+ continue
177
+ if block == "" and line.startswith("# association"):
178
+ section = 1
179
+ if not line or line.startswith("#"):
180
+ continue
181
+ cells = [cell.strip() for cell in line.split(";")]
182
+ if block in _ROW_BLOCKS and (block or section == 0):
183
+ limit = cells[_LIMIT] if len(cells) > _LIMIT else ""
184
+ model.subjects.append(Subject(cells[0], cells[1], limit))
185
+ elif block == "" and len(cells) > _RESTRICTION:
186
+ model.restrictions[cells[0]] = cells[_RESTRICTION]
187
+ elif block == "filters":
188
+ model.filters.append(line)
189
+ elif block in _IGNORED_BLOCKS and block not in model.ignored:
190
+ model.ignored.append(block)
191
+ return model
192
+
193
+
194
+ @dataclass
195
+ class _Translator:
196
+ datamodel: DataModel
197
+ model: ExtractionModel
198
+ catalog: Catalog
199
+ case_sensitive: bool
200
+ problems: list[str] = field(default_factory=list[str])
201
+
202
+ def fold(self, name: str) -> str:
203
+ return name if self.case_sensitive else name.lower()
204
+
205
+ def table(self, jailer: str) -> Table | None:
206
+ """The catalog table a Jailer table name means, matching from the right."""
207
+ pieces = jailer.split(".")
208
+ found = [
209
+ table
210
+ for table in self.catalog.tables
211
+ if ends_with(table.name.parts, pieces, lambda a, b: self.fold(a) == self.fold(b))
212
+ ]
213
+ if len(found) > 1:
214
+ names = ", ".join(str(table.name) for table in found)
215
+ self.problems.append(
216
+ f"table {jailer} in the Jailer model is ambiguous: it matches {names}"
217
+ )
218
+ return None
219
+ if not found:
220
+ self.problems.append(f"table {jailer} is in the Jailer model but not in the catalog")
221
+ return None
222
+ return found[0]
223
+
224
+ def column(self, table: Table, jailer: str) -> str | None:
225
+ for column in table.columns:
226
+ if self.fold(column.name) == self.fold(jailer):
227
+ return str(column.name)
228
+ self.problems.append(
229
+ f"column {table.name}.{jailer} is in the Jailer model but not in the catalog"
230
+ )
231
+ return None
232
+
233
+ def check_keys(self) -> None:
234
+ """The data model's primary keys must be the catalog's."""
235
+ for name, keys in self.datamodel.tables.items():
236
+ table = self.table(name)
237
+ if table is None or not keys:
238
+ continue
239
+ if [self.fold(k) for k in keys] != [self.fold(k) for k in table.primary_key]:
240
+ self.problems.append(
241
+ f"the primary key of {name} in the Jailer model ({', '.join(keys)}) "
242
+ f"is not the catalog's ({', '.join(table.primary_key)})"
243
+ )
244
+
245
+ def seeds(self) -> dict[str, str]:
246
+ seeds: dict[str, list[str]] = {}
247
+ for subject in self.model.subjects:
248
+ table = self.table(subject.table)
249
+ if subject.limit:
250
+ self.problems.append(
251
+ f"subject {subject.table} has a limit, which Datadouble does not support yet"
252
+ )
253
+ if _PARAMETER.search(subject.condition):
254
+ self.problems.append(f"subject {subject.table} uses a ${{param}} placeholder")
255
+ if table is not None:
256
+ condition = _strip_alias(subject.condition) or "1 = 1"
257
+ seeds.setdefault(str(table.name), []).append(f"({condition})")
258
+ return {name: " OR ".join(parts) for name, parts in seeds.items()}
259
+
260
+ def edges(self) -> tuple[list[str], dict[str, EdgePolicy], dict[str, VirtualForeignKey]]:
261
+ down: list[str] = []
262
+ policies: dict[str, EdgePolicy] = {}
263
+ virtual: dict[str, VirtualForeignKey] = {}
264
+ for association in self.datamodel.associations:
265
+ resolved = self.association(association)
266
+ if resolved is None:
267
+ continue
268
+ child, child_columns, parent, parent_columns, upward, downward = resolved
269
+ reference = (
270
+ f"{child.name}.({', '.join(child_columns)}) -> "
271
+ f"{parent.name}.({', '.join(parent_columns)})"
272
+ )
273
+ if not _declared(child, child_columns, parent):
274
+ virtual[reference] = VirtualForeignKey()
275
+ excluded = association.name in self.datamodel.excluded_associations
276
+ up, below = (
277
+ ("ignore", "ignore")
278
+ if excluded
279
+ else (
280
+ self.model.restrictions.get(upward, ""),
281
+ self.model.restrictions.get(downward, ""),
282
+ )
283
+ )
284
+ for direction, restriction in ((upward, up), (downward, below)):
285
+ if restriction and restriction.lower() != "ignore":
286
+ self.problems.append(
287
+ f"association {direction} has the restriction {restriction!r}; "
288
+ "restriction conditions are not supported yet"
289
+ )
290
+ if up.lower() == "ignore":
291
+ policies[reference] = EdgePolicy(on_missing=OnMissing.NULL)
292
+ if not below:
293
+ down.append(
294
+ f"{parent.name}.({', '.join(parent_columns)}) -> "
295
+ f"{child.name}.({', '.join(child_columns)})"
296
+ )
297
+ return down, policies, virtual
298
+
299
+ def association(
300
+ self, association: Association
301
+ ) -> tuple[Table, list[str], Table, list[str], str, str] | None:
302
+ """Child, its columns, parent, its columns, and the up and down direction names."""
303
+ parts = _AND.split(association.join.strip())
304
+ pairs = [match for part in parts if (match := _PAIR.match(part)) is not None]
305
+ if len(pairs) != len(parts):
306
+ self.problems.append(
307
+ f"association {association.name} joins on {association.join!r}; "
308
+ "only equality between columns is supported"
309
+ )
310
+ return None
311
+ if association.first_insert.upper() == "B" or (
312
+ not association.first_insert and association.cardinality == "n:1"
313
+ ):
314
+ child_side, upward, downward = "A", association.name, f"inverse-{association.name}"
315
+ elif association.first_insert.upper() == "A" or association.cardinality == "1:n":
316
+ child_side, upward, downward = "B", f"inverse-{association.name}", association.name
317
+ else:
318
+ self.problems.append(
319
+ f"association {association.name} has no direction "
320
+ "(no first-insert side and cardinality is not n:1 or 1:n)"
321
+ )
322
+ return None
323
+ child = self.table(association.a if child_side == "A" else association.b)
324
+ parent = self.table(association.b if child_side == "A" else association.a)
325
+ if child is None or parent is None:
326
+ return None
327
+ child_columns: list[str] = []
328
+ parent_columns: list[str] = []
329
+ for match in pairs:
330
+ sides = {match.group(1).upper(): match.group(2), match.group(3).upper(): match.group(4)}
331
+ if set(sides) != {"A", "B"}:
332
+ self.problems.append(f"association {association.name} compares a table with itself")
333
+ return None
334
+ mine = self.column(child, sides[child_side])
335
+ theirs = self.column(parent, sides["B" if child_side == "A" else "A"])
336
+ if mine is None or theirs is None:
337
+ return None
338
+ child_columns.append(mine)
339
+ parent_columns.append(theirs)
340
+ return child, child_columns, parent, parent_columns, upward, downward
341
+
342
+
343
+ def _strip_alias(condition: str) -> str:
344
+ """``condition`` without Jailer's ``T.`` alias, outside quoted strings."""
345
+ parts = re.split(r"('(?:[^']|'')*')", condition)
346
+ return "".join(
347
+ part if i % 2 else _ALIAS_T.sub("", part) for i, part in enumerate(parts)
348
+ ).strip()
349
+
350
+
351
+ def _declared(child: Table, columns: Iterable[str], parent: Table) -> bool:
352
+ wanted = tuple(columns)
353
+ return any(
354
+ fk.target == parent.name and tuple(fk.columns) == wanted for fk in child.foreign_keys
355
+ )
356
+
357
+
358
+ def translate(
359
+ datamodel: DataModel,
360
+ model: ExtractionModel,
361
+ catalog: Catalog,
362
+ *,
363
+ case_sensitive: bool = False,
364
+ ) -> Translation:
365
+ """The native subset for a Jailer subset over ``catalog``; raises listing every problem."""
366
+ translator = _Translator(datamodel, model, catalog, case_sensitive)
367
+ translator.check_keys()
368
+ seeds = translator.seeds()
369
+ down, policies, virtual = translator.edges()
370
+ if model.filters:
371
+ translator.problems.append("column filters are not supported; use anonymization rules")
372
+ if translator.problems:
373
+ raise JailerError("; ".join(dict.fromkeys(translator.problems)))
374
+ excluded = sorted(
375
+ str(table.name)
376
+ for name in datamodel.excluded_tables
377
+ if (table := translator.table(name)) is not None
378
+ )
379
+ # Jailer exports only what its subjects and associations reach, so a table
380
+ # they don't reach keeps no rows rather than failing the plan.
381
+ subset = Subset(
382
+ seeds=seeds,
383
+ follow=Follow(down=tuple(down)),
384
+ edges=policies,
385
+ virtual_fks=virtual,
386
+ unselected=Unselected.NONE,
387
+ )
388
+ report = tuple(
389
+ f"ignored the {block} block, which does not choose rows" for block in model.ignored
390
+ )
391
+ return Translation(subset=subset, exclude=tuple(excluded), report=report)
392
+
393
+
394
+ def load(
395
+ model: Path, datamodel: Path, catalog: Catalog, *, case_sensitive: bool = False
396
+ ) -> Translation:
397
+ """Read and translate a Jailer subset."""
398
+ return translate(
399
+ read_datamodel(datamodel),
400
+ read_extraction_model(model),
401
+ catalog,
402
+ case_sensitive=case_sensitive,
403
+ )