tedious

  • Version 18.2.0
  • Published
  • 3.42 MB
  • 9 dependencies
  • MIT license

Install

npm i tedious
yarn add tedious
pnpm add tedious

Overview

A TDS driver, for connecting to MS SQLServer databases.

Index

Variables

Functions

Classes

Interfaces

Type Aliases

Namespaces

Variables

variable ISOLATION_LEVEL

const ISOLATION_LEVEL: { [key: string]: number };

    variable library

    const library: { name: string };

      variable TDS_VERSION

      const TDS_VERSION: { [key: string]: number };

        variable TYPES

        const TYPES: {
        TinyInt: DataType;
        Bit: DataType;
        SmallInt: DataType;
        Int: DataType;
        SmallDateTime: DataType;
        Real: DataType;
        Money: DataType;
        DateTime: DataType;
        Float: DataType;
        Decimal: DataType & {
        resolvePrecision: (parameter: Parameter) => number;
        resolveScale: (parameter: Parameter) => number;
        };
        Numeric: DataType & {
        resolveScale: (parameter: Parameter) => number;
        resolvePrecision: (parameter: Parameter) => number;
        };
        SmallMoney: DataType;
        BigInt: DataType;
        Image: DataType;
        Text: DataType;
        UniqueIdentifier: DataType;
        NText: DataType;
        VarBinary: { maximumLength: number } & DataType;
        VarChar: { maximumLength: number } & DataType;
        Binary: { maximumLength: number } & DataType;
        Char: { maximumLength: number } & DataType;
        NVarChar: { maximumLength: number } & DataType;
        NChar: DataType & { maximumLength: number };
        Xml: DataType;
        Time: DataType;
        Date: DataType;
        DateTime2: DataType & { resolveScale: (parameter: Parameter) => number };
        DateTimeOffset: DataType & { resolveScale: (parameter: Parameter) => number };
        UDT: DataType;
        TVP: DataType;
        Variant: DataType;
        };
        • Type Constant JavaScript Result set Parameter

          Exact numerics bit [[TYPES.Bit]] boolean tinyint [[TYPES.TinyInt]] number smallint [[TYPES.SmallInt]] number int [[TYPES.Int]] number bigint1 [[TYPES.BigInt]] string numeric2 [[TYPES.Numeric]] number decimal2 [[TYPES.Decimal]] number smallmoney [[TYPES.SmallMoney]] number money [[TYPES.Money]] number

          Approximate numerics float [[TYPES.Float]] number real [[TYPES.Real]] number

          Date and Time smalldatetime [[TYPES.SmallDateTime]] Date datetime [[TYPES.DateTime]] Date datetime2 [[TYPES.DateTime2]] Date datetimeoffset [[TYPES.DateTimeOffset]] Date time [[TYPES.Time]] Date date [[TYPES.Date]] Date

          Character Strings char [[TYPES.Char]] string varchar3 [[TYPES.VarChar]] string text [[TYPES.Text]] string

          Unicode Strings nchar [[TYPES.NChar]] string nvarchar3 [[TYPES.NVarChar]] string ntext [[TYPES.NText]] string -

          Binary Strings4 binary [[TYPES.Binary]] Buffer varbinary [[TYPES.VarBinary]] Buffer image [[TYPES.Image]] Buffer

          Other Data Types TVP [[TYPES.TVP]] Object - UDT [[TYPES.UDT]] Buffer - uniqueidentifier4 [[TYPES.UniqueIdentifier]] string variant [[TYPES.Variant]] any - xml [[TYPES.Xml]] string -

          BigInt Values are returned as a string. This is because values can exceed 53 bits of significant data, which is greater than a Javascript number type can represent as an integer. Numerical, Decimal For input parameters, default precision is 18 and default scale is 0. Maximum supported precision is 19. VarChar, NVarChar varchar(max) and nvarchar(max) are also supported. UniqueIdentifier Values are returned as a 16 byte hexadecimal string. Note that the order of bytes is not the same as the character representation. See Using uniqueidentifier Data for an example of the different ordering of bytes.

        Functions

        function connect

        connect: (
        config: ConnectionConfiguration,
        connectListener?: (err?: Error) => void
        ) => Connection;

          Classes

          class BulkLoad

          class BulkLoad extends EventEmitter {}
          • A BulkLoad instance is used to perform a bulk insert.

            Use [[Connection.newBulkLoad]] to create a new instance, and [[Connection.execBulkLoad]] to execute it.

            Example of BulkLoad Usages:

            // optional BulkLoad options
            const options = { keepNulls: true };
            // instantiate - provide the table where you'll be inserting to, options and a callback
            const bulkLoad = connection.newBulkLoad('MyTable', options, (error, rowCount) => {
            console.log('inserted %d rows', rowCount);
            });
            // setup your columns - always indicate whether the column is nullable
            bulkLoad.addColumn('myInt', TYPES.Int, { nullable: false });
            bulkLoad.addColumn('myString', TYPES.NVarChar, { length: 50, nullable: true });
            // execute
            connection.execBulkLoad(bulkLoad, [
            { myInt: 7, myString: 'hello' },
            { myInt: 23, myString: 'world' }
            ]);

          constructor

          constructor(
          table: string,
          collation: Collation,
          connectionOptions: InternalConnectionOptions,
          { checkConstraints, fireTriggers, keepNulls, lockTable, order }: Options,
          callback: Callback
          );

          property bulkOptions

          bulkOptions: InternalOptions;

          property callback

          callback: Callback;

          property canceled

          canceled: boolean;

          property collation

          collation: Collation;

            property columns

            columns: Column[];

            property columnsByName

            columnsByName: { [name: string]: Column };

            property connection

            connection: Connection;

            property error

            error: Error;

            property executionStarted

            executionStarted: boolean;

            property firstRowWritten

            firstRowWritten: boolean;

            property options

            options: InternalConnectionOptions;

            property rowCount

            rowCount: number;

            property rows

            rows: any[];

            property rowToPacketTransform

            rowToPacketTransform: RowTransform;

            property rst

            rst: any[];

            property streamingMode

            streamingMode: boolean;

            property table

            table: string;

            property timeout

            timeout: number;

            method addColumn

            addColumn: (
            name: string,
            type: DataType,
            { output, length, precision, scale, objName, nullable }: ColumnOptions
            ) => void;
            • Adds a column to the bulk load.

              The column definitions should match the table you are trying to insert into. Attempting to call addColumn after the first row has been added will throw an exception.

              bulkLoad.addColumn('MyIntColumn', TYPES.Int, { nullable: false });

              Parameter name

              The name of the column.

              Parameter type

              One of the supported data types.

              Parameter __namedParameters

              Additional column type information. At a minimum, nullable must be set to true or false.

              Parameter length

              For VarChar, NVarChar, VarBinary. Use length as Infinity for VarChar(max), NVarChar(max) and VarBinary(max).

              Parameter nullable

              Indicates whether the column accepts NULL values.

              Parameter objName

              If the name of the column is different from the name of the property found on rowObj arguments passed to [[addRow]] or [[Connection.execBulkLoad]], then you can use this option to specify the property name.

              Parameter precision

              For Numeric, Decimal.

              Parameter scale

              For Numeric, Decimal, Time, DateTime2, DateTimeOffset.

            method cancel

            cancel: () => void;

            method createDoneToken

            createDoneToken: () => Buffer;

            method getBulkInsertSql

            getBulkInsertSql: () => string;

            method getColMetaData

            getColMetaData: () => Buffer;

            method getOptionsSql

            getOptionsSql: () => string;

            method getTableCreationSql

            getTableCreationSql: () => string;
            • This is simply a helper utility function which returns a CREATE TABLE SQL statement based on the columns added to the bulkLoad object. This may be particularly handy when you want to insert into a temporary table (a table which starts with #).

              var sql = bulkLoad.getTableCreationSql();

              A side note on bulk inserting into temporary tables: if you want to access a local temporary table after executing the bulk load, you'll need to use the same connection and execute your requests using [[Connection.execSqlBatch]] instead of [[Connection.execSql]]

            method setTimeout

            setTimeout: (timeout?: number) => void;
            • Sets a timeout for this bulk load.

              bulkLoad.setTimeout(timeout);

              Parameter timeout

              The number of milliseconds before the bulk load is considered failed, or 0 for no timeout. When no timeout is set for the bulk load, the [[ConnectionOptions.requestTimeout]] of the Connection is used.

            class Connection

            class Connection extends EventEmitter {}
            • A [[Connection]] instance represents a single connection to a database server.

              var Connection = require('tedious').Connection;
              var config = {
              "authentication": {
              ...,
              "options": {...}
              },
              "options": {...}
              };
              var connection = new Connection(config);

              Only one request at a time may be executed on a connection. Once a [[Request]] has been initiated (with [[Connection.callProcedure]], [[Connection.execSql]], or [[Connection.execSqlBatch]]), another should not be initiated until the [[Request]]'s completion callback is called.

            constructor

            constructor(config: ConnectionConfiguration);
            • Note: be aware of the different options field: 1. config.authentication.options 2. config.options

              const { Connection } = require('tedious');
              const config = {
              "authentication": {
              ...,
              "options": {...}
              },
              "options": {...}
              };
              const connection = new Connection(config);

              Parameter config

            property cancelTimer

            cancelTimer: any;

            property closed

            closed: boolean;

            property config

            config: InternalConnectionConfig;

            property connectTimer

            connectTimer: any;

            property curTransientRetryCount

            curTransientRetryCount: number;

            property databaseCollation

            databaseCollation: Collation;

            property debug

            debug: Debug;

            property fedAuthRequired

            fedAuthRequired: boolean;

            property inTransaction

            inTransaction: boolean;

            property isSqlBatch

            isSqlBatch: boolean;

            property loginError

            loginError: AggregateError | ConnectionError;

            property messageBuffer

            messageBuffer: Buffer;

            property messageIo

            messageIo: MessageIO;

            property ntlmpacket

            ntlmpacket: any;

            property ntlmpacketBuffer

            ntlmpacketBuffer: any;

            property procReturnStatusValue

            procReturnStatusValue: any;

            property request

            request: Request | BulkLoad;

            property requestTimer

            requestTimer: any;

            property resetConnectionOnNextRequest

            resetConnectionOnNextRequest: boolean;

            property retryTimer

            retryTimer: any;

            property routingData

            routingData: RoutingData;

            property secureContextOptions

            secureContextOptions: SecureContextOptions;

            property socket

            socket: any;

            property state

            state: State;

            property STATE

            STATE: {
            INITIALIZED: State;
            CONNECTING: State;
            SENT_PRELOGIN: State;
            REROUTING: State;
            TRANSIENT_FAILURE_RETRY: State;
            SENT_TLSSSLNEGOTIATION: State;
            SENT_LOGIN7_WITH_STANDARD_LOGIN: State;
            SENT_LOGIN7_WITH_NTLM: State;
            SENT_LOGIN7_WITH_FEDAUTH: State;
            LOGGED_IN_SENDING_INITIAL_SQL: State;
            LOGGED_IN: State;
            SENT_CLIENT_REQUEST: State;
            SENT_ATTENTION: State;
            FINAL: State;
            };

            property transactionDepth

            transactionDepth: number;

            property transactionDescriptors

            transactionDescriptors: Buffer[];

            property transientErrorLookup

            transientErrorLookup: TransientErrorLookup;

            method beginTransaction

            beginTransaction: (
            callback: BeginTransactionCallback,
            name?: string,
            isolationLevel?: number
            ) => void;
            • Start a transaction.

              Parameter callback

              Parameter name

              A string representing a name to associate with the transaction. Optional, and defaults to an empty string. Required when isolationLevel is present.

              Parameter isolationLevel

              The isolation level that the transaction is to be run with.

              The isolation levels are available from require('tedious').ISOLATION_LEVEL. * READ_UNCOMMITTED * READ_COMMITTED * REPEATABLE_READ * SERIALIZABLE * SNAPSHOT

              Optional, and defaults to the Connection's isolation level.

            method callProcedure

            callProcedure: (request: Request) => void;
            • Call a stored procedure represented by [[Request]].

              Parameter request

              A [[Request]] object representing the request.

            method cancel

            cancel: () => boolean;
            • Cancel currently executed request.

            method cancelTimeout

            cancelTimeout: () => void;

            method cleanupConnection

            cleanupConnection: (
            cleanupType: (typeof CLEANUP_TYPE)[keyof typeof CLEANUP_TYPE]
            ) => void;

            method clearCancelTimer

            clearCancelTimer: () => void;

            method clearConnectTimer

            clearConnectTimer: () => void;

            method clearRequestTimer

            clearRequestTimer: () => void;

            method clearRetryTimer

            clearRetryTimer: () => void;

            method close

            close: () => void;
            • Closes the connection to the database.

              The [[Event_end]] will be emitted once the connection has been closed.

            method closeConnection

            closeConnection: () => void;

            method commitTransaction

            commitTransaction: (callback: CommitTransactionCallback, name?: string) => void;
            • Commit a transaction.

              There should be an active transaction - that is, [[beginTransaction]] should have been previously called.

              Parameter callback

              Parameter name

              A string representing a name to associate with the transaction. Optional, and defaults to an empty string. Required when isolationLevelis present.

            method connect

            connect: (connectListener?: (err?: Error) => void) => void;

              method connectOnPort

              connectOnPort: (
              port: number,
              multiSubnetFailover: boolean,
              signal: AbortSignal,
              customConnector?: () => Promise<net.Socket>
              ) => void;

                method connectTimeout

                connectTimeout: () => void;

                method createCancelTimer

                createCancelTimer: () => void;

                method createConnectTimer

                createConnectTimer: () => AbortSignal;

                method createDebug

                createDebug: () => Debug;

                method createRequestTimer

                createRequestTimer: () => void;

                method createRetryTimer

                createRetryTimer: () => void;

                method createTokenStreamParser

                createTokenStreamParser: (
                message: Message,
                handler: TokenHandler
                ) => TokenStreamParser;

                method currentTransactionDescriptor

                currentTransactionDescriptor: () => Buffer;

                method dispatchEvent

                dispatchEvent: <
                T extends
                | 'retry'
                | 'socketError'
                | 'connectTimeout'
                | 'message'
                | 'reconnect'
                >(
                eventName: T,
                ...args: Parameters<NonNullable<State['events'][T]>>
                ) => void;

                method emit

                emit: {
                (event: 'charsetChange', charset: string): boolean;
                (event: 'connect', error?: Error): boolean;
                (event: 'databaseChange', databaseName: string): boolean;
                (event: 'debug', messageText: string): boolean;
                (event: 'error', error: Error): boolean;
                (event: 'errorMessage', message: ErrorMessageToken): boolean;
                (event: 'end'): boolean;
                (event: 'infoMessage', message: InfoMessageToken): boolean;
                (event: 'languageChange', languageName: string): boolean;
                (event: 'secure', cleartext: any): boolean;
                (event: 'rerouting'): boolean;
                (event: 'resetConnection'): boolean;
                (event: 'retry'): boolean;
                (event: 'rollbackTransaction'): boolean;
                };

                method execBulkLoad

                execBulkLoad: (
                bulkLoad: BulkLoad,
                rows:
                | AsyncIterable<unknown[] | { [columnName: string]: unknown }>
                | Iterable<unknown[] | { [columnName: string]: unknown }>
                ) => void;
                • Execute a [[BulkLoad]].

                  // We want to perform a bulk load into a table with the following format:
                  // CREATE TABLE employees (first_name nvarchar(255), last_name nvarchar(255), day_of_birth date);
                  const bulkLoad = connection.newBulkLoad('employees', (err, rowCount) => {
                  // ...
                  });
                  // First, we need to specify the columns that we want to write to,
                  // and their definitions. These definitions must match the actual table,
                  // otherwise the bulk load will fail.
                  bulkLoad.addColumn('first_name', TYPES.NVarchar, { nullable: false });
                  bulkLoad.addColumn('last_name', TYPES.NVarchar, { nullable: false });
                  bulkLoad.addColumn('date_of_birth', TYPES.Date, { nullable: false });
                  // Execute a bulk load with a predefined list of rows.
                  //
                  // Note that these rows are held in memory until the
                  // bulk load was performed, so if you need to write a large
                  // number of rows (e.g. by reading from a CSV file),
                  // passing an `AsyncIterable` is advisable to keep memory usage low.
                  connection.execBulkLoad(bulkLoad, [
                  { 'first_name': 'Steve', 'last_name': 'Jobs', 'day_of_birth': new Date('02-24-1955') },
                  { 'first_name': 'Bill', 'last_name': 'Gates', 'day_of_birth': new Date('10-28-1955') }
                  ]);

                  Parameter bulkLoad

                  A previously created [[BulkLoad]].

                  Parameter rows

                  A [[Iterable]] or [[AsyncIterable]] that contains the rows that should be bulk loaded.

                method execSql

                execSql: (request: Request) => void;
                • Execute the SQL represented by [[Request]].

                  As sp_executesql is used to execute the SQL, if the same SQL is executed multiples times using this function, the SQL Server query optimizer is likely to reuse the execution plan it generates for the first execution. This may also result in SQL server treating the request like a stored procedure which can result in the [[Event_doneInProc]] or [[Event_doneProc]] events being emitted instead of the [[Event_done]] event you might expect. Using [[execSqlBatch]] will prevent this from occurring but may have a negative performance impact.

                  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) If you're running in to scoping issues, then [[execSqlBatch]] may be a better choice. See also [issue #24](https://github.com/pekim/tedious/issues/24)

                  Parameter request

                  A [[Request]] object representing the request.

                method execSqlBatch

                execSqlBatch: (request: Request) => void;
                • Execute the SQL batch represented by [[Request]]. There is no param support, and unlike [[Request.execSql]], it is not likely that SQL Server will reuse the execution plan it generates for the SQL.

                  In almost all cases, [[Request.execSql]] will be a better choice.

                  Parameter request

                  A [[Request]] object representing the request.

                method execute

                execute: (request: Request, parameters?: { [key: string]: unknown }) => void;
                • Execute previously prepared SQL, using the supplied parameters.

                  Parameter request

                  A previously prepared [[Request]].

                  Parameter parameters

                  An object whose names correspond to the names of parameters that were added to the [[Request]] before it was prepared. The object's values are passed as the parameters' values when the request is executed.

                method getEventHandler

                getEventHandler: <
                T extends
                | 'retry'
                | 'socketError'
                | 'connectTimeout'
                | 'message'
                | 'reconnect'
                >(
                eventName: T
                ) => NonNullable<State['events'][T]>;

                method getInitialSql

                getInitialSql: () => string;

                method getIsolationLevelText

                getIsolationLevelText: (
                isolationLevel: (typeof ISOLATION_LEVEL)[keyof typeof ISOLATION_LEVEL]
                ) =>
                | 'read uncommitted'
                | 'repeatable read'
                | 'serializable'
                | 'snapshot'
                | 'read committed';

                method initialiseConnection

                initialiseConnection: () => void | Promise<void>;

                method makeRequest

                makeRequest: (
                request: Request | BulkLoad,
                packetType: number,
                payload: (Iterable<Buffer> | AsyncIterable<Buffer>) & {
                toString: (indent?: string) => string;
                }
                ) => void;

                method newBulkLoad

                newBulkLoad: {
                (table: string, callback: BulkLoadCallback): BulkLoad;
                (
                table: string,
                options: BulkLoadOptions,
                callback: BulkLoadCallback
                ): BulkLoad;
                };
                • Creates a new BulkLoad instance.

                  Parameter table

                  The name of the table to bulk-insert into.

                  Parameter options

                  A set of bulk load options.

                method on

                on: {
                (event: 'charsetChange', listener: (charset: string) => void): this;
                (event: 'connect', listener: (err: Error) => void): this;
                (event: 'databaseChange', listener: (databaseName: string) => void): this;
                (event: 'debug', listener: (messageText: string) => void): this;
                (event: 'error', listener: (err: Error) => void): this;
                (
                event: 'errorMessage',
                listener: (message: ErrorMessageToken) => void
                ): this;
                (event: 'end', listener: () => void): this;
                (event: 'infoMessage', listener: (message: InfoMessageToken) => void): this;
                (event: 'languageChange', listener: (languageName: string) => void): this;
                (event: 'resetConnection', listener: () => void): this;
                (event: 'secure', listener: (cleartext: any) => void): this;
                };
                • The server has reported that the charset has changed.

                • The attempt to connect and validate has completed.

                • The server has reported that the active database has changed. This may be as a result of a successful login, or a use statement.

                • A debug message is available. It may be logged or ignored.

                • Internal error occurs.

                • The server has issued an error message.

                • The connection has ended.

                  This may be as a result of the client calling [[close]], the server closing the connection, or a network error.

                • The server has issued an information message.

                • The server has reported that the language has changed.

                • The connection was reset.

                • A secure connection has been established.

                method prepare

                prepare: (request: Request) => void;
                • Prepare the SQL represented by the request.

                  The request can then be used in subsequent calls to [[execute]] and [[unprepare]]

                  Parameter request

                  A [[Request]] object representing the request. Parameters only require a name and type. Parameter values are ignored.

                method processedInitialSql

                processedInitialSql: () => void;

                method requestTimeout

                requestTimeout: () => void;

                method reset

                reset: (callback: ResetCallback) => void;
                • Reset the connection to its initial state. Can be useful for connection pool implementations.

                  Parameter callback

                method retryTimeout

                retryTimeout: () => void;

                method rollbackTransaction

                rollbackTransaction: (
                callback: RollbackTransactionCallback,
                name?: string
                ) => void;
                • Rollback a transaction.

                  There should be an active transaction - that is, [[beginTransaction]] should have been previously called.

                  Parameter callback

                  Parameter name

                  A string representing a name to associate with the transaction. Optional, and defaults to an empty string. Required when isolationLevel is present.

                method saveTransaction

                saveTransaction: (callback: SaveTransactionCallback, name: string) => void;
                • Set a savepoint within a transaction.

                  There should be an active transaction - that is, [[beginTransaction]] should have been previously called.

                  Parameter callback

                  Parameter name

                  A string representing a name to associate with the transaction.\ Optional, and defaults to an empty string. Required when isolationLevel is present.

                method sendFedAuthTokenMessage

                sendFedAuthTokenMessage: (token: string) => void;

                method sendInitialSql

                sendInitialSql: () => void;

                method sendLogin7Packet

                sendLogin7Packet: () => void;

                method sendPreLogin

                sendPreLogin: () => void;

                method socketClose

                socketClose: () => void;

                method socketEnd

                socketEnd: () => void;

                method socketError

                socketError: (error: Error) => void;

                method socketHandlingForSendPreLogin

                socketHandlingForSendPreLogin: (socket: net.Socket) => void;

                  method transaction

                  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;
                  • Run the given callback after starting a transaction, and commit or rollback the transaction afterwards.

                    This is a helper that employs [[beginTransaction]], [[commitTransaction]], [[rollbackTransaction]], and [[saveTransaction]] to greatly simplify the use of database transactions and automatically handle transaction nesting.

                    Parameter cb

                    Parameter isolationLevel

                    The isolation level that the transaction is to be run with.

                    The isolation levels are available from require('tedious').ISOLATION_LEVEL. * READ_UNCOMMITTED * READ_COMMITTED * REPEATABLE_READ * SERIALIZABLE * SNAPSHOT

                    Optional, and defaults to the Connection's isolation level.

                  method transitionTo

                  transitionTo: (newState: State) => void;

                  method unprepare

                  unprepare: (request: Request) => void;
                  • Release the SQL Server resources associated with a previously prepared request.

                    Parameter request

                    A [[Request]] object representing the request. Parameters only require a name and type. Parameter values are ignored.

                  method wrapWithTls

                  wrapWithTls: (socket: net.Socket, signal: AbortSignal) => Promise<tls.TLSSocket>;

                    class ConnectionError

                    class ConnectionError extends Error {}

                      constructor

                      constructor(message: string, code?: string);

                        property code

                        code: string;

                          property isTransient

                          isTransient: boolean;

                            class Request

                            class Request extends EventEmitter {}
                            • const { Request } = require('tedious');
                              const request = new Request("select 42, 'hello world'", (err, rowCount) {
                              // Request completion callback...
                              });
                              connection.execSql(request);

                            constructor

                            constructor(
                            sqlTextOrProcedure: string,
                            callback: CompletionCallback,
                            options?: RequestOptions
                            );
                            • Parameter sqlTextOrProcedure

                              The SQL statement to be executed

                              Parameter callback

                              The callback to execute once the request has been fully completed.

                            property callback

                            callback: CompletionCallback;

                            property canceled

                            canceled: boolean;

                            property connection

                            connection: Connection;

                            property cryptoMetadataLoaded

                            cryptoMetadataLoaded: boolean;

                              property error

                              error: Error;

                              property handle

                              handle: number;

                              property parameters

                              parameters: Parameter[];

                              property parametersByName

                              parametersByName: { [key: string]: Parameter };

                              property paused

                              paused: boolean;

                              property preparing

                              preparing: boolean;

                              property rowCount

                              rowCount?: number;

                              property rows

                              rows?: any[];

                              property rst

                              rst?: any[];

                              property shouldHonorAE

                              shouldHonorAE?: boolean;

                                property sqlTextOrProcedure

                                sqlTextOrProcedure: string;

                                property statementColumnEncryptionSetting

                                statementColumnEncryptionSetting: SQLServerStatementColumnEncryptionSetting;

                                  property timeout

                                  timeout: number;

                                  property userCallback

                                  userCallback: CompletionCallback;

                                  method addOutputParameter

                                  addOutputParameter: (
                                  name: string,
                                  type: DataType,
                                  value?: unknown,
                                  options?: Readonly<ParameterOptions> | null
                                  ) => void;
                                  • Parameter name

                                    The parameter name. This should correspond to a parameter in the SQL, or a parameter that a called procedure expects.

                                    Parameter type

                                    One of the supported data types.

                                    Parameter value

                                    The value that the parameter is to be given. The Javascript type of the argument should match that documented for data types

                                    Parameter options

                                    Additional type options. Optional.

                                  method addParameter

                                  addParameter: (
                                  name: string,
                                  type: DataType,
                                  value?: unknown,
                                  options?: Readonly<ParameterOptions> | null
                                  ) => void;
                                  • Parameter name

                                    The parameter name. This should correspond to a parameter in the SQL, or a parameter that a called procedure expects. The name should not start with @.

                                    Parameter type

                                    One of the supported data types.

                                    Parameter value

                                    The value that the parameter is to be given. The Javascript type of the argument should match that documented for data types.

                                    Parameter options

                                    Additional type options. Optional.

                                  method cancel

                                  cancel: () => void;
                                  • Cancels a request while waiting for a server response.

                                  method emit

                                  emit: {
                                  (
                                  event: 'columnMetadata',
                                  columns: ColumnMetadata[] | { [key: string]: ColumnMetadata }
                                  ): boolean;
                                  (event: 'prepared'): boolean;
                                  (event: 'error', err: Error): boolean;
                                  (event: 'row', columns: any): boolean;
                                  (event: 'done', rowCount: number, more: boolean, rst?: any[]): boolean;
                                  (event: 'doneInProc', rowCount: number, more: boolean, rst?: any[]): boolean;
                                  (
                                  event: 'doneProc',
                                  rowCount: number,
                                  more: boolean,
                                  procReturnStatusValue: number,
                                  rst?: any[]
                                  ): boolean;
                                  (
                                  event: 'returnValue',
                                  parameterName: string,
                                  value: unknown,
                                  metadata: Metadata
                                  ): boolean;
                                  (event: 'requestCompleted'): boolean;
                                  (event: 'cancel'): boolean;
                                  (event: 'pause'): boolean;
                                  (event: 'resume'): boolean;
                                  (event: 'order', orderColumns: number[]): boolean;
                                  };

                                  method makeParamsParameter

                                  makeParamsParameter: (parameters: Parameter[]) => string;

                                  method on

                                  on: {
                                  (
                                  event: 'columnMetadata',
                                  listener: (
                                  columns: ColumnMetadata[] | { [key: string]: ColumnMetadata }
                                  ) => void
                                  ): this;
                                  (event: 'prepared', listener: () => void): this;
                                  (event: 'error', listener: (err: Error) => void): this;
                                  (event: 'row', listener: (columns: any) => void): this;
                                  (
                                  event: 'done',
                                  listener: (rowCount: number, more: boolean, rst?: any[]) => void
                                  ): this;
                                  (
                                  event: 'doneInProc',
                                  listener: (rowCount: number, more: boolean, rst?: any[]) => void
                                  ): this;
                                  (
                                  event: 'doneProc',
                                  listener: (
                                  rowCount: number,
                                  more: boolean,
                                  procReturnStatusValue: number,
                                  rst?: any[]
                                  ) => void
                                  ): this;
                                  (
                                  event: 'returnValue',
                                  listener: (
                                  parameterName: string,
                                  value: unknown,
                                  metadata: Metadata
                                  ) => void
                                  ): this;
                                  (event: 'order', listener: (orderColumns: number[]) => void): this;
                                  (event: 'requestCompleted', listener: () => void): this;
                                  (event: 'cancel', listener: () => void): this;
                                  (event: 'pause', listener: () => void): this;
                                  (event: 'resume', listener: () => void): this;
                                  };
                                  • This event, describing result set columns, will be emitted before row events are emitted. This event may be emitted multiple times when more than one recordset is produced by the statement.

                                    An array like object, where the columns can be accessed either by index or name. Columns with a name that is an integer are not accessible by name, as it would be interpreted as an array index.

                                  • The request has been prepared and can be used in subsequent calls to execute and unprepare.

                                  • The request encountered an error and has not been prepared.

                                  • A row resulting from execution of the SQL statement.

                                  • All rows from a result set have been provided (through row events).

                                    This token is used to indicate the completion of a SQL statement. As multiple SQL statements can be sent to the server in a single SQL batch, multiple done can be generated. An done event is emitted for each SQL statement in the SQL batch except variable declarations. For execution of SQL statements within stored procedures, doneProc and doneInProc events are used in place of done.

                                    If you are using [[Connection.execSql]] then SQL server may treat the multiple calls with the same query as a stored procedure. When this occurs, the doneProc and doneInProc events may be emitted instead. You must handle both events to ensure complete coverage.

                                  • request.on('doneInProc', function (rowCount, more, rows) { });

                                    Indicates the completion status of a SQL statement within a stored procedure. All rows from a statement in a stored procedure have been provided (through row events).

                                    This event may also occur when executing multiple calls with the same query using [[execSql]].

                                  • Indicates the completion status of a stored procedure. This is also generated for stored procedures executed through SQL statements.\ This event may also occur when executing multiple calls with the same query using [[execSql]].

                                  • A value for an output parameter (that was added to the request with [[addOutputParameter]]). See also Using Parameters.

                                  • This event gives the columns by which data is ordered, if ORDER BY clause is executed in SQL Server.

                                  method pause

                                  pause: () => void;
                                  • Temporarily suspends the flow of data from the database. No more row events will be emitted until [[resume] is called. If this request is already in a paused state, calling [[pause]] has no effect.

                                  method resume

                                  resume: () => void;
                                  • Resumes the flow of data from the database. If this request is not in a paused state, calling [[resume]] has no effect.

                                  method setTimeout

                                  setTimeout: (timeout?: number) => void;
                                  • Sets a timeout for this request.

                                    Parameter timeout

                                    The number of milliseconds before the request is considered failed, or 0 for no timeout. When no timeout is set for the request, the [[ConnectionOptions.requestTimeout]] of the [[Connection]] is used.

                                  method validateParameters

                                  validateParameters: (collation: Collation | undefined) => void;

                                  class RequestError

                                  class RequestError extends Error {}

                                    constructor

                                    constructor(message: string, code?: string);

                                      property class

                                      class: number;

                                        property code

                                        code: string;

                                          property lineNumber

                                          lineNumber: number;

                                            property number

                                            number: number;

                                              property procName

                                              procName: string;

                                                property serverName

                                                serverName: string;

                                                  property state

                                                  state: number;

                                                    Interfaces

                                                    interface ConnectionConfiguration

                                                    interface ConnectionConfiguration {}

                                                      property authentication

                                                      authentication?: AuthenticationOptions;
                                                      • Authentication related options for connection.

                                                      property options

                                                      options?: ConnectionOptions;
                                                      • Configuration options for forming the connection.

                                                      property server

                                                      server: string;
                                                      • Hostname to connect to.

                                                      interface ConnectionOptions

                                                      interface ConnectionOptions {}

                                                        property abortTransactionOnError

                                                        abortTransactionOnError?: boolean;
                                                        • A boolean determining whether to rollback a transaction automatically if any error is encountered during the given transaction's execution. This sets the value for SET XACT_ABORT during the initial SQL phase of a connection [documentation](https://docs.microsoft.com/en-us/sql/t-sql/statements/set-xact-abort-transact-sql).

                                                        property appName

                                                        appName?: string | undefined;
                                                        • Application name used for identifying a specific application in profiling, logging or tracing tools of SQLServer.

                                                          (default: Tedious)

                                                        property camelCaseColumns

                                                        camelCaseColumns?: boolean;
                                                        • A boolean, controlling whether the column names returned will have the first letter converted to lower case (true) or not. This value is ignored if you provide a [[columnNameReplacer]].

                                                          (default: false).

                                                        property cancelTimeout

                                                        cancelTimeout?: number;
                                                        • The number of milliseconds before the [[Request.cancel]] (abort) of a request is considered failed

                                                          (default: 5000).

                                                        property columnNameReplacer

                                                        columnNameReplacer?: (
                                                        colName: string,
                                                        index: number,
                                                        metadata: Metadata
                                                        ) => string;
                                                        • A function with parameters (columnName, index, columnMetaData) and returning a string. If provided, this will be called once per column per result-set. The returned value will be used instead of the SQL-provided column name on row and meta data objects. This allows you to dynamically convert between naming conventions.

                                                          (default: null)

                                                        property connectionIsolationLevel

                                                        connectionIsolationLevel?: number;
                                                        • The default isolation level for new connections. All out-of-transaction queries are executed with this setting.

                                                          The isolation levels are available from require('tedious').ISOLATION_LEVEL. * READ_UNCOMMITTED * READ_COMMITTED * REPEATABLE_READ * SERIALIZABLE * SNAPSHOT

                                                          (default: READ_COMMITED).

                                                        property connectionRetryInterval

                                                        connectionRetryInterval?: number;
                                                        • Number of milliseconds before retrying to establish connection, in case of transient failure.

                                                          (default:500)

                                                        property connector

                                                        connector?: () => Promise<net.Socket>;
                                                        • Custom connector factory method.

                                                          (default: undefined)

                                                        property connectTimeout

                                                        connectTimeout?: number;
                                                        • The number of milliseconds before the attempt to connect is considered failed

                                                          (default: 15000).

                                                        property cryptoCredentialsDetails

                                                        cryptoCredentialsDetails?: SecureContextOptions;
                                                        • When encryption is used, an object may be supplied that will be used for the first argument when calling [tls.createSecurePair](http://nodejs.org/docs/latest/api/tls.html#tls_tls_createsecurepair_credentials_isserver_requestcert_rejectunauthorized)

                                                          (default: {})

                                                        property database

                                                        database?: string | undefined;
                                                        • Database to connect to (default: dependent on server configuration).

                                                        property datefirst

                                                        datefirst?: number;
                                                        • Sets the first day of the week to a number from 1 through 7.

                                                        property dateFormat

                                                        dateFormat?: string;
                                                        • A string representing position of month, day and year in temporal datatypes.

                                                          (default: mdy)

                                                        property debug

                                                        debug?: DebugOptions;

                                                          property enableAnsiNull

                                                          enableAnsiNull?: boolean;
                                                          • A boolean, controls the way null values should be used during comparison operation.

                                                            (default: true)

                                                          property enableAnsiNullDefault

                                                          enableAnsiNullDefault?: boolean;
                                                          • If true, SET ANSI_NULL_DFLT_ON ON will be set in the initial sql. This means new columns will be nullable by default. See the [T-SQL documentation](https://msdn.microsoft.com/en-us/library/ms187375.aspx)

                                                            (default: true).

                                                          property enableAnsiPadding

                                                          enableAnsiPadding?: boolean;
                                                          • A boolean, controls if padding should be applied for values shorter than the size of defined column.

                                                            (default: true)

                                                          property enableAnsiWarnings

                                                          enableAnsiWarnings?: boolean;
                                                          • If true, SQL Server will follow ISO standard behavior during various error conditions. For details, see [documentation](https://docs.microsoft.com/en-us/sql/t-sql/statements/set-ansi-warnings-transact-sql)

                                                            (default: true)

                                                          property enableArithAbort

                                                          enableArithAbort?: boolean;
                                                          • Ends a query when an overflow or divide-by-zero error occurs during query execution. See [documentation](https://docs.microsoft.com/en-us/sql/t-sql/statements/set-arithabort-transact-sql?view=sql-server-2017) for more details.

                                                            (default: true)

                                                          property enableConcatNullYieldsNull

                                                          enableConcatNullYieldsNull?: boolean;
                                                          • A boolean, determines if concatenation with NULL should result in NULL or empty string value, more details in [documentation](https://docs.microsoft.com/en-us/sql/t-sql/statements/set-concat-null-yields-null-transact-sql)

                                                            (default: true)

                                                          property enableCursorCloseOnCommit

                                                          enableCursorCloseOnCommit?: boolean | null;
                                                          • A boolean, controls whether cursor should be closed, if the transaction opening it gets committed or rolled back.

                                                            (default: null)

                                                          property enableImplicitTransactions

                                                          enableImplicitTransactions?: boolean;
                                                          • A boolean, sets the connection to either implicit or autocommit transaction mode.

                                                            (default: false)

                                                          property enableNumericRoundabort

                                                          enableNumericRoundabort?: boolean;
                                                          • If false, error is not generated during loss of precession.

                                                            (default: false)

                                                          property enableQuotedIdentifier

                                                          enableQuotedIdentifier?: boolean;
                                                          • If true, characters enclosed in single quotes are treated as literals and those enclosed double quotes are treated as identifiers.

                                                            (default: true)

                                                          property encrypt

                                                          encrypt?: string | boolean;
                                                          • A string value that can be only set to 'strict', which indicates the usage TDS 8.0 protocol. Otherwise, a boolean determining whether or not the connection will be encrypted.

                                                            (default: true)

                                                          property fallbackToDefaultDb

                                                          fallbackToDefaultDb?: boolean;
                                                          • By default, if the database requested by [[database]] cannot be accessed, the connection will fail with an error. However, if [[fallbackToDefaultDb]] is set to true, then the user's default database will be used instead

                                                            (default: false)

                                                          property instanceName

                                                          instanceName?: string | undefined;
                                                          • The instance name to connect to. The SQL Server Browser service must be running on the database server, and UDP port 1434 on the database server must be reachable.

                                                            (no default)

                                                            Mutually exclusive with [[port]].

                                                          property isolationLevel

                                                          isolationLevel?: number;
                                                          • The default isolation level that transactions will be run with.

                                                            The isolation levels are available from require('tedious').ISOLATION_LEVEL. * READ_UNCOMMITTED * READ_COMMITTED * REPEATABLE_READ * SERIALIZABLE * SNAPSHOT

                                                            (default: READ_COMMITED).

                                                          property language

                                                          language?: string;
                                                          • Specifies the language environment for the session. The session language determines the datetime formats and system messages.

                                                            (default: us_english).

                                                          property localAddress

                                                          localAddress?: string | undefined;
                                                          • A string indicating which network interface (ip address) to use when connecting to SQL Server.

                                                          property lowerCaseGuids

                                                          lowerCaseGuids?: boolean;
                                                          • A boolean determining whether to parse unique identifier type with lowercase case characters.

                                                            (default: false).

                                                          property maxRetriesOnTransientErrors

                                                          maxRetriesOnTransientErrors?: number;
                                                          • The maximum number of connection retries for transient errors.、

                                                            (default: 3).

                                                          property multiSubnetFailover

                                                          multiSubnetFailover?: boolean;
                                                          • Sets the MultiSubnetFailover = True parameter, which can help minimize the client recovery latency when failovers occur.

                                                            (default: false).

                                                          property packetSize

                                                          packetSize?: number;
                                                          • The size of TDS packets (subject to negotiation with the server). Should be a power of 2.

                                                            (default: 4096).

                                                          property port

                                                          port?: number;
                                                          • Port to connect to (default: 1433).

                                                            Mutually exclusive with [[instanceName]]

                                                          property readOnlyIntent

                                                          readOnlyIntent?: boolean;
                                                          • A boolean, determining whether the connection will request read only access from a SQL Server Availability Group. For more information, see [here](http://msdn.microsoft.com/en-us/library/hh710054.aspx "Microsoft: Configure Read-Only Routing for an Availability Group (SQL Server)")

                                                            (default: false).

                                                          property requestTimeout

                                                          requestTimeout?: number;
                                                          • The number of milliseconds before a request is considered failed, or 0 for no timeout.

                                                            As soon as a response is received, the timeout is cleared. This means that queries that immediately return a response have ability to run longer than this timeout.

                                                            (default: 15000).

                                                          property rowCollectionOnDone

                                                          rowCollectionOnDone?: boolean;
                                                          • A boolean, that when true will expose received rows in Requests done related events: * [[Request.Event_doneInProc]] * [[Request.Event_doneProc]] * [[Request.Event_done]]

                                                            (default: false)

                                                            Caution: If many row are received, enabling this option could result in excessive memory usage.

                                                          property rowCollectionOnRequestCompletion

                                                          rowCollectionOnRequestCompletion?: boolean;
                                                          • A boolean, that when true will expose received rows in Requests' completion callback.See [[Request.constructor]].

                                                            (default: false)

                                                            Caution: If many row are received, enabling this option could result in excessive memory usage.

                                                          property serverName

                                                          serverName?: string;

                                                          property tdsVersion

                                                          tdsVersion?: string;
                                                          • The version of TDS to use. If server doesn't support specified version, negotiated version is used instead.

                                                            The versions are available from require('tedious').TDS_VERSION. * 7_1 * 7_2 * 7_3_A * 7_3_B * 7_4

                                                            (default: 7_4)

                                                          property textsize

                                                          textsize?: string;
                                                          • Specifies the size of varchar(max), nvarchar(max), varbinary(max), text, ntext, and image data returned by a SELECT statement.

                                                            (default: 2147483647)

                                                          property trustServerCertificate

                                                          trustServerCertificate?: boolean;
                                                          • If "true", the SQL Server SSL certificate is automatically trusted when the communication layer is encrypted using SSL.

                                                            If "false", the SQL Server validates the server SSL certificate. If the server certificate validation fails, the driver raises an error and terminates the connection. Make sure the value passed to serverName exactly matches the Common Name (CN) or DNS name in the Subject Alternate Name in the server certificate for an SSL connection to succeed.

                                                            (default: true)

                                                          property useColumnNames

                                                          useColumnNames?: boolean;
                                                          • A boolean determining whether to return rows as arrays or key-value collections.

                                                            (default: false).

                                                          property useUTC

                                                          useUTC?: boolean;
                                                          • A boolean determining whether to pass time values in UTC or local time.

                                                            (default: true).

                                                          property workstationId

                                                          workstationId?: string | undefined;
                                                          • The workstation ID (WSID) of the client, default os.hostname(). Used for identifying a specific client in profiling, logging or tracing client activity in SQLServer.

                                                            The value is reported by the TSQL function HOST_NAME().

                                                          Type Aliases

                                                          type ConnectionAuthentication

                                                          type ConnectionAuthentication =
                                                          | DefaultAuthentication
                                                          | NtlmAuthentication
                                                          | AzureActiveDirectoryPasswordAuthentication
                                                          | AzureActiveDirectoryMsiAppServiceAuthentication
                                                          | AzureActiveDirectoryMsiVmAuthentication
                                                          | AzureActiveDirectoryAccessTokenAuthentication
                                                          | AzureActiveDirectoryServicePrincipalSecret
                                                          | AzureActiveDirectoryDefaultAuthentication;

                                                            Namespaces

                                                            namespace js-md4

                                                            module 'js-md4' {}

                                                              variable md4

                                                              const md4: { arrayBuffer(message: string | ArrayBuffer): ArrayBuffer };

                                                                namespace native-duplexpair

                                                                module 'native-duplexpair' {}

                                                                  class DuplexPair

                                                                  class DuplexPair {}

                                                                    property socket1

                                                                    socket1: DuplexSocket;

                                                                      property socket2

                                                                      socket2: DuplexSocket;

                                                                        Package Files (10)

                                                                        Dependencies (9)

                                                                        Dev Dependencies (28)

                                                                        Peer Dependencies (0)

                                                                        No peer dependencies.

                                                                        Badge

                                                                        To add a badge like this onejsDocs.io badgeto your package's README, use the codes available below.

                                                                        You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/tedious.

                                                                        • Markdown
                                                                          [![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/tedious)
                                                                        • HTML
                                                                          <a href="https://www.jsdocs.io/package/tedious"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>