oca_rs/repositories/
capture_base_cache_repo.rs

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
use oca_bundle_semantics::state::oca::capture_base::CaptureBase;

use crate::facade::Connection;

#[derive(Debug)]
pub struct CaptureBaseCacheRecord {
    pub said: String,
    pub capture_base: String,
}

impl CaptureBaseCacheRecord {
    pub fn new(capture_base: &CaptureBase) -> Self {
        Self {
            said: capture_base.said.clone().unwrap().to_string(),
            capture_base: serde_json::to_string(capture_base).unwrap(),
        }
    }
}

#[derive(Debug)]
pub struct AllCaptureBaseRecord {
    pub cache_record: Option<CaptureBaseCacheRecord>,
    pub total: usize,
}

pub struct CaptureBaseCacheRepo {
    connection: Connection,
}

impl CaptureBaseCacheRepo {
    pub fn new(connection: Connection) -> Self {
        let create_table_query = r#"
        CREATE TABLE IF NOT EXISTS capture_base_cache(
            said TEXT PRIMARY KEY,
            capture_base TEXT
        )"#;
        let _ = connection.execute(create_table_query, ());

        Self { connection }
    }

    pub fn insert(&self, model: CaptureBaseCacheRecord) {
        let query = r#"
        INSERT INTO capture_base_cache(said, capture_base)
            VALUES (?1, ?2)"#;
        let _ = self
            .connection
            .execute(query, [&model.said, &model.capture_base]);
    }

    pub fn fetch_all(&self, limit: usize, page: usize) -> Vec<AllCaptureBaseRecord> {
        let offset = (page - 1) * limit;
        let mut results = vec![];
        let query = "
        SELECT results.*, count.total
        FROM
        (
            SELECT COUNT(*) OVER() AS total
            FROM capture_base_cache
        ) AS count
        LEFT JOIN
        (
            SELECT *
            FROM capture_base_cache
            LIMIT ?1 OFFSET ?2
        ) AS results
        ON true
        GROUP BY said";

        let connection = self.connection.connection.lock().unwrap();
        let mut statement = connection.prepare(query).unwrap();

        let models = statement
            .query_map([limit, offset], |row| {
                let cache_record =
                    row.get::<_, Option<String>>(0)
                        .unwrap()
                        .map(|said| CaptureBaseCacheRecord {
                            said,
                            capture_base: row.get(1).unwrap(),
                        });
                Ok(AllCaptureBaseRecord {
                    cache_record,
                    total: row.get(2).unwrap(),
                })
            })
            .unwrap();
        models.for_each(|model| results.push(model.unwrap()));
        results
    }
}