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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
use super::*;
use tidb_query_datatype::codec::{datum, Datum};
use tidb_query_datatype::expr::EvalContext;
use tipb::{ColumnInfo, FieldType};
pub const TYPE_VAR_CHAR: i32 = 1;
pub const TYPE_LONG: i32 = 2;
#[derive(Clone)]
pub struct Column {
pub id: i64,
pub(crate) col_type: i32,
pub index: i64,
pub(crate) default_val: Option<Datum>,
}
impl Column {
pub fn as_column_info(&self) -> ColumnInfo {
let mut c_info = ColumnInfo::default();
c_info.set_column_id(self.id);
c_info.set_tp(self.col_field_type());
c_info.set_pk_handle(self.index == 0);
if let Some(ref dv) = self.default_val {
c_info.set_default_val(
datum::encode_value(&mut EvalContext::default(), &[dv.clone()]).unwrap(),
)
}
c_info
}
pub fn as_field_type(&self) -> FieldType {
let mut ft = FieldType::default();
ft.set_tp(self.col_field_type());
ft
}
pub fn col_field_type(&self) -> i32 {
match self.col_type {
TYPE_LONG => 8,
TYPE_VAR_CHAR => 15,
_ => unreachable!("col_type: {}", self.col_type),
}
}
}
pub struct ColumnBuilder {
col_type: i32,
index: i64,
default_val: Option<Datum>,
}
impl ColumnBuilder {
pub fn new() -> ColumnBuilder {
ColumnBuilder {
col_type: TYPE_LONG,
index: -1,
default_val: None,
}
}
pub fn col_type(mut self, t: i32) -> ColumnBuilder {
self.col_type = t;
self
}
pub fn primary_key(mut self, b: bool) -> ColumnBuilder {
if b {
self.index = 0;
} else {
self.index = -1;
}
self
}
pub fn index_key(mut self, idx_id: i64) -> ColumnBuilder {
self.index = idx_id;
self
}
pub fn default(mut self, val: Datum) -> ColumnBuilder {
self.default_val = Some(val);
self
}
pub fn build(self) -> Column {
Column {
id: next_id(),
col_type: self.col_type,
index: self.index,
default_val: self.default_val,
}
}
}