@mikro-orm/sql 7.0.2 → 7.0.3-dev.0

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