mssql 12.7.15 → 12.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +53 -12
- package/lib/base/connection-pool.js +66 -26
- package/lib/base/prepared-statement.js +64 -4
- package/lib/base/request.js +4 -2
- package/lib/base/transaction.js +1 -1
- package/lib/global-connection.js +21 -9
- package/lib/msnodesqlv8/connection-pool.js +9 -1
- package/lib/msnodesqlv8/request.js +74 -20
- package/lib/msnodesqlv8/transaction.js +2 -0
- package/lib/tedious/request.js +21 -12
- package/lib/tedious/transaction.js +3 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
Supported TDS drivers:
|
|
8
8
|
|
|
9
9
|
- [Tedious][tedious-url] (pure JavaScript - Windows/macOS/Linux, default)
|
|
10
|
-
- [MSNodeSQLv8][msnodesqlv8-url] (Microsoft / Contributors Node V8 Driver for Node.js for SQL Server, v2-v6 native - Windows or Linux/macOS 64 bits only)
|
|
10
|
+
- [MSNodeSQLv8][msnodesqlv8-url] (Microsoft / Contributors Node V8 Driver for Node.js for SQL Server, v2.4.8-v6 native - Windows or Linux/macOS 64 bits only)
|
|
11
11
|
|
|
12
12
|
## Installation
|
|
13
13
|
|
|
@@ -23,7 +23,7 @@ npm install mssql
|
|
|
23
23
|
npm install mssql msnodesqlv8
|
|
24
24
|
```
|
|
25
25
|
|
|
26
|
-
msnodesqlv8 6 needs Node.js 22 or later. On an older Node.js, install msnodesqlv8 5 (`npm install mssql msnodesqlv8@5`).
|
|
26
|
+
msnodesqlv8 6 needs Node.js 22 or later. On an older Node.js, install msnodesqlv8 5 (`npm install mssql msnodesqlv8@5`). With msnodesqlv8 6, use its latest release, 6.2.1 or later: 6.0.0 to 6.2.0 keep hold of the connection of a stream that is paused after it is cancelled.
|
|
27
27
|
|
|
28
28
|
## SQL Server prerequisites
|
|
29
29
|
|
|
@@ -468,6 +468,8 @@ Awaiting or `.then`-ing the pool creation is a safe way to ensure that the pool
|
|
|
468
468
|
|
|
469
469
|
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.
|
|
470
470
|
|
|
471
|
+
While `sql.connect()` is in progress, `sql.close()` rejects with `ECONNECTING` and the global pool continues to connect. Wait for `sql.connect()` to finish before you call `sql.close()`. While `sql.close()` is in progress, `sql.connect()` creates a new global pool and does not reject with `ECLOSING`. If `sql.connect()` fails, the next `sql.connect()` call creates a new global pool.
|
|
472
|
+
|
|
471
473
|
### Global Pool Single Instance
|
|
472
474
|
|
|
473
475
|
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.
|
|
@@ -663,6 +665,8 @@ Complete list of pool options can be found [here](https://github.com/vincit/tarn
|
|
|
663
665
|
|
|
664
666
|
In addition to configuration object there is an option to pass config as a connection string. Connection strings are supported.
|
|
665
667
|
|
|
668
|
+
The number keys `Connection Timeout`, `ConnectRetryInterval`, `Max Pool Size`, `Min Pool Size`, `Packet Size` and `Request Timeout` must have a value that starts with a number. For a value such as `abc`, the parser throws an error that names the key and the value.
|
|
669
|
+
|
|
666
670
|
##### Classic Connection String
|
|
667
671
|
|
|
668
672
|
###### Standard configuration using tedious driver
|
|
@@ -675,6 +679,8 @@ Server=localhost,1433;Database=database;User Id=username;Password=password;Encry
|
|
|
675
679
|
Driver=msnodesqlv8;Server=(local)\INSTANCE;Database=database;UID=DOMAIN\username;PWD=password;Encrypt=true
|
|
676
680
|
```
|
|
677
681
|
|
|
682
|
+
`Encrypt` takes `true`, `yes`, `mandatory` or `1` to encrypt, and `false`, `no`, `optional` or `0` to not encrypt. It also takes `strict`, which sets `options.encrypt` to `'strict'` and turns on TDS 8.0 strict encryption with the [tedious](#tedious) and [MSNodeSQLv8](#msnodesqlv8) drivers. These values are not case sensitive. With the tedious driver, a connection that does not encrypt fails if the server requires encryption.
|
|
683
|
+
|
|
678
684
|
##### Azure Active Directory Authentication Connection String
|
|
679
685
|
|
|
680
686
|
Several types of Azure Authentication are supported:
|
|
@@ -726,7 +732,7 @@ require('mssql').connect({...config, beforeConnect: conn => {
|
|
|
726
732
|
```
|
|
727
733
|
- **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.
|
|
728
734
|
- **options.useUTC** - A boolean determining whether or not use UTC time for values without time zone offset (default: `true`).
|
|
729
|
-
- **options.encrypt** - A boolean determining whether or not the connection will be encrypted (default: `true`).
|
|
735
|
+
- **options.encrypt** - A boolean determining whether or not the connection will be encrypted, or `'strict'` to use TDS 8.0 strict encryption (default: `true`). In a connection string, `Encrypt=strict` sets `'strict'`.
|
|
730
736
|
- **options.tdsVersion** - The version of TDS to use (default: `7_4`, available: `7_1`, `7_2`, `7_3_A`, `7_3_B`, `7_4`).
|
|
731
737
|
- **options.appName** - Application name used for SQL server logging.
|
|
732
738
|
- **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.
|
|
@@ -765,6 +771,7 @@ msnodesqlv8 5 and earlier round `float` and `real` values, and `decimal` values
|
|
|
765
771
|
- **connectionString** - Connection string (default: see below).
|
|
766
772
|
- **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.
|
|
767
773
|
- **options.trustedConnection** - Use Windows Authentication (default: `false`).
|
|
774
|
+
- **options.encrypt** - A boolean determining whether or not the connection will be encrypted, or `'strict'` to use TDS 8.0 strict encryption (default: `false`). `'strict'` writes `Encrypt=Strict` to the connection string, which needs ODBC Driver 18 or later, so set `driver` to that driver, for example `driver: 'ODBC Driver 18 for SQL Server'`.
|
|
768
775
|
- **options.useUTC** - A boolean determining whether or not to use UTC time for values without time zone offset (default: `true`).
|
|
769
776
|
|
|
770
777
|
Default connection string when connecting to port:
|
|
@@ -801,6 +808,10 @@ const pool = new sql.ConnectionPool({ /* config */ })
|
|
|
801
808
|
|
|
802
809
|
Create a new connection pool. The initial probe connection is created to find out whether the configuration is valid.
|
|
803
810
|
|
|
811
|
+
If the pool is already connected, `connect()` resolves with the pool. If the pool is connecting, `connect()` waits for the connection attempt in progress and gets its result.
|
|
812
|
+
|
|
813
|
+
Until the pool has closed, `connect()` rejects with `ECLOSING`. Wait for `close()` to finish before you connect the pool again, or create a new `ConnectionPool`. The pool has closed when it publishes `mssql:pool:close` (`POOL_CLOSE`), just before `close()` completes. Thus a subscriber to that channel can connect the pool again.
|
|
814
|
+
|
|
804
815
|
__Arguments__
|
|
805
816
|
|
|
806
817
|
- **callback(err)** - A callback which is called after initial probe connection has established, or an error has occurred. Optional. If omitted, returns [Promise](#promises).
|
|
@@ -823,10 +834,10 @@ pool.connect(err => {
|
|
|
823
834
|
__Errors__
|
|
824
835
|
- ELOGIN (`ConnectionError`) - Login failed.
|
|
825
836
|
- ETIMEOUT (`ConnectionError`) - Connection timeout.
|
|
826
|
-
-
|
|
827
|
-
- EALREADYCONNECTING (`ConnectionError`) - Already connecting to database!
|
|
837
|
+
- EDRIVER (`ConnectionError`) - Driver version not supported (msnodesqlv8 older than 2.4.8).
|
|
828
838
|
- EINSTLOOKUP (`ConnectionError`) - Instance lookup failed.
|
|
829
839
|
- ESOCKET (`ConnectionError`) - Socket error.
|
|
840
|
+
- ECLOSING (`ConnectionError`) - Cannot connect a pool while it is closing.
|
|
830
841
|
|
|
831
842
|
---------------------------------------
|
|
832
843
|
|
|
@@ -834,17 +845,28 @@ __Errors__
|
|
|
834
845
|
|
|
835
846
|
Close all active connections in the pool.
|
|
836
847
|
|
|
848
|
+
`close()` waits for running requests, open transactions and prepared statements to release their connections back to the pool. This wait has no timeout. A request on the pool, `begin()` or `prepare()` that waits for a free connection does not get one, even if you called it before `close()`. It fails before `close()` completes, or earlier if its wait for a connection times out (`pool.acquireTimeoutMillis`, default `30000`). This error does not always have a `code`.
|
|
849
|
+
|
|
850
|
+
After you call `close()`, `pool.connected` is `false`. New work then fails with `ECONNCLOSED` (`ConnectionError`): new requests (on the pool or on an open transaction), `begin()`, `prepare()` and a prepared statement's `execute()`.
|
|
851
|
+
|
|
852
|
+
A prepared statement or a transaction can still release its connection while the pool closes: `unprepare()`, `commit()` and `rollback()` work as usual. `close()` does not complete until every prepared statement is unprepared and every transaction has ended. With tedious, if the server rolls back a transaction, `close()` does not wait for the statements prepared in it (see [Prepared Statement](#prepared-statement)).
|
|
853
|
+
|
|
854
|
+
Until the pool has closed, `connect()` rejects with `ECLOSING`. Thus a prepared statement that you do not unprepare, or a transaction that you do not end, stops the pool from connecting again. To connect while `close()` waits, create a new `ConnectionPool`.
|
|
855
|
+
|
|
837
856
|
__Example__
|
|
838
857
|
|
|
839
858
|
```javascript
|
|
840
859
|
pool.close()
|
|
841
860
|
```
|
|
842
861
|
|
|
862
|
+
__Errors__
|
|
863
|
+
- ECONNECTING (`ConnectionError`) - Cannot close a pool while it is connecting.
|
|
864
|
+
|
|
843
865
|
---------------------------------------
|
|
844
866
|
|
|
845
867
|
### Pool properties
|
|
846
868
|
|
|
847
|
-
These properties are available on a connected `ConnectionPool` instance (after `connect()` has resolved)
|
|
869
|
+
These properties are available on a connected `ConnectionPool` instance (after `connect()` has resolved). Before the pool has connected, and after `close()` has finished, `size`, `available`, `pending` and `borrowed` are `0`:
|
|
848
870
|
|
|
849
871
|
- **pool.healthy** - `Boolean` - Whether the pool is able to create new connections.
|
|
850
872
|
- **pool.size** - `Number` - Total number of connections in the pool (free + used + pending creation).
|
|
@@ -1285,7 +1307,11 @@ request.cancel()
|
|
|
1285
1307
|
|
|
1286
1308
|
A cancelled stream emits an `error` event with code `ECANCEL`, followed by `done`.
|
|
1287
1309
|
|
|
1288
|
-
With the `msnodesqlv8` driver, a request that is already running can only be cancelled from msnodesqlv8 5.6. Earlier versions can cancel a paused stream, but let any other running request run to the end and complete as if `cancel()` had not been called. A paused stream is cancelled once the driver stops reading, at the end of a batch of 50 rows or the start of the next result set
|
|
1310
|
+
With the `msnodesqlv8` driver, a request that is already running can only be cancelled from msnodesqlv8 5.6. Earlier versions can cancel a paused stream, but let any other running request run to the end and complete as if `cancel()` had not been called. A paused stream is cancelled once the driver stops reading, at the end of a batch of 50 rows or the start of the next result set.
|
|
1311
|
+
|
|
1312
|
+
Before msnodesqlv8 6, that includes a stream paused before its query reaches its first result set, as `toReadableStream()` leaves one until it is read. Cancelling it while msnodesqlv8 is still working through the statements ahead of that result set can crash the process, so the cancel waits for them: they run to the end and keep their effects, however long they take. The request timeout ends the wait if it is at least a second. With `requestTimeout: 0`, or anything under a second, which msnodesqlv8 takes as no timeout, nothing ends it. msnodesqlv8 6 cancels such a stream at once.
|
|
1313
|
+
|
|
1314
|
+
A query that ends before the cancel takes effect, or times out, completes as cancelled, after emitting any error it ended with.
|
|
1289
1315
|
|
|
1290
1316
|
## Transaction
|
|
1291
1317
|
|
|
@@ -1485,6 +1511,8 @@ You can execute multiple queries against the same prepared statement but you *mu
|
|
|
1485
1511
|
|
|
1486
1512
|
**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`.
|
|
1487
1513
|
|
|
1514
|
+
If the server rolls back a transaction that has a prepared statement (for example, when `abortTransactionOnError` is on and a statement fails), the transaction gives its connection back to the pool, and the pool can lend it to another caller, or to the same transaction when it begins again. From then on, `execute` rejects with `EABORT` and doesn't use the connection. Still call `unprepare`: it releases the statement without sending anything to the server. The server keeps the statement's handle on that connection until the connection closes. The msnodesqlv8 driver can't tell when the server rolls a transaction back (see [Aborted transactions](#transaction)), so with msnodesqlv8 the statement keeps its connection.
|
|
1515
|
+
|
|
1488
1516
|
---------------------------------------
|
|
1489
1517
|
|
|
1490
1518
|
### input (name, type)
|
|
@@ -1626,18 +1654,31 @@ ps.prepare('select @param as value', err => {
|
|
|
1626
1654
|
**TIP**: To learn more about how number of affected rows works, see section [Affected Rows](#affected-rows).
|
|
1627
1655
|
|
|
1628
1656
|
__Errors__
|
|
1657
|
+
- ENOCONN (`PreparedStatementError`) - No connection is specified for that prepared statement.
|
|
1658
|
+
- ECONNCLOSED (`ConnectionError`) - Connection is closed.
|
|
1629
1659
|
- ENOTPREPARED (`PreparedStatementError`) - Statement is not prepared.
|
|
1630
1660
|
- ETIMEOUT (`RequestError`) - Request timeout.
|
|
1631
1661
|
- EREQUEST (`RequestError`) - *Message from SQL Server*
|
|
1632
1662
|
- EPARAM (`RequestError`) - A parameter value is not valid for its type.
|
|
1633
1663
|
- ECANCEL (`RequestError`) - Cancelled.
|
|
1634
1664
|
- EREQINPROG (`TransactionError`) - Can't acquire connection for the request. There is another request in progress.
|
|
1665
|
+
- EABORT (`TransactionError`) - The transaction that the statement was prepared in has been aborted.
|
|
1635
1666
|
|
|
1636
1667
|
---------------------------------------
|
|
1637
1668
|
|
|
1638
1669
|
### unprepare ([callback])
|
|
1639
1670
|
|
|
1640
|
-
Unprepare a prepared statement.
|
|
1671
|
+
Unprepare a prepared statement. With the tedious driver, if the server has rolled back the transaction of the statement, `unprepare` releases the statement and sends nothing to the server.
|
|
1672
|
+
|
|
1673
|
+
If the request to unprepare the statement fails (for example, because the connection has died), `unprepare` rejects with that error. The statement still gives its connection back and is no longer prepared. The pool then closes that connection instead of lending it out again. In a transaction, the connection stays with the transaction until you commit or roll it back. With the tedious driver, the transaction also gives the connection back if the server rolls the transaction back.
|
|
1674
|
+
|
|
1675
|
+
If another request on the statement is in progress, `unprepare` rejects and changes nothing:
|
|
1676
|
+
|
|
1677
|
+
- While `prepare` is in progress, `unprepare` rejects with `ENOTPREPARED`. Call `unprepare` when `prepare` has finished.
|
|
1678
|
+
- While `execute` is in progress, `unprepare` rejects with `EREQINPROG`. The statement stays prepared and keeps its connection. Call `unprepare` again when `execute` has finished.
|
|
1679
|
+
- While an earlier `unprepare` call is in progress, `unprepare` rejects with `EREQINPROG`. The earlier call releases the statement, so a later `unprepare` call rejects with `ENOTPREPARED`.
|
|
1680
|
+
|
|
1681
|
+
With the tedious driver, after the server has rolled back the transaction, `unprepare` releases the statement at once. A second call then rejects with `ENOTPREPARED`.
|
|
1641
1682
|
|
|
1642
1683
|
__Arguments__
|
|
1643
1684
|
|
|
@@ -2220,13 +2261,13 @@ Name | Code | Message
|
|
|
2220
2261
|
:--- | :--- | :---
|
|
2221
2262
|
`ConnectionError` | ELOGIN | Login failed.
|
|
2222
2263
|
`ConnectionError` | ETIMEOUT | Connection timeout.
|
|
2223
|
-
`ConnectionError` | EDRIVER | Unknown driver.
|
|
2224
|
-
`ConnectionError` | EALREADYCONNECTED | Database is already connected!
|
|
2225
|
-
`ConnectionError` | EALREADYCONNECTING | Already connecting to database!
|
|
2264
|
+
`ConnectionError` | EDRIVER | Unknown driver, or a driver version that is not supported.
|
|
2226
2265
|
`ConnectionError` | ENOTOPEN | Connection not yet open.
|
|
2227
2266
|
`ConnectionError` | EINSTLOOKUP | Instance lookup failed.
|
|
2228
2267
|
`ConnectionError` | ESOCKET | Socket error.
|
|
2229
2268
|
`ConnectionError` | ECONNCLOSED | Connection is closed.
|
|
2269
|
+
`ConnectionError` | ECLOSING | Cannot connect a pool while it is closing.
|
|
2270
|
+
`ConnectionError` | ECONNECTING | Cannot close a pool while it is connecting.
|
|
2230
2271
|
`TransactionError` | ENOTBEGUN | Transaction has not begun.
|
|
2231
2272
|
`TransactionError` | EALREADYBEGUN | Transaction has already begun.
|
|
2232
2273
|
`TransactionError` | EREQINPROG | Can't commit/rollback transaction, unprepare the statement or acquire connection for the request. There is a request in progress.
|
|
@@ -2467,7 +2508,7 @@ dc.subscribe(CHANNELS.CONNECTION_RELEASE, ({ connectionId, poolId }) => {
|
|
|
2467
2508
|
| `TRANSACTION_COMMIT` | `mssql:transaction:commit` | Transaction committed |
|
|
2468
2509
|
| `TRANSACTION_ROLLBACK` | `mssql:transaction:rollback` | Transaction rolled back (includes `aborted` flag) |
|
|
2469
2510
|
| `REQUEST_CANCEL` | `mssql:request:cancel` | Request cancelled |
|
|
2470
|
-
| `PREPARED_STATEMENT_UNPREPARE` | `mssql:prepared-statement:unprepare` | Prepared statement
|
|
2511
|
+
| `PREPARED_STATEMENT_UNPREPARE` | `mssql:prepared-statement:unprepare` | Prepared statement unprepared (only when `unprepare()` succeeds) |
|
|
2471
2512
|
|
|
2472
2513
|
### Example: OpenTelemetry Spans
|
|
2473
2514
|
|
|
@@ -10,14 +10,18 @@ const shared = require('../shared')
|
|
|
10
10
|
const { MSSQLError } = require('../error')
|
|
11
11
|
const { CHANNELS, tracePromise, traceCallback, publish } = require('../diagnostics')
|
|
12
12
|
|
|
13
|
-
|
|
13
|
+
// toSchema() gives the schema default for an empty boolean or number value.
|
|
14
|
+
// This schema drops the defaults, so an empty value gives undefined, and the
|
|
15
|
+
// parser handles it the same as a left-out key.
|
|
16
|
+
const NODE_MSSQL_SCHEMA = Object.fromEntries(Object.entries({
|
|
14
17
|
...MSSQL_SCHEMA,
|
|
15
|
-
|
|
18
|
+
// read as a string, because `strict` is a valid value as well as a boolean
|
|
19
|
+
encrypt: { ...MSSQL_SCHEMA.encrypt, type: 'string' },
|
|
16
20
|
useutc: { type: 'boolean' },
|
|
17
21
|
stream: { type: 'boolean' },
|
|
18
22
|
parsejson: { type: 'boolean' },
|
|
19
23
|
'request timeout': { type: 'number' }
|
|
20
|
-
}
|
|
24
|
+
}).map(([key, { default: _default, ...item }]) => [key, item]))
|
|
21
25
|
|
|
22
26
|
/**
|
|
23
27
|
* Class ConnectionPool.
|
|
@@ -142,14 +146,31 @@ class ConnectionPool extends EventEmitter {
|
|
|
142
146
|
}
|
|
143
147
|
}
|
|
144
148
|
return Object.entries(parsed).reduce((config, [key, value]) => {
|
|
149
|
+
// an empty boolean or number value is not set
|
|
150
|
+
if (value === undefined) {
|
|
151
|
+
return config
|
|
152
|
+
}
|
|
153
|
+
// a number value that parseInt cannot read is a mistake, so a key that is used throws for it
|
|
154
|
+
const number = () => {
|
|
155
|
+
if (Number.isNaN(value)) {
|
|
156
|
+
const prop = [key, ...(NODE_MSSQL_SCHEMA[key].aliases ?? [])].find(k => result.has(k))
|
|
157
|
+
throw new Error(`Invalid value for connection string key "${prop}": "${result.get(prop)}" is not a number.`)
|
|
158
|
+
}
|
|
159
|
+
return value
|
|
160
|
+
}
|
|
145
161
|
switch (key) {
|
|
146
162
|
case 'application name':
|
|
147
163
|
break
|
|
148
|
-
case 'applicationintent':
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
164
|
+
case 'applicationintent': {
|
|
165
|
+
// the value is not case-sensitive; an empty value is not set
|
|
166
|
+
const intent = value.trim().toLowerCase()
|
|
167
|
+
if (intent) {
|
|
168
|
+
Object.assign(config.options, {
|
|
169
|
+
readOnlyIntent: intent === 'readonly'
|
|
170
|
+
})
|
|
171
|
+
}
|
|
152
172
|
break
|
|
173
|
+
}
|
|
153
174
|
case 'asynchronous processing':
|
|
154
175
|
break
|
|
155
176
|
case 'attachdbfilename':
|
|
@@ -163,7 +184,7 @@ class ConnectionPool extends EventEmitter {
|
|
|
163
184
|
break
|
|
164
185
|
case 'connection timeout':
|
|
165
186
|
Object.assign(config, {
|
|
166
|
-
connectionTimeout:
|
|
187
|
+
connectionTimeout: number() * 1000
|
|
167
188
|
})
|
|
168
189
|
break
|
|
169
190
|
case 'connection lifetime':
|
|
@@ -172,7 +193,7 @@ class ConnectionPool extends EventEmitter {
|
|
|
172
193
|
break
|
|
173
194
|
case 'connectretryinterval':
|
|
174
195
|
Object.assign(config.options, {
|
|
175
|
-
connectionRetryInterval:
|
|
196
|
+
connectionRetryInterval: number() * 1000
|
|
176
197
|
})
|
|
177
198
|
break
|
|
178
199
|
case 'context connection':
|
|
@@ -233,13 +254,20 @@ class ConnectionPool extends EventEmitter {
|
|
|
233
254
|
}
|
|
234
255
|
break
|
|
235
256
|
}
|
|
236
|
-
case 'encrypt':
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
})
|
|
257
|
+
case 'encrypt': {
|
|
258
|
+
// an empty value is not set
|
|
259
|
+
if (!value.trim()) {
|
|
260
|
+
break
|
|
241
261
|
}
|
|
262
|
+
const encrypt = value.toLowerCase()
|
|
263
|
+
Object.assign(config.options, {
|
|
264
|
+
// `strict` is TDS 8.0 strict encryption, and `optional` is a
|
|
265
|
+
// synonym of `false` (as in SqlClient 5 and ODBC Driver 18); other
|
|
266
|
+
// values have the boolean meaning of @tediousjs/connection-string
|
|
267
|
+
encrypt: encrypt === 'strict' ? 'strict' : !['false', 'no', '0', 'optional'].includes(encrypt)
|
|
268
|
+
})
|
|
242
269
|
break
|
|
270
|
+
}
|
|
243
271
|
case 'enlist':
|
|
244
272
|
break
|
|
245
273
|
case 'failover partner':
|
|
@@ -253,12 +281,12 @@ class ConnectionPool extends EventEmitter {
|
|
|
253
281
|
break
|
|
254
282
|
case 'max pool size':
|
|
255
283
|
Object.assign(config.pool, {
|
|
256
|
-
max:
|
|
284
|
+
max: number()
|
|
257
285
|
})
|
|
258
286
|
break
|
|
259
287
|
case 'min pool size':
|
|
260
288
|
Object.assign(config.pool, {
|
|
261
|
-
min:
|
|
289
|
+
min: number()
|
|
262
290
|
})
|
|
263
291
|
break
|
|
264
292
|
case 'msi endpoint':
|
|
@@ -282,7 +310,7 @@ class ConnectionPool extends EventEmitter {
|
|
|
282
310
|
break
|
|
283
311
|
case 'packet size':
|
|
284
312
|
Object.assign(config.options, {
|
|
285
|
-
packetSize:
|
|
313
|
+
packetSize: number()
|
|
286
314
|
})
|
|
287
315
|
break
|
|
288
316
|
case 'password':
|
|
@@ -351,7 +379,7 @@ class ConnectionPool extends EventEmitter {
|
|
|
351
379
|
break
|
|
352
380
|
case 'request timeout':
|
|
353
381
|
Object.assign(config, {
|
|
354
|
-
requestTimeout:
|
|
382
|
+
requestTimeout: number()
|
|
355
383
|
})
|
|
356
384
|
break
|
|
357
385
|
case 'stream':
|
|
@@ -505,6 +533,13 @@ class ConnectionPool extends EventEmitter {
|
|
|
505
533
|
return setImmediate(callback, null, this)
|
|
506
534
|
}
|
|
507
535
|
|
|
536
|
+
// we don't allow a pool that is still closing to connect: the close waits for borrowed connections to be
|
|
537
|
+
// released, and they would be released into the new pool instead, so the close would never finish
|
|
538
|
+
if (this.pool && this.pool.destroyed) {
|
|
539
|
+
debug('pool(%d): connect called while closing', IDS.get(this))
|
|
540
|
+
return setImmediate(callback, new ConnectionError('Cannot connect a pool while it is closing', 'ECLOSING'))
|
|
541
|
+
}
|
|
542
|
+
|
|
508
543
|
this._connectStack.push(callback)
|
|
509
544
|
|
|
510
545
|
if (this._connecting) {
|
|
@@ -560,20 +595,22 @@ class ConnectionPool extends EventEmitter {
|
|
|
560
595
|
})
|
|
561
596
|
}
|
|
562
597
|
|
|
598
|
+
// the pool has no connections before connect() and after close(), so each count is then 0
|
|
599
|
+
|
|
563
600
|
get size () {
|
|
564
|
-
return this.pool.numFree() + this.pool.numUsed() + this.pool.numPendingCreates()
|
|
601
|
+
return this.pool ? this.pool.numFree() + this.pool.numUsed() + this.pool.numPendingCreates() : 0
|
|
565
602
|
}
|
|
566
603
|
|
|
567
604
|
get available () {
|
|
568
|
-
return this.pool.numFree()
|
|
605
|
+
return this.pool ? this.pool.numFree() : 0
|
|
569
606
|
}
|
|
570
607
|
|
|
571
608
|
get pending () {
|
|
572
|
-
return this.pool.numPendingAcquires()
|
|
609
|
+
return this.pool ? this.pool.numPendingAcquires() : 0
|
|
573
610
|
}
|
|
574
611
|
|
|
575
612
|
get borrowed () {
|
|
576
|
-
return this.pool.numUsed()
|
|
613
|
+
return this.pool ? this.pool.numUsed() : 0
|
|
577
614
|
}
|
|
578
615
|
|
|
579
616
|
/**
|
|
@@ -607,7 +644,7 @@ class ConnectionPool extends EventEmitter {
|
|
|
607
644
|
// edge cases to deal with
|
|
608
645
|
if (this._connecting) {
|
|
609
646
|
debug('pool(%d): close called while connecting', IDS.get(this))
|
|
610
|
-
return setImmediate(callback, new ConnectionError('Cannot close a pool while it is connecting'))
|
|
647
|
+
return setImmediate(callback, new ConnectionError('Cannot close a pool while it is connecting', 'ECONNECTING'))
|
|
611
648
|
}
|
|
612
649
|
|
|
613
650
|
if (!this.pool) {
|
|
@@ -621,23 +658,26 @@ class ConnectionPool extends EventEmitter {
|
|
|
621
658
|
|
|
622
659
|
this._connecting = this._connected = this._healthy = false
|
|
623
660
|
|
|
624
|
-
|
|
661
|
+
// clear only the pool this close destroyed, not one that has replaced it since
|
|
662
|
+
const pool = this.pool
|
|
663
|
+
pool.destroy().then(() => {
|
|
625
664
|
debug('pool(%d): pool closed, removing pool reference and executing close callbacks', IDS.get(this))
|
|
665
|
+
// the pool is closed by the time its subscribers hear of it, so one of them can connect it again
|
|
666
|
+
if (this.pool === pool) this.pool = null
|
|
626
667
|
publish(CHANNELS.POOL_CLOSE, () => ({
|
|
627
668
|
poolId: IDS.get(this),
|
|
628
669
|
reason: 'closed'
|
|
629
670
|
}))
|
|
630
|
-
this.pool = null
|
|
631
671
|
this._closeStack.forEach(cb => {
|
|
632
672
|
setImmediate(cb, null)
|
|
633
673
|
})
|
|
634
674
|
}).catch(err => {
|
|
675
|
+
if (this.pool === pool) this.pool = null
|
|
635
676
|
publish(CHANNELS.POOL_CLOSE, () => ({
|
|
636
677
|
poolId: IDS.get(this),
|
|
637
678
|
reason: 'error',
|
|
638
679
|
error: err
|
|
639
680
|
}))
|
|
640
|
-
this.pool = null
|
|
641
681
|
this._closeStack.forEach(cb => {
|
|
642
682
|
setImmediate(cb, err)
|
|
643
683
|
})
|
|
@@ -6,6 +6,7 @@ const { IDS, objectHasProperty, getPoolId, isValidParameterName } = require('../
|
|
|
6
6
|
const globalConnection = require('../global-connection')
|
|
7
7
|
const { ConnectionError, TransactionError, PreparedStatementError } = require('../error')
|
|
8
8
|
const shared = require('../shared')
|
|
9
|
+
const Transaction = require('./transaction')
|
|
9
10
|
const { TYPES, declare } = require('../datatypes')
|
|
10
11
|
const { CHANNELS, tracePromise, traceCallback, publish } = require('../diagnostics')
|
|
11
12
|
|
|
@@ -42,11 +43,26 @@ class PreparedStatement extends EventEmitter {
|
|
|
42
43
|
}
|
|
43
44
|
|
|
44
45
|
get config () {
|
|
45
|
-
return this.parent.config
|
|
46
|
+
return this.parent ? this.parent.config : {}
|
|
46
47
|
}
|
|
47
48
|
|
|
48
49
|
get connected () {
|
|
49
|
-
return this.parent.connected
|
|
50
|
+
return this.parent ? this.parent.connected : false
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Whether the statement was prepared in a transaction that no longer lends its connection
|
|
55
|
+
* to the statement. This happens when the server rolls the transaction back (XACT_ABORT):
|
|
56
|
+
* the transaction then gives its connection back to the pool, and the pool can lend it to
|
|
57
|
+
* another caller, or to the same transaction when it begins again. While the statement is
|
|
58
|
+
* prepared, the transaction lends its connection to the statement and to nothing else.
|
|
59
|
+
*
|
|
60
|
+
* @private
|
|
61
|
+
* @return {boolean}
|
|
62
|
+
*/
|
|
63
|
+
|
|
64
|
+
_transactionLostConnection () {
|
|
65
|
+
return this.parent instanceof Transaction && (this.parent._acquiredConnection !== this._acquiredConnection || this.parent._activeRequest !== this)
|
|
50
66
|
}
|
|
51
67
|
|
|
52
68
|
/**
|
|
@@ -63,6 +79,12 @@ class PreparedStatement extends EventEmitter {
|
|
|
63
79
|
return this
|
|
64
80
|
}
|
|
65
81
|
|
|
82
|
+
// the connection may now belong to another caller, so nothing more is run on it
|
|
83
|
+
if (this._transactionLostConnection()) {
|
|
84
|
+
setImmediate(callback, this.parent._createAbortError())
|
|
85
|
+
return this
|
|
86
|
+
}
|
|
87
|
+
|
|
66
88
|
if (this._activeRequest) {
|
|
67
89
|
setImmediate(callback, new TransactionError("Can't acquire connection for the request. There is another request in progress.", 'EREQINPROG'))
|
|
68
90
|
return this
|
|
@@ -372,6 +394,13 @@ class PreparedStatement extends EventEmitter {
|
|
|
372
394
|
}
|
|
373
395
|
}
|
|
374
396
|
|
|
397
|
+
if (!this.parent) {
|
|
398
|
+
// with no pool, the request's own guard would report the statement as closed (ECONNCLOSED);
|
|
399
|
+
// fail it as prepare() does, but through the request, so that the error reaches the caller
|
|
400
|
+
// in every mode (promise, callback, stream) the way any other execute() error does
|
|
401
|
+
req._execute = (procedure, callback) => setImmediate(callback, new PreparedStatementError('No connection is specified for that prepared statement.', 'ENOCONN'))
|
|
402
|
+
}
|
|
403
|
+
|
|
375
404
|
req.execute('sp_execute', typeof callback === 'function'
|
|
376
405
|
? callback
|
|
377
406
|
: () => {}
|
|
@@ -429,19 +458,50 @@ class PreparedStatement extends EventEmitter {
|
|
|
429
458
|
return setImmediate(callback, new TransactionError("Can't unprepare the statement. There is a request in progress.", 'EREQINPROG'))
|
|
430
459
|
}
|
|
431
460
|
|
|
461
|
+
// the transaction has already given the connection back to the pool, and another caller
|
|
462
|
+
// may now use it, so sp_unprepare is not sent. The handle stays allocated on that session
|
|
463
|
+
// until the connection closes, and the server gives its number to no other statement
|
|
464
|
+
// until then
|
|
465
|
+
if (this._transactionLostConnection()) {
|
|
466
|
+
this._acquiredConnection = null
|
|
467
|
+
this._acquiredConfig = null
|
|
468
|
+
this._handle = 0
|
|
469
|
+
this.prepared = false
|
|
470
|
+
|
|
471
|
+
debug('ps(%d): unprepared without the connection, as the transaction has lost it', IDS.get(this))
|
|
472
|
+
|
|
473
|
+
return setImmediate(callback, null)
|
|
474
|
+
}
|
|
475
|
+
|
|
432
476
|
const req = new shared.driver.Request(this, this.overrides)
|
|
433
477
|
req._internal = true
|
|
434
478
|
req.stream = false
|
|
435
479
|
req.input('handle', TYPES.Int, this._handle)
|
|
480
|
+
req._allowDuringClose = true
|
|
436
481
|
req.execute('sp_unprepare', err => {
|
|
437
|
-
|
|
482
|
+
const connection = this._acquiredConnection
|
|
483
|
+
|
|
484
|
+
// this request never reached the connection: another request on the statement held it, or
|
|
485
|
+
// another call has already given it back. Nothing is changed
|
|
486
|
+
if (err && (err.code === 'EREQINPROG' || !connection)) return callback(err)
|
|
438
487
|
|
|
439
|
-
|
|
488
|
+
if (err) {
|
|
489
|
+
debug('ps(%d): failed to unprepare', IDS.get(this), err)
|
|
490
|
+
|
|
491
|
+
// the connection may have died, or the statement may still be prepared on it, so the
|
|
492
|
+
// pool is left to close it rather than lend it out again. It is given back all the
|
|
493
|
+
// same, as nothing else can give it back, and closing the pool waits until it is
|
|
494
|
+
connection.hasError = true
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
this.parent.release(connection)
|
|
440
498
|
this._acquiredConnection = null
|
|
441
499
|
this._acquiredConfig = null
|
|
442
500
|
this._handle = 0
|
|
443
501
|
this.prepared = false
|
|
444
502
|
|
|
503
|
+
if (err) return callback(err)
|
|
504
|
+
|
|
445
505
|
debug('ps(%d): unprepared', IDS.get(this))
|
|
446
506
|
|
|
447
507
|
return callback(null)
|
package/lib/base/request.js
CHANGED
|
@@ -51,6 +51,8 @@ class Request extends EventEmitter {
|
|
|
51
51
|
this.canceled = false
|
|
52
52
|
this._paused = false
|
|
53
53
|
this._internal = false
|
|
54
|
+
// Cleanup must still return borrowed connections while pool.close() waits for them.
|
|
55
|
+
this._allowDuringClose = false
|
|
54
56
|
this.parent = parent || globalConnection.pool
|
|
55
57
|
this.parameters = {}
|
|
56
58
|
this.stream = null
|
|
@@ -597,7 +599,7 @@ class Request extends EventEmitter {
|
|
|
597
599
|
return setImmediate(callback, new RequestError('No connection is specified for that request.', 'ENOCONN'))
|
|
598
600
|
}
|
|
599
601
|
|
|
600
|
-
if (!this.parent.connected) {
|
|
602
|
+
if (!this.parent.connected && !this._allowDuringClose) {
|
|
601
603
|
return setImmediate(callback, new ConnectionError('Connection is closed.', 'ECONNCLOSED'))
|
|
602
604
|
}
|
|
603
605
|
|
|
@@ -695,7 +697,7 @@ class Request extends EventEmitter {
|
|
|
695
697
|
return setImmediate(callback, new RequestError('No connection is specified for that request.', 'ENOCONN'))
|
|
696
698
|
}
|
|
697
699
|
|
|
698
|
-
if (!this.parent.connected) {
|
|
700
|
+
if (!this.parent.connected && !this._allowDuringClose) {
|
|
699
701
|
return setImmediate(callback, new ConnectionError('Connection is closed.', 'ECONNCLOSED'))
|
|
700
702
|
}
|
|
701
703
|
|
package/lib/base/transaction.js
CHANGED
package/lib/global-connection.js
CHANGED
|
@@ -26,6 +26,11 @@ function connect (config, callback) {
|
|
|
26
26
|
const ogClose = globalConnection.close
|
|
27
27
|
|
|
28
28
|
const globalClose = function (callback) {
|
|
29
|
+
// a pool refuses to close while it is connecting, so it stays the global pool with its handlers
|
|
30
|
+
if (this.connecting) {
|
|
31
|
+
return ogClose.call(this, callback)
|
|
32
|
+
}
|
|
33
|
+
|
|
29
34
|
// remove event handlers from the global connection
|
|
30
35
|
for (const event in globalConnectionHandlers) {
|
|
31
36
|
for (let i = 0, l = globalConnectionHandlers[event].length; i < l; i++) {
|
|
@@ -42,22 +47,27 @@ function connect (config, callback) {
|
|
|
42
47
|
}
|
|
43
48
|
})
|
|
44
49
|
|
|
45
|
-
|
|
50
|
+
// this close stays on the pool after another pool has become global, so leave that one alone
|
|
51
|
+
if (globalConnection === this) globalConnection = null
|
|
46
52
|
return ogClose.call(this, callback)
|
|
47
53
|
}
|
|
48
54
|
|
|
49
55
|
globalConnection.close = globalClose.bind(globalConnection)
|
|
50
56
|
}
|
|
57
|
+
// a failed connect is reported in a later setImmediate. By then sql.close() may have cleared the pool and
|
|
58
|
+
// sql.connect() made another one global, or sql.connect() may be connecting this pool again.
|
|
59
|
+
const pool = globalConnection
|
|
60
|
+
const forgetFailedPool = () => {
|
|
61
|
+
if (globalConnection === pool && !pool.connecting && !pool.connected) globalConnection = null
|
|
62
|
+
}
|
|
51
63
|
if (typeof callback === 'function') {
|
|
52
|
-
return
|
|
53
|
-
if (err)
|
|
54
|
-
globalConnection = null
|
|
55
|
-
}
|
|
64
|
+
return pool.connect((err, connection) => {
|
|
65
|
+
if (err) forgetFailedPool()
|
|
56
66
|
callback(err, connection)
|
|
57
67
|
})
|
|
58
68
|
}
|
|
59
|
-
return
|
|
60
|
-
|
|
69
|
+
return pool.connect().catch((err) => {
|
|
70
|
+
forgetFailedPool()
|
|
61
71
|
return shared.Promise.reject(err)
|
|
62
72
|
})
|
|
63
73
|
}
|
|
@@ -72,7 +82,8 @@ function connect (config, callback) {
|
|
|
72
82
|
function close (callback) {
|
|
73
83
|
if (globalConnection) {
|
|
74
84
|
const gc = globalConnection
|
|
75
|
-
|
|
85
|
+
// a pool refuses to close while it is connecting, so it stays the global pool
|
|
86
|
+
if (!gc.connecting) globalConnection = null
|
|
76
87
|
return gc.close(callback)
|
|
77
88
|
}
|
|
78
89
|
|
|
@@ -115,7 +126,8 @@ function removeListener (event, handler) {
|
|
|
115
126
|
const index = globalConnectionHandlers[event].indexOf(handler)
|
|
116
127
|
if (index === -1) return globalConnection
|
|
117
128
|
globalConnectionHandlers[event].splice(index, 1)
|
|
118
|
-
|
|
129
|
+
// sql.connect() and sql.close() go through every event in here, so an event with no handlers left must go
|
|
130
|
+
if (globalConnectionHandlers[event].length === 0) delete globalConnectionHandlers[event]
|
|
119
131
|
|
|
120
132
|
if (globalConnection) globalConnection.removeListener(event, handler)
|
|
121
133
|
return globalConnection
|
|
@@ -30,7 +30,8 @@ class ConnectionPool extends BaseConnectionPool {
|
|
|
30
30
|
Uid: this.config.user,
|
|
31
31
|
Pwd: this.config.password,
|
|
32
32
|
Trusted_Connection: !!this.config.options.trustedConnection,
|
|
33
|
-
|
|
33
|
+
// ODBC Driver 18 and later accept Strict (TDS 8.0); older drivers do not
|
|
34
|
+
Encrypt: this.config.options.encrypt === 'strict' ? 'Strict' : !!this.config.options.encrypt
|
|
34
35
|
})
|
|
35
36
|
}
|
|
36
37
|
|
|
@@ -54,6 +55,13 @@ class ConnectionPool extends BaseConnectionPool {
|
|
|
54
55
|
return reject(err)
|
|
55
56
|
}
|
|
56
57
|
|
|
58
|
+
// numbers come over as strings, so that bigint values stay exact as they do on tedious;
|
|
59
|
+
// msnodesqlv8 added the option in 2.4.8
|
|
60
|
+
if (typeof tds.setUseNumericString !== 'function') {
|
|
61
|
+
debug('connection(%d): msnodesqlv8 is older than 2.4.8, closing', connedtionId)
|
|
62
|
+
tds.close(() => {})
|
|
63
|
+
return reject(new ConnectionError('msnodesqlv8 2.4.8 or later is required.', 'EDRIVER'))
|
|
64
|
+
}
|
|
57
65
|
tds.setUseNumericString(true)
|
|
58
66
|
|
|
59
67
|
IDS.add(tds, 'Connection', connedtionId)
|
|
@@ -10,6 +10,25 @@ const { PARSERS: UDT } = require('../udt')
|
|
|
10
10
|
const Table = require('../table')
|
|
11
11
|
const { valueHandler } = require('../shared')
|
|
12
12
|
|
|
13
|
+
// the major version of msnodesqlv8, or 0 if it cannot be read
|
|
14
|
+
const driverMajorVersion = () => {
|
|
15
|
+
try {
|
|
16
|
+
return Number(require('msnodesqlv8/package.json').version.split('.')[0])
|
|
17
|
+
} catch (err) {
|
|
18
|
+
return 0
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// msnodesqlv8 6 emits nothing for a paused query until it is resumed, 'meta' and 'done' included,
|
|
23
|
+
// and ends a paused query it cancels once nothing is under way, without freeing its statement
|
|
24
|
+
// first. What the request does for earlier versions while a query is held back would wait for
|
|
25
|
+
// those events forever
|
|
26
|
+
const driverHoldsPausedQueries = () => driverMajorVersion() >= 6
|
|
27
|
+
|
|
28
|
+
// msnodesqlv8 6 takes one cancel per query. It refuses any other in its callback, while the one
|
|
29
|
+
// it took goes on to end the query
|
|
30
|
+
const driverTakesOneCancel = () => driverMajorVersion() >= 6
|
|
31
|
+
|
|
13
32
|
const JSON_COLUMN_ID = 'JSON_F52E2B61-18A1-11d1-B105-00805F49916B'
|
|
14
33
|
const XML_COLUMN_ID = 'XML_F52E2B61-18A1-11d1-B105-00805F49916B'
|
|
15
34
|
const EMPTY_BUFFER = Buffer.alloc(0)
|
|
@@ -403,6 +422,8 @@ class Request extends BaseRequest {
|
|
|
403
422
|
let driverPaused = false
|
|
404
423
|
// a cancel of a paused stream waits for the driver to reach a point where it can be paused
|
|
405
424
|
let cancelDeferred = false
|
|
425
|
+
// the cancel waits for a query held back before its first result set
|
|
426
|
+
let cancelBeforeResults = false
|
|
406
427
|
// msnodesqlv8 has freed the statement, which it does without 'done' after an error ends the query
|
|
407
428
|
let freed = false
|
|
408
429
|
let resuming = false
|
|
@@ -594,12 +615,14 @@ class Request extends BaseRequest {
|
|
|
594
615
|
let detached = false
|
|
595
616
|
let settingAside = false
|
|
596
617
|
let cancelHeld = false
|
|
618
|
+
let driverCancelled = false
|
|
597
619
|
const detach = () => {
|
|
598
620
|
detached = true
|
|
599
621
|
}
|
|
600
622
|
const reachable = () => !detached && !settingAside && !stopped(req)
|
|
601
623
|
|
|
602
624
|
const cancelDriver = (attempt = cancelAttempts) => {
|
|
625
|
+
driverCancelled = true
|
|
603
626
|
req.cancelQuery(err => {
|
|
604
627
|
if (err) {
|
|
605
628
|
debug('request(%d): failed to cancel', IDS.get(this), err)
|
|
@@ -626,43 +649,54 @@ class Request extends BaseRequest {
|
|
|
626
649
|
const pauseAndCancelDriver = () => {
|
|
627
650
|
cancelDeferred = false
|
|
628
651
|
// msnodesqlv8 5.0 to 5.5 send a query one cancel, which a cancel made before the query
|
|
629
|
-
// started has used up and they refused, so the query runs on
|
|
652
|
+
// started has used up and they refused, so the query runs on. A query held back before its
|
|
653
|
+
// first result set was paused when that cancel went out, as it is when msnodesqlv8 cancels
|
|
654
|
+
// it itself on a timeout, so there the cancel went through and the query is ending
|
|
630
655
|
if (typeof req.getCancelSent === 'function' && req.getCancelSent()) {
|
|
656
|
+
if (cancelBeforeResults) return true
|
|
631
657
|
cancelRequested = false
|
|
632
658
|
return false
|
|
633
659
|
}
|
|
634
|
-
driverPaused
|
|
635
|
-
|
|
660
|
+
if (!driverPaused) {
|
|
661
|
+
driverPaused = true
|
|
662
|
+
req.pauseQuery()
|
|
663
|
+
}
|
|
636
664
|
cancelDriver()
|
|
637
665
|
return true
|
|
638
666
|
}
|
|
639
667
|
|
|
640
|
-
// msnodesqlv8 6 ends a cancelled query only if it was paused when the cancel went out, or is
|
|
641
|
-
// never paused after it: one paused after its cancel is held for good, and holds its
|
|
642
|
-
// connection. So once a cancel has gone out, and until it is refused, the query is not paused
|
|
643
|
-
const cancelSent = () => cancelRequested && typeof req.getCancelSent === 'function' && req.getCancelSent()
|
|
644
|
-
|
|
645
668
|
// called with each row once it is complete
|
|
646
669
|
const pauseDriverAtEndOfBatch = () => {
|
|
647
670
|
if (driverPaused || rowsInRecordset % DRIVER_ROW_BATCH_SIZE !== 0) return
|
|
648
671
|
if (cancelDeferred && pauseAndCancelDriver()) return
|
|
649
|
-
if (this.stream && this.paused
|
|
672
|
+
if (this.stream && this.paused) {
|
|
650
673
|
driverPaused = true
|
|
651
674
|
req.pauseQuery()
|
|
652
675
|
}
|
|
653
676
|
}
|
|
654
677
|
|
|
655
678
|
// until the first result set the driver has read nothing, so a stream paused before then,
|
|
656
|
-
// or before its query starts, holds it back at once
|
|
679
|
+
// or before its query starts, holds it back at once. But msnodesqlv8 < 6's resume() fetches
|
|
680
|
+
// at once, whatever the query is doing, and once the query has started ('submitted') it may
|
|
681
|
+
// still be executing, or moving on through statements with no result, when the fetch fails
|
|
682
|
+
// with a 'Function sequence error' or the result set is fetched twice. So a query held back
|
|
683
|
+
// then is resumed only once it has stopped at a result set, a tick after its 'meta', and not
|
|
684
|
+
// at all if it ends first. Until msnodesqlv8 starts it, a resume only stops it starting paused.
|
|
685
|
+
// msnodesqlv8 6 resumes only what it has held back, so there it is resumed at once
|
|
686
|
+
let heldBeforeResults = false
|
|
687
|
+
let submitted = false
|
|
688
|
+
let atResultSet = false
|
|
689
|
+
req.once('submitted', () => { submitted = true })
|
|
657
690
|
this._pauseStream = () => {
|
|
658
|
-
if (!columns && !driverPaused && !finished &&
|
|
691
|
+
if (!columns && !driverPaused && !finished && reachable()) {
|
|
659
692
|
driverPaused = true
|
|
693
|
+
heldBeforeResults = true
|
|
660
694
|
req.pauseQuery()
|
|
661
695
|
}
|
|
662
696
|
}
|
|
663
697
|
if (this.stream && this.paused) this._pauseStream()
|
|
664
698
|
|
|
665
|
-
|
|
699
|
+
const resumeStream = () => {
|
|
666
700
|
// a listener that resumes the stream while it is emitting what was waiting leaves the
|
|
667
701
|
// rest to this loop, so that every listener gets the events in order
|
|
668
702
|
if (resuming) return
|
|
@@ -678,11 +712,13 @@ class Request extends BaseRequest {
|
|
|
678
712
|
// stream completes as cancelled straight away, as it does when it is paused first
|
|
679
713
|
if (finished && cancelRequested && this.paused && pending.length) emitPendingOnCancel()
|
|
680
714
|
// a query that is being cancelled stays paused, so that the cancel can go through
|
|
681
|
-
if (!pending.length && !this.paused && driverPaused && !finished && !cancelRequested && reachable()
|
|
715
|
+
if (!pending.length && !this.paused && driverPaused && !finished && !cancelRequested && reachable() &&
|
|
716
|
+
(!heldBeforeResults || !submitted || atResultSet || driverHoldsPausedQueries())) {
|
|
682
717
|
driverPaused = false
|
|
683
718
|
req.resumeQuery()
|
|
684
719
|
}
|
|
685
720
|
}
|
|
721
|
+
this._resumeStream = resumeStream
|
|
686
722
|
|
|
687
723
|
const cancel = () => {
|
|
688
724
|
debug('request(%d): cancel', IDS.get(this))
|
|
@@ -694,13 +730,26 @@ class Request extends BaseRequest {
|
|
|
694
730
|
cancelHeld = true
|
|
695
731
|
return
|
|
696
732
|
}
|
|
697
|
-
//
|
|
698
|
-
// outcome of the first one stands
|
|
699
|
-
if (cancelDeferred || (typeof req.getCancelSent === 'function' && req.getCancelSent())
|
|
733
|
+
// msnodesqlv8 5.0 to 5.5 drop a repeat cancel without calling back, and 6 refuses it, so
|
|
734
|
+
// the outcome of the first one stands
|
|
735
|
+
if (cancelDeferred || (typeof req.getCancelSent === 'function' && req.getCancelSent()) ||
|
|
736
|
+
(driverCancelled && driverTakesOneCancel())) {
|
|
700
737
|
return
|
|
701
738
|
}
|
|
702
739
|
cancelRequested = true
|
|
703
740
|
cancelAttempts++
|
|
741
|
+
// A query held back before its first result set still runs the statements ahead of it,
|
|
742
|
+
// which have none. msnodesqlv8 < 6 cancels a paused query by freeing its statement (5.6 not
|
|
743
|
+
// while the first statement is still executing), and a free that lands while msnodesqlv8
|
|
744
|
+
// reads on to the next result can crash the process. Nothing tells the request when the
|
|
745
|
+
// query moves on, so a held query is cancelled once it stops at its first result set, and
|
|
746
|
+
// one that ends first is reported as cancelled. The statements ahead run to their end, or
|
|
747
|
+
// to the request timeout. msnodesqlv8 6 cancels it at once.
|
|
748
|
+
if (driverPaused && !columns && !driverHoldsPausedQueries()) {
|
|
749
|
+
cancelDeferred = true
|
|
750
|
+
cancelBeforeResults = true
|
|
751
|
+
return
|
|
752
|
+
}
|
|
704
753
|
if (!this.stream || !this.paused || driverPaused) {
|
|
705
754
|
return cancelDriver()
|
|
706
755
|
}
|
|
@@ -725,10 +774,15 @@ class Request extends BaseRequest {
|
|
|
725
774
|
cancelHeld = false
|
|
726
775
|
cancel()
|
|
727
776
|
}
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
777
|
+
}
|
|
778
|
+
// msnodesqlv8 calls dispatch() once 'meta' is handled, which returns while the query is
|
|
779
|
+
// paused, so a tick later a query held back before its first result set has stopped there.
|
|
780
|
+
// That includes one whose stream was resumed while an error had detached the request
|
|
781
|
+
if (heldBeforeResults && !atResultSet) {
|
|
782
|
+
setImmediate(() => {
|
|
783
|
+
atResultSet = true
|
|
784
|
+
resumeStream()
|
|
785
|
+
})
|
|
732
786
|
}
|
|
733
787
|
|
|
734
788
|
if (row) {
|
|
@@ -76,6 +76,7 @@ class Transaction extends BaseTransaction {
|
|
|
76
76
|
|
|
77
77
|
const req = new Request(this)
|
|
78
78
|
req.stream = false
|
|
79
|
+
req._allowDuringClose = true
|
|
79
80
|
req.query('commit tran', err => {
|
|
80
81
|
if (err) err = new TransactionError(err)
|
|
81
82
|
|
|
@@ -98,6 +99,7 @@ class Transaction extends BaseTransaction {
|
|
|
98
99
|
|
|
99
100
|
const req = new Request(this)
|
|
100
101
|
req.stream = false
|
|
102
|
+
req._allowDuringClose = true
|
|
101
103
|
req.query('rollback tran', err => {
|
|
102
104
|
if (err) err = new TransactionError(err)
|
|
103
105
|
|
package/lib/tedious/request.js
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
const tds = require('tedious')
|
|
4
4
|
const debug = require('debug')('mssql:tedi')
|
|
5
5
|
const BaseRequest = require('../base/request')
|
|
6
|
+
const BaseTransaction = require('../base/transaction')
|
|
6
7
|
const RequestError = require('../error/request-error')
|
|
7
8
|
const { IDS, objectHasProperty, assertSafeColumnName, assertSafeTypeName, assertSafeTypeSize, assertSafeProcedureName } = require('../utils')
|
|
8
9
|
const { TYPES, DECLARATIONS, declare, cast } = require('../datatypes')
|
|
@@ -217,6 +218,23 @@ const parameterCorrection = function (value) {
|
|
|
217
218
|
}
|
|
218
219
|
|
|
219
220
|
class Request extends BaseRequest {
|
|
221
|
+
/*
|
|
222
|
+
Record the error that made the server roll back the transaction that the request ran in.
|
|
223
|
+
The request of a prepared statement has the statement as its parent, so the transaction
|
|
224
|
+
is the parent of the statement.
|
|
225
|
+
*/
|
|
226
|
+
|
|
227
|
+
_recordAbortReason (reason) {
|
|
228
|
+
let transaction = this.parent
|
|
229
|
+
while (transaction && !(transaction instanceof BaseTransaction)) {
|
|
230
|
+
transaction = transaction.parent
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
if (reason && transaction && transaction._aborted) {
|
|
234
|
+
transaction._abortReason = reason
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
|
|
220
238
|
/*
|
|
221
239
|
Execute specified sql batch.
|
|
222
240
|
*/
|
|
@@ -306,10 +324,7 @@ class Request extends BaseRequest {
|
|
|
306
324
|
} catch (e) {
|
|
307
325
|
// noop
|
|
308
326
|
}
|
|
309
|
-
|
|
310
|
-
const reason = err || errors[errors.length - 1]
|
|
311
|
-
if (reason) this.parent._abortReason = reason
|
|
312
|
-
}
|
|
327
|
+
this._recordAbortReason(err || errors[errors.length - 1])
|
|
313
328
|
callback(err, ...args)
|
|
314
329
|
}
|
|
315
330
|
if (err) return callbackWithRelease(err)
|
|
@@ -561,10 +576,7 @@ class Request extends BaseRequest {
|
|
|
561
576
|
}
|
|
562
577
|
|
|
563
578
|
this.parent.release(connection)
|
|
564
|
-
|
|
565
|
-
const reason = error || errors[errors.length - 1]
|
|
566
|
-
if (reason) this.parent._abortReason = reason
|
|
567
|
-
}
|
|
579
|
+
this._recordAbortReason(error || errors[errors.length - 1])
|
|
568
580
|
hasReturned = true
|
|
569
581
|
|
|
570
582
|
if (error) {
|
|
@@ -958,10 +970,7 @@ class Request extends BaseRequest {
|
|
|
958
970
|
}
|
|
959
971
|
|
|
960
972
|
this.parent.release(connection)
|
|
961
|
-
|
|
962
|
-
const reason = error || errors[errors.length - 1]
|
|
963
|
-
if (reason) this.parent._abortReason = reason
|
|
964
|
-
}
|
|
973
|
+
this._recordAbortReason(error || errors[errors.length - 1])
|
|
965
974
|
hasReturned = true
|
|
966
975
|
|
|
967
976
|
if (error) {
|
|
@@ -22,6 +22,9 @@ class Transaction extends BaseTransaction {
|
|
|
22
22
|
this._acquiredConnection.removeListener('rollbackTransaction', this._abort)
|
|
23
23
|
this._acquiredConnection = null
|
|
24
24
|
this._acquiredConfig = null
|
|
25
|
+
// the request or prepared statement that holds the connection can no longer give it
|
|
26
|
+
// back to the transaction, so the transaction stops waiting for it
|
|
27
|
+
this._activeRequest = null
|
|
25
28
|
this._aborted = true
|
|
26
29
|
this._abortReason = this._abortReason || new Error('Transaction was rolled back by the server')
|
|
27
30
|
|