expression
tokio-postgres: declare parameter types
A prepared statement can specify database parameter types explicitly. INT4 corresponds to a PostgreSQL integer; the Rust value must be encodable as that database type. A typed parameter is still validated at runtime. 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): total: 7 Common mistake: Confusing explicit database parameter types with compile-time SQL checking.
Formal Syntax & Structure
rust syntaxrust
client.prepare_typed(sql, &[Type::INT4]).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?; use tokio_postgres::types::Type; let stmt = client.prepare_typed("SELECT $1 + 2 AS total", &[Type::INT4]).await?; let row = client.query_one(&stmt, &[&5_i32]).await?; let total: i32 = row.try_get("total")?; println!("total: {total}"); drop(stmt); drop(client); tokio::time::timeout(Duration::from_secs(5), driver).await???; Ok(())}