github.com/turingchain2020/turingchain@v1.1.21/common/db/mvcc_iter.go (about) 1 // Copyright Turing Corp. 2018 All Rights Reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package db 6 7 import ( 8 "bytes" 9 10 "github.com/turingchain2020/turingchain/types" 11 ) 12 13 //MVCCIter mvcc迭代器版本 14 //支持db 原生迭代器接口 15 //为了支持快速迭代,我这里采用了复制数据的做法 16 type MVCCIter struct { 17 *MVCCHelper 18 } 19 20 //NewMVCCIter new 21 func NewMVCCIter(db DB) *MVCCIter { 22 return &MVCCIter{MVCCHelper: NewMVCC(db)} 23 } 24 25 //AddMVCC add 26 func (m *MVCCIter) AddMVCC(kvs []*types.KeyValue, hash []byte, prevHash []byte, version int64) ([]*types.KeyValue, error) { 27 kvlist, err := m.MVCCHelper.AddMVCC(kvs, hash, prevHash, version) 28 if err != nil { 29 return nil, err 30 } 31 //添加last 32 for _, v := range kvs { 33 last := getLastKey(v.Key) 34 kv := &types.KeyValue{Key: last, Value: v.Value} 35 kvlist = append(kvlist, kv) 36 } 37 return kvlist, nil 38 } 39 40 //DelMVCC del 41 func (m *MVCCIter) DelMVCC(hash []byte, version int64, strict bool) ([]*types.KeyValue, error) { 42 kvs, err := m.GetDelKVList(version) 43 if err != nil { 44 return nil, err 45 } 46 kvlist, err := m.MVCCHelper.delMVCC(kvs, hash, version, strict) 47 if err != nil { 48 return nil, err 49 } 50 //更新last, 读取上次版本的 lastv值,更新last 51 for _, v := range kvs { 52 if version > 0 { 53 lastv, err := m.GetV(v.Key, version-1) 54 if err == types.ErrNotFound { 55 kvlist = append(kvlist, &types.KeyValue{Key: getLastKey(v.Key)}) 56 continue 57 } 58 if err != nil { 59 return nil, err 60 } 61 kvlist = append(kvlist, &types.KeyValue{Key: getLastKey(v.Key), Value: lastv}) 62 } 63 } 64 return kvlist, nil 65 } 66 67 //Iterator 迭代 68 func (m *MVCCIter) Iterator(start, end []byte, reserver bool) Iterator { 69 if start == nil { 70 start = mvccLast 71 } else { 72 start = getLastKey(start) 73 } 74 if end != nil { 75 end = getLastKey(end) 76 } else { 77 end = bytesPrefix(start) 78 } 79 return &mvccIt{m.db.Iterator(start, end, reserver)} 80 } 81 82 type mvccIt struct { 83 Iterator 84 } 85 86 //Prefix 前缀 87 func (dbit *mvccIt) Prefix() []byte { 88 return mvccLast 89 } 90 91 //Key key 92 func (dbit *mvccIt) Key() []byte { 93 key := dbit.Iterator.Key() 94 if bytes.HasPrefix(key, dbit.Prefix()) { 95 return key[len(dbit.Prefix()):] 96 } 97 return nil 98 } 99 100 //Valid 检查合法性 101 func (dbit *mvccIt) Valid() bool { 102 if !dbit.Iterator.Valid() { 103 return false 104 } 105 return dbit.Key() != nil 106 }