wormhole_common/boot/
cache.rs

1use crate::util::get_data_dir;
2use rusqlite::{params, Connection};
3
4pub struct Cache {
5    conn: Connection,
6}
7
8impl Cache {
9    pub fn new(path: &str) -> Result<Self, rusqlite::Error> {
10        let dir_path = get_data_dir().join("cache");
11        let conn = Connection::open(dir_path.join(path))?;
12
13        conn.execute(
14            "CREATE TABLE IF NOT EXISTS cache (
15                 game_id INTEGER PRIMARY KEY,
16                 data TEXT
17             )",
18            params![],
19        )?;
20
21        Ok(Self { conn })
22    }
23
24    pub fn get(&self, game_id: i32) -> Result<Option<String>, rusqlite::Error> {
25        let mut stmt = self
26            .conn
27            .prepare("SELECT data FROM cache WHERE game_id = ?1")?;
28
29        let row = stmt.query_row(params![game_id], |row| row.get(0));
30
31        match row {
32            Ok(data) => Ok(Some(data)),
33            Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
34            Err(e) => Err(e),
35        }
36    }
37
38    pub fn set(&self, game_id: i32, data: &str) -> Result<(), rusqlite::Error> {
39        self.conn.execute(
40            "INSERT OR REPLACE INTO cache (game_id, data) VALUES (?1, ?2)",
41            params![game_id, data],
42        )?;
43
44        Ok(())
45    }
46}
47
48pub fn update_cache() {
49    let cache = Cache::new("cache.sqlite").unwrap();
50
51    cache.set(1, "test").unwrap();
52
53    println!("{:?}", cache.get(1).unwrap());
54}