UNPKG

44.2 kBTypeScriptView Raw
1/// <reference types="node" />
2/// <reference types="node" />
3/// <reference types="node" />
4/// <reference types="node" />
5/// <reference types="node" />
6/// <reference types="node" />
7import * as tls from 'tls';
8import * as net from 'net';
9import { type SecureContextOptions } from 'tls';
10import { type TokenCredential } from '@azure/core-auth';
11import BulkLoad, { type Options as BulkLoadOptions, type Callback as BulkLoadCallback } from './bulk-load';
12import Debug from './debug';
13import { EventEmitter } from 'events';
14import { TransientErrorLookup } from './transient-error-lookup';
15import Request from './request';
16import MessageIO from './message-io';
17import { Parser as TokenStreamParser } from './token/token-stream-parser';
18import { ISOLATION_LEVEL } from './transaction';
19import { ConnectionError } from './errors';
20import Message from './message';
21import { type Metadata } from './metadata-parser';
22import { ColumnEncryptionAzureKeyVaultProvider } from './always-encrypted/keystore-provider-azure-key-vault';
23import { Collation } from './collation';
24import { TokenHandler } from './token/handler';
25type BeginTransactionCallback =
26/**
27 * The callback is called when the request to start the transaction has completed,
28 * either successfully or with an error.
29 * If an error occurred then `err` will describe the error.
30 *
31 * As only one request at a time may be executed on a connection, another request should not
32 * be initiated until this callback is called.
33 *
34 * @param err If an error occurred, an [[Error]] object with details of the error.
35 * @param transactionDescriptor A Buffer that describe the transaction
36 */
37(err: Error | null | undefined, transactionDescriptor?: Buffer) => void;
38type SaveTransactionCallback =
39/**
40 * The callback is called when the request to set a savepoint within the
41 * transaction has completed, either successfully or with an error.
42 * If an error occurred then `err` will describe the error.
43 *
44 * As only one request at a time may be executed on a connection, another request should not
45 * be initiated until this callback is called.
46 *
47 * @param err If an error occurred, an [[Error]] object with details of the error.
48 */
49(err: Error | null | undefined) => void;
50type CommitTransactionCallback =
51/**
52 * The callback is called when the request to commit the transaction has completed,
53 * either successfully or with an error.
54 * If an error occurred then `err` will describe the error.
55 *
56 * As only one request at a time may be executed on a connection, another request should not
57 * be initiated until this callback is called.
58 *
59 * @param err If an error occurred, an [[Error]] object with details of the error.
60 */
61(err: Error | null | undefined) => void;
62type RollbackTransactionCallback =
63/**
64 * The callback is called when the request to rollback the transaction has
65 * completed, either successfully or with an error.
66 * If an error occurred then err will describe the error.
67 *
68 * As only one request at a time may be executed on a connection, another request should not
69 * be initiated until this callback is called.
70 *
71 * @param err If an error occurred, an [[Error]] object with details of the error.
72 */
73(err: Error | null | undefined) => void;
74type ResetCallback =
75/**
76 * The callback is called when the connection reset has completed,
77 * either successfully or with an error.
78 *
79 * If an error occurred then `err` will describe the error.
80 *
81 * As only one request at a time may be executed on a connection, another
82 * request should not be initiated until this callback is called
83 *
84 * @param err If an error occurred, an [[Error]] object with details of the error.
85 */
86(err: Error | null | undefined) => void;
87type TransactionDoneCallback = (err: Error | null | undefined, ...args: any[]) => void;
88type CallbackParameters<T extends (err: Error | null | undefined, ...args: any[]) => any> = T extends (err: Error | null | undefined, ...args: infer P) => any ? P : never;
89interface AzureActiveDirectoryMsiAppServiceAuthentication {
90 type: 'azure-active-directory-msi-app-service';
91 options: {
92 /**
93 * If you user want to connect to an Azure app service using a specific client account
94 * they need to provide `clientId` associate to their created identity.
95 *
96 * This is optional for retrieve token from azure web app service
97 */
98 clientId?: string;
99 };
100}
101interface AzureActiveDirectoryMsiVmAuthentication {
102 type: 'azure-active-directory-msi-vm';
103 options: {
104 /**
105 * If you want to connect using a specific client account
106 * they need to provide `clientId` associated to their created identity.
107 *
108 * This is optional for retrieve a token
109 */
110 clientId?: string;
111 };
112}
113interface AzureActiveDirectoryDefaultAuthentication {
114 type: 'azure-active-directory-default';
115 options: {
116 /**
117 * If you want to connect using a specific client account
118 * they need to provide `clientId` associated to their created identity.
119 *
120 * This is optional for retrieving a token
121 */
122 clientId?: string;
123 };
124}
125interface AzureActiveDirectoryAccessTokenAuthentication {
126 type: 'azure-active-directory-access-token';
127 options: {
128 /**
129 * A user need to provide `token` which they retrieved else where
130 * to forming the connection.
131 */
132 token: string;
133 };
134}
135interface AzureActiveDirectoryPasswordAuthentication {
136 type: 'azure-active-directory-password';
137 options: {
138 /**
139 * A user need to provide `userName` associate to their account.
140 */
141 userName: string;
142 /**
143 * A user need to provide `password` associate to their account.
144 */
145 password: string;
146 /**
147 * A client id to use.
148 */
149 clientId: string;
150 /**
151 * Optional parameter for specific Azure tenant ID
152 */
153 tenantId: string;
154 };
155}
156interface AzureActiveDirectoryServicePrincipalSecret {
157 type: 'azure-active-directory-service-principal-secret';
158 options: {
159 /**
160 * Application (`client`) ID from your registered Azure application
161 */
162 clientId: string;
163 /**
164 * The created `client secret` for this registered Azure application
165 */
166 clientSecret: string;
167 /**
168 * Directory (`tenant`) ID from your registered Azure application
169 */
170 tenantId: string;
171 };
172}
173/** Structure that defines the options that are necessary to authenticate the Tedious.JS instance with an `@azure/identity` token credential. */
174interface TokenCredentialAuthentication {
175 /** Unique designator for the type of authentication to be used. */
176 type: 'token-credential';
177 /** Set of configurations that are required or allowed with this authentication type. */
178 options: {
179 /** Credential object used to authenticate to the resource. */
180 credential: TokenCredential;
181 };
182}
183interface NtlmAuthentication {
184 type: 'ntlm';
185 options: {
186 /**
187 * User name from your windows account.
188 */
189 userName: string;
190 /**
191 * Password from your windows account.
192 */
193 password: string;
194 /**
195 * Once you set domain for ntlm authentication type, driver will connect to SQL Server using domain login.
196 *
197 * This is necessary for forming a connection using ntlm type
198 */
199 domain: string;
200 };
201}
202interface DefaultAuthentication {
203 type: 'default';
204 options: {
205 /**
206 * User name to use for sql server login.
207 */
208 userName?: string | undefined;
209 /**
210 * Password to use for sql server login.
211 */
212 password?: string | undefined;
213 };
214}
215export type ConnectionAuthentication = DefaultAuthentication | NtlmAuthentication | TokenCredentialAuthentication | AzureActiveDirectoryPasswordAuthentication | AzureActiveDirectoryMsiAppServiceAuthentication | AzureActiveDirectoryMsiVmAuthentication | AzureActiveDirectoryAccessTokenAuthentication | AzureActiveDirectoryServicePrincipalSecret | AzureActiveDirectoryDefaultAuthentication;
216interface InternalConnectionConfig {
217 server: string;
218 authentication: ConnectionAuthentication;
219 options: InternalConnectionOptions;
220}
221export interface InternalConnectionOptions {
222 abortTransactionOnError: boolean;
223 appName: undefined | string;
224 camelCaseColumns: boolean;
225 cancelTimeout: number;
226 columnEncryptionKeyCacheTTL: number;
227 columnEncryptionSetting: boolean;
228 columnNameReplacer: undefined | ((colName: string, index: number, metadata: Metadata) => string);
229 connectionRetryInterval: number;
230 connector: undefined | (() => Promise<net.Socket>);
231 connectTimeout: number;
232 connectionIsolationLevel: typeof ISOLATION_LEVEL[keyof typeof ISOLATION_LEVEL];
233 cryptoCredentialsDetails: SecureContextOptions;
234 database: undefined | string;
235 datefirst: number;
236 dateFormat: string;
237 debug: {
238 data: boolean;
239 packet: boolean;
240 payload: boolean;
241 token: boolean;
242 };
243 enableAnsiNull: null | boolean;
244 enableAnsiNullDefault: null | boolean;
245 enableAnsiPadding: null | boolean;
246 enableAnsiWarnings: null | boolean;
247 enableArithAbort: null | boolean;
248 enableConcatNullYieldsNull: null | boolean;
249 enableCursorCloseOnCommit: null | boolean;
250 enableImplicitTransactions: null | boolean;
251 enableNumericRoundabort: null | boolean;
252 enableQuotedIdentifier: null | boolean;
253 encrypt: string | boolean;
254 encryptionKeyStoreProviders: KeyStoreProviderMap | undefined;
255 fallbackToDefaultDb: boolean;
256 instanceName: undefined | string;
257 isolationLevel: typeof ISOLATION_LEVEL[keyof typeof ISOLATION_LEVEL];
258 language: string;
259 localAddress: undefined | string;
260 maxRetriesOnTransientErrors: number;
261 multiSubnetFailover: boolean;
262 packetSize: number;
263 port: undefined | number;
264 readOnlyIntent: boolean;
265 requestTimeout: number;
266 rowCollectionOnDone: boolean;
267 rowCollectionOnRequestCompletion: boolean;
268 serverName: undefined | string;
269 serverSupportsColumnEncryption: boolean;
270 tdsVersion: string;
271 textsize: number;
272 trustedServerNameAE: string | undefined;
273 trustServerCertificate: boolean;
274 useColumnNames: boolean;
275 useUTC: boolean;
276 workstationId: undefined | string;
277 lowerCaseGuids: boolean;
278}
279interface KeyStoreProviderMap {
280 [key: string]: ColumnEncryptionAzureKeyVaultProvider;
281}
282/**
283 * @private
284 */
285interface State {
286 name: string;
287 enter?(this: Connection): void;
288 exit?(this: Connection, newState: State): void;
289 events: {
290 socketError?(this: Connection, err: Error): void;
291 connectTimeout?(this: Connection): void;
292 message?(this: Connection, message: Message): void;
293 retry?(this: Connection): void;
294 reconnect?(this: Connection): void;
295 };
296}
297type Authentication = DefaultAuthentication | NtlmAuthentication | TokenCredentialAuthentication | AzureActiveDirectoryPasswordAuthentication | AzureActiveDirectoryMsiAppServiceAuthentication | AzureActiveDirectoryMsiVmAuthentication | AzureActiveDirectoryAccessTokenAuthentication | AzureActiveDirectoryServicePrincipalSecret | AzureActiveDirectoryDefaultAuthentication;
298type AuthenticationType = Authentication['type'];
299export interface ConnectionConfiguration {
300 /**
301 * Hostname to connect to.
302 */
303 server: string;
304 /**
305 * Configuration options for forming the connection.
306 */
307 options?: ConnectionOptions;
308 /**
309 * Authentication related options for connection.
310 */
311 authentication?: AuthenticationOptions;
312}
313interface DebugOptions {
314 /**
315 * A boolean, controlling whether [[debug]] events will be emitted with text describing packet data details
316 *
317 * (default: `false`)
318 */
319 data: boolean;
320 /**
321 * A boolean, controlling whether [[debug]] events will be emitted with text describing packet details
322 *
323 * (default: `false`)
324 */
325 packet: boolean;
326 /**
327 * A boolean, controlling whether [[debug]] events will be emitted with text describing packet payload details
328 *
329 * (default: `false`)
330 */
331 payload: boolean;
332 /**
333 * A boolean, controlling whether [[debug]] events will be emitted with text describing token stream tokens
334 *
335 * (default: `false`)
336 */
337 token: boolean;
338}
339interface AuthenticationOptions {
340 /**
341 * Type of the authentication method, valid types are `default`, `ntlm`,
342 * `azure-active-directory-password`, `azure-active-directory-access-token`,
343 * `azure-active-directory-msi-vm`, `azure-active-directory-msi-app-service`,
344 * `azure-active-directory-default`
345 * or `azure-active-directory-service-principal-secret`
346 */
347 type?: AuthenticationType;
348 /**
349 * Different options for authentication types:
350 *
351 * * `default`: [[DefaultAuthentication.options]]
352 * * `ntlm` :[[NtlmAuthentication]]
353 * * `token-credential`: [[CredentialChainAuthentication.options]]
354 * * `azure-active-directory-password` : [[AzureActiveDirectoryPasswordAuthentication.options]]
355 * * `azure-active-directory-access-token` : [[AzureActiveDirectoryAccessTokenAuthentication.options]]
356 * * `azure-active-directory-msi-vm` : [[AzureActiveDirectoryMsiVmAuthentication.options]]
357 * * `azure-active-directory-msi-app-service` : [[AzureActiveDirectoryMsiAppServiceAuthentication.options]]
358 * * `azure-active-directory-service-principal-secret` : [[AzureActiveDirectoryServicePrincipalSecret.options]]
359 * * `azure-active-directory-default` : [[AzureActiveDirectoryDefaultAuthentication.options]]
360 */
361 options?: any;
362}
363export interface ConnectionOptions {
364 /**
365 * A boolean determining whether to rollback a transaction automatically if any error is encountered
366 * during the given transaction's execution. This sets the value for `SET XACT_ABORT` during the
367 * initial SQL phase of a connection [documentation](https://docs.microsoft.com/en-us/sql/t-sql/statements/set-xact-abort-transact-sql).
368 */
369 abortTransactionOnError?: boolean | undefined;
370 /**
371 * Application name used for identifying a specific application in profiling, logging or tracing tools of SQLServer.
372 *
373 * (default: `Tedious`)
374 */
375 appName?: string | undefined;
376 /**
377 * A boolean, controlling whether the column names returned will have the first letter converted to lower case
378 * (`true`) or not. This value is ignored if you provide a [[columnNameReplacer]].
379 *
380 * (default: `false`).
381 */
382 camelCaseColumns?: boolean;
383 /**
384 * The number of milliseconds before the [[Request.cancel]] (abort) of a request is considered failed
385 *
386 * (default: `5000`).
387 */
388 cancelTimeout?: number;
389 /**
390 * A function with parameters `(columnName, index, columnMetaData)` and returning a string. If provided,
391 * this will be called once per column per result-set. The returned value will be used instead of the SQL-provided
392 * column name on row and meta data objects. This allows you to dynamically convert between naming conventions.
393 *
394 * (default: `null`)
395 */
396 columnNameReplacer?: (colName: string, index: number, metadata: Metadata) => string;
397 /**
398 * Number of milliseconds before retrying to establish connection, in case of transient failure.
399 *
400 * (default:`500`)
401 */
402 connectionRetryInterval?: number;
403 /**
404 * Custom connector factory method.
405 *
406 * (default: `undefined`)
407 */
408 connector?: () => Promise<net.Socket>;
409 /**
410 * The number of milliseconds before the attempt to connect is considered failed
411 *
412 * (default: `15000`).
413 */
414 connectTimeout?: number;
415 /**
416 * The default isolation level for new connections. All out-of-transaction queries are executed with this setting.
417 *
418 * The isolation levels are available from `require('tedious').ISOLATION_LEVEL`.
419 * * `READ_UNCOMMITTED`
420 * * `READ_COMMITTED`
421 * * `REPEATABLE_READ`
422 * * `SERIALIZABLE`
423 * * `SNAPSHOT`
424 *
425 * (default: `READ_COMMITED`).
426 */
427 connectionIsolationLevel?: number;
428 /**
429 * When encryption is used, an object may be supplied that will be used
430 * for the first argument when calling [`tls.createSecurePair`](http://nodejs.org/docs/latest/api/tls.html#tls_tls_createsecurepair_credentials_isserver_requestcert_rejectunauthorized)
431 *
432 * (default: `{}`)
433 */
434 cryptoCredentialsDetails?: SecureContextOptions;
435 /**
436 * Database to connect to (default: dependent on server configuration).
437 */
438 database?: string | undefined;
439 /**
440 * Sets the first day of the week to a number from 1 through 7.
441 */
442 datefirst?: number;
443 /**
444 * A string representing position of month, day and year in temporal datatypes.
445 *
446 * (default: `mdy`)
447 */
448 dateFormat?: string;
449 debug?: DebugOptions;
450 /**
451 * A boolean, controls the way null values should be used during comparison operation.
452 *
453 * (default: `true`)
454 */
455 enableAnsiNull?: boolean;
456 /**
457 * If true, `SET ANSI_NULL_DFLT_ON ON` will be set in the initial sql. This means new columns will be
458 * nullable by default. See the [T-SQL documentation](https://msdn.microsoft.com/en-us/library/ms187375.aspx)
459 *
460 * (default: `true`).
461 */
462 enableAnsiNullDefault?: boolean;
463 /**
464 * A boolean, controls if padding should be applied for values shorter than the size of defined column.
465 *
466 * (default: `true`)
467 */
468 enableAnsiPadding?: boolean;
469 /**
470 * If true, SQL Server will follow ISO standard behavior during various error conditions. For details,
471 * see [documentation](https://docs.microsoft.com/en-us/sql/t-sql/statements/set-ansi-warnings-transact-sql)
472 *
473 * (default: `true`)
474 */
475 enableAnsiWarnings?: boolean;
476 /**
477 * Ends a query when an overflow or divide-by-zero error occurs during query execution.
478 * See [documentation](https://docs.microsoft.com/en-us/sql/t-sql/statements/set-arithabort-transact-sql?view=sql-server-2017)
479 * for more details.
480 *
481 * (default: `true`)
482 */
483 enableArithAbort?: boolean;
484 /**
485 * A boolean, determines if concatenation with NULL should result in NULL or empty string value, more details in
486 * [documentation](https://docs.microsoft.com/en-us/sql/t-sql/statements/set-concat-null-yields-null-transact-sql)
487 *
488 * (default: `true`)
489 */
490 enableConcatNullYieldsNull?: boolean;
491 /**
492 * A boolean, controls whether cursor should be closed, if the transaction opening it gets committed or rolled
493 * back.
494 *
495 * (default: `null`)
496 */
497 enableCursorCloseOnCommit?: boolean | null;
498 /**
499 * A boolean, sets the connection to either implicit or autocommit transaction mode.
500 *
501 * (default: `false`)
502 */
503 enableImplicitTransactions?: boolean;
504 /**
505 * If false, error is not generated during loss of precession.
506 *
507 * (default: `false`)
508 */
509 enableNumericRoundabort?: boolean;
510 /**
511 * If true, characters enclosed in single quotes are treated as literals and those enclosed double quotes are treated as identifiers.
512 *
513 * (default: `true`)
514 */
515 enableQuotedIdentifier?: boolean;
516 /**
517 * A string value that can be only set to 'strict', which indicates the usage TDS 8.0 protocol. Otherwise,
518 * a boolean determining whether or not the connection will be encrypted.
519 *
520 * (default: `true`)
521 */
522 encrypt?: string | boolean;
523 /**
524 * By default, if the database requested by [[database]] cannot be accessed,
525 * the connection will fail with an error. However, if [[fallbackToDefaultDb]] is
526 * set to `true`, then the user's default database will be used instead
527 *
528 * (default: `false`)
529 */
530 fallbackToDefaultDb?: boolean;
531 /**
532 * The instance name to connect to.
533 * The SQL Server Browser service must be running on the database server,
534 * and UDP port 1434 on the database server must be reachable.
535 *
536 * (no default)
537 *
538 * Mutually exclusive with [[port]].
539 */
540 instanceName?: string | undefined;
541 /**
542 * The default isolation level that transactions will be run with.
543 *
544 * The isolation levels are available from `require('tedious').ISOLATION_LEVEL`.
545 * * `READ_UNCOMMITTED`
546 * * `READ_COMMITTED`
547 * * `REPEATABLE_READ`
548 * * `SERIALIZABLE`
549 * * `SNAPSHOT`
550 *
551 * (default: `READ_COMMITED`).
552 */
553 isolationLevel?: number;
554 /**
555 * Specifies the language environment for the session. The session language determines the datetime formats and system messages.
556 *
557 * (default: `us_english`).
558 */
559 language?: string;
560 /**
561 * A string indicating which network interface (ip address) to use when connecting to SQL Server.
562 */
563 localAddress?: string | undefined;
564 /**
565 * A boolean determining whether to parse unique identifier type with lowercase case characters.
566 *
567 * (default: `false`).
568 */
569 lowerCaseGuids?: boolean;
570 /**
571 * The maximum number of connection retries for transient errors.、
572 *
573 * (default: `3`).
574 */
575 maxRetriesOnTransientErrors?: number;
576 /**
577 * Sets the MultiSubnetFailover = True parameter, which can help minimize the client recovery latency when failovers occur.
578 *
579 * (default: `false`).
580 */
581 multiSubnetFailover?: boolean;
582 /**
583 * The size of TDS packets (subject to negotiation with the server).
584 * Should be a power of 2.
585 *
586 * (default: `4096`).
587 */
588 packetSize?: number;
589 /**
590 * Port to connect to (default: `1433`).
591 *
592 * Mutually exclusive with [[instanceName]]
593 */
594 port?: number | undefined;
595 /**
596 * A boolean, determining whether the connection will request read only access from a SQL Server Availability
597 * 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)")
598 *
599 * (default: `false`).
600 */
601 readOnlyIntent?: boolean;
602 /**
603 * The number of milliseconds before a request is considered failed, or `0` for no timeout.
604 *
605 * 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.
606 *
607 * (default: `15000`).
608 */
609 requestTimeout?: number;
610 /**
611 * A boolean, that when true will expose received rows in Requests done related events:
612 * * [[Request.Event_doneInProc]]
613 * * [[Request.Event_doneProc]]
614 * * [[Request.Event_done]]
615 *
616 * (default: `false`)
617 *
618 * Caution: If many row are received, enabling this option could result in
619 * excessive memory usage.
620 */
621 rowCollectionOnDone?: boolean;
622 /**
623 * A boolean, that when true will expose received rows in Requests' completion callback.See [[Request.constructor]].
624 *
625 * (default: `false`)
626 *
627 * Caution: If many row are received, enabling this option could result in
628 * excessive memory usage.
629 */
630 rowCollectionOnRequestCompletion?: boolean;
631 /**
632 * The version of TDS to use. If server doesn't support specified version, negotiated version is used instead.
633 *
634 * The versions are available from `require('tedious').TDS_VERSION`.
635 * * `7_1`
636 * * `7_2`
637 * * `7_3_A`
638 * * `7_3_B`
639 * * `7_4`
640 *
641 * (default: `7_4`)
642 */
643 tdsVersion?: string | undefined;
644 /**
645 * Specifies the size of varchar(max), nvarchar(max), varbinary(max), text, ntext, and image data returned by a SELECT statement.
646 *
647 * (default: `2147483647`)
648 */
649 textsize?: number;
650 /**
651 * If "true", the SQL Server SSL certificate is automatically trusted when the communication layer is encrypted using SSL.
652 *
653 * If "false", the SQL Server validates the server SSL certificate. If the server certificate validation fails,
654 * the driver raises an error and terminates the connection. Make sure the value passed to serverName exactly
655 * matches the Common Name (CN) or DNS name in the Subject Alternate Name in the server certificate for an SSL connection to succeed.
656 *
657 * (default: `true`)
658 */
659 trustServerCertificate?: boolean;
660 /**
661 *
662 */
663 serverName?: string;
664 /**
665 * A boolean determining whether to return rows as arrays or key-value collections.
666 *
667 * (default: `false`).
668 */
669 useColumnNames?: boolean;
670 /**
671 * A boolean determining whether to pass time values in UTC or local time.
672 *
673 * (default: `true`).
674 */
675 useUTC?: boolean;
676 /**
677 * The workstation ID (WSID) of the client, default os.hostname().
678 * Used for identifying a specific client in profiling, logging or
679 * tracing client activity in SQLServer.
680 *
681 * The value is reported by the TSQL function HOST_NAME().
682 */
683 workstationId?: string | undefined;
684}
685/**
686 * @private
687 */
688declare const CLEANUP_TYPE: {
689 NORMAL: number;
690 REDIRECT: number;
691 RETRY: number;
692};
693interface RoutingData {
694 server: string;
695 port: number;
696}
697/**
698 * A [[Connection]] instance represents a single connection to a database server.
699 *
700 * ```js
701 * var Connection = require('tedious').Connection;
702 * var config = {
703 * "authentication": {
704 * ...,
705 * "options": {...}
706 * },
707 * "options": {...}
708 * };
709 * var connection = new Connection(config);
710 * ```
711 *
712 * Only one request at a time may be executed on a connection. Once a [[Request]]
713 * has been initiated (with [[Connection.callProcedure]], [[Connection.execSql]],
714 * or [[Connection.execSqlBatch]]), another should not be initiated until the
715 * [[Request]]'s completion callback is called.
716 */
717declare class Connection extends EventEmitter {
718 /**
719 * @private
720 */
721 fedAuthRequired: boolean;
722 /**
723 * @private
724 */
725 config: InternalConnectionConfig;
726 /**
727 * @private
728 */
729 secureContextOptions: SecureContextOptions;
730 /**
731 * @private
732 */
733 inTransaction: boolean;
734 /**
735 * @private
736 */
737 transactionDescriptors: Buffer[];
738 /**
739 * @private
740 */
741 transactionDepth: number;
742 /**
743 * @private
744 */
745 isSqlBatch: boolean;
746 /**
747 * @private
748 */
749 curTransientRetryCount: number;
750 /**
751 * @private
752 */
753 transientErrorLookup: TransientErrorLookup;
754 /**
755 * @private
756 */
757 closed: boolean;
758 /**
759 * @private
760 */
761 loginError: undefined | AggregateError | ConnectionError;
762 /**
763 * @private
764 */
765 debug: Debug;
766 /**
767 * @private
768 */
769 ntlmpacket: undefined | any;
770 /**
771 * @private
772 */
773 ntlmpacketBuffer: undefined | Buffer;
774 /**
775 * @private
776 */
777 STATE: {
778 INITIALIZED: State;
779 CONNECTING: State;
780 SENT_PRELOGIN: State;
781 REROUTING: State;
782 TRANSIENT_FAILURE_RETRY: State;
783 SENT_TLSSSLNEGOTIATION: State;
784 SENT_LOGIN7_WITH_STANDARD_LOGIN: State;
785 SENT_LOGIN7_WITH_NTLM: State;
786 SENT_LOGIN7_WITH_FEDAUTH: State;
787 LOGGED_IN_SENDING_INITIAL_SQL: State;
788 LOGGED_IN: State;
789 SENT_CLIENT_REQUEST: State;
790 SENT_ATTENTION: State;
791 FINAL: State;
792 };
793 /**
794 * @private
795 */
796 routingData: undefined | RoutingData;
797 /**
798 * @private
799 */
800 messageIo: MessageIO;
801 /**
802 * @private
803 */
804 state: State;
805 /**
806 * @private
807 */
808 resetConnectionOnNextRequest: undefined | boolean;
809 /**
810 * @private
811 */
812 request: undefined | Request | BulkLoad;
813 /**
814 * @private
815 */
816 procReturnStatusValue: undefined | any;
817 /**
818 * @private
819 */
820 socket: undefined | net.Socket;
821 /**
822 * @private
823 */
824 messageBuffer: Buffer;
825 /**
826 * @private
827 */
828 connectTimer: undefined | NodeJS.Timeout;
829 /**
830 * @private
831 */
832 cancelTimer: undefined | NodeJS.Timeout;
833 /**
834 * @private
835 */
836 requestTimer: undefined | NodeJS.Timeout;
837 /**
838 * @private
839 */
840 retryTimer: undefined | NodeJS.Timeout;
841 /**
842 * @private
843 */
844 _cancelAfterRequestSent: () => void;
845 /**
846 * @private
847 */
848 databaseCollation: Collation | undefined;
849 /**
850 * Note: be aware of the different options field:
851 * 1. config.authentication.options
852 * 2. config.options
853 *
854 * ```js
855 * const { Connection } = require('tedious');
856 *
857 * const config = {
858 * "authentication": {
859 * ...,
860 * "options": {...}
861 * },
862 * "options": {...}
863 * };
864 *
865 * const connection = new Connection(config);
866 * ```
867 *
868 * @param config
869 */
870 constructor(config: ConnectionConfiguration);
871 connect(connectListener?: (err?: Error) => void): void;
872 /**
873 * The server has reported that the charset has changed.
874 */
875 on(event: 'charsetChange', listener: (charset: string) => void): this;
876 /**
877 * The attempt to connect and validate has completed.
878 */
879 on(event: 'connect',
880 /**
881 * @param err If successfully connected, will be falsey. If there was a
882 * problem (with either connecting or validation), will be an [[Error]] object.
883 */
884 listener: (err: Error | undefined) => void): this;
885 /**
886 * The server has reported that the active database has changed.
887 * This may be as a result of a successful login, or a `use` statement.
888 */
889 on(event: 'databaseChange', listener: (databaseName: string) => void): this;
890 /**
891 * A debug message is available. It may be logged or ignored.
892 */
893 on(event: 'debug', listener: (messageText: string) => void): this;
894 /**
895 * Internal error occurs.
896 */
897 on(event: 'error', listener: (err: Error) => void): this;
898 /**
899 * The server has issued an error message.
900 */
901 on(event: 'errorMessage', listener: (message: import('./token/token').ErrorMessageToken) => void): this;
902 /**
903 * The connection has ended.
904 *
905 * This may be as a result of the client calling [[close]], the server
906 * closing the connection, or a network error.
907 */
908 on(event: 'end', listener: () => void): this;
909 /**
910 * The server has issued an information message.
911 */
912 on(event: 'infoMessage', listener: (message: import('./token/token').InfoMessageToken) => void): this;
913 /**
914 * The server has reported that the language has changed.
915 */
916 on(event: 'languageChange', listener: (languageName: string) => void): this;
917 /**
918 * The connection was reset.
919 */
920 on(event: 'resetConnection', listener: () => void): this;
921 /**
922 * A secure connection has been established.
923 */
924 on(event: 'secure', listener: (cleartext: import('tls').TLSSocket) => void): this;
925 /**
926 * @private
927 */
928 emit(event: 'charsetChange', charset: string): boolean;
929 /**
930 * @private
931 */
932 emit(event: 'connect', error?: Error): boolean;
933 /**
934 * @private
935 */
936 emit(event: 'databaseChange', databaseName: string): boolean;
937 /**
938 * @private
939 */
940 emit(event: 'debug', messageText: string): boolean;
941 /**
942 * @private
943 */
944 emit(event: 'error', error: Error): boolean;
945 /**
946 * @private
947 */
948 emit(event: 'errorMessage', message: import('./token/token').ErrorMessageToken): boolean;
949 /**
950 * @private
951 */
952 emit(event: 'end'): boolean;
953 /**
954 * @private
955 */
956 emit(event: 'infoMessage', message: import('./token/token').InfoMessageToken): boolean;
957 /**
958 * @private
959 */
960 emit(event: 'languageChange', languageName: string): boolean;
961 /**
962 * @private
963 */
964 emit(event: 'secure', cleartext: import('tls').TLSSocket): boolean;
965 /**
966 * @private
967 */
968 emit(event: 'rerouting'): boolean;
969 /**
970 * @private
971 */
972 emit(event: 'resetConnection'): boolean;
973 /**
974 * @private
975 */
976 emit(event: 'retry'): boolean;
977 /**
978 * @private
979 */
980 emit(event: 'rollbackTransaction'): boolean;
981 /**
982 * Closes the connection to the database.
983 *
984 * The [[Event_end]] will be emitted once the connection has been closed.
985 */
986 close(): void;
987 /**
988 * @private
989 */
990 initialiseConnection(): void | Promise<void>;
991 /**
992 * @private
993 */
994 cleanupConnection(cleanupType: typeof CLEANUP_TYPE[keyof typeof CLEANUP_TYPE]): void;
995 /**
996 * @private
997 */
998 createDebug(): Debug;
999 /**
1000 * @private
1001 */
1002 createTokenStreamParser(message: Message, handler: TokenHandler): TokenStreamParser;
1003 socketHandlingForSendPreLogin(socket: net.Socket): void;
1004 wrapWithTls(socket: net.Socket, signal: AbortSignal): Promise<tls.TLSSocket>;
1005 connectOnPort(port: number, multiSubnetFailover: boolean, signal: AbortSignal, customConnector?: () => Promise<net.Socket>): void;
1006 /**
1007 * @private
1008 */
1009 closeConnection(): void;
1010 /**
1011 * @private
1012 */
1013 createConnectTimer(): AbortSignal;
1014 /**
1015 * @private
1016 */
1017 createCancelTimer(): void;
1018 /**
1019 * @private
1020 */
1021 createRequestTimer(): void;
1022 /**
1023 * @private
1024 */
1025 createRetryTimer(): void;
1026 /**
1027 * @private
1028 */
1029 connectTimeout(): void;
1030 /**
1031 * @private
1032 */
1033 cancelTimeout(): void;
1034 /**
1035 * @private
1036 */
1037 requestTimeout(): void;
1038 /**
1039 * @private
1040 */
1041 retryTimeout(): void;
1042 /**
1043 * @private
1044 */
1045 clearConnectTimer(): void;
1046 /**
1047 * @private
1048 */
1049 clearCancelTimer(): void;
1050 /**
1051 * @private
1052 */
1053 clearRequestTimer(): void;
1054 /**
1055 * @private
1056 */
1057 clearRetryTimer(): void;
1058 /**
1059 * @private
1060 */
1061 transitionTo(newState: State): void;
1062 /**
1063 * @private
1064 */
1065 getEventHandler<T extends keyof State['events']>(eventName: T): NonNullable<State['events'][T]>;
1066 /**
1067 * @private
1068 */
1069 dispatchEvent<T extends keyof State['events']>(eventName: T, ...args: Parameters<NonNullable<State['events'][T]>>): void;
1070 /**
1071 * @private
1072 */
1073 socketError(error: Error): void;
1074 /**
1075 * @private
1076 */
1077 socketEnd(): void;
1078 /**
1079 * @private
1080 */
1081 socketClose(): void;
1082 /**
1083 * @private
1084 */
1085 sendPreLogin(): void;
1086 /**
1087 * @private
1088 */
1089 sendLogin7Packet(): void;
1090 /**
1091 * @private
1092 */
1093 sendFedAuthTokenMessage(token: string): void;
1094 /**
1095 * @private
1096 */
1097 sendInitialSql(): void;
1098 /**
1099 * @private
1100 */
1101 getInitialSql(): string;
1102 /**
1103 * @private
1104 */
1105 processedInitialSql(): void;
1106 /**
1107 * Execute the SQL batch represented by [[Request]].
1108 * There is no param support, and unlike [[Request.execSql]],
1109 * it is not likely that SQL Server will reuse the execution plan it generates for the SQL.
1110 *
1111 * In almost all cases, [[Request.execSql]] will be a better choice.
1112 *
1113 * @param request A [[Request]] object representing the request.
1114 */
1115 execSqlBatch(request: Request): void;
1116 /**
1117 * Execute the SQL represented by [[Request]].
1118 *
1119 * As `sp_executesql` is used to execute the SQL, if the same SQL is executed multiples times
1120 * using this function, the SQL Server query optimizer is likely to reuse the execution plan it generates
1121 * for the first execution. This may also result in SQL server treating the request like a stored procedure
1122 * which can result in the [[Event_doneInProc]] or [[Event_doneProc]] events being emitted instead of the
1123 * [[Event_done]] event you might expect. Using [[execSqlBatch]] will prevent this from occurring but may have a negative performance impact.
1124 *
1125 * Beware of the way that scoping rules apply, and how they may [affect local temp tables](http://weblogs.sqlteam.com/mladenp/archive/2006/11/03/17197.aspx)
1126 * If you're running in to scoping issues, then [[execSqlBatch]] may be a better choice.
1127 * See also [issue #24](https://github.com/pekim/tedious/issues/24)
1128 *
1129 * @param request A [[Request]] object representing the request.
1130 */
1131 execSql(request: Request): void;
1132 /**
1133 * Creates a new BulkLoad instance.
1134 *
1135 * @param table The name of the table to bulk-insert into.
1136 * @param options A set of bulk load options.
1137 */
1138 newBulkLoad(table: string, callback: BulkLoadCallback): BulkLoad;
1139 newBulkLoad(table: string, options: BulkLoadOptions, callback: BulkLoadCallback): BulkLoad;
1140 /**
1141 * Execute a [[BulkLoad]].
1142 *
1143 * ```js
1144 * // We want to perform a bulk load into a table with the following format:
1145 * // CREATE TABLE employees (first_name nvarchar(255), last_name nvarchar(255), day_of_birth date);
1146 *
1147 * const bulkLoad = connection.newBulkLoad('employees', (err, rowCount) => {
1148 * // ...
1149 * });
1150 *
1151 * // First, we need to specify the columns that we want to write to,
1152 * // and their definitions. These definitions must match the actual table,
1153 * // otherwise the bulk load will fail.
1154 * bulkLoad.addColumn('first_name', TYPES.NVarchar, { nullable: false });
1155 * bulkLoad.addColumn('last_name', TYPES.NVarchar, { nullable: false });
1156 * bulkLoad.addColumn('date_of_birth', TYPES.Date, { nullable: false });
1157 *
1158 * // Execute a bulk load with a predefined list of rows.
1159 * //
1160 * // Note that these rows are held in memory until the
1161 * // bulk load was performed, so if you need to write a large
1162 * // number of rows (e.g. by reading from a CSV file),
1163 * // passing an `AsyncIterable` is advisable to keep memory usage low.
1164 * connection.execBulkLoad(bulkLoad, [
1165 * { 'first_name': 'Steve', 'last_name': 'Jobs', 'day_of_birth': new Date('02-24-1955') },
1166 * { 'first_name': 'Bill', 'last_name': 'Gates', 'day_of_birth': new Date('10-28-1955') }
1167 * ]);
1168 * ```
1169 *
1170 * @param bulkLoad A previously created [[BulkLoad]].
1171 * @param rows A [[Iterable]] or [[AsyncIterable]] that contains the rows that should be bulk loaded.
1172 */
1173 execBulkLoad(bulkLoad: BulkLoad, rows: AsyncIterable<unknown[] | {
1174 [columnName: string]: unknown;
1175 }> | Iterable<unknown[] | {
1176 [columnName: string]: unknown;
1177 }>): void;
1178 /**
1179 * Prepare the SQL represented by the request.
1180 *
1181 * The request can then be used in subsequent calls to
1182 * [[execute]] and [[unprepare]]
1183 *
1184 * @param request A [[Request]] object representing the request.
1185 * Parameters only require a name and type. Parameter values are ignored.
1186 */
1187 prepare(request: Request): void;
1188 /**
1189 * Release the SQL Server resources associated with a previously prepared request.
1190 *
1191 * @param request A [[Request]] object representing the request.
1192 * Parameters only require a name and type.
1193 * Parameter values are ignored.
1194 */
1195 unprepare(request: Request): void;
1196 /**
1197 * Execute previously prepared SQL, using the supplied parameters.
1198 *
1199 * @param request A previously prepared [[Request]].
1200 * @param parameters An object whose names correspond to the names of
1201 * parameters that were added to the [[Request]] before it was prepared.
1202 * The object's values are passed as the parameters' values when the
1203 * request is executed.
1204 */
1205 execute(request: Request, parameters?: {
1206 [key: string]: unknown;
1207 }): void;
1208 /**
1209 * Call a stored procedure represented by [[Request]].
1210 *
1211 * @param request A [[Request]] object representing the request.
1212 */
1213 callProcedure(request: Request): void;
1214 /**
1215 * Start a transaction.
1216 *
1217 * @param callback
1218 * @param name A string representing a name to associate with the transaction.
1219 * Optional, and defaults to an empty string. Required when `isolationLevel`
1220 * is present.
1221 * @param isolationLevel The isolation level that the transaction is to be run with.
1222 *
1223 * The isolation levels are available from `require('tedious').ISOLATION_LEVEL`.
1224 * * `READ_UNCOMMITTED`
1225 * * `READ_COMMITTED`
1226 * * `REPEATABLE_READ`
1227 * * `SERIALIZABLE`
1228 * * `SNAPSHOT`
1229 *
1230 * Optional, and defaults to the Connection's isolation level.
1231 */
1232 beginTransaction(callback: BeginTransactionCallback, name?: string, isolationLevel?: number): void;
1233 /**
1234 * Commit a transaction.
1235 *
1236 * There should be an active transaction - that is, [[beginTransaction]]
1237 * should have been previously called.
1238 *
1239 * @param callback
1240 * @param name A string representing a name to associate with the transaction.
1241 * Optional, and defaults to an empty string. Required when `isolationLevel`is present.
1242 */
1243 commitTransaction(callback: CommitTransactionCallback, name?: string): void;
1244 /**
1245 * Rollback a transaction.
1246 *
1247 * There should be an active transaction - that is, [[beginTransaction]]
1248 * should have been previously called.
1249 *
1250 * @param callback
1251 * @param name A string representing a name to associate with the transaction.
1252 * Optional, and defaults to an empty string.
1253 * Required when `isolationLevel` is present.
1254 */
1255 rollbackTransaction(callback: RollbackTransactionCallback, name?: string): void;
1256 /**
1257 * Set a savepoint within a transaction.
1258 *
1259 * There should be an active transaction - that is, [[beginTransaction]]
1260 * should have been previously called.
1261 *
1262 * @param callback
1263 * @param name A string representing a name to associate with the transaction.\
1264 * Optional, and defaults to an empty string.
1265 * Required when `isolationLevel` is present.
1266 */
1267 saveTransaction(callback: SaveTransactionCallback, name: string): void;
1268 /**
1269 * Run the given callback after starting a transaction, and commit or
1270 * rollback the transaction afterwards.
1271 *
1272 * This is a helper that employs [[beginTransaction]], [[commitTransaction]],
1273 * [[rollbackTransaction]], and [[saveTransaction]] to greatly simplify the
1274 * use of database transactions and automatically handle transaction nesting.
1275 *
1276 * @param cb
1277 * @param isolationLevel
1278 * The isolation level that the transaction is to be run with.
1279 *
1280 * The isolation levels are available from `require('tedious').ISOLATION_LEVEL`.
1281 * * `READ_UNCOMMITTED`
1282 * * `READ_COMMITTED`
1283 * * `REPEATABLE_READ`
1284 * * `SERIALIZABLE`
1285 * * `SNAPSHOT`
1286 *
1287 * Optional, and defaults to the Connection's isolation level.
1288 */
1289 transaction(cb: (err: Error | null | undefined, txDone?: <T extends TransactionDoneCallback>(err: Error | null | undefined, done: T, ...args: CallbackParameters<T>) => void) => void, isolationLevel?: typeof ISOLATION_LEVEL[keyof typeof ISOLATION_LEVEL]): void;
1290 /**
1291 * @private
1292 */
1293 makeRequest(request: Request | BulkLoad, packetType: number, payload: (Iterable<Buffer> | AsyncIterable<Buffer>) & {
1294 toString: (indent?: string) => string;
1295 }): void;
1296 /**
1297 * Cancel currently executed request.
1298 */
1299 cancel(): boolean;
1300 /**
1301 * Reset the connection to its initial state.
1302 * Can be useful for connection pool implementations.
1303 *
1304 * @param callback
1305 */
1306 reset(callback: ResetCallback): void;
1307 /**
1308 * @private
1309 */
1310 currentTransactionDescriptor(): Buffer;
1311 /**
1312 * @private
1313 */
1314 getIsolationLevelText(isolationLevel: typeof ISOLATION_LEVEL[keyof typeof ISOLATION_LEVEL]): "read uncommitted" | "repeatable read" | "serializable" | "snapshot" | "read committed";
1315}
1316export default Connection;
1317
\No newline at end of file