Using unsafe to set a DB pool reference

static mut DB_POOL: Mutex<Pool<PostgresConnectionManager<NoTls>>> = ?????;
    unsafe {
        DB_POOL = Mutex::from(bb8::Pool::builder()
            .max_size(20)
            .build(
                PostgresConnectionManager::new_from_stringlike(
                    format!(
                        "postgresql://{}:{}@{}:{}/{}",
                        "username", "password", "localhost", "5432", "dbname",
                    ),
                    bb8_postgres::tokio_postgres::NoTls,
                )
                    .unwrap(),
            )
.await
            .unwrap());
    }

I'm trying to use this method to get a static reference to my db credentials so I can use them anywhere without hassle of passing them around to every function in the chain.

  1. I'm not sure what default value to give the initial static variable
  2. Is this safe as long as I use a mutex... do I even need a mutex since I believe I'm just reading the value after it's initial assignment?

Never use static mut. To initialize global variable externally use OnceCell.

Thanks for the advice! This looks exactly like what I need.

Could I bug you to write me the code I need based on my example? Otherwise, I will probably spend my whole night tinkering with the unfamiliar syntax to get it right.

Since your initialization step is asynchronous, you need the OnceCell in Tokio. Something like this should do it:

use tokio::sync::OnceCell;

static POOL: OnceCell<Pool<PostgresConnectionManager<NoTls>>> = OnceCell::new();

async fn get_pool() -> &'static Pool<PostgresConnectionManager<NoTls>> {
    POOL.get_or_init(|| {
        bb8::Pool::builder()
            .max_size(20)
            .build(
                PostgresConnectionManager::new_from_stringlike(
                    format!(
                        "postgresql://{}:{}@{}:{}/{}",
                        "username", "password", "localhost", "5432", "dbname",
                    ),
                    bb8_postgres::tokio_postgres::NoTls,
                )
                .unwrap(),
            )
            .await
            .unwrap()
    })
    .await
}
1 Like

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.