forked from Hypermediaisobar-admin/node-any-db-mssql
-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
909 lines (788 loc) · 23.7 KB
/
index.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
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
var EventEmitter = require('events').EventEmitter;
var Extend = require('util')._extend;
var sql = require('tedious');
/**
* Implementation of Adapter as defined by Any-DB API ({@link https://github.com/grncdr/node-any-db}).
*
* @module any-db-mssql
*/
/**
* Database connection options Object.
*
* @external Tedious~ConfigOptions
* @see {@link http://pekim.github.io/tedious/api-connection.html#function_newConnection}
* @property {String} [instanceName] - e.g., 'SQLEXPRESS'
* @property {String} [database] - database name, e.g., 'MyDataBase'
* @property {Number} [port] - server port, e.g., 1433.
*/
/**
* Database connection configuration Object.
*
* @external Tedious~Config
* @see {@link http://pekim.github.io/tedious/api-connection.html#function_newConnection}
* @property {String} server - address, e.g., '10.48.0.1'
* @property {String} userName - user name, e.g., 'MyUserName'
* @property {String} password
* @property {Tedious~ConfigOptions} [options]
*/
/**
* Default configuration for connections.
*
* @private
* @type {Tedious~Config}
*/
var defaultConfig = {
userName: 'sa',
password: '**********',
server: 'localhost',
options: {
port: 1433,
instanceName: false,
database: 'myDataBase',
requestTimeout: 90*1000,
useUTC: false
}
};
var specialDataHandler = null;
/**
* Any DB config.
*
* @external any-db~Config
* @see {@link https://github.com/grncdr/node-any-db-adapter-spec#adaptercreateconnection}
*/
/**
* Convert config provided by Any DB to the one used by Tedious.
*
* @private
* @param {any-db~Config} anyConfig
* @return {Tedious~Config}
*/
var parseConfig = function(anyConfig) {
var result = {};
result.userName = anyConfig.user || anyConfig.userName || defaultConfig.userName;
result.password = anyConfig.password || defaultConfig.password;
result.server = anyConfig.host || anyConfig.server || defaultConfig.host;
result.options = anyConfig.options || {};
result.options.database = anyConfig.database || result.options.database || defaultConfig.options.database;
result.domain = anyConfig.domain || result.options.domain || '';
if (anyConfig.instanceName || result.options.instanceName) {
result.options.instanceName = anyConfig.instanceName || result.options.instanceName;
result.options.port = false;
}
else {
result.options.port = anyConfig.port || result.options.port || defaultConfig.options.port;
}
result.options.requestTimeout = anyConfig.requestTimeout || result.options.requestTimeout || defaultConfig.options.requestTimeout;
result.options.useUTC = anyConfig.useUTC || result.options.useUTC || defaultConfig.options.useUTC;
return result;
};
/**
* Each key is a parameter name, and each value is that value.
* Data types will be detected automatically.
*
* Example:
* ```
* {
* first: 1,
* second: 'two',
* third: true
* }
* ```
*
* You can enforce types by setting values to objects with `type`, `value` and
* (optionally) `options` properties, e.g.,
* ```
* {
* first: 1,
* second: {
* type: adapter.getTypeByName('string'),
* value: 'two',
* options: {
* length: 3
* }
* }
* }
* ```
* For more information about type options, see: {@link http://pekim.github.io/tedious/api-request.html#function_addParameter}.
*
* @typedef {Object} namedParameters
*/
/**
* Contains values of parameters. Each index corresponds to the parameter identifier in SQL query string.
* Data types will be detected automatically.
*
* Every value in positionalParameters Array can be either simple value, or object containing type and
* value (to enforce data type). It works same way as with namedParameters ({@link module:any-db-mssql~namedParameters more information}).
*
* @typedef {Array} positionalParameters
*/
/**
* Look through the parameters and "unroll" the ones with Array value, e.g.,
*
* ```sql
* WHERE foo IN (@foo)
* ```
*
* will become:
*
* ```sql
* WHERE foo IN (@foo1, @foo0)
* ```
*
* if `query.values.foo` is an Array.
*
* Since Tedious does not support positional parameters, this function will also convert
* them to named parameters.
*
* This function mutates `query.text` and `query.values`.
*
* @param {any-db~Query} query
* @return {any-db~Query} modified query
*/
exports.prepareQueryParameters = function(query) {
if (!query.values) {
return query;
}
var keys = Object.keys(query.values);
var value;
var i, j, param, temp;
var newParameters = {};
var targetPrefix = exports.namedParameterPrefix;
var sourcePrefixPositional = exports.positionalParameterPrefix;
var sourcePrefixIndexed = exports.indexedParameterPrefix;
var positionalOrIndexed = query.values instanceof Array;
var sql = query.text;
for (i = 0; i < keys.length; i++) {
value = query.values[keys[i]];
if (!(value instanceof Array)) {
if (value instanceof Object && !(value instanceof Date) && !(value instanceof Buffer))
value = JSON.stringify(value);
// Tedious does not support positional parameters, so we have to replace them with named parameters.
if (positionalOrIndexed) {
newParameters['p'+i] = value;
sql = sql.replace(sourcePrefixPositional, targetPrefix+'p'+i);
sql = sql.replace(new RegExp('\\'+sourcePrefixIndexed+'('+(i+1)+')(\\D|$)', 'g'), function(str, group1, group2) {
return targetPrefix+'p'+i+group2;
});
}
else {
newParameters[keys[i]] = value;
}
continue;
}
param = [];
temp = targetPrefix+keys[i];
for (j = 0; j < value.length; j++) {
param.push(temp+j);
newParameters[keys[i]+j] = value[j];
}
if (positionalOrIndexed) {
sql = sql.replace(sourcePrefixPositional, param.join(', '));
sql = sql.replace(new RegExp('\\'+sourcePrefixIndexed+'('+(i+1)+')(\\D|$)', 'g'), function(str, group1, group2) {
return targetPrefix+'p'+i+group2;
});
}
else {
temp = new RegExp(temp, 'g');
sql = sql.replace(temp, param.join(', '));
}
}
query.values = newParameters;
query.text = sql;
//console.log(sql, newParameters);
return query;
};
/**
* RegExp used by `detectParameterType()`.
*
* @private
*/
var _typeCheck = (function(){
var regexTypes = {
'(^-?\\d+$)': sql.TYPES.Int,
'(^-?\\d+\\.\\d+$)': sql.TYPES.Real,
'(^\\d{4}-\\d{2}-\\d{2}$)': sql.TYPES.Date,
'(^\\d{2}\\:\\d{2}(?:\\:\\d{2})?(?:\\+\\d{4})?$)': sql.TYPES.Time,
// MSSQL does not implement full ISO 8601 standard:
// when string contains letter "T", MSSQL rejects time value without seconds specified,
// it also rejects any time value that contains only hour value (omitting minutes and seconds),
// it also rejects formats without colons.
'(^\\d{4}-\\d{2}-\\d{2}\\s+\\d{2}\\:\\d{2}(?:\\:\\d{2}(?:\\.\\d+)?)?$)': sql.TYPES.DateTimeOffset,
'(^\\d{4}-\\d{2}-\\d{2}T\\d{2}\\:\\d{2}\\:\\d{2}(?:\\.\\d+)?$)': sql.TYPES.DateTimeOffset,
'(^\\d{4}-\\d{2}-\\d{2}\\s+\\d{2}\\:\\d{2}(?:\\:\\d{2}(?:\\.\\d+)?)?(?:[\\+\\-]\\d{2}\\:\\d{2}|Z)?$)': sql.TYPES.DateTimeOffset,
'(^\\d{4}-\\d{2}-\\d{2}T\\d{2}\\:\\d{2}\\:\\d{2}(?:\\.\\d+)?(?:[\\+\\-]\\d{2}\\:\\d{2}|Z)?$)': sql.TYPES.DateTimeOffset,
'(^[\\w\\W]+$)': sql.TYPES.NVarChar
};
var r = new RegExp(Object.keys(regexTypes).join('|'));
r._exec = r.exec;
r.exec = function(str){
var result = this._exec(str);
if (!result) {
return false;
}
for (var i = 1; i < result.length; i++) {
if (!result[i]) {
continue;
}
return regexTypes[(Object.keys(regexTypes))[i-1]];
}
return sql.TYPES.VarBinary;
};
return r;
})();
/**
* Tedious type definition.
* @external Tedious~Type
* @see {@link http://pekim.github.io/tedious/api-datatypes.html}
* @property {number} id - internal identification number
* @property {string} type - internal type name
* @property {string} name - SQL type name
*/
/**
* Check the type of the parameter value and return MSSQL type most suitable for it.
* Defaults to VarBinary type.
*
* @param {*} value
* @return {Tedious~Type} Tedious type definition
*/
exports.detectParameterType = function(value) {
if (value === null || typeof value === 'undefined') {
return sql.TYPES.NVarChar;
}
else if ((value instanceof Boolean) || value === true || value === false) {
return sql.TYPES.Bit;
}
else if (value instanceof Array) {
return (value.length > 0 ? exports.detectParameterType(value[0]) : sql.TYPES.Null);
}
else if (value instanceof Date) {
return sql.TYPES.DateTimeOffset;
}
else if (value instanceof Buffer) {
return sql.TYPES.VarBinary;
}
else if (value === '') {
return sql.TYPES.NVarChar;
}
var type = _typeCheck.exec(value) || sql.TYPES.VarBinary;
if (type === sql.TYPES.Int) {
// Check if we should promote to BigInt (value larger than 2^31-1 && -2^31
if (value > 2147483647 || value < -2147483648) {
type = sql.TYPES.BigInt;
}
}
return type;
};
/**
* Tedious' Request object.
*
* @external Tedious~Request
* @see {@link http://pekim.github.io/tedious/api-request.html}
*/
/**
* Add parameters to the request.
*
* @private
* @param {Tedious~Request} request
* @param {namedParameters|positionalParameters} [parameters]
*/
var setRequestParameters = function(request, parameters) {
if (!parameters) {
return;
}
var keys = Object.keys(parameters);
var type = false;
var value = null;
var options = null;
for (var i = keys.length - 1; i >= 0; i--) {
value = parameters[keys[i]];
options = null;
if (value instanceof Object && value.type && value.hasOwnProperty('value')) {
if (value.hasOwnProperty('options')) {
options = value.options;
}
type = value.type;
value = value.value;
}
else {
type = exports.detectParameterType(value);
}
if (type === sql.TYPES.DateTimeOffset || type === sql.TYPES.DateTime2 || type === sql.TYPES.DateTime) {
if (!(value instanceof Date) && typeof value === 'string') {
// This avoids a bug regarding string date parsing in Tedious (< 1.13.1 at the time of writing)
value = new Date(Date.parse(value));
}
}
if (!(value instanceof Array)) {
request.addParameter(keys[i], type, value, options);
continue;
}
}
};
exports.setSpecialDataHandler = function(handler) {
var oldHandler = specialDataHandler;
specialDataHandler = handler;
return oldHandler;
}
/**
* Generic callback function.
*
* First argument will allways be error value or empty.
* Second and any next argument are optional and depend on the calling function.
*
* @typedef {Function} genericCallback
* @param {string|Object|null} error - error, if any happened, or null
* @param {Array|Number|string|null} result
*/
/**
* EventEmitter is part of node.js API.
*
* @external events~EventEmitter
* @see {@link http://nodejs.org/api/events.html#events_class_events_eventemitter}
*/
/**
* Readable stream is part of node.js API.
*
* @external stream~Readable
* @see {@link http://nodejs.org/api/stream.html#stream_class_stream_readable}
*/
/**
* Adapter is defined by Any-DB API.
*
* @external any-db~Adapter
* @see {@link https://github.com/grncdr/node-any-db-adapter-spec#adapter}
* @property {string} name
* @property {function} createConnection
* @property {function} createQuery
*/
/**
* Queryable is defined by Any-DB API.
*
* @external any-db~Queryable
* @see {@link https://github.com/grncdr/node-any-db-adapter-spec#queryable}
* @extends {EventEmitter}
* @property {any-db~Adapter} adapter
* @property {function} query
*/
/**
* Query is defined by Any-DB API.
*
* @external any-db~Query
* @see {@link https://github.com/grncdr/node-any-db-adapter-spec#query}
* @extends {stream~Readable}
* @property {string} text
* @property {Array|Object} values
* @property {genericCallback} callback
*/
/**
* Connection is defined by Any-DB API.
*
* @external any-db~Connection
* @see {@link https://github.com/grncdr/node-any-db-adapter-spec#connection}
* @extends {any-db~Queryable}
* @property {function} end
*/
/**
* Do not call this directly, as it has to be bound to a Queryable object.
*
* This function is used by `makeQueryable` function to inject into
* Queryable objects as `query` function.
*
* @private
* @param {string|any-db~Query} query
* @param {Array|Object} [parameters] - used only when query is a string
* @param {genericCallback} [callback] - used only when query is a string
*/
var execQuery = function(query, parameters, callback) {
query = this.adapter.createQuery(query, parameters, callback);
var requestDone = function (err, rowCount) {
//console.log('--> ', query.text, err);
query._isDone = true;
if (query._resultSet) {
query._resultSet.rowCount = rowCount;
}
if (query._connection) {
query._connection.close();
query._connection = null;
}
if (query._request) {
delete query._request;
query._request = null;
}
query.emit('close');
if (query.callback && !query._emittedError) {
query.callback(err, query._resultSet);
}
// Do not emit `end` event if there was no one listening.
// TODO: this is strange requirement, but it comes from emulating stream.Readable,
// which does not emit `end` untill all data is consumed. If data was not consumed,
// i.e., no callback and no `data` event are used, there should be no `end`.
// This is most probably wrong way, because we're still closing the query
// (remember: Tedious query is not a stream waiting for read - it finishes anyway).
// We should change this once Tedious query is instance of `stream.Readable`, or
// can be paused and resumed.
if (query.callback || EventEmitter.listenerCount(query, 'data')) {
query.emit('end');
}
};
if (query.text === 'BEGIN' || query.text === 'BEGIN TRANSACTION') {
this.beginTransaction(requestDone);
} else if (query.text === 'COMMIT') {
this.commitTransaction(requestDone);
} else if (query.text === 'ROLLBACK') {
var that = this;
// There seems to be a bug somewhere that makes Tedious not be in the LoggedIn state
// (it is in SentClientRequest state) and that causes us to not be able to call rollack at this moment in time.
// Tests have shown that this can be worked around by using a timer. This is an ugly hack though...
setTimeout(function() {
that.rollbackTransaction(function (err) {
if (err) {
console.error('Rollback error: ', err);
}
requestDone(err);
});
}, 0);
} else {
if (query.values) {
exports.prepareQueryParameters(query);
}
query._request = new sql.Request(query.text, requestDone);
if (query.values) {
setRequestParameters(query._request, query.values);
}
query._request.on('row', function(columns){
var row = {};
for (var i = 0; i < columns.length; i++) {
var column = columns[i];
// Fix for BIGINT numbers being parsed as string
if (column.metadata.type === sql.TYPES.IntN || column.metadata.type === sql.TYPES.BigInt) {
if (typeof column.value === 'string') {
var value = parseInt(column.value);
if (isFinite(value)) {
column.value = value;
}
}
}
if (specialDataHandler) {
specialDataHandler(column);
}
row[column.metadata.colName] = column.value;
}
query.emit('data', row);
if (query._resultSet && query._resultSet.rows instanceof Array) {
query._resultSet.rows.push(row);
}
});
query._request.on('columnMetadata', function(columns){
var fields = [];
columns.forEach(function(column){
if (!column.colName) {
return;
}
var field = {
name: column.colName
};
Object.keys(column).forEach(function(name){
field[name] = column[name];
});
fields.push(field);
});
query.emit('fields', fields);
if (query._resultSet) {
query._resultSet.fields = fields;
}
});
query._request.on('error', function(err){
// According to Any-DB API, query error event can be emitted only once per query:
// https://github.com/grncdr/node-any-db-adapter-spec#error-event-1
if (!query._emittedError) {
query._emittedError = true;
query.emit('error', err);
}
});
if (query.callback && query.callback instanceof Function) {
query._resultSet = {
fields: [],
rows: [],
rowCount: 0,
lastInsertId: null, // Not supported
// Output parameter values
values: []
};
// We collect parameters only when _resultSet is being used.
query._request.on('returnValue', function(parameterName, value, metadata){
query._resultSet.values.push({
name: parameterName,
value: value,
meta: metadata
});
});
// According to Any-DB API, callback should be subscribed to the error event:
// https://github.com/grncdr/node-any-db-adapter-spec#error-event-1
query.on('error', query.callback);
}
else {
// Add empty error handler, just in case there is none set up by the caller.
// This fixes Any-DB adapter spec tests.
query.on('error', function(){});
}
this.execNextInQueue(query);
}
return query;
};
/**
* Inject Queryable API into object.
*
* @private
* @param {Object} target
* @return {any-db~Queryable} target object with Queryable API injected
*/
var makeQueryable = function(target) {
target.adapter = exports;
target.query = execQuery.bind(target);
// Tedious cannot execute more than one query at a time, so we have to
// implement a queue for queries, just in case someone tries to set
// multiple queries in a row (like node-any-db-adapter-spec tests do).
target._queue = [];
target._waitingForQueryToFinish = false;
var _execNextInQueue = function(){
if (target._waitingForQueryToFinish) {
return;
}
var query = target._queue.shift();
if (query) {
target._waitingForQueryToFinish = true;
target.emit('query', query);
query.once('close', function(){
target._waitingForQueryToFinish = false;
target.execNextInQueue();
});
target.execSql(query._request);
}
};
target.execNextInQueue = function(query){
if (query) {
target._queue.push(query);
}
if (target._isConnected) {
process.nextTick(_execNextInQueue);
}
};
return target;
};
/**
* Adapter's schema name.
*/
exports.name = 'mssql';
/**
* Extend Any-DB API with namedParameterPrefix flag, that can be used when build SQL query strings
* with named parameters, for example:
*
* ```
* connection.query(
* 'SELECT '+adapter.namedParameterPrefix+'myParam AS test`,
* { myParam: 1 }
* );
* ```
*/
exports.namedParameterPrefix = '@';
Object.defineProperty(exports, 'namedParameterPrefix', { value: '@', writable : false });
/**
* Extend Any-DB API with positionalParameterPrefix flag, that can be used when build SQL query strings
* with positioned parameters, for example:
*
* ```
* connection.query(
* 'SELECT '+adapter.positionalParameterPrefix+' AS test`,
* [ 1 ]
* );
* ``` */
exports.positionalParameterPrefix = '?';
Object.defineProperty(exports, 'positionalParameterPrefix', { value: '?', writable : false });
/**
* Extend Any-DB API with indexedParameterPrefix flag, that can be used when build SQL query strings
* with indexed parameters, for example:
*
* ```
* connection.query(
* 'SELECT '+adapter.indexedParameterPrefix+' AS test`,
* [ 1 ]
* );
* ``` */
exports.indexedParameterPrefix = '$';
Object.defineProperty(exports, 'indexedParameterPrefix', { value: '$', writable : false });
/**
* Implementation of `Adapter.createConnection` method defined by Any-DB API.
*
* @see {@link https://github.com/grncdr/node-any-db-adapter-spec#adaptercreateconnection}
* @param {any-db~Config} config
* @param {genericCallback} [callback]
* @return {any-db~Connection} connection
*/
exports.createConnection = function(config, callback) {
var result = new sql.Connection(parseConfig(config));
// `id` is added only for testing purposes and should not be counted on
result.id = process.hrtime().join('.');
result._isConnected = false;
makeQueryable(result);
// Tedious Connection has `close()` method, but Any-DB
// expects `end()` method, so we have to build a bridge.
result.end = function(callback){
if (callback instanceof Function) {
result.on('close', callback);
}
result.close();
};
if (callback && callback instanceof Function) {
callback._done = false;
result.once('error', function(err){
if (callback._done) {
return;
}
callback._done = true;
callback(err, result);
});
}
if (result.config.options.hasOwnProperty('debug')) {
result.on('debug', function(msg) {
console.log(msg);
});
}
// Tedious emits `end`, but any-db expects `close` event,
// so we have to fake it.
result.on('end', function(){
result._isConnected = false;
result.emit('close');
result._queue = [];
});
result.on('connect', function(err){
if (err) {
result.emit('error', err);
}
else {
result._isConnected = true;
// This is not mentioned in Any-DB documentation, but connection should
// emit `open` event when it is ready for queries.
result.emit('open');
}
if (callback && callback instanceof Function && !callback._done) {
callback._done = true;
callback(err, result);
}
result.execNextInQueue();
});
result.on('errorMessage', function(err){
if (this.request) {
this.request.emit('error', err);
}
});
return result;
};
/**
* Partial implementation of `Adapter.createQuery` method defined by Any-DB API.
*
* Partial because returned Query DOES NOT inherit Readable stream.
* It inherits EventEmitter only, because Tedious library does not provide Readable
* stream, and faking it does not make much sense.
*
* @see {@link https://github.com/grncdr/node-any-db-adapter-spec#adaptercreatequery}
* @param {string|any-db~Query} query
* @param {Array} [parameters] - used only when query is a string
* @param {genericCallback} [callback] - used only when query is a string
* @return {any-db~Query} query
*/
exports.createQuery = function(query, parameters, callback) {
if (typeof query === 'object') {
return query;
}
// Tedious does not use Readable stream, so we cannot support Any-DB fully :(.
var result = new EventEmitter();
result.text = query;
if (parameters && parameters instanceof Function && !callback) {
result.values = false;
result.callback = parameters;
}
else {
result.values = parameters;
result.callback = callback;
}
result._connection = null;
result._request = null;
result._resultSet = null;
result._isDone = false;
result._emittedError = false;
return result;
};
/**
* Support API of node-any-db-params (https://github.com/grncdr/node-any-db-params).
* This is based on the code of `prefixed.js` from that module.
*
* This function will be called by node-any-db-params, but also can be used directly.
* @see {@link https://github.com/grncdr/node-any-db-params}
*/
exports.createParamAccessor = function(){
var values = {};
var param = function param(name, value) {
var prefixedName = '@' + name;
if (arguments.length > 1) {
values[name] = value;
}
else if (!values.hasOwnProperty(name)) {
throw new Error('Undefined parameter ' + name);
}
return '@' + name;
};
param.values = Extend.bind(null, {}, values);
return param;
};
/**
* Extend Any-DB API by providing function that returns Tedious type for given generic type name.
*
* Following type names are supported (aside from "native" type names supported by Tedious):
*
* - integer
* - float
* - real
* - boolean
* - text
* - string
* - date
* - time
* - datetime
* - binary
*
* Unrecognized types will be handled as binary.
*
* @param {string} typeName
* @return {Tedious~Type} Tedious type definition object
*/
exports.getTypeByName = function(typeName) {
if (sql.TYPES.hasOwnProperty(typeName)) {
return sql.TYPES[typeName];
}
switch (typeName) {
case 'int':
case 'integer':
return sql.TYPES.Int;
case 'float':
case 'real':
return sql.TYPES.Real;
case 'bool':
case 'boolean':
case 'bit':
return sql.TYPES.Bit;
case 'text':
case 'string':
return sql.TYPES.NVarChar;
case 'date':
return sql.TYPES.Date;
case 'datetime':
return sql.TYPES.DateTimeOffset;
case 'time':
return sql.TYPES.Time;
case 'binary':
return sql.TYPES.VarBinary;
default:
return sql.TYPES.VarBinary;
}
};