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,444 +1,444 @@
1
- // MSSQL Query Compiler
2
- // ------
3
- const QueryCompiler = require('../../../query/compiler');
4
-
5
- const compact = require('lodash/compact');
6
- const identity = require('lodash/identity');
7
- const isEmpty = require('lodash/isEmpty');
8
-
9
- const components = [
10
- 'columns',
11
- 'join',
12
- 'lock',
13
- 'where',
14
- 'union',
15
- 'group',
16
- 'having',
17
- 'order',
18
- 'limit',
19
- 'offset',
20
- ];
21
-
22
- class QueryCompiler_MSSQL extends QueryCompiler {
23
- constructor(client, builder) {
24
- super(client, builder);
25
-
26
- const { onConflict } = this.single;
27
- if (onConflict) {
28
- throw new Error('.onConflict() is not supported for mssql.');
29
- }
30
-
31
- this._emptyInsertValue = 'default values';
32
- }
33
-
34
- select() {
35
- const sql = this.with();
36
- const statements = components.map((component) => this[component](this));
37
- return sql + compact(statements).join(' ');
38
- }
39
-
40
- //#region Insert
41
- // Compiles an "insert" query, allowing for multiple
42
- // inserts using a single query statement.
43
- insert() {
44
- if (this.single.options && this.single.options.includeTriggerModifications) {
45
- return this.insertWithTriggers();
46
- } else {
47
- return this.standardInsert();
48
- }
49
- }
50
-
51
- insertWithTriggers() {
52
- const insertValues = this.single.insert || [];
53
- const { returning } = this.single;
54
- let sql = this.with() + `${this._buildTempTable(returning)}insert into ${this.tableName} `;
55
- const returningSql = returning
56
- ? this._returning('insert', returning, true) + ' '
57
- : '';
58
-
59
- if (Array.isArray(insertValues)) {
60
- if (insertValues.length === 0) {
61
- return '';
62
- }
63
- } else if (typeof insertValues === 'object' && isEmpty(insertValues)) {
64
- return {
65
- sql: sql + returningSql + this._emptyInsertValue + this._buildReturningSelect(returning),
66
- returning,
67
- };
68
- }
69
-
70
- const insertData = this._prepInsert(insertValues);
71
- if (typeof insertData === 'string') {
72
- sql += insertData;
73
- } else {
74
- if (insertData.columns.length) {
75
- sql += `(${this.formatter.columnize(insertData.columns)}`;
76
- sql += `) ${returningSql}values (`;
77
- let i = -1;
78
- while (++i < insertData.values.length) {
79
- if (i !== 0) sql += '), (';
80
- sql += this.formatter.parameterize(
81
- insertData.values[i],
82
- this.client.valueForUndefined
83
- );
84
- }
85
- sql += ')';
86
- } else if (insertValues.length === 1 && insertValues[0]) {
87
- sql += returningSql + this._emptyInsertValue;
88
- } else {
89
- sql = '';
90
- }
91
- }
92
-
93
- if (returning) {
94
- sql += this._buildReturningSelect(returning);
95
- }
96
-
97
- return {
98
- sql,
99
- returning,
100
- };
101
- }
102
-
103
- standardInsert() {
104
- const insertValues = this.single.insert || [];
105
- let sql = this.with() + `insert into ${this.tableName} `;
106
- const { returning } = this.single;
107
- const returningSql = returning
108
- ? this._returning('insert', returning) + ' '
109
- : '';
110
-
111
- if (Array.isArray(insertValues)) {
112
- if (insertValues.length === 0) {
113
- return '';
114
- }
115
- } else if (typeof insertValues === 'object' && isEmpty(insertValues)) {
116
- return {
117
- sql: sql + returningSql + this._emptyInsertValue,
118
- returning,
119
- };
120
- }
121
-
122
- const insertData = this._prepInsert(insertValues);
123
- if (typeof insertData === 'string') {
124
- sql += insertData;
125
- } else {
126
- if (insertData.columns.length) {
127
- sql += `(${this.formatter.columnize(insertData.columns)}`;
128
- sql += `) ${returningSql}values (`;
129
- let i = -1;
130
- while (++i < insertData.values.length) {
131
- if (i !== 0) sql += '), (';
132
- sql += this.formatter.parameterize(
133
- insertData.values[i],
134
- this.client.valueForUndefined
135
- );
136
- }
137
- sql += ')';
138
- } else if (insertValues.length === 1 && insertValues[0]) {
139
- sql += returningSql + this._emptyInsertValue;
140
- } else {
141
- sql = '';
142
- }
143
- }
144
-
145
- return {
146
- sql,
147
- returning,
148
- };
149
- }
150
- //#endregion
151
-
152
- //#region Update
153
- // Compiles an `update` query, allowing for a return value.
154
- update() {
155
- if (this.single.options && this.single.options.includeTriggerModifications) {
156
- return this.updateWithTriggers();
157
- } else {
158
- return this.standardUpdate();
159
- }
160
- }
161
-
162
- updateWithTriggers() {
163
- const top = this.top();
164
- const withSQL = this.with();
165
- const updates = this._prepUpdate(this.single.update);
166
- const join = this.join();
167
- const where = this.where();
168
- const order = this.order();
169
- const { returning } = this.single;
170
- const declaredTemp = this._buildTempTable(returning);
171
- return {
172
- sql:
173
- withSQL +
174
- declaredTemp +
175
- `update ${top ? top + ' ' : ''}${this.tableName}` +
176
- ' set ' +
177
- updates.join(', ') +
178
- (returning ? ` ${this._returning('update', returning, true)}` : '') +
179
- (join ? ` from ${this.tableName} ${join}` : '') +
180
- (where ? ` ${where}` : '') +
181
- (order ? ` ${order}` : '') +
182
- (!returning
183
- ? this._returning('rowcount', '@@rowcount')
184
- : this._buildReturningSelect(returning)),
185
- returning: returning || '@@rowcount',
186
- };
187
- }
188
-
189
- standardUpdate() {
190
- const top = this.top();
191
- const withSQL = this.with();
192
- const updates = this._prepUpdate(this.single.update);
193
- const join = this.join();
194
- const where = this.where();
195
- const order = this.order();
196
- const { returning } = this.single;
197
- return {
198
- sql:
199
- withSQL +
200
- `update ${top ? top + ' ' : ''}${this.tableName}` +
201
- ' set ' +
202
- updates.join(', ') +
203
- (returning ? ` ${this._returning('update', returning)}` : '') +
204
- (join ? ` from ${this.tableName} ${join}` : '') +
205
- (where ? ` ${where}` : '') +
206
- (order ? ` ${order}` : '') +
207
- (!returning
208
- ? this._returning('rowcount', '@@rowcount')
209
- : ""),
210
- returning: returning || '@@rowcount',
211
- };
212
- }
213
- //#endregion
214
-
215
- //#region Delete
216
- // Compiles a `delete` query.
217
- del() {
218
- if (this.single.options && this.single.options.includeTriggerModifications) {
219
- return this.deleteWithTriggers();
220
- } else {
221
- return this.standardDelete();
222
- }
223
- }
224
-
225
- deleteWithTriggers() {
226
- // Make sure tableName is processed by the formatter first.
227
- const withSQL = this.with();
228
- const { tableName } = this;
229
- const wheres = this.where();
230
- const { returning } = this.single;
231
- return {
232
- sql:
233
- withSQL +
234
- `${this._buildTempTable(returning)}delete from ${tableName}` +
235
- (returning ? ` ${this._returning('del', returning, true)}` : '') +
236
- (wheres ? ` ${wheres}` : '') +
237
- (!returning ? this._returning('rowcount', '@@rowcount') : this._buildReturningSelect(returning)),
238
- returning: returning || '@@rowcount',
239
- };
240
- }
241
-
242
- standardDelete() {
243
- // Make sure tableName is processed by the formatter first.
244
- const withSQL = this.with();
245
- const { tableName } = this;
246
- const wheres = this.where();
247
- const { returning } = this.single;
248
- return {
249
- sql:
250
- withSQL +
251
- `delete from ${tableName}` +
252
- (returning ? ` ${this._returning('del', returning)}` : '') +
253
- (wheres ? ` ${wheres}` : '') +
254
- (!returning ? this._returning('rowcount', '@@rowcount') : ""),
255
- returning: returning || '@@rowcount',
256
- };
257
- }
258
- //#endregion
259
-
260
- // Compiles the columns in the query, specifying if an item was distinct.
261
- columns() {
262
- let distinctClause = '';
263
- if (this.onlyUnions()) return '';
264
- const top = this.top();
265
- const hints = this._hintComments()
266
- const columns = this.grouped.columns || [];
267
- let i = -1,
268
- sql = [];
269
- if (columns) {
270
- while (++i < columns.length) {
271
- const stmt = columns[i];
272
- if (stmt.distinct) distinctClause = 'distinct ';
273
- if (stmt.distinctOn) {
274
- distinctClause = this.distinctOn(stmt.value);
275
- continue;
276
- }
277
- if (stmt.type === 'aggregate') {
278
- sql.push(...this.aggregate(stmt));
279
- } else if (stmt.type === 'aggregateRaw') {
280
- sql.push(this.aggregateRaw(stmt));
281
- } else if (stmt.value && stmt.value.length > 0) {
282
- sql.push(this.formatter.columnize(stmt.value));
283
- }
284
- }
285
- }
286
- if (sql.length === 0) sql = ['*'];
287
-
288
- return (
289
- `select ${hints}${distinctClause}` +
290
- (top ? top + ' ' : '') +
291
- sql.join(', ') +
292
- (this.tableName ? ` from ${this.tableName}` : '')
293
- );
294
- }
295
-
296
- _returning(method, value, withTrigger) {
297
- switch (method) {
298
- case 'update':
299
- case 'insert':
300
- return value
301
- ? `output ${this.formatter.columnizeWithPrefix('inserted.', value)}${withTrigger ? " into #out" : ""}`
302
- : '';
303
- case 'del':
304
- return value
305
- ? `output ${this.formatter.columnizeWithPrefix('deleted.', value)}${withTrigger ? " into #out" : ""}`
306
- : '';
307
- case 'rowcount':
308
- return value ? ';select @@rowcount' : '';
309
- }
310
- }
311
-
312
- _buildTempTable(values) {
313
- // If value is nothing then return an empty string
314
- if (values && values.length > 0) {
315
- let selections = "";
316
-
317
- // Build values that will be returned from this procedure
318
- if (Array.isArray(values)) {
319
- selections = values.map(value => `[t].${this.formatter.columnize(value)}`).join(",");
320
- } else {
321
- selections = `[t].${this.formatter.columnize(values)}`;
322
- }
323
-
324
- // Force #out to be correctly populated with the correct column structure.
325
- let sql = `select top(0) ${selections} into #out `;
326
- sql += `from ${this.tableName} as t `;
327
- sql += `left join ${this.tableName} on 0=1;`;
328
-
329
- return sql;
330
- }
331
-
332
- return '';
333
- }
334
-
335
- _buildReturningSelect(values) {
336
- // If value is nothing then return an empty string
337
- if (values && values.length > 0) {
338
- let selections = "";
339
-
340
- // Build columns to return
341
- if (Array.isArray(values)) {
342
- selections = values.map(value => `${this.formatter.columnize(value)}`).join(",");
343
- } else {
344
- selections = this.formatter.columnize(values);
345
- }
346
-
347
- // Get the returned values
348
- let sql = `; select ${selections} from #out; `
349
- // Drop the temp table to prevent memory leaks
350
- sql += `drop table #out;`;
351
-
352
- return sql;
353
- }
354
-
355
- return '';
356
- }
357
-
358
- // Compiles a `truncate` query.
359
- truncate() {
360
- return `truncate table ${this.tableName}`;
361
- }
362
-
363
- forUpdate() {
364
- // this doesn't work exacltly as it should, one should also mention index while locking
365
- // https://stackoverflow.com/a/9818448/360060
366
- return 'with (UPDLOCK)';
367
- }
368
-
369
- forShare() {
370
- // http://www.sqlteam.com/article/introduction-to-locking-in-sql-server
371
- return 'with (HOLDLOCK)';
372
- }
373
-
374
- // Compiles a `columnInfo` query.
375
- columnInfo() {
376
- const column = this.single.columnInfo;
377
- let schema = this.single.schema;
378
-
379
- // The user may have specified a custom wrapIdentifier function in the config. We
380
- // need to run the identifiers through that function, but not format them as
381
- // identifiers otherwise.
382
- const table = this.client.customWrapIdentifier(this.single.table, identity);
383
-
384
- if (schema) {
385
- schema = this.client.customWrapIdentifier(schema, identity);
386
- }
387
-
388
- let sql = `select * from information_schema.columns where table_name = ? and table_catalog = ?`;
389
- const bindings = [table, this.client.database()];
390
-
391
- if (schema) {
392
- sql += ' and table_schema = ?';
393
- bindings.push(schema);
394
- } else {
395
- sql += ` and table_schema = 'dbo'`;
396
- }
397
-
398
- return {
399
- sql,
400
- bindings: bindings,
401
- output(resp) {
402
- const out = resp.reduce(function (columns, val) {
403
- columns[val.COLUMN_NAME] = {
404
- defaultValue: val.COLUMN_DEFAULT,
405
- type: val.DATA_TYPE,
406
- maxLength: val.CHARACTER_MAXIMUM_LENGTH,
407
- nullable: val.IS_NULLABLE === 'YES',
408
- };
409
- return columns;
410
- }, {});
411
- return (column && out[column]) || out;
412
- },
413
- };
414
- }
415
-
416
- top() {
417
- const noLimit = !this.single.limit && this.single.limit !== 0;
418
- const noOffset = !this.single.offset;
419
- if (noLimit || !noOffset) return '';
420
- return `top (${this.formatter.parameter(this.single.limit)})`;
421
- }
422
-
423
- limit() {
424
- return '';
425
- }
426
-
427
- offset() {
428
- const noLimit = !this.single.limit && this.single.limit !== 0;
429
- const noOffset = !this.single.offset;
430
- if (noOffset) return '';
431
- let offset = `offset ${noOffset ? '0' : this.formatter.parameter(this.single.offset)
432
- } rows`;
433
- if (!noLimit) {
434
- offset += ` fetch next ${this.formatter.parameter(
435
- this.single.limit
436
- )} rows only`;
437
- }
438
- return offset;
439
- }
440
- }
441
-
442
- // Set the QueryBuilder & QueryCompiler on the client object,
443
- // in case anyone wants to modify things to suit their own purposes.
444
- module.exports = QueryCompiler_MSSQL;
1
+ // MSSQL Query Compiler
2
+ // ------
3
+ const QueryCompiler = require('../../../query/compiler');
4
+
5
+ const compact = require('lodash/compact');
6
+ const identity = require('lodash/identity');
7
+ const isEmpty = require('lodash/isEmpty');
8
+
9
+ const components = [
10
+ 'columns',
11
+ 'join',
12
+ 'lock',
13
+ 'where',
14
+ 'union',
15
+ 'group',
16
+ 'having',
17
+ 'order',
18
+ 'limit',
19
+ 'offset',
20
+ ];
21
+
22
+ class QueryCompiler_MSSQL extends QueryCompiler {
23
+ constructor(client, builder) {
24
+ super(client, builder);
25
+
26
+ const { onConflict } = this.single;
27
+ if (onConflict) {
28
+ throw new Error('.onConflict() is not supported for mssql.');
29
+ }
30
+
31
+ this._emptyInsertValue = 'default values';
32
+ }
33
+
34
+ select() {
35
+ const sql = this.with();
36
+ const statements = components.map((component) => this[component](this));
37
+ return sql + compact(statements).join(' ');
38
+ }
39
+
40
+ //#region Insert
41
+ // Compiles an "insert" query, allowing for multiple
42
+ // inserts using a single query statement.
43
+ insert() {
44
+ if (this.single.options && this.single.options.includeTriggerModifications) {
45
+ return this.insertWithTriggers();
46
+ } else {
47
+ return this.standardInsert();
48
+ }
49
+ }
50
+
51
+ insertWithTriggers() {
52
+ const insertValues = this.single.insert || [];
53
+ const { returning } = this.single;
54
+ let sql = this.with() + `${this._buildTempTable(returning)}insert into ${this.tableName} `;
55
+ const returningSql = returning
56
+ ? this._returning('insert', returning, true) + ' '
57
+ : '';
58
+
59
+ if (Array.isArray(insertValues)) {
60
+ if (insertValues.length === 0) {
61
+ return '';
62
+ }
63
+ } else if (typeof insertValues === 'object' && isEmpty(insertValues)) {
64
+ return {
65
+ sql: sql + returningSql + this._emptyInsertValue + this._buildReturningSelect(returning),
66
+ returning,
67
+ };
68
+ }
69
+
70
+ const insertData = this._prepInsert(insertValues);
71
+ if (typeof insertData === 'string') {
72
+ sql += insertData;
73
+ } else {
74
+ if (insertData.columns.length) {
75
+ sql += `(${this.formatter.columnize(insertData.columns)}`;
76
+ sql += `) ${returningSql}values (`;
77
+ let i = -1;
78
+ while (++i < insertData.values.length) {
79
+ if (i !== 0) sql += '), (';
80
+ sql += this.formatter.parameterize(
81
+ insertData.values[i],
82
+ this.client.valueForUndefined
83
+ );
84
+ }
85
+ sql += ')';
86
+ } else if (insertValues.length === 1 && insertValues[0]) {
87
+ sql += returningSql + this._emptyInsertValue;
88
+ } else {
89
+ sql = '';
90
+ }
91
+ }
92
+
93
+ if (returning) {
94
+ sql += this._buildReturningSelect(returning);
95
+ }
96
+
97
+ return {
98
+ sql,
99
+ returning,
100
+ };
101
+ }
102
+
103
+ standardInsert() {
104
+ const insertValues = this.single.insert || [];
105
+ let sql = this.with() + `insert into ${this.tableName} `;
106
+ const { returning } = this.single;
107
+ const returningSql = returning
108
+ ? this._returning('insert', returning) + ' '
109
+ : '';
110
+
111
+ if (Array.isArray(insertValues)) {
112
+ if (insertValues.length === 0) {
113
+ return '';
114
+ }
115
+ } else if (typeof insertValues === 'object' && isEmpty(insertValues)) {
116
+ return {
117
+ sql: sql + returningSql + this._emptyInsertValue,
118
+ returning,
119
+ };
120
+ }
121
+
122
+ const insertData = this._prepInsert(insertValues);
123
+ if (typeof insertData === 'string') {
124
+ sql += insertData;
125
+ } else {
126
+ if (insertData.columns.length) {
127
+ sql += `(${this.formatter.columnize(insertData.columns)}`;
128
+ sql += `) ${returningSql}values (`;
129
+ let i = -1;
130
+ while (++i < insertData.values.length) {
131
+ if (i !== 0) sql += '), (';
132
+ sql += this.formatter.parameterize(
133
+ insertData.values[i],
134
+ this.client.valueForUndefined
135
+ );
136
+ }
137
+ sql += ')';
138
+ } else if (insertValues.length === 1 && insertValues[0]) {
139
+ sql += returningSql + this._emptyInsertValue;
140
+ } else {
141
+ sql = '';
142
+ }
143
+ }
144
+
145
+ return {
146
+ sql,
147
+ returning,
148
+ };
149
+ }
150
+ //#endregion
151
+
152
+ //#region Update
153
+ // Compiles an `update` query, allowing for a return value.
154
+ update() {
155
+ if (this.single.options && this.single.options.includeTriggerModifications) {
156
+ return this.updateWithTriggers();
157
+ } else {
158
+ return this.standardUpdate();
159
+ }
160
+ }
161
+
162
+ updateWithTriggers() {
163
+ const top = this.top();
164
+ const withSQL = this.with();
165
+ const updates = this._prepUpdate(this.single.update);
166
+ const join = this.join();
167
+ const where = this.where();
168
+ const order = this.order();
169
+ const { returning } = this.single;
170
+ const declaredTemp = this._buildTempTable(returning);
171
+ return {
172
+ sql:
173
+ withSQL +
174
+ declaredTemp +
175
+ `update ${top ? top + ' ' : ''}${this.tableName}` +
176
+ ' set ' +
177
+ updates.join(', ') +
178
+ (returning ? ` ${this._returning('update', returning, true)}` : '') +
179
+ (join ? ` from ${this.tableName} ${join}` : '') +
180
+ (where ? ` ${where}` : '') +
181
+ (order ? ` ${order}` : '') +
182
+ (!returning
183
+ ? this._returning('rowcount', '@@rowcount')
184
+ : this._buildReturningSelect(returning)),
185
+ returning: returning || '@@rowcount',
186
+ };
187
+ }
188
+
189
+ standardUpdate() {
190
+ const top = this.top();
191
+ const withSQL = this.with();
192
+ const updates = this._prepUpdate(this.single.update);
193
+ const join = this.join();
194
+ const where = this.where();
195
+ const order = this.order();
196
+ const { returning } = this.single;
197
+ return {
198
+ sql:
199
+ withSQL +
200
+ `update ${top ? top + ' ' : ''}${this.tableName}` +
201
+ ' set ' +
202
+ updates.join(', ') +
203
+ (returning ? ` ${this._returning('update', returning)}` : '') +
204
+ (join ? ` from ${this.tableName} ${join}` : '') +
205
+ (where ? ` ${where}` : '') +
206
+ (order ? ` ${order}` : '') +
207
+ (!returning
208
+ ? this._returning('rowcount', '@@rowcount')
209
+ : ""),
210
+ returning: returning || '@@rowcount',
211
+ };
212
+ }
213
+ //#endregion
214
+
215
+ //#region Delete
216
+ // Compiles a `delete` query.
217
+ del() {
218
+ if (this.single.options && this.single.options.includeTriggerModifications) {
219
+ return this.deleteWithTriggers();
220
+ } else {
221
+ return this.standardDelete();
222
+ }
223
+ }
224
+
225
+ deleteWithTriggers() {
226
+ // Make sure tableName is processed by the formatter first.
227
+ const withSQL = this.with();
228
+ const { tableName } = this;
229
+ const wheres = this.where();
230
+ const { returning } = this.single;
231
+ return {
232
+ sql:
233
+ withSQL +
234
+ `${this._buildTempTable(returning)}delete from ${tableName}` +
235
+ (returning ? ` ${this._returning('del', returning, true)}` : '') +
236
+ (wheres ? ` ${wheres}` : '') +
237
+ (!returning ? this._returning('rowcount', '@@rowcount') : this._buildReturningSelect(returning)),
238
+ returning: returning || '@@rowcount',
239
+ };
240
+ }
241
+
242
+ standardDelete() {
243
+ // Make sure tableName is processed by the formatter first.
244
+ const withSQL = this.with();
245
+ const { tableName } = this;
246
+ const wheres = this.where();
247
+ const { returning } = this.single;
248
+ return {
249
+ sql:
250
+ withSQL +
251
+ `delete from ${tableName}` +
252
+ (returning ? ` ${this._returning('del', returning)}` : '') +
253
+ (wheres ? ` ${wheres}` : '') +
254
+ (!returning ? this._returning('rowcount', '@@rowcount') : ""),
255
+ returning: returning || '@@rowcount',
256
+ };
257
+ }
258
+ //#endregion
259
+
260
+ // Compiles the columns in the query, specifying if an item was distinct.
261
+ columns() {
262
+ let distinctClause = '';
263
+ if (this.onlyUnions()) return '';
264
+ const top = this.top();
265
+ const hints = this._hintComments()
266
+ const columns = this.grouped.columns || [];
267
+ let i = -1,
268
+ sql = [];
269
+ if (columns) {
270
+ while (++i < columns.length) {
271
+ const stmt = columns[i];
272
+ if (stmt.distinct) distinctClause = 'distinct ';
273
+ if (stmt.distinctOn) {
274
+ distinctClause = this.distinctOn(stmt.value);
275
+ continue;
276
+ }
277
+ if (stmt.type === 'aggregate') {
278
+ sql.push(...this.aggregate(stmt));
279
+ } else if (stmt.type === 'aggregateRaw') {
280
+ sql.push(this.aggregateRaw(stmt));
281
+ } else if (stmt.value && stmt.value.length > 0) {
282
+ sql.push(this.formatter.columnize(stmt.value));
283
+ }
284
+ }
285
+ }
286
+ if (sql.length === 0) sql = ['*'];
287
+
288
+ return (
289
+ `select ${hints}${distinctClause}` +
290
+ (top ? top + ' ' : '') +
291
+ sql.join(', ') +
292
+ (this.tableName ? ` from ${this.tableName}` : '')
293
+ );
294
+ }
295
+
296
+ _returning(method, value, withTrigger) {
297
+ switch (method) {
298
+ case 'update':
299
+ case 'insert':
300
+ return value
301
+ ? `output ${this.formatter.columnizeWithPrefix('inserted.', value)}${withTrigger ? " into #out" : ""}`
302
+ : '';
303
+ case 'del':
304
+ return value
305
+ ? `output ${this.formatter.columnizeWithPrefix('deleted.', value)}${withTrigger ? " into #out" : ""}`
306
+ : '';
307
+ case 'rowcount':
308
+ return value ? ';select @@rowcount' : '';
309
+ }
310
+ }
311
+
312
+ _buildTempTable(values) {
313
+ // If value is nothing then return an empty string
314
+ if (values && values.length > 0) {
315
+ let selections = "";
316
+
317
+ // Build values that will be returned from this procedure
318
+ if (Array.isArray(values)) {
319
+ selections = values.map(value => `[t].${this.formatter.columnize(value)}`).join(",");
320
+ } else {
321
+ selections = `[t].${this.formatter.columnize(values)}`;
322
+ }
323
+
324
+ // Force #out to be correctly populated with the correct column structure.
325
+ let sql = `select top(0) ${selections} into #out `;
326
+ sql += `from ${this.tableName} as t `;
327
+ sql += `left join ${this.tableName} on 0=1;`;
328
+
329
+ return sql;
330
+ }
331
+
332
+ return '';
333
+ }
334
+
335
+ _buildReturningSelect(values) {
336
+ // If value is nothing then return an empty string
337
+ if (values && values.length > 0) {
338
+ let selections = "";
339
+
340
+ // Build columns to return
341
+ if (Array.isArray(values)) {
342
+ selections = values.map(value => `${this.formatter.columnize(value)}`).join(",");
343
+ } else {
344
+ selections = this.formatter.columnize(values);
345
+ }
346
+
347
+ // Get the returned values
348
+ let sql = `; select ${selections} from #out; `
349
+ // Drop the temp table to prevent memory leaks
350
+ sql += `drop table #out;`;
351
+
352
+ return sql;
353
+ }
354
+
355
+ return '';
356
+ }
357
+
358
+ // Compiles a `truncate` query.
359
+ truncate() {
360
+ return `truncate table ${this.tableName}`;
361
+ }
362
+
363
+ forUpdate() {
364
+ // this doesn't work exacltly as it should, one should also mention index while locking
365
+ // https://stackoverflow.com/a/9818448/360060
366
+ return 'with (UPDLOCK)';
367
+ }
368
+
369
+ forShare() {
370
+ // http://www.sqlteam.com/article/introduction-to-locking-in-sql-server
371
+ return 'with (HOLDLOCK)';
372
+ }
373
+
374
+ // Compiles a `columnInfo` query.
375
+ columnInfo() {
376
+ const column = this.single.columnInfo;
377
+ let schema = this.single.schema;
378
+
379
+ // The user may have specified a custom wrapIdentifier function in the config. We
380
+ // need to run the identifiers through that function, but not format them as
381
+ // identifiers otherwise.
382
+ const table = this.client.customWrapIdentifier(this.single.table, identity);
383
+
384
+ if (schema) {
385
+ schema = this.client.customWrapIdentifier(schema, identity);
386
+ }
387
+
388
+ let sql = `select * from information_schema.columns where table_name = ? and table_catalog = ?`;
389
+ const bindings = [table, this.client.database()];
390
+
391
+ if (schema) {
392
+ sql += ' and table_schema = ?';
393
+ bindings.push(schema);
394
+ } else {
395
+ sql += ` and table_schema = 'dbo'`;
396
+ }
397
+
398
+ return {
399
+ sql,
400
+ bindings: bindings,
401
+ output(resp) {
402
+ const out = resp.reduce(function (columns, val) {
403
+ columns[val.COLUMN_NAME] = {
404
+ defaultValue: val.COLUMN_DEFAULT,
405
+ type: val.DATA_TYPE,
406
+ maxLength: val.CHARACTER_MAXIMUM_LENGTH,
407
+ nullable: val.IS_NULLABLE === 'YES',
408
+ };
409
+ return columns;
410
+ }, {});
411
+ return (column && out[column]) || out;
412
+ },
413
+ };
414
+ }
415
+
416
+ top() {
417
+ const noLimit = !this.single.limit && this.single.limit !== 0;
418
+ const noOffset = !this.single.offset;
419
+ if (noLimit || !noOffset) return '';
420
+ return `top (${this.formatter.parameter(this.single.limit)})`;
421
+ }
422
+
423
+ limit() {
424
+ return '';
425
+ }
426
+
427
+ offset() {
428
+ const noLimit = !this.single.limit && this.single.limit !== 0;
429
+ const noOffset = !this.single.offset;
430
+ if (noOffset) return '';
431
+ let offset = `offset ${noOffset ? '0' : this.formatter.parameter(this.single.offset)
432
+ } rows`;
433
+ if (!noLimit) {
434
+ offset += ` fetch next ${this.formatter.parameter(
435
+ this.single.limit
436
+ )} rows only`;
437
+ }
438
+ return offset;
439
+ }
440
+ }
441
+
442
+ // Set the QueryBuilder & QueryCompiler on the client object,
443
+ // in case anyone wants to modify things to suit their own purposes.
444
+ module.exports = QueryCompiler_MSSQL;