//! Database connection setup for the native API server. //! //! Provides [`open`] which opens a `tokio-rusqlite` connection, configures //! SQLite pragmas for WAL mode and foreign key enforcement, and wraps the //! result in a [`NativeRepository`]. use super::{DbError, NativeRepository}; use tokio_rusqlite::Connection; /// Open a SQLite database at `path` and return a configured [`NativeRepository`]. /// /// This function: /// 1. Opens the file-backed SQLite connection via `tokio_rusqlite::Connection::open`. /// 2. Enables Write-Ahead Logging (`PRAGMA journal_mode=WAL`) for better /// concurrent read performance. /// 3. Enables foreign key enforcement (`PRAGMA foreign_keys=ON`) so that /// `ON DELETE CASCADE` works on the `quote_tags` table. /// /// Returns `Err(DbError::Internal(...))` if the file cannot be opened or if /// the pragma commands fail. /// /// # Examples /// /// ```no_run /// # async fn example() -> Result<(), Box> { /// let repo = quotesdb::db::connection::open("quotesdb.sqlite").await?; /// repo.run_migrations().await?; /// # Ok(()) /// # } /// ``` pub async fn open(path: &str) -> Result { let conn = Connection::open(path) .await .map_err(|e| DbError::Internal(format!("failed to open database: {e}")))?; // Configure SQLite pragmas on the connection thread conn.call(|c| { // WAL mode improves concurrent reader throughput c.execute_batch("PRAGMA journal_mode=WAL; PRAGMA foreign_keys=ON;")?; Ok(()) }) .await .map_err(|e| DbError::Internal(format!("pragma configuration failed: {e}")))?; Ok(NativeRepository::new(conn)) }