Skip to main content

toolkit_db/
config.rs

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