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/__init__.py +10 -0
- datadouble/announce.py +380 -0
- datadouble/anonymize.py +165 -0
- datadouble/api.py +1159 -0
- datadouble/boundary.py +47 -0
- datadouble/catalog.py +677 -0
- datadouble/channels.py +62 -0
- datadouble/ci.py +1357 -0
- datadouble/cli.py +940 -0
- datadouble/closure.py +712 -0
- datadouble/engine.py +435 -0
- datadouble/files.py +78 -0
- datadouble/images.py +265 -0
- datadouble/jailer.py +403 -0
- datadouble/names.py +114 -0
- datadouble/notify.py +262 -0
- datadouble/objects.py +195 -0
- datadouble/outcome.py +27 -0
- datadouble/pii.py +109 -0
- datadouble/planner.py +1492 -0
- datadouble/programs.py +68 -0
- datadouble/promote.py +190 -0
- datadouble/prune.py +258 -0
- datadouble/py.typed +0 -0
- datadouble/redaction.py +131 -0
- datadouble/registry.py +128 -0
- datadouble/replicate.py +562 -0
- datadouble/resolve.py +201 -0
- datadouble/run.py +1075 -0
- datadouble/runtime.py +154 -0
- datadouble/secrets.py +57 -0
- datadouble/settings.py +81 -0
- datadouble/signing.py +98 -0
- datadouble/spec.py +1590 -0
- datadouble/staging.py +346 -0
- datadouble/storage.py +222 -0
- datadouble/strict.py +498 -0
- datadouble/subset.py +406 -0
- datadouble/verify.py +171 -0
- datadouble/versions.py +25 -0
- datadouble-0.0.3.dist-info/METADATA +36 -0
- datadouble-0.0.3.dist-info/RECORD +45 -0
- datadouble-0.0.3.dist-info/WHEEL +4 -0
- datadouble-0.0.3.dist-info/entry_points.txt +12 -0
- datadouble-0.0.3.dist-info/licenses/LICENSE +21 -0
datadouble/names.py
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
# Copyright (c) 2026- Tight Line LLC
|
|
2
|
+
# SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
"""Typed identifiers.
|
|
5
|
+
|
|
6
|
+
Catalog objects, images and runs are named by small value types rather than
|
|
7
|
+
plain strings, so a column cannot be passed where a table is expected.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import re
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
from typing import NewType, Self
|
|
13
|
+
|
|
14
|
+
from pydantic import ConfigDict
|
|
15
|
+
|
|
16
|
+
SpecName = NewType("SpecName", str)
|
|
17
|
+
"""The name of a spec, the first part of every image's identity."""
|
|
18
|
+
|
|
19
|
+
GroupName = NewType("GroupName", str)
|
|
20
|
+
"""The name of an image group (``images:`` in the spec)."""
|
|
21
|
+
|
|
22
|
+
SourceName = NewType("SourceName", str)
|
|
23
|
+
"""The name of one of a spec's sources (``sources:`` in the spec)."""
|
|
24
|
+
|
|
25
|
+
EngineName = NewType("EngineName", str)
|
|
26
|
+
"""The name an engine adapter registers under, such as ``postgres``."""
|
|
27
|
+
|
|
28
|
+
Generation = NewType("Generation", str)
|
|
29
|
+
"""The ID shared by every image from one build; sorts by build time."""
|
|
30
|
+
|
|
31
|
+
ColumnName = NewType("ColumnName", str)
|
|
32
|
+
"""A column name as the catalog spells it."""
|
|
33
|
+
|
|
34
|
+
FileDigest = NewType("FileDigest", str)
|
|
35
|
+
"""The SHA-256 of a file's bytes, written as ``sha256:`` and the hex digest."""
|
|
36
|
+
|
|
37
|
+
DEFAULT_GROUP = GroupName("all")
|
|
38
|
+
"""The single group a spec without an ``images:`` section produces."""
|
|
39
|
+
|
|
40
|
+
_NAME = re.compile(r"^[a-z0-9][a-z0-9_-]{0,62}$")
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def check_name(kind: str, value: str) -> str:
|
|
44
|
+
"""Return ``value`` if it is a valid spec, group or channel name.
|
|
45
|
+
|
|
46
|
+
These names become path components in stores, so they are limited to
|
|
47
|
+
lowercase letters, digits, ``-`` and ``_``.
|
|
48
|
+
"""
|
|
49
|
+
if not _NAME.match(value):
|
|
50
|
+
message = (
|
|
51
|
+
f"{kind} {value!r} must be 1-63 lowercase letters, digits, '-' or '_', "
|
|
52
|
+
"starting with a letter or digit"
|
|
53
|
+
)
|
|
54
|
+
raise ValueError(message)
|
|
55
|
+
return value
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
@dataclass(frozen=True, order=True, slots=True)
|
|
59
|
+
class TableName:
|
|
60
|
+
"""A table (or collection, index, object set) and the namespaces it sits in.
|
|
61
|
+
|
|
62
|
+
``namespace`` is the path of namespaces that hold the table, outermost
|
|
63
|
+
first: a schema for SQL Server and Oracle, a database for MySQL, MongoDB
|
|
64
|
+
and Redis, a database and a schema for PostgreSQL, and nothing for engines
|
|
65
|
+
with a single namespace. Its length is fixed per engine, so names compare
|
|
66
|
+
and sort part by part.
|
|
67
|
+
"""
|
|
68
|
+
|
|
69
|
+
__pydantic_config__ = ConfigDict(strict=True, extra="forbid")
|
|
70
|
+
|
|
71
|
+
namespace: tuple[str, ...]
|
|
72
|
+
name: str
|
|
73
|
+
|
|
74
|
+
def __post_init__(self) -> None:
|
|
75
|
+
"""Refuse empty parts, which would print as stray dots."""
|
|
76
|
+
if not self.name or not all(self.namespace):
|
|
77
|
+
message = f"a table name has an empty part: {self.parts!r}"
|
|
78
|
+
raise ValueError(message)
|
|
79
|
+
|
|
80
|
+
def __str__(self) -> str:
|
|
81
|
+
"""The parts joined with dots, such as ``shop.public.users``."""
|
|
82
|
+
return ".".join(self.parts)
|
|
83
|
+
|
|
84
|
+
@property
|
|
85
|
+
def parts(self) -> tuple[str, ...]:
|
|
86
|
+
"""The namespaces and then the name."""
|
|
87
|
+
return (*self.namespace, self.name)
|
|
88
|
+
|
|
89
|
+
@property
|
|
90
|
+
def outermost(self) -> str:
|
|
91
|
+
"""The outermost namespace (a database, say), or the name when there is none."""
|
|
92
|
+
return self.parts[0]
|
|
93
|
+
|
|
94
|
+
@classmethod
|
|
95
|
+
def of(cls, *parts: str) -> Self:
|
|
96
|
+
"""Build a table name from its namespaces and name, outermost first."""
|
|
97
|
+
if not parts:
|
|
98
|
+
message = "a table name needs at least its name"
|
|
99
|
+
raise ValueError(message)
|
|
100
|
+
return cls(namespace=parts[:-1], name=parts[-1])
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
@dataclass(frozen=True, order=True, slots=True)
|
|
104
|
+
class ColumnRef:
|
|
105
|
+
"""A column of a particular table."""
|
|
106
|
+
|
|
107
|
+
__pydantic_config__ = ConfigDict(strict=True, extra="forbid")
|
|
108
|
+
|
|
109
|
+
table: TableName
|
|
110
|
+
column: ColumnName
|
|
111
|
+
|
|
112
|
+
def __str__(self) -> str:
|
|
113
|
+
"""The table's name and then the column's, such as ``public.users.email``."""
|
|
114
|
+
return f"{self.table}.{self.column}"
|
datadouble/notify.py
ADDED
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
# Copyright (c) 2026- Tight Line LLC
|
|
2
|
+
# SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
"""Notifications from generated CI jobs (decision 125).
|
|
5
|
+
|
|
6
|
+
A job ``ci init`` writes names itself in its requests (``ci.job``). When its
|
|
7
|
+
command ends with an outcome the spec's ``notify`` section lists, Datadouble
|
|
8
|
+
posts a :class:`Notification` to each webhook target itself, after the
|
|
9
|
+
command and before the job ends, so webhooks work the same way on every CI
|
|
10
|
+
system. Email goes through the CI system's own mechanism, which the CI/CD
|
|
11
|
+
adapter writes, or explains in ``ci init``'s instructions.
|
|
12
|
+
|
|
13
|
+
A notification that fails never changes the job's outcome: the problem is
|
|
14
|
+
returned for the caller to log, and the job ends as it would have. The
|
|
15
|
+
payload, its ``text`` line included, carries names, codes and outcomes, never
|
|
16
|
+
data values or secrets (decisions 18 and 54), and problems never quote the
|
|
17
|
+
webhook's URL, which is a secret.
|
|
18
|
+
|
|
19
|
+
A recovery (decision 142) needs the job's previous outcome, which only the job
|
|
20
|
+
itself can keep. When ``ci init`` names a record file (``ci.record``), the
|
|
21
|
+
command reads it before it starts, marks it ``running`` and writes its own
|
|
22
|
+
outcome there when it ends. A success after anything else, including a run
|
|
23
|
+
that never got to write its outcome, is a recovery. The record holds only an
|
|
24
|
+
outcome.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
import base64
|
|
28
|
+
import contextlib
|
|
29
|
+
import http.client
|
|
30
|
+
import json
|
|
31
|
+
import os
|
|
32
|
+
import ssl
|
|
33
|
+
import urllib.error
|
|
34
|
+
import urllib.request
|
|
35
|
+
from collections.abc import Callable, Mapping
|
|
36
|
+
from email.message import Message
|
|
37
|
+
from pathlib import Path
|
|
38
|
+
from typing import IO, override
|
|
39
|
+
from urllib.parse import unquote, urlsplit, urlunsplit
|
|
40
|
+
|
|
41
|
+
from pydantic import BaseModel, ConfigDict, ValidationError
|
|
42
|
+
|
|
43
|
+
from datadouble import __version__
|
|
44
|
+
from datadouble.ci import JobKind
|
|
45
|
+
from datadouble.outcome import Outcome
|
|
46
|
+
from datadouble.secrets import SecretError, resolve_secret
|
|
47
|
+
from datadouble.spec import Notify, WebhookFormat
|
|
48
|
+
|
|
49
|
+
TIMEOUT_SECONDS = 10
|
|
50
|
+
"""How long a webhook may take to answer; a job never waits on one for longer."""
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class Notification(BaseModel):
|
|
54
|
+
"""The JSON body posted to a webhook: what ran and how it ended, never data."""
|
|
55
|
+
|
|
56
|
+
model_config = ConfigDict(strict=True, frozen=True, extra="forbid")
|
|
57
|
+
|
|
58
|
+
spec: str
|
|
59
|
+
"""The spec's name."""
|
|
60
|
+
job: JobKind
|
|
61
|
+
"""The generated job: ``build``, ``promote``, ``fetch``, ``provision`` and so on."""
|
|
62
|
+
outcome: Outcome
|
|
63
|
+
recovered: bool = False
|
|
64
|
+
"""Whether this success follows a run that did not succeed (``recovery``)."""
|
|
65
|
+
generation: str | None = None
|
|
66
|
+
"""The generation a ``build`` made or resumed, when it got that far."""
|
|
67
|
+
error: str | None = None
|
|
68
|
+
"""The error code of a failed request, such as ``store_failed``."""
|
|
69
|
+
run_url: str | None = None
|
|
70
|
+
"""The CI system's page for the run, where it has one."""
|
|
71
|
+
|
|
72
|
+
@property
|
|
73
|
+
def text(self) -> str:
|
|
74
|
+
"""One line a person can read, built from the other fields.
|
|
75
|
+
|
|
76
|
+
Chat incoming webhooks (Slack, Mattermost, Rocket.Chat) show ``text``
|
|
77
|
+
and ignore the other keys, such as
|
|
78
|
+
``Datadouble shop: build failed (store_failed) - https://ci.example.com/7``.
|
|
79
|
+
"""
|
|
80
|
+
said = "recovered" if self.recovered else _SAID[self.outcome]
|
|
81
|
+
line = f"Datadouble {self.spec}: {self.job} {said}"
|
|
82
|
+
if self.error is not None:
|
|
83
|
+
line += f" ({self.error})"
|
|
84
|
+
if self.generation is not None:
|
|
85
|
+
line += f", generation {self.generation}"
|
|
86
|
+
if self.run_url is not None:
|
|
87
|
+
line += f" - {self.run_url}"
|
|
88
|
+
return " ".join(line.split())
|
|
89
|
+
|
|
90
|
+
def body(self, shape: WebhookFormat = WebhookFormat.JSON) -> bytes:
|
|
91
|
+
"""The JSON posted: every field then ``text``, or for ``chat`` only ``text``."""
|
|
92
|
+
if shape is WebhookFormat.CHAT:
|
|
93
|
+
return json.dumps({"text": self.text}).encode()
|
|
94
|
+
return json.dumps({**self.model_dump(mode="json"), "text": self.text}).encode()
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
_SAID = {
|
|
98
|
+
Outcome.FAILURE: "failed",
|
|
99
|
+
Outcome.WARNING: "passed with warnings",
|
|
100
|
+
Outcome.SUCCESS: "succeeded",
|
|
101
|
+
}
|
|
102
|
+
"""How ``text`` says each outcome."""
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
class NotifyError(Exception):
|
|
106
|
+
"""A webhook that cannot be posted to."""
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
type Post = Callable[[str, bytes], None]
|
|
110
|
+
"""Posts a JSON body to a URL, raising on any failure."""
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
class _Post(urllib.request.Request):
|
|
114
|
+
"""A JSON POST; the URL's scheme is checked before one is made."""
|
|
115
|
+
|
|
116
|
+
def __init__(self, url: str, body: bytes, headers: dict[str, str]) -> None:
|
|
117
|
+
super().__init__(url, data=body, headers=headers, method="POST")
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
class _NoRedirects(urllib.request.HTTPRedirectHandler):
|
|
121
|
+
"""Never follow a redirect: a 3xx answer is a failure, like any status but 2xx."""
|
|
122
|
+
|
|
123
|
+
@override
|
|
124
|
+
def redirect_request(
|
|
125
|
+
self,
|
|
126
|
+
req: urllib.request.Request,
|
|
127
|
+
fp: IO[bytes],
|
|
128
|
+
code: int,
|
|
129
|
+
msg: str,
|
|
130
|
+
headers: Message,
|
|
131
|
+
newurl: str,
|
|
132
|
+
) -> urllib.request.Request | None:
|
|
133
|
+
return None
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def tls_context() -> ssl.SSLContext:
|
|
137
|
+
"""The TLS settings webhooks are posted with: certificates and host names verified."""
|
|
138
|
+
return ssl.create_default_context()
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def post(url: str, body: bytes) -> None:
|
|
142
|
+
"""POST ``body`` as JSON to ``url``; any status but 2xx raises.
|
|
143
|
+
|
|
144
|
+
The environment's proxy settings apply (``HTTPS_PROXY``, ``HTTP_PROXY``,
|
|
145
|
+
``NO_PROXY``). Credentials in the URL (``https://user:token@host/...``)
|
|
146
|
+
are sent as basic authentication, and only over https.
|
|
147
|
+
"""
|
|
148
|
+
parts = urlsplit(url)
|
|
149
|
+
if parts.scheme not in {"https", "http"} or not parts.hostname:
|
|
150
|
+
message = "its URL must start with https:// or http:// and name a host"
|
|
151
|
+
raise NotifyError(message)
|
|
152
|
+
headers = {"Content-Type": "application/json", "User-Agent": f"datadouble/{__version__}"}
|
|
153
|
+
if parts.username is not None:
|
|
154
|
+
if parts.scheme != "https":
|
|
155
|
+
message = "a URL with credentials must use https://"
|
|
156
|
+
raise NotifyError(message)
|
|
157
|
+
pair = f"{unquote(parts.username)}:{unquote(parts.password or '')}"
|
|
158
|
+
headers["Authorization"] = "Basic " + base64.b64encode(pair.encode()).decode()
|
|
159
|
+
host = f"[{parts.hostname}]" if ":" in parts.hostname else parts.hostname
|
|
160
|
+
netloc = host if parts.port is None else f"{host}:{parts.port}"
|
|
161
|
+
bare = urlunsplit((parts.scheme, netloc, parts.path or "/", parts.query, ""))
|
|
162
|
+
opener = urllib.request.build_opener(
|
|
163
|
+
urllib.request.ProxyHandler(),
|
|
164
|
+
urllib.request.HTTPSHandler(context=tls_context()),
|
|
165
|
+
_NoRedirects(),
|
|
166
|
+
)
|
|
167
|
+
try:
|
|
168
|
+
with opener.open(_Post(bare, body, headers), timeout=TIMEOUT_SECONDS) as response:
|
|
169
|
+
response.read()
|
|
170
|
+
except urllib.error.HTTPError as error:
|
|
171
|
+
error.close()
|
|
172
|
+
message = f"the server answered with HTTP status {error.code}"
|
|
173
|
+
raise NotifyError(message) from None
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def _problem(error: Exception) -> str:
|
|
177
|
+
"""Why a post failed, without the URL or anything the server sent."""
|
|
178
|
+
match error:
|
|
179
|
+
case NotifyError() | SecretError():
|
|
180
|
+
return str(error)
|
|
181
|
+
case urllib.error.URLError(reason=BaseException() as reason):
|
|
182
|
+
return f"the request failed ({type(reason).__name__})"
|
|
183
|
+
case _:
|
|
184
|
+
return f"the request failed ({type(error).__name__})"
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def send(
|
|
188
|
+
notify: Notify | None,
|
|
189
|
+
notification: Notification,
|
|
190
|
+
*,
|
|
191
|
+
environ: Mapping[str, str] | None = None,
|
|
192
|
+
poster: Post = post,
|
|
193
|
+
) -> tuple[str, ...]:
|
|
194
|
+
"""Post to every webhook target, if the outcome is one ``notify`` lists.
|
|
195
|
+
|
|
196
|
+
Returns a problem per webhook that failed; never raises for one.
|
|
197
|
+
"""
|
|
198
|
+
if notify is None or not notify.sends(notification.outcome, recovered=notification.recovered):
|
|
199
|
+
return ()
|
|
200
|
+
problems: list[str] = []
|
|
201
|
+
for index, webhook in enumerate(notify.webhooks(), start=1):
|
|
202
|
+
try:
|
|
203
|
+
poster(resolve_secret(webhook.url, environ), notification.body(webhook.format))
|
|
204
|
+
except (
|
|
205
|
+
NotifyError,
|
|
206
|
+
SecretError,
|
|
207
|
+
OSError,
|
|
208
|
+
ValueError,
|
|
209
|
+
http.client.HTTPException,
|
|
210
|
+
) as error:
|
|
211
|
+
problems.append(f"webhook {index}: {_problem(error)}")
|
|
212
|
+
return tuple(problems)
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
RUNNING = "running"
|
|
216
|
+
"""What a job's record says while its command runs. A run stopped before it
|
|
217
|
+
ends leaves it so, and is not a success."""
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
class _Record(BaseModel):
|
|
221
|
+
"""A job's record: its last run's outcome, and nothing else."""
|
|
222
|
+
|
|
223
|
+
model_config = ConfigDict(strict=True, frozen=True, extra="forbid")
|
|
224
|
+
|
|
225
|
+
outcome: str
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def recall(path: Path) -> tuple[str | None, tuple[str, ...]]:
|
|
229
|
+
"""The outcome the job's previous run recorded, then mark this run as running.
|
|
230
|
+
|
|
231
|
+
No record, or one that cannot be read, is None: no recovery is posted.
|
|
232
|
+
Returns the problems for the caller to log; never raises for one.
|
|
233
|
+
"""
|
|
234
|
+
previous: str | None = None
|
|
235
|
+
problems: list[str] = []
|
|
236
|
+
try:
|
|
237
|
+
previous = _Record.model_validate_json(path.read_bytes()).outcome
|
|
238
|
+
except FileNotFoundError:
|
|
239
|
+
pass
|
|
240
|
+
except (OSError, ValidationError) as error:
|
|
241
|
+
problems.append(f"the job's outcome record could not be read ({type(error).__name__})")
|
|
242
|
+
problems.extend(remember(path, RUNNING))
|
|
243
|
+
return previous, tuple(problems)
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def remember(path: Path, outcome: str) -> tuple[str, ...]:
|
|
247
|
+
"""Write the job's outcome to its record; returns a problem instead of raising."""
|
|
248
|
+
temporary = path.with_name(f".{path.name}.{os.getpid()}")
|
|
249
|
+
try:
|
|
250
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
251
|
+
temporary.write_text(_Record(outcome=outcome).model_dump_json(), encoding="utf-8")
|
|
252
|
+
temporary.replace(path)
|
|
253
|
+
except OSError as error:
|
|
254
|
+
with contextlib.suppress(OSError):
|
|
255
|
+
temporary.unlink(missing_ok=True)
|
|
256
|
+
return (f"the job's outcome record could not be written ({type(error).__name__})",)
|
|
257
|
+
return ()
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def recovered(previous: str | None, outcome: Outcome) -> bool:
|
|
261
|
+
"""Whether a run ending with ``outcome`` recovers from one that ended with ``previous``."""
|
|
262
|
+
return outcome is Outcome.SUCCESS and previous is not None and previous != Outcome.SUCCESS
|
datadouble/objects.py
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
# Copyright (c) 2026- Tight Line LLC
|
|
2
|
+
# SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
"""Inferring an object's dependencies from the text of its definition.
|
|
5
|
+
|
|
6
|
+
Engines record exactly what views and triggers depend on, but rarely what a
|
|
7
|
+
procedural routine's body uses. For those bodies an adapter calls
|
|
8
|
+
:func:`infer_dependencies`, which strips comments and string literals, reads
|
|
9
|
+
the identifiers left, and matches them against the catalog's tables and
|
|
10
|
+
objects by name. Every edge it returns is marked ``inferred``: it is a best
|
|
11
|
+
effort, which a name that happens to match a column or a variable can fool,
|
|
12
|
+
and a statement built from strings at run time escapes.
|
|
13
|
+
|
|
14
|
+
The matching is engine-neutral; the adapter describes its engine's
|
|
15
|
+
:class:`Dialect`: how it quotes identifiers and strings and how it comments.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
import re
|
|
19
|
+
from collections import defaultdict
|
|
20
|
+
from collections.abc import Iterable, Iterator
|
|
21
|
+
from dataclasses import dataclass, field
|
|
22
|
+
|
|
23
|
+
from datadouble.catalog import Dependency, ObjectKind, ObjectRef, SourceObject, Table
|
|
24
|
+
from datadouble.names import TableName
|
|
25
|
+
|
|
26
|
+
_QUOTED = {
|
|
27
|
+
'"': r'"(?:[^"]|"")+"',
|
|
28
|
+
"`": r"`(?:[^`]|``)+`",
|
|
29
|
+
"[": r"\[(?:[^\]]|\]\])+\]",
|
|
30
|
+
}
|
|
31
|
+
_WORD = r"[^\W\d][\w$#@]*"
|
|
32
|
+
"""An unquoted identifier: a letter or underscore, any script, then word characters."""
|
|
33
|
+
|
|
34
|
+
_NAMED_IN_CODE = frozenset(
|
|
35
|
+
{
|
|
36
|
+
ObjectKind.FUNCTION,
|
|
37
|
+
ObjectKind.PROCEDURE,
|
|
38
|
+
ObjectKind.PACKAGE,
|
|
39
|
+
ObjectKind.VIEW,
|
|
40
|
+
ObjectKind.MATERIALIZED_VIEW,
|
|
41
|
+
ObjectKind.TYPE,
|
|
42
|
+
ObjectKind.SEQUENCE,
|
|
43
|
+
}
|
|
44
|
+
)
|
|
45
|
+
"""Kinds a body names to use them; triggers and events are never called by name."""
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@dataclass(frozen=True)
|
|
49
|
+
class Dialect:
|
|
50
|
+
"""How an engine spells identifiers, literals and comments in its routine bodies."""
|
|
51
|
+
|
|
52
|
+
quotes: str
|
|
53
|
+
"""The characters that open a quoted identifier: ``"``, a backtick, ``[``."""
|
|
54
|
+
backslash_escapes: bool = False
|
|
55
|
+
"""Whether a backslash escapes the next character in a string literal."""
|
|
56
|
+
hash_comments: bool = False
|
|
57
|
+
"""Whether ``#`` starts a comment, as in MySQL and PL/Python."""
|
|
58
|
+
double_quoted_strings: bool = False
|
|
59
|
+
"""Whether ``"..."`` is a string, as in MySQL's default SQL mode."""
|
|
60
|
+
dollar_quotes: bool = False
|
|
61
|
+
"""Whether ``$tag$...$tag$`` is a string, as in PostgreSQL; ``E'...'`` escapes too."""
|
|
62
|
+
|
|
63
|
+
def pattern(self) -> re.Pattern[str]:
|
|
64
|
+
"""A name of one to three dotted parts."""
|
|
65
|
+
part = "(?:" + "|".join([*(_QUOTED[q] for q in self.quotes), _WORD]) + ")"
|
|
66
|
+
return re.compile(rf"({part})(?:\s*\.\s*({part}))?(?:\s*\.\s*({part}))?")
|
|
67
|
+
|
|
68
|
+
def strip(self, text: str) -> str:
|
|
69
|
+
"""``text`` without comments and string literals, keeping quoted identifiers.
|
|
70
|
+
|
|
71
|
+
One scan reads every token left to right, so a ``--`` inside a quoted
|
|
72
|
+
identifier or a quote inside a dollar-quoted string is read correctly.
|
|
73
|
+
"""
|
|
74
|
+
escaped = r"'(?:[^'\\]|\\.|'')*'"
|
|
75
|
+
skipped = [r"--[^\n]*", r"/\*.*?\*/"]
|
|
76
|
+
if self.hash_comments:
|
|
77
|
+
skipped.append(r"#[^\n]*")
|
|
78
|
+
if self.dollar_quotes:
|
|
79
|
+
skipped += [r"\$(?P<tag>(?:[^\W\d]\w*)?)\$.*?\$(?P=tag)\$", r"[Ee]" + escaped]
|
|
80
|
+
skipped.append(escaped if self.backslash_escapes else r"'(?:[^']|'')*'")
|
|
81
|
+
if self.double_quoted_strings:
|
|
82
|
+
skipped.append(r'"(?:[^"\\]|\\.|"")*"')
|
|
83
|
+
kept = [_QUOTED[q] for q in self.quotes]
|
|
84
|
+
scan = re.compile(
|
|
85
|
+
"|".join([f"(?P<kept>{'|'.join(kept)})", *skipped]) if kept else "|".join(skipped),
|
|
86
|
+
flags=re.DOTALL,
|
|
87
|
+
)
|
|
88
|
+
return scan.sub(lambda found: found["kept"] or " " if kept else " ", text)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _unquote(part: str) -> str:
|
|
92
|
+
if part[:1] in _QUOTED and len(part) > 1:
|
|
93
|
+
closing = "]" if part[0] == "[" else part[0]
|
|
94
|
+
return part[1:-1].replace(closing * 2, closing)
|
|
95
|
+
return part
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
@dataclass
|
|
99
|
+
class Candidates:
|
|
100
|
+
"""The tables and objects a body might name, by lowercased name, with their namespaces."""
|
|
101
|
+
|
|
102
|
+
by_name: defaultdict[str, list[tuple[tuple[str, ...], Dependency]]] = field(
|
|
103
|
+
default_factory=lambda: defaultdict[str, list[tuple[tuple[str, ...], Dependency]]](list)
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
@classmethod
|
|
107
|
+
def of(cls, tables: Iterable[Table], objects: Iterable[SourceObject]) -> "Candidates":
|
|
108
|
+
"""Every table, and every object a body can name."""
|
|
109
|
+
found = cls()
|
|
110
|
+
for table in tables:
|
|
111
|
+
found.add(
|
|
112
|
+
table.name.namespace, table.name.name, Dependency(table=table.name, inferred=True)
|
|
113
|
+
)
|
|
114
|
+
for item in objects:
|
|
115
|
+
if item.ref.kind in _NAMED_IN_CODE:
|
|
116
|
+
found.add(
|
|
117
|
+
item.ref.namespace, item.ref.name, Dependency(object=item.ref, inferred=True)
|
|
118
|
+
)
|
|
119
|
+
return found
|
|
120
|
+
|
|
121
|
+
def add(self, namespace: tuple[str, ...], name: str, edge: Dependency) -> None:
|
|
122
|
+
"""Index ``edge`` under its name."""
|
|
123
|
+
self.by_name[name.lower()].append((_lower(namespace), edge))
|
|
124
|
+
|
|
125
|
+
def lookup(self, parts: tuple[str, ...], home: tuple[str, ...]) -> list[Dependency]:
|
|
126
|
+
"""The candidates a dotted name may mean.
|
|
127
|
+
|
|
128
|
+
The name's qualifiers and a candidate's namespace must agree from the
|
|
129
|
+
right, as spec names match: ``public.users`` fits ``shop.public``, and
|
|
130
|
+
a database-qualified ``shop.dbo.users`` fits ``dbo``. Of those, the ones sharing the
|
|
131
|
+
most leading namespaces with ``home`` (the object's own) win: an
|
|
132
|
+
unqualified name means the object's own schema first, then its own
|
|
133
|
+
database, then anywhere.
|
|
134
|
+
"""
|
|
135
|
+
qualifiers = _lower(parts[:-1])
|
|
136
|
+
found = [
|
|
137
|
+
(namespace, edge)
|
|
138
|
+
for namespace, edge in self.by_name.get(parts[-1].lower(), [])
|
|
139
|
+
if _tail(namespace, len(qualifiers)) == _tail(qualifiers, len(namespace))
|
|
140
|
+
]
|
|
141
|
+
scores = [_shared(namespace, _lower(home)) for namespace, _ in found]
|
|
142
|
+
best = max(scores, default=0)
|
|
143
|
+
return [edge for (_, edge), score in zip(found, scores, strict=True) if score == best]
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def _lower(parts: tuple[str, ...]) -> tuple[str, ...]:
|
|
147
|
+
return tuple(part.lower() for part in parts)
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _tail(parts: tuple[str, ...], count: int) -> tuple[str, ...]:
|
|
151
|
+
return parts[len(parts) - count :] if count < len(parts) else parts
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _shared(one: tuple[str, ...], other: tuple[str, ...]) -> int:
|
|
155
|
+
"""How many leading parts two namespaces share."""
|
|
156
|
+
count = 0
|
|
157
|
+
for left, right in zip(one, other, strict=False):
|
|
158
|
+
if left != right:
|
|
159
|
+
break
|
|
160
|
+
count += 1
|
|
161
|
+
return count
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def _named(
|
|
165
|
+
text: str, home: tuple[str, ...], candidates: Candidates, dialect: Dialect
|
|
166
|
+
) -> Iterator[Dependency]:
|
|
167
|
+
"""Every candidate a name in ``text`` may mean, read from ``home``."""
|
|
168
|
+
for match in dialect.pattern().finditer(dialect.strip(text)):
|
|
169
|
+
parts = tuple(_unquote(part) for part in match.groups() if part)
|
|
170
|
+
# `users.email` names the table users; `public.users` names it too.
|
|
171
|
+
for end in range(len(parts), 0, -1):
|
|
172
|
+
yield from candidates.lookup(parts[:end], home)
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def infer_dependencies(
|
|
176
|
+
text: str, own: ObjectRef, candidates: Candidates, dialect: Dialect
|
|
177
|
+
) -> tuple[Dependency, ...]:
|
|
178
|
+
"""The tables and objects ``text`` names, as inferred edges, leaving out ``own``."""
|
|
179
|
+
found = _named(text, own.namespace, candidates, dialect)
|
|
180
|
+
return tuple(dict.fromkeys(edge for edge in found if edge.object != own))
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def infer_table_needs(
|
|
184
|
+
text: str, table: TableName, candidates: Candidates, dialect: Dialect
|
|
185
|
+
) -> tuple[Dependency, ...]:
|
|
186
|
+
"""The objects a table's default or check expression ``text`` names, as inferred edges."""
|
|
187
|
+
found = _named(text, table.namespace, candidates, dialect)
|
|
188
|
+
return tuple(dict.fromkeys(edge for edge in found if edge.object is not None))
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def merge(exact: Iterable[Dependency], inferred: Iterable[Dependency]) -> tuple[Dependency, ...]:
|
|
192
|
+
"""Exact edges, then inferred ones that no exact edge already covers."""
|
|
193
|
+
known = {(edge.table, edge.object) for edge in exact}
|
|
194
|
+
extra = [edge for edge in inferred if (edge.table, edge.object) not in known]
|
|
195
|
+
return (*dict.fromkeys(exact), *dict.fromkeys(extra))
|
datadouble/outcome.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
# Copyright (c) 2026- Tight Line LLC
|
|
2
|
+
# SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
"""How an operation ended, and the exit codes that say so."""
|
|
5
|
+
|
|
6
|
+
from enum import IntEnum, StrEnum
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class Outcome(StrEnum):
|
|
10
|
+
"""How an operation ended.
|
|
11
|
+
|
|
12
|
+
Anything that could put real personal data into a copy is always a
|
|
13
|
+
failure, never a warning.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
SUCCESS = "success"
|
|
17
|
+
WARNING = "warning"
|
|
18
|
+
FAILURE = "failure"
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class ExitCode(IntEnum):
|
|
22
|
+
"""Process exit codes, so CI systems can tell a warning from a failure."""
|
|
23
|
+
|
|
24
|
+
SUCCESS = 0
|
|
25
|
+
FAILURE = 1
|
|
26
|
+
USAGE = 2
|
|
27
|
+
WARNING = 3
|