batch.go 832 Bytes
Newer Older
Jeromy's avatar
Jeromy committed
1 2
package datastore

Jeromy's avatar
Jeromy committed
3
// basicBatch implements the transaction interface for datastores who do
Jeromy's avatar
Jeromy committed
4
// not have any sort of underlying transactional support
Jeromy's avatar
Jeromy committed
5
type basicBatch struct {
6
	puts    map[Key][]byte
Jeromy's avatar
Jeromy committed
7 8 9 10 11
	deletes map[Key]struct{}

	target Datastore
}

Jeromy's avatar
Jeromy committed
12 13
func NewBasicBatch(ds Datastore) Batch {
	return &basicBatch{
14
		puts:    make(map[Key][]byte),
Jeromy's avatar
Jeromy committed
15 16 17 18 19
		deletes: make(map[Key]struct{}),
		target:  ds,
	}
}

20
func (bt *basicBatch) Put(key Key, val []byte) error {
Jeromy's avatar
Jeromy committed
21 22 23 24
	bt.puts[key] = val
	return nil
}

Jeromy's avatar
Jeromy committed
25
func (bt *basicBatch) Delete(key Key) error {
Jeromy's avatar
Jeromy committed
26 27 28 29
	bt.deletes[key] = struct{}{}
	return nil
}

Jeromy's avatar
Jeromy committed
30
func (bt *basicBatch) Commit() error {
Jeromy's avatar
Jeromy committed
31 32 33 34 35 36 37 38 39 40 41 42 43 44
	for k, val := range bt.puts {
		if err := bt.target.Put(k, val); err != nil {
			return err
		}
	}

	for k, _ := range bt.deletes {
		if err := bt.target.Delete(k); err != nil {
			return err
		}
	}

	return nil
}