transaction.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. var Utils = require('./utils')
  2. , util = require('util')
  3. var Transaction = module.exports = function(sequelize, options) {
  4. this.sequelize = sequelize
  5. this.id = Utils.generateUUID()
  6. this.options = Utils._.extend({
  7. autocommit: true,
  8. isolationLevel: Transaction.ISOLATION_LEVELS.REPEATABLE_READ
  9. }, options || {})
  10. }
  11. util.inherits(Transaction, Utils.CustomEventEmitter)
  12. Transaction.ISOLATION_LEVELS = {
  13. READ_UNCOMMITTED: "READ UNCOMMITTED",
  14. READ_COMMITTED: "READ COMMITTED",
  15. REPEATABLE_READ: "REPEATABLE READ",
  16. SERIALIZABLE: "SERIALIZABLE"
  17. }
  18. Transaction.prototype.commit = function() {
  19. return this
  20. .sequelize
  21. .getQueryInterface()
  22. .commitTransaction(this, {})
  23. .proxy(this)
  24. .done(this.cleanup.bind(this))
  25. }
  26. Transaction.prototype.rollback = function() {
  27. return this
  28. .sequelize
  29. .getQueryInterface()
  30. .rollbackTransaction(this, {})
  31. .proxy(this)
  32. .done(this.cleanup.bind(this))
  33. }
  34. Transaction.prototype.prepareEnvironment = function(callback) {
  35. var self = this
  36. , connectorManager = self.sequelize.transactionManager.getConnectorManager(this.id)
  37. this.begin(function() {
  38. self.setIsolationLevel(function() {
  39. self.setAutocommit(function() {
  40. connectorManager.afterTransactionSetup(callback)
  41. })
  42. })
  43. })
  44. }
  45. Transaction.prototype.begin = function(callback) {
  46. this
  47. .sequelize
  48. .getQueryInterface()
  49. .startTransaction(this, {})
  50. .success(callback)
  51. .error(onError.bind(this))
  52. }
  53. Transaction.prototype.setAutocommit = function(callback) {
  54. this
  55. .sequelize
  56. .getQueryInterface()
  57. .setAutocommit(this, this.options.autocommit)
  58. .success(callback)
  59. .error(onError.bind(this))
  60. }
  61. Transaction.prototype.setIsolationLevel = function(callback) {
  62. this
  63. .sequelize
  64. .getQueryInterface()
  65. .setIsolationLevel(this, this.options.isolationLevel)
  66. .success(callback)
  67. .error(onError.bind(this))
  68. }
  69. Transaction.prototype.cleanup = function() {
  70. this.sequelize.transactionManager.releaseConnectionManager(this.id)
  71. }
  72. // private
  73. var onError = function(err) {
  74. this.emit('error', err)
  75. }