Named connection pool using bb8

Hello,

I'm building an app which will have multiple types of db connections (postgres no tls, postgres with tls, redis no tls>, redis with tls). This will be user defined from a config file. Each of the connection types can have N number of instances. Each of those instances can be referenced by a name. I'm trying to create a pool of each instances.

Eg.

Name = CustomersDB - Type - Postgres No Tls
Name = UsersDB - Type - Postgres No Tls
Name = PersonDB - Type - Postgres TLS
Name = UserCache - Type - Redis No TLS

Here is what I have so far for implementation

pool.rs

use core::panic;
use std::collections::HashMap;

use bb8_postgres::PostgresConnectionManager;
use serde_json::Value;
use tokio_postgres::NoTls;

use bb8::Pool;

pub struct AnyConnection {
    name: String,
    details: HashMap<String, Value>,
    secure: bool
}

impl AnyConnection {

    pub fn new(name: String, details: HashMap<String, Value>, secure: bool) -> Self {
        return AnyConnection { name: name, details: details, secure: secure };
    }
}


#[salvo::async_trait]
pub trait PostgresPool {
    async fn make_unsecure(&self) -> Pool<PostgresConnectionManager<NoTls>>;
}

#[salvo::async_trait]
impl PostgresPool for AnyConnection {
    async fn make_unsecure(&self) -> Pool<PostgresConnectionManager<NoTls>> {

        let manager = PostgresConnectionManager::new_from_stringlike(
            &self.details.get("DATABASE_URL").unwrap().to_string(),
            tokio_postgres::NoTls,
        );
    
        let conn = match manager {
            Ok(m) => m,
            Err(err) => panic!("Error opening a connection for: {} with error: {:?}", &self.name, err.to_string())
        };        


        let pool = match Pool::builder().max_size(5).build(conn).await {
            Ok(p) => p,
            Err(err) => panic!("Error creating pool for: {} with error: {:?}", &self.name, err.to_string())
        };
    
        return pool;
    }
}

main.rs

    let mut conns: HashMap<String, AnyConnection> = HashMap::new();

    let mut details: HashMap<String, Value> = HashMap::new();
    details.insert("DATABASE_URL".to_string(), Value::String("postgresql://localhost:5432/customers?user=postgres&password=postgres".to_string()));


    let customers_db: AnyConnection = AnyConnection::new("customers_db".to_string(), details, false);        

    let pg = PostgresPool::make_unsecure(&customers_db).await;

How and where do I store the conns hashmap which has reference to all the connection pools which I can access from my other parts of the app to retrieve and return connections?

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.