/
driver_tidb.go
453 lines (408 loc) · 14 KB
/
driver_tidb.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
// 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,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package server
import (
"context"
"crypto/tls"
"fmt"
"strings"
"github.com/pingcap/errors"
"github.com/pingcap/tidb/pkg/bindinfo"
"github.com/pingcap/tidb/pkg/expression"
"github.com/pingcap/tidb/pkg/extension"
"github.com/pingcap/tidb/pkg/kv"
"github.com/pingcap/tidb/pkg/parser/ast"
"github.com/pingcap/tidb/pkg/parser/mysql"
"github.com/pingcap/tidb/pkg/parser/terror"
"github.com/pingcap/tidb/pkg/planner/core"
servererr "github.com/pingcap/tidb/pkg/server/err"
"github.com/pingcap/tidb/pkg/server/internal/column"
"github.com/pingcap/tidb/pkg/server/internal/resultset"
"github.com/pingcap/tidb/pkg/session"
sessiontypes "github.com/pingcap/tidb/pkg/session/types"
"github.com/pingcap/tidb/pkg/sessionctx"
"github.com/pingcap/tidb/pkg/sessionctx/sessionstates"
"github.com/pingcap/tidb/pkg/util/chunk"
contextutil "github.com/pingcap/tidb/pkg/util/context"
"github.com/pingcap/tidb/pkg/util/sqlexec"
"github.com/pingcap/tidb/pkg/util/topsql/stmtstats"
)
// TiDBDriver implements IDriver.
type TiDBDriver struct {
store kv.Storage
}
// NewTiDBDriver creates a new TiDBDriver.
func NewTiDBDriver(store kv.Storage) *TiDBDriver {
driver := &TiDBDriver{
store: store,
}
return driver
}
// TiDBContext implements QueryCtx.
type TiDBContext struct {
sessiontypes.Session
stmts map[int]*TiDBStatement
}
// TiDBStatement implements PreparedStatement.
type TiDBStatement struct {
id uint32
numParams int
boundParams [][]byte
paramsType []byte
ctx *TiDBContext
// this result set should have been closed before stored here. Only the `rowIterator` are used here. This field is
// not moved out to reuse the logic inside functions `writeResultSet...`
// TODO: move the `fetchedRows` into the statement, and remove the `ResultSet` from statement.
rs resultset.CursorResultSet
// the `rowContainer` should contain all pre-fetched results of the statement in `EXECUTE` command.
// it's stored here to be closed in RESET and CLOSE command
rowContainer *chunk.RowContainer
sql string
hasActiveCursor bool
}
// ID implements PreparedStatement ID method.
func (ts *TiDBStatement) ID() int {
return int(ts.id)
}
// Execute implements PreparedStatement Execute method.
func (ts *TiDBStatement) Execute(ctx context.Context, args []expression.Expression) (rs resultset.ResultSet, err error) {
tidbRecordset, err := ts.ctx.ExecutePreparedStmt(ctx, ts.id, args)
if err != nil {
return nil, err
}
if tidbRecordset == nil {
return
}
rs = resultset.New(tidbRecordset, ts.ctx.GetSessionVars().PreparedStmts[ts.id].(*core.PlanCacheStmt))
return
}
// AppendParam implements PreparedStatement AppendParam method.
func (ts *TiDBStatement) AppendParam(paramID int, data []byte) error {
if paramID >= len(ts.boundParams) {
return mysql.NewErr(mysql.ErrWrongArguments, "stmt_send_longdata")
}
// If len(data) is 0, append an empty byte slice to the end to distinguish no data and no parameter.
if len(data) == 0 {
ts.boundParams[paramID] = []byte{}
} else {
ts.boundParams[paramID] = append(ts.boundParams[paramID], data...)
}
return nil
}
// NumParams implements PreparedStatement NumParams method.
func (ts *TiDBStatement) NumParams() int {
return ts.numParams
}
// BoundParams implements PreparedStatement BoundParams method.
func (ts *TiDBStatement) BoundParams() [][]byte {
return ts.boundParams
}
// SetParamsType implements PreparedStatement SetParamsType method.
func (ts *TiDBStatement) SetParamsType(paramsType []byte) {
ts.paramsType = paramsType
}
// GetParamsType implements PreparedStatement GetParamsType method.
func (ts *TiDBStatement) GetParamsType() []byte {
return ts.paramsType
}
// StoreResultSet stores ResultSet for stmt fetching
func (ts *TiDBStatement) StoreResultSet(rs resultset.CursorResultSet) {
// the original reset set should have been closed, and it's only used to store the iterator through the rowContainer
// so it's fine to just overwrite it.
ts.rs = rs
}
// GetResultSet gets ResultSet associated this statement
func (ts *TiDBStatement) GetResultSet() resultset.CursorResultSet {
return ts.rs
}
// Reset implements PreparedStatement Reset method.
func (ts *TiDBStatement) Reset() error {
for i := range ts.boundParams {
ts.boundParams[i] = nil
}
ts.hasActiveCursor = false
if ts.rs != nil && ts.rs.GetRowContainerReader() != nil {
ts.rs.GetRowContainerReader().Close()
}
ts.rs = nil
if ts.rowContainer != nil {
ts.rowContainer.GetMemTracker().Detach()
ts.rowContainer.GetDiskTracker().Detach()
rc := ts.rowContainer
ts.rowContainer = nil
err := rc.Close()
if err != nil {
return err
}
}
return nil
}
// Close implements PreparedStatement Close method.
func (ts *TiDBStatement) Close() error {
if ts.rs != nil && ts.rs.GetRowContainerReader() != nil {
ts.rs.GetRowContainerReader().Close()
}
if ts.rowContainer != nil {
ts.rowContainer.GetMemTracker().Detach()
ts.rowContainer.GetDiskTracker().Detach()
err := ts.rowContainer.Close()
if err != nil {
return err
}
}
// TODO close at tidb level
if ts.ctx.GetSessionVars().TxnCtx != nil && ts.ctx.GetSessionVars().TxnCtx.CouldRetry {
err := ts.ctx.DropPreparedStmt(ts.id)
if err != nil {
return err
}
} else {
if ts.ctx.GetSessionVars().EnablePreparedPlanCache {
preparedPointer := ts.ctx.GetSessionVars().PreparedStmts[ts.id]
preparedObj, ok := preparedPointer.(*core.PlanCacheStmt)
if !ok {
return errors.Errorf("invalid PlanCacheStmt type")
}
bindSQL, _ := bindinfo.MatchSQLBindingForPlanCache(ts.ctx, preparedObj.PreparedAst.Stmt, &preparedObj.BindingInfo)
cacheKey, err := core.NewPlanCacheKey(ts.ctx.GetSessionVars(), preparedObj.StmtText, preparedObj.StmtDB,
preparedObj.SchemaVersion, 0, bindSQL, expression.ExprPushDownBlackListReloadTimeStamp.Load(), preparedObj.RelateVersion)
if err != nil {
return err
}
if !ts.ctx.GetSessionVars().IgnorePreparedCacheCloseStmt { // keep the plan in cache
ts.ctx.GetSessionPlanCache().Delete(cacheKey)
}
}
ts.ctx.GetSessionVars().RemovePreparedStmt(ts.id)
}
delete(ts.ctx.stmts, int(ts.id))
return nil
}
// GetCursorActive implements PreparedStatement GetCursorActive method.
func (ts *TiDBStatement) GetCursorActive() bool {
return ts.hasActiveCursor
}
// SetCursorActive implements PreparedStatement SetCursorActive method.
func (ts *TiDBStatement) SetCursorActive(fetchEnd bool) {
ts.hasActiveCursor = fetchEnd
}
// StoreRowContainer stores a row container into the prepared statement
func (ts *TiDBStatement) StoreRowContainer(c *chunk.RowContainer) {
ts.rowContainer = c
}
// GetRowContainer returns the row container of the statement
func (ts *TiDBStatement) GetRowContainer() *chunk.RowContainer {
return ts.rowContainer
}
// OpenCtx implements IDriver.
func (qd *TiDBDriver) OpenCtx(connID uint64, capability uint32, collation uint8, _ string,
tlsState *tls.ConnectionState, extensions *extension.SessionExtensions) (*TiDBContext, error) {
se, err := session.CreateSession(qd.store)
if err != nil {
return nil, err
}
se.SetTLSState(tlsState)
err = se.SetCollation(int(collation))
if err != nil {
return nil, err
}
se.SetClientCapability(capability)
se.SetConnectionID(connID)
tc := &TiDBContext{
Session: se,
stmts: make(map[int]*TiDBStatement),
}
se.SetSessionStatesHandler(sessionstates.StatePrepareStmt, tc)
se.SetExtensions(extensions)
return tc, nil
}
// GetWarnings implements QueryCtx GetWarnings method.
func (tc *TiDBContext) GetWarnings() []contextutil.SQLWarn {
return tc.GetSessionVars().StmtCtx.GetWarnings()
}
// WarningCount implements QueryCtx WarningCount method.
func (tc *TiDBContext) WarningCount() uint16 {
return tc.GetSessionVars().StmtCtx.WarningCount()
}
func (tc *TiDBContext) checkSandBoxMode(stmt ast.StmtNode) error {
if !tc.Session.GetSessionVars().InRestrictedSQL && tc.InSandBoxMode() {
switch stmt.(type) {
case *ast.SetPwdStmt, *ast.AlterUserStmt:
default:
return servererr.ErrMustChangePassword.GenWithStackByArgs()
}
}
return nil
}
// ExecuteStmt implements QueryCtx interface.
func (tc *TiDBContext) ExecuteStmt(ctx context.Context, stmt ast.StmtNode) (resultset.ResultSet, error) {
var rs sqlexec.RecordSet
var err error
if err = tc.checkSandBoxMode(stmt); err != nil {
return nil, err
}
if s, ok := stmt.(*ast.NonTransactionalDMLStmt); ok {
rs, err = session.HandleNonTransactionalDML(ctx, s, tc.Session)
} else {
rs, err = tc.Session.ExecuteStmt(ctx, stmt)
}
if err != nil {
tc.Session.GetSessionVars().StmtCtx.AppendError(err)
return nil, err
}
if rs == nil {
return nil, nil
}
return resultset.New(rs, nil), nil
}
// Close implements QueryCtx Close method.
func (tc *TiDBContext) Close() error {
// close PreparedStatement associated with this connection
for _, v := range tc.stmts {
terror.Call(v.Close)
}
tc.Session.Close()
return nil
}
// FieldList implements QueryCtx FieldList method.
func (tc *TiDBContext) FieldList(table string) (columns []*column.Info, err error) {
fields, err := tc.Session.FieldList(table)
if err != nil {
return nil, err
}
columns = make([]*column.Info, 0, len(fields))
for _, f := range fields {
columns = append(columns, column.ConvertColumnInfo(f))
}
return columns, nil
}
// GetStatement implements QueryCtx GetStatement method.
func (tc *TiDBContext) GetStatement(stmtID int) PreparedStatement {
tcStmt := tc.stmts[stmtID]
if tcStmt != nil {
return tcStmt
}
return nil
}
// Prepare implements QueryCtx Prepare method.
func (tc *TiDBContext) Prepare(sql string) (statement PreparedStatement, columns, params []*column.Info, err error) {
stmtID, paramCount, fields, err := tc.Session.PrepareStmt(sql)
if err != nil {
return
}
stmt := &TiDBStatement{
sql: sql,
id: stmtID,
numParams: paramCount,
boundParams: make([][]byte, paramCount),
ctx: tc,
}
statement = stmt
columns = make([]*column.Info, len(fields))
for i := range fields {
columns[i] = column.ConvertColumnInfo(fields[i])
}
params = make([]*column.Info, paramCount)
for i := range params {
params[i] = &column.Info{
Type: mysql.TypeBlob,
}
}
tc.stmts[int(stmtID)] = stmt
return
}
// GetStmtStats implements the sessionctx.Context interface.
func (tc *TiDBContext) GetStmtStats() *stmtstats.StatementStats {
return tc.Session.GetStmtStats()
}
// EncodeSessionStates implements SessionStatesHandler.EncodeSessionStates interface.
func (tc *TiDBContext) EncodeSessionStates(_ context.Context, _ sessionctx.Context, sessionStates *sessionstates.SessionStates) error {
sessionVars := tc.Session.GetSessionVars()
sessionStates.PreparedStmts = make(map[uint32]*sessionstates.PreparedStmtInfo, len(sessionVars.PreparedStmts))
for preparedID, preparedObj := range sessionVars.PreparedStmts {
preparedStmt, ok := preparedObj.(*core.PlanCacheStmt)
if !ok {
return errors.Errorf("invalid PlanCacheStmt type")
}
sessionStates.PreparedStmts[preparedID] = &sessionstates.PreparedStmtInfo{
StmtText: preparedStmt.StmtText,
StmtDB: preparedStmt.StmtDB,
}
}
for name, id := range sessionVars.PreparedStmtNameToID {
// Only text protocol statements have names.
if preparedStmtInfo, ok := sessionStates.PreparedStmts[id]; ok {
preparedStmtInfo.Name = name
}
}
for id, stmt := range tc.stmts {
// Only binary protocol statements have paramTypes.
preparedStmtInfo, ok := sessionStates.PreparedStmts[uint32(id)]
if !ok {
return errors.Errorf("prepared statement %d not found", id)
}
// Bound params are sent by CMD_STMT_SEND_LONG_DATA, the proxy can wait for COM_STMT_EXECUTE.
for _, boundParam := range stmt.BoundParams() {
if boundParam != nil {
return sessionstates.ErrCannotMigrateSession.GenWithStackByArgs("prepared statements have bound params")
}
}
if stmt.GetCursorActive() {
return sessionstates.ErrCannotMigrateSession.GenWithStackByArgs("prepared statements have unfetched rows")
}
preparedStmtInfo.ParamTypes = stmt.GetParamsType()
}
return nil
}
// DecodeSessionStates implements SessionStatesHandler.DecodeSessionStates interface.
func (tc *TiDBContext) DecodeSessionStates(ctx context.Context, _ sessionctx.Context, sessionStates *sessionstates.SessionStates) error {
if len(sessionStates.PreparedStmts) == 0 {
return nil
}
sessionVars := tc.Session.GetSessionVars()
savedPreparedStmtID := sessionVars.GetNextPreparedStmtID()
savedCurrentDB := sessionVars.CurrentDB
defer func() {
sessionVars.SetNextPreparedStmtID(savedPreparedStmtID - 1)
sessionVars.CurrentDB = savedCurrentDB
}()
for id, preparedStmtInfo := range sessionStates.PreparedStmts {
// Set the next id and currentDB manually.
sessionVars.SetNextPreparedStmtID(id - 1)
sessionVars.CurrentDB = preparedStmtInfo.StmtDB
if preparedStmtInfo.Name == "" {
// Binary protocol: add to sessionVars.PreparedStmts and TiDBContext.stmts.
stmt, _, _, err := tc.Prepare(preparedStmtInfo.StmtText)
if err != nil {
return err
}
// Only binary protocol uses paramsType, which is passed from the first COM_STMT_EXECUTE.
stmt.SetParamsType(preparedStmtInfo.ParamTypes)
} else {
// Text protocol: add to sessionVars.PreparedStmts and sessionVars.PreparedStmtNameToID.
stmtText := strings.ReplaceAll(preparedStmtInfo.StmtText, "\\", "\\\\")
stmtText = strings.ReplaceAll(stmtText, "'", "\\'")
// Add single quotes because the sql_mode might contain ANSI_QUOTES.
sql := fmt.Sprintf("PREPARE `%s` FROM '%s'", preparedStmtInfo.Name, stmtText)
stmts, err := tc.Parse(ctx, sql)
if err != nil {
return err
}
if _, err = tc.ExecuteStmt(ctx, stmts[0]); err != nil {
return err
}
}
}
return nil
}