Giter Club home page Giter Club logo

node-mssql's Introduction

node-mssql

Microsoft SQL Server client for Node.js

NPM Version NPM Downloads Appveyor CI Join the chat at https://gitter.im/patriksimek/node-mssql

Supported TDS drivers:

Installation

npm install mssql

Short Example: Use Connect String

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 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:

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

Configuration

Drivers

Connections

Requests

Transactions

Prepared Statements

Other

Examples

Config

const config = {
    user: '...',
    password: '...',
    server: 'localhost', // You can use 'localhost\\instance' to connect to named instance
    database: '...',
}

Async/Await

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

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

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

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

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.

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:

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();
}

Connection Pools

An important concept to understand when using this library is Connection Pooling 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 sql.connect() function that is used to connect to the global connection pool. You can make repeated calls to this function, and if the global pool is already connected, it will resolve to the connected pool. The following example obtains the global connection pool by running sql.connect(), and then runs the query against the pool.

NB: It's important to note that there can only be one global connection pool connected at a time. Providing a different connection config to the connect() function will not create a new connection if it is already connected.

const sql = require('mssql')
const config = { ... }

// run a query against the global connection pool
function runQuery(query) {
  // sql.connect() will return the existing global pool if it exists or create a new one if it doesn't
  return sql.connect(config).then((pool) => {
    return pool.query(query)
  })
}

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 connect() call.

Also notice that we do not close the global pool by calling sql.close() after the query is executed, because other queries may need to be run against this pool and closing it will add additional overhead to running subsequent queries. You should only ever close the global pool if you're certain the application is finished. Or for example, if you are running some kind of CLI tool or a CRON job you can close the pool at the end of the script.

Global Pool Single Instance

The ability to call connect() and close() repeatedly on the global pool is intended to make pool management easier, however it is better to maintain your own reference to the pool, where connect() is called once, and the resulting global pool's connection promise is re-used throughout the entire application.

For example, in Express applications, the following approach uses a single global pool instance added to the app.locals so the application has access to it when needed. The server start is then chained inside the connect() promise.

const express = require('express')
const sql = require('mssql')
const config  = {/*...*/}
//instantiate a connection pool
const appPool = new sql.ConnectionPool(config)
//require route handlers and use the same connection pool everywhere
const route1 = require('./routes/route1')
const app = express()
app.get('/path', route1)

//connect the pool and start the web server when done
appPool.connect().then(function(pool) {
  app.locals.db = pool;
  const server = app.listen(3000, function () {
    const host = server.address().address
    const port = server.address().port
    console.log('Example app listening at http://%s:%s', host, port)
  })
}).catch(function(err) {
  console.error('Error creating connection pool', err)
});

Then the route uses the connection pool in the app.locals object:

// ./routes/route1.js
const sql = require('mssql');

module.exports = function(req, res) {
  req.app.locals.db.query('SELECT TOP 10 * FROM table_name', function(err, recordset) {
    if (err) {
      console.error(err)
      res.status(500).send('SERVER ERROR')
      return
    }
    res.status(200).json({ message: 'success' })
  })
}

Advanced Pool Management

For some use-cases you may want to implement your own connection pool management, rather than using the global connection pool. Reasons for doing this include:

  • Supporting connections to multiple databases
  • Creation of separate pools for read vs read/write operations

The following code is an example of a custom connection pool implementation.

// pool-manager.js
const mssql = require('mssql')
const pools = new Map();

module.exports = {
 /**
  * Get or create a pool. If a pool doesn't exist the config must be provided.
  * If the pool does exist the config is ignored (even if it was different to the one provided
  * when creating the pool)
  *
  * @param {string} name
  * @param {{}} [config]
  * @return {Promise.<mssql.ConnectionPool>}
  */
 get: (name, config) => {
  if (!pools.has(name)) {
   if (!config) {
    throw new Error('Pool does not exist');
   }
   const pool = new mssql.ConnectionPool(config);
   // automatically remove the pool from the cache if `pool.close()` is called
   const close = pool.close.bind(pool);
   pool.close = (...args) => {
    pools.delete(name);
    return close(...args);
   }
   pools.set(name, pool.connect());
  }
  return pools.get(name);
 },
 /**
  * Closes all the pools and removes them from the store
  *
  * @return {Promise<mssql.ConnectionPool[]>}
  */
 closeAll: () => Promise.all(Array.from(pools.values()).map((connect) => {
  return connect.then((pool) => pool.close());
 })),
};

This file can then be used in your application to create, fetch, and close pools.

const { get } = require('./pool-manager')

async function example() {
  const pool = await get('default')
  return pool.request().query('SELECT 1')
}

Similar to the global connection pool, you should aim to only close a pool when you know it will never be needed by the application again. Typically this will only be when your application is shutting down.

Result value manipulation

In some instances it is desirable to manipulate the record data as it is returned from the database, this may be to cast it as a particular object (eg: moment object instead of Date) or similar.

In v8.0.0+ it is possible to register per-datatype handlers:

const sql = require('mssql')

// in this example all integer values will return 1 more than their actual value in the database
sql.valueHandler.set(sql.TYPES.Int, (value) => value + 1)

sql.query('SELECT * FROM [example]').then((result) => {
  // all `int` columns will return a manipulated value as per the callback above
})

Configuration

The following is an example configuration object:

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.
  • 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. (default: false) See Handling Duplicate Column Names

Complete list of pool options can be found here.

Formats

In addition to configuration object there is an option to pass config as a connection string. Connection strings are supported.

Classic Connection String
Standard configuration using tedious driver
Server=localhost,1433;Database=database;User Id=username;Password=password;Encrypt=true
Standard configuration using msnodesqlv8 driver
Driver=msnodesqlv8;Server=(local)\INSTANCE;Database=database;UID=DOMAIN\username;PWD=password;Encrypt=true
Azure Active Directory Authentication Connection String

Several types of Azure Authentication are supported:

Authentication using Active Directory Integrated
Server=*.database.windows.net;Database=database;Authentication=Active Directory Integrated;Client secret=clientsecret;Client Id=clientid;Tenant Id=tenantid;Encrypt=true

Note: Internally, the 'Active Directory Integrated' will change its type depending on the other parameters you add to it. On the example above, it will change to azure-active-directory-service-principal-secret because we supplied a Client Id, Client secret and Tenant Id.

If you want to utilize Authentication tokens (azure-active-directory-access-token) Just remove the unnecessary additional parameters and supply only a token parameter, such as in this example:

Server=*.database.windows.net;Database=database;Authentication=Active Directory Integrated;token=token;Encrypt=true

Finally if you want to utilize managed identity services such as managed identity service app service you can follow this example below:

Server=*.database.windows.net;Database=database;Authentication=Active Directory Integrated;msi endpoint=msiendpoint;Client Id=clientid;msi secret=msisecret;Encrypt=true

or if its managed identity service virtual machines, then follow this:

Server=*.database.windows.net;Database=database;Authentication=Active Directory Integrated;msi endpoint=msiendpoint;Client Id=clientid;Encrypt=true

We can also utilizes Active Directory Password but unlike the previous examples, it is not part of the Active Directory Integrated Authentication.

Authentication using Active Directory Password
Server=*.database.windows.net;Database=database;Authentication=Active Directory Password;User Id=username;Password=password;Client Id=clientid;Tenant Id=tenantid;Encrypt=true

For more reference, you can consult here. Under the authentication.type parameter.

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:
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. 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

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 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.

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.

Example

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

pool.close()

Request

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.

Example

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

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.

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

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

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

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

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 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.

Example

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).
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.


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 omitted, returns Promise.

Example

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.

Example

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

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.

const transaction = new sql.Transaction(/* [pool] */)

If you omit connection argument, global connection is used instead.

Example

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.

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.

Example

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.

Example

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.

Example

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.

const ps = new sql.PreparedStatement(/* [pool] */)

If you omit the connection argument, the global connection is used instead.

Example

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

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

  • 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.

Example

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.

Example

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.

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.

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.

Example

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

If you want to add the MSSQL CLI tool to your path, you must install it globally with npm install -g mssql.

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; select * 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.

Overriding config settings

You can override some config settings via CLI options (--user, --password, --server, --database, --port).

echo "select * from mytable" | mssql /path/to/config --database anotherdatabase

Results in:

[[{"username":"onotheruser","password":"quiteeasy"}]]

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:

select geography::STGeomFromText(N'POLYGON((1 1, 3 1, 3 1, 1 1))',4326)

results in:

{
  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: You will also see x and y coordinates in parsed Geography points, they are not recommended for use. They have thus been omitted from this example. For compatibility, they remain flipped (x, the horizontal offset, is instead used for latitude, the vertical), and thus risk misleading you. Prefer instead to use the lat and lng properties.

Geometry

Geometry types can also be constructed in several ways. Unlike Geographies, they are consistent in always placing x before y. node-mssql decodes the result of this query:

select geometry::STGeomFromText(N'POLYGON((1 1, 3 1, 3 7, 1 1))',4326)

into the JavaScript object:

{
  srid: 4326,
  version: 1,
  points: [
    Point { x: 1, y: 1, z: null, m: null },
    Point { x: 1, y: 3, z: null, m: null },
    Point { x: 7, y: 3, z: null, m: null },
    Point { x: 1, y: 1, z: null, m: null }
  ],
  figures: [ { attribute: 2, pointOffset: 0 } ],
  shapes: [ { parentOffset: -1, figureOffset: 0, type: 3 } ],
  segments: []
}

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.

const tvp = new sql.Table() // You can optionally specify table type name in the first argument.

// Columns must correspond with type we have created in database.
tvp.columns.add('a', sql.VarChar(50))
tvp.columns.add('b', sql.Int)

// Add rows
tvp.rows.add('hello tvp', 777) // Values are in same order as columns.

You can send table as a parameter to stored procedure.

const request = new sql.Request()
request.input('tvp', tvp)
request.execute('MyCustomStoredProcedure', (err, result) => {
    // ... error checks

    console.dir(result.recordsets[0][0]) // {a: 'hello tvp', b: 777}
})

TIP: You can also create Table variable from any recordset with recordset.toTable(). You can optionally specify table type name in the first argument.

You can clear the table rows for easier batching by using table.rows.clear()

const tvp = new sql.Table() // You can optionally specify table type name in the first argument.

// Columns must correspond with type we have created in database.
tvp.columns.add('a', sql.VarChar(50))
tvp.columns.add('b', sql.Int)

// Add rows
tvp.rows.add('hello tvp', 777) // Values are in same order as columns.
tvp.rows.clear()

Response Schema

An object returned from a sucessful basic query would look like the following.

{
	recordsets: [
		[
			{
				COL1: "some content",
				COL2: "some more content"
			}
		]
	],
	recordset: [
		{
			COL1: "some content",
			COL2: "some more content"
		}
	],
	output: {},
	rowsAffected: [1]
}

Affected Rows

If you're performing INSERT, UPDATE or DELETE in a query, you can read number of affected rows. The rowsAffected variable is an array of numbers. Each number represents number of affected rows by a single statement.

Example using Promises

const request = new sql.Request()
request.query('update myAwesomeTable set awesomness = 100').then(result => {
    console.log(result.rowsAffected)
})

Example using callbacks

const request = new sql.Request()
request.query('update myAwesomeTable set awesomness = 100', (err, result) => {
    console.log(result.rowsAffected)
})

Example using streaming

In addition to the rowsAffected attribute on the done event, each statement will emit the number of affected rows as it is completed.

const request = new sql.Request()
request.stream = true
request.query('update myAwesomeTable set awesomness = 100')
request.on('rowsaffected', rowCount => {
    console.log(rowCount)
})
request.on('done', result => {
    console.log(result.rowsAffected)
})

JSON support

SQL Server 2016 introduced built-in JSON serialization. By default, JSON is returned as a plain text in a special column named JSON_F52E2B61-18A1-11d1-B105-00805F49916B.

Example

SELECT
    1 AS 'a.b.c',
    2 AS 'a.b.d',
    3 AS 'a.x',
    4 AS 'a.y'
FOR JSON PATH

Results in:

recordset = [ { 'JSON_F52E2B61-18A1-11d1-B105-00805F49916B': '{"a":{"b":{"c":1,"d":2},"x":3,"y":4}}' } ]

You can enable built-in JSON parser with config.parseJSON = true. Once you enable this, recordset will contain rows of parsed JS objects. Given the same example, result will look like this:

recordset = [ { a: { b: { c: 1, d: 2 }, x: 3, y: 4 } } ]

IMPORTANT: In order for this to work, there must be exactly one column named JSON_F52E2B61-18A1-11d1-B105-00805F49916B in the recordset.

More information about JSON support can be found in official documentation.

Handling Duplicate Column Names

If your queries contain output columns with identical names, the default behaviour of mssql will only return column metadata for the last column with that name. You will also not always be able to re-assemble the order of output columns requested.

Default behaviour:

const request = new sql.Request()
request
    .query("select 'asdf' as name, 'qwerty' as other_name, 'jkl' as name")
    .then(result => {
        console.log(result)
    });

Results in:

{
  recordsets: [
    [ { name: [ 'asdf', 'jkl' ], other_name: 'qwerty' } ]
  ],
  recordset: [ { name: [ 'asdf', 'jkl' ], other_name: 'qwerty' } ],
  output: {},
  rowsAffected: [ 1 ]
}

You can use the arrayRowMode configuration parameter to return the row values as arrays and add a separate array of column values. arrayRowMode can be set globally during the initial connection, or per-request.

const request = new sql.Request()
request.arrayRowMode = true
request
    .query("select 'asdf' as name, 'qwerty' as other_name, 'jkl' as name")
    .then(result => {
        console.log(result)
    });

Results in:

{
  recordsets: [ [ [ 'asdf', 'qwerty', 'jkl' ] ] ],
  recordset: [ [ 'asdf', 'qwerty', 'jkl' ] ],
  output: {},
  rowsAffected: [ 1 ],
  columns: [
    [
      {
        index: 0,
        name: 'name',
        length: 4,
        type: [sql.VarChar],
        scale: undefined,
        precision: undefined,
        nullable: false,
        caseSensitive: false,
        identity: false,
        readOnly: true
      },
      {
        index: 1,
        name: 'other_name',
        length: 6,
        type: [sql.VarChar],
        scale: undefined,
        precision: undefined,
        nullable: false,
        caseSensitive: false,
        identity: false,
        readOnly: true
      },
      {
        index: 2,
        name: 'name',
        length: 3,
        type: [sql.VarChar],
        scale: undefined,
        precision: undefined,
        nullable: false,
        caseSensitive: false,
        identity: false,
        readOnly: true
      }
    ]
  ]
}

Streaming Duplicate Column Names

When using arrayRowMode with stream enabled, the output from the recordset event (as described in Streaming) is returned as an array of column metadata, instead of as a keyed object. The order of the column metadata provided by the recordset event will match the order of row values when arrayRowMode is enabled.

Default behaviour (without arrayRowMode):

const request = new sql.Request()
request.stream = true
request.query("select 'asdf' as name, 'qwerty' as other_name, 'jkl' as name")
request.on('recordset', recordset => console.log(recordset))

Results in:

{
  name: {
    index: 2,
    name: 'name',
    length: 3,
    type: [sql.VarChar],
    scale: undefined,
    precision: undefined,
    nullable: false,
    caseSensitive: false,
    identity: false,
    readOnly: true
  },
  other_name: {
    index: 1,
    name: 'other_name',
    length: 6,
    type: [sql.VarChar],
    scale: undefined,
    precision: undefined,
    nullable: false,
    caseSensitive: false,
    identity: false,
    readOnly: true
  }
}

With arrayRowMode:

const request = new sql.Request()
request.stream = true
request.arrayRowMode = true
request.query("select 'asdf' as name, 'qwerty' as other_name, 'jkl' as name")

request.on('recordset', recordset => console.log(recordset))

Results in:

[
  {
    index: 0,
    name: 'name',
    length: 4,
    type: [sql.VarChar],
    scale: undefined,
    precision: undefined,
    nullable: false,
    caseSensitive: false,
    identity: false,
    readOnly: true
  },
  {
    index: 1,
    name: 'other_name',
    length: 6,
    type: [sql.VarChar],
    scale: undefined,
    precision: undefined,
    nullable: false,
    caseSensitive: false,
    identity: false,
    readOnly: true
  },
  {
    index: 2,
    name: 'name',
    length: 3,
    type: [sql.VarChar],
    scale: undefined,
    precision: undefined,
    nullable: false,
    caseSensitive: false,
    identity: false,
    readOnly: true
  }
]

Errors

There are 4 types of errors you can handle:

  • ConnectionError - Errors related to connections and connection pool.
  • TransactionError - Errors related to creating, committing 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 name, code and message properties.

Name Code Message
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 Socket 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 Cancelled.
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.

  • err.number - The error number.
  • err.state - The error state, used as a modifier to the number.
  • err.class - The class (severity) of the error. A class of less than 10 indicates an informational message. Detailed explanation can be found here.
  • err.lineNumber - The line number in the SQL batch or stored procedure that caused the error. Line numbers begin at 1; therefore, if the line number is not applicable to the message, the value of LineNumber will be 0.
  • err.serverName - The server name.
  • err.procName - The stored procedure name.

Informational messages

To receive informational messages generated by PRINT or RAISERROR commands use:

const request = new sql.Request()
request.on('info', info => {
    console.dir(info)
})
request.query('print \'Hello world.\';', (err, result) => {
    // ...
})

Structure of informational message:

  • info.message - Message.
  • info.number - The message number.
  • info.state - The message state, used as a modifier to the number.
  • info.class - The class (severity) of the message. Equal or lower than 10. Detailed explanation can be found here.
  • info.lineNumber - The line number in the SQL batch or stored procedure that generated the message. Line numbers begin at 1; therefore, if the line number is not applicable to the message, the value of LineNumber will be 0.
  • info.serverName - The server name.
  • info.procName - The stored procedure name.

Metadata

Recordset metadata are accessible through the recordset.columns property.

const request = new sql.Request()
request.query('select convert(decimal(18, 4), 1) as first, \'asdf\' as second', (err, result) => {
    console.dir(result.recordset.columns)

    console.log(result.recordset.columns.first.type === sql.Decimal) // true
    console.log(result.recordset.columns.second.type === sql.VarChar) // true
})

Columns structure for example above:

{
    first: {
        index: 0,
        name: 'first',
        length: 17,
        type: [sql.Decimal],
        scale: 4,
        precision: 18,
        nullable: true,
        caseSensitive: false
        identity: false
        readOnly: true
    },
    second: {
        index: 1,
        name: 'second',
        length: 4,
        type: [sql.VarChar],
        nullable: false,
        caseSensitive: false
        identity: false
        readOnly: true
    }
}

Data Types

You can define data types with length/precision/scale:

request.input("name", sql.VarChar, "abc")               // varchar(3)
request.input("name", sql.VarChar(50), "abc")           // varchar(50)
request.input("name", sql.VarChar(sql.MAX), "abc")      // varchar(MAX)
request.output("name", sql.VarChar)                     // varchar(8000)
request.output("name", sql.VarChar, "abc")              // varchar(3)

request.input("name", sql.Decimal, 155.33)              // decimal(18, 0)
request.input("name", sql.Decimal(10), 155.33)          // decimal(10, 0)
request.input("name", sql.Decimal(10, 2), 155.33)       // decimal(10, 2)

request.input("name", sql.DateTime2, new Date())        // datetime2(7)
request.input("name", sql.DateTime2(5), new Date())     // datetime2(5)

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.Variant

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. Types sql.XML and sql.Variant are not supported as input parameters.

SQL injection

This module has built-in SQL injection protection. Always use parameters or tagged template literals to pass sanitized values to your queries.

const request = new sql.Request()
request.input('myval', sql.VarChar, '-- commented')
request.query('select @myval as myval', (err, result) => {
    console.dir(result)
})

Known issues

Tedious

  • If you're facing problems with connecting SQL Server 2000, try setting the default TDS version to 7.1 with config.options.tdsVersion = '7_1' (issue)
  • If you're executing a statement longer than 4000 chars on SQL Server 2000, always use batch instead of query (issue)

8.x to 9.x changes

  • Upgraded to tedious version 15
  • Dropped support for Node version <= 12

7.x to 8.x changes

  • Upgraded to tedious version 14
  • Removed internal library for connection string parsing. Connection strings can be resolved using the static method parseConnectionString on ConnectionPool

6.x to 7.x changes

  • Upgraded tedious version to v11
  • Upgraded msnodesqlv8 version support to v2
  • Upgraded tarn.js version to v3
  • Requests in stream mode that pipe into other streams no longer pass errors up the stream chain
  • Request.pipe now pipes a true node stream for better support of backpressure
  • tedious config option trustServerCertificate defaults to false if not supplied
  • Dropped support for Node < 10

5.x to 6.x changes

  • Upgraded tarn.js so _poolDestroy can take advantage of being a promise
  • ConnectionPool.close() now returns a promise / callbacks will be executed once closing of the pool is complete; you must make sure that connections are properly released back to the pool otherwise the pool may fail to close.
  • It is safe to pass read-only config objects to the library; config objects are now cloned
  • options.encrypt is now true by default
  • TYPES.Null has now been removed
  • Upgraded tedious driver to v6 and upgraded support for msnodesqlv8]
  • You can now close the global connection by reference and this will clean up the global connection, eg: const conn = sql.connect(); conn.close() will be the same as sql.close()
  • Bulk table inserts will attempt to coerce dates from non-Date objects if the column type is expecting a date
  • Repeat calls to the global connect function (sql.connect()) will return the current global connection if it exists (rather than throwing an error)
  • Attempting to add a parameter to queries / stored procedures will now throw an error; use replaceInput and replaceOutput instead
  • Invalid isolation levels passed to Transactions will now throw an error
  • ConnectionPool now reports if it is healthy or not (ConnectionPool.healthy) which can be used to determine if the pool is able to create new connections or not
  • Pause/Resume support for streamed results has been added to the msnodesqlv8 driver

4.x to 5.x changes

  • Moved pool library from node-pool to tarn.js
  • ConnectionPool.pool.size deprecated, use ConnectionPool.size instead
  • ConnectionPool.pool.available deprecated, use ConnectionPool.available instead
  • ConnectionPool.pool.pending deprecated, use ConnectionPool.pending instead
  • ConnectionPool.pool.borrowed deprecated, use ConnectionPool.borrowed instead

3.x to 4.x changes

  • Library & tests are rewritten to ES6.
  • Connection was renamed to ConnectionPool.
  • Drivers are no longer loaded dynamically so the library is now compatible with Webpack. To use msnodesqlv8 driver, use const sql = require('mssql/msnodesqlv8') syntax.
  • Every callback/resolve now returns result object only. This object contains recordsets (array of recordsets), recordset (first recordset from array of recordsets), rowsAffected (array of numbers representig number of affected rows by each insert/update/delete statement) and output (key/value collection of output parameters' values).
  • Affected rows are now returned as an array. A separate number for each SQL statement.
  • Directive multiple: true was removed.
  • Transaction and PreparedStatement internal queues was removed.
  • ConnectionPool no longer emits connect and close events.
  • Removed verbose and debug mode.
  • Removed support for tds and msnodesql drivers.
  • Removed support for Node versions lower than 4.

node-mssql's People

Contributors

0klce avatar andyneale avatar arthurschreiber avatar cahilfoley avatar darryl-davidson avatar dbmercer avatar dependabot[bot] avatar dhensby avatar elhaard avatar fdawgs avatar funkydev avatar ghost1face avatar jacqt avatar jaroslavdextems avatar jeffbski-rga avatar jeremy-w avatar jordanjennings avatar josh-hemphill avatar jp1016 avatar kibertoad avatar marvinscharle avatar mtriff avatar nippur72 avatar palmerek avatar patriksimek avatar shin-aska avatar stovenator avatar swantzter avatar tomv avatar willmorgan avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

node-mssql's Issues

throw TypeError('value is out of bounds');

[root@ISAAPI01 ser-web-api]# node api.js
Kill PID:6644

buffer.js:784
    throw TypeError('value is out of bounds');
          ^
TypeError: value is out of bounds
    at TypeError (<anonymous>)
    at checkInt (buffer.js:784:11)
    at Buffer.writeUInt32LE (buffer.js:841:5)
    at WritableTrackingBuffer.writeUInt32LE (/sites/ser-web-api/node_modules/mssql/node_modules/tedious/lib/tracking-buffer/writable-tracking-buffer.js:92:17)
    at WritableTrackingBuffer.writeUInt64LE (/sites/ser-web-api/node_modules/mssql/node_modules/tedious/lib/tracking-buffer/writable-tracking-buffer.js:119:17)
    at Object.TYPE.writeParameterData (/sites/ser-web-api/node_modules/mssql/node_modules/tedious/lib/data-type.js:268:25)
    at new RpcRequestPayload (/sites/ser-web-api/node_modules/mssql/node_modules/tedious/lib/rpcrequest-payload.js:66:22)
    at Connection.callProcedure (/sites/ser-web-api/node_modules/mssql/node_modules/tedious/lib/connection.js:731:56)
    at /sites/ser-web-api/node_modules/mssql/lib/tedious.js:723:33
    at dispense (/sites/ser-web-api/node_modules/mssql/node_modules/generic-pool/lib/generic-pool.js:247:16)
    at Object.me.acquire (/sites/ser-web-api/node_modules/mssql/node_modules/generic-pool/lib/generic-pool.js:316:5)
    at Request._acquire (/sites/ser-web-api/node_modules/mssql/lib/main.js:884:37)
    at Request.TediousRequest.execute (/sites/ser-web-api/node_modules/mssql/lib/tedious.js:586:21)
    at Request.execute (/sites/ser-web-api/node_modules/mssql/lib/main.js:1088:56)
    at /sites/ser-web-api/controllers/lubricantes.js:28:21
    at Array.forEach (native)
    at /sites/ser-web-api/controllers/lubricantes.js:12:14
    at /sites/ser-web-api/helpers/mssql.js:40:17
    at /sites/ser-web-api/node_modules/mssql/lib/main.js:236:51
    at /sites/ser-web-api/node_modules/mssql/lib/tedious.js:330:20
    at /sites/ser-web-api/node_modules/mssql/node_modules/generic-pool/lib/generic-pool.js:278:11
    at Connection.<anonymous> (/sites/ser-web-api/node_modules/mssql/lib/tedious.js:308:24)
    at Connection.g (events.js:180:16)
    at Connection.EventEmitter.emit (events.js:92:17)
    at Connection.processedInitialSql (/sites/ser-web-api/node_modules/mssql/node_modules/tedious/lib/connection.js:690:17)
    at Connection.STATE.LOGGED_IN_SENDING_INITIAL_SQL.events.message (/sites/ser-web-api/node_modules/mssql/node_modules/tedious/lib/connection.js:173:23)
    at Connection.dispatchEvent (/sites/ser-web-api/node_modules/mssql/node_modules/tedious/lib/connection.js:573:59)
    at MessageIO.<anonymous> (/sites/ser-web-api/node_modules/mssql/node_modules/tedious/lib/connection.js:528:22)
    at MessageIO.EventEmitter.emit (events.js:92:17)
    at MessageIO.eventData (/sites/ser-web-api/node_modules/mssql/node_modules/tedious/lib/message-io.js:58:21)
    at Socket.<anonymous> (/sites/ser-web-api/node_modules/mssql/node_modules/tedious/lib/message-io.js:3:59)
    at Socket.EventEmitter.emit (events.js:95:17)
    at Socket.<anonymous> (_stream_readable.js:746:14)
    at Socket.EventEmitter.emit (events.js:92:17)
    at emitReadable_ (_stream_readable.js:408:10)
    at emitReadable (_stream_readable.js:404:5)
    at readableAddChunk (_stream_readable.js:165:9)
    at Socket.Readable.push (_stream_readable.js:127:10)
    at TCP.onread (net.js:528:21)
[root@ISAAPI01 ser-web-api]# 

Problem on connection and authentication

When run the following code, keep getting error
"Login failed; one or more errorMessage events should have been emitted"

config = {user: p.username, password: p.password, server: p.host, database: p.other};
        console.log("connecting to mssql");
        CBS[id].conn = new mssql.Connection(config, function(err) {
            if (err) {
                sendMsg(id, {error: err}); return;
            }
            sendMsg(id, {result:"connected"} );
        });

packet sniffer shows it failed too. The question is, what mode of authentication the above code uses. Is it Windows Authentication?

Thanks in advance.

Queries don't support parameters

Here's a simple patch to add that support:

src/tedious.coffee
===================================================================
--- src/tedious.coffee  (revision )
+++ src/tedious.coffee  (revision )
@@ -172,6 +172,16 @@
                        recordset.push row

                    if @verbose then console.log "---------- response -----------"
+
+                   for name, param of @parameters when param.io is 1
+                           if @verbose
+                               if param.value is tds.TYPES.Null
+                                   console.log "    input: @#{param.name}, null"
+                               else
+                                   console.log "    input: @#{param.name}, #{param.type.name.toLowerCase()}, #{param.value}"
+
+                           req.addParameter param.name, getTediousType(param.type), if param.value? then param.value else tds.TYPES.Null
+
                    connection.execSql req

                else

How to use input parameters in a INSERT INTO Query

Hi,

Im a begginer in programming, i canยดt pass an input parameter to my sql statement, please can you help me. Also i need to insert the value of the input parameter from another external variable, is it possible?

var sql = require('mssql');
var qstring = {
user: 'sa',
password: '*',
server: '**
',
database: '**
**'
}
var connection = new sql.Connection(qstring, function(err) {
var r = new sql.Request(connection);
r.input('cinco',sql.VarChar,'tres');
r.multiple = true;
r.query("INSERT INTO Test(userid,userod) values (cinco,'ridiculo')",function(err,recordsets) {

connection.close();

});

});

Module Hanging on Failed Connections

As a little background I'm writing a simple script to check if a connection to a DB can be established. When the DB connection is successful everything works great, however in the case where one or more of the connections fails the script will hang until idleTimeoutMillis + connectTimeout has passed and then errors with the following:

mssql-test-connection/node_modules/mssql/lib/tedious.js:204
            return c.close();
                     ^
TypeError: Cannot call method 'close' of null
    at Object.cfg_pool.destroy (mssql-test-connection/node_modules/mssql/lib/tedious.js:204:22)
    at Object.me.destroy (mssql-test-connection/node_modules/mssql/node_modules/generic-pool/lib/generic-pool.js:149:13)
    at removeIdle (mssql-test-connection/node_modules/mssql/node_modules/generic-pool/lib/generic-pool.js:178:10)
    at Timer.listOnTimeout [as ontimeout] (timers.js:110:15)

It appears that the code is waiting for the failed connection to go idle and then trying to close it at that point causing an error.

Here's the associated code to reproduce the error:

var sql    = require('mssql');

//To Reproduce: this is a connection to a DB that does not exist or is inaccessible
connectionsToTest = [
  {
    name: '...',
    user: '...',
    password: '...',
    server: '...',
    database: '...'
  }
];

connectionsToTest.forEach(function(config) {
  //To prevent a 45sec wait for failure
  config.pool = { idleTimeoutMillis : 500 };
  config.options = { connectTimeout : 5000 };

  var connection = new sql.Connection(config, function(err) {
      var result = 'Attempting to Connect to '+config.name+' DB ';

      if(err) {
        result += '[ '+err+' ]\n';
        process.stdout.write(result);
      } else {
        var request = new sql.Request(connection);

        request.query('select 1 as number', function(err, recordset) {
            if(recordset[0].number == 1) {
              result += '[ Success ]\n';
            } else {
              result += '[ '+err+' ]\n';
            }

            process.stdout.write(result);
        });
      }
  });
});

Multiple errors only showing last. Can we show the preceding too?

When I do

    var request = new sql.Request();
    request.query('select a;select b;', function(err, recordset) {
        console.log(err.originalError)
    });

I would only get the last error

{
  name: 'RequestError',
  message: 'Msg 207, Level 16, State 1, Line 2. Invalid column name 'b'.',
  code: 'EREQUEST'
}

Would you consider implementing something like this that shows the preceding messages too in a way that we don't break existing code?

{
  name: 'RequestError',
  message: 'Msg 207, Level 16, State 1, Line 2. Invalid column name 'b'.',
  code: 'EREQUEST',
  precedingErrors: [{
    name: 'RequestError',
    message: 'Msg 207, Level 16, State 1, Line 2. Invalid column name 'a'.',
    code: 'EREQUEST'
  }]
}

Support Streaming

Have you any plans to support streaming?

The library looks really promising as an alternative to tedious, but we have some procs which returns hundreds of thousands of records and waiting for the callback will hurt performance.

RangeError: Trying to access beyond buffer length

I am getting this error while getting records from mssql. If there are 1 - 2 records it is working fine but in case of more records it is throwing this error: RangeError: Trying to access beyond buffer length. The function where I am getting error is ReadableTrackingBuffer.prototype.assertEnoughLeftFor. and the function is in file the function in the files : \node_modules\mssql\node_modules\tedious\lib\tracking-buffer\readable-tracking-buffer.js .

The way I am connecting and fetching data is:

var sqlQuery = "SELECT * from [BackOffice.Applications] ";
var request = new sql.Request(connection);
request.query(sqlQuery, function (err, recordset) {
//Some logic here
});

Please help.

The server did not return a response for this request. Server returned 0 bytes

I have a node service connect successfully to azure database from local host using tedious and retrieve data correctly ,but when i deploy the service on a cloud service like nodejitsu or any cloud service, the request takes long time and ends with "The server did not return a response for this request. Server returned 0 bytes".Where is the problem?

Combine execute() callback parameters

Currently the signature for the execute() callback is function (err, recordsets, returnValue) {}. This causes a problem with every node library that relies on the standard node callback signature of function (err, result) {}.

I'd like to propose that the standard signature be adopted, and an object literal be returned with the following signature:

{
  recordsets: [...],
  returnValue: ...
}

Error Handling

Hello,

I was wondering the most elegant way to handle errors using prepared statements or transactions.. In my code, there are always 3 nested functions (preparedstatement .prepare, .execute, and .unprepare). The code gets really convoluted quickly when handling the possibility of an error at each of these steps. Also, I am using prepared statements for each of my queries so I can bind input variables.

ps.prepare('select @param as value', function(err) {
    // ... error checks

    ps.execute({param: 12345}, function(err, recordset) {
        // ... error checks

        ps.unprepare(function(err) {
            // ... error checks

        });
    });
});

Is there a clean, recommended method of handling errors for a prepared statement query if I want to handle most of these errors the same way?

Support for prepared statements?

Hello

Is there any built in support for prepared statements? Do you have any suggestions as to how to implement them?

Thank you for your amazing work!

Reuse connection?

Is the connection reusable like with the oracle package? Is so would an example be possible?

Oracle.connect = function(callback) {
   oracle_driver.connect(connectData, function(err, connection) {
      if(err) {
         console.log(err);
      } else {
         callback(err, connection);
      }
      connection.close();
   });
}

Oracle.query = function(query, callback) {
   Oracle.connect(function(err, connection) {
      connection.execute(query, [], function(err, results) {
         if (err) {
            console.log(err);
            callback(err, results);
         } else {
            callback(err, results);
         }
      });
   });
}

Connection 'close' event not firing

With tedious.

Currently, the 'close' event is not fired on a connection when said connection is closed by the connection pool manager (ex. on idle timeout)

From briefly poking around, may be a tedious issue; but thought I'd raise it here first

SQL Server Instance

hello! How i can use MS SQL Server instance name?
localhost\i2008 dont work

2 simultaneous different database connection don't seem to work

I've created 2 simultaneous sql.connect call to 2 different configuration on a Hapi server, where each call is mapped to a different path.
When testing each call on it's on it seems to work just fine.
but if I try to run both of them at the same time only 1 of them seem to return results, the other one returns an error message: 'Invalid object name...'

if I add a timeout function in the front end when making the call and if one of the calls wait for a bit it works just fine.
can you please advice?
Thanks in advance.

question how to determine which of the two modules are used

I am using Ubuntu on my PC. So when I use node-mssql module to set up connections, I can be using either tedious module or node-tds module. From the quick example, it wasn't clear which of the two is being used. How can we tell?

Thanks in advance.

Performance issue

Hello,

I am trying to save 3 documents (head and body in transaction) in sql server 2008 r2. Each document has 4 or 5 rows as body, so in total I need just to insert about 20 rows in database.
The time that it is needed to make this insertion is about 1 minute. I tried to insert just one document with 5 rows in body, and it was needed about 45 seconds. While reading this 3 documents it was needed just 0.8 seconds. My question is: Is this a normal performance or am I doing something wrong?

Best Regards

Information regarding best practices, tips or heads up?

Hello,

I'm working on an API that will be pulling information from multiple databases, lots of different mssql databases. But it's possible it would receive concurrent requests for the same db during short periods of time.

Naturally, I still haven't done an all out testing of the product, but I'm already wondering if there are gotchas, best practices or, in general, any kind of information that would help me get the best out of this library.

For instance, I was thinking about probably preparing some sort of connection pool, or a store of connections that have been recently used. Maybe keep those connections open or something.

BTW, I'm also new to this node culture. Maybe my question is a silly. Yet any help would be greatly appreciated :)

Thanks in advance,

CREATE/ALTER PROCEDURE CALLS

Hello,
I'm pretty much having this issue
tediousjs/tedious#79

can you please provide a way to use tedious' execSqlBatch?

I added a these lines around line 205 in tedious.coffee.

if @batch
    connection.execSqlBatch req
else connection.execSqlBatch req

But i am not sure if these would have any implications, or cause any problems.

Synchronous methods

For any decent sized webapp, you'll have situations where the query of a dataset requires the result of another dataset. You'll also have situations in which you want to query data in a particular order.

At the moment I'm using chaining/shifting and separate synchronous libraries to replicate this. As evidenced by node.js core modules and a very large number of popular modules, 'Sync' methods are becoming commonplace.

It'd be wonderful for this module to implement sync methods as well.

Connect to sql server 2000 throws an uncaught exception and is terminated

I am on a machine with node-mssql installed but also MSSMS. I can connect to a SQL Server (2000) using MSSMS (Microsoft SQL Server Management Studio), but when I use node-mssql to connect to the same SQL Server I don't get an error, but it doesn't connect either. This is my code:

var sql   = require('mssql');
sql.connect({server: "ip", user: "user", password: "password"}, function(err) {
      console.log('sql.connect error', err);
      if (err) return callback(err);
      var request = new sql.Request();
      request.query(sql, callback);
});

The line console.log is never called and instead the node application throws an uncaught exception and is terminated:

TypeError: Uncaught, unspecified "error" event.
    at TypeError (<anonymous>)
    at Connection.EventEmitter.emit (events.js:74:15)
    at Parser.<anonymous> (folder\node_modules\mssql\node_modules\tedious\lib\connection.js:490:15)
    at Parser.EventEmitter.emit (events.js:95:17)
    at Parser.nextToken (folder\node_modules\mssql\node_modules\tedious\lib\token\token-stream-parser.js:100:14)
    at Parser.addBuffer (folder\node_modules\mssql\node_modules\tedious\lib\token\token-stream-parser.js:66:17)
    at Connection.sendDataToTokenStreamParser (folder\node_modules\mssql\node_modules\tedious\lib\connection.js:675:35)
    at Connection.STATE.SENT_LOGIN7_WITH_STANDARD_LOGIN.events.data (folder\node_modules\mssql\node_modules\tedious\lib\connection.js:146:23)
    at Connection.dispatchEvent (folder\node_modules\mssql\node_modules\tedious\lib\connection.js:573:59)
    at MessageIO.<anonymous> (folder\node_modules\mssql\node_modules\tedious\lib\connection.js:523:22)

When I connect with node-mssql using an ip address of another machine without mssql I get a nice ETIMEOUT, "Failed to connect to 10.101.0.11:1433 in 15000ms"

PS: I changed a lot of content in this issue since I originally wrote it 20 minutes ago!

TypeError: Cannot call method 'acquire' of null

I get this error when i try connect in my database.

Follow the code:

var sql = require('mssql'); 

var config = {
    user: 'xx',
    password: 'xx',
    server: 'localhost',
    database: 'xx'
}

var connection = new sql.Connection(config, function(err) {
    if (err) {
        console.log(err);
    }
    else {
        console.log('connected');
    }
});

and the error:

image

Thanks.
Will

Prepared Statement,NVarChar and sql.MAX

I'm probably missing something simple but I'm getting a request error (statement not prepared) when I try to prepare a statement that uses sql.MAX with a sql.NVarChar. My SQL table has a field named SValue that is an nvarchar(MAX). I get the error when I execute something like the following:

...
var ps = new sql.PreparedStatement(connection);
ps.input('TID', sql.Int);
ps.input('SValue',sql.NVarChar(sql.MAX));

var statement = 'insert into TTable (TID,SValue) values (@tid,@svalue)'

ps .prepare(statement, function(err, recordsets) {
...

If I replace sql.MAX with a number, it works fine. What am I missing?

ReadableTrackingBuffer.prototype.assertEnoughLeftFor Error: required : 4, available : 0

When I get more than 30 rows data from a mssql table, the function : ReadableTrackingBuffer.prototype.assertEnoughLeftFor will throw the error : "required : 4, available : 0" or "Error: required : 76, available : 42" . but if I get less than 20 rows data from the same table, it can return the right result .

the function in the files : \node_modules\mssql\node_modules\tedious\lib\tracking-buffer\readable-tracking-buffer.js

How to disable Pooling for node-mssql

Hey, guys

I'm trying to use node-mssql for testing performance of MSSQL Server using nodejs.

Currently, I just fork 256 child processes which in charge of sending query to MSSQL Server, and I need to create 256 active connections definitely, how can I make it work?

thanks,
Khalil

Session and local temporary tables

Hi,
I have problem with local temporary tables - it seems that they are not visible in concurent requests.
The error I got is: [RequestError: Invalid object name '#tbltemp'.]

create procedure p_temp as
begin
insert into #tbltemp (dt) values (GetDate());
end;
var sqlConfig: {
        user: 'xxx',
        password: 'xxx',
        server: 'xxx',
        database: 'xxx'
    }

/* POST new events . */
router.post('/loctmp', function(req, res) {
    try {
        var connection = sql.connect(config.sqlConfig, function(err) {
        var transaction = new sql.Transaction(connection);
        transaction.begin(function(err) {
        var request = new sql.Request(transaction);

        //var request = new sql.Request(transaction);
        request.query("create table #tbltemp (dt datetime)", function(err, recordsets, returnValue) {
            console.dir(err);

            //var request = new sql.Request(transaction);
            request.execute('p_temp', function(err, recordsets, returnValue) {
                console.dir(err);

                //var request = new sql.Request(transaction);
                request.query('select * from  #tbltemp', function(err, recordset) 
                    {
                        console.dir(err);
                        console.log(recordset);
                    }); 

            }); //p_temp
        }); //create table

        }); //transaction
    }); //connection
    } catch (e) {
        console.error("Error:", e); 
    }

});

Doesn't know if the connection failed after connection is made.

From what I've seen, Tedious provides events to let you know when a connection has ended. I'm not 100% certain if this even is fired if the server has gone down or the connection is broken by some other source. If it does though, it would be nice to gain access to such events. From what I've seen, this library doesn't handle failed connections.

I tested the connected property of the connection object, but it seems to only stay true all the time once a connection has been successfully created. I tested it by pulling out the ethernet wire and it still claimed to be connected.

Remote Server and Windows Authentication

I am logging into a remote server for our SQL DB. Currently the DB uses Windows Authentication for the login. Is this supported. Looking to see if this is supported before submitting a request to change security items in the DB.

Thanks in advance.

Problem with getting last inserted ID

Anybody have issues with retrieving the last inserted ID from db after an insert statement?

Assume a table student contains 3 fields (id, age, name).
Here's my code:

        var query = "INSERT INTO student(age, tagname) values (6, 'Bob') ";
        db = new sql.Request();
        db.query(query, function(err, data) {
        if (!err)
        {
            var str = "SELECT @@IDENTITY AS 'identity'";    
            db = new sql.Request();
            db.query(str, function(suberr, subdata)
            {
                console.log(" this is LAST inserted id : ");
                console.log(subdata);   // -> RETURNED NOTHING
            });
        }

The above code returned nothing as the ID eventhough the student record was captured correctly into the db.

OUTPUT

 this is last LAST inserted id :
[ { identity: null } ]

I am wondering if there's something wrong with my code, or if this is a bug.
Any feedbacks are appreciated.

PS. If I do another query in between the INSERT and SELECT @@IDENTITY, be it a select query, or insert query, then it would give me the ID that I am looking for.

How can I keep the connection of sql server?

I start a new server connected to the database server, after a long time no connections to db, when reconnect it, the app idled.

Can you add a 'error' or 'timeout' event for connection that we can use it.

Thank you so much.

Cannot prepare statement when using Decimal type

I'm trying to use Prepared Statements and am running into an issue where Decimal types will not prepare. I'm using mssql version 0.5.5 with the bundled tedious, connecting to SQL Server 2000.

The following is minimal code reproduction:

var sql = require('mssql');

var opts = {
  user     : "username",
  password : "password",
  server   : "10.0.0.1",
  database : "database",
  options  : {
    // SQL Server 2000
    tdsVersion : "7_1"
  }
};

var conn = new sql.Connection(opts, function(err) {
  var query = "select @param as value";
  var data = { 
    param : 155.33,
  };

  var ps = new sql.PreparedStatement(conn);
  ps.input('param', sql.Decimal);
  ps.prepare(query, function(err) {
    if (err) {
      console.log(err);
      return;
    }
    ps.execute(data, function(err, recordset) {
      // ... snip error check ...
      console.log(recordset);
      ps.unprepare(function(err) {
        // ...
      });
    });
  });
});

The error message is as follows:

{ [RequestError: Statement(s) could not be prepared.]
  name: 'RequestError',
  message: 'Statement(s) could not be prepared.',
  code: 'EREQUEST',
  precedingErrors: 
   [ { [RequestError: Line 1: Incorrect syntax near '18'.]
       name: 'RequestError',
       message: 'Line 1: Incorrect syntax near \'18\'.',
       code: 'EREQUEST' },
     { [RequestError: Must declare the variable '@param'.]
       name: 'RequestError',
       message: 'Must declare the variable \'@param\'.',
       code: 'EREQUEST' } ] }

If I use sql.Int, the query is prepared properly. sql.Numeric errors as well, with the same error message as above. Any help would be appreciated.

Wrong? number of recordsets returned by executing request.execute()

First of all I want to say that I really like your module and it is definitely the best MSSQL node module I've tried so far.

Not sure if I'm missing something but I have a problem with request.execute() it seems that the returning recordsets argument has more recordsets than I expect. I created a stored procedure which simply returns me 2 tables: 1 with the returnCode and message and another table contains the result.

For some reason request.execute() returns me 4 tables where some of them are empty. If I execute the same stored procedure using request.query I will get a precise number of recordsets back which is 2.

Here is my example code:

var sql = require('mssql');

var connection = new sql.Connection(config.dbconfig);

connection.connect(function(err) {
  if (err) {
    console.log(err);
  }
});

var request1 = new sql.Request(connection);
request1.multiple = true;
request1.verbose = false;
request1.execute('stGetLocations', function(err, recordsets) {
  console.log('====== stored procedure request ======');
  console.log(recordsets.length);
  console.log(recordsets);
});

var request2 = new sql.Request(connection);
request2.multiple = true;
request2.verbose = false;
request2.query('EXEC [dbo].[stGetLocations]', function(err, recordsets) {
  console.log('====== query request ======');
  console.log(recordsets.length);
  console.log(recordsets);
});

And here is what I see in my output

====== stored procedure request ======
4
[ [],
  [ { errorCode: 1,
      errorMessage: 'Locations retrieved successfully' } ],
  [ { locationid: 1, name: 'Ontario' },
    { locationid: 2, name: 'Quebec' } ],
  [] ]
====== query request ======
2
[ [ { errorCode: 1,
      errorMessage: 'Locations retrieved successfully' } ],
  [ { locationid: 1, name: 'Ontario' },
    { locationid: 2, name: 'Quebec' } ] ]

using OSX 10.7.5
mssql 0.3.4
node 0.10.12
sql server 11.0.3000 (SQL Server 2012)

requests execute using multiple connections?

I'm not too familiar with Coffeescript, but I think there might be a scoping issue with connections and requests.

I wrote a little test case to show what's happening. Below 2 connections are created, but a request is only run on 1 of them. The callback however is called twice however, with the request being run against both connections.

Thanks for the work you've put into this library by the way - I prefer this api much more than the usual tedious api

var server1Config = {
    user: "s1user",
    password: "s1password",
    server: "s1server",
    database: "s1database"
}

var server2Config = {
    user: "s2user",
    password: "s2password",
    server: "s2server",
    database: "s2database"
}

var server1 = require('mssql');
server1.connect(server1Config, function(err) {
    // At this point server1 is connected. 
    // We'll go ahead and also connect up to another server at the same time
    var server2 = require('mssql');
    server2.connect(server2Config, function(err) {
        // now server2 is connected
        // Here we'll create a request with server1, 
        // but it will actually be executed twice using both server1 and server2
        var request = new server1.Request();
        var sql = "SELECT @@Servername AS ServerName";
        request.query(sql, function(err, recordset) {
            console.log(recordset);
        });
    });
});

RangeError: Trying to access beyond buffer length

1

Hello,
I am getting this Notification while connecting to MSSql, I tried to resolve this issue in all aspects but i didn't achieved, can you please help me out to solve this problem.
Please reply me as soon as possible.

Thank you in advance

Stored procedure return value: -1 becomes 4294967295

I've found that an SP that returns -1 will result in a returnVal of 4294967295.

POC:

create proc sp_negone as begin
return -1
end
app.get("/poc",function(req,res){
    var sqlcmd = new mssql.Request(dbc);
    sqlcmd.execute("sp_negOne",function(err,rs,rv){
        console.log(rv);
        res.end(rv.toString());
    })
});

4294967295 is logged to console and sent as response.

Thanks

RequestError: Invalid object name 'people'

After a hard time, I successfully connecting to azure database with this configuration
var config = {
"user": "MyService@server",
"password": "password",

"options":{
"database": "database",
"encrypt": true,
},
};
but when i tried to request a query like (select * from people), it shows an error
RequestError: Invalid object name 'people'.although i have a table named people and i can use it with this statement locally.
please help.

The problem with using data types for stored procedure

the transmission parameters stored in the procedure as described in your reference, (for example "request.input ('input_parameter', sql.Int, 10);" )
when writing code:

var sql = require('mssql');
var request = new sql.Request();

request.input('position', sql.Int, 99);

request.execute('[TestSql].[dbo].[Test]', function(err) {
if (err){
console.error(err);
return next();
}
res.redirect('/');
});

error:

TypeError: Cannot read property 'Int' of undefined
at ContentHandler.postAddUser (D:\Node JS\TestDbSql\routes\post\index.js:98:38)
at callbacks (D:\Node JS\TestDbSql\node_modules\express\lib\router\index.js:164:37)
at idSprav (D:\Node JS\TestDbSql\middleware\idSprav.js:11:5)
at callbacks (D:\Node JS\TestDbSql\node_modules\express\lib\router\index.js:164:37)
at param (D:\Node JS\TestDbSql\node_modules\express\lib\router\index.js:138:11)
at pass (D:\Node JS\TestDbSql\node_modules\express\lib\router\index.js:145:5)
at Router._dispatch (D:\Node JS\TestDbSql\node_modules\express\lib\router\index.js:173:5)
at Object.router (D:\Node JS\TestDbSql\node_modules\express\lib\router\index.js:33:10)
at next (D:\Node JS\TestDbSql\node_modules\express\node_modules\connect\lib\proto.js:193:15)
at Object.handle (D:\Node JS\TestDbSql\middleware\index.js:22:9)
POST /add 500 140ms - 892b

ConnectionError?

I have the following code:

    var config = {
         . . . . .
.   };
    var callback = printError;
    var connection = new sql.Connection(config, function(err) {
        if(err) return callback(err);
        var request = new sql.Request(connection);
        request.query('select p.PresentationId from PlaybackAudits p', function(err, recordset) {
            if(err) return callback(err);
            console.dir(recordset);
        });
    });

And I get the error:

{ name: 'ConnectionError',
message: 'Login failed; one or more errorMessage events should have been emitted' }

I tried these same credentials with SQL Server Management Studio and it succeeded but these credentials fail with node-mssql.

Kevin

Failed login seems to leave an open connection

Test code:

sql = require('mssql')

config =
  database: 'MyDb'
  user: 'username'
  password: 'INVALID'

conn = new sql.Connection config

conn.connect (err)->
  if err
    console.error err.message
  else
    console.log 'connected'
  conn.close()

If the password in the above configuration is correct, the I get:

$ coffee test-login.coffee
connected

$

Buf if it's incorrect, I get

$ coffee test-login.coffee
Login failed for user 'username'

and then I have to wait about 30 seconds until the connection times out. I believe I've traced this to the fact that neither the @connecting or @connected flag gets set on the connection, so when the @close method is called on the Connection object, the underlying driver's Connection::close method never gets called.

I tried applying this patch:

diff --git a/src/main.coffee b/src/main.coffee
index 5de6756..05ac216 100644
--- a/src/main.coffee
+++ b/src/main.coffee
@@ -210,7 +210,11 @@ class Connection extends EventEmitter
                                callback? err

                        @driver = null
-
+               else
+                       @driver.Connection::close.call @, (err) =>
+                               callback? err
+
+                       @driver = null
                @

But still no luck. Is this an issue with node-mssql or with the generic-pool module?

Cannot connect using instance-name

I have config like below, but get connection error. When i use port instead of instance-name everything works.

var config = {
   user: 'sa',
   password: '...',
   server: '192.168.1.2\\sql2005',
   database: 'db1'
};

Using options (tedious format) works good

var config = {
   user: 'sa',
   password: '...',
   server: '192.168.1.2',
   database: 'db1',
   options: {
       instanceName: 'sql2005'
   }
};

TypeError('value is out of bounds')

This error is crashing my app, and I'm having a hard time tracking down the parameter and value that's causing it:

buffer.js:784
    throw TypeError('value is out of bounds');
          ^
TypeError: value is out of bounds
    at TypeError (<anonymous>)
    at checkInt (buffer.js:784:11)
    at Buffer.writeUInt32LE (buffer.js:841:5)
    at WritableTrackingBuffer.writeUInt32LE (./node_modules/mssql/node_modules/tedious/lib/tracking-buffer/writable-tracking-buffer.js:92:17)
    at Object.TYPE.writeParameterData (./node_modules/mssql/node_modules/tedious/lib/data-type.js:264:25)
    at new RpcRequestPayload (./node_modules/mssql/node_modules/tedious/lib/rpcrequest-payload.js:66:22)
    at Connection.execSql (./node_modules/mssql/node_modules/tedious/lib/connection.js:712:56)
    at ./node_modules/mssql/lib/tedious.js:563:33
    at Transaction.next (./node_modules/mssql/lib/main.js:738:28)
    at Request._release (./node_modules/mssql/lib/main.js:895:33)
    at Request.userCallback (./node_modules/mssql/lib/tedious.js:462:23)

It's happening in a batch of about 2k inserts inside a transaction. Any pointers to figuring this out would be greatly appreciated.

Closing Connections

Looking at the coffee script, it appears that when a connection is closed and pooling is enabled, the entire pool is cleared. (Not coffee script literate)

What's the recommended use of connections with pooling enabled? Should i

  1. connect once and share amongst modules
  2. connect, execute query and then close for each db request
  3. connect, execute query and not close for each db request.

thanks for a great module

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.