expression
tokio-postgres: decode nullable columns
Decode SQL NULL into Option rather than using a non-nullable String. try_get returns a decoding or column-access error instead of panicking. An existing row with a NULL column is different from no row. 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): id: 7; null: true; bad column: true Common mistake: Using get with unchecked column names or incompatible types.
Formal Syntax & Structure
rust syntaxrust
let value: Option<String> = row.try_get("label")?;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 row = client.query_one("SELECT NULL::text AS label, 7::integer AS id", &[]).await?; let label: Option<String> = row.try_get("label")?; let id: i32 = row.try_get("id")?; let bad: Result<i32, _> = row.try_get("missing"); println!("id: {id}; null: {}; bad column: {}", label.is_none(), bad.is_err()); drop(client); tokio::time::timeout(Duration::from_secs(5), driver).await???; Ok(())}