transaction.js 8.3 KB

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