Transactions and locks
A transaction groups statements so that they all happen, or none does. A lock keeps other transactions from changing the rows you read until yours ends. Together they are what makes “check, then write” safe when two requests do it at the same moment.
A transaction
#![allow(unused)]
fn main() {
// sample/crates/booking/booking-ops/src/lib.rs
let tx = db.begin().await?;
let current = tx
.db()
.first(&Query::<Reservation>::new().filter(Reservation::id().eq(id)).for_update())
.await?;
// … what must not be done twice at the same time …
tx.db()
.execute(&Update::<Reservation>::new()
.set(Reservation::status(), "cancelled")
.filter(Reservation::id().eq(id)))
.await?;
tx.commit().await?;
}
db.begin()opens a transaction, on a connection of its own taken from the pool.tx.db()is aDbwhose every statement runs in the transaction. Pass it to any function that takes a&Db: the function does not need to know it runs in a transaction.tx.commit()keeps what was done;tx.rollback()drops it.- A transaction dropped without
commitis rolled back: an early?, areturn, a panic. You cannot forget to roll back.
#![allow(unused)]
fn main() {
let tx = db.begin().await?;
tx.db().execute(&Update::<Reservation>::new().set(Reservation::status(), "cancelled")
.filter(Reservation::id().eq(1))).await?;
drop(tx);
// reservation 1 is still "booked"
}
db.in_transaction() tells which kind of Db you have: false for a
pool’s, true for a transaction’s.
Coming from Django: there is no
atomic()decorator or context manager; a transaction is a value you hold. Django runs each statement in its own transaction by default (autocommit); so does rind, outsidebegin().
No nested transactions
begin() on a transaction’s Db is an error:
configuration: already in a transaction: nested transactions are not supported
Django’s nested atomic() blocks use savepoints; rind has none yet. So
a function that begins its own transaction cannot be called from code
that is already in one. The sample’s booking_ops::cancel begins one,
which is right for the cancel action (an action is not a write, its
ctx.db is the pool’s), but it could not be called from a resource’s
write hook.
The practical rule: a function that takes a &Db and may be called
from a write does not begin a transaction. It works in whatever its
Db is, and the caller decides.
In a request
A resource’s create, update and delete already run in a transaction.
In their hooks, ctx.db is that transaction’s
Db:
#![allow(unused)]
fn main() {
impl Writes for LoanResource {
async fn creating(ctx: &Ctx, input: &LoanIn, insert: Insert<Loan>) -> Result<Insert<Loan>, ApiError> {
// ctx.db is the creation's transaction: what is read here
// and what is written here is kept or dropped with the creation.
…
}
}
}
Write with ctx.db, and do not call begin(). If the hook returns an
error, the whole write is rolled back.
A model’s object writes with hooks open their own
transaction when given a pool’s Db, and join yours when given a
transaction’s.
Locking rows: for_update
#![allow(unused)]
fn main() {
Query::<Reservation>::new().filter(Reservation::id().eq(1)).for_update()
}
SELECT "t0"."id", "t0"."code", …
FROM "booking_reservation" AS "t0"
WHERE "t0"."id" = $1
FOR UPDATE OF "t0"
for_update() locks the rows the query reads, until the end of the
transaction: another transaction that wants to change them, or lock them
too, waits. This is Django’s select_for_update().
-
Only the query’s own table is locked (
FOR UPDATE OF "t0"), not the tables it joins:#![allow(unused)] fn main() { Query::<Reservation>::new().filter(Reservation::journey().code().eq("J100")).for_update() // INNER JOIN "timetable_journey" AS "journey" … // FOR UPDATE OF "t0" -- the reservations, not the journey } -
A lock outside a transaction is useless: the statement is its own transaction, and the lock ends with it. Use
for_updateontx.db(), or onctx.dbin a write. -
There is no
nowaitorskip_lockedyet.
The pattern: check, then write
The sample checks that a seat is free before it books it. Without a lock, two requests could both see the seat free, and both book it. The reservation’s check locks the journey’s row first, so the second request waits until the first has written its reservation, then sees the seat taken:
request A request B
begin begin
lock journey 1 ───────────────► lock journey 1 … waits …
seat 2 is free
insert reservation
commit ───────────────► (gets the lock)
seat 2 is taken: refused
rollback
The lock is on a row that both requests must read (the journey), not on the rows that do not exist yet (the reservations). A unique index on the seat is the second safety: even a request that forgot the lock cannot book the seat twice (Indexes).
Next: Raw SQL.