@mikro-orm/core 7.0.4 → 7.0.5-dev.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (206) hide show
  1. package/EntityManager.d.ts +583 -884
  2. package/EntityManager.js +1895 -1922
  3. package/MikroORM.d.ts +74 -103
  4. package/MikroORM.js +179 -178
  5. package/README.md +1 -1
  6. package/cache/CacheAdapter.d.ts +36 -36
  7. package/cache/FileCacheAdapter.d.ts +24 -30
  8. package/cache/FileCacheAdapter.js +78 -80
  9. package/cache/GeneratedCacheAdapter.d.ts +20 -18
  10. package/cache/GeneratedCacheAdapter.js +30 -30
  11. package/cache/MemoryCacheAdapter.d.ts +20 -18
  12. package/cache/MemoryCacheAdapter.js +36 -35
  13. package/cache/NullCacheAdapter.d.ts +16 -16
  14. package/cache/NullCacheAdapter.js +24 -24
  15. package/connections/Connection.d.ts +84 -95
  16. package/connections/Connection.js +168 -165
  17. package/drivers/DatabaseDriver.d.ts +80 -186
  18. package/drivers/DatabaseDriver.js +443 -450
  19. package/drivers/IDatabaseDriver.d.ts +301 -440
  20. package/entity/BaseEntity.d.ts +83 -120
  21. package/entity/BaseEntity.js +43 -43
  22. package/entity/Collection.d.ts +179 -212
  23. package/entity/Collection.js +721 -727
  24. package/entity/EntityAssigner.d.ts +77 -88
  25. package/entity/EntityAssigner.js +230 -231
  26. package/entity/EntityFactory.d.ts +54 -66
  27. package/entity/EntityFactory.js +383 -425
  28. package/entity/EntityHelper.d.ts +22 -34
  29. package/entity/EntityHelper.js +267 -280
  30. package/entity/EntityIdentifier.d.ts +4 -4
  31. package/entity/EntityIdentifier.js +10 -10
  32. package/entity/EntityLoader.d.ts +72 -98
  33. package/entity/EntityLoader.js +723 -753
  34. package/entity/EntityRepository.d.ts +201 -316
  35. package/entity/EntityRepository.js +213 -213
  36. package/entity/PolymorphicRef.d.ts +5 -5
  37. package/entity/PolymorphicRef.js +10 -10
  38. package/entity/Reference.d.ts +82 -126
  39. package/entity/Reference.js +274 -278
  40. package/entity/WrappedEntity.d.ts +72 -115
  41. package/entity/WrappedEntity.js +166 -168
  42. package/entity/defineEntity.d.ts +636 -1315
  43. package/entity/defineEntity.js +518 -527
  44. package/entity/utils.d.ts +3 -13
  45. package/entity/utils.js +73 -71
  46. package/entity/validators.js +43 -43
  47. package/entity/wrap.js +8 -8
  48. package/enums.d.ts +253 -258
  49. package/enums.js +252 -251
  50. package/errors.d.ts +72 -114
  51. package/errors.js +253 -350
  52. package/events/EventManager.d.ts +14 -26
  53. package/events/EventManager.js +77 -79
  54. package/events/EventSubscriber.d.ts +29 -29
  55. package/events/TransactionEventBroadcaster.d.ts +8 -15
  56. package/events/TransactionEventBroadcaster.js +14 -14
  57. package/exceptions.d.ts +40 -23
  58. package/exceptions.js +52 -35
  59. package/hydration/Hydrator.d.ts +17 -42
  60. package/hydration/Hydrator.js +43 -43
  61. package/hydration/ObjectHydrator.d.ts +17 -50
  62. package/hydration/ObjectHydrator.js +416 -481
  63. package/index.d.ts +2 -116
  64. package/index.js +1 -10
  65. package/logging/DefaultLogger.d.ts +32 -34
  66. package/logging/DefaultLogger.js +86 -86
  67. package/logging/Logger.d.ts +41 -41
  68. package/logging/SimpleLogger.d.ts +11 -13
  69. package/logging/SimpleLogger.js +22 -22
  70. package/logging/colors.d.ts +6 -6
  71. package/logging/colors.js +10 -11
  72. package/logging/inspect.js +7 -7
  73. package/metadata/EntitySchema.d.ts +127 -211
  74. package/metadata/EntitySchema.js +398 -397
  75. package/metadata/MetadataDiscovery.d.ts +114 -114
  76. package/metadata/MetadataDiscovery.js +1870 -1951
  77. package/metadata/MetadataProvider.d.ts +21 -24
  78. package/metadata/MetadataProvider.js +84 -82
  79. package/metadata/MetadataStorage.d.ts +32 -38
  80. package/metadata/MetadataStorage.js +118 -118
  81. package/metadata/MetadataValidator.d.ts +39 -39
  82. package/metadata/MetadataValidator.js +338 -381
  83. package/metadata/discover-entities.d.ts +2 -5
  84. package/metadata/discover-entities.js +37 -35
  85. package/metadata/types.d.ts +531 -615
  86. package/naming-strategy/AbstractNamingStrategy.d.ts +39 -54
  87. package/naming-strategy/AbstractNamingStrategy.js +85 -90
  88. package/naming-strategy/EntityCaseNamingStrategy.d.ts +6 -6
  89. package/naming-strategy/EntityCaseNamingStrategy.js +22 -22
  90. package/naming-strategy/MongoNamingStrategy.d.ts +6 -6
  91. package/naming-strategy/MongoNamingStrategy.js +18 -18
  92. package/naming-strategy/NamingStrategy.d.ts +99 -109
  93. package/naming-strategy/UnderscoreNamingStrategy.d.ts +7 -7
  94. package/naming-strategy/UnderscoreNamingStrategy.js +21 -21
  95. package/not-supported.js +4 -7
  96. package/package.json +1 -1
  97. package/platforms/ExceptionConverter.d.ts +1 -1
  98. package/platforms/ExceptionConverter.js +4 -4
  99. package/platforms/Platform.d.ts +301 -310
  100. package/platforms/Platform.js +640 -663
  101. package/serialization/EntitySerializer.d.ts +26 -49
  102. package/serialization/EntitySerializer.js +218 -224
  103. package/serialization/EntityTransformer.d.ts +6 -10
  104. package/serialization/EntityTransformer.js +217 -219
  105. package/serialization/SerializationContext.d.ts +23 -27
  106. package/serialization/SerializationContext.js +105 -105
  107. package/types/ArrayType.d.ts +8 -8
  108. package/types/ArrayType.js +33 -33
  109. package/types/BigIntType.d.ts +10 -17
  110. package/types/BigIntType.js +37 -37
  111. package/types/BlobType.d.ts +3 -3
  112. package/types/BlobType.js +13 -13
  113. package/types/BooleanType.d.ts +4 -4
  114. package/types/BooleanType.js +12 -12
  115. package/types/CharacterType.d.ts +2 -2
  116. package/types/CharacterType.js +6 -6
  117. package/types/DateTimeType.d.ts +5 -5
  118. package/types/DateTimeType.js +15 -15
  119. package/types/DateType.d.ts +5 -5
  120. package/types/DateType.js +15 -15
  121. package/types/DecimalType.d.ts +7 -7
  122. package/types/DecimalType.js +26 -26
  123. package/types/DoubleType.d.ts +3 -3
  124. package/types/DoubleType.js +12 -12
  125. package/types/EnumArrayType.d.ts +5 -5
  126. package/types/EnumArrayType.js +24 -24
  127. package/types/EnumType.d.ts +3 -3
  128. package/types/EnumType.js +11 -11
  129. package/types/FloatType.d.ts +3 -3
  130. package/types/FloatType.js +9 -9
  131. package/types/IntegerType.d.ts +3 -3
  132. package/types/IntegerType.js +9 -9
  133. package/types/IntervalType.d.ts +4 -4
  134. package/types/IntervalType.js +12 -12
  135. package/types/JsonType.d.ts +8 -8
  136. package/types/JsonType.js +32 -32
  137. package/types/MediumIntType.d.ts +1 -1
  138. package/types/MediumIntType.js +3 -3
  139. package/types/SmallIntType.d.ts +3 -3
  140. package/types/SmallIntType.js +9 -9
  141. package/types/StringType.d.ts +4 -4
  142. package/types/StringType.js +12 -12
  143. package/types/TextType.d.ts +3 -3
  144. package/types/TextType.js +9 -9
  145. package/types/TimeType.d.ts +5 -5
  146. package/types/TimeType.js +17 -17
  147. package/types/TinyIntType.d.ts +3 -3
  148. package/types/TinyIntType.js +10 -10
  149. package/types/Type.d.ts +79 -83
  150. package/types/Type.js +82 -82
  151. package/types/Uint8ArrayType.d.ts +4 -4
  152. package/types/Uint8ArrayType.js +21 -21
  153. package/types/UnknownType.d.ts +4 -4
  154. package/types/UnknownType.js +12 -12
  155. package/types/UuidType.d.ts +5 -5
  156. package/types/UuidType.js +19 -19
  157. package/types/index.d.ts +49 -75
  158. package/types/index.js +26 -52
  159. package/typings.d.ts +737 -1250
  160. package/typings.js +231 -244
  161. package/unit-of-work/ChangeSet.d.ts +26 -26
  162. package/unit-of-work/ChangeSet.js +56 -56
  163. package/unit-of-work/ChangeSetComputer.d.ts +12 -12
  164. package/unit-of-work/ChangeSetComputer.js +170 -178
  165. package/unit-of-work/ChangeSetPersister.d.ts +44 -63
  166. package/unit-of-work/ChangeSetPersister.js +421 -442
  167. package/unit-of-work/CommitOrderCalculator.d.ts +40 -40
  168. package/unit-of-work/CommitOrderCalculator.js +88 -89
  169. package/unit-of-work/IdentityMap.d.ts +31 -31
  170. package/unit-of-work/IdentityMap.js +105 -105
  171. package/unit-of-work/UnitOfWork.d.ts +141 -181
  172. package/unit-of-work/UnitOfWork.js +1183 -1200
  173. package/utils/AbstractMigrator.d.ts +91 -111
  174. package/utils/AbstractMigrator.js +275 -275
  175. package/utils/AbstractSchemaGenerator.d.ts +34 -43
  176. package/utils/AbstractSchemaGenerator.js +122 -121
  177. package/utils/AsyncContext.d.ts +3 -3
  178. package/utils/AsyncContext.js +35 -34
  179. package/utils/Configuration.d.ts +808 -852
  180. package/utils/Configuration.js +344 -359
  181. package/utils/Cursor.d.ts +22 -40
  182. package/utils/Cursor.js +127 -135
  183. package/utils/DataloaderUtils.d.ts +43 -58
  184. package/utils/DataloaderUtils.js +198 -203
  185. package/utils/EntityComparator.d.ts +81 -98
  186. package/utils/EntityComparator.js +732 -828
  187. package/utils/NullHighlighter.d.ts +1 -1
  188. package/utils/NullHighlighter.js +3 -3
  189. package/utils/QueryHelper.d.ts +51 -79
  190. package/utils/QueryHelper.js +361 -372
  191. package/utils/RawQueryFragment.d.ts +34 -50
  192. package/utils/RawQueryFragment.js +105 -107
  193. package/utils/RequestContext.d.ts +32 -32
  194. package/utils/RequestContext.js +53 -52
  195. package/utils/TransactionContext.d.ts +16 -16
  196. package/utils/TransactionContext.js +27 -27
  197. package/utils/TransactionManager.d.ts +58 -58
  198. package/utils/TransactionManager.js +197 -199
  199. package/utils/Utils.d.ts +145 -204
  200. package/utils/Utils.js +812 -812
  201. package/utils/clone.js +113 -104
  202. package/utils/env-vars.js +88 -90
  203. package/utils/fs-utils.d.ts +15 -15
  204. package/utils/fs-utils.js +181 -180
  205. package/utils/upsert-utils.d.ts +5 -20
  206. package/utils/upsert-utils.js +116 -114
@@ -6,52 +6,8 @@ import { type EntityRepository } from './entity/EntityRepository.js';
6
6
  import { EntityLoader, type EntityLoaderOptions } from './entity/EntityLoader.js';
7
7
  import { Reference } from './entity/Reference.js';
8
8
  import { UnitOfWork } from './unit-of-work/UnitOfWork.js';
9
- import type {
10
- CountOptions,
11
- DeleteOptions,
12
- FilterOptions,
13
- FindAllOptions,
14
- FindByCursorOptions,
15
- FindOneOptions,
16
- FindOneOrFailOptions,
17
- FindOptions,
18
- GetReferenceOptions,
19
- IDatabaseDriver,
20
- LockOptions,
21
- NativeInsertUpdateOptions,
22
- StreamOptions,
23
- UpdateOptions,
24
- UpsertManyOptions,
25
- UpsertOptions,
26
- } from './drivers/IDatabaseDriver.js';
27
- import type {
28
- AnyString,
29
- ArrayElement,
30
- AutoPath,
31
- ConnectionType,
32
- Dictionary,
33
- EntityClass,
34
- EntityData,
35
- EntityDictionary,
36
- EntityDTO,
37
- EntityMetadata,
38
- EntityName,
39
- FilterDef,
40
- FilterQuery,
41
- FromEntityType,
42
- GetRepository,
43
- IHydrator,
44
- IsSubset,
45
- Loaded,
46
- MergeLoaded,
47
- MergeSelected,
48
- ObjectQuery,
49
- PopulateOptions,
50
- Primary,
51
- Ref,
52
- RequiredEntityData,
53
- UnboxArray,
54
- } from './typings.js';
9
+ import type { CountOptions, DeleteOptions, FilterOptions, FindAllOptions, FindByCursorOptions, FindOneOptions, FindOneOrFailOptions, FindOptions, GetReferenceOptions, IDatabaseDriver, LockOptions, NativeInsertUpdateOptions, StreamOptions, UpdateOptions, UpsertManyOptions, UpsertOptions } from './drivers/IDatabaseDriver.js';
10
+ import type { AnyString, ArrayElement, AutoPath, ConnectionType, Dictionary, EntityClass, EntityData, EntityDictionary, EntityDTO, EntityMetadata, EntityName, FilterDef, FilterQuery, FromEntityType, GetRepository, IHydrator, IsSubset, Loaded, MergeLoaded, MergeSelected, ObjectQuery, PopulateOptions, Primary, Ref, RequiredEntityData, UnboxArray } from './typings.js';
55
11
  import { FlushMode, LockMode, PopulatePath, type TransactionOptions } from './enums.js';
56
12
  import type { MetadataStorage } from './metadata/MetadataStorage.js';
57
13
  import type { Transaction } from './connections/Connection.js';
@@ -63,850 +19,593 @@ import type { EntityComparator } from './utils/EntityComparator.js';
63
19
  * @template {IDatabaseDriver} Driver current driver type
64
20
  */
65
21
  export declare class EntityManager<Driver extends IDatabaseDriver = IDatabaseDriver> {
66
- #private;
67
- readonly config: Configuration;
68
- protected readonly driver: Driver;
69
- protected readonly metadata: MetadataStorage;
70
- protected readonly eventManager: EventManager;
71
- /** @internal */
72
- readonly '~entities'?: unknown;
73
- /** @internal */
74
- readonly _id: number;
75
- /** Whether this is the global (root) EntityManager instance. */
76
- readonly global = false;
77
- /** The context name of this EntityManager, derived from the ORM configuration. */
78
- readonly name: string;
79
- protected loggerContext?: Dictionary;
80
- /**
81
- * @internal
82
- */
83
- constructor(
84
- config: Configuration,
85
- driver: Driver,
86
- metadata: MetadataStorage,
87
- useContext?: boolean,
88
- eventManager?: EventManager,
89
- );
90
- /**
91
- * Gets the Driver instance used by this EntityManager.
92
- * Driver is singleton, for one MikroORM instance, only one driver is created.
93
- */
94
- getDriver(): Driver;
95
- /**
96
- * Gets the Connection instance, by default returns write connection
97
- */
98
- getConnection(type?: ConnectionType): ReturnType<Driver['getConnection']>;
99
- /**
100
- * Gets the platform instance. Just like the driver, platform is singleton, one for a MikroORM instance.
101
- */
102
- getPlatform(): ReturnType<Driver['getPlatform']>;
103
- /**
104
- * Gets repository for given entity. You can pass either string name or entity class reference.
105
- */
106
- getRepository<Entity extends object, Repository extends EntityRepository<Entity> = EntityRepository<Entity>>(
107
- entityName: EntityName<Entity>,
108
- ): GetRepository<Entity, Repository>;
109
- /**
110
- * Shortcut for `em.getRepository()`.
111
- */
112
- repo<Entity extends object, Repository extends EntityRepository<Entity> = EntityRepository<Entity>>(
113
- entityName: EntityName<Entity>,
114
- ): GetRepository<Entity, Repository>;
115
- /**
116
- * Finds all entities matching your `where` query. You can pass additional options via the `options` parameter.
117
- */
118
- find<
119
- Entity extends object,
120
- Hint extends string = never,
121
- Fields extends string = never,
122
- Excludes extends string = never,
123
- >(
124
- entityName: EntityName<Entity>,
125
- where: FilterQuery<NoInfer<Entity>>,
126
- options?: FindOptions<Entity, Hint, Fields, Excludes>,
127
- ): Promise<Loaded<Entity, Hint, Fields, Excludes>[]>;
128
- /**
129
- * Finds all entities and returns an async iterable (async generator) that yields results one by one.
130
- * The results are merged and mapped to entity instances, without adding them to the identity map.
131
- * You can disable merging by passing the options `{ mergeResults: false }`.
132
- * With `mergeResults` disabled, to-many collections will contain at most one item, and you will get duplicate
133
- * root entities when there are multiple items in the populated collection.
134
- * This is useful for processing large datasets without loading everything into memory at once.
135
- *
136
- * ```ts
137
- * const stream = em.stream(Book, { populate: ['author'] });
138
- *
139
- * for await (const book of stream) {
140
- * // book is an instance of Book entity
141
- * console.log(book.title, book.author.name);
142
- * }
143
- * ```
144
- */
145
- stream<
146
- Entity extends object,
147
- Hint extends string = never,
148
- Fields extends string = never,
149
- Excludes extends string = never,
150
- >(
151
- entityName: EntityName<Entity>,
152
- options?: StreamOptions<NoInfer<Entity>, Hint, Fields, Excludes>,
153
- ): AsyncIterableIterator<Loaded<Entity, Hint, Fields, Excludes>>;
154
- /**
155
- * Finds all entities of given type, optionally matching the `where` condition provided in the `options` parameter.
156
- */
157
- findAll<
158
- Entity extends object,
159
- Hint extends string = never,
160
- Fields extends string = never,
161
- Excludes extends string = never,
162
- >(
163
- entityName: EntityName<Entity>,
164
- options?: FindAllOptions<NoInfer<Entity>, Hint, Fields, Excludes>,
165
- ): Promise<Loaded<Entity, Hint, Fields, Excludes>[]>;
166
- private getPopulateWhere;
167
- /**
168
- * Registers global filter to this entity manager. Global filters are enabled by default (unless disabled via last parameter).
169
- */
170
- addFilter<T extends EntityName | readonly EntityName[]>(options: FilterDef<T>): void;
171
- /**
172
- * Sets filter parameter values globally inside context defined by this entity manager.
173
- * If you want to set shared value for all contexts, be sure to use the root entity manager.
174
- */
175
- setFilterParams(name: string, args: Dictionary): void;
176
- /**
177
- * Returns filter parameters for given filter set in this context.
178
- */
179
- getFilterParams<T extends Dictionary = Dictionary>(name: string): T;
180
- /**
181
- * Sets logger context for this entity manager.
182
- */
183
- setLoggerContext(context: Dictionary): void;
184
- /**
185
- * Gets logger context for this entity manager.
186
- */
187
- getLoggerContext<T extends Dictionary = Dictionary>(options?: { disableContextResolution?: boolean }): T;
188
- /** Sets the flush mode for this EntityManager. Pass `undefined` to reset to the global default. */
189
- setFlushMode(flushMode?: FlushMode | `${FlushMode}`): void;
190
- protected processWhere<
191
- Entity extends object,
192
- Hint extends string = never,
193
- Fields extends string = never,
194
- Excludes extends string = never,
195
- >(
196
- entityName: EntityName<Entity>,
197
- where: FilterQuery<Entity>,
198
- options: FindOptions<Entity, Hint, Fields, Excludes> | FindOneOptions<Entity, Hint, Fields, Excludes>,
199
- type: 'read' | 'update' | 'delete',
200
- ): Promise<FilterQuery<Entity>>;
201
- protected processUnionWhere<Entity extends object, Hint extends string = never>(
202
- entityName: EntityName<Entity>,
203
- options:
204
- | FindOptions<Entity, Hint, any, any>
205
- | CountOptions<Entity, Hint>
206
- | UpdateOptions<Entity>
207
- | DeleteOptions<Entity>,
208
- type: 'read' | 'update' | 'delete',
209
- ): Promise<void>;
210
- protected applyDiscriminatorCondition<Entity extends object>(
211
- entityName: EntityName<Entity>,
212
- where: FilterQuery<Entity>,
213
- ): FilterQuery<Entity>;
214
- protected createPopulateWhere<Entity extends object>(
215
- cond: ObjectQuery<Entity>,
216
- options: FindOptions<Entity, any, any, any> | FindOneOptions<Entity, any, any, any> | CountOptions<Entity, any>,
217
- ): ObjectQuery<Entity>;
218
- protected getJoinedFilters<Entity extends object>(
219
- meta: EntityMetadata<Entity>,
220
- options: FindOptions<Entity, any, any, any> | FindOneOptions<Entity, any, any, any>,
221
- ): Promise<ObjectQuery<Entity> | undefined>;
222
- /**
223
- * 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.
224
- */
225
- protected autoJoinRefsForFilters<T extends object>(
226
- meta: EntityMetadata<T>,
227
- options: FindOptions<T, any, any, any> | FindOneOptions<T, any, any, any>,
228
- parent?: {
229
- class: EntityClass;
230
- propName: string;
231
- },
232
- ): Promise<void>;
233
- /**
234
- * @internal
235
- */
236
- applyFilters<Entity extends object>(
237
- entityName: EntityName<Entity>,
238
- where: FilterQuery<Entity> | undefined,
239
- options: FilterOptions | undefined,
240
- type: 'read' | 'update' | 'delete',
241
- findOptions?: FindOptions<any, any, any, any> | FindOneOptions<any, any, any, any>,
242
- ): Promise<FilterQuery<Entity> | undefined>;
243
- /**
244
- * Calls `em.find()` and `em.count()` with the same arguments (where applicable) and returns the results as tuple
245
- * where the first element is the array of entities, and the second is the count.
246
- */
247
- findAndCount<
248
- Entity extends object,
249
- Hint extends string = never,
250
- Fields extends string = never,
251
- Excludes extends string = never,
252
- >(
253
- entityName: EntityName<Entity>,
254
- where: FilterQuery<NoInfer<Entity>>,
255
- options?: FindOptions<Entity, Hint, Fields, Excludes>,
256
- ): Promise<[Loaded<Entity, Hint, Fields, Excludes>[], number]>;
257
- /**
258
- * Calls `em.find()` and `em.count()` with the same arguments (where applicable) and returns the results as {@apilink Cursor} object.
259
- * Supports `before`, `after`, `first` and `last` options while disallowing `limit` and `offset`. Explicit `orderBy` option
260
- * is required.
261
- *
262
- * Use `first` and `after` for forward pagination, or `last` and `before` for backward pagination.
263
- *
264
- * - `first` and `last` are numbers and serve as an alternative to `offset`, those options are mutually exclusive, use only one at a time
265
- * - `before` and `after` specify the previous cursor value, it can be one of the:
266
- * - `Cursor` instance
267
- * - opaque string provided by `startCursor/endCursor` properties
268
- * - POJO/entity instance
269
- *
270
- * ```ts
271
- * const currentCursor = await em.findByCursor(User, {
272
- * first: 10,
273
- * after: previousCursor, // cursor instance
274
- * orderBy: { id: 'desc' },
275
- * });
276
- *
277
- * // to fetch next page
278
- * const nextCursor = await em.findByCursor(User, {
279
- * first: 10,
280
- * after: currentCursor.endCursor, // opaque string
281
- * orderBy: { id: 'desc' },
282
- * });
283
- *
284
- * // to fetch next page
285
- * const nextCursor2 = await em.findByCursor(User, {
286
- * first: 10,
287
- * after: { id: lastSeenId }, // entity-like POJO
288
- * orderBy: { id: 'desc' },
289
- * });
290
- * ```
291
- *
292
- * The options also support an `includeCount` (true by default) option. If set to false, the `totalCount` is not
293
- * returned as part of the cursor. This is useful for performance reason, when you don't care about the total number
294
- * of pages.
295
- *
296
- * The `Cursor` object provides the following interface:
297
- *
298
- * ```ts
299
- * Cursor<User> {
300
- * items: [
301
- * User { ... },
302
- * User { ... },
303
- * User { ... },
304
- * ],
305
- * totalCount: 50, // not included if `includeCount: false`
306
- * startCursor: 'WzRd',
307
- * endCursor: 'WzZd',
308
- * hasPrevPage: true,
309
- * hasNextPage: true,
310
- * }
311
- * ```
312
- */
313
- findByCursor<
314
- Entity extends object,
315
- Hint extends string = never,
316
- Fields extends string = never,
317
- Excludes extends string = never,
318
- IncludeCount extends boolean = true,
319
- >(
320
- entityName: EntityName<Entity>,
321
- options: FindByCursorOptions<Entity, Hint, Fields, Excludes, IncludeCount>,
322
- ): Promise<Cursor<Entity, Hint, Fields, Excludes, IncludeCount>>;
323
- /**
324
- * Refreshes the persistent state of an entity from the database, overriding any local changes that have not yet been
325
- * persisted. Returns the same entity instance (same object reference), but re-hydrated. If the entity is no longer
326
- * in database, the method throws an error just like `em.findOneOrFail()` (and respects the same config options).
327
- */
328
- refreshOrFail<
329
- Entity extends object,
330
- Naked extends FromEntityType<Entity> = FromEntityType<Entity>,
331
- Hint extends string = never,
332
- Fields extends string = never,
333
- Excludes extends string = never,
334
- >(
335
- entity: Entity,
336
- options?: FindOneOrFailOptions<Entity, Hint, Fields, Excludes>,
337
- ): Promise<MergeLoaded<Entity, Naked, Hint, Fields, Excludes, true>>;
338
- /**
339
- * Refreshes the persistent state of an entity from the database, overriding any local changes that have not yet been
340
- * persisted. Returns the same entity instance (same object reference), but re-hydrated. If the entity is no longer
341
- * in database, the method returns `null`.
342
- */
343
- refresh<
344
- Entity extends object,
345
- Naked extends FromEntityType<Entity> = FromEntityType<Entity>,
346
- Hint extends string = never,
347
- Fields extends string = never,
348
- Excludes extends string = never,
349
- >(
350
- entity: Entity,
351
- options?: FindOneOptions<Entity, Hint, Fields, Excludes>,
352
- ): Promise<MergeLoaded<Entity, Naked, Hint, Fields, Excludes, true> | null>;
353
- /**
354
- * Finds first entity matching your `where` query.
355
- */
356
- findOne<
357
- Entity extends object,
358
- Hint extends string = never,
359
- Fields extends string = never,
360
- Excludes extends string = never,
361
- >(
362
- entityName: EntityName<Entity>,
363
- where: FilterQuery<NoInfer<Entity>>,
364
- options?: FindOneOptions<Entity, Hint, Fields, Excludes>,
365
- ): Promise<Loaded<Entity, Hint, Fields, Excludes> | null>;
366
- /**
367
- * Finds first entity matching your `where` query. If nothing found, it will throw an error.
368
- * If the `strict` option is specified and nothing is found or more than one matching entity is found, it will throw an error.
369
- * You can override the factory for creating this method via `options.failHandler` locally
370
- * or via `Configuration.findOneOrFailHandler` (`findExactlyOneOrFailHandler` when specifying `strict`) globally.
371
- */
372
- findOneOrFail<
373
- Entity extends object,
374
- Hint extends string = never,
375
- Fields extends string = never,
376
- Excludes extends string = never,
377
- >(
378
- entityName: EntityName<Entity>,
379
- where: FilterQuery<NoInfer<Entity>>,
380
- options?: FindOneOrFailOptions<Entity, Hint, Fields, Excludes>,
381
- ): Promise<Loaded<Entity, Hint, Fields, Excludes>>;
382
- /**
383
- * Creates or updates the entity, based on whether it is already present in the database.
384
- * This method performs an `insert on conflict merge` query ensuring the database is in sync, returning a managed
385
- * entity instance. The method accepts either `entityName` together with the entity `data`, or just entity instance.
386
- *
387
- * ```ts
388
- * // insert into "author" ("age", "email") values (33, 'foo@bar.com') on conflict ("email") do update set "age" = 41
389
- * const author = await em.upsert(Author, { email: 'foo@bar.com', age: 33 });
390
- * ```
391
- *
392
- * 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:
393
- *
394
- * ```ts
395
- * // insert into "author" ("age", "email") values (33, 'foo@bar.com') on conflict ("email") do update set "age" = 41
396
- * // select "id" from "author" where "email" = 'foo@bar.com'
397
- * const author = await em.upsert(Author, { email: 'foo@bar.com', age: 33 });
398
- * ```
399
- *
400
- * 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`.
401
- *
402
- * 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.
403
- */
404
- upsert<Entity extends object, Fields extends string = any>(
405
- entityNameOrEntity: EntityName<Entity> | Entity,
406
- data?: EntityData<Entity> | NoInfer<Entity>,
407
- options?: UpsertOptions<Entity, Fields>,
408
- ): Promise<Entity>;
409
- /**
410
- * Creates or updates the entity, based on whether it is already present in the database.
411
- * This method performs an `insert on conflict merge` query ensuring the database is in sync, returning a managed
412
- * entity instance. The method accepts either `entityName` together with the entity `data`, or just entity instance.
413
- *
414
- * ```ts
415
- * // insert into "author" ("age", "email") values (33, 'foo@bar.com') on conflict ("email") do update set "age" = 41
416
- * const authors = await em.upsertMany(Author, [{ email: 'foo@bar.com', age: 33 }, ...]);
417
- * ```
418
- *
419
- * 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:
420
- *
421
- * ```ts
422
- * // insert into "author" ("age", "email") values (33, 'foo@bar.com'), (666, 'lol@lol.lol') on conflict ("email") do update set "age" = excluded."age"
423
- * // select "id" from "author" where "email" = 'foo@bar.com'
424
- * const author = await em.upsertMany(Author, [
425
- * { email: 'foo@bar.com', age: 33 },
426
- * { email: 'lol@lol.lol', age: 666 },
427
- * ]);
428
- * ```
429
- *
430
- * 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`.
431
- *
432
- * 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.
433
- */
434
- upsertMany<Entity extends object, Fields extends string = any>(
435
- entityNameOrEntity: EntityName<Entity> | Entity[],
436
- data?: (EntityData<Entity> | NoInfer<Entity>)[],
437
- options?: UpsertManyOptions<Entity, Fields>,
438
- ): Promise<Entity[]>;
439
- /**
440
- * Runs your callback wrapped inside a database transaction.
441
- *
442
- * If a transaction is already active, a new savepoint (nested transaction) will be created by default. This behavior
443
- * can be controlled via the `propagation` option. Use the provided EntityManager instance for all operations that
444
- * should be part of the transaction. You can safely use a global EntityManager instance from a DI container, as this
445
- * method automatically creates an async context for the transaction.
446
- *
447
- * **Concurrency note:** When running multiple transactions concurrently (e.g. in parallel requests or jobs), use the
448
- * `clear: true` option. This ensures the callback runs in a clear fork of the EntityManager, providing full isolation
449
- * between concurrent transactional handlers. Using `clear: true` is an alternative to forking explicitly and calling
450
- * the method on the new fork – it already provides the necessary isolation for safe concurrent usage.
451
- *
452
- * **Propagation note:** Changes made within a transaction (whether top-level or nested) are always propagated to the
453
- * parent context, unless the parent context is a global one. If you want to avoid that, fork the EntityManager first
454
- * and then call this method on the fork.
455
- *
456
- * **Example:**
457
- * ```ts
458
- * await em.transactional(async (em) => {
459
- * const author = new Author('Jon');
460
- * em.persist(author);
461
- * // flush is called automatically at the end of the callback
462
- * });
463
- * ```
464
- */
465
- transactional<T>(cb: (em: this) => T | Promise<T>, options?: TransactionOptions): Promise<T>;
466
- /**
467
- * Starts new transaction bound to this EntityManager. Use `ctx` parameter to provide the parent when nesting transactions.
468
- */
469
- begin(options?: Omit<TransactionOptions, 'ignoreNestedTransactions'>): Promise<void>;
470
- /**
471
- * Commits the transaction bound to this EntityManager. Flushes before doing the actual commit query.
472
- */
473
- commit(): Promise<void>;
474
- /**
475
- * Rollbacks the transaction bound to this EntityManager.
476
- */
477
- rollback(): Promise<void>;
478
- /**
479
- * Runs your callback wrapped inside a database transaction.
480
- */
481
- lock<T extends object>(entity: T, lockMode: LockMode, options?: LockOptions | number | Date): Promise<void>;
482
- /**
483
- * Fires native insert query. Calling this has no side effects on the context (identity map).
484
- */
485
- insert<Entity extends object>(
486
- entityNameOrEntity: EntityName<Entity> | Entity,
487
- data?: RequiredEntityData<Entity> | Entity,
488
- options?: NativeInsertUpdateOptions<Entity>,
489
- ): Promise<Primary<Entity>>;
490
- /**
491
- * Fires native multi-insert query. Calling this has no side effects on the context (identity map).
492
- */
493
- insertMany<Entity extends object>(
494
- entityNameOrEntities: EntityName<Entity> | Entity[],
495
- data?: RequiredEntityData<Entity>[] | Entity[],
496
- options?: NativeInsertUpdateOptions<Entity>,
497
- ): Promise<Primary<Entity>[]>;
498
- /**
499
- * Fires native update query. Calling this has no side effects on the context (identity map).
500
- */
501
- nativeUpdate<Entity extends object>(
502
- entityName: EntityName<Entity>,
503
- where: FilterQuery<NoInfer<Entity>>,
504
- data: EntityData<Entity>,
505
- options?: UpdateOptions<Entity>,
506
- ): Promise<number>;
507
- /**
508
- * Fires native delete query. Calling this has no side effects on the context (identity map).
509
- */
510
- nativeDelete<Entity extends object>(
511
- entityName: EntityName<Entity>,
512
- where: FilterQuery<NoInfer<Entity>>,
513
- options?: DeleteOptions<Entity>,
514
- ): Promise<number>;
515
- /**
516
- * Maps raw database result to an entity and merges it to this EntityManager.
517
- */
518
- map<Entity extends object>(
519
- entityName: EntityName<Entity>,
520
- result: EntityDictionary<Entity>,
521
- options?: {
522
- schema?: string;
523
- },
524
- ): Entity;
525
- /**
526
- * Merges given entity to this EntityManager so it becomes managed. You can force refreshing of existing entities
527
- * via second parameter. By default, it will return already loaded entities without modifying them.
528
- */
529
- merge<Entity extends object>(entity: Entity, options?: MergeOptions): Entity;
530
- /**
531
- * Merges given entity to this EntityManager so it becomes managed. You can force refreshing of existing entities
532
- * via second parameter. By default, it will return already loaded entities without modifying them.
533
- */
534
- merge<Entity extends object>(
535
- entityName: EntityName<Entity>,
536
- data: EntityData<Entity> | EntityDTO<Entity>,
537
- options?: MergeOptions,
538
- ): Entity;
539
- /**
540
- * Creates new instance of given entity and populates it with given data.
541
- * The entity constructor will be used unless you provide `{ managed: true }` in the `options` parameter.
542
- * The constructor will be given parameters based on the defined constructor of the entity. If the constructor
543
- * parameter matches a property name, its value will be extracted from `data`. If no matching property exists,
544
- * the whole `data` parameter will be passed. This means we can also define `constructor(data: Partial<T>)` and
545
- * `em.create()` will pass the data into it (unless we have a property named `data` too).
546
- *
547
- * The parameters are strictly checked, you need to provide all required properties. You can use `OptionalProps`
548
- * symbol to omit some properties from this check without making them optional. Alternatively, use `partial: true`
549
- * in the options to disable the strict checks for required properties. This option has no effect on runtime.
550
- *
551
- * The newly created entity will be automatically marked for persistence via `em.persist` unless you disable this
552
- * behavior, either locally via `persist: false` option, or globally via `persistOnCreate` ORM config option.
553
- */
554
- create<
555
- Entity extends object,
556
- Convert extends boolean = false,
557
- Data extends RequiredEntityData<Entity, never, Convert> = RequiredEntityData<Entity, never, Convert>,
558
- >(
559
- entityName: EntityName<Entity>,
560
- data: Data & IsSubset<RequiredEntityData<Entity, never, Convert>, Data>,
561
- options?: CreateOptions<Convert>,
562
- ): Entity;
563
- /**
564
- * Creates new instance of given entity and populates it with given data.
565
- * The entity constructor will be used unless you provide `{ managed: true }` in the `options` parameter.
566
- * The constructor will be given parameters based on the defined constructor of the entity. If the constructor
567
- * parameter matches a property name, its value will be extracted from `data`. If no matching property exists,
568
- * the whole `data` parameter will be passed. This means we can also define `constructor(data: Partial<T>)` and
569
- * `em.create()` will pass the data into it (unless we have a property named `data` too).
570
- *
571
- * The parameters are strictly checked, you need to provide all required properties. You can use `OptionalProps`
572
- * symbol to omit some properties from this check without making them optional. Alternatively, use `partial: true`
573
- * in the options to disable the strict checks for required properties. This option has no effect on runtime.
574
- *
575
- * The newly created entity will be automatically marked for persistence via `em.persist` unless you disable this
576
- * behavior, either locally via `persist: false` option, or globally via `persistOnCreate` ORM config option.
577
- */
578
- create<
579
- Entity extends object,
580
- Convert extends boolean = false,
581
- Data extends EntityData<Entity, Convert> = EntityData<Entity, Convert>,
582
- >(
583
- entityName: EntityName<Entity>,
584
- data: Data & IsSubset<EntityData<Entity, Convert>, Data>,
585
- options: CreateOptions<Convert> & {
586
- partial: true;
587
- },
588
- ): Entity;
589
- /**
590
- * Shortcut for `wrap(entity).assign(data, { em })`
591
- */
592
- assign<
593
- Entity extends object,
594
- Naked extends FromEntityType<Entity> = FromEntityType<Entity>,
595
- Convert extends boolean = false,
596
- Data extends EntityData<Naked, Convert> | Partial<EntityDTO<Naked>> =
597
- | EntityData<Naked, Convert>
598
- | Partial<EntityDTO<Naked>>,
599
- >(
600
- entity: Entity | Partial<Entity>,
601
- data: Data & IsSubset<EntityData<Naked, Convert>, Data>,
602
- options?: AssignOptions<Convert>,
603
- ): MergeSelected<Entity, Naked, keyof Data & string>;
604
- /**
605
- * Gets a reference to the entity identified by the given type and alternate key property without actually loading it.
606
- * The key option specifies which property to use for identity map lookup instead of the primary key.
607
- */
608
- getReference<Entity extends object, K extends string & keyof Entity>(
609
- entityName: EntityName<Entity>,
610
- id: Entity[K],
611
- options: Omit<GetReferenceOptions, 'key' | 'wrapped'> & {
612
- key: K;
613
- wrapped: true;
614
- },
615
- ): Ref<Entity>;
616
- /**
617
- * Gets a reference to the entity identified by the given type and alternate key property without actually loading it.
618
- * The key option specifies which property to use for identity map lookup instead of the primary key.
619
- */
620
- getReference<Entity extends object, K extends string & keyof Entity>(
621
- entityName: EntityName<Entity>,
622
- id: Entity[K],
623
- options: Omit<GetReferenceOptions, 'key'> & {
624
- key: K;
625
- wrapped?: false;
626
- },
627
- ): Entity;
628
- /**
629
- * Gets a reference to the entity identified by the given type and identifier without actually loading it, if the entity is not yet loaded
630
- */
631
- getReference<Entity extends object>(
632
- entityName: EntityName<Entity>,
633
- id: Primary<Entity>,
634
- options: Omit<GetReferenceOptions, 'wrapped' | 'key'> & {
635
- wrapped: true;
636
- },
637
- ): Ref<Entity>;
638
- /**
639
- * Gets a reference to the entity identified by the given type and identifier without actually loading it, if the entity is not yet loaded
640
- */
641
- getReference<Entity extends object>(entityName: EntityName<Entity>, id: Primary<Entity> | Primary<Entity>[]): Entity;
642
- /**
643
- * Gets a reference to the entity identified by the given type and identifier without actually loading it, if the entity is not yet loaded
644
- */
645
- getReference<Entity extends object>(
646
- entityName: EntityName<Entity>,
647
- id: Primary<Entity>,
648
- options: Omit<GetReferenceOptions, 'wrapped' | 'key'> & {
649
- wrapped: false;
650
- },
651
- ): Entity;
652
- /**
653
- * Gets a reference to the entity identified by the given type and identifier without actually loading it, if the entity is not yet loaded
654
- */
655
- getReference<Entity extends object>(
656
- entityName: EntityName<Entity>,
657
- id: Primary<Entity>,
658
- options?: GetReferenceOptions,
659
- ): Entity | Reference<Entity>;
660
- /**
661
- * Returns total number of entities matching your `where` query.
662
- */
663
- count<Entity extends object, Hint extends string = never>(
664
- entityName: EntityName<Entity>,
665
- where?: FilterQuery<NoInfer<Entity>>,
666
- options?: CountOptions<Entity, Hint>,
667
- ): Promise<number>;
668
- /**
669
- * Tells the EntityManager to make an instance managed and persistent.
670
- * The entity will be entered into the database at or before transaction commit or as a result of the flush operation.
671
- */
672
- persist<Entity extends object>(entity: Entity | Reference<Entity> | Iterable<Entity | Reference<Entity>>): this;
673
- /**
674
- * Marks entity for removal.
675
- * A removed entity will be removed from the database at or before transaction commit or as a result of the flush operation.
676
- *
677
- * To remove entities by condition, use `em.nativeDelete()`.
678
- */
679
- remove<Entity extends object>(entity: Entity | Reference<Entity> | Iterable<Entity | Reference<Entity>>): this;
680
- /**
681
- * Flushes all changes to objects that have been queued up to now to the database.
682
- * This effectively synchronizes the in-memory state of managed objects with the database.
683
- */
684
- flush(): Promise<void>;
685
- /**
686
- * @internal
687
- */
688
- tryFlush<Entity extends object>(
689
- entityName: EntityName<Entity>,
690
- options: {
691
- flushMode?: FlushMode | AnyString;
692
- },
693
- ): Promise<void>;
694
- /**
695
- * Clears the EntityManager. All entities that are currently managed by this EntityManager become detached.
696
- */
697
- clear(): void;
698
- /**
699
- * Checks whether given property can be populated on the entity.
700
- */
701
- canPopulate<Entity extends object>(entityName: EntityName<Entity>, property: string): boolean;
702
- /**
703
- * Loads specified relations in batch. This will execute one query for each relation, that will populate it on all the specified entities.
704
- */
705
- populate<
706
- Entity extends object,
707
- Naked extends FromEntityType<UnboxArray<Entity>> = FromEntityType<UnboxArray<Entity>>,
708
- Hint extends string = never,
709
- Fields extends string = never,
710
- Excludes extends string = never,
711
- >(
712
- entities: Entity,
713
- populate: readonly AutoPath<Naked, Hint, PopulatePath.ALL>[] | false,
714
- options?: EntityLoaderOptions<Naked, Fields, Excludes>,
715
- ): Promise<
716
- Entity extends object[]
717
- ? MergeLoaded<ArrayElement<Entity>, Naked, Hint, Fields, Excludes>[]
718
- : MergeLoaded<Entity, Naked, Hint, Fields, Excludes>
719
- >;
720
- /**
721
- * Returns new EntityManager instance with its own identity map
722
- */
723
- fork(options?: ForkOptions): this;
724
- /**
725
- * Gets the UnitOfWork used by the EntityManager to coordinate operations.
726
- */
727
- getUnitOfWork(useContext?: boolean): UnitOfWork;
728
- /**
729
- * Gets the EntityFactory used by the EntityManager.
730
- */
731
- getEntityFactory(): EntityFactory;
732
- /**
733
- * @internal use `em.populate()` as the user facing API, this is exposed only for internal usage
734
- */
735
- getEntityLoader(): EntityLoader;
736
- /**
737
- * Gets the Hydrator used by the EntityManager.
738
- */
739
- getHydrator(): IHydrator;
740
- /**
741
- * Gets the EntityManager based on current transaction/request context.
742
- * @internal
743
- */
744
- getContext(validate?: boolean): this;
745
- /** Gets the EventManager instance used by this EntityManager. */
746
- getEventManager(): EventManager;
747
- /**
748
- * Checks whether this EntityManager is currently operating inside a database transaction.
749
- */
750
- isInTransaction(): boolean;
751
- /**
752
- * Gets the transaction context (driver dependent object used to make sure queries are executed on same connection).
753
- */
754
- getTransactionContext<T extends Transaction = Transaction>(): T | undefined;
755
- /**
756
- * Sets the transaction context.
757
- */
758
- setTransactionContext(ctx?: Transaction): void;
759
- /**
760
- * Resets the transaction context.
761
- */
762
- resetTransactionContext(): void;
763
- /**
764
- * Gets the `MetadataStorage`.
765
- */
766
- getMetadata(): MetadataStorage;
767
- /**
768
- * Gets the `EntityMetadata` instance when provided with the `entityName` parameter.
769
- */
770
- getMetadata<Entity extends object>(entityName: EntityName<Entity>): EntityMetadata<Entity>;
771
- /**
772
- * Gets the EntityComparator.
773
- */
774
- getComparator(): EntityComparator;
775
- private checkLockRequirements;
776
- private lockAndPopulate;
777
- private buildFields;
778
- /** @internal */
779
- preparePopulate<Entity extends object>(
780
- entityName: EntityName<Entity>,
781
- options: Pick<
782
- FindOptions<Entity, any, any, any>,
783
- 'populate' | 'strategy' | 'fields' | 'flags' | 'filters' | 'exclude' | 'populateHints'
784
- >,
785
- validate?: boolean,
786
- ): Promise<PopulateOptions<Entity>[]>;
787
- /**
788
- * when the entity is found in identity map, we check if it was partially loaded or we are trying to populate
789
- * some additional lazy properties, if so, we reload and merge the data from database
790
- */
791
- protected shouldRefresh<
792
- T extends object,
793
- P extends string = never,
794
- F extends string = never,
795
- E extends string = never,
796
- >(meta: EntityMetadata<T>, entity: T, options: FindOneOptions<T, P, F, E>): boolean;
797
- protected prepareOptions(
798
- options: FindOptions<any, any, any, any> | FindOneOptions<any, any, any, any> | CountOptions<any, any>,
799
- ): void;
800
- /**
801
- * @internal
802
- */
803
- cacheKey<T extends object>(
804
- entityName: EntityName<T>,
805
- options: FindOptions<T, any, any, any> | FindOneOptions<T, any, any, any> | CountOptions<T, any>,
806
- method: string,
807
- where: FilterQuery<T>,
808
- ): unknown[];
809
- /**
810
- * @internal
811
- */
812
- tryCache<T extends object, R>(
813
- entityName: EntityName<T>,
814
- config: boolean | number | [string, number] | undefined,
815
- key: unknown,
816
- refresh?: boolean,
817
- merge?: boolean,
818
- ): Promise<
819
- | {
22
+ #private;
23
+ readonly config: Configuration;
24
+ protected readonly driver: Driver;
25
+ protected readonly metadata: MetadataStorage;
26
+ protected readonly eventManager: EventManager;
27
+ /** @internal */
28
+ readonly '~entities'?: unknown;
29
+ /** @internal */
30
+ readonly _id: number;
31
+ /** Whether this is the global (root) EntityManager instance. */
32
+ readonly global = false;
33
+ /** The context name of this EntityManager, derived from the ORM configuration. */
34
+ readonly name: string;
35
+ protected loggerContext?: Dictionary;
36
+ /**
37
+ * @internal
38
+ */
39
+ constructor(config: Configuration, driver: Driver, metadata: MetadataStorage, useContext?: boolean, eventManager?: EventManager);
40
+ /**
41
+ * Gets the Driver instance used by this EntityManager.
42
+ * Driver is singleton, for one MikroORM instance, only one driver is created.
43
+ */
44
+ getDriver(): Driver;
45
+ /**
46
+ * Gets the Connection instance, by default returns write connection
47
+ */
48
+ getConnection(type?: ConnectionType): ReturnType<Driver['getConnection']>;
49
+ /**
50
+ * Gets the platform instance. Just like the driver, platform is singleton, one for a MikroORM instance.
51
+ */
52
+ getPlatform(): ReturnType<Driver['getPlatform']>;
53
+ /**
54
+ * Gets repository for given entity. You can pass either string name or entity class reference.
55
+ */
56
+ getRepository<Entity extends object, Repository extends EntityRepository<Entity> = EntityRepository<Entity>>(entityName: EntityName<Entity>): GetRepository<Entity, Repository>;
57
+ /**
58
+ * Shortcut for `em.getRepository()`.
59
+ */
60
+ repo<Entity extends object, Repository extends EntityRepository<Entity> = EntityRepository<Entity>>(entityName: EntityName<Entity>): GetRepository<Entity, Repository>;
61
+ /**
62
+ * Finds all entities matching your `where` query. You can pass additional options via the `options` parameter.
63
+ */
64
+ find<Entity extends object, Hint extends string = never, Fields extends string = never, Excludes extends string = never>(entityName: EntityName<Entity>, where: FilterQuery<NoInfer<Entity>>, options?: FindOptions<Entity, Hint, Fields, Excludes>): Promise<Loaded<Entity, Hint, Fields, Excludes>[]>;
65
+ /**
66
+ * Finds all entities and returns an async iterable (async generator) that yields results one by one.
67
+ * The results are merged and mapped to entity instances, without adding them to the identity map.
68
+ * You can disable merging by passing the options `{ mergeResults: false }`.
69
+ * With `mergeResults` disabled, to-many collections will contain at most one item, and you will get duplicate
70
+ * root entities when there are multiple items in the populated collection.
71
+ * This is useful for processing large datasets without loading everything into memory at once.
72
+ *
73
+ * ```ts
74
+ * const stream = em.stream(Book, { populate: ['author'] });
75
+ *
76
+ * for await (const book of stream) {
77
+ * // book is an instance of Book entity
78
+ * console.log(book.title, book.author.name);
79
+ * }
80
+ * ```
81
+ */
82
+ stream<Entity extends object, Hint extends string = never, Fields extends string = never, Excludes extends string = never>(entityName: EntityName<Entity>, options?: StreamOptions<NoInfer<Entity>, Hint, Fields, Excludes>): AsyncIterableIterator<Loaded<Entity, Hint, Fields, Excludes>>;
83
+ /**
84
+ * Finds all entities of given type, optionally matching the `where` condition provided in the `options` parameter.
85
+ */
86
+ findAll<Entity extends object, Hint extends string = never, Fields extends string = never, Excludes extends string = never>(entityName: EntityName<Entity>, options?: FindAllOptions<NoInfer<Entity>, Hint, Fields, Excludes>): Promise<Loaded<Entity, Hint, Fields, Excludes>[]>;
87
+ private getPopulateWhere;
88
+ /**
89
+ * Registers global filter to this entity manager. Global filters are enabled by default (unless disabled via last parameter).
90
+ */
91
+ addFilter<T extends EntityName | readonly EntityName[]>(options: FilterDef<T>): void;
92
+ /**
93
+ * Sets filter parameter values globally inside context defined by this entity manager.
94
+ * If you want to set shared value for all contexts, be sure to use the root entity manager.
95
+ */
96
+ setFilterParams(name: string, args: Dictionary): void;
97
+ /**
98
+ * Returns filter parameters for given filter set in this context.
99
+ */
100
+ getFilterParams<T extends Dictionary = Dictionary>(name: string): T;
101
+ /**
102
+ * Sets logger context for this entity manager.
103
+ */
104
+ setLoggerContext(context: Dictionary): void;
105
+ /**
106
+ * Gets logger context for this entity manager.
107
+ */
108
+ getLoggerContext<T extends Dictionary = Dictionary>(options?: {
109
+ disableContextResolution?: boolean;
110
+ }): T;
111
+ /** Sets the flush mode for this EntityManager. Pass `undefined` to reset to the global default. */
112
+ setFlushMode(flushMode?: FlushMode | `${FlushMode}`): void;
113
+ protected processWhere<Entity extends object, Hint extends string = never, Fields extends string = never, Excludes extends string = never>(entityName: EntityName<Entity>, where: FilterQuery<Entity>, options: FindOptions<Entity, Hint, Fields, Excludes> | FindOneOptions<Entity, Hint, Fields, Excludes>, type: 'read' | 'update' | 'delete'): Promise<FilterQuery<Entity>>;
114
+ protected processUnionWhere<Entity extends object, Hint extends string = never>(entityName: EntityName<Entity>, options: FindOptions<Entity, Hint, any, any> | CountOptions<Entity, Hint> | UpdateOptions<Entity> | DeleteOptions<Entity>, type: 'read' | 'update' | 'delete'): Promise<void>;
115
+ protected applyDiscriminatorCondition<Entity extends object>(entityName: EntityName<Entity>, where: FilterQuery<Entity>): FilterQuery<Entity>;
116
+ protected createPopulateWhere<Entity extends object>(cond: ObjectQuery<Entity>, options: FindOptions<Entity, any, any, any> | FindOneOptions<Entity, any, any, any> | CountOptions<Entity, any>): ObjectQuery<Entity>;
117
+ protected getJoinedFilters<Entity extends object>(meta: EntityMetadata<Entity>, options: FindOptions<Entity, any, any, any> | FindOneOptions<Entity, any, any, any>): Promise<ObjectQuery<Entity> | undefined>;
118
+ /**
119
+ * 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.
120
+ */
121
+ protected autoJoinRefsForFilters<T extends object>(meta: EntityMetadata<T>, options: FindOptions<T, any, any, any> | FindOneOptions<T, any, any, any>, parent?: {
122
+ class: EntityClass;
123
+ propName: string;
124
+ }): Promise<void>;
125
+ /**
126
+ * @internal
127
+ */
128
+ applyFilters<Entity extends object>(entityName: EntityName<Entity>, where: FilterQuery<Entity> | undefined, options: FilterOptions | undefined, type: 'read' | 'update' | 'delete', findOptions?: FindOptions<any, any, any, any> | FindOneOptions<any, any, any, any>): Promise<FilterQuery<Entity> | undefined>;
129
+ /**
130
+ * Calls `em.find()` and `em.count()` with the same arguments (where applicable) and returns the results as tuple
131
+ * where the first element is the array of entities, and the second is the count.
132
+ */
133
+ findAndCount<Entity extends object, Hint extends string = never, Fields extends string = never, Excludes extends string = never>(entityName: EntityName<Entity>, where: FilterQuery<NoInfer<Entity>>, options?: FindOptions<Entity, Hint, Fields, Excludes>): Promise<[Loaded<Entity, Hint, Fields, Excludes>[], number]>;
134
+ /**
135
+ * Calls `em.find()` and `em.count()` with the same arguments (where applicable) and returns the results as {@apilink Cursor} object.
136
+ * Supports `before`, `after`, `first` and `last` options while disallowing `limit` and `offset`. Explicit `orderBy` option
137
+ * is required.
138
+ *
139
+ * Use `first` and `after` for forward pagination, or `last` and `before` for backward pagination.
140
+ *
141
+ * - `first` and `last` are numbers and serve as an alternative to `offset`, those options are mutually exclusive, use only one at a time
142
+ * - `before` and `after` specify the previous cursor value, it can be one of the:
143
+ * - `Cursor` instance
144
+ * - opaque string provided by `startCursor/endCursor` properties
145
+ * - POJO/entity instance
146
+ *
147
+ * ```ts
148
+ * const currentCursor = await em.findByCursor(User, {
149
+ * first: 10,
150
+ * after: previousCursor, // cursor instance
151
+ * orderBy: { id: 'desc' },
152
+ * });
153
+ *
154
+ * // to fetch next page
155
+ * const nextCursor = await em.findByCursor(User, {
156
+ * first: 10,
157
+ * after: currentCursor.endCursor, // opaque string
158
+ * orderBy: { id: 'desc' },
159
+ * });
160
+ *
161
+ * // to fetch next page
162
+ * const nextCursor2 = await em.findByCursor(User, {
163
+ * first: 10,
164
+ * after: { id: lastSeenId }, // entity-like POJO
165
+ * orderBy: { id: 'desc' },
166
+ * });
167
+ * ```
168
+ *
169
+ * The options also support an `includeCount` (true by default) option. If set to false, the `totalCount` is not
170
+ * returned as part of the cursor. This is useful for performance reason, when you don't care about the total number
171
+ * of pages.
172
+ *
173
+ * The `Cursor` object provides the following interface:
174
+ *
175
+ * ```ts
176
+ * Cursor<User> {
177
+ * items: [
178
+ * User { ... },
179
+ * User { ... },
180
+ * User { ... },
181
+ * ],
182
+ * totalCount: 50, // not included if `includeCount: false`
183
+ * startCursor: 'WzRd',
184
+ * endCursor: 'WzZd',
185
+ * hasPrevPage: true,
186
+ * hasNextPage: true,
187
+ * }
188
+ * ```
189
+ */
190
+ findByCursor<Entity extends object, Hint extends string = never, Fields extends string = never, Excludes extends string = never, IncludeCount extends boolean = true>(entityName: EntityName<Entity>, options: FindByCursorOptions<Entity, Hint, Fields, Excludes, IncludeCount>): Promise<Cursor<Entity, Hint, Fields, Excludes, IncludeCount>>;
191
+ /**
192
+ * Refreshes the persistent state of an entity from the database, overriding any local changes that have not yet been
193
+ * persisted. Returns the same entity instance (same object reference), but re-hydrated. If the entity is no longer
194
+ * in database, the method throws an error just like `em.findOneOrFail()` (and respects the same config options).
195
+ */
196
+ refreshOrFail<Entity extends object, Naked extends FromEntityType<Entity> = FromEntityType<Entity>, Hint extends string = never, Fields extends string = never, Excludes extends string = never>(entity: Entity, options?: FindOneOrFailOptions<Entity, Hint, Fields, Excludes>): Promise<MergeLoaded<Entity, Naked, Hint, Fields, Excludes, true>>;
197
+ /**
198
+ * Refreshes the persistent state of an entity from the database, overriding any local changes that have not yet been
199
+ * persisted. Returns the same entity instance (same object reference), but re-hydrated. If the entity is no longer
200
+ * in database, the method returns `null`.
201
+ */
202
+ refresh<Entity extends object, Naked extends FromEntityType<Entity> = FromEntityType<Entity>, Hint extends string = never, Fields extends string = never, Excludes extends string = never>(entity: Entity, options?: FindOneOptions<Entity, Hint, Fields, Excludes>): Promise<MergeLoaded<Entity, Naked, Hint, Fields, Excludes, true> | null>;
203
+ /**
204
+ * Finds first entity matching your `where` query.
205
+ */
206
+ findOne<Entity extends object, Hint extends string = never, Fields extends string = never, Excludes extends string = never>(entityName: EntityName<Entity>, where: FilterQuery<NoInfer<Entity>>, options?: FindOneOptions<Entity, Hint, Fields, Excludes>): Promise<Loaded<Entity, Hint, Fields, Excludes> | null>;
207
+ /**
208
+ * Finds first entity matching your `where` query. If nothing found, it will throw an error.
209
+ * If the `strict` option is specified and nothing is found or more than one matching entity is found, it will throw an error.
210
+ * You can override the factory for creating this method via `options.failHandler` locally
211
+ * or via `Configuration.findOneOrFailHandler` (`findExactlyOneOrFailHandler` when specifying `strict`) globally.
212
+ */
213
+ findOneOrFail<Entity extends object, Hint extends string = never, Fields extends string = never, Excludes extends string = never>(entityName: EntityName<Entity>, where: FilterQuery<NoInfer<Entity>>, options?: FindOneOrFailOptions<Entity, Hint, Fields, Excludes>): Promise<Loaded<Entity, Hint, Fields, Excludes>>;
214
+ /**
215
+ * Creates or updates the entity, based on whether it is already present in the database.
216
+ * This method performs an `insert on conflict merge` query ensuring the database is in sync, returning a managed
217
+ * entity instance. The method accepts either `entityName` together with the entity `data`, or just entity instance.
218
+ *
219
+ * ```ts
220
+ * // insert into "author" ("age", "email") values (33, 'foo@bar.com') on conflict ("email") do update set "age" = 41
221
+ * const author = await em.upsert(Author, { email: 'foo@bar.com', age: 33 });
222
+ * ```
223
+ *
224
+ * 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:
225
+ *
226
+ * ```ts
227
+ * // insert into "author" ("age", "email") values (33, 'foo@bar.com') on conflict ("email") do update set "age" = 41
228
+ * // select "id" from "author" where "email" = 'foo@bar.com'
229
+ * const author = await em.upsert(Author, { email: 'foo@bar.com', age: 33 });
230
+ * ```
231
+ *
232
+ * 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`.
233
+ *
234
+ * 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.
235
+ */
236
+ upsert<Entity extends object, Fields extends string = any>(entityNameOrEntity: EntityName<Entity> | Entity, data?: EntityData<Entity> | NoInfer<Entity>, options?: UpsertOptions<Entity, Fields>): Promise<Entity>;
237
+ /**
238
+ * Creates or updates the entity, based on whether it is already present in the database.
239
+ * This method performs an `insert on conflict merge` query ensuring the database is in sync, returning a managed
240
+ * entity instance. The method accepts either `entityName` together with the entity `data`, or just entity instance.
241
+ *
242
+ * ```ts
243
+ * // insert into "author" ("age", "email") values (33, 'foo@bar.com') on conflict ("email") do update set "age" = 41
244
+ * const authors = await em.upsertMany(Author, [{ email: 'foo@bar.com', age: 33 }, ...]);
245
+ * ```
246
+ *
247
+ * 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:
248
+ *
249
+ * ```ts
250
+ * // insert into "author" ("age", "email") values (33, 'foo@bar.com'), (666, 'lol@lol.lol') on conflict ("email") do update set "age" = excluded."age"
251
+ * // select "id" from "author" where "email" = 'foo@bar.com'
252
+ * const author = await em.upsertMany(Author, [
253
+ * { email: 'foo@bar.com', age: 33 },
254
+ * { email: 'lol@lol.lol', age: 666 },
255
+ * ]);
256
+ * ```
257
+ *
258
+ * 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`.
259
+ *
260
+ * 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.
261
+ */
262
+ upsertMany<Entity extends object, Fields extends string = any>(entityNameOrEntity: EntityName<Entity> | Entity[], data?: (EntityData<Entity> | NoInfer<Entity>)[], options?: UpsertManyOptions<Entity, Fields>): Promise<Entity[]>;
263
+ /**
264
+ * Runs your callback wrapped inside a database transaction.
265
+ *
266
+ * If a transaction is already active, a new savepoint (nested transaction) will be created by default. This behavior
267
+ * can be controlled via the `propagation` option. Use the provided EntityManager instance for all operations that
268
+ * should be part of the transaction. You can safely use a global EntityManager instance from a DI container, as this
269
+ * method automatically creates an async context for the transaction.
270
+ *
271
+ * **Concurrency note:** When running multiple transactions concurrently (e.g. in parallel requests or jobs), use the
272
+ * `clear: true` option. This ensures the callback runs in a clear fork of the EntityManager, providing full isolation
273
+ * between concurrent transactional handlers. Using `clear: true` is an alternative to forking explicitly and calling
274
+ * the method on the new fork – it already provides the necessary isolation for safe concurrent usage.
275
+ *
276
+ * **Propagation note:** Changes made within a transaction (whether top-level or nested) are always propagated to the
277
+ * parent context, unless the parent context is a global one. If you want to avoid that, fork the EntityManager first
278
+ * and then call this method on the fork.
279
+ *
280
+ * **Example:**
281
+ * ```ts
282
+ * await em.transactional(async (em) => {
283
+ * const author = new Author('Jon');
284
+ * em.persist(author);
285
+ * // flush is called automatically at the end of the callback
286
+ * });
287
+ * ```
288
+ */
289
+ transactional<T>(cb: (em: this) => T | Promise<T>, options?: TransactionOptions): Promise<T>;
290
+ /**
291
+ * Starts new transaction bound to this EntityManager. Use `ctx` parameter to provide the parent when nesting transactions.
292
+ */
293
+ begin(options?: Omit<TransactionOptions, 'ignoreNestedTransactions'>): Promise<void>;
294
+ /**
295
+ * Commits the transaction bound to this EntityManager. Flushes before doing the actual commit query.
296
+ */
297
+ commit(): Promise<void>;
298
+ /**
299
+ * Rollbacks the transaction bound to this EntityManager.
300
+ */
301
+ rollback(): Promise<void>;
302
+ /**
303
+ * Runs your callback wrapped inside a database transaction.
304
+ */
305
+ lock<T extends object>(entity: T, lockMode: LockMode, options?: LockOptions | number | Date): Promise<void>;
306
+ /**
307
+ * Fires native insert query. Calling this has no side effects on the context (identity map).
308
+ */
309
+ insert<Entity extends object>(entityNameOrEntity: EntityName<Entity> | Entity, data?: RequiredEntityData<Entity> | Entity, options?: NativeInsertUpdateOptions<Entity>): Promise<Primary<Entity>>;
310
+ /**
311
+ * Fires native multi-insert query. Calling this has no side effects on the context (identity map).
312
+ */
313
+ insertMany<Entity extends object>(entityNameOrEntities: EntityName<Entity> | Entity[], data?: RequiredEntityData<Entity>[] | Entity[], options?: NativeInsertUpdateOptions<Entity>): Promise<Primary<Entity>[]>;
314
+ /**
315
+ * Fires native update query. Calling this has no side effects on the context (identity map).
316
+ */
317
+ nativeUpdate<Entity extends object>(entityName: EntityName<Entity>, where: FilterQuery<NoInfer<Entity>>, data: EntityData<Entity>, options?: UpdateOptions<Entity>): Promise<number>;
318
+ /**
319
+ * Fires native delete query. Calling this has no side effects on the context (identity map).
320
+ */
321
+ nativeDelete<Entity extends object>(entityName: EntityName<Entity>, where: FilterQuery<NoInfer<Entity>>, options?: DeleteOptions<Entity>): Promise<number>;
322
+ /**
323
+ * Maps raw database result to an entity and merges it to this EntityManager.
324
+ */
325
+ map<Entity extends object>(entityName: EntityName<Entity>, result: EntityDictionary<Entity>, options?: {
326
+ schema?: string;
327
+ }): Entity;
328
+ /**
329
+ * Merges given entity to this EntityManager so it becomes managed. You can force refreshing of existing entities
330
+ * via second parameter. By default, it will return already loaded entities without modifying them.
331
+ */
332
+ merge<Entity extends object>(entity: Entity, options?: MergeOptions): Entity;
333
+ /**
334
+ * Merges given entity to this EntityManager so it becomes managed. You can force refreshing of existing entities
335
+ * via second parameter. By default, it will return already loaded entities without modifying them.
336
+ */
337
+ merge<Entity extends object>(entityName: EntityName<Entity>, data: EntityData<Entity> | EntityDTO<Entity>, options?: MergeOptions): Entity;
338
+ /**
339
+ * Creates new instance of given entity and populates it with given data.
340
+ * The entity constructor will be used unless you provide `{ managed: true }` in the `options` parameter.
341
+ * The constructor will be given parameters based on the defined constructor of the entity. If the constructor
342
+ * parameter matches a property name, its value will be extracted from `data`. If no matching property exists,
343
+ * the whole `data` parameter will be passed. This means we can also define `constructor(data: Partial<T>)` and
344
+ * `em.create()` will pass the data into it (unless we have a property named `data` too).
345
+ *
346
+ * The parameters are strictly checked, you need to provide all required properties. You can use `OptionalProps`
347
+ * symbol to omit some properties from this check without making them optional. Alternatively, use `partial: true`
348
+ * in the options to disable the strict checks for required properties. This option has no effect on runtime.
349
+ *
350
+ * The newly created entity will be automatically marked for persistence via `em.persist` unless you disable this
351
+ * behavior, either locally via `persist: false` option, or globally via `persistOnCreate` ORM config option.
352
+ */
353
+ create<Entity extends object, Convert extends boolean = false, Data extends RequiredEntityData<Entity, never, Convert> = RequiredEntityData<Entity, never, Convert>>(entityName: EntityName<Entity>, data: Data & IsSubset<RequiredEntityData<Entity, never, Convert>, Data>, options?: CreateOptions<Convert>): Entity;
354
+ /**
355
+ * Creates new instance of given entity and populates it with given data.
356
+ * The entity constructor will be used unless you provide `{ managed: true }` in the `options` parameter.
357
+ * The constructor will be given parameters based on the defined constructor of the entity. If the constructor
358
+ * parameter matches a property name, its value will be extracted from `data`. If no matching property exists,
359
+ * the whole `data` parameter will be passed. This means we can also define `constructor(data: Partial<T>)` and
360
+ * `em.create()` will pass the data into it (unless we have a property named `data` too).
361
+ *
362
+ * The parameters are strictly checked, you need to provide all required properties. You can use `OptionalProps`
363
+ * symbol to omit some properties from this check without making them optional. Alternatively, use `partial: true`
364
+ * in the options to disable the strict checks for required properties. This option has no effect on runtime.
365
+ *
366
+ * The newly created entity will be automatically marked for persistence via `em.persist` unless you disable this
367
+ * behavior, either locally via `persist: false` option, or globally via `persistOnCreate` ORM config option.
368
+ */
369
+ create<Entity extends object, Convert extends boolean = false, Data extends EntityData<Entity, Convert> = EntityData<Entity, Convert>>(entityName: EntityName<Entity>, data: Data & IsSubset<EntityData<Entity, Convert>, Data>, options: CreateOptions<Convert> & {
370
+ partial: true;
371
+ }): Entity;
372
+ /**
373
+ * Shortcut for `wrap(entity).assign(data, { em })`
374
+ */
375
+ assign<Entity extends object, Naked extends FromEntityType<Entity> = FromEntityType<Entity>, Convert extends boolean = false, Data extends EntityData<Naked, Convert> | Partial<EntityDTO<Naked>> = EntityData<Naked, Convert> | Partial<EntityDTO<Naked>>>(entity: Entity | Partial<Entity>, data: Data & IsSubset<EntityData<Naked, Convert>, Data>, options?: AssignOptions<Convert>): MergeSelected<Entity, Naked, keyof Data & string>;
376
+ /**
377
+ * Gets a reference to the entity identified by the given type and alternate key property without actually loading it.
378
+ * The key option specifies which property to use for identity map lookup instead of the primary key.
379
+ */
380
+ getReference<Entity extends object, K extends string & keyof Entity>(entityName: EntityName<Entity>, id: Entity[K], options: Omit<GetReferenceOptions, 'key' | 'wrapped'> & {
381
+ key: K;
382
+ wrapped: true;
383
+ }): Ref<Entity>;
384
+ /**
385
+ * Gets a reference to the entity identified by the given type and alternate key property without actually loading it.
386
+ * The key option specifies which property to use for identity map lookup instead of the primary key.
387
+ */
388
+ getReference<Entity extends object, K extends string & keyof Entity>(entityName: EntityName<Entity>, id: Entity[K], options: Omit<GetReferenceOptions, 'key'> & {
389
+ key: K;
390
+ wrapped?: false;
391
+ }): Entity;
392
+ /**
393
+ * Gets a reference to the entity identified by the given type and identifier without actually loading it, if the entity is not yet loaded
394
+ */
395
+ getReference<Entity extends object>(entityName: EntityName<Entity>, id: Primary<Entity>, options: Omit<GetReferenceOptions, 'wrapped' | 'key'> & {
396
+ wrapped: true;
397
+ }): Ref<Entity>;
398
+ /**
399
+ * Gets a reference to the entity identified by the given type and identifier without actually loading it, if the entity is not yet loaded
400
+ */
401
+ getReference<Entity extends object>(entityName: EntityName<Entity>, id: Primary<Entity> | Primary<Entity>[]): Entity;
402
+ /**
403
+ * Gets a reference to the entity identified by the given type and identifier without actually loading it, if the entity is not yet loaded
404
+ */
405
+ getReference<Entity extends object>(entityName: EntityName<Entity>, id: Primary<Entity>, options: Omit<GetReferenceOptions, 'wrapped' | 'key'> & {
406
+ wrapped: false;
407
+ }): Entity;
408
+ /**
409
+ * Gets a reference to the entity identified by the given type and identifier without actually loading it, if the entity is not yet loaded
410
+ */
411
+ getReference<Entity extends object>(entityName: EntityName<Entity>, id: Primary<Entity>, options?: GetReferenceOptions): Entity | Reference<Entity>;
412
+ /**
413
+ * Returns total number of entities matching your `where` query.
414
+ */
415
+ count<Entity extends object, Hint extends string = never>(entityName: EntityName<Entity>, where?: FilterQuery<NoInfer<Entity>>, options?: CountOptions<Entity, Hint>): Promise<number>;
416
+ /**
417
+ * Tells the EntityManager to make an instance managed and persistent.
418
+ * The entity will be entered into the database at or before transaction commit or as a result of the flush operation.
419
+ */
420
+ persist<Entity extends object>(entity: Entity | Reference<Entity> | Iterable<Entity | Reference<Entity>>): this;
421
+ /**
422
+ * Marks entity for removal.
423
+ * A removed entity will be removed from the database at or before transaction commit or as a result of the flush operation.
424
+ *
425
+ * To remove entities by condition, use `em.nativeDelete()`.
426
+ */
427
+ remove<Entity extends object>(entity: Entity | Reference<Entity> | Iterable<Entity | Reference<Entity>>): this;
428
+ /**
429
+ * Flushes all changes to objects that have been queued up to now to the database.
430
+ * This effectively synchronizes the in-memory state of managed objects with the database.
431
+ */
432
+ flush(): Promise<void>;
433
+ /**
434
+ * @internal
435
+ */
436
+ tryFlush<Entity extends object>(entityName: EntityName<Entity>, options: {
437
+ flushMode?: FlushMode | AnyString;
438
+ }): Promise<void>;
439
+ /**
440
+ * Clears the EntityManager. All entities that are currently managed by this EntityManager become detached.
441
+ */
442
+ clear(): void;
443
+ /**
444
+ * Checks whether given property can be populated on the entity.
445
+ */
446
+ canPopulate<Entity extends object>(entityName: EntityName<Entity>, property: string): boolean;
447
+ /**
448
+ * Loads specified relations in batch. This will execute one query for each relation, that will populate it on all the specified entities.
449
+ */
450
+ populate<Entity extends object, Naked extends FromEntityType<UnboxArray<Entity>> = FromEntityType<UnboxArray<Entity>>, Hint extends string = never, Fields extends string = never, Excludes extends string = never>(entities: Entity, populate: readonly AutoPath<Naked, Hint, PopulatePath.ALL>[] | false, options?: EntityLoaderOptions<Naked, Fields, Excludes>): Promise<Entity extends object[] ? MergeLoaded<ArrayElement<Entity>, Naked, Hint, Fields, Excludes>[] : MergeLoaded<Entity, Naked, Hint, Fields, Excludes>>;
451
+ /**
452
+ * Returns new EntityManager instance with its own identity map
453
+ */
454
+ fork(options?: ForkOptions): this;
455
+ /**
456
+ * Gets the UnitOfWork used by the EntityManager to coordinate operations.
457
+ */
458
+ getUnitOfWork(useContext?: boolean): UnitOfWork;
459
+ /**
460
+ * Gets the EntityFactory used by the EntityManager.
461
+ */
462
+ getEntityFactory(): EntityFactory;
463
+ /**
464
+ * @internal use `em.populate()` as the user facing API, this is exposed only for internal usage
465
+ */
466
+ getEntityLoader(): EntityLoader;
467
+ /**
468
+ * Gets the Hydrator used by the EntityManager.
469
+ */
470
+ getHydrator(): IHydrator;
471
+ /**
472
+ * Gets the EntityManager based on current transaction/request context.
473
+ * @internal
474
+ */
475
+ getContext(validate?: boolean): this;
476
+ /** Gets the EventManager instance used by this EntityManager. */
477
+ getEventManager(): EventManager;
478
+ /**
479
+ * Checks whether this EntityManager is currently operating inside a database transaction.
480
+ */
481
+ isInTransaction(): boolean;
482
+ /**
483
+ * Gets the transaction context (driver dependent object used to make sure queries are executed on same connection).
484
+ */
485
+ getTransactionContext<T extends Transaction = Transaction>(): T | undefined;
486
+ /**
487
+ * Sets the transaction context.
488
+ */
489
+ setTransactionContext(ctx?: Transaction): void;
490
+ /**
491
+ * Resets the transaction context.
492
+ */
493
+ resetTransactionContext(): void;
494
+ /**
495
+ * Gets the `MetadataStorage`.
496
+ */
497
+ getMetadata(): MetadataStorage;
498
+ /**
499
+ * Gets the `EntityMetadata` instance when provided with the `entityName` parameter.
500
+ */
501
+ getMetadata<Entity extends object>(entityName: EntityName<Entity>): EntityMetadata<Entity>;
502
+ /**
503
+ * Gets the EntityComparator.
504
+ */
505
+ getComparator(): EntityComparator;
506
+ private checkLockRequirements;
507
+ private lockAndPopulate;
508
+ private buildFields;
509
+ /** @internal */
510
+ preparePopulate<Entity extends object>(entityName: EntityName<Entity>, options: Pick<FindOptions<Entity, any, any, any>, 'populate' | 'strategy' | 'fields' | 'flags' | 'filters' | 'exclude' | 'populateHints'>, validate?: boolean): Promise<PopulateOptions<Entity>[]>;
511
+ /**
512
+ * when the entity is found in identity map, we check if it was partially loaded or we are trying to populate
513
+ * some additional lazy properties, if so, we reload and merge the data from database
514
+ */
515
+ protected shouldRefresh<T extends object, P extends string = never, F extends string = never, E extends string = never>(meta: EntityMetadata<T>, entity: T, options: FindOneOptions<T, P, F, E>): boolean;
516
+ protected prepareOptions(options: FindOptions<any, any, any, any> | FindOneOptions<any, any, any, any> | CountOptions<any, any>): void;
517
+ /**
518
+ * @internal
519
+ */
520
+ cacheKey<T extends object>(entityName: EntityName<T>, options: FindOptions<T, any, any, any> | FindOneOptions<T, any, any, any> | CountOptions<T, any>, method: string, where: FilterQuery<T>): unknown[];
521
+ /**
522
+ * @internal
523
+ */
524
+ tryCache<T extends object, R>(entityName: EntityName<T>, config: boolean | number | [string, number] | undefined, key: unknown, refresh?: boolean, merge?: boolean): Promise<{
820
525
  data?: R | null;
821
526
  key: string;
822
- }
823
- | undefined
824
- >;
825
- /**
826
- * @internal
827
- */
828
- storeCache<T>(
829
- config: boolean | number | [string, number] | undefined,
830
- key: {
831
- key: string;
832
- },
833
- data: T | (() => T),
834
- ): Promise<void>;
835
- /**
836
- * Clears result cache for given cache key. If we want to be able to call this method,
837
- * we need to set the cache key explicitly when storing the cache.
838
- *
839
- * ```ts
840
- * // set the cache key to 'book-cache-key', with expiration of 60s
841
- * const res = await em.find(Book, { ... }, { cache: ['book-cache-key', 60_000] });
842
- *
843
- * // clear the cache key by name
844
- * await em.clearCache('book-cache-key');
845
- * ```
846
- */
847
- clearCache(cacheKey: string): Promise<void>;
848
- /**
849
- * Returns the default schema of this EntityManager. Respects the context, so global EM will give you the contextual schema
850
- * if executed inside request context handler.
851
- */
852
- get schema(): string | undefined;
853
- /**
854
- * Sets the default schema of this EntityManager. Respects the context, so global EM will set the contextual schema
855
- * if executed inside request context handler.
856
- */
857
- set schema(schema: string | null | undefined);
858
- /** @internal */
859
- getDataLoader(type: 'ref' | '1:m' | 'm:n'): Promise<any>;
860
- /**
861
- * Returns the ID of this EntityManager. Respects the context, so global EM will give you the contextual ID
862
- * if executed inside request context handler.
863
- */
864
- get id(): number;
527
+ } | undefined>;
528
+ /**
529
+ * @internal
530
+ */
531
+ storeCache<T>(config: boolean | number | [string, number] | undefined, key: {
532
+ key: string;
533
+ }, data: T | (() => T)): Promise<void>;
534
+ /**
535
+ * Clears result cache for given cache key. If we want to be able to call this method,
536
+ * we need to set the cache key explicitly when storing the cache.
537
+ *
538
+ * ```ts
539
+ * // set the cache key to 'book-cache-key', with expiration of 60s
540
+ * const res = await em.find(Book, { ... }, { cache: ['book-cache-key', 60_000] });
541
+ *
542
+ * // clear the cache key by name
543
+ * await em.clearCache('book-cache-key');
544
+ * ```
545
+ */
546
+ clearCache(cacheKey: string): Promise<void>;
547
+ /**
548
+ * Returns the default schema of this EntityManager. Respects the context, so global EM will give you the contextual schema
549
+ * if executed inside request context handler.
550
+ */
551
+ get schema(): string | undefined;
552
+ /**
553
+ * Sets the default schema of this EntityManager. Respects the context, so global EM will set the contextual schema
554
+ * if executed inside request context handler.
555
+ */
556
+ set schema(schema: string | null | undefined);
557
+ /** @internal */
558
+ getDataLoader(type: 'ref' | '1:m' | 'm:n'): Promise<any>;
559
+ /**
560
+ * Returns the ID of this EntityManager. Respects the context, so global EM will give you the contextual ID
561
+ * if executed inside request context handler.
562
+ */
563
+ get id(): number;
865
564
  }
866
565
  export interface CreateOptions<Convert extends boolean> {
867
- /** creates a managed entity instance instead, bypassing the constructor call */
868
- managed?: boolean;
869
- /** create entity in a specific schema - alternatively, use `wrap(entity).setSchema()` */
870
- schema?: string;
871
- /** persist the entity automatically - this is the default behavior and is also configurable globally via `persistOnCreate` option */
872
- persist?: boolean;
873
- /** this option disables the strict typing which requires all mandatory properties to have value, it has no effect on runtime */
874
- partial?: boolean;
875
- /** convert raw database values based on mapped types (by default, already converted values are expected) */
876
- convertCustomTypes?: Convert;
877
- /**
878
- * Property `onCreate` hooks are normally executed during `flush` operation.
879
- * With this option, they will be processed early inside `em.create()` method.
880
- */
881
- processOnCreateHooksEarly?: boolean;
566
+ /** creates a managed entity instance instead, bypassing the constructor call */
567
+ managed?: boolean;
568
+ /** create entity in a specific schema - alternatively, use `wrap(entity).setSchema()` */
569
+ schema?: string;
570
+ /** persist the entity automatically - this is the default behavior and is also configurable globally via `persistOnCreate` option */
571
+ persist?: boolean;
572
+ /** this option disables the strict typing which requires all mandatory properties to have value, it has no effect on runtime */
573
+ partial?: boolean;
574
+ /** convert raw database values based on mapped types (by default, already converted values are expected) */
575
+ convertCustomTypes?: Convert;
576
+ /**
577
+ * Property `onCreate` hooks are normally executed during `flush` operation.
578
+ * With this option, they will be processed early inside `em.create()` method.
579
+ */
580
+ processOnCreateHooksEarly?: boolean;
882
581
  }
883
582
  export interface MergeOptions {
884
- refresh?: boolean;
885
- convertCustomTypes?: boolean;
886
- schema?: string;
887
- disableContextResolution?: boolean;
888
- validate?: boolean;
889
- cascade?: boolean /** @default true */;
583
+ refresh?: boolean;
584
+ convertCustomTypes?: boolean;
585
+ schema?: string;
586
+ disableContextResolution?: boolean;
587
+ validate?: boolean;
588
+ cascade?: boolean /** @default true */;
890
589
  }
891
590
  export interface ForkOptions {
892
- /** do we want a clear identity map? defaults to true */
893
- clear?: boolean;
894
- /** use request context? should be used only for top level request scope EM, defaults to false */
895
- useContext?: boolean;
896
- /** do we want to use fresh EventManager instance? defaults to false (global instance) */
897
- freshEventManager?: boolean;
898
- /** do we want to clone current EventManager instance? defaults to false (global instance) */
899
- cloneEventManager?: boolean;
900
- /** use this flag to ignore the current async context - this is required if we want to call `em.fork()` inside the `getContext` handler */
901
- disableContextResolution?: boolean;
902
- /** set flush mode for this fork, overrides the global option can be overridden locally via FindOptions */
903
- flushMode?: FlushMode | `${FlushMode}`;
904
- /** disable transactions for this fork */
905
- disableTransactions?: boolean;
906
- /** should we keep the transaction context of the parent EM? */
907
- keepTransactionContext?: boolean;
908
- /** default schema to use for this fork */
909
- schema?: string;
910
- /** default logger context, can be overridden via {@apilink FindOptions} */
911
- loggerContext?: Dictionary;
591
+ /** do we want a clear identity map? defaults to true */
592
+ clear?: boolean;
593
+ /** use request context? should be used only for top level request scope EM, defaults to false */
594
+ useContext?: boolean;
595
+ /** do we want to use fresh EventManager instance? defaults to false (global instance) */
596
+ freshEventManager?: boolean;
597
+ /** do we want to clone current EventManager instance? defaults to false (global instance) */
598
+ cloneEventManager?: boolean;
599
+ /** use this flag to ignore the current async context - this is required if we want to call `em.fork()` inside the `getContext` handler */
600
+ disableContextResolution?: boolean;
601
+ /** set flush mode for this fork, overrides the global option can be overridden locally via FindOptions */
602
+ flushMode?: FlushMode | `${FlushMode}`;
603
+ /** disable transactions for this fork */
604
+ disableTransactions?: boolean;
605
+ /** should we keep the transaction context of the parent EM? */
606
+ keepTransactionContext?: boolean;
607
+ /** default schema to use for this fork */
608
+ schema?: string;
609
+ /** default logger context, can be overridden via {@apilink FindOptions} */
610
+ loggerContext?: Dictionary;
912
611
  }