-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
safe_session.go
789 lines (687 loc) · 24.1 KB
/
safe_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
/*
Copyright 2019 The Vitess Authors.
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 vtgate
import (
"fmt"
"strings"
"sync"
"time"
"google.golang.org/protobuf/proto"
"vitess.io/vitess/go/vt/vterrors"
querypb "vitess.io/vitess/go/vt/proto/query"
topodatapb "vitess.io/vitess/go/vt/proto/topodata"
vtgatepb "vitess.io/vitess/go/vt/proto/vtgate"
vtrpcpb "vitess.io/vitess/go/vt/proto/vtrpc"
)
// SafeSession is a mutex-protected version of the Session.
// It is thread-safe if each thread only accesses one shard.
// (the use pattern is 'Find', if not found, then 'AppendOrUpdate',
// for a single shard)
type SafeSession struct {
mu sync.Mutex
mustRollback bool
autocommitState autocommitState
commitOrder vtgatepb.CommitOrder
savepointState savepointState
// rollbackOnPartialExec is set if any DML was successfully
// executed. If there was a subsequent failure, if we have a savepoint we rollback to that.
// Otherwise, the transaction is rolled back.
rollbackOnPartialExec string
savepointName string
// this is a signal that found_rows has already been handles by the primitives,
// and doesn't have to be updated by the executor
foundRowsHandled bool
*vtgatepb.Session
}
// autocommitState keeps track of whether a single round-trip
// commit to vttablet is possible. It starts as autocommitable
// if we started a transaction because of the autocommit flag
// being set. Otherwise, it starts as notAutocommitable.
// If execute is recursively called using the same session,
// like from a vindex, we will already be in a transaction,
// and this should cause the state to become notAutocommitable.
//
// SafeSession lets you request a commit token, which will
// be issued if the state is autocommitable,
// implying that no intermediate transactions were started.
// If so, the state transitions to autocommited, which is terminal.
// If the token is successfully issued, the caller has to perform
// the commit. If a token cannot be issued, then a traditional
// commit has to be performed at the outermost level where
// the autocommitable transition happened.
type autocommitState int
const (
notAutocommittable = autocommitState(iota)
autocommittable
autocommitted
)
// savepointState keeps track of whether savepoints need to be inserted
// before running the query. This will help us prevent rolling back the
// entire transaction in case of partial failures, and be closer to MySQL
// compatibility, by only reverting the changes from the failed statement
// If execute is recursively called using the same session,
// like from a vindex, we should not override the savePointState.
// It is set the first time and is then permanent for the remainder of the query
// execution. It should not be affected later by transactions starting or not.
type savepointState int
const (
savepointStateNotSet = savepointState(iota)
// savepointNotNeeded - savepoint is not required
savepointNotNeeded
// savepointNeeded - savepoint may be required
savepointNeeded
// savepointSet - savepoint is set on the session
savepointSet
// savepointRollbackSet - rollback to savepoint is set on the session
savepointRollbackSet
// savepointRollback - rollback happened on the savepoint
savepointRollback
)
// NewSafeSession returns a new SafeSession based on the Session
func NewSafeSession(sessn *vtgatepb.Session) *SafeSession {
if sessn == nil {
sessn = &vtgatepb.Session{}
}
return &SafeSession{Session: sessn}
}
// NewAutocommitSession returns a SafeSession based on the original
// session, but with autocommit enabled.
func NewAutocommitSession(sessn *vtgatepb.Session) *SafeSession {
newSession := proto.Clone(sessn).(*vtgatepb.Session)
newSession.InTransaction = false
newSession.ShardSessions = nil
newSession.PreSessions = nil
newSession.PostSessions = nil
newSession.Autocommit = true
newSession.Warnings = nil
return NewSafeSession(newSession)
}
// ResetTx clears the session
func (session *SafeSession) ResetTx() {
session.mu.Lock()
defer session.mu.Unlock()
session.mustRollback = false
session.autocommitState = notAutocommittable
session.Session.InTransaction = false
session.commitOrder = vtgatepb.CommitOrder_NORMAL
session.Savepoints = nil
if !session.Session.InReservedConn {
session.ShardSessions = nil
session.PreSessions = nil
session.PostSessions = nil
}
}
// Reset clears the session
func (session *SafeSession) Reset() {
session.mu.Lock()
defer session.mu.Unlock()
session.mustRollback = false
session.autocommitState = notAutocommittable
session.Session.InTransaction = false
session.commitOrder = vtgatepb.CommitOrder_NORMAL
session.Savepoints = nil
session.ShardSessions = nil
session.PreSessions = nil
session.PostSessions = nil
}
// SavePoints returns the save points of the session. It's safe to use concurrently
func (session *SafeSession) SavePoints() []string {
session.mu.Lock()
defer session.mu.Unlock()
return session.GetSavepoints()
}
// SetAutocommittable sets the state to autocommitable if true.
// Otherwise, it's notAutocommitable.
func (session *SafeSession) SetAutocommittable(flag bool) {
session.mu.Lock()
defer session.mu.Unlock()
if session.autocommitState == autocommitted {
// Unreachable.
return
}
if flag {
session.autocommitState = autocommittable
} else {
session.autocommitState = notAutocommittable
}
}
// AutocommitApproval returns true if we can perform a single round-trip
// autocommit. If so, the caller is responsible for committing their
// transaction.
func (session *SafeSession) AutocommitApproval() bool {
session.mu.Lock()
defer session.mu.Unlock()
if session.autocommitState == autocommitted {
// Unreachable.
return false
}
if session.autocommitState == autocommittable {
session.autocommitState = autocommitted
return true
}
return false
}
// SetSavepointState sets the state only once for the complete query execution life.
// Calling the function multiple times will have no effect, only the first call would be used.
// Default state is savepointStateNotSet,
// if savepoint needed (spNeed true) then it will be set to savepointNeeded otherwise savepointNotNeeded.
func (session *SafeSession) SetSavepointState(spNeed bool) {
session.mu.Lock()
defer session.mu.Unlock()
if session.savepointState != savepointStateNotSet {
return
}
if spNeed {
session.savepointState = savepointNeeded
} else {
session.savepointState = savepointNotNeeded
}
}
// CanAddSavepoint returns true if we should insert savepoint and there is no existing savepoint.
func (session *SafeSession) CanAddSavepoint() bool {
session.mu.Lock()
defer session.mu.Unlock()
return session.savepointState == savepointNeeded
}
// SetSavepoint stores the savepoint name to session.
func (session *SafeSession) SetSavepoint(name string) {
session.mu.Lock()
defer session.mu.Unlock()
session.savepointName = name
session.savepointState = savepointSet
}
// SetRollbackCommand stores the rollback command to session and executed if required.
func (session *SafeSession) SetRollbackCommand() {
session.mu.Lock()
defer session.mu.Unlock()
// if the rollback already happened on the savepoint. There is nothing to set or execute on later.
if session.savepointState == savepointRollback {
return
}
if session.savepointState == savepointSet {
session.rollbackOnPartialExec = fmt.Sprintf("rollback to %s", session.savepointName)
} else {
session.rollbackOnPartialExec = txRollback
}
session.savepointState = savepointRollbackSet
}
// SavepointRollback updates the state that transaction was rolledback to the savepoint stored in the session.
func (session *SafeSession) SavepointRollback() {
session.mu.Lock()
defer session.mu.Unlock()
session.savepointState = savepointRollback
}
// IsRollbackSet returns true if rollback to savepoint can be done.
func (session *SafeSession) IsRollbackSet() bool {
session.mu.Lock()
defer session.mu.Unlock()
return session.savepointState == savepointRollbackSet
}
// SetCommitOrder sets the commit order.
func (session *SafeSession) SetCommitOrder(co vtgatepb.CommitOrder) {
session.mu.Lock()
defer session.mu.Unlock()
session.commitOrder = co
}
// InTransaction returns true if we are in a transaction
func (session *SafeSession) InTransaction() bool {
session.mu.Lock()
defer session.mu.Unlock()
return session.Session.InTransaction
}
// Find returns the transactionId and tabletAlias, if any, for a session
func (session *SafeSession) Find(keyspace, shard string, tabletType topodatapb.TabletType) (transactionID int64, reservedID int64, alias *topodatapb.TabletAlias) {
session.mu.Lock()
defer session.mu.Unlock()
sessions := session.ShardSessions
switch session.commitOrder {
case vtgatepb.CommitOrder_PRE:
sessions = session.PreSessions
case vtgatepb.CommitOrder_POST:
sessions = session.PostSessions
}
for _, shardSession := range sessions {
if keyspace == shardSession.Target.Keyspace && tabletType == shardSession.Target.TabletType && shard == shardSession.Target.Shard {
return shardSession.TransactionId, shardSession.ReservedId, shardSession.TabletAlias
}
}
return 0, 0, nil
}
func addOrUpdate(shardSession *vtgatepb.Session_ShardSession, sessions []*vtgatepb.Session_ShardSession) ([]*vtgatepb.Session_ShardSession, error) {
appendSession := true
for i, sess := range sessions {
targetedAtSameTablet := sess.Target.Keyspace == shardSession.Target.Keyspace &&
sess.Target.TabletType == shardSession.Target.TabletType &&
sess.Target.Shard == shardSession.Target.Shard
if targetedAtSameTablet {
if !proto.Equal(sess.TabletAlias, shardSession.TabletAlias) {
errorDetails := fmt.Sprintf("got non-matching aliases (%v vs %v) for the same target (keyspace: %v, tabletType: %v, shard: %v)",
sess.TabletAlias, shardSession.TabletAlias,
sess.Target.Keyspace, sess.Target.TabletType, sess.Target.Shard)
return nil, vterrors.New(vtrpcpb.Code_FAILED_PRECONDITION, errorDetails)
}
// replace the old info with the new one
sessions[i] = shardSession
appendSession = false
break
}
}
if appendSession {
sessions = append(sessions, shardSession)
}
return sessions, nil
}
// AppendOrUpdate adds a new ShardSession, or updates an existing one if one already exists for the given shard session
func (session *SafeSession) AppendOrUpdate(shardSession *vtgatepb.Session_ShardSession, txMode vtgatepb.TransactionMode) error {
session.mu.Lock()
defer session.mu.Unlock()
// additional check of transaction id is required
// as now in autocommit mode there can be session due to reserved connection
// that needs to be stored as shard session.
if session.autocommitState == autocommitted && shardSession.TransactionId != 0 {
// Should be unreachable
return vterrors.New(vtrpcpb.Code_INTERNAL, "[BUG] unexpected 'autocommitted' state in transaction")
}
if !(session.Session.InTransaction || session.Session.InReservedConn) {
// Should be unreachable
return vterrors.New(vtrpcpb.Code_INTERNAL, "[BUG] current session neither in transaction nor in reserved connection")
}
session.autocommitState = notAutocommittable
// Always append, in order for rollback to succeed.
switch session.commitOrder {
case vtgatepb.CommitOrder_NORMAL:
newSessions, err := addOrUpdate(shardSession, session.ShardSessions)
if err != nil {
return err
}
session.ShardSessions = newSessions
// isSingle is enforced only for normmal commit order operations.
if session.isSingleDB(txMode) && len(session.ShardSessions) > 1 {
session.mustRollback = true
return vterrors.Errorf(vtrpcpb.Code_ABORTED, "multi-db transaction attempted: %v", session.ShardSessions)
}
case vtgatepb.CommitOrder_PRE:
newSessions, err := addOrUpdate(shardSession, session.PreSessions)
if err != nil {
return err
}
session.PreSessions = newSessions
case vtgatepb.CommitOrder_POST:
newSessions, err := addOrUpdate(shardSession, session.PostSessions)
if err != nil {
return err
}
session.PostSessions = newSessions
default:
// Should be unreachable
return vterrors.Errorf(vtrpcpb.Code_INTERNAL, "[BUG] SafeSession.AppendOrUpdate: unexpected commitOrder")
}
return nil
}
func (session *SafeSession) isSingleDB(txMode vtgatepb.TransactionMode) bool {
return session.TransactionMode == vtgatepb.TransactionMode_SINGLE ||
(session.TransactionMode == vtgatepb.TransactionMode_UNSPECIFIED && txMode == vtgatepb.TransactionMode_SINGLE)
}
// SetRollback sets the flag indicating that the transaction must be rolled back.
// The call is a no-op if the session is not in a transaction.
func (session *SafeSession) SetRollback() {
session.mu.Lock()
defer session.mu.Unlock()
if session.Session.InTransaction {
session.mustRollback = true
}
}
// MustRollback returns true if the transaction must be rolled back.
func (session *SafeSession) MustRollback() bool {
session.mu.Lock()
defer session.mu.Unlock()
return session.mustRollback
}
// RecordWarning stores the given warning in the session
func (session *SafeSession) RecordWarning(warning *querypb.QueryWarning) {
session.mu.Lock()
defer session.mu.Unlock()
session.Session.Warnings = append(session.Session.Warnings, warning)
}
// ClearWarnings removes all the warnings from the session
func (session *SafeSession) ClearWarnings() {
session.mu.Lock()
defer session.mu.Unlock()
session.Session.Warnings = nil
}
// SetUserDefinedVariable sets the user defined variable in the session.
func (session *SafeSession) SetUserDefinedVariable(key string, value *querypb.BindVariable) {
session.mu.Lock()
defer session.mu.Unlock()
if session.UserDefinedVariables == nil {
session.UserDefinedVariables = make(map[string]*querypb.BindVariable)
}
session.UserDefinedVariables[key] = value
}
// SetTargetString sets the target string in the session.
func (session *SafeSession) SetTargetString(target string) {
session.mu.Lock()
defer session.mu.Unlock()
session.TargetString = target
}
// SetSystemVariable sets the system variable in the session.
func (session *SafeSession) SetSystemVariable(name string, expr string) {
session.mu.Lock()
defer session.mu.Unlock()
if session.SystemVariables == nil {
session.SystemVariables = make(map[string]string)
}
session.SystemVariables[name] = expr
}
// GetSystemVariables takes a visitor function that will save each system variables of the session
func (session *SafeSession) GetSystemVariables(f func(k string, v string)) {
session.mu.Lock()
defer session.mu.Unlock()
for k, v := range session.SystemVariables {
f(k, v)
}
}
// HasSystemVariables returns whether the session has system variables set or not.
func (session *SafeSession) HasSystemVariables() bool {
session.mu.Lock()
defer session.mu.Unlock()
return len(session.SystemVariables) > 0
}
// SetOptions sets the options
func (session *SafeSession) SetOptions(options *querypb.ExecuteOptions) {
session.mu.Lock()
defer session.mu.Unlock()
session.Options = options
}
// StoreSavepoint stores the savepoint and release savepoint queries in the session
func (session *SafeSession) StoreSavepoint(sql string) {
session.mu.Lock()
defer session.mu.Unlock()
session.Savepoints = append(session.Savepoints, sql)
}
// InReservedConn returns true if the session needs to execute on a dedicated connection
func (session *SafeSession) InReservedConn() bool {
session.mu.Lock()
defer session.mu.Unlock()
return session.Session.InReservedConn
}
// SetReservedConn set the InReservedConn setting.
func (session *SafeSession) SetReservedConn(reservedConn bool) {
session.mu.Lock()
defer session.mu.Unlock()
session.Session.InReservedConn = reservedConn
}
// SetPreQueries returns the prequeries that need to be run when reserving a connection
func (session *SafeSession) SetPreQueries() []string {
session.mu.Lock()
defer session.mu.Unlock()
result := make([]string, len(session.SystemVariables))
idx := 0
for k, v := range session.SystemVariables {
result[idx] = fmt.Sprintf("set @@%s = %s", k, v)
idx++
}
return result
}
// SetLockSession sets the lock session.
func (session *SafeSession) SetLockSession(lockSession *vtgatepb.Session_ShardSession) {
session.mu.Lock()
defer session.mu.Unlock()
session.LockSession = lockSession
session.LastLockHeartbeat = time.Now().Unix()
}
// UpdateLockHeartbeat updates the LastLockHeartbeat time
func (session *SafeSession) UpdateLockHeartbeat() {
session.mu.Lock()
defer session.mu.Unlock()
session.LastLockHeartbeat = time.Now().Unix()
}
// TriggerLockHeartBeat returns if it time to trigger next lock heartbeat
func (session *SafeSession) TriggerLockHeartBeat() bool {
session.mu.Lock()
defer session.mu.Unlock()
now := time.Now().Unix()
return now-session.LastLockHeartbeat >= int64(lockHeartbeatTime.Seconds())
}
// InLockSession returns whether locking is used on this session.
func (session *SafeSession) InLockSession() bool {
session.mu.Lock()
defer session.mu.Unlock()
return session.LockSession != nil
}
// ResetLock resets the lock session
func (session *SafeSession) ResetLock() {
session.mu.Lock()
defer session.mu.Unlock()
session.LockSession = nil
session.AdvisoryLock = nil
}
// ResetAll resets the shard sessions and lock session.
func (session *SafeSession) ResetAll() {
session.mu.Lock()
defer session.mu.Unlock()
session.mustRollback = false
session.autocommitState = notAutocommittable
session.Session.InTransaction = false
session.commitOrder = vtgatepb.CommitOrder_NORMAL
session.Savepoints = nil
session.ShardSessions = nil
session.PreSessions = nil
session.PostSessions = nil
session.LockSession = nil
session.AdvisoryLock = nil
}
// ResetShard reset the shard session for the provided tablet alias.
func (session *SafeSession) ResetShard(tabletAlias *topodatapb.TabletAlias) error {
session.mu.Lock()
defer session.mu.Unlock()
// Always append, in order for rollback to succeed.
switch session.commitOrder {
case vtgatepb.CommitOrder_NORMAL:
newSessions, err := removeShard(tabletAlias, session.ShardSessions)
if err != nil {
return err
}
session.ShardSessions = newSessions
case vtgatepb.CommitOrder_PRE:
newSessions, err := removeShard(tabletAlias, session.PreSessions)
if err != nil {
return err
}
session.PreSessions = newSessions
case vtgatepb.CommitOrder_POST:
newSessions, err := removeShard(tabletAlias, session.PostSessions)
if err != nil {
return err
}
session.PostSessions = newSessions
default:
// Should be unreachable
return vterrors.Errorf(vtrpcpb.Code_INTERNAL, "[BUG] SafeSession.ResetShard: unexpected commitOrder")
}
return nil
}
// SetDDLStrategy set the DDLStrategy setting.
func (session *SafeSession) SetDDLStrategy(strategy string) {
session.mu.Lock()
defer session.mu.Unlock()
session.DDLStrategy = strategy
}
// GetDDLStrategy returns the DDLStrategy value.
func (session *SafeSession) GetDDLStrategy() string {
session.mu.Lock()
defer session.mu.Unlock()
return session.DDLStrategy
}
// GetSessionUUID returns the SessionUUID value.
func (session *SafeSession) GetSessionUUID() string {
session.mu.Lock()
defer session.mu.Unlock()
return session.SessionUUID
}
// SetSessionEnableSystemSettings set the SessionEnableSystemSettings setting.
func (session *SafeSession) SetSessionEnableSystemSettings(allow bool) {
session.mu.Lock()
defer session.mu.Unlock()
session.EnableSystemSettings = allow
}
// GetSessionEnableSystemSettings returns the SessionEnableSystemSettings value.
func (session *SafeSession) GetSessionEnableSystemSettings() bool {
session.mu.Lock()
defer session.mu.Unlock()
return session.EnableSystemSettings
}
// SetReadAfterWriteGTID set the ReadAfterWriteGtid setting.
func (session *SafeSession) SetReadAfterWriteGTID(vtgtid string) {
session.mu.Lock()
defer session.mu.Unlock()
if session.ReadAfterWrite == nil {
session.ReadAfterWrite = &vtgatepb.ReadAfterWrite{}
}
session.ReadAfterWrite.ReadAfterWriteGtid = vtgtid
}
// SetReadAfterWriteTimeout set the ReadAfterWriteTimeout setting.
func (session *SafeSession) SetReadAfterWriteTimeout(timeout float64) {
session.mu.Lock()
defer session.mu.Unlock()
if session.ReadAfterWrite == nil {
session.ReadAfterWrite = &vtgatepb.ReadAfterWrite{}
}
session.ReadAfterWrite.ReadAfterWriteTimeout = timeout
}
// SetSessionTrackGtids set the SessionTrackGtids setting.
func (session *SafeSession) SetSessionTrackGtids(enable bool) {
session.mu.Lock()
defer session.mu.Unlock()
if session.ReadAfterWrite == nil {
session.ReadAfterWrite = &vtgatepb.ReadAfterWrite{}
}
session.ReadAfterWrite.SessionTrackGtids = enable
}
func removeShard(tabletAlias *topodatapb.TabletAlias, sessions []*vtgatepb.Session_ShardSession) ([]*vtgatepb.Session_ShardSession, error) {
idx := -1
for i, session := range sessions {
if proto.Equal(session.TabletAlias, tabletAlias) {
if session.TransactionId != 0 {
return nil, vterrors.New(vtrpcpb.Code_INTERNAL, "[BUG] removing shard session when in transaction")
}
idx = i
}
}
if idx == -1 {
return nil, vterrors.New(vtrpcpb.Code_INTERNAL, "[BUG] tried to remove missing shard")
}
return append(sessions[:idx], sessions[idx+1:]...), nil
}
// GetOrCreateOptions will return the current options struct, or create one and return it if no-one exists
func (session *SafeSession) GetOrCreateOptions() *querypb.ExecuteOptions {
if session.Session.Options == nil {
session.Session.Options = &querypb.ExecuteOptions{}
}
return session.Session.Options
}
var _ iQueryOption = (*SafeSession)(nil)
func (session *SafeSession) cachePlan() bool {
if session == nil || session.Options == nil {
return true
}
session.mu.Lock()
defer session.mu.Unlock()
return !(session.Options.SkipQueryPlanCache || session.Options.HasCreatedTempTables)
}
func (session *SafeSession) getSelectLimit() int {
if session == nil || session.Options == nil {
return -1
}
session.mu.Lock()
defer session.mu.Unlock()
return int(session.Options.SqlSelectLimit)
}
// isTxOpen returns true if there is open connection to any of the shard.
func (session *SafeSession) isTxOpen() bool {
session.mu.Lock()
defer session.mu.Unlock()
return len(session.ShardSessions) > 0 || len(session.PreSessions) > 0 || len(session.PostSessions) > 0
}
// getSessions returns the shard session for the current commit order.
func (session *SafeSession) getSessions() []*vtgatepb.Session_ShardSession {
session.mu.Lock()
defer session.mu.Unlock()
switch session.commitOrder {
case vtgatepb.CommitOrder_PRE:
return session.PreSessions
case vtgatepb.CommitOrder_POST:
return session.PostSessions
default:
return session.ShardSessions
}
}
func (session *SafeSession) RemoveInternalSavepoint() {
session.mu.Lock()
defer session.mu.Unlock()
if session.savepointName == "" {
return
}
sCount := len(session.Savepoints)
if sCount == 0 {
return
}
sLast := sCount - 1
if strings.Contains(session.Savepoints[sLast], session.savepointName) {
session.Savepoints = session.Savepoints[0:sLast]
}
}
// HasAdvisoryLock returns if any advisory lock is taken
func (session *SafeSession) HasAdvisoryLock() bool {
session.mu.Lock()
defer session.mu.Unlock()
return len(session.AdvisoryLock) != 0
}
// AddAdvisoryLock adds the advisory lock to the list.
func (session *SafeSession) AddAdvisoryLock(name string) {
session.mu.Lock()
defer session.mu.Unlock()
if session.AdvisoryLock == nil {
session.AdvisoryLock = map[string]int64{name: 1}
return
}
count, exists := session.AdvisoryLock[name]
if exists {
count++
}
session.AdvisoryLock[name] = count
}
// RemoveAdvisoryLock removes the advisory lock from the list.
func (session *SafeSession) RemoveAdvisoryLock(name string) {
session.mu.Lock()
defer session.mu.Unlock()
if session.AdvisoryLock == nil {
return
}
count, exists := session.AdvisoryLock[name]
if !exists {
return
}
count--
if count == 0 {
delete(session.AdvisoryLock, name)
return
}
session.AdvisoryLock[name] = count
}
// ClearAdvisoryLock clears the advisory lock list.
func (session *SafeSession) ClearAdvisoryLock() {
session.mu.Lock()
defer session.mu.Unlock()
session.AdvisoryLock = nil
}