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,79 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT OR Apache-2.0
|
|
2
|
+
"""Explicit administrative backfills; Weft owns all UPDATE SQL and literals."""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
|
|
7
|
+
from .catalog import CatalogError, _cursor, _execute, _q
|
|
8
|
+
from .seeds import _binding
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def _apply_backfill(connection, plan, step):
|
|
12
|
+
from weft import prepare_table_operation_module_json
|
|
13
|
+
|
|
14
|
+
bundle = plan['next']
|
|
15
|
+
options = plan.get('options', {})
|
|
16
|
+
derived = (plan.get('version') == 'umf.table-migration/0.4'
|
|
17
|
+
and options.get('version') == 'umf.table-migration-options/0.4')
|
|
18
|
+
if ((plan.get('version') == 'umf.table-migration/0.4') != derived
|
|
19
|
+
or (derived and step.get('phaseOperation') != 'backfill')):
|
|
20
|
+
raise CatalogError('backfill-program-version-refused')
|
|
21
|
+
selected = [b for b in options.get('backfills', []) if b['operation'] == step['operation']]
|
|
22
|
+
if len(selected) != 1 or selected[0]['scopedRows'] is not True:
|
|
23
|
+
raise CatalogError('backfill-scope-required')
|
|
24
|
+
selection = selected[0]
|
|
25
|
+
table = next(t for t in bundle['expectedCatalog']['tables'] if t['id'] == selection['table'])
|
|
26
|
+
binding = _binding(bundle)
|
|
27
|
+
module = prepare_table_operation_module_json(json.dumps({
|
|
28
|
+
'version': 'weft.table-operation-module/0.1', 'target': 'postgresql18',
|
|
29
|
+
'binding': binding, 'module': bundle['module']}, separators=(',', ':')))
|
|
30
|
+
compiled = module.prepare(selection['operation'])
|
|
31
|
+
program = json.loads(compiled.bind_json(json.dumps({
|
|
32
|
+
'call': {'kind': 'single', 'inputs': {}}, 'idempotencyKey': plan['digest']})))
|
|
33
|
+
guard = {'profile':'pg18-row-expression-exact/0.1','sqlstate':'22012',
|
|
34
|
+
'scope':'all-direct-target-rows',
|
|
35
|
+
'nullResult':'statement-error-and-transaction-rollback',
|
|
36
|
+
'nonfiniteInput':'statement-error-and-transaction-rollback',
|
|
37
|
+
'lossyAssignment':'statement-error-and-transaction-rollback',
|
|
38
|
+
'privateResults':True}
|
|
39
|
+
result_profile = program.get('result', {})
|
|
40
|
+
guard_matches = (result_profile.get('nativeExactValueGuard') == guard
|
|
41
|
+
if derived else 'nativeExactValueGuard' not in result_profile)
|
|
42
|
+
if (program.get('status') != 'compiled' or program.get('outputs') != []
|
|
43
|
+
or program.get('version') != ('weft.table-operation/0.2' if derived else 'weft.table-operation/0.1')
|
|
44
|
+
or program.get('binding',{}).get('modelSha256') != bundle['sourceDigest']
|
|
45
|
+
or program.get('module') != bundle['module'] or program.get('operation') != selection['operation']
|
|
46
|
+
or program.get('result',{}).get('kind') != 'mutation'
|
|
47
|
+
or not guard_matches
|
|
48
|
+
or len(program.get('nativeInputs', [])) != 1):
|
|
49
|
+
raise CatalogError('backfill-compilation-refused')
|
|
50
|
+
sources = {slot['id']: slot['source'] for slot in program['parameterSources']}
|
|
51
|
+
arguments = []
|
|
52
|
+
for name in program['dbapiParameterOrder']:
|
|
53
|
+
source = sources[name]
|
|
54
|
+
if source['kind'] != 'literal':
|
|
55
|
+
raise CatalogError('backfill-parameter-refused')
|
|
56
|
+
arguments.append(source['nativeValue'])
|
|
57
|
+
relation = _q(bundle['configuration']['schema']) + '.' + _q(table['name'])
|
|
58
|
+
# The enclosing approved migration savepoint restores RLS on any failure.
|
|
59
|
+
_execute(connection, 'ALTER TABLE ' + relation + ' DISABLE ROW LEVEL SECURITY')
|
|
60
|
+
try:
|
|
61
|
+
with _cursor(connection) as cursor:
|
|
62
|
+
cursor.execute(program['dbapiSql'], tuple(arguments))
|
|
63
|
+
if [column[0] for column in cursor.description] != [program['result']['affectedMarker']]:
|
|
64
|
+
raise CatalogError('backfill-result-profile')
|
|
65
|
+
rows = cursor.fetchmany(program['result']['maxRows'] + 1)
|
|
66
|
+
if len(rows) > program['result']['maxRows'] or any(row != (1,) for row in rows):
|
|
67
|
+
raise CatalogError('backfill-effect-bound')
|
|
68
|
+
except CatalogError:
|
|
69
|
+
raise
|
|
70
|
+
except Exception as error:
|
|
71
|
+
if not derived:
|
|
72
|
+
raise
|
|
73
|
+
# Keep PostgreSQL's machine-readable class while dropping DETAIL and row data.
|
|
74
|
+
from psycopg import Error as PsycopgError
|
|
75
|
+
if isinstance(error, PsycopgError):
|
|
76
|
+
raise CatalogError('derived-backfill-native-error', sqlstate=error.sqlstate) from None
|
|
77
|
+
raise
|
|
78
|
+
_execute(connection, 'ALTER TABLE ' + relation + ' ENABLE ROW LEVEL SECURITY')
|
|
79
|
+
_execute(connection, 'ALTER TABLE ' + relation + ' FORCE ROW LEVEL SECURITY')
|
|
@@ -0,0 +1,289 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT OR Apache-2.0
|
|
2
|
+
"""Source-derived PG18 catalog checks within a caller-owned install transaction.
|
|
3
|
+
|
|
4
|
+
The verifier checks relation/column shape, defaults, constraints, indexes and
|
|
5
|
+
policies. It cannot authorize data execution: ACL and transitive role closure
|
|
6
|
+
remain separate gates. Expected shape always comes from recompiled source.
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import hashlib
|
|
11
|
+
from collections.abc import Iterator
|
|
12
|
+
from contextlib import contextmanager
|
|
13
|
+
from typing import Any, cast
|
|
14
|
+
from uuid import uuid4
|
|
15
|
+
|
|
16
|
+
from .table_boundary import TABLE_BOUNDARY
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class CatalogError(RuntimeError):
|
|
20
|
+
"""Fixed administrative failure reason, without native diagnostics or data."""
|
|
21
|
+
|
|
22
|
+
def __init__(self, message: str, *, sqlstate: str | None = None):
|
|
23
|
+
super().__init__(message)
|
|
24
|
+
self.sqlstate = sqlstate
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _q(value: str) -> str:
|
|
28
|
+
return '"' + value.replace('"', '""') + '"'
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _q_bound(value: str) -> str:
|
|
32
|
+
"""Identifier in a fixed DBAPI statement that also binds parameters."""
|
|
33
|
+
return _q(value).replace('%','%%')
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _cursor(connection: Any) -> Any:
|
|
37
|
+
from psycopg.rows import tuple_row
|
|
38
|
+
|
|
39
|
+
return connection.cursor(row_factory=tuple_row)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _one(connection: Any, statement: str, parameters: tuple[Any, ...] = ()) -> Any:
|
|
43
|
+
with _cursor(connection) as cursor:
|
|
44
|
+
# No parameters means no DBAPI percent interpretation for compiler SQL.
|
|
45
|
+
cursor.execute(statement, parameters) if parameters else cursor.execute(statement)
|
|
46
|
+
return cursor.fetchone()
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _execute(connection: Any, statement: str, parameters: tuple[Any, ...] = ()) -> None:
|
|
50
|
+
with _cursor(connection) as cursor:
|
|
51
|
+
cursor.execute(statement, parameters) if parameters else cursor.execute(statement)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
_COLUMNS = """SELECT a.attname,tn.nspname,t.typname,a.atttypmod,NOT a.attnotnull,
|
|
55
|
+
CASE WHEN a.attcollation=0 THEN NULL ELSE cn.nspname||'.'||co.collname END,
|
|
56
|
+
a.attidentity,a.attgenerated,pg_catalog.pg_get_expr(d.adbin,d.adrelid)
|
|
57
|
+
FROM pg_catalog.pg_attribute a
|
|
58
|
+
JOIN pg_catalog.pg_class c ON c.oid=a.attrelid
|
|
59
|
+
JOIN pg_catalog.pg_namespace n ON n.oid=c.relnamespace
|
|
60
|
+
JOIN pg_catalog.pg_type t ON t.oid=a.atttypid
|
|
61
|
+
JOIN pg_catalog.pg_namespace tn ON tn.oid=t.typnamespace
|
|
62
|
+
LEFT JOIN pg_catalog.pg_collation co ON co.oid=a.attcollation
|
|
63
|
+
LEFT JOIN pg_catalog.pg_namespace cn ON cn.oid=co.collnamespace
|
|
64
|
+
LEFT JOIN pg_catalog.pg_attrdef d ON d.adrelid=a.attrelid AND d.adnum=a.attnum
|
|
65
|
+
WHERE n.nspname=%s AND c.relname=%s AND a.attnum>0 AND NOT a.attisdropped ORDER BY a.attnum"""
|
|
66
|
+
|
|
67
|
+
_POLICY = """SELECT p.polcmd,p.polpermissive,p.polroles,
|
|
68
|
+
pg_catalog.pg_get_expr(p.polqual,p.polrelid),pg_catalog.pg_get_expr(p.polwithcheck,p.polrelid),
|
|
69
|
+
ARRAY(SELECT d.refclassid::pg_catalog.text||':'||d.refobjid::pg_catalog.text||':'||
|
|
70
|
+
d.refobjsubid::pg_catalog.text||':'||d.deptype::pg_catalog.text FROM pg_catalog.pg_depend d
|
|
71
|
+
WHERE d.classid='pg_catalog.pg_policy'::pg_catalog.regclass AND d.objid=p.oid
|
|
72
|
+
ORDER BY d.refclassid,d.refobjid,d.refobjsubid,d.deptype)
|
|
73
|
+
FROM pg_catalog.pg_policy p JOIN pg_catalog.pg_class c ON c.oid=p.polrelid
|
|
74
|
+
JOIN pg_catalog.pg_namespace n ON n.oid=c.relnamespace
|
|
75
|
+
WHERE n.nspname=%s AND c.relname=%s AND p.polname=%s"""
|
|
76
|
+
|
|
77
|
+
_CONSTRAINTS = """SELECT co.conname,co.contype,pg_catalog.pg_get_constraintdef(co.oid,true),
|
|
78
|
+
ARRAY(SELECT a.attname FROM pg_catalog.unnest(co.conkey) WITH ORDINALITY k(num,ord)
|
|
79
|
+
JOIN pg_catalog.pg_attribute a ON a.attrelid=co.conrelid AND a.attnum=k.num ORDER BY k.ord),
|
|
80
|
+
co.condeferrable,co.condeferred,co.convalidated,co.conenforced,co.connoinherit,co.conperiod,
|
|
81
|
+
ix.relname,co.conpfeqop,co.conppeqop,co.conffeqop
|
|
82
|
+
FROM pg_catalog.pg_constraint co JOIN pg_catalog.pg_class c ON c.oid=co.conrelid
|
|
83
|
+
JOIN pg_catalog.pg_namespace n ON n.oid=c.relnamespace
|
|
84
|
+
LEFT JOIN pg_catalog.pg_class ix ON ix.oid=co.conindid
|
|
85
|
+
WHERE n.nspname=%s AND c.relname=%s ORDER BY co.conname"""
|
|
86
|
+
|
|
87
|
+
_INDEXES = """SELECT ic.relname,i.indnatts,i.indnkeyatts,i.indisunique,i.indisprimary,
|
|
88
|
+
i.indisexclusion,i.indimmediate,i.indisvalid,i.indcheckxmin,i.indisready,i.indislive,
|
|
89
|
+
i.indisreplident,i.indnullsnotdistinct,
|
|
90
|
+
ARRAY(SELECT a.attname FROM pg_catalog.unnest(i.indkey::pg_catalog.int2[]) WITH ORDINALITY k(num,ord)
|
|
91
|
+
LEFT JOIN pg_catalog.pg_attribute a ON a.attrelid=i.indrelid AND a.attnum=k.num ORDER BY k.ord),
|
|
92
|
+
i.indclass::pg_catalog.oid[],i.indcollation::pg_catalog.oid[],i.indoption::pg_catalog.int2[],
|
|
93
|
+
pg_catalog.pg_get_expr(i.indexprs,i.indrelid),pg_catalog.pg_get_expr(i.indpred,i.indrelid),am.amname,am.amhandler
|
|
94
|
+
FROM pg_catalog.pg_index i JOIN pg_catalog.pg_class c ON c.oid=i.indrelid
|
|
95
|
+
JOIN pg_catalog.pg_namespace n ON n.oid=c.relnamespace
|
|
96
|
+
JOIN pg_catalog.pg_class ic ON ic.oid=i.indexrelid JOIN pg_catalog.pg_am am ON am.oid=ic.relam
|
|
97
|
+
WHERE n.nspname=%s AND c.relname=%s ORDER BY ic.relname"""
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _all(connection: Any, statement: str, parameters: tuple[Any, ...]) -> list[tuple[Any, ...]]:
|
|
101
|
+
with _cursor(connection) as cursor:
|
|
102
|
+
cursor.execute(statement, parameters) if parameters else cursor.execute(statement)
|
|
103
|
+
return cast(list[tuple[Any, ...]], cursor.fetchall())
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _constraint_shapes(connection: Any, schema: str, table: str, aliases: dict[str, str]) -> dict[Any, Any]:
|
|
107
|
+
result = {}
|
|
108
|
+
for row in _all(connection, _CONSTRAINTS, (schema, table)):
|
|
109
|
+
name, kind, definition, columns, *metadata = row
|
|
110
|
+
name = aliases.get(name, name)
|
|
111
|
+
identity = ("not-null", tuple(columns)) if kind == "n" else ("named", name)
|
|
112
|
+
if identity in result:
|
|
113
|
+
raise CatalogError("catalog-mismatch")
|
|
114
|
+
metadata[6] = aliases.get(metadata[6], metadata[6])
|
|
115
|
+
result[identity] = (kind, definition, columns, *metadata)
|
|
116
|
+
return result
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _index_shapes(connection: Any, schema: str, table: str, aliases: dict[str, str]) -> dict[str, Any]:
|
|
120
|
+
return {aliases.get(row[0], row[0]): row[1:] for row in _all(connection, _INDEXES, (schema, table))}
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _columns(connection: Any, schema: str, table: str) -> list[tuple[Any, ...]]:
|
|
124
|
+
with _cursor(connection) as cursor:
|
|
125
|
+
cursor.execute(_COLUMNS, (schema, table))
|
|
126
|
+
return cast(list[tuple[Any, ...]], cursor.fetchall())
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _verify_table_shape(connection: Any, bundle: dict[str, Any], table: dict[str, Any]) -> None:
|
|
130
|
+
schema = bundle["configuration"]["schema"]
|
|
131
|
+
expected = [c for c in bundle["expectedCatalog"]["columns"] if c["table"] == table["id"]]
|
|
132
|
+
rows = _columns(connection, schema, table["name"])
|
|
133
|
+
if len(rows) != len(expected):
|
|
134
|
+
raise CatalogError("catalog-mismatch")
|
|
135
|
+
for column, row in zip(expected, rows, strict=True):
|
|
136
|
+
shape = (column["name"], column["typeSchema"], column["typeName"], column["typeMod"],
|
|
137
|
+
column["nullable"], "pg_catalog.C" if column["collation"] == "C" else None,
|
|
138
|
+
column["identity"], "")
|
|
139
|
+
if tuple(row[:8]) != shape:
|
|
140
|
+
raise CatalogError("catalog-mismatch")
|
|
141
|
+
# Reparse original column declarations on a fresh private-schema relation.
|
|
142
|
+
# No permanent column or dropped-attribute tombstone is added to real tables.
|
|
143
|
+
temporary = "umf_verify_" + uuid4().hex
|
|
144
|
+
relation = _q(schema) + "." + _q(temporary)
|
|
145
|
+
definitions = [c["definitionSql"] for c in expected]
|
|
146
|
+
catalog = bundle["expectedCatalog"]
|
|
147
|
+
aliases = {}
|
|
148
|
+
for key in [key for key in catalog["keys"] if key["table"] == table["id"]]:
|
|
149
|
+
prefix = "CONSTRAINT " + _q(key["name"]) + " "
|
|
150
|
+
if not key["definitionSql"].startswith(prefix):
|
|
151
|
+
raise CatalogError("source-mismatch")
|
|
152
|
+
name = "umf_verify_" + uuid4().hex
|
|
153
|
+
aliases[name] = key["name"]
|
|
154
|
+
definitions.append("CONSTRAINT " + _q(name) + " " + key["definitionSql"][len(prefix):])
|
|
155
|
+
definitions.extend(c["definitionSql"] for c in catalog["checks"] if c["table"] == table["id"])
|
|
156
|
+
_execute(connection, "CREATE TABLE " + relation + " (" + ", ".join(definitions) + ")")
|
|
157
|
+
reference = _columns(connection, schema, temporary)
|
|
158
|
+
if rows != reference:
|
|
159
|
+
raise CatalogError("catalog-mismatch")
|
|
160
|
+
for fk in [fk for fk in catalog["foreignKeys"] if fk["table"] == table["id"]]:
|
|
161
|
+
_execute(connection, "ALTER TABLE " + relation + " ADD " + fk["definitionSql"])
|
|
162
|
+
actual = _one(connection, """SELECT ix.relname FROM pg_catalog.pg_constraint co
|
|
163
|
+
JOIN pg_catalog.pg_class c ON c.oid=co.conrelid JOIN pg_catalog.pg_namespace n ON n.oid=c.relnamespace
|
|
164
|
+
JOIN pg_catalog.pg_class ix ON ix.oid=co.conindid WHERE n.nspname=%s AND c.relname=%s AND co.conname=%s""", (schema, table["name"], fk["name"]))
|
|
165
|
+
if actual != (fk["targetKey"],):
|
|
166
|
+
raise CatalogError("catalog-mismatch")
|
|
167
|
+
for index in [index for index in catalog["indexes"] if index["table"] == table["id"]]:
|
|
168
|
+
name = "umf_verify_" + uuid4().hex
|
|
169
|
+
aliases[name] = index["name"]
|
|
170
|
+
_execute(connection, "CREATE " + ("UNIQUE " if index["unique"] else "") + "INDEX " + _q(name) + " ON " + relation + " " + index["definitionSql"])
|
|
171
|
+
if _constraint_shapes(connection, schema, table["name"], {}) != _constraint_shapes(connection, schema, temporary, aliases):
|
|
172
|
+
raise CatalogError("catalog-mismatch")
|
|
173
|
+
if _index_shapes(connection, schema, table["name"], {}) != _index_shapes(connection, schema, temporary, aliases):
|
|
174
|
+
raise CatalogError("catalog-mismatch")
|
|
175
|
+
_execute(connection, "DROP TABLE " + relation)
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def _verify_policies(connection: Any, bundle: dict[str, Any]) -> None:
|
|
179
|
+
schema = bundle["configuration"]["schema"]
|
|
180
|
+
for step in bundle["steps"]:
|
|
181
|
+
if step["kind"] != "policy":
|
|
182
|
+
continue
|
|
183
|
+
parts = step["sourcePath"].split("/")
|
|
184
|
+
table = bundle["expectedCatalog"]["tables"][int(parts[6])]["name"]
|
|
185
|
+
name = "umf_" + parts[-2] + "_" + parts[-1]
|
|
186
|
+
prefix = "CREATE POLICY " + _q(name) + " "
|
|
187
|
+
if not step["sql"].startswith(prefix):
|
|
188
|
+
raise CatalogError("source-mismatch")
|
|
189
|
+
temporary = "umf_verify_" + uuid4().hex
|
|
190
|
+
_execute(connection, "CREATE POLICY " + _q(temporary) + " " + step["sql"][len(prefix):])
|
|
191
|
+
actual = _one(connection, _POLICY, (schema, table, name))
|
|
192
|
+
expected = _one(connection, _POLICY, (schema, table, temporary))
|
|
193
|
+
if actual is None or actual != expected:
|
|
194
|
+
raise CatalogError("catalog-mismatch")
|
|
195
|
+
_execute(connection, "DROP POLICY " + _q(temporary) + " ON " + _q(schema) + "." + _q(table))
|
|
196
|
+
for table in bundle["expectedCatalog"]["tables"]:
|
|
197
|
+
count = _one(connection, "SELECT count(*) FROM pg_catalog.pg_policies WHERE schemaname=%s AND tablename=%s", (schema, table["name"]))
|
|
198
|
+
if count != (8,):
|
|
199
|
+
raise CatalogError("catalog-mismatch")
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
@contextmanager
|
|
203
|
+
def _installation(connection: Any, bundle: dict[str, object], *,
|
|
204
|
+
statement_timeout_ms: int, lock_timeout_ms: int) -> Iterator[dict[str, Any]]:
|
|
205
|
+
"""Shared source, install authority, lock, deadline and savepoint boundary."""
|
|
206
|
+
for timeout in (statement_timeout_ms, lock_timeout_ms):
|
|
207
|
+
if type(timeout) is not int or not 1 <= timeout <= 300_000:
|
|
208
|
+
raise ValueError("administrative timeouts must be 1..300000 milliseconds")
|
|
209
|
+
from psycopg import Error as NativeError
|
|
210
|
+
from umf_codegen import verify_table_deployment
|
|
211
|
+
|
|
212
|
+
try:
|
|
213
|
+
source = cast(dict[str, Any], verify_table_deployment(bundle))
|
|
214
|
+
except (ValueError, TypeError):
|
|
215
|
+
raise CatalogError("source-mismatch") from None
|
|
216
|
+
if int(connection.info.transaction_status) != 2:
|
|
217
|
+
raise CatalogError("transaction-required")
|
|
218
|
+
configuration = source["configuration"]
|
|
219
|
+
schema, owner = configuration["schema"], configuration["ownerRole"]
|
|
220
|
+
try:
|
|
221
|
+
with connection.transaction():
|
|
222
|
+
previous = _one(connection, "SELECT pg_catalog.current_setting('statement_timeout'),pg_catalog.current_setting('lock_timeout')")
|
|
223
|
+
_one(connection, "SELECT pg_catalog.set_config('statement_timeout',%s,true),pg_catalog.set_config('lock_timeout',%s,true)", (str(statement_timeout_ms), str(lock_timeout_ms)))
|
|
224
|
+
state = _one(connection, """SELECT current_user, r.rolsuper,r.rolbypassrls,r.rolcreatedb,
|
|
225
|
+
r.rolcreaterole,r.rolcanlogin,n.nspowner=r.oid,pg_catalog.current_schemas(false),
|
|
226
|
+
pg_catalog.current_setting('transaction_read_only'),pg_catalog.current_setting('server_version_num')::pg_catalog.int4,
|
|
227
|
+
pg_catalog.current_setting('row_security'),pg_catalog.current_setting('session_replication_role'),pg_catalog.current_setting('server_encoding'),pg_catalog.current_setting('transaction_isolation'),pg_catalog.current_setting('default_table_access_method')
|
|
228
|
+
FROM pg_catalog.pg_roles r JOIN pg_catalog.pg_namespace n ON n.nspname=%s WHERE r.rolname=current_user""", (schema,))
|
|
229
|
+
if state is None or tuple(state[:9]) != (owner, False, False, False, False, False, True, ["pg_catalog"], "off") or state[9] // 10000 != 18 or tuple(state[10:]) != ('on','origin','UTF8','read committed','heap'):
|
|
230
|
+
raise CatalogError("install-authority-required")
|
|
231
|
+
lock = int.from_bytes(hashlib.sha256(("umf.table-lifecycle/0.1\0" + schema).encode()).digest()[:8], "big", signed=True)
|
|
232
|
+
_one(connection, "SELECT pg_catalog.pg_advisory_xact_lock(%s)", (lock,))
|
|
233
|
+
yield source
|
|
234
|
+
_one(connection, "SELECT pg_catalog.set_config('statement_timeout',%s,true),pg_catalog.set_config('lock_timeout',%s,true)", tuple(previous))
|
|
235
|
+
except CatalogError:
|
|
236
|
+
raise
|
|
237
|
+
except (NativeError, ValueError, TypeError, KeyError, IndexError):
|
|
238
|
+
raise CatalogError("catalog-verification-failed") from None
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def verify_native_catalog(connection: Any, bundle: dict[str, object], *,
|
|
242
|
+
statement_timeout_ms: int = 30_000, lock_timeout_ms: int = 5_000) -> dict[str, object]:
|
|
243
|
+
"""Check source shape/policies; never commit the caller or admit data methods.
|
|
244
|
+
|
|
245
|
+
Requires a healthy active Psycopg3 transaction, configured NOLOGIN install
|
|
246
|
+
owner and exactly pg_catalog resolution. Success leaves no scratch objects;
|
|
247
|
+
failure rolls back this function's savepoint. Full lifecycle admission remains
|
|
248
|
+
false until grants and transitive role closure also qualify.
|
|
249
|
+
"""
|
|
250
|
+
with _installation(connection, bundle, statement_timeout_ms=statement_timeout_ms,
|
|
251
|
+
lock_timeout_ms=lock_timeout_ms) as source:
|
|
252
|
+
schema, owner = source["configuration"]["schema"], source["configuration"]["ownerRole"]
|
|
253
|
+
heap = _one(connection,"SELECT oid FROM pg_catalog.pg_am WHERE amname='heap'")[0]
|
|
254
|
+
owner_id = _one(connection,'SELECT oid FROM pg_catalog.pg_roles WHERE rolname=%s',(owner,))[0]
|
|
255
|
+
module_oids = [_one(connection,"""SELECT c.oid FROM pg_catalog.pg_class c
|
|
256
|
+
JOIN pg_catalog.pg_namespace n ON n.oid=c.relnamespace WHERE n.nspname=%s AND c.relname=%s""",(schema,t['name'])) for t in source['expectedCatalog']['tables']]
|
|
257
|
+
if any(row is None for row in module_oids):
|
|
258
|
+
raise CatalogError('catalog-mismatch')
|
|
259
|
+
relation_ids = [row[0] for row in module_oids]
|
|
260
|
+
for table in source["expectedCatalog"]["tables"]:
|
|
261
|
+
if _one(connection,"""SELECT c.relkind,c.relam FROM pg_catalog.pg_class c
|
|
262
|
+
JOIN pg_catalog.pg_namespace n ON n.oid=c.relnamespace WHERE n.nspname=%s AND c.relname=%s""",(schema,table['name'])) != ('r',heap):
|
|
263
|
+
raise CatalogError('catalog-mismatch')
|
|
264
|
+
relation = _q(schema) + "." + _q(table["name"])
|
|
265
|
+
_execute(connection, "LOCK TABLE " + relation + " IN ACCESS EXCLUSIVE MODE")
|
|
266
|
+
for table in source["expectedCatalog"]["tables"]:
|
|
267
|
+
native = _one(connection, """SELECT c.relkind,c.relrowsecurity,c.relforcerowsecurity,r.rolname,c.relpersistence,
|
|
268
|
+
c.relispartition,c.relhassubclass,EXISTS(SELECT FROM pg_catalog.pg_trigger t WHERE t.tgrelid=c.oid AND NOT t.tgisinternal),
|
|
269
|
+
c.relhasrules,EXISTS(SELECT FROM pg_catalog.pg_inherits inh WHERE inh.inhrelid=c.oid),c.relreplident,c.relam
|
|
270
|
+
FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid=c.relnamespace JOIN pg_catalog.pg_roles r ON r.oid=c.relowner
|
|
271
|
+
WHERE n.nspname=%s AND c.relname=%s""", (schema, table["name"]))
|
|
272
|
+
if native != ("r", True, True, owner, "p", False, False, False, False, False, "d",heap):
|
|
273
|
+
raise CatalogError("catalog-mismatch")
|
|
274
|
+
# Initial/source reproof establishes the same boundary later used
|
|
275
|
+
# by ordinary connections, rather than blessing first observations.
|
|
276
|
+
boundary = _one(connection,TABLE_BOUNDARY,(relation_ids,relation_ids,schema,table['name']))
|
|
277
|
+
if boundary != ('r','p',True,True,False,False,False,'d',owner_id,heap,False,8,False,False):
|
|
278
|
+
raise CatalogError('catalog-mismatch')
|
|
279
|
+
_verify_table_shape(connection, source, table)
|
|
280
|
+
for comment in source['expectedCatalog'].get('comments', []):
|
|
281
|
+
table = next(t for t in source['expectedCatalog']['tables'] if t['id'] == comment['table'])
|
|
282
|
+
if 'column' in comment:
|
|
283
|
+
actual = _one(connection, "SELECT pg_catalog.col_description(c.oid,a.attnum) FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid=c.relnamespace JOIN pg_catalog.pg_attribute a ON a.attrelid=c.oid WHERE n.nspname=%s AND c.relname=%s AND a.attname=%s AND NOT a.attisdropped", (schema,table['name'],comment['column']))
|
|
284
|
+
else:
|
|
285
|
+
actual = _one(connection, "SELECT pg_catalog.obj_description(c.oid,'pg_class') FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid=c.relnamespace WHERE n.nspname=%s AND c.relname=%s", (schema,table['name']))
|
|
286
|
+
if actual != (comment['text'],):
|
|
287
|
+
raise CatalogError('catalog-comment-mismatch')
|
|
288
|
+
_verify_policies(connection, source)
|
|
289
|
+
return {"bundleDigest": source["bundleDigest"], "catalogShapeVerified": True, "lifecycleAdmission": False}
|
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT OR Apache-2.0
|
|
2
|
+
"""Explicit administrative new/check/apply entrypoint; offline commands do no I/O to DB."""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import hashlib
|
|
7
|
+
import json
|
|
8
|
+
import sys
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
from .catalog import CatalogError, _execute, _q
|
|
12
|
+
from .concurrent import apply_concurrent_indexes
|
|
13
|
+
from .host import MigrationRequest, PsycopgMigrationHost, apply_migration_on_host
|
|
14
|
+
from .ledger import apply_table_migration
|
|
15
|
+
from .mixed import apply_mixed_migration
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _load(path):
|
|
19
|
+
return json.loads(Path(path).read_text(encoding='utf-8'))
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def check_chain(paths, *, current_bundle=None, manifest=None):
|
|
23
|
+
"""Verify original file bytes when pinned, complete source and terminal snapshot."""
|
|
24
|
+
from umf_codegen import verify_table_deployment, verify_table_migration
|
|
25
|
+
|
|
26
|
+
previous = None
|
|
27
|
+
identities = set()
|
|
28
|
+
files = []
|
|
29
|
+
for path in paths:
|
|
30
|
+
raw = Path(path).read_bytes()
|
|
31
|
+
digest = hashlib.sha256(raw).hexdigest()
|
|
32
|
+
if manifest is not None and manifest.get(Path(path).name) != digest:
|
|
33
|
+
raise CatalogError('migration-file-digest-conflict')
|
|
34
|
+
plan = verify_table_migration(json.loads(raw))
|
|
35
|
+
if (plan['id'] in identities or plan['predecessor'] !=
|
|
36
|
+
({'id':previous['id'],'digest':previous['digest']} if previous else None)
|
|
37
|
+
or plan['fromBundleDigest'] != (previous['toBundleDigest'] if previous else None)):
|
|
38
|
+
raise CatalogError('migration-chain-mismatch')
|
|
39
|
+
identities.add(plan['id'])
|
|
40
|
+
files.append({'file':Path(path).name,'sha256':digest,'planDigest':plan['digest']})
|
|
41
|
+
previous = plan
|
|
42
|
+
if not previous:
|
|
43
|
+
raise CatalogError('migration-chain-empty')
|
|
44
|
+
if current_bundle is not None and verify_table_deployment(current_bundle)['bundleDigest'] != previous['toBundleDigest']:
|
|
45
|
+
raise CatalogError('migration-terminal-source-mismatch')
|
|
46
|
+
return {'status':'checked','files':files,'toBundleDigest':previous['toBundleDigest']}
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def main(argv=None):
|
|
50
|
+
parser = argparse.ArgumentParser(prog='umf-table',allow_abbrev=False)
|
|
51
|
+
commands = parser.add_subparsers(dest='command',required=True)
|
|
52
|
+
new = commands.add_parser('new',allow_abbrev=False)
|
|
53
|
+
new.add_argument('--request',required=True,type=Path)
|
|
54
|
+
new.add_argument('--output',required=True,type=Path)
|
|
55
|
+
check = commands.add_parser('check',allow_abbrev=False)
|
|
56
|
+
check.add_argument('--plan',required=True,action='append',type=Path)
|
|
57
|
+
check.add_argument('--current-bundle',type=Path)
|
|
58
|
+
check.add_argument('--manifest',type=Path)
|
|
59
|
+
apply = commands.add_parser('apply',allow_abbrev=False)
|
|
60
|
+
apply.add_argument('--plan',required=True,type=Path)
|
|
61
|
+
apply.add_argument('--dsn',default='')
|
|
62
|
+
apply.add_argument('--approved-digest',help='Legacy plan-digest gate; does not create host approval')
|
|
63
|
+
apply.add_argument('--expected-head',help='Prior entryDigest, or initial for an empty installation')
|
|
64
|
+
apply.add_argument('--person-role',action='append',default=[])
|
|
65
|
+
apply.add_argument('--repair-invalid',action='store_true')
|
|
66
|
+
_add_host_arguments(apply, include_receipt=True)
|
|
67
|
+
approve = commands.add_parser('approve',aliases=['record-approval'],allow_abbrev=False)
|
|
68
|
+
approve.add_argument('--plan',required=True,type=Path)
|
|
69
|
+
approve.add_argument('--dsn',default='')
|
|
70
|
+
approve.add_argument('--expected-head',required=True,help='Prior entryDigest for the installed predecessor')
|
|
71
|
+
approve.add_argument('--decision',choices=('approved','denied'),default='approved')
|
|
72
|
+
approve.add_argument('--person-role',action='append',default=[])
|
|
73
|
+
_add_host_arguments(approve)
|
|
74
|
+
args = parser.parse_args(argv)
|
|
75
|
+
try:
|
|
76
|
+
if args.command == 'new':
|
|
77
|
+
from umf_codegen import compile_table_migration
|
|
78
|
+
|
|
79
|
+
request = _load(args.request)
|
|
80
|
+
if set(request)-{'id','predecessor','previous','next','options'} or not {'id','predecessor','previous','next'} <= set(request):
|
|
81
|
+
raise CatalogError('migration-request-shape')
|
|
82
|
+
result = compile_table_migration(migration_id=request['id'],predecessor=request['predecessor'],
|
|
83
|
+
previous_bundle=request['previous'],next_bundle=request['next'],options=request.get('options'))
|
|
84
|
+
if result['status'] != 'compiled':
|
|
85
|
+
print(json.dumps(result),file=sys.stderr)
|
|
86
|
+
return 1
|
|
87
|
+
with args.output.open('x',encoding='utf-8') as output:
|
|
88
|
+
output.write(json.dumps(result['plan'],ensure_ascii=False,indent=2)+'\n')
|
|
89
|
+
response = {'status':'created','digest':result['plan']['digest']}
|
|
90
|
+
elif args.command == 'check':
|
|
91
|
+
response = check_chain(args.plan,current_bundle=_load(args.current_bundle) if args.current_bundle else None,
|
|
92
|
+
manifest=_load(args.manifest) if args.manifest else None)
|
|
93
|
+
elif args.command == 'approve' or args.command == 'record-approval':
|
|
94
|
+
from psycopg import connect
|
|
95
|
+
from umf_codegen import verify_table_migration
|
|
96
|
+
|
|
97
|
+
raw = args.plan.read_bytes()
|
|
98
|
+
plan = verify_table_migration(json.loads(raw))
|
|
99
|
+
_require_host_profile(plan)
|
|
100
|
+
_require_host_arguments(args)
|
|
101
|
+
head = _required_head(args.expected_head)
|
|
102
|
+
file_digest = hashlib.sha256(raw).hexdigest()
|
|
103
|
+
with connect(args.dsn,autocommit=True) as connection:
|
|
104
|
+
_set_owner(connection,plan)
|
|
105
|
+
host = PsycopgMigrationHost(connection,
|
|
106
|
+
person_roles=tuple(args.person_role),target_profile=args.target_profile,
|
|
107
|
+
installation_id=args.installation_id)
|
|
108
|
+
request = MigrationRequest(plan,head,file_digest)
|
|
109
|
+
receipt = host.record_approval(request,decision=args.decision,
|
|
110
|
+
qualification_profile=args.qualification_profile,
|
|
111
|
+
evidence_digest=args.evidence_digest)
|
|
112
|
+
response = {'status':'recorded','receiptId':receipt.receipt_id,
|
|
113
|
+
'decision':receipt.decision,'bindingDigest':receipt.binding_digest,
|
|
114
|
+
'installationId':args.installation_id,
|
|
115
|
+
'decider':receipt.decider,
|
|
116
|
+
'decidedAt':receipt.decided_at,
|
|
117
|
+
'qualificationProfile':receipt.qualification_profile,
|
|
118
|
+
'evidenceDigest':receipt.evidence_digest}
|
|
119
|
+
else:
|
|
120
|
+
from psycopg import connect
|
|
121
|
+
from umf_codegen import verify_table_migration
|
|
122
|
+
|
|
123
|
+
raw = args.plan.read_bytes()
|
|
124
|
+
plan = verify_table_migration(json.loads(raw))
|
|
125
|
+
if plan.get('version') in ('umf.table-migration/0.3','umf.table-migration/0.4','umf.table-migration/0.5'):
|
|
126
|
+
_require_host_arguments(args)
|
|
127
|
+
head = _required_head(args.expected_head)
|
|
128
|
+
else:
|
|
129
|
+
if args.expected_head is None:
|
|
130
|
+
raise CatalogError('migration-head-required')
|
|
131
|
+
head = None if args.expected_head == 'initial' else args.expected_head
|
|
132
|
+
file_digest = hashlib.sha256(raw).hexdigest()
|
|
133
|
+
if plan.get('version') in ('umf.table-migration/0.3','umf.table-migration/0.4','umf.table-migration/0.5'):
|
|
134
|
+
_require_host_profile(plan)
|
|
135
|
+
if args.repair_invalid:
|
|
136
|
+
raise CatalogError('repair-profile-unsupported')
|
|
137
|
+
if args.approved_digest is not None and args.approved_digest != plan['digest']:
|
|
138
|
+
raise CatalogError('migration-digest-mismatch')
|
|
139
|
+
if args.approval_id is None:
|
|
140
|
+
raise CatalogError('approval-receipt-required')
|
|
141
|
+
with connect(args.dsn,autocommit=True) as connection:
|
|
142
|
+
_set_owner(connection,plan)
|
|
143
|
+
host = PsycopgMigrationHost(connection,
|
|
144
|
+
person_roles=tuple(args.person_role),target_profile=args.target_profile,
|
|
145
|
+
installation_id=args.installation_id)
|
|
146
|
+
response = apply_migration_on_host(host,plan,expected_head=head,
|
|
147
|
+
file_digest=file_digest,qualification_profile=args.qualification_profile,
|
|
148
|
+
evidence_digest=args.evidence_digest,approval_id=args.approval_id)
|
|
149
|
+
else:
|
|
150
|
+
if args.approved_digest is None or args.approved_digest != plan['digest']:
|
|
151
|
+
raise CatalogError('approval-required')
|
|
152
|
+
with connect(args.dsn,autocommit=True) as connection:
|
|
153
|
+
owner = plan['next']['configuration']['ownerRole']
|
|
154
|
+
if plan.get('executionProfile') is not None:
|
|
155
|
+
_execute(connection,'SET ROLE '+_q(owner))
|
|
156
|
+
_execute(connection,'SET search_path=pg_catalog')
|
|
157
|
+
response = apply_mixed_migration(connection,plan,approved_digest=args.approved_digest,
|
|
158
|
+
expected_head=head,person_roles=tuple(args.person_role),file_digest=file_digest,
|
|
159
|
+
repair_invalid=args.repair_invalid)
|
|
160
|
+
elif any(s['transaction']=='forbidden' for s in plan['steps']):
|
|
161
|
+
_execute(connection,'SET ROLE '+_q(owner))
|
|
162
|
+
_execute(connection,'SET search_path=pg_catalog')
|
|
163
|
+
response = apply_concurrent_indexes(connection,plan,approved_digest=args.approved_digest,
|
|
164
|
+
expected_head=head,person_roles=tuple(args.person_role),repair_invalid=args.repair_invalid,file_digest=file_digest)
|
|
165
|
+
else:
|
|
166
|
+
if args.repair_invalid:
|
|
167
|
+
raise CatalogError('index-phase-profile')
|
|
168
|
+
with connection.transaction():
|
|
169
|
+
_execute(connection,'SET LOCAL ROLE '+_q(owner))
|
|
170
|
+
_execute(connection,'SET LOCAL search_path=pg_catalog')
|
|
171
|
+
response = apply_table_migration(connection,plan,approved_digest=args.approved_digest,
|
|
172
|
+
expected_head=head,person_roles=tuple(args.person_role),file_digest=file_digest)
|
|
173
|
+
response = {**response,'status':'committed','commitResponsibility':'runner'}
|
|
174
|
+
print(json.dumps(response))
|
|
175
|
+
return 0
|
|
176
|
+
except Exception as error: # noqa: BLE001 -- fixed sanitized process boundary, never DSN/native data
|
|
177
|
+
code = str(error) if isinstance(error,CatalogError) else getattr(error,'code','LIFECYCLE_FAILED')
|
|
178
|
+
payload = {'status':'blocked','code':code}
|
|
179
|
+
if isinstance(error,CatalogError) and error.sqlstate is not None:
|
|
180
|
+
payload['sqlstate'] = error.sqlstate
|
|
181
|
+
print(json.dumps(payload),file=sys.stderr)
|
|
182
|
+
return 1
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def _add_host_arguments(command, *, include_receipt=False):
|
|
186
|
+
command.add_argument('--installation-id',help='Stable trusted host identifier for this database installation')
|
|
187
|
+
command.add_argument('--target-profile',help='Host-selected target profile, e.g. local-postgresql18')
|
|
188
|
+
command.add_argument('--qualification-profile',help='Host qualification profile bound into the receipt')
|
|
189
|
+
command.add_argument('--evidence-digest',help='SHA-256 digest of the host qualification evidence')
|
|
190
|
+
if include_receipt:
|
|
191
|
+
command.add_argument('--approval-id',help='Exact host-issued approval receipt identifier')
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def _require_host_profile(plan):
|
|
195
|
+
expected_options = {
|
|
196
|
+
'umf.table-migration/0.3': 'umf.table-migration-options/0.3',
|
|
197
|
+
'umf.table-migration/0.4': 'umf.table-migration-options/0.4',
|
|
198
|
+
'umf.table-migration/0.5': 'umf.table-migration-options/0.5',
|
|
199
|
+
}
|
|
200
|
+
if (plan.get('version') not in expected_options
|
|
201
|
+
or plan.get('options', {}).get('version') != expected_options.get(plan.get('version'))
|
|
202
|
+
or plan.get('approvalProfile') != {
|
|
203
|
+
'version':'umf.table-migration-approval/0.1',
|
|
204
|
+
'relation':'umf_lifecycle_approvals','ownerOnly':True}):
|
|
205
|
+
raise CatalogError('host-migration-profile')
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def _require_host_arguments(args):
|
|
209
|
+
values = (args.installation_id,args.target_profile,args.qualification_profile)
|
|
210
|
+
if any(type(value) is not str or not value.strip() for value in values):
|
|
211
|
+
raise CatalogError('host-configuration-required')
|
|
212
|
+
if (type(args.evidence_digest) is not str
|
|
213
|
+
or len(args.evidence_digest) != 64
|
|
214
|
+
or any(char not in '0123456789abcdef' for char in args.evidence_digest)):
|
|
215
|
+
raise CatalogError('host-evidence-digest-invalid')
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def _required_head(value):
|
|
219
|
+
if value is None or value == 'initial':
|
|
220
|
+
raise CatalogError('migration-head-required')
|
|
221
|
+
return value
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def _set_owner(connection, plan):
|
|
225
|
+
owner = plan['next']['configuration']['ownerRole']
|
|
226
|
+
_execute(connection,'SET ROLE '+_q(owner))
|
|
227
|
+
_execute(connection,'SET search_path=pg_catalog')
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
if __name__ == '__main__':
|
|
231
|
+
sys.exit(main())
|