transaction.js 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  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. try {
  52. return await this.sequelize.getQueryInterface().commitTransaction(this, this.options);
  53. } finally {
  54. this.finished = 'commit';
  55. this.cleanup();
  56. for (const hook of this._afterCommitHooks) {
  57. await hook.apply(this, [this]);
  58. }
  59. }
  60. }
  61. /**
  62. * Rollback (abort) the transaction
  63. *
  64. * @returns {Promise}
  65. */
  66. async rollback() {
  67. if (this.finished) {
  68. throw new Error(`Transaction cannot be rolled back because it has been finished with state: ${this.finished}`);
  69. }
  70. if (!this.connection) {
  71. throw new Error('Transaction cannot be rolled back because it never started');
  72. }
  73. try {
  74. return await this
  75. .sequelize
  76. .getQueryInterface()
  77. .rollbackTransaction(this, this.options);
  78. } finally {
  79. this.cleanup();
  80. }
  81. }
  82. /**
  83. * Called to acquire a connection to use and set the correct options on the connection.
  84. * We should ensure all of the environment that's set up is cleaned up in `cleanup()` below.
  85. *
  86. * @param {boolean} useCLS Defaults to true: Use CLS (Continuation Local Storage) with Sequelize. With CLS, all queries within the transaction callback will automatically receive the transaction object.
  87. * @returns {Promise}
  88. */
  89. async prepareEnvironment(useCLS) {
  90. let connectionPromise;
  91. if (useCLS === undefined) {
  92. useCLS = true;
  93. }
  94. if (this.parent) {
  95. connectionPromise = Promise.resolve(this.parent.connection);
  96. } else {
  97. const acquireOptions = { uuid: this.id };
  98. if (this.options.readOnly) {
  99. acquireOptions.type = 'SELECT';
  100. }
  101. connectionPromise = this.sequelize.connectionManager.getConnection(acquireOptions);
  102. }
  103. let result;
  104. const connection = await connectionPromise;
  105. this.connection = connection;
  106. this.connection.uuid = this.id;
  107. try {
  108. await this.begin();
  109. result = await this.setDeferrable();
  110. } catch (setupErr) {
  111. try {
  112. result = await this.rollback();
  113. } finally {
  114. throw setupErr; // eslint-disable-line no-unsafe-finally
  115. }
  116. }
  117. if (useCLS && this.sequelize.constructor._cls) {
  118. this.sequelize.constructor._cls.set('transaction', this);
  119. }
  120. return result;
  121. }
  122. async setDeferrable() {
  123. if (this.options.deferrable) {
  124. return await this
  125. .sequelize
  126. .getQueryInterface()
  127. .deferConstraints(this, this.options);
  128. }
  129. }
  130. async begin() {
  131. const queryInterface = this.sequelize.getQueryInterface();
  132. if ( this.sequelize.dialect.supports.settingIsolationLevelDuringTransaction ) {
  133. await queryInterface.startTransaction(this, this.options);
  134. return queryInterface.setIsolationLevel(this, this.options.isolationLevel, this.options);
  135. }
  136. await queryInterface.setIsolationLevel(this, this.options.isolationLevel, this.options);
  137. return queryInterface.startTransaction(this, this.options);
  138. }
  139. cleanup() {
  140. // Don't release the connection if there's a parent transaction or
  141. // if we've already cleaned up
  142. if (this.parent || this.connection.uuid === undefined) return;
  143. this._clearCls();
  144. const res = this.sequelize.connectionManager.releaseConnection(this.connection);
  145. this.connection.uuid = undefined;
  146. return res;
  147. }
  148. _clearCls() {
  149. const cls = this.sequelize.constructor._cls;
  150. if (cls) {
  151. if (cls.get('transaction') === this) {
  152. cls.set('transaction', null);
  153. }
  154. }
  155. }
  156. /**
  157. * A hook that is run after a transaction is committed
  158. *
  159. * @param {Function} fn A callback function that is called with the committed transaction
  160. * @name afterCommit
  161. * @memberof Sequelize.Transaction
  162. */
  163. afterCommit(fn) {
  164. if (!fn || typeof fn !== 'function') {
  165. throw new Error('"fn" must be a function');
  166. }
  167. this._afterCommitHooks.push(fn);
  168. }
  169. /**
  170. * Types can be set per-transaction by passing `options.type` to `sequelize.transaction`.
  171. * Default to `DEFERRED` but you can override the default type by passing `options.transactionType` in `new Sequelize`.
  172. * Sqlite only.
  173. *
  174. * Pass in the desired level as the first argument:
  175. *
  176. * @example
  177. * try {
  178. * await sequelize.transaction({ type: Sequelize.Transaction.TYPES.EXCLUSIVE }, transaction => {
  179. * // your transactions
  180. * });
  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. * try {
  205. * const result = await sequelize.transaction({isolationLevel: Sequelize.Transaction.ISOLATION_LEVELS.SERIALIZABLE}, transaction => {
  206. * // your transactions
  207. * });
  208. * // transaction has been committed. Do something after the commit if required.
  209. * } catch(err) {
  210. * // do something with the err.
  211. * }
  212. *
  213. * @property READ_UNCOMMITTED
  214. * @property READ_COMMITTED
  215. * @property REPEATABLE_READ
  216. * @property SERIALIZABLE
  217. */
  218. static get ISOLATION_LEVELS() {
  219. return {
  220. READ_UNCOMMITTED: 'READ UNCOMMITTED',
  221. READ_COMMITTED: 'READ COMMITTED',
  222. REPEATABLE_READ: 'REPEATABLE READ',
  223. SERIALIZABLE: 'SERIALIZABLE'
  224. };
  225. }
  226. /**
  227. * Possible options for row locking. Used in conjunction with `find` calls:
  228. *
  229. * @example
  230. * // t1 is a transaction
  231. * Model.findAll({
  232. * where: ...,
  233. * transaction: t1,
  234. * lock: t1.LOCK...
  235. * });
  236. *
  237. * @example <caption>Postgres also supports specific locks while eager loading by using OF:</caption>
  238. * UserModel.findAll({
  239. * where: ...,
  240. * include: [TaskModel, ...],
  241. * transaction: t1,
  242. * lock: {
  243. * level: t1.LOCK...,
  244. * of: UserModel
  245. * }
  246. * });
  247. *
  248. * # UserModel will be locked but TaskModel won't!
  249. *
  250. * @example <caption>You can also skip locked rows:</caption>
  251. * // t1 is a transaction
  252. * Model.findAll({
  253. * where: ...,
  254. * transaction: t1,
  255. * lock: true,
  256. * skipLocked: true
  257. * });
  258. * # The query will now return any rows that aren't locked by another transaction
  259. *
  260. * @returns {object}
  261. * @property UPDATE
  262. * @property SHARE
  263. * @property KEY_SHARE Postgres 9.3+ only
  264. * @property NO_KEY_UPDATE Postgres 9.3+ only
  265. */
  266. static get LOCK() {
  267. return {
  268. UPDATE: 'UPDATE',
  269. SHARE: 'SHARE',
  270. KEY_SHARE: 'KEY SHARE',
  271. NO_KEY_UPDATE: 'NO KEY UPDATE'
  272. };
  273. }
  274. /**
  275. * Please see {@link Transaction.LOCK}
  276. */
  277. get LOCK() {
  278. return Transaction.LOCK;
  279. }
  280. }
  281. module.exports = Transaction;
  282. module.exports.Transaction = Transaction;
  283. module.exports.default = Transaction;