use super::SerializerError;
use reinhardt_db::pool::{ConnectionPool, PoolConfig};
use std::sync::{Arc, RwLock};
pub struct ConnectionPoolManager {
pool: Option<Arc<ConnectionPool<sqlx::Postgres>>>,
}
impl std::fmt::Debug for ConnectionPoolManager {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ConnectionPoolManager")
.field("pool", &"<ConnectionPool>")
.finish()
}
}
impl ConnectionPoolManager {
pub fn new() -> Self {
Self { pool: None }
}
fn instance() -> &'static RwLock<ConnectionPoolManager> {
static INSTANCE: once_cell::sync::Lazy<RwLock<ConnectionPoolManager>> =
once_cell::sync::Lazy::new(|| RwLock::new(ConnectionPoolManager::new()));
&INSTANCE
}
pub fn set_pool(pool: Arc<ConnectionPool<sqlx::Postgres>>) {
let instance = Self::instance();
let mut manager = instance.write().expect("Failed to acquire write lock");
manager.pool = Some(pool);
}
pub fn get_pool() -> Option<Arc<ConnectionPool<sqlx::Postgres>>> {
let instance = Self::instance();
let manager = instance.read().expect("Failed to acquire read lock");
manager.pool.clone()
}
pub async fn acquire()
-> Result<reinhardt_db::pool::PooledConnection<sqlx::Postgres>, SerializerError> {
let pool = Self::get_pool().ok_or_else(|| SerializerError::Other {
message: "Connection pool not initialized".to_string(),
})?;
pool.acquire().await.map_err(|e| SerializerError::Other {
message: format!("Failed to acquire connection from pool: {}", e),
})
}
pub fn is_initialized() -> bool {
Self::get_pool().is_some()
}
pub fn clear() {
let instance = Self::instance();
let mut manager = instance.write().expect("Failed to acquire write lock");
manager.pool = None;
}
}
impl Default for ConnectionPoolManager {
fn default() -> Self {
Self::new()
}
}
pub fn default_pool_config() -> PoolConfig {
PoolConfig::default()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_pool_manager_not_initialized() {
ConnectionPoolManager::clear();
assert!(!ConnectionPoolManager::is_initialized());
}
#[test]
fn test_default_pool_config() {
let config = default_pool_config();
assert_eq!(config.max_connections, 10);
assert_eq!(config.min_connections, 1);
}
#[test]
fn test_pool_manager_creation() {
let manager = ConnectionPoolManager::new();
let _ = manager; }
#[test]
fn test_pool_manager_default() {
let manager = ConnectionPoolManager::default();
let _ = manager;
}
}