@mikro-orm/sql 7.0.15-dev.9 → 7.0.15

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 (89) hide show
  1. package/AbstractSqlConnection.d.ts +94 -58
  2. package/AbstractSqlConnection.js +235 -238
  3. package/AbstractSqlDriver.d.ts +410 -155
  4. package/AbstractSqlDriver.js +2100 -1972
  5. package/AbstractSqlPlatform.d.ts +86 -76
  6. package/AbstractSqlPlatform.js +169 -167
  7. package/PivotCollectionPersister.d.ts +33 -15
  8. package/PivotCollectionPersister.js +158 -160
  9. package/README.md +1 -1
  10. package/SqlEntityManager.d.ts +67 -22
  11. package/SqlEntityManager.js +54 -38
  12. package/SqlEntityRepository.d.ts +14 -14
  13. package/SqlEntityRepository.js +23 -23
  14. package/SqlMikroORM.d.ts +49 -8
  15. package/SqlMikroORM.js +8 -8
  16. package/dialects/mssql/MsSqlNativeQueryBuilder.d.ts +12 -12
  17. package/dialects/mssql/MsSqlNativeQueryBuilder.js +199 -201
  18. package/dialects/mysql/BaseMySqlPlatform.d.ts +65 -46
  19. package/dialects/mysql/BaseMySqlPlatform.js +137 -134
  20. package/dialects/mysql/MySqlExceptionConverter.d.ts +6 -6
  21. package/dialects/mysql/MySqlExceptionConverter.js +91 -77
  22. package/dialects/mysql/MySqlNativeQueryBuilder.d.ts +3 -3
  23. package/dialects/mysql/MySqlNativeQueryBuilder.js +66 -69
  24. package/dialects/mysql/MySqlSchemaHelper.d.ts +58 -39
  25. package/dialects/mysql/MySqlSchemaHelper.js +327 -319
  26. package/dialects/oracledb/OracleDialect.d.ts +81 -52
  27. package/dialects/oracledb/OracleDialect.js +155 -149
  28. package/dialects/oracledb/OracleNativeQueryBuilder.d.ts +12 -12
  29. package/dialects/oracledb/OracleNativeQueryBuilder.js +239 -243
  30. package/dialects/postgresql/BasePostgreSqlPlatform.d.ts +110 -107
  31. package/dialects/postgresql/BasePostgreSqlPlatform.js +370 -369
  32. package/dialects/postgresql/FullTextType.d.ts +10 -6
  33. package/dialects/postgresql/FullTextType.js +51 -51
  34. package/dialects/postgresql/PostgreSqlExceptionConverter.d.ts +5 -5
  35. package/dialects/postgresql/PostgreSqlExceptionConverter.js +55 -43
  36. package/dialects/postgresql/PostgreSqlNativeQueryBuilder.d.ts +1 -1
  37. package/dialects/postgresql/PostgreSqlNativeQueryBuilder.js +4 -4
  38. package/dialects/postgresql/PostgreSqlSchemaHelper.d.ts +117 -82
  39. package/dialects/postgresql/PostgreSqlSchemaHelper.js +748 -712
  40. package/dialects/sqlite/BaseSqliteConnection.d.ts +3 -5
  41. package/dialects/sqlite/BaseSqliteConnection.js +21 -19
  42. package/dialects/sqlite/NodeSqliteDialect.d.ts +1 -1
  43. package/dialects/sqlite/NodeSqliteDialect.js +23 -23
  44. package/dialects/sqlite/SqliteDriver.d.ts +1 -1
  45. package/dialects/sqlite/SqliteDriver.js +3 -3
  46. package/dialects/sqlite/SqliteExceptionConverter.d.ts +6 -6
  47. package/dialects/sqlite/SqliteExceptionConverter.js +67 -51
  48. package/dialects/sqlite/SqliteNativeQueryBuilder.d.ts +2 -2
  49. package/dialects/sqlite/SqliteNativeQueryBuilder.js +7 -7
  50. package/dialects/sqlite/SqlitePlatform.d.ts +64 -73
  51. package/dialects/sqlite/SqlitePlatform.js +143 -143
  52. package/dialects/sqlite/SqliteSchemaHelper.d.ts +78 -61
  53. package/dialects/sqlite/SqliteSchemaHelper.js +541 -522
  54. package/package.json +3 -3
  55. package/plugin/index.d.ts +42 -35
  56. package/plugin/index.js +43 -36
  57. package/plugin/transformer.d.ts +137 -95
  58. package/plugin/transformer.js +1012 -881
  59. package/query/ArrayCriteriaNode.d.ts +4 -4
  60. package/query/ArrayCriteriaNode.js +18 -18
  61. package/query/CriteriaNode.d.ts +35 -25
  62. package/query/CriteriaNode.js +142 -132
  63. package/query/CriteriaNodeFactory.d.ts +49 -6
  64. package/query/CriteriaNodeFactory.js +97 -94
  65. package/query/NativeQueryBuilder.d.ts +120 -120
  66. package/query/NativeQueryBuilder.js +507 -501
  67. package/query/ObjectCriteriaNode.d.ts +12 -12
  68. package/query/ObjectCriteriaNode.js +298 -282
  69. package/query/QueryBuilder.d.ts +1558 -906
  70. package/query/QueryBuilder.js +2346 -2217
  71. package/query/QueryBuilderHelper.d.ts +153 -72
  72. package/query/QueryBuilderHelper.js +1084 -1032
  73. package/query/ScalarCriteriaNode.d.ts +3 -3
  74. package/query/ScalarCriteriaNode.js +53 -46
  75. package/query/enums.d.ts +14 -14
  76. package/query/enums.js +14 -14
  77. package/query/raw.d.ts +16 -6
  78. package/query/raw.js +10 -10
  79. package/schema/DatabaseSchema.d.ts +74 -50
  80. package/schema/DatabaseSchema.js +359 -331
  81. package/schema/DatabaseTable.d.ts +96 -73
  82. package/schema/DatabaseTable.js +1046 -974
  83. package/schema/SchemaComparator.d.ts +70 -66
  84. package/schema/SchemaComparator.js +790 -765
  85. package/schema/SchemaHelper.d.ts +128 -97
  86. package/schema/SchemaHelper.js +683 -668
  87. package/schema/SqlSchemaGenerator.d.ts +79 -59
  88. package/schema/SqlSchemaGenerator.js +525 -495
  89. package/typings.d.ts +405 -275
@@ -1,2034 +1,2162 @@
1
- import { ALIAS_REPLACEMENT_RE, DatabaseDriver, EntityManagerType, getLoadingStrategy, getOnConflictFields, getOnConflictReturningFields, helper, isRaw, LoadStrategy, parseJsonSafe, PolymorphicRef, QueryFlag, QueryHelper, QueryOrder, raw, RawQueryFragment, ReferenceKind, Utils, } from '@mikro-orm/core';
1
+ import {
2
+ ALIAS_REPLACEMENT_RE,
3
+ DatabaseDriver,
4
+ EntityManagerType,
5
+ getLoadingStrategy,
6
+ getOnConflictFields,
7
+ getOnConflictReturningFields,
8
+ helper,
9
+ isRaw,
10
+ LoadStrategy,
11
+ parseJsonSafe,
12
+ PolymorphicRef,
13
+ QueryFlag,
14
+ QueryHelper,
15
+ QueryOrder,
16
+ raw,
17
+ RawQueryFragment,
18
+ ReferenceKind,
19
+ Utils,
20
+ } from '@mikro-orm/core';
2
21
  import { QueryBuilder } from './query/QueryBuilder.js';
3
22
  import { JoinType, QueryType } from './query/enums.js';
4
23
  import { SqlEntityManager } from './SqlEntityManager.js';
5
24
  import { PivotCollectionPersister } from './PivotCollectionPersister.js';
6
25
  /** Base class for SQL database drivers, implementing find/insert/update/delete using QueryBuilder. */
7
26
  export class AbstractSqlDriver extends DatabaseDriver {
8
- [EntityManagerType];
9
- connection;
10
- replicas = [];
11
- platform;
12
- constructor(config, platform, connection, connector) {
13
- super(config, connector);
14
- this.connection = new connection(this.config);
15
- this.replicas = this.createReplicas(conf => new connection(this.config, conf, 'read'));
16
- this.platform = platform;
17
- }
18
- getPlatform() {
19
- return this.platform;
20
- }
21
- /** Evaluates a formula callback, handling both string and Raw return values. */
22
- evaluateFormula(formula, columns, table) {
23
- const result = formula(columns, table);
24
- return isRaw(result) ? this.platform.formatQuery(result.sql, result.params) : result;
25
- }
26
- /** For TPT entities, returns ownProps (columns in this table); otherwise returns all props. */
27
- getTableProps(meta) {
28
- return meta.inheritanceType === 'tpt' && meta.ownProps ? meta.ownProps : meta.props;
29
- }
30
- /** Creates a FormulaTable object for use in formula callbacks. */
31
- createFormulaTable(alias, meta, schema) {
32
- const effectiveSchema = schema ?? (meta.schema !== '*' ? meta.schema : undefined);
33
- const qualifiedName = effectiveSchema ? `${effectiveSchema}.${meta.tableName}` : meta.tableName;
34
- return { alias, name: meta.tableName, schema: effectiveSchema, qualifiedName, toString: () => alias };
35
- }
36
- validateSqlOptions(options) {
37
- if (options.collation != null && typeof options.collation !== 'string') {
38
- throw new Error('Collation option for SQL drivers must be a string (collation name). Use a CollationOptions object only with MongoDB.');
39
- }
40
- if (options.indexHint != null && typeof options.indexHint !== 'string') {
41
- throw new Error("indexHint for SQL drivers must be a string (e.g. 'force index(my_index)'). Use an object only with MongoDB.");
42
- }
27
+ [EntityManagerType];
28
+ connection;
29
+ replicas = [];
30
+ platform;
31
+ constructor(config, platform, connection, connector) {
32
+ super(config, connector);
33
+ this.connection = new connection(this.config);
34
+ this.replicas = this.createReplicas(conf => new connection(this.config, conf, 'read'));
35
+ this.platform = platform;
36
+ }
37
+ getPlatform() {
38
+ return this.platform;
39
+ }
40
+ /** Evaluates a formula callback, handling both string and Raw return values. */
41
+ evaluateFormula(formula, columns, table) {
42
+ const result = formula(columns, table);
43
+ return isRaw(result) ? this.platform.formatQuery(result.sql, result.params) : result;
44
+ }
45
+ /** For TPT entities, returns ownProps (columns in this table); otherwise returns all props. */
46
+ getTableProps(meta) {
47
+ return meta.inheritanceType === 'tpt' && meta.ownProps ? meta.ownProps : meta.props;
48
+ }
49
+ /** Creates a FormulaTable object for use in formula callbacks. */
50
+ createFormulaTable(alias, meta, schema) {
51
+ const effectiveSchema = schema ?? (meta.schema !== '*' ? meta.schema : undefined);
52
+ const qualifiedName = effectiveSchema ? `${effectiveSchema}.${meta.tableName}` : meta.tableName;
53
+ return { alias, name: meta.tableName, schema: effectiveSchema, qualifiedName, toString: () => alias };
54
+ }
55
+ validateSqlOptions(options) {
56
+ if (options.collation != null && typeof options.collation !== 'string') {
57
+ throw new Error(
58
+ 'Collation option for SQL drivers must be a string (collation name). Use a CollationOptions object only with MongoDB.',
59
+ );
43
60
  }
44
- createEntityManager(useContext) {
45
- const EntityManagerClass = this.config.get('entityManager', SqlEntityManager);
46
- return new EntityManagerClass(this.config, this, this.metadata, useContext);
47
- }
48
- async createQueryBuilderFromOptions(meta, where, options = {}) {
49
- const connectionType = this.resolveConnectionType({ ctx: options.ctx, connectionType: options.connectionType });
50
- const populate = this.autoJoinOneToOneOwner(meta, options.populate, options.fields);
51
- const joinedProps = this.joinedProps(meta, populate, options);
52
- const schema = this.getSchemaName(meta, options);
53
- const qb = this.createQueryBuilder(meta.class, options.ctx, connectionType, false, options.logging, undefined, options.em)
54
- .withSchema(schema)
55
- .cache(false);
56
- const fields = this.buildFields(meta, populate, joinedProps, qb, qb.alias, options, schema);
57
- const orderBy = this.buildOrderBy(qb, meta, populate, options);
58
- const populateWhere = this.buildPopulateWhere(meta, joinedProps, options);
59
- Utils.asArray(options.flags).forEach(flag => qb.setFlag(flag));
60
- if (Utils.isPrimaryKey(where, meta.compositePK)) {
61
- where = { [Utils.getPrimaryKeyHash(meta.primaryKeys)]: where };
62
- }
63
- this.validateSqlOptions(options);
64
- const { first, last, before, after } = options;
65
- const isCursorPagination = [first, last, before, after].some(v => v != null);
66
- qb.state.resolvedPopulateWhere = options._populateWhere;
67
- qb.select(fields)
68
- // only add populateWhere if we are populate-joining, as this will be used to add `on` conditions
69
- .populate(populate, joinedProps.length > 0 ? populateWhere : undefined, joinedProps.length > 0 ? options.populateFilter : undefined)
70
- .where(where)
71
- .groupBy(options.groupBy)
72
- .having(options.having)
73
- .indexHint(options.indexHint)
74
- .collation(options.collation)
75
- .comment(options.comments)
76
- .hintComment(options.hintComments);
77
- if (isCursorPagination) {
78
- const { orderBy: newOrderBy, where } = this.processCursorOptions(meta, options, orderBy);
79
- qb.andWhere(where).orderBy(newOrderBy);
80
- }
81
- else {
82
- qb.orderBy(orderBy);
83
- }
84
- if (options.limit != null || options.offset != null) {
85
- qb.limit(options.limit, options.offset);
86
- }
87
- if (options.lockMode) {
88
- qb.setLockMode(options.lockMode, options.lockTableAliases);
89
- }
90
- if (options.em) {
91
- await qb.applyJoinedFilters(options.em, options.filters);
92
- }
93
- return qb;
61
+ if (options.indexHint != null && typeof options.indexHint !== 'string') {
62
+ throw new Error(
63
+ "indexHint for SQL drivers must be a string (e.g. 'force index(my_index)'). Use an object only with MongoDB.",
64
+ );
94
65
  }
95
- async find(entityName, where, options = {}) {
96
- options = { populate: [], orderBy: [], ...options };
97
- const meta = this.metadata.get(entityName);
98
- if (meta.virtual) {
99
- return this.findVirtual(entityName, where, options);
100
- }
101
- if (options.unionWhere?.length) {
102
- where = await this.applyUnionWhere(meta, where, options);
103
- }
104
- const qb = await this.createQueryBuilderFromOptions(meta, where, options);
105
- const result = await this.rethrow(qb.execute('all'));
106
- if (options.last && !options.first) {
107
- result.reverse();
108
- }
109
- return result;
110
- }
111
- async findOne(entityName, where, options) {
112
- const opts = { populate: [], ...options };
113
- const meta = this.metadata.find(entityName);
114
- const populate = this.autoJoinOneToOneOwner(meta, opts.populate, opts.fields);
115
- const joinedProps = this.joinedProps(meta, populate, options);
116
- const hasToManyJoins = joinedProps.some(hint => this.hasToManyJoins(hint, meta));
117
- if (joinedProps.length === 0 || !hasToManyJoins) {
118
- opts.limit = 1;
119
- }
120
- if (opts.limit > 0 && !opts.flags?.includes(QueryFlag.DISABLE_PAGINATE)) {
121
- opts.flags ??= [];
122
- opts.flags.push(QueryFlag.DISABLE_PAGINATE);
123
- }
124
- const res = await this.find(entityName, where, opts);
125
- return res[0] || null;
66
+ }
67
+ createEntityManager(useContext) {
68
+ const EntityManagerClass = this.config.get('entityManager', SqlEntityManager);
69
+ return new EntityManagerClass(this.config, this, this.metadata, useContext);
70
+ }
71
+ async createQueryBuilderFromOptions(meta, where, options = {}) {
72
+ const connectionType = this.resolveConnectionType({ ctx: options.ctx, connectionType: options.connectionType });
73
+ const populate = this.autoJoinOneToOneOwner(meta, options.populate, options.fields);
74
+ const joinedProps = this.joinedProps(meta, populate, options);
75
+ const schema = this.getSchemaName(meta, options);
76
+ const qb = this.createQueryBuilder(
77
+ meta.class,
78
+ options.ctx,
79
+ connectionType,
80
+ false,
81
+ options.logging,
82
+ undefined,
83
+ options.em,
84
+ )
85
+ .withSchema(schema)
86
+ .cache(false);
87
+ const fields = this.buildFields(meta, populate, joinedProps, qb, qb.alias, options, schema);
88
+ const orderBy = this.buildOrderBy(qb, meta, populate, options);
89
+ const populateWhere = this.buildPopulateWhere(meta, joinedProps, options);
90
+ Utils.asArray(options.flags).forEach(flag => qb.setFlag(flag));
91
+ if (Utils.isPrimaryKey(where, meta.compositePK)) {
92
+ where = { [Utils.getPrimaryKeyHash(meta.primaryKeys)]: where };
126
93
  }
127
- hasToManyJoins(hint, meta) {
128
- const [propName] = hint.field.split(':', 2);
129
- const prop = meta.properties[propName];
130
- if (prop && [ReferenceKind.ONE_TO_MANY, ReferenceKind.MANY_TO_MANY].includes(prop.kind)) {
131
- return true;
132
- }
133
- if (hint.children && prop.targetMeta) {
134
- return hint.children.some(hint => this.hasToManyJoins(hint, prop.targetMeta));
135
- }
136
- return false;
94
+ this.validateSqlOptions(options);
95
+ const { first, last, before, after } = options;
96
+ const isCursorPagination = [first, last, before, after].some(v => v != null);
97
+ qb.state.resolvedPopulateWhere = options._populateWhere;
98
+ qb.select(fields)
99
+ // only add populateWhere if we are populate-joining, as this will be used to add `on` conditions
100
+ .populate(
101
+ populate,
102
+ joinedProps.length > 0 ? populateWhere : undefined,
103
+ joinedProps.length > 0 ? options.populateFilter : undefined,
104
+ )
105
+ .where(where)
106
+ .groupBy(options.groupBy)
107
+ .having(options.having)
108
+ .indexHint(options.indexHint)
109
+ .collation(options.collation)
110
+ .comment(options.comments)
111
+ .hintComment(options.hintComments);
112
+ if (isCursorPagination) {
113
+ const { orderBy: newOrderBy, where } = this.processCursorOptions(meta, options, orderBy);
114
+ qb.andWhere(where).orderBy(newOrderBy);
115
+ } else {
116
+ qb.orderBy(orderBy);
137
117
  }
138
- async findVirtual(entityName, where, options) {
139
- return this.findFromVirtual(entityName, where, options, QueryType.SELECT);
118
+ if (options.limit != null || options.offset != null) {
119
+ qb.limit(options.limit, options.offset);
140
120
  }
141
- async countVirtual(entityName, where, options) {
142
- return this.findFromVirtual(entityName, where, options, QueryType.COUNT);
121
+ if (options.lockMode) {
122
+ qb.setLockMode(options.lockMode, options.lockTableAliases);
143
123
  }
144
- async findFromVirtual(entityName, where, options, type) {
145
- const meta = this.metadata.get(entityName);
146
- /* v8 ignore next */
147
- if (!meta.expression) {
148
- return type === QueryType.SELECT ? [] : 0;
149
- }
150
- if (typeof meta.expression === 'string') {
151
- return this.wrapVirtualExpressionInSubquery(meta, meta.expression, where, options, type);
152
- }
153
- const em = this.createEntityManager();
154
- em.setTransactionContext(options.ctx);
155
- const res = meta.expression(em, where, options);
156
- if (typeof res === 'string') {
157
- return this.wrapVirtualExpressionInSubquery(meta, res, where, options, type);
158
- }
159
- if (res instanceof QueryBuilder) {
160
- return this.wrapVirtualExpressionInSubquery(meta, res.getFormattedQuery(), where, options, type);
161
- }
162
- if (isRaw(res)) {
163
- const expr = this.platform.formatQuery(res.sql, res.params);
164
- return this.wrapVirtualExpressionInSubquery(meta, expr, where, options, type);
165
- }
166
- /* v8 ignore next */
167
- return res;
124
+ if (options.em) {
125
+ await qb.applyJoinedFilters(options.em, options.filters);
168
126
  }
169
- async *streamFromVirtual(entityName, where, options) {
170
- const meta = this.metadata.get(entityName);
171
- /* v8 ignore next */
172
- if (!meta.expression) {
173
- return;
174
- }
175
- if (typeof meta.expression === 'string') {
176
- yield* this.wrapVirtualExpressionInSubqueryStream(meta, meta.expression, where, options, QueryType.SELECT);
177
- return;
178
- }
179
- const em = this.createEntityManager();
180
- em.setTransactionContext(options.ctx);
181
- const res = meta.expression(em, where, options, true);
182
- if (typeof res === 'string') {
183
- yield* this.wrapVirtualExpressionInSubqueryStream(meta, res, where, options, QueryType.SELECT);
184
- return;
185
- }
186
- if (res instanceof QueryBuilder) {
187
- yield* this.wrapVirtualExpressionInSubqueryStream(meta, res.getFormattedQuery(), where, options, QueryType.SELECT);
188
- return;
189
- }
190
- if (isRaw(res)) {
191
- const expr = this.platform.formatQuery(res.sql, res.params);
192
- yield* this.wrapVirtualExpressionInSubqueryStream(meta, expr, where, options, QueryType.SELECT);
193
- return;
194
- }
195
- /* v8 ignore next */
196
- yield* res;
197
- }
198
- async wrapVirtualExpressionInSubquery(meta, expression, where, options, type) {
199
- const qb = await this.createQueryBuilderFromOptions(meta, where, this.forceBalancedStrategy(options));
200
- qb.setFlag(QueryFlag.DISABLE_PAGINATE);
201
- const isCursorPagination = [options.first, options.last, options.before, options.after].some(v => v != null);
202
- const native = qb.getNativeQuery(false);
203
- if (type === QueryType.COUNT) {
204
- native.clear('select').clear('limit').clear('offset').count();
205
- }
206
- const asKeyword = this.platform.usesAsKeyword() ? ' as ' : ' ';
207
- native.from(raw(`(${expression})${asKeyword}${this.platform.quoteIdentifier(qb.alias)}`));
208
- const query = native.compile();
209
- const res = await this.execute(query.sql, query.params, 'all', options.ctx);
210
- if (type === QueryType.COUNT) {
211
- return res[0].count;
212
- }
213
- if (isCursorPagination && !options.first && !!options.last) {
214
- res.reverse();
215
- }
216
- return res.map(row => this.mapResult(row, meta));
217
- }
218
- async *wrapVirtualExpressionInSubqueryStream(meta, expression, where, options, type) {
219
- const qb = await this.createQueryBuilderFromOptions(meta, where, this.forceBalancedStrategy(options));
220
- qb.unsetFlag(QueryFlag.DISABLE_PAGINATE);
221
- const native = qb.getNativeQuery(false);
222
- const asKeyword = this.platform.usesAsKeyword() ? ' as ' : ' ';
223
- native.from(raw(`(${expression})${asKeyword}${this.platform.quoteIdentifier(qb.alias)}`));
224
- const query = native.compile();
225
- const connectionType = this.resolveConnectionType({ ctx: options.ctx, connectionType: options.connectionType });
226
- const res = this.getConnection(connectionType).stream(query.sql, query.params, options.ctx, options.loggerContext);
227
- for await (const row of res) {
228
- yield this.mapResult(row, meta);
229
- }
127
+ return qb;
128
+ }
129
+ async find(entityName, where, options = {}) {
130
+ options = { populate: [], orderBy: [], ...options };
131
+ const meta = this.metadata.get(entityName);
132
+ if (meta.virtual) {
133
+ return this.findVirtual(entityName, where, options);
230
134
  }
231
- /**
232
- * Virtual entities have no PKs, so to-many populate joins can't be deduplicated.
233
- * Force balanced strategy to load to-many relations via separate queries.
234
- */
235
- forceBalancedStrategy(options) {
236
- const clearStrategy = (hints) => {
237
- return hints.map(hint => ({
238
- ...hint,
239
- strategy: undefined,
240
- children: hint.children ? clearStrategy(hint.children) : undefined,
241
- }));
242
- };
243
- const opts = { ...options, strategy: 'balanced' };
244
- if (Array.isArray(opts.populate)) {
245
- opts.populate = clearStrategy(opts.populate);
246
- }
247
- return opts;
135
+ if (options.unionWhere?.length) {
136
+ where = await this.applyUnionWhere(meta, where, options);
248
137
  }
249
- mapResult(result, meta, populate = [], qb, map = {}) {
250
- // For TPT inheritance, map aliased parent table columns back to their field names
251
- if (qb && meta.inheritanceType === 'tpt' && meta.tptParent) {
252
- this.mapTPTColumns(result, meta, qb);
253
- }
254
- // For TPT polymorphic queries (querying a base class), map child table fields
255
- if (qb && meta.inheritanceType === 'tpt' && meta.allTPTDescendants?.length) {
256
- const mainAlias = qb.mainAlias?.aliasName ?? 'e0';
257
- this.mapTPTChildFields(result, meta, mainAlias, qb, result);
258
- }
259
- const ret = super.mapResult(result, meta);
260
- /* v8 ignore next */
261
- if (!ret) {
262
- return null;
263
- }
264
- if (qb) {
265
- // here we map the aliased results (cartesian product) to an object graph
266
- this.mapJoinedProps(ret, meta, populate, qb, ret, map);
267
- }
268
- return ret;
269
- }
270
- /**
271
- * Maps aliased columns from TPT parent tables back to their original field names.
272
- * TPT parent columns are selected with aliases like `parent_alias__column_name`,
273
- * and need to be renamed back to `column_name` for the result mapper to work.
274
- */
275
- mapTPTColumns(result, meta, qb) {
276
- const tptAliases = qb.state.tptAlias;
277
- // Walk up the TPT hierarchy
278
- let parentMeta = meta.tptParent;
279
- while (parentMeta) {
280
- const parentAlias = tptAliases[parentMeta.className];
281
- if (parentAlias) {
282
- // Rename columns from this parent table
283
- for (const prop of parentMeta.ownProps) {
284
- if (!prop.fieldNames) {
285
- continue;
286
- }
287
- for (const fieldName of prop.fieldNames) {
288
- const aliasedKey = `${parentAlias}__${fieldName}`;
289
- if (aliasedKey in result) {
290
- // Copy the value to the unaliased field name and remove the aliased key
291
- result[fieldName] = result[aliasedKey];
292
- delete result[aliasedKey];
293
- }
294
- }
295
- }
296
- }
297
- parentMeta = parentMeta.tptParent;
298
- }
138
+ const qb = await this.createQueryBuilderFromOptions(meta, where, options);
139
+ const result = await this.rethrow(qb.execute('all'));
140
+ if (options.last && !options.first) {
141
+ result.reverse();
299
142
  }
300
- mapJoinedProps(result, meta, populate, qb, root, map, parentJoinPath) {
301
- const joinedProps = this.joinedProps(meta, populate);
302
- joinedProps.forEach(hint => {
303
- const [propName, ref] = hint.field.split(':', 2);
304
- const prop = meta.properties[propName];
305
- /* v8 ignore next */
306
- if (!prop) {
307
- return;
308
- }
309
- // Polymorphic to-one: iterate targets, find the matching one, build entity from its columns.
310
- // Skip :ref hints — no JOINs were created, so the FK reference is already set by the result mapper.
311
- if (prop.polymorphic &&
312
- prop.polymorphTargets?.length &&
313
- !ref &&
314
- [ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(prop.kind)) {
315
- const basePath = parentJoinPath ? `${parentJoinPath}.${prop.name}` : `${meta.name}.${prop.name}`;
316
- const pathPrefix = !parentJoinPath ? '[populate]' : '';
317
- let matched = false;
318
- for (const targetMeta of prop.polymorphTargets) {
319
- const targetPath = `${pathPrefix}${basePath}[${targetMeta.className}]`;
320
- const relationAlias = qb.getAliasForJoinPath(targetPath, { matchPopulateJoins: true });
321
- const meta2 = targetMeta;
322
- const targetProps = meta2.props.filter(p => this.platform.shouldHaveColumn(p, hint.children || []));
323
- const hasPK = meta2
324
- .getPrimaryProps()
325
- .every(pk => pk.fieldNames.every(name => root[`${relationAlias}__${name}`] != null));
326
- if (hasPK && !matched) {
327
- matched = true;
328
- const relationPojo = {};
329
- const tz = this.platform.getTimezone();
330
- for (const p of targetProps) {
331
- this.mapJoinedProp(relationPojo, p, relationAlias, root, tz, meta2);
332
- }
333
- // For TPT base targets, map child-specific fields and resolve the
334
- // concrete class so the factory creates the correct subtype.
335
- const concreteMeta = this.mapTPTChildFields(relationPojo, meta2, relationAlias, qb, root);
336
- Object.defineProperty(relationPojo, 'constructor', {
337
- value: concreteMeta?.class ?? meta2.class,
338
- enumerable: false,
339
- configurable: true,
340
- });
341
- result[prop.name] = relationPojo;
342
- const populateChildren = hint.children || [];
343
- this.mapJoinedProps(relationPojo, meta2, populateChildren, qb, root, map, targetPath);
344
- }
345
- // Clean up aliased columns for ALL targets (even non-matching ones)
346
- for (const p of targetProps) {
347
- for (const name of p.fieldNames) {
348
- delete root[`${relationAlias}__${name}`];
349
- }
350
- }
351
- }
352
- if (!matched) {
353
- result[prop.name] = null;
354
- }
355
- return;
356
- }
357
- const pivotRefJoin = prop.kind === ReferenceKind.MANY_TO_MANY && ref;
358
- const meta2 = prop.targetMeta;
359
- let path = parentJoinPath ? `${parentJoinPath}.${prop.name}` : `${meta.name}.${prop.name}`;
360
- if (!parentJoinPath) {
361
- path = '[populate]' + path;
362
- }
363
- if (pivotRefJoin) {
364
- path += '[pivot]';
365
- }
366
- const relationAlias = qb.getAliasForJoinPath(path, { matchPopulateJoins: true });
367
- /* v8 ignore next */
368
- if (!relationAlias) {
369
- return;
370
- }
371
- // pivot ref joins via joined strategy need to be handled separately here, as they dont join the target entity
372
- if (pivotRefJoin) {
373
- let item;
374
- if (prop.inverseJoinColumns.length > 1) {
375
- // composite keys
376
- item = prop.inverseJoinColumns.map(name => root[`${relationAlias}__${name}`]);
377
- }
378
- else {
379
- const alias = `${relationAlias}__${prop.inverseJoinColumns[0]}`;
380
- item = root[alias];
381
- }
382
- prop.joinColumns.forEach(name => delete root[`${relationAlias}__${name}`]);
383
- prop.inverseJoinColumns.forEach(name => delete root[`${relationAlias}__${name}`]);
384
- result[prop.name] ??= [];
385
- if (item) {
386
- result[prop.name].push(item);
387
- }
388
- return;
389
- }
390
- const mapToPk = !hint.dataOnly && !!(ref || prop.mapToPk);
391
- const targetProps = mapToPk
392
- ? meta2.getPrimaryProps()
393
- : meta2.props.filter(prop => this.platform.shouldHaveColumn(prop, hint.children || []));
394
- // If the primary key value for the relation is null, we know we haven't joined to anything
395
- // and therefore we don't return any record (since all values would be null)
396
- const hasPK = meta2.getPrimaryProps().every(pk => pk.fieldNames.every(name => {
397
- return root[`${relationAlias}__${name}`] != null;
398
- }));
399
- if (!hasPK) {
400
- if ([ReferenceKind.MANY_TO_MANY, ReferenceKind.ONE_TO_MANY].includes(prop.kind)) {
401
- result[prop.name] = [];
402
- }
403
- if ([ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(prop.kind)) {
404
- result[prop.name] = null;
405
- }
406
- for (const prop of targetProps) {
407
- for (const name of prop.fieldNames) {
408
- delete root[`${relationAlias}__${name}`];
409
- }
410
- }
411
- return;
412
- }
413
- let relationPojo = {};
414
- meta2.props
415
- .filter(prop => !ref && prop.persist === false && prop.fieldNames)
416
- .forEach(prop => {
417
- /* v8 ignore next */
418
- if (prop.fieldNames.length > 1) {
419
- // composite keys
420
- relationPojo[prop.name] = prop.fieldNames.map(name => root[`${relationAlias}__${name}`]);
421
- }
422
- else {
423
- const alias = `${relationAlias}__${prop.fieldNames[0]}`;
424
- relationPojo[prop.name] = root[alias];
425
- }
426
- });
143
+ return result;
144
+ }
145
+ async findOne(entityName, where, options) {
146
+ const opts = { populate: [], ...options };
147
+ const meta = this.metadata.find(entityName);
148
+ const populate = this.autoJoinOneToOneOwner(meta, opts.populate, opts.fields);
149
+ const joinedProps = this.joinedProps(meta, populate, options);
150
+ const hasToManyJoins = joinedProps.some(hint => this.hasToManyJoins(hint, meta));
151
+ if (joinedProps.length === 0 || !hasToManyJoins) {
152
+ opts.limit = 1;
153
+ }
154
+ if (opts.limit > 0 && !opts.flags?.includes(QueryFlag.DISABLE_PAGINATE)) {
155
+ opts.flags ??= [];
156
+ opts.flags.push(QueryFlag.DISABLE_PAGINATE);
157
+ }
158
+ const res = await this.find(entityName, where, opts);
159
+ return res[0] || null;
160
+ }
161
+ hasToManyJoins(hint, meta) {
162
+ const [propName] = hint.field.split(':', 2);
163
+ const prop = meta.properties[propName];
164
+ if (prop && [ReferenceKind.ONE_TO_MANY, ReferenceKind.MANY_TO_MANY].includes(prop.kind)) {
165
+ return true;
166
+ }
167
+ if (hint.children && prop.targetMeta) {
168
+ return hint.children.some(hint => this.hasToManyJoins(hint, prop.targetMeta));
169
+ }
170
+ return false;
171
+ }
172
+ async findVirtual(entityName, where, options) {
173
+ return this.findFromVirtual(entityName, where, options, QueryType.SELECT);
174
+ }
175
+ async countVirtual(entityName, where, options) {
176
+ return this.findFromVirtual(entityName, where, options, QueryType.COUNT);
177
+ }
178
+ async findFromVirtual(entityName, where, options, type) {
179
+ const meta = this.metadata.get(entityName);
180
+ /* v8 ignore next */
181
+ if (!meta.expression) {
182
+ return type === QueryType.SELECT ? [] : 0;
183
+ }
184
+ if (typeof meta.expression === 'string') {
185
+ return this.wrapVirtualExpressionInSubquery(meta, meta.expression, where, options, type);
186
+ }
187
+ const em = this.createEntityManager();
188
+ em.setTransactionContext(options.ctx);
189
+ const res = meta.expression(em, where, options);
190
+ if (typeof res === 'string') {
191
+ return this.wrapVirtualExpressionInSubquery(meta, res, where, options, type);
192
+ }
193
+ if (res instanceof QueryBuilder) {
194
+ return this.wrapVirtualExpressionInSubquery(meta, res.getFormattedQuery(), where, options, type);
195
+ }
196
+ if (isRaw(res)) {
197
+ const expr = this.platform.formatQuery(res.sql, res.params);
198
+ return this.wrapVirtualExpressionInSubquery(meta, expr, where, options, type);
199
+ }
200
+ /* v8 ignore next */
201
+ return res;
202
+ }
203
+ async *streamFromVirtual(entityName, where, options) {
204
+ const meta = this.metadata.get(entityName);
205
+ /* v8 ignore next */
206
+ if (!meta.expression) {
207
+ return;
208
+ }
209
+ if (typeof meta.expression === 'string') {
210
+ yield* this.wrapVirtualExpressionInSubqueryStream(meta, meta.expression, where, options, QueryType.SELECT);
211
+ return;
212
+ }
213
+ const em = this.createEntityManager();
214
+ em.setTransactionContext(options.ctx);
215
+ const res = meta.expression(em, where, options, true);
216
+ if (typeof res === 'string') {
217
+ yield* this.wrapVirtualExpressionInSubqueryStream(meta, res, where, options, QueryType.SELECT);
218
+ return;
219
+ }
220
+ if (res instanceof QueryBuilder) {
221
+ yield* this.wrapVirtualExpressionInSubqueryStream(
222
+ meta,
223
+ res.getFormattedQuery(),
224
+ where,
225
+ options,
226
+ QueryType.SELECT,
227
+ );
228
+ return;
229
+ }
230
+ if (isRaw(res)) {
231
+ const expr = this.platform.formatQuery(res.sql, res.params);
232
+ yield* this.wrapVirtualExpressionInSubqueryStream(meta, expr, where, options, QueryType.SELECT);
233
+ return;
234
+ }
235
+ /* v8 ignore next */
236
+ yield* res;
237
+ }
238
+ async wrapVirtualExpressionInSubquery(meta, expression, where, options, type) {
239
+ const qb = await this.createQueryBuilderFromOptions(meta, where, this.forceBalancedStrategy(options));
240
+ qb.setFlag(QueryFlag.DISABLE_PAGINATE);
241
+ const isCursorPagination = [options.first, options.last, options.before, options.after].some(v => v != null);
242
+ const native = qb.getNativeQuery(false);
243
+ if (type === QueryType.COUNT) {
244
+ native.clear('select').clear('limit').clear('offset').count();
245
+ }
246
+ const asKeyword = this.platform.usesAsKeyword() ? ' as ' : ' ';
247
+ native.from(raw(`(${expression})${asKeyword}${this.platform.quoteIdentifier(qb.alias)}`));
248
+ const query = native.compile();
249
+ const res = await this.execute(query.sql, query.params, 'all', options.ctx);
250
+ if (type === QueryType.COUNT) {
251
+ return res[0].count;
252
+ }
253
+ if (isCursorPagination && !options.first && !!options.last) {
254
+ res.reverse();
255
+ }
256
+ return res.map(row => this.mapResult(row, meta));
257
+ }
258
+ async *wrapVirtualExpressionInSubqueryStream(meta, expression, where, options, type) {
259
+ const qb = await this.createQueryBuilderFromOptions(meta, where, this.forceBalancedStrategy(options));
260
+ qb.unsetFlag(QueryFlag.DISABLE_PAGINATE);
261
+ const native = qb.getNativeQuery(false);
262
+ const asKeyword = this.platform.usesAsKeyword() ? ' as ' : ' ';
263
+ native.from(raw(`(${expression})${asKeyword}${this.platform.quoteIdentifier(qb.alias)}`));
264
+ const query = native.compile();
265
+ const connectionType = this.resolveConnectionType({ ctx: options.ctx, connectionType: options.connectionType });
266
+ const res = this.getConnection(connectionType).stream(query.sql, query.params, options.ctx, options.loggerContext);
267
+ for await (const row of res) {
268
+ yield this.mapResult(row, meta);
269
+ }
270
+ }
271
+ /**
272
+ * Virtual entities have no PKs, so to-many populate joins can't be deduplicated.
273
+ * Force balanced strategy to load to-many relations via separate queries.
274
+ */
275
+ forceBalancedStrategy(options) {
276
+ const clearStrategy = hints => {
277
+ return hints.map(hint => ({
278
+ ...hint,
279
+ strategy: undefined,
280
+ children: hint.children ? clearStrategy(hint.children) : undefined,
281
+ }));
282
+ };
283
+ const opts = { ...options, strategy: 'balanced' };
284
+ if (Array.isArray(opts.populate)) {
285
+ opts.populate = clearStrategy(opts.populate);
286
+ }
287
+ return opts;
288
+ }
289
+ mapResult(result, meta, populate = [], qb, map = {}) {
290
+ // For TPT inheritance, map aliased parent table columns back to their field names
291
+ if (qb && meta.inheritanceType === 'tpt' && meta.tptParent) {
292
+ this.mapTPTColumns(result, meta, qb);
293
+ }
294
+ // For TPT polymorphic queries (querying a base class), map child table fields
295
+ if (qb && meta.inheritanceType === 'tpt' && meta.allTPTDescendants?.length) {
296
+ const mainAlias = qb.mainAlias?.aliasName ?? 'e0';
297
+ this.mapTPTChildFields(result, meta, mainAlias, qb, result);
298
+ }
299
+ const ret = super.mapResult(result, meta);
300
+ /* v8 ignore next */
301
+ if (!ret) {
302
+ return null;
303
+ }
304
+ if (qb) {
305
+ // here we map the aliased results (cartesian product) to an object graph
306
+ this.mapJoinedProps(ret, meta, populate, qb, ret, map);
307
+ }
308
+ return ret;
309
+ }
310
+ /**
311
+ * Maps aliased columns from TPT parent tables back to their original field names.
312
+ * TPT parent columns are selected with aliases like `parent_alias__column_name`,
313
+ * and need to be renamed back to `column_name` for the result mapper to work.
314
+ */
315
+ mapTPTColumns(result, meta, qb) {
316
+ const tptAliases = qb.state.tptAlias;
317
+ // Walk up the TPT hierarchy
318
+ let parentMeta = meta.tptParent;
319
+ while (parentMeta) {
320
+ const parentAlias = tptAliases[parentMeta.className];
321
+ if (parentAlias) {
322
+ // Rename columns from this parent table
323
+ for (const prop of parentMeta.ownProps) {
324
+ if (!prop.fieldNames) {
325
+ continue;
326
+ }
327
+ for (const fieldName of prop.fieldNames) {
328
+ const aliasedKey = `${parentAlias}__${fieldName}`;
329
+ if (aliasedKey in result) {
330
+ // Copy the value to the unaliased field name and remove the aliased key
331
+ result[fieldName] = result[aliasedKey];
332
+ delete result[aliasedKey];
333
+ }
334
+ }
335
+ }
336
+ }
337
+ parentMeta = parentMeta.tptParent;
338
+ }
339
+ }
340
+ mapJoinedProps(result, meta, populate, qb, root, map, parentJoinPath) {
341
+ const joinedProps = this.joinedProps(meta, populate);
342
+ joinedProps.forEach(hint => {
343
+ const [propName, ref] = hint.field.split(':', 2);
344
+ const prop = meta.properties[propName];
345
+ /* v8 ignore next */
346
+ if (!prop) {
347
+ return;
348
+ }
349
+ // Polymorphic to-one: iterate targets, find the matching one, build entity from its columns.
350
+ // Skip :ref hints — no JOINs were created, so the FK reference is already set by the result mapper.
351
+ if (
352
+ prop.polymorphic &&
353
+ prop.polymorphTargets?.length &&
354
+ !ref &&
355
+ [ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(prop.kind)
356
+ ) {
357
+ const basePath = parentJoinPath ? `${parentJoinPath}.${prop.name}` : `${meta.name}.${prop.name}`;
358
+ const pathPrefix = !parentJoinPath ? '[populate]' : '';
359
+ let matched = false;
360
+ for (const targetMeta of prop.polymorphTargets) {
361
+ const targetPath = `${pathPrefix}${basePath}[${targetMeta.className}]`;
362
+ const relationAlias = qb.getAliasForJoinPath(targetPath, { matchPopulateJoins: true });
363
+ const meta2 = targetMeta;
364
+ const targetProps = meta2.props.filter(p => this.platform.shouldHaveColumn(p, hint.children || []));
365
+ const hasPK = meta2
366
+ .getPrimaryProps()
367
+ .every(pk => pk.fieldNames.every(name => root[`${relationAlias}__${name}`] != null));
368
+ if (hasPK && !matched) {
369
+ matched = true;
370
+ const relationPojo = {};
427
371
  const tz = this.platform.getTimezone();
428
- for (const prop of targetProps) {
429
- this.mapJoinedProp(relationPojo, prop, relationAlias, root, tz, meta2);
430
- }
431
- // Handle TPT polymorphic child fields - map fields from child table aliases
432
- this.mapTPTChildFields(relationPojo, meta2, relationAlias, qb, root);
433
- // properties can be mapped to multiple places, e.g. when sharing a column in multiple FKs,
434
- // so we need to delete them after everything is mapped from given level
435
- for (const prop of targetProps) {
436
- for (const name of prop.fieldNames) {
437
- delete root[`${relationAlias}__${name}`];
438
- }
439
- }
440
- if (mapToPk) {
441
- const tmp = Object.values(relationPojo);
442
- /* v8 ignore next */
443
- relationPojo = (meta2.compositePK ? tmp : tmp[0]);
444
- }
445
- if ([ReferenceKind.MANY_TO_MANY, ReferenceKind.ONE_TO_MANY].includes(prop.kind)) {
446
- result[prop.name] ??= [];
447
- result[prop.name].push(relationPojo);
448
- }
449
- else {
450
- result[prop.name] = relationPojo;
451
- }
372
+ for (const p of targetProps) {
373
+ this.mapJoinedProp(relationPojo, p, relationAlias, root, tz, meta2);
374
+ }
375
+ // For TPT base targets, map child-specific fields and resolve the
376
+ // concrete class so the factory creates the correct subtype.
377
+ const concreteMeta = this.mapTPTChildFields(relationPojo, meta2, relationAlias, qb, root);
378
+ Object.defineProperty(relationPojo, 'constructor', {
379
+ value: concreteMeta?.class ?? meta2.class,
380
+ enumerable: false,
381
+ configurable: true,
382
+ });
383
+ result[prop.name] = relationPojo;
452
384
  const populateChildren = hint.children || [];
453
- this.mapJoinedProps(relationPojo, meta2, populateChildren, qb, root, map, path);
454
- });
455
- }
456
- /**
457
- * Maps a single property from a joined result row into the relation pojo.
458
- * Handles polymorphic FKs, composite keys, Date parsing, and embedded objects.
459
- */
460
- mapJoinedProp(relationPojo, prop, relationAlias, root, tz, meta, options) {
461
- if (prop.fieldNames.every(name => typeof root[`${relationAlias}__${name}`] === 'undefined')) {
462
- return;
463
- }
464
- if (prop.polymorphic) {
465
- const discriminatorAlias = `${relationAlias}__${prop.fieldNames[0]}`;
466
- const discriminatorValue = root[discriminatorAlias];
467
- const pkFieldNames = prop.fieldNames.slice(1);
468
- const pkValues = pkFieldNames.map(name => root[`${relationAlias}__${name}`]);
469
- const pkValue = pkValues.length === 1 ? pkValues[0] : pkValues;
470
- if (discriminatorValue != null && pkValue != null) {
471
- relationPojo[prop.name] = new PolymorphicRef(discriminatorValue, pkValue);
472
- }
473
- else {
474
- relationPojo[prop.name] = null;
475
- }
476
- }
477
- else if (prop.fieldNames.length > 1) {
385
+ this.mapJoinedProps(relationPojo, meta2, populateChildren, qb, root, map, targetPath);
386
+ }
387
+ // Clean up aliased columns for ALL targets (even non-matching ones)
388
+ for (const p of targetProps) {
389
+ for (const name of p.fieldNames) {
390
+ delete root[`${relationAlias}__${name}`];
391
+ }
392
+ }
393
+ }
394
+ if (!matched) {
395
+ result[prop.name] = null;
396
+ }
397
+ return;
398
+ }
399
+ const pivotRefJoin = prop.kind === ReferenceKind.MANY_TO_MANY && ref;
400
+ const meta2 = prop.targetMeta;
401
+ let path = parentJoinPath ? `${parentJoinPath}.${prop.name}` : `${meta.name}.${prop.name}`;
402
+ if (!parentJoinPath) {
403
+ path = '[populate]' + path;
404
+ }
405
+ if (pivotRefJoin) {
406
+ path += '[pivot]';
407
+ }
408
+ const relationAlias = qb.getAliasForJoinPath(path, { matchPopulateJoins: true });
409
+ /* v8 ignore next */
410
+ if (!relationAlias) {
411
+ return;
412
+ }
413
+ // pivot ref joins via joined strategy need to be handled separately here, as they dont join the target entity
414
+ if (pivotRefJoin) {
415
+ let item;
416
+ if (prop.inverseJoinColumns.length > 1) {
417
+ // composite keys
418
+ item = prop.inverseJoinColumns.map(name => root[`${relationAlias}__${name}`]);
419
+ } else {
420
+ const alias = `${relationAlias}__${prop.inverseJoinColumns[0]}`;
421
+ item = root[alias];
422
+ }
423
+ prop.joinColumns.forEach(name => delete root[`${relationAlias}__${name}`]);
424
+ prop.inverseJoinColumns.forEach(name => delete root[`${relationAlias}__${name}`]);
425
+ result[prop.name] ??= [];
426
+ if (item) {
427
+ result[prop.name].push(item);
428
+ }
429
+ return;
430
+ }
431
+ const mapToPk = !hint.dataOnly && !!(ref || prop.mapToPk);
432
+ const targetProps = mapToPk
433
+ ? meta2.getPrimaryProps()
434
+ : meta2.props.filter(prop => this.platform.shouldHaveColumn(prop, hint.children || []));
435
+ // If the primary key value for the relation is null, we know we haven't joined to anything
436
+ // and therefore we don't return any record (since all values would be null)
437
+ const hasPK = meta2.getPrimaryProps().every(pk =>
438
+ pk.fieldNames.every(name => {
439
+ return root[`${relationAlias}__${name}`] != null;
440
+ }),
441
+ );
442
+ if (!hasPK) {
443
+ if ([ReferenceKind.MANY_TO_MANY, ReferenceKind.ONE_TO_MANY].includes(prop.kind)) {
444
+ result[prop.name] = [];
445
+ }
446
+ if ([ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(prop.kind)) {
447
+ result[prop.name] = null;
448
+ }
449
+ for (const prop of targetProps) {
450
+ for (const name of prop.fieldNames) {
451
+ delete root[`${relationAlias}__${name}`];
452
+ }
453
+ }
454
+ return;
455
+ }
456
+ let relationPojo = {};
457
+ meta2.props
458
+ .filter(prop => !ref && prop.persist === false && prop.fieldNames)
459
+ .forEach(prop => {
460
+ /* v8 ignore next */
461
+ if (prop.fieldNames.length > 1) {
478
462
  // composite keys
479
- const fk = prop.fieldNames.map(name => root[`${relationAlias}__${name}`]);
480
- const pk = Utils.mapFlatCompositePrimaryKey(fk, prop);
481
- relationPojo[prop.name] = pk.every(val => val != null) ? pk : null;
482
- }
483
- else if (prop.runtimeType === 'Date') {
484
- const alias = `${relationAlias}__${prop.fieldNames[0]}`;
485
- const value = root[alias];
486
- if (tz &&
487
- tz !== 'local' &&
488
- typeof value === 'string' &&
489
- !value.includes('+') &&
490
- value.lastIndexOf('-') < 11 &&
491
- !value.endsWith('Z')) {
492
- relationPojo[prop.name] = this.platform.parseDate(value + tz);
493
- }
494
- else if (['string', 'number'].includes(typeof value)) {
495
- relationPojo[prop.name] = this.platform.parseDate(value);
496
- }
497
- else {
498
- relationPojo[prop.name] = value;
499
- }
500
- }
501
- else {
463
+ relationPojo[prop.name] = prop.fieldNames.map(name => root[`${relationAlias}__${name}`]);
464
+ } else {
502
465
  const alias = `${relationAlias}__${prop.fieldNames[0]}`;
503
466
  relationPojo[prop.name] = root[alias];
504
- if (prop.kind === ReferenceKind.EMBEDDED && (prop.object || meta.embeddable)) {
505
- const item = parseJsonSafe(relationPojo[prop.name]);
506
- if (Array.isArray(item)) {
507
- relationPojo[prop.name] = item.map(row => row == null ? row : this.comparator.mapResult(prop.targetMeta, row));
508
- }
509
- else {
510
- relationPojo[prop.name] =
511
- item == null ? item : this.comparator.mapResult(prop.targetMeta, item);
512
- }
513
- }
514
- }
515
- if (options?.deleteFromRoot) {
516
- for (const name of prop.fieldNames) {
517
- delete root[`${relationAlias}__${name}`];
518
- }
519
- }
520
- }
521
- async count(entityName, where, options = {}) {
522
- const meta = this.metadata.get(entityName);
523
- if (meta.virtual) {
524
- return this.countVirtual(entityName, where, options);
525
- }
526
- if (options.unionWhere?.length) {
527
- where = await this.applyUnionWhere(meta, where, options);
528
- }
529
- options = { populate: [], ...options };
530
- const populate = options.populate;
531
- const joinedProps = this.joinedProps(meta, populate, options);
532
- const schema = this.getSchemaName(meta, options);
533
- const qb = this.createQueryBuilder(entityName, options.ctx, options.connectionType, false, options.logging);
534
- const populateWhere = this.buildPopulateWhere(meta, joinedProps, options);
535
- if (meta && !Utils.isEmpty(populate)) {
536
- this.buildFields(meta, populate, joinedProps, qb, qb.alias, options, schema);
537
- }
538
- this.validateSqlOptions(options);
539
- qb.state.resolvedPopulateWhere = options._populateWhere;
540
- qb.indexHint(options.indexHint)
541
- .collation(options.collation)
542
- .comment(options.comments)
543
- .hintComment(options.hintComments)
544
- .groupBy(options.groupBy)
545
- .having(options.having)
546
- .populate(populate, joinedProps.length > 0 ? populateWhere : undefined, joinedProps.length > 0 ? options.populateFilter : undefined)
547
- .withSchema(schema)
548
- .where(where);
549
- if (options.em) {
550
- await qb.applyJoinedFilters(options.em, options.filters);
551
- }
552
- return this.rethrow(qb.getCount());
553
- }
554
- async nativeInsert(entityName, data, options = {}) {
555
- options.convertCustomTypes ??= true;
556
- const meta = this.metadata.get(entityName);
557
- const collections = this.extractManyToMany(meta, data);
558
- const qb = this.createQueryBuilder(entityName, options.ctx, 'write', options.convertCustomTypes, options.loggerContext).withSchema(this.getSchemaName(meta, options));
559
- const res = await this.rethrow(qb.insert(data).execute('run', false));
560
- res.row = res.row || {};
561
- let pk;
562
- if (meta.primaryKeys.length > 1) {
563
- // owner has composite pk
564
- pk = Utils.getPrimaryKeyCond(data, meta.primaryKeys);
565
- }
566
- else {
567
- /* v8 ignore next */
568
- res.insertId = data[meta.primaryKeys[0]] ?? res.insertId ?? res.row[meta.primaryKeys[0]];
569
- if (options.convertCustomTypes && meta?.getPrimaryProp().customType) {
570
- pk = [meta.getPrimaryProp().customType.convertToDatabaseValue(res.insertId, this.platform)];
571
- }
572
- else {
573
- pk = [res.insertId];
574
- }
575
- }
576
- await this.processManyToMany(meta, pk, collections, false, options);
577
- return res;
578
- }
579
- async nativeInsertMany(entityName, data, options = {}, transform) {
580
- options.processCollections ??= true;
581
- options.convertCustomTypes ??= true;
582
- const entityMeta = this.metadata.get(entityName);
583
- const meta = entityMeta.inheritanceType === 'tpt' ? entityMeta : entityMeta.root;
584
- const collections = options.processCollections ? data.map(d => this.extractManyToMany(meta, d)) : [];
585
- const pks = this.getPrimaryKeyFields(meta);
586
- const set = new Set();
587
- data.forEach(row => Utils.keys(row).forEach(k => set.add(k)));
588
- const props = [...set].map(name => meta.properties[name] ?? { name, fieldNames: [name] });
589
- // For STI with conflicting fieldNames, include all alternative columns
590
- let fields = Utils.flatten(props.map(prop => prop.stiFieldNames ?? prop.fieldNames));
591
- const duplicates = Utils.findDuplicates(fields);
592
- const params = [];
593
- if (duplicates.length) {
594
- fields = Utils.unique(fields);
595
- }
596
- const tableName = this.getTableName(meta, options);
597
- let sql = `insert into ${tableName} `;
598
- sql +=
599
- fields.length > 0
600
- ? '(' + fields.map(k => this.platform.quoteIdentifier(k)).join(', ') + ')'
601
- : `(${this.platform.quoteIdentifier(pks[0])})`;
602
- if (this.platform.usesOutputStatement()) {
603
- const returningProps = this.getTableProps(meta)
604
- .filter(prop => (prop.persist !== false && prop.defaultRaw) || prop.autoincrement || prop.generated)
605
- .filter(prop => !(prop.name in data[0]) || isRaw(data[0][prop.name]));
606
- const returningFields = Utils.flatten(returningProps.map(prop => prop.fieldNames));
607
- sql +=
608
- returningFields.length > 0
609
- ? ` output ${returningFields.map(field => 'inserted.' + this.platform.quoteIdentifier(field)).join(', ')}`
610
- : '';
611
- }
612
- if (fields.length > 0 || this.platform.usesDefaultKeyword()) {
613
- sql += ' values ';
614
- }
615
- else {
616
- sql += ' ' + data.map(() => `select null as ${this.platform.quoteIdentifier(pks[0])}`).join(' union all ');
617
- }
618
- const addParams = (prop, row) => {
619
- const rowValue = row[prop.name];
620
- if (prop.nullable && rowValue === null) {
621
- params.push(null);
622
- return;
623
- }
624
- let value = rowValue ?? prop.default;
625
- if (prop.kind === ReferenceKind.EMBEDDED && prop.object) {
626
- if (prop.array && value) {
627
- value = this.platform.cloneEmbeddable(value);
628
- for (let i = 0; i < value.length; i++) {
629
- const item = value[i];
630
- value[i] = this.mapDataToFieldNames(item, false, prop.embeddedProps, options.convertCustomTypes);
631
- }
632
- }
633
- else {
634
- value = this.mapDataToFieldNames(value, false, prop.embeddedProps, options.convertCustomTypes);
635
- }
636
- }
637
- if (typeof value === 'undefined' && this.platform.usesDefaultKeyword()) {
638
- params.push(raw('default'));
639
- return;
640
- }
641
- if (options.convertCustomTypes && prop.customType) {
642
- params.push(prop.customType.convertToDatabaseValue(value, this.platform, { key: prop.name, mode: 'query-data' }));
643
- return;
644
- }
645
- params.push(value);
646
- };
647
- if (fields.length > 0 || this.platform.usesDefaultKeyword()) {
648
- sql += data
649
- .map(row => {
650
- const keys = [];
651
- const usedDups = [];
652
- props.forEach(prop => {
653
- // For STI with conflicting fieldNames, use discriminator to determine which field gets value
654
- if (prop.stiFieldNames && prop.stiFieldNameMap && meta.discriminatorColumn) {
655
- const activeField = prop.stiFieldNameMap[row[meta.discriminatorColumn]];
656
- for (const field of prop.stiFieldNames) {
657
- params.push(field === activeField ? row[prop.name] : null);
658
- keys.push('?');
659
- }
660
- return;
661
- }
662
- if (prop.fieldNames.length > 1) {
663
- const newFields = [];
664
- let rawParam;
665
- const target = row[prop.name];
666
- if (prop.polymorphic && target instanceof PolymorphicRef) {
667
- rawParam = target.toTuple();
668
- }
669
- else {
670
- rawParam = target == null ? prop.fieldNames.map(() => null) : Utils.asArray(target);
671
- }
672
- // Deep flatten nested arrays when needed (for deeply nested composite keys like Tag -> Comment -> Post -> User)
673
- const needsFlatten = rawParam.length !== prop.fieldNames.length && rawParam.some(v => Array.isArray(v));
674
- const allParam = needsFlatten ? Utils.flatten(rawParam, true) : rawParam;
675
- // TODO(v7): instead of making this conditional here, the entity snapshot should respect `ownColumns`,
676
- // but that means changing the compiled PK getters, which might be seen as breaking
677
- const columns = allParam.length > 1 ? prop.fieldNames : prop.ownColumns;
678
- const param = [];
679
- columns.forEach((field, idx) => {
680
- if (usedDups.includes(field)) {
681
- return;
682
- }
683
- newFields.push(field);
684
- param.push(allParam[idx]);
685
- });
686
- newFields.forEach((field, idx) => {
687
- if (!duplicates.includes(field) || !usedDups.includes(field)) {
688
- params.push(param[idx]);
689
- keys.push('?');
690
- usedDups.push(field);
691
- }
692
- });
693
- }
694
- else {
695
- const field = prop.fieldNames[0];
696
- if (!duplicates.includes(field) || !usedDups.includes(field)) {
697
- if (prop.customType &&
698
- !prop.object &&
699
- 'convertToDatabaseValueSQL' in prop.customType &&
700
- row[prop.name] != null &&
701
- !isRaw(row[prop.name])) {
702
- keys.push(prop.customType.convertToDatabaseValueSQL('?', this.platform));
703
- }
704
- else {
705
- keys.push('?');
706
- }
707
- addParams(prop, row);
708
- usedDups.push(field);
709
- }
710
- }
711
- });
712
- return '(' + (keys.join(', ') || 'default') + ')';
713
- })
714
- .join(', ');
715
- }
716
- if (meta && this.platform.usesReturningStatement()) {
717
- const returningProps = this.getTableProps(meta)
718
- .filter(prop => (prop.persist !== false && prop.defaultRaw) || prop.autoincrement || prop.generated)
719
- .filter(prop => !(prop.name in data[0]) || isRaw(data[0][prop.name]));
720
- const returningFields = Utils.flatten(returningProps.map(prop => prop.fieldNames));
721
- /* v8 ignore next */
722
- sql +=
723
- returningFields.length > 0
724
- ? ` returning ${returningFields.map(field => this.platform.quoteIdentifier(field)).join(', ')}`
725
- : '';
726
- }
727
- if (transform) {
728
- sql = transform(sql);
729
- }
730
- const res = await this.execute(sql, params, 'run', options.ctx, options.loggerContext);
731
- let pk;
467
+ }
468
+ });
469
+ const tz = this.platform.getTimezone();
470
+ for (const prop of targetProps) {
471
+ this.mapJoinedProp(relationPojo, prop, relationAlias, root, tz, meta2);
472
+ }
473
+ // Handle TPT polymorphic child fields - map fields from child table aliases
474
+ this.mapTPTChildFields(relationPojo, meta2, relationAlias, qb, root);
475
+ // properties can be mapped to multiple places, e.g. when sharing a column in multiple FKs,
476
+ // so we need to delete them after everything is mapped from given level
477
+ for (const prop of targetProps) {
478
+ for (const name of prop.fieldNames) {
479
+ delete root[`${relationAlias}__${name}`];
480
+ }
481
+ }
482
+ if (mapToPk) {
483
+ const tmp = Object.values(relationPojo);
732
484
  /* v8 ignore next */
733
- if (pks.length > 1) {
734
- // owner has composite pk
735
- pk = data.map(d => Utils.getPrimaryKeyCond(d, pks));
736
- }
737
- else {
738
- res.row ??= {};
739
- res.rows ??= [];
740
- pk = data.map((d, i) => d[pks[0]] ?? res.rows[i]?.[pks[0]]).map(d => [d]);
741
- res.insertId = res.insertId || res.row[pks[0]];
742
- }
743
- for (let i = 0; i < collections.length; i++) {
744
- await this.processManyToMany(meta, pk[i], collections[i], false, options);
745
- }
746
- return res;
747
- }
748
- async nativeUpdate(entityName, where, data, options = {}) {
749
- options.convertCustomTypes ??= true;
750
- const meta = this.metadata.get(entityName);
751
- const pks = this.getPrimaryKeyFields(meta);
752
- const collections = this.extractManyToMany(meta, data);
753
- let res = { affectedRows: 0, insertId: 0, row: {} };
754
- if (Utils.isPrimaryKey(where) && pks.length === 1) {
755
- /* v8 ignore next */
756
- where = { [meta.primaryKeys[0] ?? pks[0]]: where };
757
- }
758
- if (!options.upsert && options.unionWhere?.length) {
759
- where = (await this.applyUnionWhere(meta, where, options, true));
760
- }
761
- if (Utils.hasObjectKeys(data)) {
762
- const qb = this.createQueryBuilder(entityName, options.ctx, 'write', options.convertCustomTypes, options.loggerContext).withSchema(this.getSchemaName(meta, options));
763
- if (options.upsert) {
764
- /* v8 ignore next */
765
- const uniqueFields = options.onConflictFields ??
766
- (Utils.isPlainObject(where) ? Utils.keys(where) : meta.primaryKeys);
767
- const returning = getOnConflictReturningFields(meta, data, uniqueFields, options);
768
- qb.insert(data)
769
- .onConflict(uniqueFields)
770
- .returning(returning);
771
- if (!options.onConflictAction || options.onConflictAction === 'merge') {
772
- const fields = getOnConflictFields(meta, data, uniqueFields, options);
773
- qb.merge(fields);
485
+ relationPojo = meta2.compositePK ? tmp : tmp[0];
486
+ }
487
+ if ([ReferenceKind.MANY_TO_MANY, ReferenceKind.ONE_TO_MANY].includes(prop.kind)) {
488
+ result[prop.name] ??= [];
489
+ result[prop.name].push(relationPojo);
490
+ } else {
491
+ result[prop.name] = relationPojo;
492
+ }
493
+ const populateChildren = hint.children || [];
494
+ this.mapJoinedProps(relationPojo, meta2, populateChildren, qb, root, map, path);
495
+ });
496
+ }
497
+ /**
498
+ * Maps a single property from a joined result row into the relation pojo.
499
+ * Handles polymorphic FKs, composite keys, Date parsing, and embedded objects.
500
+ */
501
+ mapJoinedProp(relationPojo, prop, relationAlias, root, tz, meta, options) {
502
+ if (prop.fieldNames.every(name => typeof root[`${relationAlias}__${name}`] === 'undefined')) {
503
+ return;
504
+ }
505
+ if (prop.polymorphic) {
506
+ const discriminatorAlias = `${relationAlias}__${prop.fieldNames[0]}`;
507
+ const discriminatorValue = root[discriminatorAlias];
508
+ const pkFieldNames = prop.fieldNames.slice(1);
509
+ const pkValues = pkFieldNames.map(name => root[`${relationAlias}__${name}`]);
510
+ const pkValue = pkValues.length === 1 ? pkValues[0] : pkValues;
511
+ if (discriminatorValue != null && pkValue != null) {
512
+ relationPojo[prop.name] = new PolymorphicRef(discriminatorValue, pkValue);
513
+ } else {
514
+ relationPojo[prop.name] = null;
515
+ }
516
+ } else if (prop.fieldNames.length > 1) {
517
+ // composite keys
518
+ const fk = prop.fieldNames.map(name => root[`${relationAlias}__${name}`]);
519
+ const pk = Utils.mapFlatCompositePrimaryKey(fk, prop);
520
+ relationPojo[prop.name] = pk.every(val => val != null) ? pk : null;
521
+ } else if (prop.runtimeType === 'Date') {
522
+ const alias = `${relationAlias}__${prop.fieldNames[0]}`;
523
+ const value = root[alias];
524
+ if (
525
+ tz &&
526
+ tz !== 'local' &&
527
+ typeof value === 'string' &&
528
+ !value.includes('+') &&
529
+ value.lastIndexOf('-') < 11 &&
530
+ !value.endsWith('Z')
531
+ ) {
532
+ relationPojo[prop.name] = this.platform.parseDate(value + tz);
533
+ } else if (['string', 'number'].includes(typeof value)) {
534
+ relationPojo[prop.name] = this.platform.parseDate(value);
535
+ } else {
536
+ relationPojo[prop.name] = value;
537
+ }
538
+ } else {
539
+ const alias = `${relationAlias}__${prop.fieldNames[0]}`;
540
+ relationPojo[prop.name] = root[alias];
541
+ if (prop.kind === ReferenceKind.EMBEDDED && (prop.object || meta.embeddable)) {
542
+ const item = parseJsonSafe(relationPojo[prop.name]);
543
+ if (Array.isArray(item)) {
544
+ relationPojo[prop.name] = item.map(row =>
545
+ row == null ? row : this.comparator.mapResult(prop.targetMeta, row),
546
+ );
547
+ } else {
548
+ relationPojo[prop.name] = item == null ? item : this.comparator.mapResult(prop.targetMeta, item);
549
+ }
550
+ }
551
+ }
552
+ if (options?.deleteFromRoot) {
553
+ for (const name of prop.fieldNames) {
554
+ delete root[`${relationAlias}__${name}`];
555
+ }
556
+ }
557
+ }
558
+ async count(entityName, where, options = {}) {
559
+ const meta = this.metadata.get(entityName);
560
+ if (meta.virtual) {
561
+ return this.countVirtual(entityName, where, options);
562
+ }
563
+ if (options.unionWhere?.length) {
564
+ where = await this.applyUnionWhere(meta, where, options);
565
+ }
566
+ options = { populate: [], ...options };
567
+ const populate = options.populate;
568
+ const joinedProps = this.joinedProps(meta, populate, options);
569
+ const schema = this.getSchemaName(meta, options);
570
+ const qb = this.createQueryBuilder(entityName, options.ctx, options.connectionType, false, options.logging);
571
+ const populateWhere = this.buildPopulateWhere(meta, joinedProps, options);
572
+ if (meta && !Utils.isEmpty(populate)) {
573
+ this.buildFields(meta, populate, joinedProps, qb, qb.alias, options, schema);
574
+ }
575
+ this.validateSqlOptions(options);
576
+ qb.state.resolvedPopulateWhere = options._populateWhere;
577
+ qb.indexHint(options.indexHint)
578
+ .collation(options.collation)
579
+ .comment(options.comments)
580
+ .hintComment(options.hintComments)
581
+ .groupBy(options.groupBy)
582
+ .having(options.having)
583
+ .populate(
584
+ populate,
585
+ joinedProps.length > 0 ? populateWhere : undefined,
586
+ joinedProps.length > 0 ? options.populateFilter : undefined,
587
+ )
588
+ .withSchema(schema)
589
+ .where(where);
590
+ if (options.em) {
591
+ await qb.applyJoinedFilters(options.em, options.filters);
592
+ }
593
+ return this.rethrow(qb.getCount());
594
+ }
595
+ async nativeInsert(entityName, data, options = {}) {
596
+ options.convertCustomTypes ??= true;
597
+ const meta = this.metadata.get(entityName);
598
+ const collections = this.extractManyToMany(meta, data);
599
+ const qb = this.createQueryBuilder(
600
+ entityName,
601
+ options.ctx,
602
+ 'write',
603
+ options.convertCustomTypes,
604
+ options.loggerContext,
605
+ ).withSchema(this.getSchemaName(meta, options));
606
+ const res = await this.rethrow(qb.insert(data).execute('run', false));
607
+ res.row = res.row || {};
608
+ let pk;
609
+ if (meta.primaryKeys.length > 1) {
610
+ // owner has composite pk
611
+ pk = Utils.getPrimaryKeyCond(data, meta.primaryKeys);
612
+ } else {
613
+ /* v8 ignore next */
614
+ res.insertId = data[meta.primaryKeys[0]] ?? res.insertId ?? res.row[meta.primaryKeys[0]];
615
+ if (options.convertCustomTypes && meta?.getPrimaryProp().customType) {
616
+ pk = [meta.getPrimaryProp().customType.convertToDatabaseValue(res.insertId, this.platform)];
617
+ } else {
618
+ pk = [res.insertId];
619
+ }
620
+ }
621
+ await this.processManyToMany(meta, pk, collections, false, options);
622
+ return res;
623
+ }
624
+ async nativeInsertMany(entityName, data, options = {}, transform) {
625
+ options.processCollections ??= true;
626
+ options.convertCustomTypes ??= true;
627
+ const entityMeta = this.metadata.get(entityName);
628
+ const meta = entityMeta.inheritanceType === 'tpt' ? entityMeta : entityMeta.root;
629
+ const collections = options.processCollections ? data.map(d => this.extractManyToMany(meta, d)) : [];
630
+ const pks = this.getPrimaryKeyFields(meta);
631
+ const set = new Set();
632
+ data.forEach(row => Utils.keys(row).forEach(k => set.add(k)));
633
+ const props = [...set].map(name => meta.properties[name] ?? { name, fieldNames: [name] });
634
+ // For STI with conflicting fieldNames, include all alternative columns
635
+ let fields = Utils.flatten(props.map(prop => prop.stiFieldNames ?? prop.fieldNames));
636
+ const duplicates = Utils.findDuplicates(fields);
637
+ const params = [];
638
+ if (duplicates.length) {
639
+ fields = Utils.unique(fields);
640
+ }
641
+ const tableName = this.getTableName(meta, options);
642
+ let sql = `insert into ${tableName} `;
643
+ sql +=
644
+ fields.length > 0
645
+ ? '(' + fields.map(k => this.platform.quoteIdentifier(k)).join(', ') + ')'
646
+ : `(${this.platform.quoteIdentifier(pks[0])})`;
647
+ if (this.platform.usesOutputStatement()) {
648
+ const returningProps = this.getTableProps(meta)
649
+ .filter(prop => (prop.persist !== false && prop.defaultRaw) || prop.autoincrement || prop.generated)
650
+ .filter(prop => !(prop.name in data[0]) || isRaw(data[0][prop.name]));
651
+ const returningFields = Utils.flatten(returningProps.map(prop => prop.fieldNames));
652
+ sql +=
653
+ returningFields.length > 0
654
+ ? ` output ${returningFields.map(field => 'inserted.' + this.platform.quoteIdentifier(field)).join(', ')}`
655
+ : '';
656
+ }
657
+ if (fields.length > 0 || this.platform.usesDefaultKeyword()) {
658
+ sql += ' values ';
659
+ } else {
660
+ sql += ' ' + data.map(() => `select null as ${this.platform.quoteIdentifier(pks[0])}`).join(' union all ');
661
+ }
662
+ const addParams = (prop, row) => {
663
+ const rowValue = row[prop.name];
664
+ if (prop.nullable && rowValue === null) {
665
+ params.push(null);
666
+ return;
667
+ }
668
+ let value = rowValue ?? prop.default;
669
+ if (prop.kind === ReferenceKind.EMBEDDED && prop.object) {
670
+ if (prop.array && value) {
671
+ value = this.platform.cloneEmbeddable(value);
672
+ for (let i = 0; i < value.length; i++) {
673
+ const item = value[i];
674
+ value[i] = this.mapDataToFieldNames(item, false, prop.embeddedProps, options.convertCustomTypes);
675
+ }
676
+ } else {
677
+ value = this.mapDataToFieldNames(value, false, prop.embeddedProps, options.convertCustomTypes);
678
+ }
679
+ }
680
+ if (typeof value === 'undefined' && this.platform.usesDefaultKeyword()) {
681
+ params.push(raw('default'));
682
+ return;
683
+ }
684
+ if (options.convertCustomTypes && prop.customType) {
685
+ params.push(
686
+ prop.customType.convertToDatabaseValue(value, this.platform, { key: prop.name, mode: 'query-data' }),
687
+ );
688
+ return;
689
+ }
690
+ params.push(value);
691
+ };
692
+ if (fields.length > 0 || this.platform.usesDefaultKeyword()) {
693
+ sql += data
694
+ .map(row => {
695
+ const keys = [];
696
+ const usedDups = [];
697
+ props.forEach(prop => {
698
+ // For STI with conflicting fieldNames, use discriminator to determine which field gets value
699
+ if (prop.stiFieldNames && prop.stiFieldNameMap && meta.discriminatorColumn) {
700
+ const activeField = prop.stiFieldNameMap[row[meta.discriminatorColumn]];
701
+ for (const field of prop.stiFieldNames) {
702
+ params.push(field === activeField ? row[prop.name] : null);
703
+ keys.push('?');
704
+ }
705
+ return;
706
+ }
707
+ if (prop.fieldNames.length > 1) {
708
+ const newFields = [];
709
+ let rawParam;
710
+ const target = row[prop.name];
711
+ if (prop.polymorphic && target instanceof PolymorphicRef) {
712
+ rawParam = target.toTuple();
713
+ } else {
714
+ rawParam = target == null ? prop.fieldNames.map(() => null) : Utils.asArray(target);
715
+ }
716
+ // Deep flatten nested arrays when needed (for deeply nested composite keys like Tag -> Comment -> Post -> User)
717
+ const needsFlatten = rawParam.length !== prop.fieldNames.length && rawParam.some(v => Array.isArray(v));
718
+ const allParam = needsFlatten ? Utils.flatten(rawParam, true) : rawParam;
719
+ // TODO(v7): instead of making this conditional here, the entity snapshot should respect `ownColumns`,
720
+ // but that means changing the compiled PK getters, which might be seen as breaking
721
+ const columns = allParam.length > 1 ? prop.fieldNames : prop.ownColumns;
722
+ const param = [];
723
+ columns.forEach((field, idx) => {
724
+ if (usedDups.includes(field)) {
725
+ return;
774
726
  }
775
- if (options.onConflictAction === 'ignore') {
776
- qb.ignore();
727
+ newFields.push(field);
728
+ param.push(allParam[idx]);
729
+ });
730
+ newFields.forEach((field, idx) => {
731
+ if (!duplicates.includes(field) || !usedDups.includes(field)) {
732
+ params.push(param[idx]);
733
+ keys.push('?');
734
+ usedDups.push(field);
777
735
  }
778
- if (options.onConflictWhere) {
779
- qb.where(options.onConflictWhere);
736
+ });
737
+ } else {
738
+ const field = prop.fieldNames[0];
739
+ if (!duplicates.includes(field) || !usedDups.includes(field)) {
740
+ if (
741
+ prop.customType &&
742
+ !prop.object &&
743
+ 'convertToDatabaseValueSQL' in prop.customType &&
744
+ row[prop.name] != null &&
745
+ !isRaw(row[prop.name])
746
+ ) {
747
+ keys.push(prop.customType.convertToDatabaseValueSQL('?', this.platform));
748
+ } else {
749
+ keys.push('?');
780
750
  }
781
- }
782
- else {
783
- qb.update(data).where(where);
784
- // reload generated columns and version fields
785
- const returning = [];
786
- meta.props
787
- .filter(prop => (prop.generated && !prop.primary) || prop.version)
788
- .forEach(prop => returning.push(prop.name));
789
- qb.returning(returning);
790
- }
791
- res = await this.rethrow(qb.execute('run', false));
792
- }
751
+ addParams(prop, row);
752
+ usedDups.push(field);
753
+ }
754
+ }
755
+ });
756
+ return '(' + (keys.join(', ') || 'default') + ')';
757
+ })
758
+ .join(', ');
759
+ }
760
+ if (meta && this.platform.usesReturningStatement()) {
761
+ const returningProps = this.getTableProps(meta)
762
+ .filter(prop => (prop.persist !== false && prop.defaultRaw) || prop.autoincrement || prop.generated)
763
+ .filter(prop => !(prop.name in data[0]) || isRaw(data[0][prop.name]));
764
+ const returningFields = Utils.flatten(returningProps.map(prop => prop.fieldNames));
765
+ /* v8 ignore next */
766
+ sql +=
767
+ returningFields.length > 0
768
+ ? ` returning ${returningFields.map(field => this.platform.quoteIdentifier(field)).join(', ')}`
769
+ : '';
770
+ }
771
+ if (transform) {
772
+ sql = transform(sql);
773
+ }
774
+ const res = await this.execute(sql, params, 'run', options.ctx, options.loggerContext);
775
+ let pk;
776
+ /* v8 ignore next */
777
+ if (pks.length > 1) {
778
+ // owner has composite pk
779
+ pk = data.map(d => Utils.getPrimaryKeyCond(d, pks));
780
+ } else {
781
+ res.row ??= {};
782
+ res.rows ??= [];
783
+ pk = data.map((d, i) => d[pks[0]] ?? res.rows[i]?.[pks[0]]).map(d => [d]);
784
+ res.insertId = res.insertId || res.row[pks[0]];
785
+ }
786
+ for (let i = 0; i < collections.length; i++) {
787
+ await this.processManyToMany(meta, pk[i], collections[i], false, options);
788
+ }
789
+ return res;
790
+ }
791
+ async nativeUpdate(entityName, where, data, options = {}) {
792
+ options.convertCustomTypes ??= true;
793
+ const meta = this.metadata.get(entityName);
794
+ const pks = this.getPrimaryKeyFields(meta);
795
+ const collections = this.extractManyToMany(meta, data);
796
+ let res = { affectedRows: 0, insertId: 0, row: {} };
797
+ if (Utils.isPrimaryKey(where) && pks.length === 1) {
798
+ /* v8 ignore next */
799
+ where = { [meta.primaryKeys[0] ?? pks[0]]: where };
800
+ }
801
+ if (!options.upsert && options.unionWhere?.length) {
802
+ where = await this.applyUnionWhere(meta, where, options, true);
803
+ }
804
+ if (Utils.hasObjectKeys(data)) {
805
+ const qb = this.createQueryBuilder(
806
+ entityName,
807
+ options.ctx,
808
+ 'write',
809
+ options.convertCustomTypes,
810
+ options.loggerContext,
811
+ ).withSchema(this.getSchemaName(meta, options));
812
+ if (options.upsert) {
793
813
  /* v8 ignore next */
794
- const pk = pks.map(pk => Utils.extractPK(data[pk] || where, meta));
795
- await this.processManyToMany(meta, pk, collections, true, options);
796
- return res;
797
- }
798
- async nativeUpdateMany(entityName, where, data, options = {}, transform) {
799
- options.processCollections ??= true;
800
- options.convertCustomTypes ??= true;
801
- const meta = this.metadata.get(entityName);
802
- if (options.upsert) {
803
- const uniqueFields = options.onConflictFields ??
804
- (Utils.isPlainObject(where[0])
805
- ? Object.keys(where[0]).flatMap(key => Utils.splitPrimaryKeys(key))
806
- : meta.primaryKeys);
807
- const qb = this.createQueryBuilder(entityName, options.ctx, 'write', options.convertCustomTypes, options.loggerContext).withSchema(this.getSchemaName(meta, options));
808
- const returning = getOnConflictReturningFields(meta, data[0], uniqueFields, options);
809
- qb.insert(data)
810
- .onConflict(uniqueFields)
811
- .returning(returning);
812
- if (!options.onConflictAction || options.onConflictAction === 'merge') {
813
- const fields = getOnConflictFields(meta, data[0], uniqueFields, options);
814
- qb.merge(fields);
815
- }
816
- if (options.onConflictAction === 'ignore') {
817
- qb.ignore();
818
- }
819
- if (options.onConflictWhere) {
820
- qb.where(options.onConflictWhere);
821
- }
822
- return this.rethrow(qb.execute('run', false));
823
- }
824
- const collections = options.processCollections ? data.map(d => this.extractManyToMany(meta, d)) : [];
825
- const keys = new Set();
826
- const fields = new Set();
827
- const returning = new Set();
828
- for (const row of data) {
829
- for (const k of Utils.keys(row)) {
830
- keys.add(k);
831
- if (isRaw(row[k])) {
832
- returning.add(k);
833
- }
834
- }
835
- }
814
+ const uniqueFields =
815
+ options.onConflictFields ?? (Utils.isPlainObject(where) ? Utils.keys(where) : meta.primaryKeys);
816
+ const returning = getOnConflictReturningFields(meta, data, uniqueFields, options);
817
+ qb.insert(data).onConflict(uniqueFields).returning(returning);
818
+ if (!options.onConflictAction || options.onConflictAction === 'merge') {
819
+ const fields = getOnConflictFields(meta, data, uniqueFields, options);
820
+ qb.merge(fields);
821
+ }
822
+ if (options.onConflictAction === 'ignore') {
823
+ qb.ignore();
824
+ }
825
+ if (options.onConflictWhere) {
826
+ qb.where(options.onConflictWhere);
827
+ }
828
+ } else {
829
+ qb.update(data).where(where);
836
830
  // reload generated columns and version fields
837
- meta.props.filter(prop => prop.generated || prop.version || prop.primary).forEach(prop => returning.add(prop.name));
838
- const pkCond = Utils.flatten(meta.primaryKeys.map(pk => meta.properties[pk].fieldNames))
839
- .map(pk => `${this.platform.quoteIdentifier(pk)} = ?`)
840
- .join(' and ');
841
- const params = [];
842
- let sql = `update ${this.getTableName(meta, options)} set `;
843
- const addParams = (prop, value) => {
844
- if (prop.kind === ReferenceKind.EMBEDDED && prop.object) {
845
- if (prop.array && value) {
846
- for (let i = 0; i < value.length; i++) {
847
- const item = value[i];
848
- value[i] = this.mapDataToFieldNames(item, false, prop.embeddedProps, options.convertCustomTypes);
849
- }
850
- }
851
- else {
852
- value = this.mapDataToFieldNames(value, false, prop.embeddedProps, options.convertCustomTypes);
853
- }
854
- }
855
- params.push(value ?? null);
856
- };
857
- for (const key of keys) {
858
- const prop = meta.properties[key] ?? meta.root.properties[key];
859
- if (prop.polymorphic && prop.fieldNames.length > 1) {
860
- for (let idx = 0; idx < data.length; idx++) {
861
- const rowValue = data[idx][key];
862
- if (rowValue instanceof PolymorphicRef) {
863
- data[idx][key] = rowValue.toTuple();
864
- }
865
- }
866
- }
867
- prop.fieldNames.forEach((fieldName, fieldNameIdx) => {
868
- if (fields.has(fieldName) || (prop.ownColumns && !prop.ownColumns.includes(fieldName))) {
869
- return;
870
- }
871
- fields.add(fieldName);
872
- sql += `${this.platform.quoteIdentifier(fieldName)} = case`;
873
- where.forEach((cond, idx) => {
874
- if (key in data[idx]) {
875
- const pks = Utils.getOrderedPrimaryKeys(cond, meta);
876
- sql += ` when (${pkCond}) then `;
877
- if (prop.customType &&
878
- !prop.object &&
879
- 'convertToDatabaseValueSQL' in prop.customType &&
880
- data[idx][prop.name] != null &&
881
- !isRaw(data[idx][key])) {
882
- sql += prop.customType.convertToDatabaseValueSQL('?', this.platform);
883
- }
884
- else {
885
- sql += '?';
886
- }
887
- params.push(...pks);
888
- addParams(prop, prop.fieldNames.length > 1 ? data[idx][key]?.[fieldNameIdx] : data[idx][key]);
889
- }
890
- });
891
- sql += ` else ${this.platform.quoteIdentifier(fieldName)} end, `;
892
- return sql;
893
- });
894
- }
895
- if (meta.versionProperty) {
896
- const versionProperty = meta.properties[meta.versionProperty];
897
- const quotedFieldName = this.platform.quoteIdentifier(versionProperty.fieldNames[0]);
898
- sql += `${quotedFieldName} = `;
899
- if (versionProperty.runtimeType === 'Date') {
900
- sql += this.platform.getCurrentTimestampSQL(versionProperty.length);
901
- }
902
- else {
903
- sql += `${quotedFieldName} + 1`;
904
- }
905
- sql += `, `;
906
- }
907
- sql = sql.substring(0, sql.length - 2) + ' where ';
908
- const pkProps = meta.primaryKeys.concat(...meta.concurrencyCheckKeys);
909
- const pks = Utils.flatten(pkProps.map(pk => meta.properties[pk].fieldNames));
910
- const useTupleIn = pks.length <= 1 || this.platform.allowsComparingTuples();
911
- const condTemplate = useTupleIn
912
- ? `(${pks.map(() => '?').join(', ')})`
913
- : `(${pks.map(pk => `${this.platform.quoteIdentifier(pk)} = ?`).join(' and ')})`;
914
- const conds = where.map(cond => {
915
- if (Utils.isPlainObject(cond) && Utils.getObjectKeysSize(cond) === 1) {
916
- cond = Object.values(cond)[0];
917
- }
918
- if (pks.length > 1) {
919
- pkProps.forEach(pk => {
920
- if (Array.isArray(cond[pk])) {
921
- params.push(...Utils.flatten(cond[pk]));
922
- }
923
- else {
924
- params.push(cond[pk]);
925
- }
926
- });
927
- return condTemplate;
928
- }
929
- params.push(cond);
930
- return '?';
831
+ const returning = [];
832
+ meta.props
833
+ .filter(prop => (prop.generated && !prop.primary) || prop.version)
834
+ .forEach(prop => returning.push(prop.name));
835
+ qb.returning(returning);
836
+ }
837
+ res = await this.rethrow(qb.execute('run', false));
838
+ }
839
+ /* v8 ignore next */
840
+ const pk = pks.map(pk => Utils.extractPK(data[pk] || where, meta));
841
+ await this.processManyToMany(meta, pk, collections, true, options);
842
+ return res;
843
+ }
844
+ async nativeUpdateMany(entityName, where, data, options = {}, transform) {
845
+ options.processCollections ??= true;
846
+ options.convertCustomTypes ??= true;
847
+ const meta = this.metadata.get(entityName);
848
+ if (options.upsert) {
849
+ const uniqueFields =
850
+ options.onConflictFields ??
851
+ (Utils.isPlainObject(where[0])
852
+ ? Object.keys(where[0]).flatMap(key => Utils.splitPrimaryKeys(key))
853
+ : meta.primaryKeys);
854
+ const qb = this.createQueryBuilder(
855
+ entityName,
856
+ options.ctx,
857
+ 'write',
858
+ options.convertCustomTypes,
859
+ options.loggerContext,
860
+ ).withSchema(this.getSchemaName(meta, options));
861
+ const returning = getOnConflictReturningFields(meta, data[0], uniqueFields, options);
862
+ qb.insert(data).onConflict(uniqueFields).returning(returning);
863
+ if (!options.onConflictAction || options.onConflictAction === 'merge') {
864
+ const fields = getOnConflictFields(meta, data[0], uniqueFields, options);
865
+ qb.merge(fields);
866
+ }
867
+ if (options.onConflictAction === 'ignore') {
868
+ qb.ignore();
869
+ }
870
+ if (options.onConflictWhere) {
871
+ qb.where(options.onConflictWhere);
872
+ }
873
+ return this.rethrow(qb.execute('run', false));
874
+ }
875
+ const collections = options.processCollections ? data.map(d => this.extractManyToMany(meta, d)) : [];
876
+ const keys = new Set();
877
+ const fields = new Set();
878
+ const returning = new Set();
879
+ for (const row of data) {
880
+ for (const k of Utils.keys(row)) {
881
+ keys.add(k);
882
+ if (isRaw(row[k])) {
883
+ returning.add(k);
884
+ }
885
+ }
886
+ }
887
+ // reload generated columns and version fields
888
+ meta.props.filter(prop => prop.generated || prop.version || prop.primary).forEach(prop => returning.add(prop.name));
889
+ const pkCond = Utils.flatten(meta.primaryKeys.map(pk => meta.properties[pk].fieldNames))
890
+ .map(pk => `${this.platform.quoteIdentifier(pk)} = ?`)
891
+ .join(' and ');
892
+ const params = [];
893
+ let sql = `update ${this.getTableName(meta, options)} set `;
894
+ const addParams = (prop, value) => {
895
+ if (prop.kind === ReferenceKind.EMBEDDED && prop.object) {
896
+ if (prop.array && value) {
897
+ for (let i = 0; i < value.length; i++) {
898
+ const item = value[i];
899
+ value[i] = this.mapDataToFieldNames(item, false, prop.embeddedProps, options.convertCustomTypes);
900
+ }
901
+ } else {
902
+ value = this.mapDataToFieldNames(value, false, prop.embeddedProps, options.convertCustomTypes);
903
+ }
904
+ }
905
+ params.push(value ?? null);
906
+ };
907
+ for (const key of keys) {
908
+ const prop = meta.properties[key] ?? meta.root.properties[key];
909
+ if (prop.polymorphic && prop.fieldNames.length > 1) {
910
+ for (let idx = 0; idx < data.length; idx++) {
911
+ const rowValue = data[idx][key];
912
+ if (rowValue instanceof PolymorphicRef) {
913
+ data[idx][key] = rowValue.toTuple();
914
+ }
915
+ }
916
+ }
917
+ prop.fieldNames.forEach((fieldName, fieldNameIdx) => {
918
+ if (fields.has(fieldName) || (prop.ownColumns && !prop.ownColumns.includes(fieldName))) {
919
+ return;
920
+ }
921
+ fields.add(fieldName);
922
+ sql += `${this.platform.quoteIdentifier(fieldName)} = case`;
923
+ where.forEach((cond, idx) => {
924
+ if (key in data[idx]) {
925
+ const pks = Utils.getOrderedPrimaryKeys(cond, meta);
926
+ sql += ` when (${pkCond}) then `;
927
+ if (
928
+ prop.customType &&
929
+ !prop.object &&
930
+ 'convertToDatabaseValueSQL' in prop.customType &&
931
+ data[idx][prop.name] != null &&
932
+ !isRaw(data[idx][key])
933
+ ) {
934
+ sql += prop.customType.convertToDatabaseValueSQL('?', this.platform);
935
+ } else {
936
+ sql += '?';
937
+ }
938
+ params.push(...pks);
939
+ addParams(prop, prop.fieldNames.length > 1 ? data[idx][key]?.[fieldNameIdx] : data[idx][key]);
940
+ }
931
941
  });
932
- if (useTupleIn) {
933
- sql +=
934
- pks.length > 1
935
- ? `(${pks.map(pk => this.platform.quoteIdentifier(pk)).join(', ')})`
936
- : this.platform.quoteIdentifier(pks[0]);
937
- sql += ` in (${conds.join(', ')})`;
938
- }
939
- else {
940
- sql += conds.join(' or ');
941
- }
942
- if (this.platform.usesReturningStatement() && returning.size > 0) {
943
- const returningFields = Utils.flatten([...returning].map(prop => meta.properties[prop].fieldNames));
944
- /* v8 ignore next */
945
- sql +=
946
- returningFields.length > 0
947
- ? ` returning ${returningFields.map(field => this.platform.quoteIdentifier(field)).join(', ')}`
948
- : '';
949
- }
950
- if (transform) {
951
- sql = transform(sql, params);
952
- }
953
- const res = await this.rethrow(this.execute(sql, params, 'run', options.ctx, options.loggerContext));
954
- for (let i = 0; i < collections.length; i++) {
955
- await this.processManyToMany(meta, where[i], collections[i], false, options);
956
- }
957
- return res;
942
+ sql += ` else ${this.platform.quoteIdentifier(fieldName)} end, `;
943
+ return sql;
944
+ });
958
945
  }
959
- async nativeDelete(entityName, where, options = {}) {
960
- const meta = this.metadata.get(entityName);
961
- const pks = this.getPrimaryKeyFields(meta);
962
- if (Utils.isPrimaryKey(where) && pks.length === 1) {
963
- where = { [pks[0]]: where };
964
- }
965
- if (options.unionWhere?.length) {
966
- where = await this.applyUnionWhere(meta, where, options, true);
967
- }
968
- const qb = this.createQueryBuilder(entityName, options.ctx, 'write', false, options.loggerContext)
969
- .delete(where)
970
- .withSchema(this.getSchemaName(meta, options));
971
- return this.rethrow(qb.execute('run', false));
972
- }
973
- /**
974
- * Fast comparison for collection snapshots that are represented by PK arrays.
975
- * Compares scalars via `===` and fallbacks to Utils.equals()` for more complex types like Buffer.
976
- * Always expects the same length of the arrays, since we only compare PKs of the same entity type.
977
- */
978
- comparePrimaryKeyArrays(a, b) {
979
- for (let i = a.length; i-- !== 0;) {
980
- if (['number', 'string', 'bigint', 'boolean'].includes(typeof a[i])) {
981
- if (a[i] !== b[i]) {
982
- return false;
983
- }
984
- }
985
- else {
986
- if (!Utils.equals(a[i], b[i])) {
987
- return false;
988
- }
989
- }
946
+ if (meta.versionProperty) {
947
+ const versionProperty = meta.properties[meta.versionProperty];
948
+ const quotedFieldName = this.platform.quoteIdentifier(versionProperty.fieldNames[0]);
949
+ sql += `${quotedFieldName} = `;
950
+ if (versionProperty.runtimeType === 'Date') {
951
+ sql += this.platform.getCurrentTimestampSQL(versionProperty.length);
952
+ } else {
953
+ sql += `${quotedFieldName} + 1`;
954
+ }
955
+ sql += `, `;
956
+ }
957
+ sql = sql.substring(0, sql.length - 2) + ' where ';
958
+ const pkProps = meta.primaryKeys.concat(...meta.concurrencyCheckKeys);
959
+ const pks = Utils.flatten(pkProps.map(pk => meta.properties[pk].fieldNames));
960
+ const useTupleIn = pks.length <= 1 || this.platform.allowsComparingTuples();
961
+ const condTemplate = useTupleIn
962
+ ? `(${pks.map(() => '?').join(', ')})`
963
+ : `(${pks.map(pk => `${this.platform.quoteIdentifier(pk)} = ?`).join(' and ')})`;
964
+ const conds = where.map(cond => {
965
+ if (Utils.isPlainObject(cond) && Utils.getObjectKeysSize(cond) === 1) {
966
+ cond = Object.values(cond)[0];
967
+ }
968
+ if (pks.length > 1) {
969
+ pkProps.forEach(pk => {
970
+ if (Array.isArray(cond[pk])) {
971
+ params.push(...Utils.flatten(cond[pk]));
972
+ } else {
973
+ params.push(cond[pk]);
974
+ }
975
+ });
976
+ return condTemplate;
977
+ }
978
+ params.push(cond);
979
+ return '?';
980
+ });
981
+ if (useTupleIn) {
982
+ sql +=
983
+ pks.length > 1
984
+ ? `(${pks.map(pk => this.platform.quoteIdentifier(pk)).join(', ')})`
985
+ : this.platform.quoteIdentifier(pks[0]);
986
+ sql += ` in (${conds.join(', ')})`;
987
+ } else {
988
+ sql += conds.join(' or ');
989
+ }
990
+ if (this.platform.usesReturningStatement() && returning.size > 0) {
991
+ const returningFields = Utils.flatten([...returning].map(prop => meta.properties[prop].fieldNames));
992
+ /* v8 ignore next */
993
+ sql +=
994
+ returningFields.length > 0
995
+ ? ` returning ${returningFields.map(field => this.platform.quoteIdentifier(field)).join(', ')}`
996
+ : '';
997
+ }
998
+ if (transform) {
999
+ sql = transform(sql, params);
1000
+ }
1001
+ const res = await this.rethrow(this.execute(sql, params, 'run', options.ctx, options.loggerContext));
1002
+ for (let i = 0; i < collections.length; i++) {
1003
+ await this.processManyToMany(meta, where[i], collections[i], false, options);
1004
+ }
1005
+ return res;
1006
+ }
1007
+ async nativeDelete(entityName, where, options = {}) {
1008
+ const meta = this.metadata.get(entityName);
1009
+ const pks = this.getPrimaryKeyFields(meta);
1010
+ if (Utils.isPrimaryKey(where) && pks.length === 1) {
1011
+ where = { [pks[0]]: where };
1012
+ }
1013
+ if (options.unionWhere?.length) {
1014
+ where = await this.applyUnionWhere(meta, where, options, true);
1015
+ }
1016
+ const qb = this.createQueryBuilder(entityName, options.ctx, 'write', false, options.loggerContext)
1017
+ .delete(where)
1018
+ .withSchema(this.getSchemaName(meta, options));
1019
+ return this.rethrow(qb.execute('run', false));
1020
+ }
1021
+ /**
1022
+ * Fast comparison for collection snapshots that are represented by PK arrays.
1023
+ * Compares scalars via `===` and fallbacks to Utils.equals()` for more complex types like Buffer.
1024
+ * Always expects the same length of the arrays, since we only compare PKs of the same entity type.
1025
+ */
1026
+ comparePrimaryKeyArrays(a, b) {
1027
+ for (let i = a.length; i-- !== 0; ) {
1028
+ if (['number', 'string', 'bigint', 'boolean'].includes(typeof a[i])) {
1029
+ if (a[i] !== b[i]) {
1030
+ return false;
1031
+ }
1032
+ } else {
1033
+ if (!Utils.equals(a[i], b[i])) {
1034
+ return false;
1035
+ }
1036
+ }
1037
+ }
1038
+ return true;
1039
+ }
1040
+ async syncCollections(collections, options) {
1041
+ const groups = {};
1042
+ for (const coll of collections) {
1043
+ const wrapped = helper(coll.owner);
1044
+ const meta = wrapped.__meta;
1045
+ const pks = wrapped.getPrimaryKeys(true);
1046
+ const snap = coll.getSnapshot();
1047
+ const includes = (arr, item) => !!arr.find(i => this.comparePrimaryKeyArrays(i, item));
1048
+ const snapshot = snap ? snap.map(item => helper(item).getPrimaryKeys(true)) : [];
1049
+ const current = coll.getItems(false).map(item => helper(item).getPrimaryKeys(true));
1050
+ const deleteDiff = snap ? snapshot.filter(item => !includes(current, item)) : true;
1051
+ const insertDiff = current.filter(item => !includes(snapshot, item));
1052
+ const target = snapshot.filter(item => includes(current, item)).concat(...insertDiff);
1053
+ const equals = Utils.equals(current, target);
1054
+ // wrong order if we just delete and insert to the end (only owning sides can have fixed order)
1055
+ if (coll.property.owner && coll.property.fixedOrder && !equals && Array.isArray(deleteDiff)) {
1056
+ deleteDiff.length = insertDiff.length = 0;
1057
+ for (const item of snapshot) {
1058
+ deleteDiff.push(item);
1059
+ }
1060
+ for (const item of current) {
1061
+ insertDiff.push(item);
1062
+ }
1063
+ }
1064
+ if (coll.property.kind === ReferenceKind.ONE_TO_MANY) {
1065
+ const cols = coll.property.referencedColumnNames;
1066
+ const qb = this.createQueryBuilder(coll.property.targetMeta.class, options?.ctx, 'write').withSchema(
1067
+ this.getSchemaName(meta, options),
1068
+ );
1069
+ if (coll.getSnapshot() === undefined) {
1070
+ if (coll.property.orphanRemoval) {
1071
+ const query = qb
1072
+ .delete({ [coll.property.mappedBy]: pks })
1073
+ .andWhere({ [cols.join(Utils.PK_SEPARATOR)]: { $nin: insertDiff } });
1074
+ await this.rethrow(query.execute());
1075
+ continue;
1076
+ }
1077
+ const query = qb
1078
+ .update({ [coll.property.mappedBy]: null })
1079
+ .where({ [coll.property.mappedBy]: pks })
1080
+ .andWhere({ [cols.join(Utils.PK_SEPARATOR)]: { $nin: insertDiff } });
1081
+ await this.rethrow(query.execute());
1082
+ continue;
990
1083
  }
1084
+ /* v8 ignore next */
1085
+ const query = qb
1086
+ .update({ [coll.property.mappedBy]: pks })
1087
+ .where({ [cols.join(Utils.PK_SEPARATOR)]: { $in: insertDiff } });
1088
+ await this.rethrow(query.execute());
1089
+ continue;
1090
+ }
1091
+ const pivotMeta = this.metadata.find(coll.property.pivotEntity);
1092
+ let schema = pivotMeta.schema;
1093
+ if (schema === '*') {
1094
+ if (coll.property.owner) {
1095
+ schema = wrapped.getSchema() === '*' ? (options?.schema ?? this.config.get('schema')) : wrapped.getSchema();
1096
+ } else {
1097
+ const targetMeta = coll.property.targetMeta;
1098
+ const targetSchema = (coll[0] ?? snap?.[0]) && helper(coll[0] ?? snap?.[0]).getSchema();
1099
+ schema =
1100
+ targetMeta.schema === '*'
1101
+ ? (options?.schema ?? targetSchema ?? this.config.get('schema'))
1102
+ : targetMeta.schema;
1103
+ }
1104
+ } else if (schema == null) {
1105
+ schema = this.config.get('schema');
1106
+ }
1107
+ const tableName = `${schema ?? '_'}.${pivotMeta.tableName}`;
1108
+ const persister = (groups[tableName] ??= new PivotCollectionPersister(
1109
+ pivotMeta,
1110
+ this,
1111
+ options?.ctx,
1112
+ schema,
1113
+ options?.loggerContext,
1114
+ ));
1115
+ persister.enqueueUpdate(coll.property, insertDiff, deleteDiff, pks, coll.isInitialized());
1116
+ }
1117
+ for (const persister of Utils.values(groups)) {
1118
+ await this.rethrow(persister.execute());
1119
+ }
1120
+ }
1121
+ async loadFromPivotTable(prop, owners, where = {}, orderBy, ctx, options, pivotJoin) {
1122
+ /* v8 ignore next */
1123
+ if (owners.length === 0) {
1124
+ return {};
1125
+ }
1126
+ const pivotMeta = this.metadata.get(prop.pivotEntity);
1127
+ if (prop.polymorphic && prop.discriminatorColumn && prop.discriminatorValue) {
1128
+ return this.loadFromPolymorphicPivotTable(prop, owners, where, orderBy, ctx, options, pivotJoin);
1129
+ }
1130
+ const pivotProp1 = pivotMeta.relations[prop.owner ? 1 : 0];
1131
+ const pivotProp2 = pivotMeta.relations[prop.owner ? 0 : 1];
1132
+ const ownerMeta = pivotProp2.targetMeta;
1133
+ // The pivot query builder doesn't convert custom types, so we need to manually
1134
+ // convert owner PKs to DB format for the query and convert result FKs back to
1135
+ // JS format for consistent key hashing in buildPivotResultMap.
1136
+ const pkProp = ownerMeta.properties[ownerMeta.primaryKeys[0]];
1137
+ const needsConversion = pkProp?.customType?.ensureComparable(ownerMeta, pkProp) && !ownerMeta.compositePK;
1138
+ let ownerPks = ownerMeta.compositePK ? owners : owners.map(o => o[0]);
1139
+ if (needsConversion) {
1140
+ ownerPks = ownerPks.map(v => pkProp.customType.convertToDatabaseValue(v, this.platform, { mode: 'query' }));
1141
+ }
1142
+ const cond = {
1143
+ [pivotProp2.name]: { $in: ownerPks },
1144
+ };
1145
+ if (!Utils.isEmpty(where)) {
1146
+ cond[pivotProp1.name] = { ...where };
1147
+ }
1148
+ where = cond;
1149
+ const populateField = pivotJoin ? `${pivotProp1.name}:ref` : pivotProp1.name;
1150
+ const populate = this.autoJoinOneToOneOwner(prop.targetMeta, options?.populate ?? [], options?.fields);
1151
+ const childFields = !Utils.isEmpty(options?.fields) ? options.fields.map(f => `${pivotProp1.name}.${f}`) : [];
1152
+ const childExclude = !Utils.isEmpty(options?.exclude) ? options.exclude.map(f => `${pivotProp1.name}.${f}`) : [];
1153
+ const fields = pivotJoin ? [pivotProp1.name, pivotProp2.name] : [pivotProp1.name, pivotProp2.name, ...childFields];
1154
+ const res = await this.find(pivotMeta.class, where, {
1155
+ ctx,
1156
+ ...options,
1157
+ fields,
1158
+ exclude: childExclude,
1159
+ orderBy: this.getPivotOrderBy(prop, pivotProp1, orderBy, options?.orderBy),
1160
+ populate: [
1161
+ {
1162
+ field: populateField,
1163
+ strategy: LoadStrategy.JOINED,
1164
+ joinType: JoinType.innerJoin,
1165
+ children: populate,
1166
+ dataOnly: pivotProp1.mapToPk && !pivotJoin,
1167
+ },
1168
+ ],
1169
+ populateWhere: undefined,
1170
+ // @ts-ignore
1171
+ _populateWhere: 'infer',
1172
+ populateFilter: this.wrapPopulateFilter(options, pivotProp2.name),
1173
+ });
1174
+ // Convert result FK values back to JS format so key hashing
1175
+ // in buildPivotResultMap is consistent with the owner keys.
1176
+ if (needsConversion) {
1177
+ for (const item of res) {
1178
+ const fk = item[pivotProp2.name];
1179
+ if (fk != null) {
1180
+ item[pivotProp2.name] = pkProp.customType.convertToJSValue(fk, this.platform);
1181
+ }
1182
+ }
1183
+ }
1184
+ return this.buildPivotResultMap(owners, res, pivotProp2.name, pivotProp1.name);
1185
+ }
1186
+ /**
1187
+ * Load from a polymorphic M:N pivot table.
1188
+ */
1189
+ async loadFromPolymorphicPivotTable(prop, owners, where = {}, orderBy, ctx, options, pivotJoin) {
1190
+ const pivotMeta = this.metadata.get(prop.pivotEntity);
1191
+ // Find the M:1 relation on the pivot pointing to the target entity.
1192
+ // We exclude virtual polymorphic owner relations (persist: false) and non-M:1 relations.
1193
+ const inverseProp = pivotMeta.relations.find(
1194
+ r => r.kind === ReferenceKind.MANY_TO_ONE && r.persist !== false && r.targetMeta === prop.targetMeta,
1195
+ );
1196
+ if (inverseProp) {
1197
+ return this.loadPolymorphicPivotOwnerSide(prop, owners, where, orderBy, ctx, options, pivotJoin, inverseProp);
1198
+ }
1199
+ return this.loadPolymorphicPivotInverseSide(prop, owners, where, orderBy, ctx, options);
1200
+ }
1201
+ /**
1202
+ * Load from owner side of polymorphic M:N (e.g., Post -> Tags)
1203
+ */
1204
+ async loadPolymorphicPivotOwnerSide(prop, owners, where, orderBy, ctx, options, pivotJoin, inverseProp) {
1205
+ const pivotMeta = this.metadata.get(prop.pivotEntity);
1206
+ const targetMeta = prop.targetMeta;
1207
+ // Build condition: discriminator = 'post' AND {discriminator} IN (...)
1208
+ const cond = {
1209
+ [prop.discriminatorColumn]: prop.discriminatorValue,
1210
+ [prop.discriminator]: { $in: owners.length === 1 && owners[0].length === 1 ? owners.map(o => o[0]) : owners },
1211
+ };
1212
+ if (!Utils.isEmpty(where)) {
1213
+ cond[inverseProp.name] = { ...where };
1214
+ }
1215
+ const populateField = pivotJoin ? `${inverseProp.name}:ref` : inverseProp.name;
1216
+ const populate = this.autoJoinOneToOneOwner(targetMeta, options?.populate ?? [], options?.fields);
1217
+ const childFields = !Utils.isEmpty(options?.fields) ? options.fields.map(f => `${inverseProp.name}.${f}`) : [];
1218
+ const childExclude = !Utils.isEmpty(options?.exclude) ? options.exclude.map(f => `${inverseProp.name}.${f}`) : [];
1219
+ const fields = pivotJoin
1220
+ ? [inverseProp.name, prop.discriminator, prop.discriminatorColumn]
1221
+ : [inverseProp.name, prop.discriminator, prop.discriminatorColumn, ...childFields];
1222
+ const res = await this.find(pivotMeta.class, cond, {
1223
+ ctx,
1224
+ ...options,
1225
+ fields,
1226
+ exclude: childExclude,
1227
+ orderBy: this.getPivotOrderBy(prop, inverseProp, orderBy, options?.orderBy),
1228
+ populate: [
1229
+ {
1230
+ field: populateField,
1231
+ strategy: LoadStrategy.JOINED,
1232
+ joinType: JoinType.innerJoin,
1233
+ children: populate,
1234
+ dataOnly: inverseProp.mapToPk && !pivotJoin,
1235
+ },
1236
+ ],
1237
+ populateWhere: undefined,
1238
+ // @ts-ignore
1239
+ _populateWhere: 'infer',
1240
+ populateFilter: this.wrapPopulateFilter(options, inverseProp.name),
1241
+ });
1242
+ return this.buildPivotResultMap(owners, res, prop.discriminator, inverseProp.name);
1243
+ }
1244
+ /**
1245
+ * Load from inverse side of polymorphic M:N (e.g., Tag -> Posts)
1246
+ * Uses single query with join via virtual relation on pivot.
1247
+ */
1248
+ async loadPolymorphicPivotInverseSide(prop, owners, where, orderBy, ctx, options) {
1249
+ const pivotMeta = this.metadata.get(prop.pivotEntity);
1250
+ const targetMeta = prop.targetMeta;
1251
+ // Find the relation to the entity we're starting from (e.g., Tag_inverse -> Tag)
1252
+ // Exclude virtual polymorphic owner relations (persist: false) - we want the actual M:N inverse relation
1253
+ const tagProp = pivotMeta.relations.find(r => r.persist !== false && r.targetMeta !== targetMeta);
1254
+ // Find the virtual relation to the polymorphic owner (e.g., taggable_Post -> Post)
1255
+ const ownerRelationName = `${prop.discriminator}_${targetMeta.tableName}`;
1256
+ const ownerProp = pivotMeta.properties[ownerRelationName];
1257
+ // Build condition: discriminator = 'post' AND Tag_inverse IN (tagIds)
1258
+ const cond = {
1259
+ [prop.discriminatorColumn]: prop.discriminatorValue,
1260
+ [tagProp.name]: { $in: owners.length === 1 && owners[0].length === 1 ? owners.map(o => o[0]) : owners },
1261
+ };
1262
+ if (!Utils.isEmpty(where)) {
1263
+ cond[ownerRelationName] = { ...where };
1264
+ }
1265
+ const populateField = ownerRelationName;
1266
+ const populate = this.autoJoinOneToOneOwner(targetMeta, options?.populate ?? [], options?.fields);
1267
+ const childFields = !Utils.isEmpty(options?.fields) ? options.fields.map(f => `${ownerRelationName}.${f}`) : [];
1268
+ const childExclude = !Utils.isEmpty(options?.exclude) ? options.exclude.map(f => `${ownerRelationName}.${f}`) : [];
1269
+ const fields = [ownerRelationName, tagProp.name, prop.discriminatorColumn, ...childFields];
1270
+ const res = await this.find(pivotMeta.class, cond, {
1271
+ ctx,
1272
+ ...options,
1273
+ fields,
1274
+ exclude: childExclude,
1275
+ orderBy: this.getPivotOrderBy(prop, ownerProp, orderBy, options?.orderBy),
1276
+ populate: [
1277
+ {
1278
+ field: populateField,
1279
+ strategy: LoadStrategy.JOINED,
1280
+ joinType: JoinType.innerJoin,
1281
+ children: populate,
1282
+ },
1283
+ ],
1284
+ populateWhere: undefined,
1285
+ // @ts-ignore
1286
+ _populateWhere: 'infer',
1287
+ populateFilter: this.wrapPopulateFilter(options, ownerRelationName),
1288
+ });
1289
+ return this.buildPivotResultMap(owners, res, tagProp.name, ownerRelationName);
1290
+ }
1291
+ /**
1292
+ * Build a map from owner PKs to their related entities from pivot table results.
1293
+ */
1294
+ buildPivotResultMap(owners, results, keyProp, valueProp) {
1295
+ const map = {};
1296
+ for (const owner of owners) {
1297
+ const key = Utils.getPrimaryKeyHash(owner);
1298
+ map[key] = [];
1299
+ }
1300
+ for (const item of results) {
1301
+ const key = Utils.getPrimaryKeyHash(Utils.asArray(item[keyProp]));
1302
+ const entity = item[valueProp];
1303
+ if (map[key]) {
1304
+ map[key].push(entity);
1305
+ }
1306
+ }
1307
+ return map;
1308
+ }
1309
+ wrapPopulateFilter(options, propName) {
1310
+ if (!Utils.isEmpty(options?.populateFilter) || RawQueryFragment.hasObjectFragments(options?.populateFilter)) {
1311
+ return { [propName]: options?.populateFilter };
1312
+ }
1313
+ return undefined;
1314
+ }
1315
+ getPivotOrderBy(prop, pivotProp, orderBy, parentOrderBy) {
1316
+ if (!Utils.isEmpty(orderBy) || RawQueryFragment.hasObjectFragments(orderBy)) {
1317
+ return Utils.asArray(orderBy).map(o => ({ [pivotProp.name]: o }));
1318
+ }
1319
+ if (prop.kind === ReferenceKind.MANY_TO_MANY && Utils.asArray(parentOrderBy).some(o => o[prop.name])) {
1320
+ return Utils.asArray(parentOrderBy)
1321
+ .filter(o => o[prop.name])
1322
+ .map(o => ({ [pivotProp.name]: o[prop.name] }));
1323
+ }
1324
+ if (!Utils.isEmpty(prop.orderBy) || RawQueryFragment.hasObjectFragments(prop.orderBy)) {
1325
+ return Utils.asArray(prop.orderBy).map(o => ({ [pivotProp.name]: o }));
1326
+ }
1327
+ if (prop.fixedOrder) {
1328
+ return [{ [prop.fixedOrderColumn]: QueryOrder.ASC }];
1329
+ }
1330
+ return [];
1331
+ }
1332
+ async execute(query, params = [], method = 'all', ctx, loggerContext) {
1333
+ return this.rethrow(this.connection.execute(query, params, method, ctx, loggerContext));
1334
+ }
1335
+ async *stream(entityName, where, options) {
1336
+ options = { populate: [], orderBy: [], ...options };
1337
+ const meta = this.metadata.get(entityName);
1338
+ if (meta.virtual) {
1339
+ yield* this.streamFromVirtual(entityName, where, options);
1340
+ return;
1341
+ }
1342
+ const qb = await this.createQueryBuilderFromOptions(meta, where, options);
1343
+ try {
1344
+ const result = qb.stream(options);
1345
+ for await (const item of result) {
1346
+ yield item;
1347
+ }
1348
+ } catch (e) {
1349
+ throw this.convertException(e);
1350
+ }
1351
+ }
1352
+ /**
1353
+ * 1:1 owner side needs to be marked for population so QB auto-joins the owner id
1354
+ */
1355
+ autoJoinOneToOneOwner(meta, populate, fields = []) {
1356
+ if (!this.config.get('autoJoinOneToOneOwner')) {
1357
+ return populate;
1358
+ }
1359
+ const relationsToPopulate = populate.map(({ field }) => field.split(':')[0]);
1360
+ const toPopulate = meta.relations
1361
+ .filter(
1362
+ prop =>
1363
+ prop.kind === ReferenceKind.ONE_TO_ONE &&
1364
+ !prop.owner &&
1365
+ !prop.lazy &&
1366
+ !relationsToPopulate.includes(prop.name),
1367
+ )
1368
+ .filter(prop => fields.length === 0 || fields.some(f => prop.name === f || prop.name.startsWith(`${String(f)}.`)))
1369
+ .map(prop => ({ field: `${prop.name}:ref`, strategy: LoadStrategy.JOINED }));
1370
+ return [...populate, ...toPopulate];
1371
+ }
1372
+ /**
1373
+ * @internal
1374
+ */
1375
+ joinedProps(meta, populate, options) {
1376
+ return populate.filter(hint => {
1377
+ const [propName, ref] = hint.field.split(':', 2);
1378
+ const prop = meta.properties[propName] || {};
1379
+ const strategy = getLoadingStrategy(
1380
+ hint.strategy || prop.strategy || options?.strategy || this.config.get('loadStrategy'),
1381
+ prop.kind,
1382
+ );
1383
+ if (ref && [ReferenceKind.ONE_TO_ONE, ReferenceKind.MANY_TO_ONE].includes(prop.kind)) {
991
1384
  return true;
1385
+ }
1386
+ // skip redundant joins for 1:1 owner population hints when using `mapToPk`
1387
+ if (prop.kind === ReferenceKind.ONE_TO_ONE && prop.mapToPk && prop.owner) {
1388
+ return false;
1389
+ }
1390
+ if (strategy !== LoadStrategy.JOINED) {
1391
+ // force joined strategy for explicit 1:1 owner populate hint as it would require a join anyway
1392
+ return prop.kind === ReferenceKind.ONE_TO_ONE && !prop.owner;
1393
+ }
1394
+ return ![ReferenceKind.SCALAR, ReferenceKind.EMBEDDED].includes(prop.kind);
1395
+ });
1396
+ }
1397
+ /**
1398
+ * @internal
1399
+ */
1400
+ mergeJoinedResult(rawResults, meta, joinedProps) {
1401
+ if (rawResults.length <= 1) {
1402
+ return rawResults;
992
1403
  }
993
- async syncCollections(collections, options) {
994
- const groups = {};
995
- for (const coll of collections) {
996
- const wrapped = helper(coll.owner);
997
- const meta = wrapped.__meta;
998
- const pks = wrapped.getPrimaryKeys(true);
999
- const snap = coll.getSnapshot();
1000
- const includes = (arr, item) => !!arr.find(i => this.comparePrimaryKeyArrays(i, item));
1001
- const snapshot = snap ? snap.map(item => helper(item).getPrimaryKeys(true)) : [];
1002
- const current = coll.getItems(false).map(item => helper(item).getPrimaryKeys(true));
1003
- const deleteDiff = snap ? snapshot.filter(item => !includes(current, item)) : true;
1004
- const insertDiff = current.filter(item => !includes(snapshot, item));
1005
- const target = snapshot.filter(item => includes(current, item)).concat(...insertDiff);
1006
- const equals = Utils.equals(current, target);
1007
- // wrong order if we just delete and insert to the end (only owning sides can have fixed order)
1008
- if (coll.property.owner && coll.property.fixedOrder && !equals && Array.isArray(deleteDiff)) {
1009
- deleteDiff.length = insertDiff.length = 0;
1010
- for (const item of snapshot) {
1011
- deleteDiff.push(item);
1012
- }
1013
- for (const item of current) {
1014
- insertDiff.push(item);
1015
- }
1016
- }
1017
- if (coll.property.kind === ReferenceKind.ONE_TO_MANY) {
1018
- const cols = coll.property.referencedColumnNames;
1019
- const qb = this.createQueryBuilder(coll.property.targetMeta.class, options?.ctx, 'write').withSchema(this.getSchemaName(meta, options));
1020
- if (coll.getSnapshot() === undefined) {
1021
- if (coll.property.orphanRemoval) {
1022
- const query = qb
1023
- .delete({ [coll.property.mappedBy]: pks })
1024
- .andWhere({ [cols.join(Utils.PK_SEPARATOR)]: { $nin: insertDiff } });
1025
- await this.rethrow(query.execute());
1026
- continue;
1027
- }
1028
- const query = qb
1029
- .update({ [coll.property.mappedBy]: null })
1030
- .where({ [coll.property.mappedBy]: pks })
1031
- .andWhere({ [cols.join(Utils.PK_SEPARATOR)]: { $nin: insertDiff } });
1032
- await this.rethrow(query.execute());
1033
- continue;
1034
- }
1035
- /* v8 ignore next */
1036
- const query = qb
1037
- .update({ [coll.property.mappedBy]: pks })
1038
- .where({ [cols.join(Utils.PK_SEPARATOR)]: { $in: insertDiff } });
1039
- await this.rethrow(query.execute());
1040
- continue;
1041
- }
1042
- const pivotMeta = this.metadata.find(coll.property.pivotEntity);
1043
- let schema = pivotMeta.schema;
1044
- if (schema === '*') {
1045
- if (coll.property.owner) {
1046
- schema = wrapped.getSchema() === '*' ? (options?.schema ?? this.config.get('schema')) : wrapped.getSchema();
1047
- }
1048
- else {
1049
- const targetMeta = coll.property.targetMeta;
1050
- const targetSchema = (coll[0] ?? snap?.[0]) && helper(coll[0] ?? snap?.[0]).getSchema();
1051
- schema =
1052
- targetMeta.schema === '*'
1053
- ? (options?.schema ?? targetSchema ?? this.config.get('schema'))
1054
- : targetMeta.schema;
1055
- }
1056
- }
1057
- else if (schema == null) {
1058
- schema = this.config.get('schema');
1059
- }
1060
- const tableName = `${schema ?? '_'}.${pivotMeta.tableName}`;
1061
- const persister = (groups[tableName] ??= new PivotCollectionPersister(pivotMeta, this, options?.ctx, schema, options?.loggerContext));
1062
- persister.enqueueUpdate(coll.property, insertDiff, deleteDiff, pks, coll.isInitialized());
1063
- }
1064
- for (const persister of Utils.values(groups)) {
1065
- await this.rethrow(persister.execute());
1066
- }
1404
+ const res = [];
1405
+ const map = {};
1406
+ const collectionsToMerge = {};
1407
+ const hints = joinedProps.map(hint => {
1408
+ const [propName, ref] = hint.field.split(':', 2);
1409
+ return { propName, ref, children: hint.children };
1410
+ });
1411
+ for (const item of rawResults) {
1412
+ const pk = Utils.getCompositeKeyHash(item, meta);
1413
+ if (map[pk]) {
1414
+ for (const { propName } of hints) {
1415
+ if (!item[propName]) {
1416
+ continue;
1417
+ }
1418
+ collectionsToMerge[pk] ??= {};
1419
+ collectionsToMerge[pk][propName] ??= [map[pk][propName]];
1420
+ collectionsToMerge[pk][propName].push(item[propName]);
1421
+ }
1422
+ } else {
1423
+ map[pk] = item;
1424
+ res.push(item);
1425
+ }
1067
1426
  }
1068
- async loadFromPivotTable(prop, owners, where = {}, orderBy, ctx, options, pivotJoin) {
1069
- /* v8 ignore next */
1070
- if (owners.length === 0) {
1071
- return {};
1072
- }
1073
- const pivotMeta = this.metadata.get(prop.pivotEntity);
1074
- if (prop.polymorphic && prop.discriminatorColumn && prop.discriminatorValue) {
1075
- return this.loadFromPolymorphicPivotTable(prop, owners, where, orderBy, ctx, options, pivotJoin);
1076
- }
1077
- const pivotProp1 = pivotMeta.relations[prop.owner ? 1 : 0];
1078
- const pivotProp2 = pivotMeta.relations[prop.owner ? 0 : 1];
1079
- const ownerMeta = pivotProp2.targetMeta;
1080
- // The pivot query builder doesn't convert custom types, so we need to manually
1081
- // convert owner PKs to DB format for the query and convert result FKs back to
1082
- // JS format for consistent key hashing in buildPivotResultMap.
1083
- const pkProp = ownerMeta.properties[ownerMeta.primaryKeys[0]];
1084
- const needsConversion = pkProp?.customType?.ensureComparable(ownerMeta, pkProp) && !ownerMeta.compositePK;
1085
- let ownerPks = ownerMeta.compositePK ? owners : owners.map(o => o[0]);
1086
- if (needsConversion) {
1087
- ownerPks = ownerPks.map(v => pkProp.customType.convertToDatabaseValue(v, this.platform, { mode: 'query' }));
1088
- }
1089
- const cond = {
1090
- [pivotProp2.name]: { $in: ownerPks },
1091
- };
1092
- if (!Utils.isEmpty(where)) {
1093
- cond[pivotProp1.name] = { ...where };
1094
- }
1095
- where = cond;
1096
- const populateField = pivotJoin ? `${pivotProp1.name}:ref` : pivotProp1.name;
1097
- const populate = this.autoJoinOneToOneOwner(prop.targetMeta, options?.populate ?? [], options?.fields);
1098
- const childFields = !Utils.isEmpty(options?.fields) ? options.fields.map(f => `${pivotProp1.name}.${f}`) : [];
1099
- const childExclude = !Utils.isEmpty(options?.exclude) ? options.exclude.map(f => `${pivotProp1.name}.${f}`) : [];
1100
- const fields = pivotJoin
1101
- ? [pivotProp1.name, pivotProp2.name]
1102
- : [pivotProp1.name, pivotProp2.name, ...childFields];
1103
- const res = await this.find(pivotMeta.class, where, {
1104
- ctx,
1105
- ...options,
1106
- fields,
1107
- exclude: childExclude,
1108
- orderBy: this.getPivotOrderBy(prop, pivotProp1, orderBy, options?.orderBy),
1109
- populate: [
1110
- {
1111
- field: populateField,
1112
- strategy: LoadStrategy.JOINED,
1113
- joinType: JoinType.innerJoin,
1114
- children: populate,
1115
- dataOnly: pivotProp1.mapToPk && !pivotJoin,
1116
- },
1117
- ],
1118
- populateWhere: undefined,
1119
- // @ts-ignore
1120
- _populateWhere: 'infer',
1121
- populateFilter: this.wrapPopulateFilter(options, pivotProp2.name),
1122
- });
1123
- // Convert result FK values back to JS format so key hashing
1124
- // in buildPivotResultMap is consistent with the owner keys.
1125
- if (needsConversion) {
1126
- for (const item of res) {
1127
- const fk = item[pivotProp2.name];
1128
- if (fk != null) {
1129
- item[pivotProp2.name] = pkProp.customType.convertToJSValue(fk, this.platform);
1130
- }
1131
- }
1427
+ for (const pk in collectionsToMerge) {
1428
+ const entity = map[pk];
1429
+ const collections = collectionsToMerge[pk];
1430
+ for (const { propName, ref, children } of hints) {
1431
+ if (!collections[propName]) {
1432
+ continue;
1132
1433
  }
1133
- return this.buildPivotResultMap(owners, res, pivotProp2.name, pivotProp1.name);
1434
+ const prop = meta.properties[propName];
1435
+ const items = collections[propName].flat();
1436
+ if ([ReferenceKind.ONE_TO_MANY, ReferenceKind.MANY_TO_MANY].includes(prop.kind) && ref) {
1437
+ entity[propName] = items;
1438
+ continue;
1439
+ }
1440
+ switch (prop.kind) {
1441
+ case ReferenceKind.ONE_TO_MANY:
1442
+ case ReferenceKind.MANY_TO_MANY:
1443
+ entity[propName] = this.mergeJoinedResult(items, prop.targetMeta, children ?? []);
1444
+ break;
1445
+ case ReferenceKind.MANY_TO_ONE:
1446
+ case ReferenceKind.ONE_TO_ONE:
1447
+ entity[propName] = this.mergeJoinedResult(items, prop.targetMeta, children ?? [])[0];
1448
+ break;
1449
+ }
1450
+ }
1134
1451
  }
1135
- /**
1136
- * Load from a polymorphic M:N pivot table.
1137
- */
1138
- async loadFromPolymorphicPivotTable(prop, owners, where = {}, orderBy, ctx, options, pivotJoin) {
1139
- const pivotMeta = this.metadata.get(prop.pivotEntity);
1140
- // Find the M:1 relation on the pivot pointing to the target entity.
1141
- // We exclude virtual polymorphic owner relations (persist: false) and non-M:1 relations.
1142
- const inverseProp = pivotMeta.relations.find(r => r.kind === ReferenceKind.MANY_TO_ONE && r.persist !== false && r.targetMeta === prop.targetMeta);
1143
- if (inverseProp) {
1144
- return this.loadPolymorphicPivotOwnerSide(prop, owners, where, orderBy, ctx, options, pivotJoin, inverseProp);
1145
- }
1146
- return this.loadPolymorphicPivotInverseSide(prop, owners, where, orderBy, ctx, options);
1452
+ return res;
1453
+ }
1454
+ shouldHaveColumn(meta, prop, populate, fields, exclude) {
1455
+ if (!this.platform.shouldHaveColumn(prop, populate, exclude)) {
1456
+ return false;
1147
1457
  }
1148
- /**
1149
- * Load from owner side of polymorphic M:N (e.g., Post -> Tags)
1150
- */
1151
- async loadPolymorphicPivotOwnerSide(prop, owners, where, orderBy, ctx, options, pivotJoin, inverseProp) {
1152
- const pivotMeta = this.metadata.get(prop.pivotEntity);
1153
- const targetMeta = prop.targetMeta;
1154
- // Build condition: discriminator = 'post' AND {discriminator} IN (...)
1155
- const cond = {
1156
- [prop.discriminatorColumn]: prop.discriminatorValue,
1157
- [prop.discriminator]: { $in: owners.length === 1 && owners[0].length === 1 ? owners.map(o => o[0]) : owners },
1158
- };
1159
- if (!Utils.isEmpty(where)) {
1160
- cond[inverseProp.name] = { ...where };
1161
- }
1162
- const populateField = pivotJoin ? `${inverseProp.name}:ref` : inverseProp.name;
1163
- const populate = this.autoJoinOneToOneOwner(targetMeta, options?.populate ?? [], options?.fields);
1164
- const childFields = !Utils.isEmpty(options?.fields) ? options.fields.map(f => `${inverseProp.name}.${f}`) : [];
1165
- const childExclude = !Utils.isEmpty(options?.exclude)
1166
- ? options.exclude.map(f => `${inverseProp.name}.${f}`)
1167
- : [];
1168
- const fields = pivotJoin
1169
- ? [inverseProp.name, prop.discriminator, prop.discriminatorColumn]
1170
- : [inverseProp.name, prop.discriminator, prop.discriminatorColumn, ...childFields];
1171
- const res = await this.find(pivotMeta.class, cond, {
1172
- ctx,
1458
+ if (!fields || fields.includes('*') || prop.primary || meta.root.discriminatorColumn === prop.name) {
1459
+ return true;
1460
+ }
1461
+ return fields.some(f => f === prop.name || f.toString().startsWith(prop.name + '.'));
1462
+ }
1463
+ getFieldsForJoinedLoad(qb, meta, options) {
1464
+ const fields = [];
1465
+ const populate = options.populate ?? [];
1466
+ const joinedProps = this.joinedProps(meta, populate, options);
1467
+ const populateWhereAll = options?._populateWhere === 'all' || Utils.isEmpty(options?._populateWhere);
1468
+ // Ensure TPT joins are applied early so that _tptAlias is available for join resolution
1469
+ // This is needed when populating relations that are inherited from TPT parent entities
1470
+ if (!options.parentJoinPath) {
1471
+ qb.ensureTPTJoins();
1472
+ }
1473
+ // root entity is already handled, skip that
1474
+ if (options.parentJoinPath) {
1475
+ // alias all fields in the primary table
1476
+ meta.props
1477
+ .filter(prop => this.shouldHaveColumn(meta, prop, populate, options.explicitFields, options.exclude))
1478
+ .forEach(prop =>
1479
+ fields.push(
1480
+ ...this.mapPropToFieldNames(
1481
+ qb,
1482
+ prop,
1483
+ options.parentTableAlias,
1484
+ meta,
1485
+ options.schema,
1486
+ options.explicitFields,
1487
+ ),
1488
+ ),
1489
+ );
1490
+ }
1491
+ for (const hint of joinedProps) {
1492
+ const [propName, ref] = hint.field.split(':', 2);
1493
+ const prop = meta.properties[propName];
1494
+ // Polymorphic to-one: create a LEFT JOIN per target type
1495
+ // Skip regular :ref hints — polymorphic to-one already has FK + discriminator in the row
1496
+ // But allow filter :ref hints through to create per-target LEFT JOINs with filter checks
1497
+ if (
1498
+ prop.polymorphic &&
1499
+ prop.polymorphTargets?.length &&
1500
+ (!ref || hint.filter) &&
1501
+ [ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(prop.kind)
1502
+ ) {
1503
+ const basePath = options.parentJoinPath
1504
+ ? `${options.parentJoinPath}.${prop.name}`
1505
+ : `${meta.name}.${prop.name}`;
1506
+ const pathPrefix =
1507
+ !options.parentJoinPath && populateWhereAll && !basePath.startsWith('[populate]') ? '[populate]' : '';
1508
+ for (const targetMeta of prop.polymorphTargets) {
1509
+ const tableAlias = qb.getNextAlias(targetMeta.className);
1510
+ const targetPath = `${pathPrefix}${basePath}[${targetMeta.className}]`;
1511
+ const schema = targetMeta.schema === '*' ? (options?.schema ?? this.config.get('schema')) : targetMeta.schema;
1512
+ qb.addPolymorphicJoin(
1513
+ prop,
1514
+ targetMeta,
1515
+ options.parentTableAlias,
1516
+ tableAlias,
1517
+ JoinType.leftJoin,
1518
+ targetPath,
1519
+ schema,
1520
+ );
1521
+ // For polymorphic targets that are TPT base classes, also LEFT JOIN
1522
+ // all descendant tables so child-specific fields can be selected.
1523
+ if (targetMeta.inheritanceType === 'tpt' && targetMeta.tptChildren?.length && !ref) {
1524
+ const tptMeta = this.metadata.get(targetMeta.class);
1525
+ this.addTPTPolymorphicJoinsForRelation(qb, tptMeta, tableAlias, fields);
1526
+ }
1527
+ if (ref) {
1528
+ // For filter :ref hints, schedule filter check for each target (no field selection)
1529
+ qb.scheduleFilterCheck(targetPath);
1530
+ } else {
1531
+ // Select fields from each target table
1532
+ fields.push(
1533
+ ...this.getFieldsForJoinedLoad(qb, targetMeta, {
1534
+ ...options,
1535
+ populate: hint.children,
1536
+ parentTableAlias: tableAlias,
1537
+ parentJoinPath: targetPath,
1538
+ }),
1539
+ );
1540
+ }
1541
+ }
1542
+ continue;
1543
+ }
1544
+ // ignore ref joins of known FKs unless it's a filter hint
1545
+ if (
1546
+ ref &&
1547
+ !hint.filter &&
1548
+ (prop.kind === ReferenceKind.MANY_TO_ONE || (prop.kind === ReferenceKind.ONE_TO_ONE && prop.owner))
1549
+ ) {
1550
+ continue;
1551
+ }
1552
+ const meta2 = prop.targetMeta;
1553
+ const pivotRefJoin = prop.kind === ReferenceKind.MANY_TO_MANY && ref;
1554
+ const tableAlias = qb.getNextAlias(prop.name);
1555
+ const field = `${options.parentTableAlias}.${prop.name}`;
1556
+ let path = options.parentJoinPath ? `${options.parentJoinPath}.${prop.name}` : `${meta.name}.${prop.name}`;
1557
+ if (!options.parentJoinPath && populateWhereAll && !hint.filter && !path.startsWith('[populate]')) {
1558
+ path = '[populate]' + path;
1559
+ }
1560
+ const mandatoryToOneProperty =
1561
+ [ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(prop.kind) && !prop.nullable;
1562
+ const joinType = pivotRefJoin
1563
+ ? JoinType.pivotJoin
1564
+ : hint.joinType
1565
+ ? hint.joinType
1566
+ : (hint.filter && !prop.nullable) || mandatoryToOneProperty
1567
+ ? JoinType.innerJoin
1568
+ : JoinType.leftJoin;
1569
+ const schema =
1570
+ prop.targetMeta.schema === '*' ? (options?.schema ?? this.config.get('schema')) : prop.targetMeta.schema;
1571
+ qb.join(field, tableAlias, {}, joinType, path, schema);
1572
+ // For relations to TPT child entities, INNER JOIN parent tables (GH #7469)
1573
+ if (meta2.inheritanceType === 'tpt' && meta2.tptParent) {
1574
+ let childAlias = tableAlias;
1575
+ let childMeta = meta2;
1576
+ while (childMeta.tptParent) {
1577
+ const parentMeta = childMeta.tptParent;
1578
+ const parentAlias = qb.getNextAlias(parentMeta.className);
1579
+ qb.createAlias(parentMeta.class, parentAlias);
1580
+ qb.state.tptAlias[`${tableAlias}:${parentMeta.className}`] = parentAlias;
1581
+ qb.addPropertyJoin(
1582
+ childMeta.tptParentProp,
1583
+ childAlias,
1584
+ parentAlias,
1585
+ JoinType.innerJoin,
1586
+ `${path}.[tpt]${childMeta.className}`,
1587
+ );
1588
+ childAlias = parentAlias;
1589
+ childMeta = parentMeta;
1590
+ }
1591
+ }
1592
+ // For relations to TPT base classes, add LEFT JOINs for all child tables (polymorphic loading)
1593
+ if (meta2.inheritanceType === 'tpt' && meta2.tptChildren?.length && !ref) {
1594
+ // Use the registry metadata to ensure allTPTDescendants is available
1595
+ const tptMeta = this.metadata.get(meta2.class);
1596
+ this.addTPTPolymorphicJoinsForRelation(qb, tptMeta, tableAlias, fields);
1597
+ }
1598
+ if (pivotRefJoin) {
1599
+ fields.push(
1600
+ ...prop.joinColumns.map(col =>
1601
+ qb.helper.mapper(`${tableAlias}.${col}`, qb.type, undefined, `${tableAlias}__${col}`),
1602
+ ),
1603
+ ...prop.inverseJoinColumns.map(col =>
1604
+ qb.helper.mapper(`${tableAlias}.${col}`, qb.type, undefined, `${tableAlias}__${col}`),
1605
+ ),
1606
+ );
1607
+ }
1608
+ if (prop.kind === ReferenceKind.ONE_TO_MANY && ref) {
1609
+ fields.push(
1610
+ ...this.getFieldsForJoinedLoad(qb, meta2, {
1611
+ ...options,
1612
+ explicitFields: prop.referencedColumnNames,
1613
+ exclude: undefined,
1614
+ populate: hint.children,
1615
+ parentTableAlias: tableAlias,
1616
+ parentJoinPath: path,
1617
+ }),
1618
+ );
1619
+ }
1620
+ const childExplicitFields =
1621
+ options.explicitFields?.filter(f => Utils.isPlainObject(f)).map(o => o[prop.name])[0] || [];
1622
+ options.explicitFields?.forEach(f => {
1623
+ if (typeof f === 'string' && f.startsWith(`${prop.name}.`)) {
1624
+ childExplicitFields.push(f.substring(prop.name.length + 1));
1625
+ }
1626
+ });
1627
+ const childExclude = options.exclude ? Utils.extractChildElements(options.exclude, prop.name) : options.exclude;
1628
+ if (!ref && (!prop.mapToPk || hint.dataOnly)) {
1629
+ fields.push(
1630
+ ...this.getFieldsForJoinedLoad(qb, meta2, {
1173
1631
  ...options,
1174
- fields,
1632
+ explicitFields: childExplicitFields.length === 0 ? undefined : childExplicitFields,
1175
1633
  exclude: childExclude,
1176
- orderBy: this.getPivotOrderBy(prop, inverseProp, orderBy, options?.orderBy),
1177
- populate: [
1178
- {
1179
- field: populateField,
1180
- strategy: LoadStrategy.JOINED,
1181
- joinType: JoinType.innerJoin,
1182
- children: populate,
1183
- dataOnly: inverseProp.mapToPk && !pivotJoin,
1184
- },
1185
- ],
1186
- populateWhere: undefined,
1187
- // @ts-ignore
1188
- _populateWhere: 'infer',
1189
- populateFilter: this.wrapPopulateFilter(options, inverseProp.name),
1190
- });
1191
- return this.buildPivotResultMap(owners, res, prop.discriminator, inverseProp.name);
1634
+ populate: hint.children,
1635
+ parentTableAlias: tableAlias,
1636
+ parentJoinPath: path,
1637
+ }),
1638
+ );
1639
+ } else if (
1640
+ hint.filter ||
1641
+ (prop.mapToPk && !hint.dataOnly) ||
1642
+ (ref && [ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(prop.kind))
1643
+ ) {
1644
+ fields.push(
1645
+ ...prop.referencedColumnNames.map(col =>
1646
+ qb.helper.mapper(`${tableAlias}.${col}`, qb.type, undefined, `${tableAlias}__${col}`),
1647
+ ),
1648
+ );
1649
+ }
1192
1650
  }
1193
- /**
1194
- * Load from inverse side of polymorphic M:N (e.g., Tag -> Posts)
1195
- * Uses single query with join via virtual relation on pivot.
1196
- */
1197
- async loadPolymorphicPivotInverseSide(prop, owners, where, orderBy, ctx, options) {
1651
+ return fields;
1652
+ }
1653
+ /**
1654
+ * Adds LEFT JOINs and fields for TPT polymorphic loading when populating a relation to a TPT base class.
1655
+ * @internal
1656
+ */
1657
+ addTPTPolymorphicJoinsForRelation(qb, meta, baseAlias, fields) {
1658
+ // allTPTDescendants is pre-computed during discovery, sorted by depth (deepest first)
1659
+ const descendants = meta.allTPTDescendants;
1660
+ const childAliases = {};
1661
+ // LEFT JOIN each descendant table
1662
+ for (const childMeta of descendants) {
1663
+ const childAlias = qb.getNextAlias(childMeta.className);
1664
+ qb.createAlias(childMeta.class, childAlias);
1665
+ childAliases[childMeta.className] = childAlias;
1666
+ qb.addPropertyJoin(childMeta.tptInverseProp, baseAlias, childAlias, JoinType.leftJoin, `[tpt]${meta.className}`);
1667
+ // Add fields from this child (only ownProps, skip PKs)
1668
+ const schema = childMeta.schema === '*' ? '*' : this.getSchemaName(childMeta);
1669
+ childMeta.ownProps
1670
+ .filter(p => !p.primary && this.platform.shouldHaveColumn(p, []))
1671
+ .forEach(prop => fields.push(...this.mapPropToFieldNames(qb, prop, childAlias, childMeta, schema)));
1672
+ }
1673
+ // Add computed discriminator (descendants already sorted by depth)
1674
+ if (meta.root.tptDiscriminatorColumn) {
1675
+ fields.push(this.buildTPTDiscriminatorExpression(meta, descendants, childAliases, baseAlias));
1676
+ }
1677
+ }
1678
+ /**
1679
+ * Find the alias for a TPT child table in the query builder.
1680
+ * @internal
1681
+ */
1682
+ findTPTChildAlias(qb, childMeta) {
1683
+ const joins = qb.state.joins;
1684
+ for (const key of Object.keys(joins)) {
1685
+ if (joins[key].table === childMeta.tableName && key.includes('[tpt]')) {
1686
+ return joins[key].alias;
1687
+ }
1688
+ }
1689
+ return undefined;
1690
+ }
1691
+ /**
1692
+ * Builds a CASE WHEN expression for TPT discriminator.
1693
+ * Determines concrete entity type based on which child table has a non-null PK.
1694
+ * @internal
1695
+ */
1696
+ buildTPTDiscriminatorExpression(meta, descendants, aliasMap, baseAlias) {
1697
+ const cases = descendants.map(child => {
1698
+ const childAlias = aliasMap[child.className];
1699
+ const pkFieldName = child.properties[child.primaryKeys[0]].fieldNames[0];
1700
+ return `when ${this.platform.quoteIdentifier(`${childAlias}.${pkFieldName}`)} is not null then '${child.discriminatorValue}'`;
1701
+ });
1702
+ const defaultValue = meta.abstract ? 'null' : `'${meta.discriminatorValue}'`;
1703
+ const caseExpr = `case ${cases.join(' ')} else ${defaultValue} end`;
1704
+ const aliased = this.platform.quoteIdentifier(`${baseAlias}__${meta.root.tptDiscriminatorColumn}`);
1705
+ return raw(`${caseExpr} as ${aliased}`);
1706
+ }
1707
+ /**
1708
+ * Maps TPT child-specific fields during hydration.
1709
+ * When a relation points to a TPT base class, the actual entity might be a child class.
1710
+ * This method reads the discriminator to determine the concrete type and maps child-specific fields.
1711
+ * @internal
1712
+ */
1713
+ mapTPTChildFields(relationPojo, meta, relationAlias, qb, root) {
1714
+ if (meta.inheritanceType !== 'tpt' || !meta.root.tptDiscriminatorColumn) {
1715
+ return;
1716
+ }
1717
+ const discriminatorAlias = `${relationAlias}__${meta.root.tptDiscriminatorColumn}`;
1718
+ const discriminatorValue = root[discriminatorAlias];
1719
+ if (!discriminatorValue) {
1720
+ return;
1721
+ }
1722
+ relationPojo[meta.root.tptDiscriminatorColumn] = discriminatorValue;
1723
+ const concreteClass = meta.root.discriminatorMap?.[discriminatorValue];
1724
+ /* v8 ignore next 3 - defensive check for invalid discriminator values */
1725
+ if (!concreteClass) {
1726
+ return;
1727
+ }
1728
+ const concreteMeta = this.metadata.get(concreteClass);
1729
+ delete root[discriminatorAlias];
1730
+ if (concreteMeta === meta) {
1731
+ return concreteMeta;
1732
+ }
1733
+ // Traverse up from concrete type and map fields from each level's table
1734
+ const tz = this.platform.getTimezone();
1735
+ let currentMeta = concreteMeta;
1736
+ while (currentMeta && currentMeta !== meta) {
1737
+ const childAlias = this.findTPTChildAlias(qb, currentMeta);
1738
+ if (childAlias) {
1739
+ // Map fields using same filtering as joined loading, plus skip PKs
1740
+ for (const prop of currentMeta.ownProps.filter(p => !p.primary && this.platform.shouldHaveColumn(p, []))) {
1741
+ this.mapJoinedProp(relationPojo, prop, childAlias, root, tz, currentMeta, {
1742
+ deleteFromRoot: true,
1743
+ });
1744
+ }
1745
+ }
1746
+ currentMeta = currentMeta.tptParent;
1747
+ }
1748
+ return concreteMeta;
1749
+ }
1750
+ /**
1751
+ * @internal
1752
+ */
1753
+ mapPropToFieldNames(qb, prop, tableAlias, meta, schema, explicitFields) {
1754
+ if (prop.kind === ReferenceKind.EMBEDDED && !prop.object) {
1755
+ return Object.entries(prop.embeddedProps).flatMap(([name, childProp]) => {
1756
+ const childFields = explicitFields ? Utils.extractChildElements(explicitFields, prop.name) : [];
1757
+ if (
1758
+ !this.shouldHaveColumn(
1759
+ prop.targetMeta,
1760
+ { ...childProp, name },
1761
+ [],
1762
+ childFields.length > 0 ? childFields : undefined,
1763
+ )
1764
+ ) {
1765
+ return [];
1766
+ }
1767
+ return this.mapPropToFieldNames(qb, childProp, tableAlias, meta, schema, childFields);
1768
+ });
1769
+ }
1770
+ const aliased = this.platform.quoteIdentifier(`${tableAlias}__${prop.fieldNames[0]}`);
1771
+ if (prop.customTypes?.some(type => !!type?.convertToJSValueSQL)) {
1772
+ return prop.fieldNames.map((col, idx) => {
1773
+ if (!prop.customTypes[idx]?.convertToJSValueSQL) {
1774
+ return col;
1775
+ }
1776
+ const prefixed = this.platform.quoteIdentifier(`${tableAlias}.${col}`);
1777
+ const aliased = this.platform.quoteIdentifier(`${tableAlias}__${col}`);
1778
+ return raw(`${prop.customTypes[idx].convertToJSValueSQL(prefixed, this.platform)} as ${aliased}`);
1779
+ });
1780
+ }
1781
+ if (prop.customType?.convertToJSValueSQL) {
1782
+ const prefixed = this.platform.quoteIdentifier(`${tableAlias}.${prop.fieldNames[0]}`);
1783
+ return [raw(`${prop.customType.convertToJSValueSQL(prefixed, this.platform)} as ${aliased}`)];
1784
+ }
1785
+ if (prop.formula) {
1786
+ const quotedAlias = this.platform.quoteIdentifier(tableAlias).toString();
1787
+ const table = this.createFormulaTable(quotedAlias, meta, schema);
1788
+ const columns = meta.createColumnMappingObject(tableAlias);
1789
+ return [raw(`${this.evaluateFormula(prop.formula, columns, table)} as ${aliased}`)];
1790
+ }
1791
+ const sourceAlias = qb.helper.getTPTAliasForProperty(prop.name, tableAlias);
1792
+ return prop.fieldNames.map(fieldName => {
1793
+ return raw('?? as ??', [`${sourceAlias}.${fieldName}`, `${tableAlias}__${fieldName}`]);
1794
+ });
1795
+ }
1796
+ /** @internal */
1797
+ createQueryBuilder(entityName, ctx, preferredConnectionType, convertCustomTypes, loggerContext, alias, em) {
1798
+ // do not compute the connectionType if EM is provided as it will be computed from it in the QB later on
1799
+ const connectionType = em
1800
+ ? preferredConnectionType
1801
+ : this.resolveConnectionType({ ctx, connectionType: preferredConnectionType });
1802
+ const qb = new QueryBuilder(entityName, this.metadata, this, ctx, alias, connectionType, em, loggerContext);
1803
+ if (!convertCustomTypes) {
1804
+ qb.unsetFlag(QueryFlag.CONVERT_CUSTOM_TYPES);
1805
+ }
1806
+ return qb;
1807
+ }
1808
+ resolveConnectionType(args) {
1809
+ if (args.ctx) {
1810
+ return 'write';
1811
+ }
1812
+ if (args.connectionType) {
1813
+ return args.connectionType;
1814
+ }
1815
+ if (this.config.get('preferReadReplicas')) {
1816
+ return 'read';
1817
+ }
1818
+ return 'write';
1819
+ }
1820
+ extractManyToMany(meta, data) {
1821
+ const ret = {};
1822
+ for (const prop of meta.relations) {
1823
+ if (prop.kind === ReferenceKind.MANY_TO_MANY && data[prop.name]) {
1824
+ ret[prop.name] = data[prop.name].map(item => Utils.asArray(item));
1825
+ delete data[prop.name];
1826
+ }
1827
+ }
1828
+ return ret;
1829
+ }
1830
+ async processManyToMany(meta, pks, collections, clear, options) {
1831
+ for (const prop of meta.relations) {
1832
+ if (collections[prop.name]) {
1198
1833
  const pivotMeta = this.metadata.get(prop.pivotEntity);
1834
+ const persister = new PivotCollectionPersister(
1835
+ pivotMeta,
1836
+ this,
1837
+ options?.ctx,
1838
+ options?.schema,
1839
+ options?.loggerContext,
1840
+ );
1841
+ persister.enqueueUpdate(prop, collections[prop.name], clear, pks);
1842
+ await this.rethrow(persister.execute());
1843
+ }
1844
+ }
1845
+ }
1846
+ async lockPessimistic(entity, options) {
1847
+ const meta = helper(entity).__meta;
1848
+ const qb = this.createQueryBuilder(meta.class, options.ctx, undefined, undefined, options.logging).withSchema(
1849
+ options.schema ?? meta.schema,
1850
+ );
1851
+ const cond = Utils.getPrimaryKeyCond(entity, meta.primaryKeys);
1852
+ qb.select(raw('1')).where(cond).setLockMode(options.lockMode, options.lockTableAliases);
1853
+ await this.rethrow(qb.execute());
1854
+ }
1855
+ buildPopulateWhere(meta, joinedProps, options) {
1856
+ const where = {};
1857
+ for (const hint of joinedProps) {
1858
+ const [propName] = hint.field.split(':', 2);
1859
+ const prop = meta.properties[propName];
1860
+ if (!Utils.isEmpty(prop.where) || RawQueryFragment.hasObjectFragments(prop.where)) {
1861
+ where[prop.name] = Utils.copy(prop.where);
1862
+ }
1863
+ if (hint.children) {
1199
1864
  const targetMeta = prop.targetMeta;
1200
- // Find the relation to the entity we're starting from (e.g., Tag_inverse -> Tag)
1201
- // Exclude virtual polymorphic owner relations (persist: false) - we want the actual M:N inverse relation
1202
- const tagProp = pivotMeta.relations.find(r => r.persist !== false && r.targetMeta !== targetMeta);
1203
- // Find the virtual relation to the polymorphic owner (e.g., taggable_Post -> Post)
1204
- const ownerRelationName = `${prop.discriminator}_${targetMeta.tableName}`;
1205
- const ownerProp = pivotMeta.properties[ownerRelationName];
1206
- // Build condition: discriminator = 'post' AND Tag_inverse IN (tagIds)
1207
- const cond = {
1208
- [prop.discriminatorColumn]: prop.discriminatorValue,
1209
- [tagProp.name]: { $in: owners.length === 1 && owners[0].length === 1 ? owners.map(o => o[0]) : owners },
1210
- };
1211
- if (!Utils.isEmpty(where)) {
1212
- cond[ownerRelationName] = { ...where };
1213
- }
1214
- const populateField = ownerRelationName;
1215
- const populate = this.autoJoinOneToOneOwner(targetMeta, options?.populate ?? [], options?.fields);
1216
- const childFields = !Utils.isEmpty(options?.fields) ? options.fields.map(f => `${ownerRelationName}.${f}`) : [];
1217
- const childExclude = !Utils.isEmpty(options?.exclude)
1218
- ? options.exclude.map(f => `${ownerRelationName}.${f}`)
1219
- : [];
1220
- const fields = [ownerRelationName, tagProp.name, prop.discriminatorColumn, ...childFields];
1221
- const res = await this.find(pivotMeta.class, cond, {
1222
- ctx,
1223
- ...options,
1224
- fields,
1225
- exclude: childExclude,
1226
- orderBy: this.getPivotOrderBy(prop, ownerProp, orderBy, options?.orderBy),
1227
- populate: [
1228
- {
1229
- field: populateField,
1230
- strategy: LoadStrategy.JOINED,
1231
- joinType: JoinType.innerJoin,
1232
- children: populate,
1233
- },
1234
- ],
1235
- populateWhere: undefined,
1236
- // @ts-ignore
1237
- _populateWhere: 'infer',
1238
- populateFilter: this.wrapPopulateFilter(options, ownerRelationName),
1239
- });
1240
- return this.buildPivotResultMap(owners, res, tagProp.name, ownerRelationName);
1241
- }
1242
- /**
1243
- * Build a map from owner PKs to their related entities from pivot table results.
1244
- */
1245
- buildPivotResultMap(owners, results, keyProp, valueProp) {
1246
- const map = {};
1247
- for (const owner of owners) {
1248
- const key = Utils.getPrimaryKeyHash(owner);
1249
- map[key] = [];
1250
- }
1251
- for (const item of results) {
1252
- const key = Utils.getPrimaryKeyHash(Utils.asArray(item[keyProp]));
1253
- const entity = item[valueProp];
1254
- if (map[key]) {
1255
- map[key].push(entity);
1256
- }
1257
- }
1258
- return map;
1865
+ if (targetMeta) {
1866
+ const inner = this.buildPopulateWhere(targetMeta, hint.children, {});
1867
+ if (!Utils.isEmpty(inner) || RawQueryFragment.hasObjectFragments(inner)) {
1868
+ where[prop.name] ??= {};
1869
+ Object.assign(where[prop.name], inner);
1870
+ }
1871
+ }
1872
+ }
1259
1873
  }
1260
- wrapPopulateFilter(options, propName) {
1261
- if (!Utils.isEmpty(options?.populateFilter) || RawQueryFragment.hasObjectFragments(options?.populateFilter)) {
1262
- return { [propName]: options?.populateFilter };
1263
- }
1264
- return undefined;
1874
+ if (Utils.isEmpty(options.populateWhere) && !RawQueryFragment.hasObjectFragments(options.populateWhere)) {
1875
+ return where;
1265
1876
  }
1266
- getPivotOrderBy(prop, pivotProp, orderBy, parentOrderBy) {
1267
- if (!Utils.isEmpty(orderBy) || RawQueryFragment.hasObjectFragments(orderBy)) {
1268
- return Utils.asArray(orderBy).map(o => ({ [pivotProp.name]: o }));
1269
- }
1270
- if (prop.kind === ReferenceKind.MANY_TO_MANY && Utils.asArray(parentOrderBy).some(o => o[prop.name])) {
1271
- return Utils.asArray(parentOrderBy)
1272
- .filter(o => o[prop.name])
1273
- .map(o => ({ [pivotProp.name]: o[prop.name] }));
1274
- }
1275
- if (!Utils.isEmpty(prop.orderBy) || RawQueryFragment.hasObjectFragments(prop.orderBy)) {
1276
- return Utils.asArray(prop.orderBy).map(o => ({ [pivotProp.name]: o }));
1277
- }
1278
- if (prop.fixedOrder) {
1279
- return [{ [prop.fixedOrderColumn]: QueryOrder.ASC }];
1280
- }
1281
- return [];
1877
+ if (Utils.isEmpty(where) && !RawQueryFragment.hasObjectFragments(where)) {
1878
+ return options.populateWhere;
1282
1879
  }
1283
- async execute(query, params = [], method = 'all', ctx, loggerContext) {
1284
- return this.rethrow(this.connection.execute(query, params, method, ctx, loggerContext));
1880
+ /* v8 ignore next */
1881
+ return { $and: [options.populateWhere, where] };
1882
+ }
1883
+ /**
1884
+ * Builds a UNION ALL (or UNION) subquery from `unionWhere` branches and merges it
1885
+ * into the main WHERE as `pk IN (branch_1 UNION ALL branch_2 ...)`.
1886
+ * Each branch is planned independently by the database, enabling per-table index usage.
1887
+ */
1888
+ async applyUnionWhere(meta, where, options, forDml = false) {
1889
+ const unionWhere = options.unionWhere;
1890
+ const strategy = options.unionWhereStrategy ?? 'union-all';
1891
+ const schema = this.getSchemaName(meta, options);
1892
+ const connectionType = this.resolveConnectionType({
1893
+ ctx: options.ctx,
1894
+ connectionType: options.connectionType,
1895
+ });
1896
+ const branchQbs = [];
1897
+ for (const branch of unionWhere) {
1898
+ const qb = this.createQueryBuilder(meta.class, options.ctx, connectionType, false, options.logging).withSchema(
1899
+ schema,
1900
+ );
1901
+ const pkFields = meta.primaryKeys.map(pk => {
1902
+ const prop = meta.properties[pk];
1903
+ return `${qb.alias}.${prop.fieldNames[0]}`;
1904
+ });
1905
+ qb.select(pkFields).where(branch);
1906
+ if (options.em) {
1907
+ await qb.applyJoinedFilters(options.em, options.filters);
1908
+ }
1909
+ branchQbs.push(qb);
1285
1910
  }
1286
- async *stream(entityName, where, options) {
1287
- options = { populate: [], orderBy: [], ...options };
1288
- const meta = this.metadata.get(entityName);
1289
- if (meta.virtual) {
1290
- yield* this.streamFromVirtual(entityName, where, options);
1291
- return;
1292
- }
1293
- const qb = await this.createQueryBuilderFromOptions(meta, where, options);
1294
- try {
1295
- const result = qb.stream(options);
1296
- for await (const item of result) {
1297
- yield item;
1298
- }
1299
- }
1300
- catch (e) {
1301
- throw this.convertException(e);
1302
- }
1911
+ const [first, ...rest] = branchQbs;
1912
+ const unionQb = strategy === 'union' ? first.union(...rest) : first.unionAll(...rest);
1913
+ const pkHash = Utils.getPrimaryKeyHash(meta.primaryKeys);
1914
+ // MySQL does not allow referencing the target table in a subquery
1915
+ // for UPDATE/DELETE, so we wrap the union in a derived table.
1916
+ if (forDml) {
1917
+ const { sql, params } = unionQb.toQuery();
1918
+ return {
1919
+ $and: [where, { [pkHash]: { $in: raw(`select * from (${sql}) as __u`, params) } }],
1920
+ };
1303
1921
  }
1304
- /**
1305
- * 1:1 owner side needs to be marked for population so QB auto-joins the owner id
1306
- */
1307
- autoJoinOneToOneOwner(meta, populate, fields = []) {
1308
- if (!this.config.get('autoJoinOneToOneOwner')) {
1309
- return populate;
1922
+ return {
1923
+ $and: [where, { [pkHash]: { $in: unionQb.toRaw() } }],
1924
+ };
1925
+ }
1926
+ buildOrderBy(qb, meta, populate, options) {
1927
+ const joinedProps = this.joinedProps(meta, populate, options);
1928
+ // `options._populateWhere` is a copy of the value provided by user with a fallback to the global config option
1929
+ // as `options.populateWhere` will be always recomputed to respect filters
1930
+ const populateWhereAll = options._populateWhere !== 'infer' && !Utils.isEmpty(options._populateWhere);
1931
+ const path = (populateWhereAll ? '[populate]' : '') + meta.className;
1932
+ const optionsOrderBy = Utils.asArray(options.orderBy);
1933
+ const populateOrderBy = this.buildPopulateOrderBy(
1934
+ qb,
1935
+ meta,
1936
+ Utils.asArray(options.populateOrderBy ?? options.orderBy),
1937
+ path,
1938
+ !!options.populateOrderBy,
1939
+ );
1940
+ const joinedPropsOrderBy = this.buildJoinedPropsOrderBy(qb, meta, joinedProps, options, path);
1941
+ return [...optionsOrderBy, ...populateOrderBy, ...joinedPropsOrderBy];
1942
+ }
1943
+ buildPopulateOrderBy(qb, meta, populateOrderBy, parentPath, explicit, parentAlias = qb.alias) {
1944
+ const orderBy = [];
1945
+ for (let i = 0; i < populateOrderBy.length; i++) {
1946
+ const orderHint = populateOrderBy[i];
1947
+ for (const field of Utils.getObjectQueryKeys(orderHint)) {
1948
+ const childOrder = orderHint[field];
1949
+ if (RawQueryFragment.isKnownFragmentSymbol(field)) {
1950
+ const { sql, params } = RawQueryFragment.getKnownFragment(field);
1951
+ const key = raw(sql.replace(new RegExp(ALIAS_REPLACEMENT_RE, 'g'), parentAlias), params);
1952
+ orderBy.push({ [key]: childOrder });
1953
+ continue;
1954
+ }
1955
+ const prop = meta.properties[field];
1956
+ if (!prop) {
1957
+ throw new Error(`Trying to order by not existing property ${meta.className}.${field}`);
1958
+ }
1959
+ let path = parentPath;
1960
+ const meta2 = prop.targetMeta;
1961
+ if (
1962
+ prop.kind !== ReferenceKind.SCALAR &&
1963
+ (![ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(prop.kind) ||
1964
+ !prop.owner ||
1965
+ Utils.isPlainObject(childOrder))
1966
+ ) {
1967
+ path += `.${field}`;
1968
+ }
1969
+ if (prop.kind === ReferenceKind.MANY_TO_MANY && typeof childOrder !== 'object') {
1970
+ path += '[pivot]';
1310
1971
  }
1311
- const relationsToPopulate = populate.map(({ field }) => field.split(':')[0]);
1312
- const toPopulate = meta.relations
1313
- .filter(prop => prop.kind === ReferenceKind.ONE_TO_ONE &&
1314
- !prop.owner &&
1315
- !prop.lazy &&
1316
- !relationsToPopulate.includes(prop.name))
1317
- .filter(prop => fields.length === 0 || fields.some(f => prop.name === f || prop.name.startsWith(`${String(f)}.`)))
1318
- .map(prop => ({ field: `${prop.name}:ref`, strategy: LoadStrategy.JOINED }));
1319
- return [...populate, ...toPopulate];
1320
- }
1321
- /**
1322
- * @internal
1323
- */
1324
- joinedProps(meta, populate, options) {
1325
- return populate.filter(hint => {
1326
- const [propName, ref] = hint.field.split(':', 2);
1327
- const prop = meta.properties[propName] || {};
1328
- const strategy = getLoadingStrategy(hint.strategy || prop.strategy || options?.strategy || this.config.get('loadStrategy'), prop.kind);
1329
- if (ref && [ReferenceKind.ONE_TO_ONE, ReferenceKind.MANY_TO_ONE].includes(prop.kind)) {
1330
- return true;
1331
- }
1332
- // skip redundant joins for 1:1 owner population hints when using `mapToPk`
1333
- if (prop.kind === ReferenceKind.ONE_TO_ONE && prop.mapToPk && prop.owner) {
1334
- return false;
1335
- }
1336
- if (strategy !== LoadStrategy.JOINED) {
1337
- // force joined strategy for explicit 1:1 owner populate hint as it would require a join anyway
1338
- return prop.kind === ReferenceKind.ONE_TO_ONE && !prop.owner;
1339
- }
1340
- return ![ReferenceKind.SCALAR, ReferenceKind.EMBEDDED].includes(prop.kind);
1341
- });
1972
+ const join = qb.getJoinForPath(path, { matchPopulateJoins: true });
1973
+ const propAlias = qb.getAliasForJoinPath(join ?? path, { matchPopulateJoins: true }) ?? parentAlias;
1974
+ if (!join) {
1975
+ continue;
1976
+ }
1977
+ if (
1978
+ join &&
1979
+ ![ReferenceKind.SCALAR, ReferenceKind.EMBEDDED].includes(prop.kind) &&
1980
+ typeof childOrder === 'object'
1981
+ ) {
1982
+ const children = this.buildPopulateOrderBy(qb, meta2, Utils.asArray(childOrder), path, explicit, propAlias);
1983
+ orderBy.push(...children);
1984
+ continue;
1985
+ }
1986
+ if (prop.kind === ReferenceKind.MANY_TO_MANY && join) {
1987
+ if (prop.fixedOrderColumn) {
1988
+ orderBy.push({ [`${join.alias}.${prop.fixedOrderColumn}`]: childOrder });
1989
+ } else {
1990
+ for (const col of prop.inverseJoinColumns) {
1991
+ orderBy.push({ [`${join.ownerAlias}.${col}`]: childOrder });
1992
+ }
1993
+ }
1994
+ continue;
1995
+ }
1996
+ const order = typeof childOrder === 'object' ? childOrder[field] : childOrder;
1997
+ if (order) {
1998
+ orderBy.push({ [`${propAlias}.${field}`]: order });
1999
+ }
2000
+ }
1342
2001
  }
1343
- /**
1344
- * @internal
1345
- */
1346
- mergeJoinedResult(rawResults, meta, joinedProps) {
1347
- if (rawResults.length <= 1) {
1348
- return rawResults;
1349
- }
1350
- const res = [];
1351
- const map = {};
1352
- const collectionsToMerge = {};
1353
- const hints = joinedProps.map(hint => {
1354
- const [propName, ref] = hint.field.split(':', 2);
1355
- return { propName, ref, children: hint.children };
1356
- });
1357
- for (const item of rawResults) {
1358
- const pk = Utils.getCompositeKeyHash(item, meta);
1359
- if (map[pk]) {
1360
- for (const { propName } of hints) {
1361
- if (!item[propName]) {
1362
- continue;
1363
- }
1364
- collectionsToMerge[pk] ??= {};
1365
- collectionsToMerge[pk][propName] ??= [map[pk][propName]];
1366
- collectionsToMerge[pk][propName].push(item[propName]);
1367
- }
1368
- }
1369
- else {
1370
- map[pk] = item;
1371
- res.push(item);
1372
- }
1373
- }
1374
- for (const pk in collectionsToMerge) {
1375
- const entity = map[pk];
1376
- const collections = collectionsToMerge[pk];
1377
- for (const { propName, ref, children } of hints) {
1378
- if (!collections[propName]) {
1379
- continue;
1380
- }
1381
- const prop = meta.properties[propName];
1382
- const items = collections[propName].flat();
1383
- if ([ReferenceKind.ONE_TO_MANY, ReferenceKind.MANY_TO_MANY].includes(prop.kind) && ref) {
1384
- entity[propName] = items;
1385
- continue;
1386
- }
1387
- switch (prop.kind) {
1388
- case ReferenceKind.ONE_TO_MANY:
1389
- case ReferenceKind.MANY_TO_MANY:
1390
- entity[propName] = this.mergeJoinedResult(items, prop.targetMeta, children ?? []);
1391
- break;
1392
- case ReferenceKind.MANY_TO_ONE:
1393
- case ReferenceKind.ONE_TO_ONE:
1394
- entity[propName] = this.mergeJoinedResult(items, prop.targetMeta, children ?? [])[0];
1395
- break;
1396
- }
1397
- }
1398
- }
1399
- return res;
2002
+ return orderBy;
2003
+ }
2004
+ buildJoinedPropsOrderBy(qb, meta, populate, options, parentPath) {
2005
+ const orderBy = [];
2006
+ const joinedProps = this.joinedProps(meta, populate, options);
2007
+ for (const hint of joinedProps) {
2008
+ const [propName, ref] = hint.field.split(':', 2);
2009
+ const prop = meta.properties[propName];
2010
+ let path = `${parentPath}.${propName}`;
2011
+ if (prop.kind === ReferenceKind.MANY_TO_MANY && ref) {
2012
+ path += '[pivot]';
2013
+ }
2014
+ if ([ReferenceKind.MANY_TO_MANY, ReferenceKind.ONE_TO_MANY].includes(prop.kind)) {
2015
+ this.buildToManyOrderBy(qb, prop, path, ref, orderBy);
2016
+ }
2017
+ if (hint.children) {
2018
+ orderBy.push(...this.buildJoinedPropsOrderBy(qb, prop.targetMeta, hint.children, options, path));
2019
+ }
1400
2020
  }
1401
- shouldHaveColumn(meta, prop, populate, fields, exclude) {
1402
- if (!this.platform.shouldHaveColumn(prop, populate, exclude)) {
1403
- return false;
1404
- }
1405
- if (!fields || fields.includes('*') || prop.primary || meta.root.discriminatorColumn === prop.name) {
1406
- return true;
1407
- }
1408
- return fields.some(f => f === prop.name || f.toString().startsWith(prop.name + '.'));
1409
- }
1410
- getFieldsForJoinedLoad(qb, meta, options) {
1411
- const fields = [];
1412
- const populate = options.populate ?? [];
1413
- const joinedProps = this.joinedProps(meta, populate, options);
1414
- const populateWhereAll = options?._populateWhere === 'all' || Utils.isEmpty(options?._populateWhere);
1415
- // Ensure TPT joins are applied early so that _tptAlias is available for join resolution
1416
- // This is needed when populating relations that are inherited from TPT parent entities
1417
- if (!options.parentJoinPath) {
1418
- qb.ensureTPTJoins();
1419
- }
1420
- // root entity is already handled, skip that
1421
- if (options.parentJoinPath) {
1422
- // alias all fields in the primary table
1423
- meta.props
1424
- .filter(prop => this.shouldHaveColumn(meta, prop, populate, options.explicitFields, options.exclude))
1425
- .forEach(prop => fields.push(...this.mapPropToFieldNames(qb, prop, options.parentTableAlias, meta, options.schema, options.explicitFields)));
1426
- }
1427
- for (const hint of joinedProps) {
1428
- const [propName, ref] = hint.field.split(':', 2);
1429
- const prop = meta.properties[propName];
1430
- // Polymorphic to-one: create a LEFT JOIN per target type
1431
- // Skip regular :ref hints — polymorphic to-one already has FK + discriminator in the row
1432
- // But allow filter :ref hints through to create per-target LEFT JOINs with filter checks
1433
- if (prop.polymorphic &&
1434
- prop.polymorphTargets?.length &&
1435
- (!ref || hint.filter) &&
1436
- [ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(prop.kind)) {
1437
- const basePath = options.parentJoinPath
1438
- ? `${options.parentJoinPath}.${prop.name}`
1439
- : `${meta.name}.${prop.name}`;
1440
- const pathPrefix = !options.parentJoinPath && populateWhereAll && !basePath.startsWith('[populate]') ? '[populate]' : '';
1441
- for (const targetMeta of prop.polymorphTargets) {
1442
- const tableAlias = qb.getNextAlias(targetMeta.className);
1443
- const targetPath = `${pathPrefix}${basePath}[${targetMeta.className}]`;
1444
- const schema = targetMeta.schema === '*' ? (options?.schema ?? this.config.get('schema')) : targetMeta.schema;
1445
- qb.addPolymorphicJoin(prop, targetMeta, options.parentTableAlias, tableAlias, JoinType.leftJoin, targetPath, schema);
1446
- // For polymorphic targets that are TPT base classes, also LEFT JOIN
1447
- // all descendant tables so child-specific fields can be selected.
1448
- if (targetMeta.inheritanceType === 'tpt' && targetMeta.tptChildren?.length && !ref) {
1449
- const tptMeta = this.metadata.get(targetMeta.class);
1450
- this.addTPTPolymorphicJoinsForRelation(qb, tptMeta, tableAlias, fields);
1451
- }
1452
- if (ref) {
1453
- // For filter :ref hints, schedule filter check for each target (no field selection)
1454
- qb.scheduleFilterCheck(targetPath);
1455
- }
1456
- else {
1457
- // Select fields from each target table
1458
- fields.push(...this.getFieldsForJoinedLoad(qb, targetMeta, {
1459
- ...options,
1460
- populate: hint.children,
1461
- parentTableAlias: tableAlias,
1462
- parentJoinPath: targetPath,
1463
- }));
1464
- }
1465
- }
1466
- continue;
1467
- }
1468
- // ignore ref joins of known FKs unless it's a filter hint
1469
- if (ref &&
1470
- !hint.filter &&
1471
- (prop.kind === ReferenceKind.MANY_TO_ONE || (prop.kind === ReferenceKind.ONE_TO_ONE && prop.owner))) {
1472
- continue;
1473
- }
1474
- const meta2 = prop.targetMeta;
1475
- const pivotRefJoin = prop.kind === ReferenceKind.MANY_TO_MANY && ref;
1476
- const tableAlias = qb.getNextAlias(prop.name);
1477
- const field = `${options.parentTableAlias}.${prop.name}`;
1478
- let path = options.parentJoinPath ? `${options.parentJoinPath}.${prop.name}` : `${meta.name}.${prop.name}`;
1479
- if (!options.parentJoinPath && populateWhereAll && !hint.filter && !path.startsWith('[populate]')) {
1480
- path = '[populate]' + path;
1481
- }
1482
- const mandatoryToOneProperty = [ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(prop.kind) && !prop.nullable;
1483
- const joinType = pivotRefJoin
1484
- ? JoinType.pivotJoin
1485
- : hint.joinType
1486
- ? hint.joinType
1487
- : (hint.filter && !prop.nullable) || mandatoryToOneProperty
1488
- ? JoinType.innerJoin
1489
- : JoinType.leftJoin;
1490
- const schema = prop.targetMeta.schema === '*' ? (options?.schema ?? this.config.get('schema')) : prop.targetMeta.schema;
1491
- qb.join(field, tableAlias, {}, joinType, path, schema);
1492
- // For relations to TPT child entities, INNER JOIN parent tables (GH #7469)
1493
- if (meta2.inheritanceType === 'tpt' && meta2.tptParent) {
1494
- let childAlias = tableAlias;
1495
- let childMeta = meta2;
1496
- while (childMeta.tptParent) {
1497
- const parentMeta = childMeta.tptParent;
1498
- const parentAlias = qb.getNextAlias(parentMeta.className);
1499
- qb.createAlias(parentMeta.class, parentAlias);
1500
- qb.state.tptAlias[`${tableAlias}:${parentMeta.className}`] = parentAlias;
1501
- qb.addPropertyJoin(childMeta.tptParentProp, childAlias, parentAlias, JoinType.innerJoin, `${path}.[tpt]${childMeta.className}`);
1502
- childAlias = parentAlias;
1503
- childMeta = parentMeta;
1504
- }
1505
- }
1506
- // For relations to TPT base classes, add LEFT JOINs for all child tables (polymorphic loading)
1507
- if (meta2.inheritanceType === 'tpt' && meta2.tptChildren?.length && !ref) {
1508
- // Use the registry metadata to ensure allTPTDescendants is available
1509
- const tptMeta = this.metadata.get(meta2.class);
1510
- this.addTPTPolymorphicJoinsForRelation(qb, tptMeta, tableAlias, fields);
1511
- }
1512
- if (pivotRefJoin) {
1513
- fields.push(...prop.joinColumns.map(col => qb.helper.mapper(`${tableAlias}.${col}`, qb.type, undefined, `${tableAlias}__${col}`)), ...prop.inverseJoinColumns.map(col => qb.helper.mapper(`${tableAlias}.${col}`, qb.type, undefined, `${tableAlias}__${col}`)));
1514
- }
1515
- if (prop.kind === ReferenceKind.ONE_TO_MANY && ref) {
1516
- fields.push(...this.getFieldsForJoinedLoad(qb, meta2, {
1517
- ...options,
1518
- explicitFields: prop.referencedColumnNames,
1519
- exclude: undefined,
1520
- populate: hint.children,
1521
- parentTableAlias: tableAlias,
1522
- parentJoinPath: path,
1523
- }));
1524
- }
1525
- const childExplicitFields = options.explicitFields?.filter(f => Utils.isPlainObject(f)).map(o => o[prop.name])[0] || [];
1526
- options.explicitFields?.forEach(f => {
1527
- if (typeof f === 'string' && f.startsWith(`${prop.name}.`)) {
1528
- childExplicitFields.push(f.substring(prop.name.length + 1));
1529
- }
1530
- });
1531
- const childExclude = options.exclude
1532
- ? Utils.extractChildElements(options.exclude, prop.name)
1533
- : options.exclude;
1534
- if (!ref && (!prop.mapToPk || hint.dataOnly)) {
1535
- fields.push(...this.getFieldsForJoinedLoad(qb, meta2, {
1536
- ...options,
1537
- explicitFields: childExplicitFields.length === 0 ? undefined : childExplicitFields,
1538
- exclude: childExclude,
1539
- populate: hint.children,
1540
- parentTableAlias: tableAlias,
1541
- parentJoinPath: path,
1542
- }));
1543
- }
1544
- else if (hint.filter ||
1545
- (prop.mapToPk && !hint.dataOnly) ||
1546
- (ref && [ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(prop.kind))) {
1547
- fields.push(...prop.referencedColumnNames.map(col => qb.helper.mapper(`${tableAlias}.${col}`, qb.type, undefined, `${tableAlias}__${col}`)));
1548
- }
1549
- }
1550
- return fields;
1551
- }
1552
- /**
1553
- * Adds LEFT JOINs and fields for TPT polymorphic loading when populating a relation to a TPT base class.
1554
- * @internal
1555
- */
1556
- addTPTPolymorphicJoinsForRelation(qb, meta, baseAlias, fields) {
1557
- // allTPTDescendants is pre-computed during discovery, sorted by depth (deepest first)
1558
- const descendants = meta.allTPTDescendants;
1559
- const childAliases = {};
1560
- // LEFT JOIN each descendant table
1561
- for (const childMeta of descendants) {
1562
- const childAlias = qb.getNextAlias(childMeta.className);
1563
- qb.createAlias(childMeta.class, childAlias);
1564
- childAliases[childMeta.className] = childAlias;
1565
- qb.addPropertyJoin(childMeta.tptInverseProp, baseAlias, childAlias, JoinType.leftJoin, `[tpt]${meta.className}`);
1566
- // Add fields from this child (only ownProps, skip PKs)
1567
- const schema = childMeta.schema === '*' ? '*' : this.getSchemaName(childMeta);
1568
- childMeta
1569
- .ownProps.filter(p => !p.primary && this.platform.shouldHaveColumn(p, []))
1570
- .forEach(prop => fields.push(...this.mapPropToFieldNames(qb, prop, childAlias, childMeta, schema)));
1571
- }
1572
- // Add computed discriminator (descendants already sorted by depth)
1573
- if (meta.root.tptDiscriminatorColumn) {
1574
- fields.push(this.buildTPTDiscriminatorExpression(meta, descendants, childAliases, baseAlias));
1575
- }
2021
+ return orderBy;
2022
+ }
2023
+ buildToManyOrderBy(qb, prop, path, ref, orderBy) {
2024
+ const join = qb.getJoinForPath(path, { matchPopulateJoins: true });
2025
+ const propAlias = qb.getAliasForJoinPath(join ?? path, { matchPopulateJoins: true });
2026
+ if (prop.kind === ReferenceKind.MANY_TO_MANY && prop.fixedOrder && join) {
2027
+ const alias = ref ? propAlias : join.ownerAlias;
2028
+ orderBy.push({ [`${alias}.${prop.fixedOrderColumn}`]: QueryOrder.ASC });
1576
2029
  }
1577
- /**
1578
- * Find the alias for a TPT child table in the query builder.
1579
- * @internal
1580
- */
1581
- findTPTChildAlias(qb, childMeta) {
1582
- const joins = qb.state.joins;
1583
- for (const key of Object.keys(joins)) {
1584
- if (joins[key].table === childMeta.tableName && key.includes('[tpt]')) {
1585
- return joins[key].alias;
1586
- }
1587
- }
1588
- return undefined;
1589
- }
1590
- /**
1591
- * Builds a CASE WHEN expression for TPT discriminator.
1592
- * Determines concrete entity type based on which child table has a non-null PK.
1593
- * @internal
1594
- */
1595
- buildTPTDiscriminatorExpression(meta, descendants, aliasMap, baseAlias) {
1596
- const cases = descendants.map(child => {
1597
- const childAlias = aliasMap[child.className];
1598
- const pkFieldName = child.properties[child.primaryKeys[0]].fieldNames[0];
1599
- return `when ${this.platform.quoteIdentifier(`${childAlias}.${pkFieldName}`)} is not null then '${child.discriminatorValue}'`;
1600
- });
1601
- const defaultValue = meta.abstract ? 'null' : `'${meta.discriminatorValue}'`;
1602
- const caseExpr = `case ${cases.join(' ')} else ${defaultValue} end`;
1603
- const aliased = this.platform.quoteIdentifier(`${baseAlias}__${meta.root.tptDiscriminatorColumn}`);
1604
- return raw(`${caseExpr} as ${aliased}`);
1605
- }
1606
- /**
1607
- * Maps TPT child-specific fields during hydration.
1608
- * When a relation points to a TPT base class, the actual entity might be a child class.
1609
- * This method reads the discriminator to determine the concrete type and maps child-specific fields.
1610
- * @internal
1611
- */
1612
- mapTPTChildFields(relationPojo, meta, relationAlias, qb, root) {
1613
- if (meta.inheritanceType !== 'tpt' || !meta.root.tptDiscriminatorColumn) {
1614
- return;
1615
- }
1616
- const discriminatorAlias = `${relationAlias}__${meta.root.tptDiscriminatorColumn}`;
1617
- const discriminatorValue = root[discriminatorAlias];
1618
- if (!discriminatorValue) {
1619
- return;
1620
- }
1621
- relationPojo[meta.root.tptDiscriminatorColumn] = discriminatorValue;
1622
- const concreteClass = meta.root.discriminatorMap?.[discriminatorValue];
1623
- /* v8 ignore next 3 - defensive check for invalid discriminator values */
1624
- if (!concreteClass) {
1625
- return;
1626
- }
1627
- const concreteMeta = this.metadata.get(concreteClass);
1628
- delete root[discriminatorAlias];
1629
- if (concreteMeta === meta) {
1630
- return concreteMeta;
1631
- }
1632
- // Traverse up from concrete type and map fields from each level's table
1633
- const tz = this.platform.getTimezone();
1634
- let currentMeta = concreteMeta;
1635
- while (currentMeta && currentMeta !== meta) {
1636
- const childAlias = this.findTPTChildAlias(qb, currentMeta);
1637
- if (childAlias) {
1638
- // Map fields using same filtering as joined loading, plus skip PKs
1639
- for (const prop of currentMeta.ownProps.filter(p => !p.primary && this.platform.shouldHaveColumn(p, []))) {
1640
- this.mapJoinedProp(relationPojo, prop, childAlias, root, tz, currentMeta, {
1641
- deleteFromRoot: true,
1642
- });
1643
- }
1644
- }
1645
- currentMeta = currentMeta.tptParent;
1646
- }
1647
- return concreteMeta;
1648
- }
1649
- /**
1650
- * @internal
1651
- */
1652
- mapPropToFieldNames(qb, prop, tableAlias, meta, schema, explicitFields) {
1653
- if (prop.kind === ReferenceKind.EMBEDDED && !prop.object) {
1654
- return Object.entries(prop.embeddedProps).flatMap(([name, childProp]) => {
1655
- const childFields = explicitFields ? Utils.extractChildElements(explicitFields, prop.name) : [];
1656
- if (!this.shouldHaveColumn(prop.targetMeta, { ...childProp, name }, [], childFields.length > 0 ? childFields : undefined)) {
1657
- return [];
1658
- }
1659
- return this.mapPropToFieldNames(qb, childProp, tableAlias, meta, schema, childFields);
1660
- });
1661
- }
1662
- const aliased = this.platform.quoteIdentifier(`${tableAlias}__${prop.fieldNames[0]}`);
1663
- if (prop.customTypes?.some(type => !!type?.convertToJSValueSQL)) {
1664
- return prop.fieldNames.map((col, idx) => {
1665
- if (!prop.customTypes[idx]?.convertToJSValueSQL) {
1666
- return col;
1667
- }
1668
- const prefixed = this.platform.quoteIdentifier(`${tableAlias}.${col}`);
1669
- const aliased = this.platform.quoteIdentifier(`${tableAlias}__${col}`);
1670
- return raw(`${prop.customTypes[idx].convertToJSValueSQL(prefixed, this.platform)} as ${aliased}`);
1671
- });
1672
- }
1673
- if (prop.customType?.convertToJSValueSQL) {
1674
- const prefixed = this.platform.quoteIdentifier(`${tableAlias}.${prop.fieldNames[0]}`);
1675
- return [raw(`${prop.customType.convertToJSValueSQL(prefixed, this.platform)} as ${aliased}`)];
1676
- }
1677
- if (prop.formula) {
1678
- const quotedAlias = this.platform.quoteIdentifier(tableAlias).toString();
1679
- const table = this.createFormulaTable(quotedAlias, meta, schema);
1680
- const columns = meta.createColumnMappingObject(tableAlias);
1681
- return [raw(`${this.evaluateFormula(prop.formula, columns, table)} as ${aliased}`)];
1682
- }
1683
- const sourceAlias = qb.helper.getTPTAliasForProperty(prop.name, tableAlias);
1684
- return prop.fieldNames.map(fieldName => {
1685
- return raw('?? as ??', [`${sourceAlias}.${fieldName}`, `${tableAlias}__${fieldName}`]);
1686
- });
2030
+ const effectiveOrderBy = QueryHelper.mergeOrderBy(prop.orderBy, prop.targetMeta?.orderBy);
2031
+ for (const item of effectiveOrderBy) {
2032
+ for (const field of Utils.getObjectQueryKeys(item)) {
2033
+ const order = item[field];
2034
+ if (RawQueryFragment.isKnownFragmentSymbol(field)) {
2035
+ const { sql, params } = RawQueryFragment.getKnownFragment(field);
2036
+ const sql2 = propAlias ? sql.replace(new RegExp(ALIAS_REPLACEMENT_RE, 'g'), propAlias) : sql;
2037
+ const key = raw(sql2, params);
2038
+ orderBy.push({ [key]: order });
2039
+ continue;
2040
+ }
2041
+ orderBy.push({ [`${propAlias}.${field}`]: order });
2042
+ }
1687
2043
  }
1688
- /** @internal */
1689
- createQueryBuilder(entityName, ctx, preferredConnectionType, convertCustomTypes, loggerContext, alias, em) {
1690
- // do not compute the connectionType if EM is provided as it will be computed from it in the QB later on
1691
- const connectionType = em
1692
- ? preferredConnectionType
1693
- : this.resolveConnectionType({ ctx, connectionType: preferredConnectionType });
1694
- const qb = new QueryBuilder(entityName, this.metadata, this, ctx, alias, connectionType, em, loggerContext);
1695
- if (!convertCustomTypes) {
1696
- qb.unsetFlag(QueryFlag.CONVERT_CUSTOM_TYPES);
1697
- }
1698
- return qb;
2044
+ }
2045
+ normalizeFields(fields, prefix = '') {
2046
+ const ret = [];
2047
+ for (const field of fields) {
2048
+ if (typeof field === 'string') {
2049
+ ret.push(prefix + field);
2050
+ continue;
2051
+ }
2052
+ if (Utils.isPlainObject(field)) {
2053
+ for (const key of Object.keys(field)) {
2054
+ ret.push(...this.normalizeFields(field[key], key + '.'));
2055
+ }
2056
+ }
1699
2057
  }
1700
- resolveConnectionType(args) {
1701
- if (args.ctx) {
1702
- return 'write';
1703
- }
1704
- if (args.connectionType) {
1705
- return args.connectionType;
1706
- }
1707
- if (this.config.get('preferReadReplicas')) {
1708
- return 'read';
1709
- }
1710
- return 'write';
1711
- }
1712
- extractManyToMany(meta, data) {
1713
- const ret = {};
1714
- for (const prop of meta.relations) {
1715
- if (prop.kind === ReferenceKind.MANY_TO_MANY && data[prop.name]) {
1716
- ret[prop.name] = data[prop.name].map((item) => Utils.asArray(item));
1717
- delete data[prop.name];
1718
- }
1719
- }
1720
- return ret;
1721
- }
1722
- async processManyToMany(meta, pks, collections, clear, options) {
1723
- for (const prop of meta.relations) {
1724
- if (collections[prop.name]) {
1725
- const pivotMeta = this.metadata.get(prop.pivotEntity);
1726
- const persister = new PivotCollectionPersister(pivotMeta, this, options?.ctx, options?.schema, options?.loggerContext);
1727
- persister.enqueueUpdate(prop, collections[prop.name], clear, pks);
1728
- await this.rethrow(persister.execute());
1729
- }
1730
- }
2058
+ return ret;
2059
+ }
2060
+ processField(meta, prop, field, ret) {
2061
+ if (!prop || (prop.kind === ReferenceKind.ONE_TO_ONE && !prop.owner)) {
2062
+ return;
1731
2063
  }
1732
- async lockPessimistic(entity, options) {
1733
- const meta = helper(entity).__meta;
1734
- const qb = this.createQueryBuilder(meta.class, options.ctx, undefined, undefined, options.logging).withSchema(options.schema ?? meta.schema);
1735
- const cond = Utils.getPrimaryKeyCond(entity, meta.primaryKeys);
1736
- qb.select(raw('1'))
1737
- .where(cond)
1738
- .setLockMode(options.lockMode, options.lockTableAliases);
1739
- await this.rethrow(qb.execute());
1740
- }
1741
- buildPopulateWhere(meta, joinedProps, options) {
1742
- const where = {};
1743
- for (const hint of joinedProps) {
1744
- const [propName] = hint.field.split(':', 2);
1745
- const prop = meta.properties[propName];
1746
- if (!Utils.isEmpty(prop.where) || RawQueryFragment.hasObjectFragments(prop.where)) {
1747
- where[prop.name] = Utils.copy(prop.where);
1748
- }
1749
- if (hint.children) {
1750
- const targetMeta = prop.targetMeta;
1751
- if (targetMeta) {
1752
- const inner = this.buildPopulateWhere(targetMeta, hint.children, {});
1753
- if (!Utils.isEmpty(inner) || RawQueryFragment.hasObjectFragments(inner)) {
1754
- where[prop.name] ??= {};
1755
- Object.assign(where[prop.name], inner);
1756
- }
1757
- }
1758
- }
1759
- }
1760
- if (Utils.isEmpty(options.populateWhere) && !RawQueryFragment.hasObjectFragments(options.populateWhere)) {
1761
- return where;
1762
- }
1763
- if (Utils.isEmpty(where) && !RawQueryFragment.hasObjectFragments(where)) {
1764
- return options.populateWhere;
1765
- }
1766
- /* v8 ignore next */
1767
- return { $and: [options.populateWhere, where] };
1768
- }
1769
- /**
1770
- * Builds a UNION ALL (or UNION) subquery from `unionWhere` branches and merges it
1771
- * into the main WHERE as `pk IN (branch_1 UNION ALL branch_2 ...)`.
1772
- * Each branch is planned independently by the database, enabling per-table index usage.
1773
- */
1774
- async applyUnionWhere(meta, where, options, forDml = false) {
1775
- const unionWhere = options.unionWhere;
1776
- const strategy = options.unionWhereStrategy ?? 'union-all';
1777
- const schema = this.getSchemaName(meta, options);
1778
- const connectionType = this.resolveConnectionType({
1779
- ctx: options.ctx,
1780
- connectionType: options.connectionType,
1781
- });
1782
- const branchQbs = [];
1783
- for (const branch of unionWhere) {
1784
- const qb = this.createQueryBuilder(meta.class, options.ctx, connectionType, false, options.logging).withSchema(schema);
1785
- const pkFields = meta.primaryKeys.map(pk => {
1786
- const prop = meta.properties[pk];
1787
- return `${qb.alias}.${prop.fieldNames[0]}`;
1788
- });
1789
- qb.select(pkFields).where(branch);
1790
- if (options.em) {
1791
- await qb.applyJoinedFilters(options.em, options.filters);
1792
- }
1793
- branchQbs.push(qb);
1794
- }
1795
- const [first, ...rest] = branchQbs;
1796
- const unionQb = strategy === 'union' ? first.union(...rest) : first.unionAll(...rest);
1797
- const pkHash = Utils.getPrimaryKeyHash(meta.primaryKeys);
1798
- // MySQL does not allow referencing the target table in a subquery
1799
- // for UPDATE/DELETE, so we wrap the union in a derived table.
1800
- if (forDml) {
1801
- const { sql, params } = unionQb.toQuery();
1802
- return {
1803
- $and: [where, { [pkHash]: { $in: raw(`select * from (${sql}) as __u`, params) } }],
1804
- };
1805
- }
1806
- return {
1807
- $and: [where, { [pkHash]: { $in: unionQb.toRaw() } }],
1808
- };
1809
- }
1810
- buildOrderBy(qb, meta, populate, options) {
1811
- const joinedProps = this.joinedProps(meta, populate, options);
1812
- // `options._populateWhere` is a copy of the value provided by user with a fallback to the global config option
1813
- // as `options.populateWhere` will be always recomputed to respect filters
1814
- const populateWhereAll = options._populateWhere !== 'infer' && !Utils.isEmpty(options._populateWhere);
1815
- const path = (populateWhereAll ? '[populate]' : '') + meta.className;
1816
- const optionsOrderBy = Utils.asArray(options.orderBy);
1817
- const populateOrderBy = this.buildPopulateOrderBy(qb, meta, Utils.asArray(options.populateOrderBy ?? options.orderBy), path, !!options.populateOrderBy);
1818
- const joinedPropsOrderBy = this.buildJoinedPropsOrderBy(qb, meta, joinedProps, options, path);
1819
- return [...optionsOrderBy, ...populateOrderBy, ...joinedPropsOrderBy];
1820
- }
1821
- buildPopulateOrderBy(qb, meta, populateOrderBy, parentPath, explicit, parentAlias = qb.alias) {
1822
- const orderBy = [];
1823
- for (let i = 0; i < populateOrderBy.length; i++) {
1824
- const orderHint = populateOrderBy[i];
1825
- for (const field of Utils.getObjectQueryKeys(orderHint)) {
1826
- const childOrder = orderHint[field];
1827
- if (RawQueryFragment.isKnownFragmentSymbol(field)) {
1828
- const { sql, params } = RawQueryFragment.getKnownFragment(field);
1829
- const key = raw(sql.replace(new RegExp(ALIAS_REPLACEMENT_RE, 'g'), parentAlias), params);
1830
- orderBy.push({ [key]: childOrder });
1831
- continue;
1832
- }
1833
- const prop = meta.properties[field];
1834
- if (!prop) {
1835
- throw new Error(`Trying to order by not existing property ${meta.className}.${field}`);
1836
- }
1837
- let path = parentPath;
1838
- const meta2 = prop.targetMeta;
1839
- if (prop.kind !== ReferenceKind.SCALAR &&
1840
- (![ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(prop.kind) ||
1841
- !prop.owner ||
1842
- Utils.isPlainObject(childOrder))) {
1843
- path += `.${field}`;
1844
- }
1845
- if (prop.kind === ReferenceKind.MANY_TO_MANY && typeof childOrder !== 'object') {
1846
- path += '[pivot]';
1847
- }
1848
- const join = qb.getJoinForPath(path, { matchPopulateJoins: true });
1849
- const propAlias = qb.getAliasForJoinPath(join ?? path, { matchPopulateJoins: true }) ?? parentAlias;
1850
- if (!join) {
1851
- continue;
1852
- }
1853
- if (join &&
1854
- ![ReferenceKind.SCALAR, ReferenceKind.EMBEDDED].includes(prop.kind) &&
1855
- typeof childOrder === 'object') {
1856
- const children = this.buildPopulateOrderBy(qb, meta2, Utils.asArray(childOrder), path, explicit, propAlias);
1857
- orderBy.push(...children);
1858
- continue;
1859
- }
1860
- if (prop.kind === ReferenceKind.MANY_TO_MANY && join) {
1861
- if (prop.fixedOrderColumn) {
1862
- orderBy.push({ [`${join.alias}.${prop.fixedOrderColumn}`]: childOrder });
1863
- }
1864
- else {
1865
- for (const col of prop.inverseJoinColumns) {
1866
- orderBy.push({ [`${join.ownerAlias}.${col}`]: childOrder });
1867
- }
1868
- }
1869
- continue;
1870
- }
1871
- const order = typeof childOrder === 'object' ? childOrder[field] : childOrder;
1872
- if (order) {
1873
- orderBy.push({ [`${propAlias}.${field}`]: order });
1874
- }
1875
- }
1876
- }
1877
- return orderBy;
1878
- }
1879
- buildJoinedPropsOrderBy(qb, meta, populate, options, parentPath) {
1880
- const orderBy = [];
1881
- const joinedProps = this.joinedProps(meta, populate, options);
1882
- for (const hint of joinedProps) {
1883
- const [propName, ref] = hint.field.split(':', 2);
1884
- const prop = meta.properties[propName];
1885
- let path = `${parentPath}.${propName}`;
1886
- if (prop.kind === ReferenceKind.MANY_TO_MANY && ref) {
1887
- path += '[pivot]';
1888
- }
1889
- if ([ReferenceKind.MANY_TO_MANY, ReferenceKind.ONE_TO_MANY].includes(prop.kind)) {
1890
- this.buildToManyOrderBy(qb, prop, path, ref, orderBy);
1891
- }
1892
- if (hint.children) {
1893
- orderBy.push(...this.buildJoinedPropsOrderBy(qb, prop.targetMeta, hint.children, options, path));
1894
- }
1895
- }
1896
- return orderBy;
2064
+ if (prop.kind === ReferenceKind.EMBEDDED) {
2065
+ if (prop.object) {
2066
+ ret.push(prop.name);
2067
+ return;
2068
+ }
2069
+ const parts = field.split('.');
2070
+ const top = parts.shift();
2071
+ for (const key of Object.keys(prop.embeddedProps)) {
2072
+ if (!top || key === top) {
2073
+ this.processField(meta, prop.embeddedProps[key], parts.join('.'), ret);
2074
+ }
2075
+ }
2076
+ return;
1897
2077
  }
1898
- buildToManyOrderBy(qb, prop, path, ref, orderBy) {
1899
- const join = qb.getJoinForPath(path, { matchPopulateJoins: true });
1900
- const propAlias = qb.getAliasForJoinPath(join ?? path, { matchPopulateJoins: true });
1901
- if (prop.kind === ReferenceKind.MANY_TO_MANY && prop.fixedOrder && join) {
1902
- const alias = ref ? propAlias : join.ownerAlias;
1903
- orderBy.push({ [`${alias}.${prop.fixedOrderColumn}`]: QueryOrder.ASC });
1904
- }
1905
- const effectiveOrderBy = QueryHelper.mergeOrderBy(prop.orderBy, prop.targetMeta?.orderBy);
1906
- for (const item of effectiveOrderBy) {
1907
- for (const field of Utils.getObjectQueryKeys(item)) {
1908
- const order = item[field];
1909
- if (RawQueryFragment.isKnownFragmentSymbol(field)) {
1910
- const { sql, params } = RawQueryFragment.getKnownFragment(field);
1911
- const sql2 = propAlias ? sql.replace(new RegExp(ALIAS_REPLACEMENT_RE, 'g'), propAlias) : sql;
1912
- const key = raw(sql2, params);
1913
- orderBy.push({ [key]: order });
1914
- continue;
1915
- }
1916
- orderBy.push({ [`${propAlias}.${field}`]: order });
1917
- }
1918
- }
2078
+ if (prop.persist === false && !prop.embedded && !prop.formula) {
2079
+ return;
1919
2080
  }
1920
- normalizeFields(fields, prefix = '') {
1921
- const ret = [];
1922
- for (const field of fields) {
1923
- if (typeof field === 'string') {
1924
- ret.push(prefix + field);
1925
- continue;
1926
- }
1927
- if (Utils.isPlainObject(field)) {
1928
- for (const key of Object.keys(field)) {
1929
- ret.push(...this.normalizeFields(field[key], key + '.'));
1930
- }
1931
- }
1932
- }
1933
- return ret;
2081
+ ret.push(prop.name);
2082
+ }
2083
+ buildFields(meta, populate, joinedProps, qb, alias, options, schema) {
2084
+ const lazyProps = meta.props.filter(prop => prop.lazy && !populate.some(p => this.isPopulated(meta, prop, p)));
2085
+ const hasLazyFormulas = meta.props.some(p => p.lazy && p.formula);
2086
+ const requiresSQLConversion = meta.props.some(p => p.customType?.convertToJSValueSQL && p.persist !== false);
2087
+ const hasExplicitFields = !!options.fields;
2088
+ const ret = [];
2089
+ let addFormulas = false;
2090
+ // handle root entity properties first, this is used for both strategies in the same way
2091
+ if (options.fields) {
2092
+ for (const field of this.normalizeFields(options.fields)) {
2093
+ if (field === '*') {
2094
+ ret.push('*');
2095
+ continue;
2096
+ }
2097
+ const parts = field.split('.');
2098
+ const rootPropName = parts.shift(); // first one is the `prop`
2099
+ const prop = QueryHelper.findProperty(rootPropName, {
2100
+ metadata: this.metadata,
2101
+ platform: this.platform,
2102
+ entityName: meta.class,
2103
+ where: {},
2104
+ aliasMap: qb.getAliasMap(),
2105
+ });
2106
+ this.processField(meta, prop, parts.join('.'), ret);
2107
+ }
2108
+ if (!options.fields.includes('*') && !options.fields.includes(`${qb.alias}.*`)) {
2109
+ ret.unshift(...meta.primaryKeys.filter(pk => !options.fields.includes(pk)));
2110
+ }
2111
+ if (
2112
+ meta.root.inheritanceType === 'sti' &&
2113
+ !options.fields.includes(`${qb.alias}.${meta.root.discriminatorColumn}`)
2114
+ ) {
2115
+ ret.push(meta.root.discriminatorColumn);
2116
+ }
2117
+ } else if (!Utils.isEmpty(options.exclude) || lazyProps.some(p => !p.formula && (p.kind !== '1:1' || p.owner))) {
2118
+ const props = meta.props.filter(prop =>
2119
+ this.platform.shouldHaveColumn(prop, populate, options.exclude, false, false),
2120
+ );
2121
+ ret.push(...props.filter(p => !lazyProps.includes(p)).map(p => p.name));
2122
+ addFormulas = true;
2123
+ } else if (hasLazyFormulas || requiresSQLConversion) {
2124
+ ret.push('*');
2125
+ addFormulas = true;
2126
+ } else {
2127
+ ret.push('*');
1934
2128
  }
1935
- processField(meta, prop, field, ret) {
1936
- if (!prop || (prop.kind === ReferenceKind.ONE_TO_ONE && !prop.owner)) {
1937
- return;
2129
+ if (ret.length > 0 && !hasExplicitFields && addFormulas) {
2130
+ // Create formula column mapping with unquoted aliases - quoting should be handled by the user via `quote` helper
2131
+ const quotedAlias = this.platform.quoteIdentifier(alias);
2132
+ const columns = meta.createColumnMappingObject(alias);
2133
+ const effectiveSchema = schema ?? (meta.schema !== '*' ? meta.schema : undefined);
2134
+ for (const prop of meta.props) {
2135
+ if (lazyProps.includes(prop)) {
2136
+ continue;
1938
2137
  }
1939
- if (prop.kind === ReferenceKind.EMBEDDED) {
1940
- if (prop.object) {
1941
- ret.push(prop.name);
1942
- return;
1943
- }
1944
- const parts = field.split('.');
1945
- const top = parts.shift();
1946
- for (const key of Object.keys(prop.embeddedProps)) {
1947
- if (!top || key === top) {
1948
- this.processField(meta, prop.embeddedProps[key], parts.join('.'), ret);
1949
- }
1950
- }
1951
- return;
2138
+ if (prop.formula) {
2139
+ const aliased = this.platform.quoteIdentifier(prop.fieldNames[0]);
2140
+ const table = this.createFormulaTable(quotedAlias.toString(), meta, effectiveSchema);
2141
+ ret.push(raw(`${this.evaluateFormula(prop.formula, columns, table)} as ${aliased}`));
1952
2142
  }
1953
- if (prop.persist === false && !prop.embedded && !prop.formula) {
1954
- return;
2143
+ if (!prop.object && (prop.hasConvertToDatabaseValueSQL || prop.hasConvertToJSValueSQL)) {
2144
+ ret.push(prop.name);
1955
2145
  }
1956
- ret.push(prop.name);
2146
+ }
1957
2147
  }
1958
- buildFields(meta, populate, joinedProps, qb, alias, options, schema) {
1959
- const lazyProps = meta.props.filter(prop => prop.lazy && !populate.some(p => this.isPopulated(meta, prop, p)));
1960
- const hasLazyFormulas = meta.props.some(p => p.lazy && p.formula);
1961
- const requiresSQLConversion = meta.props.some(p => p.customType?.convertToJSValueSQL && p.persist !== false);
1962
- const hasExplicitFields = !!options.fields;
1963
- const ret = [];
1964
- let addFormulas = false;
1965
- // handle root entity properties first, this is used for both strategies in the same way
1966
- if (options.fields) {
1967
- for (const field of this.normalizeFields(options.fields)) {
1968
- if (field === '*') {
1969
- ret.push('*');
1970
- continue;
1971
- }
1972
- const parts = field.split('.');
1973
- const rootPropName = parts.shift(); // first one is the `prop`
1974
- const prop = QueryHelper.findProperty(rootPropName, {
1975
- metadata: this.metadata,
1976
- platform: this.platform,
1977
- entityName: meta.class,
1978
- where: {},
1979
- aliasMap: qb.getAliasMap(),
1980
- });
1981
- this.processField(meta, prop, parts.join('.'), ret);
1982
- }
1983
- if (!options.fields.includes('*') && !options.fields.includes(`${qb.alias}.*`)) {
1984
- ret.unshift(...meta.primaryKeys.filter(pk => !options.fields.includes(pk)));
1985
- }
1986
- if (meta.root.inheritanceType === 'sti' &&
1987
- !options.fields.includes(`${qb.alias}.${meta.root.discriminatorColumn}`)) {
1988
- ret.push(meta.root.discriminatorColumn);
1989
- }
1990
- }
1991
- else if (!Utils.isEmpty(options.exclude) || lazyProps.some(p => !p.formula && (p.kind !== '1:1' || p.owner))) {
1992
- const props = meta.props.filter(prop => this.platform.shouldHaveColumn(prop, populate, options.exclude, false, false));
1993
- ret.push(...props.filter(p => !lazyProps.includes(p)).map(p => p.name));
1994
- addFormulas = true;
1995
- }
1996
- else if (hasLazyFormulas || requiresSQLConversion) {
1997
- ret.push('*');
1998
- addFormulas = true;
1999
- }
2000
- else {
2001
- ret.push('*');
2002
- }
2003
- if (ret.length > 0 && !hasExplicitFields && addFormulas) {
2004
- // Create formula column mapping with unquoted aliases - quoting should be handled by the user via `quote` helper
2005
- const quotedAlias = this.platform.quoteIdentifier(alias);
2006
- const columns = meta.createColumnMappingObject(alias);
2007
- const effectiveSchema = schema ?? (meta.schema !== '*' ? meta.schema : undefined);
2008
- for (const prop of meta.props) {
2009
- if (lazyProps.includes(prop)) {
2010
- continue;
2011
- }
2012
- if (prop.formula) {
2013
- const aliased = this.platform.quoteIdentifier(prop.fieldNames[0]);
2014
- const table = this.createFormulaTable(quotedAlias.toString(), meta, effectiveSchema);
2015
- ret.push(raw(`${this.evaluateFormula(prop.formula, columns, table)} as ${aliased}`));
2016
- }
2017
- if (!prop.object && (prop.hasConvertToDatabaseValueSQL || prop.hasConvertToJSValueSQL)) {
2018
- ret.push(prop.name);
2019
- }
2020
- }
2021
- }
2022
- // add joined relations after the root entity fields
2023
- if (joinedProps.length > 0) {
2024
- ret.push(...this.getFieldsForJoinedLoad(qb, meta, {
2025
- explicitFields: options.fields,
2026
- exclude: options.exclude,
2027
- populate,
2028
- parentTableAlias: alias,
2029
- ...options,
2030
- }));
2031
- }
2032
- return Utils.unique(ret);
2148
+ // add joined relations after the root entity fields
2149
+ if (joinedProps.length > 0) {
2150
+ ret.push(
2151
+ ...this.getFieldsForJoinedLoad(qb, meta, {
2152
+ explicitFields: options.fields,
2153
+ exclude: options.exclude,
2154
+ populate,
2155
+ parentTableAlias: alias,
2156
+ ...options,
2157
+ }),
2158
+ );
2033
2159
  }
2160
+ return Utils.unique(ret);
2161
+ }
2034
2162
  }