sqlalchemy-audit-trail 0.2.0__tar.gz → 0.3.0__tar.gz

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 (30) hide show
  1. {sqlalchemy_audit_trail-0.2.0 → sqlalchemy_audit_trail-0.3.0}/PKG-INFO +5 -6
  2. {sqlalchemy_audit_trail-0.2.0 → sqlalchemy_audit_trail-0.3.0}/README.md +3 -3
  3. {sqlalchemy_audit_trail-0.2.0 → sqlalchemy_audit_trail-0.3.0}/audit_trail/_compaction.py +1 -2
  4. {sqlalchemy_audit_trail-0.2.0 → sqlalchemy_audit_trail-0.3.0}/audit_trail/checks.py +1 -2
  5. {sqlalchemy_audit_trail-0.2.0 → sqlalchemy_audit_trail-0.3.0}/audit_trail/diff.py +203 -14
  6. {sqlalchemy_audit_trail-0.2.0 → sqlalchemy_audit_trail-0.3.0}/audit_trail/events.py +2 -1
  7. {sqlalchemy_audit_trail-0.2.0 → sqlalchemy_audit_trail-0.3.0}/audit_trail/listener.py +23 -0
  8. {sqlalchemy_audit_trail-0.2.0 → sqlalchemy_audit_trail-0.3.0}/audit_trail/maintenance.py +2 -2
  9. {sqlalchemy_audit_trail-0.2.0 → sqlalchemy_audit_trail-0.3.0}/audit_trail/migrations.py +5 -5
  10. {sqlalchemy_audit_trail-0.2.0 → sqlalchemy_audit_trail-0.3.0}/audit_trail/mixin.py +19 -2
  11. {sqlalchemy_audit_trail-0.2.0 → sqlalchemy_audit_trail-0.3.0}/audit_trail/query.py +3 -4
  12. {sqlalchemy_audit_trail-0.2.0 → sqlalchemy_audit_trail-0.3.0}/audit_trail/tables.py +1 -3
  13. {sqlalchemy_audit_trail-0.2.0 → sqlalchemy_audit_trail-0.3.0}/audit_trail/writer.py +3 -8
  14. {sqlalchemy_audit_trail-0.2.0 → sqlalchemy_audit_trail-0.3.0}/pyproject.toml +5 -6
  15. sqlalchemy_audit_trail-0.2.0/audit_trail/_typing.py +0 -17
  16. {sqlalchemy_audit_trail-0.2.0 → sqlalchemy_audit_trail-0.3.0}/.gitignore +0 -0
  17. {sqlalchemy_audit_trail-0.2.0 → sqlalchemy_audit_trail-0.3.0}/LICENSE +0 -0
  18. {sqlalchemy_audit_trail-0.2.0 → sqlalchemy_audit_trail-0.3.0}/audit_trail/__init__.py +0 -0
  19. {sqlalchemy_audit_trail-0.2.0 → sqlalchemy_audit_trail-0.3.0}/audit_trail/config.py +0 -0
  20. {sqlalchemy_audit_trail-0.2.0 → sqlalchemy_audit_trail-0.3.0}/audit_trail/context.py +0 -0
  21. {sqlalchemy_audit_trail-0.2.0 → sqlalchemy_audit_trail-0.3.0}/audit_trail/integrations/__init__.py +0 -0
  22. {sqlalchemy_audit_trail-0.2.0 → sqlalchemy_audit_trail-0.3.0}/audit_trail/integrations/fastapi.py +0 -0
  23. {sqlalchemy_audit_trail-0.2.0 → sqlalchemy_audit_trail-0.3.0}/audit_trail/privacy.py +0 -0
  24. {sqlalchemy_audit_trail-0.2.0 → sqlalchemy_audit_trail-0.3.0}/audit_trail/py.typed +0 -0
  25. {sqlalchemy_audit_trail-0.2.0 → sqlalchemy_audit_trail-0.3.0}/audit_trail/pytest_plugin.py +0 -0
  26. {sqlalchemy_audit_trail-0.2.0 → sqlalchemy_audit_trail-0.3.0}/audit_trail/relations.py +0 -0
  27. {sqlalchemy_audit_trail-0.2.0 → sqlalchemy_audit_trail-0.3.0}/audit_trail/serialization.py +0 -0
  28. {sqlalchemy_audit_trail-0.2.0 → sqlalchemy_audit_trail-0.3.0}/audit_trail/testing.py +0 -0
  29. {sqlalchemy_audit_trail-0.2.0 → sqlalchemy_audit_trail-0.3.0}/benchmark/README.md +0 -0
  30. {sqlalchemy_audit_trail-0.2.0 → sqlalchemy_audit_trail-0.3.0}/examples/fastapi_app/README.md +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: sqlalchemy-audit-trail
3
- Version: 0.2.0
3
+ Version: 0.3.0
4
4
  Summary: Audit trail for SQLAlchemy on PostgreSQL: entity change diffs and domain events in one partitioned log
5
5
  Project-URL: Homepage, https://github.com/WiktorB2004/sqlalchemy-audit-trail
6
6
  Project-URL: Repository, https://github.com/WiktorB2004/sqlalchemy-audit-trail
@@ -19,13 +19,12 @@ Classifier: Operating System :: OS Independent
19
19
  Classifier: Programming Language :: Python
20
20
  Classifier: Programming Language :: Python :: 3
21
21
  Classifier: Programming Language :: Python :: 3 :: Only
22
- Classifier: Programming Language :: Python :: 3.10
23
22
  Classifier: Programming Language :: Python :: 3.11
24
23
  Classifier: Programming Language :: Python :: 3.12
25
24
  Classifier: Programming Language :: Python :: 3.13
26
25
  Classifier: Topic :: Database
27
26
  Classifier: Typing :: Typed
28
- Requires-Python: <4.0,>=3.10
27
+ Requires-Python: <4.0,>=3.11
29
28
  Requires-Dist: sqlalchemy<2.2,>=2.0
30
29
  Provides-Extra: asyncio
31
30
  Requires-Dist: sqlalchemy[asyncio]<2.2,>=2.0; extra == 'asyncio'
@@ -45,7 +44,7 @@ Description-Content-Type: text/markdown
45
44
  Audit trail for **SQLAlchemy on PostgreSQL**: automatic entity change diffs and explicit domain events in one chronological, partitioned log, with who, where and how on every entry. Not a version-table library like sqlalchemy-continuum.
46
45
 
47
46
  [![PyPI](https://img.shields.io/pypi/v/sqlalchemy-audit-trail)](https://pypi.org/project/sqlalchemy-audit-trail/)
48
- [![Python 3.10+](https://img.shields.io/badge/python-3.10%2B-blue)](https://pypi.org/project/sqlalchemy-audit-trail/)
47
+ [![Python 3.11+](https://img.shields.io/badge/python-3.11%2B-blue)](https://pypi.org/project/sqlalchemy-audit-trail/)
49
48
  [![Docs](https://img.shields.io/badge/docs-GitHub%20Pages-blue)](https://wiktorb2004.github.io/sqlalchemy-audit-trail/)
50
49
  [![CI](https://img.shields.io/github/actions/workflow/status/WiktorB2004/sqlalchemy-audit-trail/ci.yml?branch=main&label=CI)](https://github.com/WiktorB2004/sqlalchemy-audit-trail/actions/workflows/ci.yml)
51
50
  [![License: MIT](https://img.shields.io/github/license/WiktorB2004/sqlalchemy-audit-trail)](LICENSE)
@@ -61,7 +60,7 @@ pip install "sqlalchemy-audit-trail[asyncpg]" # AsyncSession on asyncpg
61
60
  # more extras: asyncio, pydantic (payload schemas), fastapi
62
61
  ```
63
62
 
64
- Requires Python 3.10+, SQLAlchemy 2.0 or 2.1, and PostgreSQL 14+.
63
+ Requires Python 3.11+, SQLAlchemy 2.0 or 2.1, and PostgreSQL 14+.
65
64
 
66
65
  ## Quickstart
67
66
 
@@ -192,7 +191,7 @@ AUDIT_TEST_PG_IMAGE=postgres:14 uv run pytest # oldest supported PostgreSQL
192
191
  uv run ruff check . && uv run mypy
193
192
  ```
194
193
 
195
- To use a server you already have, set `AUDIT_TEST_DATABASE_URL`. CI runs PostgreSQL 14, 16, 17 and 18, SQLAlchemy 2.0 and 2.1, and Python 3.10 to 3.13.
194
+ To use a server you already have, set `AUDIT_TEST_DATABASE_URL`. CI runs PostgreSQL 14, 16, 17 and 18, SQLAlchemy 2.0 and 2.1, and Python 3.11 to 3.13.
196
195
 
197
196
  ## Docs
198
197
 
@@ -3,7 +3,7 @@
3
3
  Audit trail for **SQLAlchemy on PostgreSQL**: automatic entity change diffs and explicit domain events in one chronological, partitioned log, with who, where and how on every entry. Not a version-table library like sqlalchemy-continuum.
4
4
 
5
5
  [![PyPI](https://img.shields.io/pypi/v/sqlalchemy-audit-trail)](https://pypi.org/project/sqlalchemy-audit-trail/)
6
- [![Python 3.10+](https://img.shields.io/badge/python-3.10%2B-blue)](https://pypi.org/project/sqlalchemy-audit-trail/)
6
+ [![Python 3.11+](https://img.shields.io/badge/python-3.11%2B-blue)](https://pypi.org/project/sqlalchemy-audit-trail/)
7
7
  [![Docs](https://img.shields.io/badge/docs-GitHub%20Pages-blue)](https://wiktorb2004.github.io/sqlalchemy-audit-trail/)
8
8
  [![CI](https://img.shields.io/github/actions/workflow/status/WiktorB2004/sqlalchemy-audit-trail/ci.yml?branch=main&label=CI)](https://github.com/WiktorB2004/sqlalchemy-audit-trail/actions/workflows/ci.yml)
9
9
  [![License: MIT](https://img.shields.io/github/license/WiktorB2004/sqlalchemy-audit-trail)](LICENSE)
@@ -19,7 +19,7 @@ pip install "sqlalchemy-audit-trail[asyncpg]" # AsyncSession on asyncpg
19
19
  # more extras: asyncio, pydantic (payload schemas), fastapi
20
20
  ```
21
21
 
22
- Requires Python 3.10+, SQLAlchemy 2.0 or 2.1, and PostgreSQL 14+.
22
+ Requires Python 3.11+, SQLAlchemy 2.0 or 2.1, and PostgreSQL 14+.
23
23
 
24
24
  ## Quickstart
25
25
 
@@ -150,7 +150,7 @@ AUDIT_TEST_PG_IMAGE=postgres:14 uv run pytest # oldest supported PostgreSQL
150
150
  uv run ruff check . && uv run mypy
151
151
  ```
152
152
 
153
- To use a server you already have, set `AUDIT_TEST_DATABASE_URL`. CI runs PostgreSQL 14, 16, 17 and 18, SQLAlchemy 2.0 and 2.1, and Python 3.10 to 3.13.
153
+ To use a server you already have, set `AUDIT_TEST_DATABASE_URL`. CI runs PostgreSQL 14, 16, 17 and 18, SQLAlchemy 2.0 and 2.1, and Python 3.11 to 3.13.
154
154
 
155
155
  ## Docs
156
156
 
@@ -13,10 +13,9 @@ import json
13
13
  from collections.abc import Iterable, Sequence
14
14
  from datetime import datetime
15
15
  from itertools import pairwise
16
- from typing import TypeAlias, TypedDict
16
+ from typing import TypeAlias, TypedDict, assert_never
17
17
  from uuid import UUID
18
18
 
19
- from audit_trail._typing import assert_never
20
19
  from audit_trail.context import ContextSnapshot
21
20
  from audit_trail.diff import ERASED, REDACTED, UNKNOWN
22
21
  from audit_trail.events import Crud
@@ -14,14 +14,13 @@ from __future__ import annotations
14
14
  import re
15
15
  from collections.abc import Collection, Iterator
16
16
  from dataclasses import dataclass
17
- from typing import TYPE_CHECKING, Any, Literal, TypeAlias
17
+ from typing import TYPE_CHECKING, Any, Literal, TypeAlias, assert_never
18
18
 
19
19
  from sqlalchemy import Column
20
20
  from sqlalchemy.ext.mutable import Mutable
21
21
  from sqlalchemy.orm import registry
22
22
  from sqlalchemy.types import JSON, TypeDecorator
23
23
 
24
- from audit_trail._typing import assert_never
25
24
  from audit_trail.config import AuditOptions
26
25
  from audit_trail.diff import field_policy, options_of
27
26
  from audit_trail.mixin import Audited
@@ -15,17 +15,26 @@ from __future__ import annotations
15
15
  import functools
16
16
  import json
17
17
  import logging
18
+ import weakref
18
19
  from collections.abc import Callable, Collection, Iterable, Mapping, Sequence
19
20
  from dataclasses import dataclass
20
21
  from enum import Enum
21
- from typing import TYPE_CHECKING, Any, Literal, NamedTuple, TypeAlias, cast
22
+ from typing import (
23
+ TYPE_CHECKING,
24
+ Any,
25
+ Literal,
26
+ NamedTuple,
27
+ TypeAlias,
28
+ assert_never,
29
+ cast,
30
+ )
22
31
 
23
32
  from sqlalchemy import Column, inspect
24
33
  from sqlalchemy.orm import ColumnProperty
25
34
  from sqlalchemy.orm.attributes import instance_state
26
35
  from sqlalchemy.orm.base import NO_VALUE
36
+ from sqlalchemy.sql import ClauseElement
27
37
 
28
- from audit_trail._typing import assert_never
29
38
  from audit_trail.config import AuditOptions, Target
30
39
  from audit_trail.serialization import JSONValue, KeyRing, encode_value, hash_value
31
40
 
@@ -55,6 +64,14 @@ ERASED = "[erased]"
55
64
  SNAPSHOT_INFO_KEY = "audit_trail.snapshot"
56
65
  """``InstanceState.info`` key holding the ``snapshot_on_load`` copies."""
57
66
 
67
+ _FLUSH_CAPTURE_KEY = "audit_trail.flush_capture"
68
+ """``Session.info`` key holding the values captured during the current flush.
69
+
70
+ Set to a new ``{InstanceState: _Captured}`` dict by the installed
71
+ ``before_flush`` listener and removed after the flush, so it only exists
72
+ while a flush of an installed session runs.
73
+ """
74
+
58
75
  _POLICIES: dict[str, FieldPolicy] = {
59
76
  "exclude": "exclude",
60
77
  "redact": "redact",
@@ -95,6 +112,103 @@ class _AuditedColumn:
95
112
  policy: _ValuePolicy | None
96
113
 
97
114
 
115
+ @dataclass(frozen=True, slots=True)
116
+ class _Captured:
117
+ """Old values of one row, taken in ``before_update``.
118
+
119
+ Attributes:
120
+ expr: Old values of audited columns assigned a SQL expression.
121
+ derived: Old values of audited columns the UPDATE may set without an
122
+ assignment (``onupdate``, ``server_onupdate``, ``Computed``, the
123
+ version counter), for those not assigned.
124
+ """
125
+
126
+ expr: dict[str, object]
127
+ derived: dict[str, object]
128
+
129
+
130
+ @dataclass(frozen=True, slots=True)
131
+ class _FlushKeys:
132
+ audited: tuple[str, ...]
133
+ derived: tuple[str, ...]
134
+ server_side: frozenset[str]
135
+
136
+
137
+ _flush_keys: weakref.WeakKeyDictionary[Mapper[Any], _FlushKeys] = (
138
+ weakref.WeakKeyDictionary()
139
+ )
140
+
141
+
142
+ def _is_sql(value: object) -> bool:
143
+ # The test the flush uses to send a value as SQL rather than a parameter.
144
+ return isinstance(value, ClauseElement) or hasattr(value, "__clause_element__")
145
+
146
+
147
+ def _keys_for_flush(mapper: Mapper[Any]) -> _FlushKeys:
148
+ keys = _flush_keys.get(mapper)
149
+ if keys is not None:
150
+ return keys
151
+ version = mapper.version_id_col
152
+ derived: list[str] = []
153
+ server_side: set[str] = set()
154
+ columns = _audited_columns(mapper)
155
+ for spec in columns:
156
+ column = spec.column
157
+ is_version = version is not None and column is version
158
+ if column.server_onupdate is not None or (
159
+ is_version and mapper.version_id_generator is False
160
+ ):
161
+ server_side.add(spec.key)
162
+ elif not (column.onupdate is not None or is_version):
163
+ continue
164
+ derived.append(spec.key)
165
+ keys = _FlushKeys(
166
+ tuple(spec.key for spec in columns), tuple(derived), frozenset(server_side)
167
+ )
168
+ _flush_keys[mapper] = keys
169
+ return keys
170
+
171
+
172
+ def _capture_before_update(state: InstanceState[Any]) -> None:
173
+ """Keep the old values the UPDATE of ``state`` is about to lose.
174
+
175
+ Called from the mapper's ``before_update`` event. Does nothing unless
176
+ the state's session is in a flush of an installed session.
177
+
178
+ Args:
179
+ state: The state of an ``Audited`` instance about to be updated.
180
+ """
181
+ session = state.session
182
+ capture: dict[InstanceState[Any], _Captured] | None = (
183
+ None if session is None else session.info.get(_FLUSH_CAPTURE_KEY)
184
+ )
185
+ if capture is None:
186
+ return
187
+ keys = _keys_for_flush(state.mapper)
188
+ committed = state.committed_state
189
+ current = state.dict
190
+ expr = {
191
+ key: _MISSING if committed[key] is NO_VALUE else committed[key]
192
+ for key in keys.audited
193
+ if key in committed and _is_sql(current.get(key))
194
+ }
195
+ derived = {
196
+ key: current.get(key, _MISSING) for key in keys.derived if key not in committed
197
+ }
198
+ if expr or derived:
199
+ capture[state] = _Captured(expr, derived)
200
+
201
+
202
+ def _captured(state: InstanceState[Any]) -> _Captured | None:
203
+ session = state.session
204
+ if session is None:
205
+ return None
206
+ capture: dict[InstanceState[Any], _Captured] | None = session.info.get(
207
+ _FLUSH_CAPTURE_KEY
208
+ )
209
+ return None if capture is None else capture.get(state)
210
+
211
+
98
212
  def options_of(model: type[Any]) -> AuditOptions:
99
213
  """Return the model's ``__audit__`` options, or the defaults.
100
214
 
@@ -189,7 +303,14 @@ def entity_changes(
189
303
  - ``updated``: only columns with a net change. Old and new raw values are
190
304
  compared with ``column.type.compare_values`` before any redaction or
191
305
  encoding, so ``Decimal("1.5")`` vs ``Decimal("1.50")`` is no change.
192
- An empty result means there is nothing to record.
306
+ An empty result means there is nothing to record. A column assigned a
307
+ SQL expression (``obj.placed_at = func.now()``) is a change on its
308
+ own. Columns the UPDATE sets without an assignment (``onupdate``,
309
+ ``server_onupdate``, ``Computed``, the mapper's ``version_id_col``)
310
+ are added only next to another column change of their table; an old
311
+ value that is not in memory (a second flush in one transaction) is
312
+ ``"<unknown>"``. Server-side ones only when ``eager_defaults=True``
313
+ fetched the new value back and it differs.
193
314
  - ``deleted``: every audited column as ``[value, None]``.
194
315
 
195
316
  ``exclude`` columns are left out. ``redact`` stores ``"***"`` and
@@ -197,15 +318,27 @@ def entity_changes(
197
318
  goes through ``encode_value``.
198
319
 
199
320
  ``"<unknown>"`` is a marker, not a value: it stands where the value is not
200
- in memory. That is the old value of a JSON column changed in place
201
- (``MutableDict``) without ``snapshot_on_load``, a ``deleted`` column that
202
- is not loaded (for example ``deferred``), and a ``created`` column filled
203
- by a server-side default (``server_default``, ``Computed``, ``Identity``)
204
- that was not fetched back. On PostgreSQL the mapper's default
205
- ``eager_defaults="auto"`` fetches them with ``RETURNING`` on INSERT, so
206
- ``created`` entries hold the real values; only a mapper with
207
- ``eager_defaults=False`` leaves them ``"<unknown>"``. A ``created`` column
208
- that was not set and has no server-side default is ``None``, as stored.
321
+ in memory. A new value of ``"<unknown>"`` means the column was written,
322
+ possibly with its old value. The marker appears for:
323
+
324
+ - the old value of a JSON column changed in place (``MutableDict``)
325
+ without ``snapshot_on_load``;
326
+ - a ``deleted`` column that is not loaded (for example ``deferred``);
327
+ - a ``created`` column filled by a server-side default
328
+ (``server_default``, ``Computed``, ``Identity``) that was not fetched
329
+ back. On PostgreSQL the mapper's default ``eager_defaults="auto"``
330
+ fetches them with ``RETURNING`` on INSERT, so ``created`` entries hold
331
+ the real values; only a mapper with ``eager_defaults=False`` leaves
332
+ them ``"<unknown>"``. The same goes for a client-side SQL default
333
+ (``default=func.now()``);
334
+ - the new value of a column assigned a SQL expression, in ``created`` and
335
+ ``updated``: SQLAlchemy does not fetch it back, whatever
336
+ ``eager_defaults`` says;
337
+ - the new value of a client-side SQL ``onupdate`` (``onupdate=func.now()``)
338
+ unless ``eager_defaults=True``; ``"auto"`` fetches nothing on UPDATE.
339
+
340
+ A ``created`` column that was not set and has no server-side or SQL
341
+ default is ``None``, as stored.
209
342
 
210
343
  Args:
211
344
  obj: A mapped instance.
@@ -242,8 +375,14 @@ def entity_changes(
242
375
  case "created":
243
376
  for spec in columns:
244
377
  new = state.dict.get(spec.key, _MISSING)
245
- if new is _MISSING and spec.column.server_default is None:
246
- # Identity and Computed also live in server_default.
378
+ if (
379
+ new is _MISSING
380
+ and spec.column.server_default is None
381
+ and spec.key not in state.expired_attributes
382
+ ):
383
+ # Identity and Computed also live in server_default. An
384
+ # expired column was written by SQL (a client-side SQL
385
+ # default or an assigned expression) and not fetched.
247
386
  new = None
248
387
  changes[spec.key] = [None, render(new, spec)]
249
388
  case "deleted":
@@ -266,11 +405,61 @@ def entity_changes(
266
405
  if old is not _MISSING and spec.column.type.compare_values(old, new):
267
406
  continue
268
407
  changes[spec.key] = [render(old, spec), render(new, spec)]
408
+ captured = _captured(state)
409
+ if captured is not None:
410
+ _add_captured(state, columns, captured, changes, render)
269
411
  case _:
270
412
  assert_never(kind)
271
413
  return changes
272
414
 
273
415
 
416
+ def _add_captured(
417
+ state: InstanceState[Any],
418
+ columns: Sequence[_AuditedColumn],
419
+ captured: _Captured,
420
+ changes: Changes,
421
+ render: Callable[[object, _AuditedColumn], JSONValue],
422
+ ) -> None:
423
+ # Columns the UPDATE wrote without leaving attribute history: assigned
424
+ # SQL expressions, then (only next to a real change) derived columns.
425
+ by_key = {spec.key: spec for spec in columns}
426
+ current = state.dict
427
+ for key, old in captured.expr.items():
428
+ spec = by_key.get(key)
429
+ if spec is None or key in changes:
430
+ continue
431
+ new = current.get(key, _MISSING)
432
+ if _same(spec, old, new):
433
+ continue
434
+ changes[key] = [render(old, spec), render(new, spec)]
435
+ if not changes:
436
+ return
437
+ server_side = _keys_for_flush(state.mapper).server_side
438
+ # Tables this UPDATE certainly wrote: those of the changed columns. With
439
+ # joined inheritance a child-only change leaves the parent table alone.
440
+ updated = {by_key[key].column.table for key in changes if key in by_key}
441
+ for key, old in captured.derived.items():
442
+ spec = by_key.get(key)
443
+ if spec is None or key in changes:
444
+ continue
445
+ if old is _MISSING and spec.column.table not in updated:
446
+ continue # unknown old value and maybe no write at all
447
+ new = current.get(key, _MISSING)
448
+ if new is _MISSING and key in server_side:
449
+ continue # not fetched back, and may well be unchanged
450
+ if _same(spec, old, new):
451
+ continue
452
+ changes[key] = [render(old, spec), render(new, spec)]
453
+
454
+
455
+ def _same(spec: _AuditedColumn, old: object, new: object) -> bool:
456
+ return (
457
+ old is not _MISSING
458
+ and new is not _MISSING
459
+ and bool(spec.column.type.compare_values(old, new))
460
+ )
461
+
462
+
274
463
  def _render(
275
464
  value: object,
276
465
  policy: _ValuePolicy | None,
@@ -8,8 +8,9 @@ from types import MappingProxyType
8
8
  from typing import TYPE_CHECKING, NamedTuple
9
9
 
10
10
  if TYPE_CHECKING:
11
+ from typing import Self
12
+
11
13
  from pydantic import BaseModel
12
- from typing_extensions import Self
13
14
 
14
15
  from audit_trail.config import AuditOptions
15
16
 
@@ -60,6 +60,7 @@ from sqlalchemy.orm import Session, sessionmaker
60
60
  from audit_trail._compaction import FieldChange
61
61
  from audit_trail.context import AuditContext, ContextSnapshot, resolve_context
62
62
  from audit_trail.diff import (
63
+ _FLUSH_CAPTURE_KEY,
63
64
  USE_CONTEXT,
64
65
  ChangeKind,
65
66
  entity_changes,
@@ -191,7 +192,9 @@ def install(
191
192
  f"installing on {cls.__qualname__} would audit its sessions twice"
192
193
  )
193
194
  listener = _Listener(trail)
195
+ event.listen(cls, "before_flush", _before_flush)
194
196
  event.listen(cls, "after_flush", listener.after_flush)
197
+ event.listen(cls, "after_flush_postexec", _after_flush_postexec)
195
198
  event.listen(cls, "do_orm_execute", listener.do_orm_execute)
196
199
  event.listen(cls, "do_orm_execute", _explain_async_load)
197
200
  event.listen(cls, "after_transaction_end", _after_transaction_end)
@@ -618,11 +621,31 @@ def _cached_row(session: Session, connection: Connection) -> TransactionRow | No
618
621
  return None if cached is None else cached.row
619
622
 
620
623
 
624
+ def _before_flush(
625
+ session: Session, flush_context: UOWTransaction, instances: object
626
+ ) -> None:
627
+ # A fresh capture per flush, filled by Audited's before_update listener
628
+ # and read by entity_changes in after_flush. Without it (another session
629
+ # class, or capture switched off) before_update keeps nothing.
630
+ if session.info.get(AUDIT_ENABLED_KEY) is False:
631
+ session.info.pop(_FLUSH_CAPTURE_KEY, None)
632
+ else:
633
+ session.info[_FLUSH_CAPTURE_KEY] = {}
634
+
635
+
636
+ def _after_flush_postexec(session: Session, flush_context: UOWTransaction) -> None:
637
+ session.info.pop(_FLUSH_CAPTURE_KEY, None)
638
+
639
+
621
640
  def _after_transaction_end(session: Session, transaction: SessionTransaction) -> None:
622
641
  # Fires for every way a transaction ends, including Session.close()
623
642
  # without commit or rollback, which fires no commit or rollback event.
624
643
  # A released savepoint or a flush's subtransaction is not the end of the
625
644
  # database transaction: the rows live on in the enclosing one.
645
+ # A failed flush never reaches after_flush_postexec: drop its capture.
646
+ # A nested end is a host savepoint opened inside the flush: keep it.
647
+ if not transaction.nested:
648
+ session.info.pop(_FLUSH_CAPTURE_KEY, None)
626
649
  if transaction.parent is None:
627
650
  session.info.pop(_CACHE_KEY, None)
628
651
 
@@ -54,7 +54,7 @@ import logging
54
54
  import re
55
55
  from collections.abc import Iterable, Mapping
56
56
  from dataclasses import dataclass
57
- from datetime import date, datetime, timedelta, timezone
57
+ from datetime import UTC, date, datetime, timedelta
58
58
  from typing import TYPE_CHECKING, Literal, NamedTuple, TypeVar
59
59
 
60
60
  from sqlalchemy import Connection, Engine, Table, bindparam, text
@@ -770,7 +770,7 @@ def _oid(conn: Connection, qualified: str) -> int:
770
770
 
771
771
 
772
772
  def _months(now: datetime, months_ahead: int) -> list[date]:
773
- utc = now.astimezone(timezone.utc)
773
+ utc = now.astimezone(UTC)
774
774
  index = utc.year * 12 + utc.month - 1
775
775
  return [
776
776
  date(i // 12, i % 12 + 1, 1) for i in range(index, index + months_ahead + 1)
@@ -42,7 +42,7 @@ whatever the session or server time zone.
42
42
  from __future__ import annotations
43
43
 
44
44
  from collections.abc import Iterable
45
- from datetime import date, datetime, timezone
45
+ from datetime import UTC, date, datetime
46
46
 
47
47
  from sqlalchemy import Connection
48
48
  from sqlalchemy.dialects.postgresql.base import PGDialect
@@ -103,11 +103,11 @@ def month_bounds(month: date) -> tuple[datetime, datetime]:
103
103
  Returns:
104
104
  The first instant of the month and of the next one, both in UTC.
105
105
  """
106
- start = datetime(month.year, month.month, 1, tzinfo=timezone.utc)
106
+ start = datetime(month.year, month.month, 1, tzinfo=UTC)
107
107
  if month.month == 12:
108
- end = datetime(month.year + 1, 1, 1, tzinfo=timezone.utc)
108
+ end = datetime(month.year + 1, 1, 1, tzinfo=UTC)
109
109
  else:
110
- end = datetime(month.year, month.month + 1, 1, tzinfo=timezone.utc)
110
+ end = datetime(month.year, month.month + 1, 1, tzinfo=UTC)
111
111
  return start, end
112
112
 
113
113
 
@@ -306,4 +306,4 @@ def _script(statements: list[str]) -> str:
306
306
 
307
307
  def _timestamptz(value: datetime) -> str:
308
308
  # Explicit +00 offset: the literal means the same instant in any TimeZone.
309
- return f"'{value.astimezone(timezone.utc):%Y-%m-%d %H:%M:%S}+00'"
309
+ return f"'{value.astimezone(UTC):%Y-%m-%d %H:%M:%S}+00'"
@@ -7,7 +7,11 @@ Mixing ``Audited`` into a mapped class, when its mappers are configured:
7
7
  expired attribute loads its old value at assignment time rather than
8
8
  leaving the old value unknown at flush time;
9
9
  - deep-copies the ``snapshot_on_load`` columns whenever the instance is
10
- loaded or refreshed, so an in-place change still has an old value.
10
+ loaded or refreshed, so an in-place change still has an old value;
11
+ - in a flush of an installed session, keeps the old values of columns the
12
+ UPDATE writes without attribute history (assigned SQL expressions,
13
+ ``onupdate``, ``server_onupdate``, the version counter) for
14
+ ``entity_changes``.
11
15
  """
12
16
 
13
17
  from __future__ import annotations
@@ -20,9 +24,15 @@ from sqlalchemy import event
20
24
  from sqlalchemy.orm.attributes import instance_state
21
25
 
22
26
  from audit_trail.config import AuditOptions
23
- from audit_trail.diff import SNAPSHOT_INFO_KEY, _audited_columns, options_of
27
+ from audit_trail.diff import (
28
+ SNAPSHOT_INFO_KEY,
29
+ _audited_columns,
30
+ _capture_before_update,
31
+ options_of,
32
+ )
24
33
 
25
34
  if TYPE_CHECKING:
35
+ from sqlalchemy import Connection
26
36
  from sqlalchemy.orm import AttributeEventToken, InstanceState, Mapper, QueryContext
27
37
 
28
38
 
@@ -92,6 +102,12 @@ def _on_refresh(
92
102
  _take_snapshot(instance_state(target), attrs)
93
103
 
94
104
 
105
+ def _before_update(
106
+ mapper: Mapper[Any], connection: Connection, target: Audited
107
+ ) -> None:
108
+ _capture_before_update(instance_state(target))
109
+
110
+
95
111
  def _keep_old_value(
96
112
  target: object, value: object, oldvalue: object, initiator: AttributeEventToken
97
113
  ) -> None:
@@ -116,3 +132,4 @@ def _on_mapper_configured(mapper: Mapper[_A], cls: type[_A]) -> None:
116
132
  event.listen(Audited, "mapper_configured", _on_mapper_configured, propagate=True)
117
133
  event.listen(Audited, "load", _on_load, propagate=True)
118
134
  event.listen(Audited, "refresh", _on_refresh, propagate=True)
135
+ event.listen(Audited, "before_update", _before_update, propagate=True)
@@ -34,9 +34,9 @@ import binascii
34
34
  import heapq
35
35
  from collections.abc import Collection, Iterable, Iterator, Sequence
36
36
  from dataclasses import dataclass
37
- from datetime import datetime, timedelta, timezone
37
+ from datetime import UTC, datetime, timedelta
38
38
  from enum import Enum
39
- from typing import TYPE_CHECKING, Any, NamedTuple, TypeAlias, TypedDict
39
+ from typing import TYPE_CHECKING, Any, NamedTuple, TypeAlias, TypedDict, assert_never
40
40
  from uuid import UUID
41
41
 
42
42
  from sqlalchemy import (
@@ -58,7 +58,6 @@ from sqlalchemy import (
58
58
  from sqlalchemy.exc import NoReferenceError
59
59
 
60
60
  from audit_trail._compaction import ActivityData, ActivityRow, FieldChange, compact_rows
61
- from audit_trail._typing import assert_never
62
61
  from audit_trail.checks import _registry_of
63
62
  from audit_trail.diff import REDACTED, UNKNOWN, field_policy, options_of
64
63
  from audit_trail.serialization import JSONValue
@@ -1047,7 +1046,7 @@ class AuditQuery:
1047
1046
  case None:
1048
1047
  if window is None:
1049
1048
  return ALL_HISTORY
1050
- return (datetime.now(timezone.utc) if until is None else until) - window
1049
+ return (datetime.now(UTC) if until is None else until) - window
1051
1050
  case _:
1052
1051
  assert_never(since)
1053
1052
 
@@ -18,7 +18,7 @@ from __future__ import annotations
18
18
 
19
19
  from collections.abc import Collection
20
20
  from dataclasses import dataclass
21
- from typing import TYPE_CHECKING, Literal, get_args
21
+ from typing import TYPE_CHECKING, Literal, assert_never, get_args
22
22
 
23
23
  from sqlalchemy import (
24
24
  BigInteger,
@@ -37,8 +37,6 @@ from sqlalchemy import (
37
37
  from sqlalchemy.dialects.postgresql import INET, JSONB, UUID
38
38
  from sqlalchemy.exc import UnboundExecutionError
39
39
 
40
- from audit_trail._typing import assert_never
41
-
42
40
  if TYPE_CHECKING:
43
41
  from sqlalchemy import Connection
44
42
  from sqlalchemy.orm import Session
@@ -15,13 +15,12 @@ once and never through the caller's session.
15
15
 
16
16
  from __future__ import annotations
17
17
 
18
- import asyncio
19
18
  import functools
20
19
  import logging
21
20
  import re
22
21
  from collections.abc import Callable, Mapping, Sequence
23
22
  from datetime import datetime
24
- from typing import TYPE_CHECKING, NamedTuple, TypedDict, TypeVar
23
+ from typing import TYPE_CHECKING, NamedTuple, TypedDict, TypeVar, assert_never
25
24
  from uuid import UUID
26
25
 
27
26
  from sqlalchemy import Connection, Table, insert
@@ -29,7 +28,6 @@ from sqlalchemy.exc import DBAPIError
29
28
  from sqlalchemy.exc import TimeoutError as PoolTimeoutError
30
29
 
31
30
  from audit_trail._compaction import ActivityData
32
- from audit_trail._typing import assert_never
33
31
  from audit_trail.context import AuditContext, ContextSnapshot, context_snapshot
34
32
  from audit_trail.events import PayloadError
35
33
  from audit_trail.maintenance import PartitionError, ensure_partitions
@@ -463,9 +461,7 @@ def async_durable_write_errors() -> tuple[type[Exception], ...]:
463
461
  - ``OSError``: asyncpg, SQLAlchemy 2.0 and 2.1: an unreachable server
464
462
  (``ConnectionRefusedError``), an unresolvable host
465
463
  (``socket.gaierror``), no route to host, TLS failures, and the connect
466
- timeout on Python 3.11+ (``TimeoutError``).
467
- - ``asyncio.TimeoutError``: asyncpg, SQLAlchemy 2.0 on Python 3.10 (2.1
468
- needs 3.11): its connect timeout, which is not an ``OSError`` there.
464
+ timeout (``TimeoutError``; ``asyncio.TimeoutError`` is the same class).
469
465
  - ``asyncpg.PostgresError``: asyncpg, SQLAlchemy 2.0 only: the server
470
466
  refusing the connection (missing database, bad password, too many
471
467
  connections, closed during the handshake); 2.1 wraps it.
@@ -474,8 +470,7 @@ def async_durable_write_errors() -> tuple[type[Exception], ...]:
474
470
  The exception types; ``asyncpg.PostgresError`` only when asyncpg is
475
471
  installed.
476
472
  """
477
- # asyncio.TimeoutError, not TimeoutError: a different class on 3.10.
478
- errors = (*DURABLE_WRITE_ERRORS, OSError, asyncio.TimeoutError)
473
+ errors = (*DURABLE_WRITE_ERRORS, OSError)
479
474
  try:
480
475
  from asyncpg import PostgresError # type: ignore[import-untyped]
481
476
  except ImportError: # asyncpg is an optional driver
@@ -1,10 +1,10 @@
1
1
  [project]
2
2
  name = "sqlalchemy-audit-trail"
3
- version = "0.2.0"
3
+ version = "0.3.0"
4
4
  description = "Audit trail for SQLAlchemy on PostgreSQL: entity change diffs and domain events in one partitioned log"
5
5
  readme = "README.md"
6
6
  license = "MIT"
7
- requires-python = ">=3.10,<4.0"
7
+ requires-python = ">=3.11,<4.0"
8
8
  authors = [{ name = "WiktorB2004" }]
9
9
  keywords = [
10
10
  "sqlalchemy",
@@ -23,7 +23,6 @@ classifiers = [
23
23
  "Programming Language :: Python",
24
24
  "Programming Language :: Python :: 3",
25
25
  "Programming Language :: Python :: 3 :: Only",
26
- "Programming Language :: Python :: 3.10",
27
26
  "Programming Language :: Python :: 3.11",
28
27
  "Programming Language :: Python :: 3.12",
29
28
  "Programming Language :: Python :: 3.13",
@@ -89,11 +88,11 @@ markers = [
89
88
 
90
89
  [tool.ruff.lint]
91
90
  select = ["E", "F", "W", "I", "UP", "B", "SIM", "C4", "PIE", "RUF", "PT", "RET"]
92
- # assert_never for Python 3.10; lets RET503 see it as NoReturn.
93
- typing-modules = ["audit_trail._typing"]
91
+ # StrEnum changes str() and format() of the public AuditEvent members.
92
+ ignore = ["UP042"]
94
93
 
95
94
  [tool.mypy]
96
- python_version = "3.10"
95
+ python_version = "3.11"
97
96
  files = ["audit_trail", "benchmark", "tests"]
98
97
  strict = true
99
98
  warn_unreachable = true
@@ -1,17 +0,0 @@
1
- """Typing helpers shared across modules."""
2
-
3
- from __future__ import annotations
4
-
5
- from typing import NoReturn
6
-
7
-
8
- def assert_never(value: NoReturn) -> NoReturn:
9
- """Mark a branch that exhaustive matching makes unreachable.
10
-
11
- ``typing.assert_never`` needs Python 3.11; this is the 3.10-compatible
12
- equivalent. Type checkers report an error when a value can still reach it.
13
-
14
- Raises:
15
- AssertionError: Always, if reached at runtime.
16
- """
17
- raise AssertionError(f"unhandled value: {value!r}")