Skip to content

Commit 1d9533a

Browse files
committed
fix(postgres): enable whoami/std feature
Commit 1dd526a 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.
1 parent 75bc048 commit 1d9533a

2 files changed

Lines changed: 33 additions & 1 deletion

File tree

sqlx-postgres/Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ num-bigint = { version = "0.4.3", optional = true }
6464
smallvec = { version = "1.13.1" }
6565
stringprep = "0.1.2"
6666
tracing = { version = "0.1.37", features = ["log"] }
67-
whoami = { version = "2.0.2", default-features = false }
67+
whoami = { version = "2.0.2", default-features = false, features = ["std"] }
6868

6969
dotenvy.workspace = true
7070
thiserror.workspace = true

sqlx-postgres/src/options/parse.rs

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,9 @@ use sqlx_core::Url;
55
use std::net::IpAddr;
66
use std::str::FromStr;
77

8+
#[cfg(all(test, unix, not(target_arch = "wasm32")))]
9+
use std::sync::Mutex;
10+
811
impl PgConnectOptions {
912
pub(crate) fn parse_from_url(url: &Url) -> Result<Self, Error> {
1013
let mut options = Self::new_without_pgpass();
@@ -340,3 +343,32 @@ fn built_url_can_be_parsed() {
340343

341344
assert!(parsed.is_ok());
342345
}
346+
347+
#[cfg(all(test, unix, not(target_arch = "wasm32")))]
348+
struct PgUserTestGuard(Option<std::ffi::OsString>);
349+
350+
#[cfg(all(test, unix, not(target_arch = "wasm32")))]
351+
impl Drop for PgUserTestGuard {
352+
fn drop(&mut self) {
353+
if let Some(old_pguser) = &self.0 {
354+
std::env::set_var("PGUSER", old_pguser);
355+
} else {
356+
std::env::remove_var("PGUSER");
357+
}
358+
}
359+
}
360+
361+
#[test]
362+
#[cfg(all(unix, not(target_arch = "wasm32")))]
363+
fn it_uses_the_os_username_when_url_omits_user() {
364+
static ENV_LOCK: Mutex<()> = Mutex::new(());
365+
366+
let _guard = ENV_LOCK.lock().unwrap();
367+
let _pguser_guard = PgUserTestGuard(std::env::var_os("PGUSER"));
368+
369+
std::env::remove_var("PGUSER");
370+
371+
let opts = PgConnectOptions::from_str("postgresql:///database").unwrap();
372+
373+
assert_ne!(opts.username, "anonymous");
374+
}

0 commit comments

Comments
 (0)