Skip to main content

modo_db/
config.rs

1use serde::Deserialize;
2
3/// Database configuration, deserialized from YAML via `modo::config::load()`.
4///
5/// Backend is auto-detected from the URL scheme (`sqlite://` or `postgres://`).
6/// Irrelevant fields are silently ignored for the active backend.
7#[derive(Debug, Clone, Deserialize)]
8#[serde(default)]
9pub struct DatabaseConfig {
10    /// Connection URL (e.g., `sqlite://data.db?mode=rwc` or `postgres://localhost/myapp`).
11    pub url: String,
12    /// Maximum number of connections in the pool.
13    pub max_connections: u32,
14    /// Minimum number of connections in the pool.
15    pub min_connections: u32,
16    /// Seconds to wait for a connection from the pool before timing out (default: 30).
17    pub acquire_timeout_secs: u64,
18    /// Seconds a connection may sit idle in the pool before being closed (default: 600).
19    pub idle_timeout_secs: u64,
20    /// Maximum lifetime of a connection in seconds before it is closed and replaced (default: 1800).
21    pub max_lifetime_secs: u64,
22}
23
24impl Default for DatabaseConfig {
25    fn default() -> Self {
26        Self {
27            url: "sqlite://data/main.db?mode=rwc".to_string(),
28            max_connections: 5,
29            min_connections: 1,
30            acquire_timeout_secs: 30,
31            idle_timeout_secs: 600,
32            max_lifetime_secs: 1800,
33        }
34    }
35}
36
37#[cfg(test)]
38mod tests {
39    use super::*;
40
41    #[test]
42    fn default_timeout_values() {
43        let config = DatabaseConfig::default();
44        assert_eq!(config.acquire_timeout_secs, 30);
45        assert_eq!(config.idle_timeout_secs, 600);
46        assert_eq!(config.max_lifetime_secs, 1800);
47    }
48
49    #[test]
50    fn partial_yaml_deserialization() {
51        let yaml = r#"
52url: "postgres://localhost/test"
53acquire_timeout_secs: 10
54"#;
55        let config: DatabaseConfig = serde_yaml_ng::from_str(yaml).unwrap();
56        assert_eq!(config.url, "postgres://localhost/test");
57        assert_eq!(config.acquire_timeout_secs, 10);
58        // defaults for omitted fields
59        assert_eq!(config.idle_timeout_secs, 600);
60        assert_eq!(config.max_lifetime_secs, 1800);
61        assert_eq!(config.max_connections, 5);
62        assert_eq!(config.min_connections, 1);
63    }
64}