From b512674da9b77048118350940671d6db0da634a7 Mon Sep 17 00:00:00 2001 From: Fionera Date: Sun, 2 Aug 2020 03:08:07 +0200 Subject: [PATCH] Add Connection string builder --- src/main.rs | 29 ++++++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/src/main.rs b/src/main.rs index e071a12..b7d29ad 100644 --- a/src/main.rs +++ b/src/main.rs @@ -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");