forked from pingcap/tidb
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsequence_state.go
72 lines (64 loc) · 2.3 KB
/
sequence_state.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
// Copyright 2020 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 variable
import (
"sync"
)
// SequenceState cache all sequence's latest value accessed by lastval() builtins. It's a session scoped
// variable, and all public methods of SequenceState are currently-safe.
type SequenceState struct {
mu sync.Mutex
// latestValueMap caches the last value obtained by nextval() for each sequence id.
latestValueMap map[int64]int64
}
// NewSequenceState creates a SequenceState.
func NewSequenceState() *SequenceState {
return &SequenceState{mu: sync.Mutex{}, latestValueMap: make(map[int64]int64)}
}
// UpdateState will update the last value of specified sequenceID in a session.
func (ss *SequenceState) UpdateState(sequenceID, value int64) {
ss.mu.Lock()
defer ss.mu.Unlock()
ss.latestValueMap[sequenceID] = value
}
// GetLastValue will return last value of the specified sequenceID, bool(true) indicates
// the sequenceID is not in the cache map and NULL will be returned.
func (ss *SequenceState) GetLastValue(sequenceID int64) (int64, bool, error) {
ss.mu.Lock()
defer ss.mu.Unlock()
if len(ss.latestValueMap) > 0 {
if last, ok := ss.latestValueMap[sequenceID]; ok {
return last, false, nil
}
}
return 0, true, nil
}
// GetAllStates returns a copied latestValueMap.
func (ss *SequenceState) GetAllStates() map[int64]int64 {
ss.mu.Lock()
defer ss.mu.Unlock()
latestValueMap := make(map[int64]int64, len(ss.latestValueMap))
for seqID, latestValue := range ss.latestValueMap {
latestValueMap[seqID] = latestValue
}
return latestValueMap
}
// SetAllStates sets latestValueMap as a whole.
func (ss *SequenceState) SetAllStates(latestValueMap map[int64]int64) {
ss.mu.Lock()
defer ss.mu.Unlock()
for seqID, latestValue := range latestValueMap {
ss.latestValueMap[seqID] = latestValue
}
}