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,1230 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT OR Apache-2.0
|
|
2
|
+
"""Execute compiled reads on the host's existing PostgreSQL connection.
|
|
3
|
+
|
|
4
|
+
No pools, credentials, compiler imports, role switches or runtime query lowering.
|
|
5
|
+
The supplied connection must be idle; the read owns only its own transaction.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import hashlib
|
|
11
|
+
import json
|
|
12
|
+
import math
|
|
13
|
+
import struct
|
|
14
|
+
import time
|
|
15
|
+
from collections.abc import AsyncGenerator, Generator, Mapping, Sequence
|
|
16
|
+
from contextlib import nullcontext
|
|
17
|
+
from decimal import Decimal
|
|
18
|
+
from typing import Any, Protocol, cast
|
|
19
|
+
|
|
20
|
+
from .codec_support import revalidate_model, validate_graph
|
|
21
|
+
from .pages import (
|
|
22
|
+
ReadContinuation,
|
|
23
|
+
ReadObligationUnmet,
|
|
24
|
+
ReadPage,
|
|
25
|
+
StaleContinuation,
|
|
26
|
+
StreamLimitReached,
|
|
27
|
+
stream_page_size,
|
|
28
|
+
)
|
|
29
|
+
from .related_keys import decode_related_keys, transport_spec
|
|
30
|
+
from .reviewed import (
|
|
31
|
+
CatalogRead,
|
|
32
|
+
P,
|
|
33
|
+
R,
|
|
34
|
+
ReadBuildError,
|
|
35
|
+
catalog_fence,
|
|
36
|
+
validate_list_parameters,
|
|
37
|
+
)
|
|
38
|
+
from .types import CodecError, StrictModel
|
|
39
|
+
from .values import validate_vector
|
|
40
|
+
from .verification import postgres_verification_cache
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class TimedOut(TimeoutError):
|
|
44
|
+
pass
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class Cursor(Protocol):
|
|
49
|
+
description: Any
|
|
50
|
+
|
|
51
|
+
def execute(self, query: str, params: Sequence[object] | Mapping[str, object] | None = None) -> object: ...
|
|
52
|
+
def fetchone(self) -> Any: ...
|
|
53
|
+
def fetchmany(self, size: int = 1) -> list[Any]: ...
|
|
54
|
+
# A cursor context may return a compatible delegate.
|
|
55
|
+
def __enter__(self) -> Cursor: ... # noqa: PYI034
|
|
56
|
+
def __exit__(self, *args: object) -> object: ...
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class Connection(Protocol):
|
|
60
|
+
info: Any
|
|
61
|
+
|
|
62
|
+
def cursor(self) -> Any: ...
|
|
63
|
+
def transaction(self) -> Any: ...
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class _DeadlineCursor:
|
|
67
|
+
def __init__(self, cursor: Cursor, deadline: float) -> None:
|
|
68
|
+
self.raw = cursor
|
|
69
|
+
self.deadline = deadline
|
|
70
|
+
|
|
71
|
+
@property
|
|
72
|
+
def description(self) -> Any:
|
|
73
|
+
return self.raw.description
|
|
74
|
+
|
|
75
|
+
def check(self) -> int:
|
|
76
|
+
remaining = math.ceil((self.deadline - time.monotonic()) * 1000)
|
|
77
|
+
if remaining <= 0:
|
|
78
|
+
raise TimedOut("catalog read exceeded its per-call timeout")
|
|
79
|
+
return remaining
|
|
80
|
+
|
|
81
|
+
def execute(self, query: str, params: Sequence[object] | Mapping[str, object] | None = None) -> object:
|
|
82
|
+
self.raw.execute(
|
|
83
|
+
"SELECT pg_catalog.set_config('statement_timeout', %s, true)",
|
|
84
|
+
(str(self.check()),),
|
|
85
|
+
)
|
|
86
|
+
return self.raw.execute(query, params)
|
|
87
|
+
|
|
88
|
+
def fetchone(self) -> Any:
|
|
89
|
+
self.check()
|
|
90
|
+
return self.raw.fetchone()
|
|
91
|
+
|
|
92
|
+
def fetchmany(self, size: int = 1) -> list[Any]:
|
|
93
|
+
self.check()
|
|
94
|
+
return self.raw.fetchmany(size)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
_ROLE = """SELECT current_user, session_user, r.rolsuper, r.rolbypassrls
|
|
98
|
+
FROM pg_catalog.pg_roles r WHERE r.rolname = current_user"""
|
|
99
|
+
_TABLE = """SELECT c.oid, c.relkind, c.relrowsecurity, c.relforcerowsecurity,
|
|
100
|
+
pg_catalog.pg_has_role(current_user, c.relowner, 'USAGE')
|
|
101
|
+
FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
|
|
102
|
+
WHERE n.nspname = %s AND c.relname = %s
|
|
103
|
+
AND NOT EXISTS (SELECT 1 FROM pg_catalog.pg_inherits inheritance
|
|
104
|
+
WHERE inheritance.inhrelid = c.oid OR inheritance.inhparent = c.oid)"""
|
|
105
|
+
_COLUMNS = """SELECT a.attname, tn.nspname, t.typname, a.attnotnull
|
|
106
|
+
FROM pg_catalog.pg_attribute a JOIN pg_catalog.pg_type t ON t.oid = a.atttypid
|
|
107
|
+
JOIN pg_catalog.pg_namespace tn ON tn.oid = t.typnamespace
|
|
108
|
+
WHERE a.attrelid = %s AND a.attnum > 0 AND NOT a.attisdropped"""
|
|
109
|
+
# Equality and ordering must agree with the operators used by the compiled SQL.
|
|
110
|
+
# Attribute-number coincidence alone does not prove a to-one/keyset Key.
|
|
111
|
+
_KEYS = """SELECT ARRAY(SELECT a.attname FROM pg_catalog.unnest(i.indkey) WITH ORDINALITY AS k(attnum, pos)
|
|
112
|
+
JOIN pg_catalog.pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = k.attnum
|
|
113
|
+
WHERE k.pos <= i.indnkeyatts ORDER BY k.pos)
|
|
114
|
+
FROM pg_catalog.pg_index i
|
|
115
|
+
JOIN pg_catalog.pg_class ix ON ix.oid = i.indexrelid
|
|
116
|
+
JOIN pg_catalog.pg_am am ON am.oid = ix.relam
|
|
117
|
+
WHERE i.indrelid = %s AND i.indisunique AND i.indisvalid AND i.indisready
|
|
118
|
+
AND i.indpred IS NULL AND i.indexprs IS NULL AND i.indimmediate AND am.amname = 'btree'
|
|
119
|
+
AND NOT EXISTS (
|
|
120
|
+
SELECT 1 FROM pg_catalog.unnest(i.indkey) WITH ORDINALITY AS k(attnum, pos)
|
|
121
|
+
JOIN pg_catalog.pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = k.attnum
|
|
122
|
+
JOIN pg_catalog.pg_type t ON t.oid = a.atttypid
|
|
123
|
+
JOIN pg_catalog.pg_namespace tn ON tn.oid = t.typnamespace
|
|
124
|
+
LEFT JOIN pg_catalog.pg_opclass op ON op.oid = i.indclass[(k.pos - 1)::integer]
|
|
125
|
+
LEFT JOIN pg_catalog.pg_namespace ons ON ons.oid = op.opcnamespace
|
|
126
|
+
LEFT JOIN pg_catalog.pg_collation co ON co.oid = a.attcollation
|
|
127
|
+
WHERE k.pos <= i.indnkeyatts AND (
|
|
128
|
+
a.attnotnull AND tn.nspname = 'pg_catalog' AND ons.nspname = 'pg_catalog'
|
|
129
|
+
AND op.opcmethod = ix.relam
|
|
130
|
+
AND op.opcname = CASE t.typname WHEN 'int2' THEN 'int2_ops' WHEN 'int4' THEN 'int4_ops'
|
|
131
|
+
WHEN 'int8' THEN 'int8_ops' WHEN 'numeric' THEN 'numeric_ops'
|
|
132
|
+
WHEN 'text' THEN 'text_ops' WHEN 'varchar' THEN 'text_ops' WHEN 'bool' THEN 'bool_ops' END
|
|
133
|
+
AND i.indcollation[(k.pos - 1)::integer] = a.attcollation
|
|
134
|
+
AND (a.attcollation = 0 OR co.collisdeterministic)
|
|
135
|
+
) IS NOT TRUE
|
|
136
|
+
)"""
|
|
137
|
+
|
|
138
|
+
_TYPES = {"integer": {"int2", "int4", "int8"}, "decimal": {"numeric"},
|
|
139
|
+
"string": {"text", "varchar"}, "boolean": {"bool"}}
|
|
140
|
+
|
|
141
|
+
# Native metadata only. Full rows here contain catalog scalars/arrays, never
|
|
142
|
+
# application datums or a user-supplied expression to execute. Observe every
|
|
143
|
+
# requested relation, including missing ones; a hash of a partial result is not
|
|
144
|
+
# a verification proof. This fingerprint is not an authorization cache.
|
|
145
|
+
_SHAPE = """SELECT c.oid, n.nspname, c.relname,
|
|
146
|
+
pg_catalog.jsonb_build_object(
|
|
147
|
+
'table', pg_catalog.jsonb_build_array(c.relkind,c.relowner,c.relrowsecurity,c.relforcerowsecurity),
|
|
148
|
+
'inheritance', (SELECT pg_catalog.jsonb_agg(pg_catalog.to_jsonb(inheritance) ORDER BY inheritance.inhrelid,inheritance.inhseqno)
|
|
149
|
+
FROM pg_catalog.pg_inherits inheritance WHERE inheritance.inhrelid=c.oid OR inheritance.inhparent=c.oid),
|
|
150
|
+
'columns', (SELECT pg_catalog.jsonb_agg(pg_catalog.jsonb_build_array(
|
|
151
|
+
a.attnum,a.attname,a.atttypid,a.atttypmod,a.attnotnull,a.attidentity,a.attgenerated,
|
|
152
|
+
a.attisdropped,a.atthasdef,a.attcollation,tn.nspname,pg_catalog.to_jsonb(t),pg_catalog.to_jsonb(co)) ORDER BY a.attnum)
|
|
153
|
+
FROM pg_catalog.pg_attribute a
|
|
154
|
+
LEFT JOIN pg_catalog.pg_type t ON t.oid=a.atttypid
|
|
155
|
+
LEFT JOIN pg_catalog.pg_namespace tn ON tn.oid=t.typnamespace
|
|
156
|
+
LEFT JOIN pg_catalog.pg_collation co ON co.oid=a.attcollation
|
|
157
|
+
WHERE a.attrelid=c.oid AND a.attnum>0),
|
|
158
|
+
'keys', (SELECT pg_catalog.jsonb_agg(pg_catalog.jsonb_build_array(pg_catalog.to_jsonb(i),ix.relam,
|
|
159
|
+
(SELECT pg_catalog.jsonb_agg(pg_catalog.jsonb_build_array(k.pos,pg_catalog.to_jsonb(op),ons.nspname,
|
|
160
|
+
pg_catalog.to_jsonb(family),fns.nspname,
|
|
161
|
+
(SELECT pg_catalog.jsonb_agg(pg_catalog.to_jsonb(member) ORDER BY member.oid)
|
|
162
|
+
FROM pg_catalog.pg_amop member WHERE member.amopfamily=op.opcfamily)) ORDER BY k.pos)
|
|
163
|
+
FROM pg_catalog.unnest(i.indclass) WITH ORDINALITY k(classoid,pos)
|
|
164
|
+
LEFT JOIN pg_catalog.pg_opclass op ON op.oid=k.classoid
|
|
165
|
+
LEFT JOIN pg_catalog.pg_namespace ons ON ons.oid=op.opcnamespace
|
|
166
|
+
LEFT JOIN pg_catalog.pg_opfamily family ON family.oid=op.opcfamily
|
|
167
|
+
LEFT JOIN pg_catalog.pg_namespace fns ON fns.oid=family.opfnamespace),pg_catalog.to_jsonb(am)) ORDER BY i.indexrelid)
|
|
168
|
+
FROM pg_catalog.pg_index i JOIN pg_catalog.pg_class ix ON ix.oid=i.indexrelid
|
|
169
|
+
JOIN pg_catalog.pg_am am ON am.oid=ix.relam WHERE i.indrelid=c.oid),
|
|
170
|
+
'extensions', (SELECT pg_catalog.jsonb_agg(pg_catalog.jsonb_build_array(e.oid,e.extname,e.extnamespace,e.extversion) ORDER BY e.oid)
|
|
171
|
+
FROM pg_catalog.pg_extension e)
|
|
172
|
+
)::pg_catalog.text
|
|
173
|
+
FROM pg_catalog.unnest(%s::pg_catalog.oid[]) WITH ORDINALITY wanted(id,pos)
|
|
174
|
+
LEFT JOIN pg_catalog.pg_class c ON c.oid=wanted.id
|
|
175
|
+
LEFT JOIN pg_catalog.pg_namespace n ON n.oid=c.relnamespace ORDER BY wanted.pos"""
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def _shape_fingerprint(native_ids: list[object], app_schema: str) -> Generator[tuple[Any, ...], Any, str]:
|
|
179
|
+
relations = cast(list[tuple[str, int]], native_ids)
|
|
180
|
+
yield ("execute", _SHAPE, ([oid for _, oid in relations],))
|
|
181
|
+
rows = yield ("many", len(relations) + 1)
|
|
182
|
+
if len(rows) != len(relations):
|
|
183
|
+
raise ReadObligationUnmet("native verification relation inventory differs")
|
|
184
|
+
for row, (name, oid) in zip(rows, relations, strict=True):
|
|
185
|
+
if (
|
|
186
|
+
not isinstance(row, (list, tuple)) or len(row) != 4
|
|
187
|
+
or row[:3] not in ((oid, app_schema, name), [oid, app_schema, name])
|
|
188
|
+
or type(row[3]) is not str or not row[3] or len(row[3]) > 8_388_608
|
|
189
|
+
):
|
|
190
|
+
raise ReadObligationUnmet("native verification metadata is missing or differs")
|
|
191
|
+
return hashlib.sha256(json.dumps(rows, separators=(",", ":")).encode()).hexdigest()
|
|
192
|
+
|
|
193
|
+
_RESOLUTION = """WITH context AS MATERIALIZED (
|
|
194
|
+
SELECT pg_catalog.current_database()::pg_catalog.text AS database_name,
|
|
195
|
+
(pg_catalog.pg_control_system()).system_identifier::pg_catalog.text AS system_id,
|
|
196
|
+
pg_catalog.current_schemas(true) AS schemas, current_user::pg_catalog.text AS actor,
|
|
197
|
+
session_user::pg_catalog.text AS session_actor,
|
|
198
|
+
(SELECT oid FROM pg_catalog.pg_database WHERE datname=pg_catalog.current_database()) AS database_oid
|
|
199
|
+
)
|
|
200
|
+
SELECT context.database_name, context.system_id, context.schemas,
|
|
201
|
+
wanted.name, n.nspname, c.oid, context.actor, context.session_actor, context.database_oid
|
|
202
|
+
FROM context CROSS JOIN pg_catalog.unnest(%s::pg_catalog.text[]) WITH ORDINALITY AS wanted(name,position)
|
|
203
|
+
LEFT JOIN pg_catalog.pg_class c ON c.oid = pg_catalog.to_regclass(
|
|
204
|
+
CASE WHEN %s THEN pg_catalog.quote_ident(%s) || '.' || pg_catalog.quote_ident(wanted.name)
|
|
205
|
+
ELSE pg_catalog.quote_ident(wanted.name) END)
|
|
206
|
+
LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace ORDER BY wanted.position"""
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def _resolution_context(rows: list[Any], names: list[str], app_schema: str, mode: str, database: str) -> tuple[object, ...]:
|
|
210
|
+
if len(rows) != len(names) or not rows:
|
|
211
|
+
raise ReadObligationUnmet("native relation resolution inventory differs")
|
|
212
|
+
context = None
|
|
213
|
+
identities = []
|
|
214
|
+
for row, name in zip(rows, names, strict=True):
|
|
215
|
+
if (
|
|
216
|
+
not isinstance(row, (list, tuple)) or len(row) != 9 or row[0] != database
|
|
217
|
+
or type(row[1]) is not str or not row[1].isascii() or not row[1].isdecimal()
|
|
218
|
+
or type(row[2]) is not list or not row[2]
|
|
219
|
+
or any(type(schema) is not str for schema in row[2])
|
|
220
|
+
or mode == "search-path" and row[2][0] != "pg_catalog"
|
|
221
|
+
or row[3] != name or row[4] != app_schema
|
|
222
|
+
or type(row[5]) is not int or row[5] < 1
|
|
223
|
+
or any(type(row[i]) is not str or not row[i] for i in (6, 7))
|
|
224
|
+
or type(row[8]) is not int or row[8] < 1
|
|
225
|
+
):
|
|
226
|
+
raise ReadObligationUnmet("native database, schema, path or relation differs from host binding")
|
|
227
|
+
current = (row[0], row[1], row[6], row[7], row[8])
|
|
228
|
+
if context is not None and current != context:
|
|
229
|
+
raise ReadObligationUnmet("native connection identity changed during resolution")
|
|
230
|
+
context = current
|
|
231
|
+
identities.append((name, row[4], row[5]))
|
|
232
|
+
return (mode, app_schema, context, tuple(identities))
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def _observe_resolution(binding: dict[str, object], app_schema: str, mode: str, database: str) -> Generator[tuple[Any, ...], Any, tuple[object, ...]]:
|
|
236
|
+
names = sorted({str(table["native"]) for table in cast(list[dict[str, object]], binding["tables"])})
|
|
237
|
+
if not 1 <= len(names) <= 2000:
|
|
238
|
+
raise ReadObligationUnmet("bounded native relation inventory required")
|
|
239
|
+
yield ("execute", _RESOLUTION, (names, mode == "qualified", app_schema))
|
|
240
|
+
rows = yield ("many", len(names) + 1)
|
|
241
|
+
return _resolution_context(rows, names, app_schema, mode, database)
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def _catalog_fence_programs(
|
|
245
|
+
artifact: Mapping[str, object],
|
|
246
|
+
) -> tuple[str, tuple[tuple[str, dict[str, object]], ...]] | None:
|
|
247
|
+
"""Bind only original owner fence programs; deployment remains inert."""
|
|
248
|
+
packet = catalog_fence(artifact)
|
|
249
|
+
if packet is None:
|
|
250
|
+
return None
|
|
251
|
+
admissions = _compiled_admissions([{"nativeAdmission": packet["nativeAdmission"]}], "")
|
|
252
|
+
return cast(str, packet["lockSql"]), admissions
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def _snapshot_free_timeout(deadline: float) -> str:
|
|
256
|
+
"""Session-control utility with a validated integer, before any snapshot."""
|
|
257
|
+
if not math.isfinite(deadline):
|
|
258
|
+
raise ValueError("finite absolute deadline required")
|
|
259
|
+
milliseconds = math.ceil((deadline - time.monotonic()) * 1000)
|
|
260
|
+
if milliseconds <= 0:
|
|
261
|
+
raise TimedOut("deadline expired before native catalog fence")
|
|
262
|
+
if milliseconds > 2_147_483_647:
|
|
263
|
+
raise ValueError("deadline exceeds native PostgreSQL timeout bound")
|
|
264
|
+
return "SET LOCAL statement_timeout = '" + str(milliseconds) + "ms'"
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def _snapshot_free_search_path(app_schema: str) -> str:
|
|
268
|
+
"""Preserve legacy host schema selection without assigning a snapshot."""
|
|
269
|
+
try:
|
|
270
|
+
valid = (type(app_schema) is str and "\x00" not in app_schema
|
|
271
|
+
and 1 <= len(app_schema.encode("utf-8")) <= 63)
|
|
272
|
+
except UnicodeEncodeError:
|
|
273
|
+
valid = False
|
|
274
|
+
if not valid:
|
|
275
|
+
raise ReadObligationUnmet("valid native application schema required")
|
|
276
|
+
return 'SET LOCAL search_path = pg_catalog, "' + app_schema.replace('"', '""') + '", pg_temp'
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def _early_relation_locks(
|
|
280
|
+
binding: Mapping[str, object], lock_sql: Sequence[str], app_schema: str,
|
|
281
|
+
) -> Generator[tuple[Any, ...], Any, None]:
|
|
282
|
+
"""Execute opaque original locks in their original binding context."""
|
|
283
|
+
locks = tuple(dict.fromkeys(lock_sql))
|
|
284
|
+
if locks and binding.get("schemaBinding") is None and binding.get("schema") is None:
|
|
285
|
+
yield ("snapshot-free", _snapshot_free_search_path(app_schema))
|
|
286
|
+
for sql in locks:
|
|
287
|
+
yield ("snapshot-free", sql)
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
def _term_admissions(
|
|
291
|
+
obligations: dict[str, object], app_schema: str
|
|
292
|
+
) -> tuple[tuple[str, dict[str, object]], ...]:
|
|
293
|
+
"""Bind retained compiler programs; never construct or lower admission SQL."""
|
|
294
|
+
if "termFilter" not in obligations:
|
|
295
|
+
return ()
|
|
296
|
+
term = obligations["termFilter"]
|
|
297
|
+
if (
|
|
298
|
+
not isinstance(term, dict)
|
|
299
|
+
or term.get("version") != "umf.raw-term-filter/0.1"
|
|
300
|
+
or term.get("nativeCatalogBeforeAfter") is not True
|
|
301
|
+
or not isinstance(term.get("indexes"), list)
|
|
302
|
+
or not term["indexes"]
|
|
303
|
+
):
|
|
304
|
+
raise ReadBuildError("unsupported native term-filter obligation")
|
|
305
|
+
return _compiled_admissions(term["indexes"], app_schema)
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def _projection_admissions(
|
|
309
|
+
obligations: dict[str, object], app_schema: str
|
|
310
|
+
) -> tuple[tuple[str, dict[str, object]], ...]:
|
|
311
|
+
if "nativeProjection" not in obligations:
|
|
312
|
+
raise ReadBuildError("NATIVE_SCHEMA_SOURCE_EXACT_REQUIRED")
|
|
313
|
+
projection = obligations["nativeProjection"]
|
|
314
|
+
if (
|
|
315
|
+
not isinstance(projection, dict)
|
|
316
|
+
or projection.get("version") != "umf.native-columns/0.1"
|
|
317
|
+
or projection.get("verificationProfile") != "source-exact/0.1"
|
|
318
|
+
or projection.get("nativeCatalogBeforeAfter") is not True
|
|
319
|
+
or not isinstance(projection.get("columns"), list)
|
|
320
|
+
or not 1 <= len(projection["columns"]) <= 2000
|
|
321
|
+
):
|
|
322
|
+
raise ReadBuildError("unsupported original native projection obligation")
|
|
323
|
+
return _compiled_admissions(projection["columns"], app_schema)
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
def _relationship_admissions(
|
|
327
|
+
obligations: dict[str, object], app_schema: str
|
|
328
|
+
) -> tuple[tuple[str, dict[str, object]], ...]:
|
|
329
|
+
if "nativeRelationshipKeys" not in obligations:
|
|
330
|
+
return ()
|
|
331
|
+
descriptor = obligations["nativeRelationshipKeys"]
|
|
332
|
+
if (
|
|
333
|
+
not isinstance(descriptor, dict)
|
|
334
|
+
or descriptor.get("version") != "umf.native-relationship-keys/0.1"
|
|
335
|
+
or descriptor.get("nativeCatalogBeforeAfter") is not True
|
|
336
|
+
or not isinstance(descriptor.get("keys"), list)
|
|
337
|
+
or not 1 <= len(descriptor["keys"]) <= 2000
|
|
338
|
+
):
|
|
339
|
+
raise ReadBuildError("unsupported original native relationship Key obligation")
|
|
340
|
+
for key in descriptor["keys"]:
|
|
341
|
+
if not isinstance(key, dict):
|
|
342
|
+
raise ReadBuildError("malformed original relationship Key")
|
|
343
|
+
table, logical, native = (key.get(name) for name in ("logicalTable", "logicalFields", "nativeFields"))
|
|
344
|
+
if (
|
|
345
|
+
not isinstance(table, list) or len(table) != 2
|
|
346
|
+
or not isinstance(logical, list) or not 1 <= len(logical) <= 16
|
|
347
|
+
or not isinstance(native, list) or len(native) != len(logical)
|
|
348
|
+
or any(type(name) is not str for name in table)
|
|
349
|
+
or any(type(name) is not str or not name or "\x00" in name for name in logical + native)
|
|
350
|
+
or len(set(logical)) != len(logical) or len(set(native)) != len(native)
|
|
351
|
+
):
|
|
352
|
+
raise ReadBuildError("malformed original relationship Key inventory")
|
|
353
|
+
return _compiled_admissions(descriptor["keys"], app_schema)
|
|
354
|
+
|
|
355
|
+
|
|
356
|
+
def _native_relationship_admissions(
|
|
357
|
+
obligations: dict[str, object], app_schema: str
|
|
358
|
+
) -> tuple[tuple[str, dict[str, object]], ...]:
|
|
359
|
+
if "nativeRelationships" not in obligations:
|
|
360
|
+
return ()
|
|
361
|
+
descriptor = obligations["nativeRelationships"]
|
|
362
|
+
if (
|
|
363
|
+
not isinstance(descriptor, dict)
|
|
364
|
+
or descriptor.get("version") != "umf.native-relationships/0.1"
|
|
365
|
+
or descriptor.get("nativeCatalogBeforeAfter") is not True
|
|
366
|
+
or not isinstance(descriptor.get("relationships"), list)
|
|
367
|
+
or not 1 <= len(descriptor["relationships"]) <= 2000
|
|
368
|
+
):
|
|
369
|
+
raise ReadBuildError("unsupported original native relationship obligation")
|
|
370
|
+
for relation in descriptor["relationships"]:
|
|
371
|
+
if not isinstance(relation, dict):
|
|
372
|
+
raise ReadBuildError("malformed original native relationship")
|
|
373
|
+
if any(type(relation.get(name)) is not str for name in ("module", "id")):
|
|
374
|
+
raise ReadBuildError("original relationship identity required")
|
|
375
|
+
for name in ("sourceTable", "targetTable"):
|
|
376
|
+
table = relation.get(name)
|
|
377
|
+
if not isinstance(table, list) or len(table) != 2 or any(type(value) is not str for value in table):
|
|
378
|
+
raise ReadBuildError("original relationship endpoint required")
|
|
379
|
+
logical, native = relation.get("logicalPairs"), relation.get("nativePairs")
|
|
380
|
+
if (
|
|
381
|
+
not isinstance(logical, list) or not 1 <= len(logical) <= 16
|
|
382
|
+
or not isinstance(native, list) or len(native) != len(logical)
|
|
383
|
+
or any(not isinstance(pair, list) or len(pair) != 2
|
|
384
|
+
or any(type(value) is not str or not value for value in pair) for pair in logical + native)
|
|
385
|
+
or type(relation.get("completeNativeSnapshotRequired")) is not bool
|
|
386
|
+
):
|
|
387
|
+
raise ReadBuildError("original relationship pair/snapshot inventory required")
|
|
388
|
+
if relation["completeNativeSnapshotRequired"] and obligations.get("readIsolation") != "repeatable-read":
|
|
389
|
+
raise ReadBuildError("complete native relationship scope requires original repeatable-read obligation")
|
|
390
|
+
return _compiled_admissions(descriptor["relationships"], app_schema)
|
|
391
|
+
|
|
392
|
+
|
|
393
|
+
def _compiled_admissions(
|
|
394
|
+
descriptors: list[Any], app_schema: str
|
|
395
|
+
) -> tuple[tuple[str, dict[str, object]], ...]:
|
|
396
|
+
"""Bind original owner metadata programs, shared by independent profiles."""
|
|
397
|
+
result = []
|
|
398
|
+
for index in descriptors:
|
|
399
|
+
admission = index.get("nativeAdmission") if isinstance(index, dict) else None
|
|
400
|
+
if (
|
|
401
|
+
not isinstance(admission, dict)
|
|
402
|
+
or not isinstance(admission.get("dbapiSql"), str)
|
|
403
|
+
or not admission["dbapiSql"]
|
|
404
|
+
or not isinstance(admission.get("parameters"), list)
|
|
405
|
+
):
|
|
406
|
+
raise ReadBuildError("missing compiled native metadata admission")
|
|
407
|
+
values: dict[str, object] = {}
|
|
408
|
+
for parameter in admission["parameters"]:
|
|
409
|
+
if not isinstance(parameter, dict):
|
|
410
|
+
raise ReadBuildError("malformed native metadata admission parameter")
|
|
411
|
+
name, source = parameter.get("name"), parameter.get("source")
|
|
412
|
+
if not isinstance(name, str) or not name or name in values or parameter.get("carrier") != "string":
|
|
413
|
+
raise ReadBuildError("invalid native metadata admission parameter")
|
|
414
|
+
if isinstance(source, dict) and set(source) == {"appSchema"} and source["appSchema"] is True:
|
|
415
|
+
values[name] = app_schema
|
|
416
|
+
elif (
|
|
417
|
+
isinstance(source, dict)
|
|
418
|
+
and set(source) == {"literal"}
|
|
419
|
+
and isinstance(source["literal"], dict)
|
|
420
|
+
and set(source["literal"]) == {"string"}
|
|
421
|
+
and isinstance(source["literal"]["string"], str)
|
|
422
|
+
):
|
|
423
|
+
values[name] = source["literal"]["string"]
|
|
424
|
+
else:
|
|
425
|
+
raise ReadBuildError("unsupported native metadata admission source")
|
|
426
|
+
if admission.get("dbapiParameterOrder") != list(values):
|
|
427
|
+
raise ReadBuildError("native metadata admission parameter inventory differs")
|
|
428
|
+
result.append((admission["dbapiSql"], values))
|
|
429
|
+
return tuple(result)
|
|
430
|
+
|
|
431
|
+
|
|
432
|
+
def _verify_terms(
|
|
433
|
+
admissions: tuple[tuple[str, dict[str, object]], ...],
|
|
434
|
+
) -> Generator[tuple[Any, ...], Any, None]:
|
|
435
|
+
yield from _verify_admissions(admissions, "native keyword index or analyzer differs from catalog")
|
|
436
|
+
|
|
437
|
+
|
|
438
|
+
def _verify_admissions(
|
|
439
|
+
admissions: tuple[tuple[str, dict[str, object]], ...], message: str
|
|
440
|
+
) -> Generator[tuple[Any, ...], Any, None]:
|
|
441
|
+
for sql, values in admissions:
|
|
442
|
+
yield ("execute", sql, values)
|
|
443
|
+
rows = yield ("many", 2)
|
|
444
|
+
if len(rows) != 1 or len(rows[0]) != 1 or rows[0][0] is not True:
|
|
445
|
+
raise ReadObligationUnmet(message)
|
|
446
|
+
|
|
447
|
+
|
|
448
|
+
def _vector_output(value: object, output: Mapping[str, Any]) -> object:
|
|
449
|
+
"""Decode the original pgvector native float32 text-output profile only."""
|
|
450
|
+
decoder = output.get("decoder")
|
|
451
|
+
if (
|
|
452
|
+
not isinstance(decoder, dict)
|
|
453
|
+
or decoder.get("profile") not in (
|
|
454
|
+
"pgvector-text-float32/0.8.6", "pgvector-text-float32/0.8.7"
|
|
455
|
+
)
|
|
456
|
+
or type(decoder.get("dimensions")) is not int
|
|
457
|
+
or decoder["dimensions"] < 1
|
|
458
|
+
or type(value) is not str
|
|
459
|
+
or len(value) > 500_000
|
|
460
|
+
):
|
|
461
|
+
raise ReadObligationUnmet("native vector decoder profile mismatch")
|
|
462
|
+
try:
|
|
463
|
+
items = json.loads(value, parse_int=float, parse_float=float)
|
|
464
|
+
if (
|
|
465
|
+
not isinstance(items, list)
|
|
466
|
+
or len(items) != decoder["dimensions"]
|
|
467
|
+
or any(type(item) is not float for item in items)
|
|
468
|
+
):
|
|
469
|
+
raise ValueError("native vector output inventory mismatch")
|
|
470
|
+
# pgvector's native text uses shortest float32 spellings. Reconstruct
|
|
471
|
+
# those native values; this decoder is never used for input vectors.
|
|
472
|
+
result = tuple(struct.unpack("!f", struct.pack("!f", item))[0] for item in items)
|
|
473
|
+
return validate_vector(result, dimensions=decoder["dimensions"])
|
|
474
|
+
except (ValueError, OverflowError, struct.error) as error:
|
|
475
|
+
raise ReadObligationUnmet("native vector output differs from its profile") from error
|
|
476
|
+
|
|
477
|
+
|
|
478
|
+
def _output_value(value: object, output: dict[str, object], *, key_model: type[StrictModel] | None = None) -> object:
|
|
479
|
+
if output.get("carrier") == "related-keys":
|
|
480
|
+
if key_model is None:
|
|
481
|
+
raise ReadObligationUnmet("original generated relationship Key class required")
|
|
482
|
+
try:
|
|
483
|
+
return decode_related_keys(value, output.get("decoder"), key_model)
|
|
484
|
+
except CodecError:
|
|
485
|
+
raise ReadObligationUnmet("native related-Key output differs from original decoder") from None
|
|
486
|
+
if output.get("carrier") in ("binary", "vector"):
|
|
487
|
+
if value is None:
|
|
488
|
+
if output.get("nullable") is not True:
|
|
489
|
+
raise ReadObligationUnmet("native projection returned forbidden NULL")
|
|
490
|
+
return None
|
|
491
|
+
if output["carrier"] == "vector":
|
|
492
|
+
return _vector_output(value, output)
|
|
493
|
+
if output.get("decoder") != {"profile": "pg-bytea/0.1"} or type(value) not in (bytes, bytearray, memoryview):
|
|
494
|
+
raise ReadObligationUnmet("native binary decoder profile mismatch")
|
|
495
|
+
return bytes(value)
|
|
496
|
+
# PostgreSQL SUM(int8) and unbounded integer bucket expressions use NUMERIC.
|
|
497
|
+
# Decode only the compiler's Integer carrier, without rounding or allowing
|
|
498
|
+
# coercion of strings, floats, booleans or fractional/nonfinite NUMERICs.
|
|
499
|
+
if output.get("carrier") == "integer" and type(value) is Decimal:
|
|
500
|
+
if not value.is_finite() or value != value.to_integral_value():
|
|
501
|
+
raise ReadObligationUnmet("native numeric output differs from Integer carrier")
|
|
502
|
+
return int(value)
|
|
503
|
+
return value
|
|
504
|
+
|
|
505
|
+
|
|
506
|
+
|
|
507
|
+
|
|
508
|
+
def _check_cursor_value(field: dict[str,object], value: object) -> None:
|
|
509
|
+
expected={"integer":int,"decimal":Decimal,"string":str,"boolean":bool}.get(str(field["carrier"]))
|
|
510
|
+
if expected is None or value is None and not field['nullable'] or value is not None and type(value) is not expected or isinstance(value,Decimal) and not value.is_finite():
|
|
511
|
+
raise ReadObligationUnmet("cursor carrier differs from ordering")
|
|
512
|
+
|
|
513
|
+
|
|
514
|
+
def _checked_sort_values(fields: list[dict[str,object]], values: Sequence[object]) -> tuple[object,...]:
|
|
515
|
+
if len(fields)!=len(values): raise ReadObligationUnmet("cursor output inventory differs")
|
|
516
|
+
for field,value in zip(fields,values,strict=True):
|
|
517
|
+
_check_cursor_value(field, value)
|
|
518
|
+
return tuple(values)
|
|
519
|
+
|
|
520
|
+
|
|
521
|
+
def native_read_admission(
|
|
522
|
+
binding: dict[str, object], app_schema: str, lock_sql: tuple[str, ...],
|
|
523
|
+
*, cache_context: object | None = None, shape_proof: list[str] | None = None,
|
|
524
|
+
) -> Generator[tuple[Any, ...], Any, tuple[Any, list[object]]]:
|
|
525
|
+
"""Shared native role/table/key admission inside the caller's read snapshot."""
|
|
526
|
+
yield ("execute", _ROLE)
|
|
527
|
+
before = yield ("one",)
|
|
528
|
+
if before is None or before[2] or before[3]:
|
|
529
|
+
raise ReadObligationUnmet("caller role bypasses native row security")
|
|
530
|
+
# Locks are compiled by Weft. They stabilize names and native facts
|
|
531
|
+
# until this transaction ends; none are constructed from call input.
|
|
532
|
+
for sql in lock_sql:
|
|
533
|
+
yield ("execute", sql)
|
|
534
|
+
native_ids: list[object] = []
|
|
535
|
+
for table in cast(list[dict[str, object]], binding["tables"]):
|
|
536
|
+
yield ("execute", _TABLE, (app_schema, table["native"]))
|
|
537
|
+
native = yield ("one",)
|
|
538
|
+
if (
|
|
539
|
+
native is None
|
|
540
|
+
or native[1] != "r"
|
|
541
|
+
or native[2]
|
|
542
|
+
and native[4]
|
|
543
|
+
and not native[3]
|
|
544
|
+
):
|
|
545
|
+
raise ReadObligationUnmet(
|
|
546
|
+
"bound base table missing or caller has owner RLS bypass"
|
|
547
|
+
)
|
|
548
|
+
native_ids.append((table["native"], native[0]))
|
|
549
|
+
yield (
|
|
550
|
+
"execute",
|
|
551
|
+
"SELECT pg_catalog.to_regclass(%s)::pg_catalog.oid",
|
|
552
|
+
('"' + str(table["native"]).replace('"', '""') + '"',),
|
|
553
|
+
)
|
|
554
|
+
if (yield ("one",))[0] != native[0]:
|
|
555
|
+
raise ReadObligationUnmet("search_path resolves table outside app schema")
|
|
556
|
+
cache_key = fingerprint = None
|
|
557
|
+
if cache_context is not None:
|
|
558
|
+
cache_key = hashlib.sha256(json.dumps([binding, cache_context, native_ids], sort_keys=True, separators=(",", ":")).encode()).hexdigest()
|
|
559
|
+
fingerprint = yield from _shape_fingerprint(native_ids, app_schema)
|
|
560
|
+
if shape_proof is not None:
|
|
561
|
+
shape_proof.append(fingerprint)
|
|
562
|
+
if postgres_verification_cache().matches(cache_key, fingerprint):
|
|
563
|
+
return before, native_ids
|
|
564
|
+
for table, (_, oid) in zip(cast(list[dict[str, object]], binding["tables"]), native_ids, strict=True):
|
|
565
|
+
yield ("execute", _COLUMNS, (oid,))
|
|
566
|
+
facts = {row[0]: row[1:] for row in (yield ("many", 2000))}
|
|
567
|
+
columns = cast(list[dict[str, object]], table["columns"])
|
|
568
|
+
for column in columns:
|
|
569
|
+
fact = facts.get(column["native"])
|
|
570
|
+
if (
|
|
571
|
+
fact is None
|
|
572
|
+
or fact[0] != "pg_catalog"
|
|
573
|
+
or fact[1] not in _TYPES[cast(str, column["carrier"])]
|
|
574
|
+
or not column["nullable"]
|
|
575
|
+
and not fact[2]
|
|
576
|
+
):
|
|
577
|
+
raise ReadObligationUnmet("native column differs from compiled type")
|
|
578
|
+
yield ("execute", _KEYS, (oid,))
|
|
579
|
+
physical = {col["logical"]: col["native"] for col in columns}
|
|
580
|
+
key = [physical[name] for name in cast(list[str], table["key"])]
|
|
581
|
+
if not any(list(row[0]) == key for row in (yield ("many", 2000))):
|
|
582
|
+
raise ReadObligationUnmet("compiled unique key has no native constraint")
|
|
583
|
+
if cache_key is not None and fingerprint is not None:
|
|
584
|
+
postgres_verification_cache().remember(cache_key, fingerprint)
|
|
585
|
+
return before, native_ids
|
|
586
|
+
|
|
587
|
+
|
|
588
|
+
def _program(
|
|
589
|
+
connection: Connection,
|
|
590
|
+
entry: CatalogRead[P, R],
|
|
591
|
+
params: P | None,
|
|
592
|
+
*,
|
|
593
|
+
app_schema: str,
|
|
594
|
+
target: str = "postgresql18",
|
|
595
|
+
timeout_ms: int = 5000,
|
|
596
|
+
after: ReadContinuation | None = None,
|
|
597
|
+
_snapshot: bool = False,
|
|
598
|
+
_verify_only: bool = False,
|
|
599
|
+
_page_size: int | None = None,
|
|
600
|
+
) -> Generator[tuple[Any, ...], Any, ReadPage[R]]:
|
|
601
|
+
artifact = entry.artifact()
|
|
602
|
+
selected_page_size = stream_page_size(artifact, _page_size)
|
|
603
|
+
if type(timeout_ms) is not int or not 1 <= timeout_ms <= 2_147_483_647:
|
|
604
|
+
raise ValueError("timeout_ms must be a positive PostgreSQL millisecond bound")
|
|
605
|
+
if (
|
|
606
|
+
not app_schema
|
|
607
|
+
or "\x00" in app_schema
|
|
608
|
+
or app_schema in ("pg_catalog", "information_schema")
|
|
609
|
+
or app_schema.startswith("pg_")
|
|
610
|
+
):
|
|
611
|
+
raise ReadObligationUnmet("app schema is outside the application profile")
|
|
612
|
+
if connection.info.transaction_status != (2 if _snapshot else 0):
|
|
613
|
+
raise ReadObligationUnmet(
|
|
614
|
+
"caller connection must be idle; no nested read transaction"
|
|
615
|
+
)
|
|
616
|
+
if (
|
|
617
|
+
not 180000 <= connection.info.server_version < 190000
|
|
618
|
+
or target != artifact["target"]
|
|
619
|
+
):
|
|
620
|
+
raise ReadObligationUnmet(
|
|
621
|
+
"catalog requires its exact PostgreSQL 18 target profile"
|
|
622
|
+
)
|
|
623
|
+
binding = cast(dict[str, object], artifact["binding"])
|
|
624
|
+
schema = binding["schema"]
|
|
625
|
+
if schema is not None and schema != app_schema:
|
|
626
|
+
raise ReadObligationUnmet("catalog schema differs from app schema")
|
|
627
|
+
if not _verify_only and type(params) is not entry.parameters:
|
|
628
|
+
raise TypeError("parameters require the exact declared model")
|
|
629
|
+
# Revalidate raw attributes: model_construct/model_copy never bypass codecs.
|
|
630
|
+
checked = None if _verify_only else revalidate_model(entry.parameters, params)
|
|
631
|
+
values = {} if checked is None else {name: getattr(checked, name) for name in entry.parameters.model_fields}
|
|
632
|
+
if checked is not None:
|
|
633
|
+
validate_list_parameters(artifact["parameters"], values)
|
|
634
|
+
if any(isinstance(value, Decimal) and not value.is_finite() for value in values.values()):
|
|
635
|
+
raise ValueError("nonfinite decimal parameter")
|
|
636
|
+
order = cast(list[str], artifact["dbapiParameterOrder"])
|
|
637
|
+
obligations = cast(dict[str, object], artifact["obligations"])
|
|
638
|
+
schema_mode = obligations.get("schemaBinding")
|
|
639
|
+
if schema_mode is None and binding.get("schemaBinding") is not None:
|
|
640
|
+
raise ReadBuildError("missing original schema binding obligation")
|
|
641
|
+
if schema_mode is not None and (
|
|
642
|
+
schema_mode not in ("qualified", "search-path")
|
|
643
|
+
or binding.get("schemaBinding") != schema_mode
|
|
644
|
+
or (schema_mode == "qualified") != (schema is not None)
|
|
645
|
+
):
|
|
646
|
+
raise ReadBuildError("unsupported original schema binding obligation")
|
|
647
|
+
fence_programs = _catalog_fence_programs(artifact)
|
|
648
|
+
term_admissions = _term_admissions(obligations, app_schema)
|
|
649
|
+
projection_admissions = _projection_admissions(obligations, app_schema)
|
|
650
|
+
relationship_admissions = _relationship_admissions(obligations, app_schema)
|
|
651
|
+
native_relationship_admissions = _native_relationship_admissions(obligations, app_schema)
|
|
652
|
+
isolation = obligations.get("readIsolation")
|
|
653
|
+
if isolation not in (None, "repeatable-read"):
|
|
654
|
+
raise ReadBuildError("unsupported original read isolation obligation")
|
|
655
|
+
cap = obligations["rowCap"]
|
|
656
|
+
if (
|
|
657
|
+
type(cap) is not int
|
|
658
|
+
or not 1 <= cap <= 1000
|
|
659
|
+
or obligations.get("transaction") != "read-only"
|
|
660
|
+
):
|
|
661
|
+
raise ReadBuildError("invalid catalog read obligations")
|
|
662
|
+
if selected_page_size is not None:
|
|
663
|
+
cap = selected_page_size
|
|
664
|
+
values["__umf_page_size"] = selected_page_size
|
|
665
|
+
search_path = 'pg_catalog, "' + app_schema.replace('"', '""') + '", pg_temp'
|
|
666
|
+
deadline = time.monotonic() + timeout_ms / 1000
|
|
667
|
+
yield ("begin", deadline, isolation)
|
|
668
|
+
if fence_programs is not None:
|
|
669
|
+
lock_sql = fence_programs[0]
|
|
670
|
+
# Utility timeout and original LOCK precede every snapshot-taking query.
|
|
671
|
+
# A retained stream transaction keeps these locks across bounded pages.
|
|
672
|
+
yield ("catalog-fence", lock_sql)
|
|
673
|
+
yield from _early_relation_locks(binding, cast(list[str], artifact["lockSql"]), app_schema)
|
|
674
|
+
native_context = None
|
|
675
|
+
if schema_mode is not None:
|
|
676
|
+
yield ("execute", "SELECT pg_catalog.set_config('row_security', 'on', true)", ())
|
|
677
|
+
native_context = yield from _observe_resolution(binding, app_schema, cast(str, schema_mode), connection.info.dbname)
|
|
678
|
+
yield (
|
|
679
|
+
"execute",
|
|
680
|
+
"SELECT pg_catalog.set_config('search_path', %s, true), pg_catalog.set_config('row_security', 'on', true)",
|
|
681
|
+
(search_path,),
|
|
682
|
+
)
|
|
683
|
+
if fence_programs is not None:
|
|
684
|
+
# Preserve caller-resolution observations first; canonical view output
|
|
685
|
+
# is checked only under the established pg_catalog-first host context.
|
|
686
|
+
yield from _verify_admissions(
|
|
687
|
+
fence_programs[1], "native text-search catalog fence differs from deployment"
|
|
688
|
+
)
|
|
689
|
+
shape_proof: list[str] = []
|
|
690
|
+
before, native_ids = yield from native_read_admission(
|
|
691
|
+
binding, app_schema, (),
|
|
692
|
+
cache_context=(target, connection.info.server_version, native_context) if native_context is not None else None,
|
|
693
|
+
shape_proof=shape_proof,
|
|
694
|
+
)
|
|
695
|
+
yield from _verify_terms(term_admissions)
|
|
696
|
+
yield from _verify_admissions(projection_admissions, "native projection column shape differs from catalog")
|
|
697
|
+
yield from _verify_admissions(relationship_admissions, "native relationship Key differs from catalog")
|
|
698
|
+
yield from _verify_admissions(native_relationship_admissions, "native relationship integrity or complete scope differs from catalog")
|
|
699
|
+
yield ("verified",)
|
|
700
|
+
identity_parts: list[object] = [
|
|
701
|
+
entry.artifact_json, entry.context_json, app_schema,
|
|
702
|
+
[(name, type(value).__name__, str(value)) for name, value in values.items()],
|
|
703
|
+
before[0], connection.info.dbname, connection.info.host, connection.info.port,
|
|
704
|
+
native_ids,
|
|
705
|
+
]
|
|
706
|
+
if native_context is not None:
|
|
707
|
+
identity_parts.append(native_context)
|
|
708
|
+
identity = hashlib.sha256(
|
|
709
|
+
json.dumps(
|
|
710
|
+
identity_parts,
|
|
711
|
+
separators=(",", ":"),
|
|
712
|
+
).encode()
|
|
713
|
+
).hexdigest()
|
|
714
|
+
cursor_fields = cast(list[dict[str, object]], artifact["cursorOutputs"])
|
|
715
|
+
if after is not None and (
|
|
716
|
+
after.identity_digest != identity or len(after.values) != len(cursor_fields)
|
|
717
|
+
):
|
|
718
|
+
raise StaleContinuation("stale or incompatible read continuation")
|
|
719
|
+
cursor_params = cast(list[dict[str, object]], artifact["cursorParameters"])
|
|
720
|
+
if cursor_params:
|
|
721
|
+
values["__umf_has_after"] = after is not None
|
|
722
|
+
for i, field in enumerate(cursor_fields):
|
|
723
|
+
value = after.values[i] if after is not None else None
|
|
724
|
+
if after is not None:
|
|
725
|
+
try:
|
|
726
|
+
_check_cursor_value(field, value)
|
|
727
|
+
except ReadObligationUnmet:
|
|
728
|
+
raise StaleContinuation("continuation carrier differs from ordering") from None
|
|
729
|
+
values[f"__umf_after_{i}"] = value
|
|
730
|
+
elif after is not None:
|
|
731
|
+
raise ReadObligationUnmet("catalog is not a keyset page")
|
|
732
|
+
yield (
|
|
733
|
+
"execute",
|
|
734
|
+
cast(str, artifact["dbapiSql"]),
|
|
735
|
+
tuple(values[name] for name in order),
|
|
736
|
+
)
|
|
737
|
+
expected = list(entry.result.model_fields)
|
|
738
|
+
names = [col.name for col in (yield ("columns",))]
|
|
739
|
+
if names != expected + [f["name"] for f in cursor_fields]:
|
|
740
|
+
raise ReadObligationUnmet("result column inventory differs from catalog")
|
|
741
|
+
rows = yield ("many", cap + 1)
|
|
742
|
+
if len(rows) > cap:
|
|
743
|
+
raise ReadObligationUnmet("target returned more than the catalog row cap")
|
|
744
|
+
outputs = cast(list[dict[str, object]], artifact["outputs"])
|
|
745
|
+
related = transport_spec(entry.result)
|
|
746
|
+
result = [validate_graph(entry.result, {
|
|
747
|
+
name: _output_value(value, output, key_model=related[1] if related is not None and name == related[0] else None)
|
|
748
|
+
for name, value, output in zip(expected, row[:len(expected)], outputs, strict=True)
|
|
749
|
+
}) for row in rows]
|
|
750
|
+
if fence_programs is not None:
|
|
751
|
+
yield from _verify_admissions(
|
|
752
|
+
fence_programs[1], "native text-search catalog fence differs before release"
|
|
753
|
+
)
|
|
754
|
+
yield from _verify_terms(term_admissions)
|
|
755
|
+
yield from _verify_admissions(projection_admissions, "native projection column shape differs before release")
|
|
756
|
+
yield from _verify_admissions(relationship_admissions, "native relationship Key differs before release")
|
|
757
|
+
yield from _verify_admissions(native_relationship_admissions, "native relationship integrity or complete scope differs before release")
|
|
758
|
+
if native_context is not None and (yield from _observe_resolution(binding, app_schema, cast(str, schema_mode), connection.info.dbname)) != native_context:
|
|
759
|
+
raise ReadObligationUnmet("native database or schema resolution changed before release")
|
|
760
|
+
if shape_proof and (yield from _shape_fingerprint(native_ids, app_schema)) != shape_proof[0]:
|
|
761
|
+
raise ReadObligationUnmet("native verified shape changed before release")
|
|
762
|
+
yield ("execute", _ROLE)
|
|
763
|
+
if (yield ("one",)) != before:
|
|
764
|
+
raise ReadObligationUnmet("caller role changed during read")
|
|
765
|
+
continuation = (
|
|
766
|
+
ReadContinuation(
|
|
767
|
+
_checked_sort_values(cursor_fields, rows[-1][len(expected) :]), identity
|
|
768
|
+
)
|
|
769
|
+
if cursor_fields and len(rows) == cap
|
|
770
|
+
else None
|
|
771
|
+
)
|
|
772
|
+
yield ("check",)
|
|
773
|
+
return ReadPage(tuple(result), continuation)
|
|
774
|
+
|
|
775
|
+
|
|
776
|
+
def _drive(
|
|
777
|
+
program: Generator[tuple[Any, ...], Any, ReadPage[R]],
|
|
778
|
+
cursor: _DeadlineCursor,
|
|
779
|
+
verify_only: bool = False,
|
|
780
|
+
) -> ReadPage[R]:
|
|
781
|
+
answer: Any = None
|
|
782
|
+
while True:
|
|
783
|
+
try:
|
|
784
|
+
step = program.send(answer)
|
|
785
|
+
except StopIteration as done:
|
|
786
|
+
return cast(ReadPage[R], done.value)
|
|
787
|
+
if step[0] in ("catalog-fence", "snapshot-free"):
|
|
788
|
+
cursor.raw.execute(_snapshot_free_timeout(cursor.deadline))
|
|
789
|
+
cursor.raw.execute(step[1])
|
|
790
|
+
answer = None
|
|
791
|
+
elif step[0] == "execute":
|
|
792
|
+
cursor.execute(step[1], step[2] if len(step) > 2 else None)
|
|
793
|
+
answer = None
|
|
794
|
+
elif step[0] == "one":
|
|
795
|
+
answer = cursor.fetchone()
|
|
796
|
+
elif step[0] == "many":
|
|
797
|
+
answer = cursor.fetchmany(step[1])
|
|
798
|
+
elif step[0] == "columns":
|
|
799
|
+
answer = cursor.description
|
|
800
|
+
elif step[0] == "check":
|
|
801
|
+
answer = cursor.check()
|
|
802
|
+
elif step[0] == "verified":
|
|
803
|
+
if verify_only:
|
|
804
|
+
return ReadPage((), None)
|
|
805
|
+
answer = None
|
|
806
|
+
else:
|
|
807
|
+
raise ReadBuildError("unknown read operation")
|
|
808
|
+
|
|
809
|
+
|
|
810
|
+
def _execute(
|
|
811
|
+
connection: Connection,
|
|
812
|
+
entry: CatalogRead[P, R],
|
|
813
|
+
params: P | None,
|
|
814
|
+
*,
|
|
815
|
+
app_schema: str,
|
|
816
|
+
target: str = "postgresql18",
|
|
817
|
+
timeout_ms: int = 5000,
|
|
818
|
+
after: ReadContinuation | None = None,
|
|
819
|
+
_snapshot: bool = False,
|
|
820
|
+
_verify_only: bool = False,
|
|
821
|
+
_page_size: int | None = None,
|
|
822
|
+
) -> ReadPage[R]:
|
|
823
|
+
program = _program(
|
|
824
|
+
connection,
|
|
825
|
+
entry,
|
|
826
|
+
params,
|
|
827
|
+
app_schema=app_schema,
|
|
828
|
+
target=target,
|
|
829
|
+
timeout_ms=timeout_ms,
|
|
830
|
+
after=after,
|
|
831
|
+
_snapshot=_snapshot,
|
|
832
|
+
_verify_only=_verify_only,
|
|
833
|
+
_page_size=_page_size,
|
|
834
|
+
)
|
|
835
|
+
begin = next(program) # All call/identity checks precede transaction entry.
|
|
836
|
+
try:
|
|
837
|
+
with (
|
|
838
|
+
nullcontext() if _snapshot else connection.transaction(),
|
|
839
|
+
connection.cursor() as raw,
|
|
840
|
+
):
|
|
841
|
+
if not _snapshot:
|
|
842
|
+
raw.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY" if begin[2] == "repeatable-read" else "SET TRANSACTION READ ONLY")
|
|
843
|
+
return _drive(program, _DeadlineCursor(raw, begin[1]), _verify_only)
|
|
844
|
+
except Exception as error:
|
|
845
|
+
if getattr(error, "sqlstate", None) == "57014":
|
|
846
|
+
raise TimedOut("catalog read exceeded its per-call timeout") from None
|
|
847
|
+
raise
|
|
848
|
+
finally:
|
|
849
|
+
program.close()
|
|
850
|
+
|
|
851
|
+
|
|
852
|
+
class AsyncConnection(Protocol):
|
|
853
|
+
info: Any
|
|
854
|
+
|
|
855
|
+
def cursor(self) -> Any: ...
|
|
856
|
+
def transaction(self) -> Any: ...
|
|
857
|
+
|
|
858
|
+
|
|
859
|
+
async def _async_drive(
|
|
860
|
+
program: Generator[tuple[Any, ...], Any, ReadPage[R]],
|
|
861
|
+
raw: Any,
|
|
862
|
+
deadline: float,
|
|
863
|
+
verify_only: bool = False,
|
|
864
|
+
) -> ReadPage[R]:
|
|
865
|
+
answer: Any = None
|
|
866
|
+
while True:
|
|
867
|
+
try:
|
|
868
|
+
step = program.send(answer)
|
|
869
|
+
except StopIteration as done:
|
|
870
|
+
return cast(ReadPage[R], done.value)
|
|
871
|
+
remaining = math.ceil((deadline - time.monotonic()) * 1000)
|
|
872
|
+
if remaining <= 0:
|
|
873
|
+
raise TimedOut("catalog read exceeded its per-call timeout")
|
|
874
|
+
if step[0] in ("catalog-fence", "snapshot-free"):
|
|
875
|
+
await raw.execute(_snapshot_free_timeout(deadline))
|
|
876
|
+
await raw.execute(step[1])
|
|
877
|
+
answer = None
|
|
878
|
+
elif step[0] == "execute":
|
|
879
|
+
await raw.execute(
|
|
880
|
+
"SELECT pg_catalog.set_config('statement_timeout', %s, true)",
|
|
881
|
+
(str(remaining),),
|
|
882
|
+
)
|
|
883
|
+
await raw.execute(step[1], step[2] if len(step) > 2 else None)
|
|
884
|
+
answer = None
|
|
885
|
+
elif step[0] == "one":
|
|
886
|
+
answer = await raw.fetchone()
|
|
887
|
+
elif step[0] == "many":
|
|
888
|
+
answer = await raw.fetchmany(step[1])
|
|
889
|
+
elif step[0] == "columns":
|
|
890
|
+
answer = raw.description
|
|
891
|
+
elif step[0] == "check":
|
|
892
|
+
answer = remaining
|
|
893
|
+
elif step[0] == "verified":
|
|
894
|
+
if verify_only:
|
|
895
|
+
return ReadPage((), None)
|
|
896
|
+
answer = None
|
|
897
|
+
else:
|
|
898
|
+
raise ReadBuildError("unknown read operation")
|
|
899
|
+
|
|
900
|
+
|
|
901
|
+
async def _async_execute(
|
|
902
|
+
connection: AsyncConnection,
|
|
903
|
+
entry: CatalogRead[P, R],
|
|
904
|
+
params: P | None,
|
|
905
|
+
*,
|
|
906
|
+
app_schema: str,
|
|
907
|
+
target: str = "postgresql18",
|
|
908
|
+
timeout_ms: int = 5000,
|
|
909
|
+
after: ReadContinuation | None = None,
|
|
910
|
+
_snapshot: bool = False,
|
|
911
|
+
_verify_only: bool = False,
|
|
912
|
+
_page_size: int | None = None,
|
|
913
|
+
) -> ReadPage[R]:
|
|
914
|
+
program = _program(
|
|
915
|
+
connection,
|
|
916
|
+
entry,
|
|
917
|
+
params,
|
|
918
|
+
app_schema=app_schema,
|
|
919
|
+
target=target,
|
|
920
|
+
timeout_ms=timeout_ms,
|
|
921
|
+
after=after,
|
|
922
|
+
_snapshot=_snapshot,
|
|
923
|
+
_verify_only=_verify_only,
|
|
924
|
+
_page_size=_page_size,
|
|
925
|
+
)
|
|
926
|
+
begin = next(program)
|
|
927
|
+
try:
|
|
928
|
+
async with (
|
|
929
|
+
nullcontext() if _snapshot else connection.transaction(),
|
|
930
|
+
connection.cursor() as raw,
|
|
931
|
+
):
|
|
932
|
+
if not _snapshot:
|
|
933
|
+
await raw.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY" if begin[2] == "repeatable-read" else "SET TRANSACTION READ ONLY")
|
|
934
|
+
return await _async_drive(program, raw, begin[1], _verify_only)
|
|
935
|
+
except Exception as error:
|
|
936
|
+
if getattr(error, "sqlstate", None) == "57014":
|
|
937
|
+
raise TimedOut("catalog read exceeded its per-call timeout") from None
|
|
938
|
+
raise
|
|
939
|
+
finally:
|
|
940
|
+
program.close()
|
|
941
|
+
|
|
942
|
+
|
|
943
|
+
async def execute_read_async(
|
|
944
|
+
connection: AsyncConnection,
|
|
945
|
+
entry: CatalogRead[P, R],
|
|
946
|
+
params: P,
|
|
947
|
+
*,
|
|
948
|
+
app_schema: str,
|
|
949
|
+
target: str = "postgresql18",
|
|
950
|
+
timeout_ms: int = 5000,
|
|
951
|
+
) -> list[R]:
|
|
952
|
+
return list(
|
|
953
|
+
(
|
|
954
|
+
await _async_execute(
|
|
955
|
+
connection,
|
|
956
|
+
entry,
|
|
957
|
+
params,
|
|
958
|
+
app_schema=app_schema,
|
|
959
|
+
target=target,
|
|
960
|
+
timeout_ms=timeout_ms,
|
|
961
|
+
)
|
|
962
|
+
).items
|
|
963
|
+
)
|
|
964
|
+
|
|
965
|
+
|
|
966
|
+
async def execute_page_async(
|
|
967
|
+
connection: AsyncConnection,
|
|
968
|
+
entry: CatalogRead[P, R],
|
|
969
|
+
params: P,
|
|
970
|
+
*,
|
|
971
|
+
app_schema: str,
|
|
972
|
+
after: ReadContinuation | None = None,
|
|
973
|
+
target: str = "postgresql18",
|
|
974
|
+
timeout_ms: int = 5000,
|
|
975
|
+
) -> ReadPage[R]:
|
|
976
|
+
if not entry.artifact().get("cursorOutputs"):
|
|
977
|
+
raise ReadObligationUnmet("catalog was not built as a keyset page")
|
|
978
|
+
return await _async_execute(
|
|
979
|
+
connection,
|
|
980
|
+
entry,
|
|
981
|
+
params,
|
|
982
|
+
app_schema=app_schema,
|
|
983
|
+
after=after,
|
|
984
|
+
target=target,
|
|
985
|
+
timeout_ms=timeout_ms,
|
|
986
|
+
)
|
|
987
|
+
|
|
988
|
+
|
|
989
|
+
def execute_stream_async(
|
|
990
|
+
connection: AsyncConnection,
|
|
991
|
+
entry: CatalogRead[P, R],
|
|
992
|
+
params: P,
|
|
993
|
+
*,
|
|
994
|
+
app_schema: str,
|
|
995
|
+
max_rows: int,
|
|
996
|
+
page_size: int | None = None,
|
|
997
|
+
target: str = "postgresql18",
|
|
998
|
+
timeout_ms: int = 5000,
|
|
999
|
+
) -> AsyncGenerator[R, None]:
|
|
1000
|
+
stream_page_size(entry.artifact(), page_size)
|
|
1001
|
+
if type(max_rows) is not int or max_rows < 1:
|
|
1002
|
+
raise ValueError("max_rows must be a positive integer")
|
|
1003
|
+
if connection.info.transaction_status != 0:
|
|
1004
|
+
raise ReadObligationUnmet("caller connection must be idle")
|
|
1005
|
+
if not entry.artifact().get("cursorOutputs"):
|
|
1006
|
+
raise ReadObligationUnmet("stream requires a compiled keyset catalog")
|
|
1007
|
+
if type(timeout_ms) is not int or not 1 <= timeout_ms <= 2_147_483_647:
|
|
1008
|
+
raise ValueError("timeout_ms must be a positive PostgreSQL millisecond bound")
|
|
1009
|
+
return _async_stream(
|
|
1010
|
+
connection,
|
|
1011
|
+
entry,
|
|
1012
|
+
params,
|
|
1013
|
+
app_schema=app_schema,
|
|
1014
|
+
max_rows=max_rows,
|
|
1015
|
+
page_size=page_size,
|
|
1016
|
+
target=target,
|
|
1017
|
+
timeout_ms=timeout_ms,
|
|
1018
|
+
)
|
|
1019
|
+
|
|
1020
|
+
|
|
1021
|
+
async def _async_stream(
|
|
1022
|
+
connection: AsyncConnection,
|
|
1023
|
+
entry: CatalogRead[P, R],
|
|
1024
|
+
params: P,
|
|
1025
|
+
*,
|
|
1026
|
+
app_schema: str,
|
|
1027
|
+
max_rows: int,
|
|
1028
|
+
page_size: int | None = None,
|
|
1029
|
+
target: str,
|
|
1030
|
+
timeout_ms: int,
|
|
1031
|
+
) -> AsyncGenerator[R, None]:
|
|
1032
|
+
if connection.info.transaction_status != 0:
|
|
1033
|
+
raise ReadObligationUnmet("caller connection must remain idle")
|
|
1034
|
+
async with connection.transaction():
|
|
1035
|
+
async with connection.cursor() as cursor:
|
|
1036
|
+
await cursor.execute(
|
|
1037
|
+
"SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY"
|
|
1038
|
+
)
|
|
1039
|
+
emitted = 0
|
|
1040
|
+
after = None
|
|
1041
|
+
while emitted < max_rows:
|
|
1042
|
+
page = await _async_execute(
|
|
1043
|
+
connection,
|
|
1044
|
+
entry,
|
|
1045
|
+
params,
|
|
1046
|
+
app_schema=app_schema,
|
|
1047
|
+
target=target,
|
|
1048
|
+
timeout_ms=timeout_ms,
|
|
1049
|
+
after=after,
|
|
1050
|
+
_snapshot=True,
|
|
1051
|
+
_page_size=page_size,
|
|
1052
|
+
)
|
|
1053
|
+
for item in page.items:
|
|
1054
|
+
if emitted == max_rows:
|
|
1055
|
+
raise StreamLimitReached(max_rows, truncated=True)
|
|
1056
|
+
emitted += 1
|
|
1057
|
+
yield item
|
|
1058
|
+
if page.next_after is None:
|
|
1059
|
+
return
|
|
1060
|
+
if emitted == max_rows:
|
|
1061
|
+
raise StreamLimitReached(max_rows, truncated=None)
|
|
1062
|
+
if not page.items:
|
|
1063
|
+
raise ReadObligationUnmet("empty page cannot advance an export")
|
|
1064
|
+
after = page.next_after
|
|
1065
|
+
|
|
1066
|
+
|
|
1067
|
+
def execute_read(
|
|
1068
|
+
connection: Connection,
|
|
1069
|
+
entry: CatalogRead[P, R],
|
|
1070
|
+
params: P,
|
|
1071
|
+
*,
|
|
1072
|
+
app_schema: str,
|
|
1073
|
+
target: str = "postgresql18",
|
|
1074
|
+
timeout_ms: int = 5000,
|
|
1075
|
+
) -> list[R]:
|
|
1076
|
+
return list(
|
|
1077
|
+
_execute(
|
|
1078
|
+
connection,
|
|
1079
|
+
entry,
|
|
1080
|
+
params,
|
|
1081
|
+
app_schema=app_schema,
|
|
1082
|
+
target=target,
|
|
1083
|
+
timeout_ms=timeout_ms,
|
|
1084
|
+
).items
|
|
1085
|
+
)
|
|
1086
|
+
|
|
1087
|
+
|
|
1088
|
+
def execute_page(
|
|
1089
|
+
connection: Connection,
|
|
1090
|
+
entry: CatalogRead[P, R],
|
|
1091
|
+
params: P,
|
|
1092
|
+
*,
|
|
1093
|
+
app_schema: str,
|
|
1094
|
+
after: ReadContinuation | None = None,
|
|
1095
|
+
target: str = "postgresql18",
|
|
1096
|
+
timeout_ms: int = 5000,
|
|
1097
|
+
) -> ReadPage[R]:
|
|
1098
|
+
if not entry.artifact().get("cursorOutputs"):
|
|
1099
|
+
raise ReadObligationUnmet("catalog was not built as a keyset page")
|
|
1100
|
+
return _execute(
|
|
1101
|
+
connection,
|
|
1102
|
+
entry,
|
|
1103
|
+
params,
|
|
1104
|
+
app_schema=app_schema,
|
|
1105
|
+
after=after,
|
|
1106
|
+
target=target,
|
|
1107
|
+
timeout_ms=timeout_ms,
|
|
1108
|
+
)
|
|
1109
|
+
|
|
1110
|
+
|
|
1111
|
+
def execute_stream(
|
|
1112
|
+
connection: Connection,
|
|
1113
|
+
entry: CatalogRead[P, R],
|
|
1114
|
+
params: P,
|
|
1115
|
+
*,
|
|
1116
|
+
app_schema: str,
|
|
1117
|
+
max_rows: int,
|
|
1118
|
+
page_size: int | None = None,
|
|
1119
|
+
target: str = "postgresql18",
|
|
1120
|
+
timeout_ms: int = 5000,
|
|
1121
|
+
) -> Generator[R, None, None]:
|
|
1122
|
+
"""Bounded export in one repeatable-read snapshot, using compiled keyset pages.
|
|
1123
|
+
|
|
1124
|
+
Close the iterator when abandoning an export to release its transaction.
|
|
1125
|
+
Each page receives its own finite deadline; exceptions never signal a
|
|
1126
|
+
successfully completed export. The host retains ownership of the connection.
|
|
1127
|
+
"""
|
|
1128
|
+
stream_page_size(entry.artifact(), page_size)
|
|
1129
|
+
if type(max_rows) is not int or max_rows < 1:
|
|
1130
|
+
raise ValueError("max_rows must be a positive integer")
|
|
1131
|
+
if connection.info.transaction_status != 0:
|
|
1132
|
+
raise ReadObligationUnmet("caller connection must be idle")
|
|
1133
|
+
if not entry.artifact().get("cursorOutputs"):
|
|
1134
|
+
raise ReadObligationUnmet("stream requires a compiled keyset catalog")
|
|
1135
|
+
if type(timeout_ms) is not int or not 1 <= timeout_ms <= 2_147_483_647:
|
|
1136
|
+
raise ValueError("timeout_ms must be a positive PostgreSQL millisecond bound")
|
|
1137
|
+
return _stream(
|
|
1138
|
+
connection,
|
|
1139
|
+
entry,
|
|
1140
|
+
params,
|
|
1141
|
+
app_schema=app_schema,
|
|
1142
|
+
max_rows=max_rows,
|
|
1143
|
+
page_size=page_size,
|
|
1144
|
+
target=target,
|
|
1145
|
+
timeout_ms=timeout_ms,
|
|
1146
|
+
)
|
|
1147
|
+
|
|
1148
|
+
|
|
1149
|
+
def _stream(
|
|
1150
|
+
connection: Connection,
|
|
1151
|
+
entry: CatalogRead[P, R],
|
|
1152
|
+
params: P,
|
|
1153
|
+
*,
|
|
1154
|
+
app_schema: str,
|
|
1155
|
+
max_rows: int,
|
|
1156
|
+
page_size: int | None = None,
|
|
1157
|
+
target: str,
|
|
1158
|
+
timeout_ms: int,
|
|
1159
|
+
) -> Generator[R, None, None]:
|
|
1160
|
+
# Recheck at first iteration: a host may have started a transaction since
|
|
1161
|
+
# constructing the iterator. Never nest inside host-owned work.
|
|
1162
|
+
if connection.info.transaction_status != 0:
|
|
1163
|
+
raise ReadObligationUnmet("caller connection must remain idle")
|
|
1164
|
+
with connection.transaction():
|
|
1165
|
+
with connection.cursor() as cursor:
|
|
1166
|
+
cursor.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY")
|
|
1167
|
+
emitted = 0
|
|
1168
|
+
after = None
|
|
1169
|
+
while emitted < max_rows:
|
|
1170
|
+
page = _execute(
|
|
1171
|
+
connection,
|
|
1172
|
+
entry,
|
|
1173
|
+
params,
|
|
1174
|
+
app_schema=app_schema,
|
|
1175
|
+
target=target,
|
|
1176
|
+
timeout_ms=timeout_ms,
|
|
1177
|
+
after=after,
|
|
1178
|
+
_snapshot=True,
|
|
1179
|
+
_page_size=page_size,
|
|
1180
|
+
)
|
|
1181
|
+
for item in page.items:
|
|
1182
|
+
if emitted == max_rows:
|
|
1183
|
+
raise StreamLimitReached(max_rows, truncated=True)
|
|
1184
|
+
emitted += 1
|
|
1185
|
+
yield item
|
|
1186
|
+
if page.next_after is None:
|
|
1187
|
+
return
|
|
1188
|
+
if emitted == max_rows:
|
|
1189
|
+
raise StreamLimitReached(max_rows, truncated=None)
|
|
1190
|
+
if not page.items:
|
|
1191
|
+
raise ReadObligationUnmet("empty page cannot advance an export")
|
|
1192
|
+
after = page.next_after
|
|
1193
|
+
|
|
1194
|
+
|
|
1195
|
+
def verify_read(
|
|
1196
|
+
connection: Connection,
|
|
1197
|
+
entry: CatalogRead[P, R],
|
|
1198
|
+
*,
|
|
1199
|
+
app_schema: str,
|
|
1200
|
+
target: str = "postgresql18",
|
|
1201
|
+
timeout_ms: int = 5000,
|
|
1202
|
+
) -> None:
|
|
1203
|
+
_execute(
|
|
1204
|
+
connection,
|
|
1205
|
+
entry,
|
|
1206
|
+
None,
|
|
1207
|
+
app_schema=app_schema,
|
|
1208
|
+
target=target,
|
|
1209
|
+
timeout_ms=timeout_ms,
|
|
1210
|
+
_verify_only=True,
|
|
1211
|
+
)
|
|
1212
|
+
|
|
1213
|
+
|
|
1214
|
+
async def verify_read_async(
|
|
1215
|
+
connection: AsyncConnection,
|
|
1216
|
+
entry: CatalogRead[P, R],
|
|
1217
|
+
*,
|
|
1218
|
+
app_schema: str,
|
|
1219
|
+
target: str = "postgresql18",
|
|
1220
|
+
timeout_ms: int = 5000,
|
|
1221
|
+
) -> None:
|
|
1222
|
+
await _async_execute(
|
|
1223
|
+
connection,
|
|
1224
|
+
entry,
|
|
1225
|
+
None,
|
|
1226
|
+
app_schema=app_schema,
|
|
1227
|
+
target=target,
|
|
1228
|
+
timeout_ms=timeout_ms,
|
|
1229
|
+
_verify_only=True,
|
|
1230
|
+
)
|