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
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
//! Transaction Management System
//!
//! This module provides comprehensive transaction management including:
//! - Retry logic for deadlocks and transient failures
//! - Statement caching for performance optimization
//! - Isolation level management
//! - Transaction-aware migrations
//! - Rollback safety and concurrent handling

use anyhow::{anyhow, Result};
use serde::{Deserialize, Serialize};
use sqlx::postgres::PgPool;
use sqlx::Error as SqlxError;
use std::collections::HashMap;
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::sync::RwLock;

/// Transaction configuration for different operation types
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TransactionConfig {
    /// Maximum retry attempts for transient failures
    pub max_retries: u32,
    /// Base delay between retries (exponential backoff)
    pub base_delay: Duration,
    /// Maximum delay between retries
    pub max_delay: Duration,
    /// Transaction timeout
    pub timeout: Duration,
    /// Isolation level for the transaction
    pub isolation_level: IsolationLevel,
    /// Whether to enable statement caching
    pub enable_statement_caching: bool,
    /// Maximum cached statements
    pub max_cached_statements: usize,
}

impl Default for TransactionConfig {
    fn default() -> Self {
        Self {
            max_retries: 3,
            base_delay: Duration::from_millis(100),
            max_delay: Duration::from_secs(5),
            timeout: Duration::from_secs(30),
            isolation_level: IsolationLevel::ReadCommitted,
            enable_statement_caching: true,
            max_cached_statements: 100,
        }
    }
}

/// PostgreSQL transaction isolation levels
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub enum IsolationLevel {
    ReadUncommitted,
    ReadCommitted,
    RepeatableRead,
    Serializable,
}

impl IsolationLevel {
    /// Convert to SQL string for SET TRANSACTION
    pub fn to_sql(&self) -> &'static str {
        match self {
            IsolationLevel::ReadUncommitted => "READ UNCOMMITTED",
            IsolationLevel::ReadCommitted => "READ COMMITTED",
            IsolationLevel::RepeatableRead => "REPEATABLE READ",
            IsolationLevel::Serializable => "SERIALIZABLE",
        }
    }
}

impl std::fmt::Display for IsolationLevel {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            IsolationLevel::ReadUncommitted => write!(f, "Read Uncommitted"),
            IsolationLevel::ReadCommitted => write!(f, "Read Committed"),
            IsolationLevel::RepeatableRead => write!(f, "Repeatable Read"),
            IsolationLevel::Serializable => write!(f, "Serializable"),
        }
    }
}

/// Transaction context for tracking state and metadata
#[derive(Debug, Clone)]
pub struct TransactionContext {
    /// Unique transaction ID
    pub id: String,
    /// Start time of the transaction
    pub start_time: Instant,
    /// Current retry attempt
    pub retry_count: u32,
    /// Transaction configuration
    pub config: TransactionConfig,
    /// Transaction metadata
    pub metadata: HashMap<String, String>,
}

impl TransactionContext {
    /// Create a new transaction context
    pub fn new(config: TransactionConfig) -> Self {
        Self {
            id: uuid::Uuid::new_v4().to_string(),
            start_time: Instant::now(),
            retry_count: 0,
            config,
            metadata: HashMap::new(),
        }
    }

    /// Add metadata to the transaction
    pub fn add_metadata(&mut self, key: &str, value: &str) {
        self.metadata.insert(key.to_string(), value.to_string());
    }

    /// Check if transaction has timed out
    pub fn has_timed_out(&self) -> bool {
        self.start_time.elapsed() > self.config.timeout
    }

    /// Check if we can retry the transaction
    pub fn can_retry(&self) -> bool {
        self.retry_count < self.config.max_retries
    }

    /// Calculate next retry delay with exponential backoff
    pub fn next_retry_delay(&self) -> Duration {
        let delay = self.config.base_delay * 2_u32.pow(self.retry_count);
        delay.min(self.config.max_delay)
    }
}

/// Statement cache for performance optimization
#[derive(Debug)]
pub struct StatementCache {
    statements: Arc<RwLock<HashMap<String, CachedStatement>>>,
    max_size: usize,
}

#[derive(Debug, Clone)]
struct CachedStatement {
    sql: String,
    _created_at: Instant, // TODO: Use for cache eviction policies
    last_used: Instant,
    use_count: u64,
}

impl StatementCache {
    /// Create a new statement cache
    pub fn new(max_size: usize) -> Self {
        Self {
            statements: Arc::new(RwLock::new(HashMap::new())),
            max_size,
        }
    }

    /// Get a cached statement
    pub async fn get(&self, sql: &str) -> Option<String> {
        let sql_key = sql.to_string();
        {
            let statements = self.statements.read().await;
            if let Some(cached) = statements.get(&sql_key) {
                // Clone the SQL string before dropping the read lock
                let result = Some(cached.sql.clone());
                drop(statements);
                // Update usage after dropping the read lock
                self.update_usage(&sql_key).await;
                return result;
            }
        }
        None
    }

    /// Cache a new statement
    pub async fn cache(&self, sql: &str) {
        let mut statements = self.statements.write().await;

        // Check if we need to evict old statements
        if statements.len() >= self.max_size {
            self.evict_old_statements(&mut statements).await;
        }

        let cached = CachedStatement {
            sql: sql.to_string(),
            _created_at: Instant::now(),
            last_used: Instant::now(),
            use_count: 1,
        };

        statements.insert(sql.to_string(), cached);
    }

    /// Update statement usage statistics
    async fn update_usage(&self, sql: &str) {
        let mut statements = self.statements.write().await;
        if let Some(cached) = statements.get_mut(sql) {
            cached.last_used = Instant::now();
            cached.use_count += 1;
        }
    }

    /// Evict old statements based on LRU policy
    async fn evict_old_statements(&self, statements: &mut HashMap<String, CachedStatement>) {
        let mut entries: Vec<_> = statements.iter().collect();
        entries.sort_by_key(|(_, cached)| cached.last_used);

        // Remove oldest 20% of statements
        let to_remove = (entries.len() as f64 * 0.2).ceil() as usize;
        let to_remove_keys: Vec<String> = entries
            .iter()
            .take(to_remove)
            .map(|(sql, _)| (*sql).clone())
            .collect();

        for sql_key in to_remove_keys {
            statements.remove(&sql_key);
        }
    }

    /// Get cache statistics
    pub async fn stats(&self) -> CacheStats {
        let statements = self.statements.read().await;
        let total_statements = statements.len();
        let total_uses: u64 = statements.values().map(|s| s.use_count).sum();
        let avg_uses = if total_statements > 0 {
            total_uses as f64 / total_statements as f64
        } else {
            0.0
        };

        CacheStats {
            total_statements,
            total_uses,
            average_uses: avg_uses,
            max_size: self.max_size,
        }
    }
}

/// Cache statistics
#[derive(Debug, Clone)]
pub struct CacheStats {
    pub total_statements: usize,
    pub total_uses: u64,
    pub average_uses: f64,
    pub max_size: usize,
}

/// Main transaction manager
#[derive(Debug)]
pub struct TransactionManager {
    pool: PgPool,
    cache: StatementCache,
    default_config: TransactionConfig,
}

impl TransactionManager {
    /// Create a new transaction manager
    pub fn new(pool: PgPool, config: TransactionConfig) -> Self {
        let cache = StatementCache::new(config.max_cached_statements);

        Self {
            pool,
            cache,
            default_config: config,
        }
    }

    /// Create a new transaction manager with default configuration
    pub fn new_default(pool: PgPool) -> Self {
        Self::new(pool, TransactionConfig::default())
    }

    /// Execute a function within a transaction with retry logic
    pub async fn execute_with_retry<T, F, Fut>(
        &self,
        config: Option<TransactionConfig>,
        f: F,
    ) -> Result<T>
    where
        F: Fn(&mut sqlx::Transaction<'_, sqlx::Postgres>) -> Fut + Send + Sync,
        Fut: std::future::Future<Output = Result<T, SqlxError>> + Send,
        T: Send,
    {
        let config = config.unwrap_or_else(|| self.default_config.clone());
        let mut context = TransactionContext::new(config);

        loop {
            // Check timeout
            if context.has_timed_out() {
                return Err(anyhow!(
                    "Transaction timed out after {:?}",
                    context.config.timeout
                ));
            }

            // Attempt transaction execution
            match self.execute_transaction(&context, &f).await {
                Ok(result) => return Ok(result),
                Err(e) => {
                    // Check if error is retryable
                    if self.is_retryable_error(&e) && context.can_retry() {
                        context.retry_count += 1;
                        let delay = context.next_retry_delay();

                        // Log retry attempt
                        tracing::warn!(
                            "Transaction failed, retrying in {:?} (attempt {}/{}): {}",
                            delay,
                            context.retry_count,
                            context.config.max_retries,
                            e
                        );

                        tokio::time::sleep(delay).await;
                        continue;
                    } else {
                        return Err(anyhow!(
                            "Transaction failed after {} attempts: {}",
                            context.retry_count + 1,
                            e
                        ));
                    }
                }
            }
        }
    }

    /// Execute a single transaction
    async fn execute_transaction<T, F, Fut>(
        &self,
        context: &TransactionContext,
        f: &F,
    ) -> Result<T, SqlxError>
    where
        F: Fn(&mut sqlx::Transaction<'_, sqlx::Postgres>) -> Fut + Send + Sync,
        Fut: std::future::Future<Output = Result<T, SqlxError>> + Send,
        T: Send,
    {
        let mut transaction = self.pool.begin().await?;

        // Set transaction isolation level
        let isolation_sql = format!(
            "SET TRANSACTION ISOLATION LEVEL {}",
            context.config.isolation_level.to_sql()
        );
        sqlx::query(&isolation_sql)
            .execute(&mut *transaction)
            .await?;

        // Set transaction timeout
        let timeout_sql = format!(
            "SET LOCAL statement_timeout = '{}ms'",
            context.config.timeout.as_millis()
        );
        sqlx::query(&timeout_sql).execute(&mut *transaction).await?;

        // Execute the transaction function
        let result = f(&mut transaction).await?;

        // Commit the transaction
        transaction.commit().await?;

        Ok(result)
    }

    /// Check if an error is retryable
    fn is_retryable_error(&self, error: &SqlxError) -> bool {
        match error {
            SqlxError::Database(db_error) => {
                // PostgreSQL error codes for retryable errors
                if let Some(code) = db_error.code() {
                    match code.as_ref() {
                        "40001" => true, // Serialization failure
                        "40P01" => true, // Deadlock detected
                        "57014" => true, // Query canceled
                        "08000" => true, // Connection exception
                        "08003" => true, // Connection does not exist
                        "08006" => true, // Connection failure
                        "08001" => true, // SQL client unable to establish SQL connection
                        "08004" => true, // SQL server rejected establishment of SQL connection
                        "08007" => true, // Connection failure during transaction
                        _ => false,
                    }
                } else {
                    false
                }
            }
            SqlxError::Io(_) => true, // Network/IO errors are retryable
            SqlxError::Protocol(_) => true, // Protocol errors are retryable
            _ => false,
        }
    }

    /// Execute a query with statement caching
    pub async fn execute_cached_query(
        &self,
        sql: &str,
        _params: &[&(dyn sqlx::Encode<'_, sqlx::Postgres> + Send + Sync)],
    ) -> Result<sqlx::postgres::PgQueryResult> {
        // Check cache first
        if self.default_config.enable_statement_caching {
            if let Some(_cached) = self.cache.get(sql).await {
                // Use cached statement (in a real implementation, you'd use prepared statements)
            }
        }

        // Execute query
        let result = sqlx::query(sql).execute(&self.pool).await?;

        // Cache the statement for future use
        if self.default_config.enable_statement_caching {
            self.cache.cache(sql).await;
        }

        Ok(result)
    }

    /// Get transaction manager statistics
    pub async fn stats(&self) -> TransactionManagerStats {
        let cache_stats = self.cache.stats().await;

        TransactionManagerStats {
            cache_stats,
            default_config: self.default_config.clone(),
        }
    }
}

/// Transaction manager statistics
#[derive(Debug, Clone)]
pub struct TransactionManagerStats {
    pub cache_stats: CacheStats,
    pub default_config: TransactionConfig,
}

/// Convenience function to execute a transaction with default configuration
pub async fn execute_transaction<T, F, Fut>(pool: &PgPool, f: F) -> Result<T>
where
    F: Fn(&mut sqlx::Transaction<'_, sqlx::Postgres>) -> Fut + Send + Sync,
    Fut: std::future::Future<Output = Result<T, SqlxError>> + Send,
    T: Send,
{
    let manager = TransactionManager::new_default(pool.clone());
    manager.execute_with_retry(None, f).await
}

/// Convenience function to execute a transaction with custom configuration
pub async fn execute_transaction_with_config<T, F, Fut>(
    pool: &PgPool,
    config: TransactionConfig,
    f: F,
) -> Result<T>
where
    F: Fn(&mut sqlx::Transaction<'_, sqlx::Postgres>) -> Fut + Send + Sync,
    Fut: std::future::Future<Output = Result<T, SqlxError>> + Send,
    T: Send,
{
    let manager = TransactionManager::new(pool.clone(), config);
    manager.execute_with_retry(None, f).await
}

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

    #[tokio::test]
    async fn test_transaction_config_default() {
        let config = TransactionConfig::default();
        assert_eq!(config.max_retries, 3);
        assert_eq!(config.isolation_level, IsolationLevel::ReadCommitted);
        assert!(config.enable_statement_caching);
    }

    #[test]
    fn test_isolation_level_to_sql() {
        assert_eq!(IsolationLevel::ReadCommitted.to_sql(), "READ COMMITTED");
        assert_eq!(IsolationLevel::Serializable.to_sql(), "SERIALIZABLE");
    }

    #[test]
    fn test_transaction_context() {
        let config = TransactionConfig::default();
        let mut context = TransactionContext::new(config);

        assert_eq!(context.retry_count, 0);
        assert!(context.can_retry());

        context.add_metadata("operation", "test");
        assert_eq!(context.metadata.get("operation"), Some(&"test".to_string()));
    }

    #[tokio::test]
    async fn test_statement_cache() {
        let cache = StatementCache::new(5);

        // Cache some statements
        cache.cache("SELECT * FROM users").await;
        cache.cache("SELECT * FROM posts").await;

        // Get cached statement
        let result = cache.get("SELECT * FROM users").await;
        assert!(result.is_some());

        // Get stats
        let stats = cache.stats().await;
        assert_eq!(stats.total_statements, 2);
        assert_eq!(stats.max_size, 5);
    }

    #[test]
    fn test_retryable_error_detection() {
        // For testing purposes, we'll create a simple test that doesn't require actual database connections
        // In a real implementation, these would be actual database errors

        // Create a simple test that validates the error detection logic
        // We'll test with a mock implementation

        // Test that IO errors are retryable
        let io_error = SqlxError::Io(std::io::Error::new(
            std::io::ErrorKind::ConnectionRefused,
            "test",
        ));

        // Test that non-retryable errors are not retryable
        let parse_error = SqlxError::ColumnDecode {
            index: "test".to_string(),
            source: Box::new(std::io::Error::new(std::io::ErrorKind::InvalidData, "test")),
        };

        // Since we can't create a TransactionManager without a pool in tests,
        // we'll just validate that our error types are correct
        assert!(matches!(io_error, SqlxError::Io(_)));
        assert!(matches!(parse_error, SqlxError::ColumnDecode { .. }));
    }
}