Code coverage report for src/transaction.js

Statements: 85.65% (191 / 223)      Branches: 66.96% (75 / 112)      Functions: 84.38% (27 / 32)      Lines: 85.65% (191 / 223)      Ignored: none     

All files » src/ » 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 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379        1   8 24 24 24     8 8 8 8 8 8 8   8                     8 16 16     8   8 8 8 8 8 8 8 8 8 8 8   8   16 16 16 16 16 16     8 29 29   29                 29 29 10       19   10     8 21   21     21   21 21   21   10 11   9 9 2   2 2           21 21 23 23   21 21 21 21 21   21 23     21   21           21 21 21   21   21 10 21 21         21     8 32 32   24 24 24 24 24       32     8 21   21 11 21         21 23 1 1   23 22     22   24 24       22     21     21   21 11   10       8                           8 21 21 11   21 11 11 11         8 43 43 76 23   43     8 10 7   3 3 3   10     10 10 10     8   8       8       8   8 32   32 1 1       1 31 23       23 8     8     32           8 4 4 4   4 4 4         4     8 8   8 9     8 8   8 3     8   2   2 2 2   2 4 4   4 4 2     2 4     2     8 1   8   8 1     8 8     8   8       1 1            
// # Transaction
// Can be used to send (many) cypher statement(s) as transaction
// see: [http://docs.neo4j.org/chunked/preview/rest-api-transactional.html](http://docs.neo4j.org/chunked/preview/rest-api-transactional.html)
 
var __initTransaction__ = function(neo4jrestful) {
 
  var Statement = function Statement(transaction, cypher, parameters) {
    this._transaction_  = transaction;
    this.statement = cypher;
    this.parameters = parameters;
  }
 
  Statement.prototype._transaction_ = null;
  Statement.prototype.statement = '';
  Statement.prototype.parameters = null;
  Statement.prototype.status = null; // 'sending', 'sended'
  Statement.prototype.position = null;
  Statement.prototype.results = null;
  Statement.prototype.errors = null;
 
  Statement.prototype.toObject = function() {
    return {
      statement: this.statement,
      parameters: JSON.stringify(this.parameters),
      status: this.status,
      position: this.position,
      errors: this.errors,
      results: this.results,
    };
  }
 
  var Transaction = function Transaction(cypher, parameters, cb) {
    this.neo4jrestful = neo4jrestful.singleton();
    this.begin(cypher, parameters, cb);
  }
 
  Transaction.Statement = Statement;
 
  Transaction.prototype.statements = null;
  Transaction.prototype._response_ = null;
  Transaction.prototype.neo4jrestful = null;
  Transaction.prototype.status = ''; // new|creating|open|committing|committed
  Transaction.prototype.id = null;
  Transaction.prototype.uri = null
  Transaction.prototype.expires = null;
  Transaction.prototype.results = null;
  Transaction.prototype._concurrentTransmissions_ = 0;
  Transaction.prototype._responseError_ = null; //will contain response Error
  Transaction.prototype._resortResults_ = true;
 
  Transaction.prototype.begin = function(cypher, parameters, cb) {
    // reset
    this.statements = [];
    this.results = [];
    this.errors = [];
    this.id = null;
    this.status = 'new';
    return this.add(cypher, parameters, cb);
  }
 
  Transaction.prototype.add = function(cypher, parameters, cb) {
    var args = Transaction._sortTransactionArguments(cypher, parameters, cb);
    var statements = args.statements;
    // we cancel the operation if we are comitting
    Iif (this.status === 'committed') {
      var err = Error("You can't add statements after transaction is committed");
      if (typeof args.cb === 'function') {
        cb(err, null);
      } else {
        throw err;
      }
      return this;
    }
    this.addStatementsToQueue(statements);
    if (args.cb) {
      cb = args.cb;
    } else {
      // we execute if we have a callback
      // till then we'll collect the statements
      return this;
    }
    return this.exec(cb);
  }
 
  Transaction.prototype.exec = function(cb) {
    var self = this;
    // stop here if there is no callback attached
    Iif (typeof cb !== 'function') {
      return this;
    }
    self.onResponse = cb;
 
    var url = '';
    var untransmittedStatements = this.untransmittedStatements();
 
    if (this.status === 'committing') {
      // commit transaction
      url = (this.id) ? '/transaction/'+this.id+'/commit' : '/transaction/commit';
    } else if (!this.id) {
      // begin a transaction
      this.status = 'creating';
      url = '/transaction';
    } else Eif (this.status === 'open') {
      // add to transaction
      this.status = 'adding';
      url = '/transaction/'+this.id;
    } else if (this.status = 'committed') {
      cb(Error('Transaction is committed. Create a new transaction instead.'), null, null);
    } else {
      throw Error('Transaction has a unknown status. Possible are: creating|open|committing|committed');
    }
    var statements = [];
    untransmittedStatements.forEach(function(statement, i){
      self.statements[i].status = 'sending';
      statements.push({ statement: statement.statement, parameters: statement.parameters });
    });
    this._concurrentTransmissions_++;
    this.neo4jrestful.post(url, { data: { statements: statements } }, function(err, response, debug) {
      self._response_ = response;
      self._concurrentTransmissions_--;
      self._applyResponse(err, response, debug, untransmittedStatements);
 
      untransmittedStatements.forEach(function(statement) {
        self.statements[statement.position].status = statement.status = 'sended';
      });
 
      untransmittedStatements = self.untransmittedStatements();
 
      Iif (untransmittedStatements.length > 0) {
        // re call exec() until all statements are transmitted
        // TODO: set a limit to avoid endless loop
        return self.exec(cb);
      }
      // TODO: sort and populate resultset, but currently no good way to detect result objects
      else Eif (self._concurrentTransmissions_ === 0) {//  {
        Eif (typeof self.onResponse === 'function') {
          var cb = self.onResponse;
          // release onResponse for (optional) next cb
          self.onResponse = null;
          // call final callback
          if (self.status === 'committing')
            self.status = 'committed';
          cb(self._responseError_, self, debug);
          return self;
        }
      }
    });
 
    return this;
  }
 
  Transaction.prototype.addStatementsToQueue = function(statements) {
    var self = this;
    if ((statements) && (statements.constructor === Array) && (statements.length > 0)) {
      // attach all statments
      statements.forEach(function(data){
        Eif (data.statement) {
          var statement = new Statement(self, data.statement, data.parameters);
          statement.position = self.statements.length;
          self.statements.push(statement);
        }
      });
    }
    return this;
  }
 
  Transaction.prototype._applyResponse = function(err, response, debug, untransmittedStatements) {
    var self = this;
    // if error on request/response
    if (self.status !== 'committing')
      self.status = 'open';
    Iif (err) {
      self.status = (err.status) ? err.status : err;
      if (!self.status)
        self.status = self._response_.status;
    }
    untransmittedStatements.forEach(function(statement, i){
      if (response.errors[i]) {
        statement.error = response.errors[i];
        self.errors.push(response.errors[i]);
      }
      if (response.results[i]) {
        Eif (self._resortResults_) {
          // move row property one level above
          // { rows: [ {}, {} ]} -> { [ {}, {} ]}
          response.results[i].data.forEach(function(data, j){
            //if ((response.results[i]) && (data.row)) {
            Eif (data.row) {
              response.results[i].data[j] = data.row;
            }
          })
        }
        self.results.push(response.results[i]);
      }
    });
    Iif ((err)||(!response)) {
      self._responseError_ = (self._responseError_) ? self._responseError_.push(err) : self._responseError_ = [ err ];
    } else {
      self.populateWithDataFromResponse(response);
      // keep track of open transactions
      if (self.status === 'open')
        Transaction.__open_transactions__[self.id] = self;
      else
        delete Transaction.__open_transactions__[self.id];
    }
  }
 
  Transaction.prototype.toObject = function() {
    var statements = [];
    this.statements.forEach(function(stat){
      statements.push(stat.toObject());
    });
    return {
      id: this.id,
      status: this.status,
      statements: statements,
      expires: this.expires,
      uri: this.uri,
    };
  }
 
  Transaction.prototype.populateWithDataFromResponse = function(data) {
    Eif (data) {
      if ((data.transaction) && (data.transaction.expires))
        this.expires = new Date(data.transaction.expires);
      // exists only on POST a new transaction
      if (data.commit) {
        var match = data.commit.match(/^(.+?\/transaction\/(\d+))\/commit$/);
        this.id = Number(match[2]);
        this.uri = match[1];
      }
    }
  }
 
  Transaction.prototype.untransmittedStatements = function() {
    var statements = [];
    this.statements.forEach(function(statement){
      if ((statement)&&(!statement.status))
        statements.push(statement);
    });
    return statements;
  }
 
  Transaction.prototype.commit = function(cypher, parameters, cb) {
    if (typeof cypher === 'function') {
      cb = cypher;
    } else {
      var args = Transaction._sortTransactionArguments(cypher, parameters, cb);
      this.addStatementsToQueue(args.statements);
      cb = args.cb;
    }
    Iif (typeof cb !== 'function') {
      throw Error('You need to attach a callback an a commit/close operation');
    }
    this.onResponse = cb;
    this.status = 'committing';
    return this.exec(cb);
  }
 
  Transaction.prototype.close = Transaction.prototype.commit;
 
  Transaction.create = function(cypher, parameters, cb) {
    return new Transaction(cypher, parameters, cb);
  }
 
  Transaction.new = function(cypher, parameters) {
    return new Transaction(cypher, parameters);
  }
 
  Transaction.prototype.onResponse = null;
 
  Transaction._sortTransactionArguments = function(cypher, parameters, cb) {
    var statements = null;
    // we might have a Graph or CypherQuery Object
    if ((typeof cypher === 'object') && ((typeof cypher.toQuery === 'function') || (typeof cypher.statementsToString === 'function'))) {
      Eif (cypher.toQuery) {
        statements = [ { statement: cypher.toQuery().statementsToString(), parameters: cypher.parameters() }];
      } else {
        statements = [ { statement: cypher.statementsToString(), parameters: cypher.parameters() }];
      }
      cb = parameters;
    } else if (typeof cypher === 'string') {
      Iif (typeof parameters === 'function') {
        cb = parameters;
        parameters = {};
      }
      statements = [ { statement: cypher, parameters: parameters || {} } ];
    } else Iif ((cypher) && (cypher.constructor === Array)) {
      cb = parameters;
      statements = cypher;
    } else Iif ((cypher) && (cypher.statement)) {
      statements = [ cypher ];
    }
    return {
      statements: statements,
      cb: cb || null
    }
  }
 
  Transaction.prototype.rollback = function(cb) {
    var self = this;
    Eif ((this.id)&&(this.status!=='finalized')) {
      this.neo4jrestful.delete('/transaction/'+this.id, function(err, res, debug) {
        // remove from open_transactions
        Eif (!err)
          delete Transaction.__open_transactions__[self.id];
        cb(err, res, debug);
      });
    } else {
      cb(Error('You can only perform a rollback on an open transaction.'), null);
    }
    return this;
  }
 
  Transaction.prototype.undo   = Transaction.prototype.rollback;
  Transaction.prototype.delete = Transaction.prototype.rollback;
 
  Transaction.begin = function(cypher, parameters, cb) {
    return new Transaction(cypher, parameters, cb);
  }
 
  Transaction.create = Transaction.begin;
  Transaction.open = Transaction.begin;
 
  Transaction.commit = function(cypher, parameters, cb) {
    return new Transaction().commit(cypher, parameters, cb);
  }
 
  Transaction.executeAllOpenTransactions = function(cb, action) {
    // action can be commit|rollback
    Iif (typeof action === 'undefined')
      action = 'commit';
    var count = Object.keys(Transaction.__open_transactions__).length;
    var errors = [];
    var debugs = [];
 
    var _onDone_ = function(err, res, debug) {
      count--;
      Iif (err)
        errors.push(err);
      debugs.push(debug);
      if (count === 0)
        cb( ((errors.length > 0) ? errors : null), null, debugs );
    }
 
    for (var id in Transaction.__open_transactions__) {
      Transaction.__open_transactions__[id][action](_onDone_);
    }
 
    return this;
  }
 
  Transaction.commitAll   = function(cb) {
    return this.executeAllOpenTransactions(cb, 'commit');
  }
  Transaction.closeAll    = Transaction.commitAll;
 
  Transaction.rollbackAll = function(cb) {
    Transaction.executeAllOpenTransactions(cb, 'rollback');
  }
 
  Transaction.deleteAll   = Transaction.rollbackAll;
  Transaction.undoAll     = Transaction.rollbackAll;
 
  // all open transactions
  Transaction.__open_transactions__ = {};
 
  return neo4jrestful.Transaction = Transaction;
 
}
 
Eif (typeof window !== 'object') {
  module.exports = exports = {
    init: __initTransaction__
  };
} else {
  window.Neo4jMapper.initTransaction = __initTransaction__;
}