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
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
//! Global database access for RustF framework
//!
//! This module provides global database access with support for both
//! single database (legacy) and multiple database connections.
use crate::database::config::DatabasesConfig;
use crate::database::types::SqlValue;
use crate::database::{adapters::*, DatabaseAdapter, DatabaseRegistry};
use crate::error::{Error, Result};
use crate::models::query_builder::{AnyDatabase, DatabaseBackend, QueryBuilder};
use once_cell::sync::OnceCell;
use std::sync::Arc;
/// Global database instance (for backward compatibility)
static DATABASE: OnceCell<Option<Arc<AnyDatabase>>> = OnceCell::new();
/// Global database registry (for multi-database support)
static REGISTRY: OnceCell<Arc<DatabaseRegistry>> = OnceCell::new();
/// Global database access point
pub struct DB;
impl DB {
/// Initialize the global database connection from a database URL (legacy)
///
/// This method maintains backward compatibility with existing code.
/// For new applications, consider using `init_registry` for multi-database support.
///
/// # Arguments
/// * `database_url` - Optional database connection URL. If None, database operations will return errors.
///
/// # Examples
/// ```no_run
/// # use rustf::prelude::*;
/// # async fn _doctest() -> rustf::Result<()> {
/// // Initialize with MySQL
/// DB::init(Some("mysql://user:pass@localhost/mydb")).await?;
///
/// // Initialize without database (some apps don't need it)
/// DB::init(None).await?;
/// # Ok(()) }
/// ```
pub async fn init(database_url: Option<&str>) -> Result<()> {
// Initialize registry if not already done
let _ = REGISTRY.get_or_init(|| Arc::new(DatabaseRegistry::new()));
let db_option = if let Some(url) = database_url {
log::info!(
"Initializing database connection to: {}",
Self::sanitize_url(url)
);
// Also add to registry as default
if let Ok(registry) = Self::get_registry() {
let adapter = Self::create_adapter("primary", url).await?;
registry.register("primary", adapter, true).await?;
}
match AnyDatabase::connect(url).await {
Ok(db) => {
log::info!("Database connected");
Some(Arc::new(db))
}
Err(e) => {
log::error!("Failed to connect to database: {}", e);
return Err(Error::database_connection(format!(
"Database connection failed: {}",
e
)));
}
}
} else {
None
};
DATABASE.set(db_option).map_err(|_| {
Error::database_connection("Database has already been initialized".to_string())
})?;
Ok(())
}
/// Initialize database registry with multiple databases
///
/// This is the new recommended way to initialize databases, supporting
/// multiple named connections.
///
/// # Arguments
/// * `config` - Database configuration with one or more database connections
///
/// # Examples
/// ```no_run
/// # use rustf::prelude::*;
/// # use rustf::database::config::{DatabasesConfig, DatabaseConnectionConfigBuilder};
/// # async fn _doctest() -> rustf::Result<()> {
/// let mut config = DatabasesConfig::new();
/// config.add_database("primary", DatabaseConnectionConfigBuilder::new()
/// .url("postgresql://localhost/main")
/// .max_connections(20)
/// .build()
/// .unwrap());
/// config.add_database("analytics", DatabaseConnectionConfigBuilder::new()
/// .url("mysql://localhost/analytics")
/// .max_connections(10)
/// .build()
/// .unwrap());
///
/// DB::init_registry(config).await?;
/// # Ok(()) }
/// ```
pub async fn init_registry(config: DatabasesConfig) -> Result<()> {
let registry = REGISTRY.get_or_init(|| Arc::new(DatabaseRegistry::new()));
// Get default database name if any
let default_name = config.get_default().map(|(name, _)| name.clone());
// Register all databases
for (name, db_config) in &config.databases {
log::info!(
"Registering database '{}': {}",
name,
Self::sanitize_url(&db_config.url)
);
let adapter = Self::create_adapter(name, &db_config.url).await?;
let is_default = default_name.as_ref().map(|d| d == name).unwrap_or(false);
registry.register(name.clone(), adapter, is_default).await?;
}
// If we have a default database, also set it in the legacy DATABASE global
if let Some(default_name) = default_name {
if let Some(_adapter) = registry.get(&default_name).await {
// Convert adapter back to AnyDatabase for legacy compatibility
// This is a bit of a hack but maintains backward compatibility
if let Some(default_config) = config.get(&default_name) {
if let Ok(db) = AnyDatabase::connect(&default_config.url).await {
let _ = DATABASE.set(Some(Arc::new(db)));
}
}
}
}
Ok(())
}
/// Create a database adapter based on the URL
async fn create_adapter(name: &str, url: &str) -> Result<Box<dyn DatabaseAdapter>> {
let _ = name;
#[cfg(feature = "db-postgres")]
if url.starts_with("postgresql://") || url.starts_with("postgres://") {
let adapter = PostgresAdapter::new(name, url).await?;
return Ok(Box::new(adapter));
}
#[cfg(feature = "db-mysql")]
if url.starts_with("mysql://") || url.starts_with("mariadb://") {
let adapter = MySqlAdapter::new(name, url).await?;
return Ok(Box::new(adapter));
}
#[cfg(feature = "db-sqlite")]
if url.starts_with("sqlite://") {
let adapter = SqliteAdapter::new(name, url).await?;
return Ok(Box::new(adapter));
}
Err(Error::database_connection(format!(
"Unsupported database URL scheme (or its driver feature is not enabled): {}",
url
)))
}
/// Get access to the database registry
fn get_registry() -> Result<Arc<DatabaseRegistry>> {
REGISTRY.get().cloned().ok_or_else(|| {
Error::database_connection("Database registry not initialized".to_string())
})
}
/// Use a specific named database
///
/// # Arguments
/// * `name` - Name of the database to use
///
/// # Returns
/// A database handle that can be used to execute queries
///
/// # Examples
/// ```no_run
/// # use rustf::prelude::*;
/// # async fn _doctest() -> std::result::Result<(), Box<dyn std::error::Error>> {
/// let users = DB::r#use("analytics")
/// .await?
/// .query()
/// .from("users")
/// .where_eq("active", true)
/// .build()?;
/// # Ok(()) }
/// ```
pub async fn r#use(name: &str) -> Result<Box<dyn DatabaseAdapter>> {
let registry = Self::get_registry()?;
registry
.get(name)
.await
.ok_or_else(|| Error::database_connection(format!("Database '{}' not found", name)))
}
/// Get a specific database adapter
///
/// Alias for `use` that doesn't require the `r#` prefix
pub async fn adapter(name: &str) -> Result<Box<dyn DatabaseAdapter>> {
Self::r#use(name).await
}
/// Get a query builder for the configured database
///
/// Returns a QueryBuilder that's pre-configured for the current database backend.
/// This maintains backward compatibility with existing code.
///
/// # Returns
/// * `Ok(QueryBuilder)` - Ready-to-use query builder
/// * `Err(Error)` - If database is not initialized or not configured
///
/// # Examples
/// ```no_run
/// # use rustf::prelude::*;
/// # fn _doctest() -> std::result::Result<(), Box<dyn std::error::Error>> {
/// let users = DB::query()?
/// .from("users")
/// .where_eq("active", true)
/// .limit(10)
/// .build()?;
/// # Ok(()) }
/// ```
pub fn query() -> Result<QueryBuilder> {
// First try registry default
if let Ok(registry) = Self::get_registry() {
if let Ok(query) = futures::executor::block_on(registry.query_default()) {
return Ok(query);
}
}
// Fall back to legacy DATABASE
match Self::connection() {
Some(db) => Ok(db.query()),
None => Err(Error::database_connection(
"Database not configured. Add database.url to your configuration or call DB::init()".to_string()
))
}
}
/// Get direct access to the database connection
///
/// Returns the underlying AnyDatabase connection for advanced operations.
///
/// # Returns
/// * `Some(Arc<AnyDatabase>)` - Database connection if initialized
/// * `None` - If no database is configured
pub fn connection() -> Option<Arc<AnyDatabase>> {
DATABASE.get()?.clone()
}
/// Get the database connection pool for direct use
///
/// This method is for compatibility with code expecting DB::get().
/// Returns a Result containing the database connection.
///
/// # Returns
/// * `Ok(Arc<AnyDatabase>)` - Database connection if initialized
/// * `Err(Error)` - If database is not configured
pub async fn get() -> Result<Arc<AnyDatabase>> {
Self::connection().ok_or_else(|| {
Error::database_connection(
"Database not configured. Add database.url to your configuration".to_string(),
)
})
}
/// Check if database is initialized and available
///
/// # Returns
/// * `true` - Database is ready for use
/// * `false` - Database is not configured or initialization failed
pub fn is_initialized() -> bool {
// Check both registry and legacy DATABASE
if let Ok(registry) = Self::get_registry() {
if futures::executor::block_on(registry.stats()).total_databases > 0 {
return true;
}
}
DATABASE.get().map(|db| db.is_some()).unwrap_or(false)
}
/// Get the database backend type if initialized
///
/// # Returns
/// * `Some(DatabaseBackend)` - The type of database (Postgres, MySQL, SQLite)
/// * `None` - If database is not initialized
pub fn backend() -> Option<DatabaseBackend> {
Self::connection().map(|db| db.backend())
}
/// Get the PostgreSQL pool if database is PostgreSQL
///
/// # Returns
/// * `Ok(Arc<sqlx::PgPool>)` - PostgreSQL connection pool wrapped in Arc
/// * `Err(Error)` - If database is not configured or is not PostgreSQL
#[cfg(feature = "db-postgres")]
pub fn pg_pool() -> Result<Arc<sqlx::PgPool>> {
let db = Self::connection()
.ok_or_else(|| Error::database_connection("Database not configured".to_string()))?;
match db.as_ref() {
AnyDatabase::Postgres(pool) => Ok(Arc::new(pool.clone())),
#[allow(unreachable_patterns)]
_ => Err(Error::database_connection(
"Database is not PostgreSQL".to_string(),
)),
}
}
/// Get the MySQL pool if database is MySQL
///
/// # Returns
/// * `Ok(Arc<sqlx::MySqlPool>)` - MySQL connection pool wrapped in Arc
/// * `Err(Error)` - If database is not configured or is not MySQL
#[cfg(feature = "db-mysql")]
pub fn mysql_pool() -> Result<Arc<sqlx::MySqlPool>> {
let db = Self::connection()
.ok_or_else(|| Error::database_connection("Database not configured".to_string()))?;
match db.as_ref() {
AnyDatabase::MySQL(pool) => Ok(Arc::new(pool.clone())),
#[allow(unreachable_patterns)]
_ => Err(Error::database_connection(
"Database is not MySQL".to_string(),
)),
}
}
/// Get the SQLite pool if database is SQLite
///
/// # Returns
/// * `Ok(Arc<sqlx::SqlitePool>)` - SQLite connection pool wrapped in Arc
/// * `Err(Error)` - If database is not configured or is not SQLite
#[cfg(feature = "db-sqlite")]
pub fn sqlite_pool() -> Result<Arc<sqlx::SqlitePool>> {
let db = Self::connection()
.ok_or_else(|| Error::database_connection("Database not configured".to_string()))?;
match db.as_ref() {
AnyDatabase::SQLite(pool) => Ok(Arc::new(pool.clone())),
#[allow(unreachable_patterns)]
_ => Err(Error::database_connection(
"Database is not SQLite".to_string(),
)),
}
}
/// Execute a query with parameters using the appropriate database adapter
///
/// This method automatically handles database-specific type conversions
/// through the adapter layer, eliminating the need for database-specific
/// binding code in models.
///
/// # Arguments
/// * `sql` - SQL query to execute
/// * `params` - Parameters to bind to the query
///
/// # Returns
/// * `Ok(u64)` - Number of rows affected
/// * `Err(Error)` - If execution fails
pub async fn execute_with_params(sql: &str, params: Vec<SqlValue>) -> Result<u64> {
// Try registry first
if let Ok(registry) = Self::get_registry() {
if let Ok(adapter) = registry.get_default().await {
let result = adapter.execute(sql, params).await?;
return Ok(result.rows_affected);
}
}
// Fallback to legacy connection
let db = Self::connection()
.ok_or_else(|| Error::database_connection("Database not configured".to_string()))?;
// Use the appropriate adapter based on database type
match db.as_ref() {
#[cfg(feature = "db-postgres")]
AnyDatabase::Postgres(pool) => {
use crate::database::adapters::PostgresAdapter;
let adapter = PostgresAdapter::from_pool("default", pool.clone());
let result = adapter.execute(sql, params).await?;
Ok(result.rows_affected)
}
#[cfg(feature = "db-mysql")]
AnyDatabase::MySQL(pool) => {
use crate::database::adapters::MySqlAdapter;
let adapter = MySqlAdapter::from_pool("default", pool.clone());
let result = adapter.execute(sql, params).await?;
Ok(result.rows_affected)
}
#[cfg(feature = "db-sqlite")]
AnyDatabase::SQLite(pool) => {
use crate::database::adapters::SqliteAdapter;
let adapter = SqliteAdapter::from_pool("default", pool.clone());
let result = adapter.execute(sql, params).await?;
Ok(result.rows_affected)
}
}
}
/// Fetch all rows from a query with parameters
///
/// Returns results as JSON values for flexibility.
///
/// # Arguments
/// * `sql` - SQL query to execute
/// * `params` - Parameters to bind to the query
///
/// # Returns
/// * `Ok(Vec<serde_json::Value>)` - Query results as JSON
/// * `Err(Error)` - If execution fails
pub async fn fetch_all_with_params(
sql: &str,
params: Vec<SqlValue>,
) -> Result<Vec<serde_json::Value>> {
// Try registry first
if let Ok(registry) = Self::get_registry() {
if let Ok(adapter) = registry.get_default().await {
return adapter.fetch_all(sql, params).await;
}
}
// Fallback to legacy connection
let db = Self::connection()
.ok_or_else(|| Error::database_connection("Database not configured".to_string()))?;
// Use the appropriate adapter based on database type
match db.as_ref() {
#[cfg(feature = "db-postgres")]
AnyDatabase::Postgres(pool) => {
use crate::database::adapters::PostgresAdapter;
let adapter = PostgresAdapter::from_pool("default", pool.clone());
adapter.fetch_all(sql, params).await
}
#[cfg(feature = "db-mysql")]
AnyDatabase::MySQL(pool) => {
use crate::database::adapters::MySqlAdapter;
let adapter = MySqlAdapter::from_pool("default", pool.clone());
adapter.fetch_all(sql, params).await
}
#[cfg(feature = "db-sqlite")]
AnyDatabase::SQLite(pool) => {
use crate::database::adapters::SqliteAdapter;
let adapter = SqliteAdapter::from_pool("default", pool.clone());
adapter.fetch_all(sql, params).await
}
}
}
/// Fetch one row from a query with parameters
///
/// Returns result as JSON value for flexibility.
///
/// # Arguments
/// * `sql` - SQL query to execute
/// * `params` - Parameters to bind to the query
///
/// # Returns
/// * `Ok(Option<serde_json::Value>)` - Query result as JSON if found
/// * `Err(Error)` - If execution fails
pub async fn fetch_one_with_params(
sql: &str,
params: Vec<SqlValue>,
) -> Result<Option<serde_json::Value>> {
// Try registry first
if let Ok(registry) = Self::get_registry() {
if let Ok(adapter) = registry.get_default().await {
return adapter.fetch_one(sql, params).await;
}
}
// Fallback to legacy connection
let db = Self::connection()
.ok_or_else(|| Error::database_connection("Database not configured".to_string()))?;
// Use the appropriate adapter based on database type
match db.as_ref() {
#[cfg(feature = "db-postgres")]
AnyDatabase::Postgres(pool) => {
use crate::database::adapters::PostgresAdapter;
let adapter = PostgresAdapter::from_pool("default", pool.clone());
adapter.fetch_one(sql, params).await
}
#[cfg(feature = "db-mysql")]
AnyDatabase::MySQL(pool) => {
use crate::database::adapters::MySqlAdapter;
let adapter = MySqlAdapter::from_pool("default", pool.clone());
adapter.fetch_one(sql, params).await
}
#[cfg(feature = "db-sqlite")]
AnyDatabase::SQLite(pool) => {
use crate::database::adapters::SqliteAdapter;
let adapter = SqliteAdapter::from_pool("default", pool.clone());
adapter.fetch_one(sql, params).await
}
}
}
/// Execute an INSERT query and return the inserted row
///
/// This method handles database-specific RETURNING syntax and type conversions.
/// For databases that don't support RETURNING, it uses alternative methods
/// to fetch the inserted row.
///
/// # Arguments
/// * `sql` - INSERT SQL query (without RETURNING clause)
/// * `params` - Parameters to bind to the query
/// * `table` - Table name for fallback fetch
/// * `id_field` - Name of the ID field for fallback fetch
///
/// # Returns
/// * `Ok(Some(JsonValue))` - The inserted row as JSON
/// * `Err(Error)` - If insertion fails
pub async fn execute_insert_returning(
sql: &str,
params: Vec<SqlValue>,
table: &str,
id_field: &str,
) -> Result<Option<serde_json::Value>> {
// Try registry first
if let Ok(registry) = Self::get_registry() {
if let Ok(adapter) = registry.get_default().await {
// Add RETURNING clause based on database type
if adapter.backend() == DatabaseBackend::Postgres {
// PostgreSQL supports RETURNING, but has issues with enum types
// Try RETURNING first, fall back to separate INSERT + SELECT if it fails
let sql_with_returning = format!("{} RETURNING *", sql);
match adapter.fetch_one(&sql_with_returning, params.clone()).await {
Ok(result) => return Ok(result),
Err(e) if e.to_string().contains("but expression is of type") => {
// Enum type error - fall back to INSERT then SELECT
log::debug!(
"PostgreSQL enum type issue detected, using fallback approach"
);
// Execute the INSERT without RETURNING
adapter.execute(sql, params).await?;
// Fetch the inserted row using a simple SELECT
// This assumes we have an id field - might need adjustment
let fetch_sql = format!(
"SELECT * FROM {} ORDER BY {} DESC LIMIT 1",
table, id_field
);
return adapter.fetch_one(&fetch_sql, vec![]).await;
}
Err(e) => return Err(e),
}
} else if adapter.backend() == DatabaseBackend::SQLite {
// SQLite also supports RETURNING (since 3.35)
let sql_with_returning = format!("{} RETURNING *", sql);
return adapter.fetch_one(&sql_with_returning, params).await;
} else {
// MySQL and SQLite need alternative approach
let result = adapter.execute(sql, params).await?;
// Fetch the inserted row
let fetch_sql = match adapter.backend() {
DatabaseBackend::MySQL | DatabaseBackend::MariaDB => {
// Use LAST_INSERT_ID() for MySQL/MariaDB
if let Some(last_id) = result.last_insert_id {
format!("SELECT * FROM {} WHERE {} = {}", table, id_field, last_id)
} else {
return Ok(None);
}
}
DatabaseBackend::SQLite => {
// SQLite uses last_insert_rowid()
format!(
"SELECT * FROM {} WHERE {} = last_insert_rowid()",
table, id_field
)
}
_ => return Ok(None),
};
return adapter.fetch_one(&fetch_sql, vec![]).await;
}
}
}
// Fallback to legacy connection
let db = Self::connection()
.ok_or_else(|| Error::database_connection("Database not configured".to_string()))?;
// Use the appropriate adapter based on database type
match db.as_ref() {
#[cfg(feature = "db-postgres")]
AnyDatabase::Postgres(pool) => {
use crate::database::adapters::PostgresAdapter;
let adapter = PostgresAdapter::from_pool("default", pool.clone());
// Add RETURNING clause for PostgreSQL
let sql_with_returning = format!("{} RETURNING *", sql);
adapter.fetch_one(&sql_with_returning, params).await
}
#[cfg(feature = "db-mysql")]
AnyDatabase::MySQL(pool) => {
use crate::database::adapters::MySqlAdapter;
let adapter = MySqlAdapter::from_pool("default", pool.clone());
let result = adapter.execute(sql, params).await?;
if let Some(last_id) = result.last_insert_id {
let fetch_sql =
format!("SELECT * FROM {} WHERE {} = {}", table, id_field, last_id);
adapter.fetch_one(&fetch_sql, vec![]).await
} else {
Ok(None)
}
}
#[cfg(feature = "db-sqlite")]
AnyDatabase::SQLite(pool) => {
use crate::database::adapters::SqliteAdapter;
let adapter = SqliteAdapter::from_pool("default", pool.clone());
// Add RETURNING clause for SQLite
let sql_with_returning = format!("{} RETURNING *", sql);
adapter.fetch_one(&sql_with_returning, params).await
}
}
}
/// Test database connectivity
///
/// Sends a simple ping/test query to verify the database connection is alive.
/// This is useful for health checks and monitoring.
///
/// # Returns
/// * `Ok(true)` - Database is connected and responding
/// * `Ok(false)` - Database is not configured (no connection URL)
/// * `Err(Error)` - Database is configured but connection test failed
///
/// # Examples
/// ```no_run
/// # use rustf::prelude::*;
/// # async fn _doctest() -> rustf::Result<()> {
/// // Health check during startup or monitoring
/// if DB::ping().await? {
/// println!("Database is healthy");
/// }
/// # Ok(()) }
/// ```
pub async fn ping() -> Result<bool> {
// Try registry first
if let Ok(registry) = Self::get_registry() {
if let Ok(adapter) = registry.get_default().await {
return adapter.ping().await;
}
}
// Fall back to legacy DATABASE
// If no database is configured, return false (not an error)
let db = match Self::connection() {
Some(connection) => connection,
None => return Ok(false),
};
// Test connectivity based on database type
match db.as_ref() {
#[cfg(feature = "db-postgres")]
AnyDatabase::Postgres(pool) => {
// PostgreSQL: SELECT 1
sqlx::query("SELECT 1")
.fetch_one(pool)
.await
.map(|_| true)
.map_err(|e| {
Error::database_connection(format!("PostgreSQL ping failed: {}", e))
})
}
#[cfg(feature = "db-mysql")]
AnyDatabase::MySQL(pool) => {
// MySQL: SELECT 1
sqlx::query("SELECT 1")
.fetch_one(pool)
.await
.map(|_| true)
.map_err(|e| Error::database_connection(format!("MySQL ping failed: {}", e)))
}
#[cfg(feature = "db-sqlite")]
AnyDatabase::SQLite(pool) => {
// SQLite: SELECT 1
sqlx::query("SELECT 1")
.fetch_one(pool)
.await
.map(|_| true)
.map_err(|e| Error::database_connection(format!("SQLite ping failed: {}", e)))
}
}
}
/// Gracefully close all database connections
///
/// This method should be called during application shutdown to ensure
/// all database connections are properly closed and resources are released.
///
/// # Examples
/// ```no_run
/// # use rustf::prelude::*;
/// # async fn _doctest() -> rustf::Result<()> {
/// // During application shutdown
/// DB::shutdown().await?;
/// # Ok(()) }
/// ```
pub async fn shutdown() -> Result<()> {
// Shutdown registry databases
if let Ok(registry) = Self::get_registry() {
registry.clear().await;
}
// Shutdown legacy DATABASE
if let Some(db_option) = DATABASE.get() {
if let Some(connection) = db_option.as_ref() {
match connection.as_ref() {
#[cfg(feature = "db-postgres")]
AnyDatabase::Postgres(pool) => {
pool.close().await;
}
#[cfg(feature = "db-mysql")]
AnyDatabase::MySQL(pool) => {
pool.close().await;
}
#[cfg(feature = "db-sqlite")]
AnyDatabase::SQLite(pool) => {
pool.close().await;
}
}
}
}
Ok(())
}
/// Sanitize database URL for logging (hide password)
fn sanitize_url(url: &str) -> String {
if let Ok(parsed) = url::Url::parse(url) {
let mut sanitized = parsed.clone();
if sanitized.password().is_some() {
let _ = sanitized.set_password(Some("***"));
}
sanitized.to_string()
} else {
"[invalid URL]".to_string()
}
}
}
/// Helper function to check database status for debugging
pub fn database_status() -> String {
// Check registry first
if let Ok(registry) = DB::get_registry() {
let stats = futures::executor::block_on(registry.stats());
if stats.total_databases > 0 {
return format!(
"Database: {} registered (default: {:?})",
stats.total_databases, stats.default_database
);
}
}
// Fall back to legacy DATABASE
if let Some(db) = DB::connection() {
format!("Database: Connected ({:?})", db.backend())
} else if DATABASE.get().is_some() {
"Database: Configured but not connected".to_string()
} else {
"Database: Not configured".to_string()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn test_db_query_without_connection() {
// Test behavior when database is not properly initialized
// Note: We can't reset global state due to OnceCell limitations
// This test checks error handling when no connection exists
// If DATABASE is already initialized with None, query should return error
if let Some(None) = DATABASE.get() {
assert!(DB::query().is_err());
assert!(DB::connection().is_none());
assert!(!DB::is_initialized());
}
// If DATABASE has a connection, we can't test this scenario
// This is a limitation of global state testing
}
#[tokio::test]
async fn test_db_initialization_without_url() {
// Test initialization with None URL
// Note: This test may fail if DATABASE is already initialized
match DB::init(None).await {
Ok(_) => {
// Successfully initialized with None
assert!(!DB::is_initialized());
assert!(DB::connection().is_none());
}
Err(_) => {
// DATABASE was already initialized - this is expected in test environments
// We can't reset OnceCell in tests, so this is acceptable
}
}
// Query should return error when no URL provided
assert!(DATABASE.get().is_some());
}
#[test]
fn test_url_sanitization() {
let url = "mysql://user:password@localhost/db";
let sanitized = DB::sanitize_url(url);
assert!(sanitized.contains("user:***"));
assert!(!sanitized.contains("password"));
}
#[test]
fn test_database_status() {
let status = database_status();
assert!(status.starts_with("Database:"));
}
}