github.com/dolthub/dolt/go@v0.40.5-0.20240520175717-68db7794bea6/performance/kvbench/bolt_store.go (about) 1 // Copyright 2021 Dolthub, 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 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package kvbench 16 17 import ( 18 "path" 19 20 "github.com/boltdb/bolt" 21 ) 22 23 const ( 24 dbFileName = "bolt_store.db" 25 bucketName = "bench" 26 ) 27 28 func newBoltStore(dir string) keyValStore { 29 db, err := bolt.Open(path.Join(dir, dbFileName), 0600, nil) 30 if err != nil { 31 panic(err) 32 } 33 34 err = db.Update(func(tx *bolt.Tx) error { 35 _, err := tx.CreateBucketIfNotExists([]byte(bucketName)) 36 return err 37 }) 38 if err != nil { 39 panic(err) 40 } 41 42 return boltStore{DB: db} 43 } 44 45 type boltStore struct { 46 *bolt.DB 47 } 48 49 var _ keyValStore = boltStore{} 50 51 func (bs boltStore) get(key []byte) (val []byte, ok bool) { 52 err := bs.DB.View(func(tx *bolt.Tx) (err error) { 53 b := tx.Bucket([]byte(bucketName)) 54 v := b.Get(key) 55 ok = v != nil 56 if ok { 57 val = make([]byte, len(v)) 58 copy(val, v) 59 } 60 return 61 }) 62 if err != nil { 63 panic(err) 64 } 65 return val, ok 66 } 67 68 func (bs boltStore) put(key, val []byte) { 69 err := bs.DB.Update(func(tx *bolt.Tx) (err error) { 70 b := tx.Bucket([]byte(bucketName)) 71 return b.Put(key, val) 72 }) 73 if err != nil { 74 panic(err) 75 } 76 } 77 78 func (bs boltStore) putMany(keys, vals [][]byte) { 79 err := bs.DB.Update(func(tx *bolt.Tx) (err error) { 80 b := tx.Bucket([]byte(bucketName)) 81 for i := range keys { 82 err = b.Put(keys[i], vals[i]) 83 if err != nil { 84 break 85 } 86 } 87 return 88 }) 89 if err != nil { 90 panic(err) 91 } 92 } 93 94 func (bs boltStore) delete(key []byte) { 95 err := bs.DB.Update(func(tx *bolt.Tx) (err error) { 96 b := tx.Bucket([]byte(bucketName)) 97 return b.Put(key, nil) 98 }) 99 if err != nil { 100 panic(err) 101 } 102 }