@mikro-orm/sql 7.0.9 → 7.0.10-dev.1

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