sql_middleware/sqlite/
config.rs

1use deadpool_sqlite::{Config as DeadpoolSqliteConfig, Runtime};
2
3use crate::middleware::{ConfigAndPool, DatabaseType, MiddlewarePool, SqlMiddlewareDbError};
4
5impl ConfigAndPool {
6    /// Asynchronous initializer for `ConfigAndPool` with Sqlite using `deadpool_sqlite`
7    ///
8    /// # Errors
9    /// Returns `SqlMiddlewareDbError::ConnectionError` if pool creation or connection test fails.
10    pub async fn new_sqlite(db_path: String) -> Result<Self, SqlMiddlewareDbError> {
11        // Configure deadpool_sqlite
12        let cfg: DeadpoolSqliteConfig = DeadpoolSqliteConfig::new(db_path.clone());
13
14        // Create the pool
15        let pool = cfg.create_pool(Runtime::Tokio1).map_err(|e| {
16            SqlMiddlewareDbError::ConnectionError(format!("Failed to create SQLite pool: {e}"))
17        })?;
18
19        // Initialize the database (e.g., create tables)
20        {
21            let conn = pool
22                .get()
23                .await
24                .map_err(SqlMiddlewareDbError::PoolErrorSqlite)?;
25            let _res = conn
26                .interact(|conn| {
27                    conn.execute_batch(
28                        "
29                    PRAGMA journal_mode = WAL;
30                ",
31                    )
32                    .map_err(SqlMiddlewareDbError::SqliteError)
33                })
34                .await?;
35        }
36
37        Ok(ConfigAndPool {
38            pool: MiddlewarePool::Sqlite(pool),
39            db_type: DatabaseType::Sqlite,
40        })
41    }
42}
43
44/// Convert `InteractError` to a more specific `SqlMiddlewareDbError`
45impl From<deadpool_sqlite::InteractError> for SqlMiddlewareDbError {
46    fn from(err: deadpool_sqlite::InteractError) -> Self {
47        SqlMiddlewareDbError::ConnectionError(format!("SQLite Interact Error: {err}"))
48    }
49}