Explicit transactions with SQLx
A unit of work that begins a transaction, passes it as &mut Transaction to repositories, and commits once or rolls back on drop.
A transfer between two accounts must debit one and credit the other or do neither. This recipe starts a SQLx transaction in one place, passes it down as &mut Transaction to the repositories, and commits at the end. The transaction is an argument of the call, so the code that runs inside it is visible in the signatures.
An ambient form, where a transaction scoped to the execution is opened for a handler and committed or rolled back when the execution ends, is not available. The design for the integrations (docs/experiments/di-redesign/integrations/DESIGN.md, section 12) defers "transactions scoped to an execution": the core has no asynchronous hook at an execution's end, so a commit or rollback cannot run there, and it is a core design of its own. Until then, pass the transaction.
The recipe is compiled and run against SQLite in a file. The code is the same against Postgres with PgPool and Postgres in place of the SQLite types and $1 placeholders in place of ?1. That variant was not compiled.
Versions compiled with: sqlx 0.9.0 (through ulo-db-sqlx, feature sqlite), ulo 0.1.0-alpha.3.
The code
use std::fmt;
use serde::Deserialize;
use ulo::{App, AppBuilder, Dep, Module, ModuleDef, ModuleIdentity, controller, handlers, injectable};
use ulo_db_sqlx::sqlx::{self, Sqlite, SqlitePool, Transaction};
use ulo_db_sqlx::{Sqlite as SqliteStore, SqliteOptions, SqlxModule};
use ulo_http::{Classify, Json};
#[derive(Debug, Classify)]
pub enum TransferError {
#[classify(not_found)]
NoAccount(i64),
#[classify(conflict)]
Insufficient(i64),
#[classify(unavailable)]
Store(sqlx::Error),
}
impl fmt::Display for TransferError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
TransferError::NoAccount(id) => write!(f, "no account {id}"),
TransferError::Insufficient(id) => write!(f, "account {id} has too little"),
TransferError::Store(_) => f.write_str("the ledger is unavailable"),
}
}
}
impl std::error::Error for TransferError {}
impl From<sqlx::Error> for TransferError {
fn from(e: sqlx::Error) -> Self {
TransferError::Store(e)
}
}
/// Repositories take the transaction they run in. They never begin, commit or roll back.
#[injectable]
pub struct Accounts;
impl Accounts {
pub async fn debit(&self, tx: &mut Transaction<'_, Sqlite>, id: i64, cents: i64) -> Result<(), TransferError> {
let moved = sqlx::query("update accounts set cents = cents - ?1 where id = ?2 and cents >= ?1")
.bind(cents)
.bind(id)
.execute(&mut **tx)
.await?
.rows_affected();
if moved == 1 {
return Ok(());
}
let exists: Option<(i64,)> = sqlx::query_as("select id from accounts where id = ?1").bind(id).fetch_optional(&mut **tx).await?;
Err(if exists.is_some() { TransferError::Insufficient(id) } else { TransferError::NoAccount(id) })
}
pub async fn credit(&self, tx: &mut Transaction<'_, Sqlite>, id: i64, cents: i64) -> Result<(), TransferError> {
let moved = sqlx::query("update accounts set cents = cents + ?1 where id = ?2").bind(cents).bind(id).execute(&mut **tx).await?.rows_affected();
if moved == 1 { Ok(()) } else { Err(TransferError::NoAccount(id)) }
}
}
#[injectable]
pub struct Audit;
impl Audit {
pub async fn record(&self, tx: &mut Transaction<'_, Sqlite>, line: &str) -> Result<(), TransferError> {
sqlx::query("insert into audit (line) values (?1)").bind(line).execute(&mut **tx).await?;
Ok(())
}
}
/// The unit of work: it owns the pool and decides where the transaction begins and ends.
#[injectable]
pub struct Transfers {
pool: Dep<SqlitePool>,
accounts: Dep<Accounts>,
audit: Dep<Audit>,
}
impl Transfers {
pub async fn transfer(&self, from: i64, to: i64, cents: i64) -> Result<(), TransferError> {
let mut tx = self.pool.begin().await?;
self.accounts.debit(&mut tx, from, cents).await?;
self.accounts.credit(&mut tx, to, cents).await?;
self.audit.record(&mut tx, &format!("{from} -> {to}: {cents}")).await?;
tx.commit().await?;
Ok(())
}
}
#[derive(Deserialize)]
pub struct Transfer {
pub from: i64,
pub to: i64,
pub cents: i64,
}
#[controller]
pub struct TransfersController {
transfers: Dep<Transfers>,
}
#[handlers]
impl TransfersController {
#[ulo_http::post("/transfers")]
async fn create(&self, Json(t): Json<Transfer>) -> Result<(), TransferError> {
self.transfers.transfer(t.from, t.to, t.cents).await
}
}
pub struct LedgerModule {
pub url: String,
}
impl Module for LedgerModule {
fn identity(&self) -> ModuleIdentity {
ModuleIdentity::of_type::<Self>()
}
fn register(&self, m: &mut ModuleDef<'_>) {
let options = SqliteOptions { url: self.url.clone().into(), max_connections: Some(4), min_connections: None, acquire_timeout_secs: None };
m.import(SqlxModule::<SqliteStore>::from_options(options));
m.provide::<Accounts>();
m.provide::<Audit>();
m.provide::<Transfers>();
m.controller::<TransfersController>();
}
}
pub fn builder(url: &str) -> AppBuilder {
App::builder(LedgerModule { url: url.to_owned() })
}What each seam does
Accounts and Audit are repositories. Each method takes &mut Transaction<'_, Sqlite> and runs its queries on &mut **tx, the connection under the transaction. They never begin, commit or roll back, so any caller that holds a transaction can compose them. Neither holds the pool.
Transfers is the unit of work. It owns the Dep<SqlitePool>, calls begin(), passes &mut tx to each repository and ends with tx.commit(). An error returned by ? leaves transfer before the commit, and the dropped Transaction rolls back.
TransferError carries the classification: #[classify(not_found)], #[classify(conflict)] and #[classify(unavailable)] are the answers 404, 409 and 503. The From<sqlx::Error> impl lets ? lift a driver error into it. See Error handling.
Sqlite in the imports is SQLx's database type. The store's marker type of the same name is imported as SqliteStore.
What ran
With accounts 1 and 2 holding 1000 and 0 cents, in a file database through the store module:
| Call | Answer | Accounts afterward | Audit |
|---|---|---|---|
POST /transfers 1 to 2, 300 | 204 | 1: 700, 2: 300 | one line, 1 -> 2: 300 |
POST /transfers 1 to 99, 100 | 404, detail no account 99 | unchanged | unchanged |
POST /transfers 2 to 1, 5000 | 409, detail account 2 has too little | unchanged | unchanged |
The second call debited account 1 inside the transaction before the credit to account 99 failed, and account 1 still held 700 afterward. The rollback happened on drop, with no explicit call.
Failure modes
A path that returns Ok without committing loses the work. Only commit() persists. A function that returns early with Ok(()) after the writes rolls them back.
A transaction holds a pooled connection. Everything between begin() and commit() keeps one connection out of the pool, so a slow call inside it, such as an HTTP request to another service, holds that connection for its duration. The pool's wait for a connection is bounded by acquire_timeout_secs, 5 seconds unless set (see SQLx), and a caller that waits longer than that fails.
Do not mix the pool and the transaction. A query inside transfer that runs on &*self.pool instead of &mut **tx runs on another connection, outside the transaction, and does not roll back with it.
One transaction per call chain. Nothing in the container carries the transaction from Transfers to a provider that was not passed it. A repository that should join must take the argument.
Reference
- SQLx: the module, its options and the pool.
- Connecting: the connect bound.
- Migrations: where the schema the queries assume comes from. The run above created its tables with plain statements.
- Error handling:
Classifyand the problem-document body. - Providers:
#[injectable]andDep<T>.
A MongoDB ODM over the injected client
Models with oximod that read and write through the mongodb::Client the MongoDB module already built, with no second connection.
A mailer over lettre
An SMTP transport built at startup with a bounded connection test, behind a Mailer trait that a test replaces with a fake.