2021-04-04 12:30:31 +00:00
|
|
|
use sqlx::postgres::{PgPool, PgPoolOptions};
|
|
|
|
use std::env;
|
2022-09-30 12:38:33 +00:00
|
|
|
use time::ext::NumericalStdDuration;
|
2021-04-04 12:30:31 +00:00
|
|
|
|
|
|
|
pub async fn setup_db() -> PgPool {
|
|
|
|
let conn_url = &get_db_url();
|
|
|
|
log::info!("Using Connection string {}", conn_url);
|
|
|
|
|
|
|
|
let pool = PgPoolOptions::new()
|
|
|
|
.max_connections(5)
|
2022-09-30 12:38:33 +00:00
|
|
|
.acquire_timeout(5.std_seconds())
|
2021-04-04 12:30:31 +00:00
|
|
|
.connect(conn_url)
|
|
|
|
.await
|
|
|
|
.expect("could not create db pool");
|
|
|
|
|
2022-02-26 23:34:57 +00:00
|
|
|
for query in include_str!("../init-db.sql").split_inclusive(';') {
|
2021-04-04 12:30:31 +00:00
|
|
|
sqlx::query(query)
|
|
|
|
.execute(&pool)
|
|
|
|
.await
|
|
|
|
.expect("could not initialize database schema");
|
|
|
|
}
|
|
|
|
|
|
|
|
pool
|
|
|
|
}
|
|
|
|
|
|
|
|
fn get_db_url() -> String {
|
|
|
|
if let Ok(database_url) = env::var("DATABASE_URL") {
|
|
|
|
return database_url;
|
|
|
|
}
|
|
|
|
|
|
|
|
let auth = if let Ok(user) = env::var("DATABASE_USER") {
|
|
|
|
if let Ok(pass) = env::var("DATABASE_PASS") {
|
2022-10-07 13:52:12 +00:00
|
|
|
format!("{user}:{pass}@")
|
2021-04-04 12:30:31 +00:00
|
|
|
} else {
|
2022-10-07 13:52:12 +00:00
|
|
|
format!("{user}@")
|
2021-04-04 12:30:31 +00:00
|
|
|
}
|
|
|
|
} else {
|
|
|
|
String::new()
|
|
|
|
};
|
|
|
|
|
2022-10-07 13:52:12 +00:00
|
|
|
let host = env::var("DATABASE_HOST").unwrap_or_else(|_| "localhost".to_string());
|
|
|
|
let name = env::var("DATABASE_NAME").unwrap_or_else(|_| "datatrash".to_string());
|
|
|
|
format!("postgresql://{auth}{host}/{name}")
|
2021-04-04 12:30:31 +00:00
|
|
|
}
|