Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Transactions

Every CRUD method and Query::all is generic over sqlx::Acquire<'c, Database = sqlx::Postgres>. Both &PgPool and &mut Transaction<'_, Postgres> satisfy that bound, so the same call works in either context.

Basic pattern

#![allow(unused)]
fn main() {
let mut tx = pool.begin().await?;

let user = User::create(&mut tx, UserCreate {
    name: "Ali Khan".into(),
    email: "ali@example.com".into(),
    age: 28,
    bio: None,
}).await?;

let post = Post::create(&mut tx, PostCreate {
    title: "First post".into(),
    content: None,
    published: false,
    view_count: 0,
    user_id: user.id,
}).await?;

User::update(&mut tx, user.id, UserUpdate {
    bio: Some(Some("Now with a post".into())),
    name: None,
    email: None,
    age: None,
    created_at: None,
}).await?;

tx.commit().await?;
}

Note &mut tx, not &tx.

Rollback

Explicit:

#![allow(unused)]
fn main() {
tx.rollback().await?;
}

Or implicit — dropping a Transaction without committing rolls it back. That means the ? operator gives you rollback for free:

#![allow(unused)]
fn main() {
async fn seed(pool: &PgPool) -> Result<(), Box<dyn std::error::Error>> {
    let mut tx = pool.begin().await?;
    User::create(&mut tx, a).await?;   // any error → early return → tx dropped → rollback
    Post::create(&mut tx, b).await?;
    tx.commit().await?;
    Ok(())
}
}

This is the idiomatic way to make a multi-step operation atomic.

Reads inside a transaction

#![allow(unused)]
fn main() {
let mut tx = pool.begin().await?;

let users = User::find()
    .where_(User::age.gte(18))
    .all(&mut tx).await?;               // ✅ works

let with_posts = User::find()
    .with(User::posts)
    .all(&mut tx).await?;               // ✅ eager loading works too

tx.commit().await?;
}

Eager loading runs on the same connection as the parent query, so relation reads see your uncommitted writes. No surprise consistency gaps.

⚠️ Two methods that don’t work in a transaction

MethodSignatureIn a tx?
countcount(self, db: &PgPool)❌
fetch_all::<M>fetch_all<M>(self, db: &PgPool)❌

They take a concrete &PgPool rather than impl Acquire. Calling them with &mut tx won’t compile.

Workarounds:

#![allow(unused)]
fn main() {
// instead of count() inside a tx — read and count in Rust
let n = User::find().where_(cond).all(&mut tx).await?.len();

// instead of fetch_all() inside a tx — use sqlx directly on the transaction
let rows: Vec<(String, i64)> = sqlx::query_as(
    "SELECT name, COUNT(*) FROM users GROUP BY name"
)
.fetch_all(&mut *tx).await?;
}

Making these two generic over Acquire is a small change and is on the roadmap.

What’s covered by tests

The runtime test suite exercises, inside transactions: queries, create, update, delete, create_many, update_many, delete_many, and relation loading.

Isolation level

Zyvor doesn’t set one — you get PostgreSQL’s default (READ COMMITTED). If you need something stronger, configure it on the connection before starting your work, or execute SET TRANSACTION ISOLATION LEVEL ... as the first statement in the transaction.