A SQLAlchemy app adds a tenant filter to every query with do_orm_execute and with_loader_criteria; which statements does it still miss, and why?
answer
- only Session.execute and its relatives
- the is_select guard has a cost
- aliases, raw SQL, the identity map
- the lambda runs once per class
basics
~20 sThe hook rewrites only ORM statements run through the Session's execute methods, so it misses text() SQL, Core on a Connection, flush writes, aliased() entities without include_aliases=True, ORM UPDATE and DELETE behind an is_select guard, and identity-map hits.
solid answer
~40 sThe documented recipe listens for `do_orm_execute` on the `sessionmaker` and, when `is_select` is true and the statement is neither a column nor a relationship load, adds `with_loader_criteria(HasTenant, lambda cls: cls.tenant_id == tenant_id, include_aliases=True)`. That covers top-level ORM SELECTs, joins and, through `propagate_to_loaders=True`, lazy and eager relationship loads. It misses: `text()` SQL, which has no entity to filter; anything run on `session.connection()` or an `Engine`, since `do_orm_execute` fires only for `Session.execute()` and its relatives; INSERTs and UPDATEs the flush emits; ORM `update()` and `delete()`, which support the option but are excluded by the `is_select` guard; `aliased()` entities when `include_aliases` keeps its default `False`; and `session.get()` hits in the identity map. Read the tenant id outside the lambda: calling a function inside it raises `InvalidRequestError`.
code
python · 67 linesfrom contextvars import ContextVar
from sqlalchemy import ForeignKey, create_engine, event, select
from sqlalchemy.orm import (
DeclarativeBase,
Mapped,
ORMExecuteState,
mapped_column,
relationship,
sessionmaker,
with_loader_criteria,
)
current_tenant: ContextVar[int] = ContextVar("current_tenant")
class Base(DeclarativeBase):
pass
class HasTenant:
tenant_id: Mapped[int] = mapped_column(index=True)
class Customer(HasTenant, Base):
__tablename__ = "customer"
id: Mapped[int] = mapped_column(primary_key=True)
invoices: Mapped[list["Invoice"]] = relationship(back_populates="customer")
class Invoice(HasTenant, Base):
__tablename__ = "invoice"
id: Mapped[int] = mapped_column(primary_key=True)
customer_id: Mapped[int] = mapped_column(ForeignKey("customer.id"))
customer: Mapped[Customer] = relationship(back_populates="invoices")
engine = create_engine("sqlite://")
SessionLocal = sessionmaker(engine)
@event.listens_for(SessionLocal, "do_orm_execute")
def add_tenant_criteria(state: ORMExecuteState) -> None:
if state.is_select and not state.is_column_load and not state.is_relationship_load:
tenant_id = current_tenant.get() # read here, never inside the lambda
state.statement = state.statement.options(
with_loader_criteria(
HasTenant,
lambda cls: cls.tenant_id == tenant_id,
include_aliases=True,
)
)
Base.metadata.create_all(engine)
with SessionLocal() as session, session.begin():
session.add_all([Customer(id=1, tenant_id=1), Customer(id=2, tenant_id=2)])
session.flush()
session.add_all([
Invoice(id=10, tenant_id=1, customer_id=1),
Invoice(id=11, tenant_id=2, customer_id=1), # mismatched row, filtered out
])
current_tenant.set(1)
with SessionLocal() as session:
for customer in session.scalars(select(Customer)):
print(customer.id, [invoice.id for invoice in customer.invoices]) # 1 [10]go deeper
Recall that do_orm_execute is a Session event for ORM statements and that with_loader_criteria adds a WHERE condition for one entity everywhere it appears.
Explain the is_select guard, why relationship and column loads are skipped, and what include_aliases and propagate_to_loaders default to.
List each bypass, from text() and Connection.execute() to flush writes and identity-map hits, and close each one with a matching guard.
Decide whether tenant isolation may rest on an ORM hook at all, or needs a database-level guard behind it for every client.
## The recipe `do_orm_execute` is a Session event that fires for statements run through `Session.execute()` and related methods such as `Session.scalars()` and `Session.scalar()`. It receives an `ORMExecuteState`, whose `statement` can be replaced. `with_loader_criteria()` is a loader option that adds a WHERE condition to every occurrence of an entity in a query. The documented combination: ```python @event.listens_for(SessionLocal, "do_orm_execute") def add_tenant_criteria(state): if state.is_select and not state.is_column_load and not state.is_relationship_load: tenant_id = current_tenant.get() state.statement = state.statement.options( with_loader_criteria(HasTenant, lambda cls: cls.tenant_id == tenant_id, include_aliases=True) ) ``` Passing a mixin such as `HasTenant` with a lambda applies the rule to every mapped class that inherits from it; the lambda receives each concrete class. ## What it covers - **Top-level ORM SELECTs**: `select(Customer)` gains `WHERE customer.tenant_id = ?`. - **Joins and subqueries**: the criteria land in ON clauses and nested selects too. - **Relationship loads**: `propagate_to_loaders` defaults to `True`, so the option travels with loaded objects and a later lazy load of `customer.invoices` renders `... AND invoice.tenant_id = ?`. That is why the guard skips `is_relationship_load`: the criteria are already there. - **`session.get()` that has to query**: the primary-key SELECT carries the tenant filter, so another tenant's row comes back as `None`. ## What it misses | Statement | Filtered? | Why | |---|---|---| | `session.execute(text("SELECT ... FROM customer"))` | no | raw SQL has no entity; `is_select` is `False` for a `TextClause` | | `session.connection().execute(select(Customer))` | no | `do_orm_execute` fires only for `Session.execute()` and its relatives | | `engine.connect()` and Core statements | no | no Session involved | | flush INSERT and UPDATE | no | the hook does not apply to statements emitted inside the flush | | `session.execute(update(Customer)...)` | not with the recipe's guard | `with_loader_criteria` is supported by ORM UPDATE and DELETE, but `is_select` excludes them | | `select(aliased(Customer))` | only with `include_aliases=True` | the default is `False` | | `session.get()` for an object in the identity map | no SQL to filter | the Session returns the object it already holds | Each gap needs its own answer: 1. **Writes**: add the option when `state.is_update or state.is_delete` as well, and stamp `tenant_id` on new objects in a `before_flush` listener; the read filter does not protect writes. 2. **Raw SQL and Core**: a code-review rule that tenant-scoped tables are reached only through ORM statements, or a database-level guard such as row-level security on PostgreSQL. 3. **Identity map**: keep one Session per request and tenant. An object loaded under tenant 1 stays in the identity map and is returned without SQL if the same Session later serves tenant 2. 4. **Aliases**: always pass `include_aliases=True` in a global rule. ## The lambda trap The docs warn that the lambda inside `with_loader_criteria()` is invoked **once per unique class** and that custom functions should not be called inside it. SQLAlchemy analyses the lambda for caching: closure variables become bound parameters, which is why reading `tenant_id` outside the lambda and referring to it inside works, with the value appearing as a parameter in each statement. Calling `current_tenant.get()` inside the lambda instead raises: ```plaintext InvalidRequestError: Can't invoke Python callable get() inside of lambda expression argument ... ``` The message gives the reason: the lambda system normally extracts bound values without invoking the lambda or any functions within it, so a value produced by a call could not be refreshed per query. The fix it names is the one the recipe uses: call the function outside the lambda and assign the result to a local variable. ## Verifying the rule A global filter fails silently, so it needs tests that look at the SQL rather than at results that happen to be correct: - Assert on the emitted SQL, not only on results: every SELECT against a tenant table should carry the tenant condition. - Seed two tenants with deliberately mismatched rows, such as an invoice whose tenant differs from its customer's, so a missing filter returns a visible extra row. - Add one test per known bypass (`text()`, an `aliased()` entity, an ORM `update()`) so a change to the hook's guard shows up as a failure, not as a leak. - Print a statement with `str(stmt)` while developing to see where the criteria land. ## Missing context If no tenant is set, `ContextVar.get()` without a default raises `LookupError` inside the hook, which fails the query loudly. Whether a job without a tenant should fail or bypass the filter is a policy choice; bypass explicitly with an execution option checked in the hook, never by catching the error.
- How would you extend the SQLAlchemy tenant hook so that ORM bulk UPDATE and DELETE are scoped too?ORM-enabled `update()` and `delete()` support `with_loader_criteria()`; its criteria are added to the statement's WHERE clause and used during synchronisation. In the `do_orm_execute` listener, apply the same option when `state.is_update or state.is_delete`. Flush-time writes still need a separate guard, such as a `before_flush` check that every new object's `tenant_id` matches the current tenant.
- Why does the SQLAlchemy recipe skip is_relationship_load and is_column_load instead of adding the option every time?Those executions are lazy loads and deferred-column loads that descend from an earlier query. With `propagate_to_loaders=True`, the default, the criteria already travel with the loaded objects into those loads. Adding the option again would only duplicate work, and column loads fetch attributes of rows that were already filtered.
- do_orm_execute sees every statement, including session.connection().execute() calls.
- with_loader_criteria filters aliased() entities by default.
- Calling current_tenant.get() inside the criteria lambda is the simplest way to read the tenant.
- ORM-enabled UPDATE and DELETE cannot take with_loader_criteria at all.
- The read filter also stops a flush from inserting another tenant's rows.