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
//! Database configuration and connection management.
//!
//! This module provides flexible configuration for connecting to different
//! databases (PostgreSQL, MySQL, MariaDB, SQLite) via SeaORM.
#![doc = include_str!("../../doc-tests/db/db_config_module.md")]
use dotenvy::dotenv;
use sea_orm::{ConnectOptions, Database, DatabaseConnection, DbErr, RuntimeErr};
use serde::{Deserialize, Serialize};
use std::env;
use std::time::Duration;
use super::builder::DatabaseConfigBuilder;
use super::engine::{DatabaseEngine, verify_database_driver};
/// Advanced database configuration.
///
/// Contains all parameters needed to establish and manage a database
/// connection, including connection pools and timeouts.
#[doc = include_str!("../../doc-tests/db/db_config_advanced.md")]
#[derive(Clone, Serialize, Deserialize)]
pub struct DatabaseConfig {
/// Database connection URL
// Holds the password in plain text, so it's never serialized and the hand-written `Debug` masks it.
#[serde(skip_serializing)]
pub url: String,
/// Database type (PostgreSQL, MySQL, MariaDB, SQLite)
pub engine: DatabaseEngine,
/// Maximum number of connections in the pool
pub max_connections: u32,
/// Minimum number of connections in the pool
pub min_connections: u32,
/// Timeout for establishing a connection
pub connect_timeout: Duration,
/// Timeout for acquiring a connection from the pool
pub acquire_timeout: Duration,
/// Idle duration before closing a connection
pub idle_timeout: Duration,
/// Maximum lifetime of a connection
pub max_lifetime: Duration,
/// Enable or disable SQL logging
pub sqlx_logging: bool,
}
impl DatabaseConfig {
/// Creates a configuration from a connection URL.
///
/// The database type is automatically detected from the URL.
/// Default values are used for other parameters.
///
/// # Arguments
///
/// * `url` - Connection URL (e.g., "sqlite://db.sqlite", "postgres://user:pass@host/db")
///
/// # Examples
///
/// ```no_run
/// use runique::prelude::DatabaseConfig;
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// // SQLite
/// let config = DatabaseConfig::from_url("sqlite://app.db")?.build();
///
/// // PostgreSQL
/// let config = DatabaseConfig::from_url("postgres://user:pass@localhost/mydb")?
/// .max_connections(100)
/// .build();
/// # Ok(())
/// # }
/// ```
///
/// # Errors
///
/// Returns an error if the URL is invalid or unsupported.
pub fn from_url(url: impl Into<String>) -> Result<DatabaseConfigBuilder, String> {
let url = url.into();
let engine = DatabaseEngine::detect_from_url(&url)?;
Ok(DatabaseConfigBuilder {
config: DatabaseConfig {
url,
engine,
max_connections: 100,
min_connections: 20,
connect_timeout: Duration::from_secs(2),
acquire_timeout: Duration::from_millis(500),
idle_timeout: Duration::from_secs(300),
max_lifetime: Duration::from_secs(3600),
sqlx_logging: false,
},
})
}
/// Creates a configuration from environment variables.
///
/// Reads configuration from a `.env` file or system environment variables.
///
/// # Environment Variables
///
/// **Connection (URL directe — prioritaire)**
/// - `DATABASE_URL` - Full connection URL (e.g., `postgres://user:pass@host/db`). Takes priority over all component variables. Compatible with `sea-orm-cli`.
///
/// **Connection (variables composantes)**
/// - `DB_ENGINE` - Database type: `postgres`, `mysql`, `mariadb`, `sqlite` (default: `sqlite`)
/// - `DB_USER` - Username (required for non-SQLite)
/// - `DB_PASSWORD` - Password (required for non-SQLite)
/// - `DB_HOST` - Host (default: `localhost`)
/// - `DB_PORT` - Port (default: `5432` for PostgreSQL, `3306` for MySQL/MariaDB)
/// - `DB_NAME` - Database name (default: `local_base.sqlite` for SQLite)
///
/// **Connection pool**
/// - `DB_MAX_CONNECTIONS` - Maximum pool size (default: `100`)
/// - `DB_MIN_CONNECTIONS` - Minimum pool size (default: `20`)
///
/// **Timeouts (in seconds)**
/// - `DB_CONNECT_TIMEOUT` - Connection timeout (default: `2`)
/// - `DB_ACQUIRE_TIMEOUT` - Pool acquire timeout in milliseconds (default: `500`)
/// - `DB_IDLE_TIMEOUT` - Idle connection lifetime (default: `300`)
/// - `DB_MAX_LIFETIME` - Maximum connection lifetime (default: `3600`)
///
/// **Logging**
/// - `DB_LOGGING` - Enable SQL query logging: `true` / `false` (default: `false`)
///
/// # Examples
///
/// ```no_run
/// use runique::prelude::DatabaseConfig;
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let config = DatabaseConfig::from_env()?.build();
/// let db = config.connect().await?;
/// # Ok(())
/// # }
/// ```
///
/// # Errors
///
/// Returns an error if required variables are missing.
pub fn from_env() -> Result<DatabaseConfigBuilder, String> {
dotenv().ok();
Self::from_lookup(|key| env::var(key).ok())
}
/// Same as [`from_env`](Self::from_env), but reads each variable through
/// `get` instead of the process environment. The test builder relies on it
/// to read an env file without modifying the environment, which isn't safe
/// while other test threads may be reading it.
///
/// # Errors
///
/// Returns an error if required variables are missing.
pub fn from_lookup(
get: impl Fn(&str) -> Option<String>,
) -> Result<DatabaseConfigBuilder, String> {
// DATABASE_URL takes priority over component variables (compatible with sea-orm-cli)
let url = if let Some(direct_url) = get("DATABASE_URL") {
direct_url
} else {
let engine = get("DB_ENGINE")
.map(|engine| engine.trim().to_ascii_lowercase())
.unwrap_or_else(|| "sqlite".to_string());
match engine.as_str() {
"postgres" | "postgresql" | "mysql" | "mariadb" => {
let db_type = match engine.as_str() {
"postgres" | "postgresql" => ("postgres", "5432", "PostgreSQL"),
"mysql" => ("mysql", "3306", "MySQL"),
"mariadb" => ("mariadb", "3306", "MariaDB"),
_ => unreachable!(),
};
let user = get("DB_USER")
.ok_or_else(|| format!(" DB_USER not set for {}\n\nRequired variables:\n - DB_USER\n - DB_PASSWORD\n - DB_HOST (optional, default: localhost)\n - DB_PORT (optional, default: {})\n - DB_NAME", db_type.2, db_type.1))?;
let password = get("DB_PASSWORD")
.ok_or_else(|| format!(" DB_PASSWORD not set for {}", db_type.2))?;
let host = get("DB_HOST").unwrap_or_else(|| "localhost".to_string());
let port = get("DB_PORT").unwrap_or_else(|| db_type.1.to_string());
let name = get("DB_NAME")
.ok_or_else(|| format!(" DB_NAME not set for {}", db_type.2))?;
format!(
"{}://{}:{}@{}:{}/{}",
db_type.0, user, password, host, port, name
)
}
"sqlite" => {
let name = get("DB_NAME").unwrap_or_else(|| "local_base.sqlite".to_string());
format!("sqlite://{}?mode=rwc", name)
}
other => {
return Err(format!(
" Unsupported DB_ENGINE: {}\n\nSupported engines: postgres, mysql, mariadb, sqlite\nOr set DB_URL directly.",
other
));
}
}
};
let mut builder = Self::from_url(url)?;
if let Some(v) = get("DB_MAX_CONNECTIONS")
&& let Ok(n) = v.parse::<u32>()
{
builder.config.max_connections = n;
}
if let Some(v) = get("DB_MIN_CONNECTIONS")
&& let Ok(n) = v.parse::<u32>()
{
builder.config.min_connections = n;
}
if let Some(v) = get("DB_CONNECT_TIMEOUT")
&& let Ok(n) = v.parse::<u64>()
{
builder.config.connect_timeout = Duration::from_secs(n);
}
if let Some(v) = get("DB_ACQUIRE_TIMEOUT")
&& let Ok(n) = v.parse::<u64>()
{
builder.config.acquire_timeout = Duration::from_millis(n);
}
if let Some(v) = get("DB_IDLE_TIMEOUT")
&& let Ok(n) = v.parse::<u64>()
{
builder.config.idle_timeout = Duration::from_secs(n);
}
if let Some(v) = get("DB_MAX_LIFETIME")
&& let Ok(n) = v.parse::<u64>()
{
builder.config.max_lifetime = Duration::from_secs(n);
}
if let Some(v) = get("DB_LOGGING") {
builder.config.sqlx_logging = crate::utils::config::env::flag_from(&v).unwrap_or(false);
}
Ok(builder)
}
/// Establishes a connection to the database.
///
/// Creates a connection pool configured according to this `DatabaseConfig`.
///
/// # Examples
///
/// ```no_run
/// use runique::prelude::DatabaseConfig;
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let config = DatabaseConfig::from_env()?.build();
/// let db = config.connect().await?;
/// # Ok(())
/// # }
/// ```
///
/// # Errors
///
/// - Returns an error if the driver is not enabled (missing Cargo feature)
/// - Returns an error if the connection fails
pub async fn connect(&self) -> Result<DatabaseConnection, DbErr> {
if let Some(level) = crate::utils::runique_log::get_log()
.db
.as_ref()
.and_then(|d| d.connect)
{
crate::runique_log!(level, " Connecting to {} database...", self.engine.name());
}
verify_database_driver(&self.engine).map_err(DbErr::Custom)?;
let mut opt = ConnectOptions::new(&self.url);
match self.engine {
DatabaseEngine::SQLite => {
opt.max_connections(1).min_connections(1);
}
_ => {
opt.max_connections(self.max_connections)
.min_connections(self.min_connections);
}
}
opt.connect_timeout(self.connect_timeout)
.acquire_timeout(self.acquire_timeout)
.idle_timeout(self.idle_timeout)
.max_lifetime(self.max_lifetime)
.sqlx_logging(self.sqlx_logging)
.sqlx_logging_level(tracing::log::LevelFilter::Off);
match Database::connect(opt).await {
Ok(conn) => {
if let Some(level) = crate::utils::runique_log::get_log()
.db
.as_ref()
.and_then(|d| d.connect)
{
crate::runique_log!(
level,
"Database connected successfully ({})",
self.engine.name()
);
}
Ok(conn)
}
Err(e) => {
tracing::error!("└──> Database connection failed");
tracing::error!(" └──> Engine: {}", self.engine.name());
tracing::error!(" └──> URL: {}", mask_password(&self.url));
Err(redact_url(e, &self.url))
}
}
}
}
impl std::fmt::Debug for DatabaseConfig {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("DatabaseConfig")
.field("url", &mask_password(&self.url))
.field("engine", &self.engine)
.field("max_connections", &self.max_connections)
.field("min_connections", &self.min_connections)
.field("connect_timeout", &self.connect_timeout)
.field("acquire_timeout", &self.acquire_timeout)
.field("idle_timeout", &self.idle_timeout)
.field("max_lifetime", &self.max_lifetime)
.field("sqlx_logging", &self.sqlx_logging)
.finish()
}
}
/// Hides the password in a connection URL so it's safe to log: the one in
/// `user:password@`, and any passed as a query parameter (`?password=…`).
pub(crate) fn mask_password(url: &str) -> String {
mask_query_secrets(&mask_userinfo(url))
}
fn mask_userinfo(url: &str) -> String {
let Some(idx) = url.find("://") else {
return url.to_string();
};
let protocol_end = idx.checked_add(3).filter(|&x| x <= url.len());
let Some(after_protocol) = protocol_end else {
return url.to_string();
};
// Split on the last `@`, not the first: hosts never contain one, but a raw password might.
let Some(at_idx) = url[after_protocol..].rfind('@') else {
return url.to_string();
};
let at_pos = after_protocol.saturating_add(at_idx);
let before = &url[..after_protocol];
let after = &url[at_pos..];
let creds = &url[after_protocol..at_pos];
let Some(colon) = creds.find(':') else {
return url.to_string();
};
let user = &creds[..colon];
format!("{}{}:****{}", before, user, after)
}
/// SeaORM quotes the full connection string in some errors (e.g. "has no
/// supporting driver"), which then reach the terminal through `?`.
pub(crate) fn redact_url(err: DbErr, url: &str) -> DbErr {
match err {
DbErr::Conn(RuntimeErr::Internal(msg)) if msg.contains(url) => {
DbErr::Conn(RuntimeErr::Internal(msg.replace(url, &mask_password(url))))
}
other => other,
}
}
/// libpq, MySQL and sqlx all accept the password as a query parameter too.
fn mask_query_secrets(url: &str) -> String {
const SECRET_KEYS: [&str; 5] = ["password", "pass", "pwd", "passwd", "sslpassword"];
let Some((base, query)) = url.split_once('?') else {
return url.to_string();
};
let params: Vec<String> = query
.split('&')
.map(|param| match param.split_once('=') {
Some((key, _)) if SECRET_KEYS.contains(&key.to_ascii_lowercase().as_str()) => {
format!("{key}=****")
}
_ => param.to_string(),
})
.collect();
format!("{base}?{}", params.join("&"))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_redact_url_hides_the_password_in_a_connection_error() {
let url = "postgresql://postgres:secret123@localhost:5432/db";
let err = DbErr::Conn(RuntimeErr::Internal(format!(
"The connection string '{url}' has no supporting driver."
)));
let shown = redact_url(err, url).to_string();
assert!(!shown.contains("secret123"), "{shown}");
assert!(
shown.contains("postgresql://postgres:****@localhost:5432/db"),
"{shown}"
);
}
#[test]
fn test_redact_url_leaves_other_errors_alone() {
let err = DbErr::Conn(RuntimeErr::Internal("timeout".to_string()));
assert_eq!(
redact_url(err, "postgres://u:p@h/db").to_string(),
"Connection Error: timeout"
);
}
#[test]
fn test_mask_password() {
let url = "postgres://myuser:secret123@localhost:5432/mydb";
let masked = mask_password(url);
assert_eq!(masked, "postgres://myuser:****@localhost:5432/mydb");
}
#[test]
fn test_mask_password_no_password() {
let url = "sqlite://local.db";
let masked = mask_password(url);
assert_eq!(masked, "sqlite://local.db");
}
#[test]
fn test_mask_password_with_at_in_password() {
let url = "postgres://myuser:p@ss@localhost:5432/mydb";
let masked = mask_password(url);
assert_eq!(masked, "postgres://myuser:****@localhost:5432/mydb");
}
#[test]
fn test_mask_password_in_query_parameter() {
let masked = mask_password(
"postgres://db.example.com/app?user=bob&password=hunter2&sslmode=require",
);
assert!(!masked.contains("hunter2"), "{masked}");
assert!(masked.contains("password=****"));
assert!(masked.contains("sslmode=require"));
}
#[test]
fn test_mask_password_in_both_places() {
let masked = mask_password("mysql://bob:secret1@db:3306/app?PWD=secret2");
assert!(
!masked.contains("secret1") && !masked.contains("secret2"),
"{masked}"
);
}
#[test]
fn test_debug_masks_password() {
let config = DatabaseConfig::from_url("postgres://myuser:secret123@localhost:5432/mydb")
.unwrap()
.build();
let debug = format!("{config:?}");
assert!(!debug.contains("secret123"));
assert!(debug.contains("myuser:****@localhost"));
}
#[test]
fn test_from_lookup_builds_url_from_components() {
let vars: std::collections::HashMap<&str, &str> = [
("DB_ENGINE", "postgres"),
("DB_USER", "bob"),
("DB_PASSWORD", "secret"),
("DB_NAME", "app"),
]
.into();
let config = DatabaseConfig::from_lookup(|key| vars.get(key).map(|v| v.to_string()))
.unwrap()
.build();
assert_eq!(config.url, "postgres://bob:secret@localhost:5432/app");
}
#[test]
fn test_from_lookup_database_url_wins() {
let vars: std::collections::HashMap<&str, &str> = [
("DATABASE_URL", "sqlite://direct.db"),
("DB_ENGINE", "postgres"),
]
.into();
let config = DatabaseConfig::from_lookup(|key| vars.get(key).map(|v| v.to_string()))
.unwrap()
.build();
assert_eq!(config.url, "sqlite://direct.db");
}
#[test]
fn test_serialize_skips_url() {
let config = DatabaseConfig::from_url("postgres://myuser:secret123@localhost:5432/mydb")
.unwrap()
.build();
let json = serde_json::to_value(&config).unwrap();
assert!(json.get("url").is_none());
assert!(!json.to_string().contains("secret123"));
}
#[test]
fn test_detect_engine() {
assert_eq!(
DatabaseEngine::detect_from_url("postgres://localhost/db").unwrap(),
DatabaseEngine::PostgreSQL
);
assert_eq!(
DatabaseEngine::detect_from_url("mysql://localhost/db").unwrap(),
DatabaseEngine::MySQL
);
assert_eq!(
DatabaseEngine::detect_from_url("sqlite://db.sqlite").unwrap(),
DatabaseEngine::SQLite
);
}
}