use anyhow::anyhow;
use tokio_postgres::{Client, NoTls};
pub async fn connect(database_url: &str) -> anyhow::Result<Client> {
let (client, connection) = tokio_postgres::connect(database_url, NoTls)
.await
.map_err(|e| {
anyhow!(
"无法连接 PostgreSQL({}):{e}",
mask_password(database_url)
)
})?;
tokio::spawn(async move {
if let Err(e) = connection.await {
eprintln!("PostgreSQL 连接异常: {e}");
}
});
Ok(client)
}
fn mask_password(url: &str) -> String {
let Some(scheme_end) = url.find("://") else {
return url.to_string();
};
let rest = &url[scheme_end + 3..];
let Some(at) = rest.rfind('@') else {
return url.to_string();
};
let userinfo = &rest[..at];
let Some(colon) = userinfo.rfind(':') else {
return url.to_string();
};
format!(
"{}://{}:***@{}",
&url[..scheme_end],
&userinfo[..colon],
&rest[at + 1..]
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn 密码脱敏() {
assert_eq!(
mask_password("postgres://alice:s3cret@db.local:5432/cip"),
"postgres://alice:***@db.local:5432/cip"
);
assert_eq!(
mask_password("postgres://alice@db.local/cip"),
"postgres://alice@db.local/cip"
);
}
}