Skip to content

Commit dc088b3

Browse files
committed
Enable loading pgpass from custom paths
1 parent e21ba02 commit dc088b3

File tree

2 files changed

+21
-11
lines changed

2 files changed

+21
-11
lines changed

sqlx-postgres/src/options/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,7 @@ impl PgConnectOptions {
100100
self.port,
101101
&self.username,
102102
self.database.as_deref(),
103+
&[] as &[&Path],
103104
);
104105
}
105106

sqlx-postgres/src/options/pgpass.rs

Lines changed: 20 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -4,23 +4,32 @@ use std::fs::File;
44
use std::io::{BufRead, BufReader};
55
use std::path::{Path, PathBuf};
66

7-
/// try to load a password from the various pgpass file locations
7+
/// Try to load a password from the various pgpass file locations.
8+
///
9+
/// Loading is attempted in the following order:
10+
/// 1. Path given via the `PGPASSFILE` environment variable.
11+
/// 2. Paths given via custom_paths.
12+
/// 3. Default path (`~/.pgpass` on Linux and `%APPDATA%/postgres/pgpass.conf`
13+
/// on Windows)
814
pub fn load_password(
915
host: &str,
1016
port: u16,
1117
username: &str,
1218
database: Option<&str>,
19+
custom_paths: &[impl AsRef<Path>],
1320
) -> Option<String> {
14-
let custom_file = var_os("PGPASSFILE");
15-
if let Some(file) = custom_file {
16-
if let Some(password) =
17-
load_password_from_file(&PathBuf::from(file), host, port, username, database)
18-
{
19-
return Some(password);
20-
}
21-
}
22-
23-
load_password_from_file(&default_path()?, host, port, username, database)
21+
let env_path = var_os("PGPASSFILE").map(PathBuf::from);
22+
let default_path = default_path();
23+
24+
let path_iter = env_path
25+
.as_deref()
26+
.into_iter()
27+
.chain(custom_paths.iter().map(AsRef::as_ref))
28+
.chain(default_path.as_deref());
29+
30+
path_iter
31+
.filter_map(|path| load_password_from_file(path, host, port, username, database))
32+
.next()
2433
}
2534

2635
#[cfg(not(target_os = "windows"))]

0 commit comments

Comments
 (0)