65 lines
2.0 KiB
Rust
65 lines
2.0 KiB
Rust
// File for database functions
|
|
use crate::structures::*;
|
|
type MyErrorType = Box<dyn std::error::Error>;
|
|
|
|
pub fn open() -> sled::Db {
|
|
sled::open("products_db").unwrap()
|
|
}
|
|
|
|
// Register a new product
|
|
pub fn register_product(db: &sled::Db, short_name: &str, product: &Product) {
|
|
let bytes = bincode::serialize(&product).unwrap();
|
|
db.insert(short_name, bytes).unwrap();
|
|
db.flush().unwrap();
|
|
}
|
|
|
|
// Read info about a product
|
|
pub fn read_product(db: &sled::Db, short_name: &str) -> std::result::Result<Option<Product>, MyErrorType> {
|
|
let entry = db.get(short_name)?;
|
|
if let Some(product_entry) = entry {
|
|
let read_product: Product = bincode::deserialize(&product_entry)?;
|
|
db.flush().unwrap();
|
|
Ok(Some(read_product))
|
|
} else {
|
|
db.flush().unwrap();
|
|
Ok(None)
|
|
}
|
|
}
|
|
|
|
pub fn make_order(order: &Order) {
|
|
let db = sled::open("order_db").unwrap();
|
|
let bytes = bincode::serialize(&order).unwrap();
|
|
db.insert(order.uuid.to_hyphenated().to_string(), bytes).unwrap();
|
|
db.flush().unwrap();
|
|
}
|
|
|
|
pub fn read_order(uuid: &str) -> std::result::Result<Option<Order>, MyErrorType> {
|
|
let db = sled::open("order_db").unwrap();
|
|
let entry = db.get(uuid)?;
|
|
if let Some(order_entry) = entry {
|
|
let read_order: Order = bincode::deserialize(&order_entry)?;
|
|
db.flush().unwrap();
|
|
Ok(Some(read_order))
|
|
} else {
|
|
db.flush().unwrap();
|
|
Ok(None)
|
|
}
|
|
}
|
|
|
|
pub fn read_all_orders() -> Vec<Order> {
|
|
let db = sled::open("order_db").unwrap();
|
|
let first_key: &[u8] = &db.first().unwrap().unwrap().0;
|
|
let mut iter = db.range(first_key..);
|
|
let mut all_orders: Vec<Order> = Vec::new();
|
|
for order in iter {
|
|
if let order_entry = order.unwrap().1 {
|
|
let read_order: Order = bincode::deserialize(&order_entry).unwrap();
|
|
db.flush().unwrap();
|
|
all_orders.push(read_order);
|
|
} else {
|
|
db.flush().unwrap();
|
|
}
|
|
}
|
|
return all_orders;
|
|
}
|