use crate::error_handler::CustomError; use diesel::pg::PgConnection; use diesel::r2d2::ConnectionManager; use lazy_static::lazy_static; use log::{error, info}; use r2d2; use std::env; type Pool = r2d2::Pool>; pub type DbConnection = r2d2::PooledConnection>; diesel_migrations::embed_migrations!(); lazy_static! { static ref POOL: Pool = { let db_url = env::var("DATABASE_URL").expect("Database url not set"); let manager = ConnectionManager::::new(db_url); Pool::new(manager).expect("Failed to create db pool") }; } pub fn init() { lazy_static::initialize(&POOL); let conn = connection().expect("Failed to get db connection"); match embedded_migrations::run(&conn) { Ok(_) => info!("Database initialized"), Err(err) => error!("Failed to initialize database; {}", err), }; } pub fn connection() -> Result { POOL.get() .map_err(|e| CustomError::new(500, format!("Failed getting db connection: {}", e))) }