ledisdb/store/driver/batch.go

71 lines
1.1 KiB
Go
Raw Permalink Normal View History

2014-08-02 11:16:16 +04:00
package driver
2014-07-25 13:58:00 +04:00
import (
2014-11-20 17:52:29 +03:00
"github.com/syndtr/goleveldb/leveldb"
)
2014-08-02 11:16:16 +04:00
type BatchPuter interface {
2014-07-29 13:29:51 +04:00
BatchPut([]Write) error
2014-10-09 09:05:55 +04:00
SyncBatchPut([]Write) error
2014-07-29 13:29:51 +04:00
}
2014-07-25 13:58:00 +04:00
type Write struct {
Key []byte
Value []byte
}
type WriteBatch struct {
d *leveldb.Batch
wb []Write
w BatchPuter
2014-07-25 13:58:00 +04:00
}
2014-11-10 10:31:36 +03:00
func (wb *WriteBatch) Close() {
wb.d.Reset()
wb.wb = wb.wb[0:0]
}
func (wb *WriteBatch) Put(key, value []byte) {
2014-11-10 06:07:33 +03:00
if value == nil {
value = []byte{}
}
wb.wb = append(wb.wb, Write{key, value})
2014-07-25 13:58:00 +04:00
}
func (wb *WriteBatch) Delete(key []byte) {
wb.wb = append(wb.wb, Write{key, nil})
2014-07-25 13:58:00 +04:00
}
func (wb *WriteBatch) Commit() error {
return wb.w.BatchPut(wb.wb)
2014-07-25 13:58:00 +04:00
}
func (wb *WriteBatch) SyncCommit() error {
return wb.w.SyncBatchPut(wb.wb)
2014-10-09 09:05:55 +04:00
}
func (wb *WriteBatch) Rollback() error {
wb.wb = wb.wb[0:0]
2014-07-25 13:58:00 +04:00
return nil
}
2014-08-02 11:16:16 +04:00
func (wb *WriteBatch) Data() []byte {
wb.d.Reset()
for _, w := range wb.wb {
if w.Value == nil {
2014-11-10 06:07:33 +03:00
wb.d.Delete(w.Key)
} else {
2014-11-10 06:07:33 +03:00
wb.d.Put(w.Key, w.Value)
}
}
return wb.d.Dump()
}
func NewWriteBatch(puter BatchPuter) *WriteBatch {
return &WriteBatch{
&leveldb.Batch{},
[]Write{},
puter}
2014-08-02 11:16:16 +04:00
}