forked from tediousjs/tedious
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconnection.ts
3841 lines (3358 loc) · 124 KB
/
connection.ts
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
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import crypto from 'crypto';
import os from 'os';
import * as tls from 'tls';
import * as net from 'net';
import dns from 'dns';
import constants from 'constants';
import { type SecureContextOptions } from 'tls';
import { Readable } from 'stream';
import {
ClientSecretCredential,
DefaultAzureCredential,
ManagedIdentityCredential,
UsernamePasswordCredential
} from '@azure/identity';
import { type AccessToken, type TokenCredential, isTokenCredential } from '@azure/core-auth';
import BulkLoad, { type Options as BulkLoadOptions, type Callback as BulkLoadCallback } from './bulk-load';
import Debug from './debug';
import { EventEmitter, once } from 'events';
import { instanceLookup } from './instance-lookup';
import { TransientErrorLookup } from './transient-error-lookup';
import { TYPE } from './packet';
import PreloginPayload from './prelogin-payload';
import Login7Payload from './login7-payload';
import NTLMResponsePayload from './ntlm-payload';
import Request from './request';
import RpcRequestPayload from './rpcrequest-payload';
import SqlBatchPayload from './sqlbatch-payload';
import MessageIO from './message-io';
import { Parser as TokenStreamParser } from './token/token-stream-parser';
import { Transaction, ISOLATION_LEVEL, assertValidIsolationLevel } from './transaction';
import { ConnectionError, RequestError } from './errors';
import { connectInParallel, connectInSequence } from './connector';
import { name as libraryName } from './library';
import { versions } from './tds-versions';
import Message from './message';
import { type Metadata } from './metadata-parser';
import { createNTLMRequest } from './ntlm';
import { ColumnEncryptionAzureKeyVaultProvider } from './always-encrypted/keystore-provider-azure-key-vault';
import { type Parameter, TYPES } from './data-type';
import { BulkLoadPayload } from './bulk-load-payload';
import { Collation } from './collation';
import Procedures from './special-stored-procedure';
import { version } from '../package.json';
import { URL } from 'url';
import { AttentionTokenHandler, InitialSqlTokenHandler, Login7TokenHandler, RequestTokenHandler, TokenHandler } from './token/handler';
type BeginTransactionCallback =
/**
* The callback is called when the request to start the transaction has completed,
* either successfully or with an error.
* If an error occurred then `err` will describe the error.
*
* As only one request at a time may be executed on a connection, another request should not
* be initiated until this callback is called.
*
* @param err If an error occurred, an [[Error]] object with details of the error.
* @param transactionDescriptor A Buffer that describe the transaction
*/
(err: Error | null | undefined, transactionDescriptor?: Buffer) => void
type SaveTransactionCallback =
/**
* The callback is called when the request to set a savepoint within the
* transaction has completed, either successfully or with an error.
* If an error occurred then `err` will describe the error.
*
* As only one request at a time may be executed on a connection, another request should not
* be initiated until this callback is called.
*
* @param err If an error occurred, an [[Error]] object with details of the error.
*/
(err: Error | null | undefined) => void;
type CommitTransactionCallback =
/**
* The callback is called when the request to commit the transaction has completed,
* either successfully or with an error.
* If an error occurred then `err` will describe the error.
*
* As only one request at a time may be executed on a connection, another request should not
* be initiated until this callback is called.
*
* @param err If an error occurred, an [[Error]] object with details of the error.
*/
(err: Error | null | undefined) => void;
type RollbackTransactionCallback =
/**
* The callback is called when the request to rollback the transaction has
* completed, either successfully or with an error.
* If an error occurred then err will describe the error.
*
* As only one request at a time may be executed on a connection, another request should not
* be initiated until this callback is called.
*
* @param err If an error occurred, an [[Error]] object with details of the error.
*/
(err: Error | null | undefined) => void;
type ResetCallback =
/**
* The callback is called when the connection reset has completed,
* either successfully or with an error.
*
* If an error occurred then `err` will describe the error.
*
* As only one request at a time may be executed on a connection, another
* request should not be initiated until this callback is called
*
* @param err If an error occurred, an [[Error]] object with details of the error.
*/
(err: Error | null | undefined) => void;
// eslint-disable-next-line @typescript-eslint/no-unused-vars
type TransactionCallback<T extends (err: Error | null | undefined, ...args: any[]) => void> =
/**
* The callback is called when the request to start a transaction (or create a savepoint, in
* the case of a nested transaction) has completed, either successfully or with an error.
* If an error occurred, then `err` will describe the error.
* If no error occurred, the callback should perform its work and eventually call
* `done` with an error or null (to trigger a transaction rollback or a
* transaction commit) and an additional completion callback that will be called when the request
* to rollback or commit the current transaction has completed, either successfully or with an error.
* Additional arguments given to `done` will be passed through to this callback.
*
* As only one request at a time may be executed on a connection, another request should not
* be initiated until the completion callback is called.
*
* @param err If an error occurred, an [[Error]] object with details of the error.
* @param txDone If no error occurred, a function to be called to commit or rollback the transaction.
*/
(err: Error | null | undefined, txDone?: TransactionDone<T>) => void;
type TransactionDoneCallback = (err: Error | null | undefined, ...args: any[]) => void;
type CallbackParameters<T extends (err: Error | null | undefined, ...args: any[]) => any> = T extends (err: Error | null | undefined, ...args: infer P) => any ? P : never;
type TransactionDone<T extends (err: Error | null | undefined, ...args: any[]) => void> =
/**
* If no error occurred, a function to be called to commit or rollback the transaction.
*
* @param err If an err occurred, a string with details of the error.
*/
(err: Error | null | undefined, done: T, ...args: CallbackParameters<T>) => void;
/**
* @private
*/
const KEEP_ALIVE_INITIAL_DELAY = 30 * 1000;
/**
* @private
*/
const DEFAULT_CONNECT_TIMEOUT = 15 * 1000;
/**
* @private
*/
const DEFAULT_CLIENT_REQUEST_TIMEOUT = 15 * 1000;
/**
* @private
*/
const DEFAULT_CANCEL_TIMEOUT = 5 * 1000;
/**
* @private
*/
const DEFAULT_CONNECT_RETRY_INTERVAL = 500;
/**
* @private
*/
const DEFAULT_PACKET_SIZE = 4 * 1024;
/**
* @private
*/
const DEFAULT_TEXTSIZE = 2147483647;
/**
* @private
*/
const DEFAULT_DATEFIRST = 7;
/**
* @private
*/
const DEFAULT_PORT = 1433;
/**
* @private
*/
const DEFAULT_TDS_VERSION = '7_4';
/**
* @private
*/
const DEFAULT_LANGUAGE = 'us_english';
/**
* @private
*/
const DEFAULT_DATEFORMAT = 'mdy';
interface AzureActiveDirectoryMsiAppServiceAuthentication {
type: 'azure-active-directory-msi-app-service';
options: {
/**
* If you user want to connect to an Azure app service using a specific client account
* they need to provide `clientId` associate to their created identity.
*
* This is optional for retrieve token from azure web app service
*/
clientId?: string;
};
}
interface AzureActiveDirectoryMsiVmAuthentication {
type: 'azure-active-directory-msi-vm';
options: {
/**
* If you want to connect using a specific client account
* they need to provide `clientId` associated to their created identity.
*
* This is optional for retrieve a token
*/
clientId?: string;
};
}
interface AzureActiveDirectoryDefaultAuthentication {
type: 'azure-active-directory-default';
options: {
/**
* If you want to connect using a specific client account
* they need to provide `clientId` associated to their created identity.
*
* This is optional for retrieving a token
*/
clientId?: string;
};
}
interface AzureActiveDirectoryAccessTokenAuthentication {
type: 'azure-active-directory-access-token';
options: {
/**
* A user need to provide `token` which they retrieved else where
* to forming the connection.
*/
token: string;
};
}
interface AzureActiveDirectoryPasswordAuthentication {
type: 'azure-active-directory-password';
options: {
/**
* A user need to provide `userName` associate to their account.
*/
userName: string;
/**
* A user need to provide `password` associate to their account.
*/
password: string;
/**
* A client id to use.
*/
clientId: string;
/**
* Optional parameter for specific Azure tenant ID
*/
tenantId: string;
};
}
interface AzureActiveDirectoryServicePrincipalSecret {
type: 'azure-active-directory-service-principal-secret';
options: {
/**
* Application (`client`) ID from your registered Azure application
*/
clientId: string;
/**
* The created `client secret` for this registered Azure application
*/
clientSecret: string;
/**
* Directory (`tenant`) ID from your registered Azure application
*/
tenantId: string;
};
}
/** Structure that defines the options that are necessary to authenticate the Tedious.JS instance with an `@azure/identity` token credential. */
interface TokenCredentialAuthentication {
/** Unique designator for the type of authentication to be used. */
type: 'token-credential';
/** Set of configurations that are required or allowed with this authentication type. */
options: {
/** Credential object used to authenticate to the resource. */
credential: TokenCredential;
};
}
interface NtlmAuthentication {
type: 'ntlm';
options: {
/**
* User name from your windows account.
*/
userName: string;
/**
* Password from your windows account.
*/
password: string;
/**
* Once you set domain for ntlm authentication type, driver will connect to SQL Server using domain login.
*
* This is necessary for forming a connection using ntlm type
*/
domain: string;
};
}
interface DefaultAuthentication {
type: 'default';
options: {
/**
* User name to use for sql server login.
*/
userName?: string | undefined;
/**
* Password to use for sql server login.
*/
password?: string | undefined;
};
}
interface ErrorWithCode extends Error {
code?: string;
}
export type ConnectionAuthentication = DefaultAuthentication | NtlmAuthentication | TokenCredentialAuthentication | AzureActiveDirectoryPasswordAuthentication | AzureActiveDirectoryMsiAppServiceAuthentication | AzureActiveDirectoryMsiVmAuthentication | AzureActiveDirectoryAccessTokenAuthentication | AzureActiveDirectoryServicePrincipalSecret | AzureActiveDirectoryDefaultAuthentication;
interface InternalConnectionConfig {
server: string;
authentication: ConnectionAuthentication;
options: InternalConnectionOptions;
}
export interface InternalConnectionOptions {
abortTransactionOnError: boolean;
appName: undefined | string;
camelCaseColumns: boolean;
cancelTimeout: number;
columnEncryptionKeyCacheTTL: number;
columnEncryptionSetting: boolean;
columnNameReplacer: undefined | ((colName: string, index: number, metadata: Metadata) => string);
connectionRetryInterval: number;
connector: undefined | (() => Promise<net.Socket>);
connectTimeout: number;
connectionIsolationLevel: typeof ISOLATION_LEVEL[keyof typeof ISOLATION_LEVEL];
cryptoCredentialsDetails: SecureContextOptions;
database: undefined | string;
datefirst: number;
dateFormat: string;
debug: {
data: boolean;
packet: boolean;
payload: boolean;
token: boolean;
};
enableAnsiNull: null | boolean;
enableAnsiNullDefault: null | boolean;
enableAnsiPadding: null | boolean;
enableAnsiWarnings: null | boolean;
enableArithAbort: null | boolean;
enableConcatNullYieldsNull: null | boolean;
enableCursorCloseOnCommit: null | boolean;
enableImplicitTransactions: null | boolean;
enableNumericRoundabort: null | boolean;
enableQuotedIdentifier: null | boolean;
encrypt: string | boolean;
encryptionKeyStoreProviders: KeyStoreProviderMap | undefined;
fallbackToDefaultDb: boolean;
instanceName: undefined | string;
isolationLevel: typeof ISOLATION_LEVEL[keyof typeof ISOLATION_LEVEL];
language: string;
localAddress: undefined | string;
maxRetriesOnTransientErrors: number;
multiSubnetFailover: boolean;
packetSize: number;
port: undefined | number;
readOnlyIntent: boolean;
requestTimeout: number;
rowCollectionOnDone: boolean;
rowCollectionOnRequestCompletion: boolean;
serverName: undefined | string;
serverSupportsColumnEncryption: boolean;
tdsVersion: string;
textsize: number;
trustedServerNameAE: string | undefined;
trustServerCertificate: boolean;
useColumnNames: boolean;
useUTC: boolean;
workstationId: undefined | string;
lowerCaseGuids: boolean;
}
interface KeyStoreProviderMap {
[key: string]: ColumnEncryptionAzureKeyVaultProvider;
}
/**
* @private
*/
interface State {
name: string;
enter?(this: Connection): void;
exit?(this: Connection, newState: State): void;
events: {
socketError?(this: Connection, err: Error): void;
connectTimeout?(this: Connection): void;
message?(this: Connection, message: Message): void;
retry?(this: Connection): void;
reconnect?(this: Connection): void;
};
}
type Authentication = DefaultAuthentication |
NtlmAuthentication |
TokenCredentialAuthentication |
AzureActiveDirectoryPasswordAuthentication |
AzureActiveDirectoryMsiAppServiceAuthentication |
AzureActiveDirectoryMsiVmAuthentication |
AzureActiveDirectoryAccessTokenAuthentication |
AzureActiveDirectoryServicePrincipalSecret |
AzureActiveDirectoryDefaultAuthentication;
type AuthenticationType = Authentication['type'];
export interface ConnectionConfiguration {
/**
* Hostname to connect to.
*/
server: string;
/**
* Configuration options for forming the connection.
*/
options?: ConnectionOptions;
/**
* Authentication related options for connection.
*/
authentication?: AuthenticationOptions;
}
interface DebugOptions {
/**
* A boolean, controlling whether [[debug]] events will be emitted with text describing packet data details
*
* (default: `false`)
*/
data: boolean;
/**
* A boolean, controlling whether [[debug]] events will be emitted with text describing packet details
*
* (default: `false`)
*/
packet: boolean;
/**
* A boolean, controlling whether [[debug]] events will be emitted with text describing packet payload details
*
* (default: `false`)
*/
payload: boolean;
/**
* A boolean, controlling whether [[debug]] events will be emitted with text describing token stream tokens
*
* (default: `false`)
*/
token: boolean;
}
interface AuthenticationOptions {
/**
* Type of the authentication method, valid types are `default`, `ntlm`,
* `azure-active-directory-password`, `azure-active-directory-access-token`,
* `azure-active-directory-msi-vm`, `azure-active-directory-msi-app-service`,
* `azure-active-directory-default`
* or `azure-active-directory-service-principal-secret`
*/
type?: AuthenticationType;
/**
* Different options for authentication types:
*
* * `default`: [[DefaultAuthentication.options]]
* * `ntlm` :[[NtlmAuthentication]]
* * `token-credential`: [[CredentialChainAuthentication.options]]
* * `azure-active-directory-password` : [[AzureActiveDirectoryPasswordAuthentication.options]]
* * `azure-active-directory-access-token` : [[AzureActiveDirectoryAccessTokenAuthentication.options]]
* * `azure-active-directory-msi-vm` : [[AzureActiveDirectoryMsiVmAuthentication.options]]
* * `azure-active-directory-msi-app-service` : [[AzureActiveDirectoryMsiAppServiceAuthentication.options]]
* * `azure-active-directory-service-principal-secret` : [[AzureActiveDirectoryServicePrincipalSecret.options]]
* * `azure-active-directory-default` : [[AzureActiveDirectoryDefaultAuthentication.options]]
*/
options?: any;
}
export interface ConnectionOptions {
/**
* A boolean determining whether to rollback a transaction automatically if any error is encountered
* during the given transaction's execution. This sets the value for `SET XACT_ABORT` during the
* initial SQL phase of a connection [documentation](https://docs.microsoft.com/en-us/sql/t-sql/statements/set-xact-abort-transact-sql).
*/
abortTransactionOnError?: boolean | undefined;
/**
* Application name used for identifying a specific application in profiling, logging or tracing tools of SQLServer.
*
* (default: `Tedious`)
*/
appName?: string | undefined;
/**
* A boolean, controlling whether the column names returned will have the first letter converted to lower case
* (`true`) or not. This value is ignored if you provide a [[columnNameReplacer]].
*
* (default: `false`).
*/
camelCaseColumns?: boolean;
/**
* The number of milliseconds before the [[Request.cancel]] (abort) of a request is considered failed
*
* (default: `5000`).
*/
cancelTimeout?: number;
/**
* A function with parameters `(columnName, index, columnMetaData)` and returning a string. If provided,
* this will be called once per column per result-set. The returned value will be used instead of the SQL-provided
* column name on row and meta data objects. This allows you to dynamically convert between naming conventions.
*
* (default: `null`)
*/
columnNameReplacer?: (colName: string, index: number, metadata: Metadata) => string;
/**
* Number of milliseconds before retrying to establish connection, in case of transient failure.
*
* (default:`500`)
*/
connectionRetryInterval?: number;
/**
* Custom connector factory method.
*
* (default: `undefined`)
*/
connector?: () => Promise<net.Socket>;
/**
* The number of milliseconds before the attempt to connect is considered failed
*
* (default: `15000`).
*/
connectTimeout?: number;
/**
* The default isolation level for new connections. All out-of-transaction queries are executed with this setting.
*
* The isolation levels are available from `require('tedious').ISOLATION_LEVEL`.
* * `READ_UNCOMMITTED`
* * `READ_COMMITTED`
* * `REPEATABLE_READ`
* * `SERIALIZABLE`
* * `SNAPSHOT`
*
* (default: `READ_COMMITED`).
*/
connectionIsolationLevel?: number;
/**
* When encryption is used, an object may be supplied that will be used
* for the first argument when calling [`tls.createSecurePair`](http://nodejs.org/docs/latest/api/tls.html#tls_tls_createsecurepair_credentials_isserver_requestcert_rejectunauthorized)
*
* (default: `{}`)
*/
cryptoCredentialsDetails?: SecureContextOptions;
/**
* Database to connect to (default: dependent on server configuration).
*/
database?: string | undefined;
/**
* Sets the first day of the week to a number from 1 through 7.
*/
datefirst?: number;
/**
* A string representing position of month, day and year in temporal datatypes.
*
* (default: `mdy`)
*/
dateFormat?: string;
debug?: DebugOptions;
/**
* A boolean, controls the way null values should be used during comparison operation.
*
* (default: `true`)
*/
enableAnsiNull?: boolean;
/**
* If true, `SET ANSI_NULL_DFLT_ON ON` will be set in the initial sql. This means new columns will be
* nullable by default. See the [T-SQL documentation](https://msdn.microsoft.com/en-us/library/ms187375.aspx)
*
* (default: `true`).
*/
enableAnsiNullDefault?: boolean;
/**
* A boolean, controls if padding should be applied for values shorter than the size of defined column.
*
* (default: `true`)
*/
enableAnsiPadding?: boolean;
/**
* If true, SQL Server will follow ISO standard behavior during various error conditions. For details,
* see [documentation](https://docs.microsoft.com/en-us/sql/t-sql/statements/set-ansi-warnings-transact-sql)
*
* (default: `true`)
*/
enableAnsiWarnings?: boolean;
/**
* Ends a query when an overflow or divide-by-zero error occurs during query execution.
* See [documentation](https://docs.microsoft.com/en-us/sql/t-sql/statements/set-arithabort-transact-sql?view=sql-server-2017)
* for more details.
*
* (default: `true`)
*/
enableArithAbort?: boolean;
/**
* A boolean, determines if concatenation with NULL should result in NULL or empty string value, more details in
* [documentation](https://docs.microsoft.com/en-us/sql/t-sql/statements/set-concat-null-yields-null-transact-sql)
*
* (default: `true`)
*/
enableConcatNullYieldsNull?: boolean;
/**
* A boolean, controls whether cursor should be closed, if the transaction opening it gets committed or rolled
* back.
*
* (default: `null`)
*/
enableCursorCloseOnCommit?: boolean | null;
/**
* A boolean, sets the connection to either implicit or autocommit transaction mode.
*
* (default: `false`)
*/
enableImplicitTransactions?: boolean;
/**
* If false, error is not generated during loss of precession.
*
* (default: `false`)
*/
enableNumericRoundabort?: boolean;
/**
* If true, characters enclosed in single quotes are treated as literals and those enclosed double quotes are treated as identifiers.
*
* (default: `true`)
*/
enableQuotedIdentifier?: boolean;
/**
* A string value that can be only set to 'strict', which indicates the usage TDS 8.0 protocol. Otherwise,
* a boolean determining whether or not the connection will be encrypted.
*
* (default: `true`)
*/
encrypt?: string | boolean;
/**
* By default, if the database requested by [[database]] cannot be accessed,
* the connection will fail with an error. However, if [[fallbackToDefaultDb]] is
* set to `true`, then the user's default database will be used instead
*
* (default: `false`)
*/
fallbackToDefaultDb?: boolean;
/**
* The instance name to connect to.
* The SQL Server Browser service must be running on the database server,
* and UDP port 1434 on the database server must be reachable.
*
* (no default)
*
* Mutually exclusive with [[port]].
*/
instanceName?: string | undefined;
/**
* The default isolation level that transactions will be run with.
*
* The isolation levels are available from `require('tedious').ISOLATION_LEVEL`.
* * `READ_UNCOMMITTED`
* * `READ_COMMITTED`
* * `REPEATABLE_READ`
* * `SERIALIZABLE`
* * `SNAPSHOT`
*
* (default: `READ_COMMITED`).
*/
isolationLevel?: number;
/**
* Specifies the language environment for the session. The session language determines the datetime formats and system messages.
*
* (default: `us_english`).
*/
language?: string;
/**
* A string indicating which network interface (ip address) to use when connecting to SQL Server.
*/
localAddress?: string | undefined;
/**
* A boolean determining whether to parse unique identifier type with lowercase case characters.
*
* (default: `false`).
*/
lowerCaseGuids?: boolean;
/**
* The maximum number of connection retries for transient errors.、
*
* (default: `3`).
*/
maxRetriesOnTransientErrors?: number;
/**
* Sets the MultiSubnetFailover = True parameter, which can help minimize the client recovery latency when failovers occur.
*
* (default: `false`).
*/
multiSubnetFailover?: boolean;
/**
* The size of TDS packets (subject to negotiation with the server).
* Should be a power of 2.
*
* (default: `4096`).
*/
packetSize?: number;
/**
* Port to connect to (default: `1433`).
*
* Mutually exclusive with [[instanceName]]
*/
port?: number | undefined;
/**
* A boolean, determining whether the connection will request read only access from a SQL Server Availability
* Group. For more information, see [here](http://msdn.microsoft.com/en-us/library/hh710054.aspx "Microsoft: Configure Read-Only Routing for an Availability Group (SQL Server)")
*
* (default: `false`).
*/
readOnlyIntent?: boolean;
/**
* The number of milliseconds before a request is considered failed, or `0` for no timeout.
*
* As soon as a response is received, the timeout is cleared. This means that queries that immediately return a response have ability to run longer than this timeout.
*
* (default: `15000`).
*/
requestTimeout?: number;
/**
* A boolean, that when true will expose received rows in Requests done related events:
* * [[Request.Event_doneInProc]]
* * [[Request.Event_doneProc]]
* * [[Request.Event_done]]
*
* (default: `false`)
*
* Caution: If many row are received, enabling this option could result in
* excessive memory usage.
*/
rowCollectionOnDone?: boolean;
/**
* A boolean, that when true will expose received rows in Requests' completion callback.See [[Request.constructor]].
*
* (default: `false`)
*
* Caution: If many row are received, enabling this option could result in
* excessive memory usage.
*/
rowCollectionOnRequestCompletion?: boolean;
/**
* The version of TDS to use. If server doesn't support specified version, negotiated version is used instead.
*
* The versions are available from `require('tedious').TDS_VERSION`.
* * `7_1`
* * `7_2`
* * `7_3_A`
* * `7_3_B`
* * `7_4`
*
* (default: `7_4`)
*/
tdsVersion?: string | undefined;
/**
* Specifies the size of varchar(max), nvarchar(max), varbinary(max), text, ntext, and image data returned by a SELECT statement.
*
* (default: `2147483647`)
*/
textsize?: number;
/**
* If "true", the SQL Server SSL certificate is automatically trusted when the communication layer is encrypted using SSL.
*
* If "false", the SQL Server validates the server SSL certificate. If the server certificate validation fails,
* the driver raises an error and terminates the connection. Make sure the value passed to serverName exactly
* matches the Common Name (CN) or DNS name in the Subject Alternate Name in the server certificate for an SSL connection to succeed.
*
* (default: `true`)
*/
trustServerCertificate?: boolean;
/**
*
*/
serverName?: string;
/**
* A boolean determining whether to return rows as arrays or key-value collections.
*
* (default: `false`).
*/
useColumnNames?: boolean;
/**
* A boolean determining whether to pass time values in UTC or local time.
*
* (default: `true`).
*/
useUTC?: boolean;
/**
* The workstation ID (WSID) of the client, default os.hostname().
* Used for identifying a specific client in profiling, logging or
* tracing client activity in SQLServer.
*
* The value is reported by the TSQL function HOST_NAME().
*/
workstationId?: string | undefined;
}
/**
* @private
*/
const CLEANUP_TYPE = {
NORMAL: 0,
REDIRECT: 1,
RETRY: 2
};
interface RoutingData {
server: string;
port: number;
}
/**
* A [[Connection]] instance represents a single connection to a database server.
*
* ```js
* var Connection = require('tedious').Connection;
* var config = {
* "authentication": {
* ...,
* "options": {...}
* },
* "options": {...}
* };
* var connection = new Connection(config);
* ```
*
* Only one request at a time may be executed on a connection. Once a [[Request]]
* has been initiated (with [[Connection.callProcedure]], [[Connection.execSql]],
* or [[Connection.execSqlBatch]]), another should not be initiated until the
* [[Request]]'s completion callback is called.
*/
class Connection extends EventEmitter {
/**
* @private
*/
declare fedAuthRequired: boolean;
/**
* @private
*/
declare config: InternalConnectionConfig;
/**
* @private
*/
declare secureContextOptions: SecureContextOptions;
/**
* @private
*/
declare inTransaction: boolean;
/**
* @private
*/
declare transactionDescriptors: Buffer[];
/**
* @private
*/
declare transactionDepth: number;
/**
* @private
*/
declare isSqlBatch: boolean;
/**
* @private
*/
declare curTransientRetryCount: number;
/**
* @private
*/
declare transientErrorLookup: TransientErrorLookup;
/**
* @private
*/
declare closed: boolean;
/**
* @private
*/
declare loginError: undefined | AggregateError | ConnectionError;
/**
* @private
*/
declare debug: Debug;
/**
* @private
*/
declare ntlmpacket: undefined | any;
/**
* @private
*/
declare ntlmpacketBuffer: undefined | Buffer;
/**
* @private
*/
declare STATE: {
INITIALIZED: State;
CONNECTING: State;
SENT_PRELOGIN: State;
REROUTING: State;
TRANSIENT_FAILURE_RETRY: State;
SENT_TLSSSLNEGOTIATION: State;
SENT_LOGIN7_WITH_STANDARD_LOGIN: State;
SENT_LOGIN7_WITH_NTLM: State;
SENT_LOGIN7_WITH_FEDAUTH: State;
LOGGED_IN_SENDING_INITIAL_SQL: State;
LOGGED_IN: State;
SENT_CLIENT_REQUEST: State;
SENT_ATTENTION: State;
FINAL: State;
};
/**
* @private
*/
declare routingData: undefined | RoutingData;
/**
* @private
*/
declare messageIo: MessageIO;
/**
* @private
*/
declare state: State;