UNPKG

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