expression

tokio-postgres: pipeline independent queries

Concurrent polling can pipeline independent requests over one connection, reducing idle network waits. It does not make one PostgreSQL session execute both statements in parallel. Do not pipeline operations that depend on the result of earlier operations. 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): sum: 5 Common mistake: Treating a single connection as a pool or assuming server-side parallel execution.

Formal Syntax & Structure

rust syntaxrust
tokio::try_join!(client.query_one(sql1, &[]), client.query_one(sql2, &[]))?

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?;    let (a, b) = tokio::try_join!(        client.query_one("SELECT 2::integer", &[]),        client.query_one("SELECT 3::integer", &[]),    )?;    let x: i32 = a.try_get(0)?;    let y: i32 = b.try_get(0)?;    println!("sum: {}", x + y);    drop(client);    tokio::time::timeout(Duration::from_secs(5), driver).await???;    Ok(())}
Rust Reference