Skip to main content

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