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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
use rusqlite::Connection;
use std::marker::PhantomData;

use crate::entities::errors::{DbError, DbResult};
use crate::entities::types::SStr;
use crate::traits::repo::{IConnection, IDbRepo, INewDbRepo};
use crate::traits::table::ITable;

pub struct TableManager<Cnn, Tbl> {
    pub connection: Cnn,
    table: PhantomData<Tbl>,
}

impl<Cnn: Clone, Tbl> Clone for TableManager<Cnn, Tbl> {
    fn clone(&self) -> Self {
        Self {
            connection: self.connection.clone(),
            table: Default::default(),
        }
    }
}

impl<Cnn: IConnection, Tbl: ITable> TableManager<Cnn, Tbl> {
    pub fn get_one<T, F: FnMut(&rusqlite::Row<'_>) -> rusqlite::Result<T>>(
        &self,
        query: &str,
        serializer: F,
    ) -> DbResult<T> {
        let fun = move |cnn: &Connection| -> DbResult<T> {
            let val = cnn.prepare(query)?.query_map((), serializer)?.next();
            match val {
                Some(val) => Ok(val?),
                None => Err(DbError::NotFound(None)),
            }
        };
        self.connection.with(fun)
    }

    pub fn get_many<T, F: FnMut(&rusqlite::Row<'_>) -> rusqlite::Result<T>>(
        &self,
        query: &str,
        serializer: F,
    ) -> DbResult<Vec<T>> {
        let fun = move |cnn: &Connection| -> DbResult<Vec<T>> {
            let val = cnn
                .prepare(query)?
                .query_map((), serializer)?
                .collect::<Result<Vec<T>, _>>()?;
            Ok(val)
        };
        self.connection.with(fun)
    }

    pub fn execute(&self, query: &str) -> DbResult<()> {
        self.connection.with(move |cnn| {
            cnn.execute(query, ())?;
            Ok(())
        })
    }

    pub fn execute_return_id(&self, query: &str) -> DbResult<i64> {
        self.connection.with(move |cnn| {
            cnn.execute(query, ())?;
            Ok(cnn.last_insert_rowid())
        })
    }

    fn create_query(&self) -> String {
        let columns = Tbl::COLUMNS
            .iter()
            .map(|(c_name, c_type)| format!("`{}` {}", c_name, c_type));
        let unique = Tbl::UNIQUE.iter().map(Self::wrap_unique);
        let f_keys = Tbl::FOREIGN_KEYS.iter().map(|(column, table, ext_column)| {
            format!(
                "FOREIGN KEY (`{}`) REFERENCES `{}`(`{}`)",
                column, table, ext_column,
            )
        });
        let attrs = columns
            .chain(unique)
            .chain(f_keys)
            .collect::<Vec<_>>()
            .join(", ");
        format!("CREATE TABLE IF NOT EXISTS `{}` ({})", Tbl::NAME, attrs,)
    }

    fn wrap_unique(fields: &SStr) -> String {
        let fields = fields
            .split(',')
            .map(|field| format!("`{}`", field.trim()))
            .collect::<Vec<_>>()
            .join(",");
        format!("UNIQUE({})", fields)
    }

    fn make_index_name(&self, field: &str) -> String {
        format!("{}_{}_index", Tbl::NAME, field)
    }
}

impl<Cnn: IConnection, Tbl: ITable> INewDbRepo<Cnn> for TableManager<Cnn, Tbl> {
    fn create(connection: Cnn) -> Self {
        Self {
            connection,
            table: Default::default(),
        }
    }
}

impl<Cnn: IConnection, Tbl: ITable> IDbRepo for TableManager<Cnn, Tbl> {
    fn init(&self) -> DbResult<()> {
        match self.execute(&self.create_query()) {
            Err(DbError::Other(msg)) => Err(DbError::CanNotInitTable(Tbl::NAME, msg)),
            other => other,
        }
    }

    fn drop(&self) -> DbResult<()> {
        let query = format!("DROP TABLE IF EXISTS `{}`", Tbl::NAME);
        self.execute(&query)
    }

    fn set_indexes(&self) -> DbResult<()> {
        let fun = |cnn: &Connection| -> DbResult<()> {
            for column in Tbl::INDEXES.iter() {
                let index = self.make_index_name(column);
                let query = format!(
                    "CREATE INDEX IF NOT EXISTS {} ON `{}` (`{}`)",
                    index,
                    Tbl::NAME,
                    column,
                );
                cnn.execute(&query, ())?;
            }
            Ok(())
        };
        self.connection.with(fun)
    }

    fn drop_indexes(&self) -> DbResult<()> {
        let fun = |cnn: &Connection| -> DbResult<()> {
            for column in Tbl::INDEXES.iter() {
                let index = self.make_index_name(column);
                let query = format!("DROP INDEX IF EXISTS {}", index);
                cnn.execute(&query, ())?;
            }
            Ok(())
        };
        self.connection.with(fun)
    }

    fn get_size(&self) -> DbResult<usize> {
        let query = format!("SELECT COUNT(*) FROM `{}`", Tbl::NAME);
        let fun = move |cnn: &Connection| -> DbResult<usize> {
            let mut stm = cnn.prepare(&query)?;
            let mut rows = stm.raw_query();
            Ok(rows.next()?.unwrap().get(0)?)
        };
        self.connection.with(fun)
    }
}