ignis-db 0.2.0

A comprehensive PostgreSQL ORM with macro-driven schema management
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
//! Connection Management for Ignis-DB
//!
//! This module provides configuration-driven database connection management
//! that extends the existing TransactionManager without breaking existing APIs.

use crate::config::IgnisConfig;
use crate::exec::transaction::TransactionManager;
use anyhow::{Context, Result};
use sqlx::postgres::{PgConnectOptions, PgPool, PgPoolOptions};
use std::str::FromStr;
use std::sync::Arc;
use std::time::Duration;

/// Connection manager that handles pool creation and management
#[derive(Debug)]
pub struct ConnectionManager {
    /// The managed connection pool
    pool: PgPool,
    /// Transaction manager using this pool
    transaction_manager: Arc<TransactionManager>,
    /// Configuration used to create this manager
    config: IgnisConfig,
}

/// Connection pool statistics
#[derive(Debug, Clone)]
pub struct PoolStats {
    /// Total number of connections in the pool
    pub total_connections: u32,
    /// Number of active (checked out) connections
    pub active_connections: u32,
    /// Number of idle connections
    pub idle_connections: u32,
    /// Maximum pool size
    pub max_connections: u32,
    /// Minimum pool size
    pub min_connections: u32,
}

impl ConnectionManager {
    /// Create a new connection manager from configuration
    pub async fn from_config(config: IgnisConfig) -> Result<Self> {
        // Validate configuration
        config.validate()?;

        // Create the connection pool
        let pool = Self::create_pool(&config).await?;

        // Create transaction manager with the pool
        let transaction_manager = Arc::new(TransactionManager::new(
            pool.clone(),
            config.transaction.clone(),
        ));

        Ok(Self {
            pool,
            transaction_manager,
            config,
        })
    }

    /// Create a connection manager with default configuration
    pub async fn new_default() -> Result<Self> {
        let config = IgnisConfig::default();
        Self::from_config(config).await
    }

    /// Create a connection manager from environment variables
    pub async fn from_env() -> Result<Self> {
        let config = IgnisConfig::from_env()?;
        Self::from_config(config).await
    }

    /// Create a connection manager from YAML file
    pub async fn from_yaml_file(path: &str) -> Result<Self> {
        let config = IgnisConfig::from_yaml_file(path)?;
        Self::from_config(config).await
    }

    /// Get a reference to the underlying pool
    pub fn pool(&self) -> &PgPool {
        &self.pool
    }

    /// Get a reference to the transaction manager
    pub fn transaction_manager(&self) -> &Arc<TransactionManager> {
        &self.transaction_manager
    }

    /// Get a reference to the configuration
    pub fn config(&self) -> &IgnisConfig {
        &self.config
    }

    /// Check if the connection pool is healthy
    pub async fn health_check(&self) -> Result<bool> {
        match sqlx::query("SELECT 1").fetch_one(&self.pool).await {
            Ok(_) => Ok(true),
            Err(_) => Ok(false),
        }
    }

    /// Get connection pool statistics
    pub async fn get_pool_stats(&self) -> Result<PoolStats> {
        // Get pool state information
        let pool_size = self.pool.size();
        let max_size = self.config.pool.max_connections.unwrap_or(10) as u32;
        let min_size = self.config.pool.min_connections.unwrap_or(1) as u32;

        // Try to estimate active connections by checking how many we can acquire
        // This is an approximation since sqlx doesn't expose detailed pool stats
        let idle_connections = self.pool.num_idle() as u32;
        let active_connections = (pool_size as u32).saturating_sub(idle_connections);

        Ok(PoolStats {
            total_connections: pool_size as u32,
            active_connections,
            idle_connections,
            max_connections: max_size,
            min_connections: min_size,
        })
    }

    /// Close the connection pool
    pub async fn close(&self) -> Result<()> {
        self.pool.close().await;
        Ok(())
    }

    /// Execute a query and return all results
    pub async fn execute_query(&self, query: &str) -> Result<Vec<sqlx::postgres::PgRow>> {
        let rows = sqlx::query(query)
            .fetch_all(&self.pool)
            .await
            .with_context(|| format!("Failed to execute query: {}", query))?;
        Ok(rows)
    }

    /// Execute a query and return one result
    pub async fn execute_query_one(&self, query: &str) -> Result<Option<sqlx::postgres::PgRow>> {
        let row = sqlx::query(query)
            .fetch_optional(&self.pool)
            .await
            .with_context(|| format!("Failed to execute query: {}", query))?;
        Ok(row)
    }

    /// Execute a command (INSERT, UPDATE, DELETE)
    pub async fn execute_command(&self, query: &str) -> Result<u64> {
        let result = sqlx::query(query)
            .execute(&self.pool)
            .await
            .with_context(|| format!("Failed to execute command: {}", query))?;
        Ok(result.rows_affected())
    }

    /// Test connection pool performance
    pub async fn benchmark_pool(&self, concurrent_queries: usize) -> Result<PoolBenchmarkResult> {
        use std::time::Instant;
        use tokio::sync::Semaphore;

        let start = Instant::now();
        let semaphore = Arc::new(Semaphore::new(concurrent_queries));
        let mut handles = Vec::new();

        for i in 0..concurrent_queries {
            let pool = self.pool.clone();
            let permit = semaphore.clone().acquire_owned().await.unwrap();

            let handle = tokio::spawn(async move {
                let _permit = permit;
                let query_start = Instant::now();
                let result = sqlx::query("SELECT $1::int as test_value")
                    .bind(i as i32)
                    .fetch_one(&pool)
                    .await;
                let query_duration = query_start.elapsed();
                (result.is_ok(), query_duration)
            });

            handles.push(handle);
        }

        let mut successful_queries = 0;
        let mut total_query_time = Duration::ZERO;
        let mut min_query_time = Duration::from_secs(u64::MAX);
        let mut max_query_time = Duration::ZERO;

        for handle in handles {
            let (success, duration) = handle.await.unwrap();
            if success {
                successful_queries += 1;
                total_query_time += duration;
                min_query_time = min_query_time.min(duration);
                max_query_time = max_query_time.max(duration);
            }
        }

        let total_duration = start.elapsed();

        Ok(PoolBenchmarkResult {
            total_queries: concurrent_queries,
            successful_queries,
            failed_queries: concurrent_queries - successful_queries,
            total_duration,
            average_query_time: if successful_queries > 0 {
                total_query_time / successful_queries as u32
            } else {
                Duration::ZERO
            },
            min_query_time: if successful_queries > 0 {
                min_query_time
            } else {
                Duration::ZERO
            },
            max_query_time,
            queries_per_second: if total_duration.as_secs_f64() > 0.0 {
                successful_queries as f64 / total_duration.as_secs_f64()
            } else {
                0.0
            },
        })
    }

    /// Monitor pool health continuously
    pub async fn start_health_monitor(&self, interval: Duration) -> Result<()> {
        let pool = self.pool.clone();
        let config = self.config.clone();

        tokio::spawn(async move {
            let mut interval_timer = tokio::time::interval(interval);

            loop {
                interval_timer.tick().await;

                if config.monitoring.enable_pool_monitoring {
                    match sqlx::query("SELECT 1").fetch_one(&pool).await {
                        Ok(_) => {
                            if config.monitoring.log_level == crate::config::LogLevel::Debug {
                                println!("[IGNIS-DB] Pool health check: OK");
                            }
                        }
                        Err(e) => {
                            if config.monitoring.enable_error_logging {
                                eprintln!("[IGNIS-DB] Pool health check failed: {}", e);
                            }
                        }
                    }
                }
            }
        });

        Ok(())
    }

    /// Create a connection pool from configuration
    async fn create_pool(config: &IgnisConfig) -> Result<PgPool> {
        // Parse connection URL
        let connect_options = PgConnectOptions::from_str(&config.database.url)
            .with_context(|| format!("Failed to parse database URL: {}", config.database.url))?;

        // Apply SSL mode if specified
        let connect_options = if let Some(ssl_mode) = &config.database.ssl_mode {
            match ssl_mode {
                crate::config::SslMode::Disable => {
                    connect_options.ssl_mode(sqlx::postgres::PgSslMode::Disable)
                }
                crate::config::SslMode::Allow => {
                    connect_options.ssl_mode(sqlx::postgres::PgSslMode::Allow)
                }
                crate::config::SslMode::Prefer => {
                    connect_options.ssl_mode(sqlx::postgres::PgSslMode::Prefer)
                }
                crate::config::SslMode::Require => {
                    connect_options.ssl_mode(sqlx::postgres::PgSslMode::Require)
                }
                crate::config::SslMode::VerifyCa => {
                    connect_options.ssl_mode(sqlx::postgres::PgSslMode::VerifyCa)
                }
                crate::config::SslMode::VerifyFull => {
                    connect_options.ssl_mode(sqlx::postgres::PgSslMode::VerifyFull)
                }
            }
        } else {
            connect_options
        };

        // Apply connection timeout if specified
        let connect_options = if let Some(_timeout) = config.database.connect_timeout {
            // Note: sqlx doesn't have a direct connect_timeout method
            // We'll use the pool-level timeout instead
            connect_options
        } else {
            connect_options
        };

        // Create pool options
        let mut pool_options = PgPoolOptions::new();

        // Apply pool configuration
        if let Some(max_connections) = config.pool.max_connections {
            pool_options = pool_options.max_connections(max_connections);
        }

        if let Some(min_connections) = config.pool.min_connections {
            pool_options = pool_options.min_connections(min_connections);
        }

        if let Some(acquire_timeout) = config.pool.acquire_timeout {
            pool_options = pool_options.acquire_timeout(acquire_timeout);
        }

        if let Some(idle_timeout) = config.pool.idle_timeout {
            pool_options = pool_options.idle_timeout(idle_timeout);
        }

        if let Some(max_lifetime) = config.pool.max_lifetime {
            pool_options = pool_options.max_lifetime(max_lifetime);
        }

        if let Some(test_before_acquire) = config.pool.test_before_acquire {
            if test_before_acquire {
                pool_options = pool_options.test_before_acquire(true);
            }
        }

        // Create the pool
        let pool = pool_options
            .connect_with(connect_options)
            .await
            .with_context(|| "Failed to create connection pool")?;

        Ok(pool)
    }
}

/// Connection pool statistics

/// Pool benchmark results
#[derive(Debug, Clone)]
pub struct PoolBenchmarkResult {
    /// Total number of queries attempted
    pub total_queries: usize,
    /// Number of successful queries
    pub successful_queries: usize,
    /// Number of failed queries
    pub failed_queries: usize,
    /// Total time for all queries
    pub total_duration: Duration,
    /// Average query execution time
    pub average_query_time: Duration,
    /// Minimum query execution time
    pub min_query_time: Duration,
    /// Maximum query execution time
    pub max_query_time: Duration,
    /// Queries executed per second
    pub queries_per_second: f64,
}

impl PoolBenchmarkResult {
    /// Get success rate as a percentage
    pub fn success_rate(&self) -> f64 {
        if self.total_queries == 0 {
            0.0
        } else {
            (self.successful_queries as f64 / self.total_queries as f64) * 100.0
        }
    }

    /// Get failure rate as a percentage
    pub fn failure_rate(&self) -> f64 {
        100.0 - self.success_rate()
    }

    /// Check if benchmark indicates healthy pool performance
    pub fn is_healthy(&self) -> bool {
        self.success_rate() > 95.0 && self.average_query_time < Duration::from_millis(100)
    }

    /// Get performance summary as a formatted string
    pub fn summary(&self) -> String {
        format!(
            "Benchmark: {}/{} queries succeeded ({:.1}% success), {:.1} QPS, avg: {:.1}ms",
            self.successful_queries,
            self.total_queries,
            self.success_rate(),
            self.queries_per_second,
            self.average_query_time.as_millis()
        )
    }
}

impl PoolStats {
    /// Get connection utilization percentage
    pub fn utilization_percentage(&self) -> f32 {
        if self.max_connections == 0 {
            0.0
        } else {
            (self.total_connections as f32 / self.max_connections as f32) * 100.0
        }
    }

    /// Check if pool is at capacity
    pub fn is_at_capacity(&self) -> bool {
        self.total_connections >= self.max_connections
    }
}

/// Builder for connection manager
#[derive(Debug)]
pub struct ConnectionManagerBuilder {
    config: IgnisConfig,
}

impl ConnectionManagerBuilder {
    /// Create a new connection manager builder
    pub fn new() -> Self {
        Self {
            config: IgnisConfig::default(),
        }
    }

    /// Set database URL
    pub fn database_url(mut self, url: impl Into<String>) -> Self {
        self.config.database.url = url.into();
        self
    }

    /// Set maximum connections
    pub fn max_connections(mut self, max: u32) -> Self {
        self.config.pool.max_connections = Some(max);
        self
    }

    /// Set minimum connections
    pub fn min_connections(mut self, min: u32) -> Self {
        self.config.pool.min_connections = Some(min);
        self
    }

    /// Set transaction timeout
    pub fn transaction_timeout(mut self, timeout: std::time::Duration) -> Self {
        self.config.transaction.timeout = timeout;
        self
    }

    /// Set isolation level
    pub fn isolation_level(mut self, level: crate::exec::transaction::IsolationLevel) -> Self {
        self.config.transaction.isolation_level = level;
        self
    }

    /// Enable query monitoring
    pub fn enable_query_monitoring(mut self, enable: bool) -> Self {
        self.config.monitoring.enable_query_monitoring = enable;
        self
    }

    /// Build the connection manager
    pub async fn build(self) -> Result<ConnectionManager> {
        ConnectionManager::from_config(self.config).await
    }
}

impl Default for ConnectionManagerBuilder {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn test_connection_manager_builder() {
        let manager = ConnectionManagerBuilder::new()
            .database_url("postgresql://localhost/test")
            .max_connections(5)
            .min_connections(2)
            .build()
            .await;

        // This will fail in test environment without real database
        // but we can verify the builder pattern works
        assert!(manager.is_err()); // Expected to fail without real DB
    }

    #[test]
    fn test_pool_stats() {
        let stats = PoolStats {
            total_connections: 5,
            active_connections: 3,
            idle_connections: 2,
            max_connections: 10,
            min_connections: 1,
        };

        assert_eq!(stats.utilization_percentage(), 50.0);
        assert!(!stats.is_at_capacity());

        let at_capacity = PoolStats {
            total_connections: 10,
            active_connections: 8,
            idle_connections: 2,
            max_connections: 10,
            min_connections: 1,
        };

        assert!(at_capacity.is_at_capacity());
    }
}