larust_orm/pool.rs
1use larust_core::AppError;
2use sqlx::any::{AnyConnectOptions, AnyPoolOptions};
3use sqlx::AnyPool;
4use std::future::Future;
5use std::str::FromStr;
6use std::sync::OnceLock;
7
8static POOL: OnceLock<AnyPool> = OnceLock::new();
9static BACKEND: OnceLock<Backend> = OnceLock::new();
10
11/// Which real database engine `DATABASE_URL` selected - set once, inside
12/// [`connect`], by reading the URL's own scheme (`sqlite://` vs
13/// `mysql://`). `larust-orm` deliberately doesn't ask `sqlx` this
14/// (`sqlx::any::AnyKind` is `#[deprecated = "not used or returned by any
15/// API"]` in 0.8) - it already knows the answer the moment it parses the
16/// URL to connect, so it just remembers it.
17///
18/// Every other framework crate that needs to emit backend-specific SQL
19/// (an `AUTOINCREMENT` vs `AUTO_INCREMENT` `CREATE TABLE`, `INSERT OR
20/// IGNORE` vs `INSERT IGNORE`, ...) branches on [`backend`] rather than
21/// each reimplementing its own detection - see
22/// `larust-permissions`/`larust-sanctum`/`larust-notifications`/
23/// `larust-queue`/`larust-cache` for the pattern.
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25pub enum Backend {
26 Sqlite,
27 MySql,
28 Postgres,
29}
30
31tokio::task_local! {
32 /// Set only by `larust_testing::test_transaction` (via
33 /// `with_pool_override`) - everywhere else this is simply never set,
34 /// and `pool()` falls through to the process-wide `POOL` exactly as
35 /// before. Task-local, not process-wide: unlike `POOL` itself, this
36 /// doesn't need "first writer wins" semantics, since each test that
37 /// uses it sets its own value in its own task, isolated from every
38 /// other task doing the same thing concurrently.
39 static POOL_OVERRIDE: &'static AnyPool;
40 /// The pool-override's own backend - always scoped together with
41 /// [`POOL_OVERRIDE`] by [`with_pool_override`], never independently.
42 /// Closes a real correctness gap `POOL_OVERRIDE` alone didn't: before
43 /// this existed, [`backend`] always answered from the process-wide
44 /// [`BACKEND`] `OnceLock` regardless of which pool a given task was
45 /// actually routed to via `POOL_OVERRIDE` - harmless as long as every
46 /// `with_pool_override` call in a process happens to use the *same*
47 /// backend `BACKEND` was first set to (true of every caller today,
48 /// `test_transaction`'s own `connect_isolated` is SQLite-only), but a
49 /// real, silent-wrong-SQL bug waiting for the first caller that
50 /// doesn't - e.g. a future desktop-app DB-embed flow overriding to a
51 /// different backend than whatever the app's own `connect()` first
52 /// established. Found and documented, not yet exercised by a real
53 /// caller before this fix - closed proactively rather than waiting for
54 /// it to actually break something.
55 static BACKEND_OVERRIDE: Backend;
56}
57
58/// Connects to the database and stores the pool process-wide (same
59/// `OnceLock` pattern as `larust-http`'s route-name registry). Call once
60/// at startup, after config/`.env` has been loaded.
61///
62/// Builds an `sqlx::any::AnyPool` (runtime-generic - dispatches to
63/// whichever real driver `database_url`'s scheme selects) rather than a
64/// concretely-typed `SqlitePool`/`MySqlPool`, so every other framework
65/// crate and every `#[derive(Model)]` struct works unchanged regardless
66/// of which backend a given app actually runs against - see
67/// `docs/ARCHITECTURE.md`'s database-backends section.
68///
69/// `AnyConnectOptions` is deliberately opaque (just a parsed `Url` -
70/// confirmed by reading `sqlx-core`'s own source, it exposes no builder
71/// methods for engine-specific settings like SQLite's WAL mode), so the
72/// SQLite-only tuning this crate has always applied (WAL journal mode,
73/// a 5s busy timeout so brief lock contention waits instead of failing
74/// immediately, foreign keys on) can't be set through it directly.
75/// `PoolOptions::after_connect` - generic over any backend, called once
76/// per new physical connection - is the portable way to apply it: a
77/// plain `PRAGMA` statement, only ever run when [`backend`] is actually
78/// `Sqlite` (running a SQLite `PRAGMA` against a MySQL connection would
79/// error). `create_if_missing(true)`'s equivalent is SQLite's own
80/// `?mode=rwc` URL query parameter (confirmed against
81/// `sqlx-sqlite`'s own URL parser) - appended automatically here so an
82/// app's `.env` doesn't need to change to keep today's "just works on
83/// first run" behavior.
84pub async fn connect(database_url: &str) -> Result<(), AppError> {
85 sqlx::any::install_default_drivers();
86
87 let backend = ensure_backend(database_url)?;
88
89 // `sqlx::any::AnyConnectOptions::from_str` parses `database_url` with
90 // the `url` crate's strict RFC 3986 parser (confirmed by reading
91 // `sqlx-core`'s source) - unlike the old, SQLite-specific
92 // `SqliteConnectOptions::from_str` this crate used before adding
93 // MySQL support, which treated everything after `sqlite://` as a raw
94 // filesystem path via plain string splitting and never went through a
95 // URL parser at all. A Windows *absolute* path handed to `.display()`
96 // (backslash separators, a `C:` drive letter right after `sqlite://`)
97 // parses under RFC 3986 without erroring, but wrongly - `//` starts an
98 // "authority" component, so `C:` gets read as `host:port`-shaped
99 // (confirmed empirically: without this fix, the resulting connection
100 // fails with SQLite's own "unable to open database file", meaning the
101 // driver received a mangled path). Rewriting to `sqlite:///C:/...`
102 // (three slashes: an explicitly *empty* authority followed by an
103 // absolute path starting with `/`) sidesteps the ambiguity entirely -
104 // the standard way any URL scheme represents "no host, absolute path"
105 // (`file:///...` follows the identical convention). A *relative*
106 // SQLite path (the common case - `sqlite://database/database.sqlite`,
107 // this codebase's own scaffold default) is left alone beyond backslash
108 // normalization: forcing a leading `/` onto it would silently turn it
109 // into an absolute path rooted at the filesystem root, a real
110 // behavioral change, not a parsing fix. This regression would
111 // otherwise hit every framework crate's own `sqlite://{tempdir}/
112 // test.sqlite`-shaped test helper (`larust-testing`, `larust-queue`,
113 // `larust-permissions`, ...) on every Windows dev machine, since
114 // `tempfile::tempdir()` always returns this exact absolute-path shape.
115 let normalized;
116 let database_url = match backend {
117 Backend::Sqlite => {
118 normalized = normalize_sqlite_url(database_url);
119 normalized.as_str()
120 }
121 Backend::MySql | Backend::Postgres => database_url,
122 };
123
124 let connect_url = match backend {
125 Backend::Sqlite if !database_url.contains('?') => {
126 format!("{database_url}?mode=rwc")
127 }
128 Backend::Sqlite => format!("{database_url}&mode=rwc"),
129 Backend::MySql | Backend::Postgres => database_url.to_string(),
130 };
131 let options =
132 AnyConnectOptions::from_str(&connect_url).map_err(|e| AppError::Config(Box::new(e)))?;
133
134 // SQLite gets exactly one connection; MySQL/Postgres get a real pool.
135 // SQLite has exactly one writer lock for the whole database file,
136 // period - WAL mode (below) lets readers avoid blocking on a writer
137 // and vice versa, but it never lets two writers proceed at once, no
138 // matter how many separate connections a pool hands out. A 10-
139 // connection pool against SQLite doesn't buy any write concurrency;
140 // it just means up to 10 connections can simultaneously discover the
141 // lock is held and enter SQLite's own `busy_timeout` retry loop at
142 // once - a real, reproduced production failure mode: a session-write-
143 // heavy app saw `sqlx::query`'s own "slow statement" warnings climb
144 // into the 5-17s range and then hard `(code: 5) database is locked`
145 // errors once write volume was high enough, which a single, always-
146 // uncontended connection (queued fairly through sqlx's own async
147 // `PoolConnection` acquire instead of SQLite's blocking busy-handler)
148 // doesn't hit at all - there's nothing else to contend with. This is a
149 // well-established sqlx+SQLite pattern, not a Larust-specific
150 // workaround. `busy_timeout` stays set regardless (see below) - it's
151 // still real protection against a genuinely separate process (e.g. a
152 // zero-downtime restart handoff's outgoing and incoming processes
153 // both briefly holding a connection to the same file) contending for
154 // the lock, which one connection *within* this process can't prevent.
155 let max_connections = match backend {
156 Backend::Sqlite => 1,
157 Backend::MySql | Backend::Postgres => 10,
158 };
159
160 let pool = AnyPoolOptions::new()
161 .min_connections(1)
162 .max_connections(max_connections)
163 .after_connect(move |conn, _meta| {
164 Box::pin(async move {
165 // `conn.execute(&str)` (the `Executor` trait method,
166 // called directly on the connection - matching the exact
167 // pattern sqlx's own `tests/any/pool.rs` uses in an
168 // `after_connect` closure) accepts multiple `;`-separated
169 // statements in one call, unlike `sqlx::query(...)`, which
170 // only ever prepares one.
171 use sqlx::Executor;
172 match backend {
173 Backend::Sqlite => {
174 conn.execute(
175 "PRAGMA journal_mode = WAL; \
176 PRAGMA busy_timeout = 5000; \
177 PRAGMA foreign_keys = ON;",
178 )
179 .await?;
180 }
181 Backend::MySql => {
182 // Every identifier throughout this codebase - the
183 // query builder, `#[derive(Model)]`'s generated
184 // SQL, every ecosystem crate's own queries - is
185 // double-quoted (`"table"`, `"column"`), the
186 // ANSI-SQL/SQLite convention. MySQL's *default*
187 // `sql_mode` instead treats a double-quoted token
188 // as a string literal, not an identifier - so
189 // without this, every one of those queries would
190 // fail outright against a stock MySQL server.
191 // `ANSI_QUOTES` makes MySQL accept the same
192 // double-quote convention SQLite already uses,
193 // avoiding a rewrite of every quoted identifier in
194 // the framework. Appended via `CONCAT` (not a bare
195 // `SET sql_mode = 'ANSI_QUOTES'`) so it adds to
196 // the session's existing modes rather than
197 // silently dropping MySQL's own sane defaults
198 // (`STRICT_TRANS_TABLES`, etc.).
199 conn.execute("SET SESSION sql_mode = CONCAT(@@sql_mode, ',ANSI_QUOTES')")
200 .await?;
201 }
202 Backend::Postgres => {
203 // No session pragma needed - double-quoted
204 // identifiers (`"table"`, `"column"`) are
205 // Postgres's own native standard-SQL convention,
206 // unlike MySQL's non-standard default `sql_mode`
207 // above. Every query this framework emits already
208 // quotes identifiers that way, so Postgres accepts
209 // them with zero configuration.
210 }
211 }
212 Ok(())
213 })
214 })
215 .connect_with(options)
216 .await
217 .map_err(|e| AppError::Internal(Box::new(e)))?;
218
219 POOL.set(pool).map_err(|_| {
220 AppError::Internal(Box::new(std::io::Error::other(
221 "connect() called more than once",
222 )))
223 })?;
224
225 Ok(())
226}
227
228/// This app's database backend - see [`Backend`]. Checks the task-local
229/// override first (set only inside `with_pool_override`, alongside
230/// `POOL_OVERRIDE`), then falls back to the process-wide [`BACKEND`] -
231/// the identical two-step [`pool`] itself already uses for `POOL`/
232/// `POOL_OVERRIDE`, kept consistent for the same reason: code that
233/// branches on `backend()` to decide which dialect of SQL to emit must
234/// agree with whichever pool `pool()` actually resolves to in the same
235/// task, not whatever backend happened to connect first in the process.
236/// Panics if neither is set, matching `larust_core::config()`'s own "real
237/// caller-contract violation" reasoning (nothing before `connect()`/
238/// `with_pool_override` could plausibly need to know the backend either).
239pub fn backend() -> Backend {
240 if let Ok(overridden) = BACKEND_OVERRIDE.try_with(|backend| *backend) {
241 return overridden;
242 }
243
244 *BACKEND
245 .get()
246 .expect("larust_orm::backend() called before connect()")
247}
248
249/// Sets [`BACKEND`] from `database_url`'s scheme, without touching the
250/// process-wide [`POOL`] - unlike [`connect`], safe to call more than
251/// once per process (every call after the first is a harmless no-op, the
252/// same `.ok()`-swallowed idempotency [`connect`] itself already gives
253/// `BACKEND`). For `larust_testing::test_transaction`'s own
254/// `connect_isolated`, which deliberately builds its own dedicated pool
255/// *outside* the process-wide singleton (see that function's own doc
256/// comment for why) but still needs `backend()` to resolve correctly for
257/// whatever it runs - every framework crate's own bootstrap SQL branches
258/// on it.
259pub fn ensure_backend(database_url: &str) -> Result<Backend, AppError> {
260 let backend = parse_backend(database_url)?;
261 BACKEND.set(backend).ok();
262 Ok(backend)
263}
264
265/// Rewrites a `sqlite:` URL so `sqlx::any::AnyConnectOptions::from_str`'s
266/// strict RFC 3986 parsing (via the `url` crate) resolves it the same way
267/// the old, lenient, SQLite-specific `SqliteConnectOptions::from_str` this
268/// crate used before adding MySQL support always did - see [`connect`]'s
269/// own doc comment for the full explanation of *why* this is needed at
270/// all (in short: a Windows absolute path's `C:` drive letter, sitting
271/// right after `sqlite://`, gets misread as a `host:port`-shaped URL
272/// authority component otherwise).
273///
274/// Two independent fixes, both SQLite-only:
275/// - Backslash path separators become forward slashes (accepted by every
276/// SQLite/Windows filesystem API too, and never ambiguous with anything
277/// URL syntax uses).
278/// - A path that looks like a Windows drive-absolute path (`C:/...`) gets
279/// an explicit empty authority inserted (`sqlite:///C:/...`, three
280/// slashes) - the standard "no host, absolute path" URL convention
281/// (`file:///...` follows the identical shape). A *relative* path
282/// (`sqlite://database/database.sqlite`, this codebase's own scaffold
283/// default) is deliberately left as a two-slash URL: forcing a leading
284/// `/` onto it would silently turn it into a path rooted at the
285/// filesystem root, a real behavior change, not a parsing fix.
286pub fn normalize_sqlite_url(database_url: &str) -> String {
287 let forward_slashes = database_url.replace('\\', "/");
288 let path = forward_slashes
289 .strip_prefix("sqlite://")
290 .unwrap_or(&forward_slashes);
291 let is_windows_drive_absolute = path.as_bytes().first().is_some_and(u8::is_ascii_alphabetic)
292 && path.as_bytes().get(1) == Some(&b':');
293 if is_windows_drive_absolute {
294 format!("sqlite:///{path}")
295 } else {
296 forward_slashes
297 }
298}
299
300/// One placeholder for `backend` at 1-based position `n` in left-to-right
301/// order across a statement - `"?"` for SQLite/MySQL, `"$n"` for Postgres
302/// (confirmed by reading `sqlx-core`'s own doc comment: `sqlx::Any` does
303/// **not** rewrite placeholders between dialects, so every framework crate
304/// with a fixed, statically-known placeholder count in a hand-written SQL
305/// string uses this instead of a bare `"?"` literal - `larust-cache`,
306/// `larust-queue`, `larust-sanctum`, `larust-permissions`,
307/// `larust-notifications`, `larust-http::session`, and this crate's own
308/// `migrate.rs` all do. `QueryBuilder`'s own placeholder rendering
309/// (`query_builder.rs`) has a genuinely *dynamic* count instead - a running
310/// counter threaded through its own condition renderer - and doesn't use
311/// this helper, but follows the identical `?`/`$n` split.
312pub fn placeholder(backend: Backend, n: usize) -> String {
313 match backend {
314 Backend::Sqlite | Backend::MySql => "?".to_string(),
315 Backend::Postgres => format!("${n}"),
316 }
317}
318
319fn parse_backend(database_url: &str) -> Result<Backend, AppError> {
320 if database_url.starts_with("sqlite:") {
321 Ok(Backend::Sqlite)
322 } else if database_url.starts_with("mysql:") {
323 Ok(Backend::MySql)
324 } else if database_url.starts_with("postgres:") || database_url.starts_with("postgresql:") {
325 Ok(Backend::Postgres)
326 } else {
327 Err(AppError::Config(Box::new(std::io::Error::other(format!(
328 "unsupported DATABASE_URL scheme in {database_url:?} - expected \
329 \"sqlite:\", \"mysql:\", \"postgres:\", or \"postgresql:\""
330 )))))
331 }
332}
333
334/// Returns the pool every `#[derive(Model)]` method and `QueryBuilder`
335/// call resolves its connection through - this single resolution point
336/// (not a parameter threaded through every generated method) is what
337/// makes `with_pool_override` below work at all. Checks the task-local
338/// override first (set only inside `larust_testing::test_transaction`),
339/// then falls back to the process-wide pool. Errors (rather than panics)
340/// if neither is set - a misconfigured startup order is a real
341/// possibility (e.g. a route handler running before `main` finishes
342/// wiring up the database), not a truly unreachable state.
343pub fn pool() -> Result<&'static AnyPool, AppError> {
344 if let Ok(overridden) = POOL_OVERRIDE.try_with(|pool| *pool) {
345 return Ok(overridden);
346 }
347
348 POOL.get().ok_or_else(|| {
349 AppError::Internal(Box::new(std::io::Error::other(
350 "database not connected; call larust_orm::connect() \
351 (via larust_support::orm::connect) at startup before serving requests",
352 )))
353 })
354}
355
356/// Runs `fut` with `pool` (and `backend`, its own [`backend`] override -
357/// always scoped together, never independently, so [`pool`] and
358/// [`backend`] can never disagree about which database `fut` is actually
359/// talking to) resolved by every `pool()`/`backend()` call made from
360/// within it - and from anything it directly `.await`s, since a
361/// `tokio::task_local!` is visible throughout one task's execution. A
362/// future `fut` hands off to `tokio::spawn` as a *separate* detached
363/// task would **not** see this override (spawned tasks don't inherit
364/// their parent's task-locals) - confirmed nothing in `larust-orm`'s or
365/// `larust-macros`' generated code does that (`grep` for `tokio::spawn`/
366/// `join_all` in both turns up nothing), so this is safe for every
367/// existing `#[derive(Model)]`/`QueryBuilder` call path today.
368///
369/// Used by `larust_testing::test_transaction`; not meant for application
370/// code - there is deliberately no equivalent re-exported through
371/// `larust_support::orm`.
372pub async fn with_pool_override<F: Future>(
373 pool: &'static AnyPool,
374 backend: Backend,
375 fut: F,
376) -> F::Output {
377 POOL_OVERRIDE
378 .scope(pool, BACKEND_OVERRIDE.scope(backend, fut))
379 .await
380}
381
382#[cfg(test)]
383mod tests {
384 use super::*;
385
386 #[test]
387 fn parse_backend_recognizes_sqlite() {
388 assert_eq!(
389 parse_backend("sqlite://database/database.sqlite").unwrap(),
390 Backend::Sqlite
391 );
392 }
393
394 #[test]
395 fn parse_backend_recognizes_mysql() {
396 assert_eq!(
397 parse_backend("mysql://root@127.0.0.1/app").unwrap(),
398 Backend::MySql
399 );
400 }
401
402 #[test]
403 fn parse_backend_recognizes_postgres() {
404 assert_eq!(
405 parse_backend("postgres://root@127.0.0.1/app").unwrap(),
406 Backend::Postgres
407 );
408 assert_eq!(
409 parse_backend("postgresql://root@127.0.0.1/app").unwrap(),
410 Backend::Postgres
411 );
412 }
413
414 #[test]
415 fn normalize_sqlite_url_leaves_a_relative_path_alone() {
416 assert_eq!(
417 normalize_sqlite_url("sqlite://database/database.sqlite"),
418 "sqlite://database/database.sqlite"
419 );
420 }
421
422 #[test]
423 fn normalize_sqlite_url_converts_backslashes_in_a_windows_absolute_path() {
424 assert_eq!(
425 normalize_sqlite_url(r"sqlite://C:\Users\me\AppData\Local\Temp\abc\test.sqlite"),
426 "sqlite:///C:/Users/me/AppData/Local/Temp/abc/test.sqlite"
427 );
428 }
429
430 #[test]
431 fn normalize_sqlite_url_adds_the_third_slash_for_a_drive_absolute_path_already_using_forward_slashes(
432 ) {
433 assert_eq!(
434 normalize_sqlite_url("sqlite://C:/Users/me/test.sqlite"),
435 "sqlite:///C:/Users/me/test.sqlite"
436 );
437 }
438
439 #[test]
440 fn normalize_sqlite_url_leaves_a_unix_style_absolute_path_alone() {
441 assert_eq!(
442 normalize_sqlite_url("sqlite:///var/lib/app/database.sqlite"),
443 "sqlite:///var/lib/app/database.sqlite"
444 );
445 }
446
447 #[test]
448 fn parse_backend_rejects_an_unsupported_scheme() {
449 assert!(parse_backend("mongodb://localhost/app").is_err());
450 }
451}