summaryrefslogtreecommitdiff
path: root/src/repo/mod.rs
blob: 80b281404ac2e196d73cf8146061b732eb5a8454 (plain) (blame)
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
use crate::config;
use crate::error::TwinHError;
use crate::models::Car;
use crate::models::Part;
use bincode::deserialize;
use constants::*;
use sled::{Config, Db};

mod constants;

lazy_static! {
    static ref REPO_INSTANCE: Db = match Config::default().path(&config::INSTANCE.data_dir).open() {
        Err(e) => panic!("failed to open database: {}", e),
        Ok(db) => db,
    };
}

pub fn create_demo_db() -> Result<(), TwinHError> {
    let db = sled::Config::default()
        .path(&config::INSTANCE.data_dir)
        .create_new(true)
        .open()?;
    let cars_tree = db.open_tree(CARS_TREE)?;
    Ok(())
}

pub fn create_new_db() -> Result<(), TwinHError> {
    sled::Config::default()
        .path(&config::INSTANCE.data_dir)
        .create_new(true)
        .open()?;
    Ok(())
}

pub fn get_all_cars() -> Result<Vec<Car>, TwinHError> {
    let cars = REPO_INSTANCE
        .open_tree(CARS_TREE)?
        .into_iter()
        .values()
        .collect::<Result<Vec<_>, _>>()?
        .iter()
        .map(|c| deserialize::<Car>(&c))
        .collect::<Result<Vec<_>, _>>()?;
    Ok(cars)
}

pub fn insert_part(part: Part) -> Result<u64, TwinHError> {
    todo!()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::models::{Car, Part};
    use bincode::serialize;
    use std::error::Error;

    #[test]
    fn test_insert_part() -> Result<(), Box<dyn Error>> {
        let db = sled::Config::default()
            .mode(sled::Mode::HighThroughput)
            .temporary(true)
            .open()?;

        let car = Car {
            key: 1,
            make: "Hudson".into(),
            model: "Hornet".into(),
            trim: "Sedan".into(),
            doors: 4,
            year: 1953,
        };

        let tree = db.open_tree(CARS_TREE)?;
        let key = car.key.to_be_bytes();
        let val = serialize(&car)?;
        tree.insert(key, val)?;

        let part = Part {
            key: 2,
            number: "ABC123".into(),
            name: "Rear Wheel Bearing".into(),
            fits_cars: vec![car.key],
            categories: Vec::new(),
            sources: Vec::new(),
        };

        let tree = db.open_tree(PARTS_TREE)?;
        let (key, val) = (serialize(&part.key)?, serialize(&part)?);
        tree.insert(key.clone(), val)?;

        let part_out = tree.get(key)?;
        let part_out = deserialize::<Part>(&part_out.unwrap())?;
        assert_eq!(part.key, part_out.key);

        Ok(())
    }
}