expression
tokio-postgres: roll back temporary changes
A transaction borrows its client mutably; all dependent statements run through that transaction. The example creates a temporary table before starting the transaction, writes within it, and explicitly rolls back. Temporary data is session-local and vanishes when the connection closes. Requires an explicitly authorized disposable Unix-socket PostgreSQL lab; see fixture README. NoTls is restricted to that isolated local lab, never remote connections. Expected stdout (not executed): rows after rollback: 0 Common mistake: Reporting a write as durable before commit succeeds.
Formal Syntax & Structure
rust syntaxrust
let txn = client.transaction().await?; txn.rollback().await?;Working Example
Example Snippetrust
use std::{error::Error, time::Duration};use tokio_postgres::{Client, Config, NoTls, config::SslMode};type LabResult<T> = Result<T, Box<dyn Error>>;// Unix only: a private, disposable PostgreSQL cluster; no TCP fallback.async fn lab() -> LabResult<(Client, tokio::task::JoinHandle<Result<(), tokio_postgres::Error>>)> { if !matches!(std::env::var("BM_TOKIO_PG_LAB_OPT_IN").as_deref(), Ok("yes")) { return Err("disposable lab opt-in required".into()); } let mut config = Config::new(); config.host_path("/tmp/bm-v92-pg-socket") .port(55432).user("bm_learner").dbname("bm_tokio_pg_lab") .ssl_mode(SslMode::Disable).connect_timeout(Duration::from_secs(3)); let (client, connection) = tokio::time::timeout(Duration::from_secs(5), config.connect(NoTls)).await??; let driver = tokio::spawn(connection); Ok((client, driver))}#[tokio::main(flavor = "current_thread")]async fn main() -> LabResult<()> { let (mut client, driver) = lab().await?; client.batch_execute("CREATE TEMP TABLE sample_v92 (id integer)").await?; let txn = client.transaction().await?; txn.execute("INSERT INTO sample_v92 VALUES ($1)", &[&1_i32]).await?; txn.rollback().await?; let row = client.query_one("SELECT count(*) FROM sample_v92", &[]).await?; let count: i64 = row.try_get(0)?; println!("rows after rollback: {count}"); drop(client); tokio::time::timeout(Duration::from_secs(5), driver).await???; Ok(())}