### library usage example Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/api-reference/exports.md Usage example for the library constant. ```javascript const { library } = require('tedious'); console.log(`Using ${library.name} for SQL Server connections`); ``` -------------------------------- ### poolConfig example Source: https://github.com/tediousjs/tedious/wiki/Implement-connection-pooling Example configuration for generic-pool. ```json { "name": "tediousPool", "max": 100, "min": 2, "idleTimeoutMillis": 30000 } ``` -------------------------------- ### Usage Example Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/api-reference/Connection.md A complete example demonstrating how to connect to a SQL Server database using Tedious and execute a query. ```javascript const { connect, TYPES, ISOLATION_LEVEL } = require('tedious'); const connection = connect({ server: 'myserver.database.windows.net', authentication: { type: 'default', options: { userName: 'user@domain', password: 'password' } }, options: { database: 'mydb', encrypt: true, trustServerCertificate: false } }); connection.on('connect', () => { console.log('Connected'); // Execute query const request = new (require('tedious').Request)( 'SELECT COUNT(*) as count FROM Users', (err, rowCount) => { if (err) console.error(err); else console.log(`Query returned ${rowCount} rows`); connection.close(); } ); request.on('row', (row) => { console.log('Count:', row[0].value); }); connection.execSql(request); }); connection.on('error', (err) => { console.error('Connection error:', err); }); ``` -------------------------------- ### TYPES usage example Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/api-reference/exports.md Usage example for the TYPES constant. ```javascript const { TYPES } = require('tedious'); request.addParameter('id', TYPES.Int, 123); request.addParameter('name', TYPES.NVarChar, 'John', { length: 100 }); request.addParameter('email', TYPES.VarChar, 'john@example.com', { length: 255 }); request.addParameter('created', TYPES.DateTime2, new Date(), { scale: 3 }); request.addParameter('active', TYPES.Bit, true); ``` -------------------------------- ### Usage Example Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/api-reference/connect.md An example demonstrating how to use the connect() function to establish a connection to a SQL Server instance. ```javascript const { connect } = require('tedious'); const config = { server: 'localhost', authentication: { type: 'default', options: { userName: 'sa', password: 'YourPassword123' } }, options: { database: 'TestDB', encrypt: true, trustServerCertificate: true } }; const connection = connect(config, (err) => { if (err) { console.error('Connection failed:', err.message); } else { console.log('Connected to SQL Server'); // Use connection for queries } }); connection.on('error', (err) => { console.error('Connection error:', err); }); ``` -------------------------------- ### TDS_VERSION usage example Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/api-reference/exports.md Usage example for the TDS_VERSION constant. ```javascript const { TDS_VERSION } = require('tedious'); const config = { server: 'myserver', options: { tdsVersion: TDS_VERSION['7_4'] } }; ``` -------------------------------- ### Import Examples Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/api-reference/exports.md Examples of how to import the tedious library using CommonJS and ES Modules. ```typescript // CommonJS const tedious = require('tedious'); const { connect, Connection, Request, BulkLoad, TYPES, ISOLATION_LEVEL, TDS_VERSION } = require('tedious'); // TypeScript / ES Modules import { connect, Connection, Request, BulkLoad, TYPES, ISOLATION_LEVEL, TDS_VERSION } from 'tedious'; import type { ConnectionConfiguration, ConnectionOptions } from 'tedious'; ``` -------------------------------- ### TYPES for Bulk Loads usage example Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/api-reference/exports.md Usage example for the TYPES constant with Bulk Loads. ```javascript const { TYPES } = require('tedious'); const bulkLoad = connection.newBulkLoad('Users', (err, rowCount) => { console.log(`Inserted ${rowCount} rows`); }); bulkLoad.addColumn('id', TYPES.Int, { nullable: false }); bulkLoad.addColumn('email', TYPES.NVarChar, { length: 255, nullable: false }); bulkLoad.addColumn('joinDate', TYPES.Date, { nullable: false }); ``` -------------------------------- ### Transaction Usage Example Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/api-reference/Connection.md Example demonstrating the usage of the transaction method. ```typescript connection.transaction((err, txDone) => { if (err) { console.error('Transaction failed:', err); return; } // Execute queries... const request = new Request('INSERT INTO Users VALUES (@name)', (err2) => { if (err2) { txDone(err2, (doneErr) => { if (doneErr) console.error('Rollback failed:', doneErr); }); } else { txDone(null, (doneErr) => { if (doneErr) console.error('Commit failed:', doneErr); else console.log('Transaction committed'); }); } }); request.addParameter('name', TYPES.NVarChar, 'John', { length: 50 }); connection.execSql(request); }); ``` -------------------------------- ### getTableCreationSql() Usage Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/api-reference/BulkLoad.md Example of how to get the CREATE TABLE SQL statement for a bulk load. ```typescript const bulkLoad = connection.newBulkLoad('#TempTable', (err) => {}); bulkLoad.addColumn('id', TYPES.Int, { nullable: false }); bulkLoad.addColumn('name', TYPES.NVarChar, { length: 50, nullable: true }); const createSql = bulkLoad.getTableCreationSql(); console.log(createSql); // Output: CREATE TABLE #TempTable( // [id] int, // [name] nvarchar(50) // ) ``` -------------------------------- ### ISOLATION_LEVEL usage example Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/api-reference/exports.md Usage example for the ISOLATION_LEVEL constant. ```javascript const { ISOLATION_LEVEL } = require('tedious'); connection.beginTransaction( (err, txDescriptor) => { console.log('Transaction started'); }, 'myTransaction', ISOLATION_LEVEL.SERIALIZABLE ); // Or with transaction() helper: connection.transaction( (err, txDone) => { // Execute queries... txDone(null, (doneErr) => { console.log('Committed'); }); }, ISOLATION_LEVEL.READ_COMMITTED ); ``` -------------------------------- ### Connection Error Handling Example Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/errors.md A comprehensive example of handling connection errors, including specific checks for common error codes like TLS/SSL, authentication, and network issues. ```javascript const { connect } = require('tedious'); const connection = connect(config, (err) => { if (err) { console.error('Connection failed:', err.message); if (err.code === 'ETLS') { console.error('TLS/SSL error. Check certificate validation settings.'); } else if (err.code === 'ELOGIN') { console.error('Authentication failed. Check credentials.'); } else if (err.code === 'ESOCKET') { console.error('Network error. Check server address and network connectivity.'); } } else { console.log('Connected successfully'); } }); connection.on('error', (err) => { console.error('Connection error:', err); // Handle connection loss or other runtime errors }); connection.on('end', () => { console.log('Connection ended'); }); ``` -------------------------------- ### Installation Source: https://github.com/tediousjs/tedious/blob/master/README.md Install tedious using npm. ```bash npm install tedious ``` -------------------------------- ### execSql() Usage Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/api-reference/Connection.md Example usage of the execSql method. ```javascript const { Request } = require('tedious'); const request = new Request('SELECT * FROM Users WHERE id = @id', (err, rowCount) => { if (err) { console.error('Query failed:', err); } else { console.log(`Retrieved ${rowCount} rows`); } }); request.addParameter('id', TYPES.Int, 42); request.on('row', (row) => { console.log('Row:', row); }); connection.execSql(request); ``` -------------------------------- ### Connections Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/README.md Example of creating a connection to a SQL Server instance using the `connect()` function. ```typescript const { connect } = require('tedious'); const connection = connect({ server: 'localhost', authentication: { type: 'default', options: { userName: 'sa', password: 'password' } }, options: { database: 'MyDatabase' } }); ``` -------------------------------- ### Connection Pooling with generic-pool Source: https://github.com/tediousjs/tedious/wiki/Implement-connection-pooling Example of setting up a connection pool using generic-pool and Tedious. ```javascript var Connection = require('tedious').Connection var Request = require('tedious').Request var TYPES = require('tedious').TYPES exports.TYPES = TYPES //used to form parameters to send in var tediousConfig = require('./tediousConfig.json') var poolApi = require('generic-pool') var poolConfig = require('./poolConfig.json') var poolFactory = { create: function() { return new Promise(function(resolve, reject) { try { new Connection(tediousConfig).on('connect', function(err) { if(err) { console.log(err) return reject(err) } resolve(this) }) } catch(err) { console.log(err) reject(err) } }, destroy: function(conn) { return Promise.resolve(conn.close()) } } var pool = poolApi.createPool(poolFactory, poolConfig); ``` -------------------------------- ### Bulk Load with Options Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/api-reference/BulkLoad.md An example demonstrating a bulk load operation with various options configured. ```javascript const bulkLoad = connection.newBulkLoad('Orders', { checkConstraints: true, // Honor CHECK constraints fireTriggers: true, // Fire INSERT triggers keepNulls: false, // Use column defaults for NULL lockTable: true, // Apply table lock during load order: { // Data is pre-sorted for optimization 'orderId': 'ASC', 'customerId': 'ASC' } }, (err, rowCount) => { console.log(`Inserted ${rowCount} rows`); }); bulkLoad.addColumn('orderId', TYPES.Int, { nullable: false }); bulkLoad.addColumn('customerId', TYPES.Int, { nullable: false }); bulkLoad.addColumn('orderDate', TYPES.DateTime2, { nullable: false, scale: 3 }); bulkLoad.addColumn('total', TYPES.Decimal, { nullable: false, precision: 10, scale: 2 }); connection.execBulkLoad(bulkLoad, [ [1, 100, new Date(), 99.99], [2, 101, new Date(), 199.99], [3, 102, new Date(), 49.99] ]); ``` -------------------------------- ### Basic Bulk Load Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/api-reference/BulkLoad.md A basic example demonstrating how to perform a bulk load operation. ```javascript const { connect, TYPES } = require('tedious'); const connection = connect({ server: 'localhost', authentication: { type: 'default', options: { userName: 'sa', password: 'password' } }, options: { database: 'TestDB' } }); connection.on('connect', () => { const bulkLoad = connection.newBulkLoad('Users', (err, rowCount) => { if (err) { console.error('Bulk load failed:', err); } else { console.log(`Successfully inserted ${rowCount} rows`); } connection.close(); }); bulkLoad.addColumn('firstName', TYPES.NVarChar, { length: 50, nullable: false }); bulkLoad.addColumn('lastName', TYPES.NVarChar, { length: 50, nullable: false }); bulkLoad.addColumn('age', TYPES.Int, { nullable: true }); const rows = [ ['John', 'Doe', 30], ['Jane', 'Smith', 28], ['Bob', 'Johnson', 45] ]; connection.execBulkLoad(bulkLoad, rows); }); ``` -------------------------------- ### Custom Socket Connector Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/configuration.md Example of how to provide a custom socket connector function to establish a connection. ```typescript const net = require('net'); const config = { server: 'myserver.local', authentication: { type: 'default', options: { userName: 'sa', password: 'password' } }, options: { database: 'MyDatabase', connector: async () => { // Custom socket creation logic const socket = net.createConnection(1433, 'myserver.local'); return new Promise((resolve, reject) => { socket.on('connect', () => resolve(socket)); socket.on('error', reject); }); } } }; ``` -------------------------------- ### Requests Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/README.md Example of creating and executing a SQL query using the `Request` class. ```typescript const { Request } = require('tedious'); const request = new Request( 'SELECT * FROM Users WHERE id = @id', (err, rowCount) => { console.log(`Query returned ${rowCount} rows`); } ); request.addParameter('id', TYPES.Int, 123); connection.execSql(request); ``` -------------------------------- ### VarBinary Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/api-reference/DataTypes.md Example of adding a VarBinary parameter. ```typescript const buffer = Buffer.from('Hello World'); request.addParameter('fileData', TYPES.VarBinary, buffer, { length: 8000 }); // For varbinary(max): request.addParameter('largeFile', TYPES.VarBinary, largeBuffer, { length: Infinity }); ``` -------------------------------- ### callProcedure() Usage Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/api-reference/Connection.md Example usage of the callProcedure method. ```javascript const request = new Request('sp_GetUserById', (err, rowCount) => { if (err) console.error(err); }); request.addParameter('userId', TYPES.Int, 123); request.addOutputParameter('userName', TYPES.NVarChar, null, { length: 100 }); request.on('returnValue', (name, value) => { console.log(`${name} = ${value}`); }); connection.callProcedure(request); ``` -------------------------------- ### Query with Parameters Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/README.md Example of executing a SQL query with named parameters. ```typescript const request = new Request( 'SELECT id, name FROM Users WHERE status = @status AND createdDate > @date', (err, rowCount) => { if (err) console.error(err); else console.log(`Retrieved ${rowCount} rows`); } ); request.addParameter('status', TYPES.NVarChar, 'active', { length: 20 }); request.addParameter('date', TYPES.DateTime2, new Date('2023-01-01'), { scale: 3 }); request.on('row', (row) => { console.log('Row:', row); }); connection.execSql(request); ``` -------------------------------- ### Binary Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/api-reference/DataTypes.md Example of adding a Binary parameter. ```typescript const buffer = Buffer.from([1, 2, 3, 4, 5]); request.addParameter('data', TYPES.Binary, buffer, { length: 10 }); ``` -------------------------------- ### VarChar Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/api-reference/DataTypes.md Example of adding a VarChar parameter. ```typescript request.addParameter('description', TYPES.VarChar, 'Product description', { length: 255 }); // For varchar(max): request.addParameter('longText', TYPES.VarChar, 'Very long text...', { length: Infinity }); ``` -------------------------------- ### Xml Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/api-reference/DataTypes.md Example of adding an Xml parameter. ```typescript const xmlData = 'value'; request.addParameter('xmlData', TYPES.Xml, xmlData); ``` -------------------------------- ### Stored Procedure with Output Parameters Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/api-reference/Request.md An example of executing a stored procedure with both input and output parameters, and handling the return values. ```typescript const request = new Request('sp_CreateUser', (err) => { if (err) { console.error('Procedure failed:', err); } }); request.addParameter('firstName', TYPES.NVarChar, 'John', { length: 50 }); request.addParameter('lastName', TYPES.NVarChar, 'Doe', { length: 50 }); request.addParameter('email', TYPES.NVarChar, 'john@example.com', { length: 100 }); request.addOutputParameter('newUserId', TYPES.Int, null); request.addOutputParameter('errorMsg', TYPES.NVarChar, null, { length: 200 }); request.on('returnValue', (paramName, value) => { console.log(`${paramName} = ${value}`); }); request.on('row', (row) => { console.log('Returned row:', row); }); connection.callProcedure(request); ``` -------------------------------- ### Image Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/api-reference/DataTypes.md Example of adding an Image parameter. ```typescript const imageBuffer = fs.readFileSync('photo.png'); request.addParameter('photo', TYPES.Image, imageBuffer); ``` -------------------------------- ### Char Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/api-reference/DataTypes.md Example of adding a Char parameter. ```typescript request.addParameter('code', TYPES.Char, 'ABC', { length: 10 }); ``` -------------------------------- ### Bulk Insert Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/README.md Example of performing a bulk insert operation. ```typescript const bulkLoad = connection.newBulkLoad('Employees', (err, rowCount) => { if (err) console.error(err); else console.log(`Inserted ${rowCount} employees`); }); bulkLoad.addColumn('id', TYPES.Int, { nullable: false }); bulkLoad.addColumn('name', TYPES.NVarChar, { length: 100, nullable: false }); bulkLoad.addColumn('startDate', TYPES.Date, { nullable: false }); const rows = [ [1, 'Alice', new Date('2023-01-15')], [2, 'Bob', new Date('2023-02-01')], [3, 'Carol', new Date('2023-03-10')] ]; connection.execBulkLoad(bulkLoad, rows); ``` -------------------------------- ### Text Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/api-reference/DataTypes.md Example of adding a Text parameter. ```typescript request.addParameter('article', TYPES.Text, 'Large text content...'); ``` -------------------------------- ### Variant Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/api-reference/DataTypes.md Example of adding a Variant parameter. ```typescript // Can hold any SQL value request.addParameter('value', TYPES.Variant, 'String or number or date'); ``` -------------------------------- ### NVarChar Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/api-reference/DataTypes.md Example of adding an NVarChar parameter. ```typescript request.addParameter('email', TYPES.NVarChar, 'user@example.com', { length: 255 }); // For nvarchar(max): request.addParameter('comments', TYPES.NVarChar, 'Long Unicode text...', { length: Infinity }); ``` -------------------------------- ### Development Commands Source: https://github.com/tediousjs/tedious/blob/master/pull_request_template.md Commands to run during development for installation, testing, building, and linting. ```bash npm install npm run-script test-all node_modules/nodeunit test/ -t npm run build npm run lint node_modules/.bin/commitlint --from origin/master --to HEAD ``` -------------------------------- ### NText Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/api-reference/DataTypes.md Example of adding an NText parameter. ```typescript request.addParameter('content', TYPES.NText, 'Large Unicode text...'); ``` -------------------------------- ### Bulk Loads Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/README.md Example of using `BulkLoad` for efficient insertion of multiple rows. ```typescript const bulkLoad = connection.newBulkLoad('Users', (err, rowCount) => { console.log(`Inserted ${rowCount} rows`); }); bulkLoad.addColumn('id', TYPES.Int, { nullable: false }); bulkLoad.addColumn('name', TYPES.NVarChar, { length: 100, nullable: false }); connection.execBulkLoad(bulkLoad, [ [1, 'Alice'], [2, 'Bob'] ]); ``` -------------------------------- ### addColumn() Usage Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/api-reference/BulkLoad.md Example of how to add columns to a bulk load operation. ```typescript const bulkLoad = connection.newBulkLoad('Users', (err, rowCount) => { console.log(`Inserted ${rowCount} rows`); }); bulkLoad.addColumn('id', TYPES.Int, { nullable: false }); bulkLoad.addColumn('name', TYPES.NVarChar, { length: 100, nullable: false }); bulkLoad.addColumn('email', TYPES.NVarChar, { length: 255, nullable: true }); bulkLoad.addColumn('active', TYPES.Bit, { nullable: false }); ``` -------------------------------- ### With Column Name Transformation Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/configuration.md Configuration demonstrating the use of `useColumnNames` and `columnNameReplacer` to transform column names, for example, from snake_case to camelCase. ```typescript const config = { server: 'localhost', authentication: { type: 'default', options: { userName: 'sa', password: 'password' } }, options: { database: 'MyDatabase', useColumnNames: true, columnNameReplacer: (colName, index, metadata) => { // Convert snake_case to camelCase return colName.replace(/_([a-z])/g, (match, letter) => letter.toUpperCase()); } } }; ``` -------------------------------- ### addParameter() Usage Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/api-reference/Request.md Example of adding a parameter to a request. ```typescript const request = new Request('SELECT * FROM Orders WHERE customerId = @customerId'); request.addParameter('customerId', TYPES.Int, 42); connection.execSql(request); ``` -------------------------------- ### DateTime2 Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/api-reference/DataTypes.md Example of adding a DateTime2 parameter. ```typescript request.addParameter('modifiedAt', TYPES.DateTime2, new Date(), { scale: 7 }); ``` -------------------------------- ### DateTimeOffset Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/api-reference/DataTypes.md Example of adding a DateTimeOffset parameter. ```typescript request.addParameter('eventTime', TYPES.DateTimeOffset, new Date(), { scale: 7 }); ``` -------------------------------- ### Simple SELECT Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/api-reference/Request.md A basic example of creating a `Request` object for a simple SELECT query and handling the response. ```typescript const { Request } = require('tedious'); const request = new Request( 'SELECT id, name, email FROM Users', (err, rowCount) => { if (err) { console.error('Query failed:', err); } else { console.log(`Retrieved ${rowCount} rows`); } } ); let rowCount = 0; request.on('row', (row) => { rowCount++; console.log(`Row ${rowCount}:`, row); }); request.on('done', (finalRowCount) => { console.log(`Done event fired with ${finalRowCount} rows`); }); connection.execSql(request); ``` -------------------------------- ### Consuming and Piping Streams Source: https://github.com/tediousjs/tedious/wiki/Implement-streams This example shows how to consume the stream returned by `ted.callProc` and pipe it through various handler modules before sending it to a response object. ```javascript ted = require('myTediousProvider'); someHandler = require('handlerModule1'); anotherHandler = require('handlerModule2'); ted.callProc(options) .pipe(someHandler) .pipe(anotherHandler({whatIsThis:'a parameter passed to the constructor of "another handler"'})) .pipe(res); ``` -------------------------------- ### Date Type Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/api-reference/DataTypes.md Example of using the Date data type. ```typescript request.addParameter('joinDate', TYPES.Date, new Date('2023-01-15')); ``` -------------------------------- ### Stored Procedure with Output Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/README.md Example of calling a stored procedure and retrieving an output parameter. ```typescript const request = new Request('sp_GetUserById', (err) => { if (err) console.error(err); }); request.addParameter('userId', TYPES.Int, 123); request.addOutputParameter('userName', TYPES.NVarChar, null, { length: 100 }); request.on('returnValue', (name, value) => { console.log(`${name} = ${value}`); }); connection.callProcedure(request); ``` -------------------------------- ### addOutputParameter() Usage Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/api-reference/Request.md Example of adding an output parameter to a request. ```typescript const request = new Request('sp_GetUserCount', (err) => { if (err) console.error(err); }); request.addOutputParameter('totalCount', TYPES.Int, null); request.on('returnValue', (name, value) => { console.log(`${name} = ${value}`); }); connection.callProcedure(request); ``` -------------------------------- ### DateTime Type Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/api-reference/DataTypes.md Example of using the DateTime data type. ```typescript request.addParameter('createdAt', TYPES.DateTime, new Date()); ``` -------------------------------- ### Transaction Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/README.md Example of executing multiple queries within a transaction. ```typescript connection.transaction((err, txDone) => { if (err) { console.error('Begin transaction failed:', err); return; } // Execute multiple queries const updateRequest = new Request( 'UPDATE Accounts SET balance = balance - @amount WHERE id = @id', (err2) => { if (err2) { // Rollback on error txDone(err2, (rbErr) => { console.log('Rolled back due to error:', err2.message); }); return; } // Commit on success txDone(null, (cbErr) => { if (cbErr) console.error('Commit failed:', cbErr); else console.log('Transaction committed'); }); } ); updateRequest.addParameter('amount', TYPES.Money, 100.00); updateRequest.addParameter('id', TYPES.Int, 1); connection.execSql(updateRequest); }); ``` -------------------------------- ### Transactions Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/README.md Example of executing queries within a transaction using `beginTransaction` and `commitTransaction`. ```typescript connection.beginTransaction((err, txDescriptor) => { if (err) { console.error('Begin transaction failed:', err); return; } // Execute queries... connection.commitTransaction((err) => { if (err) console.error('Commit failed:', err); }); }); // Or use the helper: connection.transaction((err, txDone) => { // Execute queries txDone(null, (doneErr) => { if (doneErr) console.error('Commit failed:', doneErr); }); }); ``` -------------------------------- ### Parameter with Options Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/api-reference/DataTypes.md Example of adding parameters with specific options like length, precision, and scale. ```typescript const { Request, TYPES } = require('tedious'); const request = new Request( 'INSERT INTO Products (name, price, description) VALUES (@name, @price, @desc)' ); // String with length request.addParameter('name', TYPES.NVarChar, 'Widget', { length: 100 }); // Decimal with precision and scale request.addParameter('price', TYPES.Decimal, 29.99, { precision: 10, scale: 2 }); // Large text request.addParameter('desc', TYPES.NVarChar, 'Very long description...', { length: Infinity }); ``` -------------------------------- ### Output Parameters Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/api-reference/DataTypes.md Example of using output parameters with a stored procedure call. ```typescript const request = new Request('sp_GetStatus'); request.addParameter('statusId', TYPES.Int, 1); request.addOutputParameter('statusName', TYPES.NVarChar, null, { length: 50 }); request.addOutputParameter('errorCode', TYPES.Int, null); request.on('returnValue', (name, value) => { console.log(`${name} = ${value}`); }); ``` -------------------------------- ### Development with Debug Output Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/configuration.md Configuration for development with debug output enabled for packets and tokens, and an example of listening for debug events. ```typescript const config = { server: 'localhost', authentication: { type: 'default', options: { userName: 'sa', password: 'password' } }, options: { database: 'TestDB', debug: { packet: true, data: false, payload: false, token: true } } }; const connection = connect(config); connection.on('debug', (message) => { console.log('[DEBUG]', message); }); ``` -------------------------------- ### Handling InputError Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/errors.md Provides an example of catching InputError or TypeError when invalid constructor arguments or configuration are provided. ```javascript const { Connection, InputError } = require('tedious'); try { const connection = new Connection(null); // Invalid config } catch (err) { if (err instanceof InputError || err instanceof TypeError) { console.error('Invalid input:', err.message); } } ``` -------------------------------- ### Bulk Load with Multiple Types Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/api-reference/DataTypes.md Example of defining columns for a bulk load operation with various data types and options. ```typescript const bulkLoad = connection.newBulkLoad('Orders'); bulkLoad.addColumn('orderId', TYPES.Int, { nullable: false }); bulkLoad.addColumn('customerId', TYPES.Int, { nullable: false }); bulkLoad.addColumn('orderDate', TYPES.DateTime2, { nullable: false, scale: 3 }); bulkLoad.addColumn('total', TYPES.Decimal, { nullable: false, precision: 10, scale: 2 }); bulkLoad.addColumn('notes', TYPES.NVarChar, { length: 500, nullable: true }); bulkLoad.addColumn('paid', TYPES.Bit, { nullable: false }); ``` -------------------------------- ### Integration with Connection Pools (generic-pool) Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/README.md Example of integrating Tedious with the generic-pool library for connection pooling. ```typescript const Pool = require('generic-pool').Pool; const { connect } = require('tedious'); const factory = { create: async () => { return new Promise((resolve, reject) => { const connection = connect(config, (err) => { if (err) reject(err); else resolve(connection); }); }); }, destroy: async (connection) => { return new Promise((resolve) => { connection.close(); resolve(); }); } }; const pool = new Pool(factory, { max: 10 }); // Later, get a connection: const connection = await pool.acquire(); // Use connection... await pool.release(connection); ``` -------------------------------- ### Async reading from tracking buffer Source: https://github.com/tediousjs/tedious/wiki/Tokens-that-span-Packets Example of using a callback for asynchronous reading from a tracking buffer, which handles data that spans across packets. ```javascript trackingBuffer.readUInt32LE(function(err, value) { // Use the value. // Often this will mean calling another async read... function. }); ``` -------------------------------- ### UniqueIdentifier Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/api-reference/DataTypes.md Example of adding a UniqueIdentifier parameter. ```typescript request.addParameter('id', TYPES.UniqueIdentifier, 'A1B2C3D4-E5F6-7890-ABCD-EF1234567890'); ``` -------------------------------- ### connect() Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/api-reference/Connection.md Initiates connection to the SQL Server. Emits `connect` event on success or `error` event on failure. ```typescript connect(connectListener?: (err?: Error) => void): void ``` -------------------------------- ### unprepare() Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/api-reference/Connection.md Releases resources for a prepared statement. ```typescript unprepare(request: Request): void ``` -------------------------------- ### prepare() Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/api-reference/Connection.md Prepares a statement for repeated execution with different parameters. After preparation, call `execute()` with different parameters. ```typescript prepare(request: Request): void ``` -------------------------------- ### NChar Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/api-reference/DataTypes.md Example of adding an NChar parameter. ```typescript request.addParameter('name', TYPES.NChar, 'John', { length: 50 }); ``` -------------------------------- ### With Specific Port Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/configuration.md Configuration for connecting to SQL Server on a specific port. ```typescript const config = { server: 'myserver.local', authentication: { type: 'default', options: { userName: 'sa', password: 'password' } }, options: { port: 1434, database: 'MyDatabase' } }; ``` -------------------------------- ### Running an existing benchmark Source: https://github.com/tediousjs/tedious/blob/master/benchmarks/README.md To run an existing benchmark, execute the benchmark file with node. ```sh node benchmarks/query/select-many-rows.js ``` -------------------------------- ### Importing TYPES and using parameters Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/api-reference/DataTypes.md Demonstrates how to import the TYPES constant and use it to add parameters to a request or columns to a bulk load. ```typescript const { TYPES } = require('tedious'); // In a request parameter request.addParameter('userId', TYPES.Int, 42); // In a bulk load column bulkLoad.addColumn('email', TYPES.NVarChar, { length: 255, nullable: true }); ``` -------------------------------- ### Bulk Load with Temporary Table Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/api-reference/BulkLoad.md Illustrates performing a bulk load into a temporary table ('#TempImport') and then querying it using `execSqlBatch`. ```typescript const bulkLoad = connection.newBulkLoad('#TempImport', (err, rowCount) => { if (err) { console.error('Bulk load failed:', err); return; } console.log(`Inserted ${rowCount} rows into #TempImport`); // Now use the temporary table in a subsequent query const request = new (require('tedious').Request)( 'SELECT * FROM #TempImport WHERE status = @status', (err2) => { if (err2) console.error('Query failed:', err2); connection.close(); } ); request.addParameter('status', TYPES.NVarChar, 'active', { length: 20 }); request.on('row', (row) => { console.log('Row from temp table:', row); }); connection.execSqlBatch(request); }); bulkLoad.addColumn('id', TYPES.Int, { nullable: false }); bulkLoad.addColumn('data', TYPES.NVarChar, { length: 255, nullable: true }); bulkLoad.addColumn('status', TYPES.NVarChar, { length: 20, nullable: false }); // Get CREATE TABLE SQL and execute it first const createSql = bulkLoad.getTableCreationSql(); const createRequest = new (require('tedious').Request)(createSql, (err) => { if (err) { console.error('CREATE TABLE failed:', err); return; } console.log('Temporary table created'); // Now execute the bulk load into the created table const rows = [ [1, 'data1', 'active'], [2, 'data2', 'inactive'], [3, 'data3', 'active'] ]; connection.execBulkLoad(bulkLoad, rows); }); connection.execSqlBatch(createRequest); ``` -------------------------------- ### Handling Multiple Result Sets Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/api-reference/Request.md Shows how to execute a batch of SQL statements that return multiple result sets and how to process them. ```typescript const request = new Request( 'SELECT * FROM Users; SELECT * FROM Orders;', (err, rowCount) => { console.log(`Total rows: ${rowCount}`); } ); request.on('done', (rowCount, more) => { if (more) { console.log(`Got ${rowCount} rows, more result sets to come`); } else { console.log(`Got ${rowCount} rows, all done`); } }); connection.execSqlBatch(request); ``` -------------------------------- ### Basic Connection Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/configuration.md A basic configuration object for connecting to a local SQL Server instance using default authentication. ```typescript const config = { server: 'localhost', authentication: { type: 'default', options: { userName: 'sa', password: 'password' } }, options: { database: 'MyDatabase' } }; ``` -------------------------------- ### UDT Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/api-reference/DataTypes.md Example of adding a UDT (User-Defined Type) parameter. ```typescript const udt = { field1: 'value1', field2: 'value2' }; request.addParameter('custom', TYPES.UDT, udt); ``` -------------------------------- ### Constructor Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/api-reference/Request.md Creates a new request object. ```typescript new Request( sqlTextOrProcedure: string | undefined, callback: (error: Error | null | undefined, rowCount?: number, rows?: any[]) => void, options?: RequestOptions ) ``` -------------------------------- ### SmallDateTime Type Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/api-reference/DataTypes.md Example of using the SmallDateTime data type. ```typescript request.addParameter('timestamp', TYPES.SmallDateTime, new Date()); ``` -------------------------------- ### Table-Valued Parameter (TVP) Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/api-reference/DataTypes.md Example of how to use a table-valued parameter with Tedious. ```typescript const tableData = [ [1, 'Row 1'], [2, 'Row 2'] ]; request.addParameter('data', TYPES.TVP, tableData); ``` -------------------------------- ### Named Instance Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/configuration.md Configuration for connecting to a named instance of SQL Server. ```typescript const config = { server: 'myserver.local', instanceName: 'SQLEXPRESS', authentication: { type: 'default', options: { userName: 'sa', password: 'password' } }, options: { database: 'MyDatabase' } }; ``` -------------------------------- ### Time Type Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/api-reference/DataTypes.md Example of using the Time data type with specified scale. ```typescript request.addParameter('startTime', TYPES.Time, new Date(), { scale: 3 }); ``` -------------------------------- ### Constructor Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/api-reference/Connection.md Creates a new connection instance. The connection does not automatically connect; call `connect()` to establish the connection. ```typescript new Connection(config: ConnectionConfiguration) ``` -------------------------------- ### execBulkLoad() Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/api-reference/Connection.md Executes a bulk load operation. ```typescript execBulkLoad( bulkLoad: BulkLoad, rows?: AsyncIterable | Iterable ): void ``` -------------------------------- ### Numeric Type Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/api-reference/DataTypes.md Example of using the Numeric data type, which is an alias for Decimal. ```typescript request.addParameter('quantity', TYPES.Numeric, 1000.50, { precision: 10, scale: 2 }); ``` -------------------------------- ### Bit Type Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/api-reference/DataTypes.md Example of using the Bit data type for boolean values. ```typescript request.addParameter('isActive', TYPES.Bit, true); ``` -------------------------------- ### Catching ConnectionError Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/errors.md Demonstrates how to catch and handle ConnectionError instances, checking for transient errors. ```javascript const { connect, ConnectionError } = require('tedious'); const connection = connect(config); connection.on('error', (err) => { if (err instanceof ConnectionError) { console.log('Connection error code:', err.code); if (err.isTransient) { console.log('Transient error, may retry'); } else { console.log('Persistent error'); } } }); ``` -------------------------------- ### execSqlBatch() Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/api-reference/Connection.md Executes multiple SQL statements in a batch. Unlike `execSql()`, this allows multiple statement separators and does not prepare stored procedures. ```typescript execSqlBatch(request: Request): void ``` -------------------------------- ### Decimal Type Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/api-reference/DataTypes.md Example of using the Decimal data type with specified precision and scale. ```typescript request.addParameter('price', TYPES.Decimal, 99.99, { precision: 10, scale: 2 }); ``` -------------------------------- ### Importing ConnectionError Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/errors.md Shows how to import the ConnectionError class from the tedious library. ```javascript const { ConnectionError } = require('tedious'); ``` -------------------------------- ### Int Type Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/api-reference/DataTypes.md Example of using the Int data type for standard integer values. ```typescript request.addParameter('userId', TYPES.Int, 12345); ``` -------------------------------- ### SmallInt Type Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/api-reference/DataTypes.md Example of using the SmallInt data type for small integer values. ```typescript request.addParameter('quantity', TYPES.SmallInt, 100); ``` -------------------------------- ### Catching RequestError Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/errors.md Demonstrates how to catch and handle RequestError instances, logging detailed information about the SQL Server error. ```javascript const { Request, RequestError } = require('tedious'); const request = new Request( 'SELECT * FROM NonexistentTable', (err) => { if (err instanceof RequestError) { console.log('Request error:'); console.log(' Message:', err.message); console.log(' Code:', err.code); console.log(' SQL Error #:', err.number); console.log(' Procedure:', err.procName); console.log(' Line:', err.lineNumber); } } ); connection.execSql(request); ``` -------------------------------- ### Parameterized Query Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/api-reference/Request.md Demonstrates how to create a parameterized query using `Request.addParameter` to safely pass values into SQL statements. ```typescript const request = new Request( 'SELECT * FROM Products WHERE categoryId = @catId AND price > @minPrice' ); request.addParameter('catId', TYPES.Int, 5); request.addParameter('minPrice', TYPES.Decimal, 100.00, { precision: 10, scale: 2 }); request.on('columnMetadata', (columns) => { console.log('Columns:', columns.map(c => c.name)); }); request.on('row', (row) => { console.log('Product:', row); }); request.on('done', () => { console.log('Query complete'); }); connection.execSql(request); ``` -------------------------------- ### Float Type Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/api-reference/DataTypes.md Example of using the Float data type for 64-bit floating point numbers. ```typescript request.addParameter('distance', TYPES.Float, 3.14159); ``` -------------------------------- ### execute() Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/api-reference/Connection.md Executes a prepared statement with new parameters. A statement must be prepared first via `prepare()`. ```typescript execute(request: Request, parameters?: { [key: string]: unknown }): void ``` -------------------------------- ### Real Type Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/api-reference/DataTypes.md Example of using the Real data type for 32-bit floating point numbers. ```typescript request.addParameter('temperature', TYPES.Real, 98.6); ``` -------------------------------- ### Connection class Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/api-reference/README.md Represents a single database connection. ```typescript class Connection extends EventEmitter { constructor(config: ConnectionConfiguration) // Lifecycle connect(connectListener?: (err?: Error) => void): void close(): void cancel(): void reset(callback: ResetCallback): void // Query Execution execSql(request: Request): void execSqlBatch(request: Request): void callProcedure(request: Request): void // Prepared Statements prepare(request: Request): void unprepare(request: Request): void execute(request: Request, parameters?: { [key: string]: unknown }): void // Bulk Loading newBulkLoad(table: string, callback: BulkLoadCallback): BulkLoad newBulkLoad(table: string, options: BulkLoadOptions, callback: BulkLoadCallback): BulkLoad execBulkLoad(bulkLoad: BulkLoad, rows?: Iterable | AsyncIterable): void // Transactions beginTransaction(callback, name?: string, isolationLevel?: number): void commitTransaction(callback, name?: string): void rollbackTransaction(callback, name?: string): void saveTransaction(callback, name: string): void transaction(callback, isolationLevel?: number): void } ``` -------------------------------- ### Bulk Load with Object Rows Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/api-reference/BulkLoad.md Demonstrates how to perform a bulk load using an array of JavaScript objects, where column names are inferred from object property names. ```typescript const bulkLoad = connection.newBulkLoad('Products', (err, rowCount) => { console.log(`Inserted ${rowCount} products`); }); bulkLoad.addColumn('productId', TYPES.Int, { nullable: false }); bulkLoad.addColumn('name', TYPES.NVarChar, { length: 200, nullable: false }); bulkLoad.addColumn('price', TYPES.Decimal, { precision: 10, scale: 2, nullable: false }); bulkLoad.addColumn('stock', TYPES.Int, { nullable: false }); const rows = [ { productId: 1, name: 'Widget', price: 29.99, stock: 100 }, { productId: 2, name: 'Gadget', price: 49.99, stock: 50 }, { productId: 3, name: 'Doohickey', price: 19.99, stock: 200 } ]; connection.execBulkLoad(bulkLoad, rows); ``` -------------------------------- ### TinyInt Type Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/api-reference/DataTypes.md Example of using the TinyInt data type for small integer values (0-255). ```typescript request.addParameter('status', TYPES.TinyInt, 5); ``` -------------------------------- ### AuthenticationOptions Interface Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/types.md Specifies how to authenticate to SQL Server. ```typescript interface AuthenticationOptions { type?: AuthenticationType; options?: any; } ``` -------------------------------- ### NTLM / Windows Authentication Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/configuration.md Configuration for connecting using NTLM or Windows Authentication. ```typescript const config = { server: 'myserver.local', authentication: { type: 'ntlm', options: { userName: 'username', password: 'password', domain: 'DOMAIN' } }, options: { database: 'MyDatabase' } }; ``` -------------------------------- ### Money Type Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/api-reference/DataTypes.md Example of using the Money data type for monetary values with fixed 4 decimal places. ```typescript request.addParameter('amount', TYPES.Money, 1234.56); ``` -------------------------------- ### Global Error Handling Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/errors.md Demonstrates how to handle all errors globally using connection.on('error') and unhandled rejections from async operations. ```typescript const { connect } = require('tedious'); const connection = connect(config); // Handle all errors globally connection.on('error', (err) => { console.error('Global error handler:', err.message); console.error('Stack:', err.stack); // Attempt recovery if transient if (err.isTransient) { console.log('Attempting to reset connection...'); connection.reset((resetErr) => { if (resetErr) { console.error('Reset failed:', resetErr.message); } else { console.log('Connection reset successfully'); } }); } else { // Fatal error, close connection connection.close(); } }); // Handle unhandled rejections from async operations process.on('unhandledRejection', (reason, promise) => { console.error('Unhandled rejection:', reason); }); ``` -------------------------------- ### Connection class signature Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/api-reference/exports.md Represents a database connection. Create with connect() function or new Connection(). ```typescript class Connection extends EventEmitter ``` -------------------------------- ### connect() Signature Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/api-reference/connect.md The TypeScript signature for the connect() function. ```typescript function connect( config: ConnectionConfiguration, connectListener?: (err?: Error) => void ): Connection ``` -------------------------------- ### BulkLoad class Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/api-reference/README.md Represents a bulk insert operation. ```typescript class BulkLoad extends EventEmitter { // Column Definition addColumn( name: string, type: DataType, options?: ColumnOptions ): void // Utilities setTimeout(timeout?: number): void getTableCreationSql(): string } ``` -------------------------------- ### Pausing and Resuming Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/api-reference/Request.md Illustrates how to pause and resume processing of rows for a large query using `request.pause()` and `request.resume()`. ```typescript const request = new Request( 'SELECT * FROM LargeTable', (err) => console.log(err ? 'Error' : 'Done') ); let rowsReceived = 0; request.on('row', (row) => { rowsReceived++; console.log('Row:', row); if (rowsReceived % 1000 === 0) { console.log('Pausing after 1000 rows...'); request.pause(); setTimeout(() => { console.log('Resuming...'); request.resume(); }, 2000); } }); connection.execSql(request); ``` -------------------------------- ### SmallMoney Type Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/api-reference/DataTypes.md Example of using the SmallMoney data type for smaller monetary values with fixed 4 decimal places. ```typescript request.addParameter('fee', TYPES.SmallMoney, 99.99); ``` -------------------------------- ### BigInt Type Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/api-reference/DataTypes.md Example of using the BigInt data type, noting that it's returned as a string due to JavaScript number precision limitations. ```typescript request.addParameter('largeId', TYPES.BigInt, '9223372036854775800'); request.on('row', (row) => { // row[0].value is a string const id = row[0].value; // '9223372036854775800' }); ``` -------------------------------- ### Azure with Managed Identity (VM) Source: https://github.com/tediousjs/tedious/blob/master/_autodocs/configuration.md Configuration for connecting to Azure SQL Database using a Managed Identity assigned to a Virtual Machine. ```typescript const config = { server: 'myserver.database.windows.net', authentication: { type: 'azure-active-directory-msi-vm', options: { clientId: 'client-id-if-specific-identity' } }, options: { database: 'MyDatabase', encrypt: true } }; ```