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

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