Commit bebd894c authored by Steven Allen's avatar Steven Allen

make BasicBatch handle concurrent puts/deletes

parent f24a416e
package datastore package datastore
type verb int
type op struct {
delete bool
value []byte
}
// basicBatch implements the transaction interface for datastores who do // basicBatch implements the transaction interface for datastores who do
// not have any sort of underlying transactional support // not have any sort of underlying transactional support
type basicBatch struct { type basicBatch struct {
puts map[Key][]byte ops map[Key]op
deletes map[Key]struct{}
target Datastore target Datastore
} }
func NewBasicBatch(ds Datastore) Batch { func NewBasicBatch(ds Datastore) Batch {
return &basicBatch{ return &basicBatch{
puts: make(map[Key][]byte), ops: make(map[Key]op),
deletes: make(map[Key]struct{}),
target: ds, target: ds,
} }
} }
func (bt *basicBatch) Put(key Key, val []byte) error { func (bt *basicBatch) Put(key Key, val []byte) error {
bt.puts[key] = val bt.ops[key] = op{value: val}
return nil return nil
} }
func (bt *basicBatch) Delete(key Key) error { func (bt *basicBatch) Delete(key Key) error {
bt.deletes[key] = struct{}{} bt.ops[key] = op{delete: true}
return nil return nil
} }
func (bt *basicBatch) Commit() error { func (bt *basicBatch) Commit() error {
for k, val := range bt.puts { var err error
if err := bt.target.Put(k, val); err != nil { for k, op := range bt.ops {
return err if op.delete {
err = bt.target.Delete(k)
// We could try to do something smarter but I really
// don't care. Delete should be idempotent anyways.
if err == ErrNotFound {
err = nil
} }
} else {
err = bt.target.Put(k, op.value)
} }
if err != nil {
for k, _ := range bt.deletes { break
if err := bt.target.Delete(k); err != nil {
return err
} }
} }
return nil return err
} }
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment