Skip to content

Commit

Permalink
internal/database/memory: discard batch once cancel to match badger b…
Browse files Browse the repository at this point in the history
…ehavior
  • Loading branch information
qdm12 committed Dec 15, 2022
1 parent 459d771 commit d685c56
Showing 1 changed file with 23 additions and 0 deletions.
23 changes: 23 additions & 0 deletions internal/database/memory/writebatch.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,15 @@

package memory

import (
"errors"
"fmt"
)

var (
ErrWriteBatchDiscarded = errors.New("write batch has been discarded")
)

type operationKind uint8

const (
Expand All @@ -21,6 +30,7 @@ type operation struct {
// It is NOT thread safe, but its Flush operation is thread safe for
// the database injected.
type writeBatch struct {
discarded bool
prefix string
database *Database
operations []operation
Expand All @@ -35,6 +45,10 @@ func newWriteBatch(prefix string, database *Database) *writeBatch {

// Set sets a value at the given key prefixed with the given prefix.
func (wb *writeBatch) Set(key, value []byte) (err error) {
if wb.discarded {
return fmt.Errorf("%w", ErrWriteBatchDiscarded)
}

op := operation{
kind: operationSet,
key: wb.prefix + string(key),
Expand All @@ -47,6 +61,10 @@ func (wb *writeBatch) Set(key, value []byte) (err error) {
// Delete deletes the given key prefixed with the table prefix
// from the database.
func (wb *writeBatch) Delete(key []byte) (err error) {
if wb.discarded {
return fmt.Errorf("%w", ErrWriteBatchDiscarded)
}

op := operation{
kind: operationDelete,
key: wb.prefix + string(key),
Expand All @@ -57,6 +75,10 @@ func (wb *writeBatch) Delete(key []byte) (err error) {

// Flush flushes the write batch to the database.
func (wb *writeBatch) Flush() (err error) {
if wb.discarded {
return fmt.Errorf("%w", ErrWriteBatchDiscarded)
}

wb.database.mutex.Lock()
defer wb.database.mutex.Unlock()
defer wb.Cancel()
Expand All @@ -75,5 +97,6 @@ func (wb *writeBatch) Flush() (err error) {

// Cancel cancels the write batch.
func (wb *writeBatch) Cancel() {
wb.discarded = true
wb.operations = nil
}

0 comments on commit d685c56

Please sign in to comment.