Skip to main content

modkit_db/
config.rs

1//! Database configuration types.
2//!
3//! This module contains the canonical definitions of all database configuration
4//! structures used throughout the system. These types are deserialized directly
5//! from Figment configuration.
6//!
7//! # Configuration Precedence Rules
8//!
9//! The database configuration system follows a strict precedence hierarchy when
10//! merging global server configurations with module-specific overrides:
11//!
12//! | Priority | Source | Description | Example |
13//! |----------|--------|-------------|---------|
14//! | 1 (Highest) | Module `params` map | Key-value parameters in module config | `params: {synchronous: "FULL"}` |
15//! | 2 | Module DSN query params | Parameters in module-level DSN | `sqlite://file.db?synchronous=NORMAL` |
16//! | 3 | Module fields | Individual connection fields | `host: "localhost", port: 5432` |
17//! | 4 | Module DSN base | Core DSN without query params | `postgres://user:pass@host/db` |
18//! | 5 | Server `params` map | Key-value parameters in server config | Global server `params` |
19//! | 6 | Server DSN query params | Parameters in server-level DSN | Server DSN query string |
20//! | 7 | Server fields | Individual connection fields in server | Server `host`, `port`, etc. |
21//! | 8 (Lowest) | Server DSN base | Core server DSN without query params | Base server connection string |
22//!
23//! ## Merge Rules
24//!
25//! 1. **Field Precedence**: Module fields always override server fields
26//! 2. **DSN Precedence**: Module DSN overrides server DSN completely
27//! 3. **Params Merging**: `params` maps are merged, with module params taking precedence
28//! 4. **Pool Configuration**: Module pool config overrides server pool config entirely
29//! 5. **`SQLite` Paths**: `file`/`path` fields are module-only and never inherited from servers
30//!
31//! ## Conflict Detection
32//!
33//! The system validates configurations and returns [`DbError::ConfigConflict`] for:
34//! - `SQLite` DSN with server fields (`host`/`port`)
35//! - Non-SQLite DSN with `SQLite` fields (`file`/`path`)
36//! - Both `file` and `path` specified for `SQLite`
37//! - `SQLite` fields mixed with server connection fields
38//!
39//! ## Test Coverage
40//!
41//! These precedence rules are verified by:
42//! - [`test_precedence_module_fields_override_server`]
43//! - [`test_precedence_module_dsn_override_server`]
44//! - [`test_precedence_params_merging`]
45//! - [`test_conflict_detection_sqlite_dsn_with_server_fields`]
46//! - [`test_conflict_detection_nonsqlite_dsn_with_sqlite_fields`]
47//!
48//! See the test suite in `tests/precedence_tests.rs` for complete verification.
49
50use serde::{Deserialize, Serialize};
51use std::collections::HashMap;
52use std::path::PathBuf;
53use std::time::Duration;
54
55/// Global database configuration with server-based DBs.
56#[derive(Debug, Clone, Deserialize, Serialize)]
57#[serde(deny_unknown_fields)]
58pub struct GlobalDatabaseConfig {
59    /// Server-based DBs (postgres/mysql/sqlite/etc.), keyed by server name.
60    #[serde(default)]
61    pub servers: HashMap<String, DbConnConfig>,
62    /// Optional dev-only flag to auto-provision DB/schema when missing.
63    #[serde(default)]
64    pub auto_provision: Option<bool>,
65}
66
67/// Reusable DB connection config for both global servers and modules.
68/// DSN must be a FULL, valid DSN if provided (dsn crate compliant).
69#[derive(Debug, Clone, Deserialize, Serialize, Default)]
70#[serde(deny_unknown_fields)]
71pub struct DbConnConfig {
72    /// Explicit database engine for this connection.
73    ///
74    /// This is required for configurations without `dsn`, where the engine cannot be inferred
75    /// reliably (e.g. distinguishing `MySQL` vs `PostgreSQL`, or selecting `SQLite` for file/path configs).
76    ///
77    /// If both `engine` and `dsn` are provided, they must not conflict (validated at runtime).
78    #[serde(default)]
79    pub engine: Option<DbEngineCfg>,
80
81    // DSN-style (full, valid). Optional: can be absent and rely on fields.
82    pub dsn: Option<String>,
83
84    // Field-based style; any of these override DSN parts when present:
85    pub host: Option<String>,
86    pub port: Option<u16>,
87    pub user: Option<String>,
88    pub password: Option<String>, // literal password or ${VAR} for env expansion
89    pub dbname: Option<String>,   // MUST be present in final for server-based DBs
90    #[serde(default)]
91    pub params: Option<HashMap<String, String>>,
92
93    // SQLite file-based helpers (module-level only; ignored for global):
94    pub file: Option<String>,  // relative name under home_dir/module
95    pub path: Option<PathBuf>, // absolute path
96
97    // Connection pool overrides:
98    #[serde(default)]
99    pub pool: Option<PoolCfg>,
100
101    // Module-level only: reference to a global server by name.
102    // If absent, this module config must be fully self-sufficient (dsn or fields).
103    pub server: Option<String>,
104}
105
106/// Serializable engine selector for configuration.
107///
108/// Keep this separate from `modkit_db::DbEngine` (runtime type) to avoid coupling it to serde.
109#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq)]
110#[serde(rename_all = "lowercase")]
111pub enum DbEngineCfg {
112    Postgres,
113    Mysql,
114    Sqlite,
115}
116
117#[derive(Debug, Clone, Deserialize, Serialize, Default, PartialEq)]
118#[serde(deny_unknown_fields)]
119pub struct PoolCfg {
120    pub max_conns: Option<u32>,
121    pub min_conns: Option<u32>,
122    #[serde(with = "modkit_utils::humantime_serde::option", default)]
123    pub acquire_timeout: Option<Duration>,
124    #[serde(with = "modkit_utils::humantime_serde::option", default)]
125    pub idle_timeout: Option<Duration>,
126    #[serde(with = "modkit_utils::humantime_serde::option", default)]
127    pub max_lifetime: Option<Duration>,
128    pub test_before_acquire: Option<bool>,
129}
130
131impl PoolCfg {
132    /// Apply pool configuration to `PostgreSQL` pool options.
133    #[cfg(feature = "pg")]
134    #[must_use]
135    pub fn apply_pg(
136        &self,
137        mut opts: sea_orm::sqlx::postgres::PgPoolOptions,
138    ) -> sea_orm::sqlx::postgres::PgPoolOptions {
139        if let Some(max_conns) = self.max_conns {
140            opts = opts.max_connections(max_conns);
141        }
142        if let Some(min_conns) = self.min_conns {
143            opts = opts.min_connections(min_conns);
144        }
145        if let Some(acquire_timeout) = self.acquire_timeout {
146            opts = opts.acquire_timeout(acquire_timeout);
147        }
148        if let Some(idle_timeout) = self.idle_timeout {
149            opts = opts.idle_timeout(Some(idle_timeout));
150        }
151        if let Some(max_lifetime) = self.max_lifetime {
152            opts = opts.max_lifetime(Some(max_lifetime));
153        }
154        if let Some(test_before_acquire) = self.test_before_acquire {
155            opts = opts.test_before_acquire(test_before_acquire);
156        }
157        opts
158    }
159
160    /// Apply pool configuration to `MySQL` pool options.
161    #[cfg(feature = "mysql")]
162    #[must_use]
163    pub fn apply_mysql(
164        &self,
165        mut opts: sea_orm::sqlx::mysql::MySqlPoolOptions,
166    ) -> sea_orm::sqlx::mysql::MySqlPoolOptions {
167        if let Some(max_conns) = self.max_conns {
168            opts = opts.max_connections(max_conns);
169        }
170        if let Some(min_conns) = self.min_conns {
171            opts = opts.min_connections(min_conns);
172        }
173        if let Some(acquire_timeout) = self.acquire_timeout {
174            opts = opts.acquire_timeout(acquire_timeout);
175        }
176        if let Some(idle_timeout) = self.idle_timeout {
177            opts = opts.idle_timeout(Some(idle_timeout));
178        }
179        if let Some(max_lifetime) = self.max_lifetime {
180            opts = opts.max_lifetime(Some(max_lifetime));
181        }
182        if let Some(test_before_acquire) = self.test_before_acquire {
183            opts = opts.test_before_acquire(test_before_acquire);
184        }
185        opts
186    }
187
188    /// Apply pool configuration to `SQLite` pool options.
189    #[cfg(feature = "sqlite")]
190    #[must_use]
191    pub fn apply_sqlite(
192        &self,
193        mut opts: sea_orm::sqlx::sqlite::SqlitePoolOptions,
194    ) -> sea_orm::sqlx::sqlite::SqlitePoolOptions {
195        if let Some(max_conns) = self.max_conns {
196            opts = opts.max_connections(max_conns);
197        }
198        if let Some(min_conns) = self.min_conns {
199            opts = opts.min_connections(min_conns);
200        }
201        if let Some(acquire_timeout) = self.acquire_timeout {
202            opts = opts.acquire_timeout(acquire_timeout);
203        }
204        if let Some(idle_timeout) = self.idle_timeout {
205            opts = opts.idle_timeout(Some(idle_timeout));
206        }
207        if let Some(max_lifetime) = self.max_lifetime {
208            opts = opts.max_lifetime(Some(max_lifetime));
209        }
210        if let Some(test_before_acquire) = self.test_before_acquire {
211            opts = opts.test_before_acquire(test_before_acquire);
212        }
213        opts
214    }
215}