expression

SQLx: consume a bounded result stream

Stream rows and process each result without collecting a vector. This example sums a limited sequence and propagates decoding or transport errors. A stream may hold a database connection while it is active; release it before closing the pool. Streaming avoids this example’s application-side result collection but does not guarantee fixed memory use inside the database or driver. Requires an explicitly authorized disposable local PostgreSQL lab with verified TLS; see fixture README. Expected stdout (not executed): sum: 15 Common mistake: Retaining a stream while awaiting pool closure, or treating a partial stream as a complete successful result.

Formal Syntax & Structure

rust syntaxrust
while let Some(row) = rows.try_next().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_v87_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 futures_util::TryStreamExt;    let pool = lab_pool().await?;    let mut total = 0_i64;    {        let mut rows = sqlx::query_as::<_, (i32,)>("SELECT n FROM generate_series(1, 5) AS t(n) ORDER BY n LIMIT 5").fetch(&pool);        while let Some((n,)) = rows.try_next().await? { total += i64::from(n); }    }    println!("sum: {total}");    pool.close().await;    Ok(())}
Rust Reference