avlon_db/
lib.rs

1use serde::{Deserialize, Serialize};
2use sled::{self, Db};
3
4/// A struct representing a wrapper around a Sled database.
5pub struct AvlonDB {
6    pub db_name: String,
7    pub client: Db,
8}
9
10impl AvlonDB {
11    /// Creates a new instance of AvlonDB with the specified database name.
12    ///
13    /// # Arguments
14    ///
15    /// * `db_name` - The name of the database file.
16    ///
17    /// # Returns
18    ///
19    /// A new `AvlonDB` instance.
20    pub fn new(db_name: String) -> Self {
21        let client = sled::open(&db_name).expect("Failed to open Sled database!");
22        AvlonDB { db_name, client }
23    }
24
25    /// Saves a value to the database under the given key.
26    ///
27    /// # Arguments
28    ///
29    /// * `key` - The key to associate with the value.
30    /// * `value` - The value to store in the database.
31    ///
32    /// # Returns
33    ///
34    /// A `Result` indicating success or failure.
35    pub fn save<T>(&self, key: String, value: T) -> Result<(), Box<dyn std::error::Error>>
36    where
37        T: Serialize,
38    {
39        let serialized_data = serde_json::to_vec(&value)?;
40        self.client.insert(key, serialized_data)?;
41        Ok(())
42    }
43
44    /// Loads a value from the database associated with the given key.
45    ///
46    /// # Arguments
47    ///
48    /// * `key` - The key associated with the value to load.
49    ///
50    /// # Returns
51    ///
52    /// A `Result` containing an `Option` with the value, or `None` if the key does not exist.
53    pub fn load<T>(&self, key: &str) -> Result<Option<T>, Box<dyn std::error::Error>>
54    where
55        T: for<'de> Deserialize<'de>,
56    {
57        if let Some(data) = self.client.get(key)? {
58            let value: T = serde_json::from_slice(&data)?;
59            Ok(Some(value))
60        } else {
61            Ok(None)
62        }
63    }
64
65    /// Loads range data from the database associated with the given start key and end key.
66    ///
67    /// # Arguments
68    ///
69    /// * `start_key` - The start key of range data.
70    /// * `end_key` - The end key of range data.
71    ///
72    /// # Returns
73    ///
74    /// A `Result` containing a `Vec` of the values, or an `Err` if an issue occurs.
75    pub fn load_range<T>(&self, start_key: &str, end_key: &str) -> sled::Result<Vec<T>>
76    where
77        T: for<'de> Deserialize<'de>,
78    {
79        let mut results = Vec::new();
80
81        for result in self.client.range(start_key.as_bytes()..end_key.as_bytes()) {
82            let (_, value) = result?;
83            let item: T = serde_json::from_slice(&value).unwrap();
84            results.push(item);
85        }
86
87        Ok(results)
88    }
89
90    /// Removes a value from the database associated with the given key.
91    ///
92    /// # Arguments
93    ///
94    /// * `key` - The key associated with the value to remove.
95    ///
96    /// # Returns
97    ///
98    /// A `Result` indicating success or failure.
99    pub fn remove(&self, key: &str) -> Result<(), Box<dyn std::error::Error>> {
100        self.client.remove(key)?;
101        Ok(())
102    }
103
104    /// Updates the value associated with the given key in the database.
105    ///
106    /// # Arguments
107    ///
108    /// * `key` - The key associated with the value to update.
109    /// * `new_value` - The new value to store in the database.
110    ///
111    /// # Returns
112    ///
113    /// A `Result` indicating success or failure. Returns an error if the key does not exist.
114    pub fn update<T>(&self, key: &str, new_value: T) -> Result<(), Box<dyn std::error::Error>>
115    where
116        T: Serialize,
117    {
118        if self.client.contains_key(key)? {
119            let serialized_data = serde_json::to_vec(&new_value)?;
120            self.client.insert(key, serialized_data)?;
121            Ok(())
122        } else {
123            Err(format!("Key '{}' does not exist in the database.", key).into())
124        }
125    }
126}