@mikro-orm/core 7.0.2 → 7.0.3-dev.0

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