Skip to main content

connect

Function connect 

Source
pub async fn connect(database_url: &str) -> Result<(), AppError>
Expand description

Connects to the database and stores the pool process-wide (same OnceLock pattern as larust-http’s route-name registry). Call once at startup, after config/.env has been loaded.

Builds an sqlx::any::AnyPool (runtime-generic - dispatches to whichever real driver database_url’s scheme selects) rather than a concretely-typed SqlitePool/MySqlPool, so every other framework crate and every #[derive(Model)] struct works unchanged regardless of which backend a given app actually runs against - see docs/ARCHITECTURE.md’s database-backends section.

AnyConnectOptions is deliberately opaque (just a parsed Url - confirmed by reading sqlx-core’s own source, it exposes no builder methods for engine-specific settings like SQLite’s WAL mode), so the SQLite-only tuning this crate has always applied (WAL journal mode, a 5s busy timeout so brief lock contention waits instead of failing immediately, foreign keys on) can’t be set through it directly. PoolOptions::after_connect - generic over any backend, called once per new physical connection - is the portable way to apply it: a plain PRAGMA statement, only ever run when backend is actually Sqlite (running a SQLite PRAGMA against a MySQL connection would error). create_if_missing(true)’s equivalent is SQLite’s own ?mode=rwc URL query parameter (confirmed against sqlx-sqlite’s own URL parser) - appended automatically here so an app’s .env doesn’t need to change to keep today’s “just works on first run” behavior.