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

Statements: 95.83% (46 / 48)      Branches: 92.86% (13 / 14)      Functions: 87.5% (7 / 8)      Lines: 95.83% (46 / 48)      Ignored: 1 branch     

All files » lib/adapters/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 85              1   1 83389 83389 83389 83389 16325 16325   83389     1 7179 7179     1 28839 28839 28839 1493 1493   27346         27346 27346   15963 15963   15963   11383 11383       1 30918 54550   54550   54550 53377   1173     30918     1   6751 6751     6751 54550 54550 54550 3034   51516 51516     6751     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) {
      /* istanbul ignore else */
      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;