github.com/whtcorpsinc/milevadb-prod@v0.0.0-20211104133533-f57f4be3b597/causetstore/stochastikctx/variable/sequence_state.go (about)

     1  // Copyright 2020 WHTCORPS INC, Inc.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // See the License for the specific language governing permissions and
    12  // limitations under the License.
    13  
    14  package variable
    15  
    16  import (
    17  	"sync"
    18  )
    19  
    20  // SequenceState cache all sequence's latest value accessed by lastval() builtins. It's a stochastik scoped
    21  // variable, and all public methods of SequenceState are currently-safe.
    22  type SequenceState struct {
    23  	mu sync.Mutex
    24  	// latestValueMap caches the last value obtained by nextval() for each sequence id.
    25  	latestValueMap map[int64]int64
    26  }
    27  
    28  // NewSequenceState creates a SequenceState.
    29  func NewSequenceState() *SequenceState {
    30  	return &SequenceState{mu: sync.Mutex{}, latestValueMap: make(map[int64]int64)}
    31  }
    32  
    33  // UFIDelateState will uFIDelate the last value of specified sequenceID in a stochastik.
    34  func (ss *SequenceState) UFIDelateState(sequenceID, value int64) {
    35  	ss.mu.Lock()
    36  	defer ss.mu.Unlock()
    37  	ss.latestValueMap[sequenceID] = value
    38  }
    39  
    40  // GetLastValue will return last value of the specified sequenceID, bool(true) indicates
    41  // the sequenceID is not in the cache map and NULL will be returned.
    42  func (ss *SequenceState) GetLastValue(sequenceID int64) (int64, bool, error) {
    43  	ss.mu.Lock()
    44  	defer ss.mu.Unlock()
    45  	if len(ss.latestValueMap) > 0 {
    46  		if last, ok := ss.latestValueMap[sequenceID]; ok {
    47  			return last, false, nil
    48  		}
    49  	}
    50  	return 0, true, nil
    51  }