@jovercao/mssql
Version:
Microsoft SQL Server client for Node.js.
1,547 lines (1,133 loc) • 70.1 kB
Markdown
# node-mssql
Microsoft SQL Server client for Node.js
[![NPM Version][npm-image]][npm-url] [![NPM Downloads][downloads-image]][downloads-url] [![Travis CI][travis-image]][travis-url] [![Appveyor CI][appveyor-image]][appveyor-url] [](https://gitter.im/patriksimek/node-mssql?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
Supported TDS drivers:
- [Tedious][tedious-url] (pure JavaScript - Windows/macOS/Linux, default)
- [Microsoft / Contributors Node V8 Driver for Node.js for SQL Server][msnodesqlv8-url] (v2 native - Windows or Linux/macOS 64 bits only)
## Installation
npm install mssql
## Short Example: Use Connect String
```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
}
}
```
If you're on Windows Azure, add `?encrypt=true` to your connection string. See [docs](#configuration) to learn more.
Parts of the connection URI should be correctly URL encoded so that the URI can be parsed correctly.
## Longer Example: Connect via Config Object
Assuming you have set the appropriate environment variables, you can construct a config object as follows:
```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
}
}
```
## Documentation
### Examples
* [Async/Await](#asyncawait)
* [Promises](#promises)
* [ES6 Tagged template literals](#es6-tagged-template-literals)
* [Callbacks](#callbacks)
* [Streaming](#streaming)
* [Connection Pools](#connection-pools)
### Configuration
* [General](#general-same-for-all-drivers)
* [Formats](#formats)
### Drivers
* [Tedious](#tedious)
* [Microsoft / Contributors Node V8 Driver for Node.js for SQL Server](#microsoft--contributors-node-v8-driver-for-nodejs-for-sql-server)
### Connections
* [Pool Management](#pool-management)
* [ConnectionPool](#connections-1)
* [connect](#connect-callback)
* [close](#close)
### Requests
* [Request](#request)
* [execute](#execute-procedure-callback)
* [input](#input-name-type-value)
* [output](#output-name-type-value)
* [toReadableStream](#toReadableStream)
* [pipe](#pipe-stream)
* [query](#query-command-callback)
* [batch](#batch-batch-callback)
* [bulk](#bulk-table-options-callback)
* [cancel](#cancel)
### Transactions
* [Transaction](#transaction)
* [begin](#begin-isolationlevel-callback)
* [commit](#commit-callback)
* [rollback](#rollback-callback)
### Prepared Statements
* [PreparedStatement](#prepared-statement)
* [input](#input-name-type)
* [output](#output-name-type)
* [prepare](#prepare-statement-callback)
* [execute](#execute-values-callback)
* [unprepare](#unprepare-callback)
### Other
* [CLI](#cli)
* [Geography and Geometry](#geography-and-geometry)
* [Table-Valued Parameter](#table-valued-parameter-tvp)
* [Response Schema](#response-schema)
* [Affected Rows](#affected-rows)
* [JSON support](#json-support)
* [Handling Duplicate Column Names](#handling-duplicate-column-names)
* [Errors](#errors)
* [Informational messages](#informational-messages)
* [Metadata](#metadata)
* [Data Types](#data-types)
* [SQL injection](#sql-injection)
* [Known Issues](#known-issues)
* [Contributing](https://github.com/tediousjs/node-mssql/wiki/Contributing)
* [6.x to 7.x changes (pre-release)](#6x-to-7x-changes-pre-release)
* [5.x to 6.x changes](#5x-to-6x-changes)
* [4.x to 5.x changes](#4x-to-5x-changes)
* [3.x to 4.x changes](#3x-to-4x-changes)
* [3.x Documentation](https://github.com/tediousjs/node-mssql/blob/1893969195045a250f0fdeeb2de7f30dcf6689ad/README.md)
## Examples
### Config
```javascript
const config = {
user: '...',
password: '...',
server: 'localhost', // You can use 'localhost\\instance' to connect to named instance
database: '...',
}
```
### Async/Await
```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
})
```
### Promises
#### Queries
```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
});
```
#### Stored procedures
```js
const sql = require('mssql')
sql.on('error', err => {
// ... error handler
})
sql.connect(config).then(pool => {
// Stored procedure
return pool.request()
.input('input_parameter', sql.Int, value)
.output('output_parameter', sql.VarChar(50))
.execute('procedure_name')
}).then(result => {
console.dir(result)
}).catch(err => {
// ... error checks
})
```
Native Promise is used by default. You can easily change this with `sql.Promise = require('myownpromisepackage')`.
### ES6 Tagged template literals
```javascript
const sql = require('mssql')
sql.connect(config).then(() => {
return sql.query`select * from mytable where id = ${value}`
}).then(result => {
console.dir(result)
}).catch(err => {
// ... error checks
})
sql.on('error', err => {
// ... error handler
})
```
All values are automatically sanitized against sql injection.
This is because it is rendered as prepared statement, and thus all limitations imposed in MS SQL on parameters apply.
e.g. Column names cannot be passed/set in statements using variables.
### 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
})
```
### Streaming
If you plan to work with large amount of rows, you should always use streaming. Once you enable this, you must listen for events to receive data.
```javascript
const sql = require('mssql')
sql.connect(config, err => {
// ... error checks
const request = new sql.Request()
request.stream = true // You can set streaming differently for each request
request.query('select * from verylargetable') // or request.execute(procedure)
request.on('recordset', columns => {
// Emitted once for each recordset in a query
})
request.on('row', row => {
// Emitted for each row in a recordset
})
request.on('rowsaffected', rowCount => {
// Emitted for each `INSERT`, `UPDATE` or `DELETE` statement
// Requires NOCOUNT to be OFF (default)
})
request.on('error', err => {
// May be emitted multiple times
})
request.on('done', result => {
// Always emitted as the last one
})
})
sql.on('error', err => {
// ... error handler
})
```
When streaming large sets of data you want to back-off or chunk the amount of data you're processing
to prevent memory exhaustion issues; you can use the `Request.pause()` function to do this. Here is
an example of managing rows in batches of 15:
```javascript
let rowsToProcess = [];
request.on('row', row => {
rowsToProcess.push(row);
if (rowsToProcess.length >= 15) {
request.pause();
processRows();
}
});
request.on('done', () => {
processRows();
});
function processRows() {
// process rows
rowsToProcess = [];
request.resume();
}
```
## Pool Management
An important concept to understand when using this library is [Connection Pooling](https://en.wikipedia.org/wiki/Connection_pool)
as this library uses connection pooling extensively.
As one Node JS process is able to handle multiple requests at once, we can take advantage of this long running process
to create a pool of database connections for reuse; this saves overhead of connecting to the database for each request
(as would be the case in something like PHP, where one process handles one request).
With the advantages of pooling comes some added complexities, but these are mostly just conceptual and once you understand
how the pooling is working, it is simple to make use of it efficiently and effectively.
### The Global Connection (Pool)
To assist with pool management in your application there is the global `connect()` function that is available for use. As of
v6 of this library a developer can make repeated calls to this function to obtain the global connection pool. This means you
do not need to keep track of the pool in your application (as used to be the case). If the global pool is already connected,
it will resolve to the connected pool. For example:
```js
const sql = require('mssql')
// 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().then((pool) => {
return pool.query(query)
})
}
```
Here we obtain the global connection pool by running `sql.connect()` and we then run the query against the pool.
We also do *not* close the pool after the query is executed and that is because other queries may need to be run against
this pool and closing it will add an overhead to running the query. We should only ever close the pool when our application
is finished. For example, if we are running some kind of CLI tool or a CRON job:
```js
const sql = require('mssql')
(() => {
sql.connect().then(pool => {
return pool.query('SELECT 1')
}).then(result => {
// do something with result
}).then(() => {
return sql.close()
})
})()
```
Here the connection will be closed and the node process will exit once the queries and other application logic has completed.
You should aim to only close the pool once in your application, when it is exiting or you know your application will never make
another SQL query.
### Advanced Pool Management
In some instances you will not want to use the connection pool, you may have multiple databases to connect to or you may have
one pool for read-only operations and another pool for read-write. In this instance you will need to implement your own pool
management.
That could look something like this:
```js
const { ConnectionPool } = require('mssql')
const POOLS = {}
function createPool(config, name) {
if (getPool(name)) {
return Promise.reject(new Error('Pool with this name already exists'))
}
return (new ConnectionPool(config)).connect().then((pool) => {
return POOLS[name] = pool
})
}
function closePool(name) {
const pool = getPool(name)
if (pool) {
delete POOLS[name]
return pool.close()
}
return Promise.resolve()
}
function getPool(name) {
if (Object.prototype.hasOwnProperty.apply(POOLS, name)) {
return POOLS[name]
}
}
module.exports = {
closePool,
createPool,
getPool
}
```
This helper file can then be used in your application to create, fetch and close your pools. As with the global pools, you
should aim to only close a pool when you know it will never be needed by the application again; typically this will be when
your application is shutting down.
## Connection Pools
Using a single connection pool for your application/service is recommended.
Instantiating a pool with a callback, or immediately calling `.connect`, is asynchronous to ensure a connection can be
established before returning. From that point, you're able to acquire connections as normal:
```javascript
const sql = require('mssql')
// async/await style:
const pool1 = new sql.ConnectionPool(config);
const pool1Connect = pool1.connect();
pool1.on('error', err => {
// ... error handler
})
async function messageHandler() {
await pool1Connect; // ensures that the pool has been created
try {
const request = pool1.request(); // or: new sql.Request(pool1)
const result = await request.query('select 1 as number')
console.dir(result)
return result;
} catch (err) {
console.error('SQL error', err);
}
}
// promise style:
const pool2 = new sql.ConnectionPool(config)
const pool2Connect = pool2.connect()
pool2.on('error', err => {
// ... error handler
})
function runStoredProcedure() {
return pool2Connect.then((pool) => {
pool.request() // or: new sql.Request(pool2)
.input('input_parameter', sql.Int, 10)
.output('output_parameter', sql.VarChar(50))
.execute('procedure_name', (err, result) => {
// ... error checks
console.dir(result)
})
}).catch(err => {
// ... error handler
})
}
```
Awaiting or `.then`ing the pool creation is a safe way to ensure that the pool is always ready, without knowing where it
is needed first. In practice, once the pool is created then there will be no delay for the next operation.
As of v6.1.0 you can make repeat calls to `ConnectionPool.connect()` and `ConnectonPool.close()` without an error being
thrown, allowing for the safe use of `mssql.connect().then(...)` throughout your code as well as making multiple calls to
close when your application is shutting down.
The ability to call `connect()` repeatedly is intended to make pool management easier, however it is still recommended
to follow the example above where `connect()` is called once and using the original resolved connection promise.
Repeatedly calling `connect()` when running queries risks running into problems when `close()` is called on the pool.
**ES6 Tagged template literals**
```javascript
new sql.ConnectionPool(config).connect().then(pool => {
return pool.query`select * from mytable where id = ${value}`
}).then(result => {
console.dir(result)
}).catch(err => {
// ... error checks
})
```
All values are automatically sanitized against sql injection.
### Managing connection pools
Most applications will only need a single `ConnectionPool` that can be shared throughout the code. To aid the sharing
of a single pool this library exposes a set of functions to access a single global connection. eg:
```js
// as part of your application's boot process
const sql = require('mssql')
const poolPromise = sql.connect()
// during your applications runtime
poolPromise.then(() => {
return sql.query('SELECT 1')
}).then(result => {
console.dir(result)
})
// when your application exits
poolPromise.then(() => {
return sql.close()
})
```
If you require multiple pools per application (perhaps you have many DBs you need to connect to or you want a read-only
pool), then you will need to manage your pools yourself. The best way to do this is to create a shared library file that
can hold references to the pools for you. For example:
```js
const sql = require('mssql')
const pools = {}
// manage a set of pools by name (config will be required to create the pool)
// a pool will be removed when it is closed
async function getPool(name, config) {
if (!Object.prototype.hasOwnProperty.call(pools, name)) {
const pool = new sql.ConnectionPool(config)
const close = pool.close.bind(pool)
pool.close = (...args) => {
delete pools[name]
return close(...args)
}
await pool.connect()
pools[name] = pool
}
return pools[name]
}
// close all pools
function closeAll() {
return Promise.all(Object.values(pools).map((pool) => {
return pool.close()
}))
}
module.exports = {
closeAll,
getPool
}
```
You can then use this library file in your code to get a connected pool when you need it:
```js
const { getPool } = require('./path/to/file')
// run a query
async function runQuery(query, config) {
// pool will always be connected when the promise has resolved - may reject if the connection config is invalid
const pool = await getPool('default', config)
const result = await pool.request().query(query)
return result
}
```
## Configuration
```javascript
const config = {
user: '...',
password: '...',
server: 'localhost',
database: '...',
pool: {
max: 10,
min: 0,
idleTimeoutMillis: 30000
}
}
```
### General (same for all drivers)
- **user** - User name to use for authentication.
- **password** - Password to use for authentication.
- **server** - Server to connect to. You can use 'localhost\\instance' to connect to named instance.
- **port** - Port to connect to (default: `1433`). Don't set when connecting to named instance.
- **domain** - Once you set domain, driver will connect to SQL Server using domain login.
- **database** - Database to connect to (default: dependent on server configuration).
- **connectionTimeout** - Connection timeout in ms (default: `15000`).
- **requestTimeout** - Request timeout in ms (default: `15000`). NOTE: msnodesqlv8 driver doesn't support timeouts < 1 second. When passed via connection string, the key must be `request timeout`
- **stream** - Stream recordsets/rows instead of returning them all at once as an argument of callback (default: `false`). You can also enable streaming for each request independently (`request.stream = true`). Always set to `true` if you plan to work with large amount of rows.
- **parseJSON** - Parse JSON recordsets to JS objects (default: `false`). For more information please see section [JSON support](#json-support).
- **pool.max** - The maximum number of connections there can be in the pool (default: `10`).
- **pool.min** - The minimum of connections there can be in the pool (default: `0`).
- **pool.idleTimeoutMillis** - The Number of milliseconds before closing an unused connection (default: `30000`).
- **arrayRowMode** - Return row results as a an array instead of a keyed object. Also adds `columns` array. See [Handling Duplicate Column Names](#handling-duplicate-column-names)
Complete list of pool options can be found [here](https://github.com/vincit/tarn.js/#usage).
### Formats
In addition to configuration object there is an option to pass config as a connection string. Connection strings are supported.
##### Classic Connection String
```
Server=localhost,1433;Database=database;User Id=username;Password=password;Encrypt=true
Driver=msnodesqlv8;Server=(local)\INSTANCE;Database=database;UID=DOMAIN\username;PWD=password;Encrypt=true
```
## Drivers
### Tedious
Default driver, actively maintained and production ready. Platform independent, runs everywhere Node.js runs. Officially supported by Microsoft.
**Extra options:**
- **beforeConnect(conn)** - Function, which is invoked before opening the connection. The parameter `conn` is the configured tedious `Connection`. It can be used for attaching event handlers like in this example:
```js
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')})
}})
```
- **options.instanceName** - The instance name to connect to. The SQL Server Browser service must be running on the database server, and UDP port 1434 on the database server must be reachable.
- **options.useUTC** - A boolean determining whether or not use UTC time for values without time zone offset (default: `true`).
- **options.encrypt** - A boolean determining whether or not the connection will be encrypted (default: `true`).
- **options.tdsVersion** - The version of TDS to use (default: `7_4`, available: `7_1`, `7_2`, `7_3_A`, `7_3_B`, `7_4`).
- **options.appName** - Application name used for SQL server logging.
- **options.abortTransactionOnError** - A boolean determining whether to rollback a transaction automatically if any error is encountered during the given transaction's execution. This sets the value for `XACT_ABORT` during the initial SQL phase of a connection.
**Authentication:**
On top of the extra options, an `authentication` property can be added to the pool config option
- **authentication** - An object with authentication settings, according to the [Tedious Documentation](https://tediousjs.github.io/tedious/api-connection.html). Passing this object will override `user`, `password`, `domain` settings.
- **authentication.type** - Type of the authentication method, valid types are `default`, `ntlm`, `azure-active-directory-password`, `azure-active-directory-access-token`, `azure-active-directory-msi-vm`, or `azure-active-directory-msi-app-service`
- **authentication.options** - Options of the authentication required by the `tedious` driver, depends on `authentication.type`. For more details, check [Tedious Authentication Interfaces](https://github.com/tediousjs/tedious/blob/v11.1.1/src/connection.ts#L200-L318)
More information about Tedious specific options: http://tediousjs.github.io/tedious/api-connection.html
### Microsoft / Contributors Node V8 Driver for Node.js for SQL Server
**Requires Node.js v10+ or newer. Windows 32-64 bits or Linux/macOS 64 bits only.** This driver is not part of the default package and must be installed separately by `npm install msnodesqlv8@^2`. To use this driver, use this require syntax: `const sql = require('mssql/msnodesqlv8')`.
Note: If you use import into your lib to prepare your request (`const { VarChar } = require('mssql')`) you also need to upgrade all your types import into your code (`const { VarChar } = require('mssql/msnodesqlv8')`) or a `connection.on is not a function` error will be thrown.
**Extra options:**
- **beforeConnect(conn)** - Function, which is invoked before opening the connection. The parameter `conn` is the connection configuration, that can be modified to pass extra parameters to the driver's `open()` method.
- **connectionString** - Connection string (default: see below).
- **options.instanceName** - The instance name to connect to. The SQL Server Browser service must be running on the database server, and UDP port 1444 on the database server must be reachable.
- **options.trustedConnection** - Use Windows Authentication (default: `false`).
- **options.useUTC** - A boolean determining whether or not to use UTC time for values without time zone offset (default: `true`).
Default connection string when connecting to port:
```
Driver={SQL Server Native Client 11.0};Server={#{server},#{port}};Database={#{database}};Uid={#{user}};Pwd={#{password}};Trusted_Connection={#{trusted}};
```
Default connection string when connecting to named instance:
```
Driver={SQL Server Native Client 11.0};Server={#{server}\\#{instance}};Database={#{database}};Uid={#{user}};Pwd={#{password}};Trusted_Connection={#{trusted}};
```
Please note that the connection string with this driver is not the same than tedious and use yes/no instead of true/false. You can see more on the [ODBC](https://docs.microsoft.com/fr-fr/dotnet/api/system.data.odbc.odbcconnection.connectionstring?view=dotnet-plat-ext-5.0) documentation.
## 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 */ })
```
### Events
- **error(err)** - Dispatched on connection error.
---------------------------------------
### 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.
---------------------------------------
### close()
Close all active connections in the pool.
__Example__
```javascript
pool.close()
```
## Request
```javascript
const request = new sql.Request(/* [pool or transaction] */)
```
If you omit pool/transaction argument, global pool is used instead.
### Events
- **recordset(columns)** - Dispatched when metadata for new recordset are parsed.
- **row(row)** - Dispatched when new row is parsed.
- **done(returnValue)** - Dispatched when request is complete.
- **error(err)** - Dispatched on error.
- **info(message)** - Dispatched on informational message.
---------------------------------------
### execute (procedure, [callback])
Call a stored procedure.
__Arguments__
- **procedure** - Name of the stored procedure to be executed.
- **callback(err, recordsets, returnValue)** - A callback which is called after execution has completed, or an error has occurred. `returnValue` is also accessible as property of recordsets. Optional. If omitted, returns [Promise](#promises).
__Example__
```javascript
const request = new sql.Request()
request.input('input_parameter', sql.Int, value)
request.output('output_parameter', sql.Int)
request.execute('procedure_name', (err, result) => {
// ... error checks
console.log(result.recordsets.length) // count of recordsets returned by the procedure
console.log(result.recordsets[0].length) // count of rows contained in first recordset
console.log(result.recordset) // first recordset from result.recordsets
console.log(result.returnValue) // procedure return value
console.log(result.output) // key/value collection of output values
console.log(result.rowsAffected) // array of numbers, each number represents the number of rows affected by executed statemens
// ...
})
```
__Errors__
- EREQUEST (`RequestError`) - *Message from SQL Server*
- ECANCEL (`RequestError`) - Cancelled.
- ETIMEOUT (`RequestError`) - Request timeout.
- ENOCONN (`RequestError`) - No connection is specified for that request.
- ENOTOPEN (`ConnectionError`) - Connection not yet open.
- ECONNCLOSED (`ConnectionError`) - Connection is closed.
- ENOTBEGUN (`TransactionError`) - Transaction has not begun.
- EABORT (`TransactionError`) - Transaction was aborted (by user or because of an error).
---------------------------------------
### input (name, [type], value)
Add an input parameter to the request.
__Arguments__
- **name** - Name of the input parameter without @ char.
- **type** - SQL data type of input parameter. If you omit type, module automatically decide which SQL data type should be used based on JS data type.
- **value** - Input parameter value. `undefined` and `NaN` values are automatically converted to `null` values.
__Example__
```javascript
request.input('input_parameter', value)
request.input('input_parameter', sql.Int, value)
```
__JS Data Type To SQL Data Type Map__
- `String` -> `sql.NVarChar`
- `Number` -> `sql.Int`
- `Boolean` -> `sql.Bit`
- `Date` -> `sql.DateTime`
- `Buffer` -> `sql.VarBinary`
- `sql.Table` -> `sql.TVP`
Default data type for unknown object is `sql.NVarChar`.
You can define your own type map.
```javascript
sql.map.register(MyClass, sql.Text)
```
You can also overwrite the default type map.
```javascript
sql.map.register(Number, sql.BigInt)
```
__Errors__ (synchronous)
- EARGS (`RequestError`) - Invalid number of arguments.
- EINJECT (`RequestError`) - SQL injection warning.
---------------------------------------
NB: Do not use parameters `@p{n}` as these are used by the internal drivers and cause a conflict.
### output (name, type, [value])
Add an output parameter to the request.
__Arguments__
- **name** - Name of the output parameter without @ char.
- **type** - SQL data type of output parameter.
- **value** - Output parameter value initial value. `undefined` and `NaN` values are automatically converted to `null` values. Optional.
__Example__
```javascript
request.output('output_parameter', sql.Int)
request.output('output_parameter', sql.VarChar(50), 'abc')
```
__Errors__ (synchronous)
- EARGS (`RequestError`) - Invalid number of arguments.
- EINJECT (`RequestError`) - SQL injection warning.
---------------------------------------
### toReadableStream
Convert request to a Node.js ReadableStream
__Example__
```javascript
const { pipeline } = require('stream')
const request = new sql.Request()
const readableStream = request.toReadableStream()
pipeline(readableStream, transformStream, writableStream)
request.query('select * from mytable')
```
OR if you wanted to increase the highWaterMark of the read stream to buffer more rows in memory
```javascript
const { pipeline } = require('stream')
const request = new sql.Request()
const readableStream = request.toReadableStream({ highWaterMark: 100 })
pipeline(readableStream, transformStream, writableStream)
request.query('select * from mytable')
```
### pipe (stream)
Sets request to `stream` mode and pulls all rows from all recordsets to a given stream.
__Arguments__
- **stream** - Writable stream in object mode.
__Example__
```javascript
const request = new sql.Request()
request.pipe(stream)
request.query('select * from mytable')
stream.on('error', err => {
// ...
})
stream.on('finish', () => {
// ...
})
```
---------------------------------------
### query (command, [callback])
Execute the SQL command. To execute commands like `create procedure` or if you plan to work with local temporary tables, use [batch](#batch-batch-callback) instead.
__Arguments__
- **command** - T-SQL command to be executed.
- **callback(err, recordset)** - A callback which is called after execution has completed, or an error has occurred. Optional. If omitted, returns [Promise](#promises).
__Example__
```javascript
const request = new sql.Request()
request.query('select 1 as number', (err, result) => {
// ... error checks
console.log(result.recordset[0].number) // return 1
// ...
})
```
__Errors__
- ETIMEOUT (`RequestError`) - Request timeout.
- EREQUEST (`RequestError`) - *Message from SQL Server*
- ECANCEL (`RequestError`) - Cancelled.
- ENOCONN (`RequestError`) - No connection is specified for that request.
- ENOTOPEN (`ConnectionError`) - Connection not yet open.
- ECONNCLOSED (`ConnectionError`) - Connection is closed.
- ENOTBEGUN (`TransactionError`) - Transaction has not begun.
- EABORT (`TransactionError`) - Transaction was aborted (by user or because of an error).
```javascript
const request = new sql.Request()
request.query('select 1 as number; select 2 as number', (err, result) => {
// ... error checks
console.log(result.recordset[0].number) // return 1
console.log(result.recordsets[0][0].number) // return 1
console.log(result.recordsets[1][0].number) // return 2
})
```
**NOTE**: To get number of rows affected by the statement(s), see section [Affected Rows](#affected-rows).
---------------------------------------
### batch (batch, [callback])
Execute the SQL command. Unlike [query](#query-command-callback), it doesn't use `sp_executesql`, so is not likely that SQL Server will reuse the execution plan it generates for the SQL. Use this only in special cases, for example when you need to execute commands like `create procedure` which can't be executed with [query](#query-command-callback) or if you're executing statements longer than 4000 chars on SQL Server 2000. Also you should use this if you're plan to work with local temporary tables ([more information here](http://weblogs.sqlteam.com/mladenp/archive/2006/11/03/17197.aspx)).
NOTE: Table-Valued Parameter (TVP) is not supported in batch.
__Arguments__
- **batch** - T-SQL command to be executed.
- **callback(err, recordset)** - A callback which is called after execution has completed, or an error has occurred. Optional. If omitted, returns [Promise](#promises).
__Example__
```javascript
const request = new sql.Request()
request.batch('create procedure #temporary as select * from table', (err, result) => {
// ... error checks
})
```
__Errors__
- ETIMEOUT (`RequestError`) - Request timeout.
- EREQUEST (`RequestError`) - *Message from SQL Server*
- ECANCEL (`RequestError`) - Cancelled.
- ENOCONN (`RequestError`) - No connection is specified for that request.
- ENOTOPEN (`ConnectionError`) - Connection not yet open.
- ECONNCLOSED (`ConnectionError`) - Connection is closed.
- ENOTBEGUN (`TransactionError`) - Transaction has not begun.
- EABORT (`TransactionError`) - Transaction was aborted (by user or because of an error).
You can enable multiple recordsets in queries with the `request.multiple = true` command.
---------------------------------------
### bulk (table, [options,] [callback])
Perform a bulk insert.
__Arguments__
- **table** - `sql.Table` instance.
- **options** - Options object to be passed through to driver (currently tedious only). Optional. If argument is a function it will be treated as the callback.
- **callback(err, rowCount)** - A callback which is called after bulk insert has completed, or an error has occurred. Optional. If omitted, returns [Promise](#promises).
__Example__
```javascript
const table = new sql.Table('table_name') // or temporary table, e.g. #temptable
table.create = true
table.columns.add('a', sql.Int, {nullable: true, primary: true})
table.columns.add('b', sql.VarChar(50), {nullable: false})
table.rows.add(777, 'test')
const request = new sql.Request()
request.bulk(table, (err, result) => {
// ... error checks
})
```
**IMPORTANT**: Always indicate whether the column is nullable or not!
**TIP**: If you set `table.create` to `true`, module will check if the table exists before it start sending data. If it doesn't, it will automatically create it. You can specify primary key columns by setting `primary: true` to column's options. Primary key constraint on multiple columns is supported.
**TIP**: You can also create Table variable from any recordset with `recordset.toTable()`. You can optionally specify table type name in the first argument.
__Errors__
- ENAME (`RequestError`) - Table name must be specified for bulk insert.
- ETIMEOUT (`RequestError`) - Request timeout.
- EREQUEST (`RequestError`) - *Message from SQL Server*
- ECANCEL (`RequestError`) - Cancelled.
- ENOCONN (`RequestError`) - No connection is specified for that request.
- ENOTOPEN (`ConnectionError`) - Connection not yet open.
- ECONNCLOSED (`ConnectionError`) - Connection is closed.
- ENOTBEGUN (`TransactionError`) - Transaction has not begun.
- EABORT (`TransactionError`) - Transaction was aborted (by user or because of an error).
---------------------------------------
### cancel()
Cancel currently executing request. Return `true` if cancellation packet was send successfully.
__Example__
```javascript
const request = new sql.Request()
request.query('waitfor delay \'00:00:05\'; select 1 as number', (err, result) => {
console.log(err instanceof sql.RequestError) // true
console.log(err.message) // Cancelled.
console.log(err.code) // ECANCEL
// ...
})
request.cancel()
```
## Transaction
**IMPORTANT:** always use `Transaction` class to create transactions - it ensures that all your requests are executed on one connection. Once you call `begin`, a single connection is acquired from the connection pool and all subsequent requests (initialized with the `Transaction` object) are executed exclusively on this connection. After you call `commit` or `rollback`, connection is then released back to the connection pool.
```javascript
const transaction = new sql.Transaction(/* [pool] */)
```
If you omit connection argument, global connection is used instead.
__Example__
```javascript
const transaction = new sql.Transaction(/* [pool] */)
transaction.begin(err => {
// ... error checks
const request = new sql.Request(transaction)
request.query('insert into mytable (mycolumn) values (12345)', (err, result) => {
// ... error checks
transaction.commit(err => {
// ... error checks
console.log("Transaction committed.")
})
})
})
```
Transaction can also be created by `const transaction = pool.transaction()`. Requests can also be created by `const request = transaction.request()`.
__Aborted transactions__
This example shows how you should correctly handle transaction errors when `abortTransactionOnError` (`XACT_ABORT`) is enabled. Added in 2.0.
```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
})
}
})
})
```
### Events
- **begin** - Dispatched when transaction begin.
- **commit** - Dispatched on successful commit.
- **rollback(aborted)** - Dispatched on successful rollback with an argument determining if the transaction was aborted (by user or because of an error).
---------------------------------------
### begin ([isolationLevel], [callback])
Begin a transaction.
__Arguments__
- **isolationLevel** - Controls the locking and row versioning behavior of TSQL statements issued by a connection. Optional. `READ_COMMITTED` by default. For possible values see `sql.ISOLATION_LEVEL`.
- **callback(err)** - A callback which is called after transaction has began, or an error has occurred. Optional. If omitted, returns [Promise](#promises).
__Example__
```javascript
const transaction = new sql.Transaction()
transaction.begin(err => {
// ... error checks
})
```
__Errors__
- ENOTOPEN (`ConnectionError`) - Connection not yet open.
- EALREADYBEGUN (`TransactionError`) - Transaction has already begun.
---------------------------------------
### commit ([callback])
Commit a transaction.
__Arguments__
- **callback(err)** - A callback which is called after transaction has committed, or an error has occurred. Optional. If omitted, returns [Promise](#promises).
__Example__
```javascript
const transaction = new sql.Transaction()
transaction.begin(err => {
// ... error checks
transaction.commit(err => {
// ... error checks
})
})
```
__Errors__
- ENOTBEGUN (`TransactionError`) - Transaction has not begun.
- EREQINPROG (`TransactionError`) - Can't commit transaction. There is a request in progress.
---------------------------------------
### rollback ([callback])
Rollback a transaction. If the queue isn't empty, all queued requests will be Cancelled and the transaction will be marked as aborted.
__Arguments__
- **callback(err)** - A callback which is called after transaction has rolled back, or an error has occurred. Optional. If omitted, returns [Promise](#promises).
__Example__
```javascript
const transaction = new sql.Transaction()
transaction.begin(err => {
// ... error checks
transaction.rollback(err => {
// ... error checks
})
})
```
__Errors__
- ENOTBEGUN (`TransactionError`) - Transaction has not begun.
- EREQINPROG (`TransactionError`) - Can't rollback transaction. There is a request in progress.
## Prepared Statement
**IMPORTANT:** always use `PreparedStatement` class to create prepared statements - it ensures that all your executions of prepared statement are executed on one connection. Once you call `prepare`, a single connection is acquired from the connection pool and all subsequent executions are executed exclusively on this connection. After you call `unprepare`, the connection is then released back to the connection pool.
```javascript
const ps = new sql.PreparedStatement(/* [pool] */)
```
If you omit the connection argument, the global connection is used instead.
__Example__
```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
})
})
})
```
**IMPORTANT**: Remember that each prepared statement means one reserved connection from the pool. Don't forget to unprepare a prepared statement when you've finished your queries!
You can execute multiple queries against the same prepared statement but you *must* unprepare the statement when you have finished using it otherwise you will cause the connection pool to run out of available connections.
**TIP**: You can also create prepared statements in transactions (`new sql.PreparedStatement(transaction)`), but keep in mind you can't execute other requests in the transaction until you call `unprepare`.
---------------------------------------
### input (name, type)
Add an input parameter to the prepared statement.
__Arguments__
- **name** - Name of the input parameter without @ char.
- **type** - SQL data type of input parameter.
__Example__
```javascript
ps.input('input_parameter', sql.Int)
ps.input('input_parameter', sql.VarChar(50))
```
__Errors__ (synchronous)
- EARGS (`PreparedStatementError`) - Invalid number of arguments.
- EINJECT (`PreparedStatementError`) - SQL injection warning.
---------------------------------------
### output (name, type)
Add an output parameter to the prepared statement.
__Arguments__
- **name** - Name of the output parameter without @ char.
- **type** - SQL data type of output parameter.
__Example__
```javascript
ps.output('output_parameter', sql.Int)
ps.output('output_parameter', sql.VarChar(50))
```
__Errors__ (synchronous)
- EARGS (`PreparedStatementError`) - Invalid number of arguments.
- EINJECT (`PreparedStatementError`) - SQL injection warning.
---------------------------------------
### prepare (statement, [callback])
Prepare a statement.
__Arguments__
- **statement** - T-SQL statement to prepare.
- **callback(err)** - A callback which is called after preparation has completed, or an error has occurred. Optional. If omitted, returns [Promise](#promises).
__Example__
```javascript
const ps = new sql.PreparedStatement()
ps.prepare('select @param as value', err => {
// ... error checks
})
```
__Errors__
- ENOTOPEN (`ConnectionError`) - Connection not yet open.
- EALREADYPREPARED (`PreparedStatementError`) - Statement is already prepared.
- ENOTBEGUN (`TransactionError`) - Transaction has not begun.
---------------------------------------
### execute (values, [callback])
Execute a prepared statement.
__Arguments__
- **values** - An object whose names correspond to the names of parameters that were added to the prepared statement before it was prepared.
- **callback(err)** - A callback which is called after execution has completed, or an error has occurred. Optional. If omitted, returns [Promise](#promises).
__Example__
```javascript
const ps = new sql.PreparedStatement()
ps.input('param', sql.Int)
ps.prepare('select @param as value', err => {
// ... error checks
ps.execute({param: 12345}, (err, result) => {
// ... error checks
console.log(result.recordset[0].value) // return 12345
console.log(result.rowsAffected) // Returns number of affected rows in case of INSERT, UPDATE or DELETE statement.
ps.unprepare(err => {
// ... error checks
})
})
})
```
You can also stream executed request.
```javascript
const ps = new sql.PreparedStatement()
ps.input('param', sql.Int)
ps.prepare('select @param as value', err => {
// ... error checks
ps.stream = true
const request = ps.execute({param: 12345})
request.on('recordset', columns => {
// Emitted once for each recordset in a query
})
request.on('row', row => {
// Emitted for each row in a recordset
})
request.on('error', err => {
// May be emitted multiple times
})
request.on('done', result => {
// Always emitted as the last one
console.log(result.rowsAffected) // Returns number of affected rows in case of INSERT, UPDATE or DELETE statement.
ps.unprepare(err => {
// ... error checks
})
})
})
```
**TIP**: To learn more about how number of affected rows works, see section [Affected Rows](#affected-rows).
__Errors__
- ENOTPREPARED (`PreparedStatementError`) - Statement is not prepared.
- ETIMEOUT (`RequestError`) - Request timeout.
- EREQUEST (`RequestError`) - *Message from SQL Server*
- ECANCEL (`RequestError`) - Cancelled.
---------------------------------------
### unprepare ([callback])
Unprepare a prepared statement.
__Arguments__
- **callback(err)** - A callback which is called after unpreparation has completed, or an error has occurred. Optional. If omitted, returns [Promise](#promises).
__Example__
```javascript
const ps = new sql.PreparedStatement()
ps.input('param', sql.Int)
ps.prepare('select @param as value', err => {
// ... error checks
ps.unprepare(err => {
// ... error checks
})
})
```
__Errors__
- ENOTPREPARED (`PreparedStatementError`) - Statement is not prepared.
## CLI
Before you can start using CLI, you must install `mssql` globally with `npm install mssql -g`. Once you do that you will be able to execute `mssql` command.
__Setup__
Create a `.mssql.json` configuration file (anywhere). Structure of the file is the same as the standard configuration object.
```json
{
"user": "...",
"password": "...",
"server": "localhost",
"database": "..."
}
```
__Example__
```shell
echo "select * from mytable" | mssql /path/to/config
```
Results in:
```json
[[{"username":"patriksimek","password":"tooeasy"}]]
```
You can also query for multiple recordsets.
```shell
echo "select * from mytable; select * from myothertable" | mssql
```
Results in:
```json
[[{"username":"patriksimek","password":"tooeasy"}],[{"id":15,"name":"Product name"}]]
```
If you omit config path argument, mssql will try to load it from current working directory.
## Geography and Geometry
node-mssql has built-in deserializer for Geography and Geometry CLR data types.
### Geography
Geography types can be constructed several different ways. Refer carefully to documentation to verify the coordinate ordering; the ST methods tend to order parameters as longitude (x) then latitude (y), while custom CLR methods tend to prefer to order them as latitude (y) then longitude (x).
The query:
```sql
select geography::STGeomFromText(N'POLYGON((1 1, 3 1, 3 1, 1 1))',4326)
```
results in:
```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: []
}
```
**NOTE