This repository was archived by the owner on Jan 28, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 109
/
Copy pathtable.go
555 lines (456 loc) · 10.9 KB
/
table.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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
package memory
import (
"bytes"
"encoding/gob"
"fmt"
"io"
"strconv"
"github.com/src-d/go-mysql-server/sql"
"github.com/src-d/go-mysql-server/sql/expression"
errors "gopkg.in/src-d/go-errors.v1"
)
// Table represents an in-memory database table.
type Table struct {
name string
schema sql.Schema
partitions map[string][]sql.Row
keys [][]byte
insert int
filters []sql.Expression
projection []string
columns []int
lookup sql.IndexLookup
}
var _ sql.Table = (*Table)(nil)
var _ sql.Inserter = (*Table)(nil)
var _ sql.FilteredTable = (*Table)(nil)
var _ sql.ProjectedTable = (*Table)(nil)
var _ sql.IndexableTable = (*Table)(nil)
// NewTable creates a new Table with the given name and schema.
func NewTable(name string, schema sql.Schema) *Table {
return NewPartitionedTable(name, schema, 0)
}
// NewPartitionedTable creates a new Table with the given name, schema and number of partitions.
func NewPartitionedTable(name string, schema sql.Schema, numPartitions int) *Table {
var keys [][]byte
var partitions = map[string][]sql.Row{}
if numPartitions < 1 {
numPartitions = 1
}
for i := 0; i < numPartitions; i++ {
key := strconv.Itoa(i)
keys = append(keys, []byte(key))
partitions[key] = []sql.Row{}
}
return &Table{
name: name,
schema: schema,
partitions: partitions,
keys: keys,
}
}
// Name implements the sql.Table interface.
func (t *Table) Name() string {
return t.name
}
// Schema implements the sql.Table interface.
func (t *Table) Schema() sql.Schema {
return t.schema
}
// Partitions implements the sql.Table interface.
func (t *Table) Partitions(ctx *sql.Context) (sql.PartitionIter, error) {
var keys [][]byte
for _, k := range t.keys {
if rows, ok := t.partitions[string(k)]; ok && len(rows) > 0 {
keys = append(keys, k)
}
}
return &partitionIter{keys: keys}, nil
}
// PartitionCount implements the sql.PartitionCounter interface.
func (t *Table) PartitionCount(ctx *sql.Context) (int64, error) {
return int64(len(t.partitions)), nil
}
// PartitionRows implements the sql.PartitionRows interface.
func (t *Table) PartitionRows(ctx *sql.Context, partition sql.Partition) (sql.RowIter, error) {
rows, ok := t.partitions[string(partition.Key())]
if !ok {
return nil, fmt.Errorf(
"partition not found: %q", partition.Key(),
)
}
var values sql.IndexValueIter
if t.lookup != nil {
var err error
values, err = t.lookup.Values(partition)
if err != nil {
return nil, err
}
}
return &tableIter{
rows: rows,
columns: t.columns,
filters: t.filters,
indexValues: values,
}, nil
}
type partition struct {
key []byte
}
func (p *partition) Key() []byte { return p.key }
type partitionIter struct {
keys [][]byte
pos int
}
func (p *partitionIter) Next() (sql.Partition, error) {
if p.pos >= len(p.keys) {
return nil, io.EOF
}
key := p.keys[p.pos]
p.pos++
return &partition{key}, nil
}
func (p *partitionIter) Close() error { return nil }
type tableIter struct {
columns []int
filters []sql.Expression
rows []sql.Row
indexValues sql.IndexValueIter
pos int
}
var _ sql.RowIter = (*tableIter)(nil)
func (i *tableIter) Next() (sql.Row, error) {
row, err := i.getRow()
if err != nil {
return nil, err
}
for _, f := range i.filters {
result, err := f.Eval(sql.NewEmptyContext(), row)
if err != nil {
return nil, err
}
if result != true {
return i.Next()
}
}
return projectOnRow(i.columns, row), nil
}
func (i *tableIter) Close() error {
if i.indexValues == nil {
return nil
}
return i.indexValues.Close()
}
func (i *tableIter) getRow() (sql.Row, error) {
if i.indexValues != nil {
return i.getFromIndex()
}
if i.pos >= len(i.rows) {
return nil, io.EOF
}
row := i.rows[i.pos]
i.pos++
return row, nil
}
func projectOnRow(columns []int, row sql.Row) sql.Row {
if len(columns) < 1 {
return row
}
projected := make([]interface{}, len(columns))
for i, selected := range columns {
projected[i] = row[selected]
}
return projected
}
func (i *tableIter) getFromIndex() (sql.Row, error) {
data, err := i.indexValues.Next()
if err != nil {
return nil, err
}
value, err := decodeIndexValue(data)
if err != nil {
return nil, err
}
return i.rows[value.Pos], nil
}
type indexValue struct {
Key string
Pos int
}
func decodeIndexValue(data []byte) (*indexValue, error) {
dec := gob.NewDecoder(bytes.NewReader(data))
var value indexValue
if err := dec.Decode(&value); err != nil {
return nil, err
}
return &value, nil
}
func encodeIndexValue(value *indexValue) ([]byte, error) {
var buf bytes.Buffer
enc := gob.NewEncoder(&buf)
if err := enc.Encode(value); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
// Insert a new row into the table.
func (t *Table) Insert(ctx *sql.Context, row sql.Row) error {
if err := checkRow(t.schema, row); err != nil {
return err
}
key := string(t.keys[t.insert])
t.insert++
if t.insert == len(t.keys) {
t.insert = 0
}
t.partitions[key] = append(t.partitions[key], row)
return nil
}
// Delete the given row from the table.
func (t *Table) Delete(ctx *sql.Context, row sql.Row) error {
if err := checkRow(t.schema, row); err != nil {
return err
}
matches := false
for partitionIndex, partition := range t.partitions {
for partitionRowIndex, partitionRow := range partition {
matches = true
for rIndex, val := range row {
if val != partitionRow[rIndex] {
matches = false
break
}
}
if matches {
t.partitions[partitionIndex] = append(partition[:partitionRowIndex], partition[partitionRowIndex+1:]...)
break
}
}
if matches {
break
}
}
if !matches {
return sql.ErrDeleteRowNotFound
}
return nil
}
func (t *Table) Update(ctx *sql.Context, oldRow sql.Row, newRow sql.Row) error {
if err := checkRow(t.schema, oldRow); err != nil {
return err
}
if err := checkRow(t.schema, newRow); err != nil {
return err
}
matches := false
for partitionIndex, partition := range t.partitions {
for partitionRowIndex, partitionRow := range partition {
matches = true
for rIndex, val := range oldRow {
if val != partitionRow[rIndex] {
matches = false
break
}
}
if matches {
t.partitions[partitionIndex][partitionRowIndex] = newRow
break
}
}
if matches {
break
}
}
return nil
}
func checkRow(schema sql.Schema, row sql.Row) error {
if len(row) != len(schema) {
return sql.ErrUnexpectedRowLength.New(len(schema), len(row))
}
for i, value := range row {
c := schema[i]
if !c.Check(value) {
return sql.ErrInvalidType.New(value)
}
}
return nil
}
// String implements the sql.Table inteface.
func (t *Table) String() string {
p := sql.NewTreePrinter()
kind := ""
if len(t.columns) > 0 {
kind += "Projected "
}
if len(t.filters) > 0 {
kind += "Filtered "
}
if t.lookup != nil {
kind += "Indexed"
}
if kind != "" {
kind = ": " + kind
}
_ = p.WriteNode("Table(%s)%s", t.name, kind)
var schema = make([]string, len(t.Schema()))
for i, col := range t.Schema() {
schema[i] = fmt.Sprintf(
"Column(%s, %s, nullable=%v)",
col.Name,
col.Type.Type().String(),
col.Nullable,
)
}
_ = p.WriteChildren(schema...)
return p.String()
}
// HandledFilters implements the sql.FilteredTable interface.
func (t *Table) HandledFilters(filters []sql.Expression) []sql.Expression {
var handled []sql.Expression
for _, f := range filters {
var hasOtherFields bool
expression.Inspect(f, func(e sql.Expression) bool {
if e, ok := e.(*expression.GetField); ok {
if e.Table() != t.name || !t.schema.Contains(e.Name(), t.name) {
hasOtherFields = true
return false
}
}
return true
})
if !hasOtherFields {
handled = append(handled, f)
}
}
return handled
}
// WithFilters implements the sql.FilteredTable interface.
func (t *Table) WithFilters(filters []sql.Expression) sql.Table {
if len(filters) == 0 {
return t
}
nt := *t
nt.filters = filters
return &nt
}
// WithProjection implements the sql.ProjectedTable interface.
func (t *Table) WithProjection(colNames []string) sql.Table {
if len(colNames) == 0 {
return t
}
nt := *t
columns, schema, _ := nt.newColumnIndexesAndSchema(colNames)
nt.columns = columns
nt.projection = colNames
nt.schema = schema
return &nt
}
func (t *Table) newColumnIndexesAndSchema(colNames []string) ([]int, sql.Schema, error) {
var columns []int
var schema []*sql.Column
for _, name := range colNames {
i := t.schema.IndexOf(name, t.name)
if i == -1 {
return nil, nil, errColumnNotFound.New(name)
}
if len(t.columns) == 0 {
// if the table hasn't been projected before
// match against the origianl schema
columns = append(columns, i)
} else {
// get indexes for the new projections from
// the orginal indexes.
columns = append(columns, t.columns[i])
}
schema = append(schema, t.schema[i])
}
return columns, schema, nil
}
// WithIndexLookup implements the sql.IndexableTable interface.
func (t *Table) WithIndexLookup(lookup sql.IndexLookup) sql.Table {
if lookup == nil {
return t
}
nt := *t
nt.lookup = lookup
return &nt
}
// IndexKeyValues implements the sql.IndexableTable interface.
func (t *Table) IndexKeyValues(
ctx *sql.Context,
colNames []string,
) (sql.PartitionIndexKeyValueIter, error) {
iter, err := t.Partitions(ctx)
if err != nil {
return nil, err
}
columns, _, err := t.newColumnIndexesAndSchema(colNames)
if err != nil {
return nil, err
}
return &partitionIndexKeyValueIter{
table: t,
iter: iter,
columns: columns,
ctx: ctx,
}, nil
}
// Projection implements the sql.ProjectedTable interface.
func (t *Table) Projection() []string {
return t.projection
}
// Filters implements the sql.FilteredTable interface.
func (t *Table) Filters() []sql.Expression {
return t.filters
}
// IndexLookup implements the sql.IndexableTable interface.
func (t *Table) IndexLookup() sql.IndexLookup {
return t.lookup
}
type partitionIndexKeyValueIter struct {
table *Table
iter sql.PartitionIter
columns []int
ctx *sql.Context
}
func (i *partitionIndexKeyValueIter) Next() (sql.Partition, sql.IndexKeyValueIter, error) {
p, err := i.iter.Next()
if err != nil {
return nil, nil, err
}
iter, err := i.table.PartitionRows(i.ctx, p)
if err != nil {
return nil, nil, err
}
return p, &indexKeyValueIter{
key: string(p.Key()),
iter: iter,
columns: i.columns,
}, nil
}
func (i *partitionIndexKeyValueIter) Close() error {
return i.iter.Close()
}
var errColumnNotFound = errors.NewKind("could not find column %s")
type indexKeyValueIter struct {
key string
iter sql.RowIter
columns []int
pos int
}
func (i *indexKeyValueIter) Next() ([]interface{}, []byte, error) {
row, err := i.iter.Next()
if err != nil {
return nil, nil, err
}
value := &indexValue{Key: i.key, Pos: i.pos}
data, err := encodeIndexValue(value)
if err != nil {
return nil, nil, err
}
i.pos++
return projectOnRow(i.columns, row), data, nil
}
func (i *indexKeyValueIter) Close() error {
return i.iter.Close()
}