-
Notifications
You must be signed in to change notification settings - Fork 526
/
tidb.go
327 lines (294 loc) · 9.24 KB
/
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
// Copyright 2013 The ql Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSES/QL-LICENSE file.
// 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 session
import (
"context"
"sync"
"sync/atomic"
"time"
"github.com/pingcap/errors"
"github.com/pingcap/tidb/domain"
"github.com/pingcap/tidb/executor"
"github.com/pingcap/tidb/kv"
"github.com/pingcap/tidb/parser"
"github.com/pingcap/tidb/parser/ast"
"github.com/pingcap/tidb/parser/mysql"
"github.com/pingcap/tidb/parser/terror"
"github.com/pingcap/tidb/sessionctx"
"github.com/pingcap/tidb/sessionctx/variable"
"github.com/pingcap/tidb/util"
"github.com/pingcap/tidb/util/chunk"
"github.com/pingcap/tidb/util/logutil"
"github.com/pingcap/tidb/util/sqlexec"
"go.uber.org/zap"
)
type domainMap struct {
domains map[string]*domain.Domain
mu sync.Mutex
}
func (dm *domainMap) Get(store kv.Storage) (d *domain.Domain, err error) {
dm.mu.Lock()
defer dm.mu.Unlock()
// If this is the only domain instance, and the caller doesn't provide store.
if len(dm.domains) == 1 && store == nil {
for _, r := range dm.domains {
return r, nil
}
}
key := store.UUID()
d = dm.domains[key]
if d != nil {
return
}
ddlLease := time.Duration(atomic.LoadInt64(&schemaLease))
statisticLease := time.Duration(atomic.LoadInt64(&statsLease))
err = util.RunWithRetry(util.DefaultMaxRetries, util.RetryInterval, func() (retry bool, err1 error) {
logutil.BgLogger().Info("new domain",
zap.String("store", store.UUID()),
zap.Stringer("ddl lease", ddlLease),
zap.Stringer("stats lease", statisticLease))
factory := createSessionFunc(store)
sysFactory := createSessionWithDomainFunc(store)
d = domain.NewDomain(store, ddlLease, statisticLease, factory)
err1 = d.Init(ddlLease, sysFactory)
if err1 != nil {
// If we don't clean it, there are some dirty data when retrying the function of Init.
d.Close()
logutil.BgLogger().Error("[ddl] init domain failed",
zap.Error(err1))
}
return true, err1
})
if err != nil {
return nil, err
}
dm.domains[key] = d
return
}
func (dm *domainMap) Delete(store kv.Storage) {
dm.mu.Lock()
delete(dm.domains, store.UUID())
dm.mu.Unlock()
}
var (
domap = &domainMap{
domains: map[string]*domain.Domain{},
}
// store.UUID()-> IfBootstrapped
storeBootstrapped = make(map[string]bool)
storeBootstrappedLock sync.Mutex
// schemaLease is the time for re-updating remote schema.
// In online DDL, we must wait 2 * SchemaLease time to guarantee
// all servers get the neweset schema.
// Default schema lease time is 1 second, you can change it with a proper time,
// but you must know that too little may cause badly performance degradation.
// For production, you should set a big schema lease, like 300s+.
schemaLease = int64(1 * time.Second)
// statsLease is the time for reload stats table.
statsLease = int64(3 * time.Second)
)
func setStoreBootstrapped(storeUUID string) {
storeBootstrappedLock.Lock()
defer storeBootstrappedLock.Unlock()
storeBootstrapped[storeUUID] = true
}
// SetSchemaLease changes the default schema lease time for DDL.
// This function is very dangerous, don't use it if you really know what you do.
// SetSchemaLease only affects not local storage after bootstrapped.
func SetSchemaLease(lease time.Duration) {
atomic.StoreInt64(&schemaLease, int64(lease))
}
// SetStatsLease changes the default stats lease time for loading stats info.
func SetStatsLease(lease time.Duration) {
atomic.StoreInt64(&statsLease, int64(lease))
}
// DisableStats4Test disables the stats for tests.
func DisableStats4Test() {
SetStatsLease(-1)
}
// Parse parses a query string to raw ast.StmtNode.
func Parse(ctx sessionctx.Context, src string) ([]ast.StmtNode, error) {
logutil.BgLogger().Debug("compiling", zap.String("source", src))
charset, collation := ctx.GetSessionVars().GetCharsetInfo()
p := parser.New()
p.SetSQLMode(ctx.GetSessionVars().SQLMode)
stmts, warns, err := p.Parse(src, charset, collation)
for _, warn := range warns {
ctx.GetSessionVars().StmtCtx.AppendWarning(warn)
}
if err != nil {
logutil.BgLogger().Warn("compiling",
zap.String("source", src),
zap.Error(err))
return nil, err
}
return stmts, nil
}
// Compile is safe for concurrent use by multiple goroutines.
func Compile(ctx context.Context, sctx sessionctx.Context, stmtNode ast.StmtNode) (sqlexec.Statement, error) {
compiler := executor.Compiler{Ctx: sctx}
stmt, err := compiler.Compile(ctx, stmtNode)
return stmt, err
}
func finishStmt(ctx context.Context, sctx sessionctx.Context, se *session, sessVars *variable.SessionVars,
meetsErr error, sql sqlexec.Statement) error {
if meetsErr != nil {
if !sessVars.InTxn() {
logutil.BgLogger().Info("rollbackTxn for ddl/autocommit failed")
se.RollbackTxn(ctx)
}
return meetsErr
}
if !sessVars.InTxn() {
if err := se.CommitTxn(ctx); err != nil {
if _, ok := sql.(*executor.ExecStmt).StmtNode.(*ast.CommitStmt); ok {
err = errors.Annotatef(err, "previous statement: %s", se.GetSessionVars().PrevStmt)
}
return err
}
return nil
}
return checkStmtLimit(ctx, sctx, se)
}
func checkStmtLimit(ctx context.Context, sctx sessionctx.Context, se *session) error {
// If the user insert, insert, insert ... but never commit, TiDB would OOM.
// So we limit the statement count in a transaction here.
var err error
history := GetHistory(sctx)
if history.Count() > 5000 {
se.RollbackTxn(ctx)
return errors.Errorf("statement count %d exceeds the transaction limitation, autocommit = %t",
history.Count(), sctx.GetSessionVars().IsAutocommit())
}
return err
}
// runStmt executes the sqlexec.Statement and commit or rollback the current transaction.
func runStmt(ctx context.Context, sctx sessionctx.Context, s sqlexec.Statement) (rs sqlexec.RecordSet, err error) {
se := sctx.(*session)
sessVars := se.GetSessionVars()
defer func() {
// If it is not a select statement, we record its slow log here,
// then it could include the transaction commit time.
if rs == nil {
sessVars.PrevStmt = executor.FormatSQL(s.OriginText())
}
}()
err = se.checkTxnAborted(s)
if err != nil {
return nil, err
}
rs, err = s.Exec(ctx)
sessVars.TxnCtx.StatementCount++
if !s.IsReadOnly() {
// Handle the stmt commit/rollback.
if txn, err1 := sctx.Txn(false); err1 == nil {
if txn.Valid() {
if err != nil {
sctx.StmtRollback()
} else {
err = sctx.StmtCommit()
}
}
} else {
logutil.BgLogger().Error("get txn failed", zap.Error(err1))
}
}
err = finishStmt(ctx, sctx, se, sessVars, err, s)
if se.txn.pending() {
// After run statement finish, txn state is still pending means the
// statement never need a Txn(), such as:
//
// set @@tidb_general_log = 1
// set @@autocommit = 0
// select 1
//
// Reset txn state to invalid to dispose the pending start ts.
se.txn.changeToInvalid()
}
return rs, err
}
// GetHistory get all stmtHistory in current txn. Exported only for test.
func GetHistory(ctx sessionctx.Context) *StmtHistory {
hist, ok := ctx.GetSessionVars().TxnCtx.History.(*StmtHistory)
if ok {
return hist
}
hist = new(StmtHistory)
ctx.GetSessionVars().TxnCtx.History = hist
return hist
}
// GetRows4Test gets all the rows from a RecordSet, only used for test.
func GetRows4Test(ctx context.Context, sctx sessionctx.Context, rs sqlexec.RecordSet) ([]chunk.Row, error) {
if rs == nil {
return nil, nil
}
var rows []chunk.Row
req := rs.NewChunk()
// Must reuse `req` for imitating server.(*clientConn).writeChunks
for {
err := rs.Next(ctx, req)
if err != nil {
return nil, err
}
if req.NumRows() == 0 {
break
}
iter := chunk.NewIterator4Chunk(req.CopyConstruct())
for row := iter.Begin(); row != iter.End(); row = iter.Next() {
rows = append(rows, row)
}
}
return rows, nil
}
// ResultSetToStringSlice changes the RecordSet to [][]string.
func ResultSetToStringSlice(ctx context.Context, s Session, rs sqlexec.RecordSet) ([][]string, error) {
rows, err := GetRows4Test(ctx, s, rs)
if err != nil {
return nil, err
}
err = rs.Close()
if err != nil {
return nil, err
}
sRows := make([][]string, len(rows))
for i := range rows {
row := rows[i]
iRow := make([]string, row.Len())
for j := 0; j < row.Len(); j++ {
if row.IsNull(j) {
iRow[j] = "<nil>"
} else {
d := row.GetDatum(j, &rs.Fields()[j].Column.FieldType)
iRow[j], err = d.ToString()
if err != nil {
return nil, err
}
}
}
sRows[i] = iRow
}
return sRows, nil
}
// Session errors.
var (
ErrForUpdateCantRetry = terror.ClassSession.New(mysql.ErrForUpdateCantRetry, mysql.MySQLErrName[mysql.ErrForUpdateCantRetry])
)
func init() {
sessionMySQLErrCodes := map[terror.ErrCode]uint16{
mysql.ErrForUpdateCantRetry: mysql.ErrForUpdateCantRetry,
}
terror.ErrClassToMySQLCodes[terror.ClassSession] = sessionMySQLErrCodes
}