wangzhibo
2026-05-09 53418655c061ac26f66058253f39200aced1ab1d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
'use strict'
 
const debug = require('debug')('mssql:base')
const { EventEmitter } = require('node:events')
const { IDS } = require('../utils')
const globalConnection = require('../global-connection')
const { TransactionError } = require('../error')
const shared = require('../shared')
const ISOLATION_LEVEL = require('../isolationlevel')
 
/**
 * Class Transaction.
 *
 * @property {Number} isolationLevel Controls the locking and row versioning behavior of TSQL statements issued by a connection. READ_COMMITTED by default.
 * @property {String} name Transaction name. Empty string by default.
 *
 * @fires Transaction#begin
 * @fires Transaction#commit
 * @fires Transaction#rollback
 */
 
class Transaction extends EventEmitter {
  /**
   * Create new Transaction.
   *
   * @param {Connection} [parent] If ommited, global connection is used instead.
   */
 
  constructor (parent) {
    super()
 
    IDS.add(this, 'Transaction')
    debug('transaction(%d): created', IDS.get(this))
 
    this.parent = parent || globalConnection.pool
    this.isolationLevel = Transaction.defaultIsolationLevel
    this.name = ''
  }
 
  get config () {
    return this.parent.config
  }
 
  get connected () {
    return this.parent.connected
  }
 
  /**
   * Acquire connection from connection pool.
   *
   * @param {Request} request Request.
   * @param {ConnectionPool~acquireCallback} [callback] A callback which is called after connection has established, or an error has occurred. If omited, method returns Promise.
   * @return {Transaction|Promise}
   */
 
  acquire (request, callback) {
    if (!this._acquiredConnection) {
      setImmediate(callback, new TransactionError('Transaction has not begun. Call begin() first.', 'ENOTBEGUN'))
      return this
    }
 
    if (this._activeRequest) {
      setImmediate(callback, new TransactionError("Can't acquire connection for the request. There is another request in progress.", 'EREQINPROG'))
      return this
    }
 
    this._activeRequest = request
    setImmediate(callback, null, this._acquiredConnection, this._acquiredConfig)
    return this
  }
 
  /**
   * Release connection back to the pool.
   *
   * @param {Connection} connection Previously acquired connection.
   * @return {Transaction}
   */
 
  release (connection) {
    if (connection === this._acquiredConnection) {
      this._activeRequest = null
    }
 
    return this
  }
 
  /**
   * Begin a transaction.
   *
   * @param {Number} [isolationLevel] Controls the locking and row versioning behavior of TSQL statements issued by a connection.
   * @param {basicCallback} [callback] A callback which is called after transaction has began, or an error has occurred. If omited, method returns Promise.
   * @return {Transaction|Promise}
   */
 
  begin (isolationLevel, callback) {
    if (isolationLevel instanceof Function) {
      callback = isolationLevel
      isolationLevel = undefined
    }
 
    if (typeof callback === 'function') {
      this._begin(isolationLevel, err => {
        if (!err) {
          this.emit('begin')
        }
        callback(err)
      })
      return this
    }
 
    return new shared.Promise((resolve, reject) => {
      this._begin(isolationLevel, err => {
        if (err) return reject(err)
        this.emit('begin')
        resolve(this)
      })
    })
  }
 
  /**
   * @private
   * @param {Number} [isolationLevel]
   * @param {basicCallback} [callback]
   * @return {Transaction}
   */
 
  _begin (isolationLevel, callback) {
    if (this._acquiredConnection) {
      return setImmediate(callback, new TransactionError('Transaction has already begun.', 'EALREADYBEGUN'))
    }
 
    this._aborted = false
    this._rollbackRequested = false
    if (isolationLevel) {
      if (Object.keys(ISOLATION_LEVEL).some(key => {
        return ISOLATION_LEVEL[key] === isolationLevel
      })) {
        this.isolationLevel = isolationLevel
      } else {
        throw new TransactionError('Invalid isolation level.')
      }
    }
 
    setImmediate(callback)
  }
 
  /**
   * Commit a transaction.
   *
   * @param {basicCallback} [callback] A callback which is called after transaction has commited, or an error has occurred. If omited, method returns Promise.
   * @return {Transaction|Promise}
   */
 
  commit (callback) {
    if (typeof callback === 'function') {
      this._commit(err => {
        if (!err) {
          this.emit('commit')
        }
        callback(err)
      })
      return this
    }
 
    return new shared.Promise((resolve, reject) => {
      this._commit(err => {
        if (err) return reject(err)
        this.emit('commit')
        resolve()
      })
    })
  }
 
  /**
   * @private
   * @param {basicCallback} [callback]
   * @return {Transaction}
   */
 
  _commit (callback) {
    if (this._aborted) {
      return setImmediate(callback, new TransactionError('Transaction has been aborted.', 'EABORT'))
    }
 
    if (!this._acquiredConnection) {
      return setImmediate(callback, new TransactionError('Transaction has not begun. Call begin() first.', 'ENOTBEGUN'))
    }
 
    if (this._activeRequest) {
      return setImmediate(callback, new TransactionError("Can't commit transaction. There is a request in progress.", 'EREQINPROG'))
    }
 
    setImmediate(callback)
  }
 
  /**
   * Returns new request using this transaction.
   *
   * @return {Request}
   */
 
  request () {
    return new shared.driver.Request(this)
  }
 
  /**
   * Rollback a transaction.
   *
   * @param {basicCallback} [callback] A callback which is called after transaction has rolled back, or an error has occurred. If omited, method returns Promise.
   * @return {Transaction|Promise}
   */
 
  rollback (callback) {
    if (typeof callback === 'function') {
      this._rollback(err => {
        if (!err) {
          this.emit('rollback', this._aborted)
        }
        callback(err)
      })
      return this
    }
 
    return new shared.Promise((resolve, reject) => {
      return this._rollback(err => {
        if (err) return reject(err)
        this.emit('rollback', this._aborted)
        resolve()
      })
    })
  }
 
  /**
   * @private
   * @param {basicCallback} [callback]
   * @return {Transaction}
   */
 
  _rollback (callback) {
    if (this._aborted) {
      return setImmediate(callback, new TransactionError('Transaction has been aborted.', 'EABORT'))
    }
 
    if (!this._acquiredConnection) {
      return setImmediate(callback, new TransactionError('Transaction has not begun. Call begin() first.', 'ENOTBEGUN'))
    }
 
    if (this._activeRequest) {
      return setImmediate(callback, new TransactionError("Can't rollback transaction. There is a request in progress.", 'EREQINPROG'))
    }
 
    this._rollbackRequested = true
 
    setImmediate(callback)
  }
}
 
/**
 * Default isolation level used for any transactions that don't explicitly specify an isolation level.
 *
 * @type {number}
 */
Transaction.defaultIsolationLevel = ISOLATION_LEVEL.READ_COMMITTED
 
module.exports = Transaction