Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 18 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -856,11 +856,22 @@ const config = sql.ConnectionPool.parseConnectionString('Server=localhost,1433;D
## Request

```javascript
const request = new sql.Request(/* [pool or transaction] */)
const request = new sql.Request(/* [pool or transaction], [options] */)
```

If you omit pool/transaction argument, global pool is used instead.

The optional `options` argument allows per-request configuration overrides:

- **requestTimeout** - Override the pool's default request timeout (in ms) for this request only. This applies to queries and stored procedure executions; it does not apply to bulk data transfers (`request.bulk()`), which stream to completion as long as the connection is healthy. If you need to bound a bulk transfer, wrap the call with your own timer and call `request.cancel()`.

```javascript
// Request with a 60-second timeout instead of the pool default
const request = new sql.Request(pool, { requestTimeout: 60000 })
Comment thread
dhensby marked this conversation as resolved.
```

**Note:** When using the global pool, you must still pass `undefined` as the first argument to use options: `new sql.Request(undefined, { requestTimeout: 60000 })`.

### Events

- **recordset(columns)** - Dispatched when metadata for new recordset are parsed.
Expand Down Expand Up @@ -1226,11 +1237,13 @@ request.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.

```javascript
const transaction = new sql.Transaction(/* [pool] */)
const transaction = new sql.Transaction(/* [pool], [options] */)
```

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

The optional `options` argument allows per-transaction configuration overrides (e.g. `{ requestTimeout: 60000 }`). These are inherited by any requests created from this transaction unless overridden at the request level. Note that the timeout applies to data requests only, not to the `begin`/`commit`/`rollback` operations themselves.

__Example__

```javascript
Expand Down Expand Up @@ -1378,11 +1391,13 @@ __Errors__
**IMPORTANT:** always use `PreparedStatement` class to create prepared statements - it ensures that all your executions of prepared statement are executed on one connection. Once you call `prepare`, a single connection is acquired from the connection pool and all subsequent executions are executed exclusively on this connection. After you call `unprepare`, the connection is then released back to the connection pool.

```javascript
const ps = new sql.PreparedStatement(/* [pool] */)
const ps = new sql.PreparedStatement(/* [pool], [options] */)
```

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

The optional `options` argument allows per-statement configuration overrides (e.g. `{ requestTimeout: 60000 }`). The timeout is applied to the `prepare`, `execute`, and `unprepare` operations.

__Example__

```javascript
Expand Down
10 changes: 6 additions & 4 deletions lib/base/connection-pool.js
Original file line number Diff line number Diff line change
Expand Up @@ -627,21 +627,23 @@ class ConnectionPool extends EventEmitter {
/**
* Returns new request using this connection.
*
* @param {{ requestTimeout?: number }} [conf] Per-request overrides.
* @return {Request}
*/

request () {
return new shared.driver.Request(this)
request (conf) {
return new shared.driver.Request(this, conf)
}

/**
* Returns new transaction using this connection.
*
* @param {{ requestTimeout?: number }} [conf] Per-transaction overrides, cascaded to child requests.
* @return {Transaction}
*/

transaction () {
return new shared.driver.Transaction(this)
transaction (conf) {
return new shared.driver.Transaction(this, conf)
Comment thread
dhensby marked this conversation as resolved.
}

/**
Expand Down
15 changes: 10 additions & 5 deletions lib/base/prepared-statement.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,11 @@ class PreparedStatement extends EventEmitter {
/**
* Creates a new Prepared Statement.
*
* @param {ConnectionPool|Transaction} [holder]
* @param {ConnectionPool|Transaction} [parent]
* @param {{ requestTimeout?: number }} [overrides]
*/

constructor (parent) {
constructor (parent, overrides = {}) {
super()
Comment thread
dhensby marked this conversation as resolved.

IDS.add(this, 'PreparedStatement')
Expand All @@ -34,6 +35,10 @@ class PreparedStatement extends EventEmitter {
this._handle = 0
this.prepared = false
this.parameters = {}
this.overrides = {}
if (Number.isFinite(overrides?.requestTimeout) && overrides.requestTimeout >= 0) {
this.overrides.requestTimeout = overrides.requestTimeout
}
}

get config () {
Expand Down Expand Up @@ -245,7 +250,7 @@ class PreparedStatement extends EventEmitter {
this._acquiredConnection = connection
this._acquiredConfig = config

const req = new shared.driver.Request(this)
const req = new shared.driver.Request(this, this.overrides)
req._internal = true
req.stream = false
req.output('handle', TYPES.Int)
Expand Down Expand Up @@ -328,7 +333,7 @@ class PreparedStatement extends EventEmitter {
*/

_execute (values, callback) {
const req = new shared.driver.Request(this)
const req = new shared.driver.Request(this, this.overrides)
req._internal = true
req.stream = this.stream
req.arrayRowMode = this.arrayRowMode
Expand Down Expand Up @@ -409,7 +414,7 @@ class PreparedStatement extends EventEmitter {
return setImmediate(callback, new TransactionError("Can't unprepare the statement. There is a request in progress.", 'EREQINPROG'))
}

const req = new shared.driver.Request(this)
const req = new shared.driver.Request(this, this.overrides)
req._internal = true
req.stream = false
req.input('handle', TYPES.Int, this._handle)
Expand Down
9 changes: 7 additions & 2 deletions lib/base/request.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,11 @@ class Request extends EventEmitter {
/**
* Create new Request.
*
* @param {Connection|ConnectionPool|Transaction|PreparedStatement} parent If omitted, global connection is used instead.
* @param {Connection|ConnectionPool|Transaction|PreparedStatement} [parent] If omitted, global connection is used instead.
* @param {{ requestTimeout?: number }} [overrides]
*/

constructor (parent) {
constructor (parent, overrides = {}) {
super()

IDS.add(this, 'Request')
Expand All @@ -43,6 +44,10 @@ class Request extends EventEmitter {
this.parameters = {}
this.stream = null
this.arrayRowMode = null
this.overrides = {}
if (Number.isFinite(overrides?.requestTimeout) && overrides.requestTimeout >= 0) {
this.overrides.requestTimeout = overrides.requestTimeout
}
}

get paused () {
Expand Down
18 changes: 14 additions & 4 deletions lib/base/transaction.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,11 @@ class Transaction extends EventEmitter {
/**
* Create new Transaction.
*
* @param {Connection} [parent] If ommited, global connection is used instead.
* @param {Connection} [parent] If omitted, global connection is used instead.
* @param {{ requestTimeout?: number }} [overrides]
*/

constructor (parent) {
constructor (parent, overrides = {}) {
super()

IDS.add(this, 'Transaction')
Expand All @@ -40,6 +41,10 @@ class Transaction extends EventEmitter {
this.parent = parent || globalConnection.pool
this.isolationLevel = Transaction.defaultIsolationLevel
this.name = ''
this.overrides = {}
if (Number.isFinite(overrides?.requestTimeout) && overrides.requestTimeout >= 0) {
this.overrides.requestTimeout = overrides.requestTimeout
}
}

get config () {
Expand Down Expand Up @@ -219,11 +224,16 @@ class Transaction extends EventEmitter {
/**
* Returns new request using this transaction.
*
* @param {{ requestTimeout?: number }} [config]
* @return {Request}
*/

request () {
return new shared.driver.Request(this)
request (config) {
const overrides = { ...this.overrides }
if (Number.isFinite(config?.requestTimeout) && config.requestTimeout >= 0) {
overrides.requestTimeout = config.requestTimeout
}
return new shared.driver.Request(this, overrides)
}
Comment thread
dhensby marked this conversation as resolved.
Comment thread
dhensby marked this conversation as resolved.

/**
Expand Down
9 changes: 6 additions & 3 deletions lib/msnodesqlv8/request.js
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@ class Request extends BaseRequest {
setImmediate(callback, new RequestError("You can't use table variables for bulk insert.", 'ENAME'))
}

this.parent.acquire(this, (err, connection) => {
this.parent.acquire(this, (err, connection, config) => {
let hasReturned = false
if (!err) {
debug('connection(%d): borrowed to request #%d', IDS.get(connection), IDS.get(this))
Comment thread
dhensby marked this conversation as resolved.
Expand Down Expand Up @@ -244,7 +244,10 @@ class Request extends BaseRequest {
objectid = table.path
}

return connection.queryRaw(`if object_id('${objectid.replace(/'/g, '\'\'')}') is null ${table.declare()}`, function (err) {
return connection.queryRaw({
query_str: `if object_id('${objectid.replace(/'/g, '\'\'')}') is null ${table.declare()}`,
query_timeout: (this.overrides.requestTimeout ?? config.requestTimeout) / 1000 // msnodesqlv8 timeouts are in seconds (<1 second not supported)
}, function (err) {
if (err) { return done(err) }
go()
})
Expand Down Expand Up @@ -389,7 +392,7 @@ class Request extends BaseRequest {

const req = connection.queryRaw({
query_str: command,
query_timeout: config.requestTimeout / 1000 // msnodesqlv8 timeouts are in seconds (<1 second not supported)
query_timeout: (this.overrides.requestTimeout ?? config.requestTimeout) / 1000 // msnodesqlv8 timeouts are in seconds (<1 second not supported)
}, params)

this._setCurrentRequest(req)
Expand Down
11 changes: 11 additions & 0 deletions lib/tedious/request.js
Original file line number Diff line number Diff line change
Expand Up @@ -365,6 +365,9 @@ class Request extends BaseRequest {

connection.execBulkLoad(bulk, table.rows)
})
if (typeof this.overrides.requestTimeout === 'number') {
req.setTimeout(this.overrides.requestTimeout)
}
this._setCurrentRequest(req)

connection.execSqlBatch(req)
Expand Down Expand Up @@ -514,6 +517,10 @@ class Request extends BaseRequest {
}
})

if (typeof this.overrides.requestTimeout === 'number') {
req.setTimeout(this.overrides.requestTimeout)
}

this._setCurrentRequest(req)

req.on('columnMetadata', metadata => {
Expand Down Expand Up @@ -874,6 +881,10 @@ class Request extends BaseRequest {
}
})

if (typeof this.overrides.requestTimeout === 'number') {
req.setTimeout(this.overrides.requestTimeout)
}

this._setCurrentRequest(req)

req.on('columnMetadata', metadata => {
Expand Down
4 changes: 2 additions & 2 deletions lib/tedious/transaction.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ const TransactionError = require('../error/transaction-error')
const { CHANNELS, publish } = require('../diagnostics')

class Transaction extends BaseTransaction {
constructor (parent) {
super(parent)
constructor (parent, overrides) {
super(parent, overrides)

this._abort = () => {
if (!this._rollbackRequested) {
Expand Down
3 changes: 3 additions & 0 deletions test/cleanup.sql
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@ if exists (select * from sys.procedures where name = '__testInputOutputValue')
if exists (select * from sys.procedures where name = '__testRowsAffected')
exec('drop procedure [dbo].[__testRowsAffected]')

if exists (select * from sys.procedures where name = '__testDelay')
exec('drop procedure [dbo].[__testDelay]')

if exists (select * from sys.types where is_user_defined = 1 and name = 'MSSQLTestType')
exec('drop type [dbo].[MSSQLTestType]')

Expand Down
Loading