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