Writing a database driver
Bind the database port to a store of your own: the executor and unit of work a driver implements, and what each edge asks of it, on SeaORM's code.
The nest-rs-database
crate is a port: one UnitOfWork every edge runs its units of work through —
an HTTP request, a WebSocket message, an MCP operation, a queue attempt, a
scheduled tick, a lifecycle hook — and an object-safe Executor, the handle
each unit’s body reads from the ambient context. It names no store and no
query API, so the same contract fits a SQL pool, a document store, a
key-value session. This page and
Binding a database driver walk
nest-rs-seaorm,
the reference driver, in the order every driver page follows: each excerpt is
its code, compiled and tested in its suite.
Install
Section titled “Install”cargo add nest-rs --no-default-features --features database,configcargo add nest-rs --dev --no-default-features --features database,config,http,testingA driver implements the port rather than consuming it, so it takes database
without seaorm — the first-party integration is what you are replacing. It
needs no edge feature: every edge, HTTP included, opens its units through the
binding on its own — its tests take http to drive one. Your crate is
nestrs-<technology>, depending on the umbrella alone beside what your store
needs; the naming rule roots every name it owns
at that crate, its span target included. The app picks a driver by importing
its binding instead of SeaOrmDatabaseModule.
The contract
Section titled “The contract”The executor
Section titled “The executor”The executor is what a unit’s body reads: an enum of your store’s handles, so
one query helper returns one type whichever mode the unit is in. SeaORM’s,
SeaOrmExecutor in crates/nest-rs-seaorm/src/executor.rs, has a variant for
the pool, a transaction opened on the unit’s first statement, and an atomic
block’s savepoint. It is no part of that crate’s API: an app has nothing to do
with it, so nothing about it freezes with a release.
What as_any hands out is private to your crate. current_executor is
public, so whatever it downcasts to is in every service’s reach: a public
handle there is a connection a service could run a query on that your row
filter never saw. SeaORM installs its executor inside a crate-private
wrapper, and its Repo hands out no connection, so every statement that
reaches the database is one Repo built, and its select hands out no
statement to rewrite:
pub(crate) struct Installed(pub(crate) SeaOrmExecutor);
impl nest_rs_database::Executor for Installed { fn as_any(&self) -> &dyn Any { self } // …}Its other obligation is to keep the work an emitted event holds for the commit, which the wrapper forwards to the enum:
/// A lazy transaction or a block's savepoint holds the work for its/// settling; a pool hands it back to run at once.pub(crate) fn after_commit(&self, work: Deferred) -> Option<Deferred> { match self { SeaOrmExecutor::Lazy(lazy) => { lazy.hold(work); None } SeaOrmExecutor::Savepoint(block) => { block.hold(work); None } SeaOrmExecutor::Pool(_) => Some(work), }}The trait’s default hands the work back to run at once — right for a handle
with no transaction, and wrong for one with: a driver that leaves it out
dispatches every event emitted inside a transaction before that transaction
landed, and announces writes a rollback then undoes. The held work runs where
the unit settles, so take what it needs where it is registered: what the unit
carries into its commit (RequestContinuation::capture(Continuation::Commit))
and the scope it ran under (current_executor_scope()), inside which your
handle outside the transaction is installed when the work runs. Contain a
panic in it: the commit already stood.
The unit of work
Section titled “The unit of work”An edge declares each unit as a UnitSpec — its operation-log unit, its
scope, its TransactionPolicy, its deadline — and asks your binding to open
it, runs the body with your executor installed, then calls settle with the
edge’s own verdict:
impl UnitOfWork for SeaOrmUnitOfWork { fn open(&self, spec: &UnitSpec) -> Result<Box<dyn OpenUnit>, Unhonoured> { // … match spec.policy { TransactionPolicy::Pool => Ok(Box::new(OnPool { // … })), TransactionPolicy::PerUnit => Ok(Box::new(InTransaction { lazy: Arc::new(self.lazy(transport)), // … })), // A policy this driver does not know is refused before the body runs. _ => Err(Unhonoured::deterministic(UNSUPPORTED_POLICY)), } }
fn settle_net(&self) -> Duration { self.settle_net }}Opening sends nothing: the transaction begins on the unit’s first statement,
so a unit a guard denies costs no round trip. The settle runs on a task the
binding tracks, so an edge that drops its future — a client gone, an
operation stopped — never cuts a COMMIT:
let task = TaskContext::capture(Continuation::Commit).carry(async move { let settled = nest_rs_core::panic::contain(async move { let (outcome, held) = lazy.answer(ok).await; // The edge may have stopped listening; the settle goes on regardless. let _unheard = answer.send(classify(outcome, ok, transport, observe_conflicts)); held.run().await; }) .await; // …});let finished = settles.spawn(task);Box::pin(told(ok, transport, net, deadline, answered, async move { drop(finished.await);}))What your binding owes:
- Settle on the outcome you are handed.
okis the edge’s verdict — a 2xx or 3xx, a reply that is not an error frame, a tool answer withoutisError, a job’sOk.Settlement::Unhonouredturns a success you could not keep into the edge’s failure; a failure stands unless you answer itUnhonoured::IN_DOUBT. - Answer within your settle net. Past
settle_netwithout your store’s answer to a commit, answerUnhonoured::IN_DOUBT: the commit may have landed, so the unit is never retried. Wait for the held work until the unit’s deadline, then answer and let it run on: a slow listener never fails a committed unit. - Fail closed on an escaped handle.
settleis called once the body and the executor it ran with are dropped, so a handle still alive was carried off by a spawned task: answerUnhonouredon a success. - Honour
TransactionPolicy::Pool. It is the developer’stransactional = false, and a safe HTTP method’s. A pool unit may be dropped unsettled: a streaming body or a DataLoader batch runs on one. - Settle what
after_commitheld once the commit landed; drop it when the unit failed. A retry then announces only the attempt that stood.
What the edges ask of it
Section titled “What the edges ask of it”You write nothing per edge: each resolves your binding once, when it mounts
or boots, and runs every unit through it, around its guards — so a guard that
denies has run before anything opens. Which policy each edge’s units ask for,
and which outcome commits, is the app’s side of this contract, on
Transactions. The request
timeout cuts the body, never the commit: the edge waits your settle_net past
the unit’s deadline before it answers 500 for a commit that never answered.
What the router answers itself — a 404, a 405 — opens no unit.
Atomic blocks (optional)
Section titled “Atomic blocks (optional)”nest_rs::database::atomic(work) asks the ambient executor for a block
through Executor::atomic. The default answers None, and atomic then
refuses with AtomicError::Unsupported without running the work —
fail-closed, so a driver that offers no block loses the feature, and every
GraphQL mutation with it: each root field runs in a block. SeaORM’s nests one
in whatever the handle holds:
pub(crate) fn atomic(&self) -> Option<Arc<dyn AtomicBlock>> { let block = match self { SeaOrmExecutor::Pool(pool) => { AtomicExecutor::own(Arc::new(LazyTransaction::new(pool.clone(), ATOMIC))) } SeaOrmExecutor::Lazy(lazy) => { AtomicExecutor::savepoint(Arc::new(Savepoint::in_boundary(Arc::clone(lazy)))) } SeaOrmExecutor::Savepoint(block) => { AtomicExecutor::savepoint(Arc::new(Savepoint::in_block(Arc::clone(block)))) } }; Some(Arc::new(block))}A block owes, in order of how badly it goes wrong without it: the enclosing
unit waits for it, so none of its statements lands inside the block’s
savepoint; a failure inside poisons the block, not the unit; a refused
RELEASE or ROLLBACK TO, or a block dropped before it settled, leaves the
unit unable to commit; nothing is sent before the block’s first statement;
and a block of its own on a pool unit commits on your settle task, its pool
unit answering Unhonoured::IN_DOUBT when the body was cut before it saw
that commit’s answer. crates/nest-rs-seaorm/src/savepoint.rs and turn.rs
are the reference shape.
The outbox (optional)
Section titled “The outbox (optional)”A job pushed inside a unit is filed after its commit only where the driver
keeps an outbox: the queue port hands the sealed jobs to
Executor::write_outbox, whose default answers None — the job is filed at
once, and a rollback leaves it behind. To keep one, bind a
nest_rs::database::OutboxStore over a table of your own beside your unit of
work — arm proves the table, written wakes once a unit that wrote records
committed, claim locks due records no other relay holds, oldest first — and
import nest_rs::queue::OutboxModule, which attaches the relay that drains
it. Then write the records write_outbox hands you on each transaction a unit
settles, in its turn, and wake the relay after its commit; remove_outbox and
remove_outbox_unique delete a record no relay has filed, and wait for one a
relay holds rather than skip it. The records are opaque: write them as you
receive them, and never log the sealed text, which carries the job’s payload.
crates/nest-rs-seaorm/src/queue/outbox.rs is the reference shape.
The binding
Section titled “The binding”The module an app imports, and what it owes in production — its budgets, its failures, its TLS, its proof at boot, its health and its tests — continue on Binding a database driver.
Going further
Section titled “Going further”- Transactions — the boundary each unit settles, seen from the app.
- Repo and executor — the ambient executor your driver installs.
- Database — the module an app imports to pick a driver.