Jeff Baskin
972c4686e0
Some checks failed
MoreThanText/morethantext/pipeline/head There was a failure building this commit
100 lines
2.1 KiB
Rust
100 lines
2.1 KiB
Rust
pub mod id;
|
|
mod record;
|
|
mod table;
|
|
|
|
use crate::{
|
|
data::table::Table,
|
|
error::{ErrorType, MTTError},
|
|
};
|
|
use std::{collections::HashMap, fmt, ops::Deref};
|
|
|
|
#[derive(Debug, Clone)]
|
|
pub enum DBError {
|
|
DuplicateTable(String),
|
|
}
|
|
|
|
impl fmt::Display for DBError {
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
match self {
|
|
DBError::DuplicateTable(data) => write!(f, "'{}' already exists", data),
|
|
}
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod errora {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn duplicate_table() {
|
|
let name = "fred";
|
|
let err = DBError::DuplicateTable(name.to_string());
|
|
assert_eq!(err.to_string(), format!("'{}' already exists", name));
|
|
}
|
|
}
|
|
|
|
struct Database {
|
|
tables: HashMap<String, Table>,
|
|
}
|
|
|
|
impl Database {
|
|
fn new() -> Self {
|
|
Self {
|
|
tables: HashMap::new(),
|
|
}
|
|
}
|
|
|
|
fn add_table(&mut self, name: &str, table: Table) -> Result<(), MTTError> {
|
|
match self.tables.get(name) {
|
|
Some(_) => {
|
|
let error = ErrorType::TableRecordInvalidFieldName(name.to_string());
|
|
return Err(MTTError::new(error));
|
|
}
|
|
None => {}
|
|
}
|
|
self.tables.insert(name.to_string(), table);
|
|
Ok(())
|
|
}
|
|
}
|
|
|
|
impl Deref for Database {
|
|
type Target = HashMap<String, Table>;
|
|
|
|
fn deref(&self) -> &Self::Target {
|
|
&self.tables
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod databases {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn create_new_database() {
|
|
let db = Database::new();
|
|
assert_eq!(db.len(), 0);
|
|
}
|
|
|
|
#[test]
|
|
fn add_table() {
|
|
let mut db = Database::new();
|
|
let tbl = Table::new();
|
|
let name = "Something";
|
|
db.add_table(name, tbl).unwrap();
|
|
assert_eq!(db.len(), 1);
|
|
}
|
|
|
|
#[test]
|
|
fn no_duplicate_names() {
|
|
let mut db = Database::new();
|
|
let tbl1 = Table::new();
|
|
let tbl2 = Table::new();
|
|
let name = "Something";
|
|
db.add_table(name, tbl1).unwrap();
|
|
match db.add_table(name, tbl2) {
|
|
Ok(_) => unreachable!("Should have been an error"),
|
|
Err(err) => {}
|
|
}
|
|
}
|
|
}
|