node-mssql
An easy-to-use MSSQL database wrapper for Node.js / IO.js.
There are some TDS modules which offer functionality to communicate with MSSQL databases but none of them does offer enough comfort - implementation takes a lot of lines of code. So I decided to create this module, that make work as easy as it could without losing any important functionality. node-mssql uses other TDS modules as drivers and offer easy to use unified interface. It also add extra features and bug fixes.
Extra features:
- Unified interface for multiple MSSQL drivers
- Connection pooling with Transactions and Prepared statements
- Parametrized Stored Procedures for all drivers
- Serialization of Geography and Geometry CLR types
- Smart JS data type to SQL data type mapper
- Support both Promises and standard callbacks
- Query building API by parameters
At the moment it support three TDS modules:
What's new (stable, npm)
Installation
npm install node-mssql
Quick Example
Insert Operation:
```javascript
var node_mssql = require('node-mssql');
/* add configuration to query object */
var queryObj = new node_mssql.Query({
host: 'x.x.x.x', // You can use 'x.x.x.x\instance' to connect to named instance
port: 1433,
username: 'myuser',
password: 'mypassword',
database: 'mydatabase'
});
/* set table name to operate */
queryObj.table('dbo.mytable');
/* set required data to be inserted */
queryObj.data({
'title': 'My Test Insert',
'description': 'My test insert description'
});
/* run insert query and fetch response */
queryObj.insert(function(results) {
// success callback
console.log(results);
}, function(err, sql) {
// failed callback
if(err)
console.log(err);
console.log(sql);
});
<h6>Update Operation:</h6>
```javascript
var node_mssql = require('node-mssql');
/* add configuration to query object */
var queryObj = new node_mssql.Query({
host: 'x.x.x.x', // You can use 'x.x.x.x\\instance' to connect to named instance
port: 1433,
username: 'myuser',
password: 'mypassword',
database: 'mydatabase'
});
/* set table name to operate */
queryObj.table('dbo.mytable');
/* set required data to be updated */
queryObj.data({
'title': 'My Test Insert',
'description': 'My test insert description'
});
/* set update query condition */
queryObj.where({
'title': 'My Test',
})
/* run update query and fetch response */
queryObj.update(function(results) {
// success callback
console.log(results);
}, function(err, sql) {
// failed callback
if(err)
console.log(err);
console.log(sql);
});
Select Operation:
```javascript
var node_mssql = require('node-mssql');
/* add configuration to query object */
var queryObj = new node_mssql.Query({
host: 'x.x.x.x', // You can use 'x.x.x.x\instance' to connect to named instance
port: 1433,
username: 'myuser',
password: 'mypassword',
database: 'mydatabase'
});
/* set table name to operate */
queryObj.table('dbo.mytable');
/* set update query condition */
queryObj.where({
'title': 'My Test',
})
/* run update query and fetch response */
queryObj.select(function(results) {
// success callback
console.log(results);
}, function(err, sql) {
// failed callback
if(err)
console.log(err);
console.log(sql);
});
## Documentation
### Configuration
* [Basic](#cfg-basic)
* [Tedious](#cfg-tedious)
* [Microsoft Driver for Node.js for SQL Server](#cfg-msnodesql)
* [node-tds](#cfg-node-tds)
### Connections
* [Connection](#connection)
* [connect](#connect)
* [close](#close)
### Requests
* [Request](#request)
* [execute](#execute)
* [input](#input)
* [output](#output)
* [pipe](#pipe)
* [query](#query)
* [batch](#batch)
* [bulk](#bulk)
* [cancel](#cancel)
### Transactions
* [Transaction](#transaction)
* [begin](#begin)
* [commit](#commit)
* [rollback](#rollback)
### Prepared Statements
* [PreparedStatement](#prepared-statement)
* [input](#prepared-statement-input)
* [output](#prepared-statement-output)
* [prepare](#prepare)
* [execute](#prepared-statement-execute)
* [unprepare](#unprepare)
### Other
* [CLI](#cli)
* [Geography and Geometry](#geography)
* [Table-Valued Parameter](#tvp)
* [Errors](#errors)
* [Promises](#promises)
* [Metadata](#meta)
* [Data Types](#data-types)
* [SQL injection](#injection)
* [Verbose Mode](#verbose)
* [Known Issues](#issues)
## Configuration
```javascript
var config = {
user: '...',
password: '...',
server: 'localhost',
database: '...',
pool: {
max: 10,
min: 0,
idleTimeoutMillis: 30000
}
}
### Basic configuration is same for all drivers.
- driver - Driver to use (default:
tedious
). Possible values: tedious
, msnodesql
or tds
. - 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
). - 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. - pool.max - The maximum number of connections there can be in the pool (default:
10
). - pool.min - The minimun of connections there can be in the pool (default:
0
). - pool.idleTimeoutMillis - The Number of milliseconds before closing an unused connection (default:
30000
).
### Tedious
- 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.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:
false
) Encryption support is experimental. - 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.
More information about Tedious specific options: http://pekim.github.io/tedious/api-connection.html
### Microsoft Driver for Node.js for SQL Server
This driver is not part of the default package and must be installed separately by npm install msnodesql
. If you are looking for compiled binaries, see node-sqlserver-binary.
- 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.
- connectionString - Connection string (default: see below).
- 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}};
### node-tds
This driver is not part of the default package and must be installed separately by npm install tds
.
This module updates the node-tds driver with extra features and bug fixes by overriding some of its internal functions. If you want to disable this, require module with var sql = require('mssql/nofix')
.
## Connections
var connection = new sql.Connection({ });
Errors
- EDRIVER (
ConnectionError
) - Unknown driver.
Events
- connect - Dispatched after connection has established.
- close - Dispatched after connection has closed a pool (by calling
close
). - error(err) - Dispatched on error.
### connect([callback])
Create connection to the server.
Arguments
Example
var connection = new sql.Connection({
user: '...',
password: '...',
server: 'localhost',
database: '...'
});
connection.connect(function(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 connection to the server.
Example
connection.close();
## Requests
var request = new sql.Request();
If you omit connection argument, global connection 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.
### execute(procedure, [callback])
Call a stored procedure.
Arguments
Example
var request = new sql.Request();
request.input('input_parameter', sql.Int, value);
request.output('output_parameter', sql.Int);
request.execute('procedure_name', function(err, recordsets, returnValue) {
console.log(recordsets.length);
console.log(recordsets[0].length);
console.log(returnValue);
console.log(recordsets.returnValue);
console.log(request.parameters.output_parameter.value);
});
Errors
- EREQUEST (
RequestError
) - Message from SQL Server - ECANCEL (
RequestError
) - Canceled. - 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 automaticaly decide which SQL data type should be used based on JS data type.
- value - Input parameter value.
undefined
ans NaN
values are automatically converted to null
values.
Example
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.
sql.map.register(MyClass, sql.Text);
You can also overwrite the default type map.
sql.map.register(Number, sql.BigInt);
Errors (synchronous)
- EARGS (
RequestError
) - Invalid number of arguments. - EINJECT (
RequestError
) - SQL injection warning.
### 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
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.
### 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
var request = new sql.Request();
request.pipe(stream);
request.query('select * from mytable');
stream.on('error', function(err) {
});
stream.on('finish', function() {
});
Version
2.0
### 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 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 omited, returns Promise.
Example
var request = new sql.Request();
request.query('select 1 as number', function(err, recordset) {
console.log(recordset[0].number);
});
Errors
- ETIMEOUT (
RequestError
) - Request timeout. - EREQUEST (
RequestError
) - Message from SQL Server - ECANCEL (
RequestError
) - Canceled. - 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.
var request = new sql.Request();
request.multiple = true;
request.query('select 1 as number; select 2 as number', function(err, recordsets) {
console.log(recordsets[0][0].number);
console.log(recordsets[1][0].number);
});
### batch(batch, [callback])
Execute the SQL command. Unlike query, 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 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).
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 omited, returns Promise.
Example
var request = new sql.Request();
request.batch('create procedure #temporary as select * from table', function(err, recordset) {
});
Errors
- ETIMEOUT (
RequestError
) - Request timeout. - EREQUEST (
RequestError
) - Message from SQL Server - ECANCEL (
RequestError
) - Canceled. - 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, [callback])
Perform a bulk insert.
Arguments
Example
var table = new sql.Table('table_name');
table.create = true;
table.columns.add('a', sql.Int, {nullable: true});
table.columns.add('b', sql.VarChar(50), {nullable: false});
table.rows.add(777, 'test');
var request = new sql.Request();
request.bulk(table, function(err, rowCount) {
});
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.
TIP: You can also create Table variable from any recordset with recordset.toTable()
.
Errors
- ENAME (
RequestError
) - Table name must be specified for bulk insert. - ETIMEOUT (
RequestError
) - Request timeout. - EREQUEST (
RequestError
) - Message from SQL Server - ECANCEL (
RequestError
) - Canceled. - 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
var request = new sql.Request();
request.query('waitfor delay \'00:00:05\'; select 1 as number', function(err, recordset) {
console.log(err instanceof sql.RequestError);
console.log(err.message);
console.log(err.code);
});
request.cancel();
## Transactions
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. Transaction also contains a queue to make sure your requests are executed in series. After you call commit
or rollback
, connection is then released back to the connection pool.
var transaction = new sql.Transaction();
If you omit connection argument, global connection is used instead.
Example
var transaction = new sql.Transaction();
transaction.begin(function(err) {
var request = new sql.Request(transaction);
request.query('insert into mytable (mycolumn) values (12345)', function(err, recordset) {
transaction.commit(function(err, recordset) {
console.log("Transaction commited.");
});
});
});
Transaction can also be created by var transaction = connection.transaction();
. Requests can also be created by var 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.
var transaction = new sql.Transaction();
transaction.begin(function(err) {
var rolledBack = false;
transaction.on('rollback', function(aborted) {
rolledBack = true;
});
var request = new sql.Request(transaction);
request.query('insert into mytable (bitcolumn) values (2)', function(err, recordset) {
if (err) {
if (!rolledBack) {
transaction.rollback(function(err) {
});
}
} else {
transaction.commit(function(err) {
});
}
});
});
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
Example
var transaction = new sql.Transaction();
transaction.begin(function(err) {
});
Errors
- ENOTOPEN (
ConnectionError
) - Connection not yet open. - EALREADYBEGUN (
TransactionError
) - Transaction has already begun.
### commit([callback])
Commit a transaction.
Arguments
Example
var transaction = new sql.Transaction();
transaction.begin(function(err) {
transaction.commit(function(err) {
})
});
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 canceled and the transaction will be marked as aborted.
Arguments
Example
var transaction = new sql.Transaction();
transaction.begin(function(err) {
transaction.rollback(function(err) {
})
});
Errors
- ENOTBEGUN (
TransactionError
) - Transaction has not begun. - EREQINPROG (
TransactionError
) - Can't rollback transaction. There is a request in progress.
## PreparedStatement
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 aquired from the connection pool and all subsequent executions are executed exclusively on this connection. Prepared Statement also contains a queue to make sure your executions are executed in series. After you call unprepare
, the connection is then released back to the connection pool.
var ps = new sql.PreparedStatement();
If you omit the connection argument, the global connection is used instead.
Example
var ps = new sql.PreparedStatement();
ps.input('param', sql.Int);
ps.prepare('select @param as value', function(err) {
ps.execute({param: 12345}, function(err, recordset) {
ps.unprepare(function(err) {
});
});
});
IMPORTANT: Remember that each prepared statement means one reserved connection from the pool. Don't forget to unprepare a prepared statement!
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
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
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
Example
var ps = new sql.PreparedStatement();
ps.prepare('select @param as value', function(err) {
});
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
Example
var ps = new sql.PreparedStatement();
ps.input('param', sql.Int);
ps.prepare('select @param as value', function(err) {
ps.execute({param: 12345}, function(err, recordset) {
console.log(recordset[0].value);
});
});
You can enable multiple recordsets by ps.multiple = true
command.
var ps = new sql.PreparedStatement();
ps.input('param', sql.Int);
ps.prepare('select @param as value', function(err) {
ps.multiple = true;
ps.execute({param: 12345}, function(err, recordsets) {
console.log(recordsets[0][0].value);
});
});
You can also stream executed request.
var ps = new sql.PreparedStatement();
ps.input('param', sql.Int);
ps.prepare('select @param as value', function(err) {
ps.stream = true;
request = ps.execute({param: 12345});
request.on('recordset', function(columns) {
});
request.on('row', function(row) {
});
request.on('error', function(err) {
});
request.on('done', function(returnValue) {
});
});
Errors
- ENOTPREPARED (
PreparedStatementError
) - Statement is not prepared. - ETIMEOUT (
RequestError
) - Request timeout. - EREQUEST (
RequestError
) - Message from SQL Server - ECANCEL (
RequestError
) - Canceled.
### unprepare([callback])
Unprepare a prepared statement.
Arguments
Example
var ps = new sql.PreparedStatement();
ps.input('param', sql.Int);
ps.prepare('select @param as value', function(err, recordsets) {
ps.unprepare(function(err) {
});
});
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.
{
"user": "...",
"password": "...",
"server": "localhost",
"database": "..."
}
Example
echo "select * from mytable" | mssql /path/to/config
Results in:
[[{"username":"patriksimek","password":"tooeasy"}]]
You can also query for multiple recordsets.
echo "select * from mytable; slect * from myothertable" | mssql
Results in:
[[{"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.
Version
2.0
## Geography and Geometry
node-mssql has built-in serializer for Geography and Geometry CLR data types.
select geography::STGeomFromText('LINESTRING(-122.360 47.656, -122.343 47.656 )', 4326)
select geometry::STGeomFromText('LINESTRING (100 100 10.3 12, 20 180, 180 180)', 0)
Results in:
{ srid: 4326,
version: 1,
points: [ { x: 47.656, y: -122.36 }, { x: 47.656, y: -122.343 } ],
figures: [ { attribute: 1, pointOffset: 0 } ],
shapes: [ { parentOffset: -1, figureOffset: 0, type: 2 } ],
segments: [] }
{ srid: 0,
version: 1,
points:
[ { x: 100, y: 100, z: 10.3, m: 12 },
{ x: 20, y: 180, z: NaN, m: NaN },
{ x: 180, y: 180, z: NaN, m: NaN } ],
figures: [ { attribute: 1, pointOffset: 0 } ],
shapes: [ { parentOffset: -1, figureOffset: 0, type: 2 } ],
segments: [] }
## Table-Valued Parameter (TVP)
Supported on SQL Server 2008 and later. You can pass a data table as a parameter to stored procedure. First, we have to create custom type in our database.
CREATE TYPE TestType AS TABLE ( a VARCHAR(50), b INT );
Next we will need a stored procedure.
CREATE PROCEDURE MyCustomStoredProcedure (@tvp TestType readonly) AS SELECT * FROM @tvp
Now let's go back to our Node.js app.
var tvp = new sql.Table()
tvp.columns.add('a', sql.VarChar(50));
tvp.columns.add('b', sql.Int);
tvp.rows.add('hello tvp', 777);
You can send table as a parameter to stored procedure.
var request = new sql.Request();
request.input('tvp', tvp);
request.execute('MyCustomStoredProcedure', function(err, recordsets, returnValue) {
console.dir(recordsets[0][0]);
});
TIP: You can also create Table variable from any recordset with recordset.toTable()
.
## Promises
You can retrieve a Promise when you omit a callback argument.
var connection = new sql.Connection(config);
connection.connect().then(function() {
var request = new sql.Request(connection);
request.query('select * from mytable').then(function(recordset) {
}).catch(function(err) {
});
}).catch(function(err) {
});
Native Promise is returned by default. You can easily change this with sql.Promise = require('myownpromisepackage')
.
Version
2.0
## Errors
There are three type of errors you can handle:
- ConnectionError - Errors related to connections and connection pool.
- TransactionError - Errors related to creating, commiting and rolling back transactions.
- RequestError - Errors related to queries and stored procedures execution.
- PreparedStatementError - Errors related to prepared statements.
Those errors are initialized in node-mssql module and its original stack may be cropped. You can always access original error with err.originalError
.
SQL Server may generate more than one error for one request so you can access preceding errors with err.precedingErrors
.
Error Codes
Each known error has code
property.
Type | Code | Description |
---|
ConnectionError | ELOGIN | Login failed. |
ConnectionError | ETIMEOUT | Connection timeout. |
ConnectionError | EDRIVER | Unknown driver. |
ConnectionError | EALREADYCONNECTED | Database is already connected! |
ConnectionError | EALREADYCONNECTING | Already connecting to database! |
ConnectionError | ENOTOPEN | Connection not yet open. |
ConnectionError | EINSTLOOKUP | Instance lookup failed. |
ConnectionError | ESOCKET | Scoket error. |
ConnectionError | ECONNCLOSED | Connection is closed. |
TransactionError | ENOTBEGUN | Transaction has not begun. |
TransactionError | EALREADYBEGUN | Transaction has already begun. |
TransactionError | EREQINPROG | Can't commit/rollback transaction. There is a request in progress. |
TransactionError | EABORT | Transaction has been aborted. |
RequestError | EREQUEST | Message from SQL Server. Error object contains additional details. |
RequestError | ECANCEL | Canceled. |
RequestError | ETIMEOUT | Request timeout. |
RequestError | EARGS | Invalid number of arguments. |
RequestError | EINJECT | SQL injection warning. |
RequestError | ENOCONN | No connection is specified for that request. |
PreparedStatementError | EARGS | Invalid number of arguments. |
PreparedStatementError | EINJECT | SQL injection warning. |
PreparedStatementError | EALREADYPREPARED | Statement is already prepared. |
PreparedStatementError | ENOTPREPARED | Statement is not prepared. |
Detailed SQL Errors
SQL errors (RequestError
with err.code
equal to EREQUEST
) contains additional details.
## Metadata
Recordset metadata are accessible through the recordset.columns
property.
var request = new sql.Request();
request.query('select convert(decimal(18, 4), 1) as first, \'asdf\' as second', function(err, recordset) {
console.dir(recordset.columns);
console.log(recordset.columns.first.type === sql.Decimal);
console.log(recordset.columns.second.type === sql.VarChar);
});
Columns structure for example above:
{ first: { index: 0, name: 'first', length: 17, type: [sql.Decimal], scale: 4, precision: 18 },
second: { index: 1, name: 'second', length: 4, type: [sql.VarChar] } }
## Data Types
You can define data types with length/precision/scale:
request.input("name", sql.VarChar, "abc");
request.input("name", sql.VarChar(50), "abc");
request.input("name", sql.VarChar(sql.MAX), "abc");
request.output("name", sql.VarChar);
request.output("name", sql.VarChar, "abc");
request.input("name", sql.Decimal, 155.33);
request.input("name", sql.Decimal(10), 155.33);
request.input("name", sql.Decimal(10, 2), 155.33);
request.input("name", sql.DateTime2, new Date());
request.input("name", sql.DateTime2(5), new Date());
List of supported data types:
sql.Bit
sql.BigInt
sql.Decimal ([precision], [scale])
sql.Float
sql.Int
sql.Money
sql.Numeric ([precision], [scale])
sql.SmallInt
sql.SmallMoney
sql.Real
sql.TinyInt
sql.Char ([length])
sql.NChar ([length])
sql.Text
sql.NText
sql.VarChar ([length])
sql.NVarChar ([length])
sql.Xml
sql.Time ([scale])
sql.Date
sql.DateTime
sql.DateTime2 ([scale])
sql.DateTimeOffset ([scale])
sql.SmallDateTime
sql.UniqueIdentifier
sql.Binary
sql.VarBinary ([length])
sql.Image
sql.UDT
sql.Geography
sql.Geometry
To setup MAX length for VarChar
, NVarChar
and VarBinary
use sql.MAX
length.
## SQL injection
This module has built-in SQL injection protection. Always use parameters to pass sanitized values to your queries.
var request = new sql.Request();
request.input('myval', sql.VarChar, '-- commented');
request.query('select @myval as myval', function(err, recordset) {
console.dir(recordset);
});
## Verbose Mode
You can enable verbose mode by request.verbose = true
command.
## License
Copyright (c) 2014-2015 Techunits
The MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.