-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb.go
368 lines (334 loc) · 8.11 KB
/
db.go
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
package lsm3
import (
"bytes"
"encoding/gob"
"errors"
"fmt"
"reflect"
"sort"
"strings"
"github.com/xia-Sang/bitcask_go/bitcask"
"github.com/xia-Sang/bitcask_go/parse"
)
type TableInfo struct {
RowIndex uint32
TableName string
TableColumns []parse.ColumnDefinition
TableStructType reflect.Type
TableMapIndex map[uint32]struct{}
}
func (ti *TableInfo) Bytes() (int, []byte, error) {
var buf bytes.Buffer
enc := gob.NewEncoder(&buf)
// 创建临时结构体,不包括 TableStructType
temp := struct {
RowIndex uint32
TableName string
TableColumns []parse.ColumnDefinition
TableMapIndex map[uint32]struct{}
}{
RowIndex: ti.RowIndex,
TableName: ti.TableName,
TableColumns: ti.TableColumns,
TableMapIndex: ti.TableMapIndex,
}
// 序列化临时结构体
err := enc.Encode(temp)
if err != nil {
return 0, nil, fmt.Errorf("failed to encode TableInfo: %w", err)
}
return buf.Len(), buf.Bytes(), nil
}
func (ti *TableInfo) FromBytes(data []byte) error {
buf := bytes.NewBuffer(data)
dec := gob.NewDecoder(buf)
// 临时结构体用来反序列化,不包括 TableStructType
temp := struct {
RowIndex uint32
TableName string
TableColumns []parse.ColumnDefinition
TableMapIndex map[uint32]struct{}
}{}
// 反序列化临时结构体
err := dec.Decode(&temp)
if err != nil {
return fmt.Errorf("failed to decode TableInfo: %w", err)
}
// 还原字段
ti.RowIndex = temp.RowIndex
ti.TableName = temp.TableName
ti.TableColumns = temp.TableColumns
ti.TableMapIndex = temp.TableMapIndex
// TableStructType 不需要处理
ti.TableStructType = createStructType(ti.TableColumns)
return nil
}
func NewTableInfo(ast *parse.CreateTree) *TableInfo {
ti := &TableInfo{
RowIndex: 0,
TableName: ast.Table,
TableColumns: ast.Columns,
TableStructType: createStructType(ast.Columns),
TableMapIndex: make(map[uint32]struct{}),
}
return ti
}
type Contains struct {
table map[string]*TableInfo
ts map[string]uint32
tableIndex uint32
row uint32
db *bitcask.BitCask
dirPath string
}
// Bytes compresses the Contains into a byte slice
func (c *Contains) Bytes() (int, []byte, error) {
var buf bytes.Buffer
enc := gob.NewEncoder(&buf)
err := enc.Encode(c.ts)
if err != nil {
return 0, nil, err
}
err = enc.Encode(c.tableIndex)
if err != nil {
return 0, nil, err
}
err = enc.Encode(c.row)
if err != nil {
return 0, nil, err
}
return buf.Len(), buf.Bytes(), nil
}
// RestoreContains Restore decompresses the byte slice into a Contains
func RestoreContains(data []byte) (*Contains, error) {
buf := bytes.NewReader(data)
dec := gob.NewDecoder(buf)
var ts map[string]uint32
var tableIndex uint32
var row uint32
err := dec.Decode(&ts)
if err != nil {
return nil, err
}
err = dec.Decode(&tableIndex)
if err != nil {
return nil, err
}
err = dec.Decode(&row)
if err != nil {
return nil, err
}
return &Contains{
ts: ts,
tableIndex: tableIndex,
row: row,
}, nil
}
// NewContainsWithDirPath 创建表之后 我们需要对于table 进行存储
// 并且记录重要信息
// table index,table ast
func NewContainsWithDirPath(dirPath string) (*Contains, error) {
c, err := LoadFromDB(dirPath)
c.dirPath = dirPath
if err != nil {
return nil, err
}
opts, err := bitcask.NewOptions(dirPath)
if err != nil {
return nil, err
}
db, err := bitcask.NewBitCask(opts)
if err != nil {
return nil, err
}
c.db = db
return c, nil
}
// NewContains 测试使用
func NewContains() (*Contains, error) {
dirPath := "./data"
c, err := LoadFromDB(dirPath)
c.dirPath = dirPath
if err != nil {
return nil, err
}
opts, err := bitcask.NewOptions(dirPath)
if err != nil {
return nil, err
}
db, err := bitcask.NewBitCask(opts)
if err != nil {
return nil, err
}
c.db = db
return c, nil
}
func (c *Contains) Close() error {
if err := c.SaveToDB(); err != nil {
return err
}
if err := c.db.Close(); err != nil {
return err
}
c.ts = nil
c.table = nil
c.tableIndex = 0
c.row = 0
return nil
}
func (c *Contains) CreatTable(sql string) error {
scan := parse.NewScannerFromString(sql)
createAst, err := scan.ParseCreate()
if err != nil {
return err
}
if _, ok := c.ts[createAst.Table]; ok {
return fmt.Errorf("table exist")
}
tableInfo := NewTableInfo(createAst)
c.table[createAst.Table] = tableInfo
c.ts[createAst.Table] = c.tableIndex
c.tableIndex++
return nil
}
func (c *Contains) InsertTable(sql string) error {
scan := parse.NewScannerFromString(sql)
insertAst, err := scan.ParseInsert()
if err != nil {
return err
}
table, ok := c.table[insertAst.Table]
if !ok {
return errors.New("table not exist")
}
for _, tableInfo := range insertAst.Values {
dict := make(map[string]interface{})
for i, value := range tableInfo {
dict[insertAst.Columns[i]] = value
}
val := table.NewStructValues(dict)
serializedValue, err := serialize(val)
if err != nil {
return err
}
key, value := tableName(c.ts[table.TableName], table.RowIndex), serializedValue
if err = c.db.Set(key, value); err != nil {
return err
}
table.TableMapIndex[table.RowIndex] = struct{}{}
table.RowIndex++
}
return nil
}
func (c *Contains) SelectTable(sql string) error {
scan := parse.NewScannerFromString(sql)
selectAst, err := scan.ParseSelect()
if err != nil {
return err
}
values, _, err := c.getTableInfosWithWhere(selectAst.Table, selectAst.Where)
if err != nil {
return err
}
if len(values) > 0 {
if selectAst.Projects[0] == "*" {
printTable(values)
} else {
printTableWithColumns(values, selectAst.Projects)
}
} else {
fmt.Println("No data found.")
}
return nil
}
func (c *Contains) DeleteTable(sql string) error {
scan := parse.NewScannerFromString(sql)
deleteAst, err := scan.ParseDelete()
if err != nil {
return err
}
values, ids, err := c.getTableInfosWithWhere(deleteAst.Table, deleteAst.Where)
if err != nil {
return err
}
//fmt.Println(ids)
for _, id := range ids {
key := tableName(c.ts[deleteAst.Table], id)
if err := c.db.Delete(key); err != nil {
return err
}
delete(c.table[deleteAst.Table].TableMapIndex, id)
}
fmt.Println("Delete Table")
printTable(values)
return nil
}
// tabled_row 生成一个唯一的行标识符
func tableName(tableIndex, rowIndex uint32) []byte {
return []byte(fmt.Sprintf("%03d_%04d", tableIndex, rowIndex))
}
// 根据where信息来实现对于数据的检索
func (c *Contains) getTableInfosWithWhere(table string, where []string) ([]interface{}, []uint32, error) {
tableInfo, ok := c.table[table]
if !ok {
return nil, nil, errors.New("table not exist")
}
var keys []uint32
for id := range tableInfo.TableMapIndex {
keys = append(keys, id)
}
sort.Slice(keys, func(i, j int) bool {
return keys[i] < keys[j]
})
var values []interface{}
var ids []uint32
if len(where) == 0 {
for _, id := range keys {
key := tableName(c.ts[tableInfo.TableName], id)
encValue, err := c.db.Query(key)
if err != nil {
return nil, nil, err
}
value := tableInfo.newTableStruct()
if err := deserialize(encValue, value); err != nil {
return nil, nil, err
}
values = append(values, value)
ids = append(ids, id)
}
return values, ids, nil
}
if len(where) != 3 {
return nil, nil, errors.New("invalid where condition")
}
column := where[0]
op := where[1]
rightValueStr := where[2]
field, ok := tableInfo.TableStructType.FieldByName(strings.Title(column))
if !ok {
return nil, nil, errors.New("field not exist")
}
fieldType := field.Type
rightValue, err := convertToType(rightValueStr, fieldType)
if err != nil {
return nil, nil, err
}
for _, id := range keys {
key := tableName(c.ts[tableInfo.TableName], id)
encValue, err := c.db.Query(key)
if err != nil {
return nil, nil, err
}
value := tableInfo.newTableStruct()
if err := deserialize(encValue, value); err != nil {
return nil, nil, err
}
structValue := reflect.ValueOf(value).Elem()
leftValue := structValue.FieldByName(strings.Title(column))
if ok := evaluateCondition(op, leftValue, rightValue); ok {
values = append(values, value)
ids = append(ids, id)
}
}
return values, ids, nil
}