//! PostgreSQL connection pool configuration. //! //! Reads settings from environment variables with sensible defaults. use std::env; /// PostgreSQL connection configuration, sourced from environment variables. #[derive(Debug, Clone)] pub struct DatabaseConfig { /// PostgreSQL connection URL (e.g. `postgres://user:pass@host/db`). pub url: String, /// Maximum number of connections in the pool. pub max_connections: u32, /// Minimum number of idle connections maintained. pub min_connections: u32, /// Timeout for acquiring a new connection (seconds). pub connect_timeout_secs: u64, /// Timeout for idle connections before they are closed (seconds). pub idle_timeout_secs: u64, } impl DatabaseConfig { /// Build config by reading environment variables, falling back to defaults. pub fn from_env() -> Self { Self { url: env::var("DATABASE_URL") .unwrap_or_else(|_| "postgres://localhost/imks".to_string()), max_connections: env::var("DATABASE_MAX_CONNECTIONS") .ok() .and_then(|v| v.parse().ok()) .unwrap_or(10), min_connections: env::var("DATABASE_MIN_CONNECTIONS") .ok() .and_then(|v| v.parse().ok()) .unwrap_or(2), connect_timeout_secs: env::var("DATABASE_CONNECT_TIMEOUT") .ok() .and_then(|v| v.parse().ok()) .unwrap_or(30), idle_timeout_secs: env::var("DATABASE_IDLE_TIMEOUT") .ok() .and_then(|v| v.parse().ok()) .unwrap_or(600), } } } impl Default for DatabaseConfig { fn default() -> Self { Self::from_env() } } #[cfg(test)] mod tests { use super::*; #[test] fn test_default_config_has_sane_values() { // Without env vars set, defaults should be applied. let cfg = DatabaseConfig { url: "postgres://localhost/test".to_string(), max_connections: 10, min_connections: 2, connect_timeout_secs: 30, idle_timeout_secs: 600, }; assert_eq!(cfg.max_connections, 10); assert_eq!(cfg.min_connections, 2); } }