merge.go
merge.go - Overview
This file defines the MergeOperator
for BadgerDB, enabling users to merge values associated with a key using a custom merge function. It handles asynchronous compaction of merged values.
Detailed Documentation
MergeOperator
type MergeOperator struct {
sync.RWMutex
f MergeFunc
db *DB
key []byte
closer *z.Closer
}
- Purpose: Represents a Badger merge operator. It encapsulates the merge function, the database instance, the key to merge, and a closer for managing the compaction goroutine.
MergeFunc
type MergeFunc func(existingVal, newVal []byte) []byte
- Purpose: Defines the function signature for merging two byte slices. It takes an existing value and a new value, and returns the merged result.
- Parameters:
existingVal
: The existing value (byte slice).newVal
: The new value to merge (byte slice).
- Returns: The merged value (byte slice).
(*DB) GetMergeOperator
func (db *DB) GetMergeOperator(key []byte, f MergeFunc, dur time.Duration) *MergeOperator
- Purpose: Creates a new
MergeOperator
for a given key and starts a goroutine to perform periodic compactions using the provided merge function. - Parameters:
key
: The key to associate with the merge operator (byte slice).f
: TheMergeFunc
to use for merging values.dur
: The duration between compactions.
- Returns: A pointer to the new
MergeOperator
.
(*MergeOperator) iterateAndMerge
func (op *MergeOperator) iterateAndMerge() (newVal []byte, latest uint64, err error)
- Purpose: Iterates through all versions of a key, merging them using the merge function.
- Returns:
newVal
: The final merged value (byte slice).latest
: The version of the latest value.err
: An error, if any occurred. ReturnsErrKeyNotFound
if the key doesn't exist,errNoMerge
if there is only one version.
(*MergeOperator) compact
func (op *MergeOperator) compact() error
- Purpose: Performs a compaction by merging all versions of the key and writing the result back to the database.
- Returns: An error, if any occurred during the compaction process.
(*MergeOperator) runCompactions
func (op *MergeOperator) runCompactions(dur time.Duration)
- Purpose: Runs compactions periodically using a ticker.
- Parameters:
dur
: The duration between compactions.
(*MergeOperator) Add
func (op *MergeOperator) Add(val []byte) error
- Purpose: Adds a value to be merged with the existing values for the key.
- Parameters:
val
: The value to add (byte slice).
- Returns: An error, if any occurred during the update.
(*MergeOperator) Get
func (op *MergeOperator) Get() ([]byte, error)
- Purpose: Retrieves the latest merged value for the key.
- Returns:
- The merged value (byte slice).
- An error, if any occurred. Returns
ErrKeyNotFound
if the key has no value.
(*MergeOperator) Stop
func (op *MergeOperator) Stop()
- Purpose: Stops the background compaction goroutine.