knex/lib/transaction.js

72 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');
var _ = require('lodash');
// 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.
2013-12-27 14:44:21 -05:00
var Transaction = module.exports = function Transaction(client) {
this.client = client;
this.flags = {};
};
2013-12-27 14:44:21 -05:00
_.extend(Transaction.prototype, {
// Passed a `container` function, this method runs the current
// transaction, returning a promise.
2013-12-27 14:44:21 -05:00
run: Promise.method(function Transaction$run(container) {
return this.client.startTransaction()
.bind(this)
.then(this.getContainerObject)
2013-12-27 14:44:21 -05:00
.then(this.initiateDeferred(container));
}),
getContainerObject: function(connection) {
2013-09-04 20:47:27 -04:00
// The client we need to call `finishTransaction` on.
var client = this.client;
// The object passed around inside the transaction container.
var containerObj = {
commit: function(message) {
2013-12-27 14:44:21 -05:00
client.finishTransaction('commit', containerObj, message);
},
rollback: function(error) {
2013-12-27 14:44:21 -05:00
client.finishTransaction('rollback', containerObj, error);
},
// "rollback to"?
connection: connection
};
2013-09-05 16:36:49 -04:00
// Ensure the transacting object methods are bound with the correct context.
2013-12-27 14:44:21 -05:00
// _.bindAll(containerObj, 'commit', 'rollback');
2013-09-05 16:36:49 -04:00
return containerObj;
},
2013-09-05 16:36:49 -04:00
initiateDeferred: function(container) {
return function(containerObj) {
// Initiate a deferred object, so we know when the
// transaction completes or fails, we know what to do.
var dfd = containerObj.dfd = Promise.pending();
2013-09-05 16:36:49 -04:00
// Call the container with the transaction
// commit & rollback objects.
container(containerObj);
2013-09-05 16:36:49 -04:00
// Return the promise for the entire transaction.
return dfd.promise;
2013-09-05 16:36:49 -04:00
};
2013-09-05 16:36:49 -04:00
}
2013-09-05 16:36:49 -04:00
2013-12-27 14:44:21 -05:00
});