tedious 1.12.3 → 1.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/README.md +1 -1
  2. package/appveyor.yml +9 -5
  3. package/benchmarks/README.md +33 -0
  4. package/benchmarks/common.js +82 -0
  5. package/benchmarks/index.js +34 -0
  6. package/benchmarks/query/many-result-rows.js +49 -0
  7. package/benchmarks/query/nvarchar-large.js +44 -0
  8. package/benchmarks/query/nvarchar-small.js +44 -0
  9. package/benchmarks/query/varbinary-4.js +42 -0
  10. package/benchmarks/query/varbinary-huge.js +46 -0
  11. package/benchmarks/query/varbinary-large.js +46 -0
  12. package/benchmarks/query/varbinary-small.js +42 -0
  13. package/benchmarks/token-parser/colmetadata-token.js +42 -0
  14. package/benchmarks/token-parser/done-token.js +42 -0
  15. package/benchmarks/token-parser/simple-tokens.js +366 -0
  16. package/lib/all-headers.js +9 -11
  17. package/lib/buffertools.js +17 -13
  18. package/lib/bulk-load.js +196 -169
  19. package/lib/collation.js +80 -2
  20. package/lib/connection.js +1086 -1060
  21. package/lib/data-type.js +450 -253
  22. package/lib/debug.js +57 -51
  23. package/lib/errors.js +40 -55
  24. package/lib/guid-parser.js +12 -36
  25. package/lib/instance-lookup.js +57 -54
  26. package/lib/library.js +3 -2
  27. package/lib/login7-payload.js +187 -180
  28. package/lib/message-io.js +169 -199
  29. package/lib/metadata-parser.js +169 -255
  30. package/lib/ntlm-payload.js +173 -160
  31. package/lib/packet.js +166 -152
  32. package/lib/prelogin-payload.js +170 -160
  33. package/lib/request.js +122 -122
  34. package/lib/rpcrequest-payload.js +64 -38
  35. package/lib/special-stored-procedure.js +3 -2
  36. package/lib/sqlbatch-payload.js +20 -16
  37. package/lib/stream-parser.js +116 -104
  38. package/lib/tds-versions.js +5 -8
  39. package/lib/tedious.js +8 -14
  40. package/lib/token/colmetadata-token-parser.js +79 -125
  41. package/lib/token/done-token-parser.js +47 -129
  42. package/lib/token/env-change-token-parser.js +90 -126
  43. package/lib/token/infoerror-token-parser.js +47 -125
  44. package/lib/token/loginack-token-parser.js +36 -74
  45. package/lib/token/nbcrow-token-parser.js +40 -64
  46. package/lib/token/order-token-parser.js +26 -43
  47. package/lib/token/returnstatus-token-parser.js +11 -23
  48. package/lib/token/returnvalue-token-parser.js +31 -54
  49. package/lib/token/row-token-parser.js +39 -52
  50. package/lib/token/sspi-token-parser.js +14 -32
  51. package/lib/token/stream-parser.js +424 -304
  52. package/lib/token/token-stream-parser.js +39 -34
  53. package/lib/token/token.js +3 -6
  54. package/lib/tracking-buffer/bigint.js +45 -48
  55. package/lib/tracking-buffer/readable-tracking-buffer.js +238 -223
  56. package/lib/tracking-buffer/tracking-buffer.js +3 -9
  57. package/lib/tracking-buffer/writable-tracking-buffer.js +272 -244
  58. package/lib/transaction.js +112 -102
  59. package/lib/value-parser.js +559 -1154
  60. package/package.json +10 -9
  61. package/benchmarks/benchmarks.coffee +0 -122
  62. package/benchmarks/query.coffee +0 -57
package/lib/connection.js CHANGED
@@ -1,558 +1,294 @@
1
- // Generated by CoffeeScript 1.10.0
2
- var BulkLoad,
3
- Connection,
4
- ConnectionError,
5
- DEFAULT_CANCEL_TIMEOUT,
6
- DEFAULT_CLIENT_REQUEST_TIMEOUT,
7
- DEFAULT_CONNECT_TIMEOUT,
8
- DEFAULT_PACKET_SIZE,
9
- DEFAULT_PORT,
10
- DEFAULT_TDS_VERSION,
11
- DEFAULT_TEXTSIZE,
12
- Debug,
13
- EventEmitter,
14
- ISOLATION_LEVEL,
15
- KEEP_ALIVE_INITIAL_DELAY,
16
- Login7Payload,
17
- MessageIO,
18
- NTLMResponsePayload,
19
- PreloginPayload,
20
- Request,
21
- RequestError,
22
- RpcRequestPayload,
23
- Socket,
24
- SqlBatchPayload,
25
- TYPE,
26
- TokenStreamParser,
27
- Transaction,
28
- crypto,
29
- instanceLookup,
30
- ref,
31
- bind = function (fn, me) {
32
- return function () {
33
- return fn.apply(me, arguments);
34
- };
35
- },
36
- extend = function (child, parent) {
37
- for (var key in parent) {
38
- if (hasProp.call(parent, key)) child[key] = parent[key];
39
- }function ctor() {
40
- this.constructor = child;
41
- }ctor.prototype = parent.prototype;child.prototype = new ctor();child.__super__ = parent.prototype;return child;
42
- },
43
- hasProp = ({}).hasOwnProperty,
44
- slice = [].slice;
1
+ 'use strict';
45
2
 
46
- require('./buffertools');
47
-
48
- BulkLoad = require('./bulk-load');
49
-
50
- Debug = require('./debug');
51
-
52
- EventEmitter = require('events').EventEmitter;
53
-
54
- instanceLookup = require('./instance-lookup').instanceLookup;
55
-
56
- TYPE = require('./packet').TYPE;
57
-
58
- PreloginPayload = require('./prelogin-payload');
59
-
60
- Login7Payload = require('./login7-payload');
61
-
62
- NTLMResponsePayload = require('./ntlm-payload');
63
-
64
- Request = require('./request');
65
-
66
- RpcRequestPayload = require('./rpcrequest-payload');
67
-
68
- SqlBatchPayload = require('./sqlbatch-payload');
3
+ var _get = require('babel-runtime/helpers/get')['default'];
69
4
 
70
- MessageIO = require('./message-io');
5
+ var _inherits = require('babel-runtime/helpers/inherits')['default'];
71
6
 
72
- Socket = require('net').Socket;
7
+ var _createClass = require('babel-runtime/helpers/create-class')['default'];
73
8
 
74
- TokenStreamParser = require('./token/token-stream-parser').Parser;
9
+ var _classCallCheck = require('babel-runtime/helpers/class-call-check')['default'];
75
10
 
76
- Transaction = require('./transaction').Transaction;
77
-
78
- ISOLATION_LEVEL = require('./transaction').ISOLATION_LEVEL;
79
-
80
- crypto = require('crypto');
81
-
82
- ref = require('./errors'), ConnectionError = ref.ConnectionError, RequestError = ref.RequestError;
11
+ require('./buffertools');
83
12
 
84
- KEEP_ALIVE_INITIAL_DELAY = 30 * 1000;
13
+ var BulkLoad = require('./bulk-load');
14
+ var Debug = require('./debug');
15
+ var EventEmitter = require('events').EventEmitter;
16
+ var instanceLookup = require('./instance-lookup').instanceLookup;
17
+ var TYPE = require('./packet').TYPE;
18
+ var PreloginPayload = require('./prelogin-payload');
19
+ var Login7Payload = require('./login7-payload');
20
+ var NTLMResponsePayload = require('./ntlm-payload');
21
+ var Request = require('./request');
22
+ var RpcRequestPayload = require('./rpcrequest-payload');
23
+ var SqlBatchPayload = require('./sqlbatch-payload');
24
+ var MessageIO = require('./message-io');
25
+ var Socket = require('net').Socket;
26
+ var TokenStreamParser = require('./token/token-stream-parser').Parser;
27
+ var Transaction = require('./transaction').Transaction;
28
+ var ISOLATION_LEVEL = require('./transaction').ISOLATION_LEVEL;
29
+ var crypto = require('crypto');
30
+ var ConnectionError = require('./errors').ConnectionError;
31
+ var RequestError = require('./errors').RequestError;
32
+
33
+ // A rather basic state machine for managing a connection.
34
+ // Implements something approximating s3.2.1.
35
+
36
+ var KEEP_ALIVE_INITIAL_DELAY = 30 * 1000;
37
+ var DEFAULT_CONNECT_TIMEOUT = 15 * 1000;
38
+ var DEFAULT_CLIENT_REQUEST_TIMEOUT = 15 * 1000;
39
+ var DEFAULT_CANCEL_TIMEOUT = 5 * 1000;
40
+ var DEFAULT_PACKET_SIZE = 4 * 1024;
41
+ var DEFAULT_TEXTSIZE = '2147483647';
42
+ var DEFAULT_PORT = 1433;
43
+ var DEFAULT_TDS_VERSION = '7_4';
44
+
45
+ var Connection = (function (_EventEmitter) {
46
+ _inherits(Connection, _EventEmitter);
85
47
 
86
- DEFAULT_CONNECT_TIMEOUT = 15 * 1000;
48
+ function Connection(config) {
49
+ _classCallCheck(this, Connection);
87
50
 
88
- DEFAULT_CLIENT_REQUEST_TIMEOUT = 15 * 1000;
51
+ _get(Object.getPrototypeOf(Connection.prototype), 'constructor', this).call(this);
89
52
 
90
- DEFAULT_CANCEL_TIMEOUT = 5 * 1000;
53
+ this.config = config;
54
+ this.reset = this.reset.bind(this);
55
+ this.socketClose = this.socketClose.bind(this);
56
+ this.socketEnd = this.socketEnd.bind(this);
57
+ this.socketConnect = this.socketConnect.bind(this);
58
+ this.socketError = this.socketError.bind(this);
59
+ this.requestTimeout = this.requestTimeout.bind(this);
60
+ this.connectTimeout = this.connectTimeout.bind(this);
61
+ this.defaultConfig();
62
+ this.createDebug();
63
+ this.createTokenStreamParser();
64
+ this.inTransaction = false;
65
+ this.transactionDescriptors = [new Buffer([0, 0, 0, 0, 0, 0, 0, 0])];
66
+ this.transitionTo(this.STATE.CONNECTING);
67
+ }
91
68
 
92
- DEFAULT_PACKET_SIZE = 4 * 1024;
69
+ _createClass(Connection, [{
70
+ key: 'close',
71
+ value: function close() {
72
+ return this.transitionTo(this.STATE.FINAL);
73
+ }
74
+ }, {
75
+ key: 'initialiseConnection',
76
+ value: function initialiseConnection() {
77
+ this.connect();
78
+ return this.createConnectTimer();
79
+ }
80
+ }, {
81
+ key: 'cleanupConnection',
82
+ value: function cleanupConnection(redirect) {
83
+ this.redirect = redirect;
84
+ if (!this.closed) {
85
+ this.clearConnectTimer();
86
+ this.clearRequestTimer();
87
+ this.closeConnection();
88
+ if (!this.redirect) {
89
+ this.emit('end');
90
+ } else {
91
+ this.emit('rerouting');
92
+ }
93
+ this.closed = true;
94
+ this.loggedIn = false;
95
+ return this.loginError = null;
96
+ }
97
+ }
98
+ }, {
99
+ key: 'defaultConfig',
100
+ value: function defaultConfig() {
101
+ if (!this.config.options) {
102
+ this.config.options = {};
103
+ }
93
104
 
94
- DEFAULT_TEXTSIZE = '2147483647';
105
+ if (!this.config.options.textsize) {
106
+ this.config.options.textsize = DEFAULT_TEXTSIZE;
107
+ }
95
108
 
96
- DEFAULT_PORT = 1433;
109
+ if (!this.config.options.connectTimeout) {
110
+ this.config.options.connectTimeout = DEFAULT_CONNECT_TIMEOUT;
111
+ }
97
112
 
98
- DEFAULT_TDS_VERSION = '7_4';
113
+ if (this.config.options.requestTimeout == undefined) {
114
+ this.config.options.requestTimeout = DEFAULT_CLIENT_REQUEST_TIMEOUT;
115
+ }
99
116
 
100
- Connection = (function (superClass) {
101
- extend(Connection, superClass);
117
+ if (this.config.options.cancelTimeout == undefined) {
118
+ this.config.options.cancelTimeout = DEFAULT_CANCEL_TIMEOUT;
119
+ }
102
120
 
103
- Connection.prototype.STATE = {
104
- CONNECTING: {
105
- name: 'Connecting',
106
- enter: function () {
107
- return this.initialiseConnection();
108
- },
109
- events: {
110
- socketError: function (error) {
111
- return this.transitionTo(this.STATE.FINAL);
112
- },
113
- connectTimeout: function () {
114
- return this.transitionTo(this.STATE.FINAL);
115
- },
116
- socketConnect: function () {
117
- this.sendPreLogin();
118
- return this.transitionTo(this.STATE.SENT_PRELOGIN);
119
- }
121
+ if (!this.config.options.packetSize) {
122
+ this.config.options.packetSize = DEFAULT_PACKET_SIZE;
120
123
  }
121
- },
122
- SENT_PRELOGIN: {
123
- name: 'SentPrelogin',
124
- enter: function () {
125
- return this.emptyMessageBuffer();
126
- },
127
- events: {
128
- socketError: function (error) {
129
- return this.transitionTo(this.STATE.FINAL);
130
- },
131
- connectTimeout: function () {
132
- return this.transitionTo(this.STATE.FINAL);
133
- },
134
- data: function (data) {
135
- return this.addToMessageBuffer(data);
136
- },
137
- message: function () {
138
- return this.processPreLoginResponse();
139
- },
140
- noTls: function () {
141
- this.sendLogin7Packet();
142
- if (this.config.domain) {
143
- return this.transitionTo(this.STATE.SENT_LOGIN7_WITH_NTLM);
144
- } else {
145
- return this.transitionTo(this.STATE.SENT_LOGIN7_WITH_STANDARD_LOGIN);
146
- }
147
- },
148
- tls: function () {
149
- this.messageIo.startTls(this.config.options.cryptoCredentialsDetails);
150
- return this.transitionTo(this.STATE.SENT_TLSSSLNEGOTIATION);
151
- }
124
+
125
+ if (!this.config.options.tdsVersion) {
126
+ this.config.options.tdsVersion = DEFAULT_TDS_VERSION;
152
127
  }
153
- },
154
- REROUTING: {
155
- name: 'ReRouting',
156
- enter: function () {
157
- return this.cleanupConnection(true);
158
- },
159
- events: {
160
- message: function () {},
161
- socketError: function (error) {
162
- return this.transitionTo(this.STATE.FINAL);
163
- },
164
- connectTimeout: function () {
165
- return this.transitionTo(this.STATE.FINAL);
166
- },
167
- reconnect: function () {
168
- return this.transitionTo(this.STATE.CONNECTING);
169
- }
128
+
129
+ if (!this.config.options.isolationLevel) {
130
+ this.config.options.isolationLevel = ISOLATION_LEVEL.READ_COMMITTED;
170
131
  }
171
- },
172
- SENT_TLSSSLNEGOTIATION: {
173
- name: 'SentTLSSSLNegotiation',
174
- events: {
175
- socketError: function (error) {
176
- return this.transitionTo(this.STATE.FINAL);
177
- },
178
- connectTimeout: function () {
179
- return this.transitionTo(this.STATE.FINAL);
180
- },
181
- data: function (data) {
182
- return this.messageIo.tlsHandshakeData(data);
183
- },
184
- message: function () {
185
- if (this.messageIo.tlsNegotiationComplete) {
186
- this.sendLogin7Packet();
187
- return this.transitionTo(this.STATE.SENT_LOGIN7_WITH_STANDARD_LOGIN);
188
- }
189
- }
132
+
133
+ if (this.config.options.encrypt == undefined) {
134
+ this.config.options.encrypt = false;
190
135
  }
191
- },
192
- SENT_LOGIN7_WITH_STANDARD_LOGIN: {
193
- name: 'SentLogin7WithStandardLogin',
194
- events: {
195
- socketError: function (error) {
196
- return this.transitionTo(this.STATE.FINAL);
197
- },
198
- connectTimeout: function () {
199
- return this.transitionTo(this.STATE.FINAL);
200
- },
201
- data: function (data) {
202
- return this.sendDataToTokenStreamParser(data);
203
- },
204
- loggedIn: function () {
205
- return this.transitionTo(this.STATE.LOGGED_IN_SENDING_INITIAL_SQL);
206
- },
207
- routingChange: function () {
208
- return this.transitionTo(this.STATE.REROUTING);
209
- },
210
- loginFailed: function () {
211
- return this.transitionTo(this.STATE.FINAL);
212
- },
213
- message: function () {
214
- return this.processLogin7Response();
215
- }
136
+
137
+ if (!this.config.options.cryptoCredentialsDetails) {
138
+ this.config.options.cryptoCredentialsDetails = {};
216
139
  }
217
- },
218
- SENT_LOGIN7_WITH_NTLM: {
219
- name: 'SentLogin7WithNTLMLogin',
220
- events: {
221
- socketError: function (error) {
222
- return this.transitionTo(this.STATE.FINAL);
223
- },
224
- connectTimeout: function () {
225
- return this.transitionTo(this.STATE.FINAL);
226
- },
227
- data: function (data) {
228
- return this.sendDataToTokenStreamParser(data);
229
- },
230
- receivedChallenge: function () {
231
- this.sendNTLMResponsePacket();
232
- return this.transitionTo(this.STATE.SENT_NTLM_RESPONSE);
233
- },
234
- loginFailed: function () {
235
- return this.transitionTo(this.STATE.FINAL);
236
- },
237
- message: function () {
238
- return this.processLogin7NTLMResponse();
239
- }
140
+
141
+ if (this.config.options.useUTC == undefined) {
142
+ this.config.options.useUTC = true;
240
143
  }
241
- },
242
- SENT_NTLM_RESPONSE: {
243
- name: 'SentNTLMResponse',
244
- events: {
245
- socketError: function (error) {
246
- return this.transitionTo(this.STATE.FINAL);
247
- },
248
- connectTimeout: function () {
249
- return this.transitionTo(this.STATE.FINAL);
250
- },
251
- data: function (data) {
252
- return this.sendDataToTokenStreamParser(data);
253
- },
254
- loggedIn: function () {
255
- return this.transitionTo(this.STATE.LOGGED_IN_SENDING_INITIAL_SQL);
256
- },
257
- loginFailed: function () {
258
- return this.transitionTo(this.STATE.FINAL);
259
- },
260
- routingChange: function () {
261
- return this.transitionTo(this.STATE.REROUTING);
262
- },
263
- message: function () {
264
- return this.processLogin7NTLMAck();
265
- }
144
+
145
+ if (this.config.options.useColumnNames == undefined) {
146
+ this.config.options.useColumnNames = false;
266
147
  }
267
- },
268
- LOGGED_IN_SENDING_INITIAL_SQL: {
269
- name: 'LoggedInSendingInitialSql',
270
- enter: function () {
271
- return this.sendInitialSql();
272
- },
273
- events: {
274
- connectTimeout: function () {
275
- return this.transitionTo(this.STATE.FINAL);
276
- },
277
- data: function (data) {
278
- return this.sendDataToTokenStreamParser(data);
279
- },
280
- message: function (error) {
281
- this.transitionTo(this.STATE.LOGGED_IN);
282
- return this.processedInitialSql();
283
- }
148
+
149
+ if (!this.config.options.connectionIsolationLevel) {
150
+ this.config.options.connectionIsolationLevel = ISOLATION_LEVEL.READ_COMMITTED;
284
151
  }
285
- },
286
- LOGGED_IN: {
287
- name: 'LoggedIn',
288
- events: {
289
- socketError: function (error) {
290
- return this.transitionTo(this.STATE.FINAL);
291
- }
152
+
153
+ if (this.config.options.readOnlyIntent == undefined) {
154
+ this.config.options.readOnlyIntent = false;
292
155
  }
293
- },
294
- SENT_CLIENT_REQUEST: {
295
- name: 'SentClientRequest',
296
- events: {
297
- socketError: function (error) {
298
- return this.transitionTo(this.STATE.FINAL);
299
- },
300
- data: function (data) {
301
- return this.sendDataToTokenStreamParser(data);
302
- },
303
- message: function () {
304
- var sqlRequest;
305
- this.clearRequestTimer();
306
- this.transitionTo(this.STATE.LOGGED_IN);
307
- sqlRequest = this.request;
308
- this.request = void 0;
309
- return sqlRequest.callback(sqlRequest.error, sqlRequest.rowCount, sqlRequest.rows);
310
- }
156
+
157
+ if (this.config.options.enableAnsiNullDefault == undefined) {
158
+ this.config.options.enableAnsiNullDefault = true;
311
159
  }
312
- },
313
- SENT_ATTENTION: {
314
- name: 'SentAttention',
315
- enter: function () {
316
- return this.attentionReceived = false;
317
- },
318
- events: {
319
- socketError: function (error) {
320
- return this.transitionTo(this.STATE.FINAL);
321
- },
322
- data: function (data) {
323
- return this.sendDataToTokenStreamParser(data);
324
- },
325
- attention: function () {
326
- return this.attentionReceived = true;
327
- },
328
- message: function () {
329
- var message, sqlRequest;
330
- if (this.attentionReceived) {
331
- sqlRequest = this.request;
332
- this.request = void 0;
333
- this.transitionTo(this.STATE.LOGGED_IN);
334
- if (sqlRequest.canceled) {
335
- return sqlRequest.callback(RequestError("Canceled.", 'ECANCEL'));
336
- } else {
337
- message = "Timeout: Request failed to complete in " + this.config.options.requestTimeout + "ms";
338
- return sqlRequest.callback(RequestError(message, 'ETIMEOUT'));
339
- }
340
- }
160
+
161
+ if (!this.config.options.port && !this.config.options.instanceName) {
162
+ this.config.options.port = DEFAULT_PORT;
163
+ } else if (this.config.options.port && this.config.options.instanceName) {
164
+ throw new Error('Port and instanceName are mutually exclusive, but ' + this.config.options.port + ' and ' + this.config.options.instanceName + ' provided');
165
+ } else if (this.config.options.port) {
166
+ if (this.config.options.port < 0 || this.config.options.port > 65536) {
167
+ throw new RangeError('Port should be > 0 and < 65536');
341
168
  }
342
169
  }
343
- },
344
- FINAL: {
345
- name: 'Final',
346
- enter: function () {
347
- return this.cleanupConnection();
348
- },
349
- events: {
350
- loginFailed: function () {},
351
- connectTimeout: function () {},
352
- message: function () {},
353
- socketError: function () {}
170
+
171
+ if (this.config.options.columnNameReplacer && typeof this.config.options.columnNameReplacer !== 'function') {
172
+ throw new TypeError('options.columnNameReplacer must be a function or null.');
354
173
  }
355
174
  }
356
- };
357
-
358
- function Connection(config) {
359
- this.config = config;
360
- this.reset = bind(this.reset, this);
361
- this.socketClose = bind(this.socketClose, this);
362
- this.socketEnd = bind(this.socketEnd, this);
363
- this.socketConnect = bind(this.socketConnect, this);
364
- this.socketError = bind(this.socketError, this);
365
- this.requestTimeout = bind(this.requestTimeout, this);
366
- this.connectTimeout = bind(this.connectTimeout, this);
367
- this.defaultConfig();
368
- this.createDebug();
369
- this.createTokenStreamParser();
370
- this.inTransaction = false;
371
- this.transactionDescriptors = [new Buffer([0, 0, 0, 0, 0, 0, 0, 0])];
372
- this.transitionTo(this.STATE.CONNECTING);
373
- }
175
+ }, {
176
+ key: 'createDebug',
177
+ value: function createDebug() {
178
+ var _this = this;
374
179
 
375
- Connection.prototype.close = function () {
376
- return this.transitionTo(this.STATE.FINAL);
377
- };
180
+ this.debug = new Debug(this.config.options.debug);
181
+ return this.debug.on('debug', function (message) {
182
+ return _this.emit('debug', message);
183
+ });
184
+ }
185
+ }, {
186
+ key: 'createTokenStreamParser',
187
+ value: function createTokenStreamParser() {
188
+ var _this2 = this;
378
189
 
379
- Connection.prototype.initialiseConnection = function () {
380
- this.connect();
381
- return this.createConnectTimer();
382
- };
190
+ this.tokenStreamParser = new TokenStreamParser(this.debug, void 0, this.config.options);
383
191
 
384
- Connection.prototype.cleanupConnection = function (redirect) {
385
- this.redirect = redirect;
386
- if (!this.closed) {
387
- this.clearConnectTimer();
388
- this.clearRequestTimer();
389
- this.closeConnection();
390
- if (!this.redirect) {
391
- this.emit('end');
392
- } else {
393
- this.emit('rerouting');
394
- }
395
- this.closed = true;
396
- this.loggedIn = false;
397
- return this.loginError = null;
398
- }
399
- };
400
-
401
- Connection.prototype.defaultConfig = function () {
402
- var base, base1, base10, base11, base12, base13, base14, base2, base3, base4, base5, base6, base7, base8, base9;
403
- (base = this.config).options || (base.options = {});
404
- (base1 = this.config.options).textsize || (base1.textsize = DEFAULT_TEXTSIZE);
405
- (base2 = this.config.options).connectTimeout || (base2.connectTimeout = DEFAULT_CONNECT_TIMEOUT);
406
- if ((base3 = this.config.options).requestTimeout == null) {
407
- base3.requestTimeout = DEFAULT_CLIENT_REQUEST_TIMEOUT;
408
- }
409
- if ((base4 = this.config.options).cancelTimeout == null) {
410
- base4.cancelTimeout = DEFAULT_CANCEL_TIMEOUT;
411
- }
412
- (base5 = this.config.options).packetSize || (base5.packetSize = DEFAULT_PACKET_SIZE);
413
- (base6 = this.config.options).tdsVersion || (base6.tdsVersion = DEFAULT_TDS_VERSION);
414
- (base7 = this.config.options).isolationLevel || (base7.isolationLevel = ISOLATION_LEVEL.READ_COMMITTED);
415
- (base8 = this.config.options).encrypt || (base8.encrypt = false);
416
- (base9 = this.config.options).cryptoCredentialsDetails || (base9.cryptoCredentialsDetails = {});
417
- if ((base10 = this.config.options).useUTC == null) {
418
- base10.useUTC = true;
419
- }
420
- if ((base11 = this.config.options).useColumnNames == null) {
421
- base11.useColumnNames = false;
422
- }
423
- (base12 = this.config.options).connectionIsolationLevel || (base12.connectionIsolationLevel = ISOLATION_LEVEL.READ_COMMITTED);
424
- if ((base13 = this.config.options).readOnlyIntent == null) {
425
- base13.readOnlyIntent = false;
426
- }
427
- if ((base14 = this.config.options).enableAnsiNullDefault == null) {
428
- base14.enableAnsiNullDefault = true;
429
- }
430
- if (!this.config.options.port && !this.config.options.instanceName) {
431
- this.config.options.port = DEFAULT_PORT;
432
- } else if (this.config.options.port && this.config.options.instanceName) {
433
- throw new Error("Port and instanceName are mutually exclusive, but " + this.config.options.port + " and " + this.config.options.instanceName + " provided");
434
- } else if (this.config.options.port) {
435
- if (this.config.options.port < 0 || this.config.options.port > 65536) {
436
- throw new RangeError("Port should be > 0 and < 65536");
437
- }
438
- }
439
- if (this.config.options.columnNameReplacer && typeof this.config.options.columnNameReplacer !== 'function') {
440
- throw new TypeError('options.columnNameReplacer must be a function or null.');
441
- }
442
- };
192
+ this.tokenStreamParser.on('infoMessage', function (token) {
193
+ return _this2.emit('infoMessage', token);
194
+ });
443
195
 
444
- Connection.prototype.createDebug = function () {
445
- this.debug = new Debug(this.config.options.debug);
446
- return this.debug.on('debug', (function (_this) {
447
- return function (message) {
448
- return _this.emit('debug', message);
449
- };
450
- })(this));
451
- };
452
-
453
- Connection.prototype.createTokenStreamParser = function () {
454
- this.tokenStreamParser = new TokenStreamParser(this.debug, void 0, this.config.options);
455
- this.tokenStreamParser.on('infoMessage', (function (_this) {
456
- return function (token) {
457
- return _this.emit('infoMessage', token);
458
- };
459
- })(this));
460
- this.tokenStreamParser.on('sspichallenge', (function (_this) {
461
- return function (token) {
196
+ this.tokenStreamParser.on('sspichallenge', function (token) {
462
197
  if (token.ntlmpacket) {
463
- _this.ntlmpacket = token.ntlmpacket;
198
+ _this2.ntlmpacket = token.ntlmpacket;
464
199
  }
465
- return _this.emit('sspichallenge', token);
466
- };
467
- })(this));
468
- this.tokenStreamParser.on('errorMessage', (function (_this) {
469
- return function (token) {
470
- _this.emit('errorMessage', token);
471
- if (_this.loggedIn) {
472
- if (_this.request) {
473
- _this.request.error = RequestError(token.message, 'EREQUEST');
474
- _this.request.error.number = token.number;
475
- _this.request.error.state = token.state;
476
- _this.request.error["class"] = token["class"];
477
- _this.request.error.serverName = token.serverName;
478
- _this.request.error.procName = token.procName;
479
- return _this.request.error.lineNumber = token.lineNumber;
200
+ return _this2.emit('sspichallenge', token);
201
+ });
202
+
203
+ this.tokenStreamParser.on('errorMessage', function (token) {
204
+ _this2.emit('errorMessage', token);
205
+ if (_this2.loggedIn) {
206
+ if (_this2.request) {
207
+ _this2.request.error = RequestError(token.message, 'EREQUEST');
208
+ _this2.request.error.number = token.number;
209
+ _this2.request.error.state = token.state;
210
+ _this2.request.error['class'] = token['class'];
211
+ _this2.request.error.serverName = token.serverName;
212
+ _this2.request.error.procName = token.procName;
213
+ return _this2.request.error.lineNumber = token.lineNumber;
480
214
  }
481
215
  } else {
482
- return _this.loginError = ConnectionError(token.message, 'ELOGIN');
216
+ return _this2.loginError = ConnectionError(token.message, 'ELOGIN');
483
217
  }
484
- };
485
- })(this));
486
- this.tokenStreamParser.on('databaseChange', (function (_this) {
487
- return function (token) {
488
- return _this.emit('databaseChange', token.newValue);
489
- };
490
- })(this));
491
- this.tokenStreamParser.on('languageChange', (function (_this) {
492
- return function (token) {
493
- return _this.emit('languageChange', token.newValue);
494
- };
495
- })(this));
496
- this.tokenStreamParser.on('charsetChange', (function (_this) {
497
- return function (token) {
498
- return _this.emit('charsetChange', token.newValue);
499
- };
500
- })(this));
501
- this.tokenStreamParser.on('loginack', (function (_this) {
502
- return function (token) {
218
+ });
219
+
220
+ this.tokenStreamParser.on('databaseChange', function (token) {
221
+ return _this2.emit('databaseChange', token.newValue);
222
+ });
223
+
224
+ this.tokenStreamParser.on('languageChange', function (token) {
225
+ return _this2.emit('languageChange', token.newValue);
226
+ });
227
+
228
+ this.tokenStreamParser.on('charsetChange', function (token) {
229
+ return _this2.emit('charsetChange', token.newValue);
230
+ });
231
+
232
+ this.tokenStreamParser.on('loginack', function (token) {
503
233
  if (!token.tdsVersion) {
504
- _this.loginError = ConnectionError("Server responded with unknown TDS version.", 'ETDS');
505
- _this.loggedIn = false;
234
+ // unsupported TDS version
235
+ _this2.loginError = ConnectionError('Server responded with unknown TDS version.', 'ETDS');
236
+ _this2.loggedIn = false;
506
237
  return;
507
238
  }
508
- if (!token["interface"]) {
509
- _this.loginError = ConnectionError("Server responded with unsupported interface.", 'EINTERFACENOTSUPP');
510
- _this.loggedIn = false;
239
+
240
+ if (!token['interface']) {
241
+ // unsupported interface
242
+ _this2.loginError = ConnectionError('Server responded with unsupported interface.', 'EINTERFACENOTSUPP');
243
+ _this2.loggedIn = false;
511
244
  return;
512
245
  }
513
- _this.config.options.tdsVersion = token.tdsVersion;
514
- return _this.loggedIn = true;
515
- };
516
- })(this));
517
- this.tokenStreamParser.on('routingChange', (function (_this) {
518
- return function (token) {
519
- _this.routingData = token.newValue;
520
- return _this.dispatchEvent('routingChange');
521
- };
522
- })(this));
523
- this.tokenStreamParser.on('packetSizeChange', (function (_this) {
524
- return function (token) {
525
- return _this.messageIo.packetSize(token.newValue);
526
- };
527
- })(this));
528
- this.tokenStreamParser.on('beginTransaction', (function (_this) {
529
- return function (token) {
530
- _this.transactionDescriptors.push(token.newValue);
531
- return _this.inTransaction = true;
532
- };
533
- })(this));
534
- this.tokenStreamParser.on('commitTransaction', (function (_this) {
535
- return function (token) {
536
- _this.transactionDescriptors.length = 1;
537
- return _this.inTransaction = false;
538
- };
539
- })(this));
540
- this.tokenStreamParser.on('rollbackTransaction', (function (_this) {
541
- return function (token) {
542
- _this.transactionDescriptors.length = 1;
543
- _this.inTransaction = false;
544
- return _this.emit('rollbackTransaction');
545
- };
546
- })(this));
547
- this.tokenStreamParser.on('columnMetadata', (function (_this) {
548
- return function (token) {
549
- var col, columns, j, len, ref1;
550
- if (_this.request) {
551
- if (_this.config.options.useColumnNames) {
246
+
247
+ // use negotiated version
248
+ _this2.config.options.tdsVersion = token.tdsVersion;
249
+ return _this2.loggedIn = true;
250
+ });
251
+
252
+ this.tokenStreamParser.on('routingChange', function (token) {
253
+ _this2.routingData = token.newValue;
254
+ return _this2.dispatchEvent('routingChange');
255
+ });
256
+
257
+ this.tokenStreamParser.on('packetSizeChange', function (token) {
258
+ return _this2.messageIo.packetSize(token.newValue);
259
+ });
260
+
261
+ // A new top-level transaction was started. This is not fired
262
+ // for nested transactions.
263
+ this.tokenStreamParser.on('beginTransaction', function (token) {
264
+ _this2.transactionDescriptors.push(token.newValue);
265
+ return _this2.inTransaction = true;
266
+ });
267
+
268
+ // A top-level transaction was committed. This is not fired
269
+ // for nested transactions.
270
+ this.tokenStreamParser.on('commitTransaction', function () {
271
+ _this2.transactionDescriptors.length = 1;
272
+ return _this2.inTransaction = false;
273
+ });
274
+
275
+ // A top-level transaction was rolled back. This is not fired
276
+ // for nested transactions. This is also fired if a batch
277
+ // aborting error happened that caused a rollback.
278
+ this.tokenStreamParser.on('rollbackTransaction', function () {
279
+ _this2.transactionDescriptors.length = 1;
280
+ // An outermost transaction was rolled back. Reset the transaction counter
281
+ _this2.inTransaction = false;
282
+ return _this2.emit('rollbackTransaction');
283
+ });
284
+
285
+ this.tokenStreamParser.on('columnMetadata', function (token) {
286
+ if (_this2.request) {
287
+ var columns = undefined;
288
+ if (_this2.config.options.useColumnNames) {
552
289
  columns = {};
553
- ref1 = token.columns;
554
- for (j = 0, len = ref1.length; j < len; j++) {
555
- col = ref1[j];
290
+ for (var j = 0, len = token.columns.length; j < len; j++) {
291
+ var col = token.columns[j];
556
292
  if (columns[col.colName] == null) {
557
293
  columns[col.colName] = col;
558
294
  }
@@ -560,425 +296,444 @@ Connection = (function (superClass) {
560
296
  } else {
561
297
  columns = token.columns;
562
298
  }
563
- return _this.request.emit('columnMetadata', columns);
299
+ return _this2.request.emit('columnMetadata', columns);
564
300
  } else {
565
- _this.emit('error', new Error("Received 'columnMetadata' when no sqlRequest is in progress"));
566
- return _this.close();
301
+ _this2.emit('error', new Error("Received 'columnMetadata' when no sqlRequest is in progress"));
302
+ return _this2.close();
567
303
  }
568
- };
569
- })(this));
570
- this.tokenStreamParser.on('order', (function (_this) {
571
- return function (token) {
572
- if (_this.request) {
573
- return _this.request.emit('order', token.orderColumns);
304
+ });
305
+
306
+ this.tokenStreamParser.on('order', function (token) {
307
+ if (_this2.request) {
308
+ return _this2.request.emit('order', token.orderColumns);
574
309
  } else {
575
- _this.emit('error', new Error("Received 'order' when no sqlRequest is in progress"));
576
- return _this.close();
310
+ _this2.emit('error', new Error("Received 'order' when no sqlRequest is in progress"));
311
+ return _this2.close();
577
312
  }
578
- };
579
- })(this));
580
- this.tokenStreamParser.on('row', (function (_this) {
581
- return function (token) {
582
- if (_this.request) {
583
- if (_this.config.options.rowCollectionOnRequestCompletion) {
584
- _this.request.rows.push(token.columns);
313
+ });
314
+
315
+ this.tokenStreamParser.on('row', function (token) {
316
+ if (_this2.request) {
317
+ if (_this2.config.options.rowCollectionOnRequestCompletion) {
318
+ _this2.request.rows.push(token.columns);
585
319
  }
586
- if (_this.config.options.rowCollectionOnDone) {
587
- _this.request.rst.push(token.columns);
320
+ if (_this2.config.options.rowCollectionOnDone) {
321
+ _this2.request.rst.push(token.columns);
588
322
  }
589
- return _this.request.emit('row', token.columns);
323
+ return _this2.request.emit('row', token.columns);
590
324
  } else {
591
- _this.emit('error', new Error("Received 'row' when no sqlRequest is in progress"));
592
- return _this.close();
325
+ _this2.emit('error', new Error("Received 'row' when no sqlRequest is in progress"));
326
+ return _this2.close();
593
327
  }
594
- };
595
- })(this));
596
- this.tokenStreamParser.on('returnStatus', (function (_this) {
597
- return function (token) {
598
- if (_this.request) {
599
- return _this.procReturnStatusValue = token.value;
328
+ });
329
+
330
+ this.tokenStreamParser.on('returnStatus', function (token) {
331
+ if (_this2.request) {
332
+ // Keep value for passing in 'doneProc' event.
333
+ return _this2.procReturnStatusValue = token.value;
600
334
  }
601
- };
602
- })(this));
603
- this.tokenStreamParser.on('returnValue', (function (_this) {
604
- return function (token) {
605
- if (_this.request) {
606
- return _this.request.emit('returnValue', token.paramName, token.value, token.metadata);
335
+ });
336
+
337
+ this.tokenStreamParser.on('returnValue', function (token) {
338
+ if (_this2.request) {
339
+ return _this2.request.emit('returnValue', token.paramName, token.value, token.metadata);
607
340
  }
608
- };
609
- })(this));
610
- this.tokenStreamParser.on('doneProc', (function (_this) {
611
- return function (token) {
612
- if (_this.request) {
613
- _this.request.emit('doneProc', token.rowCount, token.more, _this.procReturnStatusValue, _this.request.rst);
614
- _this.procReturnStatusValue = void 0;
341
+ });
342
+
343
+ this.tokenStreamParser.on('doneProc', function (token) {
344
+ if (_this2.request) {
345
+ _this2.request.emit('doneProc', token.rowCount, token.more, _this2.procReturnStatusValue, _this2.request.rst);
346
+ _this2.procReturnStatusValue = void 0;
615
347
  if (token.rowCount !== void 0) {
616
- _this.request.rowCount += token.rowCount;
348
+ _this2.request.rowCount += token.rowCount;
617
349
  }
618
- if (_this.config.options.rowCollectionOnDone) {
619
- return _this.request.rst = [];
350
+ if (_this2.config.options.rowCollectionOnDone) {
351
+ return _this2.request.rst = [];
620
352
  }
621
353
  }
622
- };
623
- })(this));
624
- this.tokenStreamParser.on('doneInProc', (function (_this) {
625
- return function (token) {
626
- if (_this.request) {
627
- _this.request.emit('doneInProc', token.rowCount, token.more, _this.request.rst);
354
+ });
355
+
356
+ this.tokenStreamParser.on('doneInProc', function (token) {
357
+ if (_this2.request) {
358
+ _this2.request.emit('doneInProc', token.rowCount, token.more, _this2.request.rst);
628
359
  if (token.rowCount !== void 0) {
629
- _this.request.rowCount += token.rowCount;
360
+ _this2.request.rowCount += token.rowCount;
630
361
  }
631
- if (_this.config.options.rowCollectionOnDone) {
632
- return _this.request.rst = [];
362
+ if (_this2.config.options.rowCollectionOnDone) {
363
+ return _this2.request.rst = [];
633
364
  }
634
365
  }
635
- };
636
- })(this));
637
- this.tokenStreamParser.on('done', (function (_this) {
638
- return function (token) {
639
- if (_this.request) {
366
+ });
367
+
368
+ this.tokenStreamParser.on('done', function (token) {
369
+ if (_this2.request) {
640
370
  if (token.attention) {
641
- _this.dispatchEvent("attention");
371
+ _this2.dispatchEvent('attention');
642
372
  }
643
- if (token.sqlError && !_this.request.error) {
644
- _this.request.error = RequestError('An unknown error has occurred.', 'UNKNOWN');
373
+ if (token.sqlError && !_this2.request.error) {
374
+ // check if the DONE_ERROR flags was set, but an ERROR token was not sent.
375
+ _this2.request.error = RequestError('An unknown error has occurred.', 'UNKNOWN');
645
376
  }
646
- _this.request.emit('done', token.rowCount, token.more, _this.request.rst);
377
+ _this2.request.emit('done', token.rowCount, token.more, _this2.request.rst);
647
378
  if (token.rowCount !== void 0) {
648
- _this.request.rowCount += token.rowCount;
379
+ _this2.request.rowCount += token.rowCount;
649
380
  }
650
- if (_this.config.options.rowCollectionOnDone) {
651
- return _this.request.rst = [];
381
+ if (_this2.config.options.rowCollectionOnDone) {
382
+ return _this2.request.rst = [];
652
383
  }
653
384
  }
654
- };
655
- })(this));
656
- this.tokenStreamParser.on('resetConnection', (function (_this) {
657
- return function (token) {
658
- return _this.emit('resetConnection');
659
- };
660
- })(this));
661
- return this.tokenStreamParser.on('tokenStreamError', (function (_this) {
662
- return function (error) {
663
- _this.emit('error', error);
664
- return _this.close();
665
- };
666
- })(this));
667
- };
668
-
669
- Connection.prototype.connect = function () {
670
- if (this.config.options.port) {
671
- return this.connectOnPort(this.config.options.port);
672
- } else {
673
- return instanceLookup(this.config.server, this.config.options.instanceName, (function (_this) {
674
- return function (message, port) {
675
- if (_this.state === _this.STATE.FINAL) {
385
+ });
386
+
387
+ this.tokenStreamParser.on('resetConnection', function () {
388
+ return _this2.emit('resetConnection');
389
+ });
390
+
391
+ this.tokenStreamParser.on('tokenStreamError', function (error) {
392
+ _this2.emit('error', error);
393
+ return _this2.close();
394
+ });
395
+ }
396
+ }, {
397
+ key: 'connect',
398
+ value: function connect() {
399
+ var _this3 = this;
400
+
401
+ if (this.config.options.port) {
402
+ return this.connectOnPort(this.config.options.port);
403
+ } else {
404
+ return instanceLookup(this.config.server, this.config.options.instanceName, function (message, port) {
405
+ if (_this3.state === _this3.STATE.FINAL) {
676
406
  return;
677
407
  }
678
408
  if (message) {
679
- return _this.emit('connect', ConnectionError(message, 'EINSTLOOKUP'));
409
+ return _this3.emit('connect', ConnectionError(message, 'EINSTLOOKUP'));
680
410
  } else {
681
- return _this.connectOnPort(port);
411
+ return _this3.connectOnPort(port);
682
412
  }
683
- };
684
- })(this), this.config.options.connectTimeout);
685
- }
686
- };
687
-
688
- Connection.prototype.connectOnPort = function (port) {
689
- var connectOpts, ref1, ref2;
690
- this.socket = new Socket({});
691
- connectOpts = {
692
- host: ((ref1 = this.routingData) != null ? ref1.server : void 0) || this.config.server,
693
- port: ((ref2 = this.routingData) != null ? ref2.port : void 0) || port
694
- };
695
- if (this.config.options.localAddress) {
696
- connectOpts.localAddress = this.config.options.localAddress;
697
- }
698
- this.socket.connect(connectOpts);
699
- this.socket.on('error', this.socketError);
700
- this.socket.on('connect', this.socketConnect);
701
- this.socket.on('close', this.socketClose);
702
- this.socket.on('end', this.socketEnd);
703
- this.messageIo = new MessageIO(this.socket, this.config.options.packetSize, this.debug);
704
- this.messageIo.on('data', (function (_this) {
705
- return function (data) {
706
- return _this.dispatchEvent('data', data);
707
- };
708
- })(this));
709
- this.messageIo.on('message', (function (_this) {
710
- return function () {
711
- return _this.dispatchEvent('message');
413
+ }, this.config.options.connectTimeout);
414
+ }
415
+ }
416
+ }, {
417
+ key: 'connectOnPort',
418
+ value: function connectOnPort(port) {
419
+ var _this4 = this;
420
+
421
+ this.socket = new Socket({});
422
+ var connectOpts = {
423
+ host: this.routingData ? this.routingData.server : this.config.server,
424
+ port: this.routingData ? this.routingData.port : port
712
425
  };
713
- })(this));
714
- return this.messageIo.on('secure', this.emit.bind(this, 'secure'));
715
- };
716
-
717
- Connection.prototype.closeConnection = function () {
718
- var ref1;
719
- return (ref1 = this.socket) != null ? ref1.destroy() : void 0;
720
- };
721
-
722
- Connection.prototype.createConnectTimer = function () {
723
- return this.connectTimer = setTimeout(this.connectTimeout, this.config.options.connectTimeout);
724
- };
725
-
726
- Connection.prototype.createRequestTimer = function () {
727
- if (this.config.options.requestTimeout) {
728
- return this.requestTimer = setTimeout(this.requestTimeout, this.config.options.requestTimeout);
729
- }
730
- };
731
-
732
- Connection.prototype.connectTimeout = function () {
733
- var message;
734
- message = "Failed to connect to " + this.config.server + ":" + this.config.options.port + " in " + this.config.options.connectTimeout + "ms";
735
- this.debug.log(message);
736
- this.emit('connect', ConnectionError(message, 'ETIMEOUT'));
737
- this.connectTimer = void 0;
738
- return this.dispatchEvent('connectTimeout');
739
- };
740
-
741
- Connection.prototype.requestTimeout = function () {
742
- this.requestTimer = void 0;
743
- this.messageIo.sendMessage(TYPE.ATTENTION);
744
- return this.transitionTo(this.STATE.SENT_ATTENTION);
745
- };
746
-
747
- Connection.prototype.clearConnectTimer = function () {
748
- if (this.connectTimer) {
749
- return clearTimeout(this.connectTimer);
750
- }
751
- };
752
-
753
- Connection.prototype.clearRequestTimer = function () {
754
- if (this.requestTimer) {
755
- return clearTimeout(this.requestTimer);
756
- }
757
- };
758
-
759
- Connection.prototype.transitionTo = function (newState) {
760
- var ref1, ref2;
761
- if (this.state === newState) {
762
- this.debug.log("State is already " + newState.name);
763
- return;
764
- }
765
- if ((ref1 = this.state) != null ? ref1.exit : void 0) {
766
- this.state.exit.apply(this);
767
- }
768
- this.debug.log("State change: " + ((ref2 = this.state) != null ? ref2.name : void 0) + " -> " + newState.name);
769
- this.state = newState;
770
- if (this.state.enter) {
771
- return this.state.enter.apply(this);
772
- }
773
- };
774
-
775
- Connection.prototype.dispatchEvent = function () {
776
- var args, eventFunction, eventName, ref1;
777
- eventName = arguments[0], args = 2 <= arguments.length ? slice.call(arguments, 1) : [];
778
- if ((ref1 = this.state) != null ? ref1.events[eventName] : void 0) {
779
- return eventFunction = this.state.events[eventName].apply(this, args);
780
- } else {
781
- this.emit('error', new Error("No event '" + eventName + "' in state '" + this.state.name + "'"));
782
- return this.close();
783
- }
784
- };
785
-
786
- Connection.prototype.socketError = function (error) {
787
- var message;
788
- if (this.state === this.STATE.CONNECTING) {
789
- message = "Failed to connect to " + this.config.server + ":" + this.config.options.port + " - " + error.message;
790
- this.debug.log(message);
791
- this.emit('connect', ConnectionError(message, 'ESOCKET'));
792
- } else {
793
- message = "Connection lost - " + error.message;
426
+ if (this.config.options.localAddress) {
427
+ connectOpts.localAddress = this.config.options.localAddress;
428
+ }
429
+ this.socket.connect(connectOpts);
430
+ this.socket.on('error', this.socketError);
431
+ this.socket.on('connect', this.socketConnect);
432
+ this.socket.on('close', this.socketClose);
433
+ this.socket.on('end', this.socketEnd);
434
+ this.messageIo = new MessageIO(this.socket, this.config.options.packetSize, this.debug);
435
+ this.messageIo.on('data', function (data) {
436
+ _this4.dispatchEvent('data', data);
437
+ });
438
+ this.messageIo.on('message', function () {
439
+ return _this4.dispatchEvent('message');
440
+ });
441
+ return this.messageIo.on('secure', this.emit.bind(this, 'secure'));
442
+ }
443
+ }, {
444
+ key: 'closeConnection',
445
+ value: function closeConnection() {
446
+ if (this.socket) {
447
+ this.socket.destroy();
448
+ }
449
+ }
450
+ }, {
451
+ key: 'createConnectTimer',
452
+ value: function createConnectTimer() {
453
+ return this.connectTimer = setTimeout(this.connectTimeout, this.config.options.connectTimeout);
454
+ }
455
+ }, {
456
+ key: 'createRequestTimer',
457
+ value: function createRequestTimer() {
458
+ if (this.config.options.requestTimeout) {
459
+ return this.requestTimer = setTimeout(this.requestTimeout, this.config.options.requestTimeout);
460
+ }
461
+ }
462
+ }, {
463
+ key: 'connectTimeout',
464
+ value: function connectTimeout() {
465
+ var message = 'Failed to connect to ' + this.config.server + ':' + this.config.options.port + ' in ' + this.config.options.connectTimeout + 'ms';
794
466
  this.debug.log(message);
795
- this.emit('error', ConnectionError(message, 'ESOCKET'));
796
- }
797
- return this.dispatchEvent('socketError', error);
798
- };
799
-
800
- Connection.prototype.socketConnect = function () {
801
- this.socket.setKeepAlive(true, KEEP_ALIVE_INITIAL_DELAY);
802
- this.closed = false;
803
- this.debug.log("connected to " + this.config.server + ":" + this.config.options.port);
804
- return this.dispatchEvent('socketConnect');
805
- };
806
-
807
- Connection.prototype.socketEnd = function () {
808
- this.debug.log("socket ended");
809
- return this.transitionTo(this.STATE.FINAL);
810
- };
811
-
812
- Connection.prototype.socketClose = function () {
813
- this.debug.log("connection to " + this.config.server + ":" + this.config.options.port + " closed");
814
- if (this.state === this.STATE.REROUTING) {
815
- this.debug.log("Rerouting to " + this.routingData.server + ":" + this.routingData.port);
816
- return this.dispatchEvent('reconnect');
817
- } else {
818
- return this.transitionTo(this.STATE.FINAL);
467
+ this.emit('connect', ConnectionError(message, 'ETIMEOUT'));
468
+ this.connectTimer = void 0;
469
+ return this.dispatchEvent('connectTimeout');
819
470
  }
820
- };
821
-
822
- Connection.prototype.sendPreLogin = function () {
823
- var payload;
824
- payload = new PreloginPayload({
825
- encrypt: this.config.options.encrypt
826
- });
827
- this.messageIo.sendMessage(TYPE.PRELOGIN, payload.data);
828
- return this.debug.payload(function () {
829
- return payload.toString(' ');
830
- });
831
- };
832
-
833
- Connection.prototype.emptyMessageBuffer = function () {
834
- return this.messageBuffer = new Buffer(0);
835
- };
836
-
837
- Connection.prototype.addToMessageBuffer = function (data) {
838
- return this.messageBuffer = Buffer.concat([this.messageBuffer, data]);
839
- };
840
-
841
- Connection.prototype.processPreLoginResponse = function () {
842
- var preloginPayload, ref1;
843
- preloginPayload = new PreloginPayload(this.messageBuffer);
844
- this.debug.payload(function () {
845
- return preloginPayload.toString(' ');
846
- });
847
- if ((ref1 = preloginPayload.encryptionString) === 'ON' || ref1 === 'REQ') {
848
- return this.dispatchEvent('tls');
849
- } else {
850
- return this.dispatchEvent('noTls');
851
- }
852
- };
853
-
854
- Connection.prototype.sendLogin7Packet = function () {
855
- var loginData, payload, ref1;
856
- loginData = {
857
- domain: this.config.domain,
858
- userName: this.config.userName,
859
- password: this.config.password,
860
- database: this.config.options.database,
861
- serverName: ((ref1 = this.routingData) != null ? ref1.server : void 0) || this.config.server,
862
- appName: this.config.options.appName,
863
- packetSize: this.config.options.packetSize,
864
- tdsVersion: this.config.options.tdsVersion,
865
- initDbFatal: !this.config.options.fallbackToDefaultDb,
866
- readOnlyIntent: this.config.options.readOnlyIntent
867
- };
868
- this.routingData = void 0;
869
- payload = new Login7Payload(loginData);
870
- this.messageIo.sendMessage(TYPE.LOGIN7, payload.data);
871
- return this.debug.payload(function () {
872
- return payload.toString(' ');
873
- });
874
- };
875
-
876
- Connection.prototype.sendNTLMResponsePacket = function () {
877
- var payload, responseData;
878
- responseData = {
879
- domain: this.config.domain,
880
- userName: this.config.userName,
881
- password: this.config.password,
882
- database: this.config.options.database,
883
- appName: this.config.options.appName,
884
- packetSize: this.config.options.packetSize,
885
- tdsVersion: this.config.options.tdsVersion,
886
- ntlmpacket: this.ntlmpacket,
887
- additional: this.additional
888
- };
889
- payload = new NTLMResponsePayload(responseData);
890
- this.messageIo.sendMessage(TYPE.NTLMAUTH_PKT, payload.data);
891
- return this.debug.payload(function () {
892
- return payload.toString(' ');
893
- });
894
- };
895
-
896
- Connection.prototype.sendDataToTokenStreamParser = function (data) {
897
- return this.tokenStreamParser.addBuffer(data);
898
- };
899
-
900
- Connection.prototype.sendInitialSql = function () {
901
- var payload;
902
- payload = new SqlBatchPayload(this.getInitialSql(), this.currentTransactionDescriptor(), this.config.options);
903
- return this.messageIo.sendMessage(TYPE.SQL_BATCH, payload.data);
904
- };
905
-
906
- Connection.prototype.getInitialSql = function () {
907
- var enableAnsiNullDefault, xact_abort;
908
- xact_abort = this.config.options.abortTransactionOnError ? 'on' : 'off';
909
- enableAnsiNullDefault = this.config.options.enableAnsiNullDefault ? 'on' : 'off';
910
- return "set textsize " + this.config.options.textsize + "\nset quoted_identifier on\nset arithabort off\nset numeric_roundabort off\nset ansi_warnings on\nset ansi_padding on\nset ansi_nulls on\nset ansi_null_dflt_on " + enableAnsiNullDefault + "\nset concat_null_yields_null on\nset cursor_close_on_commit off\nset implicit_transactions off\nset language us_english\nset dateformat mdy\nset datefirst 7\nset transaction isolation level " + this.getIsolationLevelText(this.config.options.connectionIsolationLevel) + "\nset xact_abort " + xact_abort;
911
- };
912
-
913
- Connection.prototype.processedInitialSql = function () {
914
- this.clearConnectTimer();
915
- return this.emit('connect');
916
- };
917
-
918
- Connection.prototype.processLogin7Response = function () {
919
- if (this.loggedIn) {
920
- return this.dispatchEvent('loggedIn');
921
- } else {
922
- if (this.loginError) {
923
- this.emit('connect', this.loginError);
924
- } else {
925
- this.emit('connect', ConnectionError('Login failed.', 'ELOGIN'));
471
+ }, {
472
+ key: 'requestTimeout',
473
+ value: function requestTimeout() {
474
+ this.requestTimer = void 0;
475
+ this.messageIo.sendMessage(TYPE.ATTENTION);
476
+ return this.transitionTo(this.STATE.SENT_ATTENTION);
477
+ }
478
+ }, {
479
+ key: 'clearConnectTimer',
480
+ value: function clearConnectTimer() {
481
+ if (this.connectTimer) {
482
+ return clearTimeout(this.connectTimer);
483
+ }
484
+ }
485
+ }, {
486
+ key: 'clearRequestTimer',
487
+ value: function clearRequestTimer() {
488
+ if (this.requestTimer) {
489
+ return clearTimeout(this.requestTimer);
926
490
  }
927
- return this.dispatchEvent('loginFailed');
928
491
  }
929
- };
492
+ }, {
493
+ key: 'transitionTo',
494
+ value: function transitionTo(newState) {
495
+ if (this.state === newState) {
496
+ this.debug.log('State is already ' + newState.name);
497
+ return;
498
+ }
499
+
500
+ if (this.state && this.state.exit) {
501
+ this.state.exit.apply(this);
502
+ }
930
503
 
931
- Connection.prototype.processLogin7NTLMResponse = function () {
932
- if (this.ntlmpacket) {
933
- return this.dispatchEvent('receivedChallenge');
934
- } else {
935
- if (this.loginError) {
936
- this.emit('connect', this.loginError);
504
+ this.debug.log('State change: ' + (this.state ? this.state.name : undefined) + ' -> ' + newState.name);
505
+ this.state = newState;
506
+
507
+ if (this.state.enter) {
508
+ return this.state.enter.apply(this);
509
+ }
510
+ }
511
+ }, {
512
+ key: 'dispatchEvent',
513
+ value: function dispatchEvent(eventName) {
514
+ if (this.state.events[eventName]) {
515
+ var args = new Array(arguments.length - 1);
516
+ for (var i = 0; i < args.length;) {
517
+ args[i++] = arguments[i];
518
+ }
519
+ return this.state.events[eventName].apply(this, args);
520
+ } else {
521
+ this.emit('error', new Error('No event \'' + eventName + '\' in state \'' + this.state.name + '\''));
522
+ return this.close();
523
+ }
524
+ }
525
+ }, {
526
+ key: 'socketError',
527
+ value: function socketError(error) {
528
+ if (this.state === this.STATE.CONNECTING) {
529
+ var message = 'Failed to connect to ' + this.config.server + ':' + this.config.options.port + ' - ' + error.message;
530
+ this.debug.log(message);
531
+ this.emit('connect', ConnectionError(message, 'ESOCKET'));
532
+ } else {
533
+ var message = 'Connection lost - ' + error.message;
534
+ this.debug.log(message);
535
+ this.emit('error', ConnectionError(message, 'ESOCKET'));
536
+ }
537
+ return this.dispatchEvent('socketError', error);
538
+ }
539
+ }, {
540
+ key: 'socketConnect',
541
+ value: function socketConnect() {
542
+ this.socket.setKeepAlive(true, KEEP_ALIVE_INITIAL_DELAY);
543
+ this.closed = false;
544
+ this.debug.log('connected to ' + this.config.server + ':' + this.config.options.port);
545
+ return this.dispatchEvent('socketConnect');
546
+ }
547
+ }, {
548
+ key: 'socketEnd',
549
+ value: function socketEnd() {
550
+ this.debug.log('socket ended');
551
+ return this.transitionTo(this.STATE.FINAL);
552
+ }
553
+ }, {
554
+ key: 'socketClose',
555
+ value: function socketClose() {
556
+ this.debug.log('connection to ' + this.config.server + ':' + this.config.options.port + ' closed');
557
+ if (this.state === this.STATE.REROUTING) {
558
+ this.debug.log('Rerouting to ' + this.routingData.server + ':' + this.routingData.port);
559
+ return this.dispatchEvent('reconnect');
937
560
  } else {
938
- this.emit('connect', ConnectionError('Login failed.', 'ELOGIN'));
561
+ return this.transitionTo(this.STATE.FINAL);
939
562
  }
940
- return this.dispatchEvent('loginFailed');
941
563
  }
942
- };
564
+ }, {
565
+ key: 'sendPreLogin',
566
+ value: function sendPreLogin() {
567
+ var payload = new PreloginPayload({
568
+ encrypt: this.config.options.encrypt
569
+ });
570
+ this.messageIo.sendMessage(TYPE.PRELOGIN, payload.data);
571
+ return this.debug.payload(function () {
572
+ return payload.toString(' ');
573
+ });
574
+ }
575
+ }, {
576
+ key: 'emptyMessageBuffer',
577
+ value: function emptyMessageBuffer() {
578
+ return this.messageBuffer = new Buffer(0);
579
+ }
580
+ }, {
581
+ key: 'addToMessageBuffer',
582
+ value: function addToMessageBuffer(data) {
583
+ return this.messageBuffer = Buffer.concat([this.messageBuffer, data]);
584
+ }
585
+ }, {
586
+ key: 'processPreLoginResponse',
587
+ value: function processPreLoginResponse() {
588
+ var preloginPayload = new PreloginPayload(this.messageBuffer);
589
+ this.debug.payload(function () {
590
+ return preloginPayload.toString(' ');
591
+ });
943
592
 
944
- Connection.prototype.processLogin7NTLMAck = function () {
945
- if (this.loggedIn) {
946
- return this.dispatchEvent('loggedIn');
947
- } else {
948
- if (this.loginError) {
949
- this.emit('connect', this.loginError);
593
+ if (preloginPayload.encryptionString === 'ON' || preloginPayload.encryptionString === 'REQ') {
594
+ return this.dispatchEvent('tls');
950
595
  } else {
951
- this.emit('connect', ConnectionError('Login failed.', 'ELOGIN'));
596
+ return this.dispatchEvent('noTls');
952
597
  }
953
- return this.dispatchEvent('loginFailed');
954
598
  }
955
- };
599
+ }, {
600
+ key: 'sendLogin7Packet',
601
+ value: function sendLogin7Packet() {
602
+ var payload = new Login7Payload({
603
+ domain: this.config.domain,
604
+ userName: this.config.userName,
605
+ password: this.config.password,
606
+ database: this.config.options.database,
607
+ serverName: this.routingData ? this.routingData.server : this.config.server,
608
+ appName: this.config.options.appName,
609
+ packetSize: this.config.options.packetSize,
610
+ tdsVersion: this.config.options.tdsVersion,
611
+ initDbFatal: !this.config.options.fallbackToDefaultDb,
612
+ readOnlyIntent: this.config.options.readOnlyIntent
613
+ });
956
614
 
957
- Connection.prototype.execSqlBatch = function (request) {
958
- return this.makeRequest(request, TYPE.SQL_BATCH, new SqlBatchPayload(request.sqlTextOrProcedure, this.currentTransactionDescriptor(), this.config.options));
959
- };
615
+ this.routingData = undefined;
616
+ this.messageIo.sendMessage(TYPE.LOGIN7, payload.data);
960
617
 
961
- Connection.prototype.execSql = function (request) {
962
- request.transformIntoExecuteSqlRpc();
963
- if (request.error != null) {
964
- return process.nextTick((function (_this) {
965
- return function () {
966
- _this.debug.log(request.error.message);
618
+ return this.debug.payload(function () {
619
+ return payload.toString(' ');
620
+ });
621
+ }
622
+ }, {
623
+ key: 'sendNTLMResponsePacket',
624
+ value: function sendNTLMResponsePacket() {
625
+ var payload = new NTLMResponsePayload({
626
+ domain: this.config.domain,
627
+ userName: this.config.userName,
628
+ password: this.config.password,
629
+ database: this.config.options.database,
630
+ appName: this.config.options.appName,
631
+ packetSize: this.config.options.packetSize,
632
+ tdsVersion: this.config.options.tdsVersion,
633
+ ntlmpacket: this.ntlmpacket,
634
+ additional: this.additional
635
+ });
636
+ this.messageIo.sendMessage(TYPE.NTLMAUTH_PKT, payload.data);
637
+ return this.debug.payload(function () {
638
+ return payload.toString(' ');
639
+ });
640
+ }
641
+ }, {
642
+ key: 'sendDataToTokenStreamParser',
643
+ value: function sendDataToTokenStreamParser(data) {
644
+ return this.tokenStreamParser.addBuffer(data);
645
+ }
646
+ }, {
647
+ key: 'sendInitialSql',
648
+ value: function sendInitialSql() {
649
+ var payload = new SqlBatchPayload(this.getInitialSql(), this.currentTransactionDescriptor(), this.config.options);
650
+ return this.messageIo.sendMessage(TYPE.SQL_BATCH, payload.data);
651
+ }
652
+ }, {
653
+ key: 'getInitialSql',
654
+ value: function getInitialSql() {
655
+ var xact_abort = this.config.options.abortTransactionOnError ? 'on' : 'off';
656
+ var enableAnsiNullDefault = this.config.options.enableAnsiNullDefault ? 'on' : 'off';
657
+ return 'set textsize ' + this.config.options.textsize + '\nset quoted_identifier on\nset arithabort off\nset numeric_roundabort off\nset ansi_warnings on\nset ansi_padding on\nset ansi_nulls on\nset ansi_null_dflt_on ' + enableAnsiNullDefault + '\nset concat_null_yields_null on\nset cursor_close_on_commit off\nset implicit_transactions off\nset language us_english\nset dateformat mdy\nset datefirst 7\nset transaction isolation level ' + this.getIsolationLevelText(this.config.options.connectionIsolationLevel) + '\nset xact_abort ' + xact_abort;
658
+ }
659
+ }, {
660
+ key: 'processedInitialSql',
661
+ value: function processedInitialSql() {
662
+ this.clearConnectTimer();
663
+ return this.emit('connect');
664
+ }
665
+ }, {
666
+ key: 'processLogin7Response',
667
+ value: function processLogin7Response() {
668
+ if (this.loggedIn) {
669
+ return this.dispatchEvent('loggedIn');
670
+ } else {
671
+ if (this.loginError) {
672
+ this.emit('connect', this.loginError);
673
+ } else {
674
+ this.emit('connect', ConnectionError('Login failed.', 'ELOGIN'));
675
+ }
676
+ return this.dispatchEvent('loginFailed');
677
+ }
678
+ }
679
+ }, {
680
+ key: 'processLogin7NTLMResponse',
681
+ value: function processLogin7NTLMResponse() {
682
+ if (this.ntlmpacket) {
683
+ return this.dispatchEvent('receivedChallenge');
684
+ } else {
685
+ if (this.loginError) {
686
+ this.emit('connect', this.loginError);
687
+ } else {
688
+ this.emit('connect', ConnectionError('Login failed.', 'ELOGIN'));
689
+ }
690
+ return this.dispatchEvent('loginFailed');
691
+ }
692
+ }
693
+ }, {
694
+ key: 'processLogin7NTLMAck',
695
+ value: function processLogin7NTLMAck() {
696
+ if (this.loggedIn) {
697
+ return this.dispatchEvent('loggedIn');
698
+ } else {
699
+ if (this.loginError) {
700
+ this.emit('connect', this.loginError);
701
+ } else {
702
+ this.emit('connect', ConnectionError('Login failed.', 'ELOGIN'));
703
+ }
704
+ return this.dispatchEvent('loginFailed');
705
+ }
706
+ }
707
+ }, {
708
+ key: 'execSqlBatch',
709
+ value: function execSqlBatch(request) {
710
+ return this.makeRequest(request, TYPE.SQL_BATCH, new SqlBatchPayload(request.sqlTextOrProcedure, this.currentTransactionDescriptor(), this.config.options));
711
+ }
712
+ }, {
713
+ key: 'execSql',
714
+ value: function execSql(request) {
715
+ var _this5 = this;
716
+
717
+ request.transformIntoExecuteSqlRpc();
718
+ if (request.error != null) {
719
+ return process.nextTick(function () {
720
+ _this5.debug.log(request.error.message);
967
721
  return request.callback(request.error);
968
- };
969
- })(this));
722
+ });
723
+ }
724
+ return this.makeRequest(request, TYPE.RPC_REQUEST, new RpcRequestPayload(request, this.currentTransactionDescriptor(), this.config.options));
970
725
  }
971
- return this.makeRequest(request, TYPE.RPC_REQUEST, new RpcRequestPayload(request, this.currentTransactionDescriptor(), this.config.options));
972
- };
973
-
974
- Connection.prototype.newBulkLoad = function (table, callback) {
975
- return new BulkLoad(table, this.config.options, callback);
976
- };
726
+ }, {
727
+ key: 'newBulkLoad',
728
+ value: function newBulkLoad(table, callback) {
729
+ return new BulkLoad(table, this.config.options, callback);
730
+ }
731
+ }, {
732
+ key: 'execBulkLoad',
733
+ value: function execBulkLoad(bulkLoad) {
734
+ var _this6 = this;
977
735
 
978
- Connection.prototype.execBulkLoad = function (bulkLoad) {
979
- var request;
980
- request = new Request(bulkLoad.getBulkInsertSql(), (function (_this) {
981
- return function (error) {
736
+ var request = new Request(bulkLoad.getBulkInsertSql(), function (error) {
982
737
  if (error) {
983
738
  if (error.code === 'UNKNOWN') {
984
739
  error.message += ' This is likely because the schema of the BulkLoad does not match the schema of the table you are attempting to insert into.';
@@ -986,111 +741,116 @@ Connection = (function (superClass) {
986
741
  bulkLoad.error = error;
987
742
  return bulkLoad.callback(error);
988
743
  } else {
989
- return _this.makeRequest(bulkLoad, TYPE.BULK_LOAD, bulkLoad.getPayload());
744
+ return _this6.makeRequest(bulkLoad, TYPE.BULK_LOAD, bulkLoad.getPayload());
990
745
  }
991
- };
992
- })(this));
993
- return this.execSqlBatch(request);
994
- };
995
-
996
- Connection.prototype.prepare = function (request) {
997
- request.transformIntoPrepareRpc();
998
- return this.makeRequest(request, TYPE.RPC_REQUEST, new RpcRequestPayload(request, this.currentTransactionDescriptor(), this.config.options));
999
- };
1000
-
1001
- Connection.prototype.unprepare = function (request) {
1002
- request.transformIntoUnprepareRpc();
1003
- return this.makeRequest(request, TYPE.RPC_REQUEST, new RpcRequestPayload(request, this.currentTransactionDescriptor(), this.config.options));
1004
- };
1005
-
1006
- Connection.prototype.execute = function (request, parameters) {
1007
- request.transformIntoExecuteRpc(parameters);
1008
- if (request.error != null) {
1009
- return process.nextTick((function (_this) {
1010
- return function () {
1011
- _this.debug.log(request.error.message);
746
+ });
747
+ return this.execSqlBatch(request);
748
+ }
749
+ }, {
750
+ key: 'prepare',
751
+ value: function prepare(request) {
752
+ request.transformIntoPrepareRpc();
753
+ return this.makeRequest(request, TYPE.RPC_REQUEST, new RpcRequestPayload(request, this.currentTransactionDescriptor(), this.config.options));
754
+ }
755
+ }, {
756
+ key: 'unprepare',
757
+ value: function unprepare(request) {
758
+ request.transformIntoUnprepareRpc();
759
+ return this.makeRequest(request, TYPE.RPC_REQUEST, new RpcRequestPayload(request, this.currentTransactionDescriptor(), this.config.options));
760
+ }
761
+ }, {
762
+ key: 'execute',
763
+ value: function execute(request, parameters) {
764
+ var _this7 = this;
765
+
766
+ request.transformIntoExecuteRpc(parameters);
767
+ if (request.error != null) {
768
+ return process.nextTick(function () {
769
+ _this7.debug.log(request.error.message);
1012
770
  return request.callback(request.error);
1013
- };
1014
- })(this));
1015
- }
1016
- return this.makeRequest(request, TYPE.RPC_REQUEST, new RpcRequestPayload(request, this.currentTransactionDescriptor(), this.config.options));
1017
- };
1018
-
1019
- Connection.prototype.callProcedure = function (request) {
1020
- request.validateParameters();
1021
- if (request.error != null) {
1022
- return process.nextTick((function (_this) {
1023
- return function () {
1024
- _this.debug.log(request.error.message);
771
+ });
772
+ }
773
+ return this.makeRequest(request, TYPE.RPC_REQUEST, new RpcRequestPayload(request, this.currentTransactionDescriptor(), this.config.options));
774
+ }
775
+ }, {
776
+ key: 'callProcedure',
777
+ value: function callProcedure(request) {
778
+ var _this8 = this;
779
+
780
+ request.validateParameters();
781
+ if (request.error != null) {
782
+ return process.nextTick(function () {
783
+ _this8.debug.log(request.error.message);
1025
784
  return request.callback(request.error);
1026
- };
1027
- })(this));
1028
- }
1029
- return this.makeRequest(request, TYPE.RPC_REQUEST, new RpcRequestPayload(request, this.currentTransactionDescriptor(), this.config.options));
1030
- };
1031
-
1032
- Connection.prototype.beginTransaction = function (callback, name, isolationLevel) {
1033
- var request, transaction;
1034
- isolationLevel || (isolationLevel = this.config.options.isolationLevel);
1035
- transaction = new Transaction(name || '', isolationLevel);
1036
- if (this.config.options.tdsVersion < "7_2") {
1037
- return this.execSqlBatch(new Request("SET TRANSACTION ISOLATION LEVEL " + transaction.isolationLevelToTSQL() + ";BEGIN TRAN " + transaction.name, callback));
1038
- }
1039
- request = new Request(void 0, (function (_this) {
1040
- return function (err) {
1041
- return callback(err, _this.currentTransactionDescriptor());
1042
- };
1043
- })(this));
1044
- return this.makeRequest(request, TYPE.TRANSACTION_MANAGER, transaction.beginPayload(this.currentTransactionDescriptor()));
1045
- };
1046
-
1047
- Connection.prototype.commitTransaction = function (callback, name) {
1048
- var request, transaction;
1049
- transaction = new Transaction(name || '');
1050
- if (this.config.options.tdsVersion < "7_2") {
1051
- return this.execSqlBatch(new Request("COMMIT TRAN " + transaction.name, callback));
1052
- }
1053
- request = new Request(void 0, callback);
1054
- return this.makeRequest(request, TYPE.TRANSACTION_MANAGER, transaction.commitPayload(this.currentTransactionDescriptor()));
1055
- };
1056
-
1057
- Connection.prototype.rollbackTransaction = function (callback, name) {
1058
- var request, transaction;
1059
- transaction = new Transaction(name || '');
1060
- if (this.config.options.tdsVersion < "7_2") {
1061
- return this.execSqlBatch(new Request("ROLLBACK TRAN " + transaction.name, callback));
1062
- }
1063
- request = new Request(void 0, callback);
1064
- return this.makeRequest(request, TYPE.TRANSACTION_MANAGER, transaction.rollbackPayload(this.currentTransactionDescriptor()));
1065
- };
1066
-
1067
- Connection.prototype.saveTransaction = function (callback, name) {
1068
- var request, transaction;
1069
- transaction = new Transaction(name);
1070
- if (this.config.options.tdsVersion < "7_2") {
1071
- return this.execSqlBatch(new Request("SAVE TRAN " + transaction.name, callback));
1072
- }
1073
- request = new Request(void 0, callback);
1074
- return this.makeRequest(request, TYPE.TRANSACTION_MANAGER, transaction.savePayload(this.currentTransactionDescriptor()));
1075
- };
1076
-
1077
- Connection.prototype.transaction = function (cb, isolationLevel) {
1078
- var name, txDone, useSavepoint;
1079
- if (typeof cb !== 'function') {
1080
- throw new TypeError('`cb` must be a function');
1081
- }
1082
- useSavepoint = this.inTransaction;
1083
- name = "_tedious_" + crypto.randomBytes(10).toString('hex');
1084
- txDone = (function (_this) {
1085
- return function (err, done) {
1086
- var args, i, j, ref1;
1087
- args = [];
1088
- for (i = j = 2, ref1 = arguments.length; 2 <= ref1 ? j < ref1 : j > ref1; i = 2 <= ref1 ? ++j : --j) {
1089
- args.push(arguments[i]);
785
+ });
786
+ }
787
+ return this.makeRequest(request, TYPE.RPC_REQUEST, new RpcRequestPayload(request, this.currentTransactionDescriptor(), this.config.options));
788
+ }
789
+ }, {
790
+ key: 'beginTransaction',
791
+ value: function beginTransaction(callback, name, isolationLevel) {
792
+ var _this9 = this;
793
+
794
+ isolationLevel || (isolationLevel = this.config.options.isolationLevel);
795
+ var transaction = new Transaction(name || '', isolationLevel);
796
+ if (this.config.options.tdsVersion < '7_2') {
797
+ return this.execSqlBatch(new Request('SET TRANSACTION ISOLATION LEVEL ' + transaction.isolationLevelToTSQL() + ';BEGIN TRAN ' + transaction.name, callback));
798
+ }
799
+ var request = new Request(void 0, function (err) {
800
+ return callback(err, _this9.currentTransactionDescriptor());
801
+ });
802
+ return this.makeRequest(request, TYPE.TRANSACTION_MANAGER, transaction.beginPayload(this.currentTransactionDescriptor()));
803
+ }
804
+ }, {
805
+ key: 'commitTransaction',
806
+ value: function commitTransaction(callback, name) {
807
+ var transaction = new Transaction(name || '');
808
+ if (this.config.options.tdsVersion < '7_2') {
809
+ return this.execSqlBatch(new Request('COMMIT TRAN ' + transaction.name, callback));
810
+ }
811
+ var request = new Request(void 0, callback);
812
+ return this.makeRequest(request, TYPE.TRANSACTION_MANAGER, transaction.commitPayload(this.currentTransactionDescriptor()));
813
+ }
814
+ }, {
815
+ key: 'rollbackTransaction',
816
+ value: function rollbackTransaction(callback, name) {
817
+ var transaction = new Transaction(name || '');
818
+ if (this.config.options.tdsVersion < '7_2') {
819
+ return this.execSqlBatch(new Request('ROLLBACK TRAN ' + transaction.name, callback));
820
+ }
821
+ var request = new Request(void 0, callback);
822
+ return this.makeRequest(request, TYPE.TRANSACTION_MANAGER, transaction.rollbackPayload(this.currentTransactionDescriptor()));
823
+ }
824
+ }, {
825
+ key: 'saveTransaction',
826
+ value: function saveTransaction(callback, name) {
827
+ var transaction = new Transaction(name);
828
+ if (this.config.options.tdsVersion < '7_2') {
829
+ return this.execSqlBatch(new Request('SAVE TRAN ' + transaction.name, callback));
830
+ }
831
+ var request = new Request(void 0, callback);
832
+ return this.makeRequest(request, TYPE.TRANSACTION_MANAGER, transaction.savePayload(this.currentTransactionDescriptor()));
833
+ }
834
+ }, {
835
+ key: 'transaction',
836
+ value: function transaction(cb, isolationLevel) {
837
+ var _this10 = this;
838
+
839
+ if (typeof cb !== 'function') {
840
+ throw new TypeError('`cb` must be a function');
841
+ }
842
+ var useSavepoint = this.inTransaction;
843
+ var name = '_tedious_' + crypto.randomBytes(10).toString('hex');
844
+ var self = this;
845
+ var txDone = function txDone(err, done) {
846
+ var args = new Array(arguments.length - 2);
847
+ for (var i = 0; i < args.length;) {
848
+ args[i++] = arguments[i + 1];
1090
849
  }
850
+
1091
851
  if (err) {
1092
- if (_this.inTransaction) {
1093
- return _this.rollbackTransaction(function (txErr) {
852
+ if (self.inTransaction && self.state === self.STATE.LOGGED_IN) {
853
+ return self.rollbackTransaction(function (txErr) {
1094
854
  args.unshift(txErr || err);
1095
855
  return done.apply(null, args);
1096
856
  }, name);
@@ -1107,103 +867,369 @@ Connection = (function (superClass) {
1107
867
  return done.apply(null, args);
1108
868
  });
1109
869
  } else {
1110
- return _this.commitTransaction(function (txErr) {
870
+ return self.commitTransaction(function (txErr) {
1111
871
  args.unshift(txErr);
1112
872
  return done.apply(null, args);
1113
873
  }, name);
1114
874
  }
1115
875
  }
1116
876
  };
1117
- })(this);
1118
- if (useSavepoint) {
1119
- return this.saveTransaction((function (_this) {
1120
- return function (err) {
877
+ if (useSavepoint) {
878
+ return this.saveTransaction(function (err) {
1121
879
  if (err) {
1122
880
  return cb(err);
1123
881
  }
1124
882
  if (isolationLevel) {
1125
- return _this.execSqlBatch(new Request("SET transaction isolation level " + _this.getIsolationLevelText(isolationLevel), function (err) {
883
+ return _this10.execSqlBatch(new Request('SET transaction isolation level ' + _this10.getIsolationLevelText(isolationLevel), function (err) {
1126
884
  return cb(err, txDone);
1127
885
  }));
1128
886
  } else {
1129
887
  return cb(null, txDone);
1130
888
  }
1131
- };
1132
- })(this), name);
1133
- } else {
1134
- return this.beginTransaction(function (err) {
1135
- if (err) {
1136
- return cb(err);
1137
- }
1138
- return cb(null, txDone);
1139
- }, name, isolationLevel);
889
+ }, name);
890
+ } else {
891
+ return this.beginTransaction(function (err) {
892
+ if (err) {
893
+ return cb(err);
894
+ }
895
+ return cb(null, txDone);
896
+ }, name, isolationLevel);
897
+ }
1140
898
  }
1141
- };
1142
-
1143
- Connection.prototype.makeRequest = function (request, packetType, payload) {
1144
- var message;
1145
- if (this.state !== this.STATE.LOGGED_IN) {
1146
- message = "Requests can only be made in the " + this.STATE.LOGGED_IN.name + " state, not the " + this.state.name + " state";
1147
- this.debug.log(message);
1148
- return request.callback(RequestError(message, 'EINVALIDSTATE'));
1149
- } else {
1150
- this.request = request;
1151
- this.request.rowCount = 0;
1152
- this.request.rows = [];
1153
- this.request.rst = [];
1154
- this.createRequestTimer();
1155
- this.messageIo.sendMessage(packetType, payload.data, this.resetConnectionOnNextRequest);
1156
- this.resetConnectionOnNextRequest = false;
1157
- this.debug.payload(function () {
1158
- return payload.toString(' ');
899
+ }, {
900
+ key: 'makeRequest',
901
+ value: function makeRequest(request, packetType, payload) {
902
+ if (this.state !== this.STATE.LOGGED_IN) {
903
+ var message = 'Requests can only be made in the ' + this.STATE.LOGGED_IN.name + ' state, not the ' + this.state.name + ' state';
904
+ this.debug.log(message);
905
+ return request.callback(RequestError(message, 'EINVALIDSTATE'));
906
+ } else {
907
+ this.request = request;
908
+ this.request.rowCount = 0;
909
+ this.request.rows = [];
910
+ this.request.rst = [];
911
+ this.createRequestTimer();
912
+ this.messageIo.sendMessage(packetType, payload.data, this.resetConnectionOnNextRequest);
913
+ this.resetConnectionOnNextRequest = false;
914
+ this.debug.payload(function () {
915
+ return payload.toString(' ');
916
+ });
917
+ return this.transitionTo(this.STATE.SENT_CLIENT_REQUEST);
918
+ }
919
+ }
920
+ }, {
921
+ key: 'cancel',
922
+ value: function cancel() {
923
+ if (this.state !== this.STATE.SENT_CLIENT_REQUEST) {
924
+ var message = 'Requests can only be canceled in the ' + this.STATE.SENT_CLIENT_REQUEST.name + ' state, not the ' + this.state.name + ' state';
925
+ this.debug.log(message);
926
+ return false;
927
+ } else {
928
+ this.request.canceled = true;
929
+ this.messageIo.sendMessage(TYPE.ATTENTION);
930
+ this.transitionTo(this.STATE.SENT_ATTENTION);
931
+ return true;
932
+ }
933
+ }
934
+ }, {
935
+ key: 'reset',
936
+ value: function reset(callback) {
937
+ var request = new Request(this.getInitialSql(), function (err) {
938
+ return callback(err);
1159
939
  });
1160
- return this.transitionTo(this.STATE.SENT_CLIENT_REQUEST);
940
+ this.resetConnectionOnNextRequest = true;
941
+ return this.execSqlBatch(request);
1161
942
  }
1162
- };
1163
-
1164
- Connection.prototype.cancel = function () {
1165
- var message;
1166
- if (this.state !== this.STATE.SENT_CLIENT_REQUEST) {
1167
- message = "Requests can only be canceled in the " + this.STATE.SENT_CLIENT_REQUEST.name + " state, not the " + this.state.name + " state";
1168
- this.debug.log(message);
1169
- return false;
1170
- } else {
1171
- this.request.canceled = true;
1172
- this.messageIo.sendMessage(TYPE.ATTENTION);
1173
- this.transitionTo(this.STATE.SENT_ATTENTION);
1174
- return true;
1175
- }
1176
- };
1177
-
1178
- Connection.prototype.reset = function (callback) {
1179
- var request;
1180
- request = new Request(this.getInitialSql(), function (err, rowCount, rows) {
1181
- return callback(err);
1182
- });
1183
- this.resetConnectionOnNextRequest = true;
1184
- return this.execSqlBatch(request);
1185
- };
1186
-
1187
- Connection.prototype.currentTransactionDescriptor = function () {
1188
- return this.transactionDescriptors[this.transactionDescriptors.length - 1];
1189
- };
1190
-
1191
- Connection.prototype.getIsolationLevelText = function (isolationLevel) {
1192
- switch (isolationLevel) {
1193
- case ISOLATION_LEVEL.READ_UNCOMMITTED:
1194
- return 'read uncommitted';
1195
- case ISOLATION_LEVEL.REPEATABLE_READ:
1196
- return 'repeatable read';
1197
- case ISOLATION_LEVEL.SERIALIZABLE:
1198
- return 'serializable';
1199
- case ISOLATION_LEVEL.SNAPSHOT:
1200
- return 'snapshot';
1201
- default:
1202
- return 'read committed';
1203
- }
1204
- };
943
+ }, {
944
+ key: 'currentTransactionDescriptor',
945
+ value: function currentTransactionDescriptor() {
946
+ return this.transactionDescriptors[this.transactionDescriptors.length - 1];
947
+ }
948
+ }, {
949
+ key: 'getIsolationLevelText',
950
+ value: function getIsolationLevelText(isolationLevel) {
951
+ switch (isolationLevel) {
952
+ case ISOLATION_LEVEL.READ_UNCOMMITTED:
953
+ return 'read uncommitted';
954
+ case ISOLATION_LEVEL.REPEATABLE_READ:
955
+ return 'repeatable read';
956
+ case ISOLATION_LEVEL.SERIALIZABLE:
957
+ return 'serializable';
958
+ case ISOLATION_LEVEL.SNAPSHOT:
959
+ return 'snapshot';
960
+ default:
961
+ return 'read committed';
962
+ }
963
+ }
964
+ }]);
1205
965
 
1206
966
  return Connection;
1207
967
  })(EventEmitter);
1208
968
 
1209
- module.exports = Connection;
969
+ module.exports = Connection;
970
+
971
+ Connection.prototype.STATE = {
972
+ CONNECTING: {
973
+ name: 'Connecting',
974
+ enter: function enter() {
975
+ return this.initialiseConnection();
976
+ },
977
+ events: {
978
+ socketError: function socketError() {
979
+ return this.transitionTo(this.STATE.FINAL);
980
+ },
981
+ connectTimeout: function connectTimeout() {
982
+ return this.transitionTo(this.STATE.FINAL);
983
+ },
984
+ socketConnect: function socketConnect() {
985
+ this.sendPreLogin();
986
+ return this.transitionTo(this.STATE.SENT_PRELOGIN);
987
+ }
988
+ }
989
+ },
990
+ SENT_PRELOGIN: {
991
+ name: 'SentPrelogin',
992
+ enter: function enter() {
993
+ return this.emptyMessageBuffer();
994
+ },
995
+ events: {
996
+ socketError: function socketError() {
997
+ return this.transitionTo(this.STATE.FINAL);
998
+ },
999
+ connectTimeout: function connectTimeout() {
1000
+ return this.transitionTo(this.STATE.FINAL);
1001
+ },
1002
+ data: function data(_data) {
1003
+ return this.addToMessageBuffer(_data);
1004
+ },
1005
+ message: function message() {
1006
+ return this.processPreLoginResponse();
1007
+ },
1008
+ noTls: function noTls() {
1009
+ this.sendLogin7Packet();
1010
+ if (this.config.domain) {
1011
+ return this.transitionTo(this.STATE.SENT_LOGIN7_WITH_NTLM);
1012
+ } else {
1013
+ return this.transitionTo(this.STATE.SENT_LOGIN7_WITH_STANDARD_LOGIN);
1014
+ }
1015
+ },
1016
+ tls: function tls() {
1017
+ this.messageIo.startTls(this.config.options.cryptoCredentialsDetails);
1018
+ return this.transitionTo(this.STATE.SENT_TLSSSLNEGOTIATION);
1019
+ }
1020
+ }
1021
+ },
1022
+ REROUTING: {
1023
+ name: 'ReRouting',
1024
+ enter: function enter() {
1025
+ return this.cleanupConnection(true);
1026
+ },
1027
+ events: {
1028
+ message: function message() {},
1029
+ socketError: function socketError() {
1030
+ return this.transitionTo(this.STATE.FINAL);
1031
+ },
1032
+ connectTimeout: function connectTimeout() {
1033
+ return this.transitionTo(this.STATE.FINAL);
1034
+ },
1035
+ reconnect: function reconnect() {
1036
+ return this.transitionTo(this.STATE.CONNECTING);
1037
+ }
1038
+ }
1039
+ },
1040
+ SENT_TLSSSLNEGOTIATION: {
1041
+ name: 'SentTLSSSLNegotiation',
1042
+ events: {
1043
+ socketError: function socketError() {
1044
+ return this.transitionTo(this.STATE.FINAL);
1045
+ },
1046
+ connectTimeout: function connectTimeout() {
1047
+ return this.transitionTo(this.STATE.FINAL);
1048
+ },
1049
+ data: function data(_data2) {
1050
+ return this.messageIo.tlsHandshakeData(_data2);
1051
+ },
1052
+ message: function message() {
1053
+ if (this.messageIo.tlsNegotiationComplete) {
1054
+ this.sendLogin7Packet();
1055
+ return this.transitionTo(this.STATE.SENT_LOGIN7_WITH_STANDARD_LOGIN);
1056
+ }
1057
+ }
1058
+ }
1059
+ },
1060
+ SENT_LOGIN7_WITH_STANDARD_LOGIN: {
1061
+ name: 'SentLogin7WithStandardLogin',
1062
+ events: {
1063
+ socketError: function socketError() {
1064
+ return this.transitionTo(this.STATE.FINAL);
1065
+ },
1066
+ connectTimeout: function connectTimeout() {
1067
+ return this.transitionTo(this.STATE.FINAL);
1068
+ },
1069
+ data: function data(_data3) {
1070
+ return this.sendDataToTokenStreamParser(_data3);
1071
+ },
1072
+ loggedIn: function loggedIn() {
1073
+ return this.transitionTo(this.STATE.LOGGED_IN_SENDING_INITIAL_SQL);
1074
+ },
1075
+ routingChange: function routingChange() {
1076
+ return this.transitionTo(this.STATE.REROUTING);
1077
+ },
1078
+ loginFailed: function loginFailed() {
1079
+ return this.transitionTo(this.STATE.FINAL);
1080
+ },
1081
+ message: function message() {
1082
+ return this.processLogin7Response();
1083
+ }
1084
+ }
1085
+ },
1086
+ SENT_LOGIN7_WITH_NTLM: {
1087
+ name: 'SentLogin7WithNTLMLogin',
1088
+ events: {
1089
+ socketError: function socketError() {
1090
+ return this.transitionTo(this.STATE.FINAL);
1091
+ },
1092
+ connectTimeout: function connectTimeout() {
1093
+ return this.transitionTo(this.STATE.FINAL);
1094
+ },
1095
+ data: function data(_data4) {
1096
+ return this.sendDataToTokenStreamParser(_data4);
1097
+ },
1098
+ receivedChallenge: function receivedChallenge() {
1099
+ this.sendNTLMResponsePacket();
1100
+ return this.transitionTo(this.STATE.SENT_NTLM_RESPONSE);
1101
+ },
1102
+ loginFailed: function loginFailed() {
1103
+ return this.transitionTo(this.STATE.FINAL);
1104
+ },
1105
+ message: function message() {
1106
+ return this.processLogin7NTLMResponse();
1107
+ }
1108
+ }
1109
+ },
1110
+ SENT_NTLM_RESPONSE: {
1111
+ name: 'SentNTLMResponse',
1112
+ events: {
1113
+ socketError: function socketError() {
1114
+ return this.transitionTo(this.STATE.FINAL);
1115
+ },
1116
+ connectTimeout: function connectTimeout() {
1117
+ return this.transitionTo(this.STATE.FINAL);
1118
+ },
1119
+ data: function data(_data5) {
1120
+ return this.sendDataToTokenStreamParser(_data5);
1121
+ },
1122
+ loggedIn: function loggedIn() {
1123
+ return this.transitionTo(this.STATE.LOGGED_IN_SENDING_INITIAL_SQL);
1124
+ },
1125
+ loginFailed: function loginFailed() {
1126
+ return this.transitionTo(this.STATE.FINAL);
1127
+ },
1128
+ routingChange: function routingChange() {
1129
+ return this.transitionTo(this.STATE.REROUTING);
1130
+ },
1131
+ message: function message() {
1132
+ return this.processLogin7NTLMAck();
1133
+ }
1134
+ }
1135
+ },
1136
+ LOGGED_IN_SENDING_INITIAL_SQL: {
1137
+ name: 'LoggedInSendingInitialSql',
1138
+ enter: function enter() {
1139
+ return this.sendInitialSql();
1140
+ },
1141
+ events: {
1142
+ connectTimeout: function connectTimeout() {
1143
+ return this.transitionTo(this.STATE.FINAL);
1144
+ },
1145
+ data: function data(_data6) {
1146
+ return this.sendDataToTokenStreamParser(_data6);
1147
+ },
1148
+ message: function message() {
1149
+ this.transitionTo(this.STATE.LOGGED_IN);
1150
+ return this.processedInitialSql();
1151
+ }
1152
+ }
1153
+ },
1154
+ LOGGED_IN: {
1155
+ name: 'LoggedIn',
1156
+ events: {
1157
+ socketError: function socketError() {
1158
+ return this.transitionTo(this.STATE.FINAL);
1159
+ }
1160
+ }
1161
+ },
1162
+ SENT_CLIENT_REQUEST: {
1163
+ name: 'SentClientRequest',
1164
+ events: {
1165
+ socketError: function socketError(err) {
1166
+ var sqlRequest = this.request;
1167
+ this.request = void 0;
1168
+ sqlRequest.callback(err);
1169
+ return this.transitionTo(this.STATE.FINAL);
1170
+ },
1171
+ data: function data(_data7) {
1172
+ return this.sendDataToTokenStreamParser(_data7);
1173
+ },
1174
+ message: function message() {
1175
+ this.clearRequestTimer();
1176
+ this.transitionTo(this.STATE.LOGGED_IN);
1177
+ var sqlRequest = this.request;
1178
+ this.request = void 0;
1179
+ return sqlRequest.callback(sqlRequest.error, sqlRequest.rowCount, sqlRequest.rows);
1180
+ }
1181
+ }
1182
+ },
1183
+ SENT_ATTENTION: {
1184
+ name: 'SentAttention',
1185
+ enter: function enter() {
1186
+ return this.attentionReceived = false;
1187
+ },
1188
+ events: {
1189
+ socketError: function socketError() {
1190
+ return this.transitionTo(this.STATE.FINAL);
1191
+ },
1192
+ data: function data(_data8) {
1193
+ return this.sendDataToTokenStreamParser(_data8);
1194
+ },
1195
+ attention: function attention() {
1196
+ return this.attentionReceived = true;
1197
+ },
1198
+ message: function message() {
1199
+ // 3.2.5.7 Sent Attention State
1200
+ // Discard any data contained in the response, until we receive the attention response
1201
+ if (this.attentionReceived) {
1202
+ var sqlRequest = this.request;
1203
+ this.request = void 0;
1204
+ this.transitionTo(this.STATE.LOGGED_IN);
1205
+ if (sqlRequest.canceled) {
1206
+ return sqlRequest.callback(RequestError('Canceled.', 'ECANCEL'));
1207
+ } else {
1208
+ var message = 'Timeout: Request failed to complete in ' + this.config.options.requestTimeout + 'ms';
1209
+ return sqlRequest.callback(RequestError(message, 'ETIMEOUT'));
1210
+ }
1211
+ }
1212
+ }
1213
+ }
1214
+ },
1215
+ FINAL: {
1216
+ name: 'Final',
1217
+ enter: function enter() {
1218
+ return this.cleanupConnection();
1219
+ },
1220
+ events: {
1221
+ loginFailed: function loginFailed() {
1222
+ // Do nothing. The connection was probably closed by the client code.
1223
+ },
1224
+ connectTimeout: function connectTimeout() {
1225
+ // Do nothing, as the timer should be cleaned up.
1226
+ },
1227
+ message: function message() {
1228
+ // Do nothing
1229
+ },
1230
+ socketError: function socketError() {
1231
+ // Do nothing
1232
+ }
1233
+ }
1234
+ }
1235
+ };