sqlalchemy-audit-trail 0.1.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 (28) hide show
  1. sqlalchemy_audit_trail-0.1.0/.gitignore +23 -0
  2. sqlalchemy_audit_trail-0.1.0/LICENSE +21 -0
  3. sqlalchemy_audit_trail-0.1.0/PKG-INFO +200 -0
  4. sqlalchemy_audit_trail-0.1.0/README.md +158 -0
  5. sqlalchemy_audit_trail-0.1.0/audit_trail/__init__.py +67 -0
  6. sqlalchemy_audit_trail-0.1.0/audit_trail/_compaction.py +297 -0
  7. sqlalchemy_audit_trail-0.1.0/audit_trail/_typing.py +17 -0
  8. sqlalchemy_audit_trail-0.1.0/audit_trail/checks.py +303 -0
  9. sqlalchemy_audit_trail-0.1.0/audit_trail/config.py +950 -0
  10. sqlalchemy_audit_trail-0.1.0/audit_trail/context.py +375 -0
  11. sqlalchemy_audit_trail-0.1.0/audit_trail/diff.py +619 -0
  12. sqlalchemy_audit_trail-0.1.0/audit_trail/events.py +441 -0
  13. sqlalchemy_audit_trail-0.1.0/audit_trail/integrations/__init__.py +1 -0
  14. sqlalchemy_audit_trail-0.1.0/audit_trail/integrations/fastapi.py +378 -0
  15. sqlalchemy_audit_trail-0.1.0/audit_trail/listener.py +655 -0
  16. sqlalchemy_audit_trail-0.1.0/audit_trail/maintenance.py +1028 -0
  17. sqlalchemy_audit_trail-0.1.0/audit_trail/migrations.py +309 -0
  18. sqlalchemy_audit_trail-0.1.0/audit_trail/mixin.py +118 -0
  19. sqlalchemy_audit_trail-0.1.0/audit_trail/privacy.py +410 -0
  20. sqlalchemy_audit_trail-0.1.0/audit_trail/py.typed +0 -0
  21. sqlalchemy_audit_trail-0.1.0/audit_trail/pytest_plugin.py +94 -0
  22. sqlalchemy_audit_trail-0.1.0/audit_trail/query.py +1616 -0
  23. sqlalchemy_audit_trail-0.1.0/audit_trail/relations.py +222 -0
  24. sqlalchemy_audit_trail-0.1.0/audit_trail/serialization.py +400 -0
  25. sqlalchemy_audit_trail-0.1.0/audit_trail/tables.py +264 -0
  26. sqlalchemy_audit_trail-0.1.0/audit_trail/testing.py +589 -0
  27. sqlalchemy_audit_trail-0.1.0/audit_trail/writer.py +485 -0
  28. sqlalchemy_audit_trail-0.1.0/pyproject.toml +104 -0
@@ -0,0 +1,23 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ *$py.class
4
+ *.egg-info/
5
+ .eggs/
6
+ dist/
7
+ build/
8
+ .venv/
9
+ venv/
10
+ .env
11
+ .env.*
12
+ .pytest_cache/
13
+ .mypy_cache/
14
+ .ruff_cache/
15
+ .coverage
16
+ htmlcov/
17
+ .idea/
18
+ .vscode/
19
+ *.swp
20
+ .DS_Store
21
+ /site
22
+ benchmark/results/*
23
+ !benchmark/results/.gitkeep
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 WiktorB2004
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,200 @@
1
+ Metadata-Version: 2.5
2
+ Name: sqlalchemy-audit-trail
3
+ Version: 0.1.0
4
+ Summary: Audit trail for SQLAlchemy on PostgreSQL: entity change diffs and domain events in one partitioned log
5
+ Project-URL: Homepage, https://github.com/WiktorB2004/sqlalchemy-audit-trail
6
+ Project-URL: Repository, https://github.com/WiktorB2004/sqlalchemy-audit-trail
7
+ Project-URL: Issues, https://github.com/WiktorB2004/sqlalchemy-audit-trail/issues
8
+ Project-URL: Documentation, https://wiktorb2004.github.io/sqlalchemy-audit-trail/
9
+ Project-URL: Changelog, https://github.com/WiktorB2004/sqlalchemy-audit-trail/blob/main/CHANGELOG.md
10
+ Author: WiktorB2004
11
+ License-Expression: MIT
12
+ License-File: LICENSE
13
+ Keywords: audit,audit-log,audit-trail,gdpr,history,postgresql,sqlalchemy
14
+ Classifier: Development Status :: 3 - Alpha
15
+ Classifier: Framework :: FastAPI
16
+ Classifier: Intended Audience :: Developers
17
+ Classifier: License :: OSI Approved :: MIT License
18
+ Classifier: Operating System :: OS Independent
19
+ Classifier: Programming Language :: Python
20
+ Classifier: Programming Language :: Python :: 3
21
+ Classifier: Programming Language :: Python :: 3 :: Only
22
+ Classifier: Programming Language :: Python :: 3.10
23
+ Classifier: Programming Language :: Python :: 3.11
24
+ Classifier: Programming Language :: Python :: 3.12
25
+ Classifier: Programming Language :: Python :: 3.13
26
+ Classifier: Topic :: Database
27
+ Classifier: Typing :: Typed
28
+ Requires-Python: <4.0,>=3.10
29
+ Requires-Dist: sqlalchemy<2.2,>=2.0
30
+ Provides-Extra: asyncio
31
+ Requires-Dist: sqlalchemy[asyncio]<2.2,>=2.0; extra == 'asyncio'
32
+ Provides-Extra: asyncpg
33
+ Requires-Dist: asyncpg>=0.29; extra == 'asyncpg'
34
+ Requires-Dist: sqlalchemy[asyncio]<2.2,>=2.0; extra == 'asyncpg'
35
+ Provides-Extra: fastapi
36
+ Requires-Dist: fastapi>=0.110; extra == 'fastapi'
37
+ Provides-Extra: psycopg
38
+ Requires-Dist: psycopg[binary]>=3.1; extra == 'psycopg'
39
+ Provides-Extra: pydantic
40
+ Requires-Dist: pydantic>=2; extra == 'pydantic'
41
+ Description-Content-Type: text/markdown
42
+
43
+ # sqlalchemy-audit-trail
44
+
45
+ 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
+ [![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
+ [![Docs](https://img.shields.io/badge/docs-GitHub%20Pages-blue)](https://wiktorb2004.github.io/sqlalchemy-audit-trail/)
50
+ [![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
+ [![License: MIT](https://img.shields.io/github/license/WiktorB2004/sqlalchemy-audit-trail)](LICENSE)
52
+ [![Downloads](https://img.shields.io/pypi/dm/sqlalchemy-audit-trail)](https://pypi.org/project/sqlalchemy-audit-trail/)
53
+
54
+ > **Alpha.** The API may change before 1.0.
55
+
56
+ ## Install
57
+
58
+ ```bash
59
+ pip install "sqlalchemy-audit-trail[psycopg]" # Session on psycopg 3
60
+ pip install "sqlalchemy-audit-trail[asyncpg]" # AsyncSession on asyncpg
61
+ # more extras: asyncio, pydantic (payload schemas), fastapi
62
+ ```
63
+
64
+ Requires Python 3.10+, SQLAlchemy 2.0 or 2.1, and PostgreSQL 14+.
65
+
66
+ ## Quickstart
67
+
68
+ **Entity changes**: mark a model `Audited`, install the listener, and every flush records `entity.created` / `entity.updated` / `entity.deleted` with `{"field": [old, new]}` diffs:
69
+
70
+ ```python
71
+ from sqlalchemy import create_engine
72
+ from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, sessionmaker
73
+
74
+ from audit_trail import Audited, AuditOptions, AuditTrail
75
+ from audit_trail.migrations import create_audit_tables
76
+
77
+
78
+ class Base(DeclarativeBase):
79
+ pass
80
+
81
+
82
+ class Invoice(Base, Audited):
83
+ __tablename__ = "invoice"
84
+
85
+ id: Mapped[int] = mapped_column(primary_key=True)
86
+ status: Mapped[str] = mapped_column(default="draft")
87
+ payment_token: Mapped[str | None] = mapped_column(info={"audit": "redact"})
88
+
89
+ __audit__ = AuditOptions(label=lambda invoice: f"Invoice {invoice.id}")
90
+
91
+
92
+ engine = create_engine("postgresql+psycopg://localhost/app")
93
+ audit = AuditTrail(engine, events=[])
94
+ SessionLocal = sessionmaker(engine)
95
+ audit.install(SessionLocal)
96
+
97
+ with engine.begin() as connection: # in a migration, in a real application
98
+ Base.metadata.create_all(connection)
99
+ create_audit_tables(connection, audit.tables, audit.severities)
100
+ audit.maintenance.ensure_partitions() # and on a schedule
101
+
102
+ with audit.context(actor_type="user", actor_id="42", actor_label="ada@example.com"):
103
+ with SessionLocal() as session:
104
+ invoice = Invoice()
105
+ session.add(invoice)
106
+ session.commit()
107
+ invoice.status = "sent"
108
+ session.commit()
109
+
110
+ with SessionLocal() as session:
111
+ for group in audit.query.object_history(session, "Invoice", "1").groups:
112
+ for activity in group.activities:
113
+ print(activity["verb"], activity["data"]["changes"])
114
+ # entity.updated {'status': ['draft', 'sent']}
115
+ # entity.created {'id': [None, 1], 'status': [None, 'draft'], 'payment_token': [None, None]}
116
+ ```
117
+
118
+ **Domain events**: declare what else is worth auditing once, with a severity, then log it:
119
+
120
+ ```python
121
+ from audit_trail import AuditEvent, Severity, event
122
+
123
+
124
+ class AuthEvent(AuditEvent):
125
+ LOGIN = event("auth.login", Severity.INFO)
126
+ LOGIN_FAILED = event("auth.login_failed", Severity.WARNING, durable=True)
127
+
128
+
129
+ audit = AuditTrail(engine, events=[AuthEvent])
130
+ audit.log(session, AuthEvent.LOGIN_FAILED, payload={"reason": "bad password"})
131
+ ```
132
+
133
+ Docs: [wiktorb2004.github.io/sqlalchemy-audit-trail](https://wiktorb2004.github.io/sqlalchemy-audit-trail/). Runnable, tested quickstarts for sync, async and FastAPI: [`examples/`](examples/).
134
+
135
+ Audit rows are written **in your transaction**: roll back and they are gone with the change. A failed audit write does not fail your transaction by default (`on_error="log"`). `durable` events are committed on their own connection and survive a rollback; `fail_closed` events raise `AuditWriteError` when they cannot be written.
136
+
137
+ ## Why this instead of sqlalchemy-continuum, triggers or pgaudit
138
+
139
+ [sqlalchemy-continuum](https://github.com/kvesteri/sqlalchemy-continuum) copies every changed row into a version table per model. That answers "what did this row look like then", but a login, a download or someone viewing sensitive data has no row to version. Database triggers and pgaudit see statements, not the application's user, request or intent.
140
+
141
+ This library stores what changed as diffs, next to the domain events you declare and the request context (actor, IP, user agent, path, channel), in one log you can list chronologically, per object or per actor. The trade-off: there is no revert and no state at a point in time. See [migrating from continuum](https://wiktorb2004.github.io/sqlalchemy-audit-trail/migrating-from-continuum/) and [limitations](https://wiktorb2004.github.io/sqlalchemy-audit-trail/limitations/).
142
+
143
+ ## Design
144
+
145
+ ### One partitioned log
146
+
147
+ Two tables: `audit_transaction` (who, where and how, once per database transaction) and `audit_activity` (one row per object and flush, or per event). Both are partitioned by severity, then by month, so retention drops whole partitions per severity and reads touch only the partitions they need. There is no default partition: schedule `ensure_partitions()` (see [operations](https://wiktorb2004.github.io/sqlalchemy-audit-trail/guides/operations/)).
148
+
149
+ ### In your transaction, unless you say otherwise
150
+
151
+ | Kind | Written | When the audit write fails |
152
+ | --- | --- | --- |
153
+ | entity change, plain event | in your transaction | `on_error="log"`: logged, your transaction goes on; `"raise"`: propagates |
154
+ | `durable` event | on its own connection, committed before `log()` returns | as `on_error` |
155
+ | `fail_closed` event | on its own connection, committed before `log()` returns | always raises `AuditWriteError` |
156
+
157
+ ### Privacy by default, erasure on request
158
+
159
+ Per-column `exclude`, `redact` and `hash` policies, `Pseudonymized` payload fields with versioned keys, and `scrub()` / `scrub_actor()` to erase an object's values or an actor's personal context, each recorded as an `audit.scrubbed` entry. See [privacy](https://wiktorb2004.github.io/sqlalchemy-audit-trail/guides/privacy/).
160
+
161
+ ### Reads fail closed
162
+
163
+ `list_groups()` lists entries grouped by transaction, with keyset pagination. `Visibility` restrictions fail closed: `None` means no restriction, an empty set allows nothing, and a `NULL` column never passes a restriction that is set.
164
+
165
+ ### Sync, async and FastAPI
166
+
167
+ `Session` and `AsyncSession` on psycopg 3 or asyncpg. `audit_trail.integrations.fastapi` adds ASGI middleware for the request context (the client IP is read from `X-Forwarded-For` only behind trusted proxies), a session dependency, and `set_actor()` for after authentication.
168
+
169
+ ## Tests
170
+
171
+ Tests under `tests/db` run against a real PostgreSQL. With Docker running, a throwaway `postgres:18` container is started with testcontainers.
172
+
173
+ ```bash
174
+ uv sync --frozen
175
+
176
+ uv run pytest tests/unit # no database needed
177
+ uv run pytest # everything, needs Docker
178
+ AUDIT_TEST_PG_IMAGE=postgres:14 uv run pytest # oldest supported PostgreSQL
179
+
180
+ uv run ruff check . && uv run mypy
181
+ ```
182
+
183
+ 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.
184
+
185
+ ## Docs
186
+
187
+ ```bash
188
+ uv sync --group docs
189
+ uv run mkdocs serve
190
+ ```
191
+
192
+ Published at [wiktorb2004.github.io/sqlalchemy-audit-trail](https://wiktorb2004.github.io/sqlalchemy-audit-trail/).
193
+
194
+ ## Contributing
195
+
196
+ Issues and pull requests are welcome. See [CONTRIBUTING.md](CONTRIBUTING.md) and the [Code of Conduct](CODE_OF_CONDUCT.md). To report a vulnerability, use [SECURITY.md](SECURITY.md).
197
+
198
+ ## License
199
+
200
+ MIT. See [LICENSE](LICENSE). Changelog: [CHANGELOG.md](CHANGELOG.md). Cite this repo with [CITATION.cff](CITATION.cff).
@@ -0,0 +1,158 @@
1
+ # sqlalchemy-audit-trail
2
+
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
+
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/)
7
+ [![Docs](https://img.shields.io/badge/docs-GitHub%20Pages-blue)](https://wiktorb2004.github.io/sqlalchemy-audit-trail/)
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
+ [![License: MIT](https://img.shields.io/github/license/WiktorB2004/sqlalchemy-audit-trail)](LICENSE)
10
+ [![Downloads](https://img.shields.io/pypi/dm/sqlalchemy-audit-trail)](https://pypi.org/project/sqlalchemy-audit-trail/)
11
+
12
+ > **Alpha.** The API may change before 1.0.
13
+
14
+ ## Install
15
+
16
+ ```bash
17
+ pip install "sqlalchemy-audit-trail[psycopg]" # Session on psycopg 3
18
+ pip install "sqlalchemy-audit-trail[asyncpg]" # AsyncSession on asyncpg
19
+ # more extras: asyncio, pydantic (payload schemas), fastapi
20
+ ```
21
+
22
+ Requires Python 3.10+, SQLAlchemy 2.0 or 2.1, and PostgreSQL 14+.
23
+
24
+ ## Quickstart
25
+
26
+ **Entity changes**: mark a model `Audited`, install the listener, and every flush records `entity.created` / `entity.updated` / `entity.deleted` with `{"field": [old, new]}` diffs:
27
+
28
+ ```python
29
+ from sqlalchemy import create_engine
30
+ from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, sessionmaker
31
+
32
+ from audit_trail import Audited, AuditOptions, AuditTrail
33
+ from audit_trail.migrations import create_audit_tables
34
+
35
+
36
+ class Base(DeclarativeBase):
37
+ pass
38
+
39
+
40
+ class Invoice(Base, Audited):
41
+ __tablename__ = "invoice"
42
+
43
+ id: Mapped[int] = mapped_column(primary_key=True)
44
+ status: Mapped[str] = mapped_column(default="draft")
45
+ payment_token: Mapped[str | None] = mapped_column(info={"audit": "redact"})
46
+
47
+ __audit__ = AuditOptions(label=lambda invoice: f"Invoice {invoice.id}")
48
+
49
+
50
+ engine = create_engine("postgresql+psycopg://localhost/app")
51
+ audit = AuditTrail(engine, events=[])
52
+ SessionLocal = sessionmaker(engine)
53
+ audit.install(SessionLocal)
54
+
55
+ with engine.begin() as connection: # in a migration, in a real application
56
+ Base.metadata.create_all(connection)
57
+ create_audit_tables(connection, audit.tables, audit.severities)
58
+ audit.maintenance.ensure_partitions() # and on a schedule
59
+
60
+ with audit.context(actor_type="user", actor_id="42", actor_label="ada@example.com"):
61
+ with SessionLocal() as session:
62
+ invoice = Invoice()
63
+ session.add(invoice)
64
+ session.commit()
65
+ invoice.status = "sent"
66
+ session.commit()
67
+
68
+ with SessionLocal() as session:
69
+ for group in audit.query.object_history(session, "Invoice", "1").groups:
70
+ for activity in group.activities:
71
+ print(activity["verb"], activity["data"]["changes"])
72
+ # entity.updated {'status': ['draft', 'sent']}
73
+ # entity.created {'id': [None, 1], 'status': [None, 'draft'], 'payment_token': [None, None]}
74
+ ```
75
+
76
+ **Domain events**: declare what else is worth auditing once, with a severity, then log it:
77
+
78
+ ```python
79
+ from audit_trail import AuditEvent, Severity, event
80
+
81
+
82
+ class AuthEvent(AuditEvent):
83
+ LOGIN = event("auth.login", Severity.INFO)
84
+ LOGIN_FAILED = event("auth.login_failed", Severity.WARNING, durable=True)
85
+
86
+
87
+ audit = AuditTrail(engine, events=[AuthEvent])
88
+ audit.log(session, AuthEvent.LOGIN_FAILED, payload={"reason": "bad password"})
89
+ ```
90
+
91
+ Docs: [wiktorb2004.github.io/sqlalchemy-audit-trail](https://wiktorb2004.github.io/sqlalchemy-audit-trail/). Runnable, tested quickstarts for sync, async and FastAPI: [`examples/`](examples/).
92
+
93
+ Audit rows are written **in your transaction**: roll back and they are gone with the change. A failed audit write does not fail your transaction by default (`on_error="log"`). `durable` events are committed on their own connection and survive a rollback; `fail_closed` events raise `AuditWriteError` when they cannot be written.
94
+
95
+ ## Why this instead of sqlalchemy-continuum, triggers or pgaudit
96
+
97
+ [sqlalchemy-continuum](https://github.com/kvesteri/sqlalchemy-continuum) copies every changed row into a version table per model. That answers "what did this row look like then", but a login, a download or someone viewing sensitive data has no row to version. Database triggers and pgaudit see statements, not the application's user, request or intent.
98
+
99
+ This library stores what changed as diffs, next to the domain events you declare and the request context (actor, IP, user agent, path, channel), in one log you can list chronologically, per object or per actor. The trade-off: there is no revert and no state at a point in time. See [migrating from continuum](https://wiktorb2004.github.io/sqlalchemy-audit-trail/migrating-from-continuum/) and [limitations](https://wiktorb2004.github.io/sqlalchemy-audit-trail/limitations/).
100
+
101
+ ## Design
102
+
103
+ ### One partitioned log
104
+
105
+ Two tables: `audit_transaction` (who, where and how, once per database transaction) and `audit_activity` (one row per object and flush, or per event). Both are partitioned by severity, then by month, so retention drops whole partitions per severity and reads touch only the partitions they need. There is no default partition: schedule `ensure_partitions()` (see [operations](https://wiktorb2004.github.io/sqlalchemy-audit-trail/guides/operations/)).
106
+
107
+ ### In your transaction, unless you say otherwise
108
+
109
+ | Kind | Written | When the audit write fails |
110
+ | --- | --- | --- |
111
+ | entity change, plain event | in your transaction | `on_error="log"`: logged, your transaction goes on; `"raise"`: propagates |
112
+ | `durable` event | on its own connection, committed before `log()` returns | as `on_error` |
113
+ | `fail_closed` event | on its own connection, committed before `log()` returns | always raises `AuditWriteError` |
114
+
115
+ ### Privacy by default, erasure on request
116
+
117
+ Per-column `exclude`, `redact` and `hash` policies, `Pseudonymized` payload fields with versioned keys, and `scrub()` / `scrub_actor()` to erase an object's values or an actor's personal context, each recorded as an `audit.scrubbed` entry. See [privacy](https://wiktorb2004.github.io/sqlalchemy-audit-trail/guides/privacy/).
118
+
119
+ ### Reads fail closed
120
+
121
+ `list_groups()` lists entries grouped by transaction, with keyset pagination. `Visibility` restrictions fail closed: `None` means no restriction, an empty set allows nothing, and a `NULL` column never passes a restriction that is set.
122
+
123
+ ### Sync, async and FastAPI
124
+
125
+ `Session` and `AsyncSession` on psycopg 3 or asyncpg. `audit_trail.integrations.fastapi` adds ASGI middleware for the request context (the client IP is read from `X-Forwarded-For` only behind trusted proxies), a session dependency, and `set_actor()` for after authentication.
126
+
127
+ ## Tests
128
+
129
+ Tests under `tests/db` run against a real PostgreSQL. With Docker running, a throwaway `postgres:18` container is started with testcontainers.
130
+
131
+ ```bash
132
+ uv sync --frozen
133
+
134
+ uv run pytest tests/unit # no database needed
135
+ uv run pytest # everything, needs Docker
136
+ AUDIT_TEST_PG_IMAGE=postgres:14 uv run pytest # oldest supported PostgreSQL
137
+
138
+ uv run ruff check . && uv run mypy
139
+ ```
140
+
141
+ 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.
142
+
143
+ ## Docs
144
+
145
+ ```bash
146
+ uv sync --group docs
147
+ uv run mkdocs serve
148
+ ```
149
+
150
+ Published at [wiktorb2004.github.io/sqlalchemy-audit-trail](https://wiktorb2004.github.io/sqlalchemy-audit-trail/).
151
+
152
+ ## Contributing
153
+
154
+ Issues and pull requests are welcome. See [CONTRIBUTING.md](CONTRIBUTING.md) and the [Code of Conduct](CODE_OF_CONDUCT.md). To report a vulnerability, use [SECURITY.md](SECURITY.md).
155
+
156
+ ## License
157
+
158
+ MIT. See [LICENSE](LICENSE). Changelog: [CHANGELOG.md](CHANGELOG.md). Cite this repo with [CITATION.cff](CITATION.cff).
@@ -0,0 +1,67 @@
1
+ """Audit trail for SQLAlchemy on PostgreSQL."""
2
+
3
+ from importlib.metadata import PackageNotFoundError, version
4
+
5
+ from audit_trail.checks import ModelIssue, check_models
6
+ from audit_trail.config import AuditOptions, AuditTrail, Target
7
+ from audit_trail.context import Actor, AuditContext
8
+ from audit_trail.diff import AuditOptionError, FieldPolicyError
9
+ from audit_trail.events import AuditEvent, Severity, event
10
+ from audit_trail.listener import AsyncLoadError
11
+ from audit_trail.mixin import Audited
12
+ from audit_trail.privacy import ScrubNotAllowedError, ScrubResult
13
+ from audit_trail.query import (
14
+ ALL_HISTORY,
15
+ AccessCount,
16
+ ActivityDetail,
17
+ AllHistory,
18
+ Cursor,
19
+ FieldLabels,
20
+ Group,
21
+ LabelResolver,
22
+ Page,
23
+ RelationshipLabels,
24
+ TransactionHeader,
25
+ Visibility,
26
+ )
27
+ from audit_trail.serialization import Pseudonymized
28
+ from audit_trail.writer import AuditWriteError
29
+
30
+ try:
31
+ __version__ = version("sqlalchemy-audit-trail")
32
+ except PackageNotFoundError: # pragma: no cover - running from a source tree
33
+ __version__ = "0.0.0"
34
+
35
+ __all__ = [
36
+ "ALL_HISTORY",
37
+ "AccessCount",
38
+ "ActivityDetail",
39
+ "Actor",
40
+ "AllHistory",
41
+ "AsyncLoadError",
42
+ "AuditContext",
43
+ "AuditEvent",
44
+ "AuditOptionError",
45
+ "AuditOptions",
46
+ "AuditTrail",
47
+ "AuditWriteError",
48
+ "Audited",
49
+ "Cursor",
50
+ "FieldLabels",
51
+ "FieldPolicyError",
52
+ "Group",
53
+ "LabelResolver",
54
+ "ModelIssue",
55
+ "Page",
56
+ "Pseudonymized",
57
+ "RelationshipLabels",
58
+ "ScrubNotAllowedError",
59
+ "ScrubResult",
60
+ "Severity",
61
+ "Target",
62
+ "TransactionHeader",
63
+ "Visibility",
64
+ "__version__",
65
+ "check_models",
66
+ "event",
67
+ ]