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,625 @@
1
+ # SPDX-License-Identifier: MIT OR Apache-2.0
2
+ """Typed, capture-only logical expressions."""
3
+
4
+ from __future__ import annotations
5
+
6
+ from collections.abc import Callable, Mapping, Sequence
7
+ from dataclasses import dataclass, field, replace
8
+ from datetime import date, datetime
9
+ from decimal import Decimal
10
+ from typing import Any, Generic, Literal, Never, TypeVar, cast, overload
11
+
12
+ from pydantic import BaseModel
13
+
14
+ from ..types import MISSING
15
+ from ._context import CaptureError, require_capture
16
+ from ._nodes import FieldRef, KeyLiteral, Node, RecordRef, literal, owner_identity
17
+
18
+ OutputT = TypeVar("OutputT")
19
+ T = TypeVar("T")
20
+ K = TypeVar("K")
21
+ T_co = TypeVar("T_co", covariant=True)
22
+ PredicateOwner_co = TypeVar("PredicateOwner_co", covariant=True)
23
+ OtherOwner = TypeVar("OtherOwner")
24
+ MemberT = TypeVar("MemberT")
25
+
26
+
27
+ @dataclass(frozen=True)
28
+ class Param(Generic[T_co]):
29
+ name: str
30
+ components: tuple[str, ...] = ()
31
+ key_identity: tuple[tuple[str, str], ...] = ()
32
+
33
+ def __bool__(self) -> bool:
34
+ raise TypeError("symbolic parameters have no truth value")
35
+
36
+
37
+ @dataclass(frozen=True)
38
+ class Predicate(Generic[PredicateOwner_co]):
39
+ def _predicate_owner(self) -> PredicateOwner_co:
40
+ raise TypeError("internal static owner marker")
41
+
42
+ node: Node
43
+
44
+ def __bool__(self) -> bool:
45
+ raise TypeError("predicates have no truth value; use &, | and ~")
46
+
47
+ def __and__(self, other: Predicate[OtherOwner]) -> Predicate[PredicateOwner_co | OtherOwner]:
48
+ require_capture()
49
+ if not isinstance(cast(object, other), Predicate):
50
+ raise TypeError("AND requires a predicate")
51
+ return Predicate(Node("and", (self.node, other.node)))
52
+
53
+ def __or__(self, other: Predicate[OtherOwner]) -> Predicate[PredicateOwner_co | OtherOwner]:
54
+ require_capture()
55
+ if not isinstance(cast(object, other), Predicate):
56
+ raise TypeError("OR requires a predicate")
57
+ return Predicate(Node("or", (self.node, other.node)))
58
+
59
+ def __invert__(self) -> Predicate[PredicateOwner_co]:
60
+ require_capture()
61
+ return Predicate(Node("not", (self.node,)))
62
+
63
+
64
+ @dataclass(frozen=True)
65
+ class Ordering(Generic[OutputT]):
66
+ field: FieldRef | Node
67
+ direction: str
68
+ nulls: str = "LAST"
69
+
70
+ def __post_init__(self) -> None:
71
+ if self.direction not in ("ASC", "DESC") or self.nulls not in ("FIRST", "LAST"):
72
+ raise TypeError(
73
+ "ordering direction and null placement must be explicit DSL forms"
74
+ )
75
+ if not isinstance(cast(object, self.field), (FieldRef, Node)):
76
+ raise TypeError("ordering requires generated field metadata")
77
+
78
+ def _ordering_owner(self) -> OutputT:
79
+ raise TypeError("internal static owner marker")
80
+
81
+ def nulls_first(self) -> Ordering[OutputT]:
82
+ require_capture()
83
+ return replace(self, nulls="FIRST")
84
+
85
+ def nulls_last(self) -> Ordering[OutputT]:
86
+ require_capture()
87
+ return replace(self, nulls="LAST")
88
+
89
+
90
+ def operand(value: object) -> Node:
91
+ if isinstance(value, Param):
92
+ return (
93
+ Node("key_param", (value.name, value.components, value.key_identity))
94
+ if value.components
95
+ else Node("param", (value.name,))
96
+ )
97
+ if isinstance(value, Column):
98
+ return Node("column", (value.ref,))
99
+ return literal(value)
100
+
101
+
102
+ @dataclass(frozen=True, eq=False)
103
+ class Column(Generic[OutputT, T]):
104
+ ref: FieldRef
105
+ __hash__ = None # type: ignore[assignment]
106
+
107
+ def __post_init__(self) -> None:
108
+ if not isinstance(cast(object, self.ref), FieldRef):
109
+ raise TypeError("Column requires generated FieldRef metadata")
110
+
111
+ def _nullable_selection(self) -> bool:
112
+ return True
113
+
114
+ def _group_key(self) -> bool:
115
+ return True
116
+
117
+ def _selection_owner(self) -> OutputT:
118
+ raise TypeError("internal static owner marker")
119
+
120
+ def _selection_value(self) -> T:
121
+ raise TypeError("internal static value marker")
122
+
123
+ @overload
124
+ def bucket_width(self: Column[OutputT, int], width: int) -> Bucket[OutputT, int]: ...
125
+ @overload
126
+ def bucket_width(self: Column[OutputT, int | None], width: int) -> Bucket[OutputT, int | None]: ...
127
+ @overload
128
+ def bucket_width(self: Column[OutputT, int] | Column[OutputT, Decimal], width: Decimal) -> Bucket[OutputT, Decimal]: ...
129
+ @overload
130
+ def bucket_width(self: Column[OutputT, int | None] | Column[OutputT, Decimal | None], width: Decimal) -> Bucket[OutputT, Decimal | None]: ...
131
+ @overload
132
+ def bucket_width(self: Column[OutputT, Decimal], width: int) -> Bucket[OutputT, Decimal]: ...
133
+ @overload
134
+ def bucket_width(self: Column[OutputT, Decimal | None], width: int) -> Bucket[OutputT, Decimal | None]: ...
135
+ def bucket_width(self, width: int | Decimal) -> Bucket[OutputT, Any]:
136
+ return bucket_width(self, width)
137
+
138
+ def _cmp(self, op: str, value: object) -> Predicate[OutputT]:
139
+ require_capture()
140
+ if op in ("<", "<=", ">", ">=") and type(value) is bool:
141
+ raise CaptureError("CAPTURE_UNSUPPORTED", "booleans admit equality only")
142
+ right = operand(value)
143
+ other_temporal = (
144
+ value.ref.temporal
145
+ if isinstance(value, Column)
146
+ else right.op
147
+ if right.op in ("instant", "local")
148
+ else None
149
+ )
150
+ if (
151
+ self.ref.temporal is not None
152
+ and other_temporal is not None
153
+ and self.ref.temporal != other_temporal
154
+ ):
155
+ raise CaptureError(
156
+ "CAPTURE_UNSUPPORTED",
157
+ "instant/local comparison cannot preserve meaning",
158
+ )
159
+ return Predicate(Node(op, (Node("column", (self.ref,)), right)))
160
+
161
+ # Symbolic equality intentionally replaces object’s bool result. The narrow
162
+ # operand/result types remain active in caller checks (including misuse).
163
+ def __eq__(self, other: T | Param[T] | Column[OutputT, T]) -> Predicate[OutputT]: # type: ignore[override] # ty: ignore[invalid-method-override]
164
+ return self._cmp("=", other)
165
+
166
+ def __ne__(self, other: T | Param[T] | Column[OutputT, T]) -> Predicate[OutputT]: # type: ignore[override] # ty: ignore[invalid-method-override]
167
+ return self._cmp("<>", other)
168
+
169
+ def __lt__(self, other: T | Param[T] | Column[OutputT, T]) -> Predicate[OutputT]:
170
+ return self._cmp("<", other)
171
+
172
+ def __le__(self, other: T | Param[T] | Column[OutputT, T]) -> Predicate[OutputT]:
173
+ return self._cmp("<=", other)
174
+
175
+ def __gt__(self, other: T | Param[T] | Column[OutputT, T]) -> Predicate[OutputT]:
176
+ return self._cmp(">", other)
177
+
178
+ def __ge__(self, other: T | Param[T] | Column[OutputT, T]) -> Predicate[OutputT]:
179
+ return self._cmp(">=", other)
180
+
181
+ def _test(self, op: str) -> Predicate[OutputT]:
182
+ require_capture()
183
+ return Predicate(Node(op, (Node("column", (self.ref,)),)))
184
+
185
+ def is_null(self) -> Predicate[OutputT]:
186
+ return self._test("IS NULL")
187
+
188
+ def is_not_null(self) -> Predicate[OutputT]:
189
+ return self._test("IS NOT NULL")
190
+
191
+ def starts_with(
192
+ self: Column[OutputT, str] | Column[OutputT, str | None],
193
+ prefix: str | Param[str],
194
+ ) -> Predicate[OutputT]:
195
+ """Binary Unicode prefix; %, _ and backslash are ordinary characters."""
196
+ if not isinstance(prefix, (str, Param)):
197
+ raise TypeError("prefix requires a string or named string parameter")
198
+ return self._cmp("STARTS_WITH", prefix)
199
+
200
+ def is_distinct_from(
201
+ self, other: T | None | Param[T | None] | Column[OutputT, T]
202
+ ) -> Predicate[OutputT]:
203
+ """Null-safe inequality; the owner compiler preserves two-valued semantics."""
204
+ return self._cmp("IS DISTINCT FROM", other)
205
+
206
+ def is_not_distinct_from(
207
+ self, other: T | None | Param[T | None] | Column[OutputT, T]
208
+ ) -> Predicate[OutputT]:
209
+ """Null-safe equality, including two SQL null operands."""
210
+ return self._cmp("IS NOT DISTINCT FROM", other)
211
+
212
+ def matches_all_terms(self: Column[OutputT, str] | Column[OutputT, str | None], query: str | Param[str]) -> Predicate[OutputT]:
213
+ if not isinstance(query, (str, Param)):
214
+ raise CaptureError("CAPTURE_UNSUPPORTED", "term filter requires a string or declared string parameter")
215
+ return self._cmp("MATCHES_ALL_TERMS", query)
216
+
217
+ def matches_any_term(self: Column[OutputT, str] | Column[OutputT, str | None], query: str | Param[str]) -> Predicate[OutputT]:
218
+ if not isinstance(query, (str, Param)):
219
+ raise CaptureError("CAPTURE_UNSUPPORTED", "term filter requires a string or declared string parameter")
220
+ return self._cmp("MATCHES_ANY_TERM", query)
221
+
222
+ def is_missing(self) -> Predicate[OutputT]:
223
+ return self._test("IS MISSING")
224
+
225
+ def is_present(self) -> Predicate[OutputT]:
226
+ return self._test("IS NOT MISSING")
227
+
228
+ @overload
229
+ def is_in(self: Column[OutputT, MemberT | None], values: Param[list[MemberT]] | list[MemberT] | tuple[MemberT, ...]) -> Predicate[OutputT]: ...
230
+ @overload
231
+ def is_in(self, values: Param[list[T]] | Param[list[T | None]] | list[T] | list[T | None] | tuple[T | None, ...]) -> Predicate[OutputT]: ...
232
+ def is_in(self, values: object) -> Predicate[OutputT]:
233
+ return self._cmp("IN", values)
234
+
235
+ @overload
236
+ def not_in(self: Column[OutputT, MemberT | None], values: Param[list[MemberT]] | list[MemberT] | tuple[MemberT, ...]) -> Predicate[OutputT]: ...
237
+ @overload
238
+ def not_in(self, values: Param[list[T]] | Param[list[T | None]] | list[T] | list[T | None] | tuple[T | None, ...]) -> Predicate[OutputT]: ...
239
+ def not_in(self, values: object) -> Predicate[OutputT]:
240
+ return self._cmp("NOT IN", values)
241
+
242
+ def between(self, lo: T | Param[T], hi: T | Param[T]) -> Predicate[OutputT]:
243
+ require_capture()
244
+ return Predicate(
245
+ Node("BETWEEN", (Node("column", (self.ref,)), operand(lo), operand(hi)))
246
+ )
247
+
248
+ def asc(self) -> Ordering[OutputT]:
249
+ require_capture()
250
+ return Ordering(self.ref, "ASC")
251
+
252
+ def desc(self) -> Ordering[OutputT]:
253
+ require_capture()
254
+ return Ordering(self.ref, "DESC")
255
+
256
+
257
+ @dataclass(frozen=True)
258
+ class Related(Generic[OutputT, K]):
259
+ ref: FieldRef
260
+ key_target: RecordRef | None = field(default=None, kw_only=True)
261
+ direction: Literal["forward", "inverse"] = field(default="forward", kw_only=True)
262
+
263
+ def __post_init__(self) -> None:
264
+ if not isinstance(cast(object, self.ref), FieldRef):
265
+ raise TypeError("Related requires generated FieldRef metadata")
266
+ if self.direction not in ("forward", "inverse"):
267
+ raise TypeError("original directed relationship required")
268
+
269
+ def has(self, key: K | Param[K]) -> Predicate[OutputT]:
270
+ require_capture()
271
+ value = operand(key)
272
+ if self.key_target is None:
273
+ raise CaptureError("WEFT_BLOCKED", "WR-A6 regenerate exact original relationship Key metadata")
274
+ if self.key_target is not None:
275
+ target = self.key_target
276
+ if target.source is None or target.key_id is None:
277
+ raise CaptureError("CAPTURE_SIGNATURE", "relationship Key target source is absent")
278
+ expected = {"documentId": target.source.document_id, "coreVersion": target.source.core_version, "module": target.module, "element": target.element, "key": target.key_id}
279
+ if value.op == "key_param":
280
+ identity = dict(cast(tuple[tuple[str, str], ...], value.args[2]))
281
+ elif value.op == "key":
282
+ literal_key = cast(KeyLiteral, value.args[0])
283
+ identity = dict(literal_key.identity)
284
+ if literal_key.source != target.source:
285
+ raise CaptureError("CAPTURE_SIGNATURE", "relationship Key generation differs")
286
+ else:
287
+ raise CaptureError("CAPTURE_SIGNATURE", "relationship requires its declared generated Key")
288
+ if identity != expected:
289
+ raise CaptureError("CAPTURE_SIGNATURE", "relationship declared Key identity differs")
290
+ op = "HAS_INVERSE_RELATED" if self.direction == "inverse" else "HAS_RELATED"
291
+ args: tuple[object, ...] = (Node("column", (self.ref,)), value)
292
+ if self.direction == "inverse":
293
+ args += (self.ref.field_module, self.ref.field)
294
+ return Predicate(Node(op, args))
295
+
296
+
297
+ NonMissing = TypeVar(
298
+ "NonMissing",
299
+ bound=str
300
+ | bool
301
+ | int
302
+ | Decimal
303
+ | bytes
304
+ | date
305
+ | datetime
306
+ | Sequence[object]
307
+ | Mapping[str, object]
308
+ | BaseModel
309
+ | None,
310
+ )
311
+
312
+
313
+ class InvalidOptionalFilter:
314
+ """Static marker for a no-MISSING parameter; never an admitted predicate."""
315
+
316
+
317
+ @overload
318
+ def if_present(
319
+ p: Param[NonMissing], build: Callable[[Param[NonMissing]], Predicate[OutputT]]
320
+ ) -> InvalidOptionalFilter: ... # type: ignore[overload-overlap]
321
+ @overload
322
+ def if_present(
323
+ p: Param[T | MISSING], build: Callable[[Param[T]], Predicate[OutputT]]
324
+ ) -> Predicate[OutputT]: ...
325
+ def if_present(p: Any, build: Any) -> Any:
326
+ context = require_capture()
327
+ if not isinstance(p, Param) or p.name not in context.declared_optional:
328
+ raise CaptureError(
329
+ "CAPTURE_SIGNATURE", "optional filter requires declared MISSING parameter"
330
+ )
331
+ context.used_optional.add(p.name)
332
+ if p.name not in context.presence:
333
+ return Predicate[Any](Node("omitted", ()))
334
+ result = build(p)
335
+ if not isinstance(result, Predicate):
336
+ raise CaptureError(
337
+ "CAPTURE_UNSUPPORTED", "optional filter callback must return a predicate"
338
+ )
339
+ return cast(Predicate[Any], result)
340
+
341
+
342
+ def and_(*predicates: Predicate[OutputT]) -> Predicate[OutputT]:
343
+ require_capture()
344
+ if not predicates:
345
+ raise TypeError("AND requires at least one predicate")
346
+ result = predicates[0]
347
+ for predicate in predicates[1:]:
348
+ result = result & predicate
349
+ return result
350
+
351
+
352
+ def or_(*predicates: Predicate[OutputT]) -> Predicate[OutputT]:
353
+ require_capture()
354
+ if not predicates:
355
+ raise TypeError("OR requires at least one predicate")
356
+ result = predicates[0]
357
+ for predicate in predicates[1:]:
358
+ result = result | predicate
359
+ return result
360
+
361
+
362
+ def not_(predicate: Predicate[OutputT]) -> Predicate[OutputT]:
363
+ return ~predicate
364
+
365
+
366
+ J = TypeVar("J")
367
+ AliasTag = TypeVar("AliasTag")
368
+
369
+
370
+ class AliasOwner(Generic[OutputT, AliasTag]):
371
+ """Static owner identity for one explicitly aliased original Record."""
372
+
373
+
374
+ def alias_token(tag: type[AliasTag]) -> str:
375
+ if not isinstance(tag, type) or "<locals>" in tag.__qualname__:
376
+ raise TypeError("alias tag must be a stable module-level class")
377
+ return tag.__module__ + ":" + tag.__qualname__
378
+
379
+
380
+ def alias_record(ref: RecordRef, tag: type[AliasTag]) -> RecordRef:
381
+ if ref.alias is not None:
382
+ raise TypeError("an aliased Record cannot be aliased again")
383
+ token = alias_token(tag)
384
+ return replace(ref, alias=token, key=tuple(replace(f, alias=token) for f in ref.key))
385
+
386
+
387
+ @dataclass(frozen=True)
388
+ class RecordAlias(Generic[OutputT, AliasTag]):
389
+ ref: RecordRef
390
+ tag: type[AliasTag]
391
+
392
+ def __post_init__(self) -> None:
393
+ if self.ref.alias != alias_token(self.tag):
394
+ raise TypeError("alias tag differs from generated owner identity")
395
+
396
+
397
+ def alias_column(column: Column[OutputT, T], tag: type[AliasTag]) -> Column[AliasOwner[OutputT, AliasTag], T]:
398
+ if column.ref.alias is not None:
399
+ raise TypeError("an aliased Column cannot be aliased again")
400
+ return Column(replace(column.ref, alias=alias_token(tag)))
401
+
402
+
403
+ def _alias_target(relationship: Join[Any, Any, Any], target: RecordAlias[Any, Any]) -> RecordRef:
404
+ if not isinstance(target, RecordAlias) or target.ref.alias is None:
405
+ raise TypeError("join target requires an explicit generated alias")
406
+ if (target.ref.module, target.ref.element, target.ref.source) != (relationship.target.module, relationship.target.element, relationship.target.source):
407
+ raise TypeError("alias target differs from original relationship Record/Key")
408
+ if (target.ref.logical_namespace, target.ref.logical_name) != (relationship.target.logical_namespace, relationship.target.logical_name):
409
+ raise TypeError("alias target differs from original generated relationship metadata")
410
+ # An owner alias is independent of which original Key this relationship
411
+ # selects. Keep that exact Key rather than substituting the root's default.
412
+ return alias_record(relationship.target, target.tag)
413
+
414
+
415
+ @dataclass(frozen=True)
416
+ class Join(Related[OutputT, K], Generic[OutputT, J, K]):
417
+ target: RecordRef
418
+ optional: bool = False
419
+
420
+ def __post_init__(self) -> None:
421
+ super().__post_init__()
422
+ if not isinstance(self.target, RecordRef) or type(self.optional) is not bool:
423
+ raise TypeError("join requires generated target metadata")
424
+ if self.key_target is None:
425
+ object.__setattr__(self, "key_target", self.target)
426
+
427
+
428
+ @dataclass(frozen=True)
429
+ class RequiredJoin(Join[OutputT, J, K], Generic[OutputT, J, K]):
430
+ def to_alias(self, target: RecordAlias[J, AliasTag]) -> RequiredJoin[OutputT, AliasOwner[J, AliasTag], K]:
431
+ return replace(self, target=_alias_target(self, target))
432
+ def _join_owner(self) -> OutputT:
433
+ raise TypeError("internal static owner marker")
434
+ def _join_target(self) -> J:
435
+ raise TypeError("internal static target marker")
436
+ def _required_join(self) -> bool:
437
+ return True
438
+ def __post_init__(self) -> None:
439
+ super().__post_init__()
440
+ if self.optional:
441
+ raise TypeError("required relationship cannot declare optional")
442
+
443
+
444
+ @dataclass(frozen=True)
445
+ class OptionalJoin(Join[OutputT, J, K], Generic[OutputT, J, K]):
446
+ def to_alias(self, target: RecordAlias[J, AliasTag]) -> OptionalJoin[OutputT, AliasOwner[J, AliasTag], K]:
447
+ return replace(self, target=_alias_target(self, target))
448
+ def _join_owner(self) -> OutputT:
449
+ raise TypeError("internal static owner marker")
450
+ def _join_target(self) -> J:
451
+ raise TypeError("internal static target marker")
452
+ def _optional_join(self) -> bool:
453
+ return True
454
+ def __post_init__(self) -> None:
455
+ super().__post_init__()
456
+ if not self.optional:
457
+ raise TypeError("optional relationship must declare optional")
458
+
459
+
460
+ O = TypeVar("O")
461
+ N = TypeVar("N", int, Decimal)
462
+
463
+ def scalar(value: object) -> FieldRef | Node:
464
+ if isinstance(value, Column):
465
+ return value.ref
466
+ if isinstance(value, (Agg, Bucket)):
467
+ return value.node
468
+ raise TypeError("selection requires a generated column or closed scalar expression")
469
+
470
+ @dataclass(frozen=True, eq=False)
471
+ class _Scalar(Generic[O, T]):
472
+ node: Node
473
+
474
+ def __bool__(self) -> bool:
475
+ raise TypeError("scalar expressions have no truth value")
476
+
477
+ def _selection_owner(self) -> O:
478
+ raise TypeError("internal static owner marker")
479
+
480
+ def _selection_value(self) -> T:
481
+ raise TypeError("internal static value marker")
482
+
483
+ def _cmp(self, op: str, other: object) -> Predicate[O]:
484
+
485
+ require_capture()
486
+ return Predicate[O](Node(op, (self.node, operand(other))))
487
+
488
+ def __eq__(self, other: T | Param[T]) -> Predicate[O]: # type: ignore[override] # ty: ignore[invalid-method-override]
489
+ return self._cmp("=", other)
490
+
491
+ def __ne__(self, other: T | Param[T]) -> Predicate[O]: # type: ignore[override] # ty: ignore[invalid-method-override]
492
+ return self._cmp("<>", other)
493
+
494
+ def __lt__(self, other: T | Param[T]) -> Predicate[O]:
495
+ return self._cmp("<", other)
496
+
497
+ def __le__(self, other: T | Param[T]) -> Predicate[O]:
498
+ return self._cmp("<=", other)
499
+
500
+ def __gt__(self, other: T | Param[T]) -> Predicate[O]:
501
+ return self._cmp(">", other)
502
+
503
+ def __ge__(self, other: T | Param[T]) -> Predicate[O]:
504
+ return self._cmp(">=", other)
505
+
506
+ def asc(self) -> Ordering[O]:
507
+
508
+ require_capture()
509
+ return Ordering[O](self.node, "ASC")
510
+
511
+ def desc(self) -> Ordering[O]:
512
+
513
+ require_capture()
514
+ return Ordering[O](self.node, "DESC")
515
+
516
+ def is_null(self) -> Predicate[O]:
517
+
518
+ require_capture()
519
+ return Predicate[O](Node("IS NULL", (self.node,)))
520
+
521
+ @dataclass(frozen=True, eq=False)
522
+ class Agg(_Scalar[O, T], Generic[O, T]):
523
+ def _aggregate_selection(self) -> bool:
524
+ return True
525
+
526
+ @dataclass(frozen=True, eq=False)
527
+ class Bucket(_Scalar[O, T], Generic[O, T]):
528
+ def _nullable_selection(self) -> bool:
529
+ return True
530
+ def _group_key(self) -> bool:
531
+ return True
532
+
533
+ def _aggregate(column: object, op: str, scale: int | None = None) -> Agg[Any, Any]:
534
+ require_capture()
535
+ if not isinstance(column, Column):
536
+ raise CaptureError("CAPTURE_UNSUPPORTED", "aggregate requires a generated scalar column")
537
+ if column.ref.temporal is not None:
538
+ raise CaptureError("CAPTURE_UNSUPPORTED", "temporal aggregate qualification is held")
539
+ if op == "avg" and (type(scale) is not int or not 0 <= scale <= 1000):
540
+ raise CaptureError("CAPTURE_UNSUPPORTED", "average requires literal scale in 0..1000")
541
+ return Agg(Node("aggregate", (op, column.ref, scale)))
542
+
543
+ @overload
544
+ def sum_(column: Column[O, int]) -> Agg[O, int | None]: ...
545
+ @overload
546
+ def sum_(column: Column[O, int | None]) -> Agg[O, int | None]: ... # type: ignore[overload-overlap] # Invariant Column carriers are disjoint; all three clients prove exact outputs.
547
+ @overload
548
+ def sum_(column: Column[O, Decimal]) -> Agg[O, Decimal | None]: ...
549
+ @overload
550
+ def sum_(column: Column[O, Decimal | None]) -> Agg[O, Decimal | None]: ...
551
+ def sum_(column: Column[Any, Any]) -> Agg[Any, Any]:
552
+ return _aggregate(column, "sum")
553
+
554
+
555
+ def avg_(column: Column[O, int] | Column[O, int | None] | Column[O, Decimal] | Column[O, Decimal | None], *, scale: int) -> Agg[O, Decimal | None]:
556
+ return cast("Agg[O, Decimal | None]", _aggregate(column, "avg", scale))
557
+
558
+ def min_(column: Column[O, T]) -> Agg[O, T | None]:
559
+ return cast("Agg[O, T | None]", _aggregate(column, "min"))
560
+
561
+ def max_(column: Column[O, T]) -> Agg[O, T | None]:
562
+ return cast("Agg[O, T | None]", _aggregate(column, "max"))
563
+
564
+ def count_distinct(column: Column[O, T]) -> Agg[O, int]:
565
+ return cast("Agg[O, int]", _aggregate(column, "count_distinct"))
566
+
567
+
568
+ def approx_count_distinct(column: Column[O, T]) -> Agg[O, int]:
569
+ """Preserve the requested owner form; no approximation profile is inferred."""
570
+ return cast("Agg[O, int]", _aggregate(column, "approx_count_distinct"))
571
+
572
+
573
+ def bucket_width(column: object, width: int | Decimal) -> Bucket[Any, Any]:
574
+ require_capture()
575
+ if not isinstance(column, Column) or column.ref.temporal is not None:
576
+ raise CaptureError("CAPTURE_UNSUPPORTED", "numeric bucket requires a non-temporal generated column")
577
+ if type(width) not in (int, Decimal) or isinstance(width, Decimal) and not width.is_finite() or width <= 0:
578
+ raise CaptureError("CAPTURE_UNSUPPORTED", "bucket width requires a finite positive literal int or Decimal")
579
+ if type(width) is int and width.bit_length() > 13606:
580
+ raise CaptureError("CAPTURE_UNSUPPORTED", "integer bucket width exceeds the 4096-digit resource bound")
581
+ # Keep exact coefficient/exponent; rendering never rounds or uses float.
582
+ return Bucket(Node("bucket_width", (column.ref, width)))
583
+
584
+ def count() -> Agg[Never, int]:
585
+ require_capture()
586
+ return Agg(Node("aggregate", ("count", None, None)))
587
+
588
+
589
+
590
+ @overload
591
+ def alias_relationship(relationship: RequiredJoin[OutputT, J, K], tag: type[AliasTag]) -> RequiredJoin[AliasOwner[OutputT, AliasTag], J, K]: ...
592
+ @overload
593
+ def alias_relationship(relationship: OptionalJoin[OutputT, J, K], tag: type[AliasTag]) -> OptionalJoin[AliasOwner[OutputT, AliasTag], J, K]: ...
594
+ @overload
595
+ def alias_relationship(relationship: Related[OutputT, K], tag: type[AliasTag]) -> Related[AliasOwner[OutputT, AliasTag], K]: ...
596
+ def alias_relationship(relationship: Any, tag: type[AliasTag]) -> Any:
597
+ if relationship.ref.alias is not None:
598
+ raise TypeError("an aliased relationship cannot be aliased again")
599
+ return replace(relationship, ref=replace(relationship.ref, alias=alias_token(tag)))
600
+
601
+
602
+ def nullable_join_owners(steps: tuple[Node, ...]) -> frozenset[tuple[str, str, str | None]]:
603
+ """Exact flattened-join null provenance, including inner ancestor refinement."""
604
+ nullable: set[tuple[str, str, str | None]] = set()
605
+ parents: dict[tuple[str, str, str | None], tuple[str, str, str | None]] = {}
606
+ owners: set[tuple[str, str, str | None]] = set()
607
+ for step in steps:
608
+ if step.op != "join":
609
+ continue
610
+ relation = cast(Join[Any, Any, Any], step.args[0])
611
+ source, target = owner_identity(relation.ref), owner_identity(relation.target)
612
+ owners.add(source)
613
+ if target in owners:
614
+ raise CaptureError("CAPTURE_UNSUPPORTED", "duplicate query owner requires a distinct explicit alias")
615
+ owners.add(target)
616
+ parents[target] = source
617
+ if step.args[1] == "left":
618
+ nullable.add(target)
619
+ else:
620
+ nullable.discard(target)
621
+ owner = source
622
+ while owner in parents:
623
+ nullable.discard(owner)
624
+ owner = parents[owner]
625
+ return frozenset(nullable)
@@ -0,0 +1,4 @@
1
+ # SPDX-License-Identifier: MIT OR Apache-2.0
2
+ """Compatibility reexports of exact joined query builders."""
3
+ from ._query import GroupedContext as GroupedContext # noqa: PLC0414
4
+ from ._query import JoinedContext as JoinedContext # noqa: PLC0414