Gitbook: https://tigercosmos.github.io/lets-build-dbms/

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 many tables.
  • Table has many fields, and some traits, which are primary_key, foreign_key, and reference_table.
  • Field has datatype, value, not_null, and check
  • Datatype are the same enum as in Symbol

Let’s take a look:

!FILENAME component/database.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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

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
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#[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.