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
|
@@ -0,0 +1,413 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT OR Apache-2.0
|
|
2
|
+
"""Pure closed receipt representation for the native row-originals store."""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import re
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from .catalog import CatalogError
|
|
10
|
+
|
|
11
|
+
RECEIPT_PROFILE = 'umf.originals-creation-receipt/0.1'
|
|
12
|
+
COMMENT_PREFIX = RECEIPT_PROFILE + ':'
|
|
13
|
+
MAX_RECEIPT_BYTES = 1_048_576
|
|
14
|
+
MAX_OBJECTS = 1024
|
|
15
|
+
_HEX = re.compile(r'^[a-f0-9]{64}$')
|
|
16
|
+
_KINDS = {
|
|
17
|
+
'schema', 'table', 'column', 'constraint', 'index', 'row-type', 'array-type',
|
|
18
|
+
'toast-table', 'toast-index', 'internal-ri-trigger',
|
|
19
|
+
}
|
|
20
|
+
_RECEIPT_KEYS = {
|
|
21
|
+
'profile', 'providerId', 'installationId', 'storeProfile', 'storeId',
|
|
22
|
+
'reservationDigest', 'creationRequestDigest', 'creationApprovalDigest',
|
|
23
|
+
'targetCustodyDigest', 'schemaOid', 'objects', 'state',
|
|
24
|
+
}
|
|
25
|
+
_RESERVATION_PROFILE = 'umf.row-originals-store-reservation/0.1'
|
|
26
|
+
_RESERVATION_KEYS = {
|
|
27
|
+
'profile', 'reservationId', 'providerId', 'installationId', 'targetCustody',
|
|
28
|
+
'store', 'creationRequestDigest', 'creationApprovalDigest',
|
|
29
|
+
'nativeAuthorityEvidenceDigest', 'configurationDigest', 'custodySequence',
|
|
30
|
+
}
|
|
31
|
+
_OBJECT_KEYS = {
|
|
32
|
+
'classId', 'objectId', 'subId', 'kind', 'qualifiedName',
|
|
33
|
+
'definitionDigest', 'parent',
|
|
34
|
+
}
|
|
35
|
+
_ADDRESS_KEYS = {'classId', 'objectId', 'subId'}
|
|
36
|
+
_KIND_CLASS = {
|
|
37
|
+
'schema': 2615, 'table': 1259, 'column': 1259, 'constraint': 2606,
|
|
38
|
+
'index': 1259, 'row-type': 1247, 'array-type': 1247,
|
|
39
|
+
'toast-table': 1259, 'toast-index': 1259, 'internal-ri-trigger': 2620,
|
|
40
|
+
}
|
|
41
|
+
_FIXED_NOT_NULL_COLUMNS = {
|
|
42
|
+
'row_tables': ('table_token', 'installation_id', 'business_table_oid',
|
|
43
|
+
'business_schema_oid', 'table_binding', 'issued_count',
|
|
44
|
+
'record', 'record_digest'),
|
|
45
|
+
'archives': ('archive_id', 'table_token', 'state', 'values_relation_oid',
|
|
46
|
+
'row_count', 'logical_bytes', 'record', 'record_digest'),
|
|
47
|
+
'issued_instances': ('table_token', 'instance_id'),
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
def _fail(code: str = 'row-originals-creation-receipt-invalid') -> None:
|
|
51
|
+
raise CatalogError(code)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _safe_int(value: Any, low: int, high: int) -> int:
|
|
55
|
+
if type(value) is not int or not low <= value <= high:
|
|
56
|
+
_fail()
|
|
57
|
+
return value
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _uuid(value: Any) -> str:
|
|
61
|
+
if type(value) is not str or len(value) != 36 or value.lower() != value:
|
|
62
|
+
_fail()
|
|
63
|
+
import uuid
|
|
64
|
+
|
|
65
|
+
try:
|
|
66
|
+
if str(uuid.UUID(value)) != value:
|
|
67
|
+
_fail()
|
|
68
|
+
except (ValueError, AttributeError):
|
|
69
|
+
_fail()
|
|
70
|
+
return value
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _digest(value: Any) -> str:
|
|
74
|
+
if type(value) is not str or _HEX.fullmatch(value) is None:
|
|
75
|
+
_fail()
|
|
76
|
+
return value
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def canonical_bytes(value: Any) -> bytes:
|
|
80
|
+
"""Encode the closed JSON subset used by this receipt, with hard bounds."""
|
|
81
|
+
stack: list[tuple[Any, int]] = [(value, 0)]
|
|
82
|
+
nodes = 0
|
|
83
|
+
while stack:
|
|
84
|
+
item, depth = stack.pop()
|
|
85
|
+
nodes += 1
|
|
86
|
+
if nodes > 100_000 or depth > 64:
|
|
87
|
+
_fail('row-originals-creation-receipt-capacity')
|
|
88
|
+
if item is None or type(item) is bool:
|
|
89
|
+
continue
|
|
90
|
+
if type(item) is int:
|
|
91
|
+
if abs(item) > 9_007_199_254_740_991:
|
|
92
|
+
_fail()
|
|
93
|
+
continue
|
|
94
|
+
if type(item) is str:
|
|
95
|
+
try:
|
|
96
|
+
item.encode('utf-8')
|
|
97
|
+
except UnicodeEncodeError:
|
|
98
|
+
_fail()
|
|
99
|
+
if '\x00' in item:
|
|
100
|
+
_fail()
|
|
101
|
+
continue
|
|
102
|
+
if type(item) is list:
|
|
103
|
+
stack.extend((child, depth + 1) for child in item)
|
|
104
|
+
continue
|
|
105
|
+
if type(item) is dict:
|
|
106
|
+
for key, child in item.items():
|
|
107
|
+
if type(key) is not str or not key.isascii():
|
|
108
|
+
_fail()
|
|
109
|
+
stack.append((key, depth + 1))
|
|
110
|
+
stack.append((child, depth + 1))
|
|
111
|
+
continue
|
|
112
|
+
_fail()
|
|
113
|
+
try:
|
|
114
|
+
encoded = json.dumps(value, ensure_ascii=False, sort_keys=True,
|
|
115
|
+
separators=(',', ':'), allow_nan=False).encode('utf-8')
|
|
116
|
+
except (TypeError, ValueError, UnicodeError, RecursionError):
|
|
117
|
+
_fail()
|
|
118
|
+
if len(encoded) > MAX_RECEIPT_BYTES:
|
|
119
|
+
_fail('row-originals-creation-receipt-capacity')
|
|
120
|
+
return encoded
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _constraint_definition(*, kind: str, conrelid: int, confrelid: int,
|
|
124
|
+
conindid: int, conkey: Any, confkey: Any,
|
|
125
|
+
deferrable: bool, deferred: bool, validated: bool,
|
|
126
|
+
enforced: bool, noinherit: bool, period: bool,
|
|
127
|
+
update_action: str, delete_action: str,
|
|
128
|
+
match_type: str, is_local: bool, inh_count: int,
|
|
129
|
+
definition_text: str,
|
|
130
|
+
dependencies: list[dict[str, Any]]) -> dict[str, Any]:
|
|
131
|
+
"""Retain every catalog field used to define a fixed-store constraint."""
|
|
132
|
+
return {
|
|
133
|
+
'contype': kind, 'conrelid': conrelid, 'confrelid': confrelid,
|
|
134
|
+
'conindid': conindid, 'conkey': conkey, 'confkey': confkey,
|
|
135
|
+
'condeferrable': deferrable, 'condeferred': deferred,
|
|
136
|
+
'convalidated': validated, 'conenforced': enforced,
|
|
137
|
+
'connoinherit': noinherit, 'conperiod': period,
|
|
138
|
+
'confupdtype': update_action, 'confdeltype': delete_action,
|
|
139
|
+
'confmatchtype': match_type, 'conislocal': is_local,
|
|
140
|
+
'coninhcount': inh_count, 'definition': definition_text,
|
|
141
|
+
'dependencies': dependencies,
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def _validate_not_null_constraint(*, relation_name: str, constraint_name: str,
|
|
146
|
+
conrelid: int, confrelid: int, conindid: int,
|
|
147
|
+
conkey: Any, confkey: Any, deferrable: bool,
|
|
148
|
+
deferred: bool, validated: bool, enforced: bool,
|
|
149
|
+
noinherit: bool, period: bool, is_local: bool,
|
|
150
|
+
inh_count: int, update_action: str,
|
|
151
|
+
delete_action: str, match_type: str,
|
|
152
|
+
definition_text: str) -> None:
|
|
153
|
+
"""Admit only the PG18 NOT NULL rows emitted by the fixed table DDL."""
|
|
154
|
+
columns = _FIXED_NOT_NULL_COLUMNS.get(relation_name)
|
|
155
|
+
if columns is None:
|
|
156
|
+
_fail('row-originals-creation-catalog-mismatch')
|
|
157
|
+
expected = {f'{relation_name}_{column}_not_null': index
|
|
158
|
+
for index, column in enumerate(columns, 1)}
|
|
159
|
+
attnum = expected.get(constraint_name)
|
|
160
|
+
column = columns[attnum - 1] if attnum is not None else None
|
|
161
|
+
if (attnum is None or conrelid <= 0 or confrelid != 0 or conindid != 0
|
|
162
|
+
or conkey != [attnum] or confkey is not None
|
|
163
|
+
or deferrable or deferred or not validated or not enforced
|
|
164
|
+
or noinherit or period or not is_local or inh_count != 0
|
|
165
|
+
# StoreRelNotNull calls CreateConstraintEntry with spaces for the
|
|
166
|
+
# FK-only catalog fields. Keep this exact PG18 row shape closed.
|
|
167
|
+
or update_action != ' ' or delete_action != ' '
|
|
168
|
+
or match_type != ' '
|
|
169
|
+
or definition_text != f'NOT NULL {column}'):
|
|
170
|
+
_fail('row-originals-creation-catalog-mismatch')
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def _expected_ri_trigger(relation_is_referencing: bool) -> dict[str, int]:
|
|
174
|
+
"""Return PG18's exact function/event pairs for fixed RESTRICT FKs."""
|
|
175
|
+
if relation_is_referencing:
|
|
176
|
+
return {'RI_FKey_check_ins': 5, 'RI_FKey_check_upd': 17}
|
|
177
|
+
return {'RI_FKey_restrict_del': 9, 'RI_FKey_restrict_upd': 17}
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def _expected_fk_trigger_signatures(*, referencing_oid: int,
|
|
181
|
+
referenced_oid: int, index_oid: int,
|
|
182
|
+
constraint_oid: int) -> list[tuple[int, str, int, int, int, int]]:
|
|
183
|
+
"""Return the complete fixed PG18 RI trigger multiset for one FK."""
|
|
184
|
+
return [
|
|
185
|
+
(referencing_oid, 'RI_FKey_check_ins', 5, referenced_oid,
|
|
186
|
+
index_oid, constraint_oid),
|
|
187
|
+
(referencing_oid, 'RI_FKey_check_upd', 17, referenced_oid,
|
|
188
|
+
index_oid, constraint_oid),
|
|
189
|
+
(referenced_oid, 'RI_FKey_restrict_del', 9, referencing_oid,
|
|
190
|
+
index_oid, constraint_oid),
|
|
191
|
+
(referenced_oid, 'RI_FKey_restrict_upd', 17, referencing_oid,
|
|
192
|
+
index_oid, constraint_oid),
|
|
193
|
+
]
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def _validate_fk_trigger_set(observed: list[tuple[int, str, int, int, int, int]],
|
|
197
|
+
*, referencing_oid: int, referenced_oid: int,
|
|
198
|
+
index_oid: int, constraint_oid: int) -> None:
|
|
199
|
+
expected = _expected_fk_trigger_signatures(
|
|
200
|
+
referencing_oid=referencing_oid, referenced_oid=referenced_oid,
|
|
201
|
+
index_oid=index_oid, constraint_oid=constraint_oid)
|
|
202
|
+
if sorted(observed) != sorted(expected):
|
|
203
|
+
_fail('row-originals-creation-ri-trigger-mismatch')
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def _validate_ri_trigger(*, relation_is_referencing: bool, relation_oid: int,
|
|
207
|
+
expected_relation_oid: int, parent_oid: int,
|
|
208
|
+
function_oid: int, function_name: str, function_namespace: int,
|
|
209
|
+
pg_catalog_namespace: int, trigger_type: int,
|
|
210
|
+
enabled: str, internal: bool, trigger_relation: int,
|
|
211
|
+
expected_trigger_relation: int, trigger_index: int,
|
|
212
|
+
expected_index: int, trigger_constraint: int,
|
|
213
|
+
expected_constraint: int, deferrable: bool, deferred: bool,
|
|
214
|
+
argument_count: int, arguments: Any, attributes: Any,
|
|
215
|
+
comment: str | None) -> None:
|
|
216
|
+
expected_functions = _expected_ri_trigger(relation_is_referencing)
|
|
217
|
+
if (relation_oid != expected_relation_oid or not internal or parent_oid != 0
|
|
218
|
+
or enabled != 'O' or trigger_constraint != expected_constraint
|
|
219
|
+
or trigger_relation != expected_trigger_relation
|
|
220
|
+
or trigger_index != expected_index or function_namespace != pg_catalog_namespace
|
|
221
|
+
or expected_functions.get(function_name) != trigger_type
|
|
222
|
+
or type(function_oid) is not int or function_oid <= 0
|
|
223
|
+
or deferrable or deferred or argument_count != 0
|
|
224
|
+
or arguments != b'' or attributes != []
|
|
225
|
+
or comment is not None):
|
|
226
|
+
_fail('row-originals-creation-ri-trigger-mismatch')
|
|
227
|
+
|
|
228
|
+
def _address(value: Any) -> tuple[int, int, int]:
|
|
229
|
+
if type(value) is not dict or set(value) != _ADDRESS_KEYS:
|
|
230
|
+
_fail()
|
|
231
|
+
return (_safe_int(value['classId'], 1, 2**32 - 1),
|
|
232
|
+
_safe_int(value['objectId'], 1, 2**32 - 1),
|
|
233
|
+
_safe_int(value['subId'], 0, 2**32 - 1))
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def _name(value: Any, schema: str, kind: str) -> dict[str, Any]:
|
|
237
|
+
if type(value) is not dict or set(value) != {'schema', 'name', 'member'}:
|
|
238
|
+
_fail()
|
|
239
|
+
actual_schema, name, member = value['schema'], value['name'], value['member']
|
|
240
|
+
allowed_schema = {schema}
|
|
241
|
+
if kind in {'toast-table', 'toast-index'} or (
|
|
242
|
+
kind == 'column' and actual_schema == 'pg_toast'):
|
|
243
|
+
allowed_schema.add('pg_toast')
|
|
244
|
+
try:
|
|
245
|
+
name_size = len(name.encode('utf-8')) if type(name) is str else MAX_RECEIPT_BYTES + 1
|
|
246
|
+
except UnicodeEncodeError:
|
|
247
|
+
_fail()
|
|
248
|
+
if (type(actual_schema) is not str or actual_schema not in allowed_schema
|
|
249
|
+
or type(name) is not str or not name
|
|
250
|
+
or name_size > 63 or '\x00' in name):
|
|
251
|
+
_fail()
|
|
252
|
+
member_kinds = {'column', 'constraint', 'internal-ri-trigger'}
|
|
253
|
+
if kind in member_kinds:
|
|
254
|
+
try:
|
|
255
|
+
member_size = len(member.encode('utf-8')) if type(member) is str else MAX_RECEIPT_BYTES + 1
|
|
256
|
+
except UnicodeEncodeError:
|
|
257
|
+
_fail()
|
|
258
|
+
if (type(member) is not str or not member or member_size > 63 or '\x00' in member):
|
|
259
|
+
_fail()
|
|
260
|
+
elif member is not None:
|
|
261
|
+
_fail()
|
|
262
|
+
return value
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def validate_objects(value: Any, schema: str, schema_oid: int) -> list[dict[str, Any]]:
|
|
266
|
+
if (type(schema) is not str
|
|
267
|
+
or re.fullmatch(r'umf_originals_[a-f0-9]{32}', schema) is None):
|
|
268
|
+
_fail()
|
|
269
|
+
if type(value) is not list or not 1 <= len(value) <= MAX_OBJECTS:
|
|
270
|
+
_fail('row-originals-creation-receipt-capacity')
|
|
271
|
+
_safe_int(schema_oid, 1, 2**32 - 1)
|
|
272
|
+
checked: list[dict[str, Any]] = []
|
|
273
|
+
by_address: dict[tuple[int, int, int], dict[str, Any]] = {}
|
|
274
|
+
previous: tuple[int, int, int] | None = None
|
|
275
|
+
for item in value:
|
|
276
|
+
if type(item) is not dict or set(item) != _OBJECT_KEYS:
|
|
277
|
+
_fail()
|
|
278
|
+
address = _address({key: item[key] for key in _ADDRESS_KEYS})
|
|
279
|
+
if previous is not None and address <= previous:
|
|
280
|
+
_fail()
|
|
281
|
+
previous = address
|
|
282
|
+
kind = item['kind']
|
|
283
|
+
if type(kind) is not str or kind not in _KINDS:
|
|
284
|
+
_fail()
|
|
285
|
+
if address[0] != _KIND_CLASS[kind]:
|
|
286
|
+
_fail()
|
|
287
|
+
_name(item['qualifiedName'], schema, kind)
|
|
288
|
+
_digest(item['definitionDigest'])
|
|
289
|
+
parent = item['parent']
|
|
290
|
+
if parent is not None:
|
|
291
|
+
parent = _address(parent)
|
|
292
|
+
if kind == 'schema':
|
|
293
|
+
if (address[1] != schema_oid or address[2] != 0 or parent is not None
|
|
294
|
+
or item['qualifiedName'] != {'schema': schema, 'name': schema,
|
|
295
|
+
'member': None}):
|
|
296
|
+
_fail()
|
|
297
|
+
elif parent is None:
|
|
298
|
+
_fail()
|
|
299
|
+
normalized = dict(item)
|
|
300
|
+
by_address[address] = normalized
|
|
301
|
+
checked.append(normalized)
|
|
302
|
+
if sum(item['kind'] == 'schema' for item in checked) != 1:
|
|
303
|
+
_fail()
|
|
304
|
+
for item in checked:
|
|
305
|
+
kind = item['kind']
|
|
306
|
+
address = _address({key: item[key] for key in _ADDRESS_KEYS})
|
|
307
|
+
parent = item['parent']
|
|
308
|
+
if kind == 'schema':
|
|
309
|
+
continue
|
|
310
|
+
assert parent is not None
|
|
311
|
+
parent_item = by_address.get(_address(parent))
|
|
312
|
+
if parent_item is None:
|
|
313
|
+
_fail()
|
|
314
|
+
parent_kind = parent_item['kind']
|
|
315
|
+
valid_parent = {
|
|
316
|
+
'table': {'schema'}, 'index': {'table'}, 'column': {'table', 'toast-table'},
|
|
317
|
+
'constraint': {'table'}, 'row-type': {'table'}, 'array-type': {'row-type'},
|
|
318
|
+
'toast-table': {'table'}, 'toast-index': {'toast-table'},
|
|
319
|
+
'internal-ri-trigger': {'constraint'},
|
|
320
|
+
}
|
|
321
|
+
if parent_kind not in valid_parent[kind]:
|
|
322
|
+
_fail()
|
|
323
|
+
if kind == 'toast-table' and item['qualifiedName']['schema'] != 'pg_toast':
|
|
324
|
+
_fail()
|
|
325
|
+
if kind == 'toast-index' and item['qualifiedName']['schema'] != 'pg_toast':
|
|
326
|
+
_fail()
|
|
327
|
+
parent_schema = parent_item['qualifiedName']['schema']
|
|
328
|
+
child_schema = item['qualifiedName']['schema']
|
|
329
|
+
if kind == 'toast-table':
|
|
330
|
+
if parent_schema != schema or child_schema != 'pg_toast':
|
|
331
|
+
_fail()
|
|
332
|
+
elif child_schema != parent_schema:
|
|
333
|
+
_fail()
|
|
334
|
+
# Every edge must eventually terminate at the one root schema.
|
|
335
|
+
seen = {address}
|
|
336
|
+
cursor = parent_item
|
|
337
|
+
while cursor['kind'] != 'schema':
|
|
338
|
+
next_parent = cursor['parent']
|
|
339
|
+
if next_parent is None:
|
|
340
|
+
_fail()
|
|
341
|
+
next_address = _address(next_parent)
|
|
342
|
+
if next_address in seen:
|
|
343
|
+
_fail()
|
|
344
|
+
seen.add(next_address)
|
|
345
|
+
cursor = by_address.get(next_address)
|
|
346
|
+
if cursor is None:
|
|
347
|
+
_fail()
|
|
348
|
+
return checked
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
def validate_receipt(value: Any) -> dict[str, Any]:
|
|
352
|
+
if type(value) is not dict or set(value) != _RECEIPT_KEYS:
|
|
353
|
+
_fail()
|
|
354
|
+
if value['profile'] != RECEIPT_PROFILE or value['state'] != 'created':
|
|
355
|
+
_fail()
|
|
356
|
+
provider = _uuid(value['providerId'])
|
|
357
|
+
_uuid(value['storeId'])
|
|
358
|
+
if value['storeId'] != provider:
|
|
359
|
+
_fail()
|
|
360
|
+
installation = value['installationId']
|
|
361
|
+
try:
|
|
362
|
+
installation_size = len(installation.encode('utf-8')) if type(installation) is str else MAX_RECEIPT_BYTES + 1
|
|
363
|
+
except UnicodeEncodeError:
|
|
364
|
+
_fail()
|
|
365
|
+
if (type(installation) is not str or not installation or '\x00' in installation
|
|
366
|
+
or installation_size > 256):
|
|
367
|
+
_fail()
|
|
368
|
+
if value['storeProfile'] != 'umf.native-row-originals-store/0.1':
|
|
369
|
+
_fail()
|
|
370
|
+
for key in ('reservationDigest', 'creationRequestDigest', 'creationApprovalDigest',
|
|
371
|
+
'targetCustodyDigest'):
|
|
372
|
+
_digest(value[key])
|
|
373
|
+
schema_oid = _safe_int(value['schemaOid'], 1, 2**32 - 1)
|
|
374
|
+
schema = 'umf_originals_' + provider.replace('-', '')
|
|
375
|
+
checked = dict(value)
|
|
376
|
+
checked['objects'] = validate_objects(value['objects'], schema, schema_oid)
|
|
377
|
+
if len(canonical_bytes(checked)) > MAX_RECEIPT_BYTES:
|
|
378
|
+
_fail('row-originals-creation-receipt-capacity')
|
|
379
|
+
return checked
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
def encode_comment(receipt: Any) -> str:
|
|
383
|
+
checked = validate_receipt(receipt)
|
|
384
|
+
encoded = canonical_bytes(checked)
|
|
385
|
+
return COMMENT_PREFIX + encoded.decode('utf-8')
|
|
386
|
+
|
|
387
|
+
|
|
388
|
+
def decode_comment(value: Any) -> dict[str, Any]:
|
|
389
|
+
if type(value) is not str or not value.startswith(COMMENT_PREFIX):
|
|
390
|
+
_fail()
|
|
391
|
+
try:
|
|
392
|
+
if len(value.encode('utf-8')) > MAX_RECEIPT_BYTES:
|
|
393
|
+
_fail('row-originals-creation-receipt-capacity')
|
|
394
|
+
except UnicodeEncodeError:
|
|
395
|
+
_fail()
|
|
396
|
+
payload = value[len(COMMENT_PREFIX):]
|
|
397
|
+
try:
|
|
398
|
+
parsed = json.loads(payload, object_pairs_hook=_no_duplicates)
|
|
399
|
+
except (json.JSONDecodeError, UnicodeDecodeError, CatalogError, RecursionError):
|
|
400
|
+
_fail()
|
|
401
|
+
if canonical_bytes(parsed).decode('utf-8') != payload:
|
|
402
|
+
_fail()
|
|
403
|
+
return validate_receipt(parsed)
|
|
404
|
+
|
|
405
|
+
|
|
406
|
+
def _no_duplicates(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
|
|
407
|
+
result: dict[str, Any] = {}
|
|
408
|
+
for key, value in pairs:
|
|
409
|
+
if key in result:
|
|
410
|
+
_fail()
|
|
411
|
+
result[key] = value
|
|
412
|
+
return result
|
|
413
|
+
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT OR Apache-2.0
|
|
2
|
+
"""Approved migration seeds through Weft; no consumer query or receipt layer."""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
|
|
7
|
+
from .catalog import CatalogError, _cursor, _execute, _q, verify_native_catalog
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _binding(bundle):
|
|
11
|
+
if bundle['source']['format'] != 'json':
|
|
12
|
+
raise CatalogError('seed-json-source-required')
|
|
13
|
+
document=json.loads(bundle['source']['utf8'])
|
|
14
|
+
module=next(m for m in document['modules'] if m['id']==bundle['module'])
|
|
15
|
+
fields={f['id']:f for f in module['elements'] if f['kind']=='field'}
|
|
16
|
+
records={r['id']:r for r in module['elements'] if r['kind']=='record'}
|
|
17
|
+
tables=[]
|
|
18
|
+
for table in bundle['expectedCatalog']['tables']:
|
|
19
|
+
record=records[table['record']['element']]
|
|
20
|
+
primary=next((k for k in record['keys'] if k.get('primary')),None) or next(iter(record['keys']),None)
|
|
21
|
+
if primary is None:
|
|
22
|
+
raise CatalogError('seed-original-key-required')
|
|
23
|
+
logical=lambda ref:fields[ref['element']].get('name',ref['element'])
|
|
24
|
+
tables.append({'logical':[module['namespace'],record.get('name',record['id'])],
|
|
25
|
+
'native':table['name'],'key':[logical(f) for f in primary['fields']],
|
|
26
|
+
'columns':[{'logical':logical(c['field']),'native':c['name'],
|
|
27
|
+
'carrier':fields[c['field']['element']]['scalarType'],
|
|
28
|
+
'nullable':fields[c['field']['element']]['nullability']=='absent-allowed'}
|
|
29
|
+
for c in table['columns']]})
|
|
30
|
+
return {'version':'umf.raw-read-binding/0.1','schema':bundle['configuration']['schema'],
|
|
31
|
+
'modelJson':bundle['source']['utf8'],'modelSha256':bundle['sourceDigest'],
|
|
32
|
+
'tables':tables,'relationships':[],
|
|
33
|
+
'nativeLifecycle':{'version':'umf.table-lifecycle/0.1','module':bundle['module'],
|
|
34
|
+
'configurationDigest':bundle['configurationDigest'],
|
|
35
|
+
'deploymentDigest':bundle['bundleDigest']}}
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _apply_seeds(connection,plan,*,statement_timeout_ms,lock_timeout_ms):
|
|
39
|
+
"""Called only inside the approved owner's locked migration savepoint.
|
|
40
|
+
|
|
41
|
+
Disabling RLS is scoped to source-selected tables and this transaction.
|
|
42
|
+
PostgreSQL constraints remain active. On failure/cancellation the enclosing
|
|
43
|
+
migration savepoint restores schema, policies, rows and ledger together.
|
|
44
|
+
"""
|
|
45
|
+
execution=plan['seedExecution']
|
|
46
|
+
if execution=='none':
|
|
47
|
+
return
|
|
48
|
+
if type(execution) is not dict or execution.get('version')!='umf.table-seed-execution/0.1':
|
|
49
|
+
raise CatalogError('seed-execution-profile')
|
|
50
|
+
from weft import compile_table_seed_json
|
|
51
|
+
|
|
52
|
+
bundle=plan['next'];binding=_binding(bundle)
|
|
53
|
+
request={'version':'weft.table-seed/0.1','target':'postgresql18','module':bundle['module'],
|
|
54
|
+
'binding':binding,'seedSets':execution['sets']}
|
|
55
|
+
program=json.loads(compile_table_seed_json(json.dumps(request,ensure_ascii=False,separators=(',',':'))))
|
|
56
|
+
if (program.get('version')!='weft.table-seed/0.1' or program.get('status')!='compiled'
|
|
57
|
+
or program.get('module')!=bundle['module'] or program.get('schema')!=binding['schema']
|
|
58
|
+
or program.get('sourceDigest')!=bundle['sourceDigest']
|
|
59
|
+
or program.get('nativeLifecycle')!=binding['nativeLifecycle']
|
|
60
|
+
or program.get('seedSets')!=execution['sets']
|
|
61
|
+
or program.get('transport')!={'profile':'dbapi-percent/0.1','bindEmptyParameterTuple':True}
|
|
62
|
+
or program.get('obligations')!={'authority':'approved-source-selected-administrative-seed',
|
|
63
|
+
'transaction':'entire-migration','rowOrder':'authored',
|
|
64
|
+
'rls':'installer-owner-scoped-disable-and-restore','automaticRetry':False,
|
|
65
|
+
'nativeExecutionQualified':False}):
|
|
66
|
+
raise CatalogError('seed-compilation-refused')
|
|
67
|
+
selected={s['id']:s for s in bundle['seedSets']}
|
|
68
|
+
expected=sum(len(selected[s]['rows']) for s in execution['sets'])
|
|
69
|
+
names={t['name'] for t in bundle['expectedCatalog']['tables']}
|
|
70
|
+
steps=program['steps'];offset=0
|
|
71
|
+
for step in steps:
|
|
72
|
+
count=step['sourceRows']['count']
|
|
73
|
+
if (type(count) is not int or not 1<=count<=1000 or step['sourceRows']['start']!=offset
|
|
74
|
+
or step['maxEffects']!=count or step['table'] not in names
|
|
75
|
+
or step['parameterOrder'] not in ([],['nativeRows'])
|
|
76
|
+
or step['dbapiParameterOrder']!=step['parameterOrder']):
|
|
77
|
+
raise CatalogError('seed-execution-profile')
|
|
78
|
+
offset+=count
|
|
79
|
+
if offset!=expected or program['sourceRowCount']!=expected:
|
|
80
|
+
raise CatalogError('seed-execution-profile')
|
|
81
|
+
touched=sorted({s['table'] for s in steps})
|
|
82
|
+
relations=[_q(binding['schema'])+'.'+_q(name) for name in touched]
|
|
83
|
+
for relation in relations:
|
|
84
|
+
_execute(connection,'ALTER TABLE '+relation+' DISABLE ROW LEVEL SECURITY')
|
|
85
|
+
for step in steps:
|
|
86
|
+
parameters=() if not step['parameterOrder'] else (json.dumps(step['nativeRows'],ensure_ascii=False,separators=(',',':')),)
|
|
87
|
+
with _cursor(connection) as cursor:
|
|
88
|
+
cursor.execute(step['dbapiSql'],parameters)
|
|
89
|
+
if [c[0] for c in cursor.description]!=['umf_seed_count']:
|
|
90
|
+
raise CatalogError('seed-result-profile')
|
|
91
|
+
rows=cursor.fetchall()
|
|
92
|
+
if (len(rows)!=1 or len(rows[0])!=1 or type(rows[0][0]) is not str
|
|
93
|
+
or not rows[0][0].isascii() or not rows[0][0].isdigit()
|
|
94
|
+
or not 0<=int(rows[0][0])<=step['maxEffects']):
|
|
95
|
+
raise CatalogError('seed-result-profile')
|
|
96
|
+
for relation in relations:
|
|
97
|
+
_execute(connection,'ALTER TABLE '+relation+' ENABLE ROW LEVEL SECURITY')
|
|
98
|
+
_execute(connection,'ALTER TABLE '+relation+' FORCE ROW LEVEL SECURITY')
|
|
99
|
+
verify_native_catalog(connection,bundle,statement_timeout_ms=statement_timeout_ms,lock_timeout_ms=lock_timeout_ms)
|