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
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
use bson::{decode_document, encode_document, Bson, Document};

use std::collections::HashMap;
use std::fs::{self, DirBuilder, File};
use std::io::prelude::*;
use std::io::Cursor;
use std::path::Path;

pub mod config;
pub mod errors;

use config::*;
use errors::*;

/// Represents an Entry in the database.
/// 
/// Contains the key and the following content corresponding to that key.
#[derive(Clone, Debug)]
pub struct Entry {
    pub key: String,
    pub content: String,
}
impl Entry {
    pub fn as_bytes(&self) -> &[u8] {
        self.content.as_bytes()
    }

    pub fn inner(&self) -> &str {
        &self.content
    }
}

/// Represents a collection of documents.
///
/// It is the main API for data managment for Keratin.
#[derive(Clone, Debug)]
pub struct Collection {
    main_path: String,
    config: Config,
    //mapped_keys: HashMap<String, String>, // Pair (key, path to document)
    cached_docs: HashMap<String, Entry>, // Pair (key, entry)
}

impl Collection {
    fn _gen_key(&self, pk: &str) -> String {
        let digest = md5::compute(pk);

        format!("{}{:x}", self.config.coll_prefix(), digest)
    }

    /// Returns an entry of the database given the respective key, or ```None``` if the key
    /// corresponds to no known entries
    pub fn get(&mut self, k: &str) -> Option<&Entry> {
        let key = self._gen_key(k);
        self._find(&key)
    }

    fn _find(&mut self, pk: &str) -> Option<&Entry> {
        self.cache_entries();
        self.cached_docs.get(pk)
    }

    /// Insert an entry into the database given an ```Entry```
    ///
    /// # Note
    /// This does not cache the entry automaticaly 
    pub fn insert(&mut self, key: &str, entry: &str) -> Result<(), Errors> {
        // Generate primary key
        let key = self._gen_key(key);

        // Check if entry with key already exists in cache
        match self._find(&key) {
            Some(_) => Err(Errors::AlreadyExists),
            None => {
                // Write the entry to a document and save it
                let mut doc = Document::new();
                doc.insert("data".to_owned(), Bson::String(entry.to_owned()));

                let mut buf = Vec::new();
                encode_document(&mut buf, &doc).unwrap();

                let mut file =
                    File::create(format!("{}/{}.bson", self.config.data_path(), key)).unwrap();
                file.write_all(&buf).unwrap();

                Ok(())
            }
        }
    }

    /// Delete a entry in the database given the key.
    /// 
    /// This deletes from both the cache and non-volatile storage.
    /// 
    /// # Note
    /// In the future this will use a query string to find what multiple elements to delete
    ///
    /// # Return
    /// Returns an Error ```EntryNotFound``` if the key does not match any entry
    pub fn delete(&mut self, query: &str) -> Result<(), Errors>{
        let k = self._gen_key(query);
        return self._remove_entry(&k)
    }

    pub fn modify(query: &str) {}
    /// A function to create a new Keratin db from scratch for a fast setup.
    ///
    /// The config file keratin.toml is created with the default options. If it already exists, the
    /// config file.
    ///
    /// # Arguments
    /// Truncate: if it is TRUE, this function wipes every document in ```db/data/``` along with
    /// truncating the mapped keys file.
    ///
    /// # Panics
    ///
    /// This fuction uses the enviroment variable ```CARGO_MANIFEST_DIR```, so this will only work
    /// when running your project using ```cargo```, else it will panic.
    /// If you're using planning in using Keratin in production use ```configure()``` instead
    pub fn new(truncate: bool) -> Collection {
        unimplemented!()
    }

    /// A function to initialize the collection using the path of a configuration file
    ///
    /// # Arguments
    ///
    /// * `path` - An Option with a Path. If this is None, Keratin will use the default config file
    /// path (eg. ```db/keratin.toml```)
    ///
    /// # Attention
    ///
    /// USE ONLY ABSOLUTE PATHS!!!
    ///
    /// Use of the ```None``` Option is unstable
    ///
    /// # Errors
    ///
    /// This returns an error if the config file is not found OR if the folder doesn't have the
    /// right permitions
    // TODO: Error handle this
    pub fn configure(path: Option<&str>) -> Collection {
        let path = match path {
            Some(x) => Path::new(x),
            None => {
                 DirBuilder::new()
                    .recursive(true)
                    .create("db")
                    .unwrap();
                let mut f = File::create("db/keratin.toml").unwrap();

                f.write_all(r#"project = ".default."
                    [core]
                    collection = ".default."
                    primary_key = "id"
                    data_path = ".default."
                    "#.as_bytes()).unwrap();
                
                Path::new("db/keratin.toml")

               
            }
        };

        let config = Config::new_from_path(path);
        let main_path = String::from(path.parent().unwrap().to_str().unwrap());

        DirBuilder::new()
            .recursive(true)
            .create(config.data_path())
            .unwrap();

        Collection {
            main_path,
            config,
            //mapped_keys: HashMap::new(),
            cached_docs: HashMap::new(),
        }
    }

    // TODO: Error handle this
    fn _remove_entry(&mut self, given_key: &str) -> Result<(), Errors>{
        for entry in fs::read_dir(self.config.data_path()).unwrap() {
            let fp = entry.unwrap().path();
            let key = Path::new(&fp).file_stem().unwrap().to_str().unwrap().to_string();

            if key == given_key {
                fs::remove_file(fp).unwrap();
                self.cached_docs.remove(given_key);

                return Ok(())
            }
        }
        Err(Errors::EntryNotFound)
    }

    // TODO: Error handle this
    pub fn cache_entries(&mut self) {
        for entry in fs::read_dir(self.config.data_path()).unwrap() {
            let fp = entry.unwrap().path();
            let mut f = File::open(fp.clone()).unwrap();
            let mut s = String::new();
            f.read_to_string(&mut s).unwrap();

            let key = Path::new(&fp).file_stem().unwrap().to_str().unwrap().to_string();

            let doc = decode_document(&mut Cursor::new(&s)).expect("Could Not Decode");
            let upd = doc.get("data").unwrap().as_str().unwrap().to_string();

            let e = Entry {
                key: key.clone(),
                content: upd.clone()
            };


            self.cached_docs.insert(key, e);
        }
    }
}