66 lines
1.6 KiB
Rust
66 lines
1.6 KiB
Rust
use std::sync::Arc;
|
|
|
|
use crate::ressouces::zone::ZoneModel;
|
|
|
|
pub trait Db: ZoneModel + Send + Sync {}
|
|
pub type BoxedDb = Arc<dyn Db>;
|
|
|
|
impl Db for sqlite::SqliteDB {}
|
|
|
|
pub mod sqlite {
|
|
use std::path::PathBuf;
|
|
use std::sync::Arc;
|
|
|
|
#[derive(Clone)]
|
|
pub struct SqliteDB {
|
|
pub pool: bb8::Pool<SqliteConnManager>
|
|
}
|
|
|
|
impl SqliteDB {
|
|
pub async fn new(path: PathBuf) -> Self {
|
|
let pool = bb8::Pool::builder()
|
|
.build(SqliteConnManager::new(path))
|
|
.await
|
|
.expect("Unable to connect to database");
|
|
|
|
SqliteDB {
|
|
pool,
|
|
}
|
|
}
|
|
}
|
|
|
|
#[derive(Clone)]
|
|
pub struct SqliteConnManager {
|
|
path: Arc<PathBuf>
|
|
}
|
|
|
|
impl SqliteConnManager {
|
|
pub fn new(path: PathBuf) -> Self {
|
|
SqliteConnManager {
|
|
path: Arc::new(path)
|
|
}
|
|
}
|
|
}
|
|
|
|
impl bb8::ManageConnection for SqliteConnManager {
|
|
type Connection = rusqlite::Connection;
|
|
type Error = rusqlite::Error;
|
|
|
|
async fn connect(&self) -> Result<Self::Connection, Self::Error> {
|
|
let opt = self.clone();
|
|
|
|
tokio::task::spawn_blocking(move || {
|
|
rusqlite::Connection::open(opt.path.as_ref())
|
|
}).await.unwrap()
|
|
}
|
|
|
|
async fn is_valid(&self, conn: &mut Self::Connection) -> Result<(), Self::Error> {
|
|
tokio::task::block_in_place(|| conn.execute_batch(""))
|
|
}
|
|
|
|
fn has_broken(&self, _conn: &mut Self::Connection) -> bool {
|
|
false
|
|
}
|
|
}
|
|
}
|