forked from pingcap/tidb
/
adapter.go
436 lines (399 loc) · 13.6 KB
/
adapter.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
// 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 executor
import (
"fmt"
"math"
"strings"
"sync/atomic"
"time"
"github.com/juju/errors"
"github.com/pingcap/tidb/ast"
"github.com/pingcap/tidb/config"
"github.com/pingcap/tidb/expression"
"github.com/pingcap/tidb/infoschema"
"github.com/pingcap/tidb/kv"
"github.com/pingcap/tidb/model"
"github.com/pingcap/tidb/mysql"
"github.com/pingcap/tidb/plan"
"github.com/pingcap/tidb/sessionctx"
"github.com/pingcap/tidb/sessionctx/variable"
"github.com/pingcap/tidb/terror"
"github.com/pingcap/tidb/util/chunk"
"github.com/pingcap/tidb/util/logutil"
"github.com/pingcap/tidb/util/sqlexec"
log "github.com/sirupsen/logrus"
"golang.org/x/net/context"
)
type processinfoSetter interface {
SetProcessInfo(string)
}
// recordSet wraps an executor, implements ast.RecordSet interface
type recordSet struct {
fields []*ast.ResultField
executor Executor
stmt *ExecStmt
processinfo processinfoSetter
lastErr error
txnStartTS uint64
}
func (a *recordSet) Fields() []*ast.ResultField {
if len(a.fields) == 0 {
a.fields = schema2ResultFields(a.executor.Schema(), a.stmt.Ctx.GetSessionVars().CurrentDB)
}
return a.fields
}
func schema2ResultFields(schema *expression.Schema, defaultDB string) (rfs []*ast.ResultField) {
rfs = make([]*ast.ResultField, 0, schema.Len())
for _, col := range schema.Columns {
dbName := col.DBName.O
if dbName == "" && col.TblName.L != "" {
dbName = defaultDB
}
rf := &ast.ResultField{
ColumnAsName: col.ColName,
TableAsName: col.TblName,
DBName: model.NewCIStr(dbName),
Table: &model.TableInfo{Name: col.OrigTblName},
Column: &model.ColumnInfo{
FieldType: *col.RetType,
Name: col.ColName,
},
}
rfs = append(rfs, rf)
}
return rfs
}
// Next use uses recordSet's executor to get next available chunk for later usage.
// If chunk does not contain any rows, then we update last query found rows in session variable as current found rows.
// The reason we need update is that chunk with 0 rows indicating we already finished current query, we need prepare for
// next query.
// If stmt is not nil and chunk with some rows inside, we simply update last query found rows by the number of row in chunk.
func (a *recordSet) Next(ctx context.Context, chk *chunk.Chunk) error {
err := a.executor.Next(ctx, chk)
if err != nil {
a.lastErr = err
return errors.Trace(err)
}
numRows := chk.NumRows()
if numRows == 0 {
if a.stmt != nil {
a.stmt.Ctx.GetSessionVars().LastFoundRows = a.stmt.Ctx.GetSessionVars().StmtCtx.FoundRows()
}
return nil
}
if a.stmt != nil {
a.stmt.Ctx.GetSessionVars().StmtCtx.AddFoundRows(uint64(numRows))
}
return nil
}
// NewChunk create a new chunk using NewChunk function in chunk package.
func (a *recordSet) NewChunk() *chunk.Chunk {
return chunk.NewChunk(a.executor.retTypes())
}
func (a *recordSet) Close() error {
err := a.executor.Close()
a.stmt.LogSlowQuery(a.txnStartTS, a.lastErr == nil)
if a.processinfo != nil {
a.processinfo.SetProcessInfo("")
}
return errors.Trace(err)
}
// ExecStmt implements the ast.Statement interface, it builds a plan.Plan to an ast.Statement.
type ExecStmt struct {
// InfoSchema stores a reference to the schema information.
InfoSchema infoschema.InfoSchema
// Plan stores a reference to the final physical plan.
Plan plan.Plan
// Expensive represents whether this query is an expensive one.
Expensive bool
// Cacheable represents whether the physical plan can be cached.
Cacheable bool
// Text represents the origin query text.
Text string
StmtNode ast.StmtNode
Ctx sessionctx.Context
// StartTime stands for the starting time when executing the statement.
StartTime time.Time
isPreparedStmt bool
}
// OriginText returns original statement as a string.
func (a *ExecStmt) OriginText() string {
return a.Text
}
// IsPrepared returns true if stmt is a prepare statement.
func (a *ExecStmt) IsPrepared() bool {
return a.isPreparedStmt
}
// IsReadOnly returns true if a statement is read only.
// It will update readOnlyCheckStmt if current ExecStmt can be conveted to
// a plan.Execute. Last step is using ast.IsReadOnly function to determine
// a statement is read only or not.
func (a *ExecStmt) IsReadOnly() bool {
readOnlyCheckStmt := a.StmtNode
if checkPlan, ok := a.Plan.(*plan.Execute); ok {
readOnlyCheckStmt = checkPlan.Stmt
}
return ast.IsReadOnly(readOnlyCheckStmt)
}
// RebuildPlan rebuilds current execute statement plan.
func (a *ExecStmt) RebuildPlan() error {
is := GetInfoSchema(a.Ctx)
a.InfoSchema = is
if err := plan.Preprocess(a.Ctx, a.StmtNode, is, false); err != nil {
return errors.Trace(err)
}
p, err := plan.Optimize(a.Ctx, a.StmtNode, is)
if err != nil {
return errors.Trace(err)
}
a.Plan = p
return nil
}
// Exec builds an Executor from a plan. If the Executor doesn't return result,
// like the INSERT, UPDATE statements, it executes in this function, if the Executor returns
// result, execution is done after this function returns, in the returned ast.RecordSet Next method.
func (a *ExecStmt) Exec(ctx context.Context) (ast.RecordSet, error) {
a.StartTime = time.Now()
sctx := a.Ctx
if _, ok := a.Plan.(*plan.Analyze); ok && sctx.GetSessionVars().InRestrictedSQL {
oriStats, _ := sctx.GetSessionVars().GetSystemVar(variable.TiDBBuildStatsConcurrency)
oriScan := sctx.GetSessionVars().DistSQLScanConcurrency
oriIndex := sctx.GetSessionVars().IndexSerialScanConcurrency
oriIso, _ := sctx.GetSessionVars().GetSystemVar(variable.TxnIsolation)
terror.Log(errors.Trace(sctx.GetSessionVars().SetSystemVar(variable.TiDBBuildStatsConcurrency, "1")))
sctx.GetSessionVars().DistSQLScanConcurrency = 1
sctx.GetSessionVars().IndexSerialScanConcurrency = 1
terror.Log(errors.Trace(sctx.GetSessionVars().SetSystemVar(variable.TxnIsolation, ast.ReadCommitted)))
defer func() {
terror.Log(errors.Trace(sctx.GetSessionVars().SetSystemVar(variable.TiDBBuildStatsConcurrency, oriStats)))
sctx.GetSessionVars().DistSQLScanConcurrency = oriScan
sctx.GetSessionVars().IndexSerialScanConcurrency = oriIndex
terror.Log(errors.Trace(sctx.GetSessionVars().SetSystemVar(variable.TxnIsolation, oriIso)))
}()
}
e, err := a.buildExecutor(sctx)
if err != nil {
return nil, errors.Trace(err)
}
if err = e.Open(ctx); err != nil {
terror.Call(e.Close)
return nil, errors.Trace(err)
}
var pi processinfoSetter
if raw, ok := sctx.(processinfoSetter); ok {
pi = raw
sql := a.OriginText()
if simple, ok := a.Plan.(*plan.Simple); ok && simple.Statement != nil {
if ss, ok := simple.Statement.(ast.SensitiveStmtNode); ok {
// Use SecureText to avoid leak password information.
sql = ss.SecureText()
}
}
// Update processinfo, ShowProcess() will use it.
pi.SetProcessInfo(sql)
}
// If the executor doesn't return any result to the client, we execute it without delay.
if e.Schema().Len() == 0 {
return a.handleNoDelayExecutor(ctx, sctx, e, pi)
} else if proj, ok := e.(*ProjectionExec); ok && proj.calculateNoDelay {
// Currently this is only for the "DO" statement. Take "DO 1, @a=2;" as an example:
// the Projection has two expressions and two columns in the schema, but we should
// not return the result of the two expressions.
return a.handleNoDelayExecutor(ctx, sctx, e, pi)
}
var txnStartTS uint64
txn, err1 := sctx.Txn(false)
if err1 != nil {
return nil, errors.Trace(err1)
}
if txn.Valid() {
txnStartTS = txn.StartTS()
}
return &recordSet{
executor: e,
stmt: a,
processinfo: pi,
txnStartTS: txnStartTS,
}, nil
}
func (a *ExecStmt) handleNoDelayExecutor(ctx context.Context, sctx sessionctx.Context, e Executor, pi processinfoSetter) (ast.RecordSet, error) {
// Check if "tidb_snapshot" is set for the write executors.
// In history read mode, we can not do write operations.
switch e.(type) {
case *DeleteExec, *InsertExec, *UpdateExec, *ReplaceExec, *LoadData, *DDLExec:
snapshotTS := sctx.GetSessionVars().SnapshotTS
if snapshotTS != 0 {
return nil, errors.New("can not execute write statement when 'tidb_snapshot' is set")
}
txn, err := sctx.Txn(true)
if err != nil {
return nil, errors.Trace(err)
}
if !txn.Valid() {
if failer, ok := txn.(sqlexec.Failer); ok && failer.Fail() != nil {
return nil, failer.Fail()
}
return nil, errors.New("active transaction fail")
}
}
var err error
defer func() {
if pi != nil {
pi.SetProcessInfo("")
}
terror.Log(errors.Trace(e.Close()))
txnTS := uint64(0)
// Don't active pending txn here.
if txn, err1 := sctx.Txn(false); err1 != nil {
log.Error(err1)
} else {
if txn.Valid() {
txnTS = txn.StartTS()
}
}
a.LogSlowQuery(txnTS, err == nil)
}()
err = e.Next(ctx, e.newChunk())
if err != nil {
return nil, errors.Trace(err)
}
return nil, nil
}
// buildExecutor build a executor from plan, prepared statement may need additional procedure.
func (a *ExecStmt) buildExecutor(ctx sessionctx.Context) (Executor, error) {
priority := kv.PriorityNormal
if _, ok := a.Plan.(*plan.Execute); !ok {
// Do not sync transaction for Execute statement, because the real optimization work is done in
// "ExecuteExec.Build".
isPointGet, err := IsPointGetWithPKOrUniqueKeyByAutoCommit(ctx, a.Plan)
if err != nil {
return nil, errors.Trace(err)
}
if isPointGet {
log.Debugf("con:%d InitTxnWithStartTS %s", ctx.GetSessionVars().ConnectionID, a.Text)
err = ctx.InitTxnWithStartTS(math.MaxUint64)
}
if err != nil {
return nil, errors.Trace(err)
}
if stmtPri := ctx.GetSessionVars().StmtCtx.Priority; stmtPri != mysql.NoPriority {
priority = int(stmtPri)
} else {
switch {
case isPointGet:
priority = kv.PriorityHigh
case a.Expensive:
priority = kv.PriorityLow
}
}
}
if _, ok := a.Plan.(*plan.Analyze); ok && ctx.GetSessionVars().InRestrictedSQL {
priority = kv.PriorityLow
}
b := newExecutorBuilder(ctx, a.InfoSchema, priority)
e := b.build(a.Plan)
if b.err != nil {
return nil, errors.Trace(b.err)
}
// ExecuteExec is not a real Executor, we only use it to build another Executor from a prepared statement.
if executorExec, ok := e.(*ExecuteExec); ok {
err := executorExec.Build()
if err != nil {
return nil, errors.Trace(err)
}
a.Text = executorExec.stmt.Text()
a.isPreparedStmt = true
a.Plan = executorExec.plan
e = executorExec.stmtExec
}
return e, nil
}
// QueryReplacer replaces new line and tab for grep result including query string.
var QueryReplacer = strings.NewReplacer("\r", " ", "\n", " ", "\t", " ")
// LogSlowQuery is used to print the slow query in the log files.
func (a *ExecStmt) LogSlowQuery(txnTS uint64, succ bool) {
level := log.GetLevel()
if level < log.WarnLevel {
return
}
cfg := config.GetGlobalConfig()
costTime := time.Since(a.StartTime)
threshold := time.Duration(atomic.LoadUint64(&cfg.Log.SlowThreshold)) * time.Millisecond
if costTime < threshold && level < log.DebugLevel {
return
}
sql := a.Text
if len(sql) > int(cfg.Log.QueryLogMaxLen) {
sql = fmt.Sprintf("%.*q(len:%d)", cfg.Log.QueryLogMaxLen, sql, len(a.Text))
}
sql = QueryReplacer.Replace(sql)
sessVars := a.Ctx.GetSessionVars()
connID := sessVars.ConnectionID
currentDB := sessVars.CurrentDB
var tableIDs, indexIDs string
if len(sessVars.StmtCtx.TableIDs) > 0 {
tableIDs = strings.Replace(fmt.Sprintf("table_ids:%v ", a.Ctx.GetSessionVars().StmtCtx.TableIDs), " ", ",", -1)
}
if len(sessVars.StmtCtx.IndexIDs) > 0 {
indexIDs = strings.Replace(fmt.Sprintf("index_ids:%v ", a.Ctx.GetSessionVars().StmtCtx.IndexIDs), " ", ",", -1)
}
user := a.Ctx.GetSessionVars().User
if costTime < threshold {
logutil.SlowQueryLogger.Debugf(
"[QUERY] cost_time:%v %s succ:%v con:%v user:%s txn_start_ts:%v database:%v %v%vsql:%v",
costTime, sessVars.StmtCtx.GetExecDetails(), succ, connID, user, txnTS, currentDB, tableIDs, indexIDs, sql)
} else {
logutil.SlowQueryLogger.Warnf(
"[SLOW_QUERY] cost_time:%v %s succ:%v con:%v user:%s txn_start_ts:%v database:%v %v%vsql:%v",
costTime, sessVars.StmtCtx.GetExecDetails(), succ, connID, user, txnTS, currentDB, tableIDs, indexIDs, sql)
}
}
// IsPointGetWithPKOrUniqueKeyByAutoCommit returns true when meets following conditions:
// 1. ctx is auto commit tagged
// 2. txn is not valid
// 2. plan is point get by pk or unique key
func IsPointGetWithPKOrUniqueKeyByAutoCommit(ctx sessionctx.Context, p plan.Plan) (bool, error) {
// check auto commit
if !ctx.GetSessionVars().IsAutocommit() {
return false, nil
}
// check txn
txn, err := ctx.Txn(false)
if err != nil {
return false, errors.Trace(err)
}
if txn.Valid() {
return false, nil
}
// check plan
if proj, ok := p.(*plan.PhysicalProjection); ok {
if len(proj.Children()) != 1 {
return false, nil
}
p = proj.Children()[0]
}
switch v := p.(type) {
case *plan.PhysicalIndexReader:
indexScan := v.IndexPlans[0].(*plan.PhysicalIndexScan)
return indexScan.IsPointGetByUniqueKey(ctx.GetSessionVars().StmtCtx), nil
case *plan.PhysicalIndexLookUpReader:
indexScan := v.IndexPlans[0].(*plan.PhysicalIndexScan)
return indexScan.IsPointGetByUniqueKey(ctx.GetSessionVars().StmtCtx), nil
case *plan.PhysicalTableReader:
tableScan := v.TablePlans[0].(*plan.PhysicalTableScan)
return len(tableScan.Ranges) == 1 && tableScan.Ranges[0].IsPoint(ctx.GetSessionVars().StmtCtx), nil
default:
return false, nil
}
}