@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,1218 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.QueryBuilder = void 0;
4
+ const util_1 = require("util");
5
+ const core_1 = require("@mikro-orm/core");
6
+ const enums_1 = require("./enums");
7
+ const QueryBuilderHelper_1 = require("./QueryBuilderHelper");
8
+ const CriteriaNodeFactory_1 = require("./CriteriaNodeFactory");
9
+ /**
10
+ * SQL query builder with fluent interface.
11
+ *
12
+ * ```ts
13
+ * const qb = orm.em.createQueryBuilder(Publisher);
14
+ * qb.select('*')
15
+ * .where({
16
+ * name: 'test 123',
17
+ * type: PublisherType.GLOBAL,
18
+ * })
19
+ * .orderBy({
20
+ * name: QueryOrder.DESC,
21
+ * type: QueryOrder.ASC,
22
+ * })
23
+ * .limit(2, 1);
24
+ *
25
+ * const publisher = await qb.getSingleResult();
26
+ * ```
27
+ */
28
+ class QueryBuilder {
29
+ metadata;
30
+ driver;
31
+ context;
32
+ connectionType;
33
+ em;
34
+ logging;
35
+ get mainAlias() {
36
+ this.ensureFromClause();
37
+ return this._mainAlias;
38
+ }
39
+ get alias() {
40
+ return this.mainAlias.aliasName;
41
+ }
42
+ get helper() {
43
+ this.ensureFromClause();
44
+ return this._helper;
45
+ }
46
+ /** @internal */
47
+ type;
48
+ /** @internal */
49
+ _fields;
50
+ /** @internal */
51
+ _populate = [];
52
+ /** @internal */
53
+ _populateWhere;
54
+ /** @internal */
55
+ __populateWhere;
56
+ /** @internal */
57
+ _populateMap = {};
58
+ aliasCounter = 0;
59
+ flags = new Set([core_1.QueryFlag.CONVERT_CUSTOM_TYPES]);
60
+ finalized = false;
61
+ _joins = {};
62
+ _explicitAlias = false;
63
+ _schema;
64
+ _cond = {};
65
+ _data;
66
+ _orderBy = [];
67
+ _groupBy = [];
68
+ _having = {};
69
+ _returning;
70
+ _onConflict;
71
+ _limit;
72
+ _offset;
73
+ _distinctOn;
74
+ _joinedProps = new Map();
75
+ _cache;
76
+ _indexHint;
77
+ _comments = [];
78
+ _hintComments = [];
79
+ flushMode;
80
+ lockMode;
81
+ lockTables;
82
+ subQueries = {};
83
+ _mainAlias;
84
+ _aliases = {};
85
+ _helper;
86
+ platform;
87
+ knex;
88
+ /**
89
+ * @internal
90
+ */
91
+ constructor(entityName, metadata, driver, context, alias, connectionType, em, logging) {
92
+ this.metadata = metadata;
93
+ this.driver = driver;
94
+ this.context = context;
95
+ this.connectionType = connectionType;
96
+ this.em = em;
97
+ this.logging = logging;
98
+ this.platform = this.driver.getPlatform();
99
+ this.knex = this.driver.getConnection(this.connectionType).getKnex();
100
+ if (alias) {
101
+ this.aliasCounter++;
102
+ this._explicitAlias = true;
103
+ }
104
+ // @ts-expect-error union type does not match the overloaded method signature
105
+ this.from(entityName, alias);
106
+ }
107
+ select(fields, distinct = false) {
108
+ this.ensureNotFinalized();
109
+ this._fields = core_1.Utils.asArray(fields);
110
+ if (distinct) {
111
+ this.flags.add(core_1.QueryFlag.DISTINCT);
112
+ }
113
+ return this.init(enums_1.QueryType.SELECT);
114
+ }
115
+ addSelect(fields) {
116
+ this.ensureNotFinalized();
117
+ if (this.type && this.type !== enums_1.QueryType.SELECT) {
118
+ return this;
119
+ }
120
+ return this.select([...core_1.Utils.asArray(this._fields), ...core_1.Utils.asArray(fields)]);
121
+ }
122
+ distinct() {
123
+ this.ensureNotFinalized();
124
+ return this.setFlag(core_1.QueryFlag.DISTINCT);
125
+ }
126
+ /** postgres only */
127
+ distinctOn(fields) {
128
+ this.ensureNotFinalized();
129
+ this._distinctOn = core_1.Utils.asArray(fields);
130
+ return this;
131
+ }
132
+ insert(data) {
133
+ return this.init(enums_1.QueryType.INSERT, data);
134
+ }
135
+ update(data) {
136
+ return this.init(enums_1.QueryType.UPDATE, data);
137
+ }
138
+ delete(cond) {
139
+ return this.init(enums_1.QueryType.DELETE, undefined, cond);
140
+ }
141
+ truncate() {
142
+ return this.init(enums_1.QueryType.TRUNCATE);
143
+ }
144
+ count(field, distinct = false) {
145
+ if (field) {
146
+ this._fields = core_1.Utils.asArray(field);
147
+ }
148
+ else if (this.hasToManyJoins()) {
149
+ this._fields = this.mainAlias.metadata.primaryKeys;
150
+ }
151
+ else {
152
+ this._fields = [(0, core_1.raw)('*')];
153
+ }
154
+ if (distinct) {
155
+ this.flags.add(core_1.QueryFlag.DISTINCT);
156
+ }
157
+ return this.init(enums_1.QueryType.COUNT);
158
+ }
159
+ join(field, alias, cond = {}, type = enums_1.JoinType.innerJoin, path, schema) {
160
+ this.joinReference(field, alias, cond, type, path, schema);
161
+ return this;
162
+ }
163
+ innerJoin(field, alias, cond = {}, schema) {
164
+ this.join(field, alias, cond, enums_1.JoinType.innerJoin, undefined, schema);
165
+ return this;
166
+ }
167
+ innerJoinLateral(field, alias, cond = {}, schema) {
168
+ this.join(field, alias, cond, enums_1.JoinType.innerJoinLateral, undefined, schema);
169
+ return this;
170
+ }
171
+ leftJoin(field, alias, cond = {}, schema) {
172
+ return this.join(field, alias, cond, enums_1.JoinType.leftJoin, undefined, schema);
173
+ }
174
+ leftJoinLateral(field, alias, cond = {}, schema) {
175
+ return this.join(field, alias, cond, enums_1.JoinType.leftJoinLateral, undefined, schema);
176
+ }
177
+ joinAndSelect(field, alias, cond = {}, type = enums_1.JoinType.innerJoin, path, fields, schema) {
178
+ if (!this.type) {
179
+ this.select('*');
180
+ }
181
+ let subquery;
182
+ if (Array.isArray(field)) {
183
+ subquery = field[1] instanceof QueryBuilder ? field[1].getFormattedQuery() : field[1].toString();
184
+ field = field[0];
185
+ }
186
+ const prop = this.joinReference(field, alias, cond, type, path, schema, subquery);
187
+ const [fromAlias] = this.helper.splitField(field);
188
+ if (subquery) {
189
+ this._joins[`${fromAlias}.${prop.name}#${alias}`].subquery = subquery;
190
+ }
191
+ const populate = this._joinedProps.get(fromAlias);
192
+ const item = { field: prop.name, strategy: core_1.LoadStrategy.JOINED, children: [] };
193
+ if (populate) {
194
+ populate.children.push(item);
195
+ }
196
+ else { // root entity
197
+ this._populate.push(item);
198
+ }
199
+ this._joinedProps.set(alias, item);
200
+ this.addSelect(this.getFieldsForJoinedLoad(prop, alias, fields));
201
+ return this;
202
+ }
203
+ leftJoinAndSelect(field, alias, cond = {}, fields, schema) {
204
+ return this.joinAndSelect(field, alias, cond, enums_1.JoinType.leftJoin, undefined, fields, schema);
205
+ }
206
+ leftJoinLateralAndSelect(field, alias, cond = {}, fields, schema) {
207
+ return this.joinAndSelect(field, alias, cond, enums_1.JoinType.leftJoinLateral, undefined, fields, schema);
208
+ }
209
+ innerJoinAndSelect(field, alias, cond = {}, fields, schema) {
210
+ return this.joinAndSelect(field, alias, cond, enums_1.JoinType.innerJoin, undefined, fields, schema);
211
+ }
212
+ innerJoinLateralAndSelect(field, alias, cond = {}, fields, schema) {
213
+ return this.joinAndSelect(field, alias, cond, enums_1.JoinType.innerJoinLateral, undefined, fields, schema);
214
+ }
215
+ getFieldsForJoinedLoad(prop, alias, explicitFields) {
216
+ const fields = [];
217
+ const populate = [];
218
+ const joinKey = Object.keys(this._joins).find(join => join.endsWith(`#${alias}`));
219
+ if (joinKey) {
220
+ const path = this._joins[joinKey].path.split('.').slice(1);
221
+ let children = this._populate;
222
+ for (let i = 0; i < path.length; i++) {
223
+ const child = children.filter(hint => {
224
+ const [propName] = hint.field.split(':', 2);
225
+ return propName === path[i];
226
+ });
227
+ children = child.flatMap(c => c.children);
228
+ }
229
+ populate.push(...children);
230
+ }
231
+ prop.targetMeta.props
232
+ .filter(prop => explicitFields ? explicitFields.includes(prop.name) || prop.primary : this.platform.shouldHaveColumn(prop, populate))
233
+ .forEach(prop => fields.push(...this.driver.mapPropToFieldNames(this, prop, alias)));
234
+ return fields;
235
+ }
236
+ withSubQuery(subQuery, alias) {
237
+ this.ensureNotFinalized();
238
+ this.subQueries[alias] = subQuery.toString();
239
+ return this;
240
+ }
241
+ where(cond, params, operator) {
242
+ this.ensureNotFinalized();
243
+ const rawField = core_1.RawQueryFragment.getKnownFragment(cond);
244
+ if (rawField) {
245
+ const sql = this.platform.formatQuery(rawField.sql, rawField.params);
246
+ cond = { [(0, core_1.raw)(`(${sql})`)]: core_1.Utils.asArray(params) };
247
+ operator ??= '$and';
248
+ }
249
+ else if (core_1.Utils.isString(cond)) {
250
+ cond = { [(0, core_1.raw)(`(${cond})`, core_1.Utils.asArray(params))]: [] };
251
+ operator ??= '$and';
252
+ }
253
+ else {
254
+ cond = core_1.QueryHelper.processWhere({
255
+ where: cond,
256
+ entityName: this.mainAlias.entityName,
257
+ metadata: this.metadata,
258
+ platform: this.platform,
259
+ aliasMap: this.getAliasMap(),
260
+ aliased: !this.type || [enums_1.QueryType.SELECT, enums_1.QueryType.COUNT].includes(this.type),
261
+ convertCustomTypes: this.flags.has(core_1.QueryFlag.CONVERT_CUSTOM_TYPES),
262
+ });
263
+ }
264
+ const op = operator || params;
265
+ const topLevel = !op || !core_1.Utils.hasObjectKeys(this._cond);
266
+ const criteriaNode = CriteriaNodeFactory_1.CriteriaNodeFactory.createNode(this.metadata, this.mainAlias.entityName, cond);
267
+ if ([enums_1.QueryType.UPDATE, enums_1.QueryType.DELETE].includes(this.type) && criteriaNode.willAutoJoin(this)) {
268
+ // use sub-query to support joining
269
+ this.setFlag(this.type === enums_1.QueryType.UPDATE ? core_1.QueryFlag.UPDATE_SUB_QUERY : core_1.QueryFlag.DELETE_SUB_QUERY);
270
+ this.select(this.mainAlias.metadata.primaryKeys, true);
271
+ }
272
+ if (topLevel) {
273
+ this._cond = criteriaNode.process(this);
274
+ }
275
+ else if (Array.isArray(this._cond[op])) {
276
+ this._cond[op].push(criteriaNode.process(this));
277
+ }
278
+ else {
279
+ const cond1 = [this._cond, criteriaNode.process(this)];
280
+ this._cond = { [op]: cond1 };
281
+ }
282
+ if (this._onConflict) {
283
+ this._onConflict[this._onConflict.length - 1].where = this._cond;
284
+ this._cond = {};
285
+ }
286
+ return this;
287
+ }
288
+ andWhere(cond, params) {
289
+ return this.where(cond, params, '$and');
290
+ }
291
+ orWhere(cond, params) {
292
+ return this.where(cond, params, '$or');
293
+ }
294
+ orderBy(orderBy) {
295
+ this.ensureNotFinalized();
296
+ this._orderBy = [];
297
+ core_1.Utils.asArray(orderBy).forEach(o => {
298
+ const processed = core_1.QueryHelper.processWhere({
299
+ where: o,
300
+ entityName: this.mainAlias.entityName,
301
+ metadata: this.metadata,
302
+ platform: this.platform,
303
+ aliasMap: this.getAliasMap(),
304
+ aliased: !this.type || [enums_1.QueryType.SELECT, enums_1.QueryType.COUNT].includes(this.type),
305
+ convertCustomTypes: false,
306
+ type: 'orderBy',
307
+ });
308
+ this._orderBy.push(CriteriaNodeFactory_1.CriteriaNodeFactory.createNode(this.metadata, this.mainAlias.entityName, processed).process(this, { matchPopulateJoins: true }));
309
+ });
310
+ return this;
311
+ }
312
+ groupBy(fields) {
313
+ this.ensureNotFinalized();
314
+ this._groupBy = core_1.Utils.asArray(fields);
315
+ return this;
316
+ }
317
+ having(cond = {}, params) {
318
+ this.ensureNotFinalized();
319
+ if (core_1.Utils.isString(cond)) {
320
+ cond = { [(0, core_1.raw)(`(${cond})`, params)]: [] };
321
+ }
322
+ this._having = CriteriaNodeFactory_1.CriteriaNodeFactory.createNode(this.metadata, this.mainAlias.entityName, cond).process(this);
323
+ return this;
324
+ }
325
+ onConflict(fields = []) {
326
+ const meta = this.mainAlias.metadata;
327
+ this.ensureNotFinalized();
328
+ this._onConflict ??= [];
329
+ this._onConflict.push({
330
+ fields: core_1.Utils.asArray(fields).flatMap(f => {
331
+ const key = f.toString();
332
+ /* istanbul ignore next */
333
+ return meta.properties[key]?.fieldNames ?? [key];
334
+ }),
335
+ });
336
+ return this;
337
+ }
338
+ ignore() {
339
+ if (!this._onConflict) {
340
+ throw new Error('You need to call `qb.onConflict()` first to use `qb.ignore()`');
341
+ }
342
+ this._onConflict[this._onConflict.length - 1].ignore = true;
343
+ return this;
344
+ }
345
+ merge(data) {
346
+ if (!this._onConflict) {
347
+ throw new Error('You need to call `qb.onConflict()` first to use `qb.merge()`');
348
+ }
349
+ if (Array.isArray(data) && data.length === 0) {
350
+ return this.ignore();
351
+ }
352
+ this._onConflict[this._onConflict.length - 1].merge = data;
353
+ return this;
354
+ }
355
+ returning(fields) {
356
+ this._returning = core_1.Utils.asArray(fields);
357
+ return this;
358
+ }
359
+ /**
360
+ * @internal
361
+ */
362
+ populate(populate, populateWhere) {
363
+ this.ensureNotFinalized();
364
+ this._populate = populate;
365
+ this._populateWhere = populateWhere;
366
+ return this;
367
+ }
368
+ limit(limit, offset = 0) {
369
+ this.ensureNotFinalized();
370
+ this._limit = limit;
371
+ if (offset) {
372
+ this.offset(offset);
373
+ }
374
+ return this;
375
+ }
376
+ offset(offset) {
377
+ this.ensureNotFinalized();
378
+ this._offset = offset;
379
+ return this;
380
+ }
381
+ withSchema(schema) {
382
+ this.ensureNotFinalized();
383
+ this._schema = schema;
384
+ return this;
385
+ }
386
+ setLockMode(mode, tables) {
387
+ this.ensureNotFinalized();
388
+ if (mode != null && mode !== core_1.LockMode.OPTIMISTIC && !this.context) {
389
+ throw core_1.ValidationError.transactionRequired();
390
+ }
391
+ this.lockMode = mode;
392
+ this.lockTables = tables;
393
+ return this;
394
+ }
395
+ setFlushMode(flushMode) {
396
+ this.ensureNotFinalized();
397
+ this.flushMode = flushMode;
398
+ return this;
399
+ }
400
+ setFlag(flag) {
401
+ this.ensureNotFinalized();
402
+ this.flags.add(flag);
403
+ return this;
404
+ }
405
+ unsetFlag(flag) {
406
+ this.ensureNotFinalized();
407
+ this.flags.delete(flag);
408
+ return this;
409
+ }
410
+ hasFlag(flag) {
411
+ return this.flags.has(flag);
412
+ }
413
+ cache(config = true) {
414
+ this.ensureNotFinalized();
415
+ this._cache = config;
416
+ return this;
417
+ }
418
+ /**
419
+ * Adds index hint to the FROM clause.
420
+ */
421
+ indexHint(sql) {
422
+ this.ensureNotFinalized();
423
+ this._indexHint = sql;
424
+ return this;
425
+ }
426
+ /**
427
+ * Prepend comment to the sql query using the syntax `/* ... *&#8205;/`. Some characters are forbidden such as `/*, *&#8205;/` and `?`.
428
+ */
429
+ comment(comment) {
430
+ this.ensureNotFinalized();
431
+ this._comments.push(...core_1.Utils.asArray(comment));
432
+ return this;
433
+ }
434
+ /**
435
+ * Add hints to the query using comment-like syntax `/*+ ... *&#8205;/`. MySQL and Oracle use this syntax for optimizer hints.
436
+ * Also various DB proxies and routers use this syntax to pass hints to alter their behavior. In other dialects the hints
437
+ * are ignored as simple comments.
438
+ */
439
+ hintComment(comment) {
440
+ this.ensureNotFinalized();
441
+ this._hintComments.push(...core_1.Utils.asArray(comment));
442
+ return this;
443
+ }
444
+ from(target, aliasName) {
445
+ this.ensureNotFinalized();
446
+ if (target instanceof QueryBuilder) {
447
+ this.fromSubQuery(target, aliasName);
448
+ }
449
+ else {
450
+ const entityName = core_1.Utils.className(target);
451
+ if (aliasName && this._mainAlias && entityName !== this._mainAlias.aliasName) {
452
+ throw new Error(`Cannot override the alias to '${aliasName}' since a query already contains references to '${this._mainAlias.aliasName}'`);
453
+ }
454
+ this.fromEntityName(entityName, aliasName);
455
+ }
456
+ return this;
457
+ }
458
+ getKnexQuery() {
459
+ this.finalize();
460
+ const qb = this.getQueryBase();
461
+ const type = this.type ?? enums_1.QueryType.SELECT;
462
+ qb.__raw = true; // tag it as there is now way to check via `instanceof`
463
+ core_1.Utils.runIfNotEmpty(() => this.helper.appendQueryCondition(type, this._cond, qb), this._cond && !this._onConflict);
464
+ core_1.Utils.runIfNotEmpty(() => qb.groupBy(this.prepareFields(this._groupBy, 'groupBy')), this._groupBy);
465
+ core_1.Utils.runIfNotEmpty(() => this.helper.appendQueryCondition(type, this._having, qb, undefined, 'having'), this._having);
466
+ core_1.Utils.runIfNotEmpty(() => {
467
+ const queryOrder = this.helper.getQueryOrder(type, this._orderBy, this._populateMap);
468
+ if (queryOrder.length > 0) {
469
+ const sql = core_1.Utils.unique(queryOrder).join(', ');
470
+ qb.orderByRaw(sql);
471
+ return;
472
+ }
473
+ }, this._orderBy);
474
+ core_1.Utils.runIfNotEmpty(() => qb.limit(this._limit), this._limit != null);
475
+ core_1.Utils.runIfNotEmpty(() => qb.offset(this._offset), this._offset);
476
+ core_1.Utils.runIfNotEmpty(() => this._comments.forEach(comment => qb.comment(comment)), this._comments);
477
+ core_1.Utils.runIfNotEmpty(() => this._hintComments.forEach(comment => qb.hintComment(comment)), this._hintComments);
478
+ core_1.Utils.runIfNotEmpty(() => this.helper.appendOnConflictClause(type, this._onConflict, qb), this._onConflict);
479
+ if (this.type === enums_1.QueryType.TRUNCATE && this.platform.usesCascadeStatement()) {
480
+ return this.knex.raw(qb.toSQL().toNative().sql + ' cascade');
481
+ }
482
+ if (this.lockMode) {
483
+ this.helper.getLockSQL(qb, this.lockMode, this.lockTables);
484
+ }
485
+ this.helper.finalize(type, qb, this.mainAlias.metadata, this._data, this._returning);
486
+ return qb;
487
+ }
488
+ /**
489
+ * Returns the query with parameters as wildcards.
490
+ */
491
+ getQuery() {
492
+ return this.toQuery().sql;
493
+ }
494
+ #query;
495
+ toQuery() {
496
+ if (this.#query) {
497
+ return this.#query;
498
+ }
499
+ const sql = this.getKnexQuery().toSQL();
500
+ const query = sql.toNative();
501
+ return this.#query = { sql: query.sql, params: query.bindings ?? [], _sql: sql };
502
+ }
503
+ /**
504
+ * Returns the list of all parameters for this query.
505
+ */
506
+ getParams() {
507
+ return this.toQuery().params;
508
+ }
509
+ /**
510
+ * Returns raw interpolated query string with all the parameters inlined.
511
+ */
512
+ getFormattedQuery() {
513
+ const query = this.toQuery()._sql;
514
+ return this.platform.formatQuery(query.sql, query.bindings);
515
+ }
516
+ /**
517
+ * @internal
518
+ */
519
+ getAliasForJoinPath(path, options) {
520
+ if (!path || path === this.mainAlias.entityName) {
521
+ return this.mainAlias.aliasName;
522
+ }
523
+ const join = typeof path === 'string' ? this.getJoinForPath(path, options) : path;
524
+ if (join?.path?.endsWith('[pivot]')) {
525
+ return join.alias;
526
+ }
527
+ return join?.inverseAlias || join?.alias;
528
+ }
529
+ /**
530
+ * @internal
531
+ */
532
+ getJoinForPath(path, options) {
533
+ const joins = Object.values(this._joins);
534
+ if (joins.length === 0) {
535
+ return undefined;
536
+ }
537
+ let join = joins.find(j => j.path === path);
538
+ if (options?.preferNoBranch) {
539
+ join = joins.find(j => {
540
+ return j.path?.replace(/\[\d+]|\[populate]/g, '') === path.replace(/\[\d+]|\[populate]/g, '');
541
+ });
542
+ }
543
+ if (!join && options?.ignoreBranching) {
544
+ join = joins.find(j => {
545
+ return j.path?.replace(/\[\d+]/g, '') === path.replace(/\[\d+]/g, '');
546
+ });
547
+ }
548
+ if (!join && options?.matchPopulateJoins && options?.ignoreBranching) {
549
+ join = joins.find(j => {
550
+ return j.path?.replace(/\[\d+]|\[populate]/g, '') === path.replace(/\[\d+]|\[populate]/g, '');
551
+ });
552
+ }
553
+ if (!join && options?.matchPopulateJoins) {
554
+ join = joins.find(j => {
555
+ return j.path?.replace(/\[populate]/g, '') === path.replace(/\[populate]/g, '');
556
+ });
557
+ }
558
+ return join;
559
+ }
560
+ /**
561
+ * @internal
562
+ */
563
+ getNextAlias(entityName = 'e') {
564
+ return this.driver.config.getNamingStrategy().aliasName(entityName, this.aliasCounter++);
565
+ }
566
+ /**
567
+ * @internal
568
+ */
569
+ getAliasMap() {
570
+ return Object.fromEntries(Object.entries(this._aliases).map(([key, value]) => [key, value.entityName]));
571
+ }
572
+ /**
573
+ * Executes this QB and returns the raw results, mapped to the property names (unless disabled via last parameter).
574
+ * Use `method` to specify what kind of result you want to get (array/single/meta).
575
+ */
576
+ async execute(method = 'all', options) {
577
+ options = typeof options === 'boolean' ? { mapResults: options } : (options ?? {});
578
+ options.mergeResults ??= true;
579
+ options.mapResults ??= true;
580
+ if (!this.connectionType && method !== 'run' && [enums_1.QueryType.INSERT, enums_1.QueryType.UPDATE, enums_1.QueryType.DELETE, enums_1.QueryType.TRUNCATE].includes(this.type ?? enums_1.QueryType.SELECT)) {
581
+ this.connectionType = 'write';
582
+ }
583
+ const query = this.getKnexQuery().toSQL();
584
+ const cached = await this.em?.tryCache(this.mainAlias.entityName, this._cache, ['qb.execute', query.sql, query.bindings, method]);
585
+ if (cached?.data) {
586
+ return cached.data;
587
+ }
588
+ const write = method === 'run' || !this.platform.getConfig().get('preferReadReplicas');
589
+ const type = this.connectionType || (write ? 'write' : 'read');
590
+ const res = await this.driver.getConnection(type).execute(query.sql, query.bindings, method, this.context, this.logging);
591
+ const meta = this.mainAlias.metadata;
592
+ if (!options.mapResults || !meta) {
593
+ await this.em?.storeCache(this._cache, cached, res);
594
+ return res;
595
+ }
596
+ if (method === 'run') {
597
+ return res;
598
+ }
599
+ const joinedProps = this.driver.joinedProps(meta, this._populate);
600
+ let mapped;
601
+ if (Array.isArray(res)) {
602
+ const map = {};
603
+ mapped = res.map(r => this.driver.mapResult(r, meta, this._populate, this, map));
604
+ if (options.mergeResults && joinedProps.length > 0) {
605
+ mapped = this.driver.mergeJoinedResult(mapped, this.mainAlias.metadata, joinedProps);
606
+ }
607
+ }
608
+ else {
609
+ mapped = [this.driver.mapResult(res, meta, joinedProps, this)];
610
+ }
611
+ await this.em?.storeCache(this._cache, cached, mapped);
612
+ if (method === 'get') {
613
+ return mapped[0];
614
+ }
615
+ return mapped;
616
+ }
617
+ /**
618
+ * Alias for `qb.getResultList()`
619
+ */
620
+ async getResult() {
621
+ return this.getResultList();
622
+ }
623
+ /**
624
+ * Executes the query, returning array of results
625
+ */
626
+ async getResultList() {
627
+ await this.em.tryFlush(this.mainAlias.entityName, { flushMode: this.flushMode });
628
+ const res = await this.execute('all', true);
629
+ const entities = [];
630
+ function propagatePopulateHint(entity, hint) {
631
+ (0, core_1.helper)(entity).__serializationContext.populate ??= hint;
632
+ hint.forEach(hint => {
633
+ const [propName] = hint.field.split(':', 2);
634
+ const value = entity[propName];
635
+ if (core_1.Utils.isEntity(value, true)) {
636
+ (0, core_1.helper)(value).populated();
637
+ propagatePopulateHint(value, hint.children ?? []);
638
+ }
639
+ else if (core_1.Utils.isCollection(value)) {
640
+ value.populated();
641
+ value.getItems(false).forEach(item => propagatePopulateHint(item, hint.children ?? []));
642
+ }
643
+ });
644
+ }
645
+ for (const r of res) {
646
+ const entity = this.em.map(this.mainAlias.entityName, r, { schema: this._schema });
647
+ propagatePopulateHint(entity, this._populate);
648
+ entities.push(entity);
649
+ }
650
+ return entities;
651
+ }
652
+ /**
653
+ * Executes the query, returning the first result or null
654
+ */
655
+ async getSingleResult() {
656
+ const res = await this.getResultList();
657
+ return res[0] || null;
658
+ }
659
+ /**
660
+ * Executes count query (without offset and limit), returning total count of results
661
+ */
662
+ async getCount(field, distinct) {
663
+ let res;
664
+ if (this.type === enums_1.QueryType.COUNT) {
665
+ res = await this.execute('get', false);
666
+ }
667
+ else {
668
+ const qb = this.type === undefined ? this : this.clone();
669
+ qb.count(field, distinct ?? qb.hasToManyJoins()).limit(undefined).offset(undefined).orderBy([]);
670
+ res = await qb.execute('get', false);
671
+ }
672
+ return res ? +res.count : 0;
673
+ }
674
+ /**
675
+ * Executes the query, returning both array of results and total count query (without offset and limit).
676
+ */
677
+ async getResultAndCount() {
678
+ return Promise.all([
679
+ this.getResultList(),
680
+ this.getCount(),
681
+ ]);
682
+ }
683
+ /**
684
+ * Provides promise-like interface so we can await the QB instance.
685
+ */
686
+ then(onfulfilled, onrejected) {
687
+ let type = this.type ?? enums_1.QueryType.SELECT;
688
+ if (this.flags.has(core_1.QueryFlag.UPDATE_SUB_QUERY) || this.flags.has(core_1.QueryFlag.DELETE_SUB_QUERY)) {
689
+ type = enums_1.QueryType.UPDATE;
690
+ }
691
+ switch (type) {
692
+ case enums_1.QueryType.INSERT:
693
+ case enums_1.QueryType.UPDATE:
694
+ case enums_1.QueryType.DELETE:
695
+ case enums_1.QueryType.TRUNCATE:
696
+ return this.execute('run').then(onfulfilled, onrejected);
697
+ case enums_1.QueryType.COUNT:
698
+ return this.getCount().then(onfulfilled, onrejected);
699
+ case enums_1.QueryType.SELECT: return this.getResultList().then(onfulfilled, onrejected);
700
+ }
701
+ }
702
+ /**
703
+ * Returns knex instance with sub-query aliased with given alias.
704
+ * You can provide `EntityName.propName` as alias, then the field name will be used based on the metadata
705
+ */
706
+ as(alias) {
707
+ const qb = this.getKnexQuery();
708
+ if (alias.includes('.')) {
709
+ const [a, f] = alias.split('.');
710
+ const meta = this.metadata.find(a);
711
+ /* istanbul ignore next */
712
+ alias = meta?.properties[f]?.fieldNames[0] ?? alias;
713
+ }
714
+ const ret = qb.as(alias);
715
+ // tag the instance, so it is possible to detect it easily
716
+ Object.defineProperty(ret, '__as', { enumerable: false, value: alias });
717
+ return ret;
718
+ }
719
+ clone(reset) {
720
+ const qb = new QueryBuilder(this.mainAlias.entityName, this.metadata, this.driver, this.context, this.mainAlias.aliasName, this.connectionType, this.em);
721
+ if (reset) {
722
+ return qb;
723
+ }
724
+ Object.assign(qb, this);
725
+ // clone array/object properties
726
+ const properties = [
727
+ 'flags', '_populate', '_populateWhere', '__populateWhere', '_populateMap', '_joins', '_joinedProps', '_cond', '_data', '_orderBy',
728
+ '_schema', '_indexHint', '_cache', 'subQueries', 'lockMode', 'lockTables', '_groupBy', '_having', '_returning',
729
+ '_comments', '_hintComments',
730
+ ];
731
+ properties.forEach(prop => qb[prop] = core_1.Utils.copy(this[prop]));
732
+ /* istanbul ignore else */
733
+ if (this._fields) {
734
+ qb._fields = [...this._fields];
735
+ }
736
+ qb._aliases = { ...this._aliases };
737
+ qb.finalized = false;
738
+ return qb;
739
+ }
740
+ getKnex() {
741
+ const qb = this.knex.queryBuilder();
742
+ const { subQuery, aliasName, entityName } = this.mainAlias;
743
+ const ref = subQuery ? subQuery : this.knex.ref(this.helper.getTableName(entityName));
744
+ if (this.finalized && (this._explicitAlias || this.helper.isTableNameAliasRequired(this.type))) {
745
+ ref.as(aliasName);
746
+ }
747
+ const schema = this.getSchema(this.mainAlias);
748
+ if (schema) {
749
+ ref.withSchema(schema);
750
+ }
751
+ qb.from(ref);
752
+ if (this.context) {
753
+ qb.transacting(this.context);
754
+ }
755
+ return qb;
756
+ }
757
+ joinReference(field, alias, cond, type, path, schema, subquery) {
758
+ this.ensureNotFinalized();
759
+ if (typeof field === 'object') {
760
+ const prop = {
761
+ name: '__subquery__',
762
+ kind: core_1.ReferenceKind.MANY_TO_ONE,
763
+ };
764
+ if (field instanceof QueryBuilder) {
765
+ prop.type = field.mainAlias.entityName;
766
+ prop.targetMeta = field.mainAlias.metadata;
767
+ field = field.getKnexQuery();
768
+ }
769
+ this._joins[`${this.alias}.${prop.name}#${alias}`] = {
770
+ prop,
771
+ alias,
772
+ type,
773
+ cond,
774
+ schema,
775
+ subquery: field.toString(),
776
+ ownerAlias: this.alias,
777
+ };
778
+ return prop;
779
+ }
780
+ if (!subquery && type.includes('lateral')) {
781
+ throw new Error(`Lateral join can be used only with a sub-query.`);
782
+ }
783
+ const [fromAlias, fromField] = this.helper.splitField(field);
784
+ const q = (str) => `'${str}'`;
785
+ if (!this._aliases[fromAlias]) {
786
+ throw new Error(`Trying to join ${q(fromField)} with alias ${q(fromAlias)}, but ${q(fromAlias)} is not a known alias. Available aliases are: ${Object.keys(this._aliases).map(q).join(', ')}.`);
787
+ }
788
+ const entityName = this._aliases[fromAlias].entityName;
789
+ const meta = this.metadata.get(entityName);
790
+ const prop = meta.properties[fromField];
791
+ if (!prop) {
792
+ throw new Error(`Trying to join ${q(field)}, but ${q(fromField)} is not a defined relation on ${meta.className}.`);
793
+ }
794
+ this.createAlias(prop.type, alias);
795
+ cond = core_1.QueryHelper.processWhere({
796
+ where: cond,
797
+ entityName: this.mainAlias.entityName,
798
+ metadata: this.metadata,
799
+ platform: this.platform,
800
+ aliasMap: this.getAliasMap(),
801
+ aliased: !this.type || [enums_1.QueryType.SELECT, enums_1.QueryType.COUNT].includes(this.type),
802
+ });
803
+ let aliasedName = `${fromAlias}.${prop.name}#${alias}`;
804
+ path ??= `${(Object.values(this._joins).find(j => j.alias === fromAlias)?.path ?? entityName)}.${prop.name}`;
805
+ if (prop.kind === core_1.ReferenceKind.ONE_TO_MANY) {
806
+ this._joins[aliasedName] = this.helper.joinOneToReference(prop, fromAlias, alias, type, cond, schema);
807
+ }
808
+ else if (prop.kind === core_1.ReferenceKind.MANY_TO_MANY) {
809
+ let pivotAlias = alias;
810
+ if (type !== enums_1.JoinType.pivotJoin) {
811
+ const oldPivotAlias = this.getAliasForJoinPath(path + '[pivot]');
812
+ pivotAlias = oldPivotAlias ?? this.getNextAlias(prop.pivotEntity);
813
+ aliasedName = `${fromAlias}.${prop.name}#${pivotAlias}`;
814
+ }
815
+ const joins = this.helper.joinManyToManyReference(prop, fromAlias, alias, pivotAlias, type, cond, path, schema);
816
+ Object.assign(this._joins, joins);
817
+ this.createAlias(prop.pivotEntity, pivotAlias);
818
+ }
819
+ else if (prop.kind === core_1.ReferenceKind.ONE_TO_ONE) {
820
+ this._joins[aliasedName] = this.helper.joinOneToReference(prop, fromAlias, alias, type, cond, schema);
821
+ }
822
+ else { // MANY_TO_ONE
823
+ this._joins[aliasedName] = this.helper.joinManyToOneReference(prop, fromAlias, alias, type, cond, schema);
824
+ }
825
+ if (!this._joins[aliasedName].path && path) {
826
+ this._joins[aliasedName].path = path;
827
+ }
828
+ return prop;
829
+ }
830
+ prepareFields(fields, type = 'where') {
831
+ const ret = [];
832
+ const getFieldName = (name) => {
833
+ if (type === 'groupBy') {
834
+ return this.helper.mapper(name, this.type, undefined, null);
835
+ }
836
+ return this.helper.mapper(name, this.type);
837
+ };
838
+ fields.forEach(field => {
839
+ const rawField = core_1.RawQueryFragment.getKnownFragment(field);
840
+ if (rawField) {
841
+ const sql = this.platform.formatQuery(rawField.sql, rawField.params);
842
+ ret.push(this.knex.raw(sql));
843
+ return;
844
+ }
845
+ if (!core_1.Utils.isString(field)) {
846
+ ret.push(field);
847
+ return;
848
+ }
849
+ const join = Object.keys(this._joins).find(k => field === k.substring(0, k.indexOf('#')));
850
+ if (join && type === 'where') {
851
+ ret.push(...this.helper.mapJoinColumns(this.type ?? enums_1.QueryType.SELECT, this._joins[join]));
852
+ return;
853
+ }
854
+ const [a, f] = this.helper.splitField(field);
855
+ const prop = this.helper.getProperty(f, a);
856
+ /* istanbul ignore next */
857
+ if (prop && [core_1.ReferenceKind.ONE_TO_MANY, core_1.ReferenceKind.MANY_TO_MANY].includes(prop.kind)) {
858
+ return;
859
+ }
860
+ if (prop?.embedded) {
861
+ const name = prop.embeddedPath?.join('.') ?? prop.fieldNames[0];
862
+ const aliased = this._aliases[a] ? `${a}.${name}` : name;
863
+ ret.push(getFieldName(aliased));
864
+ return;
865
+ }
866
+ if (prop?.kind === core_1.ReferenceKind.EMBEDDED) {
867
+ if (prop.object) {
868
+ ret.push(getFieldName(prop.fieldNames[0]));
869
+ }
870
+ else {
871
+ const nest = (prop) => {
872
+ for (const childProp of Object.values(prop.embeddedProps)) {
873
+ if (childProp.fieldNames && (childProp.kind !== core_1.ReferenceKind.EMBEDDED || childProp.object) && childProp.persist !== false) {
874
+ ret.push(getFieldName(childProp.fieldNames[0]));
875
+ }
876
+ else {
877
+ nest(childProp);
878
+ }
879
+ }
880
+ };
881
+ nest(prop);
882
+ }
883
+ return;
884
+ }
885
+ if (prop && prop.fieldNames.length > 1) {
886
+ ret.push(...prop.fieldNames.map(f => getFieldName(f)));
887
+ return;
888
+ }
889
+ ret.push(getFieldName(field));
890
+ });
891
+ const meta = this.mainAlias.metadata;
892
+ /* istanbul ignore next */
893
+ const requiresSQLConversion = meta?.props.filter(p => p.hasConvertToJSValueSQL && p.persist !== false) ?? [];
894
+ if (this.flags.has(core_1.QueryFlag.CONVERT_CUSTOM_TYPES) && (fields.includes('*') || fields.includes(`${this.mainAlias.aliasName}.*`)) && requiresSQLConversion.length > 0) {
895
+ requiresSQLConversion.forEach(p => ret.push(this.helper.mapper(p.name, this.type)));
896
+ }
897
+ Object.keys(this._populateMap).forEach(f => {
898
+ if (!fields.includes(f.replace(/#\w+$/, '')) && type === 'where') {
899
+ const cols = this.helper.mapJoinColumns(this.type ?? enums_1.QueryType.SELECT, this._joins[f]);
900
+ ret.push(...cols);
901
+ }
902
+ });
903
+ return ret;
904
+ }
905
+ init(type, data, cond) {
906
+ this.ensureNotFinalized();
907
+ this.type = type;
908
+ if ([enums_1.QueryType.UPDATE, enums_1.QueryType.DELETE].includes(type) && core_1.Utils.hasObjectKeys(this._cond)) {
909
+ throw new Error(`You are trying to call \`qb.where().${type.toLowerCase()}()\`. Calling \`qb.${type.toLowerCase()}()\` before \`qb.where()\` is required.`);
910
+ }
911
+ if (!this.helper.isTableNameAliasRequired(type)) {
912
+ delete this._fields;
913
+ }
914
+ if (data) {
915
+ if (core_1.Utils.isEntity(data)) {
916
+ data = this.em?.getComparator().prepareEntity(data) ?? (0, core_1.serialize)(data);
917
+ }
918
+ this._data = this.helper.processData(data, this.flags.has(core_1.QueryFlag.CONVERT_CUSTOM_TYPES), false);
919
+ }
920
+ if (cond) {
921
+ this.where(cond);
922
+ }
923
+ return this;
924
+ }
925
+ getQueryBase() {
926
+ const qb = this.getKnex();
927
+ const schema = this.getSchema(this.mainAlias);
928
+ // Joined tables doesn't need to belong to the same schema as the main table
929
+ const joinSchema = this._schema ?? this.em?.schema ?? schema;
930
+ if (schema) {
931
+ qb.withSchema(schema);
932
+ }
933
+ if (this._indexHint) {
934
+ const alias = this.helper.isTableNameAliasRequired(this.type) ? ` as ${this.platform.quoteIdentifier(this.mainAlias.aliasName)}` : '';
935
+ const schemaQuoted = schema ? this.platform.quoteIdentifier(schema) + '.' : '';
936
+ const tableName = schemaQuoted + this.platform.quoteIdentifier(this.helper.getTableName(this.mainAlias.entityName)) + alias;
937
+ qb.from(this.knex.raw(`${tableName} ${this._indexHint}`));
938
+ }
939
+ switch (this.type) {
940
+ case enums_1.QueryType.SELECT:
941
+ qb.select(this.prepareFields(this._fields));
942
+ if (this._distinctOn) {
943
+ qb.distinctOn(this._distinctOn);
944
+ }
945
+ else if (this.flags.has(core_1.QueryFlag.DISTINCT)) {
946
+ qb.distinct();
947
+ }
948
+ this.helper.processJoins(qb, this._joins, joinSchema);
949
+ break;
950
+ case enums_1.QueryType.COUNT: {
951
+ const m = this.flags.has(core_1.QueryFlag.DISTINCT) ? 'countDistinct' : 'count';
952
+ qb[m]({ count: this._fields.map(f => this.helper.mapper(f, this.type)) });
953
+ this.helper.processJoins(qb, this._joins, joinSchema);
954
+ break;
955
+ }
956
+ case enums_1.QueryType.INSERT:
957
+ qb.insert(this._data);
958
+ break;
959
+ case enums_1.QueryType.UPDATE:
960
+ qb.update(this._data);
961
+ this.helper.updateVersionProperty(qb, this._data);
962
+ break;
963
+ case enums_1.QueryType.DELETE:
964
+ qb.delete();
965
+ break;
966
+ case enums_1.QueryType.TRUNCATE:
967
+ qb.truncate();
968
+ break;
969
+ }
970
+ return qb;
971
+ }
972
+ applyDiscriminatorCondition() {
973
+ const meta = this.mainAlias.metadata;
974
+ if (!meta?.discriminatorValue) {
975
+ return;
976
+ }
977
+ const types = Object.values(meta.root.discriminatorMap).map(cls => this.metadata.find(cls));
978
+ const children = [];
979
+ const lookUpChildren = (ret, type) => {
980
+ const children = types.filter(meta2 => meta2.extends === type);
981
+ children.forEach(m => lookUpChildren(ret, m.className));
982
+ ret.push(...children.filter(c => c.discriminatorValue));
983
+ return children;
984
+ };
985
+ lookUpChildren(children, meta.className);
986
+ this.andWhere({
987
+ [meta.root.discriminatorColumn]: children.length > 0 ? { $in: [meta.discriminatorValue, ...children.map(c => c.discriminatorValue)] } : meta.discriminatorValue,
988
+ });
989
+ }
990
+ finalize() {
991
+ if (this.finalized) {
992
+ return;
993
+ }
994
+ if (!this.type) {
995
+ this.select('*');
996
+ }
997
+ const meta = this.mainAlias.metadata;
998
+ this.applyDiscriminatorCondition();
999
+ if (meta && this.flags.has(core_1.QueryFlag.AUTO_JOIN_ONE_TO_ONE_OWNER)) {
1000
+ const relationsToPopulate = this._populate.map(({ field }) => field);
1001
+ meta.relations
1002
+ .filter(prop => prop.kind === core_1.ReferenceKind.ONE_TO_ONE && !prop.owner && !relationsToPopulate.includes(prop.name) && !relationsToPopulate.includes(`${prop.name}:ref`))
1003
+ .map(prop => ({ field: `${prop.name}:ref` }))
1004
+ .forEach(item => this._populate.push(item));
1005
+ }
1006
+ this._populate.forEach(({ field }) => {
1007
+ const [fromAlias, fromField] = this.helper.splitField(field);
1008
+ const aliasedField = `${fromAlias}.${fromField}`;
1009
+ const join = Object.keys(this._joins).find(k => `${aliasedField}#${this._joins[k].alias}` === k);
1010
+ if (join && this._joins[join] && this.helper.isOneToOneInverse(fromField)) {
1011
+ this._populateMap[join] = this._joins[join].alias;
1012
+ return;
1013
+ }
1014
+ if (meta && this.helper.isOneToOneInverse(fromField)) {
1015
+ const prop = meta.properties[fromField];
1016
+ const alias = this.getNextAlias(prop.pivotEntity ?? prop.type);
1017
+ const aliasedName = `${fromAlias}.${prop.name}#${alias}`;
1018
+ this._joins[aliasedName] = this.helper.joinOneToReference(prop, this.mainAlias.aliasName, alias, enums_1.JoinType.leftJoin);
1019
+ this._populateMap[aliasedName] = this._joins[aliasedName].alias;
1020
+ }
1021
+ });
1022
+ if (meta && (this._fields?.includes('*') || this._fields?.includes(`${this.mainAlias.aliasName}.*`))) {
1023
+ meta.props
1024
+ .filter(prop => prop.formula && (!prop.lazy || this.flags.has(core_1.QueryFlag.INCLUDE_LAZY_FORMULAS)))
1025
+ .map(prop => {
1026
+ const alias = this.knex.ref(this.mainAlias.aliasName).toString();
1027
+ const aliased = this.knex.ref(prop.fieldNames[0]).toString();
1028
+ return `${prop.formula(alias)} as ${aliased}`;
1029
+ })
1030
+ .filter(field => !this._fields.some(f => {
1031
+ if (f instanceof core_1.RawQueryFragment) {
1032
+ return f.sql === field && f.params.length === 0;
1033
+ }
1034
+ return f === field;
1035
+ }))
1036
+ .forEach(field => this._fields.push((0, core_1.raw)(field)));
1037
+ }
1038
+ this.processPopulateWhere();
1039
+ core_1.QueryHelper.processObjectParams(this._data);
1040
+ core_1.QueryHelper.processObjectParams(this._cond);
1041
+ core_1.QueryHelper.processObjectParams(this._having);
1042
+ // automatically enable paginate flag when we detect to-many joins, but only if there is no `group by` clause
1043
+ if (!this.flags.has(core_1.QueryFlag.DISABLE_PAGINATE) && this._groupBy.length === 0 && this.hasToManyJoins()) {
1044
+ this.flags.add(core_1.QueryFlag.PAGINATE);
1045
+ }
1046
+ if (meta && this.flags.has(core_1.QueryFlag.PAGINATE) && (this._limit > 0 || this._offset > 0)) {
1047
+ this.wrapPaginateSubQuery(meta);
1048
+ }
1049
+ if (meta && (this.flags.has(core_1.QueryFlag.UPDATE_SUB_QUERY) || this.flags.has(core_1.QueryFlag.DELETE_SUB_QUERY))) {
1050
+ this.wrapModifySubQuery(meta);
1051
+ }
1052
+ this.finalized = true;
1053
+ }
1054
+ processPopulateWhere() {
1055
+ if (this._populateWhere == null || this._populateWhere === core_1.PopulateHint.ALL) {
1056
+ return;
1057
+ }
1058
+ const joins = Object.values(this._joins);
1059
+ joins.forEach(join => {
1060
+ join.cond_ = join.cond;
1061
+ join.cond = {};
1062
+ });
1063
+ const replaceOnConditions = (cond) => {
1064
+ Object.keys(cond).forEach(k => {
1065
+ if (core_1.Utils.isOperator(k)) {
1066
+ if (Array.isArray(cond[k])) {
1067
+ return cond[k].forEach((c) => replaceOnConditions(c));
1068
+ }
1069
+ return replaceOnConditions(cond[k]);
1070
+ }
1071
+ const [alias] = this.helper.splitField(k);
1072
+ const join = joins.find(j => j.alias === alias);
1073
+ if (join) {
1074
+ join.cond = { ...join.cond, [k]: cond[k] };
1075
+ }
1076
+ });
1077
+ };
1078
+ if (typeof this._populateWhere === 'object') {
1079
+ const cond = CriteriaNodeFactory_1.CriteriaNodeFactory
1080
+ .createNode(this.metadata, this.mainAlias.entityName, this._populateWhere)
1081
+ .process(this, { matchPopulateJoins: true, ignoreBranching: true, preferNoBranch: true });
1082
+ replaceOnConditions(cond);
1083
+ }
1084
+ }
1085
+ hasToManyJoins() {
1086
+ return Object.values(this._joins).some(join => {
1087
+ return [core_1.ReferenceKind.ONE_TO_MANY, core_1.ReferenceKind.MANY_TO_MANY].includes(join.prop.kind);
1088
+ });
1089
+ }
1090
+ wrapPaginateSubQuery(meta) {
1091
+ const pks = this.prepareFields(meta.primaryKeys, 'sub-query');
1092
+ const subQuery = this.clone().select(pks).groupBy(pks).limit(this._limit);
1093
+ // revert the on conditions added via populateWhere, we want to apply those only once
1094
+ Object.values(subQuery._joins).forEach(join => join.cond = join.cond_ ?? {});
1095
+ if (this._offset) {
1096
+ subQuery.offset(this._offset);
1097
+ }
1098
+ const addToSelect = [];
1099
+ if (this._orderBy.length > 0) {
1100
+ const orderBy = [];
1101
+ for (const orderMap of this._orderBy) {
1102
+ for (const [field, direction] of Object.entries(orderMap)) {
1103
+ const [a, f] = this.helper.splitField(field);
1104
+ const prop = this.helper.getProperty(f, a);
1105
+ const type = this.platform.castColumn(prop);
1106
+ const fieldName = this.helper.mapper(field, this.type, undefined, null);
1107
+ if (!prop?.persist && !prop?.formula) {
1108
+ addToSelect.push(fieldName);
1109
+ }
1110
+ orderBy.push({ [(0, core_1.raw)(`min(${this.knex.ref(fieldName)}${type})`)]: direction });
1111
+ }
1112
+ }
1113
+ subQuery.orderBy(orderBy);
1114
+ }
1115
+ subQuery.finalized = true;
1116
+ const knexQuery = subQuery.as(this.mainAlias.aliasName).clearSelect().select(pks);
1117
+ if (addToSelect.length > 0) {
1118
+ addToSelect.forEach(prop => {
1119
+ const field = this._fields.find(field => {
1120
+ if (typeof field === 'object' && field && '__as' in field) {
1121
+ return field.__as === prop;
1122
+ }
1123
+ // not perfect, but should work most of the time, ideally we should check only the alias (`... as alias`)
1124
+ return field.toString().includes(prop);
1125
+ });
1126
+ if (field) {
1127
+ knexQuery.select(field);
1128
+ }
1129
+ });
1130
+ }
1131
+ // multiple sub-queries are needed to get around mysql limitations with order by + limit + where in + group by (o.O)
1132
+ // https://stackoverflow.com/questions/17892762/mysql-this-version-of-mysql-doesnt-yet-support-limit-in-all-any-some-subqu
1133
+ const subSubQuery = this.getKnex().select(pks).from(knexQuery);
1134
+ subSubQuery.__raw = true; // tag it as there is now way to check via `instanceof`
1135
+ this._limit = undefined;
1136
+ this._offset = undefined;
1137
+ this.select(this._fields).where({ [core_1.Utils.getPrimaryKeyHash(meta.primaryKeys)]: { $in: subSubQuery } });
1138
+ }
1139
+ wrapModifySubQuery(meta) {
1140
+ const subQuery = this.clone();
1141
+ subQuery.finalized = true;
1142
+ // wrap one more time to get around MySQL limitations
1143
+ // https://stackoverflow.com/questions/45494/mysql-error-1093-cant-specify-target-table-for-update-in-from-clause
1144
+ const subSubQuery = this.getKnex().select(this.prepareFields(meta.primaryKeys)).from(subQuery.as(this.mainAlias.aliasName));
1145
+ const method = this.flags.has(core_1.QueryFlag.UPDATE_SUB_QUERY) ? 'update' : 'delete';
1146
+ this._cond = {}; // otherwise we would trigger validation error
1147
+ this[method](this._data).where({
1148
+ [core_1.Utils.getPrimaryKeyHash(meta.primaryKeys)]: { $in: subSubQuery },
1149
+ });
1150
+ }
1151
+ getSchema(alias) {
1152
+ const { metadata } = alias;
1153
+ const metaSchema = metadata?.schema && metadata.schema !== '*' ? metadata.schema : undefined;
1154
+ return this._schema ?? metaSchema ?? this.em?.schema ?? this.em?.config.get('schema');
1155
+ }
1156
+ createAlias(entityName, aliasName, subQuery) {
1157
+ const metadata = this.metadata.find(entityName);
1158
+ const alias = { aliasName, entityName, metadata, subQuery };
1159
+ this._aliases[aliasName] = alias;
1160
+ return alias;
1161
+ }
1162
+ createMainAlias(entityName, aliasName, subQuery) {
1163
+ this._mainAlias = this.createAlias(entityName, aliasName, subQuery);
1164
+ this._helper = this.createQueryBuilderHelper();
1165
+ return this._mainAlias;
1166
+ }
1167
+ fromSubQuery(target, aliasName) {
1168
+ const subQuery = target.getKnexQuery();
1169
+ const { entityName } = target.mainAlias;
1170
+ aliasName ??= this.getNextAlias(entityName);
1171
+ this.createMainAlias(entityName, aliasName, subQuery);
1172
+ }
1173
+ fromEntityName(entityName, aliasName) {
1174
+ aliasName ??= this._mainAlias?.aliasName ?? this.getNextAlias(entityName);
1175
+ this.createMainAlias(entityName, aliasName);
1176
+ }
1177
+ createQueryBuilderHelper() {
1178
+ return new QueryBuilderHelper_1.QueryBuilderHelper(this.mainAlias.entityName, this.mainAlias.aliasName, this._aliases, this.subQueries, this.knex, this.driver);
1179
+ }
1180
+ ensureFromClause() {
1181
+ /* istanbul ignore next */
1182
+ if (!this._mainAlias) {
1183
+ throw new Error(`Cannot proceed to build a query because the main alias is not set.`);
1184
+ }
1185
+ }
1186
+ ensureNotFinalized() {
1187
+ if (this.finalized) {
1188
+ throw new Error('This QueryBuilder instance is already finalized, clone it first if you want to modify it.');
1189
+ }
1190
+ }
1191
+ /* istanbul ignore next */
1192
+ /** @ignore */
1193
+ [util_1.inspect.custom](depth) {
1194
+ const object = { ...this };
1195
+ const hidden = ['metadata', 'driver', 'context', 'platform', 'knex', 'type'];
1196
+ Object.keys(object).filter(k => k.startsWith('_')).forEach(k => delete object[k]);
1197
+ Object.keys(object).filter(k => object[k] == null).forEach(k => delete object[k]);
1198
+ hidden.forEach(k => delete object[k]);
1199
+ let prefix = this.type ? this.type.substring(0, 1) + this.type.toLowerCase().substring(1) : '';
1200
+ if (this._data) {
1201
+ object.data = this._data;
1202
+ }
1203
+ if (this._schema) {
1204
+ object.schema = this._schema;
1205
+ }
1206
+ if (!core_1.Utils.isEmpty(this._cond)) {
1207
+ object.where = this._cond;
1208
+ }
1209
+ if (this._onConflict?.[0]) {
1210
+ prefix = 'Upsert';
1211
+ object.onConflict = this._onConflict[0];
1212
+ }
1213
+ const name = this._mainAlias ? `${prefix}QueryBuilder<${this._mainAlias?.entityName}>` : 'QueryBuilder';
1214
+ const ret = (0, util_1.inspect)(object, { depth });
1215
+ return ret === '[Object]' ? `[${name}]` : name + ' ' + ret;
1216
+ }
1217
+ }
1218
+ exports.QueryBuilder = QueryBuilder;