### Database Configuration Example Source: https://github.com/tediousjs/node-mssql/blob/master/_autodocs/configuration.md Example of specifying the initial database to connect to. ```javascript const config = { database: 'master' } ``` -------------------------------- ### Port Configuration Example Source: https://github.com/tediousjs/node-mssql/blob/master/_autodocs/configuration.md Example of explicitly setting the SQL Server port number when it's not the default. ```javascript const config = { server: 'myserver', port: 1433 } ``` -------------------------------- ### Install Dependencies Source: https://github.com/tediousjs/node-mssql/blob/master/CONTRIBUTING.md Install project dependencies using npm. This is a required step for setting up the development environment. ```bash npm install ``` -------------------------------- ### User Authentication Configuration Source: https://github.com/tediousjs/node-mssql/blob/master/_autodocs/configuration.md Example of configuring user authentication with username and password. ```javascript const config = { user: 'sa', password: 'password' } ``` -------------------------------- ### Complete Example: Using Global Pool Source: https://github.com/tediousjs/node-mssql/blob/master/_autodocs/api-reference/Global-Functions.md Demonstrates connecting to a database using the global pool, executing queries, handling errors, and closing the connection. ```javascript const sql = require('mssql') const config = { user: 'sa', password: 'password', server: 'localhost', database: 'mydb' } // Handle errors on global pool sql.on('error', err => { console.error('Global pool error:', err.message) }) async function main() { try { // Connect (or reuse existing global pool) await sql.connect(config) console.log('Connected to database') // Simple query const result = await sql.query('SELECT @@version AS version') console.log('SQL Server version:', result.recordset[0].version) // Create a request for parameterized query const request = new sql.Request() request.input('userId', sql.Int, 1) const user = await request.query('SELECT * FROM users WHERE id = @userId') console.log('User:', user.recordset[0]) } catch (err) { console.error('Error:', err.message) } finally { // Close global pool when done await sql.close() console.log('Disconnected from database') } } main() ``` -------------------------------- ### Server Connection Examples Source: https://github.com/tediousjs/node-mssql/blob/master/_autodocs/configuration.md Demonstrates various ways to specify the server, including default instance, Azure, named instances, IP addresses, and explicit ports. ```javascript const config = { server: 'localhost', // Default instance server: 'myserver.database.windows.net', // Azure server: 'myserver\\SQLEXPRESS', // Named instance server: '192.168.1.1', // IP address server: 'localhost,1433' // Explicit port in server string } ``` -------------------------------- ### Windows Authentication Configuration Source: https://github.com/tediousjs/node-mssql/blob/master/_autodocs/configuration.md Example configuration for Windows authentication using NTLM. Credentials are read from environment variables. ```javascript const config = { server: 'myserver', database: 'mydb', options: { authentication: { type: 'ntlm', options: { userName: process.env.USERNAME, password: process.env.PASSWORD } } } } ``` -------------------------------- ### Connection Timeout Configuration Source: https://github.com/tediousjs/node-mssql/blob/master/_autodocs/configuration.md Example of setting a custom connection timeout in milliseconds. ```javascript const config = { connectionTimeout: 30000 // 30 seconds } ``` -------------------------------- ### Configure Connection Pool Source: https://github.com/tediousjs/node-mssql/blob/master/README.md Example configuration object for setting up a connection pool with specific parameters like max connections, min connections, and idle timeout. ```javascript const config = { user: '...', password: '...', server: 'localhost', database: '...', pool: { max: 10, min: 0, idleTimeoutMillis: 30000 } } ``` -------------------------------- ### Complete Prepared Statement Example Source: https://github.com/tediousjs/node-mssql/blob/master/_autodocs/api-reference/PreparedStatement.md Demonstrates the full lifecycle of a prepared statement, including connection pooling, input/output parameters, multiple executions within a loop, and proper cleanup. ```javascript const sql = require('mssql') const pool = new sql.ConnectionPool({ /* config */ }) await pool.connect() // Prepare a statement const ps = new sql.PreparedStatement(pool) ps.input('id', sql.Int) ps.input('status', sql.VarChar(20)) ps.output('totalCount', sql.Int) try { // Prepare the statement once await ps.prepare( 'SELECT *\n FROM orders\n WHERE id = @id AND status = @status' ) // Execute multiple times with different parameters const results = [] for (let id = 1; id <= 100; id++) { const result = await ps.execute({ id, status: 'pending' }) results.push(result.recordset) } console.log(`Executed 100 queries efficiently`) } finally { // Always unprepare await ps.unprepare() await pool.close() } ``` -------------------------------- ### Global Pool Usage Example Source: https://github.com/tediousjs/node-mssql/blob/master/_autodocs/api-reference/Global-Functions.md Demonstrates how to use the global connection pool for database operations, including connection, querying, and error handling. ```APIDOC ## Complete Example: Using Global Pool ```javascript const sql = require('mssql') const config = { user: 'sa', password: 'password', server: 'localhost', database: 'mydb' } // Handle errors on global pool sql.on('error', err => { console.error('Global pool error:', err.message) }) async function main() { try { // Connect (or reuse existing global pool) await sql.connect(config) console.log('Connected to database') // Simple query const result = await sql.query('SELECT @@version AS version') console.log('SQL Server version:', result.recordset[0].version) // Create a request for parameterized query const request = new sql.Request() request.input('userId', sql.Int, 1) const user = await request.query('SELECT * FROM users WHERE id = @userId') console.log('User:', user.recordset[0]) } catch (err) { console.error('Error:', err.message) } finally { // Close global pool when done await sql.close() console.log('Disconnected from database') } } main() ``` ## Source `lib/global-connection.js` ``` -------------------------------- ### Connect to Database and Execute Basic Query Source: https://github.com/tediousjs/node-mssql/blob/master/_autodocs/INDEX.md Establishes a connection to the SQL Server database using provided configuration and executes a parameterized SELECT query. Ensure you have the 'mssql' package installed and replace placeholder credentials with your actual database details. ```javascript const sql = require('mssql') const config = { user: 'sa', password: 'password', server: 'localhost', database: 'mydb' } const pool = await sql.connect(config) const result = await pool.request() .input('id', sql.Int, 1) .query('SELECT * FROM users WHERE id = @id') console.log(result.recordset) await pool.close() ``` -------------------------------- ### Development (Local) Connection Configuration Source: https://github.com/tediousjs/node-mssql/blob/master/_autodocs/configuration.md Example configuration for a local development environment using SQL Server authentication. Includes options for disabling encryption and trusting server certificates. ```javascript const config = { user: 'sa', password: 'DevPassword123', server: 'localhost', database: 'mydb', options: { encrypt: false, trustServerCertificate: true } } ``` -------------------------------- ### Stream Mode Configuration Source: https://github.com/tediousjs/node-mssql/blob/master/_autodocs/configuration.md Example of enabling stream mode for all requests on a connection pool. ```javascript const config = { stream: true // All requests stream by default } // Per-request override const request = new Request(pool) request.stream = false // Override pool setting ``` -------------------------------- ### Classic Connection String (Tedious) Source: https://github.com/tediousjs/node-mssql/blob/master/README.md Example of a standard connection string for the tedious driver, including server, database, user ID, password, and encryption settings. ```plaintext Server=localhost,1433;Database=database;User Id=username;Password=password;Encrypt=true ``` -------------------------------- ### Attach Event Handlers Before Connection (Tedious Driver) Source: https://github.com/tediousjs/node-mssql/blob/master/README.md This example demonstrates how to attach event handlers for 'connect' and 'end' events before establishing a connection using the Tedious driver. The `beforeConnect` function receives the configured `Connection` object. ```javascript require('mssql').connect({...config, beforeConnect: conn => { conn.once('connect', err => { err ? console.error(err) : console.log('mssql connected')}) conn.once('end', err => { err ? console.error(err) : console.log('mssql disconnected')}) }}) ``` -------------------------------- ### Before Connect Hook Configuration Source: https://github.com/tediousjs/node-mssql/blob/master/_autodocs/configuration.md Define a hook function to execute logic before a connection is established. This example logs connection and disconnection events. ```javascript const config = { options: { beforeConnect: (connection) => { connection.once('connect', () => { console.log('Connected!') }) connection.once('end', () => { console.log('Disconnected!') }) } } } ``` -------------------------------- ### Listen for Transaction Begin Event Source: https://github.com/tediousjs/node-mssql/blob/master/_autodocs/api-reference/Transaction.md Attaches an event listener to the 'begin' event, which is dispatched when the transaction successfully starts. ```javascript transaction.on('begin', () => { console.log('Transaction started') }) ``` -------------------------------- ### Handling ENOTBEGUN Transaction Error Source: https://github.com/tediousjs/node-mssql/blob/master/_autodocs/errors.md Example of attempting to use a transaction before calling begin(). ```javascript // ENOTBEGUN - Using transaction before begin() const transaction = new Transaction(pool) try { const request = new Request(transaction) await request.query('SELECT 1') } catch (err) { console.log(err.code) // 'ENOTBEGUN' console.log(err.message) // 'Transaction has not begun. Call begin() first.' } ``` -------------------------------- ### Handling ELOGIN Error Source: https://github.com/tediousjs/node-mssql/blob/master/_autodocs/errors.md Example of a login failure due to incorrect credentials. ```javascript // ELOGIN - Invalid credentials try { await pool.connect({ user: 'sa', password: 'wrongpassword', server: 'localhost' }) } catch (err) { console.log(err.code) // 'ELOGIN' console.log(err.message) // 'Login failed...' } ``` -------------------------------- ### Handling ECANCEL: User Cancellation Source: https://github.com/tediousjs/node-mssql/blob/master/_autodocs/errors.md Shows how to handle a query cancellation. This example initiates a long-running query and then cancels it using `request.cancel()` before it completes. ```javascript // ECANCEL - User cancelled const request = new Request() const promise = request.query('WAITFOR DELAY \'00:00:10\'') setTimeout(() => { request.cancel() }, 100) try { await promise } catch (err) { console.log(err.code) // 'ECANCEL' } ``` -------------------------------- ### Request Timeout Configuration Source: https://github.com/tediousjs/node-mssql/blob/master/_autodocs/configuration.md Example of setting a custom request timeout in milliseconds for query execution. ```javascript const config = { requestTimeout: 60000 // 60 seconds } ``` -------------------------------- ### Domain Authentication Configuration Source: https://github.com/tediousjs/node-mssql/blob/master/_autodocs/configuration.md Example of configuring domain authentication, where the domain property overrides user and password. ```javascript const config = { domain: 'MYCOMPANY\\', // user and password are ignored } ``` -------------------------------- ### Classic Connection String (MSNodeSQLv8) Source: https://github.com/tediousjs/node-mssql/blob/master/README.md Example of a standard connection string for the msnodesqlv8 driver, specifying the driver, server instance, database, user ID, password, and encryption. ```plaintext Driver=msnodesqlv8;Server=(local)\INSTANCE;Database=database;UID=DOMAIN\username;PWD=password;Encrypt=true ``` -------------------------------- ### Configuration Immutability Example Source: https://github.com/tediousjs/node-mssql/blob/master/_autodocs/configuration.md Demonstrates that configuration objects are immutable after being passed to the ConnectionPool constructor in v12.x+. Mutating the config object leads to undefined behavior. ```javascript const config = { server: 'localhost', database: 'mydb' } const pool = new ConnectionPool(config) // Don't do this: config.server = 'otherserver' // Undefined behavior ``` -------------------------------- ### Catching PreparedStatementError Source: https://github.com/tediousjs/node-mssql/blob/master/_autodocs/errors.md Shows how to catch `PreparedStatementError` and inspect its `code` property. This example specifically demonstrates catching the 'EALREADYPREPARED' error when attempting to prepare a statement twice. ```javascript const { PreparedStatementError } = require('mssql') try { const ps = new PreparedStatement() await ps.prepare('SELECT 1') await ps.prepare('SELECT 2') // Error } catch (err) { if (err instanceof PreparedStatementError) { console.error(err.code) // 'EALREADYPREPARED' } } ``` -------------------------------- ### Begin Transaction Source: https://github.com/tediousjs/node-mssql/blob/master/_autodocs/api-reference/Transaction.md Start a new database transaction. You can specify a custom isolation level or use the default. A callback can be provided for older callback-style error handling. ```javascript const transaction = new Transaction(pool) // Default isolation level await transaction.begin() // With specific isolation level await transaction.begin(sql.ISOLATION_LEVEL.SERIALIZABLE) // Callback style transaction.begin((err) => { if (err) throw err console.log('Transaction started') }) ``` -------------------------------- ### Request Class - Execute Queries Source: https://github.com/tediousjs/node-mssql/blob/master/_autodocs/MANIFEST.txt Documentation for executing SQL queries using the Request class. Covers parameter tables, return type specifications, and real-world usage examples. ```APIDOC ## Request Class ### Description The `Request` class is used to execute SQL queries and commands against a database connection. ### Methods - **query(sql)**: Executes a SQL query. - **bulk(data)**: Performs bulk insert operations. - **stream(sql)**: Executes a SQL query and returns a stream of results. ### Parameters #### Request.query(sql) - **sql** (string) - Required - The SQL query to execute. #### Request.bulk(data) - **data** (Array) - Required - An array of objects representing the data to be inserted in bulk. #### Request.stream(sql) - **sql** (string) - Required - The SQL query to execute. ### Response #### Success Response (query/stream) - **recordset** (Array) - The result set of the query. - **rowsAffected** (number) - The number of rows affected by the query. #### Success Response (bulk) - **rowsAffected** (number) - The number of rows affected by the bulk operation. ### Example ```javascript const sql = require('mssql'); async function executeQuery(pool) { const request = pool.request(); const result = await request.query('SELECT 1 as number'); console.dir(result); } ``` ### Source File - lib/base/request.js ``` -------------------------------- ### Handle Aborted Transactions with Rollback Source: https://github.com/tediousjs/node-mssql/blob/master/README.md This example demonstrates correct error handling for transactions when `XACT_ABORT` is enabled. It listens for the 'rollback' event to manage state and performs a rollback if an error occurs before commit. ```javascript const transaction = new sql.Transaction(/* [pool] */) transaction.begin(err => { // ... error checks let rolledBack = false transaction.on('rollback', aborted => { // emited with aborted === true rolledBack = true }) new sql.Request(transaction) .query('insert into mytable (bitcolumn) values (2)', (err, result) => { // insert should fail because of invalid value if (err) { if (!rolledBack) { transaction.rollback(err => { // ... error checks }) } } else { transaction.commit(err => { // ... error checks }) } }) }) ``` -------------------------------- ### Example TDS Traffic Log Output Source: https://github.com/tediousjs/node-mssql/wiki/Debugging-TDS This is an example of the detailed TDS traffic logs that are generated when debugging is enabled. These logs contain sensitive information like credentials. ```text connected to 192.168.5.130:1433 Sent type:0x12(PRELOGIN), status:0x01(EOM), length:0x002F, spid:0x0000, packetId:0x01, window:0x00 0000 00001A00 06010020 00010200 21000103 00220004 04002600 01FF0000 00010001 ....... ....!... ."....&. ........ 0020 02000000 000000 ....... PreLogin - version:0.0.0.1 1, encryption:0x02(NOT_SUP), instopt:0x00, threadId:0x00000000, mars:0x00(OFF) State change: Connecting -> SentPrelogin Received type:0x04(TABULAR_RESULT), status:0x01(EOM), length:0x002B, spid:0x0000, packetId:0x01, window:0x00 0000 00001A00 06010020 00010200 21000103 00220000 04002200 01FF0B00 08340000 ....... ....!... ."....". .....4.. 0020 020000 ... PreLogin - version:11.0.8.52 0, encryption:0x02(NOT_SUP), instopt:0x00, threadId:0x00000000, mars:0x00(OFF) ``` -------------------------------- ### Get Affected Rows using Streaming Source: https://github.com/tediousjs/node-mssql/blob/master/README.md This snippet demonstrates how to get the number of affected rows during streaming operations. The 'rowsaffected' event provides the count for each completed statement. ```javascript const request = new sql.Request() request.stream = true request.query('update myAwesomeTable set awesomness = 100') request.on('rowsaffected', rowCount => { console.log(rowCount) }) request.on('done', result => { console.log(result.rowsAffected) }) ``` -------------------------------- ### Connection String Formats Source: https://github.com/tediousjs/node-mssql/blob/master/_autodocs/configuration.md Illustrates different connection string formats for establishing connections, including Tedious (default), MSNodeSQLv8, and Azure Active Directory. ```javascript // Tedious (default) 'Server=localhost,1433;Database=mydb;User Id=sa;Password=password;Encrypt=true' ``` ```javascript // MSNodeSQLv8 'Driver={ODBC Driver 18 for SQL Server};Server=(local)\\INSTANCE;Database=mydb;Uid=sa;Pwd=password' ``` ```javascript // Azure Active Directory 'Server=mydb.database.windows.net;Database=mydb;Authentication=Active Directory Integrated;Client Id=client_id;Client Secret=secret;Tenant Id=tenant_id' ``` -------------------------------- ### sql.Promise Source: https://github.com/tediousjs/node-mssql/blob/master/_autodocs/api-reference/Global-Functions.md Get or set the Promise implementation used throughout the library. Defaults to native Promise. ```APIDOC ## sql.Promise ### Description Get or set the Promise implementation used throughout the library. ### Type `typeof Promise` ### Default Native `Promise` ### Example ```javascript // Use a custom Promise library const Bluebird = require('bluebird') sql.Promise = Bluebird // Now all methods return Bluebird promises const pool = await sql.connect(config) // Returns Bluebird promise ``` ``` -------------------------------- ### Connection Pool Creation Source: https://github.com/tediousjs/node-mssql/blob/master/README.md Demonstrates how to create a new ConnectionPool instance. ```APIDOC ## Connections Internally, each `ConnectionPool` instance is a separate pool of TDS connections. Once you create a new `Request`/`Transaction`/`Prepared Statement`, a new TDS connection is acquired from the pool and reserved for desired action. Once the action is complete, connection is released back to the pool. Connection health check is built-in so once the dead connection is discovered, it is immediately replaced with a new one. **IMPORTANT**: Always attach an `error` listener to created connection. Whenever something goes wrong with the connection it will emit an error and if there is no listener it will crash your application with an uncaught error. ```javascript const pool = new sql.ConnectionPool({ /* config */ }) ``` ``` -------------------------------- ### connect(config, [callback]) Source: https://github.com/tediousjs/node-mssql/blob/master/_autodocs/api-reference/Global-Functions.md Opens or reuses the global connection pool. It can accept a configuration object or a connection string. If the pool doesn't exist, it's created; otherwise, the existing pool is returned or awaited. ```APIDOC ## connect(config, [callback]) ### Description Opens or reuses the global connection pool. It can accept a configuration object or a connection string. If the pool doesn't exist, it's created; otherwise, the existing pool is returned or awaited. ### Method connect ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **config** (Object | String) - Required - Connection configuration object or connection string - **callback** (Function) - Optional - Callback when connection succeeds or fails ### Returns `Promise` - Resolves with the connected global pool if callback is omitted ### Example ```javascript // Promise-based const pool = await sql.connect('Server=localhost;Database=mydb;User Id=sa;Password=pwd') // Callback-based sql.connect(config, (err, pool) => { if (err) throw err console.log('Connected') }) ``` ``` -------------------------------- ### declare(type) Source: https://github.com/tediousjs/node-mssql/blob/master/_autodocs/types.md Get the SQL declaration string for a given type. This is useful for dynamically generating SQL statements. ```APIDOC ## declare(type) ### Description Get the SQL declaration string for a type. ### Method JavaScript Function ### Signature declare(type: DataType): String ### Parameters #### Path Parameters - **type** (DataType) - Required - The data type to declare. ### Request Example ```javascript const { declare } = require('mssql') console.log(declare(sql.VarChar(100))) // 'VARCHAR(100)' console.log(declare(sql.Decimal(10, 2))) // 'DECIMAL(10,2)' console.log(declare(sql.Int)) // 'INT' ``` ``` -------------------------------- ### Async/Await Query and Stored Procedure Execution Source: https://github.com/tediousjs/node-mssql/blob/master/README.md Demonstrates executing SQL queries and stored procedures using async/await syntax. Includes input parameters and output parameters for stored procedures. Handles connection errors globally. ```javascript const sql = require('mssql') (async function () { try { let pool = await sql.connect(config) let result1 = await pool.request() .input('input_parameter', sql.Int, value) .query('select * from mytable where id = @input_parameter') console.dir(result1) // Stored procedure let result2 = await pool.request() .input('input_parameter', sql.Int, value) .output('output_parameter', sql.VarChar(50)) .execute('procedure_name') console.dir(result2) } catch (err) { // ... error checks } })() sql.on('error', err => { // ... error handler }) ``` -------------------------------- ### connect() Source: https://github.com/tediousjs/node-mssql/blob/master/README.md Creates a new connection pool and performs an initial probe connection to validate the configuration. Can be used with a callback or returns a Promise. ```APIDOC ### connect ([callback]) Create a new connection pool. The initial probe connection is created to find out whether the configuration is valid. __Arguments__ - **callback(err)** - A callback which is called after initial probe connection has established, or an error has occurred. Optional. If omitted, returns [Promise](#promises). __Example__ ```javascript const pool = new sql.ConnectionPool({ user: '...', password: '...', server: 'localhost', database: '...' }) pool.connect(err => { // ... }) ``` __Errors__ - ELOGIN (`ConnectionError`) - Login failed. - ETIMEOUT (`ConnectionError`) - Connection timeout. - EALREADYCONNECTED (`ConnectionError`) - Database is already connected! - EALREADYCONNECTING (`ConnectionError`) - Already connecting to database! - EINSTLOOKUP (`ConnectionError`) - Instance lookup failed. - ESOCKET (`ConnectionError`) - Socket error. ``` -------------------------------- ### Prepare and Execute a Statement Source: https://github.com/tediousjs/node-mssql/blob/master/README.md Prepares a SQL statement with input parameters and then executes it. Remember to unprepare the statement to release the connection. ```javascript const ps = new sql.PreparedStatement(/* [pool] */) ps.input('param', sql.Int) ps.prepare('select @param as value', err => { // ... error checks ps.execute({param: 12345}, (err, result) => { // ... error checks // release the connection after queries are executed ps.unprepare(err => { // ... error checks }) }) }) ``` -------------------------------- ### Set Transaction Isolation Level Source: https://github.com/tediousjs/node-mssql/blob/master/_autodocs/api-reference/Global-Functions.md Configure the isolation level for a transaction using constants from sql.ISOLATION_LEVEL. This example sets the isolation level to SERIALIZABLE. ```javascript const transaction = new sql.Transaction() transaction.isolationLevel = sql.ISOLATION_LEVEL.SERIALIZABLE await transaction.begin() ``` -------------------------------- ### Configure MSSQL CLI Source: https://github.com/tediousjs/node-mssql/blob/master/README.md Create a .mssql.json file to configure the MSSQL CLI. The structure mirrors the standard configuration object. ```json { "user": "...", "password": "...", "server": "localhost", "database": "..." } ``` -------------------------------- ### Example for deprecated Image type Source: https://github.com/tediousjs/node-mssql/blob/master/_autodocs/types.md Demonstrates the usage of the deprecated sql.Image type for large binary data. It is recommended to use sql.VarBinary(sql.MAX) instead. ```javascript // Deprecated - don't use request.input('image', sql.Image, buffer) // Use this instead request.input('image', sql.VarBinary(sql.MAX), buffer) ``` -------------------------------- ### Connect and Query using Config Object Source: https://github.com/tediousjs/node-mssql/blob/master/README.md Connects to SQL Server using a configuration object and executes a query. Environment variables are used for credentials. ```javascript const sql = require('mssql') const sqlConfig = { user: process.env.DB_USER, password: process.env.DB_PWD, database: process.env.DB_NAME, server: 'localhost', pool: { max: 10, min: 0, idleTimeoutMillis: 30000 }, options: { encrypt: true, // for azure trustServerCertificate: false // change to true for local dev / self-signed certs } } (async () => { try { // make sure that any items are correctly URL encoded in the connection string await sql.connect(sqlConfig) const result = await sql.query`select * from mytable where id = ${value}` console.dir(result) } catch (err) { // ... error checks } })() ``` -------------------------------- ### Connect to Database (Async/Await) Source: https://github.com/tediousjs/node-mssql/blob/master/_autodocs/api-reference/ConnectionPool.md Open a connection to the database using the connect method within an async function for cleaner syntax. ```javascript // Async/await await pool.connect() ``` -------------------------------- ### Create Connection Pool with Configuration Object Source: https://github.com/tediousjs/node-mssql/blob/master/_autodocs/api-reference/ConnectionPool.md Instantiate a new ConnectionPool using a configuration object. The pool will attempt to connect immediately if a callback is provided. ```javascript const pool = new ConnectionPool({ user: 'sa', password: 'password', server: 'localhost', database: 'mydb', pool: { max: 10, min: 0 } }) pool.connect(err => { if (err) throw err console.log('Connected') }) ``` -------------------------------- ### Configure Database Connection for Tests Source: https://github.com/tediousjs/node-mssql/wiki/Contributing Create a `test/.mssql.json` file to specify your database connection details for running tests. Ensure sensitive information is handled appropriately. ```json { "user": "...", "password": "...", "server": "localhost", "database": "master", "options": { "encrypt": false } } ``` -------------------------------- ### Parse JSON Configuration Source: https://github.com/tediousjs/node-mssql/blob/master/_autodocs/configuration.md Example of enabling automatic JSON parsing for specific columns in result sets. Note the required column naming convention. ```javascript const config = { parseJSON: true } // Query: SELECT 1 AS a FOR JSON PATH // Without parseJSON: { JSON_F52E2B61-18A1-11d1-B105-00805F49916B: '{"a":1}' } // With parseJSON: { a: 1 } ``` -------------------------------- ### Get SQL Type by JavaScript Value Source: https://github.com/tediousjs/node-mssql/blob/master/_autodocs/api-reference/Global-Functions.md Infers the appropriate SQL data type for a given JavaScript value. Useful for dynamic query building. ```javascript console.log(sql.getTypeByValue('hello')) // NVarChar console.log(sql.getTypeByValue(42)) // Int console.log(sql.getTypeByValue(2147483648)) // BigInt console.log(sql.getTypeByValue(3.14)) // Float console.log(sql.getTypeByValue(true)) // Bit console.log(sql.getTypeByValue(new Date())) // DateTime console.log(sql.getTypeByValue(Buffer.from('data'))) // VarBinary ``` -------------------------------- ### Connect to Database with Callback Source: https://github.com/tediousjs/node-mssql/blob/master/README.md Initiate a connection to the database using a callback function. The callback is invoked once the initial probe connection is established or if an error occurs during the process. ```javascript const pool = new sql.ConnectionPool({ user: '...', password: '...', server: 'localhost', database: '...' }) pool.connect(err => { // ... }) ``` -------------------------------- ### Get Affected Rows using Callbacks Source: https://github.com/tediousjs/node-mssql/blob/master/README.md Use this snippet to retrieve the number of rows affected by an INSERT, UPDATE, or DELETE statement when using callbacks. ```javascript const request = new sql.Request() request.query('update myAwesomeTable set awesomness = 100', (err, result) => { console.log(result.rowsAffected) }) ``` -------------------------------- ### Get Affected Rows using Promises Source: https://github.com/tediousjs/node-mssql/blob/master/README.md Use this snippet to retrieve the number of rows affected by an INSERT, UPDATE, or DELETE statement when using Promises. ```javascript const request = new sql.Request() request.query('update myAwesomeTable set awesomness = 100').then(result => { console.log(result.rowsAffected) }) ``` -------------------------------- ### Define VarBinary with specific length Source: https://github.com/tediousjs/node-mssql/blob/master/_autodocs/types.md Use sql.VarBinary(length) to define a variable-length binary data type with a maximum length in bytes. For example, sql.VarBinary(8000). ```javascript const imageBuffer = Buffer.from(imageData) request.input('thumbnail', sql.VarBinary(8000), imageBuffer) ``` -------------------------------- ### Configuration Reference Source: https://github.com/tediousjs/node-mssql/blob/master/_autodocs/api-reference/ConnectionPool.md Reference for all available configuration options when initializing a connection pool. ```APIDOC ## Configuration Reference The pool configuration accepts the following properties: - **user** (string): Database user - **password** (string): Database password - **server** (string): Server hostname (supports `localhost\instancename` for named instances) - **port** (number): Server port (default: 1433) - **database** (string): Initial database name - **domain** (string): Domain for domain login - **connectionTimeout** (number): Connection timeout in milliseconds (default: 15000) - **requestTimeout** (number): Request timeout in milliseconds (default: 15000) - **stream** (boolean): Stream recordsets/rows (default: false) - **parseJSON** (boolean): Parse JSON columns (default: false) - **arrayRowMode** (boolean): Return rows as arrays instead of keyed objects (default: false) - **validateConnection** (boolean|string): Connection validation mode: `true` (SELECT 1), `'socket'` (socket check), or `false` (no validation) (default: true) - **pool.max** (number): Maximum connections in pool (default: 10) - **pool.min** (number): Minimum connections in pool (default: 0) - **pool.idleTimeoutMillis** (number): Idle connection timeout in milliseconds (default: 30000) ``` -------------------------------- ### Instantiate PreparedStatement Source: https://github.com/tediousjs/node-mssql/blob/master/_autodocs/api-reference/PreparedStatement.md Create a new PreparedStatement instance, optionally providing a parent connection pool or transaction, and configuration options. ```javascript new PreparedStatement(parent?: ConnectionPool | Transaction, options?: Object): PreparedStatement ``` ```javascript // Using global pool const ps1 = new PreparedStatement() // Using specific pool const ps2 = new PreparedStatement(pool) // Using transaction const ps3 = new PreparedStatement(transaction) // With timeout override const ps4 = new PreparedStatement(pool, { requestTimeout: 60000 }) ``` -------------------------------- ### Create Connection Pool with Connection String Source: https://github.com/tediousjs/node-mssql/blob/master/_autodocs/api-reference/ConnectionPool.md Instantiate a new ConnectionPool using a connection string. The pool will attempt to connect immediately if a callback is provided. ```javascript const pool = new ConnectionPool('Server=localhost;Database=mydb;User Id=sa;Password=password') pool.connect().then(() => console.log('Connected')) ``` -------------------------------- ### Parse Geometry Data Source: https://github.com/tediousjs/node-mssql/blob/master/README.md Example of a SQL query returning Geometry data and its JavaScript object representation. Geometry types consistently order x before y coordinates. ```sql select geometry::STGeomFromText(N'POLYGON((1 1, 3 1, 3 7, 1 1))',4326) ``` ```javascript { srid: 4326, version: 1, points: [ Point { x: 1, y: 1, z: null, m: null }, Point { x: 1, y: 3, z: null, m: null }, Point { x: 7, y: 3, z: null, m: null }, Point { x: 1, y: 1, z: null, m: null } ], figures: [ { attribute: 2, pointOffset: 0 } ], shapes: [ { parentOffset: -1, figureOffset: 0, type: 3 } ], segments: [] } ``` -------------------------------- ### Import PreparedStatement Source: https://github.com/tediousjs/node-mssql/blob/master/_autodocs/api-reference/PreparedStatement.md Import the PreparedStatement class from the mssql library. ```javascript const { PreparedStatement } = require('mssql') ``` -------------------------------- ### Connect to Database (Callback-based) Source: https://github.com/tediousjs/node-mssql/blob/master/_autodocs/api-reference/ConnectionPool.md Open a connection to the database using the connect method and a traditional callback function to handle the result. ```javascript // Callback-based pool.connect(err => { if (err) throw err console.log('Connected') }) ``` -------------------------------- ### Handle Connection Event Source: https://github.com/tediousjs/node-mssql/blob/master/_autodocs/api-reference/ConnectionPool.md Listen for the 'connect' event to execute code when a connection to the database is established. ```javascript pool.on('connect', () => { console.log('Connected to database') }) ``` -------------------------------- ### Registering Per-Datatype Value Handler Source: https://github.com/tediousjs/node-mssql/blob/master/README.md Manipulate query result data by registering per-datatype handlers. This example increments all integer values returned from the database by one. ```javascript const sql = require('mssql') // in this example all integer values will return 1 more than their actual value in the database sql.valueHandler.set(sql.TYPES.Int, (value) => value + 1) sql.query('SELECT * FROM [example]').then((result) => { // all `int` columns will return a manipulated value as per the callback above }) ``` -------------------------------- ### Connecting to the Global Connection Pool Source: https://github.com/tediousjs/node-mssql/blob/master/README.md Use `sql.connect()` to establish or retrieve the global connection pool. Repeated calls with the same configuration will return the existing pool, optimizing connection overhead. Note that only one global pool can be active at a time. ```javascript const sql = require('mssql') const config = { ... } // run a query against the global connection pool function runQuery(query) { // sql.connect() will return the existing global pool if it exists or create a new one if it doesn't return sql.connect(config).then((pool) => { return pool.query(query) }) } ``` -------------------------------- ### Define DateTime2 with specific scale Source: https://github.com/tediousjs/node-mssql/blob/master/_autodocs/types.md Use sql.DateTime2(scale) to define a DateTime2 type with a specific fractional second precision. For example, scale 3 for DATETIME2(3). ```javascript request.input('precise', sql.DateTime2(3), new Date()) // DATETIME2(3) ``` -------------------------------- ### Run Unit Tests Source: https://github.com/tediousjs/node-mssql/wiki/Contributing Execute all unit tests for the project using the `npm test` command. This verifies the core functionality of the library. ```shell npm test ``` -------------------------------- ### Parse Geography Data Source: https://github.com/tediousjs/node-mssql/blob/master/README.md Example of a SQL query returning Geography data and its corresponding JavaScript object representation. Note the use of 'lat' and 'lng' properties for coordinates. ```sql select geography::STGeomFromText(N'POLYGON((1 1, 3 1, 3 1, 1 1))',4326) ``` ```javascript { srid: 4326, version: 2, points: [ Point { lat: 1, lng: 1, z: null, m: null }, Point { lat: 1, lng: 3, z: null, m: null }, Point { lat: 1, lng: 3, z: null, m: null }, Point { lat: 1, lng: 1, z: null, m: null } ], figures: [ { attribute: 1, pointOffset: 0 } ], shapes: [ { parentOffset: -1, figureOffset: 0, type: 3 } ], segments: [] } ``` -------------------------------- ### Connect to Database (Promise-based) Source: https://github.com/tediousjs/node-mssql/blob/master/_autodocs/api-reference/ConnectionPool.md Open a connection to the database using the connect method and handle success or failure with Promises. ```javascript // Promise-based pool.connect().then(() => { console.log('Connected') }).catch(err => { console.error('Connection failed:', err.message) }) ``` -------------------------------- ### Create a Prepared Statement Source: https://github.com/tediousjs/node-mssql/blob/master/README.md Initializes a new prepared statement. An optional connection pool or options can be provided. If omitted, the global connection is used. ```javascript const ps = new sql.PreparedStatement(/* [pool], [options] */) ``` -------------------------------- ### Import ConnectionPool Source: https://github.com/tediousjs/node-mssql/blob/master/_autodocs/api-reference/ConnectionPool.md Import the ConnectionPool class from the mssql package. ```javascript const { ConnectionPool } = require('mssql') ``` -------------------------------- ### Express App with Global Connection Pool Source: https://github.com/tediousjs/node-mssql/blob/master/README.md Connect to the database once and reuse the connection pool throughout your Express application. The server start is chained inside the connect() promise. ```javascript const express = require('express') const sql = require('mssql') const config = {/*...*/} //instantiate a connection pool const appPool = new sql.ConnectionPool(config) //require route handlers and use the same connection pool everywhere const route1 = require('./routes/route1') const app = express() app.get('/path', route1) //connect the pool and start the web server when done appPool.connect().then(function(pool) { app.locals.db = pool; const server = app.listen(3000, function () { const host = server.address().address const port = server.address().port console.log('Example app listening at http://%s:%s', host, port) }) }).catch(function(err) { console.error('Error creating connection pool', err) }); ``` -------------------------------- ### Define Binary with specific length Source: https://github.com/tediousjs/node-mssql/blob/master/_autodocs/types.md Use sql.Binary(length) to define a fixed-length binary data type with a maximum length in bytes. For example, sql.Binary(4) for 4 bytes. ```javascript const buffer = Buffer.from([1, 2, 3]) request.input('checksum', sql.Binary(4), buffer) ``` -------------------------------- ### Begin a Transaction Source: https://github.com/tediousjs/node-mssql/blob/master/README.md Initiates a new transaction. An optional isolation level can be specified. If no callback is provided, a Promise is returned. ```javascript const transaction = new sql.Transaction() transaction.begin(err => { // ... error checks }) ``` -------------------------------- ### Promise-based Query Execution Source: https://github.com/tediousjs/node-mssql/blob/master/README.md Shows how to execute SQL queries using Promises. Requires establishing a connection first and handling potential errors with .catch(). ```javascript const sql = require('mssql') sql.on('error', err => { // ... error handler }) sql.connect(config).then(pool => { // Query return pool.request() .input('input_parameter', sql.Int, value) .query('select * from mytable where id = @input_parameter') }).then(result => { console.dir(result) }).catch(err => { // ... error checks }); ``` -------------------------------- ### Handling Specific Error Codes Source: https://github.com/tediousjs/node-mssql/blob/master/_autodocs/errors.md Provides examples of checking for specific error codes like 'ELOGIN', 'ETIMEOUT', and 'ESOCKET' to implement targeted responses to common connection and network issues. ```javascript try { await pool.connect() } catch (err) { if (err.code === 'ELOGIN') { console.error('Check your credentials') } else if (err.code === 'ETIMEOUT') { console.error('Server not responding') } else if (err.code === 'ESOCKET') { console.error('Network connectivity issue') } } ``` -------------------------------- ### Configure Instance Name Source: https://github.com/tediousjs/node-mssql/blob/master/_autodocs/configuration.md Set `instanceName` to specify the SQL Server instance name for dynamic port discovery. The SQL Server Browser service must be running. ```javascript const config = { server: 'myserver', options: { instanceName: 'SQLEXPRESS' } } // Or use: server: 'myserver\SQLEXPRESS' ``` -------------------------------- ### Define and Use Table-Valued Parameter (TVP) Source: https://github.com/tediousjs/node-mssql/blob/master/README.md Demonstrates creating a custom SQL type, a stored procedure that accepts a TVP, and how to construct and pass a TVP from Node.js. ```sql CREATE TYPE TestType AS TABLE ( a VARCHAR(50), b INT ); ``` ```sql CREATE PROCEDURE MyCustomStoredProcedure (@tvp TestType readonly) AS SELECT * FROM @tvp ``` ```javascript const tvp = new sql.Table() // You can optionally specify table type name in the first argument. // Columns must correspond with type we have created in database. tvp.columns.add('a', sql.VarChar(50)) tvp.columns.add('b', sql.Int) // Add rows tvp.rows.add('hello tvp', 777) // Values are in same order as columns. ``` ```javascript const request = new sql.Request() request.input('tvp', tvp) request.execute('MyCustomStoredProcedure', (err, result) => { // ... error checks console.dir(result.recordsets[0][0]) // {a: 'hello tvp', b: 777} }) ``` ```javascript const tvp = new sql.Table() // You can optionally specify table type name in the first argument. // Columns must correspond with type we have created in database. tvp.columns.add('a', sql.VarChar(50)) tvp.columns.add('b', sql.Int) // Add rows tvp.rows.add('hello tvp', 777) // Values are in same order as columns. tvp.rows.clear() ``` -------------------------------- ### Overwrite Default Type Map Source: https://github.com/tediousjs/node-mssql/blob/master/README.md Override the default JavaScript to SQL data type mappings by re-registering existing types. For example, to always map `Number` to `sql.BigInt` instead of inferring. ```javascript sql.map.register(Number, sql.BigInt) ``` -------------------------------- ### Set Custom Value Handler Source: https://github.com/tediousjs/node-mssql/blob/master/_autodocs/api-reference/Global-Functions.md Register a custom handler function to transform values of a specific SQL data type as they are retrieved from the database. This example shows how to add 1 to all retrieved Integer values. ```javascript sql.valueHandler.set(sql.TYPES.Int, (value) => value + 1) const result = await sql.query('SELECT 10 AS number') console.log(result.recordset[0].number) // 11 ``` -------------------------------- ### Connect and Query using Connection String Source: https://github.com/tediousjs/node-mssql/blob/master/README.md Connects to SQL Server using a connection string and executes a simple query. Ensure connection string components are URL encoded. ```javascript const sql = require('mssql') (async () => { try { // make sure that any items are correctly URL encoded in the connection string await sql.connect('Server=localhost,1433;Database=database;User Id=username;Password=password;Encrypt=true') const result = await sql.query`select * from mytable where id = ${value}` console.dir(result) } catch (err) { // ... error checks } })() ``` -------------------------------- ### Callback-based Query and Stored Procedure Execution Source: https://github.com/tediousjs/node-mssql/blob/master/README.md Illustrates executing SQL queries and stored procedures using traditional callbacks. This includes handling input and output parameters for stored procedures and using template literals within callbacks. ```javascript const sql = require('mssql') sql.connect(config, err => { // ... error checks // Query new sql.Request().query('select 1 as number', (err, result) => { // ... error checks console.dir(result) }) // Stored Procedure new sql.Request() .input('input_parameter', sql.Int, value) .output('output_parameter', sql.VarChar(50)) .execute('procedure_name', (err, result) => { // ... error checks console.dir(result) }) // Using template literal const request = new sql.Request() request.query(request.template`select * from mytable where id = ${value}`, (err, result) => { // ... error checks console.dir(result) }) }) sql.on('error', err => { // ... error handler }) ``` -------------------------------- ### Custom Connection Pool Manager Source: https://github.com/tediousjs/node-mssql/blob/master/README.md Implement a custom connection pool manager to support multiple databases or separate pools for read/write operations. This example uses a Map to store and retrieve pools by name. ```javascript // pool-manager.js const mssql = require('mssql') const pools = new Map(); module.exports = { /** * Get or create a pool. If a pool doesn't exist the config must be provided. * If the pool does exist the config is ignored (even if it was different to the one provided * when creating the pool) * * @param {string} name * @param {{}} [config] * @return {Promise.} */ get: (name, config) => { if (!pools.has(name)) { if (!config) { throw new Error('Pool does not exist'); } const pool = new mssql.ConnectionPool(config); // automatically remove the pool from the cache if `pool.close()` is called const close = pool.close.bind(pool); pool.close = (...args) => { pools.delete(name); return close(...args); } pools.set(name, pool.connect()); } return pools.get(name); }, /** * Closes all the pools and removes them from the store * * @return {Promise} */ closeAll: () => Promise.all(Array.from(pools.values()).map((connect) => { return connect.then((pool) => pool.close()); })), }; ``` -------------------------------- ### Subscribe to Query Tracing Events Source: https://github.com/tediousjs/node-mssql/blob/master/README.md Use diagnostics_channel to subscribe to query start and error events. The `tracing::` format is used for subscription. Parameter values are never included in trace contexts. ```javascript const dc = require('node:diagnostics_channel') const { CHANNELS } = require('mssql') dc.subscribe(`tracing:${CHANNELS.TRACE_QUERY}:start`, ({ command, requestId }) => { console.log(`[${requestId}] Query: ${command}`) }) dc.subscribe(`tracing:${CHANNELS.TRACE_QUERY}:error`, ({ requestId, error }) => { console.error(`[${requestId}] Failed:`, error.message) }) ``` -------------------------------- ### Handling EARGS: Invalid Arguments Source: https://github.com/tediousjs/node-mssql/blob/master/_autodocs/errors.md Demonstrates the `EARGS` error code, which occurs due to incorrect arguments passed to methods like `input()` or `output()`. This example shows a missing type and value for an input parameter. ```javascript // EARGS - Invalid arguments try { const request = new Request() request.input('id') // Missing type and value } catch (err) { console.log(err.code) // 'EARGS' console.log(err.message) // 'Invalid number of arguments.' } ```