@mikro-orm/core 7.0.15-dev.8 → 7.0.15

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 (206) hide show
  1. package/EntityManager.d.ts +885 -584
  2. package/EntityManager.js +1939 -1911
  3. package/MikroORM.d.ts +103 -74
  4. package/MikroORM.js +177 -178
  5. package/README.md +1 -1
  6. package/cache/CacheAdapter.d.ts +36 -36
  7. package/cache/FileCacheAdapter.d.ts +30 -24
  8. package/cache/FileCacheAdapter.js +80 -78
  9. package/cache/GeneratedCacheAdapter.d.ts +18 -20
  10. package/cache/GeneratedCacheAdapter.js +30 -30
  11. package/cache/MemoryCacheAdapter.d.ts +18 -20
  12. package/cache/MemoryCacheAdapter.js +35 -36
  13. package/cache/NullCacheAdapter.d.ts +16 -16
  14. package/cache/NullCacheAdapter.js +24 -24
  15. package/connections/Connection.d.ts +95 -84
  16. package/connections/Connection.js +165 -168
  17. package/drivers/DatabaseDriver.d.ts +186 -80
  18. package/drivers/DatabaseDriver.js +450 -443
  19. package/drivers/IDatabaseDriver.d.ts +444 -305
  20. package/entity/BaseEntity.d.ts +120 -83
  21. package/entity/BaseEntity.js +43 -43
  22. package/entity/Collection.d.ts +215 -181
  23. package/entity/Collection.js +730 -724
  24. package/entity/EntityAssigner.d.ts +88 -77
  25. package/entity/EntityAssigner.js +231 -230
  26. package/entity/EntityFactory.d.ts +67 -55
  27. package/entity/EntityFactory.js +454 -413
  28. package/entity/EntityHelper.d.ts +35 -23
  29. package/entity/EntityHelper.js +302 -290
  30. package/entity/EntityIdentifier.d.ts +4 -4
  31. package/entity/EntityIdentifier.js +10 -10
  32. package/entity/EntityLoader.d.ts +98 -72
  33. package/entity/EntityLoader.js +815 -786
  34. package/entity/EntityRepository.d.ts +316 -201
  35. package/entity/EntityRepository.js +213 -213
  36. package/entity/PolymorphicRef.d.ts +5 -5
  37. package/entity/PolymorphicRef.js +10 -10
  38. package/entity/Reference.d.ts +127 -83
  39. package/entity/Reference.js +281 -277
  40. package/entity/WrappedEntity.d.ts +115 -72
  41. package/entity/WrappedEntity.js +168 -166
  42. package/entity/defineEntity.d.ts +1412 -659
  43. package/entity/defineEntity.js +527 -518
  44. package/entity/utils.d.ts +13 -3
  45. package/entity/utils.js +71 -73
  46. package/entity/validators.js +43 -43
  47. package/entity/wrap.js +8 -8
  48. package/enums.d.ts +258 -253
  49. package/enums.js +251 -252
  50. package/errors.d.ts +114 -72
  51. package/errors.js +350 -253
  52. package/events/EventManager.d.ts +26 -14
  53. package/events/EventManager.js +79 -77
  54. package/events/EventSubscriber.d.ts +29 -29
  55. package/events/TransactionEventBroadcaster.d.ts +15 -8
  56. package/events/TransactionEventBroadcaster.js +14 -14
  57. package/exceptions.d.ts +23 -40
  58. package/exceptions.js +35 -52
  59. package/hydration/Hydrator.d.ts +42 -17
  60. package/hydration/Hydrator.js +43 -43
  61. package/hydration/ObjectHydrator.d.ts +50 -17
  62. package/hydration/ObjectHydrator.js +483 -418
  63. package/index.d.ts +118 -2
  64. package/index.js +10 -1
  65. package/logging/DefaultLogger.d.ts +34 -32
  66. package/logging/DefaultLogger.js +86 -86
  67. package/logging/Logger.d.ts +41 -41
  68. package/logging/SimpleLogger.d.ts +13 -11
  69. package/logging/SimpleLogger.js +22 -22
  70. package/logging/colors.d.ts +6 -6
  71. package/logging/colors.js +11 -10
  72. package/logging/inspect.js +7 -7
  73. package/metadata/EntitySchema.d.ts +214 -130
  74. package/metadata/EntitySchema.js +411 -412
  75. package/metadata/MetadataDiscovery.d.ts +115 -115
  76. package/metadata/MetadataDiscovery.js +2013 -1931
  77. package/metadata/MetadataProvider.d.ts +29 -26
  78. package/metadata/MetadataProvider.js +95 -97
  79. package/metadata/MetadataStorage.d.ts +38 -32
  80. package/metadata/MetadataStorage.js +118 -118
  81. package/metadata/MetadataValidator.d.ts +39 -39
  82. package/metadata/MetadataValidator.js +385 -340
  83. package/metadata/discover-entities.d.ts +5 -2
  84. package/metadata/discover-entities.js +35 -37
  85. package/metadata/types.d.ts +615 -531
  86. package/naming-strategy/AbstractNamingStrategy.d.ts +54 -39
  87. package/naming-strategy/AbstractNamingStrategy.js +90 -85
  88. package/naming-strategy/EntityCaseNamingStrategy.d.ts +6 -6
  89. package/naming-strategy/EntityCaseNamingStrategy.js +22 -22
  90. package/naming-strategy/MongoNamingStrategy.d.ts +6 -6
  91. package/naming-strategy/MongoNamingStrategy.js +18 -18
  92. package/naming-strategy/NamingStrategy.d.ts +109 -99
  93. package/naming-strategy/UnderscoreNamingStrategy.d.ts +7 -7
  94. package/naming-strategy/UnderscoreNamingStrategy.js +21 -21
  95. package/not-supported.js +7 -4
  96. package/package.json +1 -1
  97. package/platforms/ExceptionConverter.d.ts +1 -1
  98. package/platforms/ExceptionConverter.js +4 -4
  99. package/platforms/Platform.d.ts +312 -303
  100. package/platforms/Platform.js +715 -695
  101. package/serialization/EntitySerializer.d.ts +49 -26
  102. package/serialization/EntitySerializer.js +224 -218
  103. package/serialization/EntityTransformer.d.ts +10 -6
  104. package/serialization/EntityTransformer.js +219 -217
  105. package/serialization/SerializationContext.d.ts +27 -23
  106. package/serialization/SerializationContext.js +105 -105
  107. package/types/ArrayType.d.ts +8 -8
  108. package/types/ArrayType.js +33 -33
  109. package/types/BigIntType.d.ts +17 -10
  110. package/types/BigIntType.js +37 -37
  111. package/types/BlobType.d.ts +3 -3
  112. package/types/BlobType.js +13 -13
  113. package/types/BooleanType.d.ts +4 -4
  114. package/types/BooleanType.js +12 -12
  115. package/types/CharacterType.d.ts +2 -2
  116. package/types/CharacterType.js +6 -6
  117. package/types/DateTimeType.d.ts +5 -5
  118. package/types/DateTimeType.js +15 -15
  119. package/types/DateType.d.ts +5 -5
  120. package/types/DateType.js +15 -15
  121. package/types/DecimalType.d.ts +7 -7
  122. package/types/DecimalType.js +26 -26
  123. package/types/DoubleType.d.ts +3 -3
  124. package/types/DoubleType.js +12 -12
  125. package/types/EnumArrayType.d.ts +5 -5
  126. package/types/EnumArrayType.js +24 -24
  127. package/types/EnumType.d.ts +3 -3
  128. package/types/EnumType.js +11 -11
  129. package/types/FloatType.d.ts +3 -3
  130. package/types/FloatType.js +9 -9
  131. package/types/IntegerType.d.ts +3 -3
  132. package/types/IntegerType.js +9 -9
  133. package/types/IntervalType.d.ts +4 -4
  134. package/types/IntervalType.js +12 -12
  135. package/types/JsonType.d.ts +8 -8
  136. package/types/JsonType.js +32 -32
  137. package/types/MediumIntType.d.ts +1 -1
  138. package/types/MediumIntType.js +3 -3
  139. package/types/SmallIntType.d.ts +3 -3
  140. package/types/SmallIntType.js +9 -9
  141. package/types/StringType.d.ts +4 -4
  142. package/types/StringType.js +12 -12
  143. package/types/TextType.d.ts +3 -3
  144. package/types/TextType.js +9 -9
  145. package/types/TimeType.d.ts +5 -5
  146. package/types/TimeType.js +17 -17
  147. package/types/TinyIntType.d.ts +3 -3
  148. package/types/TinyIntType.js +10 -10
  149. package/types/Type.d.ts +83 -79
  150. package/types/Type.js +82 -82
  151. package/types/Uint8ArrayType.d.ts +4 -4
  152. package/types/Uint8ArrayType.js +21 -21
  153. package/types/UnknownType.d.ts +4 -4
  154. package/types/UnknownType.js +12 -12
  155. package/types/UuidType.d.ts +5 -5
  156. package/types/UuidType.js +19 -19
  157. package/types/index.d.ts +75 -49
  158. package/types/index.js +52 -26
  159. package/typings.d.ts +1268 -746
  160. package/typings.js +246 -233
  161. package/unit-of-work/ChangeSet.d.ts +26 -26
  162. package/unit-of-work/ChangeSet.js +56 -56
  163. package/unit-of-work/ChangeSetComputer.d.ts +12 -12
  164. package/unit-of-work/ChangeSetComputer.js +187 -179
  165. package/unit-of-work/ChangeSetPersister.d.ts +69 -50
  166. package/unit-of-work/ChangeSetPersister.js +469 -446
  167. package/unit-of-work/CommitOrderCalculator.d.ts +40 -40
  168. package/unit-of-work/CommitOrderCalculator.js +89 -88
  169. package/unit-of-work/IdentityMap.d.ts +31 -31
  170. package/unit-of-work/IdentityMap.js +105 -105
  171. package/unit-of-work/UnitOfWork.d.ts +181 -141
  172. package/unit-of-work/UnitOfWork.js +1240 -1226
  173. package/utils/AbstractMigrator.d.ts +112 -92
  174. package/utils/AbstractMigrator.js +286 -288
  175. package/utils/AbstractSchemaGenerator.d.ts +43 -34
  176. package/utils/AbstractSchemaGenerator.js +121 -122
  177. package/utils/AsyncContext.d.ts +3 -3
  178. package/utils/AsyncContext.js +34 -35
  179. package/utils/Configuration.d.ts +852 -808
  180. package/utils/Configuration.js +359 -344
  181. package/utils/Cursor.d.ts +40 -22
  182. package/utils/Cursor.js +135 -127
  183. package/utils/DataloaderUtils.d.ts +58 -43
  184. package/utils/DataloaderUtils.js +203 -198
  185. package/utils/EntityComparator.d.ts +99 -82
  186. package/utils/EntityComparator.js +836 -744
  187. package/utils/NullHighlighter.d.ts +1 -1
  188. package/utils/NullHighlighter.js +3 -3
  189. package/utils/QueryHelper.d.ts +85 -57
  190. package/utils/QueryHelper.js +404 -392
  191. package/utils/RawQueryFragment.d.ts +50 -34
  192. package/utils/RawQueryFragment.js +122 -121
  193. package/utils/RequestContext.d.ts +32 -32
  194. package/utils/RequestContext.js +52 -53
  195. package/utils/TransactionContext.d.ts +16 -16
  196. package/utils/TransactionContext.js +27 -27
  197. package/utils/TransactionManager.d.ts +58 -58
  198. package/utils/TransactionManager.js +202 -200
  199. package/utils/Utils.d.ts +204 -145
  200. package/utils/Utils.js +826 -826
  201. package/utils/clone.js +105 -114
  202. package/utils/env-vars.js +90 -88
  203. package/utils/fs-utils.d.ts +15 -15
  204. package/utils/fs-utils.js +181 -182
  205. package/utils/upsert-utils.d.ts +20 -5
  206. package/utils/upsert-utils.js +114 -116
package/EntityManager.js CHANGED
@@ -12,7 +12,17 @@ import { Reference } from './entity/Reference.js';
12
12
  import { helper } from './entity/wrap.js';
13
13
  import { ChangeSet, ChangeSetType } from './unit-of-work/ChangeSet.js';
14
14
  import { UnitOfWork } from './unit-of-work/UnitOfWork.js';
15
- import { EventType, FlushMode, LoadStrategy, LockMode, PopulateHint, PopulatePath, QueryFlag, ReferenceKind, SCALAR_TYPES, } from './enums.js';
15
+ import {
16
+ EventType,
17
+ FlushMode,
18
+ LoadStrategy,
19
+ LockMode,
20
+ PopulateHint,
21
+ PopulatePath,
22
+ QueryFlag,
23
+ ReferenceKind,
24
+ SCALAR_TYPES,
25
+ } from './enums.js';
16
26
  import { EventManager } from './events/EventManager.js';
17
27
  import { TransactionEventBroadcaster } from './events/TransactionEventBroadcaster.js';
18
28
  import { OptimisticLockError, ValidationError } from './errors.js';
@@ -24,1927 +34,1945 @@ import { TransactionManager } from './utils/TransactionManager.js';
24
34
  * @template {IDatabaseDriver} Driver current driver type
25
35
  */
26
36
  export class EntityManager {
27
- config;
28
- driver;
29
- metadata;
30
- eventManager;
31
- static #counter = 1;
32
- /** @internal */
33
- _id = EntityManager.#counter++;
34
- /** Whether this is the global (root) EntityManager instance. */
35
- global = false;
36
- /** The context name of this EntityManager, derived from the ORM configuration. */
37
- name;
38
- #loaders = {};
39
- #repositoryMap = new Map();
40
- #entityLoader;
41
- #comparator;
42
- #entityFactory;
43
- #unitOfWork;
44
- #resultCache;
45
- #filters = {};
46
- #filterParams = {};
47
- loggerContext;
48
- #transactionContext;
49
- #disableTransactions;
50
- #flushMode;
51
- #schema;
52
- #useContext;
53
- /**
54
- * @internal
55
- */
56
- constructor(config, driver, metadata, useContext = true, eventManager = new EventManager(config.get('subscribers'))) {
57
- this.config = config;
58
- this.driver = driver;
59
- this.metadata = metadata;
60
- this.eventManager = eventManager;
61
- this.#useContext = useContext;
62
- this.#entityLoader = new EntityLoader(this);
63
- this.name = this.config.get('contextName');
64
- this.#comparator = this.config.getComparator(this.metadata);
65
- this.#resultCache = this.config.getResultCacheAdapter();
66
- this.#disableTransactions = this.config.get('disableTransactions');
67
- this.#entityFactory = new EntityFactory(this);
68
- this.#unitOfWork = new UnitOfWork(this);
69
- }
70
- /**
71
- * Gets the Driver instance used by this EntityManager.
72
- * Driver is singleton, for one MikroORM instance, only one driver is created.
73
- */
74
- getDriver() {
75
- return this.driver;
76
- }
77
- /**
78
- * Gets the Connection instance, by default returns write connection
79
- */
80
- getConnection(type) {
81
- return this.driver.getConnection(type);
82
- }
83
- /**
84
- * Gets the platform instance. Just like the driver, platform is singleton, one for a MikroORM instance.
85
- */
86
- getPlatform() {
87
- return this.driver.getPlatform();
88
- }
89
- /**
90
- * Gets repository for given entity. You can pass either string name or entity class reference.
91
- */
92
- getRepository(entityName) {
93
- const meta = this.metadata.get(entityName);
94
- if (!this.#repositoryMap.has(meta)) {
95
- const RepositoryClass = this.config.getRepositoryClass(meta.repository);
96
- this.#repositoryMap.set(meta, new RepositoryClass(this, entityName));
97
- }
98
- return this.#repositoryMap.get(meta);
99
- }
100
- /**
101
- * Shortcut for `em.getRepository()`.
102
- */
103
- repo(entityName) {
104
- return this.getRepository(entityName);
105
- }
106
- /**
107
- * Finds all entities matching your `where` query. You can pass additional options via the `options` parameter.
108
- */
109
- async find(entityName, where, options = {}) {
110
- if (options.disableIdentityMap ?? this.config.get('disableIdentityMap')) {
111
- const em = this.getContext(false);
112
- const fork = em.fork({ keepTransactionContext: true });
113
- const ret = await fork.find(entityName, where, { ...options, disableIdentityMap: false });
114
- fork.clear();
115
- return ret;
116
- }
117
- const em = this.getContext();
118
- em.prepareOptions(options);
119
- await em.tryFlush(entityName, options);
120
- where = await em.processWhere(entityName, where, options, 'read');
121
- validateParams(where);
122
- const meta = this.metadata.get(entityName);
123
- if (meta.orderBy) {
124
- options.orderBy = QueryHelper.mergeOrderBy(options.orderBy, meta.orderBy);
125
- }
126
- else {
127
- options.orderBy ??= {};
128
- }
129
- options.populate = (await em.preparePopulate(entityName, options));
130
- const populate = options.populate;
131
- const cacheKey = em.cacheKey(entityName, options, 'em.find', where);
132
- const cached = await em.tryCache(entityName, options.cache, cacheKey, options.refresh, true);
133
- if (cached?.data) {
134
- await em.#entityLoader.populate(entityName, cached.data, populate, {
135
- ...options,
136
- ...em.getPopulateWhere(where, options),
137
- ignoreLazyScalarProperties: true,
138
- lookup: false,
139
- });
140
- return cached.data;
141
- }
142
- options = { ...options };
143
- // save the original hint value so we know it was infer/all
144
- options._populateWhere = options.populateWhere ?? this.config.get('populateWhere');
145
- options.populateWhere = this.createPopulateWhere({ ...where }, options);
146
- options.populateFilter = await this.getJoinedFilters(meta, options);
147
- await em.processUnionWhere(entityName, options, 'read');
148
- const results = await em.driver.find(entityName, where, { ctx: em.#transactionContext, em, ...options });
149
- if (results.length === 0) {
150
- await em.storeCache(options.cache, cached, []);
151
- return [];
152
- }
153
- const ret = [];
154
- for (const data of results) {
155
- const entity = em.#entityFactory.create(entityName, data, {
156
- merge: true,
157
- refresh: options.refresh,
158
- schema: options.schema,
159
- convertCustomTypes: true,
160
- });
161
- ret.push(entity);
162
- }
163
- const unique = Utils.unique(ret);
164
- await em.#entityLoader.populate(entityName, unique, populate, {
165
- ...options,
166
- ...em.getPopulateWhere(where, options),
167
- ignoreLazyScalarProperties: true,
168
- lookup: false,
169
- });
170
- await em.#unitOfWork.dispatchOnLoadEvent();
171
- if (meta.virtual) {
172
- await em.storeCache(options.cache, cached, () => ret);
173
- }
174
- else {
175
- await em.storeCache(options.cache, cached, () => unique.map(e => helper(e).toPOJO()));
176
- }
177
- return unique;
178
- }
179
- /**
180
- * Finds all entities and returns an async iterable (async generator) that yields results one by one.
181
- * The results are merged and mapped to entity instances, without adding them to the identity map.
182
- * You can disable merging by passing the options `{ mergeResults: false }`.
183
- * With `mergeResults` disabled, to-many collections will contain at most one item, and you will get duplicate
184
- * root entities when there are multiple items in the populated collection.
185
- * This is useful for processing large datasets without loading everything into memory at once.
186
- *
187
- * ```ts
188
- * const stream = em.stream(Book, { populate: ['author'] });
189
- *
190
- * for await (const book of stream) {
191
- * // book is an instance of Book entity
192
- * console.log(book.title, book.author.name);
193
- * }
194
- * ```
195
- */
196
- async *stream(entityName, options = {}) {
197
- const em = this.getContext();
198
- em.prepareOptions(options);
199
- options.strategy = 'joined';
200
- await em.tryFlush(entityName, options);
201
- const where = (await em.processWhere(entityName, options.where ?? {}, options, 'read'));
202
- validateParams(where);
203
- options.orderBy = options.orderBy || {};
204
- options.populate = (await em.preparePopulate(entityName, options));
205
- const meta = this.metadata.get(entityName);
206
- options = { ...options };
207
- // save the original hint value so we know it was infer/all
208
- options._populateWhere = options.populateWhere ?? this.config.get('populateWhere');
209
- options.populateWhere = this.createPopulateWhere({ ...where }, options);
210
- options.populateFilter = await this.getJoinedFilters(meta, options);
211
- const stream = em.driver.stream(entityName, where, {
212
- ctx: em.#transactionContext,
213
- mapResults: false,
214
- ...options,
215
- });
216
- for await (const data of stream) {
217
- const fork = em.fork();
218
- const entity = fork.#entityFactory.create(entityName, data, {
219
- refresh: options.refresh,
220
- schema: options.schema,
221
- convertCustomTypes: true,
222
- });
223
- helper(entity).setSerializationContext({
224
- populate: options.populate,
225
- fields: options.fields,
226
- exclude: options.exclude,
227
- });
228
- await fork.#unitOfWork.dispatchOnLoadEvent();
229
- fork.clear();
230
- yield entity;
231
- }
232
- }
233
- /**
234
- * Finds all entities of given type, optionally matching the `where` condition provided in the `options` parameter.
235
- */
236
- async findAll(entityName, options) {
237
- return this.find(entityName, options?.where ?? {}, options);
238
- }
239
- getPopulateWhere(where, options) {
240
- if (options.populateWhere === undefined) {
241
- options.populateWhere = this.config.get('populateWhere');
242
- }
243
- if (options.populateWhere === PopulateHint.ALL) {
244
- return { where: {}, populateWhere: options.populateWhere };
245
- }
246
- /* v8 ignore next */
247
- if (options.populateWhere === PopulateHint.INFER) {
248
- return { where, populateWhere: options.populateWhere };
249
- }
250
- return { where: options.populateWhere };
251
- }
252
- /**
253
- * Registers global filter to this entity manager. Global filters are enabled by default (unless disabled via last parameter).
254
- */
255
- addFilter(options) {
256
- if (options.entity) {
257
- options.entity = Utils.asArray(options.entity).map(n => Utils.className(n));
258
- }
259
- options.default ??= true;
260
- this.getContext(false).#filters[options.name] = options;
261
- }
262
- /**
263
- * Sets filter parameter values globally inside context defined by this entity manager.
264
- * If you want to set shared value for all contexts, be sure to use the root entity manager.
265
- */
266
- setFilterParams(name, args) {
267
- this.getContext().#filterParams[name] = args;
268
- }
269
- /**
270
- * Returns filter parameters for given filter set in this context.
271
- */
272
- getFilterParams(name) {
273
- return this.getContext().#filterParams[name];
274
- }
275
- /**
276
- * Sets logger context for this entity manager.
277
- */
278
- setLoggerContext(context) {
279
- this.getContext().loggerContext = context;
280
- }
281
- /**
282
- * Gets logger context for this entity manager.
283
- */
284
- getLoggerContext(options) {
285
- const em = options?.disableContextResolution ? this : this.getContext();
286
- em.loggerContext ??= {};
287
- return em.loggerContext;
288
- }
289
- /** Sets the flush mode for this EntityManager. Pass `undefined` to reset to the global default. */
290
- setFlushMode(flushMode) {
291
- this.getContext(false).#flushMode = flushMode;
292
- }
293
- async processWhere(entityName, where, options, type) {
294
- where = QueryHelper.processWhere({
295
- where,
296
- entityName,
297
- metadata: this.metadata,
298
- platform: this.driver.getPlatform(),
299
- convertCustomTypes: options.convertCustomTypes,
300
- aliased: type === 'read',
301
- });
302
- where = (await this.applyFilters(entityName, where, options.filters ?? {}, type, options));
303
- where = this.applyDiscriminatorCondition(entityName, where);
304
- return where;
305
- }
306
- async processUnionWhere(entityName, options, type) {
307
- if (options.unionWhere?.length) {
308
- if (!this.driver.getPlatform().supportsUnionWhere()) {
309
- throw new Error(`unionWhere is only supported on SQL drivers`);
310
- }
311
- options.unionWhere = (await Promise.all(options.unionWhere.map(branch => this.processWhere(entityName, branch, options, type))));
312
- }
313
- }
314
- // this method only handles the problem for mongo driver, SQL drivers have their implementation inside QueryBuilder
315
- applyDiscriminatorCondition(entityName, where) {
316
- const meta = this.metadata.find(entityName);
317
- if (meta?.root.inheritanceType !== 'sti' || !meta?.discriminatorValue) {
318
- return where;
319
- }
320
- const types = Object.values(meta.root.discriminatorMap).map(cls => this.metadata.get(cls));
321
- const children = [];
322
- const lookUpChildren = (ret, type) => {
323
- const children = types.filter(meta2 => meta2.extends === type);
324
- children.forEach(m => lookUpChildren(ret, m.class));
325
- ret.push(...children.filter(c => c.discriminatorValue));
326
- return children;
327
- };
328
- lookUpChildren(children, meta.class);
329
- /* v8 ignore next */
330
- where[meta.root.discriminatorColumn] =
331
- children.length > 0
332
- ? { $in: [meta.discriminatorValue, ...children.map(c => c.discriminatorValue)] }
333
- : meta.discriminatorValue;
334
- return where;
335
- }
336
- createPopulateWhere(cond, options) {
337
- const ret = {};
338
- const populateWhere = options.populateWhere ?? this.config.get('populateWhere');
339
- if (populateWhere === PopulateHint.INFER) {
340
- Utils.merge(ret, cond);
341
- }
342
- else if (typeof populateWhere === 'object') {
343
- Utils.merge(ret, populateWhere);
344
- }
345
- return ret;
346
- }
347
- async getJoinedFilters(meta, options) {
348
- // If user provided populateFilter, merge it with computed filters
349
- const userFilter = options.populateFilter;
350
- if (!this.config.get('filtersOnRelations') || !options.populate) {
351
- return userFilter;
352
- }
353
- const ret = {};
354
- for (const hint of options.populate) {
355
- const field = hint.field.split(':')[0];
356
- const prop = meta.properties[field];
357
- const strategy = getLoadingStrategy(prop.strategy || hint.strategy || options.strategy || this.config.get('loadStrategy'), prop.kind);
358
- const joined = (strategy === LoadStrategy.JOINED || (prop.kind === ReferenceKind.ONE_TO_ONE && !prop.owner)) &&
359
- prop.kind !== ReferenceKind.SCALAR;
360
- if (!joined && !hint.filter) {
361
- continue;
362
- }
363
- const filters = QueryHelper.mergePropertyFilters(prop.filters, options.filters);
364
- const where = await this.applyFilters(prop.targetMeta.class, {}, filters, 'read', {
365
- ...options,
366
- populate: hint.children,
367
- });
368
- const where2 = await this.getJoinedFilters(prop.targetMeta, {
369
- ...options,
370
- filters,
371
- populate: hint.children,
372
- populateWhere: PopulateHint.ALL,
373
- });
374
- if (Utils.hasObjectKeys(where)) {
375
- ret[field] = ret[field] ? { $and: [where, ret[field]] } : where;
376
- }
377
- if (where2 && Utils.hasObjectKeys(where2)) {
378
- if (ret[field]) {
379
- Utils.merge(ret[field], where2);
380
- }
381
- else {
382
- ret[field] = where2;
383
- }
384
- }
385
- }
386
- // Merge user-provided populateFilter with computed filters
387
- if (userFilter) {
388
- Utils.merge(ret, userFilter);
389
- }
390
- return Utils.hasObjectKeys(ret) ? ret : undefined;
391
- }
392
- /**
393
- * When filters are active on M:1 or 1:1 relations, we need to ref join them eagerly as they might affect the FK value.
394
- */
395
- async autoJoinRefsForFilters(meta, options, parent) {
396
- if (!meta || !this.config.get('autoJoinRefsForFilters') || options.filters === false) {
397
- return;
398
- }
399
- const ret = options.populate;
400
- for (const prop of meta.relations) {
401
- if (prop.object ||
402
- ![ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(prop.kind) ||
403
- !((options.fields?.length ?? 0) === 0 ||
404
- options.fields?.some(f => prop.name === f || prop.name.startsWith(`${String(f)}.`))) ||
405
- (parent?.class === prop.targetMeta.root.class && parent.propName === prop.inversedBy)) {
406
- continue;
407
- }
408
- options = { ...options, filters: QueryHelper.mergePropertyFilters(prop.filters, options.filters) };
409
- // For polymorphic relations, check all targets for filters (not just the first targetMeta)
410
- let hasActiveFilter = false;
411
- if (prop.polymorphic && prop.polymorphTargets?.length) {
412
- for (const targetMeta of prop.polymorphTargets) {
413
- const cond = await this.applyFilters(targetMeta.class, {}, options.filters, 'read', options);
414
- if (!Utils.isEmpty(cond)) {
415
- hasActiveFilter = true;
416
- break;
417
- }
418
- }
419
- }
420
- else {
421
- const cond = await this.applyFilters(prop.targetMeta.class, {}, options.filters, 'read', options);
422
- hasActiveFilter = !Utils.isEmpty(cond);
423
- }
424
- if (hasActiveFilter) {
425
- const populated = options.populate.filter(({ field }) => field.split(':')[0] === prop.name);
426
- let found = false;
427
- for (const hint of populated) {
428
- const strategy = getLoadingStrategy(prop.strategy || hint.strategy || options.strategy || this.config.get('loadStrategy'), prop.kind);
429
- // inverse 1:1 always produces a JOIN (forced by `joinedProps()`), regardless of strategy
430
- const willJoin = strategy === LoadStrategy.JOINED || (prop.kind === ReferenceKind.ONE_TO_ONE && !prop.owner);
431
- if (!hint.all || willJoin) {
432
- hint.filter = true;
433
- }
434
- if (hint.field === `${prop.name}:ref` || (hint.filter && willJoin)) {
435
- found = true;
436
- }
437
- }
438
- if (!found) {
439
- ret.push({ field: `${prop.name}:ref`, strategy: LoadStrategy.JOINED, filter: true });
440
- }
441
- }
442
- }
443
- for (const hint of ret) {
444
- const [field, ref] = hint.field.split(':');
445
- const prop = meta?.properties[field];
446
- if (prop && !ref) {
447
- hint.children ??= [];
448
- await this.autoJoinRefsForFilters(prop.targetMeta, { ...options, populate: hint.children }, { class: meta.root.class, propName: prop.name });
449
- }
450
- }
451
- }
452
- /**
453
- * @internal
454
- */
455
- async applyFilters(entityName, where, options, type, findOptions) {
456
- const meta = this.metadata.get(entityName);
457
- const filters = [];
458
- const ret = [];
459
- const active = new Set();
460
- const push = (source) => {
461
- const activeFilters = QueryHelper.getActiveFilters(meta, options, source).filter(f => !active.has(f.name));
462
- filters.push(...activeFilters);
463
- activeFilters.forEach(f => active.add(f.name));
464
- };
465
- push(this.config.get('filters'));
466
- push(this.#filters);
467
- push(meta.filters);
468
- if (filters.length === 0) {
469
- return where;
470
- }
471
- for (const filter of filters) {
472
- let cond;
473
- if (filter.cond instanceof Function) {
474
- // @ts-ignore
475
- // oxfmt-ignore
476
- const args = Utils.isPlainObject(options?.[filter.name]) ? options[filter.name] : this.getContext().#filterParams[filter.name];
477
- if (!args && filter.cond.length > 0 && filter.args !== false) {
478
- throw new Error(`No arguments provided for filter '${filter.name}'`);
479
- }
480
- cond = await filter.cond(args, type, this, findOptions, Utils.className(entityName));
481
- }
482
- else {
483
- cond = filter.cond;
484
- }
485
- cond = QueryHelper.processWhere({
486
- where: cond,
487
- entityName,
488
- metadata: this.metadata,
489
- platform: this.driver.getPlatform(),
490
- aliased: type === 'read',
491
- });
492
- if (filter.strict) {
493
- Object.defineProperty(cond, '__strict', { value: filter.strict, enumerable: false });
494
- }
495
- ret.push(cond);
496
- }
497
- const conds = [...ret, where].filter(c => Utils.hasObjectKeys(c) || Raw.hasObjectFragments(c));
498
- return conds.length > 1 ? { $and: conds } : conds[0];
499
- }
500
- /**
501
- * Calls `em.find()` and `em.count()` with the same arguments (where applicable) and returns the results as tuple
502
- * where the first element is the array of entities, and the second is the count.
503
- */
504
- async findAndCount(entityName, where, options = {}) {
505
- const em = this.getContext(false);
506
- await em.tryFlush(entityName, options);
507
- options.flushMode = 'commit'; // do not try to auto flush again
508
- return Promise.all([
509
- em.find(entityName, where, options),
510
- em.count(entityName, where, options),
511
- ]);
512
- }
513
- /**
514
- * Calls `em.find()` and `em.count()` with the same arguments (where applicable) and returns the results as {@apilink Cursor} object.
515
- * Supports `before`, `after`, `first` and `last` options while disallowing `limit` and `offset`. Explicit `orderBy` option
516
- * is required.
517
- *
518
- * Use `first` and `after` for forward pagination, or `last` and `before` for backward pagination.
519
- *
520
- * - `first` and `last` are numbers and serve as an alternative to `offset`, those options are mutually exclusive, use only one at a time
521
- * - `before` and `after` specify the previous cursor value, it can be one of the:
522
- * - `Cursor` instance
523
- * - opaque string provided by `startCursor/endCursor` properties
524
- * - POJO/entity instance
525
- *
526
- * ```ts
527
- * const currentCursor = await em.findByCursor(User, {
528
- * first: 10,
529
- * after: previousCursor, // cursor instance
530
- * orderBy: { id: 'desc' },
531
- * });
532
- *
533
- * // to fetch next page
534
- * const nextCursor = await em.findByCursor(User, {
535
- * first: 10,
536
- * after: currentCursor.endCursor, // opaque string
537
- * orderBy: { id: 'desc' },
538
- * });
539
- *
540
- * // to fetch next page
541
- * const nextCursor2 = await em.findByCursor(User, {
542
- * first: 10,
543
- * after: { id: lastSeenId }, // entity-like POJO
544
- * orderBy: { id: 'desc' },
545
- * });
546
- * ```
547
- *
548
- * The options also support an `includeCount` (true by default) option. If set to false, the `totalCount` is not
549
- * returned as part of the cursor. This is useful for performance reason, when you don't care about the total number
550
- * of pages.
551
- *
552
- * The `Cursor` object provides the following interface:
553
- *
554
- * ```ts
555
- * Cursor<User> {
556
- * items: [
557
- * User { ... },
558
- * User { ... },
559
- * User { ... },
560
- * ],
561
- * totalCount: 50, // not included if `includeCount: false`
562
- * startCursor: 'WzRd',
563
- * endCursor: 'WzZd',
564
- * hasPrevPage: true,
565
- * hasNextPage: true,
566
- * }
567
- * ```
568
- */
569
- async findByCursor(entityName, options) {
570
- const em = this.getContext(false);
571
- options.overfetch ??= true;
572
- options.where ??= {};
573
- if (Utils.isEmpty(options.orderBy) && !Raw.hasObjectFragments(options.orderBy)) {
574
- throw new Error('Explicit `orderBy` option required');
575
- }
576
- const [entities, count] = options.includeCount !== false
577
- ? await em.findAndCount(entityName, options.where, options)
578
- : [await em.find(entityName, options.where, options)];
579
- return new Cursor(entities, count, options, this.metadata.get(entityName));
580
- }
581
- /**
582
- * Refreshes the persistent state of an entity from the database, overriding any local changes that have not yet been
583
- * persisted. Returns the same entity instance (same object reference), but re-hydrated. If the entity is no longer
584
- * in database, the method throws an error just like `em.findOneOrFail()` (and respects the same config options).
585
- */
586
- async refreshOrFail(entity, options = {}) {
587
- const ret = await this.refresh(entity, options);
588
- if (!ret) {
589
- options.failHandler ??= this.config.get('findOneOrFailHandler');
590
- const wrapped = helper(entity);
591
- const where = wrapped.getPrimaryKey();
592
- throw options.failHandler(wrapped.__meta.className, where);
593
- }
594
- return ret;
595
- }
596
- /**
597
- * Refreshes the persistent state of an entity from the database, overriding any local changes that have not yet been
598
- * persisted. Returns the same entity instance (same object reference), but re-hydrated. If the entity is no longer
599
- * in database, the method returns `null`.
600
- */
601
- async refresh(entity, options = {}) {
602
- const fork = this.fork({ keepTransactionContext: true });
603
- const wrapped = helper(entity);
604
- const reloaded = await fork.findOne(wrapped.__meta.class, entity, {
605
- schema: wrapped.__schema,
606
- ...options,
607
- flushMode: FlushMode.COMMIT,
608
- });
609
- const em = this.getContext();
610
- if (!reloaded) {
611
- em.#unitOfWork.unsetIdentity(entity);
612
- return null;
613
- }
37
+ config;
38
+ driver;
39
+ metadata;
40
+ eventManager;
41
+ static #counter = 1;
42
+ /** @internal */
43
+ _id = EntityManager.#counter++;
44
+ /** Whether this is the global (root) EntityManager instance. */
45
+ global = false;
46
+ /** The context name of this EntityManager, derived from the ORM configuration. */
47
+ name;
48
+ #loaders = {};
49
+ #repositoryMap = new Map();
50
+ #entityLoader;
51
+ #comparator;
52
+ #entityFactory;
53
+ #unitOfWork;
54
+ #resultCache;
55
+ #filters = {};
56
+ #filterParams = {};
57
+ loggerContext;
58
+ #transactionContext;
59
+ #disableTransactions;
60
+ #flushMode;
61
+ #schema;
62
+ #useContext;
63
+ /**
64
+ * @internal
65
+ */
66
+ constructor(config, driver, metadata, useContext = true, eventManager = new EventManager(config.get('subscribers'))) {
67
+ this.config = config;
68
+ this.driver = driver;
69
+ this.metadata = metadata;
70
+ this.eventManager = eventManager;
71
+ this.#useContext = useContext;
72
+ this.#entityLoader = new EntityLoader(this);
73
+ this.name = this.config.get('contextName');
74
+ this.#comparator = this.config.getComparator(this.metadata);
75
+ this.#resultCache = this.config.getResultCacheAdapter();
76
+ this.#disableTransactions = this.config.get('disableTransactions');
77
+ this.#entityFactory = new EntityFactory(this);
78
+ this.#unitOfWork = new UnitOfWork(this);
79
+ }
80
+ /**
81
+ * Gets the Driver instance used by this EntityManager.
82
+ * Driver is singleton, for one MikroORM instance, only one driver is created.
83
+ */
84
+ getDriver() {
85
+ return this.driver;
86
+ }
87
+ /**
88
+ * Gets the Connection instance, by default returns write connection
89
+ */
90
+ getConnection(type) {
91
+ return this.driver.getConnection(type);
92
+ }
93
+ /**
94
+ * Gets the platform instance. Just like the driver, platform is singleton, one for a MikroORM instance.
95
+ */
96
+ getPlatform() {
97
+ return this.driver.getPlatform();
98
+ }
99
+ /**
100
+ * Gets repository for given entity. You can pass either string name or entity class reference.
101
+ */
102
+ getRepository(entityName) {
103
+ const meta = this.metadata.get(entityName);
104
+ if (!this.#repositoryMap.has(meta)) {
105
+ const RepositoryClass = this.config.getRepositoryClass(meta.repository);
106
+ this.#repositoryMap.set(meta, new RepositoryClass(this, entityName));
107
+ }
108
+ return this.#repositoryMap.get(meta);
109
+ }
110
+ /**
111
+ * Shortcut for `em.getRepository()`.
112
+ */
113
+ repo(entityName) {
114
+ return this.getRepository(entityName);
115
+ }
116
+ /**
117
+ * Finds all entities matching your `where` query. You can pass additional options via the `options` parameter.
118
+ */
119
+ async find(entityName, where, options = {}) {
120
+ if (options.disableIdentityMap ?? this.config.get('disableIdentityMap')) {
121
+ const em = this.getContext(false);
122
+ const fork = em.fork({ keepTransactionContext: true });
123
+ const ret = await fork.find(entityName, where, { ...options, disableIdentityMap: false });
124
+ fork.clear();
125
+ return ret;
126
+ }
127
+ const em = this.getContext();
128
+ em.prepareOptions(options);
129
+ await em.tryFlush(entityName, options);
130
+ where = await em.processWhere(entityName, where, options, 'read');
131
+ validateParams(where);
132
+ const meta = this.metadata.get(entityName);
133
+ if (meta.orderBy) {
134
+ options.orderBy = QueryHelper.mergeOrderBy(options.orderBy, meta.orderBy);
135
+ } else {
136
+ options.orderBy ??= {};
137
+ }
138
+ options.populate = await em.preparePopulate(entityName, options);
139
+ const populate = options.populate;
140
+ const cacheKey = em.cacheKey(entityName, options, 'em.find', where);
141
+ const cached = await em.tryCache(entityName, options.cache, cacheKey, options.refresh, true);
142
+ if (cached?.data) {
143
+ await em.#entityLoader.populate(entityName, cached.data, populate, {
144
+ ...options,
145
+ ...em.getPopulateWhere(where, options),
146
+ ignoreLazyScalarProperties: true,
147
+ lookup: false,
148
+ });
149
+ return cached.data;
150
+ }
151
+ options = { ...options };
152
+ // save the original hint value so we know it was infer/all
153
+ options._populateWhere = options.populateWhere ?? this.config.get('populateWhere');
154
+ options.populateWhere = this.createPopulateWhere({ ...where }, options);
155
+ options.populateFilter = await this.getJoinedFilters(meta, options);
156
+ await em.processUnionWhere(entityName, options, 'read');
157
+ const results = await em.driver.find(entityName, where, { ctx: em.#transactionContext, em, ...options });
158
+ if (results.length === 0) {
159
+ await em.storeCache(options.cache, cached, []);
160
+ return [];
161
+ }
162
+ const ret = [];
163
+ for (const data of results) {
164
+ const entity = em.#entityFactory.create(entityName, data, {
165
+ merge: true,
166
+ refresh: options.refresh,
167
+ schema: options.schema,
168
+ convertCustomTypes: true,
169
+ });
170
+ ret.push(entity);
171
+ }
172
+ const unique = Utils.unique(ret);
173
+ await em.#entityLoader.populate(entityName, unique, populate, {
174
+ ...options,
175
+ ...em.getPopulateWhere(where, options),
176
+ ignoreLazyScalarProperties: true,
177
+ lookup: false,
178
+ });
179
+ await em.#unitOfWork.dispatchOnLoadEvent();
180
+ if (meta.virtual) {
181
+ await em.storeCache(options.cache, cached, () => ret);
182
+ } else {
183
+ await em.storeCache(options.cache, cached, () => unique.map(e => helper(e).toPOJO()));
184
+ }
185
+ return unique;
186
+ }
187
+ /**
188
+ * Finds all entities and returns an async iterable (async generator) that yields results one by one.
189
+ * The results are merged and mapped to entity instances, without adding them to the identity map.
190
+ * You can disable merging by passing the options `{ mergeResults: false }`.
191
+ * With `mergeResults` disabled, to-many collections will contain at most one item, and you will get duplicate
192
+ * root entities when there are multiple items in the populated collection.
193
+ * This is useful for processing large datasets without loading everything into memory at once.
194
+ *
195
+ * ```ts
196
+ * const stream = em.stream(Book, { populate: ['author'] });
197
+ *
198
+ * for await (const book of stream) {
199
+ * // book is an instance of Book entity
200
+ * console.log(book.title, book.author.name);
201
+ * }
202
+ * ```
203
+ */
204
+ async *stream(entityName, options = {}) {
205
+ const em = this.getContext();
206
+ em.prepareOptions(options);
207
+ options.strategy = 'joined';
208
+ await em.tryFlush(entityName, options);
209
+ const where = await em.processWhere(entityName, options.where ?? {}, options, 'read');
210
+ validateParams(where);
211
+ options.orderBy = options.orderBy || {};
212
+ options.populate = await em.preparePopulate(entityName, options);
213
+ const meta = this.metadata.get(entityName);
214
+ options = { ...options };
215
+ // save the original hint value so we know it was infer/all
216
+ options._populateWhere = options.populateWhere ?? this.config.get('populateWhere');
217
+ options.populateWhere = this.createPopulateWhere({ ...where }, options);
218
+ options.populateFilter = await this.getJoinedFilters(meta, options);
219
+ const stream = em.driver.stream(entityName, where, {
220
+ ctx: em.#transactionContext,
221
+ mapResults: false,
222
+ ...options,
223
+ });
224
+ for await (const data of stream) {
225
+ const fork = em.fork();
226
+ const entity = fork.#entityFactory.create(entityName, data, {
227
+ refresh: options.refresh,
228
+ schema: options.schema,
229
+ convertCustomTypes: true,
230
+ });
231
+ helper(entity).setSerializationContext({
232
+ populate: options.populate,
233
+ fields: options.fields,
234
+ exclude: options.exclude,
235
+ });
236
+ await fork.#unitOfWork.dispatchOnLoadEvent();
237
+ fork.clear();
238
+ yield entity;
239
+ }
240
+ }
241
+ /**
242
+ * Finds all entities of given type, optionally matching the `where` condition provided in the `options` parameter.
243
+ */
244
+ async findAll(entityName, options) {
245
+ return this.find(entityName, options?.where ?? {}, options);
246
+ }
247
+ getPopulateWhere(where, options) {
248
+ if (options.populateWhere === undefined) {
249
+ options.populateWhere = this.config.get('populateWhere');
250
+ }
251
+ if (options.populateWhere === PopulateHint.ALL) {
252
+ return { where: {}, populateWhere: options.populateWhere };
253
+ }
254
+ /* v8 ignore next */
255
+ if (options.populateWhere === PopulateHint.INFER) {
256
+ return { where, populateWhere: options.populateWhere };
257
+ }
258
+ return { where: options.populateWhere };
259
+ }
260
+ /**
261
+ * Registers global filter to this entity manager. Global filters are enabled by default (unless disabled via last parameter).
262
+ */
263
+ addFilter(options) {
264
+ if (options.entity) {
265
+ options.entity = Utils.asArray(options.entity).map(n => Utils.className(n));
266
+ }
267
+ options.default ??= true;
268
+ this.getContext(false).#filters[options.name] = options;
269
+ }
270
+ /**
271
+ * Sets filter parameter values globally inside context defined by this entity manager.
272
+ * If you want to set shared value for all contexts, be sure to use the root entity manager.
273
+ */
274
+ setFilterParams(name, args) {
275
+ this.getContext().#filterParams[name] = args;
276
+ }
277
+ /**
278
+ * Returns filter parameters for given filter set in this context.
279
+ */
280
+ getFilterParams(name) {
281
+ return this.getContext().#filterParams[name];
282
+ }
283
+ /**
284
+ * Sets logger context for this entity manager.
285
+ */
286
+ setLoggerContext(context) {
287
+ this.getContext().loggerContext = context;
288
+ }
289
+ /**
290
+ * Gets logger context for this entity manager.
291
+ */
292
+ getLoggerContext(options) {
293
+ const em = options?.disableContextResolution ? this : this.getContext();
294
+ em.loggerContext ??= {};
295
+ return em.loggerContext;
296
+ }
297
+ /** Sets the flush mode for this EntityManager. Pass `undefined` to reset to the global default. */
298
+ setFlushMode(flushMode) {
299
+ this.getContext(false).#flushMode = flushMode;
300
+ }
301
+ async processWhere(entityName, where, options, type) {
302
+ where = QueryHelper.processWhere({
303
+ where,
304
+ entityName,
305
+ metadata: this.metadata,
306
+ platform: this.driver.getPlatform(),
307
+ convertCustomTypes: options.convertCustomTypes,
308
+ aliased: type === 'read',
309
+ });
310
+ where = await this.applyFilters(entityName, where, options.filters ?? {}, type, options);
311
+ where = this.applyDiscriminatorCondition(entityName, where);
312
+ return where;
313
+ }
314
+ async processUnionWhere(entityName, options, type) {
315
+ if (options.unionWhere?.length) {
316
+ if (!this.driver.getPlatform().supportsUnionWhere()) {
317
+ throw new Error(`unionWhere is only supported on SQL drivers`);
318
+ }
319
+ options.unionWhere = await Promise.all(
320
+ options.unionWhere.map(branch => this.processWhere(entityName, branch, options, type)),
321
+ );
322
+ }
323
+ }
324
+ // this method only handles the problem for mongo driver, SQL drivers have their implementation inside QueryBuilder
325
+ applyDiscriminatorCondition(entityName, where) {
326
+ const meta = this.metadata.find(entityName);
327
+ if (meta?.root.inheritanceType !== 'sti' || !meta?.discriminatorValue) {
328
+ return where;
329
+ }
330
+ const types = Object.values(meta.root.discriminatorMap).map(cls => this.metadata.get(cls));
331
+ const children = [];
332
+ const lookUpChildren = (ret, type) => {
333
+ const children = types.filter(meta2 => meta2.extends === type);
334
+ children.forEach(m => lookUpChildren(ret, m.class));
335
+ ret.push(...children.filter(c => c.discriminatorValue));
336
+ return children;
337
+ };
338
+ lookUpChildren(children, meta.class);
339
+ /* v8 ignore next */
340
+ where[meta.root.discriminatorColumn] =
341
+ children.length > 0
342
+ ? { $in: [meta.discriminatorValue, ...children.map(c => c.discriminatorValue)] }
343
+ : meta.discriminatorValue;
344
+ return where;
345
+ }
346
+ createPopulateWhere(cond, options) {
347
+ const ret = {};
348
+ const populateWhere = options.populateWhere ?? this.config.get('populateWhere');
349
+ if (populateWhere === PopulateHint.INFER) {
350
+ Utils.merge(ret, cond);
351
+ } else if (typeof populateWhere === 'object') {
352
+ Utils.merge(ret, populateWhere);
353
+ }
354
+ return ret;
355
+ }
356
+ async getJoinedFilters(meta, options) {
357
+ // If user provided populateFilter, merge it with computed filters
358
+ const userFilter = options.populateFilter;
359
+ if (!this.config.get('filtersOnRelations') || !options.populate) {
360
+ return userFilter;
361
+ }
362
+ const ret = {};
363
+ for (const hint of options.populate) {
364
+ const field = hint.field.split(':')[0];
365
+ const prop = meta.properties[field];
366
+ const strategy = getLoadingStrategy(
367
+ prop.strategy || hint.strategy || options.strategy || this.config.get('loadStrategy'),
368
+ prop.kind,
369
+ );
370
+ const joined =
371
+ (strategy === LoadStrategy.JOINED || (prop.kind === ReferenceKind.ONE_TO_ONE && !prop.owner)) &&
372
+ prop.kind !== ReferenceKind.SCALAR;
373
+ if (!joined && !hint.filter) {
374
+ continue;
375
+ }
376
+ const filters = QueryHelper.mergePropertyFilters(prop.filters, options.filters);
377
+ const where = await this.applyFilters(prop.targetMeta.class, {}, filters, 'read', {
378
+ ...options,
379
+ populate: hint.children,
380
+ });
381
+ const where2 = await this.getJoinedFilters(prop.targetMeta, {
382
+ ...options,
383
+ filters,
384
+ populate: hint.children,
385
+ populateWhere: PopulateHint.ALL,
386
+ });
387
+ if (Utils.hasObjectKeys(where)) {
388
+ ret[field] = ret[field] ? { $and: [where, ret[field]] } : where;
389
+ }
390
+ if (where2 && Utils.hasObjectKeys(where2)) {
391
+ if (ret[field]) {
392
+ Utils.merge(ret[field], where2);
393
+ } else {
394
+ ret[field] = where2;
395
+ }
396
+ }
397
+ }
398
+ // Merge user-provided populateFilter with computed filters
399
+ if (userFilter) {
400
+ Utils.merge(ret, userFilter);
401
+ }
402
+ return Utils.hasObjectKeys(ret) ? ret : undefined;
403
+ }
404
+ /**
405
+ * When filters are active on M:1 or 1:1 relations, we need to ref join them eagerly as they might affect the FK value.
406
+ */
407
+ async autoJoinRefsForFilters(meta, options, parent) {
408
+ if (!meta || !this.config.get('autoJoinRefsForFilters') || options.filters === false) {
409
+ return;
410
+ }
411
+ const ret = options.populate;
412
+ for (const prop of meta.relations) {
413
+ if (
414
+ prop.object ||
415
+ ![ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(prop.kind) ||
416
+ !(
417
+ (options.fields?.length ?? 0) === 0 ||
418
+ options.fields?.some(f => prop.name === f || prop.name.startsWith(`${String(f)}.`))
419
+ ) ||
420
+ (parent?.class === prop.targetMeta.root.class && parent.propName === prop.inversedBy)
421
+ ) {
422
+ continue;
423
+ }
424
+ options = { ...options, filters: QueryHelper.mergePropertyFilters(prop.filters, options.filters) };
425
+ // For polymorphic relations, check all targets for filters (not just the first targetMeta)
426
+ let hasActiveFilter = false;
427
+ if (prop.polymorphic && prop.polymorphTargets?.length) {
428
+ for (const targetMeta of prop.polymorphTargets) {
429
+ const cond = await this.applyFilters(targetMeta.class, {}, options.filters, 'read', options);
430
+ if (!Utils.isEmpty(cond)) {
431
+ hasActiveFilter = true;
432
+ break;
433
+ }
434
+ }
435
+ } else {
436
+ const cond = await this.applyFilters(prop.targetMeta.class, {}, options.filters, 'read', options);
437
+ hasActiveFilter = !Utils.isEmpty(cond);
438
+ }
439
+ if (hasActiveFilter) {
440
+ const populated = options.populate.filter(({ field }) => field.split(':')[0] === prop.name);
614
441
  let found = false;
615
- for (const e of fork.#unitOfWork.getIdentityMap()) {
616
- const ref = em.getReference(e.constructor, helper(e).getPrimaryKey());
617
- const data = helper(e).serialize({ ignoreSerializers: true, includeHidden: true, convertCustomTypes: false });
618
- em.config
619
- .getHydrator(this.metadata)
620
- .hydrate(ref, helper(ref).__meta, data, em.#entityFactory, 'full', false, false);
621
- Utils.merge(helper(ref).__originalEntityData, this.#comparator.prepareEntity(e));
622
- found ||= ref === entity;
442
+ for (const hint of populated) {
443
+ const strategy = getLoadingStrategy(
444
+ prop.strategy || hint.strategy || options.strategy || this.config.get('loadStrategy'),
445
+ prop.kind,
446
+ );
447
+ // inverse 1:1 always produces a JOIN (forced by `joinedProps()`), regardless of strategy
448
+ const willJoin = strategy === LoadStrategy.JOINED || (prop.kind === ReferenceKind.ONE_TO_ONE && !prop.owner);
449
+ if (!hint.all || willJoin) {
450
+ hint.filter = true;
451
+ }
452
+ if (hint.field === `${prop.name}:ref` || (hint.filter && willJoin)) {
453
+ found = true;
454
+ }
623
455
  }
624
456
  if (!found) {
625
- const data = helper(reloaded).serialize({
626
- ignoreSerializers: true,
627
- includeHidden: true,
628
- convertCustomTypes: false,
629
- });
630
- em.config
631
- .getHydrator(this.metadata)
632
- .hydrate(entity, wrapped.__meta, data, em.#entityFactory, 'full', false, false);
633
- Utils.merge(wrapped.__originalEntityData, this.#comparator.prepareEntity(reloaded));
634
- }
635
- return entity;
636
- }
637
- /**
638
- * Finds first entity matching your `where` query.
639
- */
640
- async findOne(entityName, where, options = {}) {
641
- if (options.disableIdentityMap ?? this.config.get('disableIdentityMap')) {
642
- const em = this.getContext(false);
643
- const fork = em.fork({ keepTransactionContext: true });
644
- const ret = await fork.findOne(entityName, where, { ...options, disableIdentityMap: false });
645
- fork.clear();
646
- return ret;
647
- }
648
- const em = this.getContext();
649
- em.prepareOptions(options);
650
- let entity = em.#unitOfWork.tryGetById(entityName, where, options.schema);
651
- // query for a not managed entity which is already in the identity map as it
652
- // was provided with a PK this entity does not exist in the db, there can't
653
- // be any relations to it, so no need to deal with the populate hint
654
- if (entity && !helper(entity).__managed) {
655
- return entity;
656
- }
657
- await em.tryFlush(entityName, options);
658
- const meta = em.metadata.get(entityName);
659
- where = await em.processWhere(entityName, where, options, 'read');
660
- validateEmptyWhere(where);
661
- em.checkLockRequirements(options.lockMode, meta);
662
- const isOptimisticLocking = options.lockMode == null || options.lockMode === LockMode.OPTIMISTIC;
663
- if (entity && !em.shouldRefresh(meta, entity, options) && isOptimisticLocking) {
664
- return em.lockAndPopulate(meta, entity, where, options);
665
- }
666
- validateParams(where);
667
- options.populate = (await em.preparePopulate(entityName, options));
668
- const cacheKey = em.cacheKey(entityName, options, 'em.findOne', where);
669
- const cached = await em.tryCache(entityName, options.cache, cacheKey, options.refresh, true);
670
- if (cached?.data !== undefined) {
671
- if (cached.data) {
672
- await em.#entityLoader.populate(entityName, [cached.data], options.populate, {
673
- ...options,
674
- ...em.getPopulateWhere(where, options),
675
- ignoreLazyScalarProperties: true,
676
- lookup: false,
677
- });
678
- }
679
- return cached.data;
680
- }
681
- options = { ...options };
682
- // save the original hint value so we know it was infer/all
683
- options._populateWhere = options.populateWhere ?? this.config.get('populateWhere');
684
- options.populateWhere = this.createPopulateWhere({ ...where }, options);
685
- options.populateFilter = await this.getJoinedFilters(meta, options);
686
- await em.processUnionWhere(entityName, options, 'read');
687
- const data = await em.driver.findOne(entityName, where, {
688
- ctx: em.#transactionContext,
689
- em,
690
- ...options,
691
- });
692
- if (!data) {
693
- await em.storeCache(options.cache, cached, null);
694
- return null;
695
- }
696
- entity = em.#entityFactory.create(entityName, data, {
697
- merge: true,
698
- refresh: options.refresh,
699
- schema: options.schema,
700
- convertCustomTypes: true,
457
+ ret.push({ field: `${prop.name}:ref`, strategy: LoadStrategy.JOINED, filter: true });
458
+ }
459
+ }
460
+ }
461
+ for (const hint of ret) {
462
+ const [field, ref] = hint.field.split(':');
463
+ const prop = meta?.properties[field];
464
+ if (prop && !ref) {
465
+ hint.children ??= [];
466
+ await this.autoJoinRefsForFilters(
467
+ prop.targetMeta,
468
+ { ...options, populate: hint.children },
469
+ { class: meta.root.class, propName: prop.name },
470
+ );
471
+ }
472
+ }
473
+ }
474
+ /**
475
+ * @internal
476
+ */
477
+ async applyFilters(entityName, where, options, type, findOptions) {
478
+ const meta = this.metadata.get(entityName);
479
+ const filters = [];
480
+ const ret = [];
481
+ const active = new Set();
482
+ const push = source => {
483
+ const activeFilters = QueryHelper.getActiveFilters(meta, options, source).filter(f => !active.has(f.name));
484
+ filters.push(...activeFilters);
485
+ activeFilters.forEach(f => active.add(f.name));
486
+ };
487
+ push(this.config.get('filters'));
488
+ push(this.#filters);
489
+ push(meta.filters);
490
+ if (filters.length === 0) {
491
+ return where;
492
+ }
493
+ for (const filter of filters) {
494
+ let cond;
495
+ if (filter.cond instanceof Function) {
496
+ // @ts-ignore
497
+ // oxfmt-ignore
498
+ const args = Utils.isPlainObject(options?.[filter.name]) ? options[filter.name] : this.getContext().#filterParams[filter.name];
499
+ if (!args && filter.cond.length > 0 && filter.args !== false) {
500
+ throw new Error(`No arguments provided for filter '${filter.name}'`);
501
+ }
502
+ cond = await filter.cond(args, type, this, findOptions, Utils.className(entityName));
503
+ } else {
504
+ cond = filter.cond;
505
+ }
506
+ cond = QueryHelper.processWhere({
507
+ where: cond,
508
+ entityName,
509
+ metadata: this.metadata,
510
+ platform: this.driver.getPlatform(),
511
+ aliased: type === 'read',
512
+ });
513
+ if (filter.strict) {
514
+ Object.defineProperty(cond, '__strict', { value: filter.strict, enumerable: false });
515
+ }
516
+ ret.push(cond);
517
+ }
518
+ const conds = [...ret, where].filter(c => Utils.hasObjectKeys(c) || Raw.hasObjectFragments(c));
519
+ return conds.length > 1 ? { $and: conds } : conds[0];
520
+ }
521
+ /**
522
+ * Calls `em.find()` and `em.count()` with the same arguments (where applicable) and returns the results as tuple
523
+ * where the first element is the array of entities, and the second is the count.
524
+ */
525
+ async findAndCount(entityName, where, options = {}) {
526
+ const em = this.getContext(false);
527
+ await em.tryFlush(entityName, options);
528
+ options.flushMode = 'commit'; // do not try to auto flush again
529
+ return Promise.all([em.find(entityName, where, options), em.count(entityName, where, options)]);
530
+ }
531
+ /**
532
+ * Calls `em.find()` and `em.count()` with the same arguments (where applicable) and returns the results as {@apilink Cursor} object.
533
+ * Supports `before`, `after`, `first` and `last` options while disallowing `limit` and `offset`. Explicit `orderBy` option
534
+ * is required.
535
+ *
536
+ * Use `first` and `after` for forward pagination, or `last` and `before` for backward pagination.
537
+ *
538
+ * - `first` and `last` are numbers and serve as an alternative to `offset`, those options are mutually exclusive, use only one at a time
539
+ * - `before` and `after` specify the previous cursor value, it can be one of the:
540
+ * - `Cursor` instance
541
+ * - opaque string provided by `startCursor/endCursor` properties
542
+ * - POJO/entity instance
543
+ *
544
+ * ```ts
545
+ * const currentCursor = await em.findByCursor(User, {
546
+ * first: 10,
547
+ * after: previousCursor, // cursor instance
548
+ * orderBy: { id: 'desc' },
549
+ * });
550
+ *
551
+ * // to fetch next page
552
+ * const nextCursor = await em.findByCursor(User, {
553
+ * first: 10,
554
+ * after: currentCursor.endCursor, // opaque string
555
+ * orderBy: { id: 'desc' },
556
+ * });
557
+ *
558
+ * // to fetch next page
559
+ * const nextCursor2 = await em.findByCursor(User, {
560
+ * first: 10,
561
+ * after: { id: lastSeenId }, // entity-like POJO
562
+ * orderBy: { id: 'desc' },
563
+ * });
564
+ * ```
565
+ *
566
+ * The options also support an `includeCount` (true by default) option. If set to false, the `totalCount` is not
567
+ * returned as part of the cursor. This is useful for performance reason, when you don't care about the total number
568
+ * of pages.
569
+ *
570
+ * The `Cursor` object provides the following interface:
571
+ *
572
+ * ```ts
573
+ * Cursor<User> {
574
+ * items: [
575
+ * User { ... },
576
+ * User { ... },
577
+ * User { ... },
578
+ * ],
579
+ * totalCount: 50, // not included if `includeCount: false`
580
+ * startCursor: 'WzRd',
581
+ * endCursor: 'WzZd',
582
+ * hasPrevPage: true,
583
+ * hasNextPage: true,
584
+ * }
585
+ * ```
586
+ */
587
+ async findByCursor(entityName, options) {
588
+ const em = this.getContext(false);
589
+ options.overfetch ??= true;
590
+ options.where ??= {};
591
+ if (Utils.isEmpty(options.orderBy) && !Raw.hasObjectFragments(options.orderBy)) {
592
+ throw new Error('Explicit `orderBy` option required');
593
+ }
594
+ const [entities, count] =
595
+ options.includeCount !== false
596
+ ? await em.findAndCount(entityName, options.where, options)
597
+ : [await em.find(entityName, options.where, options)];
598
+ return new Cursor(entities, count, options, this.metadata.get(entityName));
599
+ }
600
+ /**
601
+ * Refreshes the persistent state of an entity from the database, overriding any local changes that have not yet been
602
+ * persisted. Returns the same entity instance (same object reference), but re-hydrated. If the entity is no longer
603
+ * in database, the method throws an error just like `em.findOneOrFail()` (and respects the same config options).
604
+ */
605
+ async refreshOrFail(entity, options = {}) {
606
+ const ret = await this.refresh(entity, options);
607
+ if (!ret) {
608
+ options.failHandler ??= this.config.get('findOneOrFailHandler');
609
+ const wrapped = helper(entity);
610
+ const where = wrapped.getPrimaryKey();
611
+ throw options.failHandler(wrapped.__meta.className, where);
612
+ }
613
+ return ret;
614
+ }
615
+ /**
616
+ * Refreshes the persistent state of an entity from the database, overriding any local changes that have not yet been
617
+ * persisted. Returns the same entity instance (same object reference), but re-hydrated. If the entity is no longer
618
+ * in database, the method returns `null`.
619
+ */
620
+ async refresh(entity, options = {}) {
621
+ const fork = this.fork({ keepTransactionContext: true });
622
+ const wrapped = helper(entity);
623
+ const reloaded = await fork.findOne(wrapped.__meta.class, entity, {
624
+ schema: wrapped.__schema,
625
+ ...options,
626
+ flushMode: FlushMode.COMMIT,
627
+ });
628
+ const em = this.getContext();
629
+ if (!reloaded) {
630
+ em.#unitOfWork.unsetIdentity(entity);
631
+ return null;
632
+ }
633
+ let found = false;
634
+ for (const e of fork.#unitOfWork.getIdentityMap()) {
635
+ const ref = em.getReference(e.constructor, helper(e).getPrimaryKey());
636
+ const data = helper(e).serialize({ ignoreSerializers: true, includeHidden: true, convertCustomTypes: false });
637
+ em.config
638
+ .getHydrator(this.metadata)
639
+ .hydrate(ref, helper(ref).__meta, data, em.#entityFactory, 'full', false, false);
640
+ Utils.merge(helper(ref).__originalEntityData, this.#comparator.prepareEntity(e));
641
+ found ||= ref === entity;
642
+ }
643
+ if (!found) {
644
+ const data = helper(reloaded).serialize({
645
+ ignoreSerializers: true,
646
+ includeHidden: true,
647
+ convertCustomTypes: false,
648
+ });
649
+ em.config
650
+ .getHydrator(this.metadata)
651
+ .hydrate(entity, wrapped.__meta, data, em.#entityFactory, 'full', false, false);
652
+ Utils.merge(wrapped.__originalEntityData, this.#comparator.prepareEntity(reloaded));
653
+ }
654
+ return entity;
655
+ }
656
+ /**
657
+ * Finds first entity matching your `where` query.
658
+ */
659
+ async findOne(entityName, where, options = {}) {
660
+ if (options.disableIdentityMap ?? this.config.get('disableIdentityMap')) {
661
+ const em = this.getContext(false);
662
+ const fork = em.fork({ keepTransactionContext: true });
663
+ const ret = await fork.findOne(entityName, where, { ...options, disableIdentityMap: false });
664
+ fork.clear();
665
+ return ret;
666
+ }
667
+ const em = this.getContext();
668
+ em.prepareOptions(options);
669
+ let entity = em.#unitOfWork.tryGetById(entityName, where, options.schema);
670
+ // query for a not managed entity which is already in the identity map as it
671
+ // was provided with a PK this entity does not exist in the db, there can't
672
+ // be any relations to it, so no need to deal with the populate hint
673
+ if (entity && !helper(entity).__managed) {
674
+ return entity;
675
+ }
676
+ await em.tryFlush(entityName, options);
677
+ const meta = em.metadata.get(entityName);
678
+ where = await em.processWhere(entityName, where, options, 'read');
679
+ validateEmptyWhere(where);
680
+ em.checkLockRequirements(options.lockMode, meta);
681
+ const isOptimisticLocking = options.lockMode == null || options.lockMode === LockMode.OPTIMISTIC;
682
+ if (entity && !em.shouldRefresh(meta, entity, options) && isOptimisticLocking) {
683
+ return em.lockAndPopulate(meta, entity, where, options);
684
+ }
685
+ validateParams(where);
686
+ options.populate = await em.preparePopulate(entityName, options);
687
+ const cacheKey = em.cacheKey(entityName, options, 'em.findOne', where);
688
+ const cached = await em.tryCache(entityName, options.cache, cacheKey, options.refresh, true);
689
+ if (cached?.data !== undefined) {
690
+ if (cached.data) {
691
+ await em.#entityLoader.populate(entityName, [cached.data], options.populate, {
692
+ ...options,
693
+ ...em.getPopulateWhere(where, options),
694
+ ignoreLazyScalarProperties: true,
695
+ lookup: false,
701
696
  });
702
- await em.lockAndPopulate(meta, entity, where, options);
703
- await em.#unitOfWork.dispatchOnLoadEvent();
704
- await em.storeCache(options.cache, cached, () => helper(entity).toPOJO());
705
- return entity;
706
- }
707
- /**
708
- * Finds first entity matching your `where` query. If nothing found, it will throw an error.
709
- * If the `strict` option is specified and nothing is found or more than one matching entity is found, it will throw an error.
710
- * You can override the factory for creating this method via `options.failHandler` locally
711
- * or via `Configuration.findOneOrFailHandler` (`findExactlyOneOrFailHandler` when specifying `strict`) globally.
712
- */
713
- async findOneOrFail(entityName, where, options = {}) {
714
- let entity;
715
- let isStrictViolation = false;
716
- if (options.strict) {
717
- const ret = await this.find(entityName, where, { ...options, limit: 2 });
718
- isStrictViolation = ret.length !== 1;
719
- entity = ret[0];
720
- }
721
- else {
722
- entity = await this.findOne(entityName, where, options);
723
- }
724
- if (!entity || isStrictViolation) {
725
- const key = options.strict ? 'findExactlyOneOrFailHandler' : 'findOneOrFailHandler';
726
- options.failHandler ??= this.config.get(key);
727
- const name = Utils.className(entityName);
728
- /* v8 ignore next */
729
- where = Utils.isEntity(where) ? helper(where).getPrimaryKey() : where;
730
- throw options.failHandler(name, where);
731
- }
697
+ }
698
+ return cached.data;
699
+ }
700
+ options = { ...options };
701
+ // save the original hint value so we know it was infer/all
702
+ options._populateWhere = options.populateWhere ?? this.config.get('populateWhere');
703
+ options.populateWhere = this.createPopulateWhere({ ...where }, options);
704
+ options.populateFilter = await this.getJoinedFilters(meta, options);
705
+ await em.processUnionWhere(entityName, options, 'read');
706
+ const data = await em.driver.findOne(entityName, where, {
707
+ ctx: em.#transactionContext,
708
+ em,
709
+ ...options,
710
+ });
711
+ if (!data) {
712
+ await em.storeCache(options.cache, cached, null);
713
+ return null;
714
+ }
715
+ entity = em.#entityFactory.create(entityName, data, {
716
+ merge: true,
717
+ refresh: options.refresh,
718
+ schema: options.schema,
719
+ convertCustomTypes: true,
720
+ });
721
+ await em.lockAndPopulate(meta, entity, where, options);
722
+ await em.#unitOfWork.dispatchOnLoadEvent();
723
+ await em.storeCache(options.cache, cached, () => helper(entity).toPOJO());
724
+ return entity;
725
+ }
726
+ /**
727
+ * Finds first entity matching your `where` query. If nothing found, it will throw an error.
728
+ * If the `strict` option is specified and nothing is found or more than one matching entity is found, it will throw an error.
729
+ * You can override the factory for creating this method via `options.failHandler` locally
730
+ * or via `Configuration.findOneOrFailHandler` (`findExactlyOneOrFailHandler` when specifying `strict`) globally.
731
+ */
732
+ async findOneOrFail(entityName, where, options = {}) {
733
+ let entity;
734
+ let isStrictViolation = false;
735
+ if (options.strict) {
736
+ const ret = await this.find(entityName, where, { ...options, limit: 2 });
737
+ isStrictViolation = ret.length !== 1;
738
+ entity = ret[0];
739
+ } else {
740
+ entity = await this.findOne(entityName, where, options);
741
+ }
742
+ if (!entity || isStrictViolation) {
743
+ const key = options.strict ? 'findExactlyOneOrFailHandler' : 'findOneOrFailHandler';
744
+ options.failHandler ??= this.config.get(key);
745
+ const name = Utils.className(entityName);
746
+ /* v8 ignore next */
747
+ where = Utils.isEntity(where) ? helper(where).getPrimaryKey() : where;
748
+ throw options.failHandler(name, where);
749
+ }
750
+ return entity;
751
+ }
752
+ /**
753
+ * Creates or updates the entity, based on whether it is already present in the database.
754
+ * This method performs an `insert on conflict merge` query ensuring the database is in sync, returning a managed
755
+ * entity instance. The method accepts either `entityName` together with the entity `data`, or just entity instance.
756
+ *
757
+ * ```ts
758
+ * // insert into "author" ("age", "email") values (33, 'foo@bar.com') on conflict ("email") do update set "age" = 41
759
+ * const author = await em.upsert(Author, { email: 'foo@bar.com', age: 33 });
760
+ * ```
761
+ *
762
+ * The entity data needs to contain either the primary key, or any other unique property. Let's consider the following example, where `Author.email` is a unique property:
763
+ *
764
+ * ```ts
765
+ * // insert into "author" ("age", "email") values (33, 'foo@bar.com') on conflict ("email") do update set "age" = 41
766
+ * // select "id" from "author" where "email" = 'foo@bar.com'
767
+ * const author = await em.upsert(Author, { email: 'foo@bar.com', age: 33 });
768
+ * ```
769
+ *
770
+ * Depending on the driver support, this will either use a returning query, or a separate select query, to fetch the primary key if it's missing from the `data`.
771
+ *
772
+ * If the entity is already present in current context, there won't be any queries - instead, the entity data will be assigned and an explicit `flush` will be required for those changes to be persisted.
773
+ */
774
+ async upsert(entityNameOrEntity, data, options = {}) {
775
+ if (options.disableIdentityMap ?? this.config.get('disableIdentityMap')) {
776
+ const em = this.getContext(false);
777
+ const fork = em.fork({ keepTransactionContext: true });
778
+ const ret = await fork.upsert(entityNameOrEntity, data, { ...options, disableIdentityMap: false });
779
+ fork.clear();
780
+ return ret;
781
+ }
782
+ const em = this.getContext(false);
783
+ em.prepareOptions(options);
784
+ let entityName;
785
+ let where;
786
+ let entity = null;
787
+ if (data === undefined) {
788
+ entityName = entityNameOrEntity.constructor;
789
+ data = entityNameOrEntity;
790
+ } else {
791
+ entityName = entityNameOrEntity;
792
+ }
793
+ const meta = this.metadata.get(entityName);
794
+ const convertCustomTypes = !Utils.isEntity(data);
795
+ if (Utils.isEntity(data)) {
796
+ entity = data;
797
+ if (helper(entity).__managed && helper(entity).__em === em && !this.config.get('upsertManaged')) {
798
+ em.#entityFactory.mergeData(meta, entity, data, { initialized: true });
732
799
  return entity;
733
- }
734
- /**
735
- * Creates or updates the entity, based on whether it is already present in the database.
736
- * This method performs an `insert on conflict merge` query ensuring the database is in sync, returning a managed
737
- * entity instance. The method accepts either `entityName` together with the entity `data`, or just entity instance.
738
- *
739
- * ```ts
740
- * // insert into "author" ("age", "email") values (33, 'foo@bar.com') on conflict ("email") do update set "age" = 41
741
- * const author = await em.upsert(Author, { email: 'foo@bar.com', age: 33 });
742
- * ```
743
- *
744
- * The entity data needs to contain either the primary key, or any other unique property. Let's consider the following example, where `Author.email` is a unique property:
745
- *
746
- * ```ts
747
- * // insert into "author" ("age", "email") values (33, 'foo@bar.com') on conflict ("email") do update set "age" = 41
748
- * // select "id" from "author" where "email" = 'foo@bar.com'
749
- * const author = await em.upsert(Author, { email: 'foo@bar.com', age: 33 });
750
- * ```
751
- *
752
- * Depending on the driver support, this will either use a returning query, or a separate select query, to fetch the primary key if it's missing from the `data`.
753
- *
754
- * If the entity is already present in current context, there won't be any queries - instead, the entity data will be assigned and an explicit `flush` will be required for those changes to be persisted.
755
- */
756
- async upsert(entityNameOrEntity, data, options = {}) {
757
- if (options.disableIdentityMap ?? this.config.get('disableIdentityMap')) {
758
- const em = this.getContext(false);
759
- const fork = em.fork({ keepTransactionContext: true });
760
- const ret = await fork.upsert(entityNameOrEntity, data, { ...options, disableIdentityMap: false });
761
- fork.clear();
762
- return ret;
763
- }
764
- const em = this.getContext(false);
765
- em.prepareOptions(options);
766
- let entityName;
767
- let where;
768
- let entity = null;
769
- if (data === undefined) {
770
- entityName = entityNameOrEntity.constructor;
771
- data = entityNameOrEntity;
772
- }
773
- else {
774
- entityName = entityNameOrEntity;
775
- }
776
- const meta = this.metadata.get(entityName);
777
- const convertCustomTypes = !Utils.isEntity(data);
778
- if (Utils.isEntity(data)) {
779
- entity = data;
780
- if (helper(entity).__managed && helper(entity).__em === em && !this.config.get('upsertManaged')) {
781
- em.#entityFactory.mergeData(meta, entity, data, { initialized: true });
782
- return entity;
783
- }
784
- where = helper(entity).getPrimaryKey();
785
- em.#entityFactory.assignDefaultValues(entity, meta);
786
- data = em.#comparator.prepareEntity(entity);
787
- }
788
- else {
789
- data = Utils.copy(QueryHelper.processParams(data));
790
- where = Utils.extractPK(data, meta);
791
- if (where && !this.config.get('upsertManaged')) {
792
- const exists = em.#unitOfWork.getById(entityName, where, options.schema);
793
- if (exists) {
794
- return em.assign(exists, data);
795
- }
796
- }
797
- em.#entityFactory.assignDefaultValues(data, meta, true);
798
- for (const key of Object.keys(data)) {
799
- const prop = meta.properties[key];
800
- if (prop?.persist === false) {
801
- delete data[key];
802
- }
803
- }
804
- }
805
- where = getWhereCondition(meta, options.onConflictFields, data, where).where;
806
- data = QueryHelper.processObjectParams(data);
807
- validateParams(data, 'insert data');
808
- if (em.eventManager.hasListeners(EventType.beforeUpsert, meta)) {
809
- await em.eventManager.dispatchEvent(EventType.beforeUpsert, { entity: data, em, meta }, meta);
810
- }
811
- const ret = await em.driver.nativeUpdate(entityName, where, data, {
812
- ctx: em.#transactionContext,
813
- upsert: true,
814
- convertCustomTypes,
815
- ...options,
800
+ }
801
+ where = helper(entity).getPrimaryKey();
802
+ em.#entityFactory.assignDefaultValues(entity, meta);
803
+ data = em.#comparator.prepareEntity(entity);
804
+ } else {
805
+ data = Utils.copy(QueryHelper.processParams(data));
806
+ where = Utils.extractPK(data, meta);
807
+ if (where && !this.config.get('upsertManaged')) {
808
+ const exists = em.#unitOfWork.getById(entityName, where, options.schema);
809
+ if (exists) {
810
+ return em.assign(exists, data);
811
+ }
812
+ }
813
+ em.#entityFactory.assignDefaultValues(data, meta, true);
814
+ for (const key of Object.keys(data)) {
815
+ const prop = meta.properties[key];
816
+ if (prop?.persist === false) {
817
+ delete data[key];
818
+ }
819
+ }
820
+ }
821
+ where = getWhereCondition(meta, options.onConflictFields, data, where).where;
822
+ data = QueryHelper.processObjectParams(data);
823
+ validateParams(data, 'insert data');
824
+ if (em.eventManager.hasListeners(EventType.beforeUpsert, meta)) {
825
+ await em.eventManager.dispatchEvent(EventType.beforeUpsert, { entity: data, em, meta }, meta);
826
+ }
827
+ const ret = await em.driver.nativeUpdate(entityName, where, data, {
828
+ ctx: em.#transactionContext,
829
+ upsert: true,
830
+ convertCustomTypes,
831
+ ...options,
832
+ });
833
+ em.#unitOfWork.getChangeSetPersister().mapReturnedValues(entity, data, ret.row, meta, true);
834
+ entity ??= em.#entityFactory.create(entityName, data, {
835
+ refresh: true,
836
+ initialized: true,
837
+ schema: options.schema,
838
+ });
839
+ const uniqueFields =
840
+ options.onConflictFields ?? (Utils.isPlainObject(where) ? Object.keys(where) : meta.primaryKeys);
841
+ const returning = getOnConflictReturningFields(meta, data, uniqueFields, options);
842
+ if (
843
+ options.onConflictAction === 'ignore' ||
844
+ !helper(entity).hasPrimaryKey() ||
845
+ (returning.length > 0 && !(this.getPlatform().usesReturningStatement() && ret.row))
846
+ ) {
847
+ const where = {};
848
+ if (Array.isArray(uniqueFields)) {
849
+ for (const prop of uniqueFields) {
850
+ if (data[prop] != null) {
851
+ where[prop] = data[prop];
852
+ } else if (meta.primaryKeys.includes(prop) && ret.insertId != null) {
853
+ where[prop] = ret.insertId;
854
+ }
855
+ }
856
+ } else {
857
+ Object.keys(data).forEach(prop => {
858
+ where[prop] = data[prop];
816
859
  });
817
- em.#unitOfWork.getChangeSetPersister().mapReturnedValues(entity, data, ret.row, meta, true);
818
- entity ??= em.#entityFactory.create(entityName, data, {
860
+ if (meta.simplePK && ret.insertId != null) {
861
+ where[meta.primaryKeys[0]] = ret.insertId;
862
+ }
863
+ }
864
+ const data2 = await this.driver.findOne(meta.class, where, {
865
+ fields: returning,
866
+ ctx: em.#transactionContext,
867
+ convertCustomTypes: true,
868
+ connectionType: 'write',
869
+ schema: options.schema,
870
+ });
871
+ em.getHydrator().hydrate(entity, meta, data2, em.#entityFactory, 'full', false, true);
872
+ }
873
+ // recompute the data as there might be some values missing (e.g. those with db column defaults)
874
+ const snapshot = this.#comparator.prepareEntity(entity);
875
+ em.#unitOfWork.register(entity, snapshot, { refresh: true });
876
+ if (em.eventManager.hasListeners(EventType.afterUpsert, meta)) {
877
+ await em.eventManager.dispatchEvent(EventType.afterUpsert, { entity, em, meta }, meta);
878
+ }
879
+ return entity;
880
+ }
881
+ /**
882
+ * Creates or updates the entity, based on whether it is already present in the database.
883
+ * This method performs an `insert on conflict merge` query ensuring the database is in sync, returning a managed
884
+ * entity instance. The method accepts either `entityName` together with the entity `data`, or just entity instance.
885
+ *
886
+ * ```ts
887
+ * // insert into "author" ("age", "email") values (33, 'foo@bar.com') on conflict ("email") do update set "age" = 41
888
+ * const authors = await em.upsertMany(Author, [{ email: 'foo@bar.com', age: 33 }, ...]);
889
+ * ```
890
+ *
891
+ * The entity data needs to contain either the primary key, or any other unique property. Let's consider the following example, where `Author.email` is a unique property:
892
+ *
893
+ * ```ts
894
+ * // insert into "author" ("age", "email") values (33, 'foo@bar.com'), (666, 'lol@lol.lol') on conflict ("email") do update set "age" = excluded."age"
895
+ * // select "id" from "author" where "email" = 'foo@bar.com'
896
+ * const author = await em.upsertMany(Author, [
897
+ * { email: 'foo@bar.com', age: 33 },
898
+ * { email: 'lol@lol.lol', age: 666 },
899
+ * ]);
900
+ * ```
901
+ *
902
+ * Depending on the driver support, this will either use a returning query, or a separate select query, to fetch the primary key if it's missing from the `data`.
903
+ *
904
+ * If the entity is already present in current context, there won't be any queries - instead, the entity data will be assigned and an explicit `flush` will be required for those changes to be persisted.
905
+ */
906
+ async upsertMany(entityNameOrEntity, data, options = {}) {
907
+ if (options.disableIdentityMap ?? this.config.get('disableIdentityMap')) {
908
+ const em = this.getContext(false);
909
+ const fork = em.fork({ keepTransactionContext: true });
910
+ const ret = await fork.upsertMany(entityNameOrEntity, data, { ...options, disableIdentityMap: false });
911
+ fork.clear();
912
+ return ret;
913
+ }
914
+ const em = this.getContext(false);
915
+ em.prepareOptions(options);
916
+ let entityName;
917
+ let propIndex;
918
+ if (data === undefined) {
919
+ entityName = entityNameOrEntity[0].constructor;
920
+ data = entityNameOrEntity;
921
+ } else {
922
+ entityName = entityNameOrEntity;
923
+ }
924
+ const batchSize = options.batchSize ?? this.config.get('batchSize');
925
+ if (data.length > batchSize) {
926
+ const ret = [];
927
+ for (let i = 0; i < data.length; i += batchSize) {
928
+ const chunk = data.slice(i, i + batchSize);
929
+ ret.push(...(await this.upsertMany(entityName, chunk, options)));
930
+ }
931
+ return ret;
932
+ }
933
+ const meta = this.metadata.get(entityName);
934
+ const convertCustomTypes = !Utils.isEntity(data[0]);
935
+ const allData = [];
936
+ const allWhere = [];
937
+ const entities = new Map();
938
+ const entitiesByData = new Map();
939
+ for (let i = 0; i < data.length; i++) {
940
+ let row = data[i];
941
+ let where;
942
+ if (Utils.isEntity(row)) {
943
+ const entity = row;
944
+ if (helper(entity).__managed && helper(entity).__em === em && !this.config.get('upsertManaged')) {
945
+ em.#entityFactory.mergeData(meta, entity, row, { initialized: true });
946
+ entities.set(entity, row);
947
+ entitiesByData.set(row, entity);
948
+ continue;
949
+ }
950
+ where = helper(entity).getPrimaryKey();
951
+ em.#entityFactory.assignDefaultValues(entity, meta);
952
+ row = em.#comparator.prepareEntity(entity);
953
+ } else {
954
+ row = data[i] = Utils.copy(QueryHelper.processParams(row));
955
+ where = Utils.extractPK(row, meta);
956
+ if (where && !this.config.get('upsertManaged')) {
957
+ const exists = em.#unitOfWork.getById(entityName, where, options.schema);
958
+ if (exists) {
959
+ em.assign(exists, row);
960
+ entities.set(exists, row);
961
+ entitiesByData.set(row, exists);
962
+ continue;
963
+ }
964
+ }
965
+ em.#entityFactory.assignDefaultValues(row, meta, true);
966
+ for (const key of Object.keys(row)) {
967
+ const prop = meta.properties[key];
968
+ if (prop?.persist === false) {
969
+ delete row[key];
970
+ }
971
+ }
972
+ }
973
+ const unique = options.onConflictFields ?? meta.props.filter(p => p.unique).map(p => p.name);
974
+ propIndex = !isRaw(unique) && unique.findIndex(p => data[p] ?? data[p.substring(0, p.indexOf('.'))] != null);
975
+ const tmp = getWhereCondition(meta, options.onConflictFields, row, where);
976
+ propIndex = tmp.propIndex;
977
+ where = QueryHelper.processWhere({
978
+ where: tmp.where,
979
+ entityName,
980
+ metadata: this.metadata,
981
+ platform: this.getPlatform(),
982
+ });
983
+ row = QueryHelper.processObjectParams(row);
984
+ validateParams(row, 'insert data');
985
+ allData.push(row);
986
+ allWhere.push(where);
987
+ }
988
+ if (entities.size === data.length) {
989
+ return [...entities.keys()];
990
+ }
991
+ if (em.eventManager.hasListeners(EventType.beforeUpsert, meta)) {
992
+ for (const dto of data) {
993
+ const entity = entitiesByData.get(dto) ?? dto;
994
+ await em.eventManager.dispatchEvent(EventType.beforeUpsert, { entity, em, meta }, meta);
995
+ }
996
+ }
997
+ const res = await em.driver.nativeUpdateMany(entityName, allWhere, allData, {
998
+ ctx: em.#transactionContext,
999
+ upsert: true,
1000
+ convertCustomTypes,
1001
+ ...options,
1002
+ });
1003
+ entities.clear();
1004
+ entitiesByData.clear();
1005
+ const loadPK = new Map();
1006
+ allData.forEach((row, i) => {
1007
+ em.#unitOfWork
1008
+ .getChangeSetPersister()
1009
+ .mapReturnedValues(
1010
+ Utils.isEntity(data[i]) ? data[i] : null,
1011
+ Utils.isEntity(data[i]) ? {} : data[i],
1012
+ res.rows?.[i],
1013
+ meta,
1014
+ true,
1015
+ );
1016
+ const entity = Utils.isEntity(data[i])
1017
+ ? data[i]
1018
+ : em.#entityFactory.create(entityName, row, {
819
1019
  refresh: true,
820
1020
  initialized: true,
821
1021
  schema: options.schema,
1022
+ });
1023
+ if (!helper(entity).hasPrimaryKey()) {
1024
+ loadPK.set(entity, allWhere[i]);
1025
+ }
1026
+ entities.set(entity, row);
1027
+ entitiesByData.set(row, entity);
1028
+ });
1029
+ // skip if we got the PKs via returning statement (`rows`)
1030
+ // oxfmt-ignore
1031
+ const uniqueFields = options.onConflictFields ?? (Utils.isPlainObject(allWhere[0]) ? Object.keys(allWhere[0]).flatMap(key => Utils.splitPrimaryKeys(key)) : meta.primaryKeys);
1032
+ const returning = getOnConflictReturningFields(meta, data[0], uniqueFields, options);
1033
+ const reloadFields = returning.length > 0 && !(this.getPlatform().usesReturningStatement() && res.rows?.length);
1034
+ if (options.onConflictAction === 'ignore' || (!res.rows?.length && loadPK.size > 0) || reloadFields) {
1035
+ const unique = meta.hydrateProps.filter(p => !p.lazy).map(p => p.name);
1036
+ const add = new Set(propIndex !== false && propIndex >= 0 ? [unique[propIndex]] : []);
1037
+ for (const cond of loadPK.values()) {
1038
+ Utils.keys(cond).forEach(key => add.add(key));
1039
+ }
1040
+ const where = { $or: [] };
1041
+ data.forEach((item, idx) => {
1042
+ where.$or[idx] = {};
1043
+ const props = Array.isArray(uniqueFields) ? uniqueFields : Object.keys(item);
1044
+ props.forEach(prop => {
1045
+ where.$or[idx][prop] = item[prop];
822
1046
  });
823
- const uniqueFields = options.onConflictFields ??
824
- (Utils.isPlainObject(where) ? Object.keys(where) : meta.primaryKeys);
825
- const returning = getOnConflictReturningFields(meta, data, uniqueFields, options);
826
- if (options.onConflictAction === 'ignore' ||
827
- !helper(entity).hasPrimaryKey() ||
828
- (returning.length > 0 && !(this.getPlatform().usesReturningStatement() && ret.row))) {
829
- const where = {};
830
- if (Array.isArray(uniqueFields)) {
831
- for (const prop of uniqueFields) {
832
- if (data[prop] != null) {
833
- where[prop] = data[prop];
834
- }
835
- else if (meta.primaryKeys.includes(prop) && ret.insertId != null) {
836
- where[prop] = ret.insertId;
837
- }
838
- }
839
- }
840
- else {
841
- Object.keys(data).forEach(prop => {
842
- where[prop] = data[prop];
843
- });
844
- if (meta.simplePK && ret.insertId != null) {
845
- where[meta.primaryKeys[0]] = ret.insertId;
846
- }
1047
+ });
1048
+ const data2 = await this.driver.find(meta.class, where, {
1049
+ fields: returning.concat(...add).concat(...(Array.isArray(uniqueFields) ? uniqueFields : [])),
1050
+ ctx: em.#transactionContext,
1051
+ convertCustomTypes: true,
1052
+ connectionType: 'write',
1053
+ schema: options.schema,
1054
+ });
1055
+ for (const [entity, cond] of loadPK.entries()) {
1056
+ const row = data2.find(row => {
1057
+ const tmp = {};
1058
+ add.forEach(k => {
1059
+ if (!meta.properties[k]?.primary) {
1060
+ tmp[k] = row[k];
847
1061
  }
848
- const data2 = await this.driver.findOne(meta.class, where, {
849
- fields: returning,
850
- ctx: em.#transactionContext,
851
- convertCustomTypes: true,
852
- connectionType: 'write',
853
- schema: options.schema,
854
- });
855
- em.getHydrator().hydrate(entity, meta, data2, em.#entityFactory, 'full', false, true);
856
- }
857
- // recompute the data as there might be some values missing (e.g. those with db column defaults)
858
- const snapshot = this.#comparator.prepareEntity(entity);
859
- em.#unitOfWork.register(entity, snapshot, { refresh: true });
860
- if (em.eventManager.hasListeners(EventType.afterUpsert, meta)) {
861
- await em.eventManager.dispatchEvent(EventType.afterUpsert, { entity, em, meta }, meta);
862
- }
863
- return entity;
864
- }
865
- /**
866
- * Creates or updates the entity, based on whether it is already present in the database.
867
- * This method performs an `insert on conflict merge` query ensuring the database is in sync, returning a managed
868
- * entity instance. The method accepts either `entityName` together with the entity `data`, or just entity instance.
869
- *
870
- * ```ts
871
- * // insert into "author" ("age", "email") values (33, 'foo@bar.com') on conflict ("email") do update set "age" = 41
872
- * const authors = await em.upsertMany(Author, [{ email: 'foo@bar.com', age: 33 }, ...]);
873
- * ```
874
- *
875
- * The entity data needs to contain either the primary key, or any other unique property. Let's consider the following example, where `Author.email` is a unique property:
876
- *
877
- * ```ts
878
- * // insert into "author" ("age", "email") values (33, 'foo@bar.com'), (666, 'lol@lol.lol') on conflict ("email") do update set "age" = excluded."age"
879
- * // select "id" from "author" where "email" = 'foo@bar.com'
880
- * const author = await em.upsertMany(Author, [
881
- * { email: 'foo@bar.com', age: 33 },
882
- * { email: 'lol@lol.lol', age: 666 },
883
- * ]);
884
- * ```
885
- *
886
- * Depending on the driver support, this will either use a returning query, or a separate select query, to fetch the primary key if it's missing from the `data`.
887
- *
888
- * If the entity is already present in current context, there won't be any queries - instead, the entity data will be assigned and an explicit `flush` will be required for those changes to be persisted.
889
- */
890
- async upsertMany(entityNameOrEntity, data, options = {}) {
891
- if (options.disableIdentityMap ?? this.config.get('disableIdentityMap')) {
892
- const em = this.getContext(false);
893
- const fork = em.fork({ keepTransactionContext: true });
894
- const ret = await fork.upsertMany(entityNameOrEntity, data, { ...options, disableIdentityMap: false });
895
- fork.clear();
896
- return ret;
897
- }
898
- const em = this.getContext(false);
899
- em.prepareOptions(options);
900
- let entityName;
901
- let propIndex;
902
- if (data === undefined) {
903
- entityName = entityNameOrEntity[0].constructor;
904
- data = entityNameOrEntity;
905
- }
906
- else {
907
- entityName = entityNameOrEntity;
908
- }
909
- const batchSize = options.batchSize ?? this.config.get('batchSize');
910
- if (data.length > batchSize) {
911
- const ret = [];
912
- for (let i = 0; i < data.length; i += batchSize) {
913
- const chunk = data.slice(i, i + batchSize);
914
- ret.push(...(await this.upsertMany(entityName, chunk, options)));
915
- }
916
- return ret;
917
- }
918
- const meta = this.metadata.get(entityName);
919
- const convertCustomTypes = !Utils.isEntity(data[0]);
920
- const allData = [];
921
- const allWhere = [];
922
- const entities = new Map();
923
- const entitiesByData = new Map();
924
- for (let i = 0; i < data.length; i++) {
925
- let row = data[i];
926
- let where;
927
- if (Utils.isEntity(row)) {
928
- const entity = row;
929
- if (helper(entity).__managed && helper(entity).__em === em && !this.config.get('upsertManaged')) {
930
- em.#entityFactory.mergeData(meta, entity, row, { initialized: true });
931
- entities.set(entity, row);
932
- entitiesByData.set(row, entity);
933
- continue;
934
- }
935
- where = helper(entity).getPrimaryKey();
936
- em.#entityFactory.assignDefaultValues(entity, meta);
937
- row = em.#comparator.prepareEntity(entity);
938
- }
939
- else {
940
- row = data[i] = Utils.copy(QueryHelper.processParams(row));
941
- where = Utils.extractPK(row, meta);
942
- if (where && !this.config.get('upsertManaged')) {
943
- const exists = em.#unitOfWork.getById(entityName, where, options.schema);
944
- if (exists) {
945
- em.assign(exists, row);
946
- entities.set(exists, row);
947
- entitiesByData.set(row, exists);
948
- continue;
949
- }
950
- }
951
- em.#entityFactory.assignDefaultValues(row, meta, true);
952
- for (const key of Object.keys(row)) {
953
- const prop = meta.properties[key];
954
- if (prop?.persist === false) {
955
- delete row[key];
956
- }
957
- }
958
- }
959
- const unique = options.onConflictFields ?? meta.props.filter(p => p.unique).map(p => p.name);
960
- propIndex =
961
- !isRaw(unique) &&
962
- unique.findIndex(p => data[p] ?? data[p.substring(0, p.indexOf('.'))] != null);
963
- const tmp = getWhereCondition(meta, options.onConflictFields, row, where);
964
- propIndex = tmp.propIndex;
965
- where = QueryHelper.processWhere({
966
- where: tmp.where,
967
- entityName,
968
- metadata: this.metadata,
969
- platform: this.getPlatform(),
970
- });
971
- row = QueryHelper.processObjectParams(row);
972
- validateParams(row, 'insert data');
973
- allData.push(row);
974
- allWhere.push(where);
975
- }
976
- if (entities.size === data.length) {
977
- return [...entities.keys()];
978
- }
979
- if (em.eventManager.hasListeners(EventType.beforeUpsert, meta)) {
980
- for (const dto of data) {
981
- const entity = entitiesByData.get(dto) ?? dto;
982
- await em.eventManager.dispatchEvent(EventType.beforeUpsert, { entity, em, meta }, meta);
983
- }
984
- }
985
- const res = await em.driver.nativeUpdateMany(entityName, allWhere, allData, {
986
- ctx: em.#transactionContext,
987
- upsert: true,
988
- convertCustomTypes,
989
- ...options,
990
- });
991
- entities.clear();
992
- entitiesByData.clear();
993
- const loadPK = new Map();
994
- allData.forEach((row, i) => {
995
- em.#unitOfWork
996
- .getChangeSetPersister()
997
- .mapReturnedValues(Utils.isEntity(data[i]) ? data[i] : null, Utils.isEntity(data[i]) ? {} : data[i], res.rows?.[i], meta, true);
998
- const entity = Utils.isEntity(data[i])
999
- ? data[i]
1000
- : em.#entityFactory.create(entityName, row, {
1001
- refresh: true,
1002
- initialized: true,
1003
- schema: options.schema,
1004
- });
1005
- if (!helper(entity).hasPrimaryKey()) {
1006
- loadPK.set(entity, allWhere[i]);
1007
- }
1008
- entities.set(entity, row);
1009
- entitiesByData.set(row, entity);
1010
- });
1011
- // skip if we got the PKs via returning statement (`rows`)
1012
- // oxfmt-ignore
1013
- const uniqueFields = options.onConflictFields ?? (Utils.isPlainObject(allWhere[0]) ? Object.keys(allWhere[0]).flatMap(key => Utils.splitPrimaryKeys(key)) : meta.primaryKeys);
1014
- const returning = getOnConflictReturningFields(meta, data[0], uniqueFields, options);
1015
- const reloadFields = returning.length > 0 && !(this.getPlatform().usesReturningStatement() && res.rows?.length);
1016
- if (options.onConflictAction === 'ignore' || (!res.rows?.length && loadPK.size > 0) || reloadFields) {
1017
- const unique = meta.hydrateProps.filter(p => !p.lazy).map(p => p.name);
1018
- const add = new Set(propIndex !== false && propIndex >= 0
1019
- ? [unique[propIndex]]
1020
- : []);
1021
- for (const cond of loadPK.values()) {
1022
- Utils.keys(cond).forEach(key => add.add(key));
1023
- }
1024
- const where = { $or: [] };
1025
- data.forEach((item, idx) => {
1026
- where.$or[idx] = {};
1027
- const props = Array.isArray(uniqueFields) ? uniqueFields : Object.keys(item);
1028
- props.forEach(prop => {
1029
- where.$or[idx][prop] = item[prop];
1030
- });
1031
- });
1032
- const data2 = await this.driver.find(meta.class, where, {
1033
- fields: returning
1034
- .concat(...add)
1035
- .concat(...(Array.isArray(uniqueFields) ? uniqueFields : [])),
1036
- ctx: em.#transactionContext,
1037
- convertCustomTypes: true,
1038
- connectionType: 'write',
1039
- schema: options.schema,
1040
- });
1041
- for (const [entity, cond] of loadPK.entries()) {
1042
- const row = data2.find(row => {
1043
- const tmp = {};
1044
- add.forEach(k => {
1045
- if (!meta.properties[k]?.primary) {
1046
- tmp[k] = row[k];
1047
- }
1048
- });
1049
- return this.#comparator.matching(entityName, cond, tmp);
1050
- });
1051
- /* v8 ignore next */
1052
- if (!row) {
1053
- throw new Error(`Cannot find matching entity for condition ${JSON.stringify(cond)}`);
1054
- }
1055
- em.getHydrator().hydrate(entity, meta, row, em.#entityFactory, 'full', false, true);
1056
- }
1057
- if (loadPK.size !== data2.length && Array.isArray(uniqueFields)) {
1058
- for (let i = 0; i < allData.length; i++) {
1059
- const data = allData[i];
1060
- const cond = uniqueFields.reduce((a, b) => {
1061
- // @ts-ignore
1062
- a[b] = data[b];
1063
- return a;
1064
- }, {});
1065
- const entity = entitiesByData.get(data);
1066
- const row = data2.find(item => {
1067
- const pk = uniqueFields.reduce((a, b) => {
1068
- // @ts-ignore
1069
- a[b] = item[b];
1070
- return a;
1071
- }, {});
1072
- return this.#comparator.matching(entityName, cond, pk);
1073
- });
1074
- /* v8 ignore next */
1075
- if (!row) {
1076
- throw new Error(`Cannot find matching entity for condition ${JSON.stringify(cond)}`);
1077
- }
1078
- em.getHydrator().hydrate(entity, meta, row, em.#entityFactory, 'full');
1079
- }
1080
- }
1081
- }
1082
- for (const [entity] of entities) {
1083
- // recompute the data as there might be some values missing (e.g. those with db column defaults)
1084
- const snapshot = this.#comparator.prepareEntity(entity);
1085
- em.#unitOfWork.register(entity, snapshot, { refresh: true });
1086
- }
1087
- if (em.eventManager.hasListeners(EventType.afterUpsert, meta)) {
1088
- for (const [entity] of entities) {
1089
- await em.eventManager.dispatchEvent(EventType.afterUpsert, { entity, em, meta }, meta);
1090
- }
1091
- }
1092
- return [...entities.keys()];
1093
- }
1094
- /**
1095
- * Runs your callback wrapped inside a database transaction.
1096
- *
1097
- * If a transaction is already active, a new savepoint (nested transaction) will be created by default. This behavior
1098
- * can be controlled via the `propagation` option. Use the provided EntityManager instance for all operations that
1099
- * should be part of the transaction. You can safely use a global EntityManager instance from a DI container, as this
1100
- * method automatically creates an async context for the transaction.
1101
- *
1102
- * **Concurrency note:** When running multiple transactions concurrently (e.g. in parallel requests or jobs), use the
1103
- * `clear: true` option. This ensures the callback runs in a clear fork of the EntityManager, providing full isolation
1104
- * between concurrent transactional handlers. Using `clear: true` is an alternative to forking explicitly and calling
1105
- * the method on the new fork – it already provides the necessary isolation for safe concurrent usage.
1106
- *
1107
- * **Propagation note:** Changes made within a transaction (whether top-level or nested) are always propagated to the
1108
- * parent context, unless the parent context is a global one. If you want to avoid that, fork the EntityManager first
1109
- * and then call this method on the fork.
1110
- *
1111
- * **Example:**
1112
- * ```ts
1113
- * await em.transactional(async (em) => {
1114
- * const author = new Author('Jon');
1115
- * em.persist(author);
1116
- * // flush is called automatically at the end of the callback
1117
- * });
1118
- * ```
1119
- */
1120
- async transactional(cb, options = {}) {
1121
- const em = this.getContext(false);
1122
- if (this.#disableTransactions || em.#disableTransactions) {
1123
- return cb(em);
1124
- }
1125
- const manager = new TransactionManager(this);
1126
- return manager.handle(cb, options);
1127
- }
1128
- /**
1129
- * Starts new transaction bound to this EntityManager. Use `ctx` parameter to provide the parent when nesting transactions.
1130
- */
1131
- async begin(options = {}) {
1132
- if (this.#disableTransactions) {
1133
- return;
1134
- }
1135
- const em = this.getContext(false);
1136
- em.#transactionContext = await em.getConnection('write').begin({
1137
- ...options,
1138
- eventBroadcaster: new TransactionEventBroadcaster(em, { topLevelTransaction: !options.ctx }),
1062
+ });
1063
+ return this.#comparator.matching(entityName, cond, tmp);
1139
1064
  });
1140
- }
1141
- /**
1142
- * Commits the transaction bound to this EntityManager. Flushes before doing the actual commit query.
1143
- */
1144
- async commit() {
1145
- const em = this.getContext(false);
1146
- if (this.#disableTransactions) {
1147
- await em.flush();
1148
- return;
1149
- }
1150
- if (!em.#transactionContext) {
1151
- throw ValidationError.transactionRequired();
1152
- }
1153
- await em.flush();
1154
- await em.getConnection('write').commit(em.#transactionContext, new TransactionEventBroadcaster(em));
1155
- em.#transactionContext = undefined;
1156
- }
1157
- /**
1158
- * Rollbacks the transaction bound to this EntityManager.
1159
- */
1160
- async rollback() {
1161
- if (this.#disableTransactions) {
1162
- return;
1163
- }
1164
- const em = this.getContext(false);
1165
- if (!em.#transactionContext) {
1166
- throw ValidationError.transactionRequired();
1167
- }
1168
- await em.getConnection('write').rollback(em.#transactionContext, new TransactionEventBroadcaster(em));
1169
- em.#transactionContext = undefined;
1170
- em.#unitOfWork.clearActionsQueue();
1171
- }
1172
- /**
1173
- * Runs your callback wrapped inside a database transaction.
1174
- */
1175
- async lock(entity, lockMode, options = {}) {
1176
- options = Utils.isPlainObject(options) ? options : { lockVersion: options };
1177
- await this.getUnitOfWork().lock(entity, { lockMode, ...options });
1178
- }
1179
- /**
1180
- * Fires native insert query. Calling this has no side effects on the context (identity map).
1181
- */
1182
- async insert(entityNameOrEntity, data, options = {}) {
1183
- const em = this.getContext(false);
1184
- em.prepareOptions(options);
1185
- let entityName;
1186
- if (data === undefined) {
1187
- entityName = entityNameOrEntity.constructor;
1188
- data = entityNameOrEntity;
1189
- }
1190
- else {
1191
- entityName = entityNameOrEntity;
1192
- }
1193
- if (Utils.isEntity(data)) {
1194
- if (options.schema && helper(data).getSchema() == null) {
1195
- helper(data).setSchema(options.schema);
1196
- }
1197
- if (!helper(data).__managed) {
1198
- em.#unitOfWork.unsetIdentity(data);
1199
- }
1200
- const meta = helper(data).__meta;
1201
- const payload = em.#comparator.prepareEntity(data);
1202
- const cs = new ChangeSet(data, ChangeSetType.CREATE, payload, meta);
1203
- await em.#unitOfWork.getChangeSetPersister().executeInserts([cs], { ctx: em.#transactionContext, ...options });
1204
- return cs.getPrimaryKey();
1205
- }
1206
- data = QueryHelper.processObjectParams(data);
1207
- validateParams(data, 'insert data');
1208
- const res = await em.driver.nativeInsert(entityName, data, {
1209
- ctx: em.#transactionContext,
1210
- ...options,
1211
- });
1212
- return res.insertId;
1213
- }
1214
- /**
1215
- * Fires native multi-insert query. Calling this has no side effects on the context (identity map).
1216
- */
1217
- async insertMany(entityNameOrEntities, data, options = {}) {
1218
- const em = this.getContext(false);
1219
- em.prepareOptions(options);
1220
- let entityName;
1221
- if (data === undefined) {
1222
- entityName = entityNameOrEntities[0].constructor;
1223
- data = entityNameOrEntities;
1224
- }
1225
- else {
1226
- entityName = entityNameOrEntities;
1227
- }
1228
- if (data.length === 0) {
1229
- return [];
1230
- }
1231
- if (Utils.isEntity(data[0])) {
1232
- const meta = helper(data[0]).__meta;
1233
- const css = data.map(row => {
1234
- if (options.schema && helper(row).getSchema() == null) {
1235
- helper(row).setSchema(options.schema);
1236
- }
1237
- if (!helper(row).__managed) {
1238
- em.#unitOfWork.unsetIdentity(row);
1239
- }
1240
- const payload = em.#comparator.prepareEntity(row);
1241
- return new ChangeSet(row, ChangeSetType.CREATE, payload, meta);
1242
- });
1243
- await em.#unitOfWork.getChangeSetPersister().executeInserts(css, { ctx: em.#transactionContext, ...options });
1244
- return css.map(cs => cs.getPrimaryKey());
1245
- }
1246
- data = data.map(row => QueryHelper.processObjectParams(row));
1247
- data.forEach(row => validateParams(row, 'insert data'));
1248
- const res = await em.driver.nativeInsertMany(entityName, data, {
1249
- ctx: em.#transactionContext,
1250
- ...options,
1251
- });
1252
- if (res.insertedIds) {
1253
- return res.insertedIds;
1254
- }
1255
- return [res.insertId];
1256
- }
1257
- /**
1258
- * Fires native update query. Calling this has no side effects on the context (identity map).
1259
- */
1260
- async nativeUpdate(entityName, where, data, options = {}) {
1261
- const em = this.getContext(false);
1262
- em.prepareOptions(options);
1263
- await em.processUnionWhere(entityName, options, 'update');
1264
- data = QueryHelper.processObjectParams(data);
1265
- where = await em.processWhere(entityName, where, { ...options, convertCustomTypes: false }, 'update');
1266
- validateParams(data, 'update data');
1267
- validateParams(where, 'update condition');
1268
- const res = await em.driver.nativeUpdate(entityName, where, data, {
1269
- ctx: em.#transactionContext,
1270
- em,
1271
- ...options,
1272
- });
1273
- return res.affectedRows;
1274
- }
1275
- /**
1276
- * Fires native delete query. Calling this has no side effects on the context (identity map).
1277
- */
1278
- async nativeDelete(entityName, where, options = {}) {
1279
- const em = this.getContext(false);
1280
- em.prepareOptions(options);
1281
- await em.processUnionWhere(entityName, options, 'delete');
1282
- where = (await em.processWhere(entityName, where, options, 'delete'));
1283
- validateParams(where, 'delete condition');
1284
- const res = await em.driver.nativeDelete(entityName, where, {
1285
- ctx: em.#transactionContext,
1286
- em,
1287
- ...options,
1288
- });
1289
- return res.affectedRows;
1290
- }
1291
- /**
1292
- * Maps raw database result to an entity and merges it to this EntityManager.
1293
- */
1294
- map(entityName, result, options = {}) {
1295
- const { mapped, ...rest } = options;
1296
- const meta = this.metadata.get(entityName);
1297
- const data = (mapped ? result : this.driver.mapResult(result, meta));
1298
- for (const k of Object.keys(data)) {
1299
- const prop = meta.properties[k];
1300
- if (prop?.kind === ReferenceKind.SCALAR &&
1301
- SCALAR_TYPES.has(prop.runtimeType) &&
1302
- !prop.customType &&
1303
- (prop.setter || !prop.getter)) {
1304
- validateProperty(prop, data[k], data);
1305
- }
1306
- }
1307
- return this.merge(entityName, data, {
1308
- convertCustomTypes: true,
1309
- refresh: true,
1310
- validate: false,
1311
- ...rest,
1312
- });
1313
- }
1314
- /**
1315
- * Merges given entity to this EntityManager so it becomes managed. You can force refreshing of existing entities
1316
- * via second parameter. By default, it will return already loaded entities without modifying them.
1317
- */
1318
- merge(entityName, data, options = {}) {
1319
- if (Utils.isEntity(entityName)) {
1320
- return this.merge(entityName.constructor, entityName, data);
1321
- }
1322
- const em = options.disableContextResolution ? this : this.getContext();
1323
- options.schema ??= em.#schema;
1324
- options.validate ??= true;
1325
- options.cascade ??= true;
1326
- validatePrimaryKey(data, em.metadata.get(entityName));
1327
- let entity = em.#unitOfWork.tryGetById(entityName, data, options.schema, false);
1328
- if (entity && helper(entity).__managed && helper(entity).__initialized && !options.refresh) {
1329
- return entity;
1330
- }
1331
- const dataIsEntity = Utils.isEntity(data);
1332
- entity = dataIsEntity
1333
- ? data
1334
- : em.#entityFactory.create(entityName, data, { merge: true, ...options });
1335
- const visited = options.cascade ? undefined : new Set([entity]);
1336
- em.#unitOfWork.merge(entity, visited);
1337
- return entity;
1338
- }
1339
- /**
1340
- * Creates new instance of given entity and populates it with given data.
1341
- * The entity constructor will be used unless you provide `{ managed: true }` in the `options` parameter.
1342
- * The constructor will be given parameters based on the defined constructor of the entity. If the constructor
1343
- * parameter matches a property name, its value will be extracted from `data`. If no matching property exists,
1344
- * the whole `data` parameter will be passed. This means we can also define `constructor(data: Partial<T>)` and
1345
- * `em.create()` will pass the data into it (unless we have a property named `data` too).
1346
- *
1347
- * The parameters are strictly checked, you need to provide all required properties. You can use `OptionalProps`
1348
- * symbol to omit some properties from this check without making them optional. Alternatively, use `partial: true`
1349
- * in the options to disable the strict checks for required properties. This option has no effect on runtime.
1350
- *
1351
- * The newly created entity will be automatically marked for persistence via `em.persist` unless you disable this
1352
- * behavior, either locally via `persist: false` option, or globally via `persistOnCreate` ORM config option.
1353
- */
1354
- create(entityName, data, options = {}) {
1355
- const em = this.getContext();
1356
- options.schema ??= em.#schema;
1357
- const entity = em.#entityFactory.create(entityName, data, {
1358
- ...options,
1359
- newEntity: !options.managed,
1360
- merge: options.managed,
1361
- normalizeAccessors: true,
1362
- });
1363
- options.persist ??= em.config.get('persistOnCreate');
1364
- if (options.persist && !this.getMetadata(entityName).embeddable) {
1365
- em.persist(entity);
1366
- }
1367
- return entity;
1368
- }
1369
- /**
1370
- * Shortcut for `wrap(entity).assign(data, { em })`
1371
- */
1372
- assign(entity, data, options = {}) {
1373
- return EntityAssigner.assign(entity, data, { em: this.getContext(), ...options });
1374
- }
1375
- /**
1376
- * Gets a reference to the entity identified by the given type and identifier without actually loading it, if the entity is not yet loaded
1377
- */
1378
- getReference(entityName, id, options = {}) {
1379
- options.schema ??= this.schema;
1380
- options.convertCustomTypes ??= false;
1381
- const meta = this.metadata.get(entityName);
1382
- if (Utils.isPrimaryKey(id)) {
1383
- if (meta.compositePK) {
1384
- throw ValidationError.invalidCompositeIdentifier(meta);
1385
- }
1386
- id = [id];
1387
- }
1388
- const entity = this.getEntityFactory().createReference(entityName, id, { merge: true, ...options });
1389
- if (options.wrapped) {
1390
- return Reference.create(entity);
1391
- }
1392
- return entity;
1393
- }
1394
- /**
1395
- * Returns total number of entities matching your `where` query.
1396
- */
1397
- async count(entityName, where = {}, options = {}) {
1398
- const em = this.getContext(false);
1399
- // Shallow copy options since the object will be modified when deleting orderBy
1400
- options = { ...options };
1401
- em.prepareOptions(options);
1402
- await em.tryFlush(entityName, options);
1403
- where = await em.processWhere(entityName, where, options, 'read');
1404
- options.populate = (await em.preparePopulate(entityName, options));
1405
- options = { ...options };
1406
- // save the original hint value so we know it was infer/all
1407
- const meta = em.metadata.find(entityName);
1408
- options._populateWhere = options.populateWhere ?? this.config.get('populateWhere');
1409
- options.populateWhere = this.createPopulateWhere({ ...where }, options);
1410
- options.populateFilter = await this.getJoinedFilters(meta, options);
1411
- validateParams(where);
1412
- delete options.orderBy;
1413
- await em.processUnionWhere(entityName, options, 'read');
1414
- const cacheKey = em.cacheKey(entityName, options, 'em.count', where);
1415
- const cached = await em.tryCache(entityName, options.cache, cacheKey);
1416
- if (cached?.data !== undefined) {
1417
- return cached.data;
1418
- }
1419
- const count = await em.driver.count(entityName, where, { ctx: em.#transactionContext, em, ...options });
1420
- await em.storeCache(options.cache, cached, () => +count);
1421
- return +count;
1422
- }
1423
- /**
1424
- * Tells the EntityManager to make an instance managed and persistent.
1425
- * The entity will be entered into the database at or before transaction commit or as a result of the flush operation.
1426
- */
1427
- persist(entity) {
1428
- const em = this.getContext();
1429
- if (Utils.isEntity(entity)) {
1430
- // do not cascade just yet, cascading of entities in persist stack is done when flushing
1431
- em.#unitOfWork.persist(entity, undefined, { cascade: false });
1432
- return em;
1433
- }
1434
- const entities = Utils.asArray(entity);
1435
- for (const ent of entities) {
1436
- if (!Utils.isEntity(ent, true)) {
1437
- /* v8 ignore next */
1438
- const meta = typeof ent === 'object' ? em.metadata.find(ent.constructor) : undefined;
1439
- throw ValidationError.notDiscoveredEntity(ent, meta);
1440
- }
1441
- // do not cascade just yet, cascading of entities in persist stack is done when flushing
1442
- em.#unitOfWork.persist(Reference.unwrapReference(ent), undefined, { cascade: false });
1443
- }
1444
- return this;
1445
- }
1446
- /**
1447
- * Marks entity for removal.
1448
- * A removed entity will be removed from the database at or before transaction commit or as a result of the flush operation.
1449
- *
1450
- * To remove entities by condition, use `em.nativeDelete()`.
1451
- */
1452
- remove(entity) {
1453
- const em = this.getContext();
1454
- if (Utils.isEntity(entity)) {
1455
- // do not cascade just yet, cascading of entities in persist stack is done when flushing
1456
- em.#unitOfWork.remove(entity, undefined, { cascade: false });
1457
- return em;
1458
- }
1459
- const entities = Utils.asArray(entity, true);
1460
- for (const ent of entities) {
1461
- if (!Utils.isEntity(ent, true)) {
1462
- throw new Error(`You need to pass entity instance or reference to 'em.remove()'. To remove entities by condition, use 'em.nativeDelete()'.`);
1463
- }
1464
- // do not cascade just yet, cascading of entities in remove stack is done when flushing
1465
- em.#unitOfWork.remove(Reference.unwrapReference(ent), undefined, { cascade: false });
1466
- }
1467
- return em;
1468
- }
1469
- /**
1470
- * Flushes all changes to objects that have been queued up to now to the database.
1471
- * This effectively synchronizes the in-memory state of managed objects with the database.
1472
- */
1473
- async flush() {
1474
- await this.getUnitOfWork().commit();
1475
- }
1476
- /**
1477
- * @internal
1478
- */
1479
- async tryFlush(entityName, options) {
1480
- const em = this.getContext();
1481
- const flushMode = options.flushMode ?? em.#flushMode ?? em.config.get('flushMode');
1482
- const meta = em.metadata.get(entityName);
1483
- if (flushMode === FlushMode.COMMIT) {
1484
- return;
1485
- }
1486
- if (flushMode === FlushMode.ALWAYS || em.getUnitOfWork().shouldAutoFlush(meta)) {
1487
- await em.flush();
1488
- }
1489
- }
1490
- /**
1491
- * Clears the EntityManager. All entities that are currently managed by this EntityManager become detached.
1492
- */
1493
- clear() {
1494
- this.getContext().#unitOfWork.clear();
1495
- }
1496
- /**
1497
- * Checks whether given property can be populated on the entity.
1498
- */
1499
- canPopulate(entityName, property) {
1500
- // eslint-disable-next-line prefer-const
1501
- let [p, ...parts] = property.split('.');
1502
- const meta = this.metadata.find(entityName);
1503
- if (!meta) {
1504
- return true;
1505
- }
1506
- if (p.includes(':')) {
1507
- p = p.split(':', 2)[0];
1508
- }
1509
- // For TPT inheritance, check the entity's own properties, not just the root's
1510
- // For STI, meta.properties includes all properties anyway
1511
- const ret = p in meta.properties;
1512
- if (parts.length > 0) {
1513
- return this.canPopulate(meta.properties[p].targetMeta.class, parts.join('.'));
1514
- }
1515
- return ret;
1516
- }
1517
- /**
1518
- * Loads specified relations in batch. This will execute one query for each relation, that will populate it on all the specified entities.
1519
- */
1520
- async populate(entities, populate, options = {}) {
1521
- const arr = Utils.asArray(entities);
1522
- if (arr.length === 0) {
1523
- return entities;
1524
- }
1525
- const em = this.getContext();
1526
- em.prepareOptions(options);
1527
- const entityName = arr[0].constructor;
1528
- const preparedPopulate = await em.preparePopulate(entityName, { populate: populate, filters: options.filters }, options.validate);
1529
- await em.#entityLoader.populate(entityName, arr, preparedPopulate, options);
1530
- return entities;
1531
- }
1532
- /**
1533
- * Returns new EntityManager instance with its own identity map
1534
- */
1535
- fork(options = {}) {
1536
- const em = options.disableContextResolution ? this : this.getContext(false);
1537
- options.clear ??= true;
1538
- options.useContext ??= false;
1539
- options.freshEventManager ??= false;
1540
- options.cloneEventManager ??= false;
1541
- const eventManager = options.freshEventManager
1542
- ? new EventManager(em.config.get('subscribers'))
1543
- : options.cloneEventManager
1544
- ? em.eventManager.clone()
1545
- : em.eventManager;
1546
- // we need to allow global context here as forking from global EM is fine
1547
- const allowGlobalContext = em.config.get('allowGlobalContext');
1548
- em.config.set('allowGlobalContext', true);
1549
- const fork = new em.constructor(em.config, em.driver, em.metadata, options.useContext, eventManager);
1550
- fork.setFlushMode(options.flushMode ?? em.#flushMode);
1551
- fork.#disableTransactions =
1552
- options.disableTransactions ?? this.#disableTransactions ?? this.config.get('disableTransactions');
1553
- em.config.set('allowGlobalContext', allowGlobalContext);
1554
- if (options.keepTransactionContext) {
1555
- fork.#transactionContext = em.#transactionContext;
1556
- }
1557
- fork.#filters = { ...em.#filters };
1558
- fork.#filterParams = Utils.copy(em.#filterParams);
1559
- fork.loggerContext = Utils.merge({}, em.loggerContext, options.loggerContext);
1560
- fork.#schema = options.schema ?? em.#schema;
1561
- if (!options.clear) {
1562
- for (const entity of em.#unitOfWork.getIdentityMap()) {
1563
- fork.#unitOfWork.register(entity);
1564
- }
1565
- for (const entity of em.#unitOfWork.getPersistStack()) {
1566
- fork.#unitOfWork.persist(entity);
1567
- }
1568
- for (const entity of em.#unitOfWork.getOrphanRemoveStack()) {
1569
- fork.#unitOfWork.getOrphanRemoveStack().add(entity);
1570
- }
1571
- }
1572
- return fork;
1573
- }
1574
- /**
1575
- * Gets the UnitOfWork used by the EntityManager to coordinate operations.
1576
- */
1577
- getUnitOfWork(useContext = true) {
1578
- if (!useContext) {
1579
- return this.#unitOfWork;
1580
- }
1581
- return this.getContext().#unitOfWork;
1582
- }
1583
- /**
1584
- * Gets the EntityFactory used by the EntityManager.
1585
- */
1586
- getEntityFactory() {
1587
- return this.getContext().#entityFactory;
1588
- }
1589
- /**
1590
- * @internal use `em.populate()` as the user facing API, this is exposed only for internal usage
1591
- */
1592
- getEntityLoader() {
1593
- return this.getContext().#entityLoader;
1594
- }
1595
- /**
1596
- * Gets the Hydrator used by the EntityManager.
1597
- */
1598
- getHydrator() {
1599
- return this.config.getHydrator(this.getMetadata());
1600
- }
1601
- /**
1602
- * Gets the EntityManager based on current transaction/request context.
1603
- * @internal
1604
- */
1605
- getContext(validate = true) {
1606
- if (!this.#useContext) {
1607
- return this;
1608
- }
1609
- let em = TransactionContext.getEntityManager(this.name); // prefer the tx context
1610
- if (em) {
1611
- return em;
1612
- }
1613
- // no explicit tx started
1614
- em = this.config.get('context')(this.name) ?? this;
1615
- if (validate && !this.config.get('allowGlobalContext') && em.global) {
1616
- throw ValidationError.cannotUseGlobalContext();
1617
- }
1618
- return em;
1619
- }
1620
- /** Gets the EventManager instance used by this EntityManager. */
1621
- getEventManager() {
1622
- return this.eventManager;
1623
- }
1624
- /**
1625
- * Checks whether this EntityManager is currently operating inside a database transaction.
1626
- */
1627
- isInTransaction() {
1628
- return !!this.getContext(false).#transactionContext;
1629
- }
1630
- /**
1631
- * Gets the transaction context (driver dependent object used to make sure queries are executed on same connection).
1632
- */
1633
- getTransactionContext() {
1634
- return this.getContext(false).#transactionContext;
1635
- }
1636
- /**
1637
- * Sets the transaction context.
1638
- */
1639
- setTransactionContext(ctx) {
1640
- if (!ctx) {
1641
- this.resetTransactionContext();
1642
- }
1643
- else {
1644
- this.getContext(false).#transactionContext = ctx;
1645
- }
1646
- }
1647
- /**
1648
- * Resets the transaction context.
1649
- */
1650
- resetTransactionContext() {
1651
- this.getContext(false).#transactionContext = undefined;
1652
- }
1653
- /**
1654
- * Gets the `MetadataStorage` (without parameters) or `EntityMetadata` instance when provided with the `entityName` parameter.
1655
- */
1656
- getMetadata(entityName) {
1657
- if (entityName) {
1658
- return this.metadata.get(entityName);
1659
- }
1660
- return this.metadata;
1661
- }
1662
- /**
1663
- * Gets the EntityComparator.
1664
- */
1665
- getComparator() {
1666
- return this.#comparator;
1667
- }
1668
- checkLockRequirements(mode, meta) {
1669
- if (!mode) {
1670
- return;
1671
- }
1672
- if (mode === LockMode.OPTIMISTIC && !meta.versionProperty) {
1673
- throw OptimisticLockError.notVersioned(meta);
1674
- }
1675
- if ([LockMode.PESSIMISTIC_READ, LockMode.PESSIMISTIC_WRITE].includes(mode) && !this.isInTransaction()) {
1676
- throw ValidationError.transactionRequired();
1677
- }
1678
- }
1679
- async lockAndPopulate(meta, entity, where, options) {
1680
- if (!meta.virtual && options.lockMode === LockMode.OPTIMISTIC) {
1681
- await this.lock(entity, options.lockMode, {
1682
- lockVersion: options.lockVersion,
1683
- lockTableAliases: options.lockTableAliases,
1684
- });
1685
- }
1686
- const preparedPopulate = await this.preparePopulate(meta.class, options);
1687
- await this.#entityLoader.populate(meta.class, [entity], preparedPopulate, {
1688
- ...options,
1689
- ...this.getPopulateWhere(where, options),
1690
- orderBy: options.populateOrderBy ?? options.orderBy,
1691
- ignoreLazyScalarProperties: true,
1692
- lookup: false,
1693
- });
1694
- return entity;
1695
- }
1696
- buildFields(fields) {
1697
- return fields.reduce((ret, f) => {
1698
- if (Utils.isPlainObject(f)) {
1699
- Utils.keys(f).forEach(ff => ret.push(...this.buildFields(f[ff]).map(field => `${ff}.${field}`)));
1700
- }
1701
- else {
1702
- ret.push(f);
1703
- }
1704
- return ret;
1705
- }, []);
1706
- }
1707
- /** @internal */
1708
- async preparePopulate(entityName, options, validate = true) {
1709
- if (options.populate === false) {
1065
+ /* v8 ignore next */
1066
+ if (!row) {
1067
+ throw new Error(`Cannot find matching entity for condition ${JSON.stringify(cond)}`);
1068
+ }
1069
+ em.getHydrator().hydrate(entity, meta, row, em.#entityFactory, 'full', false, true);
1070
+ }
1071
+ if (loadPK.size !== data2.length && Array.isArray(uniqueFields)) {
1072
+ for (let i = 0; i < allData.length; i++) {
1073
+ const data = allData[i];
1074
+ const cond = uniqueFields.reduce((a, b) => {
1075
+ // @ts-ignore
1076
+ a[b] = data[b];
1077
+ return a;
1078
+ }, {});
1079
+ const entity = entitiesByData.get(data);
1080
+ const row = data2.find(item => {
1081
+ const pk = uniqueFields.reduce((a, b) => {
1082
+ // @ts-ignore
1083
+ a[b] = item[b];
1084
+ return a;
1085
+ }, {});
1086
+ return this.#comparator.matching(entityName, cond, pk);
1087
+ });
1088
+ /* v8 ignore next */
1089
+ if (!row) {
1090
+ throw new Error(`Cannot find matching entity for condition ${JSON.stringify(cond)}`);
1091
+ }
1092
+ em.getHydrator().hydrate(entity, meta, row, em.#entityFactory, 'full');
1093
+ }
1094
+ }
1095
+ }
1096
+ for (const [entity] of entities) {
1097
+ // recompute the data as there might be some values missing (e.g. those with db column defaults)
1098
+ const snapshot = this.#comparator.prepareEntity(entity);
1099
+ em.#unitOfWork.register(entity, snapshot, { refresh: true });
1100
+ }
1101
+ if (em.eventManager.hasListeners(EventType.afterUpsert, meta)) {
1102
+ for (const [entity] of entities) {
1103
+ await em.eventManager.dispatchEvent(EventType.afterUpsert, { entity, em, meta }, meta);
1104
+ }
1105
+ }
1106
+ return [...entities.keys()];
1107
+ }
1108
+ /**
1109
+ * Runs your callback wrapped inside a database transaction.
1110
+ *
1111
+ * If a transaction is already active, a new savepoint (nested transaction) will be created by default. This behavior
1112
+ * can be controlled via the `propagation` option. Use the provided EntityManager instance for all operations that
1113
+ * should be part of the transaction. You can safely use a global EntityManager instance from a DI container, as this
1114
+ * method automatically creates an async context for the transaction.
1115
+ *
1116
+ * **Concurrency note:** When running multiple transactions concurrently (e.g. in parallel requests or jobs), use the
1117
+ * `clear: true` option. This ensures the callback runs in a clear fork of the EntityManager, providing full isolation
1118
+ * between concurrent transactional handlers. Using `clear: true` is an alternative to forking explicitly and calling
1119
+ * the method on the new fork – it already provides the necessary isolation for safe concurrent usage.
1120
+ *
1121
+ * **Propagation note:** Changes made within a transaction (whether top-level or nested) are always propagated to the
1122
+ * parent context, unless the parent context is a global one. If you want to avoid that, fork the EntityManager first
1123
+ * and then call this method on the fork.
1124
+ *
1125
+ * **Example:**
1126
+ * ```ts
1127
+ * await em.transactional(async (em) => {
1128
+ * const author = new Author('Jon');
1129
+ * em.persist(author);
1130
+ * // flush is called automatically at the end of the callback
1131
+ * });
1132
+ * ```
1133
+ */
1134
+ async transactional(cb, options = {}) {
1135
+ const em = this.getContext(false);
1136
+ if (this.#disableTransactions || em.#disableTransactions) {
1137
+ return cb(em);
1138
+ }
1139
+ const manager = new TransactionManager(this);
1140
+ return manager.handle(cb, options);
1141
+ }
1142
+ /**
1143
+ * Starts new transaction bound to this EntityManager. Use `ctx` parameter to provide the parent when nesting transactions.
1144
+ */
1145
+ async begin(options = {}) {
1146
+ if (this.#disableTransactions) {
1147
+ return;
1148
+ }
1149
+ const em = this.getContext(false);
1150
+ em.#transactionContext = await em.getConnection('write').begin({
1151
+ ...options,
1152
+ eventBroadcaster: new TransactionEventBroadcaster(em, { topLevelTransaction: !options.ctx }),
1153
+ });
1154
+ }
1155
+ /**
1156
+ * Commits the transaction bound to this EntityManager. Flushes before doing the actual commit query.
1157
+ */
1158
+ async commit() {
1159
+ const em = this.getContext(false);
1160
+ if (this.#disableTransactions) {
1161
+ await em.flush();
1162
+ return;
1163
+ }
1164
+ if (!em.#transactionContext) {
1165
+ throw ValidationError.transactionRequired();
1166
+ }
1167
+ await em.flush();
1168
+ await em.getConnection('write').commit(em.#transactionContext, new TransactionEventBroadcaster(em));
1169
+ em.#transactionContext = undefined;
1170
+ }
1171
+ /**
1172
+ * Rollbacks the transaction bound to this EntityManager.
1173
+ */
1174
+ async rollback() {
1175
+ if (this.#disableTransactions) {
1176
+ return;
1177
+ }
1178
+ const em = this.getContext(false);
1179
+ if (!em.#transactionContext) {
1180
+ throw ValidationError.transactionRequired();
1181
+ }
1182
+ await em.getConnection('write').rollback(em.#transactionContext, new TransactionEventBroadcaster(em));
1183
+ em.#transactionContext = undefined;
1184
+ em.#unitOfWork.clearActionsQueue();
1185
+ }
1186
+ /**
1187
+ * Runs your callback wrapped inside a database transaction.
1188
+ */
1189
+ async lock(entity, lockMode, options = {}) {
1190
+ options = Utils.isPlainObject(options) ? options : { lockVersion: options };
1191
+ await this.getUnitOfWork().lock(entity, { lockMode, ...options });
1192
+ }
1193
+ /**
1194
+ * Fires native insert query. Calling this has no side effects on the context (identity map).
1195
+ */
1196
+ async insert(entityNameOrEntity, data, options = {}) {
1197
+ const em = this.getContext(false);
1198
+ em.prepareOptions(options);
1199
+ let entityName;
1200
+ if (data === undefined) {
1201
+ entityName = entityNameOrEntity.constructor;
1202
+ data = entityNameOrEntity;
1203
+ } else {
1204
+ entityName = entityNameOrEntity;
1205
+ }
1206
+ if (Utils.isEntity(data)) {
1207
+ if (options.schema && helper(data).getSchema() == null) {
1208
+ helper(data).setSchema(options.schema);
1209
+ }
1210
+ if (!helper(data).__managed) {
1211
+ em.#unitOfWork.unsetIdentity(data);
1212
+ }
1213
+ const meta = helper(data).__meta;
1214
+ const payload = em.#comparator.prepareEntity(data);
1215
+ const cs = new ChangeSet(data, ChangeSetType.CREATE, payload, meta);
1216
+ await em.#unitOfWork.getChangeSetPersister().executeInserts([cs], { ctx: em.#transactionContext, ...options });
1217
+ return cs.getPrimaryKey();
1218
+ }
1219
+ data = QueryHelper.processObjectParams(data);
1220
+ validateParams(data, 'insert data');
1221
+ const res = await em.driver.nativeInsert(entityName, data, {
1222
+ ctx: em.#transactionContext,
1223
+ ...options,
1224
+ });
1225
+ return res.insertId;
1226
+ }
1227
+ /**
1228
+ * Fires native multi-insert query. Calling this has no side effects on the context (identity map).
1229
+ */
1230
+ async insertMany(entityNameOrEntities, data, options = {}) {
1231
+ const em = this.getContext(false);
1232
+ em.prepareOptions(options);
1233
+ let entityName;
1234
+ if (data === undefined) {
1235
+ entityName = entityNameOrEntities[0].constructor;
1236
+ data = entityNameOrEntities;
1237
+ } else {
1238
+ entityName = entityNameOrEntities;
1239
+ }
1240
+ if (data.length === 0) {
1241
+ return [];
1242
+ }
1243
+ if (Utils.isEntity(data[0])) {
1244
+ const meta = helper(data[0]).__meta;
1245
+ const css = data.map(row => {
1246
+ if (options.schema && helper(row).getSchema() == null) {
1247
+ helper(row).setSchema(options.schema);
1248
+ }
1249
+ if (!helper(row).__managed) {
1250
+ em.#unitOfWork.unsetIdentity(row);
1251
+ }
1252
+ const payload = em.#comparator.prepareEntity(row);
1253
+ return new ChangeSet(row, ChangeSetType.CREATE, payload, meta);
1254
+ });
1255
+ await em.#unitOfWork.getChangeSetPersister().executeInserts(css, { ctx: em.#transactionContext, ...options });
1256
+ return css.map(cs => cs.getPrimaryKey());
1257
+ }
1258
+ data = data.map(row => QueryHelper.processObjectParams(row));
1259
+ data.forEach(row => validateParams(row, 'insert data'));
1260
+ const res = await em.driver.nativeInsertMany(entityName, data, {
1261
+ ctx: em.#transactionContext,
1262
+ ...options,
1263
+ });
1264
+ if (res.insertedIds) {
1265
+ return res.insertedIds;
1266
+ }
1267
+ return [res.insertId];
1268
+ }
1269
+ /**
1270
+ * Fires native update query. Calling this has no side effects on the context (identity map).
1271
+ */
1272
+ async nativeUpdate(entityName, where, data, options = {}) {
1273
+ const em = this.getContext(false);
1274
+ em.prepareOptions(options);
1275
+ await em.processUnionWhere(entityName, options, 'update');
1276
+ data = QueryHelper.processObjectParams(data);
1277
+ where = await em.processWhere(entityName, where, { ...options, convertCustomTypes: false }, 'update');
1278
+ validateParams(data, 'update data');
1279
+ validateParams(where, 'update condition');
1280
+ const res = await em.driver.nativeUpdate(entityName, where, data, {
1281
+ ctx: em.#transactionContext,
1282
+ em,
1283
+ ...options,
1284
+ });
1285
+ return res.affectedRows;
1286
+ }
1287
+ /**
1288
+ * Fires native delete query. Calling this has no side effects on the context (identity map).
1289
+ */
1290
+ async nativeDelete(entityName, where, options = {}) {
1291
+ const em = this.getContext(false);
1292
+ em.prepareOptions(options);
1293
+ await em.processUnionWhere(entityName, options, 'delete');
1294
+ where = await em.processWhere(entityName, where, options, 'delete');
1295
+ validateParams(where, 'delete condition');
1296
+ const res = await em.driver.nativeDelete(entityName, where, {
1297
+ ctx: em.#transactionContext,
1298
+ em,
1299
+ ...options,
1300
+ });
1301
+ return res.affectedRows;
1302
+ }
1303
+ /**
1304
+ * Maps raw database result to an entity and merges it to this EntityManager.
1305
+ */
1306
+ map(entityName, result, options = {}) {
1307
+ const { mapped, ...rest } = options;
1308
+ const meta = this.metadata.get(entityName);
1309
+ const data = mapped ? result : this.driver.mapResult(result, meta);
1310
+ for (const k of Object.keys(data)) {
1311
+ const prop = meta.properties[k];
1312
+ if (
1313
+ prop?.kind === ReferenceKind.SCALAR &&
1314
+ SCALAR_TYPES.has(prop.runtimeType) &&
1315
+ !prop.customType &&
1316
+ (prop.setter || !prop.getter)
1317
+ ) {
1318
+ validateProperty(prop, data[k], data);
1319
+ }
1320
+ }
1321
+ return this.merge(entityName, data, {
1322
+ convertCustomTypes: true,
1323
+ refresh: true,
1324
+ validate: false,
1325
+ ...rest,
1326
+ });
1327
+ }
1328
+ /**
1329
+ * Merges given entity to this EntityManager so it becomes managed. You can force refreshing of existing entities
1330
+ * via second parameter. By default, it will return already loaded entities without modifying them.
1331
+ */
1332
+ merge(entityName, data, options = {}) {
1333
+ if (Utils.isEntity(entityName)) {
1334
+ return this.merge(entityName.constructor, entityName, data);
1335
+ }
1336
+ const em = options.disableContextResolution ? this : this.getContext();
1337
+ options.schema ??= em.#schema;
1338
+ options.validate ??= true;
1339
+ options.cascade ??= true;
1340
+ validatePrimaryKey(data, em.metadata.get(entityName));
1341
+ let entity = em.#unitOfWork.tryGetById(entityName, data, options.schema, false);
1342
+ if (entity && helper(entity).__managed && helper(entity).__initialized && !options.refresh) {
1343
+ return entity;
1344
+ }
1345
+ const dataIsEntity = Utils.isEntity(data);
1346
+ entity = dataIsEntity ? data : em.#entityFactory.create(entityName, data, { merge: true, ...options });
1347
+ const visited = options.cascade ? undefined : new Set([entity]);
1348
+ em.#unitOfWork.merge(entity, visited);
1349
+ return entity;
1350
+ }
1351
+ /**
1352
+ * Creates new instance of given entity and populates it with given data.
1353
+ * The entity constructor will be used unless you provide `{ managed: true }` in the `options` parameter.
1354
+ * The constructor will be given parameters based on the defined constructor of the entity. If the constructor
1355
+ * parameter matches a property name, its value will be extracted from `data`. If no matching property exists,
1356
+ * the whole `data` parameter will be passed. This means we can also define `constructor(data: Partial<T>)` and
1357
+ * `em.create()` will pass the data into it (unless we have a property named `data` too).
1358
+ *
1359
+ * The parameters are strictly checked, you need to provide all required properties. You can use `OptionalProps`
1360
+ * symbol to omit some properties from this check without making them optional. Alternatively, use `partial: true`
1361
+ * in the options to disable the strict checks for required properties. This option has no effect on runtime.
1362
+ *
1363
+ * The newly created entity will be automatically marked for persistence via `em.persist` unless you disable this
1364
+ * behavior, either locally via `persist: false` option, or globally via `persistOnCreate` ORM config option.
1365
+ */
1366
+ create(entityName, data, options = {}) {
1367
+ const em = this.getContext();
1368
+ options.schema ??= em.#schema;
1369
+ const entity = em.#entityFactory.create(entityName, data, {
1370
+ ...options,
1371
+ newEntity: !options.managed,
1372
+ merge: options.managed,
1373
+ normalizeAccessors: true,
1374
+ });
1375
+ options.persist ??= em.config.get('persistOnCreate');
1376
+ if (options.persist && !this.getMetadata(entityName).embeddable) {
1377
+ em.persist(entity);
1378
+ }
1379
+ return entity;
1380
+ }
1381
+ /**
1382
+ * Shortcut for `wrap(entity).assign(data, { em })`
1383
+ */
1384
+ assign(entity, data, options = {}) {
1385
+ return EntityAssigner.assign(entity, data, { em: this.getContext(), ...options });
1386
+ }
1387
+ /**
1388
+ * Gets a reference to the entity identified by the given type and identifier without actually loading it, if the entity is not yet loaded
1389
+ */
1390
+ getReference(entityName, id, options = {}) {
1391
+ options.schema ??= this.schema;
1392
+ options.convertCustomTypes ??= false;
1393
+ const meta = this.metadata.get(entityName);
1394
+ if (Utils.isPrimaryKey(id)) {
1395
+ if (meta.compositePK) {
1396
+ throw ValidationError.invalidCompositeIdentifier(meta);
1397
+ }
1398
+ id = [id];
1399
+ }
1400
+ const entity = this.getEntityFactory().createReference(entityName, id, { merge: true, ...options });
1401
+ if (options.wrapped) {
1402
+ return Reference.create(entity);
1403
+ }
1404
+ return entity;
1405
+ }
1406
+ /**
1407
+ * Returns total number of entities matching your `where` query.
1408
+ */
1409
+ async count(entityName, where = {}, options = {}) {
1410
+ const em = this.getContext(false);
1411
+ // Shallow copy options since the object will be modified when deleting orderBy
1412
+ options = { ...options };
1413
+ em.prepareOptions(options);
1414
+ await em.tryFlush(entityName, options);
1415
+ where = await em.processWhere(entityName, where, options, 'read');
1416
+ options.populate = await em.preparePopulate(entityName, options);
1417
+ options = { ...options };
1418
+ // save the original hint value so we know it was infer/all
1419
+ const meta = em.metadata.find(entityName);
1420
+ options._populateWhere = options.populateWhere ?? this.config.get('populateWhere');
1421
+ options.populateWhere = this.createPopulateWhere({ ...where }, options);
1422
+ options.populateFilter = await this.getJoinedFilters(meta, options);
1423
+ validateParams(where);
1424
+ delete options.orderBy;
1425
+ await em.processUnionWhere(entityName, options, 'read');
1426
+ const cacheKey = em.cacheKey(entityName, options, 'em.count', where);
1427
+ const cached = await em.tryCache(entityName, options.cache, cacheKey);
1428
+ if (cached?.data !== undefined) {
1429
+ return cached.data;
1430
+ }
1431
+ const count = await em.driver.count(entityName, where, { ctx: em.#transactionContext, em, ...options });
1432
+ await em.storeCache(options.cache, cached, () => +count);
1433
+ return +count;
1434
+ }
1435
+ /**
1436
+ * Tells the EntityManager to make an instance managed and persistent.
1437
+ * The entity will be entered into the database at or before transaction commit or as a result of the flush operation.
1438
+ */
1439
+ persist(entity) {
1440
+ const em = this.getContext();
1441
+ if (Utils.isEntity(entity)) {
1442
+ // do not cascade just yet, cascading of entities in persist stack is done when flushing
1443
+ em.#unitOfWork.persist(entity, undefined, { cascade: false });
1444
+ return em;
1445
+ }
1446
+ const entities = Utils.asArray(entity);
1447
+ for (const ent of entities) {
1448
+ if (!Utils.isEntity(ent, true)) {
1449
+ /* v8 ignore next */
1450
+ const meta = typeof ent === 'object' ? em.metadata.find(ent.constructor) : undefined;
1451
+ throw ValidationError.notDiscoveredEntity(ent, meta);
1452
+ }
1453
+ // do not cascade just yet, cascading of entities in persist stack is done when flushing
1454
+ em.#unitOfWork.persist(Reference.unwrapReference(ent), undefined, { cascade: false });
1455
+ }
1456
+ return this;
1457
+ }
1458
+ /**
1459
+ * Marks entity for removal.
1460
+ * A removed entity will be removed from the database at or before transaction commit or as a result of the flush operation.
1461
+ *
1462
+ * To remove entities by condition, use `em.nativeDelete()`.
1463
+ */
1464
+ remove(entity) {
1465
+ const em = this.getContext();
1466
+ if (Utils.isEntity(entity)) {
1467
+ // do not cascade just yet, cascading of entities in persist stack is done when flushing
1468
+ em.#unitOfWork.remove(entity, undefined, { cascade: false });
1469
+ return em;
1470
+ }
1471
+ const entities = Utils.asArray(entity, true);
1472
+ for (const ent of entities) {
1473
+ if (!Utils.isEntity(ent, true)) {
1474
+ throw new Error(
1475
+ `You need to pass entity instance or reference to 'em.remove()'. To remove entities by condition, use 'em.nativeDelete()'.`,
1476
+ );
1477
+ }
1478
+ // do not cascade just yet, cascading of entities in remove stack is done when flushing
1479
+ em.#unitOfWork.remove(Reference.unwrapReference(ent), undefined, { cascade: false });
1480
+ }
1481
+ return em;
1482
+ }
1483
+ /**
1484
+ * Flushes all changes to objects that have been queued up to now to the database.
1485
+ * This effectively synchronizes the in-memory state of managed objects with the database.
1486
+ */
1487
+ async flush() {
1488
+ await this.getUnitOfWork().commit();
1489
+ }
1490
+ /**
1491
+ * @internal
1492
+ */
1493
+ async tryFlush(entityName, options) {
1494
+ const em = this.getContext();
1495
+ const flushMode = options.flushMode ?? em.#flushMode ?? em.config.get('flushMode');
1496
+ const meta = em.metadata.get(entityName);
1497
+ if (flushMode === FlushMode.COMMIT) {
1498
+ return;
1499
+ }
1500
+ if (flushMode === FlushMode.ALWAYS || em.getUnitOfWork().shouldAutoFlush(meta)) {
1501
+ await em.flush();
1502
+ }
1503
+ }
1504
+ /**
1505
+ * Clears the EntityManager. All entities that are currently managed by this EntityManager become detached.
1506
+ */
1507
+ clear() {
1508
+ this.getContext().#unitOfWork.clear();
1509
+ }
1510
+ /**
1511
+ * Checks whether given property can be populated on the entity.
1512
+ */
1513
+ canPopulate(entityName, property) {
1514
+ // eslint-disable-next-line prefer-const
1515
+ let [p, ...parts] = property.split('.');
1516
+ const meta = this.metadata.find(entityName);
1517
+ if (!meta) {
1518
+ return true;
1519
+ }
1520
+ if (p.includes(':')) {
1521
+ p = p.split(':', 2)[0];
1522
+ }
1523
+ // For TPT inheritance, check the entity's own properties, not just the root's
1524
+ // For STI, meta.properties includes all properties anyway
1525
+ const ret = p in meta.properties;
1526
+ if (parts.length > 0) {
1527
+ return this.canPopulate(meta.properties[p].targetMeta.class, parts.join('.'));
1528
+ }
1529
+ return ret;
1530
+ }
1531
+ /**
1532
+ * Loads specified relations in batch. This will execute one query for each relation, that will populate it on all the specified entities.
1533
+ */
1534
+ async populate(entities, populate, options = {}) {
1535
+ const arr = Utils.asArray(entities);
1536
+ if (arr.length === 0) {
1537
+ return entities;
1538
+ }
1539
+ const em = this.getContext();
1540
+ em.prepareOptions(options);
1541
+ const entityName = arr[0].constructor;
1542
+ const preparedPopulate = await em.preparePopulate(
1543
+ entityName,
1544
+ { populate: populate, filters: options.filters },
1545
+ options.validate,
1546
+ );
1547
+ await em.#entityLoader.populate(entityName, arr, preparedPopulate, options);
1548
+ return entities;
1549
+ }
1550
+ /**
1551
+ * Returns new EntityManager instance with its own identity map
1552
+ */
1553
+ fork(options = {}) {
1554
+ const em = options.disableContextResolution ? this : this.getContext(false);
1555
+ options.clear ??= true;
1556
+ options.useContext ??= false;
1557
+ options.freshEventManager ??= false;
1558
+ options.cloneEventManager ??= false;
1559
+ const eventManager = options.freshEventManager
1560
+ ? new EventManager(em.config.get('subscribers'))
1561
+ : options.cloneEventManager
1562
+ ? em.eventManager.clone()
1563
+ : em.eventManager;
1564
+ // we need to allow global context here as forking from global EM is fine
1565
+ const allowGlobalContext = em.config.get('allowGlobalContext');
1566
+ em.config.set('allowGlobalContext', true);
1567
+ const fork = new em.constructor(em.config, em.driver, em.metadata, options.useContext, eventManager);
1568
+ fork.setFlushMode(options.flushMode ?? em.#flushMode);
1569
+ fork.#disableTransactions =
1570
+ options.disableTransactions ?? this.#disableTransactions ?? this.config.get('disableTransactions');
1571
+ em.config.set('allowGlobalContext', allowGlobalContext);
1572
+ if (options.keepTransactionContext) {
1573
+ fork.#transactionContext = em.#transactionContext;
1574
+ }
1575
+ fork.#filters = { ...em.#filters };
1576
+ fork.#filterParams = Utils.copy(em.#filterParams);
1577
+ fork.loggerContext = Utils.merge({}, em.loggerContext, options.loggerContext);
1578
+ fork.#schema = options.schema ?? em.#schema;
1579
+ if (!options.clear) {
1580
+ for (const entity of em.#unitOfWork.getIdentityMap()) {
1581
+ fork.#unitOfWork.register(entity);
1582
+ }
1583
+ for (const entity of em.#unitOfWork.getPersistStack()) {
1584
+ fork.#unitOfWork.persist(entity);
1585
+ }
1586
+ for (const entity of em.#unitOfWork.getOrphanRemoveStack()) {
1587
+ fork.#unitOfWork.getOrphanRemoveStack().add(entity);
1588
+ }
1589
+ }
1590
+ return fork;
1591
+ }
1592
+ /**
1593
+ * Gets the UnitOfWork used by the EntityManager to coordinate operations.
1594
+ */
1595
+ getUnitOfWork(useContext = true) {
1596
+ if (!useContext) {
1597
+ return this.#unitOfWork;
1598
+ }
1599
+ return this.getContext().#unitOfWork;
1600
+ }
1601
+ /**
1602
+ * Gets the EntityFactory used by the EntityManager.
1603
+ */
1604
+ getEntityFactory() {
1605
+ return this.getContext().#entityFactory;
1606
+ }
1607
+ /**
1608
+ * @internal use `em.populate()` as the user facing API, this is exposed only for internal usage
1609
+ */
1610
+ getEntityLoader() {
1611
+ return this.getContext().#entityLoader;
1612
+ }
1613
+ /**
1614
+ * Gets the Hydrator used by the EntityManager.
1615
+ */
1616
+ getHydrator() {
1617
+ return this.config.getHydrator(this.getMetadata());
1618
+ }
1619
+ /**
1620
+ * Gets the EntityManager based on current transaction/request context.
1621
+ * @internal
1622
+ */
1623
+ getContext(validate = true) {
1624
+ if (!this.#useContext) {
1625
+ return this;
1626
+ }
1627
+ let em = TransactionContext.getEntityManager(this.name); // prefer the tx context
1628
+ if (em) {
1629
+ return em;
1630
+ }
1631
+ // no explicit tx started
1632
+ em = this.config.get('context')(this.name) ?? this;
1633
+ if (validate && !this.config.get('allowGlobalContext') && em.global) {
1634
+ throw ValidationError.cannotUseGlobalContext();
1635
+ }
1636
+ return em;
1637
+ }
1638
+ /** Gets the EventManager instance used by this EntityManager. */
1639
+ getEventManager() {
1640
+ return this.eventManager;
1641
+ }
1642
+ /**
1643
+ * Checks whether this EntityManager is currently operating inside a database transaction.
1644
+ */
1645
+ isInTransaction() {
1646
+ return !!this.getContext(false).#transactionContext;
1647
+ }
1648
+ /**
1649
+ * Gets the transaction context (driver dependent object used to make sure queries are executed on same connection).
1650
+ */
1651
+ getTransactionContext() {
1652
+ return this.getContext(false).#transactionContext;
1653
+ }
1654
+ /**
1655
+ * Sets the transaction context.
1656
+ */
1657
+ setTransactionContext(ctx) {
1658
+ if (!ctx) {
1659
+ this.resetTransactionContext();
1660
+ } else {
1661
+ this.getContext(false).#transactionContext = ctx;
1662
+ }
1663
+ }
1664
+ /**
1665
+ * Resets the transaction context.
1666
+ */
1667
+ resetTransactionContext() {
1668
+ this.getContext(false).#transactionContext = undefined;
1669
+ }
1670
+ /**
1671
+ * Gets the `MetadataStorage` (without parameters) or `EntityMetadata` instance when provided with the `entityName` parameter.
1672
+ */
1673
+ getMetadata(entityName) {
1674
+ if (entityName) {
1675
+ return this.metadata.get(entityName);
1676
+ }
1677
+ return this.metadata;
1678
+ }
1679
+ /**
1680
+ * Gets the EntityComparator.
1681
+ */
1682
+ getComparator() {
1683
+ return this.#comparator;
1684
+ }
1685
+ checkLockRequirements(mode, meta) {
1686
+ if (!mode) {
1687
+ return;
1688
+ }
1689
+ if (mode === LockMode.OPTIMISTIC && !meta.versionProperty) {
1690
+ throw OptimisticLockError.notVersioned(meta);
1691
+ }
1692
+ if ([LockMode.PESSIMISTIC_READ, LockMode.PESSIMISTIC_WRITE].includes(mode) && !this.isInTransaction()) {
1693
+ throw ValidationError.transactionRequired();
1694
+ }
1695
+ }
1696
+ async lockAndPopulate(meta, entity, where, options) {
1697
+ if (!meta.virtual && options.lockMode === LockMode.OPTIMISTIC) {
1698
+ await this.lock(entity, options.lockMode, {
1699
+ lockVersion: options.lockVersion,
1700
+ lockTableAliases: options.lockTableAliases,
1701
+ });
1702
+ }
1703
+ const preparedPopulate = await this.preparePopulate(meta.class, options);
1704
+ await this.#entityLoader.populate(meta.class, [entity], preparedPopulate, {
1705
+ ...options,
1706
+ ...this.getPopulateWhere(where, options),
1707
+ orderBy: options.populateOrderBy ?? options.orderBy,
1708
+ ignoreLazyScalarProperties: true,
1709
+ lookup: false,
1710
+ });
1711
+ return entity;
1712
+ }
1713
+ buildFields(fields) {
1714
+ return fields.reduce((ret, f) => {
1715
+ if (Utils.isPlainObject(f)) {
1716
+ Utils.keys(f).forEach(ff => ret.push(...this.buildFields(f[ff]).map(field => `${ff}.${field}`)));
1717
+ } else {
1718
+ ret.push(f);
1719
+ }
1720
+ return ret;
1721
+ }, []);
1722
+ }
1723
+ /** @internal */
1724
+ async preparePopulate(entityName, options, validate = true) {
1725
+ if (options.populate === false) {
1726
+ return [];
1727
+ }
1728
+ const meta = this.metadata.find(entityName);
1729
+ // infer populate hints from `fields` when present; merge with explicit `populate` if both are set
1730
+ const fields = options.fields ? this.buildFields(options.fields) : undefined;
1731
+ const populateArray = Array.isArray(options.populate) ? options.populate : undefined;
1732
+ const hasNestedFields = fields?.some(f => f.includes('.')) ?? false;
1733
+ const shouldInfer = fields !== undefined && options.populate === undefined;
1734
+ const shouldMerge =
1735
+ fields !== undefined && populateArray !== undefined && populateArray.length > 0 && hasNestedFields;
1736
+ if (shouldInfer || shouldMerge) {
1737
+ // we need to prune the `populate` hint from to-one relations, as partially loading them does not require their population, we want just the FK
1738
+ const pruneToOneRelations = (meta, fields) => {
1739
+ const ret = [];
1740
+ for (let field of fields) {
1741
+ if (field === PopulatePath.ALL || field.startsWith(`${PopulatePath.ALL}.`)) {
1742
+ ret.push(
1743
+ ...meta.props
1744
+ .filter(prop => prop.lazy || [ReferenceKind.SCALAR, ReferenceKind.EMBEDDED].includes(prop.kind))
1745
+ .map(prop => prop.name),
1746
+ );
1747
+ continue;
1748
+ }
1749
+ field = field.split(':')[0];
1750
+ if (
1751
+ !field.includes('.') &&
1752
+ ![ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(meta.properties[field].kind)
1753
+ ) {
1754
+ ret.push(field);
1755
+ continue;
1756
+ }
1757
+ const parts = field.split('.');
1758
+ const key = parts.shift();
1759
+ if (parts.length === 0) {
1760
+ continue;
1761
+ }
1762
+ const prop = meta.properties[key];
1763
+ if (!prop.targetMeta) {
1764
+ ret.push(key);
1765
+ continue;
1766
+ }
1767
+ const inner = pruneToOneRelations(prop.targetMeta, [parts.join('.')]);
1768
+ if (inner.length > 0) {
1769
+ ret.push(...inner.map(c => `${key}.${c}`));
1770
+ }
1771
+ }
1772
+ return Utils.unique(ret);
1773
+ };
1774
+ const fromFields = pruneToOneRelations(meta, fields);
1775
+ if (shouldInfer) {
1776
+ options.populate = fromFields;
1777
+ } else {
1778
+ // with an explicit populate, only nested paths (e.g. `item.id`) need to be merged in — they
1779
+ // require a JOIN to access sub-fields, whereas bare names are already handled by the driver
1780
+ const extras = fromFields.filter(f => f.includes('.'));
1781
+ options.populate = [...populateArray, ...extras];
1782
+ }
1783
+ }
1784
+ if (!options.populate) {
1785
+ const populate = this.#entityLoader.normalizePopulate(entityName, [], options.strategy, true, options.exclude);
1786
+ await this.autoJoinRefsForFilters(meta, { ...options, populate });
1787
+ return populate;
1788
+ }
1789
+ if (typeof options.populate !== 'boolean') {
1790
+ options.populate = Utils.asArray(options.populate)
1791
+ .map(field => {
1792
+ /* v8 ignore next */
1793
+ if (typeof field === 'boolean' || field === PopulatePath.ALL) {
1794
+ return [{ field: meta.primaryKeys[0], strategy: options.strategy, all: !!field }]; //
1795
+ }
1796
+ // will be handled in QueryBuilder when processing the where condition via CriteriaNode
1797
+ if (field === PopulatePath.INFER) {
1798
+ options.flags ??= [];
1799
+ options.flags.push(QueryFlag.INFER_POPULATE);
1710
1800
  return [];
1711
- }
1712
- const meta = this.metadata.find(entityName);
1713
- // infer populate hints from `fields` when present; merge with explicit `populate` if both are set
1714
- const fields = options.fields ? this.buildFields(options.fields) : undefined;
1715
- const populateArray = Array.isArray(options.populate) ? options.populate : undefined;
1716
- const hasNestedFields = fields?.some(f => f.includes('.')) ?? false;
1717
- const shouldInfer = fields !== undefined && options.populate === undefined;
1718
- const shouldMerge = fields !== undefined && populateArray !== undefined && populateArray.length > 0 && hasNestedFields;
1719
- if (shouldInfer || shouldMerge) {
1720
- // we need to prune the `populate` hint from to-one relations, as partially loading them does not require their population, we want just the FK
1721
- const pruneToOneRelations = (meta, fields) => {
1722
- const ret = [];
1723
- for (let field of fields) {
1724
- if (field === PopulatePath.ALL || field.startsWith(`${PopulatePath.ALL}.`)) {
1725
- ret.push(...meta.props
1726
- .filter(prop => prop.lazy || [ReferenceKind.SCALAR, ReferenceKind.EMBEDDED].includes(prop.kind))
1727
- .map(prop => prop.name));
1728
- continue;
1729
- }
1730
- field = field.split(':')[0];
1731
- if (!field.includes('.') &&
1732
- ![ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(meta.properties[field].kind)) {
1733
- ret.push(field);
1734
- continue;
1735
- }
1736
- const parts = field.split('.');
1737
- const key = parts.shift();
1738
- if (parts.length === 0) {
1739
- continue;
1740
- }
1741
- const prop = meta.properties[key];
1742
- if (!prop.targetMeta) {
1743
- ret.push(key);
1744
- continue;
1745
- }
1746
- const inner = pruneToOneRelations(prop.targetMeta, [parts.join('.')]);
1747
- if (inner.length > 0) {
1748
- ret.push(...inner.map(c => `${key}.${c}`));
1749
- }
1750
- }
1751
- return Utils.unique(ret);
1752
- };
1753
- const fromFields = pruneToOneRelations(meta, fields);
1754
- if (shouldInfer) {
1755
- options.populate = fromFields;
1756
- }
1757
- else {
1758
- // with an explicit populate, only nested paths (e.g. `item.id`) need to be merged in — they
1759
- // require a JOIN to access sub-fields, whereas bare names are already handled by the driver
1760
- const extras = fromFields.filter(f => f.includes('.'));
1761
- options.populate = [...populateArray, ...extras];
1762
- }
1763
- }
1764
- if (!options.populate) {
1765
- const populate = this.#entityLoader.normalizePopulate(entityName, [], options.strategy, true, options.exclude);
1766
- await this.autoJoinRefsForFilters(meta, { ...options, populate });
1767
- return populate;
1768
- }
1769
- if (typeof options.populate !== 'boolean') {
1770
- options.populate = Utils.asArray(options.populate)
1771
- .map(field => {
1772
- /* v8 ignore next */
1773
- if (typeof field === 'boolean' || field === PopulatePath.ALL) {
1774
- return [{ field: meta.primaryKeys[0], strategy: options.strategy, all: !!field }]; //
1775
- }
1776
- // will be handled in QueryBuilder when processing the where condition via CriteriaNode
1777
- if (field === PopulatePath.INFER) {
1778
- options.flags ??= [];
1779
- options.flags.push(QueryFlag.INFER_POPULATE);
1780
- return [];
1781
- }
1782
- if (typeof field === 'string') {
1783
- return [{ field, strategy: options.strategy }];
1784
- }
1785
- return [field];
1786
- })
1787
- .flat();
1788
- }
1789
- const populate = this.#entityLoader.normalizePopulate(entityName, options.populate, options.strategy, true, options.exclude);
1790
- const invalid = populate.find(({ field }) => !this.canPopulate(entityName, field));
1791
- if (validate && invalid) {
1792
- throw ValidationError.invalidPropertyName(entityName, invalid.field);
1793
- }
1794
- await this.autoJoinRefsForFilters(meta, { ...options, populate });
1795
- for (const field of populate) {
1796
- // force select-in strategy when populating all relations as otherwise we could cause infinite loops when self-referencing
1797
- const all = field.all ?? (Array.isArray(options.populate) && options.populate.includes('*'));
1798
- field.strategy = all ? LoadStrategy.SELECT_IN : (options.strategy ?? field.strategy);
1799
- }
1800
- if (options.populateHints) {
1801
- applyPopulateHints(populate, options.populateHints);
1802
- }
1803
- return populate;
1804
- }
1805
- /**
1806
- * when the entity is found in identity map, we check if it was partially loaded or we are trying to populate
1807
- * some additional lazy properties, if so, we reload and merge the data from database
1808
- */
1809
- shouldRefresh(meta, entity, options) {
1810
- if (!helper(entity).__initialized || options.refresh) {
1811
- return true;
1812
- }
1813
- let autoRefresh;
1814
- if (options.fields) {
1815
- autoRefresh = options.fields.some(field => !helper(entity).__loadedProperties.has(field));
1816
- }
1817
- else {
1818
- autoRefresh = meta.comparableProps.some(prop => {
1819
- const inlineEmbedded = prop.kind === ReferenceKind.EMBEDDED && !prop.object;
1820
- return !inlineEmbedded && !prop.lazy && !helper(entity).__loadedProperties.has(prop.name);
1821
- });
1822
- }
1823
- if (autoRefresh || options.filters) {
1824
- return true;
1825
- }
1826
- if (Array.isArray(options.populate)) {
1827
- return options.populate.some(field => !helper(entity).__loadedProperties.has(field));
1828
- }
1829
- return !!options.populate;
1830
- }
1831
- prepareOptions(options) {
1832
- if (!Utils.isEmpty(options.fields) && !Utils.isEmpty(options.exclude)) {
1833
- throw new ValidationError(`Cannot combine 'fields' and 'exclude' option.`);
1834
- }
1835
- options.schema ??= this.#schema;
1836
- options.logging = options.loggerContext = Utils.merge({ id: this.id }, this.loggerContext, options.loggerContext, options.logging);
1837
- }
1838
- /**
1839
- * @internal
1840
- */
1841
- cacheKey(entityName, options, method, where) {
1842
- const { ...opts } = options;
1843
- // ignore some irrelevant options, e.g. logger context can contain dynamic data for the same query
1844
- for (const k of ['ctx', 'strategy', 'flushMode', 'logging', 'loggerContext']) {
1845
- delete opts[k];
1846
- }
1847
- return [Utils.className(entityName), method, opts, where];
1848
- }
1849
- /**
1850
- * @internal
1851
- */
1852
- async tryCache(entityName, config, key, refresh, merge) {
1853
- config ??= this.config.get('resultCache').global;
1854
- if (!config) {
1855
- return undefined;
1856
- }
1857
- const em = this.getContext();
1858
- const cacheKey = Array.isArray(config) ? config[0] : JSON.stringify(key);
1859
- const cached = await em.#resultCache.get(cacheKey);
1860
- if (!cached) {
1861
- return { key: cacheKey, data: cached };
1862
- }
1863
- let data;
1864
- const createOptions = {
1865
- merge: true,
1866
- convertCustomTypes: false,
1867
- refresh,
1868
- recomputeSnapshot: true,
1869
- };
1870
- if (Array.isArray(cached) && merge) {
1871
- data = cached.map(item => em.#entityFactory.create(entityName, item, createOptions));
1872
- }
1873
- else if (Utils.isObject(cached) && merge) {
1874
- data = em.#entityFactory.create(entityName, cached, createOptions);
1875
- }
1876
- else {
1877
- data = cached;
1878
- }
1879
- await em.#unitOfWork.dispatchOnLoadEvent();
1880
- return { key: cacheKey, data };
1881
- }
1882
- /**
1883
- * @internal
1884
- */
1885
- async storeCache(config, key, data) {
1886
- config ??= this.config.get('resultCache').global;
1887
- if (config) {
1888
- const em = this.getContext();
1889
- const expiration = Array.isArray(config) ? config[1] : typeof config === 'number' ? config : undefined;
1890
- await em.#resultCache.set(key.key, data instanceof Function ? data() : data, '', expiration);
1891
- }
1892
- }
1893
- /**
1894
- * Clears result cache for given cache key. If we want to be able to call this method,
1895
- * we need to set the cache key explicitly when storing the cache.
1896
- *
1897
- * ```ts
1898
- * // set the cache key to 'book-cache-key', with expiration of 60s
1899
- * const res = await em.find(Book, { ... }, { cache: ['book-cache-key', 60_000] });
1900
- *
1901
- * // clear the cache key by name
1902
- * await em.clearCache('book-cache-key');
1903
- * ```
1904
- */
1905
- async clearCache(cacheKey) {
1906
- await this.getContext().#resultCache.remove(cacheKey);
1907
- }
1908
- /**
1909
- * Returns the default schema of this EntityManager. Respects the context, so global EM will give you the contextual schema
1910
- * if executed inside request context handler.
1911
- */
1912
- get schema() {
1913
- return this.getContext(false).#schema;
1914
- }
1915
- /**
1916
- * Sets the default schema of this EntityManager. Respects the context, so global EM will set the contextual schema
1917
- * if executed inside request context handler.
1918
- */
1919
- set schema(schema) {
1920
- this.getContext(false).#schema = schema ?? undefined;
1921
- }
1922
- /** @internal */
1923
- async getDataLoader(type) {
1924
- const em = this.getContext();
1925
- if (em.#loaders[type]) {
1926
- return em.#loaders[type];
1927
- }
1928
- const { DataloaderUtils } = await import('@mikro-orm/core/dataloader');
1929
- const DataLoader = await DataloaderUtils.getDataLoader();
1930
- switch (type) {
1931
- case 'ref':
1932
- return (em.#loaders[type] ??= new DataLoader(DataloaderUtils.getRefBatchLoadFn(em)));
1933
- case '1:m':
1934
- return (em.#loaders[type] ??= new DataLoader(DataloaderUtils.getColBatchLoadFn(em)));
1935
- case 'm:n':
1936
- return (em.#loaders[type] ??= new DataLoader(DataloaderUtils.getManyToManyColBatchLoadFn(em)));
1937
- }
1938
- }
1939
- /**
1940
- * Returns the ID of this EntityManager. Respects the context, so global EM will give you the contextual ID
1941
- * if executed inside request context handler.
1942
- */
1943
- get id() {
1944
- return this.getContext(false)._id;
1945
- }
1946
- /** @ignore */
1947
- [Symbol.for('nodejs.util.inspect.custom')]() {
1948
- return `[EntityManager<${this.id}>]`;
1949
- }
1801
+ }
1802
+ if (typeof field === 'string') {
1803
+ return [{ field, strategy: options.strategy }];
1804
+ }
1805
+ return [field];
1806
+ })
1807
+ .flat();
1808
+ }
1809
+ const populate = this.#entityLoader.normalizePopulate(
1810
+ entityName,
1811
+ options.populate,
1812
+ options.strategy,
1813
+ true,
1814
+ options.exclude,
1815
+ );
1816
+ const invalid = populate.find(({ field }) => !this.canPopulate(entityName, field));
1817
+ if (validate && invalid) {
1818
+ throw ValidationError.invalidPropertyName(entityName, invalid.field);
1819
+ }
1820
+ await this.autoJoinRefsForFilters(meta, { ...options, populate });
1821
+ for (const field of populate) {
1822
+ // force select-in strategy when populating all relations as otherwise we could cause infinite loops when self-referencing
1823
+ const all = field.all ?? (Array.isArray(options.populate) && options.populate.includes('*'));
1824
+ field.strategy = all ? LoadStrategy.SELECT_IN : (options.strategy ?? field.strategy);
1825
+ }
1826
+ if (options.populateHints) {
1827
+ applyPopulateHints(populate, options.populateHints);
1828
+ }
1829
+ return populate;
1830
+ }
1831
+ /**
1832
+ * when the entity is found in identity map, we check if it was partially loaded or we are trying to populate
1833
+ * some additional lazy properties, if so, we reload and merge the data from database
1834
+ */
1835
+ shouldRefresh(meta, entity, options) {
1836
+ if (!helper(entity).__initialized || options.refresh) {
1837
+ return true;
1838
+ }
1839
+ let autoRefresh;
1840
+ if (options.fields) {
1841
+ autoRefresh = options.fields.some(field => !helper(entity).__loadedProperties.has(field));
1842
+ } else {
1843
+ autoRefresh = meta.comparableProps.some(prop => {
1844
+ const inlineEmbedded = prop.kind === ReferenceKind.EMBEDDED && !prop.object;
1845
+ return !inlineEmbedded && !prop.lazy && !helper(entity).__loadedProperties.has(prop.name);
1846
+ });
1847
+ }
1848
+ if (autoRefresh || options.filters) {
1849
+ return true;
1850
+ }
1851
+ if (Array.isArray(options.populate)) {
1852
+ return options.populate.some(field => !helper(entity).__loadedProperties.has(field));
1853
+ }
1854
+ return !!options.populate;
1855
+ }
1856
+ prepareOptions(options) {
1857
+ if (!Utils.isEmpty(options.fields) && !Utils.isEmpty(options.exclude)) {
1858
+ throw new ValidationError(`Cannot combine 'fields' and 'exclude' option.`);
1859
+ }
1860
+ options.schema ??= this.#schema;
1861
+ options.logging = options.loggerContext = Utils.merge(
1862
+ { id: this.id },
1863
+ this.loggerContext,
1864
+ options.loggerContext,
1865
+ options.logging,
1866
+ );
1867
+ }
1868
+ /**
1869
+ * @internal
1870
+ */
1871
+ cacheKey(entityName, options, method, where) {
1872
+ const { ...opts } = options;
1873
+ // ignore some irrelevant options, e.g. logger context can contain dynamic data for the same query
1874
+ for (const k of ['ctx', 'strategy', 'flushMode', 'logging', 'loggerContext']) {
1875
+ delete opts[k];
1876
+ }
1877
+ return [Utils.className(entityName), method, opts, where];
1878
+ }
1879
+ /**
1880
+ * @internal
1881
+ */
1882
+ async tryCache(entityName, config, key, refresh, merge) {
1883
+ config ??= this.config.get('resultCache').global;
1884
+ if (!config) {
1885
+ return undefined;
1886
+ }
1887
+ const em = this.getContext();
1888
+ const cacheKey = Array.isArray(config) ? config[0] : JSON.stringify(key);
1889
+ const cached = await em.#resultCache.get(cacheKey);
1890
+ if (!cached) {
1891
+ return { key: cacheKey, data: cached };
1892
+ }
1893
+ let data;
1894
+ const createOptions = {
1895
+ merge: true,
1896
+ convertCustomTypes: false,
1897
+ refresh,
1898
+ recomputeSnapshot: true,
1899
+ };
1900
+ if (Array.isArray(cached) && merge) {
1901
+ data = cached.map(item => em.#entityFactory.create(entityName, item, createOptions));
1902
+ } else if (Utils.isObject(cached) && merge) {
1903
+ data = em.#entityFactory.create(entityName, cached, createOptions);
1904
+ } else {
1905
+ data = cached;
1906
+ }
1907
+ await em.#unitOfWork.dispatchOnLoadEvent();
1908
+ return { key: cacheKey, data };
1909
+ }
1910
+ /**
1911
+ * @internal
1912
+ */
1913
+ async storeCache(config, key, data) {
1914
+ config ??= this.config.get('resultCache').global;
1915
+ if (config) {
1916
+ const em = this.getContext();
1917
+ const expiration = Array.isArray(config) ? config[1] : typeof config === 'number' ? config : undefined;
1918
+ await em.#resultCache.set(key.key, data instanceof Function ? data() : data, '', expiration);
1919
+ }
1920
+ }
1921
+ /**
1922
+ * Clears result cache for given cache key. If we want to be able to call this method,
1923
+ * we need to set the cache key explicitly when storing the cache.
1924
+ *
1925
+ * ```ts
1926
+ * // set the cache key to 'book-cache-key', with expiration of 60s
1927
+ * const res = await em.find(Book, { ... }, { cache: ['book-cache-key', 60_000] });
1928
+ *
1929
+ * // clear the cache key by name
1930
+ * await em.clearCache('book-cache-key');
1931
+ * ```
1932
+ */
1933
+ async clearCache(cacheKey) {
1934
+ await this.getContext().#resultCache.remove(cacheKey);
1935
+ }
1936
+ /**
1937
+ * Returns the default schema of this EntityManager. Respects the context, so global EM will give you the contextual schema
1938
+ * if executed inside request context handler.
1939
+ */
1940
+ get schema() {
1941
+ return this.getContext(false).#schema;
1942
+ }
1943
+ /**
1944
+ * Sets the default schema of this EntityManager. Respects the context, so global EM will set the contextual schema
1945
+ * if executed inside request context handler.
1946
+ */
1947
+ set schema(schema) {
1948
+ this.getContext(false).#schema = schema ?? undefined;
1949
+ }
1950
+ /** @internal */
1951
+ async getDataLoader(type) {
1952
+ const em = this.getContext();
1953
+ if (em.#loaders[type]) {
1954
+ return em.#loaders[type];
1955
+ }
1956
+ const { DataloaderUtils } = await import('@mikro-orm/core/dataloader');
1957
+ const DataLoader = await DataloaderUtils.getDataLoader();
1958
+ switch (type) {
1959
+ case 'ref':
1960
+ return (em.#loaders[type] ??= new DataLoader(DataloaderUtils.getRefBatchLoadFn(em)));
1961
+ case '1:m':
1962
+ return (em.#loaders[type] ??= new DataLoader(DataloaderUtils.getColBatchLoadFn(em)));
1963
+ case 'm:n':
1964
+ return (em.#loaders[type] ??= new DataLoader(DataloaderUtils.getManyToManyColBatchLoadFn(em)));
1965
+ }
1966
+ }
1967
+ /**
1968
+ * Returns the ID of this EntityManager. Respects the context, so global EM will give you the contextual ID
1969
+ * if executed inside request context handler.
1970
+ */
1971
+ get id() {
1972
+ return this.getContext(false)._id;
1973
+ }
1974
+ /** @ignore */
1975
+ [Symbol.for('nodejs.util.inspect.custom')]() {
1976
+ return `[EntityManager<${this.id}>]`;
1977
+ }
1950
1978
  }