forked from pingcap/tidb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexecutor_pkg_test.go
431 lines (400 loc) · 13.7 KB
/
executor_pkg_test.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
// Copyright 2016 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,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package executor
import (
"context"
"runtime"
"strconv"
"testing"
"time"
"unsafe"
"github.com/pingcap/failpoint"
"github.com/pingcap/tidb/executor/aggfuncs"
"github.com/pingcap/tidb/expression"
"github.com/pingcap/tidb/kv"
"github.com/pingcap/tidb/parser/ast"
plannerutil "github.com/pingcap/tidb/planner/util"
"github.com/pingcap/tidb/sessionctx/variable"
"github.com/pingcap/tidb/tablecodec"
"github.com/pingcap/tidb/types"
"github.com/pingcap/tidb/util/collate"
"github.com/pingcap/tidb/util/memory"
"github.com/pingcap/tidb/util/mock"
"github.com/pingcap/tidb/util/ranger"
"github.com/pingcap/tidb/util/tableutil"
"github.com/stretchr/testify/require"
)
// Note: it's a tricky way to export the `inspectionSummaryRules` and `inspectionRules` for unit test but invisible for normal code
var (
InspectionSummaryRules = inspectionSummaryRules
InspectionRules = inspectionRules
)
func TestBuildKvRangesForIndexJoinWithoutCwc(t *testing.T) {
indexRanges := make([]*ranger.Range, 0, 6)
indexRanges = append(indexRanges, generateIndexRange(1, 1, 1, 1, 1))
indexRanges = append(indexRanges, generateIndexRange(1, 1, 2, 1, 1))
indexRanges = append(indexRanges, generateIndexRange(1, 1, 2, 1, 2))
indexRanges = append(indexRanges, generateIndexRange(1, 1, 3, 1, 1))
indexRanges = append(indexRanges, generateIndexRange(2, 1, 1, 1, 1))
indexRanges = append(indexRanges, generateIndexRange(2, 1, 2, 1, 1))
joinKeyRows := make([]*indexJoinLookUpContent, 0, 5)
joinKeyRows = append(joinKeyRows, &indexJoinLookUpContent{keys: generateDatumSlice(1, 1)})
joinKeyRows = append(joinKeyRows, &indexJoinLookUpContent{keys: generateDatumSlice(1, 2)})
joinKeyRows = append(joinKeyRows, &indexJoinLookUpContent{keys: generateDatumSlice(2, 1)})
joinKeyRows = append(joinKeyRows, &indexJoinLookUpContent{keys: generateDatumSlice(2, 2)})
joinKeyRows = append(joinKeyRows, &indexJoinLookUpContent{keys: generateDatumSlice(2, 3)})
keyOff2IdxOff := []int{1, 3}
ctx := mock.NewContext()
kvRanges, err := buildKvRangesForIndexJoin(ctx, 0, 0, joinKeyRows, indexRanges, keyOff2IdxOff, nil, nil, nil)
require.NoError(t, err)
// Check the kvRanges is in order.
for i, kvRange := range kvRanges {
require.True(t, kvRange.StartKey.Cmp(kvRange.EndKey) < 0)
if i > 0 {
require.True(t, kvRange.StartKey.Cmp(kvRanges[i-1].EndKey) >= 0)
}
}
}
func generateIndexRange(vals ...int64) *ranger.Range {
lowDatums := generateDatumSlice(vals...)
highDatums := make([]types.Datum, len(vals))
copy(highDatums, lowDatums)
return &ranger.Range{LowVal: lowDatums, HighVal: highDatums, Collators: collate.GetBinaryCollatorSlice(len(lowDatums))}
}
func generateDatumSlice(vals ...int64) []types.Datum {
datums := make([]types.Datum, len(vals))
for i, val := range vals {
datums[i].SetInt64(val)
}
return datums
}
func TestGetFieldsFromLine(t *testing.T) {
tests := []struct {
input string
expected []string
}{
{
`"1","a string","100.20"`,
[]string{"1", "a string", "100.20"},
},
{
`"2","a string containing a , comma","102.20"`,
[]string{"2", "a string containing a , comma", "102.20"},
},
{
`"3","a string containing a \" quote","102.20"`,
[]string{"3", "a string containing a \" quote", "102.20"},
},
{
`"4","a string containing a \", quote and comma","102.20"`,
[]string{"4", "a string containing a \", quote and comma", "102.20"},
},
// Test some escape char.
{
`"\0\b\n\r\t\Z\\\ \c\'\""`,
[]string{string([]byte{0, '\b', '\n', '\r', '\t', 26, '\\', ' ', ' ', 'c', '\'', '"'})},
},
// Test mixed.
{
`"123",456,"\t7890",abcd`,
[]string{"123", "456", "\t7890", "abcd"},
},
}
ldInfo := LoadDataInfo{
FieldsInfo: &ast.FieldsClause{
Enclosed: '"',
Terminated: ",",
Escaped: '\\',
},
}
for _, test := range tests {
got, err := ldInfo.getFieldsFromLine([]byte(test.input))
require.NoErrorf(t, err, "failed: %s", test.input)
assertEqualStrings(t, got, test.expected)
}
_, err := ldInfo.getFieldsFromLine([]byte(`1,a string,100.20`))
require.NoError(t, err)
}
func assertEqualStrings(t *testing.T, got []field, expect []string) {
require.Equal(t, len(expect), len(got))
for i := 0; i < len(got); i++ {
require.Equal(t, expect[i], string(got[i].str))
}
}
func TestSlowQueryRuntimeStats(t *testing.T) {
stats := &slowQueryRuntimeStats{
totalFileNum: 2,
readFileNum: 2,
readFile: time.Second,
initialize: time.Millisecond,
readFileSize: 1024 * 1024 * 1024,
parseLog: int64(time.Millisecond * 100),
concurrent: 15,
}
require.Equal(t, "initialize: 1ms, read_file: 1s, parse_log: {time:100ms, concurrency:15}, total_file: 2, read_file: 2, read_size: 1024 MB", stats.String())
require.Equal(t, stats.Clone().String(), stats.String())
stats.Merge(stats.Clone())
require.Equal(t, "initialize: 2ms, read_file: 2s, parse_log: {time:200ms, concurrency:15}, total_file: 4, read_file: 4, read_size: 2 GB", stats.String())
}
// Test whether the actual buckets in Golang Map is same with the estimated number.
// The test relies the implement of Golang Map. ref https://github.com/golang/go/blob/go1.13/src/runtime/map.go#L114
func TestAggPartialResultMapperB(t *testing.T) {
if runtime.Version() < `go1.13` {
t.Skip("Unsupported version")
}
type testCase struct {
rowNum int
expectedB int
expectedGrowing bool
}
cases := []testCase{
{
rowNum: 0,
expectedB: 0,
expectedGrowing: false,
},
{
rowNum: 100,
expectedB: 4,
expectedGrowing: false,
},
{
rowNum: 10000,
expectedB: 11,
expectedGrowing: false,
},
{
rowNum: 1000000,
expectedB: 18,
expectedGrowing: false,
},
{
rowNum: 851968, // 6.5 * (1 << 17)
expectedB: 17,
expectedGrowing: false,
},
{
rowNum: 851969, // 6.5 * (1 << 17) + 1
expectedB: 18,
expectedGrowing: true,
},
{
rowNum: 425984, // 6.5 * (1 << 16)
expectedB: 16,
expectedGrowing: false,
},
{
rowNum: 425985, // 6.5 * (1 << 16) + 1
expectedB: 17,
expectedGrowing: true,
},
}
for _, tc := range cases {
aggMap := make(aggPartialResultMapper)
tempSlice := make([]aggfuncs.PartialResult, 10)
for num := 0; num < tc.rowNum; num++ {
aggMap[strconv.Itoa(num)] = tempSlice
}
require.Equal(t, tc.expectedB, getB(aggMap))
require.Equal(t, tc.expectedGrowing, getGrowing(aggMap))
}
}
// A header for a Go map.
// nolint:structcheck
type hmap struct {
// Note: the format of the hmap is also encoded in cmd/compile/internal/gc/reflect.go.
// Make sure this stays in sync with the compiler's definition.
count int // nolint:unused // # live cells == size of map. Must be first (used by len() builtin)
flags uint8 // nolint:unused
B uint8 // nolint:unused // log_2 of # of buckets (can hold up to loadFactor * 2^B items)
noverflow uint16 // nolint:unused // approximate number of overflow buckets; see incrnoverflow for details
hash0 uint32 // nolint:unused // hash seed
buckets unsafe.Pointer // nolint:unused // array of 2^B Buckets. may be nil if count==0.
oldbuckets unsafe.Pointer // nolint:unused // previous bucket array of half the size, non-nil only when growing
nevacuate uintptr // nolint:unused // progress counter for evacuation (buckets less than this have been evacuated)
}
func getB(m aggPartialResultMapper) int {
point := (**hmap)(unsafe.Pointer(&m))
value := *point
return int(value.B)
}
func getGrowing(m aggPartialResultMapper) bool {
point := (**hmap)(unsafe.Pointer(&m))
value := *point
return value.oldbuckets != nil
}
func TestFilterTemporaryTableKeys(t *testing.T) {
vars := variable.NewSessionVars()
const tableID int64 = 3
vars.TxnCtx = &variable.TransactionContext{
TxnCtxNoNeedToRestore: variable.TxnCtxNoNeedToRestore{
TemporaryTables: map[int64]tableutil.TempTable{tableID: nil},
},
}
res := filterTemporaryTableKeys(vars, []kv.Key{tablecodec.EncodeTablePrefix(tableID), tablecodec.EncodeTablePrefix(42)})
require.Len(t, res, 1)
}
func TestLoadDataWithDifferentEscapeChar(t *testing.T) {
tests := []struct {
input string
escapeChar byte
expected []string
}{
{
`"{""itemRangeType"":0,""itemContainType"":0,""shopRangeType"":1,""shopJson"":""[{\""id\"":\""A1234\"",\""shopName\"":\""AAAAAA\""}]""}"`,
byte(0), // escaped by ''
[]string{`{"itemRangeType":0,"itemContainType":0,"shopRangeType":1,"shopJson":"[{\"id\":\"A1234\",\"shopName\":\"AAAAAA\"}]"}`},
},
}
for _, test := range tests {
ldInfo := LoadDataInfo{
FieldsInfo: &ast.FieldsClause{
Enclosed: '"',
Terminated: ",",
Escaped: test.escapeChar,
},
}
got, err := ldInfo.getFieldsFromLine([]byte(test.input))
require.NoErrorf(t, err, "failed: %s", test.input)
assertEqualStrings(t, got, test.expected)
}
}
func TestSortSpillDisk(t *testing.T) {
require.NoError(t, failpoint.Enable("github.com/pingcap/tidb/executor/testSortedRowContainerSpill", "return(true)"))
defer func() {
require.NoError(t, failpoint.Disable("github.com/pingcap/tidb/executor/testSortedRowContainerSpill"))
}()
ctx := mock.NewContext()
ctx.GetSessionVars().MemQuota.MemQuotaQuery = 1
ctx.GetSessionVars().InitChunkSize = variable.DefMaxChunkSize
ctx.GetSessionVars().MaxChunkSize = variable.DefMaxChunkSize
ctx.GetSessionVars().StmtCtx.MemTracker = memory.NewTracker(-1, -1)
cas := &sortCase{rows: 2048, orderByIdx: []int{0, 1}, ndvs: []int{0, 0}, ctx: ctx}
opt := mockDataSourceParameters{
schema: expression.NewSchema(cas.columns()...),
rows: cas.rows,
ctx: cas.ctx,
ndvs: cas.ndvs,
}
dataSource := buildMockDataSource(opt)
exec := &SortExec{
baseExecutor: newBaseExecutor(cas.ctx, dataSource.schema, 0, dataSource),
ByItems: make([]*plannerutil.ByItems, 0, len(cas.orderByIdx)),
schema: dataSource.schema,
}
for _, idx := range cas.orderByIdx {
exec.ByItems = append(exec.ByItems, &plannerutil.ByItems{Expr: cas.columns()[idx]})
}
tmpCtx := context.Background()
chk := newFirstChunk(exec)
dataSource.prepareChunks()
err := exec.Open(tmpCtx)
require.NoError(t, err)
for {
err = exec.Next(tmpCtx, chk)
require.NoError(t, err)
if chk.NumRows() == 0 {
break
}
}
// Test only 1 partition and all data in memory.
require.Len(t, exec.partitionList, 1)
require.Equal(t, false, exec.partitionList[0].AlreadySpilledSafeForTest())
require.Equal(t, 2048, exec.partitionList[0].NumRow())
err = exec.Close()
require.NoError(t, err)
ctx.GetSessionVars().StmtCtx.MemTracker = memory.NewTracker(-1, 1)
dataSource.prepareChunks()
err = exec.Open(tmpCtx)
require.NoError(t, err)
for {
err = exec.Next(tmpCtx, chk)
require.NoError(t, err)
if chk.NumRows() == 0 {
break
}
}
// Test 2 partitions and all data in disk.
// Now spilling is in parallel.
// Maybe the second add() will called before spilling, depends on
// Golang goroutine scheduling. So the result has two possibilities.
if len(exec.partitionList) == 2 {
require.Len(t, exec.partitionList, 2)
require.Equal(t, true, exec.partitionList[0].AlreadySpilledSafeForTest())
require.Equal(t, true, exec.partitionList[1].AlreadySpilledSafeForTest())
require.Equal(t, 1024, exec.partitionList[0].NumRow())
require.Equal(t, 1024, exec.partitionList[1].NumRow())
} else {
require.Len(t, exec.partitionList, 1)
require.Equal(t, true, exec.partitionList[0].AlreadySpilledSafeForTest())
require.Equal(t, 2048, exec.partitionList[0].NumRow())
}
err = exec.Close()
require.NoError(t, err)
ctx.GetSessionVars().StmtCtx.MemTracker = memory.NewTracker(-1, 28000)
dataSource.prepareChunks()
err = exec.Open(tmpCtx)
require.NoError(t, err)
for {
err = exec.Next(tmpCtx, chk)
require.NoError(t, err)
if chk.NumRows() == 0 {
break
}
}
// Test only 1 partition but spill disk.
require.Len(t, exec.partitionList, 1)
require.Equal(t, true, exec.partitionList[0].AlreadySpilledSafeForTest())
require.Equal(t, 2048, exec.partitionList[0].NumRow())
err = exec.Close()
require.NoError(t, err)
// Test partition nums.
ctx = mock.NewContext()
ctx.GetSessionVars().InitChunkSize = variable.DefMaxChunkSize
ctx.GetSessionVars().MaxChunkSize = variable.DefMaxChunkSize
ctx.GetSessionVars().StmtCtx.MemTracker = memory.NewTracker(-1, 16864*50)
ctx.GetSessionVars().StmtCtx.MemTracker.Consume(16864 * 45)
cas = &sortCase{rows: 20480, orderByIdx: []int{0, 1}, ndvs: []int{0, 0}, ctx: ctx}
opt = mockDataSourceParameters{
schema: expression.NewSchema(cas.columns()...),
rows: cas.rows,
ctx: cas.ctx,
ndvs: cas.ndvs,
}
dataSource = buildMockDataSource(opt)
exec = &SortExec{
baseExecutor: newBaseExecutor(cas.ctx, dataSource.schema, 0, dataSource),
ByItems: make([]*plannerutil.ByItems, 0, len(cas.orderByIdx)),
schema: dataSource.schema,
}
for _, idx := range cas.orderByIdx {
exec.ByItems = append(exec.ByItems, &plannerutil.ByItems{Expr: cas.columns()[idx]})
}
tmpCtx = context.Background()
chk = newFirstChunk(exec)
dataSource.prepareChunks()
err = exec.Open(tmpCtx)
require.NoError(t, err)
for {
err = exec.Next(tmpCtx, chk)
require.NoError(t, err)
if chk.NumRows() == 0 {
break
}
}
// Don't spill too many partitions.
require.True(t, len(exec.partitionList) <= 4)
err = exec.Close()
require.NoError(t, err)
}