aboutsummaryrefslogtreecommitdiff
path: root/src/common/sqlite.rs
blob: d3732182eb294e30fc6735dea93bf1a26566dc09 (plain)
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
use log::error;
use rusqlite::{Connection, Params, Row};

pub fn get<F, P, T>(db: &Connection, query: &str, params: P, row_mapper: F) -> rusqlite::Result<T>
where
    F: FnMut(&Row<'_>) -> rusqlite::Result<T>,
    P: Params,
{
    let mut stmt = match db.prepare(query) {
        Ok(stmt) => stmt,
        Err(e) => {
            error!("Couldn't prepare get statement: {e:?}");
            return Err(e);
        }
    };

    stmt.query_row(params, row_mapper).inspect_err(|e| {
        error!("Couldn't read from database: {e:?}");
    })
}

pub fn list<F, P, T>(
    db: &Connection,
    query: &str,
    params: P,
    row_mapper: F,
) -> rusqlite::Result<Vec<T>>
where
    F: FnMut(&Row<'_>) -> rusqlite::Result<T>,
    P: Params,
{
    let mut stmt = match db.prepare(query) {
        Ok(stmt) => stmt,
        Err(e) => {
            error!("Couldn't prepare list statement: {e:?}");
            return Err(e);
        }
    };

    let result = stmt.query_map(params, row_mapper);

    match result {
        Ok(res) => {
            let records: rusqlite::Result<Vec<T>> = res.collect();

            match records {
                Ok(records) => Ok(records),
                Err(e) => {
                    error!("Couldn't read from database: {e:?}");
                    Err(e)
                }
            }
        }
        Err(rusqlite::Error::QueryReturnedNoRows) => Ok(vec![]),
        Err(e) => {
            error!("Couldn't read from database: {e:?}");
            Err(e)
        }
    }
}