use sqlx::PgPool; use super::DbContext; impl DbContext { pub(super) async fn get_pg_connection(&mut self) -> Option<&PgPool> { if self.pg_pool.is_some() { return self.pg_pool.as_ref(); } self.pg_pool = None; self.pg_connect().await; self.pg_pool.as_ref() } pub(super) async fn pg_connect(&mut self) -> () { // Don't connect if already connected if let Some(pool) = self.pg_pool.as_ref() { if !pool.is_closed() { return; } } let db_url = match std::env::var("DATABASE_URL") { Ok(url) => url, Err(_) => { panic!("DATABASE_URL environment variable is missing, cannot connect to database") } }; self.pg_pool = match PgPool::connect(&db_url).await { Ok(x) => Some(x), Err(e) => { log::error!("Failed to connect to database at DATABASE_URL: {e}"); log::warn!( "Requests requiring postgres will request a connection retry, but may fail." ); return; } }; log::info!("Successfully connected to Postgres instance"); } }