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