Skip to content

Repo and executor

Repo is the only DB gateway a service uses; the ambient executor is what makes transactions and row-level filtering transparent.

Two pieces carry the data layer’s transparency: the ambient executor installed per request (or per job), and the Repo<E> handle every service uses to reach it. They are built on SeaORM — a query Repo hands you narrows through its own methods, in SeaORM’s vocabulary: conditions, column orders and limits — and on the seam from nest-rs-database, which is what keeps the same seam open to a non-SeaORM driver.

The invariant: every data access goes through a service, and a service reaches the DB only through Repo. That is the single audited choke point per entity.

From a handler’s point of view there is nothing to set up: you call the service, the service calls Repo, and Repo picks up the ambient executor the framework installed before the handler ran — the pool on a safe route, a transaction on a mutation. No connection parameter, no transaction object to thread through the call stack.

Repo<E> is generic over the entity. Every method runs against the ambient executor, every read carries the ambient ability filter, and every read and update of an entity declared soft_delete leaves its deleted rows out:

nest_rs::seaorm::Repo
Repo::<Posts>::all().await?; // every readable row
Repo::<Posts>::find_by_id(id).await?; // None if absent OR out of scope
Repo::<Posts>::scoped(Action::Read); // RepoSelect<E> pre-filtered, chain freely
Repo::<Posts>::with_tombstones(Action::Read); // the same, deleted rows kept
Repo::<Posts>::update(active).await?; // RepoError::NotFound if out of scope or deleted;
// RepoError::Forbidden naming a column `.fields` withholds
Repo::<Posts>::delete(model).await?; // 0 rows if out of scope; purges a deleted row too
Repo::<Posts>::can(Action::Update, &model).await?; // the instance check, in SQL
Repo::<Posts>::page(first, after, Condition::all()).await?; // keyset page — see Pagination

A by-id write (update, delete) ANDs condition_for(Update|Delete) with the primary key, so a caller cannot mutate a row outside its scope even with a leaked id. An update under a grant whose .fields narrows it holds what it sets to that list, in the same statement (What a write may set). An update that sets nothing has no statement to carry that condition, so it reads its row back under it instead, and answers as any other. can asks the same question without writing: one query on the primary key under the action’s condition, which decides a relational rule the model alone cannot show. CrudService::access(action, id) loads unscoped so a denied-but-existing row surfaces as Access::Denied (distinct from Access::Missing) — the gateway route-model binding goes through.

The deleted rows are left out after the ability’s condition, for every action but Create and Delete: Repo::delete is the hard purge, so it reaches a tombstone, and Repo::can(Delete, …) answers for it; a create checks its fresh row against the ability alone, so importing a row already deleted is no denial. Repo::unscoped and unscoped_by_id hide them too — they drop the ability, not the deletion, so a deleted account cannot sign in. Repo::with_tombstones is the one read that keeps them, for an administrator’s view or a retention job. It reads only: no Repo write brings a deleted row back yet — Repo::restore is planned for 7.x.

scoped returns a RepoSelect<E>, a query the ability already filters. It narrows through its own methods — filter, order_by, order_by_asc, order_by_desc, order_by_with_nulls, limit, offset and apply_if, each in SeaORM’s vocabulary, with no trait to import — and runs on the ambient executor through all, one, count or exists:

crates/features/src/posts/service.rs
let row = Repo::<Posts>::scoped(Action::Read)
.filter(Column::Title.eq(name))
.one()
.await?;

A RepoSelect implements none of SeaORM’s builder traits, so what runs is the statement Repo filtered, and the compiler says so: .query(), .into_query(), .select_only(), .column_as(), .join() and the rest answer E0599. Each of those traits hands out the statement as a &mut, and a trait’s method cannot be sealed, so a statement replaced, cleared or unioned through one would run past the filter, and select_only with expr_as would move a hidden column into an exposed one’s slot. An order key is a column of the entity for the same reason. A related row comes through its own service’s loader, under its own filter.

Repo hands out no connection. What sets part of the filter aside goes through a method named for it — unscoped, unscoped_by_id, insert_unscoped and insert_unscoped_or_existing drop the ability, with_tombstones keeps the deleted rows — whose rustdoc states the bar its caller must clear, so auditing the escapes is one search per name. Outside a unit of work, every Repo call returns an error naming the bindings that install one — a service called with no ambient executor is a wiring bug, not a silent miss.

A condition written as raw SQL is held where it lands: Raw SQL in a filter.

The ambient executor is a SeaORM connection — the pool or the request’s transaction — installed in the request’s ambient context for the duration of the handler. It takes one of three shapes:

  • The pool, where nothing asks for a transaction: a safe route, a GraphQL query, transactional = false.
  • A lazy transaction, the one the framework installs wherever work may write. It defers BEGIN to the first data-layer touch, so a request a guard denies — or one that never queries — costs no round-trip at all.
  • A savepoint, what an atomic block runs on inside a transaction.

None of the three is yours to name: the unit of work installs the handle, Repo reads it, and nothing public hands one out or takes one in. A test runs a service in a unit of the app’s own binding instead — app.unit(ability, || svc.list()) as a request granted ability, app.system_unit(|| svc.purge()) as a job (E2E tests).

Three scopes coexist:

ScopeInstalled byWhat it carries
Requestan HTTP request, a GraphQL operation, a WS message or hook, an MCP operationPool on safe routes and queries, txn otherwise
Joba queue attempt, a scheduled tick, a lifecycle hookOne transaction per attempt (or pool)
Unscopednothingevery Repo call errors

Every edge installs it the same way: it runs each unit of work through nest_rs::database::run_unit, over the SeaOrmUnitOfWork that SeaOrmDatabaseModule binds as dyn UnitOfWork. Your modules list no data context of their own.

current_executor_scope() distinguishes Request from Job — Repo uses it to fail closed when a request runs with no ambient ability, while a job — a worker’s attempt, a tick, a lifecycle hook — runs unscoped (no caller ⇒ no scope to apply). Only the unit an edge opens chooses its scope, and never one wider than the unit it opens in: a job unit opened inside a request runs under the request’s scope, and so does work a job captured and a request re-enters. No public function installs an executor of its own, so feature code cannot take a request’s reads out of its scope. See Security for the ability half.

An anonymous caller is a request, not a job: on a unit naming its read with #[public(Read, Entity)] the ability guard still installs one, built from define_visitor, and Repo filters by it like any other; a bare #[public] reads nothing a grant guards. Nothing here treats “no login” as “no filter” — see Public reads.

Some work a unit starts runs after the future that started it: a streaming body polled once the handler returned, a DataLoader batch on a task of its own, work held for the commit. Each runs on the pool — a pool unit of the binding that opened it — never on the unit’s transaction — a body is polled after the commit, a batch serves the whole request, held work runs once the transaction is gone — and under the caller’s ability. A task you hand to TaskContext carries the ability but no executor: it may outlive the unit, so a write in it has to open a unit of its own, and a Repo call there fails closed.

Import SeaOrmDatabaseModule and the HTTP edge runs every request as one unit of work through the binding it provides, outside the route’s guards, so guards and handlers resolve the same ambient executor through Repo:

HTTP request
↓
unit of work ──→ installs the pool (GET/HEAD/OPTIONS/TRACE)
──→ installs a lazy transaction (POST/PUT/PATCH/DELETE)
↓
guards (AuthnGuard, AbilityGuard, ...)
↓
interceptors, handler
↓
unit of work (outcome) ──→ commit on success, rollback on any failure

A request to /graphql or /mcp runs on the pool whatever its method: each operation it carries is a unit of its own (GraphQL: one unit per operation).

A safe method gets the pool, no transaction overhead. A mutating method opens a DatabaseTransaction, runs the handler against it, and commits or rolls back on the unit’s outcome:

OutcomeDecision
Ok(2xx) or Ok(3xx)commit
Ok(4xx) or Ok(5xx)rollback
Err(_) from the handler, whatever an exception filter answeredrollback

A failed mutation never half-persists. See Transactions for where each boundary sits, and Serialization conflicts for the conflict-retry knobs.

Workers — same Repo, one transaction per attempt

Section titled “Workers — same Repo, one transaction per attempt”

Queue processors and cron jobs reach Repo the same way, one transaction per attempt: Job transactions.

Every unit of work has an executor: a request, a message, an operation, a job, a tick, a listener call, and a lifecycle hook, which reaches Repo through its service like any handler. A truly contextless path has none: a one-shot command run between init() and close() (running without serving), which calls a provider outside every unit. That and the programmatic transaction retry_on_conflict re-opens are the documented Repo bypasses: inject an Arc<DatabaseConnection> and call SeaORM directly — unscoped, with no ability filter and no transaction. If you find yourself reaching for it in a request handler or a hook, something else is wrong.