sqlalchemy-audit-trail 0.1.0__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.
- audit_trail/__init__.py +67 -0
- audit_trail/_compaction.py +297 -0
- audit_trail/_typing.py +17 -0
- audit_trail/checks.py +303 -0
- audit_trail/config.py +950 -0
- audit_trail/context.py +375 -0
- audit_trail/diff.py +619 -0
- audit_trail/events.py +441 -0
- audit_trail/integrations/__init__.py +1 -0
- audit_trail/integrations/fastapi.py +378 -0
- audit_trail/listener.py +655 -0
- audit_trail/maintenance.py +1028 -0
- audit_trail/migrations.py +309 -0
- audit_trail/mixin.py +118 -0
- audit_trail/privacy.py +410 -0
- audit_trail/py.typed +0 -0
- audit_trail/pytest_plugin.py +94 -0
- audit_trail/query.py +1616 -0
- audit_trail/relations.py +222 -0
- audit_trail/serialization.py +400 -0
- audit_trail/tables.py +264 -0
- audit_trail/testing.py +589 -0
- audit_trail/writer.py +485 -0
- sqlalchemy_audit_trail-0.1.0.dist-info/METADATA +200 -0
- sqlalchemy_audit_trail-0.1.0.dist-info/RECORD +27 -0
- sqlalchemy_audit_trail-0.1.0.dist-info/WHEEL +4 -0
- sqlalchemy_audit_trail-0.1.0.dist-info/licenses/LICENSE +21 -0
audit_trail/listener.py
ADDED
|
@@ -0,0 +1,655 @@
|
|
|
1
|
+
"""Session event listeners that capture ORM changes.
|
|
2
|
+
|
|
3
|
+
``install`` registers the listeners on one session class: the class a
|
|
4
|
+
``sessionmaker`` builds, or a ``Session`` subclass (and so its subclasses).
|
|
5
|
+
Never on the base ``Session``, which would also cover Alembic, other engines
|
|
6
|
+
and every other session in the process. An ``AsyncSession`` runs a sync
|
|
7
|
+
``Session`` of its ``sync_session_class`` in a greenlet, so an async factory
|
|
8
|
+
is installed through that class, which must be the host's own subclass.
|
|
9
|
+
|
|
10
|
+
``after_flush`` turns the flushed ``Audited`` instances into ``entity.*``
|
|
11
|
+
entries and writes them with plain SQL on the session's connection for each
|
|
12
|
+
object (resolved like the flush does), in the same database transaction as
|
|
13
|
+
the changes, so a rollback undoes both.
|
|
14
|
+
|
|
15
|
+
The ``audit_transaction`` row is inserted by the first entry of a database
|
|
16
|
+
transaction on each connection and cached in ``session.info``, per
|
|
17
|
+
connection, together with the ``SessionTransaction`` (root or savepoint) it
|
|
18
|
+
was inserted in:
|
|
19
|
+
|
|
20
|
+
- rolling back that ``SessionTransaction`` or one of its ancestors
|
|
21
|
+
(``after_soft_rollback``) drops the cached row, because it is gone;
|
|
22
|
+
- ``after_transaction_end`` drops the cache when the outermost transaction ends,
|
|
23
|
+
however it ends: commit, rollback, or ``Session.close()`` (which fires no
|
|
24
|
+
commit or rollback event). Releasing a savepoint also ends a
|
|
25
|
+
``SessionTransaction``, but the row then lives on in the enclosing one;
|
|
26
|
+
- ``after_rollback`` never touches it, since it also fires when a savepoint
|
|
27
|
+
is rolled back, which may leave a row of the enclosing transaction intact.
|
|
28
|
+
|
|
29
|
+
``do_orm_execute`` warns (``warn_on_bulk``) about ORM or Core bulk
|
|
30
|
+
``UPDATE``/``DELETE`` statements on an audited table executed through the
|
|
31
|
+
session: they bypass the flush and get no entry.
|
|
32
|
+
|
|
33
|
+
A second ``do_orm_execute`` handler explains loads that fail under
|
|
34
|
+
``AsyncSession``. Loading an unloaded attribute outside an awaited call needs
|
|
35
|
+
I/O that SQLAlchemy cannot run there, so it raises ``MissingGreenlet``. For
|
|
36
|
+
the loads the library is responsible for (an expired column of an
|
|
37
|
+
``Audited`` instance, which ``Audited`` also loads on assignment to keep the
|
|
38
|
+
old value, and a collection named in ``track_relationships``) the error is
|
|
39
|
+
replaced by ``AsyncLoadError``, which names the attribute and the fix. The
|
|
40
|
+
handler adds no SQL and checks nothing in advance: it only translates the
|
|
41
|
+
error once the load has failed, and only on an async dialect.
|
|
42
|
+
|
|
43
|
+
These state listeners run even when ``session.info["audit_enabled"]`` is
|
|
44
|
+
``False``; only capture is switched off, so toggling the flag in the middle
|
|
45
|
+
of a transaction cannot leave a stale cache behind.
|
|
46
|
+
"""
|
|
47
|
+
|
|
48
|
+
from __future__ import annotations
|
|
49
|
+
|
|
50
|
+
import logging
|
|
51
|
+
import sys
|
|
52
|
+
from collections.abc import Iterable, Sequence
|
|
53
|
+
from itertools import chain
|
|
54
|
+
from typing import TYPE_CHECKING, Any, NamedTuple, TypeVar, cast
|
|
55
|
+
|
|
56
|
+
from sqlalchemy import event, inspect
|
|
57
|
+
from sqlalchemy.exc import MissingGreenlet, StatementError
|
|
58
|
+
from sqlalchemy.orm import Session, sessionmaker
|
|
59
|
+
|
|
60
|
+
from audit_trail._compaction import FieldChange
|
|
61
|
+
from audit_trail.context import AuditContext, ContextSnapshot, resolve_context
|
|
62
|
+
from audit_trail.diff import (
|
|
63
|
+
USE_CONTEXT,
|
|
64
|
+
ChangeKind,
|
|
65
|
+
entity_changes,
|
|
66
|
+
object_id_of,
|
|
67
|
+
object_type_of,
|
|
68
|
+
options_of,
|
|
69
|
+
resolve_label,
|
|
70
|
+
resolve_scope,
|
|
71
|
+
resolve_target,
|
|
72
|
+
)
|
|
73
|
+
from audit_trail.events import Crud
|
|
74
|
+
from audit_trail.mixin import Audited, refresh_snapshot
|
|
75
|
+
from audit_trail.relations import (
|
|
76
|
+
discard_relationship_changes,
|
|
77
|
+
pop_relationship_changes,
|
|
78
|
+
track_relationships,
|
|
79
|
+
)
|
|
80
|
+
from audit_trail.tables import audit_connection
|
|
81
|
+
from audit_trail.writer import (
|
|
82
|
+
ENVELOPE_VERSION,
|
|
83
|
+
Entry,
|
|
84
|
+
TransactionRow,
|
|
85
|
+
context_data,
|
|
86
|
+
insert_activities,
|
|
87
|
+
insert_transaction,
|
|
88
|
+
run_isolated,
|
|
89
|
+
transaction_values,
|
|
90
|
+
)
|
|
91
|
+
|
|
92
|
+
if TYPE_CHECKING:
|
|
93
|
+
from sqlalchemy import Connection, Result
|
|
94
|
+
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
|
|
95
|
+
from sqlalchemy.orm import (
|
|
96
|
+
InstanceState,
|
|
97
|
+
Mapper,
|
|
98
|
+
ORMExecuteState,
|
|
99
|
+
SessionTransaction,
|
|
100
|
+
UOWTransaction,
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
from audit_trail.config import AuditTrail
|
|
104
|
+
|
|
105
|
+
logger = logging.getLogger(__name__)
|
|
106
|
+
|
|
107
|
+
AUDIT_ENABLED_KEY = "audit_enabled"
|
|
108
|
+
"""``session.info`` key; ``False`` switches capture off for one session."""
|
|
109
|
+
|
|
110
|
+
_CACHE_KEY = "audit_trail.transaction"
|
|
111
|
+
|
|
112
|
+
_A = TypeVar("_A", bound=Audited)
|
|
113
|
+
|
|
114
|
+
_VERBS: dict[ChangeKind, Crud] = {
|
|
115
|
+
"created": Crud.CREATED,
|
|
116
|
+
"updated": Crud.UPDATED,
|
|
117
|
+
"deleted": Crud.DELETED,
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
# Session class -> the AuditTrail installed on it.
|
|
121
|
+
_installed: dict[type[Session], AuditTrail] = {}
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
class AsyncLoadError(MissingGreenlet):
|
|
125
|
+
"""An audited attribute needed a load that ``AsyncSession`` cannot run.
|
|
126
|
+
|
|
127
|
+
Raised in place of SQLAlchemy's ``MissingGreenlet`` (or, with psycopg,
|
|
128
|
+
the ``StatementError`` wrapping it) when host code touches, outside an
|
|
129
|
+
awaited call:
|
|
130
|
+
|
|
131
|
+
- an expired or unloaded column of an ``Audited`` instance, read or
|
|
132
|
+
assigned (``Audited`` loads an expired column's old value when it is
|
|
133
|
+
assigned);
|
|
134
|
+
- a collection named in the model's ``track_relationships`` that is not
|
|
135
|
+
loaded.
|
|
136
|
+
|
|
137
|
+
The message names the model and attribute and how to load it. The
|
|
138
|
+
original exception is the ``__cause__``. A subclass of
|
|
139
|
+
``MissingGreenlet``, so existing handlers of that error still catch it.
|
|
140
|
+
"""
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
class _CachedRow(NamedTuple):
|
|
144
|
+
owner: SessionTransaction
|
|
145
|
+
row: TransactionRow
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
class PendingEntry(NamedTuple):
|
|
149
|
+
"""An entry to write and the object it is about, if any."""
|
|
150
|
+
|
|
151
|
+
entry: Entry
|
|
152
|
+
obj: object | None
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def install(
|
|
156
|
+
trail: AuditTrail,
|
|
157
|
+
session_factory: type[Session | AsyncSession]
|
|
158
|
+
| sessionmaker[Any]
|
|
159
|
+
| async_sessionmaker[Any],
|
|
160
|
+
) -> None:
|
|
161
|
+
"""Register the audit listeners on a session factory's class.
|
|
162
|
+
|
|
163
|
+
Also starts tracking the ``track_relationships`` of every ``Audited``
|
|
164
|
+
model, configured now or later. Tracking is attached to the model
|
|
165
|
+
classes, so it is process-wide: tracked collections record their net
|
|
166
|
+
changes in any session, and those records are dropped when the instance
|
|
167
|
+
is expired or garbage collected.
|
|
168
|
+
|
|
169
|
+
Args:
|
|
170
|
+
trail: The configuration the listeners write with.
|
|
171
|
+
session_factory: A ``sessionmaker`` or a ``Session`` subclass; or
|
|
172
|
+
an ``async_sessionmaker`` or ``AsyncSession`` subclass whose
|
|
173
|
+
``sync_session_class`` is a ``Session`` subclass, e.g.
|
|
174
|
+
``async_sessionmaker(engine, sync_session_class=AppSession)``.
|
|
175
|
+
|
|
176
|
+
Raises:
|
|
177
|
+
TypeError: ``session_factory`` is none of these, or its
|
|
178
|
+
``sync_session_class`` is not a ``Session`` subclass.
|
|
179
|
+
ValueError: The session class is the base ``Session`` (for an async
|
|
180
|
+
factory: no ``sync_session_class`` was given), or an
|
|
181
|
+
``AuditTrail`` is already installed on it, a base class or a
|
|
182
|
+
subclass of it.
|
|
183
|
+
"""
|
|
184
|
+
cls = _session_class(session_factory)
|
|
185
|
+
other = next(
|
|
186
|
+
(c for c in _installed if issubclass(cls, c) or issubclass(c, cls)), None
|
|
187
|
+
)
|
|
188
|
+
if other is not None:
|
|
189
|
+
raise ValueError(
|
|
190
|
+
f"an AuditTrail is already installed on {other.__qualname__}; "
|
|
191
|
+
f"installing on {cls.__qualname__} would audit its sessions twice"
|
|
192
|
+
)
|
|
193
|
+
listener = _Listener(trail)
|
|
194
|
+
event.listen(cls, "after_flush", listener.after_flush)
|
|
195
|
+
event.listen(cls, "do_orm_execute", listener.do_orm_execute)
|
|
196
|
+
event.listen(cls, "do_orm_execute", _explain_async_load)
|
|
197
|
+
event.listen(cls, "after_transaction_end", _after_transaction_end)
|
|
198
|
+
event.listen(cls, "after_soft_rollback", _after_soft_rollback)
|
|
199
|
+
event.listen(cls, "after_rollback", _after_rollback)
|
|
200
|
+
_installed[cls] = trail
|
|
201
|
+
_track_all_relationships()
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def installed_trail(session: Session) -> AuditTrail | None:
|
|
205
|
+
"""Return the ``AuditTrail`` installed on the session's class, if any.
|
|
206
|
+
|
|
207
|
+
Args:
|
|
208
|
+
session: A session.
|
|
209
|
+
|
|
210
|
+
Returns:
|
|
211
|
+
The installed configuration, or ``None``.
|
|
212
|
+
"""
|
|
213
|
+
for cls in type(session).__mro__:
|
|
214
|
+
trail = _installed.get(cls)
|
|
215
|
+
if trail is not None:
|
|
216
|
+
return trail
|
|
217
|
+
return None
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def _session_class(factory: object) -> type[Session]:
|
|
221
|
+
if isinstance(factory, sessionmaker):
|
|
222
|
+
cls: type[Session] = factory.class_
|
|
223
|
+
elif isinstance(factory, type) and issubclass(factory, Session):
|
|
224
|
+
cls = factory
|
|
225
|
+
else:
|
|
226
|
+
sync_class = _sync_session_class(factory)
|
|
227
|
+
if sync_class is None:
|
|
228
|
+
raise TypeError(
|
|
229
|
+
"install() needs a sessionmaker or a Session subclass (or their "
|
|
230
|
+
f"async counterparts), got {factory!r}"
|
|
231
|
+
)
|
|
232
|
+
if sync_class is Session:
|
|
233
|
+
raise ValueError(
|
|
234
|
+
"install() refuses an async factory whose sync_session_class is "
|
|
235
|
+
"the base Session: its listeners would audit every session in "
|
|
236
|
+
"the process; pass sync_session_class=<your Session subclass>"
|
|
237
|
+
)
|
|
238
|
+
if not (isinstance(sync_class, type) and issubclass(sync_class, Session)):
|
|
239
|
+
raise TypeError(
|
|
240
|
+
f"sync_session_class must be a Session subclass, got {sync_class!r}"
|
|
241
|
+
)
|
|
242
|
+
cls = sync_class
|
|
243
|
+
if cls is Session:
|
|
244
|
+
raise ValueError(
|
|
245
|
+
"install() refuses the base Session: its listeners would audit "
|
|
246
|
+
"every session in the process; pass your sessionmaker or a "
|
|
247
|
+
"Session subclass"
|
|
248
|
+
)
|
|
249
|
+
return cls
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def _sync_session_class(factory: object) -> object | None:
|
|
253
|
+
# Looked up through sys.modules so sync-only hosts never import asyncio
|
|
254
|
+
# support (and greenlet): an async factory implies it is loaded already.
|
|
255
|
+
# Returns None when factory is not an async factory.
|
|
256
|
+
asyncio_module = sys.modules.get("sqlalchemy.ext.asyncio")
|
|
257
|
+
if asyncio_module is None:
|
|
258
|
+
return None
|
|
259
|
+
if isinstance(factory, asyncio_module.async_sessionmaker):
|
|
260
|
+
explicit: object = factory.kw.get("sync_session_class")
|
|
261
|
+
return explicit or factory.class_.sync_session_class
|
|
262
|
+
if isinstance(factory, type) and issubclass(factory, asyncio_module.AsyncSession):
|
|
263
|
+
return cast("type[AsyncSession]", factory).sync_session_class
|
|
264
|
+
return None
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
_tracking_registered = False
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def _track_all_relationships() -> None:
|
|
271
|
+
global _tracking_registered
|
|
272
|
+
if not _tracking_registered:
|
|
273
|
+
# Fires for Audited models configured from now on, including ones
|
|
274
|
+
# declared already but not configured yet.
|
|
275
|
+
event.listen(Audited, "mapper_configured", _track_model, propagate=True)
|
|
276
|
+
_tracking_registered = True
|
|
277
|
+
for cls in _subclasses(Audited):
|
|
278
|
+
mapper = inspect(cls, raiseerr=False)
|
|
279
|
+
if mapper is not None and mapper.configured:
|
|
280
|
+
_track_model(mapper, cls)
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def _subclasses(cls: type[Any]) -> Iterable[type[Any]]:
|
|
284
|
+
pending = list(cls.__subclasses__())
|
|
285
|
+
while pending:
|
|
286
|
+
sub = pending.pop()
|
|
287
|
+
pending.extend(sub.__subclasses__())
|
|
288
|
+
yield sub
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
def _track_model(mapper: Mapper[_A], cls: type[_A]) -> None:
|
|
292
|
+
# Runs inside mapper configuration, for every Audited model in the
|
|
293
|
+
# process: an exception here would leave SQLAlchemy's configuration
|
|
294
|
+
# failed for all models, so a bad name is skipped with a warning and
|
|
295
|
+
# check_models() reports it as an error.
|
|
296
|
+
for name in sorted(options_of(cls).track_relationships):
|
|
297
|
+
prop = mapper.relationships.get(name)
|
|
298
|
+
if prop is None or not prop.uselist:
|
|
299
|
+
what = "not a relationship" if prop is None else "a scalar relationship"
|
|
300
|
+
logger.warning(
|
|
301
|
+
"%s: track_relationships names %r, which is %s; it is not "
|
|
302
|
+
"tracked (check_models() reports this)",
|
|
303
|
+
cls.__qualname__,
|
|
304
|
+
name,
|
|
305
|
+
what,
|
|
306
|
+
)
|
|
307
|
+
continue
|
|
308
|
+
# Tracked on the declaring class; tracking again from a subclass is a
|
|
309
|
+
# no-op in track_relationships.
|
|
310
|
+
track_relationships(getattr(prop.parent.class_, name))
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
class _Listener:
|
|
314
|
+
"""The capture listener of one ``install()``."""
|
|
315
|
+
|
|
316
|
+
def __init__(self, trail: AuditTrail) -> None:
|
|
317
|
+
self.trail = trail
|
|
318
|
+
|
|
319
|
+
def after_flush(self, session: Session, flush_context: UOWTransaction) -> None:
|
|
320
|
+
if session.info.get(AUDIT_ENABLED_KEY) is False:
|
|
321
|
+
return
|
|
322
|
+
ctx = resolve_context(session, self.trail.context_provider)
|
|
323
|
+
entries = self._entries(session, ctx)
|
|
324
|
+
if entries:
|
|
325
|
+
write_entries(session, self.trail, entries, ctx)
|
|
326
|
+
|
|
327
|
+
def do_orm_execute(self, orm_execute_state: ORMExecuteState) -> None:
|
|
328
|
+
"""Warn about a bulk ``UPDATE``/``DELETE`` of an audited table.
|
|
329
|
+
|
|
330
|
+
Such statements bypass the flush, so no entry is written for them.
|
|
331
|
+
"""
|
|
332
|
+
state = orm_execute_state
|
|
333
|
+
if not self.trail.warn_on_bulk:
|
|
334
|
+
return
|
|
335
|
+
if not (state.is_update or state.is_delete):
|
|
336
|
+
return
|
|
337
|
+
if state.session.info.get(AUDIT_ENABLED_KEY) is False:
|
|
338
|
+
return
|
|
339
|
+
if state.execution_options.get("audit_bulk_ok"):
|
|
340
|
+
return
|
|
341
|
+
model = _audited_model(state)
|
|
342
|
+
if model is not None:
|
|
343
|
+
logger.warning(
|
|
344
|
+
"Bulk %s of %s bypasses the audit trail: no entry is written. "
|
|
345
|
+
"Pass execution_options(audit_bulk_ok=True) if this is intended.",
|
|
346
|
+
"UPDATE" if state.is_update else "DELETE",
|
|
347
|
+
model.__qualname__,
|
|
348
|
+
)
|
|
349
|
+
|
|
350
|
+
def _entries(self, session: Session, ctx: AuditContext) -> list[PendingEntry]:
|
|
351
|
+
trail = self.trail
|
|
352
|
+
context = context_data(ctx, trail.json_encoder)
|
|
353
|
+
batches: tuple[tuple[ChangeKind, Iterable[object]], ...] = (
|
|
354
|
+
("created", session.new),
|
|
355
|
+
("updated", session.dirty),
|
|
356
|
+
("deleted", session.deleted),
|
|
357
|
+
)
|
|
358
|
+
entries: list[PendingEntry] = []
|
|
359
|
+
for kind, objects in batches:
|
|
360
|
+
for obj in objects:
|
|
361
|
+
if not isinstance(obj, Audited):
|
|
362
|
+
continue
|
|
363
|
+
entry = self._entry(obj, kind, ctx, context)
|
|
364
|
+
if entry is not None:
|
|
365
|
+
entries.append(PendingEntry(entry, obj))
|
|
366
|
+
# Only now: the snapshots were the old values of this flush's changes.
|
|
367
|
+
for obj in chain(session.new, session.dirty):
|
|
368
|
+
if isinstance(obj, Audited):
|
|
369
|
+
refresh_snapshot(obj)
|
|
370
|
+
return entries
|
|
371
|
+
|
|
372
|
+
def _entry(
|
|
373
|
+
self,
|
|
374
|
+
obj: Audited,
|
|
375
|
+
kind: ChangeKind,
|
|
376
|
+
ctx: AuditContext,
|
|
377
|
+
context: ContextSnapshot,
|
|
378
|
+
) -> Entry | None:
|
|
379
|
+
trail = self.trail
|
|
380
|
+
changes: dict[str, FieldChange] = {}
|
|
381
|
+
changes.update(
|
|
382
|
+
entity_changes(
|
|
383
|
+
obj,
|
|
384
|
+
kind,
|
|
385
|
+
keys=trail.keys,
|
|
386
|
+
json_encoder=trail.json_encoder,
|
|
387
|
+
global_redact=trail.global_redact,
|
|
388
|
+
)
|
|
389
|
+
)
|
|
390
|
+
relationship_changes = pop_relationship_changes(obj)
|
|
391
|
+
if kind != "deleted":
|
|
392
|
+
# A deleted instance's memberships end with it; its delta, if
|
|
393
|
+
# any, is dropped.
|
|
394
|
+
changes.update(relationship_changes)
|
|
395
|
+
if kind == "updated" and not changes:
|
|
396
|
+
return None
|
|
397
|
+
options = options_of(type(obj))
|
|
398
|
+
scope = resolve_scope(obj, options)
|
|
399
|
+
target_type, target_id = resolve_target(obj, options) or (None, None)
|
|
400
|
+
event_ = _VERBS[kind]
|
|
401
|
+
return {
|
|
402
|
+
"verb": event_.value,
|
|
403
|
+
"severity": int(trail.registry.severity_of(event_, options)),
|
|
404
|
+
"object_type": object_type_of(obj),
|
|
405
|
+
"object_id": object_id_of(obj),
|
|
406
|
+
"object_label": resolve_label(obj, options),
|
|
407
|
+
"target_type": target_type,
|
|
408
|
+
"target_id": target_id,
|
|
409
|
+
"actor_id": ctx.actor_id,
|
|
410
|
+
"scope_id": ctx.scope_id if scope is USE_CONTEXT else scope,
|
|
411
|
+
"data": {"v": ENVELOPE_VERSION, "changes": changes, "context": context},
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
|
|
415
|
+
# Private SQLAlchemy load option holding the instance of a column load (2.0
|
|
416
|
+
# and 2.1); without it the message names only the model.
|
|
417
|
+
_REFRESH_STATE = "_refresh_state"
|
|
418
|
+
|
|
419
|
+
|
|
420
|
+
def _explain_async_load(orm_execute_state: ORMExecuteState) -> Result[Any] | None:
|
|
421
|
+
# Runs for every ORM statement of an installed session class, so the
|
|
422
|
+
# common case (not a lazy or expired-attribute load of an Audited
|
|
423
|
+
# instance on an async dialect) returns before running anything, and a
|
|
424
|
+
# session bound to a sync engine returns first.
|
|
425
|
+
state = orm_execute_state
|
|
426
|
+
bind = state.session.bind
|
|
427
|
+
if bind is not None and not bind.dialect.is_async:
|
|
428
|
+
return None
|
|
429
|
+
if state.is_column_load:
|
|
430
|
+
instance: InstanceState[Any] | None = getattr(
|
|
431
|
+
state.load_options, _REFRESH_STATE, None
|
|
432
|
+
)
|
|
433
|
+
mapper = state.bind_mapper if instance is None else instance.mapper
|
|
434
|
+
elif state.is_relationship_load:
|
|
435
|
+
instance = state.lazy_loaded_from
|
|
436
|
+
if instance is None:
|
|
437
|
+
return None # an eager loader, run by an awaited query
|
|
438
|
+
mapper = instance.mapper
|
|
439
|
+
else:
|
|
440
|
+
return None
|
|
441
|
+
if mapper is None or not issubclass(mapper.class_, Audited):
|
|
442
|
+
return None
|
|
443
|
+
if bind is None: # bound per mapper or table
|
|
444
|
+
bind = state.session.get_bind(**state.bind_arguments)
|
|
445
|
+
if not bind.dialect.is_async:
|
|
446
|
+
return None
|
|
447
|
+
try:
|
|
448
|
+
return state.invoke_statement()
|
|
449
|
+
except (MissingGreenlet, StatementError) as exc:
|
|
450
|
+
cause = exc if isinstance(exc, MissingGreenlet) else exc.orig
|
|
451
|
+
if not isinstance(cause, MissingGreenlet) or isinstance(exc, AsyncLoadError):
|
|
452
|
+
raise
|
|
453
|
+
message = (
|
|
454
|
+
_column_load_message(mapper, instance)
|
|
455
|
+
if state.is_column_load
|
|
456
|
+
else _collection_load_message(mapper, instance, state.bind_mapper)
|
|
457
|
+
)
|
|
458
|
+
if message is None:
|
|
459
|
+
raise
|
|
460
|
+
raise AsyncLoadError(message) from exc
|
|
461
|
+
|
|
462
|
+
|
|
463
|
+
_NO_IMPLICIT_IO = (
|
|
464
|
+
"loading it needs database I/O, which an AsyncSession cannot run outside "
|
|
465
|
+
"an awaited call"
|
|
466
|
+
)
|
|
467
|
+
|
|
468
|
+
|
|
469
|
+
def _column_load_message(
|
|
470
|
+
mapper: Mapper[Any], instance: InstanceState[Any] | None
|
|
471
|
+
) -> str:
|
|
472
|
+
name = mapper.class_.__qualname__
|
|
473
|
+
columns = {prop.key for prop in mapper.column_attrs}
|
|
474
|
+
unloaded = [] if instance is None else sorted(instance.unloaded & columns)
|
|
475
|
+
if not unloaded:
|
|
476
|
+
what = f"an attribute of {name} is"
|
|
477
|
+
elif len(unloaded) == 1:
|
|
478
|
+
what = f"{name}.{unloaded[0]} is"
|
|
479
|
+
else:
|
|
480
|
+
what = ", ".join(f"{name}.{key}" for key in unloaded) + " are"
|
|
481
|
+
return (
|
|
482
|
+
f"{what} not loaded (expired, e.g. by commit), and {_NO_IMPLICIT_IO}. "
|
|
483
|
+
"This happens when an unloaded attribute is read, and for an audited "
|
|
484
|
+
"column also when it is assigned: Audited loads the old value to "
|
|
485
|
+
"record the change. Load it first with `await session.refresh(obj)`, "
|
|
486
|
+
"or create the session with expire_on_commit=False."
|
|
487
|
+
)
|
|
488
|
+
|
|
489
|
+
|
|
490
|
+
def _collection_load_message(
|
|
491
|
+
mapper: Mapper[Any],
|
|
492
|
+
instance: InstanceState[Any] | None,
|
|
493
|
+
target: Mapper[Any] | None,
|
|
494
|
+
) -> str | None:
|
|
495
|
+
# SQLAlchemy does not say which relationship is being loaded: name the
|
|
496
|
+
# tracked ones that are unloaded and point at the loaded class.
|
|
497
|
+
if instance is None or target is None:
|
|
498
|
+
return None
|
|
499
|
+
tracked = options_of(mapper.class_).track_relationships
|
|
500
|
+
keys = [
|
|
501
|
+
rel.key
|
|
502
|
+
for rel in mapper.relationships
|
|
503
|
+
if rel.key in tracked
|
|
504
|
+
and rel.key in instance.unloaded
|
|
505
|
+
and (target.isa(rel.mapper) or rel.mapper.isa(target))
|
|
506
|
+
]
|
|
507
|
+
if not keys:
|
|
508
|
+
return None
|
|
509
|
+
name = mapper.class_.__qualname__
|
|
510
|
+
attributes = " or ".join(f"{name}.{key}" for key in keys)
|
|
511
|
+
loaders = " or ".join(f"selectinload({name}.{key})" for key in keys)
|
|
512
|
+
return (
|
|
513
|
+
f"{attributes} is not loaded, and {_NO_IMPLICIT_IO}. Load tracked "
|
|
514
|
+
f"collections eagerly before changing them: {loaders} in the query, "
|
|
515
|
+
'or lazy="selectin" on the relationship.'
|
|
516
|
+
)
|
|
517
|
+
|
|
518
|
+
|
|
519
|
+
def _audited_model(state: ORMExecuteState) -> type[Any] | None:
|
|
520
|
+
# Matched by table, which covers ORM update(Model) and Core update(table).
|
|
521
|
+
table = getattr(state.statement, "table", None)
|
|
522
|
+
for cls in _subclasses(Audited):
|
|
523
|
+
mapper = inspect(cls, raiseerr=False)
|
|
524
|
+
if mapper is not None and table in mapper.tables:
|
|
525
|
+
return cls
|
|
526
|
+
return None
|
|
527
|
+
|
|
528
|
+
|
|
529
|
+
def write_entries(
|
|
530
|
+
session: Session,
|
|
531
|
+
trail: AuditTrail,
|
|
532
|
+
entries: Sequence[PendingEntry],
|
|
533
|
+
ctx: AuditContext,
|
|
534
|
+
) -> None:
|
|
535
|
+
"""Write entries in the session's current database transaction.
|
|
536
|
+
|
|
537
|
+
Each entry goes on the connection its object's rows were flushed on:
|
|
538
|
+
``session.connection()`` with the base mapper of the object, as the flush
|
|
539
|
+
resolves it (mapper binds, then its table's, then the default bind). An
|
|
540
|
+
entry without an object uses the audit tables as the clause (their binds,
|
|
541
|
+
then the default bind). A ``get_bind`` override is honoured.
|
|
542
|
+
|
|
543
|
+
Per connection, inserts the ``audit_transaction`` row first when that
|
|
544
|
+
connection's transaction has none yet, then its entries with one
|
|
545
|
+
``executemany``, following ``trail.on_error``. Uses only the connections,
|
|
546
|
+
never the ORM.
|
|
547
|
+
|
|
548
|
+
Args:
|
|
549
|
+
session: A session of an installed class.
|
|
550
|
+
trail: The configuration to write with.
|
|
551
|
+
entries: The entries, with the objects they are about.
|
|
552
|
+
ctx: The context, used when a transaction row is created.
|
|
553
|
+
|
|
554
|
+
Raises:
|
|
555
|
+
UnboundExecutionError: An entry without an object, and the session
|
|
556
|
+
has no bind for the audit tables.
|
|
557
|
+
"""
|
|
558
|
+
by_mapper: dict[Mapper[Any] | None, Connection] = {}
|
|
559
|
+
groups: dict[Connection, list[Entry]] = {}
|
|
560
|
+
for pending in entries:
|
|
561
|
+
mapper = _base_mapper(pending.obj)
|
|
562
|
+
connection = by_mapper.get(mapper)
|
|
563
|
+
if connection is None:
|
|
564
|
+
connection = by_mapper[mapper] = _connection_for(session, trail, mapper)
|
|
565
|
+
groups.setdefault(connection, []).append(pending.entry)
|
|
566
|
+
for connection, group in groups.items():
|
|
567
|
+
_write_group(session, trail, connection, group, ctx)
|
|
568
|
+
|
|
569
|
+
|
|
570
|
+
def _base_mapper(obj: object | None) -> Mapper[Any] | None:
|
|
571
|
+
# The flush resolves an object's connection from its base mapper.
|
|
572
|
+
state = None if obj is None else inspect(obj, raiseerr=False)
|
|
573
|
+
mapper: Mapper[Any] | None = getattr(state, "mapper", None)
|
|
574
|
+
return None if mapper is None else mapper.base_mapper
|
|
575
|
+
|
|
576
|
+
|
|
577
|
+
def _connection_for(
|
|
578
|
+
session: Session, trail: AuditTrail, mapper: Mapper[Any] | None
|
|
579
|
+
) -> Connection:
|
|
580
|
+
if mapper is not None:
|
|
581
|
+
return session.connection(bind_arguments={"mapper": mapper})
|
|
582
|
+
return audit_connection(
|
|
583
|
+
session,
|
|
584
|
+
trail.tables,
|
|
585
|
+
" log() and alog() with obj= use the bind of the object instead.",
|
|
586
|
+
)
|
|
587
|
+
|
|
588
|
+
|
|
589
|
+
def _write_group(
|
|
590
|
+
session: Session,
|
|
591
|
+
trail: AuditTrail,
|
|
592
|
+
connection: Connection,
|
|
593
|
+
entries: Sequence[Entry],
|
|
594
|
+
ctx: AuditContext,
|
|
595
|
+
) -> None:
|
|
596
|
+
cached = _cached_row(session, connection)
|
|
597
|
+
|
|
598
|
+
def work() -> TransactionRow:
|
|
599
|
+
row = cached or insert_transaction(
|
|
600
|
+
connection,
|
|
601
|
+
trail.tables.transaction,
|
|
602
|
+
transaction_values(ctx, trail.json_encoder),
|
|
603
|
+
)
|
|
604
|
+
insert_activities(connection, trail.tables.activity, row, entries)
|
|
605
|
+
return row
|
|
606
|
+
|
|
607
|
+
row = run_isolated(connection, trail.on_error, work)
|
|
608
|
+
if row is not None and cached is None:
|
|
609
|
+
owner = session.get_nested_transaction() or session.get_transaction()
|
|
610
|
+
assert owner is not None # session.connection() began one
|
|
611
|
+
rows: dict[Connection, _CachedRow] = session.info.setdefault(_CACHE_KEY, {})
|
|
612
|
+
rows[connection] = _CachedRow(owner, row)
|
|
613
|
+
|
|
614
|
+
|
|
615
|
+
def _cached_row(session: Session, connection: Connection) -> TransactionRow | None:
|
|
616
|
+
rows: dict[Connection, _CachedRow] = session.info.get(_CACHE_KEY, {})
|
|
617
|
+
cached = rows.get(connection)
|
|
618
|
+
return None if cached is None else cached.row
|
|
619
|
+
|
|
620
|
+
|
|
621
|
+
def _after_transaction_end(session: Session, transaction: SessionTransaction) -> None:
|
|
622
|
+
# Fires for every way a transaction ends, including Session.close()
|
|
623
|
+
# without commit or rollback, which fires no commit or rollback event.
|
|
624
|
+
# A released savepoint or a flush's subtransaction is not the end of the
|
|
625
|
+
# database transaction: the rows live on in the enclosing one.
|
|
626
|
+
if transaction.parent is None:
|
|
627
|
+
session.info.pop(_CACHE_KEY, None)
|
|
628
|
+
|
|
629
|
+
|
|
630
|
+
def _after_soft_rollback(
|
|
631
|
+
session: Session, previous_transaction: SessionTransaction
|
|
632
|
+
) -> None:
|
|
633
|
+
rows: dict[Connection, _CachedRow] | None = session.info.get(_CACHE_KEY)
|
|
634
|
+
if not rows:
|
|
635
|
+
return
|
|
636
|
+
# A savepoint spans every connection of the session, so its rollback
|
|
637
|
+
# removes the rows it holds on each.
|
|
638
|
+
for connection, cached in list(rows.items()):
|
|
639
|
+
if _within(cached.owner, previous_transaction):
|
|
640
|
+
del rows[connection]
|
|
641
|
+
|
|
642
|
+
|
|
643
|
+
def _within(transaction: SessionTransaction, ancestor: SessionTransaction) -> bool:
|
|
644
|
+
current: SessionTransaction | None = transaction
|
|
645
|
+
while current is not None:
|
|
646
|
+
if current is ancestor:
|
|
647
|
+
return True
|
|
648
|
+
current = current.parent
|
|
649
|
+
return False
|
|
650
|
+
|
|
651
|
+
|
|
652
|
+
def _after_rollback(session: Session) -> None:
|
|
653
|
+
# Also fires for a savepoint rollback, so it must not drop the cached
|
|
654
|
+
# transaction row (see the module docstring).
|
|
655
|
+
discard_relationship_changes(session)
|