transaction.js 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. 'use strict';
  2. const Promise = require('./promise');
  3. /**
  4. * The transaction object is used to identify a running transaction.
  5. * It is created by calling `Sequelize.transaction()`.
  6. * To run a query under a transaction, you should pass the transaction in the options object.
  7. *
  8. * @class Transaction
  9. * @see {@link Sequelize.transaction}
  10. */
  11. class Transaction {
  12. /**
  13. * Creates a new transaction instance
  14. *
  15. * @param {Sequelize} sequelize A configured sequelize Instance
  16. * @param {Object} options An object with options
  17. * @param {string} [options.type] Sets the type of the transaction. Sqlite only
  18. * @param {string} [options.isolationLevel] Sets the isolation level of the transaction.
  19. * @param {string} [options.deferrable] Sets the constraints to be deferred or immediately checked. PostgreSQL only
  20. */
  21. constructor(sequelize, options) {
  22. this.sequelize = sequelize;
  23. this.savepoints = [];
  24. this._afterCommitHooks = [];
  25. // get dialect specific transaction options
  26. const generateTransactionId = this.sequelize.dialect.QueryGenerator.generateTransactionId;
  27. this.options = Object.assign({
  28. type: sequelize.options.transactionType,
  29. isolationLevel: sequelize.options.isolationLevel,
  30. readOnly: false
  31. }, options || {});
  32. this.parent = this.options.transaction;
  33. if (this.parent) {
  34. this.id = this.parent.id;
  35. this.parent.savepoints.push(this);
  36. this.name = `${this.id}-sp-${this.parent.savepoints.length}`;
  37. } else {
  38. this.id = this.name = generateTransactionId();
  39. }
  40. delete this.options.transaction;
  41. }
  42. /**
  43. * Commit the transaction
  44. *
  45. * @returns {Promise}
  46. */
  47. commit() {
  48. if (this.finished) {
  49. return Promise.reject(new Error(`Transaction cannot be committed because it has been finished with state: ${this.finished}`));
  50. }
  51. this._clearCls();
  52. return this
  53. .sequelize
  54. .getQueryInterface()
  55. .commitTransaction(this, this.options)
  56. .finally(() => {
  57. this.finished = 'commit';
  58. if (!this.parent) {
  59. return this.cleanup();
  60. }
  61. return null;
  62. }).tap(
  63. () => Promise.each(
  64. this._afterCommitHooks,
  65. hook => Promise.resolve(hook.apply(this, [this])))
  66. );
  67. }
  68. /**
  69. * Rollback (abort) the transaction
  70. *
  71. * @returns {Promise}
  72. */
  73. rollback() {
  74. if (this.finished) {
  75. return Promise.reject(new Error(`Transaction cannot be rolled back because it has been finished with state: ${this.finished}`));
  76. }
  77. if (!this.connection) {
  78. return Promise.reject(new Error('Transaction cannot be rolled back because it never started'));
  79. }
  80. this._clearCls();
  81. return this
  82. .sequelize
  83. .getQueryInterface()
  84. .rollbackTransaction(this, this.options)
  85. .finally(() => {
  86. if (!this.parent) {
  87. return this.cleanup();
  88. }
  89. return this;
  90. });
  91. }
  92. prepareEnvironment(useCLS) {
  93. let connectionPromise;
  94. if (useCLS === undefined) {
  95. useCLS = true;
  96. }
  97. if (this.parent) {
  98. connectionPromise = Promise.resolve(this.parent.connection);
  99. } else {
  100. const acquireOptions = { uuid: this.id };
  101. if (this.options.readOnly) {
  102. acquireOptions.type = 'SELECT';
  103. }
  104. connectionPromise = this.sequelize.connectionManager.getConnection(acquireOptions);
  105. }
  106. return connectionPromise
  107. .then(connection => {
  108. this.connection = connection;
  109. this.connection.uuid = this.id;
  110. })
  111. .then(() => {
  112. return this.begin()
  113. .then(() => this.setDeferrable())
  114. .catch(setupErr => this.rollback().finally(() => {
  115. throw setupErr;
  116. }));
  117. })
  118. .tap(() => {
  119. if (useCLS && this.sequelize.constructor._cls) {
  120. this.sequelize.constructor._cls.set('transaction', this);
  121. }
  122. return null;
  123. });
  124. }
  125. setDeferrable() {
  126. if (this.options.deferrable) {
  127. return this
  128. .sequelize
  129. .getQueryInterface()
  130. .deferConstraints(this, this.options);
  131. }
  132. }
  133. begin() {
  134. const queryInterface = this.sequelize.getQueryInterface();
  135. if ( this.sequelize.dialect.supports.settingIsolationLevelDuringTransaction ) {
  136. return queryInterface.startTransaction(this, this.options).then(() => {
  137. return queryInterface.setIsolationLevel(this, this.options.isolationLevel, this.options);
  138. });
  139. }
  140. return queryInterface.setIsolationLevel(this, this.options.isolationLevel, this.options).then(() => {
  141. return queryInterface.startTransaction(this, this.options);
  142. });
  143. }
  144. cleanup() {
  145. const res = this.sequelize.connectionManager.releaseConnection(this.connection);
  146. this.connection.uuid = undefined;
  147. return res;
  148. }
  149. _clearCls() {
  150. const cls = this.sequelize.constructor._cls;
  151. if (cls) {
  152. if (cls.get('transaction') === this) {
  153. cls.set('transaction', null);
  154. }
  155. }
  156. }
  157. /**
  158. * A hook that is run after a transaction is committed
  159. *
  160. * @param {Function} fn A callback function that is called with the committed transaction
  161. * @name afterCommit
  162. * @memberof Sequelize.Transaction
  163. */
  164. afterCommit(fn) {
  165. if (!fn || typeof fn !== 'function') {
  166. throw new Error('"fn" must be a function');
  167. }
  168. this._afterCommitHooks.push(fn);
  169. }
  170. /**
  171. * Types can be set per-transaction by passing `options.type` to `sequelize.transaction`.
  172. * Default to `DEFERRED` but you can override the default type by passing `options.transactionType` in `new Sequelize`.
  173. * Sqlite only.
  174. *
  175. * Pass in the desired level as the first argument:
  176. *
  177. * @example
  178. * return sequelize.transaction({type: Sequelize.Transaction.TYPES.EXCLUSIVE}, transaction => {
  179. * // your transactions
  180. * }).then(result => {
  181. * // transaction has been committed. Do something after the commit if required.
  182. * }).catch(err => {
  183. * // do something with the err.
  184. * });
  185. *
  186. * @property DEFERRED
  187. * @property IMMEDIATE
  188. * @property EXCLUSIVE
  189. */
  190. static get TYPES() {
  191. return {
  192. DEFERRED: 'DEFERRED',
  193. IMMEDIATE: 'IMMEDIATE',
  194. EXCLUSIVE: 'EXCLUSIVE'
  195. };
  196. }
  197. /**
  198. * Isolation levels can be set per-transaction by passing `options.isolationLevel` to `sequelize.transaction`.
  199. * Sequelize uses the default isolation level of the database, you can override this by passing `options.isolationLevel` in Sequelize constructor options.
  200. *
  201. * Pass in the desired level as the first argument:
  202. *
  203. * @example
  204. * return sequelize.transaction({isolationLevel: Sequelize.Transaction.ISOLATION_LEVELS.SERIALIZABLE}, transaction => {
  205. * // your transactions
  206. * }).then(result => {
  207. * // transaction has been committed. Do something after the commit if required.
  208. * }).catch(err => {
  209. * // do something with the err.
  210. * });
  211. *
  212. * @property READ_UNCOMMITTED
  213. * @property READ_COMMITTED
  214. * @property REPEATABLE_READ
  215. * @property SERIALIZABLE
  216. */
  217. static get ISOLATION_LEVELS() {
  218. return {
  219. READ_UNCOMMITTED: 'READ UNCOMMITTED',
  220. READ_COMMITTED: 'READ COMMITTED',
  221. REPEATABLE_READ: 'REPEATABLE READ',
  222. SERIALIZABLE: 'SERIALIZABLE'
  223. };
  224. }
  225. /**
  226. * Possible options for row locking. Used in conjunction with `find` calls:
  227. *
  228. * @example
  229. * // t1 is a transaction
  230. * Model.findAll({
  231. * where: ...,
  232. * transaction: t1,
  233. * lock: t1.LOCK...
  234. * });
  235. *
  236. * @example <caption>Postgres also supports specific locks while eager loading by using OF:</caption>
  237. * UserModel.findAll({
  238. * where: ...,
  239. * include: [TaskModel, ...],
  240. * transaction: t1,
  241. * lock: {
  242. * level: t1.LOCK...,
  243. * of: UserModel
  244. * }
  245. * });
  246. *
  247. * # UserModel will be locked but TaskModel won't!
  248. *
  249. * @example <caption>You can also skip locked rows:</caption>
  250. * // t1 is a transaction
  251. * Model.findAll({
  252. * where: ...,
  253. * transaction: t1,
  254. * lock: true,
  255. * skipLocked: true
  256. * });
  257. * # The query will now return any rows that aren't locked by another transaction
  258. *
  259. * @returns {Object}
  260. * @property UPDATE
  261. * @property SHARE
  262. * @property KEY_SHARE Postgres 9.3+ only
  263. * @property NO_KEY_UPDATE Postgres 9.3+ only
  264. */
  265. static get LOCK() {
  266. return {
  267. UPDATE: 'UPDATE',
  268. SHARE: 'SHARE',
  269. KEY_SHARE: 'KEY SHARE',
  270. NO_KEY_UPDATE: 'NO KEY UPDATE'
  271. };
  272. }
  273. /**
  274. * Please see {@link Transaction.LOCK}
  275. */
  276. get LOCK() {
  277. return Transaction.LOCK;
  278. }
  279. }
  280. module.exports = Transaction;
  281. module.exports.Transaction = Transaction;
  282. module.exports.default = Transaction;