Skip to content

Commit

Permalink
Merge pull request #6110 from filecoin-project/opt/elvindu/blockstore…
Browse files Browse the repository at this point in the history
…-has-check

add check before write badger / 添加检查已经存在,在写入之前
  • Loading branch information
simlecode authored Aug 21, 2023
2 parents 9b2bf79 + 4f85a4f commit 712e6d8
Showing 1 changed file with 28 additions and 0 deletions.
28 changes: 28 additions & 0 deletions venus-shared/blockstore/badger.go
Original file line number Diff line number Diff line change
Expand Up @@ -309,6 +309,20 @@ func (b *BadgerBlockstore) Put(ctx context.Context, block blocks.Block) error {
return nil
}

// Check if we have it before writing it.
switch err := b.DB.View(func(txn *badger.Txn) error {
_, err := txn.Get(key.Bytes())
return err
}); err {
case badger.ErrKeyNotFound:
case nil:
b.cache.Add(key.String(), block)
// Already exists, skip the put.
return nil
default:
return err
}

err := b.DB.Update(func(txn *badger.Txn) error {
err := txn.Set(key.Bytes(), block.RawData())
if err == nil {
Expand Down Expand Up @@ -338,6 +352,20 @@ func (b *BadgerBlockstore) PutMany(ctx context.Context, blks []blocks.Block) err
continue
}

// Check if we have it before writing it.
switch err := b.DB.View(func(txn *badger.Txn) error {
_, err := txn.Get(key.Bytes())
return err
}); err {
case badger.ErrKeyNotFound:
case nil:
// skipped because we already have it.
continue
default:
// Something is actually wrong
return err
}

if err := batch.Set(key.Bytes(), block.RawData()); err != nil {
return err
}
Expand Down

0 comments on commit 712e6d8

Please sign in to comment.