knex 2.3.0 → 2.4.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/CHANGELOG.md CHANGED
@@ -1,5 +1,24 @@
1
1
  # Master (Unreleased)
2
2
 
3
+ # 2.4.0 - 06 January, 2022
4
+
5
+ ### New features:
6
+
7
+ - Support partial unique indexes #5316
8
+ - Make compiling SQL in error message optional #5282
9
+
10
+ ### Bug fixes
11
+
12
+ - Insert array into json column #5321
13
+ - Fix unexpected max acquire-timeout #5377
14
+ - Fix: orWhereJson #5361
15
+ - MySQL: Add assertion for basic where clause not to be object or array #1227
16
+ - SQLite: Fix changing the default value of a boolean column in SQLite #5319
17
+
18
+ ### Typings:
19
+
20
+ - add missing type for 'expirationChecker' on PgConnectionConfig #5334
21
+
3
22
  # 2.3.0 - 31 August, 2022
4
23
 
5
24
  ### New features:
package/lib/client.js CHANGED
@@ -213,11 +213,16 @@ class Client extends EventEmitter {
213
213
  }
214
214
  });
215
215
 
216
+ const DEFAULT_ACQUIRE_TIMEOUT = 60000;
216
217
  const timeouts = [
217
- this.config.acquireConnectionTimeout || 60000,
218
- poolConfig.acquireTimeoutMillis,
218
+ this.config.acquireConnectionTimeout,
219
+ poolConfig.acquireTimeoutMillis
219
220
  ].filter((timeout) => timeout !== undefined);
220
221
 
222
+ if (!timeouts.length) {
223
+ timeouts.push(DEFAULT_ACQUIRE_TIMEOUT)
224
+ }
225
+
221
226
  // acquire connection timeout can be set on config or config.pool
222
227
  // choose the smallest, positive timeout setting and set on poolConfig
223
228
  poolConfig.acquireTimeoutMillis = Math.min(...timeouts);
@@ -396,7 +401,7 @@ class Client extends EventEmitter {
396
401
  if (i > 0) str += ', ';
397
402
  let value = values[i];
398
403
  // json columns can have object in values.
399
- if (isPlainObject(value)) {
404
+ if (isPlainObject(value) || Array.isArray(value)) {
400
405
  value = JSON.stringify(value);
401
406
  }
402
407
  str += this.parameter(
@@ -280,20 +280,24 @@ class TableCompiler_MSSQL extends TableCompiler {
280
280
  * Create a unique index.
281
281
  *
282
282
  * @param {string | string[]} columns
283
- * @param {string | {indexName: undefined | string, deferrable?: 'not deferrable'|'deferred'|'immediate', useConstraint?: true|false }} indexName
283
+ * @param {string | {indexName: undefined | string, deferrable?: 'not deferrable'|'deferred'|'immediate', useConstraint?: true|false, predicate?: QueryBuilder }} indexName
284
284
  */
285
285
  unique(columns, indexName) {
286
286
  /** @type {string | undefined} */
287
287
  let deferrable;
288
288
  let useConstraint = false;
289
+ let predicate;
289
290
  if (isObject(indexName)) {
290
- ({ indexName, deferrable, useConstraint } = indexName);
291
+ ({ indexName, deferrable, useConstraint, predicate } = indexName);
291
292
  }
292
293
  if (deferrable && deferrable !== 'not deferrable') {
293
294
  this.client.logger.warn(
294
295
  `mssql: unique index [${indexName}] will not be deferrable ${deferrable} because mssql does not support deferred constraints.`
295
296
  );
296
297
  }
298
+ if (useConstraint && predicate) {
299
+ throw new Error('mssql cannot create constraint with predicate');
300
+ }
297
301
  indexName = indexName
298
302
  ? this.formatter.wrap(indexName)
299
303
  : this._indexCommand('unique', this.tableNameRaw, columns);
@@ -302,10 +306,6 @@ class TableCompiler_MSSQL extends TableCompiler {
302
306
  columns = [columns];
303
307
  }
304
308
 
305
- const whereAllTheColumnsAreNotNull = columns
306
- .map((column) => this.formatter.columnize(column) + ' IS NOT NULL')
307
- .join(' AND ');
308
-
309
309
  if (useConstraint) {
310
310
  // mssql supports unique indexes and unique constraints.
311
311
  // unique indexes cannot be used with foreign key relationships hence unique constraints are used instead.
@@ -315,12 +315,18 @@ class TableCompiler_MSSQL extends TableCompiler {
315
315
  )})`
316
316
  );
317
317
  } else {
318
- // make unique constraint that allows null https://stackoverflow.com/a/767702/360060
318
+ // default to making unique index that allows null https://stackoverflow.com/a/767702/360060
319
319
  // to be more or less compatible with other DBs (if any of the columns is NULL then "duplicates" are allowed)
320
+ const predicateQuery = predicate
321
+ ? ' ' + this.client.queryCompiler(predicate).where()
322
+ : ' WHERE ' +
323
+ columns
324
+ .map((column) => this.formatter.columnize(column) + ' IS NOT NULL')
325
+ .join(' AND ');
320
326
  this.pushQuery(
321
327
  `CREATE UNIQUE INDEX ${indexName} ON ${this.tableName()} (${this.formatter.columnize(
322
328
  columns
323
- )}) WHERE ${whereAllTheColumnsAreNotNull}`
329
+ )})${predicateQuery}`
324
330
  );
325
331
  }
326
332
  }
@@ -1,6 +1,9 @@
1
1
  // MySQL Query Compiler
2
2
  // ------
3
+ const assert = require('assert');
3
4
  const identity = require('lodash/identity');
5
+ const isPlainObject = require('lodash/isPlainObject');
6
+ const isEmpty = require('lodash/isEmpty');
4
7
  const QueryCompiler = require('../../../query/querycompiler');
5
8
  const { wrapAsIdentifier } = require('../../../formatter/formatterUtils');
6
9
  const {
@@ -8,6 +11,9 @@ const {
8
11
  wrap: wrap_,
9
12
  } = require('../../../formatter/wrappingFormatter');
10
13
 
14
+ const isPlainObjectOrArray = (value) =>
15
+ isPlainObject(value) || Array.isArray(value);
16
+
11
17
  class QueryCompiler_MySQL extends QueryCompiler {
12
18
  constructor(client, builder, formatter) {
13
19
  super(client, builder, formatter);
@@ -131,7 +137,8 @@ class QueryCompiler_MySQL extends QueryCompiler {
131
137
  output(resp) {
132
138
  const out = resp.reduce(function (columns, val) {
133
139
  columns[val.COLUMN_NAME] = {
134
- defaultValue: val.COLUMN_DEFAULT === 'NULL' ? null : val.COLUMN_DEFAULT,
140
+ defaultValue:
141
+ val.COLUMN_DEFAULT === 'NULL' ? null : val.COLUMN_DEFAULT,
135
142
  type: val.DATA_TYPE,
136
143
  maxLength: val.CHARACTER_MAXIMUM_LENGTH,
137
144
  nullable: val.IS_NULLABLE === 'YES',
@@ -156,6 +163,25 @@ class QueryCompiler_MySQL extends QueryCompiler {
156
163
  return `limit ${limit}`;
157
164
  }
158
165
 
166
+ whereBasic(statement) {
167
+ assert(
168
+ !isPlainObjectOrArray(statement.value),
169
+ 'The values in where clause must not be object or array.'
170
+ );
171
+
172
+ return super.whereBasic(statement);
173
+ }
174
+
175
+ whereRaw(statement) {
176
+ assert(
177
+ isEmpty(statement.value.bindings) ||
178
+ !Object.values(statement.value.bindings).some(isPlainObjectOrArray),
179
+ 'The values in where clause must not be object or array.'
180
+ );
181
+
182
+ return super.whereRaw(statement);
183
+ }
184
+
159
185
  whereLike(statement) {
160
186
  return `${this._columnClause(statement)} ${this._not(
161
187
  statement,
@@ -189,20 +189,44 @@ class TableCompiler_PG extends TableCompiler {
189
189
 
190
190
  unique(columns, indexName) {
191
191
  let deferrable;
192
+ let useConstraint = true;
193
+ let predicate;
192
194
  if (isObject(indexName)) {
193
- ({ indexName, deferrable } = indexName);
195
+ ({ indexName, deferrable, useConstraint, predicate } = indexName);
196
+ if (useConstraint === undefined) {
197
+ useConstraint = !!deferrable || !predicate;
198
+ }
199
+ }
200
+ if (!useConstraint && deferrable && deferrable !== 'not deferrable') {
201
+ throw new Error('postgres cannot create deferrable index');
202
+ }
203
+ if (useConstraint && predicate) {
204
+ throw new Error('postgres cannot create constraint with predicate');
194
205
  }
195
206
  deferrable = deferrable ? ` deferrable initially ${deferrable}` : '';
196
207
  indexName = indexName
197
208
  ? this.formatter.wrap(indexName)
198
209
  : this._indexCommand('unique', this.tableNameRaw, columns);
199
- this.pushQuery(
200
- `alter table ${this.tableName()} add constraint ${indexName}` +
201
- ' unique (' +
202
- this.formatter.columnize(columns) +
203
- ')' +
204
- deferrable
205
- );
210
+
211
+ if (useConstraint) {
212
+ this.pushQuery(
213
+ `alter table ${this.tableName()} add constraint ${indexName}` +
214
+ ' unique (' +
215
+ this.formatter.columnize(columns) +
216
+ ')' +
217
+ deferrable
218
+ );
219
+ } else {
220
+ const predicateQuery = predicate
221
+ ? ' ' + this.client.queryCompiler(predicate).where()
222
+ : '';
223
+
224
+ this.pushQuery(
225
+ `create unique index ${indexName} on ${this.tableName()} (${this.formatter.columnize(
226
+ columns
227
+ )})${predicateQuery}`
228
+ );
229
+ }
206
230
  }
207
231
 
208
232
  index(columns, indexName, options) {
@@ -51,7 +51,7 @@ class TableCompiler_SQLite3 extends TableCompiler {
51
51
  const type = col.getColumnType();
52
52
 
53
53
  const defaultTo = col.modified['defaultTo']
54
- ? formatDefault(col.modified['defaultTo'][0], type, this.client)
54
+ ? formatDefault(col.modified['defaultTo'][0], col.type, this.client)
55
55
  : null;
56
56
 
57
57
  const notNull =
@@ -132,8 +132,9 @@ class TableCompiler_SQLite3 extends TableCompiler {
132
132
  // Compile a unique key command.
133
133
  unique(columns, indexName) {
134
134
  let deferrable;
135
+ let predicate;
135
136
  if (isObject(indexName)) {
136
- ({ indexName, deferrable } = indexName);
137
+ ({ indexName, deferrable, predicate } = indexName);
137
138
  }
138
139
  if (deferrable && deferrable !== 'not deferrable') {
139
140
  this.client.logger.warn(
@@ -144,8 +145,13 @@ class TableCompiler_SQLite3 extends TableCompiler {
144
145
  ? this.formatter.wrap(indexName)
145
146
  : this._indexCommand('unique', this.tableNameRaw, columns);
146
147
  columns = this.formatter.columnize(columns);
148
+
149
+ const predicateQuery = predicate
150
+ ? ' ' + this.client.queryCompiler(predicate).where()
151
+ : '';
152
+
147
153
  this.pushQuery(
148
- `create unique index ${indexName} on ${this.tableName()} (${columns})`
154
+ `create unique index ${indexName} on ${this.tableName()} (${columns})${predicateQuery}`
149
155
  );
150
156
  }
151
157
 
@@ -35,10 +35,14 @@ function enrichQueryObject(connection, queryParam, client) {
35
35
 
36
36
  function executeQuery(connection, queryObject, client) {
37
37
  return client._query(connection, queryObject).catch((err) => {
38
- err.message =
39
- formatQuery(queryObject.sql, queryObject.bindings, undefined, client) +
40
- ' - ' +
41
- err.message;
38
+ if (client.config && client.config.compileSqlOnError === false) {
39
+ err.message = queryObject.sql + ' - ' + err.message;
40
+ } else {
41
+ err.message =
42
+ formatQuery(queryObject.sql, queryObject.bindings, undefined, client) +
43
+ ' - ' +
44
+ err.message;
45
+ }
42
46
  client.emit(
43
47
  'query-error',
44
48
  err,
@@ -1,4 +1,8 @@
1
1
 
2
+ /**
3
+ * @param { import("knex").Knex } knex
4
+ * @returns { Promise<void> }
5
+ */
2
6
  export const up = async (knex) => {
3
7
  <% if (d.tableName) { %>
4
8
  await knex.schema.createTable("<%= d.tableName %>", function(t) {
@@ -8,6 +12,10 @@ export const up = async (knex) => {
8
12
  <% } %>
9
13
  };
10
14
 
15
+ /**
16
+ * @param { import("knex").Knex } knex
17
+ * @returns { Promise<void> }
18
+ */
11
19
  export const down = async (knex) => {
12
20
  <% if (d.tableName) { %>
13
21
  await knex.schema.dropTable("<%= d.tableName %>");
@@ -527,6 +527,7 @@ class Builder extends EventEmitter {
527
527
  // Adds a raw `where` clause to the query.
528
528
  whereRaw(sql, bindings) {
529
529
  const raw = sql.isRawInstance ? sql : this.client.raw(sql, bindings);
530
+
530
531
  this._statements.push({
531
532
  grouping: 'where',
532
533
  type: 'whereRaw',
@@ -1501,17 +1502,16 @@ class Builder extends EventEmitter {
1501
1502
  return this;
1502
1503
  }
1503
1504
 
1504
- orWhereJsonObject(column, operator, value) {
1505
- return this._bool('or').whereJsonObject(column, operator, value);
1505
+ orWhereJsonObject(column, value) {
1506
+ return this._bool('or').whereJsonObject(column, value);
1506
1507
  }
1507
1508
 
1508
1509
  whereNotJsonObject(column, value) {
1509
- this._not(true)._whereJsonWrappedValue('whereJsonObject', column, value);
1510
- return this;
1510
+ return this._not(true).whereJsonObject(column, value);
1511
1511
  }
1512
1512
 
1513
- orWhereNotJsonObject(column, operator, value) {
1514
- return this._not(true)._bool('or').whereJsonObject(column, operator, value);
1513
+ orWhereNotJsonObject(column, value) {
1514
+ return this._bool('or').whereNotJsonObject(column, value);
1515
1515
  }
1516
1516
 
1517
1517
  whereJsonPath(column, path, operator, value) {
@@ -1530,18 +1530,15 @@ class Builder extends EventEmitter {
1530
1530
  }
1531
1531
 
1532
1532
  whereJsonNotSupersetOf(column, value) {
1533
- this._not(true).whereJsonSupersetOf(column, value);
1534
- return this;
1533
+ return this._not(true).whereJsonSupersetOf(column, value);
1535
1534
  }
1536
1535
 
1537
1536
  orWhereJsonSupersetOf(column, value) {
1538
- this._whereJsonWrappedValue('whereJsonSupersetOf', column, value);
1539
- return this;
1537
+ return this._bool('or').whereJsonSupersetOf(column, value);
1540
1538
  }
1541
1539
 
1542
1540
  orWhereJsonNotSupersetOf(column, value) {
1543
- this._not(true)._bool('or').whereJsonSupersetOf(column, value);
1544
- return this;
1541
+ return this._bool('or').whereJsonNotSupersetOf(column, value);
1545
1542
  }
1546
1543
 
1547
1544
  // Json subset wheres
@@ -1551,18 +1548,15 @@ class Builder extends EventEmitter {
1551
1548
  }
1552
1549
 
1553
1550
  whereJsonNotSubsetOf(column, value) {
1554
- this._not(true).whereJsonSubsetOf(column, value);
1555
- return this;
1551
+ return this._not(true).whereJsonSubsetOf(column, value);
1556
1552
  }
1557
1553
 
1558
1554
  orWhereJsonSubsetOf(column, value) {
1559
- this._whereJsonWrappedValue('whereJsonSubsetOf', column, value);
1560
- return this;
1555
+ return this._bool('or').whereJsonSubsetOf(column, value);
1561
1556
  }
1562
1557
 
1563
1558
  orWhereJsonNotSubsetOf(column, value) {
1564
- this._not(true)._bool('or').whereJsonSubsetOf(column, value);
1565
- return this;
1559
+ return this._bool('or').whereJsonNotSubsetOf(column, value);
1566
1560
  }
1567
1561
 
1568
1562
  whereJsonHasNone(column, values) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "knex",
3
- "version": "2.3.0",
3
+ "version": "2.4.0",
4
4
  "description": "A batteries-included SQL query & schema builder for PostgresSQL, MySQL, CockroachDB, MSSQL and SQLite3",
5
5
  "main": "knex",
6
6
  "types": "types/index.d.ts",
@@ -132,7 +132,7 @@
132
132
  "pg-query-stream": "^4.2.4",
133
133
  "prettier": "2.6.2",
134
134
  "rimraf": "^3.0.2",
135
- "sinon": "^14.0.0",
135
+ "sinon": "^15.0.1",
136
136
  "sinon-chai": "^3.7.0",
137
137
  "source-map-support": "^0.5.21",
138
138
  "sqlite3": "^5.0.11",
@@ -141,8 +141,8 @@
141
141
  "tedious": "^14.4.0",
142
142
  "toxiproxy-node-client": "^2.0.6",
143
143
  "ts-node": "^10.9.1",
144
- "tsd": "^0.23.0",
145
- "typescript": "4.8.2"
144
+ "tsd": "^0.25.0",
145
+ "typescript": "4.8.3"
146
146
  },
147
147
  "buildDependencies": [
148
148
  "rimraf"
@@ -64,7 +64,8 @@ function main(cliCommand) {
64
64
  const relativeTsPath = filepath.slice(libDirectory.length + 1)
65
65
  // Swaps .ts for .js file ending
66
66
  const relativeJsPath = relativeTsPath.slice(0, relativeTsPath.length - 3) + '.js'
67
- return relativeJsPath
67
+ // Always use POSIX-style path separators - .gitignore requires it
68
+ return relativeJsPath.split(path.sep).join(path.posix.sep);
68
69
  })
69
70
  const jsFilesToIgnoreString = jsFilesToIgnore.join('\n')
70
71
  const libGitignorePath = path.join(libDirectory, '.gitignore')
package/types/index.d.ts CHANGED
@@ -2513,6 +2513,7 @@ export declare namespace Knex {
2513
2513
  storageEngineIndexType?: string;
2514
2514
  deferrable?: deferrableType;
2515
2515
  useConstraint?: boolean;
2516
+ predicate?: QueryBuilder;
2516
2517
  }>
2517
2518
  ): TableBuilder;
2518
2519
  /** @deprecated */
@@ -2716,6 +2717,7 @@ export declare namespace Knex {
2716
2717
  searchPath?: string | readonly string[];
2717
2718
  asyncStackTraces?: boolean;
2718
2719
  log?: Logger;
2720
+ compileSqlOnError?: boolean;
2719
2721
  }
2720
2722
 
2721
2723
  type StaticConnectionConfig =
@@ -3023,6 +3025,7 @@ export declare namespace Knex {
3023
3025
  connectionTimeoutMillis?: number;
3024
3026
  types?: PgCustomTypesConfig;
3025
3027
  options?: string;
3028
+ expirationChecker?(): boolean;
3026
3029
  }
3027
3030
 
3028
3031
  type PgGetTypeParser = (oid: number, format: string) => any;