-
Notifications
You must be signed in to change notification settings - Fork 5.9k
/
prepared.go
402 lines (362 loc) · 10.7 KB
/
prepared.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
// 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 (
"math"
"sort"
"github.com/juju/errors"
"github.com/pingcap/tidb/ast"
"github.com/pingcap/tidb/context"
"github.com/pingcap/tidb/expression"
"github.com/pingcap/tidb/infoschema"
"github.com/pingcap/tidb/kv"
"github.com/pingcap/tidb/parser"
"github.com/pingcap/tidb/plan"
"github.com/pingcap/tidb/sessionctx/variable"
"github.com/pingcap/tidb/util/sqlexec"
)
var (
_ Executor = &DeallocateExec{}
_ Executor = &ExecuteExec{}
_ Executor = &PrepareExec{}
)
type paramMarkerSorter struct {
markers []*ast.ParamMarkerExpr
}
func (p *paramMarkerSorter) Len() int {
return len(p.markers)
}
func (p *paramMarkerSorter) Less(i, j int) bool {
return p.markers[i].Offset < p.markers[j].Offset
}
func (p *paramMarkerSorter) Swap(i, j int) {
p.markers[i], p.markers[j] = p.markers[j], p.markers[i]
}
type paramMarkerExtractor struct {
markers []*ast.ParamMarkerExpr
}
func (e *paramMarkerExtractor) Enter(in ast.Node) (ast.Node, bool) {
return in, false
}
func (e *paramMarkerExtractor) Leave(in ast.Node) (ast.Node, bool) {
if x, ok := in.(*ast.ParamMarkerExpr); ok {
e.markers = append(e.markers, x)
}
return in, true
}
// Prepared represents a prepared statement.
type Prepared struct {
Stmt ast.StmtNode
Params []*ast.ParamMarkerExpr
SchemaVersion int64
}
// PrepareExec represents a PREPARE executor.
type PrepareExec struct {
IS infoschema.InfoSchema
Ctx context.Context
Name string
SQLText string
ID uint32
ParamCount int
Err error
Fields []*ast.ResultField
}
// Schema implements the Executor Schema interface.
func (e *PrepareExec) Schema() *expression.Schema {
// Will never be called.
return expression.NewSchema()
}
// Next implements the Executor Next interface.
func (e *PrepareExec) Next() (Row, error) {
e.DoPrepare()
return nil, e.Err
}
// Close implements the Executor Close interface.
func (e *PrepareExec) Close() error {
return nil
}
// Open implements the Executor Open interface.
func (e *PrepareExec) Open() error {
return nil
}
// DoPrepare prepares the statement, it can be called multiple times without
// side effect.
func (e *PrepareExec) DoPrepare() {
vars := e.Ctx.GetSessionVars()
if e.ID != 0 {
// Must be the case when we retry a prepare.
// Make sure it is idempotent.
_, ok := vars.PreparedStmts[e.ID]
if ok {
return
}
}
charset, collation := vars.GetCharsetInfo()
var (
stmts []ast.StmtNode
err error
)
if sqlParser, ok := e.Ctx.(sqlexec.SQLParser); ok {
stmts, err = sqlParser.ParseSQL(e.SQLText, charset, collation)
} else {
stmts, err = parser.New().Parse(e.SQLText, charset, collation)
}
if err != nil {
e.Err = errors.Trace(err)
return
}
if len(stmts) != 1 {
e.Err = errors.Trace(ErrPrepareMulti)
return
}
stmt := stmts[0]
if _, ok := stmt.(ast.DDLNode); ok {
e.Err = errors.Trace(ErrPrepareDDL)
return
}
var extractor paramMarkerExtractor
stmt.Accept(&extractor)
err = plan.Preprocess(stmt, e.IS, e.Ctx)
if err != nil {
e.Err = errors.Trace(err)
return
}
if result, ok := stmt.(ast.ResultSetNode); ok {
e.Fields = result.GetResultFields()
}
// The parameter markers are appended in visiting order, which may not
// be the same as the position order in the query string. We need to
// sort it by position.
sorter := ¶mMarkerSorter{markers: extractor.markers}
sort.Sort(sorter)
e.ParamCount = len(sorter.markers)
prepared := &Prepared{
Stmt: stmt,
Params: sorter.markers,
SchemaVersion: e.IS.SchemaMetaVersion(),
}
err = plan.PrepareStmt(e.IS, e.Ctx, stmt)
if err != nil {
e.Err = errors.Trace(err)
return
}
if e.ID == 0 {
e.ID = vars.GetNextPreparedStmtID()
}
if e.Name != "" {
vars.PreparedStmtNameToID[e.Name] = e.ID
}
vars.PreparedStmts[e.ID] = prepared
}
// ExecuteExec represents an EXECUTE executor.
// It cannot be executed by itself, all it needs to do is to build
// another Executor from a prepared statement.
type ExecuteExec struct {
IS infoschema.InfoSchema
Ctx context.Context
Name string
UsingVars []expression.Expression
ID uint32
StmtExec Executor
Stmt ast.StmtNode
Plan plan.Plan
}
// Schema implements the Executor Schema interface.
func (e *ExecuteExec) Schema() *expression.Schema {
// Will never be called.
return expression.NewSchema()
}
// Next implements the Executor Next interface.
func (e *ExecuteExec) Next() (Row, error) {
// Will never be called.
return nil, nil
}
// Open implements the Executor Open interface.
func (e *ExecuteExec) Open() error {
return nil
}
// Close implements Executor Close interface.
func (e *ExecuteExec) Close() error {
// Will never be called.
return nil
}
// Build builds a prepared statement into an executor.
// After Build, e.StmtExec will be used to do the real execution.
func (e *ExecuteExec) Build() error {
vars := e.Ctx.GetSessionVars()
if e.Name != "" {
e.ID = vars.PreparedStmtNameToID[e.Name]
}
v := vars.PreparedStmts[e.ID]
if v == nil {
return errors.Trace(ErrStmtNotFound)
}
prepared := v.(*Prepared)
if len(prepared.Params) != len(e.UsingVars) {
return errors.Trace(ErrWrongParamCount)
}
for i, usingVar := range e.UsingVars {
val, err := usingVar.Eval(nil)
if err != nil {
return errors.Trace(err)
}
prepared.Params[i].SetDatum(val)
}
if prepared.SchemaVersion != e.IS.SchemaMetaVersion() {
// If the schema version has changed we need to prepare it again,
// if this time it failed, the real reason for the error is schema changed.
err := plan.PrepareStmt(e.IS, e.Ctx, prepared.Stmt)
if err != nil {
return ErrSchemaChanged.Gen("Schema change caused error: %s", err.Error())
}
prepared.SchemaVersion = e.IS.SchemaMetaVersion()
}
p, err := plan.Optimize(e.Ctx, prepared.Stmt, e.IS)
if err != nil {
return errors.Trace(err)
}
if IsPointGetWithPKOrUniqueKeyByAutoCommit(e.Ctx, p) {
err = e.Ctx.InitTxnWithStartTS(math.MaxUint64)
} else {
err = e.Ctx.ActivePendingTxn()
}
if err != nil {
return errors.Trace(err)
}
b := newExecutorBuilder(e.Ctx, e.IS, kv.PriorityNormal)
stmtExec := b.build(p)
if b.err != nil {
return errors.Trace(b.err)
}
e.StmtExec = stmtExec
e.Stmt = prepared.Stmt
e.Plan = p
ResetStmtCtx(e.Ctx, e.Stmt)
stmtCount(e.Stmt, e.Plan, e.Ctx.GetSessionVars().InRestrictedSQL)
return nil
}
// DeallocateExec represent a DEALLOCATE executor.
type DeallocateExec struct {
Name string
ctx context.Context
}
// Schema implements the Executor Schema interface.
func (e *DeallocateExec) Schema() *expression.Schema {
// Will never be called.
return expression.NewSchema()
}
// Next implements the Executor Next interface.
func (e *DeallocateExec) Next() (Row, error) {
vars := e.ctx.GetSessionVars()
id, ok := vars.PreparedStmtNameToID[e.Name]
if !ok {
return nil, errors.Trace(ErrStmtNotFound)
}
delete(vars.PreparedStmtNameToID, e.Name)
delete(vars.PreparedStmts, id)
return nil, nil
}
// Close implements Executor Close interface.
func (e *DeallocateExec) Close() error {
return nil
}
// Open implements Executor Open interface.
func (e *DeallocateExec) Open() error {
return nil
}
// CompileExecutePreparedStmt compiles a session Execute command to a stmt.Statement.
func CompileExecutePreparedStmt(ctx context.Context, ID uint32, args ...interface{}) ast.Statement {
execPlan := &plan.Execute{ExecID: ID}
execPlan.UsingVars = make([]expression.Expression, len(args))
for i, val := range args {
value := ast.NewValueExpr(val)
execPlan.UsingVars[i] = &expression.Constant{Value: value.Datum, RetType: &value.Type}
}
stmt := &ExecStmt{
InfoSchema: GetInfoSchema(ctx),
Plan: execPlan,
}
if prepared, ok := ctx.GetSessionVars().PreparedStmts[ID].(*Prepared); ok {
stmt.Text = prepared.Stmt.Text()
}
return stmt
}
// ResetStmtCtx resets the StmtContext.
// Before every execution, we must clear statement context.
func ResetStmtCtx(ctx context.Context, s ast.StmtNode) {
sessVars := ctx.GetSessionVars()
sc := new(variable.StatementContext)
sc.TimeZone = sessVars.GetTimeZone()
switch stmt := s.(type) {
case *ast.UpdateStmt:
sc.IgnoreTruncate = false
sc.OverflowAsWarning = false
sc.TruncateAsWarning = !sessVars.StrictSQLMode || stmt.IgnoreErr
sc.InUpdateOrDeleteStmt = true
sc.DividedByZeroAsWarning = stmt.IgnoreErr
sc.IgnoreZeroInDate = !sessVars.StrictSQLMode || stmt.IgnoreErr
case *ast.DeleteStmt:
sc.IgnoreTruncate = false
sc.OverflowAsWarning = false
sc.TruncateAsWarning = !sessVars.StrictSQLMode || stmt.IgnoreErr
sc.InUpdateOrDeleteStmt = true
sc.DividedByZeroAsWarning = stmt.IgnoreErr
sc.IgnoreZeroInDate = !sessVars.StrictSQLMode || stmt.IgnoreErr
case *ast.InsertStmt:
sc.IgnoreTruncate = false
sc.TruncateAsWarning = !sessVars.StrictSQLMode || stmt.IgnoreErr
sc.InInsertStmt = true
sc.DividedByZeroAsWarning = stmt.IgnoreErr
sc.IgnoreZeroInDate = !sessVars.StrictSQLMode || stmt.IgnoreErr
case *ast.CreateTableStmt, *ast.AlterTableStmt:
// Make sure the sql_mode is strict when checking column default value.
sc.IgnoreTruncate = false
sc.OverflowAsWarning = false
sc.TruncateAsWarning = false
case *ast.LoadDataStmt:
sc.IgnoreTruncate = false
sc.OverflowAsWarning = false
sc.TruncateAsWarning = !sessVars.StrictSQLMode
case *ast.SelectStmt:
sc.InSelectStmt = true
// see https://dev.mysql.com/doc/refman/5.7/en/sql-mode.html#sql-mode-strict
// said "For statements such as SELECT that do not change data, invalid values
// generate a warning in strict mode, not an error."
// and https://dev.mysql.com/doc/refman/5.7/en/out-of-range-and-overflow.html
sc.OverflowAsWarning = true
// Return warning for truncate error in selection.
sc.IgnoreTruncate = false
sc.TruncateAsWarning = true
sc.IgnoreZeroInDate = true
if opts := stmt.SelectStmtOpts; opts != nil {
sc.Priority = opts.Priority
sc.NotFillCache = !opts.SQLCache
}
default:
sc.IgnoreTruncate = true
sc.OverflowAsWarning = false
if show, ok := s.(*ast.ShowStmt); ok {
if show.Tp == ast.ShowWarnings {
sc.InShowWarning = true
sc.SetWarnings(sessVars.StmtCtx.GetWarnings())
}
}
sc.IgnoreZeroInDate = true
}
if sessVars.LastInsertID > 0 {
sessVars.PrevLastInsertID = sessVars.LastInsertID
sessVars.LastInsertID = 0
}
sessVars.InsertID = 0
sessVars.StmtCtx = sc
}