knex 0.21.20 → 0.21.21

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.
Files changed (141) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/CONTRIBUTING.md +184 -184
  3. package/LICENSE +22 -22
  4. package/README.md +95 -95
  5. package/bin/cli.js +414 -414
  6. package/bin/utils/cli-config-utils.js +151 -151
  7. package/bin/utils/constants.js +7 -7
  8. package/bin/utils/migrationsLister.js +37 -37
  9. package/knex.js +8 -8
  10. package/lib/client.js +413 -413
  11. package/lib/config-resolver.js +61 -61
  12. package/lib/constants.js +44 -44
  13. package/lib/dialects/mssql/index.js +390 -390
  14. package/lib/dialects/mssql/query/compiler.js +444 -444
  15. package/lib/dialects/mssql/schema/columncompiler.js +103 -103
  16. package/lib/dialects/mssql/schema/compiler.js +59 -59
  17. package/lib/dialects/mssql/schema/tablecompiler.js +245 -245
  18. package/lib/dialects/mssql/transaction.js +97 -97
  19. package/lib/dialects/mysql/index.js +191 -191
  20. package/lib/dialects/mysql/query/compiler.js +142 -142
  21. package/lib/dialects/mysql/schema/columncompiler.js +171 -171
  22. package/lib/dialects/mysql/schema/compiler.js +60 -60
  23. package/lib/dialects/mysql/schema/tablecompiler.js +262 -262
  24. package/lib/dialects/mysql/transaction.js +48 -48
  25. package/lib/dialects/mysql2/index.js +35 -35
  26. package/lib/dialects/mysql2/transaction.js +46 -46
  27. package/lib/dialects/oracle/DEAD_CODE.md +5 -5
  28. package/lib/dialects/oracle/formatter.js +20 -20
  29. package/lib/dialects/oracle/index.js +79 -79
  30. package/lib/dialects/oracle/query/compiler.js +327 -327
  31. package/lib/dialects/oracle/schema/columnbuilder.js +18 -18
  32. package/lib/dialects/oracle/schema/columncompiler.js +139 -139
  33. package/lib/dialects/oracle/schema/compiler.js +81 -81
  34. package/lib/dialects/oracle/schema/tablecompiler.js +165 -165
  35. package/lib/dialects/oracle/schema/trigger.js +126 -126
  36. package/lib/dialects/oracle/utils.js +86 -86
  37. package/lib/dialects/oracledb/index.js +489 -489
  38. package/lib/dialects/oracledb/query/compiler.js +363 -363
  39. package/lib/dialects/oracledb/schema/columncompiler.js +35 -35
  40. package/lib/dialects/oracledb/transaction.js +76 -76
  41. package/lib/dialects/oracledb/utils.js +14 -14
  42. package/lib/dialects/postgres/index.js +319 -319
  43. package/lib/dialects/postgres/query/compiler.js +206 -206
  44. package/lib/dialects/postgres/schema/columncompiler.js +125 -125
  45. package/lib/dialects/postgres/schema/compiler.js +109 -109
  46. package/lib/dialects/postgres/schema/tablecompiler.js +183 -183
  47. package/lib/dialects/redshift/index.js +73 -73
  48. package/lib/dialects/redshift/query/compiler.js +119 -119
  49. package/lib/dialects/redshift/schema/columnbuilder.js +20 -20
  50. package/lib/dialects/redshift/schema/columncompiler.js +60 -60
  51. package/lib/dialects/redshift/schema/compiler.js +14 -14
  52. package/lib/dialects/redshift/schema/tablecompiler.js +123 -123
  53. package/lib/dialects/redshift/transaction.js +18 -18
  54. package/lib/dialects/sqlite3/formatter.js +21 -21
  55. package/lib/dialects/sqlite3/index.js +169 -169
  56. package/lib/dialects/sqlite3/query/compiler.js +222 -222
  57. package/lib/dialects/sqlite3/schema/columncompiler.js +27 -27
  58. package/lib/dialects/sqlite3/schema/compiler.js +49 -49
  59. package/lib/dialects/sqlite3/schema/ddl.js +525 -525
  60. package/lib/dialects/sqlite3/schema/tablecompiler.js +238 -238
  61. package/lib/formatter.js +295 -295
  62. package/lib/functionhelper.js +14 -14
  63. package/lib/helpers.js +92 -92
  64. package/lib/index.js +3 -3
  65. package/lib/interface.js +115 -115
  66. package/lib/knex.js +42 -42
  67. package/lib/logger.js +76 -76
  68. package/lib/migrate/MigrationGenerator.js +82 -82
  69. package/lib/migrate/Migrator.js +611 -611
  70. package/lib/migrate/configuration-merger.js +60 -60
  71. package/lib/migrate/migrate-stub.js +17 -17
  72. package/lib/migrate/migration-list-resolver.js +36 -36
  73. package/lib/migrate/sources/fs-migrations.js +99 -99
  74. package/lib/migrate/stub/cjs.stub +15 -15
  75. package/lib/migrate/stub/coffee.stub +13 -13
  76. package/lib/migrate/stub/eg.stub +14 -14
  77. package/lib/migrate/stub/js.stub +15 -15
  78. package/lib/migrate/stub/knexfile-coffee.stub +34 -34
  79. package/lib/migrate/stub/knexfile-eg.stub +43 -43
  80. package/lib/migrate/stub/knexfile-js.stub +44 -44
  81. package/lib/migrate/stub/knexfile-ls.stub +35 -35
  82. package/lib/migrate/stub/knexfile-ts.stub +44 -44
  83. package/lib/migrate/stub/ls.stub +14 -14
  84. package/lib/migrate/stub/ts.stub +21 -21
  85. package/lib/migrate/table-creator.js +67 -67
  86. package/lib/migrate/table-resolver.js +27 -27
  87. package/lib/query/builder.js +1372 -1372
  88. package/lib/query/compiler.js +889 -889
  89. package/lib/query/constants.js +13 -13
  90. package/lib/query/joinclause.js +263 -263
  91. package/lib/query/methods.js +92 -92
  92. package/lib/query/string.js +190 -190
  93. package/lib/raw.js +188 -188
  94. package/lib/ref.js +39 -39
  95. package/lib/runner.js +285 -285
  96. package/lib/schema/builder.js +82 -82
  97. package/lib/schema/columnbuilder.js +117 -117
  98. package/lib/schema/columncompiler.js +177 -177
  99. package/lib/schema/compiler.js +101 -101
  100. package/lib/schema/helpers.js +51 -51
  101. package/lib/schema/tablebuilder.js +288 -288
  102. package/lib/schema/tablecompiler.js +296 -296
  103. package/lib/seed/Seeder.js +203 -203
  104. package/lib/seed/seed-stub.js +13 -13
  105. package/lib/seed/stub/coffee.stub +9 -9
  106. package/lib/seed/stub/eg.stub +11 -11
  107. package/lib/seed/stub/js.stub +13 -13
  108. package/lib/seed/stub/ls.stub +11 -11
  109. package/lib/seed/stub/ts.stub +13 -13
  110. package/lib/transaction.js +363 -363
  111. package/lib/util/batchInsert.js +59 -59
  112. package/lib/util/delay.js +6 -6
  113. package/lib/util/fake-client.js +9 -9
  114. package/lib/util/finally-mixin.js +13 -13
  115. package/lib/util/fs.js +76 -76
  116. package/lib/util/import-file.js +13 -13
  117. package/lib/util/is-module-type.js +14 -14
  118. package/lib/util/is.js +32 -32
  119. package/lib/util/make-knex.js +338 -338
  120. package/lib/util/nanoid.js +29 -29
  121. package/lib/util/noop.js +1 -1
  122. package/lib/util/parse-connection.js +66 -66
  123. package/lib/util/save-async-stack.js +14 -14
  124. package/lib/util/template.js +52 -52
  125. package/lib/util/timeout.js +29 -29
  126. package/lib/util/timestamp.js +16 -16
  127. package/package.json +1 -1
  128. package/scripts/build.js +125 -125
  129. package/scripts/docker-compose.yml +111 -111
  130. package/scripts/next-release-howto.md +24 -24
  131. package/scripts/release.sh +34 -34
  132. package/scripts/runkit-example.js +34 -34
  133. package/scripts/stress-test/README.txt +18 -18
  134. package/scripts/stress-test/docker-compose.yml +47 -47
  135. package/scripts/stress-test/knex-stress-test.js +196 -196
  136. package/scripts/stress-test/mysql2-random-hanging-every-now-and-then.js +145 -145
  137. package/scripts/stress-test/mysql2-sudden-exit-without-error.js +100 -100
  138. package/scripts/stress-test/reconnect-test-mysql-based-drivers.js +184 -184
  139. package/types/index.d.ts +2249 -2249
  140. package/types/result.d.ts +27 -27
  141. package/types/tables.d.ts +4 -4
@@ -1,390 +1,390 @@
1
- // MSSQL Client
2
- // -------
3
- const flatten = require('lodash/flatten');
4
- const map = require('lodash/map');
5
- const values = require('lodash/values');
6
- const { inherits } = require('util');
7
-
8
- const Client = require('../../client');
9
-
10
- const Formatter = require('../../formatter');
11
- const Transaction = require('./transaction');
12
- const QueryCompiler = require('./query/compiler');
13
- const SchemaCompiler = require('./schema/compiler');
14
- const TableCompiler = require('./schema/tablecompiler');
15
- const ColumnCompiler = require('./schema/columncompiler');
16
-
17
- const SQL_INT4 = { MIN: -2147483648, MAX: 2147483647 };
18
- const SQL_BIGINT_SAFE = { MIN: -9007199254740991, MAX: 9007199254740991 };
19
-
20
- // Always initialize with the "QueryBuilder" and "QueryCompiler" objects, which
21
- // extend the base 'lib/query/builder' and 'lib/query/compiler', respectively.
22
- function Client_MSSQL(config = {}) {
23
- // #1235 mssql module wants 'server', not 'host'. This is to enforce the same
24
- // options object across all dialects.
25
- if (config && config.connection && config.connection.host) {
26
- config.connection.server = config.connection.host;
27
- }
28
-
29
- // mssql always creates pool :( lets try to unpool it as much as possible
30
- this.mssqlPoolSettings = {
31
- min: 1,
32
- max: 1,
33
- idleTimeoutMillis: Number.MAX_SAFE_INTEGER,
34
- };
35
-
36
- Client.call(this, config);
37
- }
38
-
39
- inherits(Client_MSSQL, Client);
40
-
41
- Object.assign(Client_MSSQL.prototype, {
42
- dialect: 'mssql',
43
-
44
- driverName: 'mssql',
45
-
46
- _driver() {
47
- const tds = require('tedious');
48
- const mssqlTedious = require('mssql');
49
- const base = require('mssql/lib/base');
50
-
51
- // Monkey patch mssql's tedious driver _poolCreate method to fix problem with hanging acquire
52
- // connection, this should be removed when https://github.com/tediousjs/node-mssql/pull/614 is
53
- // merged and released.
54
-
55
- // Also since this dialect actually always uses tedious driver (msnodesqlv8 driver should be
56
- // required in different way), it might be better to use tedious directly, because mssql
57
- // driver uses always internally extra generic-pool and just adds one unnecessary layer of
58
- // indirection between database and knex and mssql driver has been lately without maintainer
59
- // (changing implementation to use tedious will be breaking change though).
60
-
61
- // TODO: remove mssql implementation all together and use tedious directly
62
-
63
- /* istanbul ignore next */
64
- const mssqlVersion = require('mssql/package.json').version;
65
- /* istanbul ignore next */
66
- if (mssqlVersion === '4.1.0') {
67
- mssqlTedious.ConnectionPool.prototype.release = release;
68
- mssqlTedious.ConnectionPool.prototype._poolCreate = _poolCreate;
69
- } else {
70
- const [major] = mssqlVersion.split('.');
71
- // if version is not ^5.0.0
72
- if (major < 5) {
73
- throw new Error(
74
- 'This knex version only supports mssql driver versions 4.1.0 and 5.0.0+'
75
- );
76
- }
77
- }
78
-
79
- /* istanbul ignore next */
80
- // in some rare situations release is called when stream is interrupted, but
81
- // after pool is already destroyed
82
- function release(connection) {
83
- if (this.pool) {
84
- this.pool.release(connection);
85
- }
86
- }
87
-
88
- /* istanbul ignore next */
89
- function _poolCreate() {
90
- // implementation is copy-pasted from https://github.com/tediousjs/node-mssql/pull/614
91
- return new base.Promise((resolve, reject) => {
92
- const cfg = {
93
- userName: this.config.user,
94
- password: this.config.password,
95
- server: this.config.server,
96
- options: Object.assign({}, this.config.options),
97
- domain: this.config.domain,
98
- };
99
-
100
- cfg.options.database = this.config.database;
101
- cfg.options.port = this.config.port;
102
- cfg.options.connectTimeout =
103
- this.config.connectionTimeout || this.config.timeout || 15000;
104
- cfg.options.requestTimeout =
105
- this.config.requestTimeout != null
106
- ? this.config.requestTimeout
107
- : 15000;
108
- cfg.options.tdsVersion = cfg.options.tdsVersion || '7_4';
109
- cfg.options.rowCollectionOnDone = false;
110
- cfg.options.rowCollectionOnRequestCompletion = false;
111
- cfg.options.useColumnNames = false;
112
- cfg.options.appName = cfg.options.appName || 'node-mssql';
113
- cfg.options.trustServerCertificate =
114
- cfg.options.trustServerCertificate || false;
115
-
116
- // tedious always connect via tcp when port is specified
117
- if (cfg.options.instanceName) delete cfg.options.port;
118
-
119
- if (isNaN(cfg.options.requestTimeout))
120
- cfg.options.requestTimeout = 15000;
121
- if (cfg.options.requestTimeout === Infinity)
122
- cfg.options.requestTimeout = 0;
123
- if (cfg.options.requestTimeout < 0) cfg.options.requestTimeout = 0;
124
-
125
- if (this.config.debug) {
126
- cfg.options.debug = {
127
- packet: true,
128
- token: true,
129
- data: true,
130
- payload: true,
131
- };
132
- }
133
-
134
- const tedious = new tds.Connection(cfg);
135
-
136
- // prevent calling resolve again on end event
137
- let alreadyResolved = false;
138
-
139
- function safeResolve(err) {
140
- if (!alreadyResolved) {
141
- alreadyResolved = true;
142
- resolve(err);
143
- }
144
- }
145
-
146
- function safeReject(err) {
147
- if (!alreadyResolved) {
148
- alreadyResolved = true;
149
- reject(err);
150
- }
151
- }
152
-
153
- tedious.once('end', (evt) => {
154
- safeReject(
155
- new base.ConnectionError(
156
- 'Connection ended unexpectedly during connecting'
157
- )
158
- );
159
- });
160
-
161
- tedious.once('connect', (err) => {
162
- if (err) {
163
- err = new base.ConnectionError(err);
164
- return safeReject(err);
165
- }
166
- safeResolve(tedious);
167
- });
168
-
169
- tedious.on('error', (err) => {
170
- if (err.code === 'ESOCKET') {
171
- tedious.hasError = true;
172
- return;
173
- }
174
-
175
- this.emit('error', err);
176
- });
177
-
178
- if (this.config.debug) {
179
- tedious.on('debug', this.emit.bind(this, 'debug', tedious));
180
- }
181
- });
182
- }
183
-
184
- return mssqlTedious;
185
- },
186
-
187
- formatter() {
188
- return new MSSQL_Formatter(this, ...arguments);
189
- },
190
-
191
- transaction() {
192
- return new Transaction(this, ...arguments);
193
- },
194
-
195
- queryCompiler() {
196
- return new QueryCompiler(this, ...arguments);
197
- },
198
-
199
- schemaCompiler() {
200
- return new SchemaCompiler(this, ...arguments);
201
- },
202
-
203
- tableCompiler() {
204
- return new TableCompiler(this, ...arguments);
205
- },
206
-
207
- columnCompiler() {
208
- return new ColumnCompiler(this, ...arguments);
209
- },
210
-
211
- wrapIdentifierImpl(value) {
212
- if (value === '*') {
213
- return '*';
214
- }
215
-
216
- return `[${value.replace(/[[\]]+/g, '')}]`;
217
- },
218
-
219
- // Get a raw connection, called by the `pool` whenever a new
220
- // connection needs to be added to the pool.
221
- acquireRawConnection() {
222
- return new Promise((resolver, rejecter) => {
223
- const settings = Object.assign({}, this.connectionSettings);
224
- settings.pool = this.mssqlPoolSettings;
225
-
226
- const connection = new this.driver.ConnectionPool(settings);
227
- connection.connect((err) => {
228
- if (err) {
229
- return rejecter(err);
230
- }
231
- connection.on('error', (err) => {
232
- connection.__knex__disposed = err;
233
- });
234
- resolver(connection);
235
- });
236
- });
237
- },
238
-
239
- validateConnection(connection) {
240
- if (connection.connected === true) {
241
- return true;
242
- }
243
-
244
- return false;
245
- },
246
-
247
- // Used to explicitly close a connection, called internally by the pool
248
- // when a connection times out or the pool is shutdown.
249
- destroyRawConnection(connection) {
250
- return connection.close().catch((err) => {
251
- // some times close will reject just because pool has already been destoyed
252
- // internally by the driver there is nothing we can do in this case
253
- });
254
- },
255
-
256
- // Position the bindings for the query.
257
- positionBindings(sql) {
258
- let questionCount = -1;
259
- return sql.replace(/\\?\?/g, (match) => {
260
- if (match === '\\?') {
261
- return '?';
262
- }
263
-
264
- questionCount += 1;
265
- return `@p${questionCount}`;
266
- });
267
- },
268
-
269
- // Grab a connection, run the query via the MSSQL streaming interface,
270
- // and pass that through to the stream we've sent back to the client.
271
- _stream(connection, obj, stream) {
272
- if (!obj || typeof obj === 'string') obj = { sql: obj };
273
- return new Promise((resolver, rejecter) => {
274
- stream.on('error', (err) => {
275
- rejecter(err);
276
- });
277
- stream.on('end', resolver);
278
- const { sql } = obj;
279
- if (!sql) return resolver();
280
- const req = (connection.tx_ || connection).request();
281
- //req.verbose = true;
282
- req.multiple = true;
283
- req.stream = true;
284
- if (obj.bindings) {
285
- for (let i = 0; i < obj.bindings.length; i++) {
286
- this._setReqInput(req, i, obj.bindings[i]);
287
- }
288
- }
289
- req.pipe(stream);
290
- req.query(sql);
291
- });
292
- },
293
-
294
- // Runs the query on the specified connection, providing the bindings
295
- // and any other necessary prep work.
296
- _query(connection, obj) {
297
- const client = this;
298
- if (!obj || typeof obj === 'string') obj = { sql: obj };
299
- return new Promise((resolver, rejecter) => {
300
- const { sql } = obj;
301
- if (!sql) return resolver();
302
- const req = (connection.tx_ || connection).request();
303
- // req.verbose = true;
304
- req.multiple = true;
305
- if (obj.bindings) {
306
- for (let i = 0; i < obj.bindings.length; i++) {
307
- client._setReqInput(req, i, obj.bindings[i]);
308
- }
309
- }
310
- req.query(sql, (err, recordset) => {
311
- if (err) {
312
- return rejecter(err);
313
- }
314
- obj.response = recordset.recordsets[0];
315
- resolver(obj);
316
- });
317
- });
318
- },
319
-
320
- // sets a request input parameter. Detects bigints and decimals and sets type appropriately.
321
- _setReqInput(req, i, binding) {
322
- if (typeof binding == 'number') {
323
- if (binding % 1 !== 0) {
324
- req.input(`p${i}`, this.driver.Float(53), binding);
325
- } else if (binding < SQL_INT4.MIN || binding > SQL_INT4.MAX) {
326
- if (binding < SQL_BIGINT_SAFE.MIN || binding > SQL_BIGINT_SAFE.MAX) {
327
- throw new Error(
328
- `Bigint must be safe integer or must be passed as string, saw ${binding}`
329
- );
330
- }
331
- req.input(`p${i}`, this.driver.BigInt, binding);
332
- } else {
333
- req.input(`p${i}`, this.driver.Int, binding);
334
- }
335
- } else {
336
- req.input(`p${i}`, binding);
337
- }
338
- },
339
-
340
- // Process the response as returned from the query.
341
- processResponse(obj, runner) {
342
- if (obj == null) return;
343
- const { response, method } = obj;
344
- if (obj.output) return obj.output.call(runner, response);
345
- switch (method) {
346
- case 'select':
347
- case 'pluck':
348
- case 'first':
349
- if (method === 'pluck') return map(response, obj.pluck);
350
- return method === 'first' ? response[0] : response;
351
- case 'insert':
352
- case 'del':
353
- case 'update':
354
- case 'counter':
355
- if (obj.returning) {
356
- if (obj.returning === '@@rowcount') {
357
- return response[0][''];
358
- }
359
-
360
- if (
361
- (Array.isArray(obj.returning) && obj.returning.length > 1) ||
362
- obj.returning[0] === '*'
363
- ) {
364
- return response;
365
- }
366
- // return an array with values if only one returning value was specified
367
- return flatten(map(response, values));
368
- }
369
- return response;
370
- default:
371
- return response;
372
- }
373
- },
374
- });
375
-
376
- class MSSQL_Formatter extends Formatter {
377
- // Accepts a string or array of columns to wrap as appropriate.
378
- columnizeWithPrefix(prefix, target) {
379
- const columns = typeof target === 'string' ? [target] : target;
380
- let str = '',
381
- i = -1;
382
- while (++i < columns.length) {
383
- if (i > 0) str += ', ';
384
- str += prefix + this.wrap(columns[i]);
385
- }
386
- return str;
387
- }
388
- }
389
-
390
- module.exports = Client_MSSQL;
1
+ // MSSQL Client
2
+ // -------
3
+ const flatten = require('lodash/flatten');
4
+ const map = require('lodash/map');
5
+ const values = require('lodash/values');
6
+ const { inherits } = require('util');
7
+
8
+ const Client = require('../../client');
9
+
10
+ const Formatter = require('../../formatter');
11
+ const Transaction = require('./transaction');
12
+ const QueryCompiler = require('./query/compiler');
13
+ const SchemaCompiler = require('./schema/compiler');
14
+ const TableCompiler = require('./schema/tablecompiler');
15
+ const ColumnCompiler = require('./schema/columncompiler');
16
+
17
+ const SQL_INT4 = { MIN: -2147483648, MAX: 2147483647 };
18
+ const SQL_BIGINT_SAFE = { MIN: -9007199254740991, MAX: 9007199254740991 };
19
+
20
+ // Always initialize with the "QueryBuilder" and "QueryCompiler" objects, which
21
+ // extend the base 'lib/query/builder' and 'lib/query/compiler', respectively.
22
+ function Client_MSSQL(config = {}) {
23
+ // #1235 mssql module wants 'server', not 'host'. This is to enforce the same
24
+ // options object across all dialects.
25
+ if (config && config.connection && config.connection.host) {
26
+ config.connection.server = config.connection.host;
27
+ }
28
+
29
+ // mssql always creates pool :( lets try to unpool it as much as possible
30
+ this.mssqlPoolSettings = {
31
+ min: 1,
32
+ max: 1,
33
+ idleTimeoutMillis: Number.MAX_SAFE_INTEGER,
34
+ };
35
+
36
+ Client.call(this, config);
37
+ }
38
+
39
+ inherits(Client_MSSQL, Client);
40
+
41
+ Object.assign(Client_MSSQL.prototype, {
42
+ dialect: 'mssql',
43
+
44
+ driverName: 'mssql',
45
+
46
+ _driver() {
47
+ const tds = require('tedious');
48
+ const mssqlTedious = require('mssql');
49
+ const base = require('mssql/lib/base');
50
+
51
+ // Monkey patch mssql's tedious driver _poolCreate method to fix problem with hanging acquire
52
+ // connection, this should be removed when https://github.com/tediousjs/node-mssql/pull/614 is
53
+ // merged and released.
54
+
55
+ // Also since this dialect actually always uses tedious driver (msnodesqlv8 driver should be
56
+ // required in different way), it might be better to use tedious directly, because mssql
57
+ // driver uses always internally extra generic-pool and just adds one unnecessary layer of
58
+ // indirection between database and knex and mssql driver has been lately without maintainer
59
+ // (changing implementation to use tedious will be breaking change though).
60
+
61
+ // TODO: remove mssql implementation all together and use tedious directly
62
+
63
+ /* istanbul ignore next */
64
+ const mssqlVersion = require('mssql/package.json').version;
65
+ /* istanbul ignore next */
66
+ if (mssqlVersion === '4.1.0') {
67
+ mssqlTedious.ConnectionPool.prototype.release = release;
68
+ mssqlTedious.ConnectionPool.prototype._poolCreate = _poolCreate;
69
+ } else {
70
+ const [major] = mssqlVersion.split('.');
71
+ // if version is not ^5.0.0
72
+ if (major < 5) {
73
+ throw new Error(
74
+ 'This knex version only supports mssql driver versions 4.1.0 and 5.0.0+'
75
+ );
76
+ }
77
+ }
78
+
79
+ /* istanbul ignore next */
80
+ // in some rare situations release is called when stream is interrupted, but
81
+ // after pool is already destroyed
82
+ function release(connection) {
83
+ if (this.pool) {
84
+ this.pool.release(connection);
85
+ }
86
+ }
87
+
88
+ /* istanbul ignore next */
89
+ function _poolCreate() {
90
+ // implementation is copy-pasted from https://github.com/tediousjs/node-mssql/pull/614
91
+ return new base.Promise((resolve, reject) => {
92
+ const cfg = {
93
+ userName: this.config.user,
94
+ password: this.config.password,
95
+ server: this.config.server,
96
+ options: Object.assign({}, this.config.options),
97
+ domain: this.config.domain,
98
+ };
99
+
100
+ cfg.options.database = this.config.database;
101
+ cfg.options.port = this.config.port;
102
+ cfg.options.connectTimeout =
103
+ this.config.connectionTimeout || this.config.timeout || 15000;
104
+ cfg.options.requestTimeout =
105
+ this.config.requestTimeout != null
106
+ ? this.config.requestTimeout
107
+ : 15000;
108
+ cfg.options.tdsVersion = cfg.options.tdsVersion || '7_4';
109
+ cfg.options.rowCollectionOnDone = false;
110
+ cfg.options.rowCollectionOnRequestCompletion = false;
111
+ cfg.options.useColumnNames = false;
112
+ cfg.options.appName = cfg.options.appName || 'node-mssql';
113
+ cfg.options.trustServerCertificate =
114
+ cfg.options.trustServerCertificate || false;
115
+
116
+ // tedious always connect via tcp when port is specified
117
+ if (cfg.options.instanceName) delete cfg.options.port;
118
+
119
+ if (isNaN(cfg.options.requestTimeout))
120
+ cfg.options.requestTimeout = 15000;
121
+ if (cfg.options.requestTimeout === Infinity)
122
+ cfg.options.requestTimeout = 0;
123
+ if (cfg.options.requestTimeout < 0) cfg.options.requestTimeout = 0;
124
+
125
+ if (this.config.debug) {
126
+ cfg.options.debug = {
127
+ packet: true,
128
+ token: true,
129
+ data: true,
130
+ payload: true,
131
+ };
132
+ }
133
+
134
+ const tedious = new tds.Connection(cfg);
135
+
136
+ // prevent calling resolve again on end event
137
+ let alreadyResolved = false;
138
+
139
+ function safeResolve(err) {
140
+ if (!alreadyResolved) {
141
+ alreadyResolved = true;
142
+ resolve(err);
143
+ }
144
+ }
145
+
146
+ function safeReject(err) {
147
+ if (!alreadyResolved) {
148
+ alreadyResolved = true;
149
+ reject(err);
150
+ }
151
+ }
152
+
153
+ tedious.once('end', (evt) => {
154
+ safeReject(
155
+ new base.ConnectionError(
156
+ 'Connection ended unexpectedly during connecting'
157
+ )
158
+ );
159
+ });
160
+
161
+ tedious.once('connect', (err) => {
162
+ if (err) {
163
+ err = new base.ConnectionError(err);
164
+ return safeReject(err);
165
+ }
166
+ safeResolve(tedious);
167
+ });
168
+
169
+ tedious.on('error', (err) => {
170
+ if (err.code === 'ESOCKET') {
171
+ tedious.hasError = true;
172
+ return;
173
+ }
174
+
175
+ this.emit('error', err);
176
+ });
177
+
178
+ if (this.config.debug) {
179
+ tedious.on('debug', this.emit.bind(this, 'debug', tedious));
180
+ }
181
+ });
182
+ }
183
+
184
+ return mssqlTedious;
185
+ },
186
+
187
+ formatter() {
188
+ return new MSSQL_Formatter(this, ...arguments);
189
+ },
190
+
191
+ transaction() {
192
+ return new Transaction(this, ...arguments);
193
+ },
194
+
195
+ queryCompiler() {
196
+ return new QueryCompiler(this, ...arguments);
197
+ },
198
+
199
+ schemaCompiler() {
200
+ return new SchemaCompiler(this, ...arguments);
201
+ },
202
+
203
+ tableCompiler() {
204
+ return new TableCompiler(this, ...arguments);
205
+ },
206
+
207
+ columnCompiler() {
208
+ return new ColumnCompiler(this, ...arguments);
209
+ },
210
+
211
+ wrapIdentifierImpl(value) {
212
+ if (value === '*') {
213
+ return '*';
214
+ }
215
+
216
+ return `[${value.replace(/[[\]]+/g, '')}]`;
217
+ },
218
+
219
+ // Get a raw connection, called by the `pool` whenever a new
220
+ // connection needs to be added to the pool.
221
+ acquireRawConnection() {
222
+ return new Promise((resolver, rejecter) => {
223
+ const settings = Object.assign({}, this.connectionSettings);
224
+ settings.pool = this.mssqlPoolSettings;
225
+
226
+ const connection = new this.driver.ConnectionPool(settings);
227
+ connection.connect((err) => {
228
+ if (err) {
229
+ return rejecter(err);
230
+ }
231
+ connection.on('error', (err) => {
232
+ connection.__knex__disposed = err;
233
+ });
234
+ resolver(connection);
235
+ });
236
+ });
237
+ },
238
+
239
+ validateConnection(connection) {
240
+ if (connection.connected === true) {
241
+ return true;
242
+ }
243
+
244
+ return false;
245
+ },
246
+
247
+ // Used to explicitly close a connection, called internally by the pool
248
+ // when a connection times out or the pool is shutdown.
249
+ destroyRawConnection(connection) {
250
+ return connection.close().catch((err) => {
251
+ // some times close will reject just because pool has already been destoyed
252
+ // internally by the driver there is nothing we can do in this case
253
+ });
254
+ },
255
+
256
+ // Position the bindings for the query.
257
+ positionBindings(sql) {
258
+ let questionCount = -1;
259
+ return sql.replace(/\\?\?/g, (match) => {
260
+ if (match === '\\?') {
261
+ return '?';
262
+ }
263
+
264
+ questionCount += 1;
265
+ return `@p${questionCount}`;
266
+ });
267
+ },
268
+
269
+ // Grab a connection, run the query via the MSSQL streaming interface,
270
+ // and pass that through to the stream we've sent back to the client.
271
+ _stream(connection, obj, stream) {
272
+ if (!obj || typeof obj === 'string') obj = { sql: obj };
273
+ return new Promise((resolver, rejecter) => {
274
+ stream.on('error', (err) => {
275
+ rejecter(err);
276
+ });
277
+ stream.on('end', resolver);
278
+ const { sql } = obj;
279
+ if (!sql) return resolver();
280
+ const req = (connection.tx_ || connection).request();
281
+ //req.verbose = true;
282
+ req.multiple = true;
283
+ req.stream = true;
284
+ if (obj.bindings) {
285
+ for (let i = 0; i < obj.bindings.length; i++) {
286
+ this._setReqInput(req, i, obj.bindings[i]);
287
+ }
288
+ }
289
+ req.pipe(stream);
290
+ req.query(sql);
291
+ });
292
+ },
293
+
294
+ // Runs the query on the specified connection, providing the bindings
295
+ // and any other necessary prep work.
296
+ _query(connection, obj) {
297
+ const client = this;
298
+ if (!obj || typeof obj === 'string') obj = { sql: obj };
299
+ return new Promise((resolver, rejecter) => {
300
+ const { sql } = obj;
301
+ if (!sql) return resolver();
302
+ const req = (connection.tx_ || connection).request();
303
+ // req.verbose = true;
304
+ req.multiple = true;
305
+ if (obj.bindings) {
306
+ for (let i = 0; i < obj.bindings.length; i++) {
307
+ client._setReqInput(req, i, obj.bindings[i]);
308
+ }
309
+ }
310
+ req.query(sql, (err, recordset) => {
311
+ if (err) {
312
+ return rejecter(err);
313
+ }
314
+ obj.response = recordset.recordsets[0];
315
+ resolver(obj);
316
+ });
317
+ });
318
+ },
319
+
320
+ // sets a request input parameter. Detects bigints and decimals and sets type appropriately.
321
+ _setReqInput(req, i, binding) {
322
+ if (typeof binding == 'number') {
323
+ if (binding % 1 !== 0) {
324
+ req.input(`p${i}`, this.driver.Float(53), binding);
325
+ } else if (binding < SQL_INT4.MIN || binding > SQL_INT4.MAX) {
326
+ if (binding < SQL_BIGINT_SAFE.MIN || binding > SQL_BIGINT_SAFE.MAX) {
327
+ throw new Error(
328
+ `Bigint must be safe integer or must be passed as string, saw ${binding}`
329
+ );
330
+ }
331
+ req.input(`p${i}`, this.driver.BigInt, binding);
332
+ } else {
333
+ req.input(`p${i}`, this.driver.Int, binding);
334
+ }
335
+ } else {
336
+ req.input(`p${i}`, binding);
337
+ }
338
+ },
339
+
340
+ // Process the response as returned from the query.
341
+ processResponse(obj, runner) {
342
+ if (obj == null) return;
343
+ const { response, method } = obj;
344
+ if (obj.output) return obj.output.call(runner, response);
345
+ switch (method) {
346
+ case 'select':
347
+ case 'pluck':
348
+ case 'first':
349
+ if (method === 'pluck') return map(response, obj.pluck);
350
+ return method === 'first' ? response[0] : response;
351
+ case 'insert':
352
+ case 'del':
353
+ case 'update':
354
+ case 'counter':
355
+ if (obj.returning) {
356
+ if (obj.returning === '@@rowcount') {
357
+ return response[0][''];
358
+ }
359
+
360
+ if (
361
+ (Array.isArray(obj.returning) && obj.returning.length > 1) ||
362
+ obj.returning[0] === '*'
363
+ ) {
364
+ return response;
365
+ }
366
+ // return an array with values if only one returning value was specified
367
+ return flatten(map(response, values));
368
+ }
369
+ return response;
370
+ default:
371
+ return response;
372
+ }
373
+ },
374
+ });
375
+
376
+ class MSSQL_Formatter extends Formatter {
377
+ // Accepts a string or array of columns to wrap as appropriate.
378
+ columnizeWithPrefix(prefix, target) {
379
+ const columns = typeof target === 'string' ? [target] : target;
380
+ let str = '',
381
+ i = -1;
382
+ while (++i < columns.length) {
383
+ if (i > 0) str += ', ';
384
+ str += prefix + this.wrap(columns[i]);
385
+ }
386
+ return str;
387
+ }
388
+ }
389
+
390
+ module.exports = Client_MSSQL;