knex/lib/transaction.js

85 lines
2.2 KiB
JavaScript
Raw Normal View History

2013-09-13 16:58:38 -04:00
// Transaction
// -------
(function(define) {
"use strict";
define(function(require, exports) {
var Promise = require('./promise').Promise;
2013-11-25 02:00:12 -05:00
var _ = require('lodash');
2013-09-17 07:15:18 -04:00
// 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-09-04 20:47:27 -04:00
var Transaction = function(instance) {
2013-09-05 16:36:49 -04:00
this.client = instance.client;
2013-09-04 20:47:27 -04:00
};
2013-09-05 16:36:49 -04:00
Transaction.prototype = {
2013-09-05 16:36:49 -04:00
// Passed a `container` function, this method runs the current
// transaction, returning a promise.
run: function(container, connection) {
return this.client.startTransaction(connection)
.bind(this)
2013-09-05 16:36:49 -04:00
.then(this.getContainerObject)
.then(this.initiateDeferred(container))
.bind();
2013-09-05 16:36:49 -04:00
},
2013-09-05 16:36:49 -04:00
getContainerObject: function(connection) {
2013-09-05 16:36:49 -04:00
// The client we need to call `finishTransaction` on.
var client = this.client;
// The object passed around inside the transaction container.
var containerObj = {
2013-09-05 16:36:49 -04:00
commit: function(message) {
client.finishTransaction('commit', this, message);
},
2013-09-05 16:36:49 -04:00
rollback: function(error) {
client.finishTransaction('rollback', this, error);
},
2013-09-05 16:36:49 -04:00
// "rollback to"?
connection: connection
};
// Ensure the transacting object methods are bound with the correct context.
_.bindAll(containerObj, 'commit', 'rollback');
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);
// Return the promise for the entire transaction.
return dfd.promise;
};
}
};
2013-09-04 20:47:27 -04:00
exports.Transaction = Transaction;
});
})(
typeof define === 'function' && define.amd ? define : function (factory) { factory(require, exports, module); }
);