-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
Copy pathplan.go
458 lines (404 loc) · 15.8 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 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package sql
import (
"context"
"github.com/cockroachdb/cockroach/pkg/internal/client"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/settings/cluster"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/sessiondata"
"github.com/cockroachdb/cockroach/pkg/sql/sqlbase"
"github.com/cockroachdb/cockroach/pkg/util/hlc"
"github.com/cockroachdb/errors"
)
// runParams is a struct containing all parameters passed to planNode.Next() and
// startPlan.
type runParams struct {
// context.Context for this method call.
ctx context.Context
// extendedEvalCtx groups fields useful for this execution.
// Used during local execution and distsql physical planning.
extendedEvalCtx *extendedEvalContext
// planner associated with this execution. Only used during local
// execution.
p *planner
}
// EvalContext() gives convenient access to the runParam's EvalContext().
func (r *runParams) EvalContext() *tree.EvalContext {
return &r.extendedEvalCtx.EvalContext
}
// SessionData gives convenient access to the runParam's SessionData.
func (r *runParams) SessionData() *sessiondata.SessionData {
return r.extendedEvalCtx.SessionData
}
// ExecCfg gives convenient access to the runParam's ExecutorConfig.
func (r *runParams) ExecCfg() *ExecutorConfig {
return r.extendedEvalCtx.ExecCfg
}
// Ann is a shortcut for the Annotations from the eval context.
func (r *runParams) Ann() *tree.Annotations {
return r.extendedEvalCtx.EvalContext.Annotations
}
// createTimeForNewTableDescriptor consults the cluster version to determine
// whether the CommitTimestamp() needs to be observed when creating a new
// TableDescriptor. See TableDescriptor.ModificationTime.
//
// TODO(ajwerner): remove in 20.1.
func (r *runParams) creationTimeForNewTableDescriptor() hlc.Timestamp {
// Before 19.2 we needed to observe the transaction CommitTimestamp to ensure
// that CreateAsOfTime and ModificationTime reflected the timestamp at which the
// creating transaction committed. Starting in 19.2 we use a zero-valued
// CreateAsOfTime and ModificationTime when creating a table descriptor and then
// upon reading use the MVCC timestamp to populate the values.
var ts hlc.Timestamp
if !cluster.Version.IsActive(
r.ctx, r.ExecCfg().Settings, cluster.VersionTableDescModificationTimeFromMVCC,
) {
ts = r.p.txn.CommitTimestamp()
}
return ts
}
// planNode defines the interface for executing a query or portion of a query.
//
// The following methods apply to planNodes and contain special cases
// for each type; they thus need to be extended when adding/removing
// planNode instances:
// - planVisitor.visit() (walk.go)
// - planNodeNames (walk.go)
// - setLimitHint() (limit_hint.go)
// - planColumns() (plan_columns.go)
//
type planNode interface {
startExec(params runParams) error
// Next performs one unit of work, returning false if an error is
// encountered or if there is no more work to do. For statements
// that return a result set, the Values() method will return one row
// of results each time that Next() returns true.
//
// Available after startPlan(). It is illegal to call Next() after it returns
// false. It is legal to call Next() even if the node implements
// planNodeFastPath and the FastPathResults() method returns true.
Next(params runParams) (bool, error)
// Values returns the values at the current row. The result is only valid
// until the next call to Next().
//
// Available after Next().
Values() tree.Datums
// Close terminates the planNode execution and releases its resources.
// This method should be called if the node has been used in any way (any
// methods on it have been called) after it was constructed. Note that this
// doesn't imply that startExec() has been necessarily called.
//
// This method must not be called during execution - the planNode
// tree must remain "live" and readable via walk() even after
// execution completes.
Close(ctx context.Context)
}
// PlanNode is the exported name for planNode. Useful for CCL hooks.
type PlanNode = planNode
// planNodeFastPath is implemented by nodes that can perform all their
// work during startPlan(), possibly affecting even multiple rows. For
// example, DELETE can do this.
type planNodeFastPath interface {
// FastPathResults returns the affected row count and true if the
// node has no result set and has already executed when startPlan() completes.
// Note that Next() must still be valid even if this method returns
// true, although it may have nothing left to do.
FastPathResults() (int, bool)
}
// planNodeReadingOwnWrites can be implemented by planNodes which do
// not use the standard SQL principle of reading at the snapshot
// established at the start of the transaction. This is the case
// e.g. for most DDL statements that perform multiple KV operations on
// descriptors, expecting to read their own writes.
//
// This constraint is obeyed by (*planner).startExec().
type planNodeReadingOwnWrites interface {
// ReadingOwnWrites can be implemented as no-op by nodes wishing
// to request the semantics described above.
ReadingOwnWrites()
}
var _ planNode = &alterIndexNode{}
var _ planNode = &alterSequenceNode{}
var _ planNode = &alterTableNode{}
var _ planNode = &bufferNode{}
var _ planNode = &cancelQueriesNode{}
var _ planNode = &cancelSessionsNode{}
var _ planNode = &changePrivilegesNode{}
var _ planNode = &createDatabaseNode{}
var _ planNode = &createIndexNode{}
var _ planNode = &createSequenceNode{}
var _ planNode = &createStatsNode{}
var _ planNode = &createTableNode{}
var _ planNode = &CreateUserNode{}
var _ planNode = &createViewNode{}
var _ planNode = &delayedNode{}
var _ planNode = &deleteNode{}
var _ planNode = &deleteRangeNode{}
var _ planNode = &distinctNode{}
var _ planNode = &dropDatabaseNode{}
var _ planNode = &dropIndexNode{}
var _ planNode = &dropSequenceNode{}
var _ planNode = &dropTableNode{}
var _ planNode = &DropUserNode{}
var _ planNode = &dropViewNode{}
var _ planNode = &errorIfRowsNode{}
var _ planNode = &explainDistSQLNode{}
var _ planNode = &explainPlanNode{}
var _ planNode = &explainVecNode{}
var _ planNode = &filterNode{}
var _ planNode = &groupNode{}
var _ planNode = &hookFnNode{}
var _ planNode = &indexJoinNode{}
var _ planNode = &insertNode{}
var _ planNode = &insertFastPathNode{}
var _ planNode = &joinNode{}
var _ planNode = &limitNode{}
var _ planNode = &max1RowNode{}
var _ planNode = &ordinalityNode{}
var _ planNode = &projectSetNode{}
var _ planNode = &recursiveCTENode{}
var _ planNode = &relocateNode{}
var _ planNode = &renameColumnNode{}
var _ planNode = &renameDatabaseNode{}
var _ planNode = &renameIndexNode{}
var _ planNode = &renameTableNode{}
var _ planNode = &renderNode{}
var _ planNode = &rowCountNode{}
var _ planNode = &scanBufferNode{}
var _ planNode = &scanNode{}
var _ planNode = &scatterNode{}
var _ planNode = &serializeNode{}
var _ planNode = &sequenceSelectNode{}
var _ planNode = &showFingerprintsNode{}
var _ planNode = &showTraceNode{}
var _ planNode = &sortNode{}
var _ planNode = &splitNode{}
var _ planNode = &unsplitNode{}
var _ planNode = &unsplitAllNode{}
var _ planNode = &truncateNode{}
var _ planNode = &unaryNode{}
var _ planNode = &unionNode{}
var _ planNode = &updateNode{}
var _ planNode = &upsertNode{}
var _ planNode = &valuesNode{}
var _ planNode = &virtualTableNode{}
var _ planNode = &windowNode{}
var _ planNode = &zeroNode{}
var _ planNodeFastPath = &CreateUserNode{}
var _ planNodeFastPath = &DropUserNode{}
var _ planNodeFastPath = &alterUserSetPasswordNode{}
var _ planNodeFastPath = &deleteRangeNode{}
var _ planNodeFastPath = &rowCountNode{}
var _ planNodeFastPath = &serializeNode{}
var _ planNodeFastPath = &setZoneConfigNode{}
var _ planNodeFastPath = &controlJobsNode{}
var _ planNodeReadingOwnWrites = &alterIndexNode{}
var _ planNodeReadingOwnWrites = &alterSequenceNode{}
var _ planNodeReadingOwnWrites = &alterTableNode{}
var _ planNodeReadingOwnWrites = &createIndexNode{}
var _ planNodeReadingOwnWrites = &createSequenceNode{}
var _ planNodeReadingOwnWrites = &createTableNode{}
var _ planNodeReadingOwnWrites = &createViewNode{}
var _ planNodeReadingOwnWrites = &changePrivilegesNode{}
var _ planNodeReadingOwnWrites = &setZoneConfigNode{}
// planNodeRequireSpool serves as marker for nodes whose parent must
// ensure that the node is fully run to completion (and the results
// spooled) during the start phase. This is currently implemented by
// all mutation statements except for upsert.
type planNodeRequireSpool interface {
requireSpool()
}
var _ planNodeRequireSpool = &serializeNode{}
// planNodeSpool serves as marker for nodes that can perform all their
// execution during the start phase. This is different from the "fast
// path" interface because a node that performs all its execution
// during the start phase might still have some result rows and thus
// not implement the fast path.
//
// This interface exists for the following optimization: nodes
// that require spooling but are the children of a spooled node
// do not require the introduction of an explicit spool.
type planNodeSpooled interface {
spooled()
}
var _ planNodeSpooled = &spoolNode{}
// planTop is the struct that collects the properties
// of an entire plan.
// Note: some additional per-statement state is also stored in
// semaCtx (placeholders).
// TODO(jordan): investigate whether/how per-plan state like
// placeholder data can be concentrated in a single struct.
type planTop struct {
// AST is the syntax tree for the current statement.
AST tree.Statement
// plan is the top-level node of the logical plan.
plan planNode
// deps, if non-nil, collects the table/view dependencies for this query.
// Any planNode constructors that resolves a table name or reference in the query
// to a descriptor must register this descriptor into planDeps.
// This is (currently) used by CREATE VIEW.
// TODO(knz): Remove this in favor of a better encapsulated mechanism.
deps planDependencies
// subqueryPlans contains all the sub-query plans.
subqueryPlans []subquery
// postqueryPlans contains all the plans for subqueries that are to be
// executed after the main query (for example, foreign key checks).
postqueryPlans []postquery
// auditEvents becomes non-nil if any of the descriptors used by
// current statement is causing an auditing event. See exec_log.go.
auditEvents []auditEvent
// flags is populated during planning and execution.
flags planFlags
// execErr retains the last execution error, if any.
execErr error
// maybeSavePlan, if defined, is called during close() to
// conditionally save the logical plan to savedPlanForStats.
maybeSavePlan func(context.Context) *roachpb.ExplainTreePlanNode
// savedPlanForStats is conditionally populated at the end of
// statement execution, for registration in statement statistics.
savedPlanForStats *roachpb.ExplainTreePlanNode
// avoidBuffering, when set, causes the execution to avoid buffering
// results.
avoidBuffering bool
}
// postquery is a query tree that is executed after the main one. It can only
// return an error (for example, foreign key violation).
type postquery struct {
plan planNode
}
// close ensures that the plan's resources have been deallocated.
func (p *planTop) close(ctx context.Context) {
if p.plan != nil {
if p.maybeSavePlan != nil && p.flags.IsSet(planFlagExecDone) {
p.savedPlanForStats = p.maybeSavePlan(ctx)
}
p.plan.Close(ctx)
p.plan = nil
}
for i := range p.subqueryPlans {
// Once a subquery plan has been evaluated, it already closes its
// plan.
if p.subqueryPlans[i].plan != nil {
p.subqueryPlans[i].plan.Close(ctx)
p.subqueryPlans[i].plan = nil
}
}
for i := range p.postqueryPlans {
if p.postqueryPlans[i].plan != nil {
p.postqueryPlans[i].plan.Close(ctx)
p.postqueryPlans[i].plan = nil
}
}
}
// startExec calls startExec() on each planNode using a depth-first, post-order
// traversal. The subqueries, if any, are also started.
//
// If the planNode also implements the nodeReadingOwnWrites interface,
// the txn is temporarily reconfigured to use read-your-own-writes for
// the duration of the call to startExec. This is used e.g. by
// DDL statements.
//
// Reminder: walkPlan() ensures that subqueries and sub-plans are
// started before startExec() is called.
func startExec(params runParams, plan planNode) error {
o := planObserver{
enterNode: func(ctx context.Context, _ string, p planNode) (bool, error) {
switch p.(type) {
case *explainPlanNode, *explainDistSQLNode, *explainVecNode:
// Do not recurse: we're not starting the plan if we just show its structure with EXPLAIN.
return false, nil
case *showTraceNode:
// showTrace needs to override the params struct, and does so in its startExec() method.
return false, nil
}
return true, nil
},
leaveNode: func(_ string, n planNode) (err error) {
if _, ok := n.(planNodeReadingOwnWrites); ok {
_, err = params.p.Txn().ConfigureStepping(client.SteppingDisabled)
if err != nil {
return err
}
defer func() {
_, thisErr := params.p.Txn().ConfigureStepping(client.SteppingEnabled)
err = errors.CombineErrors(err, thisErr)
}()
}
return n.startExec(params)
},
}
return walkPlan(params.ctx, plan, o)
}
func (p *planner) maybePlanHook(ctx context.Context, stmt tree.Statement) (planNode, error) {
// TODO(dan): This iteration makes the plan dispatch no longer constant
// time. We could fix that with a map of `reflect.Type` but including
// reflection in such a primary codepath is unfortunate. Instead, the
// upcoming IR work will provide unique numeric type tags, which will
// elegantly solve this.
for _, planHook := range planHooks {
if fn, header, subplans, avoidBuffering, err := planHook(ctx, stmt, p); err != nil {
return nil, err
} else if fn != nil {
if avoidBuffering {
p.curPlan.avoidBuffering = true
}
return &hookFnNode{f: fn, header: header, subplans: subplans}, nil
}
}
for _, planHook := range wrappedPlanHooks {
if node, err := planHook(ctx, stmt, p); err != nil {
return nil, err
} else if node != nil {
return node, err
}
}
return nil, nil
}
// Mark transaction as operating on the system DB if the descriptor id
// is within the SystemConfig range.
func (p *planner) maybeSetSystemConfig(id sqlbase.ID) error {
if !sqlbase.IsSystemConfigID(id) {
return nil
}
// Mark transaction as operating on the system DB.
return p.txn.SetSystemConfigTrigger()
}
// planFlags is used throughout the planning code to keep track of various
// events or decisions along the way.
type planFlags uint32
const (
// planFlagOptUsed is set if the optimizer was used to create the plan.
planFlagOptUsed planFlags = (1 << iota)
// planFlagOptCacheHit is set if a plan from the query plan cache was used (and
// re-optimized).
planFlagOptCacheHit
// planFlagOptCacheMiss is set if we looked for a plan in the query plan cache but
// did not find one.
planFlagOptCacheMiss
// planFlagDistributed is set if the plan is for the DistSQL engine, in
// distributed mode.
planFlagDistributed
// planFlagDistSQLLocal is set if the plan is for the DistSQL engine,
// but in local mode.
planFlagDistSQLLocal
// planFlagExecDone marks that execution has been completed.
planFlagExecDone
// planFlagImplicitTxn marks that the plan was run inside of an implicit
// transaction.
planFlagImplicitTxn
)
func (pf planFlags) IsSet(flag planFlags) bool {
return (pf & flag) != 0
}
func (pf *planFlags) Set(flag planFlags) {
*pf |= flag
}