2014-07-26 14:39:54 +04:00
|
|
|
// +build rocksdb
|
|
|
|
|
|
|
|
package rocksdb
|
|
|
|
|
|
|
|
// #cgo LDFLAGS: -lrocksdb
|
|
|
|
// #include "rocksdb/c.h"
|
2014-10-30 06:43:04 +03:00
|
|
|
// #include "rocksdb_ext.h"
|
2014-07-26 14:39:54 +04:00
|
|
|
import "C"
|
|
|
|
|
|
|
|
import (
|
|
|
|
"unsafe"
|
|
|
|
)
|
|
|
|
|
|
|
|
type WriteBatch struct {
|
2014-10-30 06:43:04 +03:00
|
|
|
db *DB
|
|
|
|
wbatch *C.rocksdb_writebatch_t
|
|
|
|
commitOk bool
|
2014-07-26 14:39:54 +04:00
|
|
|
}
|
|
|
|
|
2014-11-10 10:31:36 +03:00
|
|
|
func (w *WriteBatch) Close() {
|
|
|
|
if w.wbatch != nil {
|
|
|
|
C.rocksdb_writebatch_destroy(w.wbatch)
|
|
|
|
w.wbatch = nil
|
|
|
|
}
|
2014-07-26 14:39:54 +04:00
|
|
|
}
|
|
|
|
|
|
|
|
func (w *WriteBatch) Put(key, value []byte) {
|
2014-10-30 06:43:04 +03:00
|
|
|
w.commitOk = false
|
|
|
|
|
2014-07-26 14:39:54 +04:00
|
|
|
var k, v *C.char
|
|
|
|
if len(key) != 0 {
|
|
|
|
k = (*C.char)(unsafe.Pointer(&key[0]))
|
|
|
|
}
|
|
|
|
if len(value) != 0 {
|
|
|
|
v = (*C.char)(unsafe.Pointer(&value[0]))
|
|
|
|
}
|
|
|
|
|
|
|
|
lenk := len(key)
|
|
|
|
lenv := len(value)
|
|
|
|
|
|
|
|
C.rocksdb_writebatch_put(w.wbatch, k, C.size_t(lenk), v, C.size_t(lenv))
|
|
|
|
}
|
|
|
|
|
|
|
|
func (w *WriteBatch) Delete(key []byte) {
|
2014-10-30 06:43:04 +03:00
|
|
|
w.commitOk = false
|
|
|
|
|
2014-07-26 14:39:54 +04:00
|
|
|
C.rocksdb_writebatch_delete(w.wbatch,
|
|
|
|
(*C.char)(unsafe.Pointer(&key[0])), C.size_t(len(key)))
|
|
|
|
}
|
|
|
|
|
|
|
|
func (w *WriteBatch) Commit() error {
|
|
|
|
return w.commit(w.db.writeOpts)
|
|
|
|
}
|
|
|
|
|
2014-10-09 09:05:55 +04:00
|
|
|
func (w *WriteBatch) SyncCommit() error {
|
|
|
|
return w.commit(w.db.syncOpts)
|
|
|
|
}
|
|
|
|
|
2014-07-26 14:39:54 +04:00
|
|
|
func (w *WriteBatch) Rollback() error {
|
2014-10-30 06:43:04 +03:00
|
|
|
if !w.commitOk {
|
|
|
|
C.rocksdb_writebatch_clear(w.wbatch)
|
|
|
|
}
|
2014-07-26 14:39:54 +04:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (w *WriteBatch) commit(wb *WriteOptions) error {
|
2014-10-30 06:43:04 +03:00
|
|
|
w.commitOk = true
|
|
|
|
|
2014-07-26 14:39:54 +04:00
|
|
|
var errStr *C.char
|
2014-10-30 06:43:04 +03:00
|
|
|
C.rocksdb_write_ext(w.db.db, wb.Opt, w.wbatch, &errStr)
|
2014-07-26 14:39:54 +04:00
|
|
|
if errStr != nil {
|
2014-10-30 06:43:04 +03:00
|
|
|
w.commitOk = false
|
2014-07-26 14:39:54 +04:00
|
|
|
return saveError(errStr)
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
2014-11-09 18:10:03 +03:00
|
|
|
|
2017-03-12 16:21:49 +03:00
|
|
|
const batchDataHeadLen = 12
|
|
|
|
|
2014-11-09 18:10:03 +03:00
|
|
|
func (w *WriteBatch) Data() []byte {
|
|
|
|
var vallen C.size_t
|
|
|
|
value := C.rocksdb_writebatch_data(w.wbatch, &vallen)
|
|
|
|
|
2017-03-12 16:21:49 +03:00
|
|
|
buf := slice(unsafe.Pointer(value), int(vallen))
|
|
|
|
return buf[batchDataHeadLen:]
|
2014-11-09 18:10:03 +03:00
|
|
|
}
|