easy_sqlite/impls/
rc_connection.rs

1use std::path::Path;
2use std::rc::Rc;
3
4use rusqlite;
5use rusqlite::{Connection, Row, ToSql};
6
7use crate::entities::errors::{DbError, DbResult};
8use crate::impls::executor::Executor;
9use crate::traits::repo::{IConnection, IExecutor};
10
11#[derive(Clone)]
12pub struct RSQLConnection {
13    inner: Rc<rusqlite::Connection>,
14}
15
16impl RSQLConnection {
17    pub fn new<P: AsRef<Path>>(path: P) -> DbResult<Self> {
18        let cnct = rusqlite::Connection::open(path)
19            .map_err(|err| DbError::CanNotConnect(err.to_string()))?;
20        Ok(Self {
21            inner: Rc::new(cnct),
22        })
23    }
24}
25
26impl IConnection for RSQLConnection {
27    type Locked = Self;
28
29    fn lock_sync(&self) -> DbResult<Self::Locked> {
30        Ok(self.clone())
31    }
32
33    fn with<T, F: FnOnce(&Connection) -> DbResult<T>>(&self, fun: F) -> DbResult<T> {
34        fun(&self.inner)
35    }
36}
37
38impl IExecutor for RSQLConnection {
39    type Locked = Self;
40
41    fn lock(&self) -> DbResult<Self::Locked> {
42        Ok(self.clone())
43    }
44
45    fn get_one<T, F: FnMut(&Row<'_>) -> DbResult<T>>(
46        &self,
47        query: &str,
48        params: &[&dyn ToSql],
49        serializer: F,
50    ) -> DbResult<T> {
51        Executor::new(self).get_one(query, params, serializer)
52    }
53
54    fn get_many<T, F: FnMut(&Row<'_>) -> DbResult<T>>(
55        &self,
56        query: &str,
57        params: &[&dyn ToSql],
58        serializer: F,
59    ) -> DbResult<Vec<T>> {
60        Executor::new(self).get_many(query, params, serializer)
61    }
62
63    fn execute(&self, query: &str, params: &[&dyn ToSql]) -> DbResult<()> {
64        Executor::new(self).execute(query, params)
65    }
66
67    fn execute_return_id(&self, query: &str, params: &[&dyn ToSql]) -> DbResult<i64> {
68        Executor::new(self).execute_return_id(query, params)
69    }
70}