Add Connection string builder

This commit is contained in:
Fionera 2020-08-02 03:08:07 +02:00
parent 9f1e1e3818
commit b512674da9
1 changed files with 28 additions and 1 deletions

View File

@ -130,11 +130,38 @@ async fn download(
}
}
fn get_db_url() -> String {
return env::var("DATABASE_URL").unwrap_or_else(|_| {
let mut url = "postgresql://".to_string();
let user = env::var("DATABASE_USER").unwrap_or_default();
if !user.is_empty() {
url += user.as_str();
let pass = env::var("DATABASE_PASS").unwrap_or_default();
if !pass.is_empty() {
url += ":";
url += pass.as_str();
}
url += "@";
}
url += env::var("DATABASE_HOST").unwrap_or_else(|_| "localhost".to_string()).as_str();
url += "/";
url += env::var("DATABASE_NAME").unwrap_or_else(|_| "datatrash".to_string()).as_str();
url.to_string()
});
}
async fn setup_db() -> PgPool {
let conn_url = &get_db_url();
log::info!("Using Connection string {}", conn_url);
let pool = PgPool::builder()
.max_size(5)
.connect_timeout(std::time::Duration::from_secs(5))
.build(&env::var("DATABASE_URL").unwrap_or_else(|_| "postgresql://localhost".to_owned()))
.build(conn_url)
.await
.expect("could not create db pool");