sqlalchemy-audit-trail 0.2.0__tar.gz → 0.4.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 (51) hide show
  1. {sqlalchemy_audit_trail-0.2.0 → sqlalchemy_audit_trail-0.4.0}/PKG-INFO +7 -6
  2. {sqlalchemy_audit_trail-0.2.0 → sqlalchemy_audit_trail-0.4.0}/README.md +3 -3
  3. {sqlalchemy_audit_trail-0.2.0 → sqlalchemy_audit_trail-0.4.0}/audit_trail/__init__.py +2 -0
  4. {sqlalchemy_audit_trail-0.2.0 → sqlalchemy_audit_trail-0.4.0}/audit_trail/_compaction.py +1 -2
  5. sqlalchemy_audit_trail-0.4.0/audit_trail/_pg.py +156 -0
  6. {sqlalchemy_audit_trail-0.2.0 → sqlalchemy_audit_trail-0.4.0}/audit_trail/checks.py +1 -2
  7. {sqlalchemy_audit_trail-0.2.0 → sqlalchemy_audit_trail-0.4.0}/audit_trail/config.py +31 -4
  8. {sqlalchemy_audit_trail-0.2.0 → sqlalchemy_audit_trail-0.4.0}/audit_trail/diff.py +203 -14
  9. {sqlalchemy_audit_trail-0.2.0 → sqlalchemy_audit_trail-0.4.0}/audit_trail/events.py +2 -1
  10. sqlalchemy_audit_trail-0.4.0/audit_trail/integrity/__init__.py +136 -0
  11. sqlalchemy_audit_trail-0.4.0/audit_trail/integrity/_anchor.py +685 -0
  12. sqlalchemy_audit_trail-0.4.0/audit_trail/integrity/_block.py +533 -0
  13. sqlalchemy_audit_trail-0.4.0/audit_trail/integrity/_canonical.py +209 -0
  14. sqlalchemy_audit_trail-0.4.0/audit_trail/integrity/_checkpoint.py +178 -0
  15. sqlalchemy_audit_trail-0.4.0/audit_trail/integrity/_codec.py +81 -0
  16. sqlalchemy_audit_trail-0.4.0/audit_trail/integrity/_commit.py +301 -0
  17. sqlalchemy_audit_trail-0.4.0/audit_trail/integrity/_ed25519.py +176 -0
  18. sqlalchemy_audit_trail-0.4.0/audit_trail/integrity/_merkle.py +54 -0
  19. sqlalchemy_audit_trail-0.4.0/audit_trail/integrity/_note.py +248 -0
  20. sqlalchemy_audit_trail-0.4.0/audit_trail/integrity/_options.py +17 -0
  21. sqlalchemy_audit_trail-0.4.0/audit_trail/integrity/_retire.py +558 -0
  22. sqlalchemy_audit_trail-0.4.0/audit_trail/integrity/_schema.py +144 -0
  23. sqlalchemy_audit_trail-0.4.0/audit_trail/integrity/_seal.py +884 -0
  24. sqlalchemy_audit_trail-0.4.0/audit_trail/integrity/_sign.py +181 -0
  25. sqlalchemy_audit_trail-0.4.0/audit_trail/integrity/_types.py +39 -0
  26. sqlalchemy_audit_trail-0.4.0/audit_trail/integrity/_verify.py +1993 -0
  27. sqlalchemy_audit_trail-0.4.0/audit_trail/integrity/_verify_db.py +602 -0
  28. sqlalchemy_audit_trail-0.4.0/audit_trail/integrity/ed25519.py +24 -0
  29. {sqlalchemy_audit_trail-0.2.0 → sqlalchemy_audit_trail-0.4.0}/audit_trail/listener.py +26 -1
  30. {sqlalchemy_audit_trail-0.2.0 → sqlalchemy_audit_trail-0.4.0}/audit_trail/maintenance.py +725 -72
  31. sqlalchemy_audit_trail-0.4.0/audit_trail/migrations.py +702 -0
  32. {sqlalchemy_audit_trail-0.2.0 → sqlalchemy_audit_trail-0.4.0}/audit_trail/mixin.py +19 -2
  33. {sqlalchemy_audit_trail-0.2.0 → sqlalchemy_audit_trail-0.4.0}/audit_trail/privacy.py +109 -12
  34. {sqlalchemy_audit_trail-0.2.0 → sqlalchemy_audit_trail-0.4.0}/audit_trail/query.py +43 -9
  35. {sqlalchemy_audit_trail-0.2.0 → sqlalchemy_audit_trail-0.4.0}/audit_trail/tables.py +38 -3
  36. {sqlalchemy_audit_trail-0.2.0 → sqlalchemy_audit_trail-0.4.0}/audit_trail/testing.py +12 -2
  37. {sqlalchemy_audit_trail-0.2.0 → sqlalchemy_audit_trail-0.4.0}/audit_trail/writer.py +142 -36
  38. {sqlalchemy_audit_trail-0.2.0 → sqlalchemy_audit_trail-0.4.0}/pyproject.toml +8 -6
  39. sqlalchemy_audit_trail-0.2.0/audit_trail/_typing.py +0 -17
  40. sqlalchemy_audit_trail-0.2.0/audit_trail/migrations.py +0 -309
  41. {sqlalchemy_audit_trail-0.2.0 → sqlalchemy_audit_trail-0.4.0}/.gitignore +0 -0
  42. {sqlalchemy_audit_trail-0.2.0 → sqlalchemy_audit_trail-0.4.0}/LICENSE +0 -0
  43. {sqlalchemy_audit_trail-0.2.0 → sqlalchemy_audit_trail-0.4.0}/audit_trail/context.py +0 -0
  44. {sqlalchemy_audit_trail-0.2.0 → sqlalchemy_audit_trail-0.4.0}/audit_trail/integrations/__init__.py +0 -0
  45. {sqlalchemy_audit_trail-0.2.0 → sqlalchemy_audit_trail-0.4.0}/audit_trail/integrations/fastapi.py +0 -0
  46. {sqlalchemy_audit_trail-0.2.0 → sqlalchemy_audit_trail-0.4.0}/audit_trail/py.typed +0 -0
  47. {sqlalchemy_audit_trail-0.2.0 → sqlalchemy_audit_trail-0.4.0}/audit_trail/pytest_plugin.py +0 -0
  48. {sqlalchemy_audit_trail-0.2.0 → sqlalchemy_audit_trail-0.4.0}/audit_trail/relations.py +0 -0
  49. {sqlalchemy_audit_trail-0.2.0 → sqlalchemy_audit_trail-0.4.0}/audit_trail/serialization.py +0 -0
  50. {sqlalchemy_audit_trail-0.2.0 → sqlalchemy_audit_trail-0.4.0}/benchmark/README.md +0 -0
  51. {sqlalchemy_audit_trail-0.2.0 → sqlalchemy_audit_trail-0.4.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.4.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'
@@ -34,6 +33,8 @@ Requires-Dist: asyncpg>=0.29; extra == 'asyncpg'
34
33
  Requires-Dist: sqlalchemy[asyncio]<2.2,>=2.0; extra == 'asyncpg'
35
34
  Provides-Extra: fastapi
36
35
  Requires-Dist: fastapi>=0.110; extra == 'fastapi'
36
+ Provides-Extra: integrity
37
+ Requires-Dist: cryptography>=42; extra == 'integrity'
37
38
  Provides-Extra: psycopg
38
39
  Requires-Dist: psycopg[binary]>=3.1; extra == 'psycopg'
39
40
  Provides-Extra: pydantic
@@ -45,7 +46,7 @@ Description-Content-Type: text/markdown
45
46
  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
47
 
47
48
  [![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/)
49
+ [![Python 3.11+](https://img.shields.io/badge/python-3.11%2B-blue)](https://pypi.org/project/sqlalchemy-audit-trail/)
49
50
  [![Docs](https://img.shields.io/badge/docs-GitHub%20Pages-blue)](https://wiktorb2004.github.io/sqlalchemy-audit-trail/)
50
51
  [![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
52
  [![License: MIT](https://img.shields.io/github/license/WiktorB2004/sqlalchemy-audit-trail)](LICENSE)
@@ -61,7 +62,7 @@ pip install "sqlalchemy-audit-trail[asyncpg]" # AsyncSession on asyncpg
61
62
  # more extras: asyncio, pydantic (payload schemas), fastapi
62
63
  ```
63
64
 
64
- Requires Python 3.10+, SQLAlchemy 2.0 or 2.1, and PostgreSQL 14+.
65
+ Requires Python 3.11+, SQLAlchemy 2.0 or 2.1, and PostgreSQL 14+.
65
66
 
66
67
  ## Quickstart
67
68
 
@@ -192,7 +193,7 @@ AUDIT_TEST_PG_IMAGE=postgres:14 uv run pytest # oldest supported PostgreSQL
192
193
  uv run ruff check . && uv run mypy
193
194
  ```
194
195
 
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.
196
+ 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
197
 
197
198
  ## Docs
198
199
 
@@ -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
 
@@ -7,6 +7,7 @@ from audit_trail.config import AuditOptions, AuditTrail, Target
7
7
  from audit_trail.context import Actor, AuditContext
8
8
  from audit_trail.diff import AuditOptionError, FieldPolicyError
9
9
  from audit_trail.events import AuditEvent, Severity, event
10
+ from audit_trail.integrity import Integrity
10
11
  from audit_trail.listener import AsyncLoadError
11
12
  from audit_trail.mixin import Audited
12
13
  from audit_trail.privacy import ScrubNotAllowedError, ScrubResult
@@ -54,6 +55,7 @@ __all__ = [
54
55
  "FieldLabels",
55
56
  "FieldPolicyError",
56
57
  "Group",
58
+ "Integrity",
57
59
  "LabelResolver",
58
60
  "ModelIssue",
59
61
  "Page",
@@ -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
@@ -0,0 +1,156 @@
1
+ """Small PostgreSQL helpers shared by the modules that talk to the database."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Iterator
6
+ from contextlib import contextmanager
7
+ from typing import TYPE_CHECKING
8
+
9
+ from sqlalchemy import text
10
+
11
+ if TYPE_CHECKING:
12
+ from sqlalchemy import Connection, Table
13
+ from sqlalchemy.exc import DBAPIError
14
+
15
+ UNIQUE_VIOLATION = "23505"
16
+ """SQLSTATE of an insert that repeats a primary or unique key."""
17
+
18
+ CHECK_VIOLATION = "23514"
19
+ """SQLSTATE of a row that fits no partition (and of other CHECK violations)."""
20
+
21
+ UNDEFINED_COLUMN = "42703"
22
+ """SQLSTATE of a statement naming a column the table lacks."""
23
+
24
+ UNDEFINED_TABLE = "42P01"
25
+ """SQLSTATE of a statement naming a relation that does not exist."""
26
+
27
+ LOCK_NOT_AVAILABLE = "55P03"
28
+ """SQLSTATE raised when ``lock_timeout`` expires."""
29
+
30
+ OBJECT_NOT_IN_PREREQUISITE_STATE = "55000"
31
+ """SQLSTATE of a ``DETACH`` while a detach from the same parent is pending."""
32
+
33
+
34
+ XACT_LOCK = "pg_advisory_xact_lock(hashtext(:key))"
35
+ """SQL that waits for the transaction-level advisory lock named by ``:key``."""
36
+
37
+ TRY_XACT_LOCK = "pg_try_advisory_xact_lock(hashtext(:key))"
38
+ """SQL that tries the transaction-level advisory lock named by ``:key``."""
39
+
40
+ SUBSCRIBED = (
41
+ "EXISTS (SELECT FROM pg_catalog.pg_subscription_rel "
42
+ "WHERE srrelid = to_regclass(:table))"
43
+ )
44
+ """SQL that is true when a logical-replication subscription of this database
45
+ writes into the table named by ``:table``, in any state, enabled or not.
46
+ Every role can read ``pg_subscription_rel``."""
47
+
48
+
49
+ def sqlstate(exc: DBAPIError) -> str | None:
50
+ """The SQLSTATE of a database error, or ``None`` when the driver gives none.
51
+
52
+ psycopg 3 names it ``sqlstate``, psycopg2 ``pgcode``.
53
+ """
54
+ orig = exc.orig
55
+ code: str | None = getattr(orig, "sqlstate", None) or getattr(orig, "pgcode", None)
56
+ return code
57
+
58
+
59
+ def is_sqlstate(exc: DBAPIError, code: str) -> bool:
60
+ """Tell whether a database error has the SQLSTATE ``code``."""
61
+ return sqlstate(exc) == code
62
+
63
+
64
+ def check_transactional(connection: Connection, name: str) -> None:
65
+ """Refuse a connection in ``AUTOCOMMIT`` mode.
66
+
67
+ Raises:
68
+ ValueError: It is; the message names the caller, ``name``.
69
+ """
70
+ dbapi = connection.connection.dbapi_connection
71
+ if getattr(dbapi, "autocommit", False):
72
+ raise ValueError(f"{name} needs a transaction, not AUTOCOMMIT")
73
+
74
+
75
+ def set_config(connection: Connection, name: str, value: str, *, local: bool) -> str:
76
+ """Set a setting for the transaction or the session; return the old value.
77
+
78
+ Args:
79
+ connection: Connection to set it on.
80
+ name: The setting, e.g. ``lock_timeout``.
81
+ value: Its new value.
82
+ local: Set it for the rest of the transaction only, as ``SET LOCAL``.
83
+ """
84
+ previous: str = connection.execute(
85
+ text("SELECT current_setting(:name)"), {"name": name}
86
+ ).scalar_one()
87
+ connection.execute(
88
+ text("SELECT set_config(:name, :value, :local)"),
89
+ {"name": name, "value": value, "local": local},
90
+ )
91
+ return previous
92
+
93
+
94
+ def execute_ddl(connection: Connection, statement: str) -> None:
95
+ """Execute one DDL statement built by this library as-is.
96
+
97
+ The statement goes to the driver without parameters, so ``%`` and ``:``
98
+ inside quoted names are not taken for placeholders.
99
+
100
+ Args:
101
+ connection: Connection to run on.
102
+ statement: A statement built by this library.
103
+ """
104
+ connection.exec_driver_sql(statement, execution_options={"no_parameters": True})
105
+
106
+
107
+ def lock_key(block: Table) -> str:
108
+ """Key of the advisory lock that lets one writer of a seal chain run at a time."""
109
+ return f"audit_trail.seal:{block.schema}.{block.name}"
110
+
111
+
112
+ @contextmanager
113
+ def read_only(conn: Connection) -> Iterator[Connection]:
114
+ """A short ``READ ONLY`` transaction on a connection."""
115
+ transaction = conn.begin()
116
+ try:
117
+ conn.execute(text("SET TRANSACTION READ ONLY"))
118
+ yield conn
119
+ finally:
120
+ # Nothing was written; ending it either way releases the snapshot.
121
+ transaction.rollback()
122
+
123
+
124
+ def regclass(connection: Connection, table: Table) -> str:
125
+ """The quoted, schema-qualified name of a table, as ``to_regclass`` takes it."""
126
+ return connection.dialect.identifier_preparer.format_table(table)
127
+
128
+
129
+ def xact_lock(connection: Connection, key: str) -> None:
130
+ """Wait for an advisory lock held until the transaction ends."""
131
+ connection.execute(text(f"SELECT {XACT_LOCK}"), {"key": key})
132
+
133
+
134
+ def session_lock(connection: Connection, key: str) -> int:
135
+ """Wait for an advisory lock held until ``session_unlock`` or disconnect.
136
+
137
+ Returns the ``pg_backend_pid()`` of the backend that took it, which the
138
+ caller compares with its own to tell whether a pooler moved it.
139
+ """
140
+ pid: int = connection.execute(
141
+ text("SELECT pg_backend_pid() FROM pg_advisory_lock(hashtext(:key))"),
142
+ {"key": key},
143
+ ).scalar_one()
144
+ return pid
145
+
146
+
147
+ def session_unlock(connection: Connection, key: str) -> tuple[bool, int]:
148
+ """Release a lock taken by ``session_lock``.
149
+
150
+ Returns whether this backend held the lock, and its ``pg_backend_pid()``.
151
+ """
152
+ unlocked, pid = connection.execute(
153
+ text("SELECT pg_advisory_unlock(hashtext(:key)), pg_backend_pid()"),
154
+ {"key": key},
155
+ ).one()
156
+ return bool(unlocked), int(pid)
@@ -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
@@ -36,6 +36,7 @@ if TYPE_CHECKING:
36
36
  from sqlalchemy.ext.asyncio import AsyncEngine, AsyncSession, async_sessionmaker
37
37
  from sqlalchemy.orm import Session, sessionmaker
38
38
 
39
+ from audit_trail.integrity._options import Integrity
39
40
  from audit_trail.privacy import ScrubbedRecord, ScrubResult
40
41
  from audit_trail.writer import Entry, TransactionValues
41
42
 
@@ -156,6 +157,13 @@ class AuditTrail:
156
157
  it is not given ``since``, for example ``timedelta(days=30)``;
157
158
  ``since=ALL_HISTORY`` still lists the whole log. ``None`` reads
158
159
  the whole log, which gets slower as it grows.
160
+ integrity: Tamper-evidence settings of this writer, or ``None`` (the
161
+ default) to leave the audit tables as they are. With
162
+ ``Integrity()`` the tables declare the integrity columns, which
163
+ ``migrations.add_integrity`` adds to an existing install, and
164
+ every write stores commitments; once the chain is started, every
165
+ process that writes audit entries needs it. See the integrity
166
+ guide.
159
167
 
160
168
  Attributes:
161
169
  severities: The severity enum in use.
@@ -201,6 +209,7 @@ class AuditTrail:
201
209
  auto_create_partitions: bool = False,
202
210
  allow_scrub: bool = False,
203
211
  default_query_window: timedelta | None = None,
212
+ integrity: Integrity | None = None,
204
213
  ) -> None:
205
214
  self.engine = engine
206
215
  self.schema = schema
@@ -228,8 +237,16 @@ class AuditTrail:
228
237
  self.auto_create_partitions = auto_create_partitions
229
238
  self.allow_scrub = allow_scrub
230
239
  self.keys = None if pseudonymize_key is None else KeyRing(pseudonymize_key)
231
- self.tables = build_tables(schema=schema, indexes=indexes)
232
- self.maintenance = PartitionManager(engine, self.tables, self.severities)
240
+ self.integrity = integrity
241
+ self.tables = build_tables(
242
+ schema=schema, indexes=indexes, integrity=integrity is not None
243
+ )
244
+ self.maintenance = PartitionManager(
245
+ engine,
246
+ self.tables,
247
+ self.severities,
248
+ system_severity=self.registry.system_severity,
249
+ )
233
250
  from audit_trail.query import AuditQuery
234
251
 
235
252
  self.query = AuditQuery(
@@ -474,7 +491,12 @@ class AuditTrail:
474
491
  auto_create_partitions=self.auto_create_partitions,
475
492
  )
476
493
  except DURABLE_WRITE_ERRORS as exc:
477
- handle_durable_failure(exc, self.on_error, entry.flags.fail_closed)
494
+ handle_durable_failure(
495
+ exc,
496
+ self.on_error,
497
+ entry.flags.fail_closed,
498
+ integrity=self.integrity is not None,
499
+ )
478
500
 
479
501
  @overload
480
502
  async def alog(
@@ -594,7 +616,12 @@ class AuditTrail:
594
616
  auto_create_partitions=self.auto_create_partitions,
595
617
  )
596
618
  except async_durable_write_errors() as exc:
597
- handle_durable_failure(exc, self.on_error, entry.flags.fail_closed)
619
+ handle_durable_failure(
620
+ exc,
621
+ self.on_error,
622
+ entry.flags.fail_closed,
623
+ integrity=self.integrity is not None,
624
+ )
598
625
 
599
626
  def scrub(
600
627
  self,
@@ -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