Should a team stamp updated_by through SQLAlchemy flush events, a mapped_column onupdate callable, or explicit service code, given the write paths each one misses?
answer
- list every way rows get written
- flush-only versus statement-level
- raw SQL escapes them all
- visibility versus completeness
basics
~20 sIt depends on the write paths: flush events see only the unit of work, an onupdate callable also covers ORM bulk and Core UPDATEs but not text(), and service code covers what developers remember. Compliance-grade audit belongs in the database.
solid answer
~40 sStart from the write paths. A `before_flush` or `before_update` listener sees only objects the Session flushes; ORM-enabled `update()`, bulk INSERT from dictionaries and Core statements bypass it. A `mapped_column(onupdate=current_actor.get)` callable is invoked by Core for any UPDATE whose SET clause omits the column, so it also stamps ORM bulk and Core `update()` statements, as long as they do not set the column themselves, but never `text()` or another client. Explicit service code is the most visible and testable, and also the easiest to forget on a new path. For a convenience column, `onupdate` plus a review rule against raw writes is usually enough; for compliance-grade audit, put the guarantee in the database and keep SQLAlchemy hooks for the actor context.
code
python · 34 linesfrom contextvars import ContextVar
from sqlalchemy import String, create_engine, select, text, update
from sqlalchemy.orm import DeclarativeBase, Mapped, Session, mapped_column
current_actor: ContextVar[str] = ContextVar("current_actor", default="system")
class Base(DeclarativeBase):
pass
class Invoice(Base):
__tablename__ = "invoice"
id: Mapped[int] = mapped_column(primary_key=True)
total: Mapped[int]
updated_by: Mapped[str] = mapped_column(
String(50), default=current_actor.get, onupdate=current_actor.get
)
engine = create_engine("sqlite://")
Base.metadata.create_all(engine)
with Session(engine) as session, session.begin():
session.add_all([Invoice(id=1, total=10), Invoice(id=2, total=20)])
current_actor.set("alice")
with Session(engine) as session, session.begin():
session.execute(update(Invoice).where(Invoice.id == 1).values(total=11)) # stamped
session.execute(text("UPDATE invoice SET total = 21 WHERE id = 2")) # not stamped
with Session(engine) as session:
print(session.execute(select(Invoice.id, Invoice.updated_by)).all())
# [(1, 'alice'), (2, 'system')]go deeper
Recall that flush events, column onupdate callables and service code are three different places a stamp can be set, and that they run at different times.
Explain which write paths each mechanism sees: flush only, every SQLAlchemy UPDATE that omits the column, or only the calls developers remember to make.
Inventory the codebase's write paths, including bulk and Core statements, and prove with a test per path that the chosen stamp actually lands.
Weigh visibility, completeness and operational cost, decide whether the stamp is convenience or evidence, and set the review rules that keep bulk and raw writes from bypassing it.
## The question behind the question `updated_by` looks like one column, but the real question is **which code paths write to the table** and how bad it is when a stamp is missing. A SQLAlchemy application typically writes through several paths at once: 1. The unit of work: objects added or modified, written at flush. 2. ORM-enabled DML: `session.execute(update(Invoice).where(...).values(...))`, and bulk INSERT or UPDATE from a list of dictionaries. 3. Core statements on a `Connection`: `update(invoice_table)` in a batch job. 4. Raw SQL via `text()`, often in a data fix or a report. 5. Clients outside the application: migrations, an admin console, another service. ## What each mechanism covers | Write path | `before_flush` / mapper events | `mapped_column(onupdate=...)` | explicit service code | database trigger | |---|---|---|---|---| | unit-of-work flush | yes | yes | yes, if called | yes | | ORM `update()` / bulk dicts | no | yes | yes, if called | yes | | Core `update(table)` | no | yes | rarely | yes | | `text("UPDATE ...")` | no | no | rarely | yes | | other clients | no | no | no | yes, if they supply an actor | Three facts drive the table: - **Flush events belong to the flush.** The docs say mapper persistence events apply only to the session flush and not to ORM-enabled `update()` and `delete()`; `before_flush` likewise sees only what the unit of work holds. - **`onupdate` is a Core column default.** A Python callable passed as `onupdate` is invoked for any UPDATE SQLAlchemy executes whose SET clause does not include that column, so the ORM flush, ORM bulk statements and Core `update()` all pick it up. `text()` is a string SQLAlchemy does not rewrite, so it escapes. - **A trigger sees every write** but needs the actor from somewhere, typically a per-transaction setting the application writes at the start of each transaction. ## The costs a lead weighs **Flush events** (`before_flush` walking `session.new` and `session.dirty`): - Centralised, and the right place for audit *rows* that need related objects. - Invisible at the call site: a reader of the service code cannot see that a save writes a stamp. - Silently incomplete as soon as someone adds a bulk statement for speed. **`onupdate` / `default` callables**: - Declared on the column, so the behaviour is visible in the model. - Covers more paths than flush events at no extra code. - Skipped when a statement sets the column explicitly, and limited to a value computed from context such as a `ContextVar`. **Explicit service code**: - Fully visible and easy to unit test; the stamp is part of the operation's contract. - Every new write path must remember it; reviews become the safeguard. **Database triggers**: - The only option that covers every client. - Moves logic into the database, where it is harder to test, version and debug, and still depends on the application passing the actor in. ## A way to decide 1. **Classify the stamp.** If `updated_by` is a debugging convenience, an `onupdate` callable reading the current actor from a context variable is usually enough, with a review rule that audited tables are never written with `text()`. 2. **If it is compliance evidence**, put the guarantee in the database and treat SQLAlchemy hooks as the way to hand the actor to it, not as the guarantee itself. 3. **For audit history rows** (who changed what, old and new values), `before_flush` is the natural home because it can add objects; accept that bulk statements need a second mechanism or are banned on audited tables. 4. **Make missing context loud.** Decide what a scheduled job without an actor writes: a named system actor, or a hard failure. 5. **Test the bypasses.** A test per write path that asserts the stamp, including one bulk `update()`, catches the first time a developer adds a path the chosen mechanism misses. The mistake to avoid is believing that one event listener stamps every change. It stamps every change *the flush makes*, and production systems grow other paths the moment the flush is too slow.
- Why does a SQLAlchemy onupdate callable stamp session.execute(update(Invoice)) while a before_update listener does not?`onupdate` is a column default invoked by Core for any UPDATE whose SET clause omits that column, and ORM-enabled `update()` is executed as a Core UPDATE. `before_update` is a mapper event of the unit-of-work flush, and the docs state it does not apply to ORM-enabled `update()` and `delete()`, which never pass through the flush.
- When would you still choose a before_flush listener over onupdate for audit work in SQLAlchemy?When the audit needs more than a column value: creating an `AuditEntry` object per change, recording old and new values from attribute history, or validating several objects together. `before_flush` may add objects and inspect the whole unit of work; a column default can only compute one value. Pair it with a rule for bulk paths.
- A before_flush listener stamps every UPDATE the application sends.
- An onupdate callable also rewrites raw text() UPDATE statements.
- Mapper before_update events fire for session.execute(update(Model)) rows.
- Explicit service code needs no tests because the stamp is visible.
- Database triggers remove the need to pass the actor from the application.