Transactions
A transaction runs several statements that commit together or not at all. Use one whenever two writes must both happen or neither: moving money between accounts, an order and its lines, a read followed by a write that depends on it. A single statement needs none: each statement sent on a Client is atomic and commits on its own.
Begin, commit, roll back
use rasterizeddb_client::prelude::*;
#[tokio::main]
async fn main() -> Result<()> {
let client = Client::connect("unix:/run/rdb/rdb.sock", Options::default()).await?;
let tx = client.begin().await?;
tx.exec("UPDATE account SET balance = balance - $1 WHERE id = $2", params![10i64, 1i64]).await?;
tx.exec("UPDATE account SET balance = balance + $1 WHERE id = $2", params![10i64, 2i64]).await?;
tx.commit().await?;
Ok(())
}| call | does |
|---|---|
client.begin() | BEGIN, at the server's default isolation (read committed) |
client.begin_with(options) | BEGIN with an isolation level or READ ONLY (see Isolation) |
tx.commit() | COMMIT; consumes the transaction |
tx.rollback() | ROLLBACK; consumes the transaction |
dropping tx | rolls back: its connection is closed, and the server rolls back a transaction whose connection ends |
tx.savepoint(name), tx.rollback_to(name), tx.release(name) | savepoints (see Savepoints) |
tx.is_usable() | whether the transaction's connection is still good (a transaction with a failed statement is still usable for a rollback) |
client.transaction(closure), client.transaction_with(options, closure) | runs a closure in a transaction, retrying on conflicts (see below) |
Inside a transaction you call the same methods as on a client: run, query, query_with, execute, exec, fetch_all, fetch_one, fetch_optional and fetch_scalar. They come from the Executor trait, which the prelude imports. The ORM calls (tx.insert(&row), Model::query()…all(&tx)) work on a transaction too.
BEGIN, COMMIT, ROLLBACK, SAVEPOINT and the rest are never sent as statements: written as SQL they are refused with Error::Unsupported. Use the methods above.
The closure form, with retries
client.transaction commits when the closure returns Ok, rolls back when it returns Err, and runs the closure again in a new transaction after a serialization failure (40001) or a deadlock (40P01):
use rasterizeddb_client::prelude::*;
#[tokio::main]
async fn main() -> Result<()> {
let client = Client::connect("unix:/run/rdb/rdb.sock", Options::default()).await?;
let new_balance: i64 = client
.transaction(|tx| {
Box::pin(async move {
let balance: i64 = tx
.fetch_scalar("SELECT balance FROM account WHERE id = $1", params![1i64])
.await?;
tx.exec("UPDATE account SET balance = $1 WHERE id = $2", params![balance - 10, 1i64])
.await?;
Ok(balance - 10)
})
})
.await?;
println!("{new_balance}");
Ok(())
}- The closure takes
&Transactionand returnsBox::pin(async move { … })(aTransactionFuture). Its result is whattransactionreturns. - The closure may run more than once. Keep side effects outside the database (sending an email, charging a card) until after
transactionreturns. - It is retried up to
TransactionOptions::retriestimes (defaultDEFAULT_TRANSACTION_RETRIES, which is 2; set 0 for none), with a short wait between runs. Only those two failures are retried: the server rolled the whole transaction back, and running it again may succeed. - A
COMMITwhose connection failed is never retried: whether it committed is unknown (Error::is_commit_outcome_unknown()). - A closure that swallows a statement's error and returns
Okdoes not commit: the server has failed the transaction, andCOMMITreports the rollback.
Give the closure what it needs from outside by value: a move closure for Copy values, and a clone per run for owned ones (see the job queue below), since it may run several times and the future it returns must not borrow your locals:
use rasterizeddb_client::prelude::*;
async fn transfer(client: &Client, from: i64, to: i64, amount: i64) -> Result<()> {
client
.transaction(move |tx| {
Box::pin(async move {
tx.exec("UPDATE account SET balance = balance - $1 WHERE id = $2", params![amount, from]).await?;
tx.exec("UPDATE account SET balance = balance + $1 WHERE id = $2", params![amount, to]).await?;
Ok(())
})
})
.await
}Isolation
use rasterizeddb_client::prelude::*;
#[tokio::main]
async fn main() -> Result<()> {
let client = Client::connect("unix:/run/rdb/rdb.sock", Options::default()).await?;
let report = TransactionOptions {
isolation: Some(Isolation::RepeatableRead),
read_only: true,
..TransactionOptions::default()
};
let tx = client.begin_with(report).await?;
let orders: i64 = tx.fetch_scalar("SELECT count(*) FROM orders", params![]).await?;
let lines: i64 = tx.fetch_scalar("SELECT count(*) FROM order_lines", params![]).await?;
tx.commit().await?;
println!("{orders} {lines}"); // both counted from one snapshot
Ok(())
}TransactionOptions field | default | what it does |
|---|---|---|
isolation | None (the server's default, read committed) | Some(Isolation::…) sends BEGIN ISOLATION LEVEL … |
read_only | false | BEGIN … READ ONLY: every write fails with 25006 |
retries | 2 | how often transaction_with reruns the closure after 40001/40P01; ignored by begin_with |
Isolation | the server |
|---|---|
ReadCommitted (the default) | a fresh snapshot per statement; a write to a row another transaction is writing waits for it, then goes on with what it committed |
RepeatableRead | one snapshot for the whole transaction; a write to a row another transaction changed after that snapshot fails with 40001 |
Serializable | accepted, and runs as RepeatableRead: write skew between transactions is not detected |
Under RepeatableRead, use the closure form so conflicts are retried for you. The server's side of this is on Transactions.
Row locks
To claim rows before changing them, lock them with SELECT … FOR UPDATE inside a transaction. Other transactions that try to lock or write those rows wait until yours ends. FOR SHARE lets several readers hold the lock, NOWAIT fails at once instead of waiting, and SKIP LOCKED leaves locked rows out, which lets several workers take different jobs from one queue:
use rasterizeddb_client::prelude::*;
async fn claim_jobs(client: &Client, worker: String) -> Result<Vec<i64>> {
client
.transaction(move |tx| {
let worker = worker.clone(); // one copy per run of the closure
Box::pin(async move {
let ids: Vec<(i64,)> = tx
.fetch_all(
"SELECT id FROM job WHERE status = 'pending' ORDER BY id LIMIT 10 FOR UPDATE SKIP LOCKED",
params![],
)
.await?;
let ids: Vec<i64> = ids.into_iter().map(|(id,)| id).collect();
if !ids.is_empty() {
tx.exec(
"UPDATE job SET status = 'running', worker = $1 WHERE id = ANY($2)",
params![worker, ids],
)
.await?;
}
Ok(ids)
})
})
.await
}A lock wait past SET lock_timeout fails with 55P03. For optimistic locking of model rows (a version column checked on every write), see The ORM.
Savepoints
A savepoint is a point inside a transaction you can return to without ending it:
use rasterizeddb_client::prelude::*;
#[tokio::main]
async fn main() -> Result<()> {
let client = Client::connect("unix:/run/rdb/rdb.sock", Options::default()).await?;
let tx = client.begin().await?;
tx.run("INSERT INTO log (id) VALUES (1)").await?;
tx.savepoint("before_risky").await?;
if tx.run("INSERT INTO log (id) VALUES (1)").await.is_err() {
// Undo the failure; the transaction can go on.
tx.rollback_to("before_risky").await?;
}
tx.release("before_risky").await?;
tx.commit().await?;
Ok(())
}| call | sends | effect |
|---|---|---|
savepoint(name) | SAVEPOINT name | marks a point; a name may be reused, the newest shadowing the older |
rollback_to(name) | ROLLBACK TO SAVEPOINT name | undoes everything since the savepoint, which stays, and clears a failure that came after it |
release(name) | RELEASE SAVEPOINT name | keeps the work and forgets the savepoint (and any taken after it) |
A savepoint name must be a plain identifier; anything else is refused before it is sent.
Errors inside a transaction
After a statement fails, the server refuses every later one with 25P02 until the transaction ends or rolls back to a savepoint taken before the failure. commit() of a failed transaction rolls it back and returns an error with 25P02.
Errors from statements in a transaction carry their SQLSTATE, read with Error::sqlstate():
| code | meaning | check |
|---|---|---|
40001 | serialization failure: retry the whole transaction | is_serialization_failure(), is_retryable() |
40P01 | chosen as a deadlock's victim: retry the whole transaction | is_deadlock(), is_retryable() |
55P03 | a lock wait passed SET lock_timeout | sqlstate() == Some("55P03") |
57014 | the statement ran past the statement timeout | is_statement_timeout() |
25P02 | the transaction had already failed | sqlstate() == Some("25P02") |
25006 | a write in a read-only transaction | sqlstate() == Some("25006") |
23505 | a unique or primary key was broken | is_unique_violation() |
See Errors for the full error type.
DDL inside a transaction rolls back with it (CREATE TABLE, ALTER TABLE, CREATE INDEX, and DROP TABLE, which is carried out at commit). CREATE DATABASE and DROP DATABASE are refused in a transaction (25001). Warnings the server raises (a RAISE NOTICE, DDL it cannot roll back) come as notices.
A statement that runs past the statement timeout (the server's --rdb-request-timeout, 30 s by default, or SET statement_timeout inside the transaction) fails with 57014. The transaction is then failed like any other, and its connection stays. SET statement_timeout = 0 inside a transaction lets its statements run as long as they need; raise the client's Options::timeout to match.
Connections
A transaction runs on a connection of its own, never on one of the client's shared connections (those carry many tasks' statements at once). Statements sent from several tasks on one Transaction queue behind each other, in order.
When a transaction ends cleanly, its connection is kept for the next transaction for up to 20 seconds; otherwise a new one is opened and logged in for it. That costs a connect and a login: little on a unix socket, a TLS handshake and (with a password) a SCRAM exchange over TCP. A SET inside a transaction lasts until the transaction ends.
When the connection fails
A transaction lives and dies with its connection. It is never moved to another connection: the client's reconnects do not apply to it.
- A transport failure ends the transaction. That call and every later one on it fail with
Error::TransactionLost. The server rolls a transaction back when its connection ends, so it did not commit. - The exception is a failure while
COMMITwas in flight: thenis_commit_outcome_unknown()is true, and whether it committed cannot be known from the client. Check the data before doing it again. - A statement whose future is dropped before its answer comes (a
tokio::time::timeoutaround it, a cancelled task) ends the transaction the same way, because its answer would otherwise be read as the next statement's.
The idle limit
The server closes a native connection that has been idle for its request timeout (--rdb-request-timeout, 30 seconds by default; the client's constant SERVER_IDLE_CLOSE is that default) and rolls back the transaction on it, releasing its locks. Nothing keeps a transaction's connection alive by itself, so a transaction someone forgot cannot hold its locks for ever. A call made after the limit fails with TransactionLost, saying the transaction was idle, without sending anything.
Keep transactions short. Do slow work (a remote call, waiting for user input) before begin() or after commit().
The Executor trait
Executor is implemented by Client, by Transaction, and by a reference to either. The ORM, the query builder and the admin calls all take E: Executor, so one function serves both cases: each statement committing on its own, or all of them inside a transaction.
use rasterizeddb_client::{Client, Executor, Options, Result, params};
async fn transfer<E: Executor>(db: &E, from: i64, to: i64, amount: i64) -> Result<()> {
db.exec("UPDATE account SET balance = balance - $1 WHERE id = $2", params![amount, from]).await?;
db.exec("UPDATE account SET balance = balance + $1 WHERE id = $2", params![amount, to]).await?;
Ok(())
}
#[tokio::main]
async fn main() -> Result<()> {
let client = Client::connect("unix:/run/rdb/rdb.sock", Options::default()).await?;
// Two statements, each committing on its own:
transfer(&client, 1, 2, 10).await?;
// The same two, committing together:
let tx = client.begin().await?;
transfer(&tx, 1, 2, 10).await?;
tx.commit().await?;
Ok(())
}Executor method | returns |
|---|---|
run(sql) | Rows |
query(sql, &[Param]), query_with(sql, params![…]) | Rows |
execute(sql, &[Param]), exec(sql, params![…]) | u64 rows affected |
fetch_all, fetch_one, fetch_optional, fetch_scalar | as on Client (Queries) |
Every future the trait returns is Send, so an Executor call can be awaited inside tokio::spawn. You do not implement Executor yourself.
Limits
Serializableruns asRepeatableRead; write skew is not detected.- A transaction cannot outlive its connection, and is not moved after a network failure.
- A transaction idle for the server's request timeout (30 s by default) is rolled back.
- A
COMMITlost in flight leaves the outcome unknown; the client never retries it. Client::simple_querycannot hold aBEGINacross calls; use a simple session for that.