umf-access 0.1.0.dev8__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.
- umf_access/__init__.py +109 -0
- umf_access/adoption.py +41 -0
- umf_access/build/__init__.py +2 -0
- umf_access/build/approximate.py +34 -0
- umf_access/build/catalog.py +1626 -0
- umf_access/build/commands.py +394 -0
- umf_access/build/pg_privileges.py +1544 -0
- umf_access/build/privileges.py +134 -0
- umf_access/build/search.py +365 -0
- umf_access/build/unity_search.py +104 -0
- umf_access/bulk.py +227 -0
- umf_access/canonical.py +23 -0
- umf_access/capture.py +410 -0
- umf_access/catalog.py +325 -0
- umf_access/codec_support.py +427 -0
- umf_access/commands.py +93 -0
- umf_access/delta_read.py +758 -0
- umf_access/dsl/__init__.py +148 -0
- umf_access/dsl/_context.py +36 -0
- umf_access/dsl/_expressions.py +625 -0
- umf_access/dsl/_joined.py +4 -0
- umf_access/dsl/_nodes.py +207 -0
- umf_access/dsl/_query.py +5559 -0
- umf_access/dsl/_selection.py +143 -0
- umf_access/dsl/navigation.py +302 -0
- umf_access/dsl/render.py +516 -0
- umf_access/dsl/search.py +343 -0
- umf_access/engine_catalog.py +563 -0
- umf_access/generated_core.py +5 -0
- umf_access/lifecycle/__init__.py +46 -0
- umf_access/lifecycle/_darwin_process_observer.c +306 -0
- umf_access/lifecycle/approval.py +366 -0
- umf_access/lifecycle/backfills.py +79 -0
- umf_access/lifecycle/catalog.py +289 -0
- umf_access/lifecycle/cli.py +231 -0
- umf_access/lifecycle/concurrent.py +196 -0
- umf_access/lifecycle/conversion_policy.py +188 -0
- umf_access/lifecycle/correspondence.py +203 -0
- umf_access/lifecycle/generation_authority_bootstrap.py +1491 -0
- umf_access/lifecycle/generation_authority_session.py +125 -0
- umf_access/lifecycle/generation_enrollment_authority.py +1108 -0
- umf_access/lifecycle/generation_enrollment_ledger.py +698 -0
- umf_access/lifecycle/generation_ingress.py +185 -0
- umf_access/lifecycle/generation_root_registry.py +138 -0
- umf_access/lifecycle/head.py +250 -0
- umf_access/lifecycle/head_view.py +81 -0
- umf_access/lifecycle/host.py +1183 -0
- umf_access/lifecycle/ingress_custody.py +750 -0
- umf_access/lifecycle/ingress_local_postgres.py +7990 -0
- umf_access/lifecycle/ingress_store.py +1488 -0
- umf_access/lifecycle/ledger.py +276 -0
- umf_access/lifecycle/ledger_schema.py +116 -0
- umf_access/lifecycle/mixed.py +593 -0
- umf_access/lifecycle/outcome_schema.py +136 -0
- umf_access/lifecycle/owner_approval_core.py +1810 -0
- umf_access/lifecycle/owner_authority.py +472 -0
- umf_access/lifecycle/owner_bootstrap.py +2077 -0
- umf_access/lifecycle/owner_wire.py +161 -0
- umf_access/lifecycle/phase_fence.py +52 -0
- umf_access/lifecycle/phase_policy.py +422 -0
- umf_access/lifecycle/privileges.py +145 -0
- umf_access/lifecycle/probe.py +39 -0
- umf_access/lifecycle/progress.py +497 -0
- umf_access/lifecycle/roles.py +96 -0
- umf_access/lifecycle/row_originals.py +1712 -0
- umf_access/lifecycle/row_originals_creation.py +759 -0
- umf_access/lifecycle/row_originals_receipt.py +413 -0
- umf_access/lifecycle/seeds.py +99 -0
- umf_access/lifecycle/sql_containment.py +358 -0
- umf_access/lifecycle/sql_containment_cli.py +33 -0
- umf_access/lifecycle/sql_containment_parser.py +20 -0
- umf_access/lifecycle/supervisor_journal_codec.py +1251 -0
- umf_access/lifecycle/table_boundary.py +22 -0
- umf_access/lifecycle/target_custody_codec.py +788 -0
- umf_access/lifecycle/witness.py +72 -0
- umf_access/managed_actions.py +271 -0
- umf_access/managed_bulk.py +353 -0
- umf_access/managed_delta.py +150 -0
- umf_access/managed_support.py +166 -0
- umf_access/manifest_commands.py +278 -0
- umf_access/native_actions.py +1007 -0
- umf_access/native_program.py +570 -0
- umf_access/pages.py +125 -0
- umf_access/postgres_bulk.py +509 -0
- umf_access/postgres_read.py +1230 -0
- umf_access/postgres_search.py +639 -0
- umf_access/protocols.py +665 -0
- umf_access/py.typed +0 -0
- umf_access/related_keys.py +233 -0
- umf_access/reviewed.py +706 -0
- umf_access/search_catalog.py +122 -0
- umf_access/targets.py +312 -0
- umf_access/types.py +220 -0
- umf_access/unified/__init__.py +187 -0
- umf_access/unified/_binding.py +654 -0
- umf_access/unified/head_session.py +144 -0
- umf_access/unified/native_binding.py +143 -0
- umf_access/unified/operation_values.py +173 -0
- umf_access/unified/outcome_values.py +76 -0
- umf_access/unified/session_async.py +161 -0
- umf_access/unified/session_binding.py +108 -0
- umf_access/unified/session_policy.py +152 -0
- umf_access/unified/session_psycopg2.py +70 -0
- umf_access/unified/session_sqlalchemy.py +161 -0
- umf_access/unified/session_sync.py +148 -0
- umf_access/unified/table_reads.py +314 -0
- umf_access/unified/table_writes.py +193 -0
- umf_access/unity_search.py +312 -0
- umf_access/values.py +280 -0
- umf_access/verification.py +64 -0
- umf_access-0.1.0.dev8.dist-info/METADATA +15 -0
- umf_access-0.1.0.dev8.dist-info/RECORD +117 -0
- umf_access-0.1.0.dev8.dist-info/WHEEL +4 -0
- umf_access-0.1.0.dev8.dist-info/entry_points.txt +4 -0
- umf_access-0.1.0.dev8.dist-info/licenses/LICENSE-APACHE +201 -0
- umf_access-0.1.0.dev8.dist-info/licenses/LICENSE-MIT +21 -0
- umf_access-0.1.0.dev8.dist-info/licenses/LICENSE.md +239 -0
umf_access/reviewed.py
ADDED
|
@@ -0,0 +1,706 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT OR Apache-2.0
|
|
2
|
+
"""Build-time reviewed reads and immutable catalog artifacts.
|
|
3
|
+
|
|
4
|
+
The compiler is supplied explicitly at build time. Runtime never imports Weft.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import hashlib
|
|
10
|
+
import json
|
|
11
|
+
import re
|
|
12
|
+
from collections.abc import Mapping
|
|
13
|
+
from dataclasses import asdict, dataclass, fields, is_dataclass
|
|
14
|
+
from decimal import Decimal
|
|
15
|
+
from typing import Generic, NoReturn, Protocol, TypeVar, cast
|
|
16
|
+
|
|
17
|
+
from pydantic import BaseModel
|
|
18
|
+
|
|
19
|
+
from .dsl import FieldRef, GeneratedSource, KeyLiteral, Node, RecordRef
|
|
20
|
+
from .related_keys import transport_spec
|
|
21
|
+
from .types import RUNTIME_ABI, RUNTIME_IDENTITY
|
|
22
|
+
|
|
23
|
+
P = TypeVar("P", bound=BaseModel)
|
|
24
|
+
R = TypeVar("R", bound=BaseModel)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class ReadBuildError(ValueError):
|
|
28
|
+
pass
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class ReadCompiler(Protocol):
|
|
32
|
+
def compile_raw_read_json(self, request: str) -> str: ...
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _json(value: object) -> str:
|
|
36
|
+
return json.dumps(
|
|
37
|
+
value,
|
|
38
|
+
sort_keys=True,
|
|
39
|
+
ensure_ascii=False,
|
|
40
|
+
separators=(",", ":"),
|
|
41
|
+
allow_nan=False,
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _object(pairs: list[tuple[str, object]]) -> dict[str, object]:
|
|
46
|
+
out: dict[str, object] = {}
|
|
47
|
+
for key, value in pairs:
|
|
48
|
+
if key in out:
|
|
49
|
+
raise ReadBuildError("duplicate catalog member")
|
|
50
|
+
out[key] = value
|
|
51
|
+
return out
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _load(text: str) -> dict[str, object]:
|
|
55
|
+
if len(text) > 2_000_000:
|
|
56
|
+
raise ReadBuildError("catalog artifact exceeds byte budget")
|
|
57
|
+
value: object = json.loads(text, object_pairs_hook=_object)
|
|
58
|
+
if not isinstance(value, dict):
|
|
59
|
+
raise ReadBuildError("catalog object required")
|
|
60
|
+
return cast(dict[str, object], value)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _parameter_positions(sql: str) -> list[tuple[int, int, int]]:
|
|
64
|
+
"""Lossless parameter-style lexing of compiler-owned SQL, never lowering."""
|
|
65
|
+
positions: list[tuple[int, int, int]] = []
|
|
66
|
+
i = 0
|
|
67
|
+
while i < len(sql):
|
|
68
|
+
if sql.startswith("--", i):
|
|
69
|
+
end = sql.find("\n", i + 2)
|
|
70
|
+
i = len(sql) if end < 0 else end + 1
|
|
71
|
+
elif sql.startswith("/*", i):
|
|
72
|
+
depth = 1
|
|
73
|
+
i += 2
|
|
74
|
+
while depth and i < len(sql):
|
|
75
|
+
if sql.startswith("/*", i):
|
|
76
|
+
depth += 1
|
|
77
|
+
i += 2
|
|
78
|
+
elif sql.startswith("*/", i):
|
|
79
|
+
depth -= 1
|
|
80
|
+
i += 2
|
|
81
|
+
else:
|
|
82
|
+
i += 1
|
|
83
|
+
if depth:
|
|
84
|
+
raise ReadBuildError("unterminated compiler SQL comment")
|
|
85
|
+
elif sql[i] in ("'", '"'):
|
|
86
|
+
quote = sql[i]
|
|
87
|
+
escaped = (
|
|
88
|
+
quote == "'"
|
|
89
|
+
and i > 0
|
|
90
|
+
and sql[i - 1] in ("E", "e")
|
|
91
|
+
and (i < 2 or not (sql[i - 2].isalnum() or sql[i - 2] == "_"))
|
|
92
|
+
)
|
|
93
|
+
i += 1
|
|
94
|
+
while i < len(sql):
|
|
95
|
+
if escaped and sql[i] == "\\":
|
|
96
|
+
i += 2
|
|
97
|
+
elif sql[i] == quote:
|
|
98
|
+
if i + 1 < len(sql) and sql[i + 1] == quote:
|
|
99
|
+
i += 2
|
|
100
|
+
else:
|
|
101
|
+
i += 1
|
|
102
|
+
break
|
|
103
|
+
else:
|
|
104
|
+
i += 1
|
|
105
|
+
else:
|
|
106
|
+
raise ReadBuildError("unterminated compiler SQL quote")
|
|
107
|
+
elif sql[i] == "$":
|
|
108
|
+
tag = re.match(r"\$(?:[A-Za-z_][A-Za-z0-9_]*)?\$", sql[i:])
|
|
109
|
+
if tag:
|
|
110
|
+
delimiter = tag[0]
|
|
111
|
+
end = sql.find(delimiter, i + len(delimiter))
|
|
112
|
+
if end < 0:
|
|
113
|
+
raise ReadBuildError("unterminated compiler SQL dollar quote")
|
|
114
|
+
i = end + len(delimiter)
|
|
115
|
+
else:
|
|
116
|
+
parameter = re.match(r"\$([1-9][0-9]*)", sql[i:])
|
|
117
|
+
if parameter:
|
|
118
|
+
end = i + len(parameter[0])
|
|
119
|
+
positions.append((i, end, int(parameter[1]) - 1))
|
|
120
|
+
i = end
|
|
121
|
+
else:
|
|
122
|
+
i += 1
|
|
123
|
+
else:
|
|
124
|
+
i += 1
|
|
125
|
+
return positions
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _dbapi(sql: str) -> str:
|
|
129
|
+
pieces: list[str] = []
|
|
130
|
+
end = 0
|
|
131
|
+
for start, stop, _ in _parameter_positions(sql):
|
|
132
|
+
pieces.extend((sql[end:start].replace("%", "%%"), "%s"))
|
|
133
|
+
end = stop
|
|
134
|
+
pieces.append(sql[end:].replace("%", "%%"))
|
|
135
|
+
return "".join(pieces)
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _dbapi_order(sql: str, order: list[str]) -> list[str]:
|
|
139
|
+
positions = _parameter_positions(sql)
|
|
140
|
+
if any(index >= len(order) for _, _, index in positions):
|
|
141
|
+
raise ReadBuildError("compiler parameter ordinal outside inventory")
|
|
142
|
+
return [order[index] for _, _, index in positions]
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def _compiler_transport(artifact: Mapping[str, object], *, catalog: bool = False) -> bool:
|
|
146
|
+
"""Retain transport sealed by the compiler; legacy catalogs keep their ABI.
|
|
147
|
+
|
|
148
|
+
This digest is an integrity check within trusted build/catalog custody, not
|
|
149
|
+
authentication of an arbitrary program supplied by a caller.
|
|
150
|
+
"""
|
|
151
|
+
structural = dict(artifact)
|
|
152
|
+
structural.pop("generatedSource", None)
|
|
153
|
+
structural.pop("stageOne", None)
|
|
154
|
+
digest = structural.pop("structuralDigest", None)
|
|
155
|
+
present = ("dbapiSql" in structural, "dbapiParameterOrder" in structural)
|
|
156
|
+
if present[0] != present[1]:
|
|
157
|
+
raise ReadBuildError("compiler transport inventory incomplete")
|
|
158
|
+
if digest == hashlib.sha256(_json(structural).encode()).hexdigest():
|
|
159
|
+
if not present[0]:
|
|
160
|
+
return False
|
|
161
|
+
sql, order, native_order = structural["dbapiSql"], structural["dbapiParameterOrder"], structural.get("parameterOrder")
|
|
162
|
+
if (not isinstance(sql, str) or not sql or not isinstance(order, list)
|
|
163
|
+
or not isinstance(native_order, list) or any(not isinstance(name, str) for name in native_order)
|
|
164
|
+
or any(not isinstance(name, str) or name not in native_order for name in order)):
|
|
165
|
+
raise ReadBuildError("compiler transport inventory invalid")
|
|
166
|
+
return True
|
|
167
|
+
# Older SDK catalogs appended their own transport after compiler sealing.
|
|
168
|
+
# Only catalog loading permits that form; a build must not accept supplied
|
|
169
|
+
# but unsealed compiler transport and silently reinterpret it.
|
|
170
|
+
if catalog and present[0]:
|
|
171
|
+
structural.pop("dbapiSql")
|
|
172
|
+
structural.pop("dbapiParameterOrder")
|
|
173
|
+
if digest == hashlib.sha256(_json(structural).encode()).hexdigest():
|
|
174
|
+
return False
|
|
175
|
+
raise ReadBuildError("compiler artifact digest mismatch")
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def parameter_style(sql: str, count: int) -> tuple[str, tuple[int, ...]]:
|
|
179
|
+
"""Build-time DB-API conversion with explicit compiler slot ordinals."""
|
|
180
|
+
positions = _parameter_positions(sql)
|
|
181
|
+
if any(index >= count for _, _, index in positions):
|
|
182
|
+
raise ReadBuildError("compiler parameter ordinal outside inventory")
|
|
183
|
+
return _dbapi(sql), tuple(index for _, _, index in positions)
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def _carrier(annotation: object, *, projection: bool = False) -> tuple[str, bool]:
|
|
187
|
+
from types import UnionType
|
|
188
|
+
from typing import Annotated, Union, get_args, get_origin
|
|
189
|
+
|
|
190
|
+
while get_origin(annotation) is Annotated:
|
|
191
|
+
annotation = get_args(annotation)[0]
|
|
192
|
+
nullable = False
|
|
193
|
+
if get_origin(annotation) in (Union, UnionType):
|
|
194
|
+
members = get_args(annotation)
|
|
195
|
+
nullable = type(None) in members
|
|
196
|
+
rest = [t for t in members if t is not type(None)]
|
|
197
|
+
if len(rest) != 1:
|
|
198
|
+
raise ReadBuildError("one scalar result/parameter carrier required")
|
|
199
|
+
annotation = rest[0]
|
|
200
|
+
while get_origin(annotation) is Annotated:
|
|
201
|
+
annotation = get_args(annotation)[0]
|
|
202
|
+
for typ, name in (
|
|
203
|
+
(str, "string"),
|
|
204
|
+
(int, "integer"),
|
|
205
|
+
(Decimal, "decimal"),
|
|
206
|
+
(bool, "boolean"),
|
|
207
|
+
):
|
|
208
|
+
if annotation is typ:
|
|
209
|
+
return name, nullable
|
|
210
|
+
if projection:
|
|
211
|
+
if annotation is bytes:
|
|
212
|
+
return "binary", nullable
|
|
213
|
+
if get_origin(annotation) is tuple and get_args(annotation) == (float, Ellipsis):
|
|
214
|
+
return "vector", nullable
|
|
215
|
+
raise ReadBuildError("unsupported reviewed-read carrier")
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def parameter_signature(annotation: object) -> dict[str, object]:
|
|
219
|
+
"""Original list facets are local read-parameter metadata, not scalar widening."""
|
|
220
|
+
from types import UnionType
|
|
221
|
+
from typing import Annotated, Union, get_args, get_origin
|
|
222
|
+
|
|
223
|
+
while get_origin(annotation) is Annotated:
|
|
224
|
+
annotation = get_args(annotation)[0]
|
|
225
|
+
if get_origin(annotation) in (Union, UnionType):
|
|
226
|
+
members = get_args(annotation)
|
|
227
|
+
if any(get_origin(member) is list for member in members):
|
|
228
|
+
raise ReadBuildError("WEFT_BLOCKED: WR-A4 list containers must be non-null")
|
|
229
|
+
if get_origin(annotation) is list:
|
|
230
|
+
members = get_args(annotation)
|
|
231
|
+
if len(members) != 1:
|
|
232
|
+
raise ReadBuildError("WEFT_BLOCKED: WR-A4 one exact list element carrier required")
|
|
233
|
+
carrier, nullable = _carrier(members[0])
|
|
234
|
+
return {"carrier": carrier, "nullable": False, "container": "list", "elementNullable": nullable, "maxItems": 1000}
|
|
235
|
+
carrier, nullable = _carrier(annotation)
|
|
236
|
+
return {"carrier": carrier, "nullable": nullable}
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def validate_list_parameters(parameters: object, values: Mapping[str, object]) -> None:
|
|
240
|
+
"""Validate every original list facet before dispatch, preserving all values."""
|
|
241
|
+
if type(parameters) is not list:
|
|
242
|
+
raise ReadBuildError("original parameter inventory required")
|
|
243
|
+
for descriptor in parameters:
|
|
244
|
+
if type(descriptor) is not dict or "container" not in descriptor:
|
|
245
|
+
continue
|
|
246
|
+
if set(descriptor) != {"name", "carrier", "nullable", "container", "elementNullable", "maxItems"} or descriptor["container"] != "list" or descriptor["nullable"] is not False or type(descriptor["elementNullable"]) is not bool or type(descriptor["maxItems"]) is not int or not 1 <= descriptor["maxItems"] <= 1000:
|
|
247
|
+
raise ReadBuildError("closed original list parameter facets required")
|
|
248
|
+
if type(descriptor["carrier"]) is not str or type(descriptor["name"]) is not str:
|
|
249
|
+
raise ReadBuildError("original list parameter identity/carrier differs")
|
|
250
|
+
annotation = {"string": str, "integer": int, "decimal": Decimal, "boolean": bool}.get(descriptor["carrier"])
|
|
251
|
+
value = values.get(descriptor["name"])
|
|
252
|
+
if annotation is None or type(value) is not list or len(value) > descriptor["maxItems"]:
|
|
253
|
+
raise ReadBuildError("original list parameter cardinality/carrier differs")
|
|
254
|
+
for item in value:
|
|
255
|
+
if item is None and descriptor["elementNullable"]:
|
|
256
|
+
continue
|
|
257
|
+
if type(item) is not annotation or isinstance(item, Decimal) and not item.is_finite() or isinstance(item, str) and ("\x00" in item or any(0xD800 <= ord(character) <= 0xDFFF for character in item)):
|
|
258
|
+
raise ReadBuildError("original list element carrier differs")
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def _compatible_outputs(actual: object, expected: list[dict[str, object]]) -> bool:
|
|
262
|
+
if not isinstance(actual, list) or len(actual) != len(expected):
|
|
263
|
+
return False
|
|
264
|
+
for a, e in zip(actual, expected, strict=True):
|
|
265
|
+
if e.get("carrier") == "related-keys":
|
|
266
|
+
if type(a) is not dict or a.get("nullable") is not False or a != e:
|
|
267
|
+
return False
|
|
268
|
+
continue
|
|
269
|
+
if (
|
|
270
|
+
not isinstance(a, dict)
|
|
271
|
+
or a.get("name") != e["name"]
|
|
272
|
+
or a.get("carrier") != e["carrier"]
|
|
273
|
+
or a.get("nullable")
|
|
274
|
+
and not e["nullable"]
|
|
275
|
+
):
|
|
276
|
+
return False
|
|
277
|
+
return True
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def _fields(model: type[BaseModel], *, projection: bool = False, parameter: bool = True, allow_related: bool = False) -> list[dict[str, object]]:
|
|
281
|
+
if (
|
|
282
|
+
model.model_config.get("extra") != "forbid"
|
|
283
|
+
or model.model_config.get("strict") is not True
|
|
284
|
+
):
|
|
285
|
+
raise ReadBuildError(
|
|
286
|
+
"reviewed read models must be strict and forbid extra fields"
|
|
287
|
+
)
|
|
288
|
+
result: list[dict[str, object]] = []
|
|
289
|
+
for name, field in model.model_fields.items():
|
|
290
|
+
if field.alias is not None:
|
|
291
|
+
raise ReadBuildError("reviewed read aliases are unsupported")
|
|
292
|
+
related = transport_spec(model) if projection or allow_related else None
|
|
293
|
+
if related is not None and name == related[0]:
|
|
294
|
+
result.append({"name": name, "carrier": "related-keys", "nullable": False, "decoder": related[2]})
|
|
295
|
+
else:
|
|
296
|
+
if projection:
|
|
297
|
+
carrier, nullable = _carrier(field.annotation, projection=True)
|
|
298
|
+
result.append({"name": name, "carrier": carrier, "nullable": nullable})
|
|
299
|
+
elif parameter:
|
|
300
|
+
result.append({"name": name, **parameter_signature(field.annotation)})
|
|
301
|
+
else:
|
|
302
|
+
carrier, nullable = _carrier(field.annotation)
|
|
303
|
+
result.append({"name": name, "carrier": carrier, "nullable": nullable})
|
|
304
|
+
return result
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
def _check_source(source: GeneratedSource, binding: Mapping[str, object]) -> None:
|
|
308
|
+
model = binding.get("modelJson")
|
|
309
|
+
if (type(model) is not str or hashlib.sha256(model.encode()).hexdigest() != source.document_sha256
|
|
310
|
+
or binding.get("modelSha256") != source.document_sha256
|
|
311
|
+
or source.runtime_abi != RUNTIME_ABI):
|
|
312
|
+
raise ReadBuildError("CATALOG_STALE: generated source differs from bound model/runtime")
|
|
313
|
+
document = _load(model)
|
|
314
|
+
if document.get("id") != source.document_id or document.get("umf") != source.core_version:
|
|
315
|
+
raise ReadBuildError("CATALOG_STALE: generated document identity differs")
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
def _model_sources(*models: type[BaseModel]) -> list[GeneratedSource]:
|
|
319
|
+
sources: list[GeneratedSource] = []
|
|
320
|
+
for model in models:
|
|
321
|
+
source = getattr(model, "UMF_SOURCE", None)
|
|
322
|
+
if source is not None:
|
|
323
|
+
if not isinstance(source, GeneratedSource):
|
|
324
|
+
raise ReadBuildError("CATALOG_STALE: malformed generated model source")
|
|
325
|
+
sources.append(source)
|
|
326
|
+
return sources
|
|
327
|
+
def _generation(*models: type[BaseModel]) -> dict[str, object] | None:
|
|
328
|
+
generations: list[dict[str, object]] = []
|
|
329
|
+
for model in models:
|
|
330
|
+
digest = getattr(model, "UMF_BUNDLE_INPUT_DIGEST", None)
|
|
331
|
+
abi = getattr(model, "UMF_RUNTIME_ABI", None)
|
|
332
|
+
if digest is None and abi is None:
|
|
333
|
+
continue # Explicit standalone reviewed models have no stage one.
|
|
334
|
+
if (
|
|
335
|
+
type(digest) is not str
|
|
336
|
+
or not re.fullmatch("[0-9a-f]{64}", digest)
|
|
337
|
+
or type(abi) is not tuple
|
|
338
|
+
or len(abi) != 3
|
|
339
|
+
or any(type(x) is not str or not x for x in abi)
|
|
340
|
+
):
|
|
341
|
+
raise ReadBuildError("CATALOG_STALE: invalid generated metadata")
|
|
342
|
+
if abi != RUNTIME_IDENTITY:
|
|
343
|
+
raise ReadBuildError("CATALOG_STALE: installed runtime differs")
|
|
344
|
+
generations.append({"inputDigest": digest, "runtimeAbi": list(abi)})
|
|
345
|
+
if generations and any(pin != generations[0] for pin in generations):
|
|
346
|
+
raise ReadBuildError("CATALOG_STALE: mixed generated model revisions")
|
|
347
|
+
return generations[0] if generations else None
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
@dataclass(frozen=True)
|
|
351
|
+
class ReviewedSQL(Generic[P, R]):
|
|
352
|
+
"""Fixed authored text, explicit generated parameter/result types, no execution."""
|
|
353
|
+
|
|
354
|
+
sql: str
|
|
355
|
+
parameters: type[P]
|
|
356
|
+
result: type[R]
|
|
357
|
+
row_cap: int = 1000
|
|
358
|
+
keyset: bool = False
|
|
359
|
+
|
|
360
|
+
def build(
|
|
361
|
+
self,
|
|
362
|
+
compiler: ReadCompiler,
|
|
363
|
+
*,
|
|
364
|
+
target: str,
|
|
365
|
+
binding: Mapping[str, object],
|
|
366
|
+
snapshots: Mapping[str, int] | None = None,
|
|
367
|
+
snapshot: bool = False,
|
|
368
|
+
stream_page_size: bool = False,
|
|
369
|
+
related_source: str | None = None,
|
|
370
|
+
related_relationship: Mapping[str, str] | None = None,
|
|
371
|
+
) -> CatalogRead[P, R]:
|
|
372
|
+
if type(self.row_cap) is not int or not 1 <= self.row_cap <= 1000:
|
|
373
|
+
raise ReadBuildError("row cap must be 1..1000")
|
|
374
|
+
request = {
|
|
375
|
+
"version": "weft.raw-read/0.1",
|
|
376
|
+
"target": target,
|
|
377
|
+
"sql": self.sql,
|
|
378
|
+
"binding": dict(binding),
|
|
379
|
+
"parameters": _fields(self.parameters),
|
|
380
|
+
"rowCap": self.row_cap,
|
|
381
|
+
"keyset": self.keyset,
|
|
382
|
+
}
|
|
383
|
+
if target in ("postgresql18", "lakebase18"):
|
|
384
|
+
request["verificationProfile"] = "source-exact/0.1"
|
|
385
|
+
if type(stream_page_size) is not bool or stream_page_size and not self.keyset:
|
|
386
|
+
raise ReadBuildError("stream page size requires a bounded keyset declaration")
|
|
387
|
+
if stream_page_size:
|
|
388
|
+
request["streamPageSize"] = True
|
|
389
|
+
if type(snapshot) is not bool:
|
|
390
|
+
raise ReadBuildError("snapshot must be boolean")
|
|
391
|
+
if snapshot:
|
|
392
|
+
if not self.keyset or target != "spark-delta4":
|
|
393
|
+
raise ReadBuildError("SNAPSHOT_UNSUPPORTED: snapshot pages require an admitted Delta target")
|
|
394
|
+
request["snapshot"] = True
|
|
395
|
+
if snapshots is not None:
|
|
396
|
+
request["snapshots"] = dict(snapshots)
|
|
397
|
+
related_request = None
|
|
398
|
+
if related_source is not None:
|
|
399
|
+
if related_relationship is None or set(related_relationship) != {"module", "id", "direction"}:
|
|
400
|
+
raise ReadBuildError("WR-A6 original relationship metadata required")
|
|
401
|
+
source_request = dict(request)
|
|
402
|
+
source_request.update(sql=related_source, keyset=False)
|
|
403
|
+
for target_only in ("streamPageSize", "snapshot"):
|
|
404
|
+
source_request.pop(target_only, None)
|
|
405
|
+
related_request = {
|
|
406
|
+
"version": "weft.related-read/0.1",
|
|
407
|
+
"source": source_request,
|
|
408
|
+
"target": request,
|
|
409
|
+
"relationship": dict(related_relationship),
|
|
410
|
+
}
|
|
411
|
+
method = getattr(compiler, "compile_related_read_json", None)
|
|
412
|
+
if not callable(method):
|
|
413
|
+
raise ReadBuildError("WEFT_BLOCKED: WR-A6 original related-read compiler required")
|
|
414
|
+
raw = method(_json(related_request))
|
|
415
|
+
else:
|
|
416
|
+
if related_relationship is not None:
|
|
417
|
+
raise ReadBuildError("WR-A6 original source query required")
|
|
418
|
+
raw = compiler.compile_raw_read_json(_json(request))
|
|
419
|
+
artifact = _load(raw)
|
|
420
|
+
if artifact.get("status") != "compiled":
|
|
421
|
+
raise ReadBuildError(
|
|
422
|
+
"Weft refused reviewed read: " + _json(artifact.get("diagnostics"))
|
|
423
|
+
)
|
|
424
|
+
if related_request is not None and artifact.get("relatedRequest") != related_request:
|
|
425
|
+
raise ReadBuildError("compiler related source/target custody differs from request")
|
|
426
|
+
if (
|
|
427
|
+
artifact.get("target") != target
|
|
428
|
+
or artifact.get("binding") != dict(binding)
|
|
429
|
+
or artifact.get("sourceSql") != self.sql
|
|
430
|
+
):
|
|
431
|
+
raise ReadBuildError("compiler response does not match request")
|
|
432
|
+
if (
|
|
433
|
+
not _compatible_outputs(artifact.get("outputs"), _fields(self.result, projection=True))
|
|
434
|
+
or artifact.get("parameters") != request["parameters"]
|
|
435
|
+
):
|
|
436
|
+
raise ReadBuildError(
|
|
437
|
+
"compiled parameter/result types differ from declaration"
|
|
438
|
+
)
|
|
439
|
+
_require_source_exact(artifact)
|
|
440
|
+
catalog_fence(artifact)
|
|
441
|
+
if not _compiler_transport(artifact):
|
|
442
|
+
artifact["dbapiSql"] = _dbapi(cast(str, artifact["sql"]))
|
|
443
|
+
artifact["dbapiParameterOrder"] = _dbapi_order(cast(str, artifact["sql"]), cast(list[str], artifact["parameterOrder"]))
|
|
444
|
+
sources = _model_sources(self.parameters, self.result)
|
|
445
|
+
source = sources[0] if sources else None
|
|
446
|
+
if source is not None:
|
|
447
|
+
if any(item != source for item in sources):
|
|
448
|
+
raise ReadBuildError("CATALOG_STALE: mixed generated models")
|
|
449
|
+
_check_source(source, binding)
|
|
450
|
+
artifact["generatedSource"] = asdict(source)
|
|
451
|
+
artifact["stageOne"] = _generation(self.parameters, self.result)
|
|
452
|
+
artifact["catalogDigest"] = hashlib.sha256(_json(artifact).encode()).hexdigest()
|
|
453
|
+
return CatalogRead(_json(artifact), self.parameters, self.result, source)
|
|
454
|
+
|
|
455
|
+
|
|
456
|
+
def catalog_fence(artifact: Mapping[str, object]) -> dict[str, object] | None:
|
|
457
|
+
"""Retain the original deployment and every selected configuration origin."""
|
|
458
|
+
def refuse() -> NoReturn:
|
|
459
|
+
raise ReadBuildError("NATIVE_TEXT_SEARCH_FENCE_REQUIRED")
|
|
460
|
+
fenced_version = artifact.get("version") in ("weft.raw-read/0.2", "weft.native-action/0.2", "weft.native-bulk/0.2", "weft.search/0.2")
|
|
461
|
+
if artifact.get("target") not in ("postgresql18", "lakebase18"):
|
|
462
|
+
if fenced_version:
|
|
463
|
+
refuse()
|
|
464
|
+
if any(isinstance(value, dict) and "nativeCatalogFence" in value for value in (artifact.get("binding"), artifact.get("obligations"))):
|
|
465
|
+
refuse()
|
|
466
|
+
return None
|
|
467
|
+
def name(value: object) -> bool:
|
|
468
|
+
if type(value) is not str or "\x00" in value:
|
|
469
|
+
return False
|
|
470
|
+
try:
|
|
471
|
+
return 1 <= len(value.encode("utf-8")) <= 63
|
|
472
|
+
except UnicodeEncodeError:
|
|
473
|
+
return False
|
|
474
|
+
obligations = artifact.get("obligations")
|
|
475
|
+
if not isinstance(obligations, dict):
|
|
476
|
+
refuse()
|
|
477
|
+
expected = set()
|
|
478
|
+
for member, entries_name in (("termFilter", "indexes"), ("keywordConfiguration", "configurations"), ("textSearchEffects", "indexes")):
|
|
479
|
+
selected = obligations.get(member)
|
|
480
|
+
if selected is None:
|
|
481
|
+
continue
|
|
482
|
+
if member == "textSearchEffects" and (not isinstance(selected, dict) or selected.get("version") != "umf.pg-ts-effects/0.1" or selected.get("nativeCatalogBeforeAfter") is not True):
|
|
483
|
+
refuse()
|
|
484
|
+
entries = selected.get(entries_name) if isinstance(selected, dict) else None
|
|
485
|
+
if not isinstance(entries, list) or not entries:
|
|
486
|
+
refuse()
|
|
487
|
+
for entry in entries:
|
|
488
|
+
if member == "textSearchEffects" and (not isinstance(entry, dict)
|
|
489
|
+
or set(entry) != {"source", "index", "nativeBinding", "logicalTable", "nativeTable", "nativeColumns", "configuration", "nativeAdmission"}
|
|
490
|
+
or not isinstance(entry.get("nativeColumns"), list) or not entry["nativeColumns"]
|
|
491
|
+
or any(type(column) is not str or not column for column in entry["nativeColumns"])):
|
|
492
|
+
refuse()
|
|
493
|
+
if not isinstance(entry, dict) or entry.get("configuration") not in ("pg_catalog.english", "pg_catalog.simple") or not isinstance(entry.get("source"), dict) or not isinstance(entry.get("index"), dict):
|
|
494
|
+
refuse()
|
|
495
|
+
expected.add(json.dumps({key: entry[key] for key in ("source", "index", "configuration")}, sort_keys=True, separators=(",", ":"), ensure_ascii=False))
|
|
496
|
+
packet = obligations.get("nativeCatalogFence")
|
|
497
|
+
if not expected and packet is None and (not fenced_version or artifact.get("version") in ("weft.native-action/0.2", "weft.native-bulk/0.2")):
|
|
498
|
+
return None
|
|
499
|
+
if not fenced_version:
|
|
500
|
+
refuse()
|
|
501
|
+
if not isinstance(packet, dict) or set(packet) != {"version", "deployment", "origins", "lockSql", "lockPosition", "nativeCatalogBeforeAfter", "nativeAdmission", "deploymentProgram"}:
|
|
502
|
+
refuse()
|
|
503
|
+
binding = artifact.get("binding")
|
|
504
|
+
deployment = packet.get("deployment")
|
|
505
|
+
if (not isinstance(binding, dict) or not isinstance(deployment, dict)
|
|
506
|
+
or set(deployment) != {"version", "schema", "view", "owner", "ownerProfile"}
|
|
507
|
+
or deployment.get("version") != "umf.pg-ts-fence/0.1"
|
|
508
|
+
or deployment.get("ownerProfile") != "non-login-maintainer/0.1"
|
|
509
|
+
or any(not name(deployment.get(key)) for key in ("schema", "view", "owner"))
|
|
510
|
+
or binding.get("nativeCatalogFence") != deployment
|
|
511
|
+
or packet.get("version") != "umf.pg-ts-fence/0.1"
|
|
512
|
+
or packet.get("lockPosition") != "before-first-snapshot"
|
|
513
|
+
or packet.get("nativeCatalogBeforeAfter") is not True
|
|
514
|
+
or type(packet.get("lockSql")) is not str or not packet["lockSql"]
|
|
515
|
+
or not isinstance(packet.get("origins"), list)):
|
|
516
|
+
refuse()
|
|
517
|
+
actual = set()
|
|
518
|
+
for origin in packet["origins"]:
|
|
519
|
+
if not isinstance(origin, dict) or set(origin) != {"source", "index", "configuration"}:
|
|
520
|
+
refuse()
|
|
521
|
+
key = json.dumps(origin, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
|
|
522
|
+
if key in actual:
|
|
523
|
+
refuse()
|
|
524
|
+
actual.add(key)
|
|
525
|
+
if not expected or actual != expected:
|
|
526
|
+
refuse()
|
|
527
|
+
admission = packet.get("nativeAdmission")
|
|
528
|
+
if not isinstance(admission, dict) or set(admission) != {"sql", "dbapiSql", "parameters", "dbapiParameterOrder"} or not isinstance(admission.get("parameters"), list):
|
|
529
|
+
refuse()
|
|
530
|
+
for parameter in admission["parameters"]:
|
|
531
|
+
source = parameter.get("source") if isinstance(parameter, dict) else None
|
|
532
|
+
if not isinstance(source, dict) or set(source) != {"literal"}:
|
|
533
|
+
refuse()
|
|
534
|
+
# Retain this original owner deployment program as inert source metadata.
|
|
535
|
+
# Runtime never executes CREATE VIEW/ALTER OWNER or grants privileges.
|
|
536
|
+
program = packet.get("deploymentProgram")
|
|
537
|
+
if (not isinstance(program, dict)
|
|
538
|
+
or set(program) != {"version", "createViewSql", "alterOwnerSql", "ownerPrerequisites", "readerPrerequisites"}
|
|
539
|
+
or program.get("version") != "weft.pg-ts-fence-deployment/0.1"
|
|
540
|
+
or any(type(program.get(key)) is not str or not program[key] for key in ("createViewSql", "alterOwnerSql"))
|
|
541
|
+
or not isinstance(program.get("ownerPrerequisites"), dict)
|
|
542
|
+
or not isinstance(program.get("readerPrerequisites"), dict)):
|
|
543
|
+
refuse()
|
|
544
|
+
owner_prerequisites = program["ownerPrerequisites"]
|
|
545
|
+
reader_prerequisites = program["readerPrerequisites"]
|
|
546
|
+
if (any(owner_prerequisites.get(key) is not False for key in ("superuser", "bypassRls", "login", "createRole", "createDb", "replication"))
|
|
547
|
+
or owner_prerequisites.get("schemaOwner") is not True
|
|
548
|
+
or reader_prerequisites.get("schemaUsage") is not True
|
|
549
|
+
or reader_prerequisites.get("viewMaintain") is not True
|
|
550
|
+
or reader_prerequisites.get("ownerMembership") is not False):
|
|
551
|
+
refuse()
|
|
552
|
+
if owner_prerequisites != {
|
|
553
|
+
"role": deployment["owner"], "superuser": False, "bypassRls": False,
|
|
554
|
+
"login": False, "createRole": False, "createDb": False, "replication": False,
|
|
555
|
+
"schemaOwner": True, "catalogMaintain": ["pg_catalog.pg_namespace", "pg_catalog.pg_proc", "pg_catalog.pg_ts_config", "pg_catalog.pg_ts_config_map", "pg_catalog.pg_ts_dict", "pg_catalog.pg_ts_parser", "pg_catalog.pg_ts_template"],
|
|
556
|
+
} or reader_prerequisites != {"schemaUsage": True, "viewMaintain": True, "ownerMembership": False}:
|
|
557
|
+
refuse()
|
|
558
|
+
return packet
|
|
559
|
+
|
|
560
|
+
|
|
561
|
+
def _require_source_exact(artifact: Mapping[str, object]) -> None:
|
|
562
|
+
"""Require original-owner native schema proof before promoting PG reads."""
|
|
563
|
+
if artifact.get("target") not in ("postgresql18", "lakebase18"):
|
|
564
|
+
return
|
|
565
|
+
obligations = artifact.get("obligations")
|
|
566
|
+
projection = obligations.get("nativeProjection") if isinstance(obligations, dict) else None
|
|
567
|
+
if (
|
|
568
|
+
not isinstance(projection, dict)
|
|
569
|
+
or projection.get("version") != "umf.native-columns/0.1"
|
|
570
|
+
or projection.get("verificationProfile") != "source-exact/0.1"
|
|
571
|
+
or projection.get("nativeCatalogBeforeAfter") is not True
|
|
572
|
+
or not isinstance(projection.get("columns"), list)
|
|
573
|
+
or not 1 <= len(projection["columns"]) <= 2000
|
|
574
|
+
):
|
|
575
|
+
raise ReadBuildError("NATIVE_SCHEMA_SOURCE_EXACT_REQUIRED")
|
|
576
|
+
|
|
577
|
+
|
|
578
|
+
@dataclass(frozen=True)
|
|
579
|
+
class CatalogRead(Generic[P, R]):
|
|
580
|
+
"""Serialized checked-in artifact plus exact model types. No SQL builder."""
|
|
581
|
+
|
|
582
|
+
artifact_json: str
|
|
583
|
+
parameters: type[P]
|
|
584
|
+
result: type[R]
|
|
585
|
+
expected_source: GeneratedSource | None = None
|
|
586
|
+
context_json: str = "{}"
|
|
587
|
+
|
|
588
|
+
def artifact(self) -> dict[str, object]:
|
|
589
|
+
_load(self.context_json)
|
|
590
|
+
artifact = _load(self.artifact_json)
|
|
591
|
+
digest = artifact.pop("catalogDigest", None)
|
|
592
|
+
if digest != hashlib.sha256(_json(artifact).encode()).hexdigest():
|
|
593
|
+
raise ReadBuildError("catalog digest mismatch")
|
|
594
|
+
if artifact.get("stageOne") != _generation(self.parameters, self.result):
|
|
595
|
+
raise ReadBuildError("CATALOG_STALE: loaded generation differs")
|
|
596
|
+
if (
|
|
597
|
+
artifact.get("version") not in ("weft.raw-read/0.1", "weft.raw-read/0.2")
|
|
598
|
+
or artifact.get("status") != "compiled"
|
|
599
|
+
or artifact.get("target")
|
|
600
|
+
not in ("postgresql18", "lakebase18", "spark-delta4")
|
|
601
|
+
):
|
|
602
|
+
raise ReadBuildError("unsupported catalog artifact")
|
|
603
|
+
if not _compatible_outputs(
|
|
604
|
+
artifact.get("outputs"), _fields(self.result, projection=True)
|
|
605
|
+
) or artifact.get("parameters") != _fields(self.parameters):
|
|
606
|
+
raise ReadBuildError("catalog model signatures changed")
|
|
607
|
+
raw_source = artifact.get("generatedSource")
|
|
608
|
+
model_sources = _model_sources(self.parameters, self.result)
|
|
609
|
+
if raw_source is not None:
|
|
610
|
+
if not isinstance(raw_source, dict):
|
|
611
|
+
raise ReadBuildError("CATALOG_STALE: malformed generated source")
|
|
612
|
+
try:
|
|
613
|
+
source = GeneratedSource(**raw_source)
|
|
614
|
+
except (TypeError, ValueError):
|
|
615
|
+
raise ReadBuildError("CATALOG_STALE: malformed generated source") from None
|
|
616
|
+
expected = self.expected_source or (model_sources[0] if model_sources else None)
|
|
617
|
+
if expected != source or any(item != source for item in model_sources):
|
|
618
|
+
raise ReadBuildError("CATALOG_STALE: catalog and loaded generation differ")
|
|
619
|
+
_check_source(source, cast(Mapping[str, object], artifact["binding"]))
|
|
620
|
+
elif self.expected_source is not None or model_sources:
|
|
621
|
+
raise ReadBuildError("CATALOG_STALE: catalog lacks generated model provenance")
|
|
622
|
+
if not _compiler_transport(artifact, catalog=True):
|
|
623
|
+
if artifact.get("dbapiSql") != _dbapi(cast(str, artifact.get("sql"))):
|
|
624
|
+
raise ReadBuildError("catalog parameter style mismatch")
|
|
625
|
+
if artifact.get("dbapiParameterOrder") != _dbapi_order(
|
|
626
|
+
cast(str, artifact["sql"]), cast(list[str], artifact["parameterOrder"])
|
|
627
|
+
):
|
|
628
|
+
raise ReadBuildError("catalog parameter order mismatch")
|
|
629
|
+
_require_source_exact(artifact)
|
|
630
|
+
catalog_fence(artifact)
|
|
631
|
+
return artifact
|
|
632
|
+
|
|
633
|
+
|
|
634
|
+
def captured_source(variant: object, *, binding: Mapping[str, object]) -> GeneratedSource:
|
|
635
|
+
"""Validate every captured reference against its exact target model bytes."""
|
|
636
|
+
from .capture import CapturedVariant
|
|
637
|
+
if not isinstance(variant, CapturedVariant):
|
|
638
|
+
raise ReadBuildError("captured query variant required")
|
|
639
|
+
root = cast(RecordRef, variant.node.args[0])
|
|
640
|
+
source = root.source
|
|
641
|
+
if source is None:
|
|
642
|
+
raise ReadBuildError("CATALOG_STALE: query lacks generated source")
|
|
643
|
+
_check_source(source, binding)
|
|
644
|
+
def check_references(value: object) -> None:
|
|
645
|
+
if isinstance(value, RecordRef) and value.key_id is None:
|
|
646
|
+
raise ReadBuildError("CATALOG_STALE: query lacks selected Key identity")
|
|
647
|
+
if isinstance(value, (RecordRef, FieldRef, KeyLiteral)) and value.source != source:
|
|
648
|
+
raise ReadBuildError("CATALOG_STALE: mixed query generations")
|
|
649
|
+
if is_dataclass(value) and not isinstance(value, type):
|
|
650
|
+
for field in fields(value):
|
|
651
|
+
check_references(getattr(value, field.name))
|
|
652
|
+
elif isinstance(value, tuple):
|
|
653
|
+
for item in value:
|
|
654
|
+
check_references(item)
|
|
655
|
+
check_references(variant.node)
|
|
656
|
+
if any(parameter.key_components and parameter.key_source != source for parameter in variant.parameters):
|
|
657
|
+
raise ReadBuildError("CATALOG_STALE: query and Key parameter generations differ")
|
|
658
|
+
keyset = variant.node.op == "page"
|
|
659
|
+
cursor_name = None
|
|
660
|
+
if keyset:
|
|
661
|
+
record = cast(RecordRef, variant.node.args[0])
|
|
662
|
+
cursor = cast(Node, variant.node.args[3])
|
|
663
|
+
cursor_name = str(cursor.args[0])
|
|
664
|
+
parameter = next(p for p in variant.parameters if p.name == cursor_name)
|
|
665
|
+
identity = dict(parameter.key_identity)
|
|
666
|
+
if identity != {"documentId": source.document_id, "coreVersion": source.core_version, "module": record.module, "element": record.element, "key": record.key_id}:
|
|
667
|
+
raise ReadBuildError("page cursor Key differs from root Record")
|
|
668
|
+
return source
|
|
669
|
+
|
|
670
|
+
|
|
671
|
+
def build_query(declaration: object, compiler: ReadCompiler, *, parameters: type[P], result: type[R], target: str, binding: Mapping[str, object], row_cap: int = 1000) -> CatalogRead[P, R]:
|
|
672
|
+
"""Capture one closed DSL read and compile it through the same Weft entrypoint."""
|
|
673
|
+
from .capture import CapturedDeclaration
|
|
674
|
+
from .dsl import render_logical, render_related_logical
|
|
675
|
+
|
|
676
|
+
if (
|
|
677
|
+
not isinstance(declaration, CapturedDeclaration)
|
|
678
|
+
or declaration.kind != "query"
|
|
679
|
+
or len(declaration.variants) != 1
|
|
680
|
+
):
|
|
681
|
+
raise ReadBuildError("one captured query variant required")
|
|
682
|
+
variant = declaration.variants[0]
|
|
683
|
+
if variant.node.op == "update":
|
|
684
|
+
raise ReadBuildError("read catalogs cannot contain mutations")
|
|
685
|
+
source = captured_source(variant, binding=binding)
|
|
686
|
+
if any(item != source for item in _model_sources(parameters, result)):
|
|
687
|
+
raise ReadBuildError("CATALOG_STALE: query and generated models differ")
|
|
688
|
+
keyset = variant.node.op == "page"
|
|
689
|
+
cursor_name = str(cast(Node, variant.node.args[3]).args[0]) if keyset else None
|
|
690
|
+
declared = [{"name": p.name, **parameter_signature(p.carrier)} for p in variant.parameters if p.name != cursor_name]
|
|
691
|
+
expected = _fields(parameters)
|
|
692
|
+
if declared != expected:
|
|
693
|
+
raise ReadBuildError("captured signature differs from parameter model")
|
|
694
|
+
snapshot = any(step.op == "snapshot" for step in cast(tuple[Node, ...], variant.node.args[1]))
|
|
695
|
+
related = render_related_logical(variant, binding=binding)
|
|
696
|
+
logical = related.target_sql if related is not None else render_logical(variant, binding=binding)
|
|
697
|
+
compiled = ReviewedSQL(logical, parameters, result, row_cap, keyset=keyset).build(
|
|
698
|
+
compiler, target=target, binding=binding, snapshot=snapshot,
|
|
699
|
+
related_source=related.source_sql if related is not None else None,
|
|
700
|
+
related_relationship=related.relationship if related is not None else None,
|
|
701
|
+
)
|
|
702
|
+
artifact = compiled.artifact()
|
|
703
|
+
artifact.pop("catalogDigest", None) # artifact() already excludes this local digest.
|
|
704
|
+
artifact["generatedSource"] = asdict(source)
|
|
705
|
+
artifact["catalogDigest"] = hashlib.sha256(_json(artifact).encode()).hexdigest()
|
|
706
|
+
return CatalogRead(_json(artifact), parameters, result, source)
|