Gathering detailed insights and metrics for mssql
Gathering detailed insights and metrics for mssql
Gathering detailed insights and metrics for mssql
Gathering detailed insights and metrics for mssql
npm install mssql
59.8
Supply Chain
98.1
Quality
82.3
Maintenance
100
Vulnerability
98.2
License
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
2,236 Stars
1,335 Commits
470 Forks
89 Watching
4 Branches
96 Contributors
Updated on 26 Nov 2024
Minified
Minified + Gzipped
JavaScript (97.51%)
TSQL (2.49%)
Cumulative downloads
Total Downloads
Last day
-13.3%
152,803
Compared to previous day
Last week
-12%
855,467
Compared to previous week
Last month
3.7%
3,992,256
Compared to previous month
Last year
54.9%
32,841,366
Compared to previous year
Microsoft SQL Server client for Node.js
Supported TDS drivers:
npm install mssql
npm install mssql msnodesqlv8
This package requires TCP/IP to connect to SQL Server, and you may need to enable this in your installation.
1const sql = require('mssql') 2 3(async () => { 4 try { 5 // make sure that any items are correctly URL encoded in the connection string 6 await sql.connect('Server=localhost,1433;Database=database;User Id=username;Password=password;Encrypt=true') 7 const result = await sql.query`select * from mytable where id = ${value}` 8 console.dir(result) 9 } catch (err) { 10 // ... error checks 11 } 12})()
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.
Assuming you have set the appropriate environment variables, you can construct a config object as follows:
1const sql = require('mssql') 2 3const sqlConfig = { 4 user: process.env.DB_USER, 5 password: process.env.DB_PWD, 6 database: process.env.DB_NAME, 7 server: 'localhost', 8 pool: { 9 max: 10, 10 min: 0, 11 idleTimeoutMillis: 30000 12 }, 13 options: { 14 encrypt: true, // for azure 15 trustServerCertificate: false // change to true for local dev / self-signed certs 16 } 17} 18 19(async () => { 20 try { 21 // make sure that any items are correctly URL encoded in the connection string 22 await sql.connect(sqlConfig) 23 const result = await sql.query`select * from mytable where id = ${value}` 24 console.dir(result) 25 } catch (err) { 26 // ... error checks 27 } 28})()
1const sql = require('mssql/msnodesqlv8'); 2 3const config = { 4 server: "MyServer", 5 database: "MyDatabase", 6 options: { 7 trustedConnection: true, // Set to true if using Windows Authentication 8 trustServerCertificate: true, // Set to true if using self-signed certificates 9 }, 10 driver: "msnodesqlv8", // Required if using Windows Authentication 11}; 12 13(async () => { 14 try { 15 await sql.connect(config); 16 const result = await sql.query`select TOP 10 * from MyTable`; 17 console.dir(result); 18 } catch (err) { 19 console.error(err); 20 } 21})();
1const config = { 2 user: '...', 3 password: '...', 4 server: 'localhost', // You can use 'localhost\\instance' to connect to named instance 5 database: '...', 6}
1const sql = require('mssql') 2 3(async function () { 4 try { 5 let pool = await sql.connect(config) 6 let result1 = await pool.request() 7 .input('input_parameter', sql.Int, value) 8 .query('select * from mytable where id = @input_parameter') 9 10 console.dir(result1) 11 12 // Stored procedure 13 14 let result2 = await pool.request() 15 .input('input_parameter', sql.Int, value) 16 .output('output_parameter', sql.VarChar(50)) 17 .execute('procedure_name') 18 19 console.dir(result2) 20 } catch (err) { 21 // ... error checks 22 } 23})() 24 25sql.on('error', err => { 26 // ... error handler 27})
1const sql = require('mssql') 2 3sql.on('error', err => { 4 // ... error handler 5}) 6 7sql.connect(config).then(pool => { 8 // Query 9 10 return pool.request() 11 .input('input_parameter', sql.Int, value) 12 .query('select * from mytable where id = @input_parameter') 13}).then(result => { 14 console.dir(result) 15}).catch(err => { 16 // ... error checks 17});
1const sql = require('mssql') 2 3sql.on('error', err => { 4 // ... error handler 5}) 6 7sql.connect(config).then(pool => { 8 9 // Stored procedure 10 11 return pool.request() 12 .input('input_parameter', sql.Int, value) 13 .output('output_parameter', sql.VarChar(50)) 14 .execute('procedure_name') 15}).then(result => { 16 console.dir(result) 17}).catch(err => { 18 // ... error checks 19})
Native Promise is used by default. You can easily change this with sql.Promise = require('myownpromisepackage')
.
1const sql = require('mssql') 2 3sql.connect(config).then(() => { 4 return sql.query`select * from mytable where id = ${value}` 5}).then(result => { 6 console.dir(result) 7}).catch(err => { 8 // ... error checks 9}) 10 11sql.on('error', err => { 12 // ... error handler 13})
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.
1const sql = require('mssql') 2 3sql.connect(config, err => { 4 // ... error checks 5 6 // Query 7 8 new sql.Request().query('select 1 as number', (err, result) => { 9 // ... error checks 10 11 console.dir(result) 12 }) 13 14 // Stored Procedure 15 16 new sql.Request() 17 .input('input_parameter', sql.Int, value) 18 .output('output_parameter', sql.VarChar(50)) 19 .execute('procedure_name', (err, result) => { 20 // ... error checks 21 22 console.dir(result) 23 }) 24 25 // Using template literal 26 27 const request = new sql.Request() 28 request.query(request.template`select * from mytable where id = ${value}`, (err, result) => { 29 // ... error checks 30 console.dir(result) 31 }) 32}) 33 34sql.on('error', err => { 35 // ... error handler 36})
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. Events must be attached before the query completes, but can be attached while in-flight.
1const sql = require('mssql') 2 3sql.connect(config, err => { 4 // ... error checks 5 6 const request = new sql.Request() 7 request.stream = true // You can set streaming differently for each request 8 9 request.on('recordset', columns => { 10 // Emitted once for each recordset in a query 11 }) 12 13 request.on('row', row => { 14 // Emitted for each row in a recordset 15 }) 16 17 request.on('rowsaffected', rowCount => { 18 // Emitted for each `INSERT`, `UPDATE` or `DELETE` statement 19 // Requires NOCOUNT to be OFF (default) 20 }) 21 22 request.on('error', err => { 23 // May be emitted multiple times 24 }) 25 26 request.on('done', result => { 27 // Always emitted as the last one 28 }) 29 30 request.query('select * from verylargetable') // or request.execute(procedure) 31}) 32 33sql.on('error', err => { 34 // ... error handler 35})
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:
1let rowsToProcess = []; 2request.on('row', row => { 3 rowsToProcess.push(row); 4 if (rowsToProcess.length >= 15) { 5 request.pause(); 6 processRows(); 7 } 8}); 9request.on('done', () => { 10 processRows(); 11}); 12 13function processRows() { 14 // process rows 15 rowsToProcess = []; 16 request.resume(); 17}
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.
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.
1const sql = require('mssql') 2const config = { ... } 3 4// run a query against the global connection pool 5function runQuery(query) { 6 // sql.connect() will return the existing global pool if it exists or create a new one if it doesn't 7 return sql.connect(config).then((pool) => { 8 return pool.query(query) 9 }) 10}
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.
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.
1const express = require('express') 2const sql = require('mssql') 3const config = {/*...*/} 4//instantiate a connection pool 5const appPool = new sql.ConnectionPool(config) 6//require route handlers and use the same connection pool everywhere 7const route1 = require('./routes/route1') 8const app = express() 9app.get('/path', route1) 10 11//connect the pool and start the web server when done 12appPool.connect().then(function(pool) { 13 app.locals.db = pool; 14 const server = app.listen(3000, function () { 15 const host = server.address().address 16 const port = server.address().port 17 console.log('Example app listening at http://%s:%s', host, port) 18 }) 19}).catch(function(err) { 20 console.error('Error creating connection pool', err) 21});
Then the route uses the connection pool in the app.locals
object:
1// ./routes/route1.js 2const sql = require('mssql'); 3 4module.exports = function(req, res) { 5 req.app.locals.db.query('SELECT TOP 10 * FROM table_name', function(err, recordset) { 6 if (err) { 7 console.error(err) 8 res.status(500).send('SERVER ERROR') 9 return 10 } 11 res.status(200).json({ message: 'success' }) 12 }) 13}
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:
The following code is an example of a custom connection pool implementation.
1// pool-manager.js 2const mssql = require('mssql') 3const pools = new Map(); 4 5module.exports = { 6 /** 7 * Get or create a pool. If a pool doesn't exist the config must be provided. 8 * If the pool does exist the config is ignored (even if it was different to the one provided 9 * when creating the pool) 10 * 11 * @param {string} name 12 * @param {{}} [config] 13 * @return {Promise.<mssql.ConnectionPool>} 14 */ 15 get: (name, config) => { 16 if (!pools.has(name)) { 17 if (!config) { 18 throw new Error('Pool does not exist'); 19 } 20 const pool = new mssql.ConnectionPool(config); 21 // automatically remove the pool from the cache if `pool.close()` is called 22 const close = pool.close.bind(pool); 23 pool.close = (...args) => { 24 pools.delete(name); 25 return close(...args); 26 } 27 pools.set(name, pool.connect()); 28 } 29 return pools.get(name); 30 }, 31 /** 32 * Closes all the pools and removes them from the store 33 * 34 * @return {Promise<mssql.ConnectionPool[]>} 35 */ 36 closeAll: () => Promise.all(Array.from(pools.values()).map((connect) => { 37 return connect.then((pool) => pool.close()); 38 })), 39};
This file can then be used in your application to create, fetch, and close pools.
1const { get } = require('./pool-manager') 2 3async function example() { 4 const pool = await get('default') 5 return pool.request().query('SELECT 1') 6}
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.
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:
1const sql = require('mssql') 2 3// in this example all integer values will return 1 more than their actual value in the database 4sql.valueHandler.set(sql.TYPES.Int, (value) => value + 1) 5 6sql.query('SELECT * FROM [example]').then((result) => { 7 // all `int` columns will return a manipulated value as per the callback above 8})
The following is an example configuration object:
1const config = { 2 user: '...', 3 password: '...', 4 server: 'localhost', 5 database: '...', 6 pool: { 7 max: 10, 8 min: 0, 9 idleTimeoutMillis: 30000 10 } 11}
1433
). Don't set when connecting to named instance.15000
).15000
). NOTE: msnodesqlv8 driver doesn't support timeouts < 1 second. When passed via connection string, the key must be request timeout
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.false
). For more information please see section JSON support.10
).0
).30000
).columns
array. (default: false
) See Handling Duplicate Column NamesComplete list of pool options can be found here.
In addition to configuration object there is an option to pass config as a connection string. Connection strings are supported.
Server=localhost,1433;Database=database;User Id=username;Password=password;Encrypt=true
Driver=msnodesqlv8;Server=(local)\INSTANCE;Database=database;UID=DOMAIN\username;PWD=password;Encrypt=true
Several types of Azure Authentication are supported:
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.
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.
Default driver, actively maintained and production ready. Platform independent, runs everywhere Node.js runs. Officially supported by Microsoft.
Extra options:
conn
is the configured tedious Connection
. It can be used for attaching event handlers like in this example:1require('mssql').connect({...config, beforeConnect: conn => { 2 conn.once('connect', err => { err ? console.error(err) : console.log('mssql connected')}) 3 conn.once('end', err => { err ? console.error(err) : console.log('mssql disconnected')}) 4}})
true
).true
).7_4
, available: 7_1
, 7_2
, 7_3_A
, 7_3_B
, 7_4
).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
user
, password
, domain
settings.default
, ntlm
, azure-active-directory-password
, azure-active-directory-access-token
, azure-active-directory-msi-vm
, or azure-active-directory-msi-app-service
tedious
driver, depends on authentication.type
. For more details, check Tedious Authentication Interfacestedious
does not support Windows Authentication/Trusted Connection, however the msnodesqlv8
driver does.More information about Tedious specific options: http://tediousjs.github.io/tedious/api-connection.html
Alternative driver, requires Node.js v10+ or newer; Windows (32 or 64-bit) or Linux/macOS (64-bit only). It's not part of the default package so it must be installed in addition. Supports Windows/Trusted Connection authentication.
To use this driver you must use this require
statement:
1const 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:
conn
is the connection configuration, that can be modified to pass extra parameters to the driver's open()
method.false
).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.
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.
1const pool = new sql.ConnectionPool({ /* config */ })
Create a new connection pool. The initial probe connection is created to find out whether the configuration is valid.
Arguments
Example
1const pool = new sql.ConnectionPool({ 2 user: '...', 3 password: '...', 4 server: 'localhost', 5 database: '...' 6}) 7 8pool.connect(err => { 9 // ... 10})
Errors
ConnectionError
) - Login failed.ConnectionError
) - Connection timeout.ConnectionError
) - Database is already connected!ConnectionError
) - Already connecting to database!ConnectionError
) - Instance lookup failed.ConnectionError
) - Socket error.Close all active connections in the pool.
Example
1pool.close()
1const request = new sql.Request(/* [pool or transaction] */)
If you omit pool/transaction argument, global pool is used instead.
Call a stored procedure.
Arguments
returnValue
is also accessible as property of recordsets. Optional. If omitted, returns Promise.Example
1const request = new sql.Request() 2request.input('input_parameter', sql.Int, value) 3request.output('output_parameter', sql.Int) 4request.execute('procedure_name', (err, result) => { 5 // ... error checks 6 7 console.log(result.recordsets.length) // count of recordsets returned by the procedure 8 console.log(result.recordsets[0].length) // count of rows contained in first recordset 9 console.log(result.recordset) // first recordset from result.recordsets 10 console.log(result.returnValue) // procedure return value 11 console.log(result.output) // key/value collection of output values 12 console.log(result.rowsAffected) // array of numbers, each number represents the number of rows affected by executed statemens 13 14 // ... 15})
Errors
RequestError
) - Message from SQL ServerRequestError
) - Cancelled.RequestError
) - Request timeout.RequestError
) - No connection is specified for that request.ConnectionError
) - Connection not yet open.ConnectionError
) - Connection is closed.TransactionError
) - Transaction has not begun.TransactionError
) - Transaction was aborted (by user or because of an error).Add an input parameter to the request.
Arguments
undefined
and NaN
values are automatically converted to null
values.Example
1request.input('input_parameter', value) 2request.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.
1sql.map.register(MyClass, sql.Text)
You can also overwrite the default type map.
1sql.map.register(Number, sql.BigInt)
Errors (synchronous)
RequestError
) - Invalid number of arguments.RequestError
) - SQL injection warning.NB: Do not use parameters @p{n}
as these are used by the internal drivers and cause a conflict.
Add an output parameter to the request.
Arguments
undefined
and NaN
values are automatically converted to null
values. Optional.Example
1request.output('output_parameter', sql.Int) 2request.output('output_parameter', sql.VarChar(50), 'abc')
Errors (synchronous)
RequestError
) - Invalid number of arguments.RequestError
) - SQL injection warning.Convert request to a Node.js ReadableStream
Example
1const { pipeline } = require('stream') 2const request = new sql.Request() 3const readableStream = request.toReadableStream() 4pipeline(readableStream, transformStream, writableStream) 5request.query('select * from mytable')
OR if you wanted to increase the highWaterMark of the read stream to buffer more rows in memory
1const { pipeline } = require('stream') 2const request = new sql.Request() 3const readableStream = request.toReadableStream({ highWaterMark: 100 }) 4pipeline(readableStream, transformStream, writableStream) 5request.query('select * from mytable')
Sets request to stream
mode and pulls all rows from all recordsets to a given stream.
Arguments
Example
1const request = new sql.Request() 2request.pipe(stream) 3request.query('select * from mytable') 4stream.on('error', err => { 5 // ... 6}) 7stream.on('finish', () => { 8 // ... 9})
Execute the SQL command. To execute commands like create procedure
or if you plan to work with local temporary tables, use batch instead.
Arguments
Example
1const request = new sql.Request() 2request.query('select 1 as number', (err, result) => { 3 // ... error checks 4 5 console.log(result.recordset[0].number) // return 1 6 7 // ... 8})
Errors
RequestError
) - Request timeout.RequestError
) - Message from SQL ServerRequestError
) - Cancelled.RequestError
) - No connection is specified for that request.ConnectionError
) - Connection not yet open.ConnectionError
) - Connection is closed.TransactionError
) - Transaction has not begun.TransactionError
) - Transaction was aborted (by user or because of an error).1const request = new sql.Request() 2request.query('select 1 as number; select 2 as number', (err, result) => { 3 // ... error checks 4 5 console.log(result.recordset[0].number) // return 1 6 console.log(result.recordsets[0][0].number) // return 1 7 console.log(result.recordsets[1][0].number) // return 2 8})
NOTE: To get number of rows affected by the statement(s), see section Affected Rows.
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
Example
1const request = new sql.Request() 2request.batch('create procedure #temporary as select * from table', (err, result) => { 3 // ... error checks 4})
Errors
RequestError
) - Request timeout.RequestError
) - Message from SQL ServerRequestError
) - Cancelled.RequestError
) - No connection is specified for that request.ConnectionError
) - Connection not yet open.ConnectionError
) - Connection is closed.TransactionError
) - Transaction has not begun.TransactionError
) - Transaction was aborted (by user or because of an error).You can enable multiple recordsets in queries with the request.multiple = true
command.
Perform a bulk insert.
Arguments
sql.Table
instance.Example
1const table = new sql.Table('table_name') // or temporary table, e.g. #temptable 2table.create = true 3table.columns.add('a', sql.Int, {nullable: true, primary: true}) 4table.columns.add('b', sql.VarChar(50), {nullable: false}) 5table.rows.add(777, 'test') 6 7const request = new sql.Request() 8request.bulk(table, (err, result) => { 9 // ... error checks 10})
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
RequestError
) - Table name must be specified for bulk insert.RequestError
) - Request timeout.RequestError
) - Message from SQL ServerRequestError
) - Cancelled.RequestError
) - No connection is specified for that request.ConnectionError
) - Connection not yet open.ConnectionError
) - Connection is closed.TransactionError
) - Transaction has not begun.TransactionError
) - Transaction was aborted (by user or because of an error).Cancel currently executing request. Return true
if cancellation packet was send successfully.
Example
1const request = new sql.Request() 2request.query('waitfor delay \'00:00:05\'; select 1 as number', (err, result) => { 3 console.log(err instanceof sql.RequestError) // true 4 console.log(err.message) // Cancelled. 5 console.log(err.code) // ECANCEL 6 7 // ... 8}) 9 10request.cancel()
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.
1const transaction = new sql.Transaction(/* [pool] */)
If you omit connection argument, global connection is used instead.
Example
1const transaction = new sql.Transaction(/* [pool] */) 2transaction.begin(err => { 3 // ... error checks 4 5 const request = new sql.Request(transaction) 6 request.query('insert into mytable (mycolumn) values (12345)', (err, result) => { 7 // ... error checks 8 9 transaction.commit(err => { 10 // ... error checks 11 12 console.log("Transaction committed.") 13 }) 14 }) 15})
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.
1const transaction = new sql.Transaction(/* [pool] */) 2transaction.begin(err => { 3 // ... error checks 4 5 let rolledBack = false 6 7 transaction.on('rollback', aborted => { 8 // emited with aborted === true 9 10 rolledBack = true 11 }) 12 13 new sql.Request(transaction) 14 .query('insert into mytable (bitcolumn) values (2)', (err, result) => { 15 // insert should fail because of invalid value 16 17 if (err) { 18 if (!rolledBack) { 19 transaction.rollback(err => { 20 // ... error checks 21 }) 22 } 23 } else { 24 transaction.commit(err => { 25 // ... error checks 26 }) 27 } 28 }) 29})
Begin a transaction.
Arguments
READ_COMMITTED
by default. For possible values see sql.ISOLATION_LEVEL
.Example
1const transaction = new sql.Transaction() 2transaction.begin(err => { 3 // ... error checks 4})
Errors
ConnectionError
) - Connection not yet open.TransactionError
) - Transaction has already begun.Commit a transaction.
Arguments
Example
1const transaction = new sql.Transaction() 2transaction.begin(err => { 3 // ... error checks 4 5 transaction.commit(err => { 6 // ... error checks 7 }) 8})
Errors
TransactionError
) - Transaction has not begun.TransactionError
) - Can't commit transaction. There is a request in progress.Rollback a transaction. If the queue isn't empty, all queued requests will be Cancelled and the transaction will be marked as aborted.
Arguments
Example
1const transaction = new sql.Transaction() 2transaction.begin(err => { 3 // ... error checks 4 5 transaction.rollback(err => { 6 // ... error checks 7 }) 8})
Errors
TransactionError
) - Transaction has not begun.TransactionError
) - Can't rollback transaction. There is a request in progress.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.
1const ps = new sql.PreparedStatement(/* [pool] */)
If you omit the connection argument, the global connection is used instead.
Example
1const ps = new sql.PreparedStatement(/* [pool] */) 2ps.input('param', sql.Int) 3ps.prepare('select @param as value', err => { 4 // ... error checks 5 6 ps.execute({param: 12345}, (err, result) => { 7 // ... error checks 8 9 // release the connection after queries are executed 10 ps.unprepare(err => { 11 // ... error checks 12 13 }) 14 }) 15})
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
.
Add an input parameter to the prepared statement.
Arguments
Example
1ps.input('input_parameter', sql.Int) 2ps.input('input_parameter', sql.VarChar(50))
Errors (synchronous)
PreparedStatementError
) - Invalid number of arguments.PreparedStatementError
) - SQL injection warning.Add an output parameter to the prepared statement.
Arguments
Example
1ps.output('output_parameter', sql.Int) 2ps.output('output_parameter', sql.VarChar(50))
Errors (synchronous)
PreparedStatementError
) - Invalid number of arguments.PreparedStatementError
) - SQL injection warning.Prepare a statement.
Arguments
Example
1const ps = new sql.PreparedStatement() 2ps.prepare('select @param as value', err => { 3 // ... error checks 4})
Errors
ConnectionError
) - Connection not yet open.PreparedStatementError
) - Statement is already prepared.TransactionError
) - Transaction has not begun.Execute a prepared statement.
Arguments
Example
1const ps = new sql.PreparedStatement() 2ps.input('param', sql.Int) 3ps.prepare('select @param as value', err => { 4 // ... error checks 5 6 ps.execute({param: 12345}, (err, result) => { 7 // ... error checks 8 9 console.log(result.recordset[0].value) // return 12345 10 console.log(result.rowsAffected) // Returns number of affected rows in case of INSERT, UPDATE or DELETE statement. 11 12 ps.unprepare(err => { 13 // ... error checks 14 }) 15 }) 16})
You can also stream executed request.
1const ps = new sql.PreparedStatement() 2ps.input('param', sql.Int) 3ps.prepare('select @param as value', err => { 4 // ... error checks 5 6 ps.stream = true 7 const request = ps.execute({param: 12345}) 8 9 request.on('recordset', columns => { 10 // Emitted once for each recordset in a query 11 }) 12 13 request.on('row', row => { 14 // Emitted for each row in a recordset 15 }) 16 17 request.on('error', err => { 18 // May be emitted multiple times 19 }) 20 21 request.on('done', result => { 22 // Always emitted as the last one 23 24 console.log(result.rowsAffected) // Returns number of affected rows in case of INSERT, UPDATE or DELETE statement. 25 26 ps.unprepare(err => { 27 // ... error checks 28 }) 29 }) 30})
TIP: To learn more about how number of affected rows works, see section Affected Rows.
Errors
PreparedStatementError
) - Statement is not prepared.RequestError
) - Request timeout.RequestError
) - Message from SQL ServerRequestError
) - Cancelled.Unprepare a prepared statement.
Arguments
Example
1const ps = new sql.PreparedStatement() 2ps.input('param', sql.Int) 3ps.prepare('select @param as value', err => { 4 // ... error checks 5 6 ps.unprepare(err => { 7 // ... error checks 8 9 }) 10})
Errors
PreparedStatementError
) - Statement is not prepared.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.
1{ 2 "user": "...", 3 "password": "...", 4 "server": "localhost", 5 "database": "..." 6}
Example
1echo "select * from mytable" | mssql /path/to/config
Results in:
1[[{"username":"patriksimek","password":"tooeasy"}]]
You can also query for multiple recordsets.
1echo "select * from mytable; select * from myothertable" | mssql
Results in:
1[[{"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
).
1echo "select * from mytable" | mssql /path/to/config --database anotherdatabase
Results in:
1[[{"username":"onotheruser","password":"quiteeasy"}]]
node-mssql has built-in deserializer for Geography and Geometry CLR data types.
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:
1select geography::STGeomFromText(N'POLYGON((1 1, 3 1, 3 1, 1 1))',4326)
results in:
1{ 2 srid: 4326, 3 version: 2, 4 points: [ 5 Point { lat: 1, lng: 1, z: null, m: null }, 6 Point { lat: 1, lng: 3, z: null, m: null }, 7 Point { lat: 1, lng: 3, z: null, m: null }, 8 Point { lat: 1, lng: 1, z: null, m: null } 9 ], 10 figures: [ { attribute: 1, pointOffset: 0 } ], 11 shapes: [ { parentOffset: -1, figureOffset: 0, type: 3 } ], 12 segments: [] 13}
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 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:
1select geometry::STGeomFromText(N'POLYGON((1 1, 3 1, 3 7, 1 1))',4326)
into the JavaScript object:
1{ 2 srid: 4326, 3 version: 1, 4 points: [ 5 Point { x: 1, y: 1, z: null, m: null }, 6 Point { x: 1, y: 3, z: null, m: null }, 7 Point { x: 7, y: 3, z: null, m: null }, 8 Point { x: 1, y: 1, z: null, m: null } 9 ], 10 figures: [ { attribute: 2, pointOffset: 0 } ], 11 shapes: [ { parentOffset: -1, figureOffset: 0, type: 3 } ], 12 segments: [] 13}
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.
1CREATE TYPE TestType AS TABLE ( a VARCHAR(50), b INT );
Next we will need a stored procedure.
1CREATE PROCEDURE MyCustomStoredProcedure (@tvp TestType readonly) AS SELECT * FROM @tvp
Now let's go back to our Node.js app.
1const tvp = new sql.Table() // You can optionally specify table type name in the first argument. 2 3// Columns must correspond with type we have created in database. 4tvp.columns.add('a', sql.VarChar(50)) 5tvp.columns.add('b', sql.Int) 6 7// Add rows 8tvp.rows.add('hello tvp', 777) // Values are in same order as columns.
You can send table as a parameter to stored procedure.
1const request = new sql.Request() 2request.input('tvp', tvp) 3request.execute('MyCustomStoredProcedure', (err, result) => { 4 // ... error checks 5 6 console.dir(result.recordsets[0][0]) // {a: 'hello tvp', b: 777} 7})
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()
1const tvp = new sql.Table() // You can optionally specify table type name in the first argument. 2 3// Columns must correspond with type we have created in database. 4tvp.columns.add('a', sql.VarChar(50)) 5tvp.columns.add('b', sql.Int) 6 7// Add rows 8tvp.rows.add('hello tvp', 777) // Values are in same order as columns. 9tvp.rows.clear()
An object returned from a sucessful
basic query would look like the following.
1{ 2 recordsets: [ 3 [ 4 { 5 COL1: "some content", 6 COL2: "some more content" 7 } 8 ] 9 ], 10 recordset: [ 11 { 12 COL1: "some content", 13 COL2: "some more content" 14 } 15 ], 16 output: {}, 17 rowsAffected: [1] 18} 19
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
1const request = new sql.Request() 2request.query('update myAwesomeTable set awesomness = 100').then(result => { 3 console.log(result.rowsAffected) 4})
Example using callbacks
1const request = new sql.Request() 2request.query('update myAwesomeTable set awesomness = 100', (err, result) => { 3 console.log(result.rowsAffected) 4})
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.
1const request = new sql.Request() 2request.stream = true 3request.query('update myAwesomeTable set awesomness = 100') 4request.on('rowsaffected', rowCount => { 5 console.log(rowCount) 6}) 7request.on('done', result => { 8 console.log(result.rowsAffected) 9})
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
1SELECT 2 1 AS 'a.b.c', 3 2 AS 'a.b.d', 4 3 AS 'a.x', 5 4 AS 'a.y' 6FOR JSON PATH
Results in:
1recordset = [ { '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:
1recordset = [ { 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.
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:
1const request = new sql.Request() 2request 3 .query("select 'asdf' as name, 'qwerty' as other_name, 'jkl' as name") 4 .then(result => { 5 console.log(result) 6 });
Results in:
1{ 2 recordsets: [ 3 [ { name: [ 'asdf', 'jkl' ], other_name: 'qwerty' } ] 4 ], 5 recordset: [ { name: [ 'asdf', 'jkl' ], other_name: 'qwerty' } ], 6 output: {}, 7 rowsAffected: [ 1 ] 8}
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.
1const request = new sql.Request() 2request.arrayRowMode = true 3request 4 .query("select 'asdf' as name, 'qwerty' as other_name, 'jkl' as name") 5 .then(result => { 6 console.log(result) 7 });
Results in:
1{ 2 recordsets: [ [ [ 'asdf', 'qwerty', 'jkl' ] ] ], 3 recordset: [ [ 'asdf', 'qwerty', 'jkl' ] ], 4 output: {}, 5 rowsAffected: [ 1 ], 6 columns: [ 7 [ 8 { 9 index: 0, 10 name: 'name', 11 length: 4, 12 type: [sql.VarChar], 13 scale: undefined, 14 precision: undefined, 15 nullable: false, 16 caseSensitive: false, 17 identity: false, 18 readOnly: true 19 }, 20 { 21 index: 1, 22 name: 'other_name', 23 length: 6, 24 type: [sql.VarChar], 25 scale: undefined, 26 precision: undefined, 27 nullable: false, 28 caseSensitive: false, 29 identity: false, 30 readOnly: true 31 }, 32 { 33 index: 2, 34 name: 'name', 35 length: 3, 36 type: [sql.VarChar], 37 scale: undefined, 38 precision: undefined, 39 nullable: false, 40 caseSensitive: false, 41 identity: false, 42 readOnly: true 43 } 44 ] 45 ] 46}
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
):
1const request = new sql.Request() 2request.stream = true 3request.query("select 'asdf' as name, 'qwerty' as other_name, 'jkl' as name") 4request.on('recordset', recordset => console.log(recordset))
Results in:
1{ 2 name: { 3 index: 2, 4 name: 'name', 5 length: 3, 6 type: [sql.VarChar], 7 scale: undefined, 8 precision: undefined, 9 nullable: false, 10 caseSensitive: false, 11 identity: false, 12 readOnly: true 13 }, 14 other_name: { 15 index: 1, 16 name: 'other_name', 17 length: 6, 18 type: [sql.VarChar], 19 scale: undefined, 20 precision: undefined, 21 nullable: false, 22 caseSensitive: false, 23 identity: false, 24 readOnly: true 25 } 26}
With arrayRowMode
:
1const request = new sql.Request() 2request.stream = true 3request.arrayRowMode = true 4request.query("select 'asdf' as name, 'qwerty' as other_name, 'jkl' as name") 5 6request.on('recordset', recordset => console.log(recordset))
Results in:
1[ 2 { 3 index: 0, 4 name: 'name', 5 length: 4, 6 type: [sql.VarChar], 7 scale: undefined, 8 precision: undefined, 9 nullable: false, 10 caseSensitive: false, 11 identity: false, 12 readOnly: true 13 }, 14 { 15 index: 1, 16 name: 'other_name', 17 length: 6, 18 type: [sql.VarChar], 19 scale: undefined, 20 precision: undefined, 21 nullable: false, 22 caseSensitive: false, 23 identity: false, 24 readOnly: true 25 }, 26 { 27 index: 2, 28 name: 'name', 29 length: 3, 30 type: [sql.VarChar], 31 scale: undefined, 32 precision: undefined, 33 nullable: false, 34 caseSensitive: false, 35 identity: false, 36 readOnly: true 37 } 38]
There are 4 types of errors you can handle:
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
.
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. |
SQL errors (RequestError
with err.code
equal to EREQUEST
) contains additional details.
To receive informational messages generated by PRINT
or RAISERROR
commands use:
1const request = new sql.Request() 2request.on('info', info => { 3 console.dir(info) 4}) 5request.query('print \'Hello world.\';', (err, result) => { 6 // ... 7})
Structure of informational message:
Recordset metadata are accessible through the recordset.columns
property.
1const request = new sql.Request() 2request.query('select convert(decimal(18, 4), 1) as first, \'asdf\' as second', (err, result) => { 3 console.dir(result.recordset.columns) 4 5 console.log(result.recordset.columns.first.type === sql.Decimal) // true 6 console.log(result.recordset.columns.second.type === sql.VarChar) // true 7})
Columns structure for example above:
1{ 2 first: { 3 index: 0, 4 name: 'first', 5 length: 17, 6 type: [sql.Decimal], 7 scale: 4, 8 precision: 18, 9 nullable: true, 10 caseSensitive: false 11 identity: false 12 readOnly: true 13 }, 14 second: { 15 index: 1, 16 name: 'second', 17 length: 4, 18 type: [sql.VarChar], 19 nullable: false, 20 caseSensitive: false 21 identity: false 22 readOnly: true 23 } 24}
You can define data types with length/precision/scale:
1request.input("name", sql.VarChar, "abc") // varchar(3) 2request.input("name", sql.VarChar(50), "abc") // varchar(50) 3request.input("name", sql.VarChar(sql.MAX), "abc") // varchar(MAX) 4request.output("name", sql.VarChar) // varchar(8000) 5request.output("name", sql.VarChar, "abc") // varchar(3) 6 7request.input("name", sql.Decimal, 155.33) // decimal(18, 0) 8request.input("name", sql.Decimal(10), 155.33) // decimal(10, 0) 9request.input("name", sql.Decimal(10, 2), 155.33) // decimal(10, 2) 10 11request.input("name", sql.DateTime2, new Date()) // datetime2(7) 12request.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.
This module has built-in SQL injection protection. Always use parameters or tagged template literals to pass sanitized values to your queries.
1const request = new sql.Request() 2request.input('myval', sql.VarChar, '-- commented') 3request.query('select @myval as myval', (err, result) => { 4 console.dir(result) 5})
config.options.tdsVersion = '7_1'
(issue)parseConnectionString
on ConnectionPooltrustServerCertificate
defaults to false
if not suppliedtarn.js
so _poolDestroy
can take advantage of being a promiseConnectionPool.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.options.encrypt
is now true
by defaultTYPES.Null
has now been removedconst conn = sql.connect(); conn.close()
will be the same as sql.close()
sql.connect()
) will return the current global connection if it exists (rather than throwing an error)replaceInput
and replaceOutput
insteadTransaction
s will now throw an errorConnectionPool
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 notnode-pool
to tarn.js
ConnectionPool.pool.size
deprecated, use ConnectionPool.size
insteadConnectionPool.pool.available
deprecated, use ConnectionPool.available
insteadConnectionPool.pool.pending
deprecated, use ConnectionPool.pending
insteadConnectionPool.pool.borrowed
deprecated, use ConnectionPool.borrowed
insteadConnection
was renamed to ConnectionPool
.msnodesqlv8
driver, use const sql = require('mssql/msnodesqlv8')
syntax.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).multiple: true
was removed.Transaction
and PreparedStatement
internal queues was removed.connect
and close
events.tds
and msnodesql
drivers.No vulnerabilities found.
Reason
22 commit(s) and 8 issue activity found in the last 90 days -- score normalized to 10
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
GitHub workflow tokens follow principle of least privilege
Details
Reason
license file detected
Details
Reason
packaging workflow detected
Details
Reason
3 existing vulnerabilities detected
Details
Reason
Found 2/4 approved changesets -- score normalized to 5
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Score
Last Scanned on 2024-11-18
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More