Skip to content

Instantly share code, notes, and snippets.

@StarpTech
Last active December 16, 2015 16:23
Show Gist options
  • Save StarpTech/ca0f923c49fd956c1c13 to your computer and use it in GitHub Desktop.
Save StarpTech/ca0f923c49fd956c1c13 to your computer and use it in GitHub Desktop.
Transaction Builder for Orientdb in NodeJs
/* ----------------------------Transaction Builder-------------------------------
Spec: https://github.com/orientechnologies/orientdb/wiki/SQL-batch
- Bluebird promise library
EXAMPLE:
var tx = new Transaction();
var s0 = tx.add(query1);
var s1 = tx.add(query2); //In query2 you can use the result of query1 with $0 ($<index>)
tx.commit().return([s0, s1]).all().then(function(result) {
return result;
}).catch(function(e) {
console.error(e.stack);
Promise.reject(e);
});
*/
function Transaction() {
this.newLine = '\n';
this.statements = ['begin' + this.newLine];
this.i = 0;
this.debug = false;
this.retrys = 10;
this.tPrefix = 't';
}
Transaction.prototype.add = function(statement, lock) {
var transactionId = this.tPrefix + (this.i++);
this.statements.push('LET ' + transactionId + ' = ' + statement + (lock ? ' lock record' : '') + this.newLine);
return '$' + transactionId;
}
Transaction.prototype.commit = function(retrys) {
this.statements.push('commit' + (retrys ? ' retry ' + retrys : '') + this.newLine);
return this;
}
Transaction.prototype.rollback = function() {
this.statements.push('rollback' + this.newLine);
return this;
}
Transaction.prototype.return = function(returnStatements) {
if (_.isArray(returnStatements)) {
var statements = '[' + returnStatements.join(',') + ']';
this.statements.push('return ' + statements + this.newLine);
} else {
this.statements.push('return ' + returnStatements);
}
return this;
}
Transaction.prototype.all = function() {
var resolver = Promise.pending();
var query = this.getQuery();
if (this.debug) {
console.log(query);
}
db.query(query, {
class: 's'
}).then(function(result) {
resolver.resolve(result);
}).error(function(err) {
resolver.reject(err);
});
return resolver.promise;
}
Transaction.prototype.getQuery = function() {
return _.reduce(this.statements, function(sum, n) {
return sum + n;
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment