@mikro-orm/knex 7.0.0-dev.7 → 7.0.0-dev.70

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 (51) hide show
  1. package/AbstractSqlConnection.d.ts +11 -5
  2. package/AbstractSqlConnection.js +79 -32
  3. package/AbstractSqlDriver.d.ts +9 -5
  4. package/AbstractSqlDriver.js +268 -220
  5. package/AbstractSqlPlatform.js +3 -3
  6. package/PivotCollectionPersister.d.ts +3 -2
  7. package/PivotCollectionPersister.js +12 -21
  8. package/README.md +3 -2
  9. package/SqlEntityManager.d.ts +9 -2
  10. package/SqlEntityManager.js +2 -2
  11. package/dialects/mssql/MsSqlNativeQueryBuilder.d.ts +2 -0
  12. package/dialects/mssql/MsSqlNativeQueryBuilder.js +43 -2
  13. package/dialects/mysql/MySqlPlatform.js +2 -1
  14. package/dialects/postgresql/PostgreSqlTableCompiler.d.ts +1 -0
  15. package/dialects/postgresql/PostgreSqlTableCompiler.js +1 -0
  16. package/dialects/sqlite/BaseSqliteConnection.d.ts +4 -2
  17. package/dialects/sqlite/BaseSqliteConnection.js +8 -5
  18. package/dialects/sqlite/BaseSqlitePlatform.js +1 -2
  19. package/dialects/sqlite/SqliteSchemaHelper.js +1 -1
  20. package/index.d.ts +1 -1
  21. package/index.js +1 -1
  22. package/package.json +5 -5
  23. package/query/ArrayCriteriaNode.d.ts +1 -0
  24. package/query/ArrayCriteriaNode.js +3 -0
  25. package/query/CriteriaNode.d.ts +4 -2
  26. package/query/CriteriaNode.js +11 -6
  27. package/query/CriteriaNodeFactory.js +12 -7
  28. package/query/NativeQueryBuilder.js +1 -1
  29. package/query/ObjectCriteriaNode.d.ts +1 -0
  30. package/query/ObjectCriteriaNode.js +38 -9
  31. package/query/QueryBuilder.d.ts +59 -7
  32. package/query/QueryBuilder.js +171 -47
  33. package/query/QueryBuilderHelper.d.ts +1 -1
  34. package/query/QueryBuilderHelper.js +15 -8
  35. package/query/ScalarCriteriaNode.d.ts +3 -3
  36. package/query/ScalarCriteriaNode.js +9 -7
  37. package/query/index.d.ts +1 -0
  38. package/query/index.js +1 -0
  39. package/query/raw.d.ts +59 -0
  40. package/query/raw.js +68 -0
  41. package/query/rawKnex.d.ts +58 -0
  42. package/query/rawKnex.js +72 -0
  43. package/schema/DatabaseSchema.js +25 -4
  44. package/schema/DatabaseTable.d.ts +5 -4
  45. package/schema/DatabaseTable.js +67 -33
  46. package/schema/SchemaComparator.js +2 -2
  47. package/schema/SchemaHelper.d.ts +2 -0
  48. package/schema/SchemaHelper.js +8 -4
  49. package/schema/SqlSchemaGenerator.d.ts +13 -6
  50. package/schema/SqlSchemaGenerator.js +38 -17
  51. package/typings.d.ts +85 -3
@@ -1,4 +1,4 @@
1
- import { ALIAS_REPLACEMENT, QueryFlag, raw, RawQueryFragment, ReferenceKind, Utils, } from '@mikro-orm/core';
1
+ import { ALIAS_REPLACEMENT, GroupOperator, QueryFlag, raw, RawQueryFragment, ReferenceKind, Utils, } from '@mikro-orm/core';
2
2
  import { CriteriaNode } from './CriteriaNode.js';
3
3
  import { JoinType, QueryType } from './enums.js';
4
4
  /**
@@ -6,7 +6,8 @@ import { JoinType, QueryType } from './enums.js';
6
6
  */
7
7
  export class ObjectCriteriaNode extends CriteriaNode {
8
8
  process(qb, options) {
9
- const nestedAlias = qb.getAliasForJoinPath(this.getPath(), options);
9
+ const matchPopulateJoins = options?.matchPopulateJoins || (this.prop && [ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(this.prop.kind));
10
+ const nestedAlias = qb.getAliasForJoinPath(this.getPath(), { ...options, matchPopulateJoins });
10
11
  const ownerAlias = options?.alias || qb.alias;
11
12
  const keys = Object.keys(this.payload);
12
13
  let alias = options?.alias;
@@ -55,7 +56,23 @@ export class ObjectCriteriaNode extends CriteriaNode {
55
56
  }
56
57
  return { $and };
57
58
  }
58
- alias = this.autoJoin(qb, ownerAlias);
59
+ alias = this.autoJoin(qb, ownerAlias, options);
60
+ }
61
+ if (this.prop && nestedAlias) {
62
+ const toOneProperty = [ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(this.prop.kind);
63
+ // if the property is nullable and the filter is strict, we need to use left join, so we mimic the inner join behaviour
64
+ // with an exclusive condition on the join columns:
65
+ // - if the owning column is null, the row is missing, we don't apply the filter
66
+ // - if the target column is not null, the row is matched, we apply the filter
67
+ if (toOneProperty && this.prop.nullable && this.isStrict()) {
68
+ const key = this.prop.owner ? this.prop.name : this.prop.referencedPKs;
69
+ qb.andWhere({
70
+ $or: [
71
+ { [ownerAlias + '.' + key]: null },
72
+ { [nestedAlias + '.' + Utils.getPrimaryKeyHash(this.prop.referencedPKs)]: { $ne: null } },
73
+ ],
74
+ });
75
+ }
59
76
  }
60
77
  return keys.reduce((o, field) => {
61
78
  const childNode = this.payload[field];
@@ -66,13 +83,14 @@ export class ObjectCriteriaNode extends CriteriaNode {
66
83
  const virtual = childNode.prop?.persist === false && !childNode.prop?.formula;
67
84
  // if key is missing, we are inside group operator and we need to prefix with alias
68
85
  const primaryKey = this.key && this.metadata.find(this.entityName)?.primaryKeys.includes(field);
86
+ const isToOne = childNode.prop && [ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(childNode.prop.kind);
69
87
  if (childNode.shouldInline(payload)) {
70
- const childAlias = qb.getAliasForJoinPath(childNode.getPath(), options);
88
+ const childAlias = qb.getAliasForJoinPath(childNode.getPath(), { preferNoBranch: isToOne, ...options });
71
89
  const a = qb.helper.isTableNameAliasRequired(qb.type) ? alias : undefined;
72
90
  this.inlineChildPayload(o, payload, field, a, childAlias);
73
91
  }
74
92
  else if (childNode.shouldRename(payload)) {
75
- this.inlineCondition(childNode.renameFieldToPK(qb), o, payload);
93
+ this.inlineCondition(childNode.renameFieldToPK(qb, alias), o, payload);
76
94
  }
77
95
  else if (isRawField) {
78
96
  const rawField = RawQueryFragment.getKnownFragment(field);
@@ -87,6 +105,11 @@ export class ObjectCriteriaNode extends CriteriaNode {
87
105
  return o;
88
106
  }, {});
89
107
  }
108
+ isStrict() {
109
+ return this.strict || Object.keys(this.payload).some(key => {
110
+ return this.payload[key].isStrict();
111
+ });
112
+ }
90
113
  unwrap() {
91
114
  return Object.keys(this.payload).reduce((o, field) => {
92
115
  o[field] = this.payload[field].unwrap();
@@ -137,7 +160,7 @@ export class ObjectCriteriaNode extends CriteriaNode {
137
160
  delete payload[k];
138
161
  o[this.aliased(field, alias)] = { [k]: tmp, ...o[this.aliased(field, alias)] };
139
162
  }
140
- else if (Utils.isGroupOperator(k) && Array.isArray(payload[k])) {
163
+ else if (k in GroupOperator && Array.isArray(payload[k])) {
141
164
  this.inlineArrayChildPayload(o, payload[k], k, prop, childAlias, alias);
142
165
  }
143
166
  else if (this.isPrefixed(k) || Utils.isOperator(k) || !childAlias) {
@@ -193,7 +216,7 @@ export class ObjectCriteriaNode extends CriteriaNode {
193
216
  });
194
217
  return !primaryKeys && !nestedAlias && !operatorKeys && !embeddable;
195
218
  }
196
- autoJoin(qb, alias) {
219
+ autoJoin(qb, alias, options) {
197
220
  const nestedAlias = qb.getNextAlias(this.prop?.pivotTable ?? this.entityName);
198
221
  const customExpression = RawQueryFragment.isKnownFragment(this.key);
199
222
  const scalar = Utils.isPrimaryKey(this.payload) || this.payload instanceof RegExp || this.payload instanceof Date || customExpression;
@@ -206,12 +229,18 @@ export class ObjectCriteriaNode extends CriteriaNode {
206
229
  }
207
230
  else {
208
231
  const prev = qb._fields?.slice();
209
- qb[method](field, nestedAlias, undefined, JoinType.leftJoin, path);
232
+ const toOneProperty = [ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(this.prop.kind);
233
+ const joinType = toOneProperty && !this.prop.nullable
234
+ ? JoinType.innerJoin
235
+ : JoinType.leftJoin;
236
+ qb[method](field, nestedAlias, undefined, joinType, path);
210
237
  if (!qb.hasFlag(QueryFlag.INFER_POPULATE)) {
211
238
  qb._fields = prev;
212
239
  }
213
240
  }
214
- qb.scheduleFilterCheck(path);
241
+ if (options?.type !== 'orderBy') {
242
+ qb.scheduleFilterCheck(path);
243
+ }
215
244
  return nestedAlias;
216
245
  }
217
246
  isPrefixed(field) {
@@ -1,5 +1,5 @@
1
1
  import { inspect } from 'node:util';
2
- import { type AnyEntity, type ConnectionType, type Dictionary, type EntityData, type EntityKey, type EntityManager, type EntityMetadata, type EntityName, type EntityProperty, type ExpandProperty, type FlushMode, type GroupOperator, type Loaded, LockMode, type LoggingOptions, type MetadataStorage, type ObjectQuery, PopulateHint, type PopulateOptions, type QBFilterQuery, type QBQueryOrderMap, QueryFlag, type QueryOrderMap, type QueryResult, RawQueryFragment, type RequiredEntityData, type Transaction } from '@mikro-orm/core';
2
+ import { type AnyEntity, type ConnectionType, type Dictionary, type EntityData, type EntityKey, type EntityManager, type EntityMetadata, type EntityName, type EntityProperty, type ExpandProperty, type FilterOptions, type FlushMode, type GroupOperator, type Loaded, LockMode, type LoggingOptions, type MetadataStorage, type ObjectQuery, PopulateHint, type PopulateOptions, type QBFilterQuery, type QBQueryOrderMap, QueryFlag, type QueryOrderMap, type QueryResult, RawQueryFragment, type RequiredEntityData, type Transaction } from '@mikro-orm/core';
3
3
  import { JoinType, QueryType } from './enums.js';
4
4
  import type { AbstractSqlDriver } from '../AbstractSqlDriver.js';
5
5
  import { type Alias, type OnConflictClause, QueryBuilderHelper } from './QueryBuilderHelper.js';
@@ -11,6 +11,30 @@ export interface ExecuteOptions {
11
11
  mapResults?: boolean;
12
12
  mergeResults?: boolean;
13
13
  }
14
+ export interface QBStreamOptions {
15
+ /**
16
+ * Results are mapped to entities, if you set `mapResults: false` you will get POJOs instead.
17
+ *
18
+ * @default true
19
+ */
20
+ mapResults?: boolean;
21
+ /**
22
+ * When populating to-many relations, the ORM streams fully merged entities instead of yielding every row.
23
+ * You can opt out of this behavior by specifying `mergeResults: false`. This will yield every row from
24
+ * the SQL result, but still mapped to entities, meaning that to-many collections will contain at most
25
+ * one item, and you will get duplicate root entities when they have multiple items in the populated
26
+ * collection.
27
+ *
28
+ * @default true
29
+ */
30
+ mergeResults?: boolean;
31
+ /**
32
+ * When enabled, the driver will return the raw database results without renaming the fields to match the entity property names.
33
+ *
34
+ * @default false
35
+ */
36
+ rawResults?: boolean;
37
+ }
14
38
  type AnyString = string & {};
15
39
  type Compute<T> = {
16
40
  [K in keyof T]: T[K];
@@ -140,7 +164,7 @@ export declare class QueryBuilder<Entity extends object = AnyEntity, RootAlias e
140
164
  /**
141
165
  * Apply filters to the QB where condition.
142
166
  */
143
- applyFilters(filterOptions?: Dictionary<boolean | Dictionary> | string[] | boolean): Promise<void>;
167
+ applyFilters(filterOptions?: FilterOptions): Promise<void>;
144
168
  private readonly autoJoinedPaths;
145
169
  /**
146
170
  * @internal
@@ -149,7 +173,7 @@ export declare class QueryBuilder<Entity extends object = AnyEntity, RootAlias e
149
173
  /**
150
174
  * @internal
151
175
  */
152
- applyJoinedFilters(em: EntityManager, filterOptions?: Dictionary<boolean | Dictionary> | string[] | boolean): Promise<void>;
176
+ applyJoinedFilters(em: EntityManager, filterOptions: FilterOptions | undefined): Promise<void>;
153
177
  withSubQuery(subQuery: RawQueryFragment | NativeQueryBuilder, alias: string): this;
154
178
  where(cond: QBFilterQuery<Entity>, operator?: keyof typeof GroupOperator): this;
155
179
  where(cond: string, params?: any[], operator?: keyof typeof GroupOperator): this;
@@ -158,6 +182,8 @@ export declare class QueryBuilder<Entity extends object = AnyEntity, RootAlias e
158
182
  orWhere(cond: QBFilterQuery<Entity>): this;
159
183
  orWhere(cond: string, params?: any[]): this;
160
184
  orderBy(orderBy: QBQueryOrderMap<Entity> | QBQueryOrderMap<Entity>[]): SelectQueryBuilder<Entity, RootAlias, Hint, Context>;
185
+ andOrderBy(orderBy: QBQueryOrderMap<Entity> | QBQueryOrderMap<Entity>[]): SelectQueryBuilder<Entity, RootAlias, Hint, Context>;
186
+ private processOrderBy;
161
187
  groupBy(fields: EntityKeyOrString<Entity> | readonly EntityKeyOrString<Entity>[]): SelectQueryBuilder<Entity, RootAlias, Hint, Context>;
162
188
  having(cond?: QBFilterQuery | string, params?: any[], operator?: keyof typeof GroupOperator): SelectQueryBuilder<Entity, RootAlias, Hint, Context>;
163
189
  andHaving(cond?: QBFilterQuery | string, params?: any[]): SelectQueryBuilder<Entity, RootAlias, Hint, Context>;
@@ -182,17 +208,17 @@ export declare class QueryBuilder<Entity extends object = AnyEntity, RootAlias e
182
208
  /**
183
209
  * Adds index hint to the FROM clause.
184
210
  */
185
- indexHint(sql: string): this;
211
+ indexHint(sql: string | undefined): this;
186
212
  /**
187
213
  * Prepend comment to the sql query using the syntax `/* ... *&#8205;/`. Some characters are forbidden such as `/*, *&#8205;/` and `?`.
188
214
  */
189
- comment(comment: string | string[]): this;
215
+ comment(comment: string | string[] | undefined): this;
190
216
  /**
191
217
  * Add hints to the query using comment-like syntax `/*+ ... *&#8205;/`. MySQL and Oracle use this syntax for optimizer hints.
192
218
  * Also various DB proxies and routers use this syntax to pass hints to alter their behavior. In other dialects the hints
193
219
  * are ignored as simple comments.
194
220
  */
195
- hintComment(comment: string | string[]): this;
221
+ hintComment(comment: string | string[] | undefined): this;
196
222
  /**
197
223
  * Specifies FROM which entity's table select/update/delete will be executed, removing all previously set FROM-s.
198
224
  * Allows setting a main string alias of the selection data.
@@ -245,14 +271,35 @@ export declare class QueryBuilder<Entity extends object = AnyEntity, RootAlias e
245
271
  * Use `method` to specify what kind of result you want to get (array/single/meta).
246
272
  */
247
273
  execute<U = any>(method?: 'all' | 'get' | 'run', options?: ExecuteOptions | boolean): Promise<U>;
274
+ private getConnection;
275
+ /**
276
+ * Executes the query and returns an async iterable (async generator) that yields results one by one.
277
+ * By default, the results are merged and mapped to entity instances, without adding them to the identity map.
278
+ * You can disable merging and mapping by passing the options `{ mergeResults: false, mapResults: false }`.
279
+ * This is useful for processing large datasets without loading everything into memory at once.
280
+ *
281
+ * ```ts
282
+ * const qb = em.createQueryBuilder(Book, 'b');
283
+ * qb.select('*').where({ title: '1984' }).leftJoinAndSelect('b.author', 'a');
284
+ *
285
+ * for await (const book of qb.stream()) {
286
+ * // book is an instance of Book entity
287
+ * console.log(book.title, book.author.name);
288
+ * }
289
+ * ```
290
+ */
291
+ stream(options?: QBStreamOptions): AsyncIterableIterator<Loaded<Entity, Hint>>;
248
292
  /**
249
293
  * Alias for `qb.getResultList()`
250
294
  */
251
295
  getResult(): Promise<Loaded<Entity, Hint>[]>;
252
296
  /**
253
- * Executes the query, returning array of results
297
+ * Executes the query, returning array of results mapped to entity instances.
254
298
  */
255
299
  getResultList(limit?: number): Promise<Loaded<Entity, Hint>[]>;
300
+ private propagatePopulateHint;
301
+ private mapResult;
302
+ private mapResults;
256
303
  /**
257
304
  * Executes the query, returning the first result or null
258
305
  */
@@ -290,6 +337,11 @@ export declare class QueryBuilder<Entity extends object = AnyEntity, RootAlias e
290
337
  processPopulateHint(): void;
291
338
  private processPopulateWhere;
292
339
  private mergeOnConditions;
340
+ /**
341
+ * When adding an inner join on a left joined relation, we need to nest them,
342
+ * otherwise the inner join could discard rows of the root table.
343
+ */
344
+ private processNestedJoins;
293
345
  private hasToManyJoins;
294
346
  protected wrapPaginateSubQuery(meta: EntityMetadata): void;
295
347
  private pruneExtraJoins;
@@ -179,10 +179,10 @@ export class QueryBuilder {
179
179
  subquery = this.platform.formatQuery(rawFragment.sql, rawFragment.params);
180
180
  field = field[0];
181
181
  }
182
- const prop = this.joinReference(field, alias, cond, type, path, schema, subquery);
182
+ const { prop, key } = this.joinReference(field, alias, cond, type, path, schema, subquery);
183
183
  const [fromAlias] = this.helper.splitField(field);
184
184
  if (subquery) {
185
- this._joins[`${fromAlias}.${prop.name}#${alias}`].subquery = subquery;
185
+ this._joins[key].subquery = subquery;
186
186
  }
187
187
  const populate = this._joinedProps.get(fromAlias);
188
188
  const item = { field: prop.name, strategy: LoadStrategy.JOINED, children: [] };
@@ -240,9 +240,12 @@ export class QueryBuilder {
240
240
  }
241
241
  }
242
242
  prop.targetMeta.props
243
- .filter(prop => explicitFields
244
- ? explicitFields.includes(prop.name) || explicitFields.includes(`${alias}.${prop.name}`) || prop.primary
245
- : this.platform.shouldHaveColumn(prop, populate))
243
+ .filter(prop => {
244
+ if (!explicitFields) {
245
+ return this.platform.shouldHaveColumn(prop, populate);
246
+ }
247
+ return prop.primary && !explicitFields.includes(prop.name) && !explicitFields.includes(`${alias}.${prop.name}`);
248
+ })
246
249
  .forEach(prop => fields.push(...this.driver.mapPropToFieldNames(this, prop, alias)));
247
250
  return fields;
248
251
  }
@@ -267,16 +270,23 @@ export class QueryBuilder {
267
270
  /**
268
271
  * @internal
269
272
  */
270
- async applyJoinedFilters(em, filterOptions = {}) {
273
+ async applyJoinedFilters(em, filterOptions) {
271
274
  for (const path of this.autoJoinedPaths) {
272
275
  const join = this.getJoinForPath(path);
273
276
  if (join.type === JoinType.pivotJoin) {
274
277
  continue;
275
278
  }
279
+ filterOptions = QueryHelper.mergePropertyFilters(join.prop.filters, filterOptions);
276
280
  const cond = await em.applyFilters(join.prop.type, join.cond, filterOptions, 'read');
277
281
  if (Utils.hasObjectKeys(cond)) {
282
+ // remove nested filters, we only care about scalars here, nesting would require another join branch
283
+ for (const key of Object.keys(cond)) {
284
+ if (Utils.isPlainObject(cond[key]) && Object.keys(cond[key]).every(k => !(Utils.isOperator(k) && !['$some', '$none', '$every'].includes(k)))) {
285
+ delete cond[key];
286
+ }
287
+ }
278
288
  if (Utils.hasObjectKeys(join.cond)) {
279
- /* istanbul ignore next */
289
+ /* v8 ignore next */
280
290
  join.cond = { $and: [join.cond, cond] };
281
291
  }
282
292
  else {
@@ -303,7 +313,7 @@ export class QueryBuilder {
303
313
  cond = { [raw(`(${sql})`)]: Utils.asArray(params) };
304
314
  operator ??= '$and';
305
315
  }
306
- else if (Utils.isString(cond)) {
316
+ else if (typeof cond === 'string') {
307
317
  cond = { [raw(`(${cond})`, Utils.asArray(params))]: [] };
308
318
  operator ??= '$and';
309
319
  }
@@ -350,8 +360,16 @@ export class QueryBuilder {
350
360
  return this.where(cond, params, '$or');
351
361
  }
352
362
  orderBy(orderBy) {
363
+ return this.processOrderBy(orderBy, true);
364
+ }
365
+ andOrderBy(orderBy) {
366
+ return this.processOrderBy(orderBy, false);
367
+ }
368
+ processOrderBy(orderBy, reset = true) {
353
369
  this.ensureNotFinalized();
354
- this._orderBy = [];
370
+ if (reset) {
371
+ this._orderBy = [];
372
+ }
355
373
  Utils.asArray(orderBy).forEach(o => {
356
374
  const processed = QueryHelper.processWhere({
357
375
  where: o,
@@ -363,7 +381,7 @@ export class QueryBuilder {
363
381
  convertCustomTypes: false,
364
382
  type: 'orderBy',
365
383
  });
366
- this._orderBy.push(CriteriaNodeFactory.createNode(this.metadata, this.mainAlias.entityName, processed).process(this, { matchPopulateJoins: true }));
384
+ this._orderBy.push(CriteriaNodeFactory.createNode(this.metadata, this.mainAlias.entityName, processed).process(this, { matchPopulateJoins: true, type: 'orderBy' }));
367
385
  });
368
386
  return this;
369
387
  }
@@ -374,7 +392,7 @@ export class QueryBuilder {
374
392
  }
375
393
  having(cond = {}, params, operator) {
376
394
  this.ensureNotFinalized();
377
- if (Utils.isString(cond)) {
395
+ if (typeof cond === 'string') {
378
396
  cond = { [raw(`(${cond})`, params)]: [] };
379
397
  }
380
398
  cond = CriteriaNodeFactory.createNode(this.metadata, this.mainAlias.entityName, cond).process(this);
@@ -459,7 +477,7 @@ export class QueryBuilder {
459
477
  }
460
478
  setLockMode(mode, tables) {
461
479
  this.ensureNotFinalized();
462
- if (mode != null && mode !== LockMode.OPTIMISTIC && !this.context) {
480
+ if (mode != null && ![LockMode.OPTIMISTIC, LockMode.NONE].includes(mode) && !this.context) {
463
481
  throw ValidationError.transactionRequired();
464
482
  }
465
483
  this.lockMode = mode;
@@ -553,7 +571,7 @@ export class QueryBuilder {
553
571
  Utils.runIfNotEmpty(() => qb.hintComment(this._hintComments), this._hintComments);
554
572
  Utils.runIfNotEmpty(() => this.helper.appendOnConflictClause(QueryType.UPSERT, this._onConflict, qb), this._onConflict);
555
573
  if (this.lockMode) {
556
- this.helper.getLockSQL(qb, this.lockMode, this.lockTables);
574
+ this.helper.getLockSQL(qb, this.lockMode, this.lockTables, this._joins);
557
575
  }
558
576
  this.helper.finalize(this.type, qb, this.mainAlias.metadata, this._data, this._returning);
559
577
  this.clearRawFragmentsCache();
@@ -667,7 +685,7 @@ export class QueryBuilder {
667
685
  options.mapResults ??= true;
668
686
  const isRunType = [QueryType.INSERT, QueryType.UPDATE, QueryType.DELETE, QueryType.TRUNCATE].includes(this.type);
669
687
  method ??= isRunType ? 'run' : 'all';
670
- if (!this.connectionType && isRunType) {
688
+ if (!this.connectionType && (isRunType || this.context)) {
671
689
  this.connectionType = 'write';
672
690
  }
673
691
  if (!this.finalized && method === 'get' && this.type === QueryType.SELECT) {
@@ -675,13 +693,11 @@ export class QueryBuilder {
675
693
  }
676
694
  const query = this.toQuery();
677
695
  const cached = await this.em?.tryCache(this.mainAlias.entityName, this._cache, ['qb.execute', query.sql, query.params, method]);
678
- if (cached?.data) {
696
+ if (cached?.data !== undefined) {
679
697
  return cached.data;
680
698
  }
681
- const write = method === 'run' || !this.platform.getConfig().get('preferReadReplicas');
682
- const type = this.connectionType || (write ? 'write' : 'read');
683
699
  const loggerContext = { id: this.em?.id, ...this.loggerContext };
684
- const res = await this.driver.getConnection(type).execute(query.sql, query.params, method, this.context, loggerContext);
700
+ const res = await this.getConnection().execute(query.sql, query.params, method, this.context, loggerContext);
685
701
  const meta = this.mainAlias.metadata;
686
702
  if (!options.mapResults || !meta) {
687
703
  await this.em?.storeCache(this._cache, cached, res);
@@ -709,6 +725,64 @@ export class QueryBuilder {
709
725
  await this.em?.storeCache(this._cache, cached, mapped);
710
726
  return mapped;
711
727
  }
728
+ getConnection() {
729
+ const write = !this.platform.getConfig().get('preferReadReplicas');
730
+ const type = this.connectionType || (write ? 'write' : 'read');
731
+ return this.driver.getConnection(type);
732
+ }
733
+ /**
734
+ * Executes the query and returns an async iterable (async generator) that yields results one by one.
735
+ * By default, the results are merged and mapped to entity instances, without adding them to the identity map.
736
+ * You can disable merging and mapping by passing the options `{ mergeResults: false, mapResults: false }`.
737
+ * This is useful for processing large datasets without loading everything into memory at once.
738
+ *
739
+ * ```ts
740
+ * const qb = em.createQueryBuilder(Book, 'b');
741
+ * qb.select('*').where({ title: '1984' }).leftJoinAndSelect('b.author', 'a');
742
+ *
743
+ * for await (const book of qb.stream()) {
744
+ * // book is an instance of Book entity
745
+ * console.log(book.title, book.author.name);
746
+ * }
747
+ * ```
748
+ */
749
+ async *stream(options) {
750
+ options ??= {};
751
+ options.mergeResults ??= true;
752
+ options.mapResults ??= true;
753
+ const query = this.toQuery();
754
+ const loggerContext = { id: this.em?.id, ...this.loggerContext };
755
+ const res = this.getConnection().stream(query.sql, query.params, this.context, loggerContext);
756
+ const meta = this.mainAlias.metadata;
757
+ if (options.rawResults || !meta) {
758
+ yield* res;
759
+ return;
760
+ }
761
+ const joinedProps = this.driver.joinedProps(meta, this._populate);
762
+ const stack = [];
763
+ const hash = (data) => {
764
+ return Utils.getPrimaryKeyHash(meta.primaryKeys.map(pk => data[pk]));
765
+ };
766
+ for await (const row of res) {
767
+ const mapped = this.driver.mapResult(row, meta, this._populate, this);
768
+ if (!options.mergeResults || joinedProps.length === 0) {
769
+ yield this.mapResult(mapped, options.mapResults);
770
+ continue;
771
+ }
772
+ if (stack.length > 0 && hash(stack[stack.length - 1]) !== hash(mapped)) {
773
+ const res = this.driver.mergeJoinedResult(stack, this.mainAlias.metadata, joinedProps);
774
+ for (const row of res) {
775
+ yield this.mapResult(row, options.mapResults);
776
+ }
777
+ stack.length = 0;
778
+ }
779
+ stack.push(mapped);
780
+ }
781
+ if (stack.length > 0) {
782
+ const merged = this.driver.mergeJoinedResult(stack, this.mainAlias.metadata, joinedProps);
783
+ yield this.mapResult(merged[0], options.mapResults);
784
+ }
785
+ }
712
786
  /**
713
787
  * Alias for `qb.getResultList()`
714
788
  */
@@ -716,29 +790,40 @@ export class QueryBuilder {
716
790
  return this.getResultList();
717
791
  }
718
792
  /**
719
- * Executes the query, returning array of results
793
+ * Executes the query, returning array of results mapped to entity instances.
720
794
  */
721
795
  async getResultList(limit) {
722
796
  await this.em.tryFlush(this.mainAlias.entityName, { flushMode: this.flushMode });
723
797
  const res = await this.execute('all', true);
724
- const entities = [];
725
- function propagatePopulateHint(entity, hint) {
726
- helper(entity).__serializationContext.populate = hint.concat(helper(entity).__serializationContext.populate ?? []);
727
- hint.forEach(hint => {
728
- const [propName] = hint.field.split(':', 2);
729
- const value = Reference.unwrapReference(entity[propName]);
730
- if (Utils.isEntity(value)) {
731
- propagatePopulateHint(value, hint.children ?? []);
732
- }
733
- else if (Utils.isCollection(value)) {
734
- value.populated();
735
- value.getItems(false).forEach(item => propagatePopulateHint(item, hint.children ?? []));
736
- }
737
- });
798
+ return this.mapResults(res, limit);
799
+ }
800
+ propagatePopulateHint(entity, hint) {
801
+ helper(entity).__serializationContext.populate = hint.concat(helper(entity).__serializationContext.populate ?? []);
802
+ hint.forEach(hint => {
803
+ const [propName] = hint.field.split(':', 2);
804
+ const value = Reference.unwrapReference(entity[propName]);
805
+ if (Utils.isEntity(value)) {
806
+ this.propagatePopulateHint(value, hint.children ?? []);
807
+ }
808
+ else if (Utils.isCollection(value)) {
809
+ value.populated();
810
+ value.getItems(false).forEach(item => this.propagatePopulateHint(item, hint.children ?? []));
811
+ }
812
+ });
813
+ }
814
+ mapResult(row, map = true) {
815
+ if (!map) {
816
+ return row;
738
817
  }
739
- for (const r of res) {
740
- const entity = this.em.map(this.mainAlias.entityName, r, { schema: this._schema });
741
- propagatePopulateHint(entity, this._populate);
818
+ const entity = this.em.map(this.mainAlias.entityName, row, { schema: this._schema });
819
+ this.propagatePopulateHint(entity, this._populate);
820
+ return entity;
821
+ }
822
+ mapResults(res, limit) {
823
+ const entities = [];
824
+ for (const row of res) {
825
+ const entity = this.mapResult(row);
826
+ this.propagatePopulateHint(entity, this._populate);
742
827
  entities.push(entity);
743
828
  if (limit != null && --limit === 0) {
744
829
  break;
@@ -873,7 +958,8 @@ export class QueryBuilder {
873
958
  if (field instanceof RawQueryFragment) {
874
959
  field = this.platform.formatQuery(field.sql, field.params);
875
960
  }
876
- this._joins[`${this.alias}.${prop.name}#${alias}`] = {
961
+ const key = `${this.alias}.${prop.name}#${alias}`;
962
+ this._joins[key] = {
877
963
  prop,
878
964
  alias,
879
965
  type,
@@ -882,7 +968,7 @@ export class QueryBuilder {
882
968
  subquery: field.toString(),
883
969
  ownerAlias: this.alias,
884
970
  };
885
- return prop;
971
+ return { prop, key };
886
972
  }
887
973
  if (!subquery && type.includes('lateral')) {
888
974
  throw new Error(`Lateral join can be used only with a sub-query.`);
@@ -907,10 +993,13 @@ export class QueryBuilder {
907
993
  aliasMap: this.getAliasMap(),
908
994
  aliased: [QueryType.SELECT, QueryType.COUNT].includes(this.type),
909
995
  });
996
+ const criteriaNode = CriteriaNodeFactory.createNode(this.metadata, prop.targetMeta.className, cond);
997
+ cond = criteriaNode.process(this, { ignoreBranching: true, alias });
910
998
  let aliasedName = `${fromAlias}.${prop.name}#${alias}`;
911
999
  path ??= `${(Object.values(this._joins).find(j => j.alias === fromAlias)?.path ?? entityName)}.${prop.name}`;
912
1000
  if (prop.kind === ReferenceKind.ONE_TO_MANY) {
913
1001
  this._joins[aliasedName] = this.helper.joinOneToReference(prop, fromAlias, alias, type, cond, schema);
1002
+ this._joins[aliasedName].path ??= path;
914
1003
  }
915
1004
  else if (prop.kind === ReferenceKind.MANY_TO_MANY) {
916
1005
  let pivotAlias = alias;
@@ -922,17 +1011,18 @@ export class QueryBuilder {
922
1011
  const joins = this.helper.joinManyToManyReference(prop, fromAlias, alias, pivotAlias, type, cond, path, schema);
923
1012
  Object.assign(this._joins, joins);
924
1013
  this.createAlias(prop.pivotEntity, pivotAlias);
1014
+ this._joins[aliasedName].path ??= path;
1015
+ aliasedName = Object.keys(joins)[1];
925
1016
  }
926
1017
  else if (prop.kind === ReferenceKind.ONE_TO_ONE) {
927
1018
  this._joins[aliasedName] = this.helper.joinOneToReference(prop, fromAlias, alias, type, cond, schema);
1019
+ this._joins[aliasedName].path ??= path;
928
1020
  }
929
1021
  else { // MANY_TO_ONE
930
1022
  this._joins[aliasedName] = this.helper.joinManyToOneReference(prop, fromAlias, alias, type, cond, schema);
1023
+ this._joins[aliasedName].path ??= path;
931
1024
  }
932
- if (!this._joins[aliasedName].path && path) {
933
- this._joins[aliasedName].path = path;
934
- }
935
- return prop;
1025
+ return { prop, key: aliasedName };
936
1026
  }
937
1027
  prepareFields(fields, type = 'where') {
938
1028
  const ret = [];
@@ -945,7 +1035,7 @@ export class QueryBuilder {
945
1035
  ret.push(rawField);
946
1036
  return;
947
1037
  }
948
- if (!Utils.isString(field)) {
1038
+ if (typeof field !== 'string') {
949
1039
  ret.push(field);
950
1040
  return;
951
1041
  }
@@ -1107,6 +1197,7 @@ export class QueryBuilder {
1107
1197
  const meta = this.mainAlias.metadata;
1108
1198
  this.applyDiscriminatorCondition();
1109
1199
  this.processPopulateHint();
1200
+ this.processNestedJoins();
1110
1201
  if (meta && (this._fields?.includes('*') || this._fields?.includes(`${this.mainAlias.aliasName}.*`))) {
1111
1202
  meta.props
1112
1203
  .filter(prop => prop.formula && (!prop.lazy || this.flags.has(QueryFlag.INCLUDE_LAZY_FORMULAS)))
@@ -1130,7 +1221,7 @@ export class QueryBuilder {
1130
1221
  if (!this.flags.has(QueryFlag.DISABLE_PAGINATE) && this._groupBy.length === 0 && this.hasToManyJoins()) {
1131
1222
  this.flags.add(QueryFlag.PAGINATE);
1132
1223
  }
1133
- if (meta && this.flags.has(QueryFlag.PAGINATE) && (this._limit > 0 || this._offset > 0)) {
1224
+ if (meta && this.flags.has(QueryFlag.PAGINATE) && !this.flags.has(QueryFlag.DISABLE_PAGINATE) && (this._limit > 0 || this._offset > 0)) {
1134
1225
  this.wrapPaginateSubQuery(meta);
1135
1226
  }
1136
1227
  if (meta && (this.flags.has(QueryFlag.UPDATE_SUB_QUERY) || this.flags.has(QueryFlag.DELETE_SUB_QUERY))) {
@@ -1166,6 +1257,7 @@ export class QueryBuilder {
1166
1257
  this._joins[aliasedName] = this.helper.joinOneToReference(prop, this.mainAlias.aliasName, alias, JoinType.leftJoin);
1167
1258
  this._joins[aliasedName].path = `${(Object.values(this._joins).find(j => j.alias === fromAlias)?.path ?? meta.className)}.${prop.name}`;
1168
1259
  this._populateMap[aliasedName] = this._joins[aliasedName].alias;
1260
+ this.createAlias(prop.type, alias);
1169
1261
  }
1170
1262
  });
1171
1263
  this.processPopulateWhere(false);
@@ -1185,7 +1277,7 @@ export class QueryBuilder {
1185
1277
  if (typeof this[key] === 'object') {
1186
1278
  const cond = CriteriaNodeFactory
1187
1279
  .createNode(this.metadata, this.mainAlias.entityName, this[key])
1188
- .process(this, { matchPopulateJoins: true, ignoreBranching: true, preferNoBranch: true });
1280
+ .process(this, { matchPopulateJoins: true, ignoreBranching: true, preferNoBranch: true, filter });
1189
1281
  // there might be new joins created by processing the `populateWhere` object
1190
1282
  joins = Object.values(this._joins);
1191
1283
  this.mergeOnConditions(joins, cond, filter);
@@ -1226,10 +1318,42 @@ export class QueryBuilder {
1226
1318
  }
1227
1319
  }
1228
1320
  }
1321
+ /**
1322
+ * When adding an inner join on a left joined relation, we need to nest them,
1323
+ * otherwise the inner join could discard rows of the root table.
1324
+ */
1325
+ processNestedJoins() {
1326
+ if (this.flags.has(QueryFlag.DISABLE_NESTED_INNER_JOIN)) {
1327
+ return;
1328
+ }
1329
+ const joins = Object.values(this._joins);
1330
+ const lookupParentGroup = (j) => {
1331
+ return j.nested ?? (j.parent ? lookupParentGroup(j.parent) : undefined);
1332
+ };
1333
+ for (const join of joins) {
1334
+ if (join.type === JoinType.innerJoin) {
1335
+ join.parent = joins.find(j => j.alias === join.ownerAlias);
1336
+ // https://stackoverflow.com/a/56815807/3665878
1337
+ if (join.parent?.type === JoinType.leftJoin || join.parent?.type === JoinType.nestedLeftJoin) {
1338
+ const nested = ((join.parent).nested ??= new Set());
1339
+ join.type = join.type === JoinType.innerJoin
1340
+ ? JoinType.nestedInnerJoin
1341
+ : JoinType.nestedLeftJoin;
1342
+ nested.add(join);
1343
+ }
1344
+ else if (join.parent?.type === JoinType.nestedInnerJoin) {
1345
+ const group = lookupParentGroup(join.parent);
1346
+ const nested = group ?? ((join.parent).nested ??= new Set());
1347
+ join.type = join.type === JoinType.innerJoin
1348
+ ? JoinType.nestedInnerJoin
1349
+ : JoinType.nestedLeftJoin;
1350
+ nested.add(join);
1351
+ }
1352
+ }
1353
+ }
1354
+ }
1229
1355
  hasToManyJoins() {
1230
- // console.log(this._joins);
1231
1356
  return Object.values(this._joins).some(join => {
1232
- // console.log(join.prop.name, join.prop.kind, [ReferenceKind.ONE_TO_MANY, ReferenceKind.MANY_TO_MANY].includes(join.prop.kind));
1233
1357
  return [ReferenceKind.ONE_TO_MANY, ReferenceKind.MANY_TO_MANY].includes(join.prop.kind);
1234
1358
  });
1235
1359
  }
@@ -49,7 +49,7 @@ export declare class QueryBuilderHelper {
49
49
  getQueryOrderFromObject(type: QueryType, orderBy: FlatQueryOrderMap, populate: Dictionary<string>): string[];
50
50
  finalize(type: QueryType, qb: NativeQueryBuilder, meta?: EntityMetadata, data?: Dictionary, returning?: Field<any>[]): void;
51
51
  splitField<T>(field: EntityKey<T>, greedyAlias?: boolean): [string, EntityKey<T>, string | undefined];
52
- getLockSQL(qb: NativeQueryBuilder, lockMode: LockMode, lockTables?: string[]): void;
52
+ getLockSQL(qb: NativeQueryBuilder, lockMode: LockMode, lockTables?: string[], joinsMap?: Dictionary<JoinOptions>): void;
53
53
  updateVersionProperty(qb: NativeQueryBuilder, data: Dictionary): void;
54
54
  private prefix;
55
55
  private appendGroupCondition;