forked from pingcap/tidb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplan.go
458 lines (396 loc) · 13.7 KB
/
plan.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
// 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 plan
import (
"bytes"
"encoding/json"
"fmt"
"github.com/juju/errors"
"github.com/pingcap/tidb/context"
"github.com/pingcap/tidb/expression"
"github.com/pingcap/tidb/util/codec"
"github.com/pingcap/tidb/util/types"
)
// UseDAGPlanBuilder means we should use new planner and dag pb.
var UseDAGPlanBuilder = false
// Plan is the description of an execution flow.
// It is created from ast.Node first, then optimized by the optimizer,
// finally used by the executor to create a Cursor which executes the statement.
type Plan interface {
// AddParent means appending a parent for plan.
AddParent(parent Plan)
// AddChild means appending a child for plan.
AddChild(children Plan)
// ReplaceParent means replacing a parent with another one.
ReplaceParent(parent, newPar Plan) error
// ReplaceChild means replacing a child with another one.
ReplaceChild(children, newChild Plan) error
// Get all the parents.
Parents() []Plan
// Get all the children.
Children() []Plan
// Set the schema.
SetSchema(schema *expression.Schema)
// Get the schema.
Schema() *expression.Schema
// Get the ID.
ID() string
// Get id allocator
Allocator() *idAllocator
// SetParents sets the parents for the plan.
SetParents(...Plan)
// SetChildren sets the children for the plan.
SetChildren(...Plan)
context() context.Context
extractCorrelatedCols() []*expression.CorrelatedColumn
}
type columnProp struct {
col *expression.Column
desc bool
}
func (c *columnProp) equal(nc *columnProp, ctx context.Context) bool {
return c.col.Equal(nc.col, ctx) && c.desc == nc.desc
}
// requriedProp stands for the required order property by parents. It will be all asc or desc.
type requiredProp struct {
cols []*expression.Column
desc bool
}
func (p *requiredProp) isEmpty() bool {
return len(p.cols) == 0
}
// getHashKey encodes prop to a unique key. The key will be stored in the memory table.
func (p *requiredProp) getHashKey() ([]byte, error) {
datums := make([]types.Datum, 0, len(p.cols)*2+1)
datums = append(datums, types.NewDatum(p.desc))
for _, c := range p.cols {
datums = append(datums, types.NewDatum(c.FromID), types.NewDatum(c.Position))
}
bytes, err := codec.EncodeValue(nil, datums...)
return bytes, errors.Trace(err)
}
// String implements fmt.Stringer interface. Just for test.
func (p *requiredProp) String() string {
return fmt.Sprintf("Prop{cols: %s, desc: %v}", p.cols, p.desc)
}
type requiredProperty struct {
props []*columnProp
sortKeyLen int
limit *Limit
}
// getHashKey encodes a requiredProperty to a unique hash code.
func (p *requiredProperty) getHashKey() ([]byte, error) {
datums := make([]types.Datum, 0, len(p.props)*3+1)
datums = append(datums, types.NewDatum(p.sortKeyLen))
for _, c := range p.props {
datums = append(datums, types.NewDatum(c.desc), types.NewDatum(c.col.FromID), types.NewDatum(c.col.Index))
}
bytes, err := codec.EncodeValue(nil, datums...)
return bytes, errors.Trace(err)
}
// String implements fmt.Stringer interface. Just for test.
func (p *requiredProperty) String() string {
ret := "Prop{"
for _, colProp := range p.props {
ret += fmt.Sprintf("col: %s, desc %v, ", colProp.col, colProp.desc)
}
ret += fmt.Sprintf("}, Len: %d", p.sortKeyLen)
if p.limit != nil {
ret += fmt.Sprintf(", Limit: %d,%d", p.limit.Offset, p.limit.Count)
}
return ret
}
type physicalPlanInfo struct {
p PhysicalPlan
cost float64
count float64
}
// LogicalPlan is a tree of logical operators.
// We can do a lot of logical optimizations to it, like predicate pushdown and column pruning.
type LogicalPlan interface {
Plan
// PredicatePushDown pushes down the predicates in the where/on/having clauses as deeply as possible.
// It will accept a predicate that is an expression slice, and return the expressions that can't be pushed.
// Because it might change the root if the having clause exists, we need to return a plan that represents a new root.
PredicatePushDown([]expression.Expression) ([]expression.Expression, LogicalPlan, error)
// PruneColumns prunes the unused columns.
PruneColumns([]*expression.Column)
// ResolveIndicesAndCorCols resolves the index for columns and initializes the correlated columns.
ResolveIndicesAndCorCols()
// convert2PhysicalPlan converts the logical plan to the physical plan.
// It is called recursively from the parent to the children to create the result physical plan.
// Some logical plans will convert the children to the physical plans in different ways, and return the one
// with the lowest cost.
convert2PhysicalPlan(prop *requiredProperty) (*physicalPlanInfo, error)
// convert2NewPhysicalPlan converts the logical plan to the physical plan. It's a new interface.
// It is called recursively from the parent to the children to create the result physical plan.
// Some logical plans will convert the children to the physical plans in different ways, and return the one
// with the lowest cost.
convert2NewPhysicalPlan(prop *requiredProp) (taskProfile, error)
// buildKeyInfo will collect the information of unique keys into schema.
buildKeyInfo()
// pushDownTopN will push down the topN or limit operator during logical optimization.
pushDownTopN(topN *Sort) LogicalPlan
}
// PhysicalPlan is a tree of the physical operators.
type PhysicalPlan interface {
json.Marshaler
Plan
// matchProperty calculates the cost of the physical plan if it matches the required property.
// It's usually called at the end of convert2PhysicalPlan. Some physical plans do not implement it because there is
// no property to match, these plans just do the cost calculation directly.
// If the cost of the physical plan does not match the required property, the cost will be set to MaxInt64
// so it will not be chosen as the result physical plan.
// childrenPlanInfo are used to calculate the result cost of the plan.
// The returned *physicalPlanInfo will be chosen as the final plan if it has the lowest cost.
// For the lowest level *PhysicalTableScan and *PhysicalIndexScan, even though it doesn't have childPlanInfo, we
// create an initial *physicalPlanInfo to pass the row count.
matchProperty(prop *requiredProperty, childPlanInfo ...*physicalPlanInfo) *physicalPlanInfo
// Copy copies the current plan.
Copy() PhysicalPlan
// attach2TaskProfile makes the current physical plan as the father of task's physicalPlan and updates the cost of
// current task. If the child's task is cop task, some operator may close this task and return a new rootTask.
attach2TaskProfile(...taskProfile) taskProfile
}
type baseLogicalPlan struct {
basePlan *basePlan
planMap map[string]*physicalPlanInfo
taskMap map[string]taskProfile
}
type basePhysicalPlan struct {
basePlan *basePlan
}
func (p *baseLogicalPlan) getTaskProfile(prop *requiredProp) (taskProfile, error) {
key, err := prop.getHashKey()
if err != nil {
return nil, errors.Trace(err)
}
return p.taskMap[string(key)], nil
}
func (p *baseLogicalPlan) getPlanInfo(prop *requiredProperty) (*physicalPlanInfo, error) {
key, err := prop.getHashKey()
if err != nil {
return nil, errors.Trace(err)
}
return p.planMap[string(key)], nil
}
func (p *baseLogicalPlan) convert2PhysicalPlan(prop *requiredProperty) (*physicalPlanInfo, error) {
info, err := p.getPlanInfo(prop)
if err != nil {
return nil, errors.Trace(err)
}
if info != nil {
return info, nil
}
if len(p.basePlan.children) == 0 {
return &physicalPlanInfo{p: p.basePlan.self.(PhysicalPlan)}, nil
}
child := p.basePlan.children[0].(LogicalPlan)
info, err = child.convert2PhysicalPlan(prop)
if err != nil {
return nil, errors.Trace(err)
}
info = addPlanToResponse(p.basePlan.self.(PhysicalPlan), info)
return info, p.storePlanInfo(prop, info)
}
func (p *baseLogicalPlan) storeTaskProfile(prop *requiredProp, task taskProfile) error {
key, err := prop.getHashKey()
if err != nil {
return errors.Trace(err)
}
p.taskMap[string(key)] = task
return nil
}
func (p *baseLogicalPlan) storePlanInfo(prop *requiredProperty, info *physicalPlanInfo) error {
key, err := prop.getHashKey()
if err != nil {
return errors.Trace(err)
}
newInfo := *info // copy it
p.planMap[string(key)] = &newInfo
return nil
}
func (p *baseLogicalPlan) buildKeyInfo() {
for _, child := range p.basePlan.children {
child.(LogicalPlan).buildKeyInfo()
}
if len(p.basePlan.children) == 1 {
switch p.basePlan.self.(type) {
case *Exists, *LogicalAggregation, *Projection:
p.basePlan.schema.Keys = nil
case *SelectLock:
p.basePlan.schema.Keys = p.basePlan.children[0].Schema().Keys
default:
p.basePlan.schema.Keys = p.basePlan.children[0].Schema().Clone().Keys
}
} else {
p.basePlan.schema.Keys = nil
}
}
func newBasePlan(tp string, allocator *idAllocator, ctx context.Context, p Plan) *basePlan {
return &basePlan{
tp: tp,
allocator: allocator,
id: tp + allocator.allocID(),
ctx: ctx,
self: p,
}
}
func newBaseLogicalPlan(basePlan *basePlan) baseLogicalPlan {
return baseLogicalPlan{
planMap: make(map[string]*physicalPlanInfo),
taskMap: make(map[string]taskProfile),
basePlan: basePlan,
}
}
func newBasePhysicalPlan(basePlan *basePlan) basePhysicalPlan {
return basePhysicalPlan{
basePlan: basePlan,
}
}
func (p *basePhysicalPlan) matchProperty(prop *requiredProperty, childPlanInfo ...*physicalPlanInfo) *physicalPlanInfo {
panic("You can't call this function!")
}
// PredicatePushDown implements LogicalPlan interface.
func (p *baseLogicalPlan) PredicatePushDown(predicates []expression.Expression) ([]expression.Expression, LogicalPlan, error) {
if len(p.basePlan.children) == 0 {
return predicates, p.basePlan.self.(LogicalPlan), nil
}
child := p.basePlan.children[0].(LogicalPlan)
rest, _, err := child.PredicatePushDown(predicates)
if err != nil {
return nil, nil, errors.Trace(err)
}
if len(rest) > 0 {
err = addSelection(p.basePlan.self, child, rest, p.basePlan.allocator)
if err != nil {
return nil, nil, errors.Trace(err)
}
}
return nil, p.basePlan.self.(LogicalPlan), nil
}
func (p *basePlan) extractCorrelatedCols() []*expression.CorrelatedColumn {
var corCols []*expression.CorrelatedColumn
for _, child := range p.children {
corCols = append(corCols, child.extractCorrelatedCols()...)
}
return corCols
}
func (p *basePlan) Allocator() *idAllocator {
return p.allocator
}
// ResolveIndicesAndCorCols implements LogicalPlan interface.
func (p *baseLogicalPlan) ResolveIndicesAndCorCols() {
for _, child := range p.basePlan.children {
child.(LogicalPlan).ResolveIndicesAndCorCols()
}
}
// PruneColumns implements LogicalPlan interface.
func (p *baseLogicalPlan) PruneColumns(parentUsedCols []*expression.Column) {
if len(p.basePlan.children) == 0 {
return
}
child := p.basePlan.children[0].(LogicalPlan)
child.PruneColumns(parentUsedCols)
p.basePlan.SetSchema(child.Schema())
}
// basePlan implements base Plan interface.
// Should be used as embedded struct in Plan implementations.
type basePlan struct {
parents []Plan
children []Plan
schema *expression.Schema
tp string
id string
allocator *idAllocator
ctx context.Context
self Plan
}
func (p *basePlan) copy() *basePlan {
np := *p
return &np
}
// MarshalJSON implements json.Marshaler interface.
func (p *basePlan) MarshalJSON() ([]byte, error) {
children := make([]string, 0, len(p.children))
for _, child := range p.children {
children = append(children, child.ID())
}
childrenStrs, err := json.Marshal(children)
if err != nil {
return nil, errors.Trace(err)
}
buffer := bytes.NewBufferString("{")
buffer.WriteString(fmt.Sprintf("\"children\": %s", childrenStrs))
buffer.WriteString("}")
return buffer.Bytes(), nil
}
// ID implements Plan ID interface.
func (p *basePlan) ID() string {
return p.id
}
// SetSchema implements Plan SetSchema interface.
func (p *basePlan) SetSchema(schema *expression.Schema) {
p.schema = schema
}
// Schema implements Plan Schema interface.
func (p *basePlan) Schema() *expression.Schema {
return p.schema
}
// AddParent implements Plan AddParent interface.
func (p *basePlan) AddParent(parent Plan) {
p.parents = append(p.parents, parent)
}
// AddChild implements Plan AddChild interface.
func (p *basePlan) AddChild(child Plan) {
p.children = append(p.children, child)
}
// ReplaceParent means replace a parent for another one.
func (p *basePlan) ReplaceParent(parent, newPar Plan) error {
for i, par := range p.parents {
if par.ID() == parent.ID() {
p.parents[i] = newPar
return nil
}
}
return SystemInternalErrorType.Gen("ReplaceParent Failed!")
}
// ReplaceChild means replace a child with another one.
func (p *basePlan) ReplaceChild(child, newChild Plan) error {
for i, ch := range p.children {
if ch.ID() == child.ID() {
p.children[i] = newChild
return nil
}
}
return SystemInternalErrorType.Gen("ReplaceChildren Failed!")
}
// Parents implements Plan Parents interface.
func (p *basePlan) Parents() []Plan {
return p.parents
}
// Children implements Plan Children interface.
func (p *basePlan) Children() []Plan {
return p.children
}
// SetParents implements Plan SetParents interface.
func (p *basePlan) SetParents(pars ...Plan) {
p.parents = pars
}
// SetChildren implements Plan SetChildren interface.
func (p *basePlan) SetChildren(children ...Plan) {
p.children = children
}
func (p *basePlan) context() context.Context {
return p.ctx
}