use std::collections::HashMap;
use std::sync::{Mutex, OnceLock};
use bb8::Pool;
use bb8_tiberius::ConnectionManager;
pub type SqlPool = Pool<ConnectionManager>;
pub async fn cached_pool(
cache_key: &str,
config: tiberius::Config,
max_size: u32,
) -> anyhow::Result<SqlPool> {
static POOLS: OnceLock<Mutex<HashMap<String, SqlPool>>> = OnceLock::new();
let pools = POOLS.get_or_init(|| Mutex::new(HashMap::new()));
if let Some(pool) = pools.lock().unwrap().get(cache_key) {
return Ok(pool.clone());
}
let manager = ConnectionManager::new(config);
let pool = Pool::builder().max_size(max_size).build(manager).await?;
let mut pools = pools.lock().unwrap();
Ok(pools.entry(cache_key.to_string()).or_insert(pool).clone())
}
#[cfg(test)]
mod tests {
use super::*;
fn unroutable_config() -> tiberius::Config {
let mut config = tiberius::Config::new();
config.host("192.0.2.1");
config.port(1433);
config
}
#[tokio::test]
async fn cached_pool_serves_a_cache_hit_on_the_same_key_without_erroring() {
let key = "cached_pool_serves_a_cache_hit_on_the_same_key_without_erroring";
cached_pool(key, unroutable_config(), 5).await.unwrap();
cached_pool(key, unroutable_config(), 5).await.unwrap();
}
#[tokio::test]
async fn cached_pool_builds_a_separate_pool_for_a_distinct_key() {
cached_pool(
"cached_pool_builds_a_separate_pool_for_a_distinct_key_a",
unroutable_config(),
5,
)
.await
.unwrap();
cached_pool(
"cached_pool_builds_a_separate_pool_for_a_distinct_key_b",
unroutable_config(),
5,
)
.await
.unwrap();
}
}