-
Notifications
You must be signed in to change notification settings - Fork 5.9k
/
executor.go
641 lines (582 loc) · 14.2 KB
/
executor.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
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
// Copyright 2017 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// See the License for the specific language governing permissions and
// limitations under the License.
package mocktikv
import (
"bytes"
"encoding/binary"
"sort"
"github.com/juju/errors"
"github.com/pingcap/kvproto/pkg/kvrpcpb"
"github.com/pingcap/tidb/expression"
"github.com/pingcap/tidb/expression/aggregation"
"github.com/pingcap/tidb/kv"
"github.com/pingcap/tidb/model"
"github.com/pingcap/tidb/mysql"
"github.com/pingcap/tidb/sessionctx/variable"
"github.com/pingcap/tidb/tablecodec"
"github.com/pingcap/tidb/util/codec"
"github.com/pingcap/tidb/util/types"
"github.com/pingcap/tipb/go-tipb"
)
type executor interface {
SetSrcExec(executor)
Next() ([][]byte, error)
}
type tableScanExec struct {
*tipb.TableScan
colIDs map[int64]int
kvRanges []kv.KeyRange
startTS uint64
isolationLevel kvrpcpb.IsolationLevel
mvccStore MVCCStore
cursor int
seekKey []byte
src executor
}
func (e *tableScanExec) SetSrcExec(exec executor) {
e.src = exec
}
func (e *tableScanExec) Next() (value [][]byte, err error) {
for e.cursor < len(e.kvRanges) {
ran := e.kvRanges[e.cursor]
if ran.IsPoint() {
value, err = e.getRowFromPoint(ran)
if err != nil {
return nil, errors.Trace(err)
}
e.seekKey = nil
e.cursor++
return value, nil
}
value, err = e.getRowFromRange(ran)
if err != nil {
return nil, errors.Trace(err)
}
if value == nil {
e.seekKey = nil
e.cursor++
continue
}
return value, nil
}
return nil, nil
}
func (e *tableScanExec) getRowFromPoint(ran kv.KeyRange) ([][]byte, error) {
val, err := e.mvccStore.Get(ran.StartKey, e.startTS, e.isolationLevel)
if err != nil {
return nil, errors.Trace(err)
}
if len(val) == 0 {
return nil, nil
}
handle, err := tablecodec.DecodeRowKey(ran.StartKey)
if err != nil {
return nil, errors.Trace(err)
}
row, err := getRowData(e.Columns, e.colIDs, handle, val)
if err != nil {
return nil, errors.Trace(err)
}
return row, nil
}
func (e *tableScanExec) getRowFromRange(ran kv.KeyRange) ([][]byte, error) {
if e.seekKey == nil {
if e.Desc {
e.seekKey = ran.EndKey
} else {
e.seekKey = ran.StartKey
}
}
var pairs []Pair
var pair Pair
if e.Desc {
pairs = e.mvccStore.ReverseScan(ran.StartKey, e.seekKey, 1, e.startTS, e.isolationLevel)
} else {
pairs = e.mvccStore.Scan(e.seekKey, ran.EndKey, 1, e.startTS, e.isolationLevel)
}
if len(pairs) > 0 {
pair = pairs[0]
}
if pair.Err != nil {
// TODO: Handle lock error.
return nil, errors.Trace(pair.Err)
}
if pair.Key == nil {
return nil, nil
}
if e.Desc {
if bytes.Compare(pair.Key, ran.StartKey) < 0 {
return nil, nil
}
e.seekKey = []byte(tablecodec.TruncateToRowKeyLen(kv.Key(pair.Key)))
} else {
if bytes.Compare(pair.Key, ran.EndKey) >= 0 {
return nil, nil
}
e.seekKey = []byte(kv.Key(pair.Key).PrefixNext())
}
handle, err := tablecodec.DecodeRowKey(pair.Key)
if err != nil {
return nil, errors.Trace(err)
}
row, err := getRowData(e.Columns, e.colIDs, handle, pair.Value)
if err != nil {
return nil, errors.Trace(err)
}
return row, nil
}
const (
pkColNotExists = iota
pkColIsSigned
pkColIsUnsigned
)
type indexScanExec struct {
*tipb.IndexScan
colsLen int
kvRanges []kv.KeyRange
startTS uint64
isolationLevel kvrpcpb.IsolationLevel
mvccStore MVCCStore
cursor int
seekKey []byte
pkStatus int
src executor
}
func (e *indexScanExec) SetSrcExec(exec executor) {
e.src = exec
}
func (e *indexScanExec) Next() (value [][]byte, err error) {
for e.cursor < len(e.kvRanges) {
ran := e.kvRanges[e.cursor]
value, err = e.getRowFromRange(ran)
if err != nil {
return nil, errors.Trace(err)
}
if value == nil {
e.cursor++
e.seekKey = nil
continue
}
return value, nil
}
return nil, nil
}
func (e *indexScanExec) getRowFromRange(ran kv.KeyRange) ([][]byte, error) {
if e.seekKey == nil {
if e.Desc {
e.seekKey = ran.EndKey
} else {
e.seekKey = ran.StartKey
}
}
var pairs []Pair
var pair Pair
if e.Desc {
pairs = e.mvccStore.ReverseScan(ran.StartKey, e.seekKey, 1, e.startTS, e.isolationLevel)
} else {
pairs = e.mvccStore.Scan(e.seekKey, ran.EndKey, 1, e.startTS, e.isolationLevel)
}
if len(pairs) > 0 {
pair = pairs[0]
}
if pair.Err != nil {
// TODO: Handle lock error.
return nil, errors.Trace(pair.Err)
}
if pair.Key == nil {
return nil, nil
}
if e.Desc {
if bytes.Compare(pair.Key, ran.StartKey) < 0 {
return nil, nil
}
e.seekKey = pair.Key
} else {
if bytes.Compare(pair.Key, ran.EndKey) >= 0 {
return nil, nil
}
e.seekKey = []byte(kv.Key(pair.Key).PrefixNext())
}
values, b, err := tablecodec.CutIndexKeyNew(pair.Key, e.colsLen)
if err != nil {
return nil, errors.Trace(err)
}
if len(b) > 0 {
if e.pkStatus != pkColNotExists {
values = append(values, b)
}
} else {
handle, err := decodeHandle(pair.Value)
if err != nil {
return nil, errors.Trace(err)
}
if e.pkStatus != pkColNotExists {
var handleDatum types.Datum
if e.pkStatus == pkColIsUnsigned {
handleDatum = types.NewUintDatum(uint64(handle))
} else {
handleDatum = types.NewIntDatum(handle)
}
handleBytes, err := codec.EncodeValue(b, handleDatum)
if err != nil {
return nil, errors.Trace(err)
}
values = append(values, handleBytes)
}
}
return values, nil
}
type selectionExec struct {
conditions []expression.Expression
relatedColOffsets []int
row []types.Datum
evalCtx *evalContext
src executor
}
func (e *selectionExec) SetSrcExec(exec executor) {
e.src = exec
}
// evalBool evaluates expression to a boolean value.
func evalBool(exprs []expression.Expression, row []types.Datum, ctx *variable.StatementContext) (bool, error) {
for _, expr := range exprs {
data, err := expr.Eval(row)
if err != nil {
return false, errors.Trace(err)
}
if data.IsNull() {
return false, nil
}
isBool, err := data.ToBool(ctx)
if err != nil {
return false, errors.Trace(err)
}
if isBool == 0 {
return false, nil
}
}
return true, nil
}
func (e *selectionExec) Next() (value [][]byte, err error) {
for {
value, err = e.src.Next()
if err != nil {
return nil, errors.Trace(err)
}
if value == nil {
return nil, nil
}
err = e.evalCtx.decodeRelatedColumnVals(e.relatedColOffsets, value, e.row)
if err != nil {
return nil, errors.Trace(err)
}
match, err := evalBool(e.conditions, e.row, e.evalCtx.sc)
if err != nil {
return nil, errors.Trace(err)
}
if match {
return value, nil
}
}
}
type aggCtxsMapper map[string][]*aggregation.AggEvaluateContext
type aggregateExec struct {
evalCtx *evalContext
aggExprs []aggregation.Aggregation
aggCtxsMap aggCtxsMapper
groupByExprs []expression.Expression
relatedColOffsets []int
row []types.Datum
groups map[string]struct{}
groupKeys [][]byte
groupKeyRows [][][]byte
executed bool
currGroupIdx int
src executor
}
func (e *aggregateExec) SetSrcExec(exec executor) {
e.src = exec
}
func (e *aggregateExec) innerNext() (bool, error) {
values, err := e.src.Next()
if err != nil {
return false, errors.Trace(err)
}
if values == nil {
return false, nil
}
err = e.aggregate(values)
if err != nil {
return false, errors.Trace(err)
}
return true, nil
}
func (e *aggregateExec) Next() (value [][]byte, err error) {
if e.aggCtxsMap == nil {
e.aggCtxsMap = make(aggCtxsMapper, 0)
}
if !e.executed {
for {
hasMore, err := e.innerNext()
if err != nil {
return nil, errors.Trace(err)
}
if !hasMore {
break
}
}
e.executed = true
}
if e.currGroupIdx >= len(e.groups) {
return nil, nil
}
gk := e.groupKeys[e.currGroupIdx]
value = make([][]byte, 0, len(e.groupByExprs)+2*len(e.aggExprs))
aggCtxs := e.getContexts(gk)
for i, agg := range e.aggExprs {
partialResults := agg.GetPartialResult(aggCtxs[i])
for _, result := range partialResults {
data, err := codec.EncodeValue(nil, result)
if err != nil {
return nil, errors.Trace(err)
}
value = append(value, data)
}
}
value = append(value, e.groupKeyRows[e.currGroupIdx]...)
e.currGroupIdx++
return value, nil
}
func (e *aggregateExec) getGroupKey() ([]byte, [][]byte, error) {
length := len(e.groupByExprs)
if length == 0 {
return nil, nil, nil
}
bufLen := 0
vals := make([]types.Datum, 0, length)
row := make([][]byte, 0, length)
for _, item := range e.groupByExprs {
v, err := item.Eval(e.row)
if err != nil {
return nil, nil, errors.Trace(err)
}
vals = append(vals, v)
b, err := codec.EncodeValue(nil, v)
if err != nil {
return nil, nil, errors.Trace(err)
}
bufLen += len(b)
row = append(row, b)
}
buf := make([]byte, 0, bufLen)
for _, col := range row {
buf = append(buf, col...)
}
return buf, row, nil
}
// aggregate updates aggregate functions with row.
func (e *aggregateExec) aggregate(value [][]byte) error {
err := e.evalCtx.decodeRelatedColumnVals(e.relatedColOffsets, value, e.row)
if err != nil {
return errors.Trace(err)
}
// Get group key.
gk, gbyKeyRow, err := e.getGroupKey()
if err != nil {
return errors.Trace(err)
}
if _, ok := e.groups[string(gk)]; !ok {
e.groups[string(gk)] = struct{}{}
e.groupKeys = append(e.groupKeys, gk)
e.groupKeyRows = append(e.groupKeyRows, gbyKeyRow)
}
// Update aggregate expressions.
aggCtxs := e.getContexts(gk)
for i, agg := range e.aggExprs {
err = agg.Update(aggCtxs[i], e.evalCtx.sc, e.row)
if err != nil {
return errors.Trace(err)
}
}
return nil
}
func (e *aggregateExec) getContexts(groupKey []byte) []*aggregation.AggEvaluateContext {
groupKeyString := string(groupKey)
aggCtxs, ok := e.aggCtxsMap[groupKeyString]
if !ok {
aggCtxs = make([]*aggregation.AggEvaluateContext, 0, len(e.aggExprs))
for _, agg := range e.aggExprs {
aggCtxs = append(aggCtxs, agg.CreateContext())
}
e.aggCtxsMap[groupKeyString] = aggCtxs
}
return aggCtxs
}
type topNExec struct {
heap *topNHeap
evalCtx *evalContext
relatedColOffsets []int
orderByExprs []expression.Expression
row []types.Datum
cursor int
executed bool
src executor
}
func (e *topNExec) SetSrcExec(src executor) {
e.src = src
}
func (e *topNExec) innerNext() (bool, error) {
value, err := e.src.Next()
if err != nil {
return false, errors.Trace(err)
}
if value == nil {
return false, nil
}
err = e.evalTopN(value)
if err != nil {
return false, errors.Trace(err)
}
return true, nil
}
func (e *topNExec) Next() (value [][]byte, err error) {
if !e.executed {
for {
hasMore, err := e.innerNext()
if err != nil {
return nil, errors.Trace(err)
}
if !hasMore {
break
}
}
e.executed = true
}
if e.cursor >= len(e.heap.rows) {
return nil, nil
}
sort.Sort(&e.heap.topNSorter)
row := e.heap.rows[e.cursor]
e.cursor++
return row.data, nil
}
// evalTopN evaluates the top n elements from the data. The input receives a record including its handle and data.
// And this function will check if this record can replace one of the old records.
func (e *topNExec) evalTopN(value [][]byte) error {
newRow := &sortRow{
key: make([]types.Datum, len(value)),
}
err := e.evalCtx.decodeRelatedColumnVals(e.relatedColOffsets, value, e.row)
if err != nil {
return errors.Trace(err)
}
for i, expr := range e.orderByExprs {
newRow.key[i], err = expr.Eval(e.row)
if err != nil {
return errors.Trace(err)
}
}
if e.heap.tryToAddRow(newRow) {
for _, val := range value {
newRow.data = append(newRow.data, val)
}
}
return errors.Trace(e.heap.err)
}
type limitExec struct {
limit uint64
cursor uint64
src executor
}
func (e *limitExec) SetSrcExec(src executor) {
e.src = src
}
func (e *limitExec) Next() (value [][]byte, err error) {
if e.cursor >= e.limit {
return nil, nil
}
value, err = e.src.Next()
if err != nil {
return nil, errors.Trace(err)
}
if value == nil {
return nil, nil
}
e.cursor++
return value, nil
}
func hasColVal(data [][]byte, colIDs map[int64]int, id int64) bool {
offset, ok := colIDs[id]
if ok && data[offset] != nil {
return true
}
return false
}
// getRowData decodes raw byte slice to row data.
func getRowData(columns []*tipb.ColumnInfo, colIDs map[int64]int, handle int64, value []byte) ([][]byte, error) {
values, err := tablecodec.CutRowNew(value, colIDs)
if err != nil {
return nil, errors.Trace(err)
}
if values == nil {
values = make([][]byte, len(colIDs))
}
// Fill the handle and null columns.
for _, col := range columns {
id := col.GetColumnId()
offset := colIDs[id]
if col.GetPkHandle() || id == model.ExtraHandleID {
var handleDatum types.Datum
if mysql.HasUnsignedFlag(uint(col.GetFlag())) {
// PK column is Unsigned.
handleDatum = types.NewUintDatum(uint64(handle))
} else {
handleDatum = types.NewIntDatum(handle)
}
handleData, err1 := codec.EncodeValue(nil, handleDatum)
if err1 != nil {
return nil, errors.Trace(err1)
}
values[offset] = handleData
continue
}
if hasColVal(values, colIDs, id) {
continue
}
if len(col.DefaultVal) > 0 {
values[offset] = col.DefaultVal
continue
}
if mysql.HasNotNullFlag(uint(col.GetFlag())) {
return nil, errors.Errorf("Miss column %d", id)
}
values[offset] = []byte{codec.NilFlag}
}
return values, nil
}
func convertToExprs(sc *variable.StatementContext, fieldTps []*types.FieldType, pbExprs []*tipb.Expr) ([]expression.Expression, error) {
exprs := make([]expression.Expression, 0, len(pbExprs))
for _, expr := range pbExprs {
e, err := expression.PBToExpr(expr, fieldTps, sc)
if err != nil {
return nil, errors.Trace(err)
}
exprs = append(exprs, e)
}
return exprs, nil
}
func decodeHandle(data []byte) (int64, error) {
var h int64
buf := bytes.NewBuffer(data)
err := binary.Read(buf, binary.BigEndian, &h)
return h, errors.Trace(err)
}