From 1d9533ae968b77b7048ba458e62867f9070de9f2 Mon Sep 17 00:00:00 2001 From: Sven Rabe Date: Fri, 22 May 2026 19:29:34 +0100 Subject: [PATCH] fix(postgres): enable whoami/std feature Commit 1dd526a2ed67fa763766e670c30b1ce3b152a42e bumped whoami to v2, but it seems that version now needs to have the `std` feature enabled to do anything useful. In earlier sqlx versions, connection strings like `postgresql:///dbname` correctly used the current user's name, matching psql's behavior. Now, it falls back to `anonymous`. Enabling the `std` feature fixes that. --- sqlx-postgres/Cargo.toml | 2 +- sqlx-postgres/src/options/parse.rs | 32 ++++++++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/sqlx-postgres/Cargo.toml b/sqlx-postgres/Cargo.toml index d5bf41f9b1..72fdd5ee94 100644 --- a/sqlx-postgres/Cargo.toml +++ b/sqlx-postgres/Cargo.toml @@ -64,7 +64,7 @@ num-bigint = { version = "0.4.3", optional = true } smallvec = { version = "1.13.1" } stringprep = "0.1.2" tracing = { version = "0.1.37", features = ["log"] } -whoami = { version = "2.0.2", default-features = false } +whoami = { version = "2.0.2", default-features = false, features = ["std"] } dotenvy.workspace = true thiserror.workspace = true diff --git a/sqlx-postgres/src/options/parse.rs b/sqlx-postgres/src/options/parse.rs index e911305698..12045487fd 100644 --- a/sqlx-postgres/src/options/parse.rs +++ b/sqlx-postgres/src/options/parse.rs @@ -5,6 +5,9 @@ use sqlx_core::Url; use std::net::IpAddr; use std::str::FromStr; +#[cfg(all(test, unix, not(target_arch = "wasm32")))] +use std::sync::Mutex; + impl PgConnectOptions { pub(crate) fn parse_from_url(url: &Url) -> Result { let mut options = Self::new_without_pgpass(); @@ -340,3 +343,32 @@ fn built_url_can_be_parsed() { assert!(parsed.is_ok()); } + +#[cfg(all(test, unix, not(target_arch = "wasm32")))] +struct PgUserTestGuard(Option); + +#[cfg(all(test, unix, not(target_arch = "wasm32")))] +impl Drop for PgUserTestGuard { + fn drop(&mut self) { + if let Some(old_pguser) = &self.0 { + std::env::set_var("PGUSER", old_pguser); + } else { + std::env::remove_var("PGUSER"); + } + } +} + +#[test] +#[cfg(all(unix, not(target_arch = "wasm32")))] +fn it_uses_the_os_username_when_url_omits_user() { + static ENV_LOCK: Mutex<()> = Mutex::new(()); + + let _guard = ENV_LOCK.lock().unwrap(); + let _pguser_guard = PgUserTestGuard(std::env::var_os("PGUSER")); + + std::env::remove_var("PGUSER"); + + let opts = PgConnectOptions::from_str("postgresql:///database").unwrap(); + + assert_ne!(opts.username, "anonymous"); +}