knex/lib/transaction.js

62 lines
1.9 KiB
JavaScript
Raw Normal View History

2013-09-13 16:58:38 -04:00
// Transaction
// -------
2013-12-27 14:44:21 -05:00
var Promise = require('./promise');
// Creates a new wrapper object for constructing a transaction.
// Called by the `knex.transaction`, which sets the correct client
// and handles the `container` object, passing along the correct
// `connection` to keep all of the transactions on the correct connection.
function Transaction(container) {
this.container = container;
}
// Build the object passed around inside the transaction container.
Transaction.prototype.containerObject = function(runner) {
2014-04-09 10:11:41 -04:00
var containerObj = {
commit: function(message) {
2014-04-09 10:11:41 -04:00
return containerObj._runner.finishTransaction(0, this, message);
},
rollback: function(error) {
2014-04-09 10:11:41 -04:00
return containerObj._runner.finishTransaction(1, this, error);
},
_runner: runner
};
2014-04-09 10:11:41 -04:00
return containerObj;
};
Transaction.prototype.initiateDeferred = function(containerObj) {
// Initiate a deferred object, bound to the container object,
// so we know when the transaction completes or fails
// and can continue from there.
var dfd = containerObj._dfd = Promise.pending();
// Call the container with the transaction
// commit & rollback objects.
this.container(containerObj);
// Return the promise for the entire transaction.
2014-04-16 01:23:50 -04:00
return dfd.promise;
};
2013-09-05 16:36:49 -04:00
2014-04-16 01:23:50 -04:00
// Allow the `Transaction` object to be utilized with full access to the relevant
// promise API.
require('./interface')(Transaction);
// Passed a `container` function, this method runs the current
// transaction, returning a promise.
2014-04-16 01:23:50 -04:00
Transaction.prototype.then = function(onFulfilled, onRejected) {
var Runner = this.client.Runner;
// Create a new "runner" object, passing the "runner"
// object along, so we can easily keep track of every
// query run on the current connection.
return new Runner(this)
.startTransaction()
.bind(this)
.then(this.containerObject)
2014-04-16 01:23:50 -04:00
.then(this.initiateDeferred)
.then(onFulfilled, onRejected);
};
2013-09-05 16:36:49 -04:00
module.exports = Transaction;