@mikro-orm/sql 7.0.13 → 7.0.14-dev.0

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