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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
use std::path::Path;
use std::rc::Rc;

use rusqlite;
use rusqlite::{Connection, Row, ToSql};

use crate::entities::errors::{DbError, DbResult};
use crate::impls::executor::Executor;
use crate::traits::repo::{IConnection, IExecutor};

#[derive(Clone)]
pub struct RSQLConnection {
    inner: Rc<rusqlite::Connection>,
}

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

impl IConnection for RSQLConnection {
    type Locked = Self;

    fn lock(&self) -> DbResult<Self::Locked> {
        panic!("Lock is not allowed for RC connection. Use mutex")
    }

    fn with<T, F: FnOnce(&Connection) -> DbResult<T>>(&self, fun: F) -> DbResult<T> {
        fun(&self.inner)
    }
}

impl IExecutor for RSQLConnection {
    type Locked = Self;

    fn lock(&self) -> DbResult<Self::Locked> {
        panic!("Lock is not allowed for RC connection. Use mutex")
    }

    fn get_one<T, F: FnMut(&Row<'_>) -> rusqlite::Result<T>>(
        &self,
        query: &str,
        params: &[&dyn ToSql],
        serializer: F,
    ) -> DbResult<T> {
        Executor::new(self).get_one(query, params, serializer)
    }

    fn get_many<T, F: FnMut(&Row<'_>) -> rusqlite::Result<T>>(
        &self,
        query: &str,
        params: &[&dyn ToSql],
        serializer: F,
    ) -> DbResult<Vec<T>> {
        Executor::new(self).get_many(query, params, serializer)
    }

    fn execute(&self, query: &str, params: &[&dyn ToSql]) -> DbResult<()> {
        Executor::new(self).execute(query, params)
    }

    fn execute_return_id(&self, query: &str, params: &[&dyn ToSql]) -> DbResult<i64> {
        Executor::new(self).execute_return_id(query, params)
    }
}