-
Notifications
You must be signed in to change notification settings - Fork 468
/
Copy pathrequest.js
640 lines (545 loc) · 17.6 KB
/
request.js
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
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
'use strict'
const debug = require('debug')('mssql:base')
const { EventEmitter } = require('events')
const { Readable } = require('stream')
const { IDS, objectHasProperty } = require('../utils')
const globalConnection = require('../global-connection')
const { RequestError, ConnectionError } = require('../error')
const { TYPES } = require('../datatypes')
const shared = require('../shared')
/**
* Class Request.
*
* @property {Transaction} transaction Reference to transaction when request was created in transaction.
* @property {*} parameters Collection of input and output parameters.
* @property {Boolean} canceled `true` if request was canceled.
*
* @fires Request#recordset
* @fires Request#row
* @fires Request#done
* @fires Request#error
*/
class Request extends EventEmitter {
/**
* Create new Request.
*
* @param {Connection|ConnectionPool|Transaction|PreparedStatement} parent If ommited, global connection is used instead.
*/
constructor (parent) {
super()
IDS.add(this, 'Request')
debug('request(%d): created', IDS.get(this))
this.canceled = false
this._paused = false
this.parent = parent || globalConnection.pool
this.parameters = {}
}
get paused () {
return this._paused
}
/**
* Generate sql string and set imput parameters from tagged template string.
*
* @param {Template literal} template
* @return {String}
*/
template () {
const values = Array.prototype.slice.call(arguments)
const strings = values.shift()
return this._template(strings, values)
}
/**
* Fetch request from tagged template string.
*
* @private
* @param {Array} strings
* @param {Array} values
* @param {String} [method] If provided, method is automatically called with serialized command on this object.
* @return {Request}
*/
_template (strings, values, method) {
const command = [strings[0]]
for (let index = 0; index < values.length; index++) {
const value = values[index]
// if value is an array, prepare each items as it's own comma separated parameter
if (Array.isArray(value)) {
for (let parameterIndex = 0; parameterIndex < value.length; parameterIndex++) {
this.input(`param${index + 1}_${parameterIndex}`, value[parameterIndex])
command.push(`@param${index + 1}_${parameterIndex}`)
if (parameterIndex < value.length - 1) {
command.push(', ')
}
}
command.push(strings[index + 1])
} else {
this.input(`param${index + 1}`, value)
command.push(`@param${index + 1}`, strings[index + 1])
}
}
if (method) {
return this[method](command.join(''))
} else {
return command.join('')
}
}
/**
* Add an input parameter to 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}
*/
input (name, type, value) {
if ((/(--| |\/\*|\*\/|')/).test(name)) {
throw new RequestError(`SQL injection warning for param '${name}'`, 'EINJECT')
}
if (arguments.length < 2) {
throw new RequestError('Invalid number of arguments. At least 2 arguments expected.', 'EARGS')
} else if (arguments.length === 2) {
value = type
type = shared.getTypeByValue(value)
}
// support for custom data types
if (value && typeof value.valueOf === 'function' && !(value instanceof Date)) value = value.valueOf()
if (value === undefined) value = null // undefined to null
if (typeof value === 'number' && isNaN(value)) value = null // NaN to null
if (type instanceof Function) type = type()
if (objectHasProperty(this.parameters, name)) {
throw new RequestError(`The parameter name ${name} has already been declared. Parameter names must be unique`, 'EDUPEPARAM')
}
this.parameters[name] = {
name,
type: type.type,
io: 1,
value,
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 request.
*
* @param {String} name Name of the output parameter without @ char.
* @param {*} type SQL data type of output parameter.
* @param {*} [value] Output parameter value initial value. `undefined` and `NaN` values are automatically converted to `null` values. Optional.
* @return {Request}
*/
output (name, type, value) {
if (!type) { type = TYPES.NVarChar }
if ((/(--| |\/\*|\*\/|')/).test(name)) {
throw new RequestError(`SQL injection warning for param '${name}'`, 'EINJECT')
}
if ((type === TYPES.Text) || (type === TYPES.NText) || (type === TYPES.Image)) {
throw new RequestError('Deprecated types (Text, NText, Image) are not supported as OUTPUT parameters.', 'EDEPRECATED')
}
// support for custom data types
if (value && typeof value.valueOf === 'function' && !(value instanceof Date)) value = value.valueOf()
if (value === undefined) value = null // undefined to null
if (typeof value === 'number' && isNaN(value)) value = null // NaN to null
if (type instanceof Function) type = type()
if (objectHasProperty(this.parameters, name)) {
throw new RequestError(`The parameter name ${name} has already been declared. Parameter names must be unique`, 'EDUPEPARAM')
}
this.parameters[name] = {
name,
type: type.type,
io: 2,
value,
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.
* @param {*} [value] Output parameter value initial value. `undefined` and `NaN` values are automatically converted to `null` values. Optional.
* @return {Request}
*/
replaceOutput (name, type, value) {
delete this.parameters[name]
return this.output(name, type, value)
}
/**
* Execute the SQL batch.
*
* @param {String} batch T-SQL batch to be executed.
* @param {Request~requestCallback} [callback] A callback which is called after execution has completed, or an error has occurred. If omited, method returns Promise.
* @return {Request|Promise}
*/
batch (batch, callback) {
if (this.stream == null && this.connection) this.stream = this.connection.config.stream
if (this.arrayRowMode == null && this.connection) this.arrayRowMode = this.connection.config.arrayRowMode
this.rowsAffected = 0
if (typeof callback === 'function') {
this._batch(batch, (err, recordsets, output, rowsAffected) => {
if (this.stream) {
if (err) this.emit('error', err)
err = null
this.emit('done', {
output,
rowsAffected
})
}
if (err) return callback(err)
callback(null, {
recordsets,
recordset: recordsets && recordsets[0],
output,
rowsAffected
})
})
return this
}
// Check is method was called as tagged template
if (typeof batch === 'object') {
const values = Array.prototype.slice.call(arguments)
const strings = values.shift()
batch = this._template(strings, values)
}
return new shared.Promise((resolve, reject) => {
this._batch(batch, (err, recordsets, output, rowsAffected) => {
if (this.stream) {
if (err) this.emit('error', err)
err = null
this.emit('done', {
output,
rowsAffected
})
}
if (err) return reject(err)
resolve({
recordsets,
recordset: recordsets && recordsets[0],
output,
rowsAffected
})
})
})
}
/**
* @private
* @param {String} batch
* @param {Request~requestCallback} callback
*/
_batch (batch, callback) {
if (!this.connection) {
return setImmediate(callback, new RequestError('No connection is specified for that request.', 'ENOCONN'))
}
if (!this.connection.connected) {
return setImmediate(callback, new ConnectionError('Connection is closed.', 'ECONNCLOSED'))
}
this.canceled = false
setImmediate(callback)
}
/**
* Bulk load.
*
* @param {Table} table SQL table.
* @param {object} [options] Options to be passed to the underlying driver (tedious only).
* @param {Request~bulkCallback} [callback] A callback which is called after bulk load has completed, or an error has occurred. If omited, method returns Promise.
* @return {Request|Promise}
*/
bulk (table, options, callback) {
if (typeof options === 'function') {
callback = options
options = {}
} else if (typeof options === 'undefined') {
options = {}
}
if (this.stream == null && this.connection) this.stream = this.connection.config.stream
if (this.arrayRowMode == null && this.connection) this.arrayRowMode = this.connection.config.arrayRowMode
if (this.stream || typeof callback === 'function') {
this._bulk(table, options, (err, rowsAffected) => {
if (this.stream) {
if (err) this.emit('error', err)
return this.emit('done', {
rowsAffected
})
}
if (err) return callback(err)
callback(null, {
rowsAffected
})
})
return this
}
return new shared.Promise((resolve, reject) => {
this._bulk(table, options, (err, rowsAffected) => {
if (err) return reject(err)
resolve({
rowsAffected
})
})
})
}
/**
* @private
* @param {Table} table
* @param {object} options
* @param {Request~bulkCallback} callback
*/
_bulk (table, options, callback) {
if (!this.parent) {
return setImmediate(callback, new RequestError('No connection is specified for that request.', 'ENOCONN'))
}
if (!this.parent.connected) {
return setImmediate(callback, new ConnectionError('Connection is closed.', 'ECONNCLOSED'))
}
this.canceled = false
setImmediate(callback)
}
/**
* Wrap original request in a Readable stream that supports back pressure and return.
* It also sets request to `stream` mode and pulls all rows from all recordsets to a given stream.
*
* @param {Object} streamOptions - optional options to configure the readable stream with like highWaterMark
* @return {Stream}
*/
toReadableStream (streamOptions = {}) {
this.stream = true
this.pause()
const readableStream = new Readable({
...streamOptions,
objectMode: true,
read: (/* size */) => {
this.resume()
}
})
this.on('row', (row) => {
if (!readableStream.push(row)) {
this.pause()
}
})
this.on('error', (error) => {
readableStream.emit('error', error)
})
this.on('done', () => {
readableStream.push(null)
})
return readableStream
}
/**
* Wrap original request in a Readable stream that supports back pressure and pipe to the Writable stream.
* It also sets request to `stream` mode and pulls all rows from all recordsets to a given stream.
*
* @param {Stream} stream Stream to pipe data into.
* @return {Stream}
*/
pipe (writableStream) {
const readableStream = this.toReadableStream()
return readableStream.pipe(writableStream)
}
/**
* Execute the SQL command.
*
* @param {String} command T-SQL command to be executed.
* @param {Request~requestCallback} [callback] A callback which is called after execution has completed, or an error has occurred. If omited, method returns Promise.
* @return {Request|Promise}
*/
query (command, callback) {
if (this.stream == null && this.connection) this.stream = this.connection.config.stream
if (this.arrayRowMode == null && this.connection) this.arrayRowMode = this.connection.config.arrayRowMode
this.rowsAffected = 0
if (typeof callback === 'function') {
this._query(command, (err, recordsets, output, rowsAffected, columns) => {
if (this.stream) {
if (err) this.emit('error', err)
err = null
this.emit('done', {
output,
rowsAffected
})
}
if (err) return callback(err)
const result = {
recordsets,
recordset: recordsets && recordsets[0],
output,
rowsAffected
}
if (this.arrayRowMode) result.columns = columns
callback(null, result)
})
return this
}
// Check is method was called as tagged template
if (typeof command === 'object') {
const values = Array.prototype.slice.call(arguments)
const strings = values.shift()
command = this._template(strings, values)
}
return new shared.Promise((resolve, reject) => {
this._query(command, (err, recordsets, output, rowsAffected, columns) => {
if (this.stream) {
if (err) this.emit('error', err)
err = null
this.emit('done', {
output,
rowsAffected
})
}
if (err) return reject(err)
const result = {
recordsets,
recordset: recordsets && recordsets[0],
output,
rowsAffected
}
if (this.arrayRowMode) result.columns = columns
resolve(result)
})
})
}
/**
* @private
* @param {String} command
* @param {Request~bulkCallback} callback
*/
_query (command, callback) {
if (!this.parent) {
return setImmediate(callback, new RequestError('No connection is specified for that request.', 'ENOCONN'))
}
if (!this.parent.connected) {
return setImmediate(callback, new ConnectionError('Connection is closed.', 'ECONNCLOSED'))
}
this.canceled = false
setImmediate(callback)
}
/**
* Call a stored procedure.
*
* @param {String} procedure Name of the stored procedure to be executed.
* @param {Request~requestCallback} [callback] A callback which is called after execution has completed, or an error has occurred. If omited, method returns Promise.
* @return {Request|Promise}
*/
execute (command, callback) {
if (this.stream == null && this.connection) this.stream = this.connection.config.stream
if (this.arrayRowMode == null && this.connection) this.arrayRowMode = this.connection.config.arrayRowMode
this.rowsAffected = 0
if (typeof callback === 'function') {
this._execute(command, (err, recordsets, output, returnValue, rowsAffected, columns) => {
if (this.stream) {
if (err) this.emit('error', err)
err = null
this.emit('done', {
output,
rowsAffected,
returnValue
})
}
if (err) return callback(err)
const result = {
recordsets,
recordset: recordsets && recordsets[0],
output,
rowsAffected,
returnValue
}
if (this.arrayRowMode) result.columns = columns
callback(null, result)
})
return this
}
return new shared.Promise((resolve, reject) => {
this._execute(command, (err, recordsets, output, returnValue, rowsAffected, columns) => {
if (this.stream) {
if (err) this.emit('error', err)
err = null
this.emit('done', {
output,
rowsAffected,
returnValue
})
}
if (err) return reject(err)
const result = {
recordsets,
recordset: recordsets && recordsets[0],
output,
rowsAffected,
returnValue
}
if (this.arrayRowMode) result.columns = columns
resolve(result)
})
})
}
/**
* @private
* @param {String} procedure
* @param {Request~bulkCallback} callback
*/
_execute (procedure, callback) {
if (!this.parent) {
return setImmediate(callback, new RequestError('No connection is specified for that request.', 'ENOCONN'))
}
if (!this.parent.connected) {
return setImmediate(callback, new ConnectionError('Connection is closed.', 'ECONNCLOSED'))
}
this.canceled = false
setImmediate(callback)
}
/**
* Cancel currently executed request.
*
* @return {Boolean}
*/
cancel () {
this._cancel()
return true
}
/**
* @private
*/
_cancel () {
this.canceled = true
}
pause () {
if (this.stream) {
this._pause()
return true
}
return false
}
_pause () {
this._paused = true
}
resume () {
if (this.stream) {
this._resume()
return true
}
return false
}
_resume () {
this._paused = false
}
_setCurrentRequest (request) {
this._currentRequest = request
if (this._paused) {
this.pause()
}
return this
}
}
module.exports = Request