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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
'use strict'
 
const debug = require('debug')('mssql:base')
const { EventEmitter } = require('node:events')
const { IDS, objectHasProperty } = require('../utils')
const globalConnection = require('../global-connection')
const { TransactionError, PreparedStatementError } = require('../error')
const shared = require('../shared')
const { TYPES, declare } = require('../datatypes')
 
/**
 * Class PreparedStatement.
 *
 * IMPORTANT: Rememeber that each prepared statement means one reserved connection from the pool. Don't forget to unprepare a prepared statement!
 *
 * @property {String} statement Prepared SQL statement.
 */
 
class PreparedStatement extends EventEmitter {
  /**
   * Creates a new Prepared Statement.
   *
   * @param {ConnectionPool|Transaction} [holder]
   */
 
  constructor (parent) {
    super()
 
    IDS.add(this, 'PreparedStatement')
    debug('ps(%d): created', IDS.get(this))
 
    this.parent = parent || globalConnection.pool
    this._handle = 0
    this.prepared = false
    this.parameters = {}
  }
 
  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 {PreparedStatement|Promise}
   */
 
  acquire (request, callback) {
    if (!this._acquiredConnection) {
      setImmediate(callback, new PreparedStatementError('Statement is not prepared. Call prepare() first.', 'ENOTPREPARED'))
      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 {PreparedStatement}
   */
 
  release (connection) {
    if (connection === this._acquiredConnection) {
      this._activeRequest = null
    }
 
    return this
  }
 
  /**
   * Add an input parameter to the prepared statement.
   *
   * @param {String} name Name of the input parameter without @ char.
   * @param {*} type SQL data type of input parameter.
   * @return {PreparedStatement}
   */
 
  input (name, type) {
    if (/--| |\/\*|\*\/|'/.test(name)) {
      throw new PreparedStatementError(`SQL injection warning for param '${name}'`, 'EINJECT')
    }
 
    if (arguments.length < 2) {
      throw new PreparedStatementError('Invalid number of arguments. 2 arguments expected.', 'EARGS')
    }
 
    if (type instanceof Function) {
      type = type()
    }
 
    if (objectHasProperty(this.parameters, name)) {
      throw new PreparedStatementError(`The parameter name ${name} has already been declared. Parameter names must be unique`, 'EDUPEPARAM')
    }
 
    this.parameters[name] = {
      name,
      type: type.type,
      io: 1,
      length: type.length,
      scale: type.scale,
      precision: type.precision,
      tvpType: type.tvpType
    }
 
    return this
  }
 
  /**
   * Replace an input parameter on the request.
   *
   * @param {String} name Name of the input parameter without @ char.
   * @param {*} [type] SQL data type of input parameter. If you omit type, module automaticaly decide which SQL data type should be used based on JS data type.
   * @param {*} value Input parameter value. `undefined` and `NaN` values are automatically converted to `null` values.
   * @return {Request}
   */
 
  replaceInput (name, type, value) {
    delete this.parameters[name]
 
    return this.input(name, type, value)
  }
 
  /**
   * Add an output parameter to the prepared statement.
   *
   * @param {String} name Name of the output parameter without @ char.
   * @param {*} type SQL data type of output parameter.
   * @return {PreparedStatement}
   */
 
  output (name, type) {
    if (/--| |\/\*|\*\/|'/.test(name)) {
      throw new PreparedStatementError(`SQL injection warning for param '${name}'`, 'EINJECT')
    }
 
    if (arguments.length < 2) {
      throw new PreparedStatementError('Invalid number of arguments. 2 arguments expected.', 'EARGS')
    }
 
    if (type instanceof Function) type = type()
 
    if (objectHasProperty(this.parameters, name)) {
      throw new PreparedStatementError(`The parameter name ${name} has already been declared. Parameter names must be unique`, 'EDUPEPARAM')
    }
 
    this.parameters[name] = {
      name,
      type: type.type,
      io: 2,
      length: type.length,
      scale: type.scale,
      precision: type.precision
    }
 
    return this
  }
 
  /**
   * Replace an output parameter on the request.
   *
   * @param {String} name Name of the output parameter without @ char.
   * @param {*} type SQL data type of output parameter.
   * @return {PreparedStatement}
   */
 
  replaceOutput (name, type) {
    delete this.parameters[name]
 
    return this.output(name, type)
  }
 
  /**
   * Prepare a statement.
   *
   * @param {String} statement SQL statement to prepare.
   * @param {basicCallback} [callback] A callback which is called after preparation has completed, or an error has occurred. If omited, method returns Promise.
   * @return {PreparedStatement|Promise}
   */
 
  prepare (statement, callback) {
    if (typeof callback === 'function') {
      this._prepare(statement, callback)
      return this
    }
 
    return new shared.Promise((resolve, reject) => {
      this._prepare(statement, err => {
        if (err) return reject(err)
        resolve(this)
      })
    })
  }
 
  /**
   * @private
   * @param {String} statement
   * @param {basicCallback} callback
   */
 
  _prepare (statement, callback) {
    debug('ps(%d): prepare', IDS.get(this))
 
    if (typeof statement === 'function') {
      callback = statement
      statement = undefined
    }
 
    if (this.prepared) {
      return setImmediate(callback, new PreparedStatementError('Statement is already prepared.', 'EALREADYPREPARED'))
    }
 
    this.statement = statement || this.statement
 
    this.parent.acquire(this, (err, connection, config) => {
      if (err) return callback(err)
 
      this._acquiredConnection = connection
      this._acquiredConfig = config
 
      const req = new shared.driver.Request(this)
      req.stream = false
      req.output('handle', TYPES.Int)
      req.input('params', TYPES.NVarChar, ((() => {
        const result = []
        for (const name in this.parameters) {
          if (!objectHasProperty(this.parameters, name)) {
            continue
          }
          const param = this.parameters[name]
          result.push(`@${name} ${declare(param.type, param)}${param.io === 2 ? ' output' : ''}`)
        }
        return result
      })()).join(','))
      req.input('stmt', TYPES.NVarChar, this.statement)
      req.execute('sp_prepare', (err, result) => {
        if (err) {
          this.parent.release(this._acquiredConnection)
          this._acquiredConnection = null
          this._acquiredConfig = null
 
          return callback(err)
        }
 
        debug('ps(%d): prepared', IDS.get(this))
 
        this._handle = result.output.handle
        this.prepared = true
 
        callback(null)
      })
    })
  }
 
  /**
   * Execute a prepared statement.
   *
   * @param {Object} values An object whose names correspond to the names of parameters that were added to the prepared statement before it was prepared.
   * @param {basicCallback} [callback] A callback which is called after execution has completed, or an error has occurred. If omited, method returns Promise.
   * @return {Request|Promise}
   */
 
  execute (values, callback) {
    if (this.stream || (typeof callback === 'function')) {
      return this._execute(values, callback)
    }
 
    return new shared.Promise((resolve, reject) => {
      this._execute(values, (err, recordset) => {
        if (err) return reject(err)
        resolve(recordset)
      })
    })
  }
 
  /**
   * @private
   * @param {Object} values
   * @param {basicCallback} callback
   */
 
  _execute (values, callback) {
    const req = new shared.driver.Request(this)
    req.stream = this.stream
    req.arrayRowMode = this.arrayRowMode
    req.input('handle', TYPES.Int, this._handle)
 
    // copy parameters with new values
    for (const name in this.parameters) {
      if (!objectHasProperty(this.parameters, name)) {
        continue
      }
      const param = this.parameters[name]
      req.parameters[name] = {
        name,
        type: param.type,
        io: param.io,
        value: values[name],
        length: param.length,
        scale: param.scale,
        precision: param.precision
      }
    }
 
    req.execute('sp_execute', (err, result) => {
      if (err) return callback(err)
 
      callback(null, result)
    })
 
    return req
  }
 
  /**
   * Unprepare a prepared statement.
   *
   * @param {basicCallback} [callback] A callback which is called after unpreparation has completed, or an error has occurred. If omited, method returns Promise.
   * @return {PreparedStatement|Promise}
   */
 
  unprepare (callback) {
    if (typeof callback === 'function') {
      this._unprepare(callback)
      return this
    }
 
    return new shared.Promise((resolve, reject) => {
      this._unprepare(err => {
        if (err) return reject(err)
        resolve()
      })
    })
  }
 
  /**
   * @private
   * @param {basicCallback} callback
   */
 
  _unprepare (callback) {
    debug('ps(%d): unprepare', IDS.get(this))
 
    if (!this.prepared) {
      return setImmediate(callback, new PreparedStatementError('Statement is not prepared. Call prepare() first.', 'ENOTPREPARED'))
    }
 
    if (this._activeRequest) {
      return setImmediate(callback, new TransactionError("Can't unprepare the statement. There is a request in progress.", 'EREQINPROG'))
    }
 
    const req = new shared.driver.Request(this)
    req.stream = false
    req.input('handle', TYPES.Int, this._handle)
    req.execute('sp_unprepare', err => {
      if (err) return callback(err)
 
      this.parent.release(this._acquiredConnection)
      this._acquiredConnection = null
      this._acquiredConfig = null
      this._handle = 0
      this.prepared = false
 
      debug('ps(%d): unprepared', IDS.get(this))
 
      return callback(null)
    })
  }
}
 
module.exports = PreparedStatement