leveldb
Version:
Bindings for using LevelDB through node.
165 lines (124 loc) • 3.4 kB
JavaScript
// Generated by CoffeeScript 1.3.3
var Batch, binding, noop;
binding = require('../../build/Release/leveldb.node');
noop = function() {};
/*
A batch holds a sequence of put/delete operations to atomically write to
the database.
Usage:
var leveldb = require('leveldb');
var db, db2, batch, batch2 = new leveldb.Batch, writes = 2;
leveldb.open('/tmp/test.db', onOpen);
function onOpen(err, handle) {
db = handle;
batch = db.batch();
batch
.put('foo', 'bar')
.del('baz')
.put('pass', 'xyzzy')
.write(afterWrite);
}
function afterWrite(err) {
leveldb.open('/tmp/test2.db', onOpen2);
}
function onOpen2(err, handle) {
db2 = handle;
batch2
.put('foo', 'coconut')
.del('pass');
db.write(batch2, afterWrite2);
db2.write(batch2, afterWrite2);
}
function afterWrite2(err) {
writes -= 1;
if (writes <= 0) {
// batch2 has not been cleared to allow for reuse.
batch2.clear();
// works because the batch is cleared after committing when using
// batch.commit()
batch
.put('hello', 'world')
.put('goodbye', 'world');
db.write(batch);
db2.write(batch);
}
}
*/
exports.Batch = Batch = (function() {
/*
Constructor.
@param {leveldb.Handle} [handle] Pass a database handle to use with
`batch.write()` or `batch.writeSync()`.
*/
function Batch(handle) {
this.handle = handle;
this.self = new binding.Batch;
this.readLock_ = 0;
}
/*
Add a put operation to the batch.
@param {String|Buffer} key The key to put.
@param {String|Buffer} val The value to put.
*/
Batch.prototype.put = function(key, val) {
if (this.readLock_ > 0) {
throw 'Read locked';
}
if (!Buffer.isBuffer(key)) {
key = new Buffer(key);
}
if (!Buffer.isBuffer(val)) {
val = new Buffer(val);
}
this.self.put(key, val);
return this;
};
/*
Add a delete operation to the batch.
@param {String|Buffer} key The key to delete.
*/
Batch.prototype.del = function(key) {
if (this.readLock_ > 0) {
throw 'Read locked';
}
if (!Buffer.isBuffer(key)) {
key = new Buffer(key);
}
this.self.del(key);
return this;
};
/*
Commit the batch operations to disk.
See `Handle.write()`.
*/
Batch.prototype.write = function(options, callback) {
var _this = this;
if (!this.handle) {
throw new Error('No handle');
}
++this.readLock_;
if (typeof options === 'function') {
callback = options;
options = null;
}
callback || (callback = noop);
return this.handle.write(this.self, options, function(err) {
--_this.readLock_;
if (!err) {
_this.self.clear();
}
return callback(err);
});
};
/*
Reset this batch instance by removing all pending operations.
*/
Batch.prototype.clear = function() {
if (this.readLock_ > 0) {
throw 'Read locked';
}
this.self.clear();
return this;
};
return Batch;
})();