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,759 @@
1
+ # SPDX-License-Identifier: MIT OR Apache-2.0
2
+ """Fixed native inventory and public creation receipt for the G04 store.
3
+
4
+ The receipt is deliberately only a catalog witness. Original custody remains
5
+ in the external supervisor/custodian registry and is required separately.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import base64
10
+ import hashlib
11
+ from typing import Any
12
+
13
+ from . import row_originals_receipt as _row_originals_receipt
14
+ from .catalog import CatalogError, _all, _one
15
+
16
+ COMMENT_PREFIX = _row_originals_receipt.COMMENT_PREFIX
17
+ MAX_OBJECTS = _row_originals_receipt.MAX_OBJECTS
18
+ MAX_RECEIPT_BYTES = _row_originals_receipt.MAX_RECEIPT_BYTES
19
+ RECEIPT_PROFILE = _row_originals_receipt.RECEIPT_PROFILE
20
+ _FIXED_NOT_NULL_COLUMNS = _row_originals_receipt._FIXED_NOT_NULL_COLUMNS
21
+ _constraint_definition = _row_originals_receipt._constraint_definition
22
+ _digest = _row_originals_receipt._digest
23
+ _expected_fk_trigger_signatures = _row_originals_receipt._expected_fk_trigger_signatures
24
+ _expected_ri_trigger = _row_originals_receipt._expected_ri_trigger
25
+ _no_duplicates = _row_originals_receipt._no_duplicates
26
+ _safe_int = _row_originals_receipt._safe_int
27
+ _uuid = _row_originals_receipt._uuid
28
+ _validate_fk_trigger_set = _row_originals_receipt._validate_fk_trigger_set
29
+ _validate_not_null_constraint = _row_originals_receipt._validate_not_null_constraint
30
+ _validate_ri_trigger = _row_originals_receipt._validate_ri_trigger
31
+ canonical_bytes = _row_originals_receipt.canonical_bytes
32
+ decode_comment = _row_originals_receipt.decode_comment
33
+ encode_comment = _row_originals_receipt.encode_comment
34
+ validate_objects = _row_originals_receipt.validate_objects
35
+ validate_receipt = _row_originals_receipt.validate_receipt
36
+
37
+
38
+ def _fail(code: str = 'row-originals-creation-receipt-invalid') -> None:
39
+ raise CatalogError(code)
40
+
41
+
42
+
43
+ def _native(value: Any) -> Any:
44
+ if isinstance(value, bytes):
45
+ return {'$bytesBase64Url': base64.urlsafe_b64encode(value).rstrip(b'=').decode('ascii')}
46
+ if isinstance(value, tuple):
47
+ return [_native(item) for item in value]
48
+ if isinstance(value, list):
49
+ return [_native(item) for item in value]
50
+ if isinstance(value, dict):
51
+ return {str(key): _native(item) for key, item in value.items()}
52
+ if value is None or type(value) in (str, int, bool):
53
+ return value
54
+ _fail('row-originals-creation-catalog-unsupported')
55
+
56
+
57
+ def _dependencies(connection: Any, class_id: int, object_id: int,
58
+ sub_id: int = 0) -> list[list[Any]]:
59
+ rows = _all(connection, '''SELECT classid::pg_catalog.oid,objid::pg_catalog.oid,objsubid,
60
+ refclassid::pg_catalog.oid,refobjid::pg_catalog.oid,refobjsubid,deptype
61
+ FROM pg_catalog.pg_depend WHERE classid=%s AND objid=%s AND objsubid=%s
62
+ ORDER BY classid,objid,objsubid,refclassid,refobjid,refobjsubid,deptype LIMIT 1025''',
63
+ (class_id, object_id, sub_id))
64
+ if len(rows) > MAX_OBJECTS:
65
+ _fail('row-originals-creation-receipt-capacity')
66
+ return [_native(row) for row in rows]
67
+
68
+
69
+ def _column_address(classes: dict[str, int], relation_oid: int,
70
+ attnum: int) -> dict[str, int]:
71
+ """Use pg_class/relation OID plus pg_depend's column-number sub-ID."""
72
+ return {'classId': classes['pg_class'], 'objectId': relation_oid, 'subId': attnum}
73
+
74
+
75
+ def _column_dependencies(connection: Any, classes: dict[str, int],
76
+ relation_oid: int, attnum: int) -> list[list[Any]]:
77
+ address = _column_address(classes, relation_oid, attnum)
78
+ return _dependencies(connection, address['classId'], address['objectId'],
79
+ address['subId'])
80
+
81
+
82
+ def _catalog_class_oids(connection: Any) -> dict[str, int]:
83
+ rows = _all(connection, '''SELECT c.relname,c.oid::pg_catalog.oid
84
+ FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid=c.relnamespace
85
+ WHERE n.nspname='pg_catalog' AND c.relname=ANY(%s)''',
86
+ (['pg_class', 'pg_namespace', 'pg_constraint', 'pg_type', 'pg_trigger'],))
87
+ result = dict(rows)
88
+ if set(result) != {'pg_class', 'pg_namespace', 'pg_constraint', 'pg_type', 'pg_trigger'}:
89
+ _fail('row-originals-creation-catalog-unsupported')
90
+ return result
91
+
92
+
93
+ def _add_object(output: list[dict[str, Any]], *, class_id: int, object_id: int,
94
+ sub_id: int, kind: str, schema: str, name: str,
95
+ member: str | None, parent: dict[str, int] | None,
96
+ definition: Any) -> dict[str, int]:
97
+ if len(output) >= MAX_OBJECTS:
98
+ _fail('row-originals-creation-receipt-capacity')
99
+ address = {'classId': int(class_id), 'objectId': int(object_id), 'subId': int(sub_id)}
100
+ object_record = {
101
+ **address, 'kind': kind,
102
+ 'qualifiedName': {'schema': schema, 'name': name, 'member': member},
103
+ 'definitionDigest': hashlib.sha256(canonical_bytes(_native(definition))).hexdigest(),
104
+ 'parent': parent,
105
+ }
106
+ output.append(object_record)
107
+ return address
108
+
109
+
110
+ def observe_creation_objects(connection: Any, schema: str, schema_oid: int,
111
+ controller_oid: int) -> list[dict[str, Any]]:
112
+ """Observe the exact fixed G04 store's created objects and native closure.
113
+
114
+ This function refuses anything outside the three-table .1 constructor,
115
+ including unmanaged triggers, parentless TOAST objects, and foreign RI
116
+ triggers. Native acceptance still requires real PG18.6 execution.
117
+ """
118
+ if (type(schema) is not str or not schema.startswith('umf_originals_')
119
+ or '\x00' in schema):
120
+ _fail('row-originals-creation-catalog-unsupported')
121
+ classes = _catalog_class_oids(connection)
122
+ ns = _one(connection, '''SELECT n.oid::pg_catalog.oid,n.nspowner::pg_catalog.oid,
123
+ pg_catalog.current_setting('server_version_num')::pg_catalog.int4
124
+ FROM pg_catalog.pg_namespace n WHERE n.nspname=%s''', (schema,))
125
+ if ns is None or ns[0] != schema_oid or ns[1] != controller_oid or ns[2] != 180006:
126
+ _fail('row-originals-creation-catalog-mismatch')
127
+ output: list[dict[str, Any]] = []
128
+ schema_address = _add_object(
129
+ output, class_id=classes['pg_namespace'], object_id=schema_oid, sub_id=0,
130
+ kind='schema', schema=schema, name=schema, member=None, parent=None,
131
+ definition={
132
+ 'owner': ns[1],
133
+ 'acl': _all(connection, '''SELECT acl.grantee::pg_catalog.oid,
134
+ acl.grantor::pg_catalog.oid,acl.privilege_type,acl.is_grantable
135
+ FROM pg_catalog.pg_namespace n CROSS JOIN LATERAL pg_catalog.aclexplode(
136
+ COALESCE(n.nspacl,pg_catalog.acldefault('n',n.nspowner))) acl WHERE n.oid=%s
137
+ ORDER BY acl.grantee,acl.grantor,acl.privilege_type,acl.is_grantable''', (schema_oid,)),
138
+ 'dependencies': _dependencies(connection, classes['pg_namespace'], schema_oid),
139
+ })
140
+
141
+ relation_rows = _all(connection, '''SELECT c.oid::pg_catalog.oid,c.relname,n.nspname,
142
+ c.relkind,c.relpersistence,c.relowner::pg_catalog.oid,c.relam::pg_catalog.oid,
143
+ c.reltablespace::pg_catalog.oid,c.reloptions,c.relrowsecurity,c.relforcerowsecurity,
144
+ c.relispartition,c.relhassubclass,c.relhasrules,c.relreplident,c.reltoastrelid::pg_catalog.oid,
145
+ c.reltype::pg_catalog.oid,c.relacl,pg_catalog.obj_description(c.oid,'pg_class')
146
+ FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid=c.relnamespace
147
+ WHERE n.nspname=%s ORDER BY c.oid LIMIT 1025''', (schema,))
148
+ if len(relation_rows) > MAX_OBJECTS:
149
+ _fail('row-originals-creation-receipt-capacity')
150
+ table_names = {'row_tables', 'archives', 'issued_instances'}
151
+ # A schema containing an extra view, sequence, materialized view, or
152
+ # unowned index is not the fixed constructor, even if the three expected
153
+ # heaps are also present.
154
+ if any(row[3] not in ('r', 'i') for row in relation_rows):
155
+ _fail('row-originals-creation-catalog-mismatch')
156
+ base_rows = [row for row in relation_rows if row[3] == 'r']
157
+ if {row[1] for row in base_rows} != table_names:
158
+ _fail('row-originals-creation-catalog-mismatch')
159
+ by_relation_oid: dict[int, dict[str, Any]] = {}
160
+ expected_index_names = {
161
+ 'row_tables': {'row_tables_pkey', 'row_tables_business_table_oid_key'},
162
+ 'archives': {'archives_pkey', 'archives_values_relation_oid_key'},
163
+ 'issued_instances': {'issued_instances_pkey'},
164
+ }
165
+ indexes_by_table_name: dict[str, set[str]] = {name: set() for name in table_names}
166
+ for row in base_rows:
167
+ (oid, name, _ns, _kind, persistence, owner, access_method, tablespace,
168
+ options, row_security, force_rls, partitioned, has_subclasses, has_rules,
169
+ replica_identity, toast_oid, row_type_oid, _acl, comment) = row
170
+ if (persistence != 'p' or owner != controller_oid or row_security or force_rls
171
+ or partitioned or has_subclasses or has_rules or comment is not None):
172
+ _fail('row-originals-creation-catalog-mismatch')
173
+ acl = _all(connection, '''SELECT acl.grantee::pg_catalog.oid,
174
+ acl.grantor::pg_catalog.oid,acl.privilege_type,acl.is_grantable
175
+ FROM pg_catalog.pg_class c CROSS JOIN LATERAL pg_catalog.aclexplode(
176
+ COALESCE(c.relacl,pg_catalog.acldefault('r',c.relowner))) acl WHERE c.oid=%s
177
+ ORDER BY acl.grantee,acl.grantor,acl.privilege_type,acl.is_grantable''', (oid,))
178
+ index_rows = _all(connection, '''SELECT i.indexrelid::pg_catalog.oid
179
+ FROM pg_catalog.pg_index i WHERE i.indrelid=%s ORDER BY i.indexrelid LIMIT 1025''', (oid,))
180
+ if len(index_rows) > MAX_OBJECTS:
181
+ _fail('row-originals-creation-receipt-capacity')
182
+ index_ids = [item[0] for item in index_rows]
183
+ definition = {
184
+ 'relkind': 'r', 'persistence': persistence, 'owner': owner,
185
+ 'accessMethod': access_method, 'tablespace': tablespace,
186
+ 'options': options, 'rowSecurity': row_security,
187
+ 'forceRowSecurity': force_rls, 'partitioned': partitioned,
188
+ 'hasSubclasses': has_subclasses, 'hasRules': has_rules,
189
+ 'replicaIdentity': replica_identity, 'toastRelationOid': toast_oid,
190
+ 'rowTypeOid': row_type_oid, 'acl': acl,
191
+ 'indexes': index_ids,
192
+ 'dependencies': _dependencies(connection, classes['pg_class'], oid),
193
+ }
194
+ address = _add_object(output, class_id=classes['pg_class'], object_id=oid,
195
+ sub_id=0, kind='table', schema=schema, name=name,
196
+ member=None, parent=schema_address, definition=definition)
197
+ by_relation_oid[oid] = {'row': row, 'address': address, 'indexes': index_ids}
198
+
199
+ # Reject additional indexes not owned by one of the three fixed heaps.
200
+ expected_index_ids = {index_oid for info in by_relation_oid.values()
201
+ for index_oid in info['indexes']}
202
+ actual_index_ids = {row[0] for row in relation_rows if row[3] == 'i'}
203
+ if actual_index_ids != expected_index_ids:
204
+ _fail('row-originals-creation-catalog-mismatch')
205
+
206
+ # Constraint records also define the exact expected internal FK-trigger set.
207
+ constraints_by_oid: dict[int, dict[str, Any]] = {}
208
+ fk_rows: list[tuple[Any, ...]] = []
209
+ for relation_oid, info in by_relation_oid.items():
210
+ relation_name = info['row'][1]
211
+ rows = _all(connection, '''SELECT co.oid::pg_catalog.oid,co.conname,co.contype,
212
+ co.conrelid::pg_catalog.oid,co.confrelid::pg_catalog.oid,co.conindid::pg_catalog.oid,
213
+ co.conkey,co.confkey,co.condeferrable,co.condeferred,co.convalidated,co.conenforced,
214
+ co.connoinherit,co.conperiod,co.confupdtype,co.confdeltype,co.confmatchtype,
215
+ co.conislocal,co.coninhcount,pg_catalog.pg_get_constraintdef(co.oid,true),
216
+ pg_catalog.obj_description(co.oid,'pg_constraint')
217
+ FROM pg_catalog.pg_constraint co WHERE co.conrelid=%s ORDER BY co.oid LIMIT 1025''', (relation_oid,))
218
+ if len(rows) > MAX_OBJECTS:
219
+ _fail('row-originals-creation-receipt-capacity')
220
+ for row in rows:
221
+ (oid, name, kind, conrelid, confrelid, conindid, conkey, confkey,
222
+ deferrable, deferred, validated, enforced, noinherit, period,
223
+ update_action, delete_action, match_type, is_local, inh_count,
224
+ definition_text, comment) = row
225
+ if comment is not None or conrelid != relation_oid:
226
+ _fail('row-originals-creation-catalog-mismatch')
227
+ if kind == 'n':
228
+ _validate_not_null_constraint(
229
+ relation_name=relation_name, constraint_name=name,
230
+ conrelid=conrelid, confrelid=confrelid, conindid=conindid,
231
+ conkey=conkey, confkey=confkey, deferrable=deferrable,
232
+ deferred=deferred, validated=validated, enforced=enforced,
233
+ noinherit=noinherit, period=period, is_local=is_local,
234
+ inh_count=inh_count, update_action=update_action,
235
+ delete_action=delete_action, match_type=match_type,
236
+ definition_text=definition_text)
237
+ # These FK-only char fields are catalog NULs for a NOT NULL row.
238
+ update_action = delete_action = match_type = None
239
+ elif kind not in {'p', 'u', 'c', 'f'}:
240
+ _fail('row-originals-creation-catalog-mismatch')
241
+ if kind == 'f' and (update_action != 'r' or delete_action != 'r'
242
+ or match_type != 's' or deferrable or deferred
243
+ or not validated or not enforced or noinherit
244
+ or period or not is_local or inh_count != 0):
245
+ _fail('row-originals-creation-catalog-mismatch')
246
+ definition = _constraint_definition(
247
+ kind=kind, conrelid=conrelid, confrelid=confrelid,
248
+ conindid=conindid, conkey=conkey, confkey=confkey,
249
+ deferrable=deferrable, deferred=deferred, validated=validated,
250
+ enforced=enforced, noinherit=noinherit, period=period,
251
+ update_action=update_action, delete_action=delete_action,
252
+ match_type=match_type, is_local=is_local, inh_count=inh_count,
253
+ definition_text=definition_text,
254
+ dependencies=_dependencies(connection, classes['pg_constraint'], oid))
255
+ address = _add_object(output, class_id=classes['pg_constraint'], object_id=oid,
256
+ sub_id=0, kind='constraint', schema=schema,
257
+ name=relation_name, member=name,
258
+ parent=info['address'], definition=definition)
259
+ constraints_by_oid[oid] = {'row': row, 'address': address}
260
+ if kind == 'f':
261
+ fk_rows.append(row)
262
+
263
+ expected_constraint_names = {
264
+ 'row_tables': {
265
+ 'row_tables_pkey', 'row_tables_business_table_oid_key',
266
+ 'row_tables_installation_id_check', 'row_tables_issued_count_check',
267
+ 'row_tables_record_check', 'row_tables_record_digest_check',
268
+ *(f'row_tables_{column}_not_null'
269
+ for column in _FIXED_NOT_NULL_COLUMNS['row_tables']),
270
+ },
271
+ 'archives': {
272
+ 'archives_pkey', 'archives_values_relation_oid_key',
273
+ 'archives_table_token_fkey', 'archives_state_check',
274
+ 'archives_row_count_check', 'archives_logical_bytes_check',
275
+ 'archives_record_check', 'archives_record_digest_check',
276
+ *(f'archives_{column}_not_null'
277
+ for column in _FIXED_NOT_NULL_COLUMNS['archives']),
278
+ },
279
+ 'issued_instances': {
280
+ 'issued_instances_pkey', 'issued_instances_table_token_fkey',
281
+ *(f'issued_instances_{column}_not_null'
282
+ for column in _FIXED_NOT_NULL_COLUMNS['issued_instances']),
283
+ },
284
+ }
285
+ if ({info['row'][1]: {entry['row'][1] for entry in constraints_by_oid.values()
286
+ if entry['row'][3] == oid}
287
+ for oid, info in by_relation_oid.items()} != expected_constraint_names):
288
+ _fail('row-originals-creation-catalog-mismatch')
289
+
290
+ index_ids_by_rel: dict[int, list[int]] = {}
291
+ for relation_oid in by_relation_oid:
292
+ index_ids_by_rel[relation_oid] = []
293
+ index_rows = _all(connection, '''SELECT i.indexrelid::pg_catalog.oid,
294
+ ic.relname,ic.relnamespace::pg_catalog.oid,ic.relowner::pg_catalog.oid,
295
+ ic.relpersistence,ic.reltablespace::pg_catalog.oid,ic.reloptions,ic.relacl,
296
+ i.indnatts,i.indnkeyatts,i.indisunique,i.indisprimary,i.indisexclusion,
297
+ i.indimmediate,i.indisvalid,i.indcheckxmin,i.indisready,i.indislive,
298
+ i.indisreplident,i.indnullsnotdistinct,i.indkey::pg_catalog.int2[],
299
+ i.indclass::pg_catalog.oid[],i.indcollation::pg_catalog.oid[],
300
+ i.indoption::pg_catalog.int2[],pg_catalog.pg_get_expr(i.indexprs,i.indrelid),
301
+ pg_catalog.pg_get_expr(i.indpred,i.indrelid),am.amname,
302
+ pg_catalog.pg_get_indexdef(i.indexrelid),pg_catalog.obj_description(ic.oid,'pg_class')
303
+ FROM pg_catalog.pg_index i JOIN pg_catalog.pg_class ic ON ic.oid=i.indexrelid
304
+ JOIN pg_catalog.pg_am am ON am.oid=ic.relam WHERE i.indrelid=%s ORDER BY i.indexrelid LIMIT 1025''',
305
+ (relation_oid,))
306
+ if len(index_rows) > MAX_OBJECTS:
307
+ _fail('row-originals-creation-receipt-capacity')
308
+ for row in index_rows:
309
+ (oid, name, namespace_oid, owner, persistence, tablespace, options, _acl,
310
+ natts, nkeyatts, unique, primary, exclusion, immediate, valid, checkxmin,
311
+ ready, live, replica, nullsnotdistinct, indkey, indclass, indcollation,
312
+ indoption, expressions, predicate, access_method, definition_text, comment) = row
313
+ if (namespace_oid != _one(connection, 'SELECT oid FROM pg_catalog.pg_namespace WHERE nspname=%s',
314
+ (schema,))[0]
315
+ or owner != controller_oid or persistence != 'p' or comment is not None):
316
+ _fail('row-originals-creation-catalog-mismatch')
317
+ indexes_by_table_name[by_relation_oid[relation_oid]['row'][1]].add(name)
318
+ acl = _all(connection, '''SELECT acl.grantee::pg_catalog.oid,
319
+ acl.grantor::pg_catalog.oid,acl.privilege_type,acl.is_grantable
320
+ FROM pg_catalog.pg_class c CROSS JOIN LATERAL pg_catalog.aclexplode(
321
+ COALESCE(c.relacl,pg_catalog.acldefault('r',c.relowner))) acl WHERE c.oid=%s
322
+ ORDER BY acl.grantee,acl.grantor,acl.privilege_type,acl.is_grantable''', (oid,))
323
+ definition = {
324
+ 'owner': owner, 'persistence': persistence, 'tablespace': tablespace,
325
+ 'options': options, 'acl': acl, 'indnatts': natts,
326
+ 'indnkeyatts': nkeyatts, 'indisunique': unique, 'indisprimary': primary,
327
+ 'indisexclusion': exclusion, 'indimmediate': immediate,
328
+ 'indisvalid': valid, 'indcheckxmin': checkxmin, 'indisready': ready,
329
+ 'indislive': live, 'indisreplident': replica,
330
+ 'indnullsnotdistinct': nullsnotdistinct, 'indkey': indkey,
331
+ 'indclass': indclass, 'indcollation': indcollation,
332
+ 'indoption': indoption, 'expressions': expressions,
333
+ 'predicate': predicate, 'accessMethod': access_method,
334
+ 'definition': definition_text,
335
+ 'dependencies': _dependencies(connection, classes['pg_class'], oid),
336
+ }
337
+ _add_object(output, class_id=classes['pg_class'], object_id=oid, sub_id=0,
338
+ kind='index', schema=schema, name=name, member=None,
339
+ parent=by_relation_oid[relation_oid]['address'], definition=definition)
340
+ index_ids_by_rel[relation_oid].append(oid)
341
+
342
+ if indexes_by_table_name != expected_index_names:
343
+ _fail('row-originals-creation-catalog-mismatch')
344
+
345
+ # User columns and their auto-created composite row and array types.
346
+ row_type_addresses: dict[int, dict[str, int]] = {}
347
+ for relation_oid, info in by_relation_oid.items():
348
+ name = info['row'][1]
349
+ columns = _all(connection, '''SELECT a.attnum,a.attname,a.attisdropped,
350
+ a.atttypid::pg_catalog.oid,a.atttypmod,a.attnotnull,a.attcollation::pg_catalog.oid,
351
+ a.attidentity,a.attgenerated,a.attstorage,a.attcompression,a.attoptions,a.attacl,
352
+ a.attinhcount,a.attislocal,a.attstattarget,
353
+ pg_catalog.pg_get_expr(d.adbin,d.adrelid),pg_catalog.col_description(a.attrelid,a.attnum)
354
+ FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_attrdef d
355
+ ON d.adrelid=a.attrelid AND d.adnum=a.attnum
356
+ WHERE a.attrelid=%s AND a.attnum>0 ORDER BY a.attnum LIMIT 1025''', (relation_oid,))
357
+ if len(columns) > MAX_OBJECTS:
358
+ _fail('row-originals-creation-receipt-capacity')
359
+ for row in columns:
360
+ (attnum, column, dropped, type_oid, typmod, notnull, collation,
361
+ identity, generated, storage, compression, options, acl,
362
+ inhcount, islocal, stattarget, default_expr, comment) = row
363
+ if dropped or comment is not None:
364
+ _fail('row-originals-creation-catalog-mismatch')
365
+ address = _column_address(classes, relation_oid, attnum)
366
+ definition = {
367
+ 'attnum': attnum, 'name': column, 'typeOid': type_oid,
368
+ 'typeMod': typmod, 'notNull': notnull, 'collationOid': collation,
369
+ 'identity': identity, 'generated': generated, 'storage': storage,
370
+ 'compression': compression, 'options': options, 'acl': acl,
371
+ 'inheritanceCount': inhcount, 'isLocal': islocal,
372
+ 'statisticsTarget': stattarget, 'default': default_expr,
373
+ 'dependencies': _column_dependencies(connection, classes,
374
+ relation_oid, attnum),
375
+ }
376
+ _add_object(output, class_id=address['classId'], object_id=address['objectId'],
377
+ sub_id=address['subId'], kind='column', schema=schema, name=name,
378
+ member=column, parent=info['address'], definition=definition)
379
+ row_type_oid = info['row'][16]
380
+ if row_type_oid:
381
+ type_address = _add_type_object(
382
+ connection, output, classes, row_type_oid, schema, name,
383
+ 'row-type', info['address'])
384
+ row_type_addresses[row_type_oid] = type_address
385
+ type_row = _one(connection, '''SELECT typarray::pg_catalog.oid
386
+ FROM pg_catalog.pg_type WHERE oid=%s''', (row_type_oid,))
387
+ if type_row is None:
388
+ _fail('row-originals-creation-catalog-mismatch')
389
+ array_oid = type_row[0]
390
+ if array_oid:
391
+ _add_type_object(connection, output, classes, array_oid, schema,
392
+ '_' + name, 'array-type', type_address)
393
+
394
+ # Exact PostgreSQL TOAST child closure; no schema-name prefix inference.
395
+ toast_by_oid: dict[int, dict[str, Any]] = {}
396
+ for relation_oid, info in by_relation_oid.items():
397
+ toast_oid = info['row'][15]
398
+ if toast_oid == 0:
399
+ continue
400
+ toast = _one(connection, '''SELECT c.oid::pg_catalog.oid,c.relname,n.nspname,
401
+ c.relkind,c.relpersistence,c.relowner::pg_catalog.oid,c.relam::pg_catalog.oid,
402
+ c.reltablespace::pg_catalog.oid,c.reloptions,c.relrowsecurity,c.relforcerowsecurity,
403
+ c.relispartition,c.relhassubclass,c.relhasrules,c.relreplident,
404
+ c.reltoastrelid::pg_catalog.oid,c.reltype::pg_catalog.oid,c.relacl,
405
+ pg_catalog.obj_description(c.oid,'pg_class')
406
+ FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid=c.relnamespace
407
+ WHERE c.oid=%s''', (toast_oid,))
408
+ if (toast is None or toast[2] != 'pg_toast' or toast[3] != 't'
409
+ or toast[1] != 'pg_toast_' + str(relation_oid)
410
+ or toast[4] != 'p' or toast[5] != controller_oid
411
+ or toast[6] != _one(connection, "SELECT oid FROM pg_catalog.pg_am WHERE amname='heap'")[0]
412
+ or toast[7] != 0 or toast[8] is not None or toast[9] or toast[10]
413
+ or toast[11] or toast[12] or toast[13] or toast[14] != 'd'
414
+ or toast[15] != 0 or toast[16] != 0 or toast[18] is not None):
415
+ _fail('row-originals-creation-toast-mismatch')
416
+ toast_acl = _all(connection, '''SELECT acl.grantee::pg_catalog.oid,
417
+ acl.grantor::pg_catalog.oid,acl.privilege_type,acl.is_grantable
418
+ FROM pg_catalog.pg_class c CROSS JOIN LATERAL pg_catalog.aclexplode(
419
+ COALESCE(c.relacl,pg_catalog.acldefault('r',c.relowner))) acl WHERE c.oid=%s
420
+ ORDER BY acl.grantee,acl.grantor,acl.privilege_type,acl.is_grantable''', (toast_oid,))
421
+ toast_definition = {
422
+ 'relkind': toast[3], 'persistence': toast[4], 'owner': toast[5],
423
+ 'accessMethod': toast[6], 'tablespace': toast[7], 'options': toast[8],
424
+ 'rowSecurity': toast[9], 'forceRowSecurity': toast[10],
425
+ 'partitioned': toast[11], 'hasSubclasses': toast[12],
426
+ 'hasRules': toast[13], 'replicaIdentity': toast[14],
427
+ 'reltoastrelid': toast[15], 'reltype': toast[16], 'acl': toast_acl,
428
+ 'dependencies': _dependencies(connection, classes['pg_class'], toast_oid),
429
+ }
430
+ toast_address = _add_object(
431
+ output, class_id=classes['pg_class'], object_id=toast_oid, sub_id=0,
432
+ kind='toast-table', schema='pg_toast', name=toast[1], member=None,
433
+ parent=info['address'], definition=toast_definition)
434
+ toast_by_oid[toast_oid] = {'row': toast, 'address': toast_address}
435
+ toast_columns = _all(connection, '''SELECT a.attnum,a.attname,a.attisdropped,
436
+ a.atttypid::pg_catalog.oid,a.atttypmod,a.attnotnull,a.attcollation::pg_catalog.oid,
437
+ a.attidentity,a.attgenerated,a.attstorage,a.attcompression,a.attoptions,a.attacl,
438
+ a.attinhcount,a.attislocal,a.attstattarget,
439
+ pg_catalog.pg_get_expr(d.adbin,d.adrelid),pg_catalog.col_description(a.attrelid,a.attnum)
440
+ FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_attrdef d
441
+ ON d.adrelid=a.attrelid AND d.adnum=a.attnum
442
+ WHERE a.attrelid=%s AND a.attnum>0 ORDER BY a.attnum LIMIT 4''', (toast_oid,))
443
+ if len(toast_columns) != 3:
444
+ _fail('row-originals-creation-toast-mismatch')
445
+ expected_toast_columns = (('chunk_id', 26), ('chunk_seq', 23), ('chunk_data', 17))
446
+ for row, (expected_name, expected_type) in zip(toast_columns, expected_toast_columns,
447
+ strict=True):
448
+ (attnum, column, dropped, type_oid, typmod, notnull, collation,
449
+ identity, generated, storage, compression, options, acl, inhcount,
450
+ islocal, stattarget, default_expr, comment) = row
451
+ if (column != expected_name or dropped or type_oid != expected_type
452
+ or typmod != -1 or not notnull or collation != 0
453
+ or identity or generated or options is not None or acl is not None
454
+ or inhcount or not islocal or stattarget != -1
455
+ or default_expr is not None or comment is not None):
456
+ _fail('row-originals-creation-toast-mismatch')
457
+ address = _column_address(classes, toast_oid, attnum)
458
+ definition = {'attnum': attnum, 'name': column, 'typeOid': type_oid,
459
+ 'typeMod': typmod, 'notNull': notnull,
460
+ 'collationOid': collation, 'identity': identity,
461
+ 'generated': generated, 'storage': storage,
462
+ 'compression': compression, 'options': options, 'acl': acl,
463
+ 'inheritanceCount': inhcount, 'isLocal': islocal,
464
+ 'statisticsTarget': stattarget, 'default': default_expr,
465
+ 'dependencies': _column_dependencies(connection, classes,
466
+ toast_oid, attnum)}
467
+ _add_object(output, class_id=address['classId'], object_id=address['objectId'],
468
+ sub_id=address['subId'], kind='column', schema='pg_toast',
469
+ name=toast[1], member=column, parent=toast_address,
470
+ definition=definition)
471
+ toast_indexes = _all(connection, '''SELECT i.indexrelid::pg_catalog.oid,
472
+ ic.relname,ic.relnamespace::pg_catalog.oid,ic.relowner::pg_catalog.oid,
473
+ ic.relpersistence,ic.reltablespace::pg_catalog.oid,ic.reloptions,
474
+ pg_catalog.pg_get_indexdef(i.indexrelid),i.indnatts,i.indnkeyatts,i.indisunique,
475
+ i.indisprimary,i.indisexclusion,i.indimmediate,i.indisvalid,i.indcheckxmin,
476
+ i.indisready,i.indislive,i.indisreplident,i.indnullsnotdistinct,
477
+ i.indkey::pg_catalog.int2[],i.indclass::pg_catalog.oid[],
478
+ i.indcollation::pg_catalog.oid[],i.indoption::pg_catalog.int2[],
479
+ pg_catalog.pg_get_expr(i.indexprs,i.indrelid),pg_catalog.pg_get_expr(i.indpred,i.indrelid),
480
+ am.amname,pg_catalog.obj_description(ic.oid,'pg_class')
481
+ FROM pg_catalog.pg_index i JOIN pg_catalog.pg_class ic ON ic.oid=i.indexrelid
482
+ JOIN pg_catalog.pg_am am ON am.oid=ic.relam
483
+ WHERE i.indrelid=%s ORDER BY i.indexrelid LIMIT 2''', (toast_oid,))
484
+ if len(toast_indexes) != 1:
485
+ _fail('row-originals-creation-toast-mismatch')
486
+ index = toast_indexes[0]
487
+ (index_oid, index_name, index_namespace, index_owner, index_persistence,
488
+ index_tablespace, index_options, index_definition, natts, nkeyatts, unique,
489
+ primary, exclusion, immediate, valid, checkxmin, ready, live, replica,
490
+ nulls_not_distinct, indkey, indclass, indcollation, indoption, expressions,
491
+ predicate, access_method, comment) = index
492
+ toast_namespace_oid = _one(connection,
493
+ "SELECT oid FROM pg_catalog.pg_namespace WHERE nspname='pg_toast'")[0]
494
+ if (index_namespace != toast_namespace_oid or index_owner != controller_oid
495
+ or index_persistence != 'p' or index_tablespace != 0
496
+ or index_options is not None or not unique or primary or exclusion
497
+ or not immediate or not valid or checkxmin or not ready or not live
498
+ or replica or nulls_not_distinct or expressions is not None
499
+ or predicate is not None or access_method != 'btree' or comment is not None):
500
+ _fail('row-originals-creation-toast-mismatch')
501
+ index_acl = _all(connection, '''SELECT acl.grantee::pg_catalog.oid,
502
+ acl.grantor::pg_catalog.oid,acl.privilege_type,acl.is_grantable
503
+ FROM pg_catalog.pg_class c CROSS JOIN LATERAL pg_catalog.aclexplode(
504
+ COALESCE(c.relacl,pg_catalog.acldefault('r',c.relowner))) acl WHERE c.oid=%s
505
+ ORDER BY acl.grantee,acl.grantor,acl.privilege_type,acl.is_grantable''', (index_oid,))
506
+ _add_object(
507
+ output, class_id=classes['pg_class'], object_id=index_oid, sub_id=0,
508
+ kind='toast-index', schema='pg_toast', name=index_name, member=None,
509
+ parent=toast_address,
510
+ definition={'namespaceOid': index_namespace, 'owner': index_owner,
511
+ 'persistence': index_persistence, 'tablespace': index_tablespace,
512
+ 'options': index_options,
513
+ 'definition': index_definition, 'indnatts': natts,
514
+ 'indnkeyatts': nkeyatts, 'unique': unique, 'primary': primary,
515
+ 'exclusion': exclusion, 'immediate': immediate,
516
+ 'valid': valid, 'checkxmin': checkxmin, 'ready': ready,
517
+ 'live': live, 'replicaIdentity': replica,
518
+ 'nullsNotDistinct': nulls_not_distinct, 'indkey': indkey,
519
+ 'indclass': indclass, 'indcollation': indcollation,
520
+ 'indoption': indoption, 'expressions': expressions,
521
+ 'predicate': predicate, 'accessMethod': access_method,
522
+ 'acl': index_acl,
523
+ 'dependencies': _dependencies(connection, classes['pg_class'],
524
+ index_oid)})
525
+
526
+ # PostgreSQL creates exactly four internal RI triggers per declared FK.
527
+ fk_trigger_addresses: list[dict[str, int]] = []
528
+ for fk in fk_rows:
529
+ constraint_oid, _constraint_name, _kind, relid, confrelid, conindid = fk[:6]
530
+ observed_signatures: list[tuple[int, str, int, int, int, int]] = []
531
+ triggers = _all(connection, '''SELECT t.oid::pg_catalog.oid,t.tgname,
532
+ t.tgrelid::pg_catalog.oid,t.tgparentid::pg_catalog.oid,t.tgfoid::pg_catalog.oid,
533
+ t.tgtype,t.tgenabled,t.tgisinternal,t.tgconstrrelid::pg_catalog.oid,
534
+ t.tgconstrindid::pg_catalog.oid,t.tgconstraint::pg_catalog.oid,
535
+ t.tgdeferrable,t.tginitdeferred,t.tgnargs,t.tgargs,t.tgattr::pg_catalog.int2[],
536
+ pg_catalog.pg_get_triggerdef(t.oid,true),p.proname,p.pronamespace::pg_catalog.oid,
537
+ pg_catalog.obj_description(t.oid,'pg_trigger')
538
+ FROM pg_catalog.pg_trigger t JOIN pg_catalog.pg_proc p ON p.oid=t.tgfoid
539
+ WHERE t.tgconstraint=%s ORDER BY t.oid LIMIT 5''', (constraint_oid,))
540
+ if len(triggers) != 4:
541
+ _fail('row-originals-creation-ri-trigger-mismatch')
542
+ for row in triggers:
543
+ (oid, name, relation_oid, parent_oid, function_oid, tgtype, enabled,
544
+ internal, trigger_relation, trigger_index, trigger_constraint,
545
+ deferrable, deferred, nargs, args, attrs, definition_text,
546
+ function_name, function_namespace, comment) = row
547
+ if (not internal or parent_oid != 0 or enabled != 'O'
548
+ or relation_oid not in (relid, confrelid)):
549
+ _fail('row-originals-creation-ri-trigger-mismatch')
550
+ relation_is_referencing = function_name in {
551
+ 'RI_FKey_check_ins', 'RI_FKey_check_upd'}
552
+ _validate_ri_trigger(
553
+ relation_is_referencing=relation_is_referencing,
554
+ relation_oid=relation_oid,
555
+ expected_relation_oid=relid if relation_is_referencing else confrelid,
556
+ parent_oid=parent_oid, function_oid=function_oid,
557
+ function_name=function_name, function_namespace=function_namespace,
558
+ pg_catalog_namespace=_one(
559
+ connection, "SELECT oid FROM pg_catalog.pg_namespace WHERE nspname='pg_catalog'")[0],
560
+ trigger_type=tgtype, enabled=enabled, internal=internal,
561
+ trigger_relation=trigger_relation,
562
+ expected_trigger_relation=confrelid if relation_is_referencing else relid,
563
+ trigger_index=trigger_index, expected_index=conindid,
564
+ trigger_constraint=trigger_constraint,
565
+ expected_constraint=constraint_oid, deferrable=deferrable,
566
+ deferred=deferred, argument_count=nargs, arguments=args,
567
+ attributes=attrs, comment=comment)
568
+ observed_signatures.append((relation_oid, function_name, tgtype,
569
+ trigger_relation, trigger_index,
570
+ trigger_constraint))
571
+ trig_definition = {
572
+ 'relationOid': relation_oid, 'parentTriggerOid': parent_oid,
573
+ 'functionOid': function_oid, 'functionName': function_name,
574
+ 'triggerType': tgtype, 'enabled': enabled, 'internal': internal,
575
+ 'constraintRelationOid': trigger_relation,
576
+ 'constraintIndexOid': trigger_index, 'constraintOid': trigger_constraint,
577
+ 'deferrable': deferrable, 'initiallyDeferred': deferred,
578
+ 'argumentCount': nargs, 'arguments': _native(args),
579
+ 'attributes': attrs, 'definition': definition_text,
580
+ 'dependencies': _dependencies(connection, classes['pg_trigger'], oid),
581
+ }
582
+ rel_info = by_relation_oid.get(relation_oid)
583
+ if rel_info is None:
584
+ _fail('row-originals-creation-ri-trigger-mismatch')
585
+ constraint = constraints_by_oid[constraint_oid]
586
+ trigger_address = _add_object(
587
+ output, class_id=classes['pg_trigger'], object_id=oid, sub_id=0,
588
+ kind='internal-ri-trigger', schema=schema,
589
+ name=rel_info['row'][1], member=name,
590
+ parent=constraint['address'], definition=trig_definition)
591
+ fk_trigger_addresses.append(trigger_address)
592
+ _validate_fk_trigger_set(
593
+ observed_signatures, referencing_oid=relid, referenced_oid=confrelid,
594
+ index_oid=conindid, constraint_oid=constraint_oid)
595
+
596
+ # Reject any trigger not accounted for by the exact two fixed FKs.
597
+ all_triggers = _all(connection, '''SELECT t.oid,t.tgname,t.tgconstraint,t.tgisinternal
598
+ FROM pg_catalog.pg_trigger t WHERE t.tgrelid=ANY(%s) ORDER BY t.oid LIMIT 1025''',
599
+ (list(by_relation_oid),))
600
+ if len(all_triggers) > MAX_OBJECTS:
601
+ _fail('row-originals-creation-receipt-capacity')
602
+ expected_trigger_oids = {item['objectId'] for item in fk_trigger_addresses}
603
+ if ({row[0] for row in all_triggers} != expected_trigger_oids
604
+ or any(not row[3] or row[2] not in constraints_by_oid for row in all_triggers)):
605
+ _fail('row-originals-creation-ri-trigger-mismatch')
606
+ objects = sorted(output, key=lambda item: (
607
+ item['classId'], item['objectId'], item['subId']))
608
+ return validate_objects(objects, schema, schema_oid)
609
+
610
+
611
+ def _add_type_object(connection: Any, output: list[dict[str, Any]],
612
+ classes: dict[str, int], type_oid: int, schema: str,
613
+ name: str, kind: str, parent: dict[str, int]) -> dict[str, int]:
614
+ row = _one(connection, '''SELECT t.oid::pg_catalog.oid,n.nspname,t.typname,
615
+ t.typnamespace::pg_catalog.oid,t.typowner::pg_catalog.oid,t.typlen,t.typbyval,
616
+ t.typtype,t.typcategory,t.typispreferred,t.typisdefined,t.typdelim,
617
+ t.typrelid::pg_catalog.oid,t.typelem::pg_catalog.oid,t.typarray::pg_catalog.oid,
618
+ t.typinput::pg_catalog.oid,t.typoutput::pg_catalog.oid,t.typreceive::pg_catalog.oid,
619
+ t.typsend::pg_catalog.oid,t.typmodin::pg_catalog.oid,t.typmodout::pg_catalog.oid,
620
+ t.typanalyze::pg_catalog.oid,t.typalign,t.typstorage,t.typnotnull,t.typbasetype::pg_catalog.oid,
621
+ t.typtypmod,t.typndims,t.typcollation::pg_catalog.oid,t.typacl,
622
+ pg_catalog.obj_description(t.oid,'pg_type')
623
+ FROM pg_catalog.pg_type t JOIN pg_catalog.pg_namespace n ON n.oid=t.typnamespace
624
+ WHERE t.oid=%s''', (type_oid,))
625
+ if row is None or row[1] != schema or row[2] != name or row[30] is not None:
626
+ _fail('row-originals-creation-catalog-mismatch')
627
+ acl = _all(connection, '''SELECT acl.grantee::pg_catalog.oid,
628
+ acl.grantor::pg_catalog.oid,acl.privilege_type,acl.is_grantable
629
+ FROM pg_catalog.pg_type t CROSS JOIN LATERAL pg_catalog.aclexplode(
630
+ COALESCE(t.typacl,pg_catalog.acldefault('T',t.typowner))) acl WHERE t.oid=%s
631
+ ORDER BY acl.grantee,acl.grantor,acl.privilege_type,acl.is_grantable''', (type_oid,))
632
+ definition = {
633
+ 'namespaceOid': row[3], 'owner': row[4], 'length': row[5], 'byValue': row[6],
634
+ 'typeKind': row[7], 'category': row[8], 'preferred': row[9],
635
+ 'defined': row[10], 'delimiter': row[11], 'relationOid': row[12],
636
+ 'elementOid': row[13], 'arrayOid': row[14], 'inputOid': row[15],
637
+ 'outputOid': row[16], 'receiveOid': row[17], 'sendOid': row[18],
638
+ 'typmodInOid': row[19], 'typmodOutOid': row[20], 'analyzeOid': row[21],
639
+ 'alignment': row[22], 'storage': row[23], 'notNull': row[24],
640
+ 'baseTypeOid': row[25], 'typeMod': row[26], 'dimensions': row[27],
641
+ 'collationOid': row[28], 'acl': acl,
642
+ 'dependencies': _dependencies(connection, classes['pg_type'], type_oid),
643
+ }
644
+ return _add_object(output, class_id=classes['pg_type'], object_id=type_oid,
645
+ sub_id=0, kind=kind, schema=schema, name=name,
646
+ member=None, parent=parent, definition=definition)
647
+
648
+
649
+ def observe_and_write_receipt(connection: Any, schema: str, schema_oid: int,
650
+ controller_oid: int, fields: dict[str, Any]) -> dict[str, Any]:
651
+ """Build the public comment after DDL; caller still must externally confirm COMMIT."""
652
+ objects = observe_creation_objects(connection, schema, schema_oid, controller_oid)
653
+ receipt = validate_receipt({**fields, 'profile': RECEIPT_PROFILE,
654
+ 'storeProfile': 'umf.native-row-originals-store/0.1',
655
+ 'schemaOid': schema_oid, 'objects': objects,
656
+ 'state': 'created'})
657
+ comment = encode_comment(receipt)
658
+ if len(comment.encode('utf-8')) > MAX_RECEIPT_BYTES:
659
+ _fail('row-originals-creation-receipt-capacity')
660
+ literal = "'" + comment.replace("'", "''") + "'"
661
+ from .catalog import _execute, _q
662
+
663
+ _execute(connection, 'COMMENT ON SCHEMA ' + _q(schema) + ' IS ' + literal)
664
+ observed = _one(connection, '''SELECT pg_catalog.obj_description(n.oid,'pg_namespace')
665
+ FROM pg_catalog.pg_namespace n WHERE n.oid=%s''', (schema_oid,))
666
+ if observed != (comment,):
667
+ _fail('row-originals-creation-receipt-unobserved')
668
+ return receipt
669
+
670
+
671
+ def verify_creation_receipt(connection: Any, schema: str, expected: dict[str, Any],
672
+ controller_oid: int) -> dict[str, Any]:
673
+ checked = validate_receipt(expected)
674
+ observed_comment = _one(connection, '''SELECT pg_catalog.obj_description(n.oid,'pg_namespace')
675
+ FROM pg_catalog.pg_namespace n WHERE n.oid=%s''', (checked['schemaOid'],))
676
+ if observed_comment is None:
677
+ _fail('row-originals-creation-receipt-unavailable')
678
+ actual = decode_comment(observed_comment[0])
679
+ if actual != checked or actual['state'] != 'created':
680
+ _fail('row-originals-creation-receipt-mismatch')
681
+ objects = observe_creation_objects(connection, schema, checked['schemaOid'], controller_oid)
682
+ if objects != checked['objects']:
683
+ _fail('row-originals-creation-inventory-mismatch')
684
+ return actual
685
+
686
+
687
+ def recover_creation_receipt(connection: Any, schema: str,
688
+ expected_fields: dict[str, Any],
689
+ controller_oid: int) -> dict[str, Any]:
690
+ """Read and fully re-observe a committed receipt without repeating DDL."""
691
+ if (type(schema) is not str or type(expected_fields) is not dict
692
+ or type(controller_oid) is not int or controller_oid <= 0):
693
+ _fail('row-originals-creation-receipt-unavailable')
694
+ with connection.transaction():
695
+ namespace = _one(connection, '''SELECT n.oid,n.nspowner
696
+ FROM pg_catalog.pg_namespace n WHERE n.nspname=%s''', (schema,))
697
+ if namespace is None or namespace[1] != controller_oid:
698
+ _fail('row-originals-creation-receipt-unavailable')
699
+ observed = _one(connection, '''SELECT pg_catalog.obj_description(n.oid,'pg_namespace')
700
+ FROM pg_catalog.pg_namespace n WHERE n.oid=%s''', (namespace[0],))
701
+ if observed is None or type(observed[0]) is not str:
702
+ _fail('row-originals-creation-receipt-unavailable')
703
+ receipt = decode_comment(observed[0])
704
+ if (receipt['schemaOid'] != namespace[0]
705
+ or any(receipt.get(key) != value for key, value in expected_fields.items())):
706
+ _fail('row-originals-creation-receipt-mismatch')
707
+ return verify_creation_receipt(connection, schema, receipt, controller_oid)
708
+
709
+
710
+ def observe_absent_creation_schema(connection: Any, schema: str,
711
+ expected_native: dict[str, Any],
712
+ controller_oid: int, *,
713
+ readonly: bool = False) -> dict[str, Any] | None:
714
+ """Prove absence on the original controller session without changing mode."""
715
+ if (type(schema) is not str or type(expected_native) is not dict
716
+ or type(controller_oid) is not int or controller_oid <= 0):
717
+ _fail('row-originals-creation-absence-unverified')
718
+ with connection.transaction():
719
+ row = _one(connection, '''SELECT pg_catalog.current_database(),d.oid,
720
+ pg_catalog.pg_control_system().system_identifier::pg_catalog.text,
721
+ session_user,current_user,pg_catalog.current_setting('role'),
722
+ pg_catalog.current_setting('search_path'),pg_catalog.current_setting('TimeZone'),
723
+ pg_catalog.current_setting('row_security'),
724
+ pg_catalog.current_setting('session_replication_role'),
725
+ pg_catalog.current_setting('transaction_read_only'),
726
+ pg_catalog.current_setting('transaction_isolation'),
727
+ (SELECT r.oid FROM pg_catalog.pg_roles r WHERE r.rolname=session_user),
728
+ (SELECT r.oid FROM pg_catalog.pg_roles r WHERE r.rolname=current_user)
729
+ FROM pg_catalog.pg_database d WHERE d.datname=pg_catalog.current_database()''')
730
+ if row is None:
731
+ _fail('row-originals-creation-absence-unverified')
732
+ actual = {
733
+ 'databaseName': row[0], 'databaseOid': row[1], 'systemIdentifier': row[2],
734
+ 'sessionUser': row[3], 'currentUser': row[4], 'roleSetting': row[5],
735
+ 'searchPath': row[6], 'timeZone': row[7], 'rowSecurity': row[8],
736
+ 'sessionReplicationRole': row[9], 'transactionReadOnly': row[10],
737
+ 'transactionIsolation': row[11], 'sessionUserOid': row[12],
738
+ 'currentUserOid': row[13],
739
+ }
740
+ if (any(expected_native.get(key) != value for key, value in actual.items())
741
+ or actual['currentUserOid'] != controller_oid
742
+ or actual['transactionReadOnly'] != ('on' if readonly else 'off')
743
+ or actual['transactionIsolation'] != 'read committed'):
744
+ _fail('row-originals-creation-absence-unverified')
745
+ namespace = _one(connection, '''SELECT n.oid,n.nspowner
746
+ FROM pg_catalog.pg_namespace n WHERE n.nspname=%s''', (schema,))
747
+ if namespace is not None:
748
+ return None
749
+ return {
750
+ 'profile': 'umf.original-store-absence-proof/0.1',
751
+ 'database': {'name': actual['databaseName'], 'oid': actual['databaseOid'],
752
+ 'systemIdentifier': actual['systemIdentifier']},
753
+ 'session': {'sessionUser': actual['sessionUser'],
754
+ 'sessionUserOid': actual['sessionUserOid'],
755
+ 'controller': actual['currentUser'],
756
+ 'controllerOid': actual['currentUserOid'],
757
+ 'roleSetting': actual['roleSetting']},
758
+ 'schemaName': schema, 'state': 'absent',
759
+ }