mssql 12.7.16 → 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 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,7 +808,9 @@ 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
 
804
- While a `close()` is in progress, `connect()` rejects with `ECLOSING`. Wait for `close()` to finish before you connect the pool again, or create a new `ConnectionPool`.
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.
805
814
 
806
815
  __Arguments__
807
816
 
@@ -825,8 +834,7 @@ pool.connect(err => {
825
834
  __Errors__
826
835
  - ELOGIN (`ConnectionError`) - Login failed.
827
836
  - ETIMEOUT (`ConnectionError`) - Connection timeout.
828
- - EALREADYCONNECTED (`ConnectionError`) - Database is already connected!
829
- - EALREADYCONNECTING (`ConnectionError`) - Already connecting to database!
837
+ - EDRIVER (`ConnectionError`) - Driver version not supported (msnodesqlv8 older than 2.4.8).
830
838
  - EINSTLOOKUP (`ConnectionError`) - Instance lookup failed.
831
839
  - ESOCKET (`ConnectionError`) - Socket error.
832
840
  - ECLOSING (`ConnectionError`) - Cannot connect a pool while it is closing.
@@ -837,11 +845,13 @@ __Errors__
837
845
 
838
846
  Close all active connections in the pool.
839
847
 
840
- `close()` waits for running requests, open transactions and prepared statements to release their connections back to the pool. This wait has no timeout.
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`.
841
849
 
842
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()`.
843
851
 
844
- 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.
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`.
845
855
 
846
856
  __Example__
847
857
 
@@ -856,7 +866,7 @@ __Errors__
856
866
 
857
867
  ### Pool properties
858
868
 
859
- 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`:
860
870
 
861
871
  - **pool.healthy** - `Boolean` - Whether the pool is able to create new connections.
862
872
  - **pool.size** - `Number` - Total number of connections in the pool (free + used + pending creation).
@@ -1297,7 +1307,11 @@ request.cancel()
1297
1307
 
1298
1308
  A cancelled stream emits an `error` event with code `ECANCEL`, followed by `done`.
1299
1309
 
1300
- 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; a query that ends first, or times out, completes as cancelled.
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.
1301
1315
 
1302
1316
  ## Transaction
1303
1317
 
@@ -1654,11 +1668,17 @@ __Errors__
1654
1668
 
1655
1669
  ### unprepare ([callback])
1656
1670
 
1657
- Unprepare a prepared statement. If the server has rolled back the transaction that the statement was prepared in, `unprepare` releases the statement without sending anything to the server.
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:
1658
1676
 
1659
- If the request to unprepare the statement fails (for example, because the connection has died), the statement still gives its connection back and is no longer prepared, and the error is passed on. 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, or until the transaction is aborted because the server has rolled it back.
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`.
1660
1680
 
1661
- If `unprepare` rejects with `EREQINPROG` because another request on the statement is in progress, nothing changes: the statement stays prepared and keeps its connection, so call `unprepare` again when that request has finished.
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`.
1662
1682
 
1663
1683
  __Arguments__
1664
1684
 
@@ -2241,9 +2261,7 @@ Name | Code | Message
2241
2261
  :--- | :--- | :---
2242
2262
  `ConnectionError` | ELOGIN | Login failed.
2243
2263
  `ConnectionError` | ETIMEOUT | Connection timeout.
2244
- `ConnectionError` | EDRIVER | Unknown driver.
2245
- `ConnectionError` | EALREADYCONNECTED | Database is already connected!
2246
- `ConnectionError` | EALREADYCONNECTING | Already connecting to database!
2264
+ `ConnectionError` | EDRIVER | Unknown driver, or a driver version that is not supported.
2247
2265
  `ConnectionError` | ENOTOPEN | Connection not yet open.
2248
2266
  `ConnectionError` | EINSTLOOKUP | Instance lookup failed.
2249
2267
  `ConnectionError` | ESOCKET | Socket error.
@@ -2490,7 +2508,7 @@ dc.subscribe(CHANNELS.CONNECTION_RELEASE, ({ connectionId, poolId }) => {
2490
2508
  | `TRANSACTION_COMMIT` | `mssql:transaction:commit` | Transaction committed |
2491
2509
  | `TRANSACTION_ROLLBACK` | `mssql:transaction:rollback` | Transaction rolled back (includes `aborted` flag) |
2492
2510
  | `REQUEST_CANCEL` | `mssql:request:cancel` | Request cancelled |
2493
- | `PREPARED_STATEMENT_UNPREPARE` | `mssql:prepared-statement:unprepare` | Prepared statement released |
2511
+ | `PREPARED_STATEMENT_UNPREPARE` | `mssql:prepared-statement:unprepare` | Prepared statement unprepared (only when `unprepare()` succeeds) |
2494
2512
 
2495
2513
  ### Example: OpenTelemetry Spans
2496
2514
 
@@ -15,6 +15,8 @@ const { CHANNELS, tracePromise, traceCallback, publish } = require('../diagnosti
15
15
  // parser handles it the same as a left-out key.
16
16
  const NODE_MSSQL_SCHEMA = Object.fromEntries(Object.entries({
17
17
  ...MSSQL_SCHEMA,
18
+ // read as a string, because `strict` is a valid value as well as a boolean
19
+ encrypt: { ...MSSQL_SCHEMA.encrypt, type: 'string' },
18
20
  useutc: { type: 'boolean' },
19
21
  stream: { type: 'boolean' },
20
22
  parsejson: { type: 'boolean' },
@@ -148,14 +150,27 @@ class ConnectionPool extends EventEmitter {
148
150
  if (value === undefined) {
149
151
  return config
150
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
+ }
151
161
  switch (key) {
152
162
  case 'application name':
153
163
  break
154
- case 'applicationintent':
155
- Object.assign(config.options, {
156
- readOnlyIntent: value === 'readonly'
157
- })
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
+ }
158
172
  break
173
+ }
159
174
  case 'asynchronous processing':
160
175
  break
161
176
  case 'attachdbfilename':
@@ -169,7 +184,7 @@ class ConnectionPool extends EventEmitter {
169
184
  break
170
185
  case 'connection timeout':
171
186
  Object.assign(config, {
172
- connectionTimeout: value * 1000
187
+ connectionTimeout: number() * 1000
173
188
  })
174
189
  break
175
190
  case 'connection lifetime':
@@ -178,7 +193,7 @@ class ConnectionPool extends EventEmitter {
178
193
  break
179
194
  case 'connectretryinterval':
180
195
  Object.assign(config.options, {
181
- connectionRetryInterval: value * 1000
196
+ connectionRetryInterval: number() * 1000
182
197
  })
183
198
  break
184
199
  case 'context connection':
@@ -239,11 +254,20 @@ class ConnectionPool extends EventEmitter {
239
254
  }
240
255
  break
241
256
  }
242
- case 'encrypt':
257
+ case 'encrypt': {
258
+ // an empty value is not set
259
+ if (!value.trim()) {
260
+ break
261
+ }
262
+ const encrypt = value.toLowerCase()
243
263
  Object.assign(config.options, {
244
- encrypt: !!value
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)
245
268
  })
246
269
  break
270
+ }
247
271
  case 'enlist':
248
272
  break
249
273
  case 'failover partner':
@@ -257,12 +281,12 @@ class ConnectionPool extends EventEmitter {
257
281
  break
258
282
  case 'max pool size':
259
283
  Object.assign(config.pool, {
260
- max: value
284
+ max: number()
261
285
  })
262
286
  break
263
287
  case 'min pool size':
264
288
  Object.assign(config.pool, {
265
- min: value
289
+ min: number()
266
290
  })
267
291
  break
268
292
  case 'msi endpoint':
@@ -286,7 +310,7 @@ class ConnectionPool extends EventEmitter {
286
310
  break
287
311
  case 'packet size':
288
312
  Object.assign(config.options, {
289
- packetSize: value
313
+ packetSize: number()
290
314
  })
291
315
  break
292
316
  case 'password':
@@ -355,7 +379,7 @@ class ConnectionPool extends EventEmitter {
355
379
  break
356
380
  case 'request timeout':
357
381
  Object.assign(config, {
358
- requestTimeout: parseInt(value, 10)
382
+ requestTimeout: number()
359
383
  })
360
384
  break
361
385
  case 'stream':
@@ -571,20 +595,22 @@ class ConnectionPool extends EventEmitter {
571
595
  })
572
596
  }
573
597
 
598
+ // the pool has no connections before connect() and after close(), so each count is then 0
599
+
574
600
  get size () {
575
- return this.pool.numFree() + this.pool.numUsed() + this.pool.numPendingCreates()
601
+ return this.pool ? this.pool.numFree() + this.pool.numUsed() + this.pool.numPendingCreates() : 0
576
602
  }
577
603
 
578
604
  get available () {
579
- return this.pool.numFree()
605
+ return this.pool ? this.pool.numFree() : 0
580
606
  }
581
607
 
582
608
  get pending () {
583
- return this.pool.numPendingAcquires()
609
+ return this.pool ? this.pool.numPendingAcquires() : 0
584
610
  }
585
611
 
586
612
  get borrowed () {
587
- return this.pool.numUsed()
613
+ return this.pool ? this.pool.numUsed() : 0
588
614
  }
589
615
 
590
616
  /**
@@ -636,21 +662,22 @@ class ConnectionPool extends EventEmitter {
636
662
  const pool = this.pool
637
663
  pool.destroy().then(() => {
638
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
639
667
  publish(CHANNELS.POOL_CLOSE, () => ({
640
668
  poolId: IDS.get(this),
641
669
  reason: 'closed'
642
670
  }))
643
- if (this.pool === pool) this.pool = null
644
671
  this._closeStack.forEach(cb => {
645
672
  setImmediate(cb, null)
646
673
  })
647
674
  }).catch(err => {
675
+ if (this.pool === pool) this.pool = null
648
676
  publish(CHANNELS.POOL_CLOSE, () => ({
649
677
  poolId: IDS.get(this),
650
678
  reason: 'error',
651
679
  error: err
652
680
  }))
653
- if (this.pool === pool) this.pool = null
654
681
  this._closeStack.forEach(cb => {
655
682
  setImmediate(cb, err)
656
683
  })
@@ -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
- Encrypt: !!this.config.options.encrypt
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 = true
635
- req.pauseQuery()
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 && !cancelSent()) {
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 && !cancelSent() && reachable()) {
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
- this._resumeStream = () => {
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
- // newer msnodesqlv8 versions drop a repeat cancel without calling back, so the
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
- // a stream resumed meanwhile left the query held back. msnodesqlv8 fetches as soon as
729
- // it is resumed, and again once 'meta' is handled, so the query is resumed a tick
730
- // later, once it has stopped at the result set
731
- if (!this.paused && driverPaused && !cancelRequested) setImmediate(this._resumeStream)
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) {
package/package.json CHANGED
@@ -21,7 +21,7 @@
21
21
  "azure",
22
22
  "node-mssql"
23
23
  ],
24
- "version": "12.7.16",
24
+ "version": "12.8.0",
25
25
  "main": "index.js",
26
26
  "type": "commonjs",
27
27
  "repository": {