summaryrefslogtreecommitdiff
path: root/src/repo
diff options
context:
space:
mode:
Diffstat (limited to 'src/repo')
-rw-r--r--src/repo/constants.rs11
-rw-r--r--src/repo/mod.rs80
2 files changed, 91 insertions, 0 deletions
diff --git a/src/repo/constants.rs b/src/repo/constants.rs
new file mode 100644
index 0000000..e168a77
--- /dev/null
+++ b/src/repo/constants.rs
@@ -0,0 +1,11 @@
+use once_cell::sync::Lazy;
+use sled::{Config, Db};
+
+pub const PARTS_TREE: &str = "parts";
+pub const CARS_TREE: &str = "cars";
+pub static REPO_INSTANCE: Lazy<Db> = Lazy::new(|| {
+ Config::default()
+ .path("/tmp/twinh")
+ .open()
+ .expect("Couldn't open DB!")
+});
diff --git a/src/repo/mod.rs b/src/repo/mod.rs
new file mode 100644
index 0000000..d4c5e44
--- /dev/null
+++ b/src/repo/mod.rs
@@ -0,0 +1,80 @@
+use crate::error::TwinHError;
+use crate::models::Car;
+use crate::models::Part;
+use bincode::deserialize;
+use constants::*;
+
+mod constants;
+
+pub fn create_new_db() -> Result<(), TwinHError> {
+ let config = sled::Config::default()
+ .path("/var/db/twinh")
+ .create_new(true);
+ let db = config.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(())
+ }
+}