You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

26 line
865 B

  1. use diesel::r2d2::{self, ConnectionManager};
  2. use diesel::PgConnection;
  3. use std::env;
  4. use dotenvy::dotenv;
  5. pub type DbPool = r2d2::Pool<ConnectionManager<PgConnection>>;
  6. pub type DbConn = r2d2::PooledConnection<ConnectionManager<PgConnection>>;
  7. pub fn establish_connection() -> Result<DbPool, Box<dyn std::error::Error>> {
  8. dotenv().ok();
  9. let database_url = env::var("DATABASE_URL")
  10. .map_err(|_| "DATABASE_URL must be set")?;
  11. let manager = ConnectionManager::<PgConnection>::new(database_url);
  12. let pool = r2d2::Pool::builder()
  13. .build(manager)
  14. .map_err(|e| format!("Failed to create pool: {}", e))?;
  15. Ok(pool)
  16. }
  17. pub fn get_connection() -> Result<DbConn, Box<dyn std::error::Error>> {
  18. let pool = establish_connection()?;
  19. pool.get().map_err(|e| -> Box<dyn std::error::Error> { Box::new(e) })
  20. }