-
-
Notifications
You must be signed in to change notification settings - Fork 548
/
common_plans.go
617 lines (522 loc) · 16.9 KB
/
common_plans.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
// Copyright 2015 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 core
import (
"bytes"
"fmt"
"strconv"
"strings"
"github.com/hanchuanchuan/goInception/ast"
"github.com/hanchuanchuan/goInception/expression"
"github.com/hanchuanchuan/goInception/infoschema"
"github.com/hanchuanchuan/goInception/model"
"github.com/hanchuanchuan/goInception/mysql"
"github.com/hanchuanchuan/goInception/sessionctx"
"github.com/hanchuanchuan/goInception/table"
"github.com/hanchuanchuan/goInception/util/auth"
"github.com/hanchuanchuan/goInception/util/chunk"
"github.com/hanchuanchuan/goInception/util/kvcache"
"github.com/hanchuanchuan/goInception/util/ranger"
"github.com/pingcap/errors"
)
// ShowDDL is for showing DDL information.
type ShowDDL struct {
baseSchemaProducer
}
// ShowDDLJobs is for showing DDL job list.
type ShowDDLJobs struct {
baseSchemaProducer
JobNumber int64
}
// ShowSlow is for showing slow queries.
type ShowSlow struct {
baseSchemaProducer
*ast.ShowSlow
}
// ShowDDLJobQueries is for showing DDL job queries sql.
type ShowDDLJobQueries struct {
baseSchemaProducer
JobIDs []int64
}
// CheckTable is used for checking table data, built from the 'admin check table' statement.
type CheckTable struct {
baseSchemaProducer
Tables []*ast.TableName
GenExprs map[string]expression.Expression
}
// RecoverIndex is used for backfilling corrupted index data.
type RecoverIndex struct {
baseSchemaProducer
Table *ast.TableName
IndexName string
}
// CleanupIndex is used to delete dangling index data.
type CleanupIndex struct {
baseSchemaProducer
Table *ast.TableName
IndexName string
}
// CheckIndex is used for checking index data, built from the 'admin check index' statement.
type CheckIndex struct {
baseSchemaProducer
IndexLookUpReader *PhysicalIndexLookUpReader
DBName string
IdxName string
}
// CheckIndexRange is used for checking index data, output the index values that handle within begin and end.
type CheckIndexRange struct {
baseSchemaProducer
Table *ast.TableName
IndexName string
HandleRanges []ast.HandleRange
}
// ChecksumTable is used for calculating table checksum, built from the `admin checksum table` statement.
type ChecksumTable struct {
baseSchemaProducer
Tables []*ast.TableName
}
// CancelDDLJobs represents a cancel DDL jobs plan.
type CancelDDLJobs struct {
baseSchemaProducer
JobIDs []int64
}
// Prepare represents prepare plan.
type Prepare struct {
baseSchemaProducer
Name string
SQLText string
}
// Execute represents prepare plan.
type Execute struct {
baseSchemaProducer
Name string
UsingVars []expression.Expression
ExecID uint32
Stmt ast.StmtNode
Plan Plan
}
// OptimizePreparedPlan optimizes the prepared statement.
func (e *Execute) OptimizePreparedPlan(ctx sessionctx.Context, is infoschema.InfoSchema) error {
vars := ctx.GetSessionVars()
if e.Name != "" {
e.ExecID = vars.PreparedStmtNameToID[e.Name]
}
prepared, ok := vars.PreparedStmts[e.ExecID]
if !ok {
return errors.Trace(ErrStmtNotFound)
}
if len(prepared.Params) != len(e.UsingVars) {
return errors.Trace(ErrWrongParamCount)
}
for i, usingVar := range e.UsingVars {
val, err := usingVar.Eval(chunk.Row{})
if err != nil {
return errors.Trace(err)
}
prepared.Params[i].SetDatum(val)
vars.PreparedParams = append(vars.PreparedParams, val)
}
if prepared.SchemaVersion != is.SchemaMetaVersion() {
// If the schema version has changed we need to preprocess it again,
// if this time it failed, the real reason for the error is schema changed.
err := Preprocess(ctx, prepared.Stmt, is, true)
if err != nil {
return ErrSchemaChanged.GenWithStack("Schema change caused error: %s", err.Error())
}
prepared.SchemaVersion = is.SchemaMetaVersion()
}
p, err := e.getPhysicalPlan(ctx, is, prepared)
if err != nil {
return errors.Trace(err)
}
e.Stmt = prepared.Stmt
e.Plan = p
return nil
}
func (e *Execute) getPhysicalPlan(ctx sessionctx.Context, is infoschema.InfoSchema, prepared *ast.Prepared) (Plan, error) {
var cacheKey kvcache.Key
sessionVars := ctx.GetSessionVars()
sessionVars.StmtCtx.UseCache = prepared.UseCache
if prepared.UseCache {
cacheKey = NewPSTMTPlanCacheKey(sessionVars, e.ExecID, prepared.SchemaVersion)
if cacheValue, exists := ctx.PreparedPlanCache().Get(cacheKey); exists {
plan := cacheValue.(*PSTMTPlanCacheValue).Plan
err := e.rebuildRange(plan)
if err != nil {
return nil, errors.Trace(err)
}
return plan, nil
}
}
p, err := OptimizeAstNode(ctx, prepared.Stmt, is)
if err != nil {
return nil, errors.Trace(err)
}
if prepared.UseCache {
ctx.PreparedPlanCache().Put(cacheKey, NewPSTMTPlanCacheValue(p))
}
return p, err
}
func (e *Execute) rebuildRange(p Plan) error {
sctx := p.context()
sc := p.context().GetSessionVars().StmtCtx
switch x := p.(type) {
case *PhysicalTableReader:
ts := x.TablePlans[0].(*PhysicalTableScan)
var pkCol *expression.Column
if ts.Table.PKIsHandle {
if pkColInfo := ts.Table.GetPkColInfo(); pkColInfo != nil {
pkCol = expression.ColInfo2Col(ts.schema.Columns, pkColInfo)
}
}
if pkCol != nil {
var err error
ts.Ranges, err = ranger.BuildTableRange(ts.AccessCondition, sc, pkCol.RetType)
if err != nil {
return errors.Trace(err)
}
} else {
ts.Ranges = ranger.FullIntRange(false)
}
case *PhysicalIndexReader:
is := x.IndexPlans[0].(*PhysicalIndexScan)
var err error
is.Ranges, err = e.buildRangeForIndexScan(sctx, is)
if err != nil {
return errors.Trace(err)
}
case *PhysicalIndexLookUpReader:
is := x.IndexPlans[0].(*PhysicalIndexScan)
var err error
is.Ranges, err = e.buildRangeForIndexScan(sctx, is)
if err != nil {
return errors.Trace(err)
}
case PhysicalPlan:
var err error
for _, child := range x.Children() {
err = e.rebuildRange(child)
if err != nil {
return errors.Trace(err)
}
}
}
return nil
}
func (e *Execute) buildRangeForIndexScan(sctx sessionctx.Context, is *PhysicalIndexScan) ([]*ranger.Range, error) {
idxCols, colLengths := expression.IndexInfo2Cols(is.schema.Columns, is.Index)
ranges := ranger.FullRange()
if len(idxCols) > 0 {
var err error
ranges, _, _, _, err = ranger.DetachCondAndBuildRangeForIndex(sctx, is.AccessCondition, idxCols, colLengths)
if err != nil {
return nil, errors.Trace(err)
}
}
return ranges, nil
}
// Deallocate represents deallocate plan.
type Deallocate struct {
baseSchemaProducer
Name string
}
// Show represents a show plan.
type Show struct {
baseSchemaProducer
Tp ast.ShowStmtType // Databases/Tables/Columns/....
DBName string
Table *ast.TableName // Used for showing columns.
Column *ast.ColumnName // Used for `desc table column`.
Flag int // Some flag parsed from sql, such as FULL.
Full bool
User *auth.UserIdentity // Used for show grants.
Conditions []expression.Expression
// Used by show variables
GlobalScope bool
}
// Set represents a plan for set stmt.
type Set struct {
baseSchemaProducer
VarAssigns []*expression.VarAssignment
}
// Simple represents a simple statement plan which doesn't need any optimization.
type Simple struct {
baseSchemaProducer
Statement ast.StmtNode
}
// InsertGeneratedColumns is for completing generated columns in Insert.
// We resolve generation expressions in plan, and eval those in executor.
type InsertGeneratedColumns struct {
Columns []*ast.ColumnName
Exprs []expression.Expression
OnDuplicates []*expression.Assignment
}
// Insert represents an insert plan.
type Insert struct {
baseSchemaProducer
Table table.Table
tableSchema *expression.Schema
Columns []*ast.ColumnName
Lists [][]expression.Expression
SetList []*expression.Assignment
OnDuplicate []*expression.Assignment
Schema4OnDuplicate *expression.Schema
IsReplace bool
// NeedFillDefaultValue is true when expr in value list reference other column.
NeedFillDefaultValue bool
GenCols InsertGeneratedColumns
SelectPlan PhysicalPlan
}
// Update represents Update plan.
type Update struct {
baseSchemaProducer
OrderedList []*expression.Assignment
SelectPlan PhysicalPlan
}
// Delete represents a delete plan.
type Delete struct {
baseSchemaProducer
Tables []*ast.TableName
IsMultiTable bool
SelectPlan PhysicalPlan
}
// AnalyzeColumnsTask is used for analyze columns.
type AnalyzeColumnsTask struct {
PhysicalTableID int64
PKInfo *model.ColumnInfo
ColsInfo []*model.ColumnInfo
}
// AnalyzeIndexTask is used for analyze index.
type AnalyzeIndexTask struct {
// PhysicalTableID is the id for a partition or a table.
PhysicalTableID int64
IndexInfo *model.IndexInfo
}
// Analyze represents an analyze plan
type Analyze struct {
baseSchemaProducer
ColTasks []AnalyzeColumnsTask
IdxTasks []AnalyzeIndexTask
MaxNumBuckets uint64
}
// LoadData represents a loaddata plan.
type LoadData struct {
baseSchemaProducer
IsLocal bool
Path string
Table *ast.TableName
Columns []*ast.ColumnName
FieldsInfo *ast.FieldsClause
LinesInfo *ast.LinesClause
IgnoreLines uint64
GenCols InsertGeneratedColumns
}
// LoadStats represents a load stats plan.
type LoadStats struct {
baseSchemaProducer
Path string
}
// DDL represents a DDL statement plan.
type DDL struct {
baseSchemaProducer
Statement ast.DDLNode
}
// Explain represents a explain plan.
type Explain struct {
baseSchemaProducer
StmtPlan Plan
Rows [][]string
explainedPlans map[int]bool
Format string
Analyze bool
ExecStmt ast.StmtNode
ExecPlan Plan
}
// prepareSchema prepares explain's result schema.
func (e *Explain) prepareSchema() error {
switch strings.ToLower(e.Format) {
case ast.ExplainFormatROW:
retFields := []string{"id", "count", "task", "operator info"}
if e.Analyze {
retFields = append(retFields, "execution info")
}
schema := expression.NewSchema(make([]*expression.Column, 0, len(retFields))...)
for _, fieldName := range retFields {
schema.Append(buildColumn("", fieldName, mysql.TypeString, mysql.MaxBlobWidth))
}
e.SetSchema(schema)
case ast.ExplainFormatDOT:
retFields := []string{"dot contents"}
schema := expression.NewSchema(make([]*expression.Column, 0, len(retFields))...)
for _, fieldName := range retFields {
schema.Append(buildColumn("", fieldName, mysql.TypeString, mysql.MaxBlobWidth))
}
e.SetSchema(schema)
default:
return errors.Errorf("explain format '%s' is not supported now", e.Format)
}
return nil
}
// RenderResult renders the explain result as specified format.
func (e *Explain) RenderResult() error {
switch strings.ToLower(e.Format) {
case ast.ExplainFormatROW:
e.explainedPlans = map[int]bool{}
e.explainPlanInRowFormat(e.StmtPlan.(PhysicalPlan), "root", "", true)
case ast.ExplainFormatDOT:
e.prepareDotInfo(e.StmtPlan.(PhysicalPlan))
default:
return errors.Errorf("explain format '%s' is not supported now", e.Format)
}
return nil
}
// explainPlanInRowFormat generates explain information for root-tasks.
func (e *Explain) explainPlanInRowFormat(p PhysicalPlan, taskType, indent string, isLastChild bool) {
e.prepareOperatorInfo(p, taskType, indent, isLastChild)
e.explainedPlans[p.ID()] = true
// For every child we create a new sub-tree rooted by it.
childIndent := e.getIndent4Child(indent, isLastChild)
for i, child := range p.Children() {
if e.explainedPlans[child.ID()] {
continue
}
e.explainPlanInRowFormat(child.(PhysicalPlan), taskType, childIndent, i == len(p.Children())-1)
}
switch copPlan := p.(type) {
case *PhysicalTableReader:
e.explainPlanInRowFormat(copPlan.tablePlan, "cop", childIndent, true)
case *PhysicalIndexReader:
e.explainPlanInRowFormat(copPlan.indexPlan, "cop", childIndent, true)
case *PhysicalIndexLookUpReader:
e.explainPlanInRowFormat(copPlan.indexPlan, "cop", childIndent, false)
e.explainPlanInRowFormat(copPlan.tablePlan, "cop", childIndent, true)
}
}
// prepareOperatorInfo generates the following information for every plan:
// operator id, task type, operator info, and the estemated row count.
func (e *Explain) prepareOperatorInfo(p PhysicalPlan, taskType string, indent string, isLastChild bool) {
operatorInfo := p.ExplainInfo()
count := string(strconv.AppendFloat([]byte{}, p.statsInfo().RowCount, 'f', 2, 64))
row := []string{e.prettyIdentifier(p.ExplainID(), indent, isLastChild), count, taskType, operatorInfo}
if e.Analyze {
runtimeStatsColl := e.ctx.GetSessionVars().StmtCtx.RuntimeStatsColl
if taskType == "cop" {
row = append(row, "") //TODO: wait collect resp from tikv
} else {
row = append(row, runtimeStatsColl.Get(p.ExplainID()).String())
}
}
e.Rows = append(e.Rows, row)
}
const (
// treeBody indicates the current operator sub-tree is not finished, still
// has child operators to be attached on.
treeBody = '│'
// treeMiddleNode indicates this operator is not the last child of the
// current sub-tree rooted by its parent.
treeMiddleNode = '├'
// treeLastNode indicates this operator is the last child of the current
// sub-tree rooted by its parent.
treeLastNode = '└'
// treeGap is used to represent the gap between the branches of the tree.
treeGap = ' '
// treeNodeIdentifier is used to replace the treeGap once we need to attach
// a node to a sub-tree.
treeNodeIdentifier = '─'
)
func (e *Explain) prettyIdentifier(id, indent string, isLastChild bool) string {
if len(indent) == 0 {
return id
}
indentBytes := []rune(indent)
for i := len(indentBytes) - 1; i >= 0; i-- {
if indentBytes[i] != treeBody {
continue
}
// Here we attach a new node to the current sub-tree by changing
// the closest treeBody to a:
// 1. treeLastNode, if this operator is the last child.
// 2. treeMiddleNode, if this operator is not the last child..
if isLastChild {
indentBytes[i] = treeLastNode
} else {
indentBytes[i] = treeMiddleNode
}
break
}
// Replace the treeGap between the treeBody and the node to a
// treeNodeIdentifier.
indentBytes[len(indentBytes)-1] = treeNodeIdentifier
return string(indentBytes) + id
}
func (e *Explain) getIndent4Child(indent string, isLastChild bool) string {
if !isLastChild {
return string(append([]rune(indent), treeBody, treeGap))
}
// If the current node is the last node of the current operator tree, we
// need to end this sub-tree by changing the closest treeBody to a treeGap.
indentBytes := []rune(indent)
for i := len(indentBytes) - 1; i >= 0; i-- {
if indentBytes[i] == treeBody {
indentBytes[i] = treeGap
break
}
}
return string(append(indentBytes, treeBody, treeGap))
}
func (e *Explain) prepareDotInfo(p PhysicalPlan) {
buffer := bytes.NewBufferString("")
buffer.WriteString(fmt.Sprintf("\ndigraph %s {\n", p.ExplainID()))
e.prepareTaskDot(p, "root", buffer)
buffer.WriteString(fmt.Sprintln("}"))
e.Rows = append(e.Rows, []string{buffer.String()})
}
func (e *Explain) prepareTaskDot(p PhysicalPlan, taskTp string, buffer *bytes.Buffer) {
buffer.WriteString(fmt.Sprintf("subgraph cluster%v{\n", p.ID()))
buffer.WriteString("node [style=filled, color=lightgrey]\n")
buffer.WriteString("color=black\n")
buffer.WriteString(fmt.Sprintf("label = \"%s\"\n", taskTp))
if len(p.Children()) == 0 {
buffer.WriteString(fmt.Sprintf("\"%s\"\n}\n", p.ExplainID()))
return
}
var copTasks []PhysicalPlan
var pipelines []string
for planQueue := []PhysicalPlan{p}; len(planQueue) > 0; planQueue = planQueue[1:] {
curPlan := planQueue[0]
switch copPlan := curPlan.(type) {
case *PhysicalTableReader:
pipelines = append(pipelines, fmt.Sprintf("\"%s\" -> \"%s\"\n", copPlan.ExplainID(), copPlan.tablePlan.ExplainID()))
copTasks = append(copTasks, copPlan.tablePlan)
case *PhysicalIndexReader:
pipelines = append(pipelines, fmt.Sprintf("\"%s\" -> \"%s\"\n", copPlan.ExplainID(), copPlan.indexPlan.ExplainID()))
copTasks = append(copTasks, copPlan.indexPlan)
case *PhysicalIndexLookUpReader:
pipelines = append(pipelines, fmt.Sprintf("\"%s\" -> \"%s\"\n", copPlan.ExplainID(), copPlan.tablePlan.ExplainID()))
pipelines = append(pipelines, fmt.Sprintf("\"%s\" -> \"%s\"\n", copPlan.ExplainID(), copPlan.indexPlan.ExplainID()))
copTasks = append(copTasks, copPlan.tablePlan)
copTasks = append(copTasks, copPlan.indexPlan)
}
for _, child := range curPlan.Children() {
buffer.WriteString(fmt.Sprintf("\"%s\" -> \"%s\"\n", curPlan.ExplainID(), child.ExplainID()))
planQueue = append(planQueue, child)
}
}
buffer.WriteString("}\n")
for _, cop := range copTasks {
e.prepareTaskDot(cop.(PhysicalPlan), "cop", buffer)
}
for i := range pipelines {
buffer.WriteString(pipelines[i])
}
}