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///
61/// Not `#[non_exhaustive]`: callers (including first-party tests) build it with struct-literal +
62/// `..Default::default()`, so that attribute would break them. Deserialization stays
63/// backward-compatible via `#[serde(default)]` on new fields, but adding a public field is a
64/// source-breaking change for exhaustive struct-literal callers — see the crate semver note.
65#[derive(Debug, Clone, Deserialize, Serialize, Default)]
66#[serde(deny_unknown_fields)]
67pub struct DbConnConfig {
68    /// Explicit database engine for this connection.
69    ///
70    /// This is required for configurations without `dsn`, where the engine cannot be inferred
71    /// reliably (e.g. distinguishing `MySQL` vs `PostgreSQL`, or selecting `SQLite` for file/path configs).
72    ///
73    /// If both `engine` and `dsn` are provided, they must not conflict (validated at runtime).
74    #[serde(default)]
75    pub engine: Option<DbEngineCfg>,
76
77    // DSN-style (full, valid). Optional: can be absent and rely on fields.
78    #[serde(
79        default,
80        serialize_with = "toolkit_utils::secret_string::serialize_option_exposed"
81    )]
82    pub dsn: Option<SecretString>,
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    #[serde(
89        default,
90        serialize_with = "toolkit_utils::secret_string::serialize_option_exposed"
91    )]
92    pub password: Option<SecretString>, // literal password or ${VAR} for env expansion
93    pub dbname: Option<String>, // MUST be present in final for server-based DBs
94    #[serde(default)]
95    pub params: Option<HashMap<String, String>>,
96
97    // SQLite file-based helpers (gear-level only; ignored for global):
98    pub file: Option<String>,  // relative name under home_dir/gear
99    pub path: Option<PathBuf>, // absolute path
100
101    // Connection pool overrides:
102    #[serde(default)]
103    pub pool: Option<PoolCfg>,
104
105    /// Keepalive ping interval for the dedicated advisory-lock session (PG/MySQL only).
106    ///
107    /// Defaults to [`crate::advisory_locks::DEFAULT_LOCK_KEEPALIVE`] when unset. Tune below any
108    /// proxy/database idle-connection cutoff so the single lock session is not reaped.
109    #[serde(with = "toolkit_utils::humantime_serde::option", default)]
110    pub lock_keepalive: Option<Duration>,
111
112    // Gear-level only: reference to a global server by name.
113    // If absent, this gear config must be fully self-sufficient (dsn or fields).
114    pub server: Option<String>,
115}
116
117/// Serializable engine selector for configuration.
118///
119/// Keep this separate from `toolkit_db::DbEngine` (runtime type) to avoid coupling it to serde.
120#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq)]
121#[serde(rename_all = "lowercase")]
122pub enum DbEngineCfg {
123    Postgres,
124    Mysql,
125    Sqlite,
126}
127
128#[derive(Debug, Clone, Deserialize, Serialize, Default, PartialEq)]
129#[serde(deny_unknown_fields)]
130pub struct PoolCfg {
131    pub max_conns: Option<u32>,
132    pub min_conns: Option<u32>,
133    #[serde(with = "toolkit_utils::humantime_serde::option", default)]
134    pub acquire_timeout: Option<Duration>,
135    #[serde(with = "toolkit_utils::humantime_serde::option", default)]
136    pub idle_timeout: Option<Duration>,
137    #[serde(with = "toolkit_utils::humantime_serde::option", default)]
138    pub max_lifetime: Option<Duration>,
139    pub test_before_acquire: Option<bool>,
140}
141
142impl PoolCfg {
143    /// Apply pool configuration to `PostgreSQL` pool options.
144    #[cfg(feature = "pg")]
145    #[must_use]
146    pub fn apply_pg(
147        &self,
148        mut opts: sqlx::postgres::PgPoolOptions,
149    ) -> sqlx::postgres::PgPoolOptions {
150        if let Some(max_conns) = self.max_conns {
151            opts = opts.max_connections(max_conns);
152        }
153        if let Some(min_conns) = self.min_conns {
154            opts = opts.min_connections(min_conns);
155        }
156        if let Some(acquire_timeout) = self.acquire_timeout {
157            opts = opts.acquire_timeout(acquire_timeout);
158        }
159        if let Some(idle_timeout) = self.idle_timeout {
160            opts = opts.idle_timeout(Some(idle_timeout));
161        }
162        if let Some(max_lifetime) = self.max_lifetime {
163            opts = opts.max_lifetime(Some(max_lifetime));
164        }
165        if let Some(test_before_acquire) = self.test_before_acquire {
166            opts = opts.test_before_acquire(test_before_acquire);
167        }
168        opts
169    }
170
171    /// Apply pool configuration to `MySQL` pool options.
172    #[cfg(feature = "mysql")]
173    #[must_use]
174    pub fn apply_mysql(
175        &self,
176        mut opts: sqlx::mysql::MySqlPoolOptions,
177    ) -> sqlx::mysql::MySqlPoolOptions {
178        if let Some(max_conns) = self.max_conns {
179            opts = opts.max_connections(max_conns);
180        }
181        if let Some(min_conns) = self.min_conns {
182            opts = opts.min_connections(min_conns);
183        }
184        if let Some(acquire_timeout) = self.acquire_timeout {
185            opts = opts.acquire_timeout(acquire_timeout);
186        }
187        if let Some(idle_timeout) = self.idle_timeout {
188            opts = opts.idle_timeout(Some(idle_timeout));
189        }
190        if let Some(max_lifetime) = self.max_lifetime {
191            opts = opts.max_lifetime(Some(max_lifetime));
192        }
193        if let Some(test_before_acquire) = self.test_before_acquire {
194            opts = opts.test_before_acquire(test_before_acquire);
195        }
196        opts
197    }
198
199    /// Apply pool configuration to `SQLite` pool options.
200    #[cfg(feature = "sqlite")]
201    #[must_use]
202    pub fn apply_sqlite(
203        &self,
204        mut opts: sqlx::sqlite::SqlitePoolOptions,
205    ) -> sqlx::sqlite::SqlitePoolOptions {
206        if let Some(max_conns) = self.max_conns {
207            opts = opts.max_connections(max_conns);
208        }
209        if let Some(min_conns) = self.min_conns {
210            opts = opts.min_connections(min_conns);
211        }
212        if let Some(acquire_timeout) = self.acquire_timeout {
213            opts = opts.acquire_timeout(acquire_timeout);
214        }
215        if let Some(idle_timeout) = self.idle_timeout {
216            opts = opts.idle_timeout(Some(idle_timeout));
217        }
218        if let Some(max_lifetime) = self.max_lifetime {
219            opts = opts.max_lifetime(Some(max_lifetime));
220        }
221        if let Some(test_before_acquire) = self.test_before_acquire {
222            opts = opts.test_before_acquire(test_before_acquire);
223        }
224        opts
225    }
226}