forked from tediousjs/node-mssql
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmsnodesqlv8.js
695 lines (570 loc) · 18.7 KB
/
msnodesqlv8.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
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
'use strict'
const msnodesql = require('msnodesqlv8')
const debug = require('debug')('mssql:msnodesql')
const base = require('./base')
const TYPES = require('./datatypes').TYPES
const declare = require('./datatypes').declare
const UDT = require('./udt').PARSERS
const DECLARATIONS = require('./datatypes').DECLARATIONS
const ISOLATION_LEVEL = require('./isolationlevel')
const EMPTY_BUFFER = new Buffer(0)
const JSON_COLUMN_ID = 'JSON_F52E2B61-18A1-11d1-B105-00805F49916B'
const XML_COLUMN_ID = 'XML_F52E2B61-18A1-11d1-B105-00805F49916B'
const CONNECTION_STRING_PORT = 'Driver={SQL Server Native Client 11.0};Server={#{server},#{port}};Database={#{database}};Uid={#{user}};Pwd={#{password}};Trusted_Connection={#{trusted}};'
const CONNECTION_STRING_NAMED_INSTANCE = 'Driver={SQL Server Native Client 11.0};Server={#{server}\\#{instance}};Database={#{database}};Uid={#{user}};Pwd={#{password}};Trusted_Connection={#{trusted}};'
const castParameter = function (value, type) {
if (value == null) {
if ((type === TYPES.Binary) || (type === TYPES.VarBinary) || (type === TYPES.Image)) {
// msnodesql has some problems with NULL values in those types, so we need to replace it with empty buffer
return EMPTY_BUFFER
}
return null
}
switch (type) {
case TYPES.VarChar:
case TYPES.NVarChar:
case TYPES.Char:
case TYPES.NChar:
case TYPES.Xml:
case TYPES.Text:
case TYPES.NText:
if ((typeof value !== 'string') && !(value instanceof String)) {
value = value.toString()
}
break
case TYPES.Int:
case TYPES.TinyInt:
case TYPES.BigInt:
case TYPES.SmallInt:
if ((typeof value !== 'number') && !(value instanceof Number)) {
value = parseInt(value)
if (isNaN(value)) { value = null }
}
break
case TYPES.Float:
case TYPES.Real:
case TYPES.Decimal:
case TYPES.Numeric:
case TYPES.SmallMoney:
case TYPES.Money:
if ((typeof value !== 'number') && !(value instanceof Number)) {
value = parseFloat(value)
if (isNaN(value)) { value = null }
}
break
case TYPES.Bit:
if ((typeof value !== 'boolean') && !(value instanceof Boolean)) {
value = Boolean(value)
}
break
case TYPES.DateTime:
case TYPES.SmallDateTime:
case TYPES.DateTimeOffset:
case TYPES.Date:
if (!(value instanceof Date)) {
value = new Date(value)
}
break
case TYPES.Binary:
case TYPES.VarBinary:
case TYPES.Image:
if (!(value instanceof Buffer)) {
value = new Buffer(value.toString())
}
break
}
return value
}
const createColumns = function (metadata) {
let out = {}
for (let index = 0, length = metadata.length; index < length; index++) {
let column = metadata[index]
out[column.name] = {
index,
name: column.name,
length: column.size,
type: DECLARATIONS[column.sqlType]
}
if (column.udtType != null) {
out[column.name].udt = {
name: column.udtType
}
if (DECLARATIONS[column.udtType]) {
out[column.name].type = DECLARATIONS[column.udtType]
}
}
}
return out
}
const isolationLevelDeclaration = function (type) {
switch (type) {
case ISOLATION_LEVEL.READ_UNCOMMITTED: return 'READ UNCOMMITTED'
case ISOLATION_LEVEL.READ_COMMITTED: return 'READ COMMITTED'
case ISOLATION_LEVEL.REPEATABLE_READ: return 'REPEATABLE READ'
case ISOLATION_LEVEL.SERIALIZABLE: return 'SERIALIZABLE'
case ISOLATION_LEVEL.SNAPSHOT: return 'SNAPSHOT'
default: throw new base.TransactionError('Invalid isolation level.')
}
}
const valueCorrection = function (value, metadata) {
if ((metadata.sqlType === 'time') && (value != null)) {
value.setFullYear(1970)
return value
} else if ((metadata.sqlType === 'udt') && (value != null)) {
if (UDT[metadata.udtType]) {
return UDT[metadata.udtType](value)
} else {
return value
}
} else {
return value
}
}
class ConnectionPool extends base.ConnectionPool {
_poolCreate () {
return new base.Promise((resolve, reject) => {
debug('pool: create')
let defaultConnectionString = CONNECTION_STRING_PORT
if (this.config.options.instanceName != null) {
defaultConnectionString = CONNECTION_STRING_NAMED_INSTANCE
}
const cfg = {
conn_str: this.config.connectionString || defaultConnectionString,
conn_timeout: (this.config.connectionTimeout || 15000) / 1000
}
cfg.conn_str = cfg.conn_str.replace(new RegExp('#{([^}]*)}', 'g'), (p) => {
let key = p.substr(2, p.length - 3)
switch (key) {
case 'instance':
return this.config.options.instanceName
case 'trusted':
return this.config.options.trustedConnection ? 'Yes' : 'No'
default:
return this.config[key] != null ? this.config[key] : ''
}
})
msnodesql.open(cfg, (err, tds) => {
if (err) {
err = new base.ConnectionError(err)
return reject(err)
}
debug('pool: create ok')
resolve(tds)
})
})
}
_poolValidate (tds) {
return new base.Promise((resolve, reject) => {
resolve(!tds.hasError)
})
}
_poolDestroy (tds) {
return new base.Promise((resolve, reject) => {
debug('pool: destroy')
tds.close()
resolve()
})
}
}
class Transaction extends base.Transaction {
_begin (isolationLevel, callback) {
super._begin(isolationLevel, err => {
if (err) return callback(err)
debug('tran: begin')
this.parent.acquire(this, (err, connection, config) => {
if (err) return callback(err)
this._acquiredConnection = connection
this._acquiredConfig = config
const req = new Request(this)
req.stream = false
req.query(`set transaction isolation level ${isolationLevelDeclaration(this.isolationLevel)};begin tran;`, err => {
if (err) {
this.parent.release(this._acquiredConnection)
this._acquiredConnection = null
this._acquiredConfig = null
return callback(err)
}
debug('tran: begin ok')
callback(null)
})
})
})
}
_commit (callback) {
super._commit(err => {
if (err) return callback(err)
debug('tran: commit')
const req = new Request(this)
req.stream = false
req.query(`commit tran`, err => {
if (err) err = new base.TransactionError(err)
this.parent.release(this._acquiredConnection)
this._acquiredConnection = null
this._acquiredConfig = null
if (!err) debug('tran: commit ok')
callback(null)
})
})
}
_rollback (callback) {
super._commit(err => {
if (err) return callback(err)
debug('tran: rollback')
const req = new Request(this)
req.stream = false
req.query(`rollback tran`, err => {
if (err) err = new base.TransactionError(err)
this.parent.release(this._acquiredConnection)
this._acquiredConnection = null
this._acquiredConfig = null
if (!err) debug('tran: rollback ok')
callback(null)
})
})
}
}
class Request extends base.Request {
_batch (batch, callback) {
this._isBatch = true
this._query(batch, callback)
}
_bulk (table, callback) {
super._bulk(table, err => {
if (err) return callback(err)
table._makeBulk()
if (!table.name) {
setImmediate(callback, new base.RequestError('Table name must be specified for bulk insert.', 'ENAME'))
}
if (table.name.charAt(0) === '@') {
setImmediate(callback, new base.RequestError("You can't use table variables for bulk insert.", 'ENAME'))
}
this.parent.acquire(this, (err, connection) => {
if (!err) {
const done = (err, rowCount) => {
if (err) {
if ((typeof err.sqlstate === 'string') && (err.sqlstate.toLowerCase() === '08s01')) {
connection.hasError = true
}
err = new base.RequestError(err)
err.code = 'EREQUEST'
}
this.parent.release(connection)
if (err) {
callback(err)
} else {
callback(null, table.rows.length)
}
}
const go = () => {
let tm = connection.tableMgr()
return tm.bind(table.path.replace(/\[|\]/g, ''), mgr => {
if (mgr.columns.length === 0) {
return done(new base.RequestError('Table was not found on the server.', 'ENAME'))
}
let rows = []
for (let row of Array.from(table.rows)) {
let item = {}
for (let index = 0; index < table.columns.length; index++) {
let col = table.columns[index]
item[col.name] = row[index]
}
rows.push(item)
}
mgr.insertRows(rows, done)
})
}
if (table.create) {
let objectid
if (table.temporary) {
objectid = `tempdb..[${table.name}]`
} else {
objectid = table.path
}
return connection.queryRaw(`if object_id('${objectid.replace(/'/g, '\'\'')}') is null ${table.declare()}`, function (err) {
if (err) { return done(err) }
go()
})
} else {
go()
}
}
})
})
}
_query (command, callback) {
super._query(command, err => {
if (err) return callback(err)
debug('req: query')
if (command.length === 0) {
return callback(null, [])
}
let row = null
let columns = null
let recordset = null
const recordsets = []
const output = {}
const rowsAffected = []
let handleOutput = false
let isChunkedRecordset = false
let chunksBuffer = null
// nested = function is called by this.execute
if (!this._nested) {
const input = []
for (let name in this.parameters) {
let param = this.parameters[name]
input.push(`@${param.name} ${declare(param.type, param)}`)
}
const sets = []
for (let name in this.parameters) {
let param = this.parameters[name]
if (param.io === 1) {
sets.push(`set @${param.name}=?`)
}
}
const output = []
for (let name in this.parameters) {
let param = this.parameters[name]
if (param.io === 2) {
output.push(`@${param.name} as '${param.name}'`)
}
}
if (input.length) command = `declare ${input.join(',')};${sets.join(';')};${command};`
if (output.length) {
command += `select ${output.join(',')};`
handleOutput = true
}
}
this.parent.acquire(this, (err, connection, config) => {
if (err) return callback(err)
debug('req:connection acquired')
const params = []
for (let name in this.parameters) {
let param = this.parameters[name]
if (param.io === 1) {
params.push(castParameter(param.value, param.type, param))
}
}
const req = connection.queryRaw(command, params)
req.on('meta', metadata => {
if (row) {
if (isChunkedRecordset) {
if ((columns[0].name === JSON_COLUMN_ID) && (config.parseJSON === true)) {
try {
row = JSON.parse(chunksBuffer.join(''))
if (!this.stream) { recordsets[recordsets.length - 1][0] = row }
} catch (ex) {
row = null
const ex2 = new base.RequestError(`Failed to parse incoming JSON. ${ex.message}`, 'EJSON')
if (this.stream) {
this.emit('error', ex2)
} else {
console.error(ex2)
}
}
} else {
row[columns[0].name] = chunksBuffer.join('')
}
chunksBuffer = null
}
if (row.___return___ == null) {
// row with ___return___ col is the last row
if (this.stream) this.emit('row', row)
}
}
row = null
columns = metadata
recordset = []
Object.defineProperty(recordset, 'columns', {
enumerable: false,
configurable: true,
value: createColumns(metadata)
})
isChunkedRecordset = false
if ((metadata.length === 1) && (metadata[0].name === JSON_COLUMN_ID || metadata[0].name === XML_COLUMN_ID)) {
isChunkedRecordset = true
chunksBuffer = []
}
if (this.stream) {
if (recordset.columns.___return___ == null) {
this.emit('recordset', recordset.columns)
}
} else {
recordsets.push(recordset)
}
})
req.on('row', rownumber => {
if (row) {
if (isChunkedRecordset) return
if (row.___return___ == null) {
// row with ___return___ col is the last row
if (this.stream) this.emit('row', row)
}
}
row = {}
if (!this.stream) recordset.push(row)
})
req.on('column', (idx, data, more) => {
if (isChunkedRecordset) {
chunksBuffer.push(data)
} else {
data = valueCorrection(data, columns[idx])
let exi = row[columns[idx].name]
if (exi != null) {
if (exi instanceof Array) {
exi.push(data)
} else {
row[columns[idx].name] = [exi, data]
}
} else {
row[columns[idx].name] = data
}
}
})
req.on('rowcount', count => {
rowsAffected.push(count)
})
req.once('error', err => {
if ((typeof err.sqlstate === 'string') && (err.sqlstate.toLowerCase() === '08s01')) {
connection.hasError = true
}
err = new base.RequestError(err)
err.code = 'EREQUEST'
this.parent.release(connection)
debug('req: query failed', err)
callback(err)
})
req.once('done', () => {
if (!this._nested) {
if (row) {
if (isChunkedRecordset) {
if ((columns[0].name === JSON_COLUMN_ID) && (config.parseJSON === true)) {
try {
row = JSON.parse(chunksBuffer.join(''))
if (!this.stream) { recordsets[recordsets.length - 1][0] = row }
} catch (ex) {
row = null
const ex2 = new base.RequestError(`Failed to parse incoming JSON. ${ex.message}`, 'EJSON')
if (this.stream) {
this.emit('error', ex2)
} else {
console.error(ex2)
}
}
} else {
row[columns[0].name] = chunksBuffer.join('')
}
chunksBuffer = null
}
if (row['___return___'] == null) {
// row with ___return___ col is the last row
if (this.stream) { this.emit('row', row) }
}
}
// do we have output parameters to handle?
if (handleOutput && recordsets.length) {
let last = recordsets.pop()[0]
for (let name in this.parameters) {
let param = this.parameters[name]
if (param.io === 2) {
output[param.name] = last[param.name]
}
}
}
}
this.parent.release(connection)
debug('req: query ok')
if (this.stream) {
callback(null, this._nested ? row : null, output, rowsAffected)
} else {
callback(null, recordsets, output, rowsAffected)
}
})
})
})
}
_execute (procedure, callback) {
super._execute(procedure, err => {
if (err) return callback(err)
const params = []
for (let name in this.parameters) {
let param = this.parameters[name]
if (param.io === 2) {
params.push(`@${param.name} ${declare(param.type, param)}`)
}
}
let cmd = `declare ${['@___return___ int'].concat(params).join(', ')};`
cmd += `exec @___return___ = ${procedure} `
const spp = []
for (let name in this.parameters) {
let param = this.parameters[name]
if (param.io === 2) {
// output parameter
spp.push(`@${param.name}=@${param.name} output`)
} else {
// input parameter
spp.push(`@${param.name}=?`)
}
}
const params2 = []
for (let name in this.parameters) {
let param = this.parameters[name]
if (param.io === 2) {
params2.push(`@${param.name} as '${param.name}'`)
}
}
cmd += `${spp.join(', ')};`
cmd += `select ${['@___return___ as \'___return___\''].concat(params2).join(', ')};`
this._nested = true
this._query(cmd, (err, recordsets, output, rowsAffected) => {
this._nested = false
if (err) return callback(err)
let last, returnValue
if (this.stream) {
last = recordsets
} else {
last = recordsets.pop()
if (last) last = last[0]
}
if (last && (last.___return___ != null)) {
returnValue = last.___return___
for (let name in this.parameters) {
let param = this.parameters[name]
if (param.io === 2) {
output[param.name] = last[param.name]
}
}
}
if (this.stream) {
callback(null, null, output, returnValue, rowsAffected)
} else {
callback(null, recordsets, output, returnValue, rowsAffected)
}
})
})
}
/*
Cancel currently executed request.
*/
cancel () {
return false // Request canceling is not implemented by msnodesql driver.
}
}
module.exports = Object.assign({
ConnectionPool,
Transaction,
Request,
PreparedStatement: base.PreparedStatement
}, base.exports)
Object.defineProperty(module.exports, 'Promise', {
enumerable: true,
get: () => {
return base.Promise
},
set: (value) => {
base.Promise = value
}
})
base.driver.name = 'msnodesqlv8'
base.driver.ConnectionPool = ConnectionPool
base.driver.Transaction = Transaction
base.driver.Request = Request