umf-access 0.1.0.dev8__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) hide show
  1. umf_access/__init__.py +109 -0
  2. umf_access/adoption.py +41 -0
  3. umf_access/build/__init__.py +2 -0
  4. umf_access/build/approximate.py +34 -0
  5. umf_access/build/catalog.py +1626 -0
  6. umf_access/build/commands.py +394 -0
  7. umf_access/build/pg_privileges.py +1544 -0
  8. umf_access/build/privileges.py +134 -0
  9. umf_access/build/search.py +365 -0
  10. umf_access/build/unity_search.py +104 -0
  11. umf_access/bulk.py +227 -0
  12. umf_access/canonical.py +23 -0
  13. umf_access/capture.py +410 -0
  14. umf_access/catalog.py +325 -0
  15. umf_access/codec_support.py +427 -0
  16. umf_access/commands.py +93 -0
  17. umf_access/delta_read.py +758 -0
  18. umf_access/dsl/__init__.py +148 -0
  19. umf_access/dsl/_context.py +36 -0
  20. umf_access/dsl/_expressions.py +625 -0
  21. umf_access/dsl/_joined.py +4 -0
  22. umf_access/dsl/_nodes.py +207 -0
  23. umf_access/dsl/_query.py +5559 -0
  24. umf_access/dsl/_selection.py +143 -0
  25. umf_access/dsl/navigation.py +302 -0
  26. umf_access/dsl/render.py +516 -0
  27. umf_access/dsl/search.py +343 -0
  28. umf_access/engine_catalog.py +563 -0
  29. umf_access/generated_core.py +5 -0
  30. umf_access/lifecycle/__init__.py +46 -0
  31. umf_access/lifecycle/_darwin_process_observer.c +306 -0
  32. umf_access/lifecycle/approval.py +366 -0
  33. umf_access/lifecycle/backfills.py +79 -0
  34. umf_access/lifecycle/catalog.py +289 -0
  35. umf_access/lifecycle/cli.py +231 -0
  36. umf_access/lifecycle/concurrent.py +196 -0
  37. umf_access/lifecycle/conversion_policy.py +188 -0
  38. umf_access/lifecycle/correspondence.py +203 -0
  39. umf_access/lifecycle/generation_authority_bootstrap.py +1491 -0
  40. umf_access/lifecycle/generation_authority_session.py +125 -0
  41. umf_access/lifecycle/generation_enrollment_authority.py +1108 -0
  42. umf_access/lifecycle/generation_enrollment_ledger.py +698 -0
  43. umf_access/lifecycle/generation_ingress.py +185 -0
  44. umf_access/lifecycle/generation_root_registry.py +138 -0
  45. umf_access/lifecycle/head.py +250 -0
  46. umf_access/lifecycle/head_view.py +81 -0
  47. umf_access/lifecycle/host.py +1183 -0
  48. umf_access/lifecycle/ingress_custody.py +750 -0
  49. umf_access/lifecycle/ingress_local_postgres.py +7990 -0
  50. umf_access/lifecycle/ingress_store.py +1488 -0
  51. umf_access/lifecycle/ledger.py +276 -0
  52. umf_access/lifecycle/ledger_schema.py +116 -0
  53. umf_access/lifecycle/mixed.py +593 -0
  54. umf_access/lifecycle/outcome_schema.py +136 -0
  55. umf_access/lifecycle/owner_approval_core.py +1810 -0
  56. umf_access/lifecycle/owner_authority.py +472 -0
  57. umf_access/lifecycle/owner_bootstrap.py +2077 -0
  58. umf_access/lifecycle/owner_wire.py +161 -0
  59. umf_access/lifecycle/phase_fence.py +52 -0
  60. umf_access/lifecycle/phase_policy.py +422 -0
  61. umf_access/lifecycle/privileges.py +145 -0
  62. umf_access/lifecycle/probe.py +39 -0
  63. umf_access/lifecycle/progress.py +497 -0
  64. umf_access/lifecycle/roles.py +96 -0
  65. umf_access/lifecycle/row_originals.py +1712 -0
  66. umf_access/lifecycle/row_originals_creation.py +759 -0
  67. umf_access/lifecycle/row_originals_receipt.py +413 -0
  68. umf_access/lifecycle/seeds.py +99 -0
  69. umf_access/lifecycle/sql_containment.py +358 -0
  70. umf_access/lifecycle/sql_containment_cli.py +33 -0
  71. umf_access/lifecycle/sql_containment_parser.py +20 -0
  72. umf_access/lifecycle/supervisor_journal_codec.py +1251 -0
  73. umf_access/lifecycle/table_boundary.py +22 -0
  74. umf_access/lifecycle/target_custody_codec.py +788 -0
  75. umf_access/lifecycle/witness.py +72 -0
  76. umf_access/managed_actions.py +271 -0
  77. umf_access/managed_bulk.py +353 -0
  78. umf_access/managed_delta.py +150 -0
  79. umf_access/managed_support.py +166 -0
  80. umf_access/manifest_commands.py +278 -0
  81. umf_access/native_actions.py +1007 -0
  82. umf_access/native_program.py +570 -0
  83. umf_access/pages.py +125 -0
  84. umf_access/postgres_bulk.py +509 -0
  85. umf_access/postgres_read.py +1230 -0
  86. umf_access/postgres_search.py +639 -0
  87. umf_access/protocols.py +665 -0
  88. umf_access/py.typed +0 -0
  89. umf_access/related_keys.py +233 -0
  90. umf_access/reviewed.py +706 -0
  91. umf_access/search_catalog.py +122 -0
  92. umf_access/targets.py +312 -0
  93. umf_access/types.py +220 -0
  94. umf_access/unified/__init__.py +187 -0
  95. umf_access/unified/_binding.py +654 -0
  96. umf_access/unified/head_session.py +144 -0
  97. umf_access/unified/native_binding.py +143 -0
  98. umf_access/unified/operation_values.py +173 -0
  99. umf_access/unified/outcome_values.py +76 -0
  100. umf_access/unified/session_async.py +161 -0
  101. umf_access/unified/session_binding.py +108 -0
  102. umf_access/unified/session_policy.py +152 -0
  103. umf_access/unified/session_psycopg2.py +70 -0
  104. umf_access/unified/session_sqlalchemy.py +161 -0
  105. umf_access/unified/session_sync.py +148 -0
  106. umf_access/unified/table_reads.py +314 -0
  107. umf_access/unified/table_writes.py +193 -0
  108. umf_access/unity_search.py +312 -0
  109. umf_access/values.py +280 -0
  110. umf_access/verification.py +64 -0
  111. umf_access-0.1.0.dev8.dist-info/METADATA +15 -0
  112. umf_access-0.1.0.dev8.dist-info/RECORD +117 -0
  113. umf_access-0.1.0.dev8.dist-info/WHEEL +4 -0
  114. umf_access-0.1.0.dev8.dist-info/entry_points.txt +4 -0
  115. umf_access-0.1.0.dev8.dist-info/licenses/LICENSE-APACHE +201 -0
  116. umf_access-0.1.0.dev8.dist-info/licenses/LICENSE-MIT +21 -0
  117. umf_access-0.1.0.dev8.dist-info/licenses/LICENSE.md +239 -0
@@ -0,0 +1,161 @@
1
+ # SPDX-License-Identifier: MIT OR Apache-2.0
2
+ """Psycopg 3 async leases with cancellation-safe transaction and pool cleanup."""
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import os
7
+ import sys
8
+ from collections.abc import AsyncIterator, Awaitable, Callable
9
+ from contextlib import AbstractAsyncContextManager, asynccontextmanager
10
+ from typing import Any, Literal
11
+
12
+ from .session_policy import (
13
+ GET_SETTING,
14
+ GET_SETTINGS,
15
+ ROLE_SETTINGS_CHECK,
16
+ SET_SETTINGS,
17
+ SETTING_NAMES,
18
+ SessionError,
19
+ SessionIdentity,
20
+ SessionPolicy,
21
+ _effective_settings,
22
+ _setting_values,
23
+ _tuple_row,
24
+ )
25
+
26
+
27
+ async def _finish(operation: Awaitable[None]) -> None:
28
+ """Finish cleanup before cancellation reaches the pool or caller."""
29
+ task = asyncio.create_task(operation)
30
+ cancellation = None
31
+ while True:
32
+ try:
33
+ await asyncio.shield(task)
34
+ break
35
+ except asyncio.CancelledError as error:
36
+ if task.done():
37
+ # Cleanup itself being cancelled is a failure, not successful cleanup.
38
+ task.result()
39
+ cancellation = error
40
+ break
41
+ cancellation = error
42
+ if cancellation is not None:
43
+ raise cancellation
44
+
45
+
46
+ class AsyncSession:
47
+ """Per-call factory counterpart to SyncSession; no global pool or event loop."""
48
+ def __init__(self, factory: Callable[[SessionIdentity], AbstractAsyncContextManager[Any]], policy: SessionPolicy,
49
+ *, transaction_owner: Literal["adapter", "caller"] = "adapter"):
50
+ if transaction_owner not in ("adapter", "caller"):
51
+ raise ValueError("transaction_owner must be adapter or caller")
52
+ self.transaction_owner = transaction_owner
53
+ self.factory = factory
54
+ self.policy = policy
55
+ self._pid = os.getpid()
56
+ self._active: set[int] = set()
57
+
58
+ def _prepare_connection(self, connection):
59
+ return connection
60
+
61
+ def _control_cursor(self, connection):
62
+ return connection.cursor(row_factory=_tuple_row)
63
+
64
+ def control_cursor(self, native):
65
+ """Async control cursor on the current lease, without creating a pool."""
66
+ return self._control_cursor(self._prepare_connection(native))
67
+
68
+ @asynccontextmanager
69
+ async def open(self, identity: SessionIdentity, *, read_only: bool = True) -> AsyncIterator[Any]:
70
+ if os.getpid() != self._pid:
71
+ raise SessionError("create session factories and pools after process creation")
72
+ if type(read_only) is not bool:
73
+ raise ValueError("read_only must be bool")
74
+ settings = self.policy.settings(identity)
75
+ lease = self.factory(identity)
76
+ connection = await lease.__aenter__()
77
+ key = id(connection)
78
+ transaction = None
79
+ entered = False
80
+ owned = False
81
+ previous = {}
82
+ failure = (None, None, None)
83
+ registered = False
84
+ try:
85
+ if key in self._active:
86
+ raise SessionError("connection already leased by this adapter")
87
+ self._active.add(key)
88
+ registered = True
89
+ native = connection
90
+ connection = self._prepare_connection(native)
91
+ status = int(connection.info.transaction_status)
92
+ if status not in (0, 2):
93
+ raise SessionError("connection is not idle or in a healthy caller transaction")
94
+ owned = self.transaction_owner == "adapter"
95
+ if status != (0 if owned else 2):
96
+ raise SessionError("connection state differs from explicit transaction ownership")
97
+ transaction = connection.transaction()
98
+ try:
99
+ await transaction.__aenter__()
100
+ entered = True
101
+ except BaseException:
102
+ await _finish(connection.close())
103
+ raise
104
+ async with self._control_cursor(connection) as cursor:
105
+ if owned:
106
+ if read_only:
107
+ await cursor.execute("SET TRANSACTION READ ONLY")
108
+ elif read_only:
109
+ await cursor.execute(GET_SETTING, ("transaction_read_only",))
110
+ if await cursor.fetchone() != ("on",):
111
+ raise SessionError("caller transaction must already be read-only")
112
+ if not owned:
113
+ await cursor.execute(GET_SETTINGS)
114
+ previous = dict(zip(SETTING_NAMES,await cursor.fetchone(),strict=True))
115
+ await cursor.execute(SET_SETTINGS, _setting_values(settings))
116
+ await cursor.execute(ROLE_SETTINGS_CHECK)
117
+ session_user,effective = _effective_settings(await cursor.fetchone(),settings["role"])
118
+ yield native
119
+ except BaseException:
120
+ failure = sys.exc_info()
121
+ raise
122
+ finally:
123
+ body_failed = failure[0] is not None
124
+
125
+ async def cleanup() -> None:
126
+ nonlocal failure
127
+ try:
128
+ if entered:
129
+ if failure[0] is None:
130
+ try:
131
+ async with self._control_cursor(connection) as cursor:
132
+ await cursor.execute(ROLE_SETTINGS_CHECK)
133
+ _,observed = _effective_settings(await cursor.fetchone(),settings["role"],session_user)
134
+ if observed != effective:
135
+ raise SessionError("session settings changed during execution")
136
+ if not owned:
137
+ await cursor.execute(SET_SETTINGS, _setting_values(previous))
138
+ except BaseException: # noqa: BLE001 -- cleanup must roll back even cancellation
139
+ failure = sys.exc_info()
140
+ try:
141
+ await transaction.__aexit__(*failure)
142
+ except BaseException:
143
+ failure = sys.exc_info()
144
+ await connection.close()
145
+ raise
146
+ if failure[0] is not None and not body_failed:
147
+ # A failure first detected during cleanup must reach the caller.
148
+ raise failure[1].with_traceback(failure[2])
149
+ except BaseException:
150
+ failure = sys.exc_info()
151
+ raise
152
+ finally:
153
+ try:
154
+ await lease.__aexit__(*failure)
155
+ except BaseException:
156
+ await connection.close()
157
+ raise
158
+ finally:
159
+ if registered:
160
+ self._active.remove(key)
161
+ await _finish(cleanup())
@@ -0,0 +1,108 @@
1
+ # SPDX-License-Identifier: MIT OR Apache-2.0
2
+ """Per-call native session composition for the Weft transport boundary.
3
+
4
+ Executors must enforce every compiler obligation. These adapters manage native
5
+ identity, leases and transactions; they do not reinterpret Weft SQL or actions.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import copy
10
+ from collections.abc import Awaitable, Callable, Mapping
11
+ from typing import Any
12
+
13
+ from . import SyncWeftTableBinding, WeftTableBinding
14
+ from .session_async import AsyncSession
15
+ from .session_policy import SessionError, SessionIdentity
16
+ from .session_sync import SyncSession
17
+
18
+ ReadExecutor = Callable[[Any, Mapping[str, object], Mapping[str, object]], Mapping[str, object]]
19
+ AsyncReadExecutor = Callable[[Any, Mapping[str, object], Mapping[str, object]], Awaitable[Mapping[str, object]]]
20
+ ActionExecutor = Callable[[Any, str, Mapping[str, object], str | None], Mapping[str, object]]
21
+ AsyncActionExecutor = Callable[[Any, str, Mapping[str, object], str | None], Awaitable[Mapping[str, object]]]
22
+
23
+
24
+ class _ResponseError(Exception):
25
+ def __init__(self, response: Mapping[str, object]):
26
+ self.response = response
27
+
28
+
29
+ class SyncSessionTransport:
30
+ """Bind a trusted identity, acquiring a fresh lease for every generated call."""
31
+ def __init__(self, session: SyncSession, identity: SessionIdentity,
32
+ binding: Mapping[str, object], compiler: object, read: ReadExecutor,
33
+ *, cursor_secret: bytes, target: str = "postgresql18",
34
+ action: ActionExecutor | None = None):
35
+ self.session, self.identity = session, identity
36
+ if binding.get("schema") not in (None, session.policy.schema):
37
+ raise ValueError("binding schema differs from the isolated session schema")
38
+ self.binding, self.compiler, self.read, self.action = copy.deepcopy(dict(binding)), compiler, read, action
39
+ self.target = target
40
+ self.secret = session.policy.cursor_secret(identity, cursor_secret)
41
+ self.schema = SyncWeftTableBinding(binding, compiler, lambda *_: {}, target=target).schema
42
+
43
+ def execute(self, request: Mapping[str, object]) -> Mapping[str, object]:
44
+ if not isinstance(request, Mapping):
45
+ return {"schema": self.schema, "error": {"code": "INVALID", "message": "request object required"}}
46
+ try:
47
+ with self.session.open(self.identity, read_only=request.get("kind") != "apply") as connection:
48
+ def read(artifact, original):
49
+ return self.read(connection, artifact, original)
50
+
51
+ def action(name, inputs, key):
52
+ return self.action(connection, name, inputs, key)
53
+
54
+ binding = SyncWeftTableBinding(self.binding, self.compiler, read,
55
+ target=self.target, cursor_secret=self.secret,
56
+ action_executor=action if self.action else None)
57
+ response = binding.execute(request)
58
+ if "error" in response:
59
+ raise _ResponseError(response) # roll back before returning a wire error
60
+ return response
61
+ except _ResponseError as error:
62
+ return error.response
63
+ except SessionError:
64
+ return {"schema": self.schema, "error": {"code": "DENIED", "message": "native session refused"}}
65
+ except Exception: # noqa: BLE001 -- sanitize native connection and cleanup failures
66
+ code = "WRITE_OUTCOME_UNKNOWN" if request.get("kind") == "apply" else "BUSY"
67
+ return {"schema": self.schema, "error": {"code": code, "message": "native session failed"}}
68
+
69
+
70
+ class AsyncSessionTransport:
71
+ """Async counterpart; cancellation propagates after lease cleanup completes."""
72
+ def __init__(self, session: AsyncSession, identity: SessionIdentity,
73
+ binding: Mapping[str, object], compiler: object, read: AsyncReadExecutor,
74
+ *, cursor_secret: bytes, target: str = "postgresql18",
75
+ action: AsyncActionExecutor | None = None):
76
+ self.session, self.identity = session, identity
77
+ if binding.get("schema") not in (None, session.policy.schema):
78
+ raise ValueError("binding schema differs from the isolated session schema")
79
+ self.binding, self.compiler, self.read, self.action = copy.deepcopy(dict(binding)), compiler, read, action
80
+ self.target = target
81
+ self.secret = session.policy.cursor_secret(identity, cursor_secret)
82
+ self.schema = SyncWeftTableBinding(binding, compiler, lambda *_: {}, target=target).schema
83
+
84
+ async def execute(self, request: Mapping[str, object]) -> Mapping[str, object]:
85
+ if not isinstance(request, Mapping):
86
+ return {"schema": self.schema, "error": {"code": "INVALID", "message": "request object required"}}
87
+ try:
88
+ async with self.session.open(self.identity, read_only=request.get("kind") != "apply") as connection:
89
+ async def read(artifact, original):
90
+ return await self.read(connection, artifact, original)
91
+
92
+ async def action(name, inputs, key):
93
+ return await self.action(connection, name, inputs, key)
94
+
95
+ binding = WeftTableBinding(self.binding, self.compiler, read,
96
+ target=self.target, cursor_secret=self.secret,
97
+ action_executor=action if self.action else None)
98
+ response = await binding.execute(request)
99
+ if "error" in response:
100
+ raise _ResponseError(response)
101
+ return response
102
+ except _ResponseError as error:
103
+ return error.response
104
+ except SessionError:
105
+ return {"schema": self.schema, "error": {"code": "DENIED", "message": "native session refused"}}
106
+ except Exception: # noqa: BLE001 -- cancellation is a BaseException and is never retried
107
+ code = "WRITE_OUTCOME_UNKNOWN" if request.get("kind") == "apply" else "BUSY"
108
+ return {"schema": self.schema, "error": {"code": code, "message": "native session failed"}}
@@ -0,0 +1,152 @@
1
+ # SPDX-License-Identifier: MIT OR Apache-2.0
2
+ """Trusted host identity and connection-local policy; never supplied on the wire."""
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import hmac
7
+ import json
8
+ from collections.abc import Mapping
9
+ from dataclasses import dataclass
10
+ from types import MappingProxyType
11
+ from typing import Literal
12
+
13
+
14
+ class SessionError(RuntimeError):
15
+ """A native session could not establish or preserve its declared authority."""
16
+
17
+
18
+ def _tuple_row(cursor):
19
+ """Psycopg3 row-factory protocol without importing an optional driver."""
20
+ return tuple
21
+
22
+
23
+ @dataclass(frozen=True)
24
+ class SessionIdentity:
25
+ kind: Literal["person", "batch"]
26
+ subject: str
27
+
28
+ def __post_init__(self) -> None:
29
+ if self.kind not in ("person", "batch") or type(self.subject) is not str or not self.subject:
30
+ raise ValueError("an explicit person or batch subject is required")
31
+
32
+
33
+ @dataclass(frozen=True)
34
+ class SessionPolicy:
35
+ """Host-authenticated subject registry, isolated schema and bounded timeouts.
36
+
37
+ Entries authorize role selection, not authentication. Construct identities
38
+ only after host authentication, outside the generated request payload.
39
+ Batch subjects have a separate registry and may not share person roles.
40
+ """
41
+ people: Mapping[str, str]
42
+ batches: Mapping[str, str]
43
+ schema: str
44
+ statement_timeout_ms: int = 30_000
45
+ lock_timeout_ms: int = 5_000
46
+ catalog_only: bool = False
47
+ table_operation_module_profile: Literal[
48
+ "weft.table-operation-module/0.1",
49
+ "weft.table-operation-module/0.2",
50
+ ] = "weft.table-operation-module/0.1"
51
+
52
+ def __post_init__(self) -> None:
53
+ if type(self.catalog_only) is not bool:
54
+ raise ValueError('catalog_only must be bool')
55
+ if type(self.table_operation_module_profile) is not str or self.table_operation_module_profile not in (
56
+ "weft.table-operation-module/0.1",
57
+ "weft.table-operation-module/0.2",
58
+ ):
59
+ raise ValueError("unsupported table operation module profile")
60
+ for name in ("people", "batches"):
61
+ entries = dict(getattr(self, name))
62
+ if any(type(k) is not str or not k or not _identifier(v) for k, v in entries.items()):
63
+ raise ValueError("subject registries require nonempty subjects and native role names")
64
+ object.__setattr__(self, name, MappingProxyType(entries))
65
+ if not _identifier(self.schema) or self.schema.startswith("pg_"):
66
+ raise ValueError("a non-system plugin schema is required")
67
+ if len(set(self.people.values())) != len(self.people):
68
+ raise ValueError("each person requires a distinct native role")
69
+ if set(self.people.values()) & set(self.batches.values()):
70
+ raise ValueError("person and batch roles must be disjoint")
71
+ for value in (self.statement_timeout_ms, self.lock_timeout_ms):
72
+ if type(value) is not int or not 1 <= value <= 300_000:
73
+ raise ValueError("session timeouts must be 1..300000 milliseconds")
74
+
75
+ def role(self, identity: SessionIdentity) -> str:
76
+ if not isinstance(identity, SessionIdentity):
77
+ raise SessionError("trusted session identity required")
78
+ registry = self.people if identity.kind == "person" else self.batches
79
+ role = registry.get(identity.subject)
80
+ if role is None:
81
+ raise SessionError("subject has no grant for this session kind")
82
+ return role
83
+
84
+ def settings(self, identity: SessionIdentity) -> dict[str, str]:
85
+ return {
86
+ "role": self.role(identity),
87
+ "search_path": 'pg_catalog' if self.catalog_only else 'pg_catalog,"' + self.schema.replace('"', '""') + '"',
88
+ "row_security": "on",
89
+ "statement_timeout": str(self.statement_timeout_ms),
90
+ "lock_timeout": str(self.lock_timeout_ms),
91
+ }
92
+
93
+ def cursor_secret(self, identity: SessionIdentity, secret: bytes) -> bytes:
94
+ """Bind page tokens to the authenticated authority and policy, across calls."""
95
+ if type(secret) is not bytes or len(secret) < 32:
96
+ raise ValueError("cursor root secret requires at least 256 bits")
97
+ if self.table_operation_module_profile == "weft.table-operation-module/0.1":
98
+ # Keep the historical 0.1 derivation byte-for-byte stable.
99
+ scope = json.dumps([identity.kind, identity.subject, self.settings(identity)], sort_keys=True)
100
+ else:
101
+ scope = json.dumps([
102
+ "umf.session-table-operation-profile/0.1",
103
+ "weft.table-operation-module/0.2",
104
+ identity.kind,
105
+ identity.subject,
106
+ self.settings(identity),
107
+ ], sort_keys=True)
108
+ return hmac.new(secret, scope.encode(), hashlib.sha256).digest()
109
+
110
+
111
+ def _identifier(value: object) -> bool:
112
+ return type(value) is str and bool(value) and "\x00" not in value and len(value.encode()) <= 63
113
+
114
+
115
+ # Fully qualified catalog references prevent caller search_path from changing admission.
116
+ ROLE_CHECK = """SELECT current_user, session_user, r.rolsuper, r.rolbypassrls
117
+ FROM pg_catalog.pg_roles AS r WHERE r.rolname = current_user"""
118
+ SET_LOCAL = "SELECT pg_catalog.set_config(%s, %s, true)"
119
+ GET_SETTING = "SELECT pg_catalog.current_setting(%s)"
120
+ SETTING_NAMES = ('role','search_path','row_security','statement_timeout','lock_timeout')
121
+ GET_SETTINGS = """SELECT pg_catalog.current_setting('role'),pg_catalog.current_setting('search_path'),
122
+ pg_catalog.current_setting('row_security'),pg_catalog.current_setting('statement_timeout'),
123
+ pg_catalog.current_setting('lock_timeout')"""
124
+ ROLE_SETTINGS_CHECK = """SELECT current_user,session_user,r.rolsuper,r.rolbypassrls,
125
+ pg_catalog.current_setting('role'),pg_catalog.current_setting('search_path'),
126
+ pg_catalog.current_setting('row_security'),pg_catalog.current_setting('statement_timeout'),
127
+ pg_catalog.current_setting('lock_timeout')
128
+ FROM pg_catalog.pg_roles AS r WHERE r.rolname=current_user"""
129
+ SET_SETTINGS = """SELECT pg_catalog.set_config('role',%s,true),
130
+ pg_catalog.set_config('search_path',%s,true),pg_catalog.set_config('row_security',%s,true),
131
+ pg_catalog.set_config('statement_timeout',%s,true),pg_catalog.set_config('lock_timeout',%s,true)"""
132
+
133
+
134
+ def _setting_values(settings):
135
+ return tuple(settings[name] for name in SETTING_NAMES)
136
+
137
+
138
+ def _effective_settings(row, expected, session_user=None):
139
+ if not isinstance(row,(tuple,list)) or len(row) != 4 + len(SETTING_NAMES):
140
+ raise SessionError("effective role differs or bypasses native row security")
141
+ verified_user = verify_role(row[:4],expected,session_user)
142
+ effective = dict(zip(SETTING_NAMES,row[4:],strict=True))
143
+ return verified_user,effective
144
+
145
+
146
+ def verify_role(row: object, expected: str, session_user: str | None = None) -> str:
147
+ if (not isinstance(row, (tuple, list)) or len(row) != 4
148
+ or row[0] != expected or type(row[1]) is not str
149
+ or session_user is not None and row[1] != session_user
150
+ or row[2] is not False or row[3] is not False):
151
+ raise SessionError("effective role differs or bypasses native row security")
152
+ return row[1]
@@ -0,0 +1,70 @@
1
+ # SPDX-License-Identifier: MIT OR Apache-2.0
2
+ """Psycopg2 2.9 session lifetimes; no query compilation or driver dependency."""
3
+ from __future__ import annotations
4
+
5
+ from uuid import uuid4
6
+
7
+ from .session_policy import SessionError
8
+ from .session_sync import SyncSession
9
+
10
+
11
+ class _Savepoint:
12
+ def __init__(self, connection):
13
+ self.connection = connection
14
+ # Only library-created identifiers enter control SQL, never model input.
15
+ self.name = "umf_" + uuid4().hex
16
+
17
+ def __enter__(self):
18
+ with self.connection.cursor() as cursor:
19
+ cursor.execute('SAVEPOINT "' + self.name + '"')
20
+ return self
21
+
22
+ def __exit__(self, kind, *_):
23
+ with self.connection.cursor() as cursor:
24
+ if kind is not None:
25
+ cursor.execute('ROLLBACK TO SAVEPOINT "' + self.name + '"')
26
+ cursor.execute('RELEASE SAVEPOINT "' + self.name + '"')
27
+
28
+
29
+ class _Connection:
30
+ def __init__(self, native):
31
+ if native.async_:
32
+ raise SessionError("Psycopg2 asynchronous connections are unsupported; use Psycopg3 AsyncSession")
33
+ self.native = native
34
+
35
+ @property
36
+ def info(self):
37
+ return self
38
+
39
+ @property
40
+ def transaction_status(self):
41
+ return self.native.get_transaction_status()
42
+
43
+ def transaction(self):
44
+ # Psycopg2's own context owns only an idle transaction. Nesting it in a
45
+ # caller transaction would commit that caller, so use an actual savepoint.
46
+ return self.native if self.transaction_status == 0 else _Savepoint(self.native)
47
+
48
+ def cursor(self):
49
+ return self.native.cursor()
50
+
51
+ def close(self):
52
+ self.native.close()
53
+
54
+
55
+ class Psycopg2Session(SyncSession):
56
+ """Same per-call contract as SyncSession, for synchronous Psycopg2 >=2.9.
57
+
58
+ The factory supplies a host-managed lease, yielding the original connection.
59
+ ``open`` yields that original connection to executors. Adapter-owned leases
60
+ use Psycopg2's transaction context (including autocommit connections); caller-
61
+ owned leases use savepoints and never commit the outer transaction. Factories
62
+ must discard closed connections, including failed cleanup, before pool reuse.
63
+ """
64
+
65
+ def _prepare_connection(self, connection):
66
+ return _Connection(connection)
67
+
68
+ def _control_cursor(self, connection):
69
+ from psycopg2.extensions import cursor
70
+ return connection.native.cursor(cursor_factory=cursor)
@@ -0,0 +1,161 @@
1
+ # SPDX-License-Identifier: MIT OR Apache-2.0
2
+ """SQLAlchemy Core session control through its own transaction and execution API."""
3
+ from __future__ import annotations
4
+
5
+ from .session_async import AsyncSession
6
+ from .session_policy import SessionError
7
+ from .session_sync import SyncSession
8
+
9
+
10
+ class _State:
11
+ def __init__(self, core, *, asynchronous=False):
12
+ dialect = getattr(core, "dialect", None)
13
+ if dialect is None:
14
+ raise SessionError("SQLAlchemy Core Connection required; ORM Session is unsupported")
15
+ drivers = ("psycopg",) if asynchronous else ("psycopg", "psycopg2")
16
+ if dialect.name != "postgresql" or dialect.driver not in drivers:
17
+ raise SessionError("SQLAlchemy sessions require PostgreSQL with a supported Psycopg driver")
18
+ if bool(dialect.is_async) != asynchronous:
19
+ raise SessionError("SQLAlchemy connection scheduling differs from the session adapter")
20
+ self.core = core
21
+ if core.closed or core.invalidated:
22
+ raise SessionError("SQLAlchemy connection must be open and valid")
23
+ self.driver = core.connection.driver_connection
24
+ if self.driver.autocommit:
25
+ raise SessionError("SQLAlchemy DBAPI autocommit cannot establish the required native transaction")
26
+
27
+ @property
28
+ def info(self):
29
+ return self
30
+
31
+ @property
32
+ def transaction_status(self):
33
+ transaction = self.core.get_transaction()
34
+ if transaction is not None and hasattr(transaction, "prepare"):
35
+ raise SessionError("SQLAlchemy two-phase transactions are unsupported")
36
+ if self.core.dialect.driver == "psycopg":
37
+ status = int(self.driver.info.transaction_status)
38
+ else:
39
+ status = self.driver.get_transaction_status()
40
+ # An autobegun SQLAlchemy transaction may not yet have reached the
41
+ # server. Refuse it rather than guessing which layer owns its lifetime.
42
+ if self.core.in_transaction() != (status in (2, 3)):
43
+ raise SessionError("SQLAlchemy and native transaction states differ")
44
+ return status
45
+
46
+
47
+ class _Cursor:
48
+ def __init__(self, connection):
49
+ self.connection = connection
50
+ self.result = None
51
+
52
+ def __enter__(self):
53
+ return self
54
+
55
+ def __exit__(self, *_):
56
+ if self.result is not None:
57
+ self.result.close()
58
+
59
+ def execute(self, statement, parameters=None):
60
+ if self.result is not None:
61
+ self.result.close()
62
+ self.result = self.connection.exec_driver_sql(statement, parameters, execution_options={'no_parameters':parameters is None})
63
+
64
+ def fetchone(self):
65
+ row = self.result.fetchone()
66
+ return None if row is None else tuple(row)
67
+
68
+ def fetchall(self):
69
+ return [tuple(row) for row in self.result.fetchall()]
70
+
71
+ @property
72
+ def native_description(self):
73
+ # SQLAlchemy's key view omits DBAPI type OIDs. Retain the live native
74
+ # cursor metadata for the once-cold typed query description check.
75
+ cursor=getattr(self.result,'cursor',None)
76
+ if cursor is None or cursor.description is None:
77
+ raise SessionError('declared query description unavailable')
78
+ return cursor.description
79
+
80
+ @property
81
+ def description(self):
82
+ names = self.result.keys()
83
+ return tuple((name,) for name in names)
84
+
85
+
86
+ class _SyncConnection(_State):
87
+ def transaction(self):
88
+ return self.core.begin_nested() if self.core.in_transaction() else self.core.begin()
89
+
90
+ def cursor(self):
91
+ return _Cursor(self.core)
92
+
93
+ def close(self):
94
+ try:
95
+ self.core.invalidate()
96
+ finally:
97
+ self.core.close()
98
+
99
+
100
+ class _AsyncCursor(_Cursor):
101
+ async def __aenter__(self):
102
+ return self
103
+
104
+ async def __aexit__(self, *args):
105
+ super().__exit__(*args)
106
+
107
+ async def execute(self, statement, parameters=None):
108
+ if self.result is not None:
109
+ self.result.close()
110
+ self.result = await self.connection.exec_driver_sql(statement, parameters, execution_options={'no_parameters':parameters is None})
111
+
112
+ async def fetchone(self):
113
+ return super().fetchone()
114
+
115
+ async def fetchall(self):
116
+ return super().fetchall()
117
+
118
+
119
+ class _AsyncConnection(_State):
120
+ def __init__(self, native):
121
+ core = getattr(native, "sync_connection", None)
122
+ super().__init__(core, asynchronous=True)
123
+ self.native = native
124
+
125
+ def transaction(self):
126
+ return self.native.begin_nested() if self.native.in_transaction() else self.native.begin()
127
+
128
+ def cursor(self):
129
+ return _AsyncCursor(self.native)
130
+
131
+ async def close(self):
132
+ try:
133
+ await self.native.invalidate()
134
+ finally:
135
+ await self.native.close()
136
+
137
+
138
+ class SQLAlchemySession(SyncSession):
139
+ """Per-call SQLAlchemy 2 PostgreSQL Core leases, using Psycopg2 or Psycopg3.
140
+
141
+ Supply a factory such as ``lambda identity: engine.connect()`` or a context
142
+ manager lending an existing Core Connection. Caller ownership requires an
143
+ actual active native transaction. DBAPI autocommit is refused. ORM Sessions
144
+ and other dialects/drivers are outside this adapter's contract.
145
+ """
146
+
147
+ def _prepare_connection(self, connection):
148
+ return _SyncConnection(connection)
149
+
150
+ def _control_cursor(self, connection):
151
+ return connection.cursor()
152
+
153
+
154
+ class AsyncSQLAlchemySession(AsyncSession):
155
+ """Async SQLAlchemy 2 Core counterpart, using its PostgreSQL Psycopg3 driver."""
156
+
157
+ def _prepare_connection(self, connection):
158
+ return _AsyncConnection(connection)
159
+
160
+ def _control_cursor(self, connection):
161
+ return connection.cursor()