transaction.js 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. 'use strict';
  2. exports.__esModule = true;
  3. var _create = require('babel-runtime/core-js/object/create');
  4. var _create2 = _interopRequireDefault(_create);
  5. var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
  6. var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
  7. var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');
  8. var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
  9. var _inherits2 = require('babel-runtime/helpers/inherits');
  10. var _inherits3 = _interopRequireDefault(_inherits2);
  11. var _uniqueId2 = require('lodash/uniqueId');
  12. var _uniqueId3 = _interopRequireDefault(_uniqueId2);
  13. var _bluebird = require('bluebird');
  14. var _bluebird2 = _interopRequireDefault(_bluebird);
  15. var _events = require('events');
  16. var _debug = require('debug');
  17. var _debug2 = _interopRequireDefault(_debug);
  18. var _makeKnex = require('./util/make-knex');
  19. var _makeKnex2 = _interopRequireDefault(_makeKnex);
  20. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  21. // Transaction
  22. // -------
  23. var debug = (0, _debug2.default)('knex:tx');
  24. // Acts as a facade for a Promise, keeping the internal state
  25. // and managing any child transactions.
  26. var Transaction = function (_EventEmitter) {
  27. (0, _inherits3.default)(Transaction, _EventEmitter);
  28. function Transaction(client, container, config, outerTx) {
  29. (0, _classCallCheck3.default)(this, Transaction);
  30. var _this = (0, _possibleConstructorReturn3.default)(this, _EventEmitter.call(this));
  31. var txid = _this.txid = (0, _uniqueId3.default)('trx');
  32. _this.client = client;
  33. _this.outerTx = outerTx;
  34. _this.trxClient = undefined;
  35. _this._debug = client.config && client.config.debug;
  36. debug('%s: Starting %s transaction', txid, outerTx ? 'nested' : 'top level');
  37. _this._promise = _bluebird2.default.using(_this.acquireConnection(client, config, txid), function (connection) {
  38. var trxClient = _this.trxClient = makeTxClient(_this, client, connection);
  39. var init = client.transacting ? _this.savepoint(connection) : _this.begin(connection);
  40. init.then(function () {
  41. return makeTransactor(_this, connection, trxClient);
  42. }).then(function (transactor) {
  43. // If we've returned a "thenable" from the transaction container, assume
  44. // the rollback and commit are chained to this object's success / failure.
  45. // Directly thrown errors are treated as automatic rollbacks.
  46. var result = void 0;
  47. try {
  48. result = container(transactor);
  49. } catch (err) {
  50. result = _bluebird2.default.reject(err);
  51. }
  52. if (result && result.then && typeof result.then === 'function') {
  53. result.then(function (val) {
  54. return transactor.commit(val);
  55. }).catch(function (err) {
  56. return transactor.rollback(err);
  57. });
  58. }
  59. return null;
  60. }).catch(function (e) {
  61. return _this._rejecter(e);
  62. });
  63. return new _bluebird2.default(function (resolver, rejecter) {
  64. _this._resolver = resolver;
  65. _this._rejecter = rejecter;
  66. });
  67. });
  68. _this._completed = false;
  69. // If there's a wrapping transaction, we need to wait for any older sibling
  70. // transactions to settle (commit or rollback) before we can start, and we
  71. // need to register ourselves with the parent transaction so any younger
  72. // siblings can wait for us to complete before they can start.
  73. _this._previousSibling = _bluebird2.default.resolve(true);
  74. if (outerTx) {
  75. if (outerTx._lastChild) _this._previousSibling = outerTx._lastChild;
  76. outerTx._lastChild = _this._promise;
  77. }
  78. return _this;
  79. }
  80. Transaction.prototype.isCompleted = function isCompleted() {
  81. return this._completed || this.outerTx && this.outerTx.isCompleted() || false;
  82. };
  83. Transaction.prototype.begin = function begin(conn) {
  84. return this.query(conn, 'BEGIN;');
  85. };
  86. Transaction.prototype.savepoint = function savepoint(conn) {
  87. return this.query(conn, 'SAVEPOINT ' + this.txid + ';');
  88. };
  89. Transaction.prototype.commit = function commit(conn, value) {
  90. return this.query(conn, 'COMMIT;', 1, value);
  91. };
  92. Transaction.prototype.release = function release(conn, value) {
  93. return this.query(conn, 'RELEASE SAVEPOINT ' + this.txid + ';', 1, value);
  94. };
  95. Transaction.prototype.rollback = function rollback(conn, error) {
  96. var _this2 = this;
  97. return this.query(conn, 'ROLLBACK;', 2, error).timeout(5000).catch(_bluebird2.default.TimeoutError, function () {
  98. _this2._resolver();
  99. });
  100. };
  101. Transaction.prototype.rollbackTo = function rollbackTo(conn, error) {
  102. var _this3 = this;
  103. return this.query(conn, 'ROLLBACK TO SAVEPOINT ' + this.txid, 2, error).timeout(5000).catch(_bluebird2.default.TimeoutError, function () {
  104. _this3._resolver();
  105. });
  106. };
  107. Transaction.prototype.query = function query(conn, sql, status, value) {
  108. var _this4 = this;
  109. var q = this.trxClient.query(conn, sql).catch(function (err) {
  110. status = 2;
  111. value = err;
  112. _this4._completed = true;
  113. debug('%s error running transaction query', _this4.txid);
  114. }).tap(function () {
  115. if (status === 1) _this4._resolver(value);
  116. if (status === 2) _this4._rejecter(value);
  117. });
  118. if (status === 1 || status === 2) {
  119. this._completed = true;
  120. }
  121. return q;
  122. };
  123. Transaction.prototype.debug = function debug(enabled) {
  124. this._debug = arguments.length ? enabled : true;
  125. return this;
  126. };
  127. // Acquire a connection and create a disposer - either using the one passed
  128. // via config or getting one off the client. The disposer will be called once
  129. // the original promise is marked completed.
  130. Transaction.prototype.acquireConnection = function acquireConnection(client, config, txid) {
  131. var configConnection = config && config.connection;
  132. return _bluebird2.default.try(function () {
  133. return configConnection || client.acquireConnection();
  134. }).disposer(function (connection) {
  135. if (!configConnection) {
  136. debug('%s: releasing connection', txid);
  137. client.releaseConnection(connection);
  138. } else {
  139. debug('%s: not releasing external connection', txid);
  140. }
  141. });
  142. };
  143. return Transaction;
  144. }(_events.EventEmitter);
  145. // The transactor is a full featured knex object, with a "commit", a "rollback"
  146. // and a "savepoint" function. The "savepoint" is just sugar for creating a new
  147. // transaction. If the rollback is run inside a savepoint, it rolls back to the
  148. // last savepoint - otherwise it rolls back the transaction.
  149. exports.default = Transaction;
  150. function makeTransactor(trx, connection, trxClient) {
  151. var transactor = (0, _makeKnex2.default)(trxClient);
  152. transactor.transaction = function (container, options) {
  153. return trxClient.transaction(container, options, trx);
  154. };
  155. transactor.savepoint = function (container, options) {
  156. return transactor.transaction(container, options);
  157. };
  158. if (trx.client.transacting) {
  159. transactor.commit = function (value) {
  160. return trx.release(connection, value);
  161. };
  162. transactor.rollback = function (error) {
  163. return trx.rollbackTo(connection, error);
  164. };
  165. } else {
  166. transactor.commit = function (value) {
  167. return trx.commit(connection, value);
  168. };
  169. transactor.rollback = function (error) {
  170. return trx.rollback(connection, error);
  171. };
  172. }
  173. return transactor;
  174. }
  175. // We need to make a client object which always acquires the same
  176. // connection and does not release back into the pool.
  177. function makeTxClient(trx, client, connection) {
  178. var trxClient = (0, _create2.default)(client.constructor.prototype);
  179. trxClient.config = client.config;
  180. trxClient.driver = client.driver;
  181. trxClient.connectionSettings = client.connectionSettings;
  182. trxClient.transacting = true;
  183. trxClient.valueForUndefined = client.valueForUndefined;
  184. trxClient.on('query', function (arg) {
  185. trx.emit('query', arg);
  186. client.emit('query', arg);
  187. });
  188. trxClient.on('query-error', function (err, obj) {
  189. trx.emit('query-error', err, obj);
  190. client.emit('query-error', err, obj);
  191. });
  192. trxClient.on('query-response', function (response, obj, builder) {
  193. trx.emit('query-response', response, obj, builder);
  194. client.emit('query-response', response, obj, builder);
  195. });
  196. var _query = trxClient.query;
  197. trxClient.query = function (conn, obj) {
  198. var completed = trx.isCompleted();
  199. return _bluebird2.default.try(function () {
  200. if (conn !== connection) throw new Error('Invalid connection for transaction query.');
  201. if (completed) completedError(trx, obj);
  202. return _query.call(trxClient, conn, obj);
  203. });
  204. };
  205. var _stream = trxClient.stream;
  206. trxClient.stream = function (conn, obj, stream, options) {
  207. var completed = trx.isCompleted();
  208. return _bluebird2.default.try(function () {
  209. if (conn !== connection) throw new Error('Invalid connection for transaction query.');
  210. if (completed) completedError(trx, obj);
  211. return _stream.call(trxClient, conn, obj, stream, options);
  212. });
  213. };
  214. trxClient.acquireConnection = function () {
  215. return _bluebird2.default.resolve(connection);
  216. };
  217. trxClient.releaseConnection = function () {
  218. return _bluebird2.default.resolve();
  219. };
  220. return trxClient;
  221. }
  222. function completedError(trx, obj) {
  223. var sql = typeof obj === 'string' ? obj : obj && obj.sql;
  224. debug('%s: Transaction completed: %s', trx.id, sql);
  225. throw new Error('Transaction query already complete, run with DEBUG=knex:tx for more info');
  226. }
  227. var promiseInterface = ['then', 'bind', 'catch', 'finally', 'asCallback', 'spread', 'map', 'reduce', 'tap', 'thenReturn', 'return', 'yield', 'ensure', 'exec', 'reflect', 'get', 'mapSeries', 'delay'];
  228. // Creates a method which "coerces" to a promise, by calling a
  229. // "then" method on the current `Target`.
  230. promiseInterface.forEach(function (method) {
  231. Transaction.prototype[method] = function () {
  232. return this._promise = this._promise[method].apply(this._promise, arguments);
  233. };
  234. });
  235. module.exports = exports['default'];