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

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