mod id; mod record; use crate::{ data::{ id::ID, record::{Field, Record}, }, error::{ErrorType, MTTError}, }; use std::collections::HashMap; enum FieldType { ID, } struct FieldDef; impl FieldDef { fn new() -> Self { Self {} } fn get_type(&self) -> FieldType { FieldType::ID } } struct Table { fields: HashMap, } impl Table { fn new() -> Self { Self { fields: HashMap::new(), } } fn description(&self) -> &HashMap { &self.fields } fn add_field(&mut self, name: &str, field_type: FieldType) -> Result<(), MTTError> { match self.fields.get(name) { Some(_) => { let err = ErrorType::TableAddFieldDuplicate(name.to_string()); Err(MTTError::new(err)) } None => { self.fields.insert(name.to_string(), FieldDef::new()); Ok(()) } } } fn add_record(&mut self, rec: Record) -> Result { for (key, _) in rec.iter() { match self.fields.get(key) { Some(_) => {} None => { let err = ErrorType::TableRecordInvalidFieldName(key.to_string()); return Err(MTTError::new(err)); } } } Ok(rec) } } #[cfg(test)] mod table { use super::*; #[test] fn new_table() { let tbl = Table::new(); let data = tbl.description(); assert_eq!(data.len(), 0); } #[test] fn add_field() { let mut tbl = Table::new(); let field_name = "something "; tbl.add_field(field_name, FieldType::ID); let data = tbl.description(); assert_eq!(data.len(), 1); match data.get(field_name) { Some(field_info) => match field_info.get_type() { FieldType::ID => {} _ => unreachable!("incorrect field type"), }, None => unreachable!("should return field definition"), } } #[test] fn error_on_duplicate_name() { let mut tbl = Table::new(); let name = "one"; tbl.add_field(name, FieldType::ID); match tbl.add_field(name, FieldType::ID) { Ok(_) => unreachable!(" Should not duplicates."), Err(err) => match err.get_code() { ErrorType::TableAddFieldDuplicate(result) => assert_eq!(result, name), _ => unreachable!("should produce a duplicate name error"), }, } } #[test] fn add_record() { let mut tbl = Table::new(); let name = "id"; let field_data = ID::random(); tbl.add_field(name, FieldType::ID).unwrap(); let mut data: HashMap = HashMap::new(); data.insert(name.to_string(), field_data.clone().into()); let rec = Record::new(data); let result = tbl.add_record(rec).unwrap(); assert_eq!( result.get(name).unwrap().to_string(), field_data.to_string() ); } #[test] fn add_record_incorrect_field_name() { let mut tbl = Table::new(); let name = "id"; let field_data = ID::random(); let mut data: HashMap = HashMap::new(); data.insert(name.to_string(), field_data.clone().into()); let rec = Record::new(data); match tbl.add_record(rec) { Ok(_) => unreachable!("should have produced an error"), Err(err) => match err.get_code() { ErrorType::TableRecordInvalidFieldName(result) => { assert_eq!(result, name); } _ => unreachable!("should have been invalid name error"), }, } } }