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