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
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
//! Database connection management
//!
//! This module provides utilities for managing database connections,
//! connection pooling, and database-specific operations.
use crate::error::{Error, Result};
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;
#[cfg(feature = "db")]
use sqlx::{Pool, Sqlite, Postgres, MySql, Row, Column};
/// Database type enumeration
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DatabaseType {
/// SQLite database
SQLite,
/// PostgreSQL database
PostgreSQL,
/// MySQL database
MySQL,
}
/// Database connection configuration
#[derive(Debug, Clone)]
pub struct DatabaseConfig {
/// Database type
pub db_type: DatabaseType,
/// Connection URL or path
pub url: String,
/// Maximum number of connections in pool
pub max_connections: u32,
/// Minimum number of connections in pool
pub min_connections: u32,
/// Connection timeout
pub connect_timeout: Duration,
/// Idle timeout for connections
pub idle_timeout: Option<Duration>,
/// Maximum lifetime of connections
pub max_lifetime: Option<Duration>,
}
impl Default for DatabaseConfig {
fn default() -> Self {
Self {
db_type: DatabaseType::SQLite,
url: ":memory:".to_string(),
max_connections: 10,
min_connections: 1,
connect_timeout: Duration::from_secs(30),
idle_timeout: Some(Duration::from_secs(600)),
max_lifetime: Some(Duration::from_secs(1800)),
}
}
}
impl DatabaseConfig {
/// Create a new database configuration
///
/// # Examples
///
/// ```rust
/// use rutool::db::{DatabaseConfig, DatabaseType};
///
/// let config = DatabaseConfig::new(
/// DatabaseType::SQLite,
/// "database.db"
/// );
/// ```
pub fn new(db_type: DatabaseType, url: &str) -> Self {
Self {
db_type,
url: url.to_string(),
..Default::default()
}
}
/// Set maximum connections in pool
pub fn with_max_connections(mut self, max: u32) -> Self {
self.max_connections = max;
self
}
/// Set minimum connections in pool
pub fn with_min_connections(mut self, min: u32) -> Self {
self.min_connections = min;
self
}
/// Set connection timeout
pub fn with_connect_timeout(mut self, timeout: Duration) -> Self {
self.connect_timeout = timeout;
self
}
/// Set idle timeout
pub fn with_idle_timeout(mut self, timeout: Duration) -> Self {
self.idle_timeout = Some(timeout);
self
}
/// Set maximum connection lifetime
pub fn with_max_lifetime(mut self, lifetime: Duration) -> Self {
self.max_lifetime = Some(lifetime);
self
}
}
/// Generic database connection wrapper
#[derive(Debug)]
pub enum DatabaseConnection {
#[cfg(feature = "db")]
/// SQLite connection pool
SQLite(Pool<Sqlite>),
#[cfg(feature = "db")]
/// PostgreSQL connection pool
PostgreSQL(Pool<Postgres>),
#[cfg(feature = "db")]
/// MySQL connection pool
MySQL(Pool<MySql>),
/// Mock connection for testing
Mock,
}
impl DatabaseConnection {
/// Create a new database connection
///
/// # Examples
///
/// ```rust
/// use rutool::db::{DatabaseConnection, DatabaseConfig, DatabaseType};
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let config = DatabaseConfig::new(DatabaseType::SQLite, ":memory:");
/// let conn = DatabaseConnection::new(config).await?;
/// Ok(())
/// }
/// ```
pub async fn new(config: DatabaseConfig) -> Result<Self> {
#[cfg(feature = "db")]
{
use sqlx::sqlite::SqlitePoolOptions;
use sqlx::postgres::PgPoolOptions;
use sqlx::mysql::MySqlPoolOptions;
match config.db_type {
DatabaseType::SQLite => {
let pool = SqlitePoolOptions::new()
.max_connections(config.max_connections)
.min_connections(config.min_connections)
.acquire_timeout(config.connect_timeout)
.idle_timeout(config.idle_timeout)
.max_lifetime(config.max_lifetime)
.connect(&config.url)
.await
.map_err(|e| Error::database(format!("Failed to connect to SQLite: {}", e)))?;
Ok(DatabaseConnection::SQLite(pool))
}
DatabaseType::PostgreSQL => {
let pool = PgPoolOptions::new()
.max_connections(config.max_connections)
.min_connections(config.min_connections)
.acquire_timeout(config.connect_timeout)
.idle_timeout(config.idle_timeout)
.max_lifetime(config.max_lifetime)
.connect(&config.url)
.await
.map_err(|e| Error::database(format!("Failed to connect to PostgreSQL: {}", e)))?;
Ok(DatabaseConnection::PostgreSQL(pool))
}
DatabaseType::MySQL => {
let pool = MySqlPoolOptions::new()
.max_connections(config.max_connections)
.min_connections(config.min_connections)
.acquire_timeout(config.connect_timeout)
.idle_timeout(config.idle_timeout)
.max_lifetime(config.max_lifetime)
.connect(&config.url)
.await
.map_err(|e| Error::database(format!("Failed to connect to MySQL: {}", e)))?;
Ok(DatabaseConnection::MySQL(pool))
}
}
}
#[cfg(not(feature = "db"))]
{
let _ = config; // Avoid unused variable warning
Ok(DatabaseConnection::Mock)
}
}
/// Execute a SQL query and return the number of affected rows
///
/// # Examples
///
/// ```rust
/// use rutool::db::{DatabaseConnection, DatabaseConfig, DatabaseType};
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let config = DatabaseConfig::new(DatabaseType::SQLite, ":memory:");
/// let conn = DatabaseConnection::new(config).await?;
///
/// let affected = conn.execute(
/// "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)"
/// ).await?;
///
/// println!("Affected rows: {}", affected);
/// Ok(())
/// }
/// ```
pub async fn execute(&self, sql: &str) -> Result<u64> {
#[cfg(feature = "db")]
{
match self {
DatabaseConnection::SQLite(pool) => {
let result = sqlx::query(sql)
.execute(pool)
.await
.map_err(|e| Error::database(format!("SQL execution failed: {}", e)))?;
Ok(result.rows_affected())
}
DatabaseConnection::PostgreSQL(pool) => {
let result = sqlx::query(sql)
.execute(pool)
.await
.map_err(|e| Error::database(format!("SQL execution failed: {}", e)))?;
Ok(result.rows_affected())
}
DatabaseConnection::MySQL(pool) => {
let result = sqlx::query(sql)
.execute(pool)
.await
.map_err(|e| Error::database(format!("SQL execution failed: {}", e)))?;
Ok(result.rows_affected())
}
DatabaseConnection::Mock => Ok(0),
}
}
#[cfg(not(feature = "db"))]
{
let _ = sql; // Avoid unused variable warning
Ok(0)
}
}
/// Execute a SQL query with parameters and return the number of affected rows
///
/// # Examples
///
/// ```rust
/// use rutool::db::{DatabaseConnection, DatabaseConfig, DatabaseType};
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let config = DatabaseConfig::new(DatabaseType::SQLite, ":memory:");
/// let conn = DatabaseConnection::new(config).await?;
///
/// // First create the table
/// conn.execute("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)").await?;
///
/// // Then insert with parameters
/// let affected = conn.execute_with_params(
/// "INSERT INTO users (name) VALUES (?)",
/// &[&"Alice"]
/// ).await?;
///
/// println!("Affected rows: {}", affected);
/// Ok(())
/// }
/// ```
pub async fn execute_with_params(&self, sql: &str, params: &[&str]) -> Result<u64> {
#[cfg(feature = "db")]
{
match self {
DatabaseConnection::SQLite(pool) => {
let mut query = sqlx::query(sql);
for ¶m in params {
query = query.bind(param);
}
let result = query
.execute(pool)
.await
.map_err(|e| Error::database(format!("SQL execution failed: {}", e)))?;
Ok(result.rows_affected())
}
DatabaseConnection::PostgreSQL(pool) => {
let mut query = sqlx::query(sql);
for ¶m in params {
query = query.bind(param);
}
let result = query
.execute(pool)
.await
.map_err(|e| Error::database(format!("SQL execution failed: {}", e)))?;
Ok(result.rows_affected())
}
DatabaseConnection::MySQL(pool) => {
let mut query = sqlx::query(sql);
for ¶m in params {
query = query.bind(param);
}
let result = query
.execute(pool)
.await
.map_err(|e| Error::database(format!("SQL execution failed: {}", e)))?;
Ok(result.rows_affected())
}
DatabaseConnection::Mock => Ok(0),
}
}
#[cfg(not(feature = "db"))]
{
let _ = (sql, params); // Avoid unused variable warnings
Ok(0)
}
}
/// Fetch all rows from a SQL query
///
/// # Examples
///
/// ```rust
/// use rutool::db::{DatabaseConnection, DatabaseConfig, DatabaseType};
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let config = DatabaseConfig::new(DatabaseType::SQLite, ":memory:");
/// let conn = DatabaseConnection::new(config).await?;
///
/// let rows = conn.fetch_all("SELECT name FROM sqlite_master WHERE type='table'").await?;
/// println!("Found {} tables", rows.len());
/// Ok(())
/// }
/// ```
pub async fn fetch_all(&self, sql: &str) -> Result<Vec<HashMap<String, serde_json::Value>>> {
#[cfg(feature = "db")]
{
match self {
DatabaseConnection::SQLite(pool) => {
let rows = sqlx::query(sql)
.fetch_all(pool)
.await
.map_err(|e| Error::database(format!("SQL fetch failed: {}", e)))?;
let mut result = Vec::new();
for row in rows {
let mut map = HashMap::new();
for (i, column) in row.columns().iter().enumerate() {
let column_name = Column::name(column).to_string();
// Simplified value extraction - convert everything to string for now
let value: serde_json::Value = match row.try_get::<String, _>(i) {
Ok(s) => serde_json::Value::String(s),
Err(_) => serde_json::Value::Null,
};
map.insert(column_name, value);
}
result.push(map);
}
Ok(result)
}
DatabaseConnection::PostgreSQL(pool) => {
let rows = sqlx::query(sql)
.fetch_all(pool)
.await
.map_err(|e| Error::database(format!("SQL fetch failed: {}", e)))?;
let mut result = Vec::new();
for row in rows {
let mut map = HashMap::new();
for (i, column) in row.columns().iter().enumerate() {
let column_name = Column::name(column).to_string();
let value: serde_json::Value = match row.try_get::<String, _>(i) {
Ok(s) => serde_json::Value::String(s),
Err(_) => serde_json::Value::Null,
};
map.insert(column_name, value);
}
result.push(map);
}
Ok(result)
}
DatabaseConnection::MySQL(pool) => {
let rows = sqlx::query(sql)
.fetch_all(pool)
.await
.map_err(|e| Error::database(format!("SQL fetch failed: {}", e)))?;
let mut result = Vec::new();
for row in rows {
let mut map = HashMap::new();
for (i, column) in row.columns().iter().enumerate() {
let column_name = Column::name(column).to_string();
let value: serde_json::Value = match row.try_get::<String, _>(i) {
Ok(s) => serde_json::Value::String(s),
Err(_) => serde_json::Value::Null,
};
map.insert(column_name, value);
}
result.push(map);
}
Ok(result)
}
DatabaseConnection::Mock => Ok(vec![]),
}
}
#[cfg(not(feature = "db"))]
{
let _ = sql; // Avoid unused variable warning
Ok(vec![])
}
}
/// Fetch a single row from a SQL query
///
/// # Examples
///
/// ```rust
/// use rutool::db::{DatabaseConnection, DatabaseConfig, DatabaseType};
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let config = DatabaseConfig::new(DatabaseType::SQLite, ":memory:");
/// let conn = DatabaseConnection::new(config).await?;
///
/// let row = conn.fetch_one("SELECT 'Hello' as greeting").await?;
/// if let Some(greeting) = row.get("greeting") {
/// println!("Greeting: {}", greeting);
/// }
/// Ok(())
/// }
/// ```
pub async fn fetch_one(&self, sql: &str) -> Result<Option<HashMap<String, serde_json::Value>>> {
#[cfg(feature = "db")]
{
match self {
DatabaseConnection::SQLite(pool) => {
let row = sqlx::query(sql)
.fetch_optional(pool)
.await
.map_err(|e| Error::database(format!("SQL fetch failed: {}", e)))?;
if let Some(row) = row {
let mut map = HashMap::new();
for (i, column) in row.columns().iter().enumerate() {
let column_name = Column::name(column).to_string();
let value: serde_json::Value = match row.try_get::<String, _>(i) {
Ok(s) => serde_json::Value::String(s),
Err(_) => serde_json::Value::Null,
};
map.insert(column_name, value);
}
Ok(Some(map))
} else {
Ok(None)
}
}
DatabaseConnection::PostgreSQL(pool) => {
let row = sqlx::query(sql)
.fetch_optional(pool)
.await
.map_err(|e| Error::database(format!("SQL fetch failed: {}", e)))?;
if let Some(row) = row {
let mut map = HashMap::new();
for (i, column) in row.columns().iter().enumerate() {
let column_name = Column::name(column).to_string();
let value: serde_json::Value = match row.try_get::<String, _>(i) {
Ok(s) => serde_json::Value::String(s),
Err(_) => serde_json::Value::Null,
};
map.insert(column_name, value);
}
Ok(Some(map))
} else {
Ok(None)
}
}
DatabaseConnection::MySQL(pool) => {
let row = sqlx::query(sql)
.fetch_optional(pool)
.await
.map_err(|e| Error::database(format!("SQL fetch failed: {}", e)))?;
if let Some(row) = row {
let mut map = HashMap::new();
for (i, column) in row.columns().iter().enumerate() {
let column_name = Column::name(column).to_string();
let value: serde_json::Value = match row.try_get::<String, _>(i) {
Ok(s) => serde_json::Value::String(s),
Err(_) => serde_json::Value::Null,
};
map.insert(column_name, value);
}
Ok(Some(map))
} else {
Ok(None)
}
}
DatabaseConnection::Mock => Ok(None),
}
}
#[cfg(not(feature = "db"))]
{
let _ = sql; // Avoid unused variable warning
Ok(None)
}
}
/// Begin a database transaction
///
/// # Examples
///
/// ```rust
/// use rutool::db::{DatabaseConnection, DatabaseConfig, DatabaseType};
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let config = DatabaseConfig::new(DatabaseType::SQLite, ":memory:");
/// let conn = DatabaseConnection::new(config).await?;
///
/// let tx = conn.begin_transaction().await?;
/// // Perform operations within transaction
/// tx.commit().await?;
/// Ok(())
/// }
/// ```
pub async fn begin_transaction(&self) -> Result<DatabaseTransaction> {
#[cfg(feature = "db")]
{
match self {
DatabaseConnection::SQLite(pool) => {
let tx = pool.begin()
.await
.map_err(|e| Error::database(format!("Failed to begin transaction: {}", e)))?;
Ok(DatabaseTransaction::SQLite(tx))
}
DatabaseConnection::PostgreSQL(pool) => {
let tx = pool.begin()
.await
.map_err(|e| Error::database(format!("Failed to begin transaction: {}", e)))?;
Ok(DatabaseTransaction::PostgreSQL(tx))
}
DatabaseConnection::MySQL(pool) => {
let tx = pool.begin()
.await
.map_err(|e| Error::database(format!("Failed to begin transaction: {}", e)))?;
Ok(DatabaseTransaction::MySQL(tx))
}
DatabaseConnection::Mock => Ok(DatabaseTransaction::Mock),
}
}
#[cfg(not(feature = "db"))]
{
Ok(DatabaseTransaction::Mock)
}
}
/// Check if the connection is healthy
pub async fn is_healthy(&self) -> bool {
#[cfg(feature = "db")]
{
match self {
DatabaseConnection::SQLite(pool) => !pool.is_closed(),
DatabaseConnection::PostgreSQL(pool) => !pool.is_closed(),
DatabaseConnection::MySQL(pool) => !pool.is_closed(),
DatabaseConnection::Mock => true,
}
}
#[cfg(not(feature = "db"))]
true
}
/// Close the database connection
pub async fn close(&self) {
#[cfg(feature = "db")]
{
match self {
DatabaseConnection::SQLite(pool) => pool.close().await,
DatabaseConnection::PostgreSQL(pool) => pool.close().await,
DatabaseConnection::MySQL(pool) => pool.close().await,
DatabaseConnection::Mock => {},
}
}
}
}
/// Database transaction wrapper
pub enum DatabaseTransaction {
#[cfg(feature = "db")]
/// SQLite transaction
SQLite(sqlx::Transaction<'static, Sqlite>),
#[cfg(feature = "db")]
/// PostgreSQL transaction
PostgreSQL(sqlx::Transaction<'static, Postgres>),
#[cfg(feature = "db")]
/// MySQL transaction
MySQL(sqlx::Transaction<'static, MySql>),
/// Mock transaction for testing
Mock,
}
impl DatabaseTransaction {
/// Commit the transaction
pub async fn commit(self) -> Result<()> {
#[cfg(feature = "db")]
{
match self {
DatabaseTransaction::SQLite(tx) => {
tx.commit()
.await
.map_err(|e| Error::database(format!("Failed to commit transaction: {}", e)))?;
}
DatabaseTransaction::PostgreSQL(tx) => {
tx.commit()
.await
.map_err(|e| Error::database(format!("Failed to commit transaction: {}", e)))?;
}
DatabaseTransaction::MySQL(tx) => {
tx.commit()
.await
.map_err(|e| Error::database(format!("Failed to commit transaction: {}", e)))?;
}
DatabaseTransaction::Mock => {},
}
}
Ok(())
}
/// Rollback the transaction
pub async fn rollback(self) -> Result<()> {
#[cfg(feature = "db")]
{
match self {
DatabaseTransaction::SQLite(tx) => {
tx.rollback()
.await
.map_err(|e| Error::database(format!("Failed to rollback transaction: {}", e)))?;
}
DatabaseTransaction::PostgreSQL(tx) => {
tx.rollback()
.await
.map_err(|e| Error::database(format!("Failed to rollback transaction: {}", e)))?;
}
DatabaseTransaction::MySQL(tx) => {
tx.rollback()
.await
.map_err(|e| Error::database(format!("Failed to rollback transaction: {}", e)))?;
}
DatabaseTransaction::Mock => {},
}
}
Ok(())
}
}
/// Connection pool manager
#[derive(Debug)]
pub struct ConnectionPool {
connections: HashMap<String, Arc<DatabaseConnection>>,
}
impl ConnectionPool {
/// Create a new connection pool
pub fn new() -> Self {
Self {
connections: HashMap::new(),
}
}
/// Add a connection to the pool
pub fn add_connection(&mut self, name: String, connection: DatabaseConnection) {
self.connections.insert(name, Arc::new(connection));
}
/// Get a connection from the pool
pub fn get_connection(&self, name: &str) -> Option<Arc<DatabaseConnection>> {
self.connections.get(name).cloned()
}
/// Remove a connection from the pool
pub fn remove_connection(&mut self, name: &str) -> Option<Arc<DatabaseConnection>> {
self.connections.remove(name)
}
/// Check if pool contains a connection
pub fn contains(&self, name: &str) -> bool {
self.connections.contains_key(name)
}
/// Get all connection names
pub fn connection_names(&self) -> Vec<String> {
self.connections.keys().cloned().collect()
}
/// Close all connections in the pool
pub async fn close_all(&self) {
for connection in self.connections.values() {
connection.close().await;
}
}
}
impl Default for ConnectionPool {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_database_config_creation() {
let config = DatabaseConfig::new(DatabaseType::SQLite, "test.db");
assert_eq!(config.db_type, DatabaseType::SQLite);
assert_eq!(config.url, "test.db");
assert_eq!(config.max_connections, 10);
}
#[test]
fn test_database_config_builder() {
let config = DatabaseConfig::new(DatabaseType::PostgreSQL, "postgresql://localhost/test")
.with_max_connections(20)
.with_min_connections(5)
.with_connect_timeout(Duration::from_secs(60));
assert_eq!(config.max_connections, 20);
assert_eq!(config.min_connections, 5);
assert_eq!(config.connect_timeout, Duration::from_secs(60));
}
#[test]
fn test_connection_pool() {
let mut pool = ConnectionPool::new();
assert!(!pool.contains("test"));
let _config = DatabaseConfig::new(DatabaseType::SQLite, ":memory:");
// Note: We can't actually create a real connection in tests without tokio runtime
// So we'll use a mock connection
let connection = DatabaseConnection::Mock;
pool.add_connection("test".to_string(), connection);
assert!(pool.contains("test"));
let names = pool.connection_names();
assert_eq!(names.len(), 1);
assert_eq!(names[0], "test");
let conn = pool.get_connection("test");
assert!(conn.is_some());
let removed = pool.remove_connection("test");
assert!(removed.is_some());
assert!(!pool.contains("test"));
}
#[tokio::test]
async fn test_mock_connection_operations() {
let connection = DatabaseConnection::Mock;
// Test basic operations with mock connection
let result = connection.execute("CREATE TABLE test (id INTEGER)").await;
assert!(result.is_ok());
assert_eq!(result.unwrap(), 0);
let rows = connection.fetch_all("SELECT * FROM test").await;
assert!(rows.is_ok());
let rows_data = rows.unwrap();
assert_eq!(rows_data.len(), 0);
let row = connection.fetch_one("SELECT 1 as test").await;
assert!(row.is_ok());
assert!(row.unwrap().is_none());
assert!(connection.is_healthy().await);
}
#[tokio::test]
async fn test_mock_transaction() {
let connection = DatabaseConnection::Mock;
let tx = connection.begin_transaction().await;
assert!(tx.is_ok());
let tx = tx.unwrap();
let commit_result = tx.commit().await;
assert!(commit_result.is_ok());
}
}