@mikro-orm/core 7.0.2-dev.9 → 7.0.2

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