Code coverage report for lib/adapters/leveldb/leveldb-transaction.js

Statements: 95.83% (46 / 48)      Branches: 85.71% (12 / 14)      Functions: 87.5% (7 / 8)      Lines: 95.83% (46 / 48)      Ignored: none     

All files » lib/adapters/leveldb/ » leveldb-transaction.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84              1   1 39819 39819 39819 39819 12065 12065   39819     1 5394 5394     1 12983 12983 12983 1018 1018   11965         11965 11965 7609 7609   7609   4356 4356       1 14976 26836   26836   26836 26104   732     14976     1   5288 5288     5288 26836 26836 26836 2560   24276 24276     5288     1
'use strict';
 
// similar to an idb or websql transaction object
// designed to be passed around. basically just caches
// things in-memory and then does a big batch() operation
// when you're done
 
var utils = require('../../utils');
 
function getCacheFor(transaction, store) {
  var prefix = store.prefix();
  var cache = transaction._cache;
  var subCache = cache.get(prefix);
  if (!subCache) {
    subCache = new utils.Map();
    cache.set(prefix, subCache);
  }
  return subCache;
}
 
function LevelTransaction() {
  this._batch = [];
  this._cache = new utils.Map();
}
 
LevelTransaction.prototype.get = function (store, key, callback) {
  var cache = getCacheFor(this, store);
  var exists = cache.get(key);
  if (exists) {
    return process.nextTick(function () {
      callback(null, exists);
    });
  } else Iif (exists === null) { // deleted marker
    return process.nextTick(function () {
      callback({name: 'NotFoundError'});
    });
  }
  store.get(key, function (err, res) {
    if (err) {
      Eif (err.name === 'NotFoundError') {
        cache.set(key, null);
      }
      return callback(err);
    }
    cache.set(key, res);
    callback(null, res);
  });
};
 
LevelTransaction.prototype.batch = function (batch) {
  for (var i = 0, len = batch.length; i < len; i++) {
    var operation = batch[i];
 
    var cache = getCacheFor(this, operation.prefix);
 
    if (operation.type === 'put') {
      cache.set(operation.key, operation.value);
    } else {
      cache.set(operation.key, null);
    }
  }
  this._batch = this._batch.concat(batch);
};
 
LevelTransaction.prototype.execute = function (db, callback) {
 
  var keys = new utils.Set();
  var uniqBatches = [];
 
  // remove duplicates; last one wins
  for (var i = this._batch.length - 1; i >= 0; i--) {
    var operation = this._batch[i];
    var lookupKey = operation.prefix.prefix() + '\xff' + operation.key;
    if (keys.has(lookupKey)) {
      continue;
    }
    keys.add(lookupKey);
    uniqBatches.push(operation);
  }
 
  db.batch(uniqBatches, callback);
};
 
module.exports = LevelTransaction;