ignis_db/connection/
mod.rs1use crate::config::IgnisConfig;
7use crate::exec::transaction::TransactionManager;
8use anyhow::{Context, Result};
9use sqlx::postgres::{PgConnectOptions, PgPool, PgPoolOptions};
10use std::str::FromStr;
11use std::sync::Arc;
12use std::time::Duration;
13
14#[derive(Debug)]
16pub struct ConnectionManager {
17 pool: PgPool,
19 transaction_manager: Arc<TransactionManager>,
21 config: IgnisConfig,
23}
24
25#[derive(Debug, Clone)]
27pub struct PoolStats {
28 pub total_connections: u32,
30 pub active_connections: u32,
32 pub idle_connections: u32,
34 pub max_connections: u32,
36 pub min_connections: u32,
38}
39
40impl ConnectionManager {
41 pub async fn from_config(config: IgnisConfig) -> Result<Self> {
43 config.validate()?;
45
46 let pool = Self::create_pool(&config).await?;
48
49 let transaction_manager = Arc::new(TransactionManager::new(
51 pool.clone(),
52 config.transaction.clone(),
53 ));
54
55 Ok(Self {
56 pool,
57 transaction_manager,
58 config,
59 })
60 }
61
62 pub async fn new_default() -> Result<Self> {
64 let config = IgnisConfig::default();
65 Self::from_config(config).await
66 }
67
68 pub async fn from_env() -> Result<Self> {
70 let config = IgnisConfig::from_env()?;
71 Self::from_config(config).await
72 }
73
74 pub async fn from_yaml_file(path: &str) -> Result<Self> {
76 let config = IgnisConfig::from_yaml_file(path)?;
77 Self::from_config(config).await
78 }
79
80 pub fn pool(&self) -> &PgPool {
82 &self.pool
83 }
84
85 pub fn transaction_manager(&self) -> &Arc<TransactionManager> {
87 &self.transaction_manager
88 }
89
90 pub fn config(&self) -> &IgnisConfig {
92 &self.config
93 }
94
95 pub async fn health_check(&self) -> Result<bool> {
97 match sqlx::query("SELECT 1").fetch_one(&self.pool).await {
98 Ok(_) => Ok(true),
99 Err(_) => Ok(false),
100 }
101 }
102
103 pub async fn get_pool_stats(&self) -> Result<PoolStats> {
105 let pool_size = self.pool.size();
107 let max_size = self.config.pool.max_connections.unwrap_or(10) as u32;
108 let min_size = self.config.pool.min_connections.unwrap_or(1) as u32;
109
110 let idle_connections = self.pool.num_idle() as u32;
113 let active_connections = (pool_size as u32).saturating_sub(idle_connections);
114
115 Ok(PoolStats {
116 total_connections: pool_size as u32,
117 active_connections,
118 idle_connections,
119 max_connections: max_size,
120 min_connections: min_size,
121 })
122 }
123
124 pub async fn close(&self) -> Result<()> {
126 self.pool.close().await;
127 Ok(())
128 }
129
130 pub async fn execute_query(&self, query: &str) -> Result<Vec<sqlx::postgres::PgRow>> {
132 let rows = sqlx::query(query)
133 .fetch_all(&self.pool)
134 .await
135 .with_context(|| format!("Failed to execute query: {}", query))?;
136 Ok(rows)
137 }
138
139 pub async fn execute_query_one(&self, query: &str) -> Result<Option<sqlx::postgres::PgRow>> {
141 let row = sqlx::query(query)
142 .fetch_optional(&self.pool)
143 .await
144 .with_context(|| format!("Failed to execute query: {}", query))?;
145 Ok(row)
146 }
147
148 pub async fn execute_command(&self, query: &str) -> Result<u64> {
150 let result = sqlx::query(query)
151 .execute(&self.pool)
152 .await
153 .with_context(|| format!("Failed to execute command: {}", query))?;
154 Ok(result.rows_affected())
155 }
156
157 pub async fn benchmark_pool(&self, concurrent_queries: usize) -> Result<PoolBenchmarkResult> {
159 use std::time::Instant;
160 use tokio::sync::Semaphore;
161
162 let start = Instant::now();
163 let semaphore = Arc::new(Semaphore::new(concurrent_queries));
164 let mut handles = Vec::new();
165
166 for i in 0..concurrent_queries {
167 let pool = self.pool.clone();
168 let permit = semaphore.clone().acquire_owned().await.unwrap();
169
170 let handle = tokio::spawn(async move {
171 let _permit = permit;
172 let query_start = Instant::now();
173 let result = sqlx::query("SELECT $1::int as test_value")
174 .bind(i as i32)
175 .fetch_one(&pool)
176 .await;
177 let query_duration = query_start.elapsed();
178 (result.is_ok(), query_duration)
179 });
180
181 handles.push(handle);
182 }
183
184 let mut successful_queries = 0;
185 let mut total_query_time = Duration::ZERO;
186 let mut min_query_time = Duration::from_secs(u64::MAX);
187 let mut max_query_time = Duration::ZERO;
188
189 for handle in handles {
190 let (success, duration) = handle.await.unwrap();
191 if success {
192 successful_queries += 1;
193 total_query_time += duration;
194 min_query_time = min_query_time.min(duration);
195 max_query_time = max_query_time.max(duration);
196 }
197 }
198
199 let total_duration = start.elapsed();
200
201 Ok(PoolBenchmarkResult {
202 total_queries: concurrent_queries,
203 successful_queries,
204 failed_queries: concurrent_queries - successful_queries,
205 total_duration,
206 average_query_time: if successful_queries > 0 {
207 total_query_time / successful_queries as u32
208 } else {
209 Duration::ZERO
210 },
211 min_query_time: if successful_queries > 0 {
212 min_query_time
213 } else {
214 Duration::ZERO
215 },
216 max_query_time,
217 queries_per_second: if total_duration.as_secs_f64() > 0.0 {
218 successful_queries as f64 / total_duration.as_secs_f64()
219 } else {
220 0.0
221 },
222 })
223 }
224
225 pub async fn start_health_monitor(&self, interval: Duration) -> Result<()> {
227 let pool = self.pool.clone();
228 let config = self.config.clone();
229
230 tokio::spawn(async move {
231 let mut interval_timer = tokio::time::interval(interval);
232
233 loop {
234 interval_timer.tick().await;
235
236 if config.monitoring.enable_pool_monitoring {
237 match sqlx::query("SELECT 1").fetch_one(&pool).await {
238 Ok(_) => {
239 if config.monitoring.log_level == crate::config::LogLevel::Debug {
240 println!("[IGNIS-DB] Pool health check: OK");
241 }
242 }
243 Err(e) => {
244 if config.monitoring.enable_error_logging {
245 eprintln!("[IGNIS-DB] Pool health check failed: {}", e);
246 }
247 }
248 }
249 }
250 }
251 });
252
253 Ok(())
254 }
255
256 async fn create_pool(config: &IgnisConfig) -> Result<PgPool> {
258 let connect_options = PgConnectOptions::from_str(&config.database.url)
260 .with_context(|| format!("Failed to parse database URL: {}", config.database.url))?;
261
262 let connect_options = if let Some(ssl_mode) = &config.database.ssl_mode {
264 match ssl_mode {
265 crate::config::SslMode::Disable => {
266 connect_options.ssl_mode(sqlx::postgres::PgSslMode::Disable)
267 }
268 crate::config::SslMode::Allow => {
269 connect_options.ssl_mode(sqlx::postgres::PgSslMode::Allow)
270 }
271 crate::config::SslMode::Prefer => {
272 connect_options.ssl_mode(sqlx::postgres::PgSslMode::Prefer)
273 }
274 crate::config::SslMode::Require => {
275 connect_options.ssl_mode(sqlx::postgres::PgSslMode::Require)
276 }
277 crate::config::SslMode::VerifyCa => {
278 connect_options.ssl_mode(sqlx::postgres::PgSslMode::VerifyCa)
279 }
280 crate::config::SslMode::VerifyFull => {
281 connect_options.ssl_mode(sqlx::postgres::PgSslMode::VerifyFull)
282 }
283 }
284 } else {
285 connect_options
286 };
287
288 let connect_options = if let Some(_timeout) = config.database.connect_timeout {
290 connect_options
293 } else {
294 connect_options
295 };
296
297 let mut pool_options = PgPoolOptions::new();
299
300 if let Some(max_connections) = config.pool.max_connections {
302 pool_options = pool_options.max_connections(max_connections);
303 }
304
305 if let Some(min_connections) = config.pool.min_connections {
306 pool_options = pool_options.min_connections(min_connections);
307 }
308
309 if let Some(acquire_timeout) = config.pool.acquire_timeout {
310 pool_options = pool_options.acquire_timeout(acquire_timeout);
311 }
312
313 if let Some(idle_timeout) = config.pool.idle_timeout {
314 pool_options = pool_options.idle_timeout(idle_timeout);
315 }
316
317 if let Some(max_lifetime) = config.pool.max_lifetime {
318 pool_options = pool_options.max_lifetime(max_lifetime);
319 }
320
321 if let Some(test_before_acquire) = config.pool.test_before_acquire {
322 if test_before_acquire {
323 pool_options = pool_options.test_before_acquire(true);
324 }
325 }
326
327 let pool = pool_options
329 .connect_with(connect_options)
330 .await
331 .with_context(|| "Failed to create connection pool")?;
332
333 Ok(pool)
334 }
335}
336
337#[derive(Debug, Clone)]
341pub struct PoolBenchmarkResult {
342 pub total_queries: usize,
344 pub successful_queries: usize,
346 pub failed_queries: usize,
348 pub total_duration: Duration,
350 pub average_query_time: Duration,
352 pub min_query_time: Duration,
354 pub max_query_time: Duration,
356 pub queries_per_second: f64,
358}
359
360impl PoolBenchmarkResult {
361 pub fn success_rate(&self) -> f64 {
363 if self.total_queries == 0 {
364 0.0
365 } else {
366 (self.successful_queries as f64 / self.total_queries as f64) * 100.0
367 }
368 }
369
370 pub fn failure_rate(&self) -> f64 {
372 100.0 - self.success_rate()
373 }
374
375 pub fn is_healthy(&self) -> bool {
377 self.success_rate() > 95.0 && self.average_query_time < Duration::from_millis(100)
378 }
379
380 pub fn summary(&self) -> String {
382 format!(
383 "Benchmark: {}/{} queries succeeded ({:.1}% success), {:.1} QPS, avg: {:.1}ms",
384 self.successful_queries,
385 self.total_queries,
386 self.success_rate(),
387 self.queries_per_second,
388 self.average_query_time.as_millis()
389 )
390 }
391}
392
393impl PoolStats {
394 pub fn utilization_percentage(&self) -> f32 {
396 if self.max_connections == 0 {
397 0.0
398 } else {
399 (self.total_connections as f32 / self.max_connections as f32) * 100.0
400 }
401 }
402
403 pub fn is_at_capacity(&self) -> bool {
405 self.total_connections >= self.max_connections
406 }
407}
408
409#[derive(Debug)]
411pub struct ConnectionManagerBuilder {
412 config: IgnisConfig,
413}
414
415impl ConnectionManagerBuilder {
416 pub fn new() -> Self {
418 Self {
419 config: IgnisConfig::default(),
420 }
421 }
422
423 pub fn database_url(mut self, url: impl Into<String>) -> Self {
425 self.config.database.url = url.into();
426 self
427 }
428
429 pub fn max_connections(mut self, max: u32) -> Self {
431 self.config.pool.max_connections = Some(max);
432 self
433 }
434
435 pub fn min_connections(mut self, min: u32) -> Self {
437 self.config.pool.min_connections = Some(min);
438 self
439 }
440
441 pub fn transaction_timeout(mut self, timeout: std::time::Duration) -> Self {
443 self.config.transaction.timeout = timeout;
444 self
445 }
446
447 pub fn isolation_level(mut self, level: crate::exec::transaction::IsolationLevel) -> Self {
449 self.config.transaction.isolation_level = level;
450 self
451 }
452
453 pub fn enable_query_monitoring(mut self, enable: bool) -> Self {
455 self.config.monitoring.enable_query_monitoring = enable;
456 self
457 }
458
459 pub async fn build(self) -> Result<ConnectionManager> {
461 ConnectionManager::from_config(self.config).await
462 }
463}
464
465impl Default for ConnectionManagerBuilder {
466 fn default() -> Self {
467 Self::new()
468 }
469}
470
471#[cfg(test)]
472mod tests {
473 use super::*;
474
475 #[tokio::test]
476 async fn test_connection_manager_builder() {
477 let manager = ConnectionManagerBuilder::new()
478 .database_url("postgresql://localhost/test")
479 .max_connections(5)
480 .min_connections(2)
481 .build()
482 .await;
483
484 assert!(manager.is_err()); }
488
489 #[test]
490 fn test_pool_stats() {
491 let stats = PoolStats {
492 total_connections: 5,
493 active_connections: 3,
494 idle_connections: 2,
495 max_connections: 10,
496 min_connections: 1,
497 };
498
499 assert_eq!(stats.utilization_percentage(), 50.0);
500 assert!(!stats.is_at_capacity());
501
502 let at_capacity = PoolStats {
503 total_connections: 10,
504 active_connections: 8,
505 idle_connections: 2,
506 max_connections: 10,
507 min_connections: 1,
508 };
509
510 assert!(at_capacity.is_at_capacity());
511 }
512}