forked from pingcap/tidb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
session.go
1536 lines (1375 loc) · 43.5 KB
/
session.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
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// 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 tidb
import (
"crypto/tls"
"encoding/json"
"fmt"
"net"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/juju/errors"
"github.com/ngaut/pools"
"github.com/opentracing/opentracing-go"
"github.com/pingcap/tidb/ast"
"github.com/pingcap/tidb/context"
"github.com/pingcap/tidb/domain"
"github.com/pingcap/tidb/executor"
"github.com/pingcap/tidb/kv"
"github.com/pingcap/tidb/meta"
"github.com/pingcap/tidb/model"
"github.com/pingcap/tidb/mysql"
"github.com/pingcap/tidb/parser"
"github.com/pingcap/tidb/plan"
"github.com/pingcap/tidb/privilege"
"github.com/pingcap/tidb/privilege/privileges"
"github.com/pingcap/tidb/sessionctx/binloginfo"
"github.com/pingcap/tidb/sessionctx/stmtctx"
"github.com/pingcap/tidb/sessionctx/variable"
"github.com/pingcap/tidb/statistics"
"github.com/pingcap/tidb/store/tikv/oracle"
"github.com/pingcap/tidb/terror"
"github.com/pingcap/tidb/types"
"github.com/pingcap/tidb/util"
"github.com/pingcap/tidb/util/auth"
"github.com/pingcap/tidb/util/charset"
"github.com/pingcap/tidb/util/kvcache"
"github.com/pingcap/tipb/go-binlog"
log "github.com/sirupsen/logrus"
goctx "golang.org/x/net/context"
)
// Session context
type Session interface {
context.Context
Status() uint16 // Flag of current status, such as autocommit.
LastInsertID() uint64 // LastInsertID is the last inserted auto_increment ID.
AffectedRows() uint64 // Affected rows by latest executed stmt.
Execute(goctx.Context, string) ([]ast.RecordSet, error) // Execute a sql statement.
String() string // String is used to debug.
CommitTxn(goctx.Context) error
RollbackTxn(goctx.Context) error
// PrepareStmt executes prepare statement in binary protocol.
PrepareStmt(sql string) (stmtID uint32, paramCount int, fields []*ast.ResultField, err error)
// ExecutePreparedStmt executes a prepared statement.
ExecutePreparedStmt(goCtx goctx.Context, stmtID uint32, param ...interface{}) (ast.RecordSet, error)
DropPreparedStmt(stmtID uint32) error
SetClientCapability(uint32) // Set client capability flags.
SetConnectionID(uint64)
SetTLSState(*tls.ConnectionState)
SetCollation(coID int) error
SetSessionManager(util.SessionManager)
Close()
Auth(user *auth.UserIdentity, auth []byte, salt []byte) bool
ShowProcess() util.ProcessInfo
// PrePareTxnCtx is exported for test.
PrepareTxnCtx(goctx.Context)
// FieldList returns fields list of a table.
FieldList(tableName string) (fields []*ast.ResultField, err error)
}
var (
_ Session = (*session)(nil)
)
type stmtRecord struct {
stmtID uint32
st ast.Statement
stmtCtx *stmtctx.StatementContext
params []interface{}
}
// StmtHistory holds all histories of statements in a txn.
type StmtHistory struct {
history []*stmtRecord
}
// Add appends a stmt to history list.
func (h *StmtHistory) Add(stmtID uint32, st ast.Statement, stmtCtx *stmtctx.StatementContext, params ...interface{}) {
s := &stmtRecord{
stmtID: stmtID,
st: st,
stmtCtx: stmtCtx,
params: append(([]interface{})(nil), params...),
}
h.history = append(h.history, s)
}
// Count returns the count of the history.
func (h *StmtHistory) Count() int {
return len(h.history)
}
type session struct {
// processInfo is used by ShowProcess(), and should be modified atomically.
processInfo atomic.Value
// TODO: Make txnFuture into StmtTxn to optimize the txn representation, avoid
// the ugly code like if s.Transaction == nil || s.Transaction.Valid()
StmtTxn
txnFuture *txnFuture
mu struct {
sync.RWMutex
values map[fmt.Stringer]interface{}
}
store kv.Storage
parser *parser.Parser
preparedPlanCache *kvcache.SimpleLRUCache
sessionVars *variable.SessionVars
sessionManager util.SessionManager
statsCollector *statistics.SessionStatsCollector
}
func (s *session) getMembufCap() int {
if s.sessionVars.ImportingData {
return kv.ImportingTxnMembufCap
}
return kv.DefaultTxnMembufCap
}
func (s *session) cleanRetryInfo() {
if !s.sessionVars.RetryInfo.Retrying {
retryInfo := s.sessionVars.RetryInfo
for _, stmtID := range retryInfo.DroppedPreparedStmtIDs {
delete(s.sessionVars.PreparedStmts, stmtID)
}
retryInfo.Clean()
}
}
func (s *session) Status() uint16 {
return s.sessionVars.Status
}
func (s *session) LastInsertID() uint64 {
if s.sessionVars.LastInsertID > 0 {
return s.sessionVars.LastInsertID
}
return s.sessionVars.InsertID
}
func (s *session) AffectedRows() uint64 {
return s.sessionVars.StmtCtx.AffectedRows()
}
func (s *session) SetClientCapability(capability uint32) {
s.sessionVars.ClientCapability = capability
}
func (s *session) SetConnectionID(connectionID uint64) {
s.sessionVars.ConnectionID = connectionID
}
func (s *session) SetTLSState(tlsState *tls.ConnectionState) {
// If user is not connected via TLS, then tlsState == nil.
if tlsState != nil {
s.sessionVars.TLSConnectionState = tlsState
}
}
func (s *session) GetTLSState() *tls.ConnectionState {
return s.sessionVars.TLSConnectionState
}
func (s *session) SetCollation(coID int) error {
cs, co, err := charset.GetCharsetInfoByID(coID)
if err != nil {
return errors.Trace(err)
}
for _, v := range variable.SetNamesVariables {
terror.Log(errors.Trace(s.sessionVars.SetSystemVar(v, cs)))
}
terror.Log(errors.Trace(s.sessionVars.SetSystemVar(variable.CollationConnection, co)))
return nil
}
func (s *session) PreparedPlanCache() *kvcache.SimpleLRUCache {
return s.preparedPlanCache
}
func (s *session) SetSessionManager(sm util.SessionManager) {
s.sessionManager = sm
}
func (s *session) GetSessionManager() util.SessionManager {
return s.sessionManager
}
func (s *session) StoreQueryFeedback(feedback interface{}) {
s.statsCollector.StoreQueryFeedback(feedback)
}
// FieldList returns fields list of a table.
func (s *session) FieldList(tableName string) ([]*ast.ResultField, error) {
is := executor.GetInfoSchema(s)
dbName := model.NewCIStr(s.GetSessionVars().CurrentDB)
tName := model.NewCIStr(tableName)
table, err := is.TableByName(dbName, tName)
if err != nil {
return nil, errors.Trace(err)
}
cols := table.Cols()
fields := make([]*ast.ResultField, 0, len(cols))
for _, col := range table.Cols() {
rf := &ast.ResultField{
ColumnAsName: col.Name,
TableAsName: tName,
DBName: dbName,
Table: table.Meta(),
Column: col.ColumnInfo,
}
fields = append(fields, rf)
}
return fields, nil
}
type schemaLeaseChecker struct {
domain.SchemaValidator
schemaVer int64
relatedTableIDs []int64
}
var (
// SchemaOutOfDateRetryInterval is the sleeping time when we fail to try.
SchemaOutOfDateRetryInterval = int64(500 * time.Millisecond)
// SchemaOutOfDateRetryTimes is upper bound of retry times when the schema is out of date.
SchemaOutOfDateRetryTimes = int32(10)
)
func (s *schemaLeaseChecker) Check(txnTS uint64) error {
schemaOutOfDateRetryInterval := atomic.LoadInt64(&SchemaOutOfDateRetryInterval)
schemaOutOfDateRetryTimes := int(atomic.LoadInt32(&SchemaOutOfDateRetryTimes))
for i := 0; i < schemaOutOfDateRetryTimes; i++ {
result := s.SchemaValidator.Check(txnTS, s.schemaVer, s.relatedTableIDs)
switch result {
case domain.ResultSucc:
return nil
case domain.ResultFail:
schemaLeaseErrorCounter.WithLabelValues("changed").Inc()
return domain.ErrInfoSchemaChanged
case domain.ResultUnknown:
schemaLeaseErrorCounter.WithLabelValues("outdated").Inc()
time.Sleep(time.Duration(schemaOutOfDateRetryInterval))
}
}
return domain.ErrInfoSchemaExpired
}
func (s *session) doCommit(ctx goctx.Context) error {
if s.Transaction == nil || !s.Transaction.Valid() {
return nil
}
defer func() {
s.Transaction = nil
s.sessionVars.SetStatusFlag(mysql.ServerStatusInTrans, false)
}()
if s.sessionVars.BinlogClient != nil {
prewriteValue := binloginfo.GetPrewriteValue(s, false)
if prewriteValue != nil {
prewriteData, err := prewriteValue.Marshal()
if err != nil {
return errors.Trace(err)
}
info := &binloginfo.BinlogInfo{
Data: &binlog.Binlog{
Tp: binlog.BinlogType_Prewrite,
PrewriteValue: prewriteData,
},
Client: s.sessionVars.BinlogClient.(binlog.PumpClient),
}
s.Transaction.SetOption(kv.BinlogInfo, info)
}
}
// Get the related table IDs.
relatedTables := s.GetSessionVars().TxnCtx.TableDeltaMap
tableIDs := make([]int64, 0, len(relatedTables))
for id := range relatedTables {
tableIDs = append(tableIDs, id)
}
// Set this option for 2 phase commit to validate schema lease.
s.Transaction.SetOption(kv.SchemaLeaseChecker, &schemaLeaseChecker{
SchemaValidator: domain.GetDomain(s).SchemaValidator,
schemaVer: s.sessionVars.TxnCtx.SchemaVersion,
relatedTableIDs: tableIDs,
})
if err := s.Transaction.Commit(ctx); err != nil {
return errors.Trace(err)
}
return nil
}
func (s *session) doCommitWithRetry(ctx goctx.Context) error {
var txnSize int
if s.Transaction != nil && s.Transaction.Valid() {
txnSize = s.Transaction.Size()
}
err := s.doCommit(ctx)
if err != nil {
if s.isRetryableError(err) {
log.Warnf("[%d] retryable error: %v, txn: %v", s.sessionVars.ConnectionID, err, s.Transaction)
// Transactions will retry 2 ~ commitRetryLimit times.
// We make larger transactions retry less times to prevent cluster resource outage.
txnSizeRate := float64(txnSize) / float64(kv.TxnTotalSizeLimit)
maxRetryCount := commitRetryLimit - int(float64(commitRetryLimit-1)*txnSizeRate)
err = s.retry(ctx, maxRetryCount)
}
}
s.cleanRetryInfo()
if err != nil {
log.Warnf("[%d] finished txn:%v, %v", s.sessionVars.ConnectionID, s.Transaction, err)
return errors.Trace(err)
}
mapper := s.GetSessionVars().TxnCtx.TableDeltaMap
if s.statsCollector != nil && mapper != nil {
for id, item := range mapper {
s.statsCollector.Update(id, item.Delta, item.Count)
}
}
return nil
}
func (s *session) CommitTxn(ctx goctx.Context) error {
if span := opentracing.SpanFromContext(ctx); span != nil {
span = opentracing.StartSpan("session.CommitTxn", opentracing.ChildOf(span.Context()))
defer span.Finish()
}
err := s.doCommitWithRetry(ctx)
label := "OK"
if err != nil {
label = "Error"
}
transactionCounter.WithLabelValues(label).Inc()
return errors.Trace(err)
}
func (s *session) RollbackTxn(ctx goctx.Context) error {
if span := opentracing.SpanFromContext(ctx); span != nil {
span = opentracing.StartSpan("session.RollbackTxn", opentracing.ChildOf(span.Context()))
defer span.Finish()
}
var err error
if s.Transaction != nil && s.Transaction.Valid() {
err = s.Transaction.Rollback()
}
s.cleanRetryInfo()
s.Transaction = nil
s.txnFuture = nil
s.sessionVars.SetStatusFlag(mysql.ServerStatusInTrans, false)
return errors.Trace(err)
}
func (s *session) GetClient() kv.Client {
return s.store.GetClient()
}
func (s *session) String() string {
// TODO: how to print binded context in values appropriately?
sessVars := s.sessionVars
data := map[string]interface{}{
"id": sessVars.ConnectionID,
"user": sessVars.User,
"currDBName": sessVars.CurrentDB,
"status": sessVars.Status,
"strictMode": sessVars.StrictSQLMode,
}
if s.Transaction != nil {
// if txn is committed or rolled back, txn is nil.
data["txn"] = s.Transaction.String()
}
if sessVars.SnapshotTS != 0 {
data["snapshotTS"] = sessVars.SnapshotTS
}
if sessVars.LastInsertID > 0 {
data["lastInsertID"] = sessVars.LastInsertID
}
if len(sessVars.PreparedStmts) > 0 {
data["preparedStmtCount"] = len(sessVars.PreparedStmts)
}
b, err := json.MarshalIndent(data, "", " ")
terror.Log(errors.Trace(err))
return string(b)
}
const sqlLogMaxLen = 1024
// SchemaChangedWithoutRetry is used for testing.
var SchemaChangedWithoutRetry bool
func (s *session) isRetryableError(err error) bool {
if SchemaChangedWithoutRetry {
return kv.IsRetryableError(err)
}
return kv.IsRetryableError(err) || domain.ErrInfoSchemaChanged.Equal(err)
}
func (s *session) retry(goCtx goctx.Context, maxCnt int) error {
span, ctx := opentracing.StartSpanFromContext(goCtx, "retry")
defer span.Finish()
connID := s.sessionVars.ConnectionID
if s.sessionVars.TxnCtx.ForUpdate {
return errors.Errorf("[%d] can not retry select for update statement", connID)
}
s.sessionVars.RetryInfo.Retrying = true
retryCnt := 0
defer func() {
s.sessionVars.RetryInfo.Retrying = false
sessionRetry.Observe(float64(retryCnt))
s.Transaction = nil
s.sessionVars.SetStatusFlag(mysql.ServerStatusInTrans, false)
}()
nh := GetHistory(s)
var err error
for {
s.PrepareTxnCtx(ctx)
s.sessionVars.RetryInfo.ResetOffset()
for i, sr := range nh.history {
st := sr.st
if st.IsReadOnly() {
continue
}
err = st.RebuildPlan()
if err != nil {
return errors.Trace(err)
}
if retryCnt == 0 {
// We do not have to log the query every time.
// We print the queries at the first try only.
log.Warnf("[%d] Retry [%d] query [%d] %s", connID, retryCnt, i, sqlForLog(st.OriginText()))
} else {
log.Warnf("[%d] Retry [%d] query [%d]", connID, retryCnt, i)
}
s.sessionVars.StmtCtx = sr.stmtCtx
s.sessionVars.StmtCtx.ResetForRetry()
_, err = st.Exec(goCtx)
if err != nil {
s.StmtRollback()
break
}
terror.Log(s.StmtCommit())
}
if hook := ctx.Value("preCommitHook"); hook != nil {
// For testing purpose.
hook.(func())()
}
if err == nil {
err = s.doCommit(ctx)
if err == nil {
break
}
}
if !s.isRetryableError(err) {
log.Warnf("[%d] session:%v, err:%v", connID, s, err)
return errors.Trace(err)
}
retryCnt++
if retryCnt >= maxCnt {
log.Warnf("[%d] Retry reached max count %d", connID, retryCnt)
return errors.Trace(err)
}
log.Warnf("[%d] retryable error: %v, txn: %v", connID, err, s.Transaction)
kv.BackOff(retryCnt)
s.Transaction = nil
s.sessionVars.SetStatusFlag(mysql.ServerStatusInTrans, false)
}
return err
}
func sqlForLog(sql string) string {
if len(sql) > sqlLogMaxLen {
return sql[:sqlLogMaxLen] + fmt.Sprintf("(len:%d)", len(sql))
}
return sql
}
func (s *session) sysSessionPool() *pools.ResourcePool {
return domain.GetDomain(s).SysSessionPool()
}
// ExecRestrictedSQL implements RestrictedSQLExecutor interface.
// This is used for executing some restricted sql statements, usually executed during a normal statement execution.
// Unlike normal Exec, it doesn't reset statement status, doesn't commit or rollback the current transaction
// and doesn't write binlog.
func (s *session) ExecRestrictedSQL(ctx context.Context, sql string) ([]types.Row, []*ast.ResultField, error) {
var span opentracing.Span
goCtx := goctx.TODO()
span, goCtx = opentracing.StartSpanFromContext(goCtx, "session.ExecRestrictedSQL")
defer span.Finish()
// Use special session to execute the sql.
tmp, err := s.sysSessionPool().Get()
if err != nil {
return nil, nil, errors.Trace(err)
}
se := tmp.(*session)
defer s.sysSessionPool().Put(tmp)
recordSets, err := se.Execute(goCtx, sql)
if err != nil {
return nil, nil, errors.Trace(err)
}
var (
rows []types.Row
fields []*ast.ResultField
)
// Execute all recordset, take out the first one as result.
for i, rs := range recordSets {
tmp, err := drainRecordSet(goCtx, rs)
if err != nil {
return nil, nil, errors.Trace(err)
}
if err = rs.Close(); err != nil {
return nil, nil, errors.Trace(err)
}
if i == 0 {
rows = tmp
fields = rs.Fields()
}
}
return rows, fields, nil
}
func createSessionFunc(store kv.Storage) pools.Factory {
return func() (pools.Resource, error) {
se, err := createSession(store)
if err != nil {
return nil, errors.Trace(err)
}
err = variable.SetSessionSystemVar(se.sessionVars, variable.AutocommitVar, types.NewStringDatum("1"))
if err != nil {
return nil, errors.Trace(err)
}
se.sessionVars.CommonGlobalLoaded = true
se.sessionVars.InRestrictedSQL = true
return se, nil
}
}
func createSessionWithDomainFunc(store kv.Storage) func(*domain.Domain) (pools.Resource, error) {
return func(dom *domain.Domain) (pools.Resource, error) {
se, err := createSessionWithDomain(store, dom)
if err != nil {
return nil, errors.Trace(err)
}
err = variable.SetSessionSystemVar(se.sessionVars, variable.AutocommitVar, types.NewStringDatum("1"))
if err != nil {
return nil, errors.Trace(err)
}
se.sessionVars.CommonGlobalLoaded = true
se.sessionVars.InRestrictedSQL = true
return se, nil
}
}
func drainRecordSet(goCtx goctx.Context, rs ast.RecordSet) ([]types.Row, error) {
var rows []types.Row
for {
row, err := rs.Next(goCtx)
if err != nil {
return nil, errors.Trace(err)
}
if row == nil {
break
}
rows = append(rows, row)
}
return rows, nil
}
// getExecRet executes restricted sql and the result is one column.
// It returns a string value.
func (s *session) getExecRet(ctx context.Context, sql string) (string, error) {
rows, fields, err := s.ExecRestrictedSQL(ctx, sql)
if err != nil {
return "", errors.Trace(err)
}
if len(rows) == 0 {
return "", executor.ErrResultIsEmpty
}
d := rows[0].GetDatum(0, &fields[0].Column.FieldType)
value, err := d.ToString()
if err != nil {
return "", errors.Trace(err)
}
return value, nil
}
// GetAllSysVars implements GlobalVarAccessor.GetAllSysVars interface.
func (s *session) GetAllSysVars() (map[string]string, error) {
if s.Value(context.Initing) != nil {
return nil, nil
}
sql := `SELECT VARIABLE_NAME, VARIABLE_VALUE FROM %s.%s;`
sql = fmt.Sprintf(sql, mysql.SystemDB, mysql.GlobalVariablesTable)
rows, _, err := s.ExecRestrictedSQL(s, sql)
if err != nil {
return nil, errors.Trace(err)
}
ret := make(map[string]string)
for _, r := range rows {
k, v := r.GetString(0), r.GetString(1)
ret[k] = v
}
return ret, nil
}
// GetGlobalSysVar implements GlobalVarAccessor.GetGlobalSysVar interface.
func (s *session) GetGlobalSysVar(name string) (string, error) {
if s.Value(context.Initing) != nil {
// When running bootstrap or upgrade, we should not access global storage.
return "", nil
}
sql := fmt.Sprintf(`SELECT VARIABLE_VALUE FROM %s.%s WHERE VARIABLE_NAME="%s";`,
mysql.SystemDB, mysql.GlobalVariablesTable, name)
sysVar, err := s.getExecRet(s, sql)
if err != nil {
if executor.ErrResultIsEmpty.Equal(err) {
if sv, ok := variable.SysVars[name]; ok {
return sv.Value, nil
}
return "", variable.UnknownSystemVar.GenByArgs(name)
}
return "", errors.Trace(err)
}
return sysVar, nil
}
// SetGlobalSysVar implements GlobalVarAccessor.SetGlobalSysVar interface.
func (s *session) SetGlobalSysVar(name string, value string) error {
if name == variable.SQLModeVar {
value = mysql.FormatSQLModeStr(value)
if _, err := mysql.GetSQLMode(value); err != nil {
return errors.Trace(err)
}
}
sql := fmt.Sprintf(`REPLACE %s.%s VALUES ('%s', '%s');`,
mysql.SystemDB, mysql.GlobalVariablesTable, strings.ToLower(name), value)
_, _, err := s.ExecRestrictedSQL(s, sql)
return errors.Trace(err)
}
func (s *session) ParseSQL(goCtx goctx.Context, sql, charset, collation string) ([]ast.StmtNode, error) {
if span := opentracing.SpanFromContext(goCtx); span != nil {
span1 := opentracing.StartSpan("session.ParseSQL", opentracing.ChildOf(span.Context()))
defer span1.Finish()
}
s.parser.SetSQLMode(s.sessionVars.SQLMode)
return s.parser.Parse(sql, charset, collation)
}
func (s *session) SetProcessInfo(sql string) {
pi := util.ProcessInfo{
ID: s.sessionVars.ConnectionID,
DB: s.sessionVars.CurrentDB,
Command: "Query",
Time: time.Now(),
State: s.Status(),
Info: sql,
}
if s.sessionVars.User != nil {
pi.User = s.sessionVars.User.Username
pi.Host = s.sessionVars.User.Hostname
}
s.processInfo.Store(pi)
}
func (s *session) executeStatement(goCtx goctx.Context, connID uint64, stmtNode ast.StmtNode, stmt ast.Statement, recordSets []ast.RecordSet) ([]ast.RecordSet, error) {
s.SetValue(context.QueryString, stmt.OriginText())
if _, ok := stmtNode.(ast.DDLNode); ok {
s.SetValue(context.LastExecuteDDL, true)
} else {
s.ClearValue(context.LastExecuteDDL)
}
logStmt(stmtNode, s.sessionVars)
startTS := time.Now()
recordSet, err := runStmt(goCtx, s, stmt)
if err != nil {
if !kv.ErrKeyExists.Equal(err) {
log.Warnf("[%d] session error:\n%v\n%s", connID, errors.ErrorStack(err), s)
}
return nil, errors.Trace(err)
}
sessionExecuteRunDuration.Observe(time.Since(startTS).Seconds())
if recordSet != nil {
recordSets = append(recordSets, recordSet)
}
return recordSets, nil
}
func (s *session) Execute(goCtx goctx.Context, sql string) (recordSets []ast.RecordSet, err error) {
if span := opentracing.SpanFromContext(goCtx); span != nil {
span, goCtx = opentracing.StartSpanFromContext(goCtx, "session.Execute")
defer span.Finish()
}
s.PrepareTxnCtx(goCtx)
var (
cacheKey kvcache.Key
cacheValue kvcache.Value
useCachedPlan = false
connID = s.sessionVars.ConnectionID
)
if plan.PlanCacheEnabled {
schemaVersion := domain.GetDomain(s).InfoSchema().SchemaMetaVersion()
readOnly := s.Txn() == nil || s.Txn().IsReadOnly()
cacheKey = plan.NewSQLCacheKey(s.sessionVars, sql, schemaVersion, readOnly)
cacheValue, useCachedPlan = plan.GlobalPlanCache.Get(cacheKey)
}
if useCachedPlan {
stmtNode := cacheValue.(*plan.SQLCacheValue).StmtNode
stmt := &executor.ExecStmt{
InfoSchema: executor.GetInfoSchema(s),
Plan: cacheValue.(*plan.SQLCacheValue).Plan,
Expensive: cacheValue.(*plan.SQLCacheValue).Expensive,
Text: stmtNode.Text(),
StmtNode: stmtNode,
Ctx: s,
}
s.PrepareTxnCtx(goCtx)
executor.ResetStmtCtx(s, stmtNode)
if recordSets, err = s.executeStatement(goCtx, connID, stmtNode, stmt, recordSets); err != nil {
return nil, errors.Trace(err)
}
} else {
err = s.loadCommonGlobalVariablesIfNeeded()
if err != nil {
return nil, errors.Trace(err)
}
charsetInfo, collation := s.sessionVars.GetCharsetInfo()
// Step1: Compile query string to abstract syntax trees(ASTs).
startTS := time.Now()
stmtNodes, err := s.ParseSQL(goCtx, sql, charsetInfo, collation)
if err != nil {
log.Warnf("[%d] parse error:\n%v\n%s", connID, err, sql)
return nil, errors.Trace(err)
}
sessionExecuteParseDuration.Observe(time.Since(startTS).Seconds())
compiler := executor.Compiler{Ctx: s}
for _, stmtNode := range stmtNodes {
s.PrepareTxnCtx(goCtx)
// Step2: Transform abstract syntax tree to a physical plan(stored in executor.ExecStmt).
startTS = time.Now()
// Some executions are done in compile stage, so we reset them before compile.
executor.ResetStmtCtx(s, stmtNode)
stmt, err := compiler.Compile(goCtx, stmtNode)
if err != nil {
log.Warnf("[%d] compile error:\n%v\n%s", connID, err, sql)
return nil, errors.Trace(err)
}
sessionExecuteCompileDuration.Observe(time.Since(startTS).Seconds())
// Step3: Cache the physical plan if possible.
if plan.PlanCacheEnabled && stmt.Cacheable && len(stmtNodes) == 1 && !s.GetSessionVars().StmtCtx.HistogramsNotLoad() {
plan.GlobalPlanCache.Put(cacheKey, plan.NewSQLCacheValue(stmtNode, stmt.Plan, stmt.Expensive))
}
// Step4: Execute the physical plan.
if recordSets, err = s.executeStatement(goCtx, connID, stmtNode, stmt, recordSets); err != nil {
return nil, errors.Trace(err)
}
}
}
if s.sessionVars.ClientCapability&mysql.ClientMultiResults == 0 && len(recordSets) > 1 {
// return the first recordset if client doesn't support ClientMultiResults.
recordSets = recordSets[:1]
}
return recordSets, nil
}
// PrepareStmt is used for executing prepare statement in binary protocol
func (s *session) PrepareStmt(sql string) (stmtID uint32, paramCount int, fields []*ast.ResultField, err error) {
if s.sessionVars.TxnCtx.InfoSchema == nil {
// We don't need to create a transaction for prepare statement, just get information schema will do.
s.sessionVars.TxnCtx.InfoSchema = domain.GetDomain(s).InfoSchema()
}
err = s.loadCommonGlobalVariablesIfNeeded()
if err != nil {
err = errors.Trace(err)
return
}
prepareExec := executor.NewPrepareExec(s, executor.GetInfoSchema(s), sql)
err = prepareExec.DoPrepare()
return prepareExec.ID, prepareExec.ParamCount, prepareExec.Fields, errors.Trace(err)
}
// checkArgs makes sure all the arguments' types are known and can be handled.
// integer types are converted to int64 and uint64, time.Time is converted to types.Time.
// time.Duration is converted to types.Duration, other known types are leaved as it is.
func checkArgs(args ...interface{}) error {
for i, v := range args {
switch x := v.(type) {
case bool:
if x {
args[i] = int64(1)
} else {
args[i] = int64(0)
}
case int8:
args[i] = int64(x)
case int16:
args[i] = int64(x)
case int32:
args[i] = int64(x)
case int:
args[i] = int64(x)
case uint8:
args[i] = uint64(x)
case uint16:
args[i] = uint64(x)
case uint32:
args[i] = uint64(x)
case uint:
args[i] = uint64(x)
case int64:
case uint64:
case float32:
case float64:
case string:
case []byte:
case time.Duration:
args[i] = types.Duration{Duration: x}
case time.Time:
args[i] = types.Time{Time: types.FromGoTime(x), Type: mysql.TypeDatetime}
case nil:
default:
return errors.Errorf("cannot use arg[%d] (type %T):unsupported type", i, v)
}
}
return nil
}
// ExecutePreparedStmt executes a prepared statement.
func (s *session) ExecutePreparedStmt(goCtx goctx.Context, stmtID uint32, args ...interface{}) (ast.RecordSet, error) {
err := checkArgs(args...)
if err != nil {
return nil, errors.Trace(err)
}
s.PrepareTxnCtx(goCtx)
st, err := executor.CompileExecutePreparedStmt(s, stmtID, args...)
if err != nil {
return nil, errors.Trace(err)
}
logQuery(st.OriginText(), s.sessionVars)
r, err := runStmt(goCtx, s, st)
return r, errors.Trace(err)
}
func (s *session) DropPreparedStmt(stmtID uint32) error {
vars := s.sessionVars
if _, ok := vars.PreparedStmts[stmtID]; !ok {
return plan.ErrStmtNotFound
}
vars.RetryInfo.DroppedPreparedStmtIDs = append(vars.RetryInfo.DroppedPreparedStmtIDs, stmtID)
return nil
}
// StmtTxn wraps kv.Transaction to provide a new kv.Transaction.
// It holds all statement related modification in the buffer before flush to the txn,
// so if execute statement meets error, the txn won't be made dirty.
type StmtTxn struct {
kv.Transaction
buf kv.MemBuffer
mutations map[int64]*binlog.TableMutation
// TODO: DirtyDB need to be statement level too.
}
// Get overrides the Transaction interface.
func (st *StmtTxn) Get(k kv.Key) ([]byte, error) {
val, err := st.buf.Get(k)
if kv.IsErrNotFound(err) {
val, err = st.Transaction.Get(k)
}
if err != nil {
return nil, errors.Trace(err)
}
if len(val) == 0 {
return nil, kv.ErrNotExist
}
return val, nil
}
// Set overrides the Transaction interface.
func (st *StmtTxn) Set(k kv.Key, v []byte) error {
return st.buf.Set(k, v)
}
// Delete overrides the Transaction interface.
func (st *StmtTxn) Delete(k kv.Key) error {
return st.buf.Delete(k)
}
// Seek overrides the Transaction interface.
func (st *StmtTxn) Seek(k kv.Key) (kv.Iterator, error) {
bufferIt, err := st.buf.Seek(k)
if err != nil {
return nil, errors.Trace(err)
}
retrieverIt, err := st.Transaction.Seek(k)
if err != nil {
return nil, errors.Trace(err)
}
return kv.NewUnionIter(bufferIt, retrieverIt, false)
}
// SeekReverse overrides the Transaction interface.
func (st *StmtTxn) SeekReverse(k kv.Key) (kv.Iterator, error) {
bufferIt, err := st.buf.SeekReverse(k)
if err != nil {
return nil, errors.Trace(err)
}
retrieverIt, err := st.Transaction.SeekReverse(k)
if err != nil {
return nil, errors.Trace(err)
}
return kv.NewUnionIter(bufferIt, retrieverIt, true)
}
func (st *StmtTxn) cleanup() {
st.buf.Reset()
for key := range st.mutations {
delete(st.mutations, key)
}
}
// StmtCommit implements the context.Context interface.
func (s *session) StmtCommit() error {
defer s.StmtTxn.cleanup()
st := &s.StmtTxn
err := kv.WalkMemBuffer(s.buf, func(k kv.Key, v []byte) error {
if len(v) == 0 {
return errors.Trace(st.Transaction.Delete(k))
}
return errors.Trace(st.Transaction.Set(k, v))
})
// Need to flush binlog.
for tableID, delta := range st.mutations {
mutation := getBinlogMutation(s, tableID)
if err == nil {
mergeToMutation(mutation, delta)
}
}
return errors.Trace(err)