status-go/vendor/github.com/ipfs/go-datastore/batch.go

54 lines
920 B
Go
Raw Normal View History

2021-10-12 12:39:28 +00:00
package datastore
2022-04-01 16:16:46 +00:00
import (
"context"
)
2021-10-12 12:39:28 +00:00
type op struct {
delete bool
value []byte
}
// basicBatch implements the transaction interface for datastores who do
// not have any sort of underlying transactional support
type basicBatch struct {
ops map[Key]op
target Datastore
}
2022-04-01 16:16:46 +00:00
var _ Batch = (*basicBatch)(nil)
2021-10-12 12:39:28 +00:00
func NewBasicBatch(ds Datastore) Batch {
return &basicBatch{
ops: make(map[Key]op),
target: ds,
}
}
2022-04-01 16:16:46 +00:00
func (bt *basicBatch) Put(ctx context.Context, key Key, val []byte) error {
2021-10-12 12:39:28 +00:00
bt.ops[key] = op{value: val}
return nil
}
2022-04-01 16:16:46 +00:00
func (bt *basicBatch) Delete(ctx context.Context, key Key) error {
2021-10-12 12:39:28 +00:00
bt.ops[key] = op{delete: true}
return nil
}
2022-04-01 16:16:46 +00:00
func (bt *basicBatch) Commit(ctx context.Context) error {
2021-10-12 12:39:28 +00:00
var err error
for k, op := range bt.ops {
if op.delete {
2022-04-01 16:16:46 +00:00
err = bt.target.Delete(ctx, k)
2021-10-12 12:39:28 +00:00
} else {
2022-04-01 16:16:46 +00:00
err = bt.target.Put(ctx, k, op.value)
2021-10-12 12:39:28 +00:00
}
if err != nil {
break
}
}
return err
}