batch.go 847 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 {
Jeromy's avatar
Jeromy committed
6 7 8 9 10 11
	puts    map[Key]interface{}
	deletes map[Key]struct{}

	target Datastore
}

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

Jeromy's avatar
Jeromy committed
20
func (bt *basicBatch) Put(key Key, val interface{}) 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
}