expression

SQLx: recover from an aborted transaction

A PostgreSQL statement error normally leaves the enclosing transaction in a failed state. Continuing with an ordinary statement produces 25P02 until the transaction is reverted (or recovery uses an appropriate existing savepoint). This fixture deliberately divides by zero, then confirms the failed state and uses a fresh statement after rollback. Requires an explicitly authorized disposable local PostgreSQL lab with verified TLS; see fixture README. Expected stdout (not executed): recovered: 1 Common mistake: Retrying just the failed SQL command inside an already aborted transaction.

Formal Syntax & Structure

rust syntaxrust
ROLLBACK; // or tx.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>> {    let pool = lab_pool().await?;    let mut conn = pool.acquire().await?;    use sqlx::Acquire;    let mut tx = conn.begin().await?;    let first = sqlx::query("SELECT 1 / 0").execute(&mut *tx).await;    assert!(matches!(first, Err(sqlx::Error::Database(ref d)) if d.code().as_deref() == Some("22012")));    let second = sqlx::query("SELECT 1").execute(&mut *tx).await;    assert!(matches!(second, Err(sqlx::Error::Database(ref d)) if d.code().as_deref() == Some("25P02")));    tx.rollback().await?;    let value: i32 = sqlx::query_scalar("SELECT 1::integer").fetch_one(&mut *conn).await?;    println!("recovered: {value}");    drop(conn);    pool.close().await;    Ok(())}
Rust Reference