UNPKG

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