expression

SQLx: nested transactions and savepoints

A nested SQLx transaction on PostgreSQL uses a savepoint. Reverting the nested scope removes its work but leaves the earlier outer work available to commit. Committing a nested transaction does not make those changes durable independently of the outer one. Requires an explicitly authorized disposable local PostgreSQL lab with verified TLS; see fixture README. Expected stdout (not executed): rows: 1 Common mistake: Calling an inner commit an independent database commit.

Formal Syntax & Structure

rust syntaxrust
let mut inner = outer.begin().await?; inner.rollback().await?;

Working Example

Example Snippetrust
async fn lab_pool() -> Result<sqlx::PgPool, Box<dyn std::error::Error>> {    use sqlx::postgres::{PgConnectOptions, PgPoolOptions, PgSslMode};    use std::time::Duration;    if std::env::var("BM_SQLX_LAB_OPT_IN").as_deref() != Ok("yes") {        return Err("disposable PostgreSQL lab required".into());    }    // Reject ambient PostgreSQL settings to keep the target explicit.    if std::env::vars_os().any(|(key, _)| key.to_string_lossy().to_ascii_uppercase().starts_with("PG")) {        return Err("remove ambient PG* environment settings".into());    }    let password = std::env::var("BM_SQLX_LAB_PASSWORD")?;    let ca = std::env::var("BM_SQLX_LAB_CA")?;    let options = PgConnectOptions::new_without_pgpass()        .host("127.0.0.1").port(55432)        .username("bm_learner").database("bm_sqlx_v86_lab")        .password(&password).ssl_mode(PgSslMode::VerifyFull)        .ssl_root_cert(ca);    let pool = PgPoolOptions::new().max_connections(2)        .acquire_timeout(Duration::from_secs(3))        .connect_with(options).await?;    Ok(pool)}
#[tokio::main(flavor = "current_thread")]async fn main() -> Result<(), Box<dyn std::error::Error>> {    use sqlx::Acquire;    let pool = lab_pool().await?;    let mut conn = pool.acquire().await?;    sqlx::query("CREATE TEMP TABLE bm_items (id integer PRIMARY KEY)")        .execute(&mut *conn).await?;    let mut outer = conn.begin().await?;    sqlx::query("INSERT INTO bm_items VALUES (1)")        .execute(&mut *outer).await?;    let mut inner = outer.begin().await?;    sqlx::query("INSERT INTO bm_items VALUES (2)")        .execute(&mut *inner).await?;    inner.rollback().await?;    outer.commit().await?;    let count: i64 = sqlx::query_scalar("SELECT count(*) FROM bm_items")        .fetch_one(&mut *conn).await?;    println!("rows: {count}");    drop(conn);    pool.close().await;    Ok(())}
Rust Reference