Skip to main content

with_transaction_pg

Function with_transaction_pg 

Source
pub async fn with_transaction_pg<F, T>(pool: &PgPool, f: F) -> SqlxResult<T>
where F: for<'c> FnOnce(&'c mut Transaction<'static, Postgres>) -> BoxFuture<'c, SqlxResult<T>>,
Expand description

Execute a closure within a PostgreSQL transaction.

The closure receives &mut sqlx::Transaction; it is committed if the closure returns Ok, and rolled back if it returns Err (or dropped, which aborts server-side, if the closure panics).

with_transaction_pg(&pool, |tx| async move {
    sqlx::query("INSERT INTO users (name) VALUES ($1)")
        .bind("Alice")
        .execute(&mut **tx)
        .await?;
    Ok(())
})
.await?;