larust_orm/config.rs
1//! A typed, Laravel-`config/database.php`-shaped connection config -
2//! `default => env('DB_CONNECTION', 'sqlite')` plus named connection
3//! blocks - as a real value fed straight into [`crate::connect`], not a
4//! `serde_json::Value` an app reads back with a dotted-key lookup the way
5//! every other generated `config/*.rs` module in this codebase does (see
6//! `larust_convert::config`'s own doc comment for that pattern). A
7//! database connection needs to become a real `Backend` + connection
8//! string at startup, not stay a loose bag of JSON - that's the whole
9//! reason this lives here as its own module instead of folding into
10//! either `larust_core::Config` (deliberately small/fixed, zero `sqlx`
11//! knowledge, no host/port-shaped fields at all) or the generic
12//! `Value`-map generated-config convention.
13//!
14//! Larust only ever connects to *one* database at a time (a process-wide
15//! `AnyPool` singleton, see [`crate::pool()`]) - true Laravel-style
16//! simultaneous multi-connection access (`DB::connection('name')`) isn't
17//! how this ORM works and isn't attempted here. [`DatabaseConnections`]
18//! still models every *named* connection block the way Laravel's config
19//! file does (so `DB_CONNECTION` can switch which one is active without
20//! a code change), but only the one named by
21//! [`DatabaseConnections::default`] is ever actually resolved to a URL.
22
23use larust_core::AppError;
24use std::collections::HashMap;
25
26/// Which wire protocol a named connection speaks - distinct from
27/// [`crate::Backend`] on purpose: `Backend` is "what `sqlx::Any` is
28/// actually talking to," resolved from a URL scheme once `connect()`
29/// runs, and every exhaustive `match` on it across this codebase assumes
30/// the connection is reachable through `AnyPool`. `Driver::Sqlsrv` names
31/// a connection SQL Server can never reach that way at all (no `sqlx`
32/// driver exists for it) - collapsing the two enums would force `Backend`
33/// to grow a variant nothing durable can do anything with.
34#[derive(Debug, Clone, Copy, PartialEq, Eq)]
35pub enum Driver {
36 Sqlite,
37 /// Also selected by the `"mariadb"` connection name - MariaDB is
38 /// wire-protocol-compatible with MySQL (the same `mysql://` scheme,
39 /// the same `sqlx`/`Any` driver), so it's a pure alias here, not a
40 /// separate variant needing its own `Backend`/SQL-branching story.
41 MySql,
42 Pgsql,
43 /// Named so a config file can select it, but never connectable via
44 /// [`DatabaseConnections::default_connection_url`] - see that
45 /// method's own doc comment, and `larust-mssql` for how a SQL-Server-
46 /// backed connection actually gets used.
47 Sqlsrv,
48}
49
50/// One named connection block - Laravel's `config/database.php`
51/// `'mysql' => [...]`, narrowed to the settings this framework actually
52/// needs (no `unix_socket`/`prefix`/`strict`/`engine` - nothing here
53/// consumes them today; add them if a real caller ever needs to).
54#[derive(Debug, Clone)]
55pub struct ConnectionConfig {
56 pub driver: Driver,
57 /// Ignored for `Driver::Sqlite` - see [`database`](Self::database)'s
58 /// own doc comment.
59 pub host: String,
60 pub port: u16,
61 /// For every driver except `Driver::Sqlite`, a schema/database name.
62 /// For `Driver::Sqlite`, a file path (Laravel's own `database.sqlite`
63 /// convention) - `host`/`port`/`username`/`password`/`charset` are
64 /// all meaningless for a local file and are ignored.
65 pub database: String,
66 pub username: String,
67 pub password: String,
68 pub charset: String,
69}
70
71impl ConnectionConfig {
72 /// Assembles the connection URL [`crate::connect`] already knows how
73 /// to consume - the one place in this codebase that turns
74 /// `(driver, host, port, database, username, password)` into a
75 /// `scheme://user:pass@host:port/db` string; nothing else does this
76 /// today (a pre-assembled URL was previously the only input format
77 /// `connect()` ever saw). Username/password are percent-encoded since
78 /// a real password containing `@`, `:`, `/`, or `%` would otherwise
79 /// corrupt `AnyConnectOptions::from_str`'s strict RFC 3986 parsing
80 /// (see [`crate::connect`]'s own doc comment on why that parser is
81 /// strict, not lenient).
82 pub fn to_url(&self) -> Result<String, AppError> {
83 match self.driver {
84 Driver::Sqlite => Ok(format!("sqlite://{}", self.database)),
85 Driver::MySql => Ok(format!(
86 "mysql://{}:{}@{}:{}/{}",
87 percent_encode_userinfo(&self.username),
88 percent_encode_userinfo(&self.password),
89 self.host,
90 self.port,
91 self.database,
92 )),
93 Driver::Pgsql => Ok(format!(
94 "postgres://{}:{}@{}:{}/{}",
95 percent_encode_userinfo(&self.username),
96 percent_encode_userinfo(&self.password),
97 self.host,
98 self.port,
99 self.database,
100 )),
101 Driver::Sqlsrv => Err(AppError::Config(Box::new(std::io::Error::other(
102 "the \"sqlsrv\" driver isn't connectable via larust_orm::connect() - \
103 sqlx has no SQL Server driver at all; see the larust-mssql crate, \
104 which connects to it separately via larust_repository::Repository",
105 )))),
106 }
107 }
108}
109
110/// Every named connection block plus which one is active - Laravel's
111/// `config/database.php` in full: `'default' => env('DB_CONNECTION',
112/// 'sqlite')` and `'connections' => [...]`.
113#[derive(Debug, Clone)]
114pub struct DatabaseConnections {
115 pub default: String,
116 pub connections: HashMap<String, ConnectionConfig>,
117}
118
119impl DatabaseConnections {
120 /// Resolves [`default`](Self::default) against
121 /// [`connections`](Self::connections) and assembles its URL - the
122 /// single call a generated `main.rs` makes to get whatever
123 /// [`crate::connect`] needs, regardless of which driver `DB_CONNECTION`
124 /// actually named.
125 pub fn default_connection_url(&self) -> Result<String, AppError> {
126 let connection = self.connections.get(&self.default).ok_or_else(|| {
127 AppError::Config(Box::new(std::io::Error::other(format!(
128 "DB_CONNECTION={:?} does not match any configured connection \
129 (expected one of: sqlite, mysql, mariadb, pgsql, sqlsrv)",
130 self.default
131 ))))
132 })?;
133 connection.to_url()
134 }
135}
136
137/// Percent-encodes `value` for safe use in a URL's userinfo component
138/// (`scheme://user:pass@host/...`). Small and hand-rolled rather than a
139/// new dependency - the same "just write the few lines this needs"
140/// precedent `larust-sanctum`'s own hex encoding already sets in this
141/// codebase.
142fn percent_encode_userinfo(value: &str) -> String {
143 let mut out = String::with_capacity(value.len());
144 for byte in value.bytes() {
145 match byte {
146 b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => {
147 out.push(byte as char);
148 }
149 _ => out.push_str(&format!("%{byte:02X}")),
150 }
151 }
152 out
153}
154
155#[cfg(test)]
156mod tests {
157 use super::*;
158
159 fn connection(driver: Driver) -> ConnectionConfig {
160 ConnectionConfig {
161 driver,
162 host: "127.0.0.1".to_string(),
163 port: 5432,
164 database: "app".to_string(),
165 username: "root".to_string(),
166 password: "secret".to_string(),
167 charset: "utf8".to_string(),
168 }
169 }
170
171 #[test]
172 fn sqlite_url_uses_the_database_field_as_a_bare_path() {
173 let config = ConnectionConfig {
174 driver: Driver::Sqlite,
175 database: "database/database.sqlite".to_string(),
176 ..connection(Driver::Sqlite)
177 };
178 assert_eq!(
179 config.to_url().unwrap(),
180 "sqlite://database/database.sqlite"
181 );
182 }
183
184 #[test]
185 fn mysql_url_assembles_every_part() {
186 let config = connection(Driver::MySql);
187 assert_eq!(
188 config.to_url().unwrap(),
189 "mysql://root:secret@127.0.0.1:5432/app"
190 );
191 }
192
193 #[test]
194 fn pgsql_url_assembles_every_part() {
195 let config = connection(Driver::Pgsql);
196 assert_eq!(
197 config.to_url().unwrap(),
198 "postgres://root:secret@127.0.0.1:5432/app"
199 );
200 }
201
202 #[test]
203 fn sqlsrv_is_named_but_not_connectable_this_way() {
204 assert!(connection(Driver::Sqlsrv).to_url().is_err());
205 }
206
207 #[test]
208 fn a_password_with_url_unsafe_characters_is_percent_encoded() {
209 let config = ConnectionConfig {
210 password: "p@ss:w/rd%".to_string(),
211 ..connection(Driver::Pgsql)
212 };
213 assert_eq!(
214 config.to_url().unwrap(),
215 "postgres://root:p%40ss%3Aw%2Frd%25@127.0.0.1:5432/app"
216 );
217 }
218
219 #[test]
220 fn default_connection_url_resolves_the_named_default() {
221 let mut connections = HashMap::new();
222 connections.insert("pgsql".to_string(), connection(Driver::Pgsql));
223 connections.insert("sqlite".to_string(), connection(Driver::Sqlite));
224 let db = DatabaseConnections {
225 default: "pgsql".to_string(),
226 connections,
227 };
228 assert_eq!(
229 db.default_connection_url().unwrap(),
230 "postgres://root:secret@127.0.0.1:5432/app"
231 );
232 }
233
234 #[test]
235 fn default_connection_url_errors_when_default_names_nothing_configured() {
236 let db = DatabaseConnections {
237 default: "oracle".to_string(),
238 connections: HashMap::new(),
239 };
240 assert!(db.default_connection_url().is_err());
241 }
242}