@mikro-orm/knex 6.0.0-dev.2 → 6.0.0-dev.200

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 (69) hide show
  1. package/{dist/AbstractSqlConnection.d.ts → AbstractSqlConnection.d.ts} +8 -4
  2. package/{dist/AbstractSqlConnection.js → AbstractSqlConnection.js} +35 -18
  3. package/AbstractSqlDriver.d.ts +73 -0
  4. package/AbstractSqlDriver.js +1085 -0
  5. package/AbstractSqlPlatform.d.ts +22 -0
  6. package/{dist/AbstractSqlPlatform.js → AbstractSqlPlatform.js} +46 -19
  7. package/{dist/MonkeyPatchable.d.ts → MonkeyPatchable.d.ts} +1 -0
  8. package/{dist/MonkeyPatchable.js → MonkeyPatchable.js} +3 -0
  9. package/PivotCollectionPersister.d.ts +17 -0
  10. package/PivotCollectionPersister.js +128 -0
  11. package/{dist/README.md → README.md} +66 -109
  12. package/{dist/SqlEntityManager.d.ts → SqlEntityManager.d.ts} +6 -10
  13. package/{dist/SqlEntityManager.js → SqlEntityManager.js} +5 -10
  14. package/SqlEntityRepository.d.ts +24 -0
  15. package/{dist/SqlEntityRepository.js → SqlEntityRepository.js} +11 -8
  16. package/{dist/index.d.ts → index.d.ts} +1 -0
  17. package/{dist/index.js → index.js} +6 -1
  18. package/index.mjs +211 -0
  19. package/package.json +20 -49
  20. package/query/ArrayCriteriaNode.d.ts +10 -0
  21. package/{dist/query → query}/ArrayCriteriaNode.js +7 -2
  22. package/{dist/query → query}/CriteriaNode.d.ts +11 -9
  23. package/{dist/query → query}/CriteriaNode.js +31 -15
  24. package/query/CriteriaNodeFactory.d.ts +12 -0
  25. package/{dist/query → query}/CriteriaNodeFactory.js +32 -15
  26. package/query/ObjectCriteriaNode.d.ts +15 -0
  27. package/{dist/query → query}/ObjectCriteriaNode.js +68 -21
  28. package/query/QueryBuilder.d.ts +284 -0
  29. package/query/QueryBuilder.js +1218 -0
  30. package/{dist/query → query}/QueryBuilderHelper.d.ts +26 -23
  31. package/query/QueryBuilderHelper.js +661 -0
  32. package/query/ScalarCriteriaNode.d.ts +10 -0
  33. package/{dist/query → query}/ScalarCriteriaNode.js +12 -8
  34. package/query/enums.d.ts +15 -0
  35. package/query/enums.js +20 -0
  36. package/{dist/query → query}/index.js +5 -1
  37. package/{dist/schema → schema}/DatabaseSchema.d.ts +6 -3
  38. package/{dist/schema → schema}/DatabaseSchema.js +35 -25
  39. package/{dist/schema → schema}/DatabaseTable.d.ts +21 -13
  40. package/schema/DatabaseTable.js +645 -0
  41. package/{dist/schema → schema}/SchemaComparator.d.ts +9 -7
  42. package/{dist/schema → schema}/SchemaComparator.js +99 -25
  43. package/{dist/schema → schema}/SchemaHelper.d.ts +20 -13
  44. package/{dist/schema → schema}/SchemaHelper.js +70 -18
  45. package/{dist/schema/SchemaGenerator.d.ts → schema/SqlSchemaGenerator.d.ts} +11 -14
  46. package/{dist/schema/SchemaGenerator.js → schema/SqlSchemaGenerator.js} +149 -63
  47. package/{dist/schema → schema}/index.d.ts +1 -1
  48. package/{dist/schema → schema}/index.js +6 -2
  49. package/{dist/typings.d.ts → typings.d.ts} +45 -22
  50. package/CHANGELOG.md +0 -661
  51. package/dist/AbstractSqlDriver.d.ts +0 -55
  52. package/dist/AbstractSqlDriver.js +0 -644
  53. package/dist/AbstractSqlPlatform.d.ts +0 -21
  54. package/dist/LICENSE +0 -21
  55. package/dist/SqlEntityRepository.d.ts +0 -23
  56. package/dist/index.mjs +0 -26
  57. package/dist/package.json +0 -99
  58. package/dist/query/ArrayCriteriaNode.d.ts +0 -9
  59. package/dist/query/CriteriaNodeFactory.d.ts +0 -12
  60. package/dist/query/ObjectCriteriaNode.d.ts +0 -14
  61. package/dist/query/QueryBuilder.d.ts +0 -211
  62. package/dist/query/QueryBuilder.js +0 -688
  63. package/dist/query/QueryBuilderHelper.js +0 -523
  64. package/dist/query/ScalarCriteriaNode.d.ts +0 -9
  65. package/dist/query/enums.d.ts +0 -8
  66. package/dist/query/enums.js +0 -12
  67. package/dist/schema/DatabaseTable.js +0 -319
  68. /package/{dist/query → query}/index.d.ts +0 -0
  69. /package/{dist/typings.js → typings.js} +0 -0
@@ -0,0 +1,661 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.QueryBuilderHelper = void 0;
4
+ const util_1 = require("util");
5
+ const core_1 = require("@mikro-orm/core");
6
+ const enums_1 = require("./enums");
7
+ /**
8
+ * @internal
9
+ */
10
+ class QueryBuilderHelper {
11
+ entityName;
12
+ alias;
13
+ aliasMap;
14
+ subQueries;
15
+ knex;
16
+ driver;
17
+ platform;
18
+ metadata;
19
+ constructor(entityName, alias, aliasMap, subQueries, knex, driver) {
20
+ this.entityName = entityName;
21
+ this.alias = alias;
22
+ this.aliasMap = aliasMap;
23
+ this.subQueries = subQueries;
24
+ this.knex = knex;
25
+ this.driver = driver;
26
+ this.platform = this.driver.getPlatform();
27
+ this.metadata = this.driver.getMetadata();
28
+ }
29
+ mapper(field, type = enums_1.QueryType.SELECT, value, alias) {
30
+ if (core_1.Utils.isRawSql(field)) {
31
+ return this.knex.raw(field.sql, field.params);
32
+ }
33
+ /* istanbul ignore next */
34
+ if (typeof field !== 'string') {
35
+ return field;
36
+ }
37
+ const isTableNameAliasRequired = this.isTableNameAliasRequired(type);
38
+ const fields = core_1.Utils.splitPrimaryKeys(field);
39
+ if (fields.length > 1) {
40
+ const parts = [];
41
+ for (const p of fields) {
42
+ const [a, f] = this.splitField(p);
43
+ const prop = this.getProperty(f, a);
44
+ const fkIdx2 = prop?.fieldNames.findIndex(name => name === f) ?? -1;
45
+ if (fkIdx2 !== -1) {
46
+ parts.push(this.mapper(a !== this.alias ? `${a}.${prop.fieldNames[fkIdx2]}` : prop.fieldNames[fkIdx2], type, value, alias));
47
+ }
48
+ else if (prop) {
49
+ parts.push(...prop.fieldNames.map(f => this.mapper(a !== this.alias ? `${a}.${f}` : f, type, value, alias)));
50
+ }
51
+ else {
52
+ parts.push(this.mapper(a !== this.alias ? `${a}.${f}` : f, type, value, alias));
53
+ }
54
+ }
55
+ // flatten the value if we see we are expanding nested composite key
56
+ // hackish, but cleaner solution would require quite a lot of refactoring
57
+ if (fields.length !== parts.length && Array.isArray(value)) {
58
+ value.forEach(row => {
59
+ if (Array.isArray(row)) {
60
+ const tmp = core_1.Utils.flatten(row);
61
+ row.length = 0;
62
+ row.push(...tmp);
63
+ }
64
+ });
65
+ }
66
+ return this.knex.raw('(' + parts.map(part => this.knex.ref(part)).join(', ') + ')');
67
+ }
68
+ const rawField = core_1.RawQueryFragment.getKnownFragment(field);
69
+ if (rawField) {
70
+ return this.knex.raw(rawField.sql, rawField.params);
71
+ }
72
+ const [a, f] = this.splitField(field);
73
+ const prop = this.getProperty(f, a);
74
+ const fkIdx2 = prop?.fieldNames.findIndex(name => name === f) ?? -1;
75
+ const fkIdx = fkIdx2 === -1 ? 0 : fkIdx2;
76
+ let ret = field;
77
+ // embeddable nested path instead of a regular property with table alias, reset alias
78
+ if (prop?.name === a && prop.embeddedProps[f]) {
79
+ return this.alias + '.' + prop.fieldNames[fkIdx];
80
+ }
81
+ const noPrefix = prop && prop.persist === false;
82
+ if (prop?.fieldNameRaw) {
83
+ return this.knex.raw(this.prefix(field, isTableNameAliasRequired));
84
+ }
85
+ if (prop?.formula) {
86
+ const alias2 = this.knex.ref(a).toString();
87
+ const aliased = this.knex.ref(prop.fieldNames[0]).toString();
88
+ const as = alias === null ? '' : ` as ${aliased}`;
89
+ return this.knex.raw(`${prop.formula(alias2)}${as}`);
90
+ }
91
+ if (prop?.hasConvertToJSValueSQL) {
92
+ let valueSQL;
93
+ if (prop.fieldNames.length > 1 && fkIdx !== -1) {
94
+ const fk = prop.targetMeta.getPrimaryProps()[fkIdx];
95
+ const prefixed = this.prefix(field, isTableNameAliasRequired, true, fkIdx);
96
+ valueSQL = fk.customType.convertToJSValueSQL(prefixed, this.platform);
97
+ }
98
+ else {
99
+ const prefixed = this.prefix(field, isTableNameAliasRequired, true);
100
+ valueSQL = prop.customType.convertToJSValueSQL(prefixed, this.platform);
101
+ }
102
+ if (alias === null) {
103
+ return this.knex.raw(valueSQL);
104
+ }
105
+ return this.knex.raw(`${valueSQL} as ${this.platform.quoteIdentifier(alias ?? prop.fieldNames[fkIdx])}`);
106
+ }
107
+ // do not wrap custom expressions
108
+ if (!rawField) {
109
+ ret = this.prefix(field, false, false, fkIdx);
110
+ }
111
+ if (alias) {
112
+ ret += ' as ' + alias;
113
+ }
114
+ if (!isTableNameAliasRequired || this.isPrefixed(ret) || noPrefix) {
115
+ return ret;
116
+ }
117
+ return this.alias + '.' + ret;
118
+ }
119
+ processData(data, convertCustomTypes, multi = false) {
120
+ if (Array.isArray(data)) {
121
+ return data.map(d => this.processData(d, convertCustomTypes, true));
122
+ }
123
+ const meta = this.metadata.find(this.entityName);
124
+ data = this.driver.mapDataToFieldNames(data, true, meta?.properties, convertCustomTypes);
125
+ if (!core_1.Utils.hasObjectKeys(data) && meta && multi) {
126
+ /* istanbul ignore next */
127
+ data[meta.primaryKeys[0]] = this.platform.usesDefaultKeyword() ? this.knex.raw('default') : undefined;
128
+ }
129
+ return data;
130
+ }
131
+ joinOneToReference(prop, ownerAlias, alias, type, cond = {}, schema) {
132
+ const prop2 = prop.targetMeta.properties[prop.mappedBy || prop.inversedBy];
133
+ const table = this.getTableName(prop.type);
134
+ const joinColumns = prop.owner ? prop.referencedColumnNames : prop2.joinColumns;
135
+ const inverseJoinColumns = prop.referencedColumnNames;
136
+ const primaryKeys = prop.owner ? prop.joinColumns : prop2.referencedColumnNames;
137
+ schema ??= prop.targetMeta?.schema === '*' ? '*' : this.driver.getSchemaName(prop.targetMeta);
138
+ return {
139
+ prop, type, cond, ownerAlias, alias, table, schema,
140
+ joinColumns, inverseJoinColumns, primaryKeys,
141
+ };
142
+ }
143
+ joinManyToOneReference(prop, ownerAlias, alias, type, cond = {}, schema) {
144
+ return {
145
+ prop, type, cond, ownerAlias, alias,
146
+ table: this.getTableName(prop.type),
147
+ schema: prop.targetMeta?.schema === '*' ? '*' : this.driver.getSchemaName(prop.targetMeta, { schema }),
148
+ joinColumns: prop.referencedColumnNames,
149
+ primaryKeys: prop.fieldNames,
150
+ };
151
+ }
152
+ joinManyToManyReference(prop, ownerAlias, alias, pivotAlias, type, cond, path, schema) {
153
+ const pivotMeta = this.metadata.find(prop.pivotEntity);
154
+ const ret = {
155
+ [`${ownerAlias}.${prop.name}#${pivotAlias}`]: {
156
+ prop, type, ownerAlias,
157
+ alias: pivotAlias,
158
+ inverseAlias: alias,
159
+ joinColumns: prop.joinColumns,
160
+ inverseJoinColumns: prop.inverseJoinColumns,
161
+ primaryKeys: prop.referencedColumnNames,
162
+ cond: {},
163
+ table: pivotMeta.tableName,
164
+ schema: prop.targetMeta?.schema === '*' ? '*' : this.driver.getSchemaName(pivotMeta, { schema }),
165
+ path: path.endsWith('[pivot]') ? path : `${path}[pivot]`,
166
+ },
167
+ };
168
+ if (type === enums_1.JoinType.pivotJoin) {
169
+ return ret;
170
+ }
171
+ const prop2 = prop.owner ? pivotMeta.relations[1] : pivotMeta.relations[0];
172
+ ret[`${pivotAlias}.${prop2.name}#${alias}`] = this.joinManyToOneReference(prop2, pivotAlias, alias, type, cond, schema);
173
+ ret[`${pivotAlias}.${prop2.name}#${alias}`].path = path;
174
+ const tmp = prop2.referencedTableName.split('.');
175
+ ret[`${pivotAlias}.${prop2.name}#${alias}`].schema ??= tmp.length > 1 ? tmp[0] : undefined;
176
+ return ret;
177
+ }
178
+ processJoins(qb, joins, schema) {
179
+ Object.values(joins).forEach(join => {
180
+ let table = join.table;
181
+ const method = join.type === enums_1.JoinType.pivotJoin ? 'left join' : join.type;
182
+ const conditions = [];
183
+ const params = [];
184
+ schema = join.schema && join.schema !== '*' ? join.schema : schema;
185
+ if (schema) {
186
+ table = `${schema}.${table}`;
187
+ }
188
+ if (!join.subquery) {
189
+ join.primaryKeys.forEach((primaryKey, idx) => {
190
+ const right = `${join.alias}.${join.joinColumns[idx]}`;
191
+ if (join.prop.formula) {
192
+ const left = join.prop.formula(join.ownerAlias);
193
+ conditions.push(`${left} = ${this.knex.ref(right)}`);
194
+ return;
195
+ }
196
+ const left = `${join.ownerAlias}.${primaryKey}`;
197
+ conditions.push(`${this.knex.ref(left)} = ${this.knex.ref(right)}`);
198
+ });
199
+ }
200
+ if (join.prop.targetMeta?.discriminatorValue && !join.path?.endsWith('[pivot]')) {
201
+ const typeProperty = join.prop.targetMeta.root.discriminatorColumn;
202
+ const alias = join.inverseAlias ?? join.alias;
203
+ join.cond[`${alias}.${typeProperty}`] = join.prop.targetMeta.discriminatorValue;
204
+ }
205
+ Object.keys(join.cond).forEach(key => {
206
+ const needsPrefix = key.includes('.') || core_1.Utils.isOperator(key) || core_1.RawQueryFragment.isKnownFragment(key);
207
+ const newKey = needsPrefix ? key : `${join.alias}.${key}`;
208
+ conditions.push(this.processJoinClause(newKey, join.cond[key], params));
209
+ });
210
+ let sql = method + ' ';
211
+ if (join.subquery) {
212
+ sql += `(${join.subquery})`;
213
+ }
214
+ else {
215
+ sql += this.knex.ref(table);
216
+ }
217
+ sql += ` as ${this.knex.ref(join.alias)}`;
218
+ if (conditions.length > 0) {
219
+ sql += ` on ${conditions.join(' and ')}`;
220
+ }
221
+ return qb.joinRaw(sql, params);
222
+ });
223
+ }
224
+ processJoinClause(key, value, params, operator = '$eq') {
225
+ if (core_1.Utils.isGroupOperator(key) && Array.isArray(value)) {
226
+ const parts = value.map(sub => {
227
+ return this.wrapQueryGroup(Object.keys(sub).map(k => this.processJoinClause(k, sub[k], params)));
228
+ });
229
+ return this.wrapQueryGroup(parts, key);
230
+ }
231
+ if (this.isSimpleRegExp(value)) {
232
+ params.push(this.getRegExpParam(value));
233
+ return `${this.knex.ref(this.mapper(key))} like ?`;
234
+ }
235
+ if (value instanceof RegExp) {
236
+ value = this.platform.getRegExpValue(value);
237
+ }
238
+ if (core_1.Utils.isOperator(key, false) && core_1.Utils.isPlainObject(value)) {
239
+ const parts = Object.keys(value).map(k => this.processJoinClause(k, value[k], params, key));
240
+ return key === '$not' ? `not ${this.wrapQueryGroup(parts)}` : this.wrapQueryGroup(parts);
241
+ }
242
+ if (core_1.Utils.isPlainObject(value) && Object.keys(value).every(k => core_1.Utils.isOperator(k, false))) {
243
+ const parts = Object.keys(value).map(op => this.processJoinClause(key, value[op], params, op));
244
+ return this.wrapQueryGroup(parts);
245
+ }
246
+ operator = operator === '$not' ? '$eq' : operator;
247
+ if (value === null) {
248
+ return `${this.knex.ref(this.mapper(key))} is ${operator === '$ne' ? 'not ' : ''}null`;
249
+ }
250
+ if (operator === '$fulltext') {
251
+ const [fromAlias, fromField] = this.splitField(key);
252
+ const property = this.getProperty(fromField, fromAlias);
253
+ const query = this.knex.raw(this.platform.getFullTextWhereClause(property), {
254
+ column: this.mapper(key),
255
+ query: this.knex.raw('?'),
256
+ }).toSQL().toNative();
257
+ params.push(value);
258
+ return query.sql;
259
+ }
260
+ const replacement = this.getOperatorReplacement(operator, { [operator]: value });
261
+ if (['$in', '$nin'].includes(operator) && Array.isArray(value)) {
262
+ params.push(...value);
263
+ return `${this.knex.ref(this.mapper(key))} ${replacement} (${value.map(() => '?').join(', ')})`;
264
+ }
265
+ if (operator === '$exists') {
266
+ value = null;
267
+ }
268
+ const rawField = core_1.RawQueryFragment.getKnownFragment(key);
269
+ if (rawField) {
270
+ let sql = rawField.sql;
271
+ params.push(...rawField.params);
272
+ params.push(...core_1.Utils.asArray(value));
273
+ if (core_1.Utils.asArray(value).length > 0) {
274
+ sql += ' = ?';
275
+ }
276
+ return sql;
277
+ }
278
+ const sql = this.mapper(key);
279
+ if (value !== null) {
280
+ params.push(value);
281
+ }
282
+ return `${this.knex.ref(sql)} ${replacement} ${value === null ? 'null' : '?'}`;
283
+ }
284
+ wrapQueryGroup(parts, operator = '$and') {
285
+ if (parts.length === 1) {
286
+ return parts[0];
287
+ }
288
+ return `(${parts.join(` ${core_1.GroupOperator[operator]} `)})`;
289
+ }
290
+ mapJoinColumns(type, join) {
291
+ if (join.prop && join.prop.kind === core_1.ReferenceKind.ONE_TO_ONE && !join.prop.owner) {
292
+ return join.prop.fieldNames.map((fieldName, idx) => {
293
+ return this.mapper(`${join.alias}.${join.inverseJoinColumns[idx]}`, type, undefined, fieldName);
294
+ });
295
+ }
296
+ return [
297
+ ...join.joinColumns.map(col => this.mapper(`${join.alias}.${col}`, type, undefined, `fk__${col}`)),
298
+ ...join.inverseJoinColumns.map(col => this.mapper(`${join.alias}.${col}`, type, undefined, `fk__${col}`)),
299
+ ];
300
+ }
301
+ isOneToOneInverse(field, meta) {
302
+ meta ??= this.metadata.find(this.entityName);
303
+ const prop = meta.properties[field.replace(/:ref$/, '')];
304
+ return prop && prop.kind === core_1.ReferenceKind.ONE_TO_ONE && !prop.owner;
305
+ }
306
+ getTableName(entityName) {
307
+ const meta = this.metadata.find(entityName);
308
+ return meta ? meta.collection : entityName;
309
+ }
310
+ /**
311
+ * Checks whether the RE can be rewritten to simple LIKE query
312
+ */
313
+ isSimpleRegExp(re) {
314
+ if (!(re instanceof RegExp)) {
315
+ return false;
316
+ }
317
+ if (re.flags.includes('i')) {
318
+ return false;
319
+ }
320
+ // when including the opening bracket/paren we consider it complex
321
+ return !re.source.match(/[{[(]/);
322
+ }
323
+ getRegExpParam(re) {
324
+ const value = re.source
325
+ .replace(/\.\*/g, '%') // .* -> %
326
+ .replace(/\./g, '_') // . -> _
327
+ .replace(/\\_/g, '.') // \. -> .
328
+ .replace(/^\^/g, '') // remove ^ from start
329
+ .replace(/\$$/g, ''); // remove $ from end
330
+ if (re.source.startsWith('^') && re.source.endsWith('$')) {
331
+ return value;
332
+ }
333
+ if (re.source.startsWith('^')) {
334
+ return value + '%';
335
+ }
336
+ if (re.source.endsWith('$')) {
337
+ return '%' + value;
338
+ }
339
+ return `%${value}%`;
340
+ }
341
+ appendOnConflictClause(type, onConflict, qb) {
342
+ onConflict.forEach(item => {
343
+ const sub = item.fields.length > 0 ? qb.onConflict(item.fields) : qb.onConflict();
344
+ core_1.Utils.runIfNotEmpty(() => sub.ignore(), item.ignore);
345
+ core_1.Utils.runIfNotEmpty(() => {
346
+ let mergeParam = item.merge;
347
+ if (core_1.Utils.isObject(item.merge)) {
348
+ mergeParam = {};
349
+ core_1.Utils.keys(item.merge).forEach(key => {
350
+ const k = this.mapper(key, type);
351
+ mergeParam[k] = item.merge[key];
352
+ });
353
+ }
354
+ if (Array.isArray(item.merge)) {
355
+ mergeParam = item.merge.map(key => this.mapper(key, type));
356
+ }
357
+ const sub2 = sub.merge(mergeParam);
358
+ core_1.Utils.runIfNotEmpty(() => this.appendQueryCondition(type, item.where, sub2), item.where);
359
+ }, 'merge' in item);
360
+ });
361
+ }
362
+ appendQueryCondition(type, cond, qb, operator, method = 'where') {
363
+ const m = operator === '$or' ? 'orWhere' : 'andWhere';
364
+ Object.keys(cond).forEach(k => {
365
+ if (k === '$and' || k === '$or') {
366
+ if (operator) {
367
+ return qb[m](inner => this.appendGroupCondition(type, inner, k, method, cond[k]));
368
+ }
369
+ return this.appendGroupCondition(type, qb, k, method, cond[k]);
370
+ }
371
+ if (k === '$not') {
372
+ const m = operator === '$or' ? 'orWhereNot' : 'whereNot';
373
+ return qb[m](inner => this.appendQueryCondition(type, cond[k], inner));
374
+ }
375
+ this.appendQuerySubCondition(qb, type, method, cond, k, operator);
376
+ });
377
+ }
378
+ appendQuerySubCondition(qb, type, method, cond, key, operator) {
379
+ const m = operator === '$or' ? 'orWhere' : method;
380
+ if (cond[key] instanceof core_1.RawQueryFragment) {
381
+ cond[key] = this.knex.raw(cond[key].sql, cond[key].params);
382
+ }
383
+ if (this.isSimpleRegExp(cond[key])) {
384
+ return void qb[m](this.mapper(key, type), 'like', this.getRegExpParam(cond[key]));
385
+ }
386
+ if (core_1.Utils.isPlainObject(cond[key]) || cond[key] instanceof RegExp) {
387
+ return this.processObjectSubCondition(cond, key, qb, method, m, type);
388
+ }
389
+ const op = cond[key] === null ? 'is' : '=';
390
+ const raw = core_1.RawQueryFragment.getKnownFragment(key);
391
+ if (raw) {
392
+ const value = core_1.Utils.asArray(cond[key]);
393
+ if (value.length > 0) {
394
+ return void qb[m](this.knex.raw(raw.sql, raw.params), op, value[0]);
395
+ }
396
+ return void qb[m](this.knex.raw(raw.sql, raw.params));
397
+ }
398
+ if (this.subQueries[key]) {
399
+ return void qb[m](this.knex.raw(`(${this.subQueries[key]})`), op, cond[key]);
400
+ }
401
+ qb[m](this.mapper(key, type, cond[key], null), op, cond[key]);
402
+ }
403
+ processObjectSubCondition(cond, key, qb, method, m, type) {
404
+ // grouped condition for one field
405
+ let value = cond[key];
406
+ const size = core_1.Utils.getObjectKeysSize(value);
407
+ if (core_1.Utils.isPlainObject(value) && size === 0) {
408
+ return;
409
+ }
410
+ if (size > 1) {
411
+ const subCondition = Object.entries(value).map(([subKey, subValue]) => ({ [key]: { [subKey]: subValue } }));
412
+ return subCondition.forEach(sub => this.appendQueryCondition(type, sub, qb, '$and', method));
413
+ }
414
+ if (value instanceof RegExp) {
415
+ value = this.platform.getRegExpValue(value);
416
+ }
417
+ // operators
418
+ const op = Object.keys(core_1.QueryOperator).find(op => op in value);
419
+ /* istanbul ignore next */
420
+ if (!op) {
421
+ throw new Error(`Invalid query condition: ${(0, util_1.inspect)(cond)}`);
422
+ }
423
+ const replacement = this.getOperatorReplacement(op, value);
424
+ const fields = core_1.Utils.splitPrimaryKeys(key);
425
+ if (fields.length > 1 && Array.isArray(value[op]) && !value[op].every((v) => Array.isArray(v))) {
426
+ const tmp = value[op].length === 1 && core_1.Utils.isPlainObject(value[op][0]) ? fields.map(f => value[op][0][f]) : value[op];
427
+ value[op] = this.knex.raw(`(${fields.map(() => '?').join(', ')})`, tmp);
428
+ }
429
+ if (this.subQueries[key]) {
430
+ return void qb[m](this.knex.raw(`(${this.subQueries[key]})`), replacement, value[op]);
431
+ }
432
+ if (op === '$fulltext') {
433
+ const [a, f] = this.splitField(key);
434
+ const prop = this.getProperty(f, a);
435
+ /* istanbul ignore next */
436
+ if (!prop) {
437
+ throw new Error(`Cannot use $fulltext operator on ${key}, property not found`);
438
+ }
439
+ qb[m](this.knex.raw(this.platform.getFullTextWhereClause(prop), {
440
+ column: this.mapper(key, type, undefined, null),
441
+ query: value[op],
442
+ }));
443
+ }
444
+ else {
445
+ const mappedKey = this.mapper(key, type, value[op], null);
446
+ qb[m](mappedKey, replacement, value[op]);
447
+ }
448
+ }
449
+ getOperatorReplacement(op, value) {
450
+ let replacement = core_1.QueryOperator[op];
451
+ if (op === '$exists') {
452
+ replacement = value[op] ? 'is not' : 'is';
453
+ value[op] = null;
454
+ }
455
+ if (value[op] === null && ['$eq', '$ne'].includes(op)) {
456
+ replacement = op === '$eq' ? 'is' : 'is not';
457
+ }
458
+ if (op === '$re') {
459
+ replacement = this.platform.getRegExpOperator(value[op], value.$flags);
460
+ }
461
+ return replacement;
462
+ }
463
+ getQueryOrder(type, orderBy, populate) {
464
+ if (Array.isArray(orderBy)) {
465
+ return orderBy.flatMap(o => this.getQueryOrder(type, o, populate));
466
+ }
467
+ return this.getQueryOrderFromObject(type, orderBy, populate);
468
+ }
469
+ getQueryOrderFromObject(type, orderBy, populate) {
470
+ const ret = [];
471
+ for (const key of Object.keys(orderBy)) {
472
+ const direction = orderBy[key];
473
+ const order = core_1.Utils.isNumber(direction) ? core_1.QueryOrderNumeric[direction] : direction;
474
+ const raw = core_1.RawQueryFragment.getKnownFragment(key);
475
+ if (raw) {
476
+ ret.push(`${this.platform.formatQuery(raw.sql, raw.params)} ${order.toLowerCase()}`);
477
+ continue;
478
+ }
479
+ for (const f of core_1.Utils.splitPrimaryKeys(key)) {
480
+ // eslint-disable-next-line prefer-const
481
+ let [alias, field] = this.splitField(f, true);
482
+ alias = populate[alias] || alias;
483
+ const prop = this.getProperty(field, alias);
484
+ const noPrefix = (prop && prop.persist === false && !prop.formula) || core_1.RawQueryFragment.isKnownFragment(f);
485
+ const column = this.mapper(noPrefix ? field : `${alias}.${field}`, type, undefined, null);
486
+ /* istanbul ignore next */
487
+ const rawColumn = core_1.Utils.isString(column) ? column.split('.').map(e => this.knex.ref(e)).join('.') : column;
488
+ const customOrder = prop?.customOrder;
489
+ let colPart = customOrder
490
+ ? this.platform.generateCustomOrder(rawColumn, customOrder)
491
+ : rawColumn;
492
+ if (core_1.Utils.isRawSql(colPart)) {
493
+ colPart = this.platform.formatQuery(colPart.sql, colPart.params);
494
+ }
495
+ if (Array.isArray(order)) {
496
+ order.forEach(part => ret.push(...this.getQueryOrderFromObject(type, part, populate)));
497
+ }
498
+ else {
499
+ ret.push(`${colPart} ${order.toLowerCase()}`);
500
+ }
501
+ }
502
+ }
503
+ return ret;
504
+ }
505
+ finalize(type, qb, meta, data, returning) {
506
+ if (!meta || !data || !this.platform.usesReturningStatement()) {
507
+ return;
508
+ }
509
+ // always respect explicit returning hint
510
+ if (returning && returning.length > 0) {
511
+ qb.returning(returning.map(field => this.mapper(field, type)));
512
+ return;
513
+ }
514
+ if (type === enums_1.QueryType.INSERT) {
515
+ const returningProps = meta.hydrateProps
516
+ .filter(prop => prop.returning || (prop.persist !== false && ((prop.primary && prop.autoincrement) || prop.defaultRaw)))
517
+ .filter(prop => !(prop.name in data));
518
+ if (returningProps.length > 0) {
519
+ qb.returning(core_1.Utils.flatten(returningProps.map(prop => prop.fieldNames)));
520
+ }
521
+ return;
522
+ }
523
+ if (type === enums_1.QueryType.UPDATE) {
524
+ const returningProps = meta.hydrateProps.filter(prop => core_1.Utils.isRawSql(data[prop.name]));
525
+ if (returningProps.length > 0) {
526
+ qb.returning(core_1.Utils.flatten(returningProps.map(prop => prop.fieldNames)));
527
+ }
528
+ }
529
+ }
530
+ splitField(field, greedyAlias = false) {
531
+ const parts = field.split('.');
532
+ const ref = parts[parts.length - 1].split(':')[1];
533
+ if (ref) {
534
+ parts[parts.length - 1] = parts[parts.length - 1].substring(0, parts[parts.length - 1].indexOf(':'));
535
+ }
536
+ if (parts.length === 1) {
537
+ return [this.alias, parts[0], ref];
538
+ }
539
+ if (greedyAlias) {
540
+ const fromField = parts.pop();
541
+ const fromAlias = parts.join('.');
542
+ return [fromAlias, fromField, ref];
543
+ }
544
+ const fromAlias = parts.shift();
545
+ const fromField = parts.join('.');
546
+ return [fromAlias, fromField, ref];
547
+ }
548
+ getLockSQL(qb, lockMode, lockTables = []) {
549
+ const meta = this.metadata.find(this.entityName);
550
+ if (lockMode === core_1.LockMode.OPTIMISTIC && meta && !meta.versionProperty) {
551
+ throw core_1.OptimisticLockError.lockFailed(this.entityName);
552
+ }
553
+ switch (lockMode) {
554
+ case core_1.LockMode.PESSIMISTIC_READ: return void qb.forShare(...lockTables);
555
+ case core_1.LockMode.PESSIMISTIC_WRITE: return void qb.forUpdate(...lockTables);
556
+ case core_1.LockMode.PESSIMISTIC_PARTIAL_WRITE: return void qb.forUpdate(...lockTables).skipLocked();
557
+ case core_1.LockMode.PESSIMISTIC_WRITE_OR_FAIL: return void qb.forUpdate(...lockTables).noWait();
558
+ case core_1.LockMode.PESSIMISTIC_PARTIAL_READ: return void qb.forShare(...lockTables).skipLocked();
559
+ case core_1.LockMode.PESSIMISTIC_READ_OR_FAIL: return void qb.forShare(...lockTables).noWait();
560
+ }
561
+ }
562
+ updateVersionProperty(qb, data) {
563
+ const meta = this.metadata.find(this.entityName);
564
+ if (!meta?.versionProperty || meta.versionProperty in data) {
565
+ return;
566
+ }
567
+ const versionProperty = meta.properties[meta.versionProperty];
568
+ let sql = this.platform.quoteIdentifier(versionProperty.fieldNames[0]) + ' + 1';
569
+ if (versionProperty.runtimeType === 'Date') {
570
+ sql = this.platform.getCurrentTimestampSQL(versionProperty.length);
571
+ }
572
+ qb.update(versionProperty.fieldNames[0], this.knex.raw(sql));
573
+ }
574
+ prefix(field, always = false, quote = false, idx) {
575
+ let ret;
576
+ if (!this.isPrefixed(field)) {
577
+ const alias = always ? (quote ? this.alias : this.platform.quoteIdentifier(this.alias)) + '.' : '';
578
+ const fieldName = this.fieldName(field, this.alias, always, idx);
579
+ if (fieldName instanceof core_1.RawQueryFragment) {
580
+ return fieldName.sql;
581
+ }
582
+ ret = alias + fieldName;
583
+ }
584
+ else {
585
+ const [a, ...rest] = field.split('.');
586
+ const f = rest.join('.');
587
+ ret = a + '.' + this.fieldName(f, a, always, idx);
588
+ }
589
+ if (quote) {
590
+ return this.platform.quoteIdentifier(ret);
591
+ }
592
+ return ret;
593
+ }
594
+ appendGroupCondition(type, qb, operator, method, subCondition) {
595
+ // single sub-condition can be ignored to reduce nesting of parens
596
+ if (subCondition.length === 1 || operator === '$and') {
597
+ return subCondition.forEach(sub => this.appendQueryCondition(type, sub, qb, undefined, method));
598
+ }
599
+ qb[method](outer => subCondition.forEach(sub => {
600
+ // skip nesting parens if the value is simple = scalar or object without operators or with only single key, being the operator
601
+ const keys = Object.keys(sub);
602
+ const val = sub[keys[0]];
603
+ const simple = !core_1.Utils.isPlainObject(val) || core_1.Utils.getObjectKeysSize(val) === 1 || Object.keys(val).every(k => !core_1.Utils.isOperator(k));
604
+ if (keys.length === 1 && simple) {
605
+ return this.appendQueryCondition(type, sub, outer, operator);
606
+ }
607
+ outer.orWhere(inner => this.appendQueryCondition(type, sub, inner));
608
+ }));
609
+ }
610
+ isPrefixed(field) {
611
+ return !!field.match(/[\w`"[\]]+\./);
612
+ }
613
+ fieldName(field, alias, always, idx = 0) {
614
+ const prop = this.getProperty(field, alias);
615
+ if (!prop) {
616
+ return field;
617
+ }
618
+ if (prop.fieldNameRaw) {
619
+ if (!always) {
620
+ return (0, core_1.raw)(prop.fieldNameRaw
621
+ .replace(new RegExp(core_1.ALIAS_REPLACEMENT_RE + '\\.?', 'g'), '')
622
+ .replace(this.platform.quoteIdentifier('') + '.', ''));
623
+ }
624
+ if (alias) {
625
+ return (0, core_1.raw)(prop.fieldNameRaw.replace(new RegExp(core_1.ALIAS_REPLACEMENT_RE, 'g'), alias));
626
+ }
627
+ /* istanbul ignore next */
628
+ return (0, core_1.raw)(prop.fieldNameRaw);
629
+ }
630
+ /* istanbul ignore next */
631
+ return prop.fieldNames?.[idx] ?? field;
632
+ }
633
+ getProperty(field, alias) {
634
+ const entityName = this.aliasMap[alias]?.entityName || this.entityName;
635
+ const meta = this.metadata.find(entityName);
636
+ // check if `alias` is not matching an embedded property name instead of alias, e.g. `address.city`
637
+ if (alias && meta) {
638
+ const prop = meta.properties[alias];
639
+ if (prop?.kind === core_1.ReferenceKind.EMBEDDED) {
640
+ // we want to select the full object property so hydration works as expected
641
+ if (prop.object) {
642
+ return prop;
643
+ }
644
+ const parts = field.split('.');
645
+ const nest = (p) => parts.length > 0 ? nest(p.embeddedProps[parts.shift()]) : p;
646
+ return nest(prop);
647
+ }
648
+ }
649
+ if (meta) {
650
+ if (meta.properties[field]) {
651
+ return meta.properties[field];
652
+ }
653
+ return meta.relations.find(prop => prop.fieldNames?.some(name => field === name));
654
+ }
655
+ return undefined;
656
+ }
657
+ isTableNameAliasRequired(type) {
658
+ return [enums_1.QueryType.SELECT, enums_1.QueryType.COUNT].includes(type ?? enums_1.QueryType.SELECT);
659
+ }
660
+ }
661
+ exports.QueryBuilderHelper = QueryBuilderHelper;
@@ -0,0 +1,10 @@
1
+ import { CriteriaNode } from './CriteriaNode';
2
+ import type { IQueryBuilder, ICriteriaNodeProcessOptions } from '../typings';
3
+ /**
4
+ * @internal
5
+ */
6
+ export declare class ScalarCriteriaNode<T extends object> extends CriteriaNode<T> {
7
+ process(qb: IQueryBuilder<T>, options?: ICriteriaNodeProcessOptions): any;
8
+ willAutoJoin<T>(qb: IQueryBuilder<T>, alias?: string): boolean;
9
+ shouldJoin(): boolean;
10
+ }