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.
Files changed (117) hide show
  1. umf_access/__init__.py +109 -0
  2. umf_access/adoption.py +41 -0
  3. umf_access/build/__init__.py +2 -0
  4. umf_access/build/approximate.py +34 -0
  5. umf_access/build/catalog.py +1626 -0
  6. umf_access/build/commands.py +394 -0
  7. umf_access/build/pg_privileges.py +1544 -0
  8. umf_access/build/privileges.py +134 -0
  9. umf_access/build/search.py +365 -0
  10. umf_access/build/unity_search.py +104 -0
  11. umf_access/bulk.py +227 -0
  12. umf_access/canonical.py +23 -0
  13. umf_access/capture.py +410 -0
  14. umf_access/catalog.py +325 -0
  15. umf_access/codec_support.py +427 -0
  16. umf_access/commands.py +93 -0
  17. umf_access/delta_read.py +758 -0
  18. umf_access/dsl/__init__.py +148 -0
  19. umf_access/dsl/_context.py +36 -0
  20. umf_access/dsl/_expressions.py +625 -0
  21. umf_access/dsl/_joined.py +4 -0
  22. umf_access/dsl/_nodes.py +207 -0
  23. umf_access/dsl/_query.py +5559 -0
  24. umf_access/dsl/_selection.py +143 -0
  25. umf_access/dsl/navigation.py +302 -0
  26. umf_access/dsl/render.py +516 -0
  27. umf_access/dsl/search.py +343 -0
  28. umf_access/engine_catalog.py +563 -0
  29. umf_access/generated_core.py +5 -0
  30. umf_access/lifecycle/__init__.py +46 -0
  31. umf_access/lifecycle/_darwin_process_observer.c +306 -0
  32. umf_access/lifecycle/approval.py +366 -0
  33. umf_access/lifecycle/backfills.py +79 -0
  34. umf_access/lifecycle/catalog.py +289 -0
  35. umf_access/lifecycle/cli.py +231 -0
  36. umf_access/lifecycle/concurrent.py +196 -0
  37. umf_access/lifecycle/conversion_policy.py +188 -0
  38. umf_access/lifecycle/correspondence.py +203 -0
  39. umf_access/lifecycle/generation_authority_bootstrap.py +1491 -0
  40. umf_access/lifecycle/generation_authority_session.py +125 -0
  41. umf_access/lifecycle/generation_enrollment_authority.py +1108 -0
  42. umf_access/lifecycle/generation_enrollment_ledger.py +698 -0
  43. umf_access/lifecycle/generation_ingress.py +185 -0
  44. umf_access/lifecycle/generation_root_registry.py +138 -0
  45. umf_access/lifecycle/head.py +250 -0
  46. umf_access/lifecycle/head_view.py +81 -0
  47. umf_access/lifecycle/host.py +1183 -0
  48. umf_access/lifecycle/ingress_custody.py +750 -0
  49. umf_access/lifecycle/ingress_local_postgres.py +7990 -0
  50. umf_access/lifecycle/ingress_store.py +1488 -0
  51. umf_access/lifecycle/ledger.py +276 -0
  52. umf_access/lifecycle/ledger_schema.py +116 -0
  53. umf_access/lifecycle/mixed.py +593 -0
  54. umf_access/lifecycle/outcome_schema.py +136 -0
  55. umf_access/lifecycle/owner_approval_core.py +1810 -0
  56. umf_access/lifecycle/owner_authority.py +472 -0
  57. umf_access/lifecycle/owner_bootstrap.py +2077 -0
  58. umf_access/lifecycle/owner_wire.py +161 -0
  59. umf_access/lifecycle/phase_fence.py +52 -0
  60. umf_access/lifecycle/phase_policy.py +422 -0
  61. umf_access/lifecycle/privileges.py +145 -0
  62. umf_access/lifecycle/probe.py +39 -0
  63. umf_access/lifecycle/progress.py +497 -0
  64. umf_access/lifecycle/roles.py +96 -0
  65. umf_access/lifecycle/row_originals.py +1712 -0
  66. umf_access/lifecycle/row_originals_creation.py +759 -0
  67. umf_access/lifecycle/row_originals_receipt.py +413 -0
  68. umf_access/lifecycle/seeds.py +99 -0
  69. umf_access/lifecycle/sql_containment.py +358 -0
  70. umf_access/lifecycle/sql_containment_cli.py +33 -0
  71. umf_access/lifecycle/sql_containment_parser.py +20 -0
  72. umf_access/lifecycle/supervisor_journal_codec.py +1251 -0
  73. umf_access/lifecycle/table_boundary.py +22 -0
  74. umf_access/lifecycle/target_custody_codec.py +788 -0
  75. umf_access/lifecycle/witness.py +72 -0
  76. umf_access/managed_actions.py +271 -0
  77. umf_access/managed_bulk.py +353 -0
  78. umf_access/managed_delta.py +150 -0
  79. umf_access/managed_support.py +166 -0
  80. umf_access/manifest_commands.py +278 -0
  81. umf_access/native_actions.py +1007 -0
  82. umf_access/native_program.py +570 -0
  83. umf_access/pages.py +125 -0
  84. umf_access/postgres_bulk.py +509 -0
  85. umf_access/postgres_read.py +1230 -0
  86. umf_access/postgres_search.py +639 -0
  87. umf_access/protocols.py +665 -0
  88. umf_access/py.typed +0 -0
  89. umf_access/related_keys.py +233 -0
  90. umf_access/reviewed.py +706 -0
  91. umf_access/search_catalog.py +122 -0
  92. umf_access/targets.py +312 -0
  93. umf_access/types.py +220 -0
  94. umf_access/unified/__init__.py +187 -0
  95. umf_access/unified/_binding.py +654 -0
  96. umf_access/unified/head_session.py +144 -0
  97. umf_access/unified/native_binding.py +143 -0
  98. umf_access/unified/operation_values.py +173 -0
  99. umf_access/unified/outcome_values.py +76 -0
  100. umf_access/unified/session_async.py +161 -0
  101. umf_access/unified/session_binding.py +108 -0
  102. umf_access/unified/session_policy.py +152 -0
  103. umf_access/unified/session_psycopg2.py +70 -0
  104. umf_access/unified/session_sqlalchemy.py +161 -0
  105. umf_access/unified/session_sync.py +148 -0
  106. umf_access/unified/table_reads.py +314 -0
  107. umf_access/unified/table_writes.py +193 -0
  108. umf_access/unity_search.py +312 -0
  109. umf_access/values.py +280 -0
  110. umf_access/verification.py +64 -0
  111. umf_access-0.1.0.dev8.dist-info/METADATA +15 -0
  112. umf_access-0.1.0.dev8.dist-info/RECORD +117 -0
  113. umf_access-0.1.0.dev8.dist-info/WHEEL +4 -0
  114. umf_access-0.1.0.dev8.dist-info/entry_points.txt +4 -0
  115. umf_access-0.1.0.dev8.dist-info/licenses/LICENSE-APACHE +201 -0
  116. umf_access-0.1.0.dev8.dist-info/licenses/LICENSE-MIT +21 -0
  117. umf_access-0.1.0.dev8.dist-info/licenses/LICENSE.md +239 -0
@@ -0,0 +1,516 @@
1
+ # SPDX-License-Identifier: MIT OR Apache-2.0
2
+ """Canonical *logical Weft* text at build time; never native SQL lowering.
3
+
4
+ Weft owns backend acceptance and execution artifacts. Page continuation stays in
5
+ captured metadata, outside this grammar (S7). Logical existence uses WR-A7's
6
+ LIMIT 1 probe, whose terminal kind is retained for catalog result decoding.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from collections.abc import Mapping
12
+ from contextvars import ContextVar
13
+ from dataclasses import dataclass
14
+ from decimal import Decimal, InvalidOperation
15
+ from types import MappingProxyType
16
+ from typing import Protocol, cast
17
+
18
+ from ._context import CaptureError
19
+ from ._expressions import Join, Ordering, Related
20
+ from ._nodes import FieldRef, KeyLiteral, Node, ProjectionRef, RecordRef, owner_identity
21
+
22
+ _ALIASES: ContextVar[Mapping[tuple[str, str, str | None], str]] = ContextVar(
23
+ "join_aliases", default=MappingProxyType({})
24
+ )
25
+
26
+
27
+ class LogicalVariant(Protocol):
28
+ @property
29
+ def node(self) -> Node: ...
30
+
31
+
32
+ def _quote(identifier: str) -> str:
33
+ if (
34
+ not identifier
35
+ or "\x00" in identifier
36
+ or any(0xD800 <= ord(c) <= 0xDFFF for c in identifier)
37
+ ):
38
+ raise CaptureError(
39
+ "CAPTURE_UNSUPPORTED", "logical identifier is outside Weft text profile"
40
+ )
41
+ return '"' + identifier.replace('"', '""') + '"'
42
+
43
+
44
+ def _marker(name: str) -> str:
45
+ if not name.isascii() or not name.isidentifier():
46
+ raise CaptureError(
47
+ "CAPTURE_SIGNATURE", "parameter is outside Weft marker grammar"
48
+ )
49
+ return ":" + name
50
+
51
+
52
+ def _column(field: FieldRef, mutation: bool = False) -> str:
53
+ if not field.logical_name:
54
+ raise CaptureError("CAPTURE_UNSUPPORTED", "Field has no authored logical name")
55
+ if mutation:
56
+ return _quote(field.logical_name)
57
+ alias = _ALIASES.get().get(owner_identity(field))
58
+ if alias is None:
59
+ raise CaptureError(
60
+ "CAPTURE_UNSUPPORTED", "column owner absent from joined query"
61
+ )
62
+ return _quote(alias) + "." + _quote(field.logical_name)
63
+
64
+
65
+ def _scalar_sql(value: FieldRef | Node) -> str:
66
+ if isinstance(value, FieldRef):
67
+ return _column(value)
68
+ if value.op == "aggregate" and len(value.args) == 3:
69
+ op, field, scale = value.args
70
+ if op == "count" and field is None:
71
+ return "COUNT(*)"
72
+ if not isinstance(field, FieldRef):
73
+ raise CaptureError("CAPTURE_UNSUPPORTED", "aggregate field metadata is absent")
74
+ column = _column(field)
75
+ if op == "avg" and type(scale) is int and 0 <= scale <= 1000:
76
+ return f"AVG_SCALE({column}, {scale})"
77
+ if op == "count_distinct":
78
+ return f"COUNT(DISTINCT {column})"
79
+ if op == "approx_count_distinct":
80
+ return f"APPROX_COUNT_DISTINCT({column})"
81
+ if op in ("sum", "min", "max") and scale is None:
82
+ return f"{str(op).upper()}({column})"
83
+ raise CaptureError("CAPTURE_UNSUPPORTED", "unknown exact aggregate")
84
+ if value.op == "bucket_width" and len(value.args) == 2:
85
+ field, width = value.args
86
+ if not isinstance(field, FieldRef) or type(width) not in (int, Decimal):
87
+ raise CaptureError("CAPTURE_UNSUPPORTED", "bucket requires a numeric literal")
88
+ if isinstance(width, Decimal):
89
+ exponent = width.as_tuple().exponent
90
+ if not width.is_finite() or type(exponent) is not int or abs(exponent) > 10000 or len(width.as_tuple().digits) > 10000:
91
+ raise CaptureError("CAPTURE_UNSUPPORTED", "bucket literal exceeds token profile")
92
+ token = format(width, "f")
93
+ if "." not in token:
94
+ token += ".0"
95
+ elif isinstance(width, int):
96
+ token = _value(Node("int", (width,)))
97
+ else:
98
+ raise CaptureError("CAPTURE_UNSUPPORTED", "bucket requires a numeric literal")
99
+ if width <= 0:
100
+ raise CaptureError("CAPTURE_UNSUPPORTED", "bucket width must be positive")
101
+ return f"BUCKET_WIDTH({_column(field)}, {token})"
102
+ raise CaptureError("CAPTURE_UNSUPPORTED", "unsupported scalar selection")
103
+
104
+
105
+ def _value(node: Node, mutation: bool = False) -> str:
106
+ if node.op in ("aggregate", "bucket_width"):
107
+ return _scalar_sql(node)
108
+ if node.op == "param":
109
+ return _marker(cast(str, node.args[0]))
110
+ if node.op == "column":
111
+ return _column(cast(FieldRef, node.args[0]), mutation)
112
+ if node.op == "null":
113
+ return "NULL"
114
+ if node.op == "str":
115
+ value = cast(str, node.args[0])
116
+ if "\x00" in value:
117
+ raise CaptureError(
118
+ "CAPTURE_UNSUPPORTED", "literal outside Weft text profile"
119
+ )
120
+ return "'" + value.replace("'", "''") + "'"
121
+ if node.op == "bool":
122
+ return "TRUE" if node.args[0] else "FALSE"
123
+ if node.op == "int":
124
+ integer_value = node.args[0]
125
+ if type(integer_value) is not int or integer_value.bit_length() > 33220:
126
+ raise CaptureError("CAPTURE_UNSUPPORTED", "Integer literal exceeds exact token profile")
127
+ token = format(Decimal(integer_value), "f")
128
+ if len(token.removeprefix("-")) > 10000:
129
+ raise CaptureError("CAPTURE_UNSUPPORTED", "Integer literal exceeds exact token profile")
130
+ return token
131
+ if node.op == "decimal":
132
+ if len(node.args) != 1 or type(node.args[0]) is not str:
133
+ raise CaptureError("CAPTURE_UNSUPPORTED", "closed Decimal literal required")
134
+ try:
135
+ decimal_value = Decimal(cast(str, node.args[0]))
136
+ except InvalidOperation:
137
+ raise CaptureError("CAPTURE_UNSUPPORTED", "finite Decimal literal required") from None
138
+ exponent = decimal_value.as_tuple().exponent
139
+ if not decimal_value.is_finite() or type(exponent) is not int or abs(exponent) > 10000 or len(decimal_value.as_tuple().digits) > 10000:
140
+ raise CaptureError("CAPTURE_UNSUPPORTED", "Decimal literal exceeds exact token profile")
141
+ token = format(decimal_value, "f")
142
+ return token if "." in token else token + ".0"
143
+ # Temporal/binary literal spelling is not specified by WR-A8. Keep typed
144
+ # named parameters, rather than substituting text with weaker meaning.
145
+ raise CaptureError(
146
+ "CAPTURE_UNSUPPORTED", "literal requires typed parameter or newer Weft grammar"
147
+ )
148
+
149
+
150
+ def _key_values(node: Node, mutation: bool = False) -> tuple[str, ...]:
151
+ if node.op == "key_param":
152
+ name = cast(str, node.args[0])
153
+ components = cast(tuple[str, ...], node.args[1])
154
+ return tuple(_marker(f"{name}__{component}") for component in components)
155
+ if node.op == "key":
156
+ return tuple(
157
+ _value(value, mutation) for value in cast(KeyLiteral, node.args[0]).values
158
+ )
159
+ return (_value(node, mutation),)
160
+
161
+
162
+ def _predicate(node: Node, mutation: bool = False) -> str | None:
163
+ if node.op == "omitted":
164
+ return None
165
+ if node.op in ("and", "or"):
166
+ parts = [_predicate(cast(Node, child), mutation) for child in node.args]
167
+ present = [part for part in parts if part is not None]
168
+ if not present:
169
+ return None
170
+ return (
171
+ present[0]
172
+ if len(present) == 1
173
+ else "(" + f" {node.op.upper()} ".join(present) + ")"
174
+ )
175
+ if node.op == "not":
176
+ predicate = _predicate(cast(Node, node.args[0]), mutation)
177
+ return None if predicate is None else "NOT (" + predicate + ")"
178
+ if node.op in ("=", "<>", "<", "<=", ">", ">=", "IS DISTINCT FROM", "IS NOT DISTINCT FROM"):
179
+ left, right = (cast(Node, v) for v in node.args)
180
+ return f"{_value(left, mutation)} {node.op} {_value(right, mutation)}"
181
+ if node.op in ("IS NULL", "IS NOT NULL", "IS MISSING", "IS NOT MISSING"):
182
+ return f"{_value(cast(Node, node.args[0]), mutation)} {node.op}"
183
+ if node.op in ("IN", "NOT IN"):
184
+ left, right = (cast(Node, v) for v in node.args)
185
+ if right.op == "list":
186
+ if not right.args:
187
+ predicate = f"IN_EMPTY({_value(left, mutation)})"
188
+ return predicate if node.op == "IN" else "NOT (" + predicate + ")"
189
+ values = ", ".join(_value(cast(Node, v), mutation) for v in right.args)
190
+ else:
191
+ values = _value(right, mutation)
192
+ return f"{_value(left, mutation)} {node.op} ({values})"
193
+ if node.op == "BETWEEN":
194
+ left, lo, hi = (cast(Node, v) for v in node.args)
195
+ return f"{_value(left, mutation)} BETWEEN {_value(lo, mutation)} AND {_value(hi, mutation)}"
196
+ if node.op in ("STARTS_WITH", "MATCHES_ALL_TERMS", "MATCHES_ANY_TERM"):
197
+ left, right = (cast(Node, value) for value in node.args)
198
+ return f"{node.op}({_value(left, mutation)}, {_value(right, mutation)})"
199
+ if node.op in ("HAS_RELATED", "HAS_INVERSE_RELATED"):
200
+ left, key = (cast(Node, v) for v in node.args[:2])
201
+ extra = ""
202
+ if node.op == "HAS_INVERSE_RELATED":
203
+ module, identifier = node.args[2:]
204
+ if not isinstance(module, str) or not isinstance(identifier, str):
205
+ raise CaptureError("CAPTURE_SIGNATURE", "original inverse relationship identity required")
206
+ extra = ", " + _value(Node("str", (module,))) + ", " + _value(Node("str", (identifier,)))
207
+ return f"{node.op}({_value(left, mutation)}, KEY({', '.join(_key_values(key, mutation))}){extra})"
208
+ raise CaptureError("CAPTURE_UNSUPPORTED", "unsupported logical predicate")
209
+
210
+
211
+ def _render_logical(
212
+ variant: LogicalVariant,
213
+ binding: Mapping[str, object] | None,
214
+ owner_bound: bool = False,
215
+ ) -> str:
216
+ """Render a captured build-time variant; runtime input is never accepted."""
217
+ node = variant.node
218
+ record = cast(RecordRef, node.args[0])
219
+ steps = cast(tuple[Node, ...], node.args[1])
220
+ if not record.logical_namespace or not record.logical_name:
221
+ raise CaptureError(
222
+ "CAPTURE_UNSUPPORTED", "Record requires authored namespace and logical name"
223
+ )
224
+ source = _quote(record.logical_namespace) + "." + _quote(record.logical_name)
225
+ mutation = node.op == "update"
226
+ predicates: list[str] = []
227
+ having: list[str] = []
228
+ selected: tuple[FieldRef | Node, ...] | None = None
229
+ projection_names: tuple[str, ...] = ()
230
+ grouped: tuple[FieldRef | Node, ...] = ()
231
+ group_seen = False
232
+ order: list[Ordering[object]] = []
233
+ includes: list[str] = []
234
+ joins: list[str] = []
235
+ limit: int | None = None
236
+ group_limit: int | None = None
237
+ for step in steps:
238
+ if step.op == "filter":
239
+ for item in step.args:
240
+ predicate = _predicate(cast(Node, item), mutation)
241
+ if predicate is not None:
242
+ predicates.append(predicate)
243
+ elif step.op == "having":
244
+ for item in step.args:
245
+ value = _predicate(cast(Node, item), mutation)
246
+ if value is not None:
247
+ having.append(value)
248
+ elif step.op == "select":
249
+ selected = cast(tuple[FieldRef | Node, ...], step.args)
250
+ elif step.op == "into":
251
+ selected = cast(ProjectionRef, step.args[0]).fields
252
+ projection_names = cast(ProjectionRef, step.args[0]).names
253
+ elif step.op == "group":
254
+ if group_seen:
255
+ raise CaptureError("CAPTURE_UNSUPPORTED", "repeated grouping requires explicit grouping semantics")
256
+ group_seen = True
257
+ if limit is not None:
258
+ raise CaptureError("CAPTURE_UNSUPPORTED", "input-row limit before grouping has no admitted semantics")
259
+ grouped = cast(tuple[FieldRef | Node, ...], step.args)
260
+ elif step.op == "order":
261
+ order.extend(cast(tuple[Ordering[object], ...], step.args))
262
+ elif step.op == "limit":
263
+ if grouped:
264
+ group_limit = cast(int, step.args[0])
265
+ else:
266
+ limit = cast(int, step.args[0])
267
+ elif step.op == "group_limit":
268
+ group_limit = cast(int, step.args[0])
269
+ elif step.op == "join":
270
+ if mutation or binding is None:
271
+ raise CaptureError(
272
+ "CAPTURE_UNSUPPORTED",
273
+ "join rendering requires declared build-time bindings",
274
+ )
275
+ rel = cast(Join[object, object, object], step.args[0])
276
+ aliases = _ALIASES.get()
277
+ target = rel.target
278
+ a = aliases[owner_identity(target)]
279
+ relationships = cast(list[dict[str, object]], binding["relationships"])
280
+ matches = [r for r in relationships if r["id"] == rel.ref.field]
281
+ if len(matches) != 1:
282
+ raise CaptureError(
283
+ "CAPTURE_UNSUPPORTED", "relationship binding is absent or ambiguous"
284
+ )
285
+ relation_binding = matches[0]
286
+ tables = cast(list[dict[str, object]], binding["tables"])
287
+ source_alias = aliases[owner_identity(rel.ref)]
288
+ target_name = [target.logical_namespace, target.logical_name]
289
+ source_record = (
290
+ record
291
+ if source_alias == "r"
292
+ else next(
293
+ cast(Join[object, object, object], other.args[0]).target
294
+ for other in steps
295
+ if other.op == "join"
296
+ and aliases[
297
+ owner_identity(cast(Join[object, object, object], other.args[0]).target)
298
+ ]
299
+ == source_alias
300
+ )
301
+ )
302
+ if (
303
+ relation_binding["source"]
304
+ != [source_record.logical_namespace, source_record.logical_name]
305
+ or relation_binding["target"] != target_name
306
+ or relation_binding["toOne"] is not True
307
+ ):
308
+ raise CaptureError(
309
+ "CAPTURE_UNSUPPORTED",
310
+ "relationship endpoint differs from generated declaration",
311
+ )
312
+ if not any(t["logical"] == target_name for t in tables):
313
+ raise CaptureError("CAPTURE_UNSUPPORTED", "join target binding absent")
314
+ on = " AND ".join(
315
+ _quote(source_alias)
316
+ + "."
317
+ + _quote(pair[0])
318
+ + " = "
319
+ + _quote(a)
320
+ + "."
321
+ + _quote(pair[1])
322
+ for pair in cast(list[list[str]], relation_binding["pairs"])
323
+ )
324
+ joins.append(
325
+ str(step.args[1]).upper()
326
+ + " JOIN "
327
+ + _quote(cast(str, target.logical_namespace))
328
+ + "."
329
+ + _quote(cast(str, target.logical_name))
330
+ + " AS "
331
+ + _quote(a)
332
+ + " ON "
333
+ + on
334
+ )
335
+ elif step.op == "snapshot":
336
+ if (node.op != "page" and not owner_bound) or step.args != (True,):
337
+ raise CaptureError("CAPTURE_UNSUPPORTED", "snapshot requires a page declaration")
338
+ elif step.op == "include_keys":
339
+ field, bound = cast(tuple[FieldRef, int], step.args[:2])
340
+ direction = step.args[3] if len(step.args) == 4 else "forward"
341
+ function = "INVERSE_RELATED_KEYS" if direction == "inverse" else "RELATED_KEYS"
342
+ extra = ""
343
+ if direction == "inverse":
344
+ if field.field_module is None:
345
+ raise CaptureError("CAPTURE_SIGNATURE", "original inverse relationship module required")
346
+ extra = ", " + _value(Node("str", (field.field_module,))) + ", " + _value(Node("str", (field.field,)))
347
+ includes.append(
348
+ f"{function}({_column(field)}, {bound}{extra}) AS {_quote(field.field + '_keys')}"
349
+ )
350
+ else:
351
+ raise CaptureError("CAPTURE_UNSUPPORTED", "unsupported logical query step")
352
+ if group_limit is not None and node.op != "group_count":
353
+ if not grouped or limit is not None:
354
+ raise CaptureError("CAPTURE_UNSUPPORTED", "conflicting or ungrouped result limits")
355
+ limit = group_limit
356
+ aggregate_query = bool(grouped) or selected is not None and any(isinstance(value, Node) and value.op == "aggregate" for value in selected)
357
+ if grouped and node.op == "all" and group_limit is None:
358
+ raise CaptureError(
359
+ "CAPTURE_UNSUPPORTED", "grouped list reads require an explicit result-group limit"
360
+ )
361
+ if having and not aggregate_query:
362
+ raise CaptureError("CAPTURE_UNSUPPORTED", "having requires aggregation")
363
+ if mutation:
364
+ if (
365
+ selected is not None
366
+ or grouped
367
+ or order
368
+ or includes
369
+ or limit is not None
370
+ or not predicates
371
+ ):
372
+ raise CaptureError(
373
+ "CAPTURE_UNSUPPORTED",
374
+ "bulk update requires a filtered unprojected selection",
375
+ )
376
+ assignments = cast(tuple[tuple[FieldRef, Node], ...], node.args[2])
377
+ setting = ", ".join(
378
+ f"{_column(field, True)} = {_value(value, True)}"
379
+ for field, value in assignments
380
+ )
381
+ return f"UPDATE {source} SET {setting} WHERE " + " AND ".join(predicates)
382
+ if node.op in ("count", "group_count"):
383
+ projection = ", ".join([*(_scalar_sql(f) for f in grouped), "COUNT(*)"])
384
+ group_result = (*grouped, Node("aggregate", ("count", None, None)))
385
+ if order or includes or limit is not None or (
386
+ selected is not None and (node.op != "group_count" or selected != group_result)
387
+ ):
388
+ raise CaptureError("CAPTURE_UNSUPPORTED", "count with projection/order/limit requires explicit Weft semantics")
389
+ if node.op == "group_count" and projection_names:
390
+ projection = ", ".join(
391
+ _scalar_sql(field) + " AS " + _quote(name)
392
+ for field, name in zip(group_result, projection_names, strict=True)
393
+ )
394
+ if node.op == "group_count":
395
+ if not grouped or group_limit is None:
396
+ raise CaptureError("CAPTURE_UNSUPPORTED", "grouped count requires an explicit result-group limit")
397
+ limit = group_limit
398
+ else:
399
+ projection = (
400
+ '"r".*' if selected is None else ", ".join(_scalar_sql(f) for f in selected)
401
+ )
402
+ if selected is not None and projection_names:
403
+ projection = ", ".join(
404
+ _scalar_sql(f) + " AS " + _quote(n)
405
+ for f, n in zip(selected, projection_names, strict=True)
406
+ )
407
+ if includes:
408
+ projection += ", " + ", ".join(includes)
409
+ if node.op == "get":
410
+ values = _key_values(cast(Node, node.args[2]))
411
+ if len(values) != len(record.key):
412
+ raise CaptureError(
413
+ "CAPTURE_UNSUPPORTED", "Key component count differs from declared Key"
414
+ )
415
+ predicates.extend(
416
+ f"{_column(field)} = {value}"
417
+ for field, value in zip(record.key, values, strict=True)
418
+ )
419
+ if node.op in ("first", "exists"):
420
+ limit = 1
421
+ elif node.op == "one":
422
+ # Two rows distinguish exactly one from more-than-one without truncation.
423
+ limit = 2
424
+ elif node.op == "page":
425
+ limit = cast(int, node.args[2])
426
+ if not order:
427
+ order = [Ordering(field, "ASC") for field in record.key]
428
+ if node.op == "exists":
429
+ projection = ", ".join(_column(field) for field in record.key)
430
+ if (
431
+ node.op not in ("count", "group_count", "get")
432
+ and limit is None
433
+ and not owner_bound
434
+ and not aggregate_query
435
+ ):
436
+ raise CaptureError(
437
+ "CAPTURE_UNSUPPORTED", "list reads require an explicit bound"
438
+ )
439
+ sql = f'SELECT {projection} FROM {source} AS "r"'
440
+ if joins:
441
+ sql += " " + " ".join(joins)
442
+ if predicates:
443
+ sql += " WHERE " + " AND ".join(predicates)
444
+ if grouped:
445
+ sql += " GROUP BY " + ", ".join(_scalar_sql(field) for field in grouped)
446
+ if having:
447
+ sql += " HAVING " + " AND ".join(having)
448
+ if order:
449
+ existing = {item.field for item in order}
450
+ if not aggregate_query:
451
+ order.extend(
452
+ Ordering(field, "ASC") for field in record.key if field not in existing
453
+ )
454
+ sql += " ORDER BY " + ", ".join(
455
+ f"{_scalar_sql(item.field)} {item.direction} NULLS {item.nulls}"
456
+ for item in order
457
+ )
458
+ if limit is not None:
459
+ sql += f" LIMIT {limit}"
460
+ return sql
461
+
462
+
463
+ def render_logical(
464
+ variant: LogicalVariant,
465
+ *,
466
+ binding: Mapping[str, object] | None = None,
467
+ owner_bound: bool = False,
468
+ ) -> str:
469
+ node = variant.node
470
+ record = cast(RecordRef, node.args[0])
471
+ aliases = {owner_identity(record): "r"}
472
+ for step in cast(tuple[Node, ...], node.args[1]):
473
+ if step.op == "join":
474
+ rel = cast(Join[object, object, object], step.args[0])
475
+ aliases[owner_identity(rel.target)] = "j" + str(len(aliases))
476
+ token = _ALIASES.set(aliases)
477
+ try:
478
+ return _render_logical(variant, binding, owner_bound)
479
+ finally:
480
+ _ALIASES.reset(token)
481
+
482
+
483
+ @dataclass(frozen=True)
484
+ class RelatedLogical:
485
+ source_sql: str
486
+ target_sql: str
487
+ relationship: Mapping[str, str]
488
+
489
+
490
+ @dataclass(frozen=True)
491
+ class _NodeVariant:
492
+ node: Node
493
+
494
+
495
+ def render_related_logical(
496
+ variant: LogicalVariant, *, binding: Mapping[str, object] | None = None,
497
+ owner_bound: bool = False,
498
+ ) -> RelatedLogical | None:
499
+ """Retain both original logical queries for the distinct owner endpoint."""
500
+ steps = cast(tuple[Node, ...], variant.node.args[1])
501
+ related = tuple(step for step in steps if step.op == "related")
502
+ if not related:
503
+ return None
504
+ if len(related) != 1 or steps[0] is not related[0]:
505
+ raise CaptureError("WEFT_BLOCKED", "WR-A6 navigation requires one original source")
506
+ source, source_steps, relationship, direction = related[0].args
507
+ original_steps = cast(tuple[Node, ...], source_steps)
508
+ if any(step.op == "related" for step in original_steps):
509
+ raise CaptureError("WEFT_BLOCKED", "WR-A6 nested navigation requires a recursive owner profile")
510
+ relation = cast(Related[object, object], relationship)
511
+ target_node = Node(variant.node.op, (variant.node.args[0], steps[1:], *variant.node.args[2:]))
512
+ return RelatedLogical(
513
+ render_logical(_NodeVariant(Node("all", (source, original_steps))), binding=binding, owner_bound=True),
514
+ render_logical(_NodeVariant(target_node), binding=binding, owner_bound=owner_bound),
515
+ {"module": cast(str, relation.ref.field_module), "id": relation.ref.field, "direction": cast(str, direction)},
516
+ )