wb_cache/test/simulation/db/driver/
sqlite.rs

1//! SQLite database driver.
2use std::borrow::Borrow;
3use std::ops::Deref;
4use std::path::Path;
5use std::sync::Arc;
6
7use async_trait::async_trait;
8use fieldx::fxstruct;
9use sea_orm::ConnectionTrait;
10use sea_orm::DatabaseConnection;
11use sea_orm_migration::IntoSchemaManagerConnection;
12use sea_orm_migration::SchemaManagerConnection;
13
14use crate::test::simulation::types::Result;
15
16use super::DatabaseDriver;
17
18/// SQLite database driver.
19#[derive(Debug)]
20#[fxstruct(sync, no_new)]
21pub struct Sqlite {
22    connection: DatabaseConnection,
23}
24
25impl Sqlite {
26    pub async fn connect(db_dir: &Path, db_name: &str) -> Result<Arc<Self>> {
27        let db_path = db_dir.join(db_name);
28
29        let schema = format!("sqlite://{}?mode=rwc", db_path.display());
30        let db = sea_orm::Database::connect(&schema)
31            .await
32            .inspect_err(|e| eprintln!("Error connecting to database {schema}: {e}"))?;
33
34        Ok(Arc::new(Self { connection: db }))
35    }
36}
37
38#[async_trait]
39impl DatabaseDriver for Sqlite {
40    fn connection(&self) -> DatabaseConnection {
41        self.connection.clone()
42    }
43
44    /// Set the following SQLite pragmas for performance:
45    ///
46    /// - `journal_mode=WAL`
47    /// - `cache=64000`
48    /// - `synchronous=NORMAL`
49    async fn configure(&self) -> Result<()> {
50        let db = &self.connection;
51
52        db.execute_unprepared("PRAGMA journal_mode=WAL;").await?;
53        db.execute_unprepared("PRAGMA cache=64000;").await?;
54        db.execute_unprepared("PRAGMA synchronous=NORMAL;").await?;
55
56        Ok(())
57    }
58
59    /// Execute `wal_checkpoint` to checkpoint the WAL (Write-Ahead Logging) journal.
60    async fn checkpoint(&self) -> Result<()> {
61        self.connection.execute_unprepared("PRAGMA wal_checkpoint;").await?;
62
63        Ok(())
64    }
65}
66
67impl Deref for Sqlite {
68    type Target = DatabaseConnection;
69
70    fn deref(&self) -> &Self::Target {
71        &self.connection
72    }
73}
74
75impl AsRef<DatabaseConnection> for Sqlite {
76    fn as_ref(&self) -> &DatabaseConnection {
77        &self.connection
78    }
79}
80
81impl Borrow<DatabaseConnection> for Sqlite {
82    fn borrow(&self) -> &DatabaseConnection {
83        &self.connection
84    }
85}
86
87impl<'c> IntoSchemaManagerConnection<'c> for &'c Sqlite {
88    fn into_schema_manager_connection(self) -> SchemaManagerConnection<'c> {
89        SchemaManagerConnection::Connection(&self.connection)
90    }
91}