Skip to content

Commit

Permalink
Merge pull request #13548 from hashicorp/f-bbolt-helpers
Browse files Browse the repository at this point in the history
boltdd: add iterate and prefix deletion helpers
  • Loading branch information
shoenig committed Jul 5, 2022
2 parents 82704d5 + 6bb52a5 commit a3b3b54
Show file tree
Hide file tree
Showing 2 changed files with 206 additions and 109 deletions.
29 changes: 29 additions & 0 deletions helper/boltdd/boltdd.go
Original file line number Diff line number Diff line change
Expand Up @@ -353,6 +353,35 @@ func (b *Bucket) Get(key []byte, obj interface{}) error {
return nil
}

// Iterate iterates each key in Bucket b that starts with prefix. fn is called on
// the key and msg-pack decoded value. If prefix is empty or nil, all keys in the
// bucket are iterated.
func Iterate[T any](b *Bucket, prefix []byte, fn func([]byte, T)) error {
c := b.boltBucket.Cursor()
for k, data := c.Seek(prefix); k != nil && bytes.HasPrefix(k, prefix); k, data = c.Next() {
var obj T
if err := codec.NewDecoderBytes(data, structs.MsgpackHandle).Decode(&obj); err != nil {
return fmt.Errorf("failed to decode data into passed object: %v", err)
}
fn(k, obj)
}
return nil
}

// DeletePrefix removes all keys starting with prefix from the bucket. If no keys
// with prefix exist then nothing is done and a nil error is returned. Returns an
// error if the bucket was created from a read-only transaction.
func (b *Bucket) DeletePrefix(prefix []byte) error {
c := b.boltBucket.Cursor()
for k, _ := c.Seek(prefix); k != nil && bytes.HasPrefix(k, prefix); k, _ = c.Next() {
if err := c.Delete(); err != nil {
return err
}
b.bm.delHash(string(k))
}
return nil
}

// Delete removes a key from the bucket. If the key does not exist then nothing
// is done and a nil error is returned. Returns an error if the bucket was
// created from a read-only transaction.
Expand Down
Loading

0 comments on commit a3b3b54

Please sign in to comment.