2014-08-02 11:16:16 +04:00
|
|
|
package driver
|
2014-07-25 13:58:00 +04:00
|
|
|
|
2014-11-09 18:10:03 +03:00
|
|
|
import (
|
|
|
|
"github.com/siddontang/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 {
|
2014-11-09 18:10:03 +03:00
|
|
|
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]
|
|
|
|
}
|
|
|
|
|
2014-11-09 18:10:03 +03:00
|
|
|
func (wb *WriteBatch) Put(key, value []byte) {
|
2014-11-10 06:07:33 +03:00
|
|
|
if value == nil {
|
|
|
|
value = []byte{}
|
|
|
|
}
|
2014-11-09 18:10:03 +03:00
|
|
|
wb.wb = append(wb.wb, Write{key, value})
|
2014-07-25 13:58:00 +04:00
|
|
|
}
|
|
|
|
|
2014-11-09 18:10:03 +03:00
|
|
|
func (wb *WriteBatch) Delete(key []byte) {
|
|
|
|
wb.wb = append(wb.wb, Write{key, nil})
|
2014-07-25 13:58:00 +04:00
|
|
|
}
|
|
|
|
|
2014-11-09 18:10:03 +03:00
|
|
|
func (wb *WriteBatch) Commit() error {
|
|
|
|
return wb.w.BatchPut(wb.wb)
|
2014-07-25 13:58:00 +04:00
|
|
|
}
|
|
|
|
|
2014-11-09 18:10:03 +03:00
|
|
|
func (wb *WriteBatch) SyncCommit() error {
|
|
|
|
return wb.w.SyncBatchPut(wb.wb)
|
2014-10-09 09:05:55 +04:00
|
|
|
}
|
|
|
|
|
2014-11-09 18:10:03 +03: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
|
|
|
|
2014-11-09 18:10:03 +03: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)
|
2014-11-09 18:10:03 +03:00
|
|
|
} else {
|
2014-11-10 06:07:33 +03:00
|
|
|
wb.d.Put(w.Key, w.Value)
|
2014-11-09 18:10:03 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
return wb.d.Dump()
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewWriteBatch(puter BatchPuter) *WriteBatch {
|
|
|
|
return &WriteBatch{
|
|
|
|
&leveldb.Batch{},
|
|
|
|
[]Write{},
|
|
|
|
puter}
|
2014-08-02 11:16:16 +04:00
|
|
|
}
|