1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
use std::path::Path;
use std::sync::{Arc, Mutex};

use rusqlite::Connection;

use crate::entities::errors::{DbError, DbResult};
use crate::traits::repo::IConnection;

#[derive(Clone)]
pub struct MSQLConnection {
    inner: Arc<Mutex<Connection>>,
}

impl MSQLConnection {
    pub fn new<P: AsRef<Path>>(path: P) -> DbResult<Self> {
        let cnct = Connection::open(path).map_err(|err| DbError::CanNotConnect(err.to_string()))?;
        Ok(Self {
            inner: Arc::new(Mutex::new(cnct)),
        })
    }
}

impl IConnection for MSQLConnection {
    fn with<T, F: FnOnce(&Connection) -> DbResult<T>>(&self, fun: F) -> DbResult<T> {
        let guard = self.inner.lock()?;
        fun(&guard)
    }
}