First Implementation for Database Components
- 2018-10-24
- Liu, An-Chi 劉安齊
I found that, before I finish the parser and the worker of SQL. I should implement the components of a database first.
So, other modules could use components. No matter the parser or the worker, if there are no information and data of components, they cannot do anything.
There are four layers of a database, which are database, table, field, and datatype.
Databasehas manytables.Tablehas manyfields, and some traits, which areprimary_key,foreign_key, andreference_table.Fieldhasdatatype,value,not_null, andcheckDatatypeare the same enum as inSymbol
Let’s take a look:
!FILENAME component/database.rs
use component::table::Table;
#[derive(Debug, Clone)]
pub struct Database {
name: String,
tables: Vec<Table>
}
impl Database {
fn new(name: &str) -> Database {
Database {
name: name.to_string(),
tables: vec![],
}
}
}
!FILENAME component/table.rs
use std::collections::HashMap;
use component::field::Field;
#[derive(Debug, Clone)]
pub struct Table {
name: String,
fields: HashMap<String,Field>,
primary_key: Vec<String>,
foreign_key: Vec<String>,
reference_table: Option<String>,
}
impl Table {
fn new(name: &str) -> Table {
Table {
name: name.to_string(),
fields: HashMap::new(),
primary_key: vec![],
foreign_key: vec![],
reference_table: None,
}
}
}
!FILENAME component/field.rs
use component::datatype::DataType;
use component::datatype::Value;
#[derive(Debug, Clone)]
pub struct Field {
name: String,
datatype: DataType,
value: Value,
not_null: bool,
check: Checker,
}
#[derive(Debug, Clone)]
pub enum Checker {
None,
Some(Operator, Value)
}
#[derive(Debug, Clone)]
enum Operator {
LT, // <
LE, // <=
EQ, // =
NE, // !=
GT, // >
GE, // >=
}
impl Field {
fn new(name: &str, datatype: DataType, value: Value, not_null: bool, check: Checker) -> Field {
Field {
name: name.to_string(),
datatype,
value,
not_null,
check,
}
}
}
!FILENAME component/datatype.rs
#[derive(Debug, Clone)]
pub enum DataType {
Char,
Double,
Float,
Int,
Varchar,
}
#[derive(Debug, Clone)]
pub enum Value{
Char(u8, String),
Double(f64),
Float(f32),
Int(i32),
Varchar(u8, String),
}
This is just the initialization. I will implement methods later.