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
use crate::component::table::Table;
use crate::storage::diskinterface::{DiskError, DiskInterface};
use std::collections::HashMap;
use std::fmt;
use uuid::Uuid;
#[derive(Debug, Clone)]
pub struct Database {
pub name: String,
pub tables: HashMap<String, Table>,
pub is_dirty: bool,
pub is_delete: bool,
uuid: String,
}
#[derive(Debug)]
pub enum DatabaseError {
CausedByFile(DiskError),
}
impl fmt::Display for DatabaseError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
DatabaseError::CausedByFile(ref e) => write!(f, "error caused by file: {}", e),
}
}
}
impl Database {
pub fn new(name: &str) -> Database {
Database {
name: name.to_string(),
tables: HashMap::new(),
is_dirty: true,
is_delete: false,
uuid: Uuid::new_v4().to_string(),
}
}
pub fn insert_new_table(&mut self, table: Table) {
self.tables.insert(table.name.to_string(), table);
}
pub fn load_db(username: &str, db_name: &str) -> Result<Database, DatabaseError> {
let mut db = Database::new(db_name);
db.is_dirty = false;
let metas =
DiskInterface::load_tables_meta(username, db_name, None).map_err(|e| DatabaseError::CausedByFile(e))?;
for meta in metas {
let name = (&meta.name).to_string();
let mut table = Table::new(&name);
table.format_meta(meta);
db.tables.insert(name, table.into());
}
Ok(db)
}
}