21: First Implementation for Database Components
2018/11/5
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
.
Database
has manytable
s.Table
has manyfield
s, and some traits, which areprimary_key
,foreign_key
, andreference_table
.Field
hasdatatype
,value
,not_null
, andcheck
Datatype
are the same enum as inSymbol
Let's take a look:
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![],
}
}
}
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,
}
}
}
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,
}
}
}
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.