@mikro-orm/core 7.0.0-dev.3 → 7.0.0-dev.300

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 (214) hide show
  1. package/EntityManager.d.ts +114 -63
  2. package/EntityManager.js +385 -310
  3. package/MikroORM.d.ts +44 -35
  4. package/MikroORM.js +109 -143
  5. package/README.md +3 -2
  6. package/cache/FileCacheAdapter.d.ts +1 -1
  7. package/cache/FileCacheAdapter.js +17 -8
  8. package/cache/GeneratedCacheAdapter.d.ts +0 -1
  9. package/cache/GeneratedCacheAdapter.js +0 -2
  10. package/cache/index.d.ts +0 -1
  11. package/cache/index.js +0 -1
  12. package/connections/Connection.d.ts +16 -7
  13. package/connections/Connection.js +23 -14
  14. package/drivers/DatabaseDriver.d.ts +25 -16
  15. package/drivers/DatabaseDriver.js +119 -36
  16. package/drivers/IDatabaseDriver.d.ts +125 -23
  17. package/entity/BaseEntity.d.ts +63 -4
  18. package/entity/BaseEntity.js +0 -3
  19. package/entity/Collection.d.ts +102 -31
  20. package/entity/Collection.js +446 -108
  21. package/entity/EntityAssigner.d.ts +1 -1
  22. package/entity/EntityAssigner.js +26 -18
  23. package/entity/EntityFactory.d.ts +13 -1
  24. package/entity/EntityFactory.js +106 -60
  25. package/entity/EntityHelper.d.ts +2 -2
  26. package/entity/EntityHelper.js +65 -20
  27. package/entity/EntityLoader.d.ts +13 -11
  28. package/entity/EntityLoader.js +257 -107
  29. package/entity/EntityRepository.d.ts +28 -8
  30. package/entity/EntityRepository.js +8 -2
  31. package/entity/PolymorphicRef.d.ts +12 -0
  32. package/entity/PolymorphicRef.js +18 -0
  33. package/entity/Reference.d.ts +9 -12
  34. package/entity/Reference.js +34 -9
  35. package/entity/WrappedEntity.d.ts +3 -8
  36. package/entity/WrappedEntity.js +3 -8
  37. package/entity/defineEntity.d.ts +753 -0
  38. package/entity/defineEntity.js +537 -0
  39. package/entity/index.d.ts +4 -2
  40. package/entity/index.js +4 -2
  41. package/entity/utils.d.ts +13 -1
  42. package/entity/utils.js +49 -4
  43. package/entity/validators.d.ts +11 -0
  44. package/entity/validators.js +65 -0
  45. package/enums.d.ts +23 -8
  46. package/enums.js +15 -1
  47. package/errors.d.ts +25 -9
  48. package/errors.js +67 -21
  49. package/events/EventManager.d.ts +2 -1
  50. package/events/EventManager.js +19 -11
  51. package/events/EventSubscriber.d.ts +3 -1
  52. package/hydration/Hydrator.js +1 -2
  53. package/hydration/ObjectHydrator.d.ts +4 -4
  54. package/hydration/ObjectHydrator.js +89 -36
  55. package/index.d.ts +2 -2
  56. package/index.js +1 -2
  57. package/logging/DefaultLogger.d.ts +1 -1
  58. package/logging/DefaultLogger.js +1 -0
  59. package/logging/SimpleLogger.d.ts +1 -1
  60. package/logging/colors.d.ts +1 -1
  61. package/logging/colors.js +7 -6
  62. package/logging/index.d.ts +1 -0
  63. package/logging/index.js +1 -0
  64. package/logging/inspect.d.ts +2 -0
  65. package/logging/inspect.js +11 -0
  66. package/metadata/EntitySchema.d.ts +53 -27
  67. package/metadata/EntitySchema.js +125 -52
  68. package/metadata/MetadataDiscovery.d.ts +64 -10
  69. package/metadata/MetadataDiscovery.js +823 -344
  70. package/metadata/MetadataProvider.d.ts +11 -2
  71. package/metadata/MetadataProvider.js +66 -2
  72. package/metadata/MetadataStorage.d.ts +13 -11
  73. package/metadata/MetadataStorage.js +71 -38
  74. package/metadata/MetadataValidator.d.ts +32 -9
  75. package/metadata/MetadataValidator.js +198 -42
  76. package/metadata/discover-entities.d.ts +5 -0
  77. package/metadata/discover-entities.js +40 -0
  78. package/metadata/index.d.ts +1 -1
  79. package/metadata/index.js +1 -1
  80. package/metadata/types.d.ts +577 -0
  81. package/metadata/types.js +1 -0
  82. package/naming-strategy/AbstractNamingStrategy.d.ts +16 -4
  83. package/naming-strategy/AbstractNamingStrategy.js +20 -2
  84. package/naming-strategy/EntityCaseNamingStrategy.d.ts +3 -3
  85. package/naming-strategy/EntityCaseNamingStrategy.js +6 -5
  86. package/naming-strategy/MongoNamingStrategy.d.ts +3 -3
  87. package/naming-strategy/MongoNamingStrategy.js +6 -6
  88. package/naming-strategy/NamingStrategy.d.ts +28 -4
  89. package/naming-strategy/UnderscoreNamingStrategy.d.ts +3 -3
  90. package/naming-strategy/UnderscoreNamingStrategy.js +6 -6
  91. package/not-supported.d.ts +2 -0
  92. package/not-supported.js +4 -0
  93. package/package.json +22 -11
  94. package/platforms/ExceptionConverter.js +1 -1
  95. package/platforms/Platform.d.ts +14 -16
  96. package/platforms/Platform.js +24 -44
  97. package/serialization/EntitySerializer.d.ts +8 -3
  98. package/serialization/EntitySerializer.js +47 -27
  99. package/serialization/EntityTransformer.js +33 -21
  100. package/serialization/SerializationContext.d.ts +6 -6
  101. package/serialization/SerializationContext.js +16 -13
  102. package/types/ArrayType.d.ts +1 -1
  103. package/types/ArrayType.js +2 -3
  104. package/types/BigIntType.d.ts +9 -6
  105. package/types/BigIntType.js +4 -1
  106. package/types/BlobType.d.ts +0 -1
  107. package/types/BlobType.js +0 -3
  108. package/types/BooleanType.d.ts +2 -1
  109. package/types/BooleanType.js +3 -0
  110. package/types/DecimalType.d.ts +6 -4
  111. package/types/DecimalType.js +3 -3
  112. package/types/DoubleType.js +2 -2
  113. package/types/EnumArrayType.js +1 -2
  114. package/types/JsonType.d.ts +1 -1
  115. package/types/JsonType.js +7 -2
  116. package/types/TinyIntType.js +1 -1
  117. package/types/Type.d.ts +2 -4
  118. package/types/Type.js +3 -3
  119. package/types/Uint8ArrayType.d.ts +0 -1
  120. package/types/Uint8ArrayType.js +1 -4
  121. package/types/index.d.ts +1 -1
  122. package/typings.d.ts +469 -175
  123. package/typings.js +120 -45
  124. package/unit-of-work/ChangeSet.d.ts +4 -6
  125. package/unit-of-work/ChangeSet.js +4 -5
  126. package/unit-of-work/ChangeSetComputer.d.ts +3 -8
  127. package/unit-of-work/ChangeSetComputer.js +44 -21
  128. package/unit-of-work/ChangeSetPersister.d.ts +15 -12
  129. package/unit-of-work/ChangeSetPersister.js +113 -45
  130. package/unit-of-work/CommitOrderCalculator.d.ts +12 -10
  131. package/unit-of-work/CommitOrderCalculator.js +13 -13
  132. package/unit-of-work/IdentityMap.d.ts +12 -0
  133. package/unit-of-work/IdentityMap.js +39 -1
  134. package/unit-of-work/UnitOfWork.d.ts +28 -3
  135. package/unit-of-work/UnitOfWork.js +315 -110
  136. package/utils/AbstractMigrator.d.ts +101 -0
  137. package/utils/AbstractMigrator.js +305 -0
  138. package/utils/AbstractSchemaGenerator.d.ts +5 -5
  139. package/utils/AbstractSchemaGenerator.js +32 -18
  140. package/utils/AsyncContext.d.ts +6 -0
  141. package/utils/AsyncContext.js +42 -0
  142. package/utils/Configuration.d.ts +801 -207
  143. package/utils/Configuration.js +150 -191
  144. package/utils/ConfigurationLoader.d.ts +1 -54
  145. package/utils/ConfigurationLoader.js +1 -352
  146. package/utils/Cursor.d.ts +3 -6
  147. package/utils/Cursor.js +27 -11
  148. package/utils/DataloaderUtils.d.ts +15 -5
  149. package/utils/DataloaderUtils.js +65 -17
  150. package/utils/EntityComparator.d.ts +21 -10
  151. package/utils/EntityComparator.js +243 -106
  152. package/utils/QueryHelper.d.ts +24 -6
  153. package/utils/QueryHelper.js +122 -26
  154. package/utils/RawQueryFragment.d.ts +60 -32
  155. package/utils/RawQueryFragment.js +69 -66
  156. package/utils/RequestContext.js +2 -2
  157. package/utils/TransactionContext.js +2 -2
  158. package/utils/TransactionManager.d.ts +65 -0
  159. package/utils/TransactionManager.js +223 -0
  160. package/utils/Utils.d.ts +15 -122
  161. package/utils/Utils.js +108 -376
  162. package/utils/clone.js +8 -23
  163. package/utils/env-vars.d.ts +7 -0
  164. package/utils/env-vars.js +97 -0
  165. package/utils/fs-utils.d.ts +34 -0
  166. package/utils/fs-utils.js +196 -0
  167. package/utils/index.d.ts +2 -3
  168. package/utils/index.js +2 -3
  169. package/utils/upsert-utils.d.ts +9 -4
  170. package/utils/upsert-utils.js +55 -4
  171. package/decorators/Check.d.ts +0 -3
  172. package/decorators/Check.js +0 -13
  173. package/decorators/CreateRequestContext.d.ts +0 -3
  174. package/decorators/CreateRequestContext.js +0 -32
  175. package/decorators/Embeddable.d.ts +0 -8
  176. package/decorators/Embeddable.js +0 -11
  177. package/decorators/Embedded.d.ts +0 -18
  178. package/decorators/Embedded.js +0 -18
  179. package/decorators/Entity.d.ts +0 -18
  180. package/decorators/Entity.js +0 -13
  181. package/decorators/Enum.d.ts +0 -9
  182. package/decorators/Enum.js +0 -16
  183. package/decorators/Filter.d.ts +0 -2
  184. package/decorators/Filter.js +0 -8
  185. package/decorators/Formula.d.ts +0 -5
  186. package/decorators/Formula.js +0 -15
  187. package/decorators/Indexed.d.ts +0 -17
  188. package/decorators/Indexed.js +0 -20
  189. package/decorators/ManyToMany.d.ts +0 -40
  190. package/decorators/ManyToMany.js +0 -14
  191. package/decorators/ManyToOne.d.ts +0 -30
  192. package/decorators/ManyToOne.js +0 -14
  193. package/decorators/OneToMany.d.ts +0 -28
  194. package/decorators/OneToMany.js +0 -17
  195. package/decorators/OneToOne.d.ts +0 -24
  196. package/decorators/OneToOne.js +0 -7
  197. package/decorators/PrimaryKey.d.ts +0 -9
  198. package/decorators/PrimaryKey.js +0 -20
  199. package/decorators/Property.d.ts +0 -250
  200. package/decorators/Property.js +0 -32
  201. package/decorators/Transactional.d.ts +0 -13
  202. package/decorators/Transactional.js +0 -28
  203. package/decorators/hooks.d.ts +0 -16
  204. package/decorators/hooks.js +0 -47
  205. package/decorators/index.d.ts +0 -17
  206. package/decorators/index.js +0 -17
  207. package/entity/ArrayCollection.d.ts +0 -116
  208. package/entity/ArrayCollection.js +0 -395
  209. package/entity/EntityValidator.d.ts +0 -19
  210. package/entity/EntityValidator.js +0 -150
  211. package/metadata/ReflectMetadataProvider.d.ts +0 -8
  212. package/metadata/ReflectMetadataProvider.js +0 -44
  213. package/utils/resolveContextProvider.d.ts +0 -10
  214. package/utils/resolveContextProvider.js +0 -28
@@ -2,7 +2,7 @@ import type { PopulatePath } from '../enums.js';
2
2
  import type { CreateOptions, EntityManager, MergeOptions } from '../EntityManager.js';
3
3
  import type { AssignOptions } from './EntityAssigner.js';
4
4
  import type { EntityData, EntityName, Primary, Loaded, FilterQuery, EntityDictionary, AutoPath, RequiredEntityData, Ref, EntityType, EntityDTO, MergeSelected, FromEntityType, IsSubset, MergeLoaded, ArrayElement } from '../typings.js';
5
- import type { CountOptions, DeleteOptions, FindAllOptions, FindByCursorOptions, FindOneOptions, FindOneOrFailOptions, FindOptions, GetReferenceOptions, NativeInsertUpdateOptions, UpdateOptions, UpsertManyOptions, UpsertOptions } from '../drivers/IDatabaseDriver.js';
5
+ import type { CountOptions, DeleteOptions, FindAllOptions, FindByCursorOptions, FindOneOptions, FindOneOrFailOptions, FindOptions, GetReferenceOptions, NativeInsertUpdateOptions, StreamOptions, UpdateOptions, UpsertManyOptions, UpsertOptions } from '../drivers/IDatabaseDriver.js';
6
6
  import type { EntityLoaderOptions } from './EntityLoader.js';
7
7
  import type { Cursor } from '../utils/Cursor.js';
8
8
  export declare class EntityRepository<Entity extends object> {
@@ -80,11 +80,15 @@ export declare class EntityRepository<Entity extends object> {
80
80
  /**
81
81
  * @inheritDoc EntityManager.findByCursor
82
82
  */
83
- findByCursor<Hint extends string = never, Fields extends string = '*', Excludes extends string = never>(where: FilterQuery<Entity>, options: FindByCursorOptions<Entity, Hint, Fields, Excludes>): Promise<Cursor<Entity, Hint, Fields, Excludes>>;
83
+ findByCursor<Hint extends string = never, Fields extends string = '*', Excludes extends string = never, IncludeCount extends boolean = true>(options: FindByCursorOptions<Entity, Hint, Fields, Excludes, IncludeCount>): Promise<Cursor<Entity, Hint, Fields, Excludes, IncludeCount>>;
84
84
  /**
85
85
  * Finds all entities of given type. You can pass additional options via the `options` parameter.
86
86
  */
87
87
  findAll<Hint extends string = never, Fields extends string = '*', Excludes extends string = never>(options?: FindAllOptions<Entity, Hint, Fields, Excludes>): Promise<Loaded<Entity, Hint, Fields, Excludes>[]>;
88
+ /**
89
+ * @inheritDoc EntityManager.stream
90
+ */
91
+ stream<Hint extends string = never, Fields extends string = '*', Excludes extends string = never>(options?: StreamOptions<Entity, Hint, Fields, Excludes>): AsyncIterableIterator<Loaded<Entity, Hint, Fields, Excludes>>;
88
92
  /**
89
93
  * @inheritDoc EntityManager.insert
90
94
  */
@@ -107,10 +111,26 @@ export declare class EntityRepository<Entity extends object> {
107
111
  map(result: EntityDictionary<Entity>, options?: {
108
112
  schema?: string;
109
113
  }): Entity;
114
+ /**
115
+ * Gets a reference to the entity identified by the given type and alternate key property without actually loading it.
116
+ * The key option specifies which property to use for identity map lookup instead of the primary key.
117
+ */
118
+ getReference<K extends string & keyof Entity>(id: Entity[K], options: Omit<GetReferenceOptions, 'key' | 'wrapped'> & {
119
+ key: K;
120
+ wrapped: true;
121
+ }): Ref<Entity>;
122
+ /**
123
+ * Gets a reference to the entity identified by the given type and alternate key property without actually loading it.
124
+ * The key option specifies which property to use for identity map lookup instead of the primary key.
125
+ */
126
+ getReference<K extends string & keyof Entity>(id: Entity[K], options: Omit<GetReferenceOptions, 'key'> & {
127
+ key: K;
128
+ wrapped?: false;
129
+ }): Entity;
110
130
  /**
111
131
  * Gets a reference to the entity identified by the given type and identifier without actually loading it, if the entity is not yet loaded
112
132
  */
113
- getReference(id: Primary<Entity>, options: Omit<GetReferenceOptions, 'wrapped'> & {
133
+ getReference(id: Primary<Entity>, options: Omit<GetReferenceOptions, 'wrapped' | 'key'> & {
114
134
  wrapped: true;
115
135
  }): Ref<Entity>;
116
136
  /**
@@ -120,7 +140,7 @@ export declare class EntityRepository<Entity extends object> {
120
140
  /**
121
141
  * Gets a reference to the entity identified by the given type and identifier without actually loading it, if the entity is not yet loaded
122
142
  */
123
- getReference(id: Primary<Entity>, options: Omit<GetReferenceOptions, 'wrapped'> & {
143
+ getReference(id: Primary<Entity>, options: Omit<GetReferenceOptions, 'wrapped' | 'key'> & {
124
144
  wrapped: false;
125
145
  }): Entity;
126
146
  /**
@@ -130,7 +150,7 @@ export declare class EntityRepository<Entity extends object> {
130
150
  /**
131
151
  * Loads specified relations in batch. This will execute one query for each relation, that will populate it on all the specified entities.
132
152
  */
133
- populate<Ent extends Entity | Entity[], Hint extends string = never, Naked extends FromEntityType<Entity> = FromEntityType<Entity>, Fields extends string = '*', Excludes extends string = never>(entities: Ent, populate: AutoPath<Naked, Hint, PopulatePath.ALL>[] | false, options?: EntityLoaderOptions<Naked, Fields, Excludes>): Promise<Ent extends object[] ? MergeLoaded<ArrayElement<Ent>, Naked, Hint, Fields, Excludes>[] : MergeLoaded<Ent, Naked, Hint, Fields, Excludes>>;
153
+ populate<Ent extends Entity | Entity[], Hint extends string = never, Naked extends FromEntityType<Entity> = FromEntityType<Entity>, Fields extends string = never, Excludes extends string = never>(entities: Ent, populate: AutoPath<Naked, Hint, PopulatePath.ALL>[] | false, options?: EntityLoaderOptions<Naked, Fields, Excludes>): Promise<Ent extends object[] ? MergeLoaded<ArrayElement<Ent>, Naked, Hint, Fields, Excludes>[] : MergeLoaded<Ent, Naked, Hint, Fields, Excludes>>;
134
154
  /**
135
155
  * Creates new instance of given entity and populates it with given data.
136
156
  * The entity constructor will be used unless you provide `{ managed: true }` in the `options` parameter.
@@ -146,13 +166,13 @@ export declare class EntityRepository<Entity extends object> {
146
166
  * The newly created entity will be automatically marked for persistence via `em.persist` unless you disable this
147
167
  * behavior, either locally via `persist: false` option, or globally via `persistOnCreate` ORM config option.
148
168
  */
149
- create<Convert extends boolean = false>(data: RequiredEntityData<Entity, never, Convert>, options?: CreateOptions<Convert>): Entity;
169
+ create<Convert extends boolean = false, Data extends RequiredEntityData<Entity, never, Convert> = RequiredEntityData<Entity, never, Convert>>(data: Data & IsSubset<RequiredEntityData<Entity, never, Convert>, Data>, options?: CreateOptions<Convert>): Entity;
150
170
  /**
151
171
  * Creates new instance of given entity and populates it with given data.
152
172
  * The entity constructor will be used unless you provide `{ managed: true }` in the `options` parameter.
153
173
  * The constructor will be given parameters based on the defined constructor of the entity. If the constructor
154
174
  * parameter matches a property name, its value will be extracted from `data`. If no matching property exists,
155
- * the whole `data` parameter will be passed. This means we can also define `constructor(data: Partial<T>)` and
175
+ * the whole `data` parameter will be pass. This means we can also define `constructor(data: Partial<T>)` and
156
176
  * `em.create()` will pass the data into it (unless we have a property named `data` too).
157
177
  *
158
178
  * The parameters are strictly checked, you need to provide all required properties. You can use `OptionalProps`
@@ -162,7 +182,7 @@ export declare class EntityRepository<Entity extends object> {
162
182
  * The newly created entity will be automatically marked for persistence via `em.persist` unless you disable this
163
183
  * behavior, either locally via `persist: false` option, or globally via `persistOnCreate` ORM config option.
164
184
  */
165
- create<Convert extends boolean = false>(data: EntityData<Entity, Convert>, options: CreateOptions<Convert> & {
185
+ create<Convert extends boolean = false, Data extends EntityData<Entity, Convert> = EntityData<Entity, Convert>>(data: Data & IsSubset<EntityData<Entity, Convert>, Data>, options: CreateOptions<Convert> & {
166
186
  partial: true;
167
187
  }): Entity;
168
188
  /**
@@ -90,8 +90,8 @@ export class EntityRepository {
90
90
  /**
91
91
  * @inheritDoc EntityManager.findByCursor
92
92
  */
93
- async findByCursor(where, options) {
94
- return this.getEntityManager().findByCursor(this.entityName, where, options);
93
+ async findByCursor(options) {
94
+ return this.getEntityManager().findByCursor(this.entityName, options);
95
95
  }
96
96
  /**
97
97
  * Finds all entities of given type. You can pass additional options via the `options` parameter.
@@ -99,6 +99,12 @@ export class EntityRepository {
99
99
  async findAll(options) {
100
100
  return this.getEntityManager().findAll(this.entityName, options);
101
101
  }
102
+ /**
103
+ * @inheritDoc EntityManager.stream
104
+ */
105
+ async *stream(options) {
106
+ yield* this.getEntityManager().stream(this.entityName, options);
107
+ }
102
108
  /**
103
109
  * @inheritDoc EntityManager.insert
104
110
  */
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Wrapper class for polymorphic relation reference data.
3
+ * Holds the discriminator value (type identifier) and the primary key value(s).
4
+ * Used internally to track polymorphic FK values before hydration.
5
+ */
6
+ export declare class PolymorphicRef {
7
+ readonly discriminator: string;
8
+ id: unknown;
9
+ constructor(discriminator: string, id: unknown);
10
+ /** Returns `[discriminator, ...idValues]` tuple suitable for column-level expansion. */
11
+ toTuple(): unknown[];
12
+ }
@@ -0,0 +1,18 @@
1
+ import { Utils } from '../utils/Utils.js';
2
+ /**
3
+ * Wrapper class for polymorphic relation reference data.
4
+ * Holds the discriminator value (type identifier) and the primary key value(s).
5
+ * Used internally to track polymorphic FK values before hydration.
6
+ */
7
+ export class PolymorphicRef {
8
+ discriminator;
9
+ id;
10
+ constructor(discriminator, id) {
11
+ this.discriminator = discriminator;
12
+ this.id = id;
13
+ }
14
+ /** Returns `[discriminator, ...idValues]` tuple suitable for column-level expansion. */
15
+ toTuple() {
16
+ return [this.discriminator, ...Utils.asArray(this.id)];
17
+ }
18
+ }
@@ -1,8 +1,8 @@
1
- import { inspect } from 'node:util';
2
- import type { AddEager, Dictionary, EntityClass, EntityKey, EntityProperty, Loaded, LoadedReference, Primary, Ref } from '../typings.js';
1
+ import type { AddEager, AddOptional, Dictionary, EntityClass, EntityKey, EntityProperty, Loaded, LoadedReference, Primary, Ref } from '../typings.js';
3
2
  import type { FindOneOptions, FindOneOrFailOptions } from '../drivers/IDatabaseDriver.js';
4
3
  export declare class Reference<T extends object> {
5
4
  private entity;
5
+ private property?;
6
6
  constructor(entity: T);
7
7
  static create<T extends object>(entity: T | Ref<T>): Ref<T>;
8
8
  static createFromPK<T extends object>(entityType: EntityClass<T>, pk: Primary<T>, options?: {
@@ -42,8 +42,6 @@ export declare class Reference<T extends object> {
42
42
  isInitialized(): boolean;
43
43
  populated(populated?: boolean): void;
44
44
  toJSON(...args: any[]): Dictionary;
45
- /** @ignore */
46
- [inspect.custom](depth?: number): string;
47
45
  }
48
46
  export declare class ScalarReference<Value> {
49
47
  private value?;
@@ -56,12 +54,15 @@ export declare class ScalarReference<Value> {
56
54
  * Returns either the whole entity, or the requested property.
57
55
  */
58
56
  load(options?: Omit<LoadReferenceOptions<any, any>, 'populate' | 'fields' | 'exclude'>): Promise<Value | undefined>;
57
+ /**
58
+ * Ensures the underlying entity is loaded first (without reloading it if it already is loaded).
59
+ * Returns the entity or throws an error just like `em.findOneOrFail()` (and respects the same config options).
60
+ */
61
+ loadOrFail(options?: Omit<LoadReferenceOrFailOptions<any, any>, 'populate' | 'fields' | 'exclude'>): Promise<Value>;
59
62
  set(value: Value): void;
60
63
  bind<Entity extends object>(entity: Entity, property: EntityKey<Entity>): void;
61
64
  unwrap(): Value | undefined;
62
65
  isInitialized(): boolean;
63
- /** @ignore */
64
- [inspect.custom](): string;
65
66
  }
66
67
  export interface LoadReferenceOptions<T extends object, P extends string = never, F extends string = '*', E extends string = never> extends FindOneOptions<T, P, F, E> {
67
68
  dataloader?: boolean;
@@ -72,15 +73,11 @@ export interface LoadReferenceOrFailOptions<T extends object, P extends string =
72
73
  /**
73
74
  * shortcut for `wrap(entity).toReference()`
74
75
  */
75
- export declare function ref<T>(entity: T | Ref<T>): Ref<T> & LoadedReference<Loaded<T, AddEager<T>>>;
76
+ export declare function ref<I extends unknown | Ref<unknown> | undefined | null, T extends I & {}>(entity: I): Ref<T> & LoadedReference<Loaded<T, AddEager<T>>> | AddOptional<typeof entity>;
76
77
  /**
77
78
  * shortcut for `Reference.createFromPK(entityType, pk)`
78
79
  */
79
- export declare function ref<T, PKV extends Primary<T> = Primary<T>>(entityType: EntityClass<T>, pk?: T | PKV): Ref<T>;
80
- /**
81
- * shortcut for `wrap(entity).toReference()`
82
- */
83
- export declare function ref<T>(value: T | Ref<T>): Ref<T> & LoadedReference<Loaded<T, AddEager<T>>>;
80
+ export declare function ref<I extends unknown | undefined | null, T, PKV extends Primary<T> = Primary<T>>(entityType: EntityClass<T>, pk: I): Ref<T> | AddOptional<typeof pk>;
84
81
  /**
85
82
  * shortcut for `Reference.createNakedFromPK(entityType, pk)`
86
83
  */
@@ -1,9 +1,12 @@
1
- import { inspect } from 'node:util';
2
1
  import { DataloaderType } from '../enums.js';
3
2
  import { helper, wrap } from './wrap.js';
4
3
  import { Utils } from '../utils/Utils.js';
4
+ import { QueryHelper } from '../utils/QueryHelper.js';
5
+ import { NotFoundError } from '../errors.js';
6
+ import { inspect } from '../logging/inspect.js';
5
7
  export class Reference {
6
8
  entity;
9
+ property;
7
10
  constructor(entity) {
8
11
  this.entity = entity;
9
12
  this.set(entity);
@@ -33,10 +36,15 @@ export class Reference {
33
36
  }
34
37
  static createFromPK(entityType, pk, options) {
35
38
  const ref = this.createNakedFromPK(entityType, pk, options);
36
- return helper(ref).toReference();
39
+ return helper(ref)?.toReference() ?? ref;
37
40
  }
38
41
  static createNakedFromPK(entityType, pk, options) {
39
42
  const factory = entityType.prototype.__factory;
43
+ if (!factory) {
44
+ // this can happen only if `ref()` is used as a property initializer, and the value is important only for the
45
+ // inference of defaults, so it's fine to return it directly without wrapping with `Reference` class
46
+ return pk;
47
+ }
40
48
  const entity = factory.createReference(entityType, pk, {
41
49
  merge: false,
42
50
  convertCustomTypes: false,
@@ -58,7 +66,9 @@ export class Reference {
58
66
  */
59
67
  static wrapReference(entity, prop) {
60
68
  if (entity && prop.ref && !Reference.isReference(entity)) {
61
- return Reference.create(entity);
69
+ const ref = Reference.create(entity);
70
+ ref.property = prop;
71
+ return ref;
62
72
  }
63
73
  return entity;
64
74
  }
@@ -78,13 +88,14 @@ export class Reference {
78
88
  if (!wrapped.__em) {
79
89
  return this.entity;
80
90
  }
91
+ options = { ...options, filters: QueryHelper.mergePropertyFilters(this.property?.filters, options.filters) };
81
92
  if (this.isInitialized() && !options.refresh && options.populate) {
82
93
  await wrapped.__em.populate(this.entity, options.populate, options);
83
94
  }
84
95
  if (!this.isInitialized() || options.refresh) {
85
96
  if (options.dataloader ?? [DataloaderType.ALL, DataloaderType.REFERENCE].includes(wrapped.__em.config.getDataloaderType())) {
86
- // eslint-disable-next-line dot-notation
87
- return wrapped.__em['refLoader'].load([this, options]);
97
+ const dataLoader = await wrapped.__em.getDataLoader('ref');
98
+ return dataLoader.load([this, options]);
88
99
  }
89
100
  return wrapped.init(options);
90
101
  }
@@ -135,9 +146,9 @@ export class Reference {
135
146
  return wrap(this.entity).toJSON(...args);
136
147
  }
137
148
  /** @ignore */
138
- [inspect.custom](depth = 2) {
149
+ [Symbol.for('nodejs.util.inspect.custom')](depth = 2) {
139
150
  const object = { ...this };
140
- const hidden = ['meta'];
151
+ const hidden = ['meta', 'property'];
141
152
  hidden.forEach(k => delete object[k]);
142
153
  const ret = inspect(object, { depth });
143
154
  const wrapped = helper(this.entity);
@@ -171,6 +182,20 @@ export class ScalarReference {
171
182
  }
172
183
  return this.value;
173
184
  }
185
+ /**
186
+ * Ensures the underlying entity is loaded first (without reloading it if it already is loaded).
187
+ * Returns the entity or throws an error just like `em.findOneOrFail()` (and respects the same config options).
188
+ */
189
+ async loadOrFail(options = {}) {
190
+ const ret = await this.load(options);
191
+ if (ret == null) {
192
+ const wrapped = helper(this.entity);
193
+ options.failHandler ??= wrapped.__em.config.get('findOneOrFailHandler');
194
+ const entityName = this.entity.constructor.name;
195
+ throw NotFoundError.failedToLoadProperty(entityName, this.property, wrapped.getPrimaryKey());
196
+ }
197
+ return ret;
198
+ }
174
199
  set(value) {
175
200
  this.value = value;
176
201
  this.initialized = true;
@@ -186,9 +211,9 @@ export class ScalarReference {
186
211
  isInitialized() {
187
212
  return this.initialized;
188
213
  }
189
- /* v8 ignore next 4 */
190
214
  /** @ignore */
191
- [inspect.custom]() {
215
+ /* v8 ignore next */
216
+ [Symbol.for('nodejs.util.inspect.custom')]() {
192
217
  return this.initialized ? `Ref<${inspect(this.value)}>` : `Ref<?>`;
193
218
  }
194
219
  }
@@ -1,7 +1,6 @@
1
1
  import type { PopulatePath } from '../enums.js';
2
- import { inspect } from 'node:util';
3
2
  import type { EntityManager } from '../EntityManager.js';
4
- import type { Dictionary, EntityData, EntityDictionary, EntityMetadata, IHydrator, EntityKey, PopulateOptions, Primary, AutoPath, Ref, AddEager, LoadedReference, EntityDTO, Loaded, FromEntityType, IsSubset, MergeSelected } from '../typings.js';
3
+ import type { Dictionary, EntityData, EntityDictionary, EntityMetadata, IHydrator, EntityKey, PopulateOptions, Primary, AutoPath, Ref, AddEager, LoadedReference, EntityDTO, Loaded, SerializeDTO, FromEntityType, IsSubset, MergeSelected } from '../typings.js';
5
4
  import { Reference } from './Reference.js';
6
5
  import { type AssignOptions } from './EntityAssigner.js';
7
6
  import type { EntityLoaderOptions } from './EntityLoader.js';
@@ -11,7 +10,6 @@ import { type SerializeOptions } from '../serialization/EntitySerializer.js';
11
10
  import type { FindOneOptions, LoadHint } from '../drivers/IDatabaseDriver.js';
12
11
  export declare class WrappedEntity<Entity extends object> {
13
12
  __initialized: boolean;
14
- __touched: boolean;
15
13
  __populated?: boolean;
16
14
  __managed?: boolean;
17
15
  __onLoadFired?: boolean;
@@ -41,18 +39,17 @@ export declare class WrappedEntity<Entity extends object> {
41
39
  private readonly pkGetterConverted?;
42
40
  constructor(entity: Entity, hydrator: IHydrator, pkGetter?: (e: Entity) => Primary<Entity>, pkSerializer?: (e: Entity) => string, pkGetterConverted?: (e: Entity) => Primary<Entity>);
43
41
  isInitialized(): boolean;
44
- isTouched(): boolean;
45
42
  isManaged(): boolean;
46
43
  populated(populated?: boolean | undefined): void;
47
44
  setSerializationContext<Hint extends string = never, Fields extends string = '*', Exclude extends string = never>(options: LoadHint<Entity, Hint, Fields, Exclude>): void;
48
45
  toReference(): Ref<Entity> & LoadedReference<Loaded<Entity, AddEager<Entity>>>;
49
46
  toObject<Ignored extends EntityKey<Entity> = never>(ignoreFields?: Ignored[]): Omit<EntityDTO<Entity>, Ignored>;
50
- serialize<Hint extends string = never, Exclude extends string = never>(options?: SerializeOptions<Entity, Hint, Exclude>): EntityDTO<Loaded<Entity, Hint>>;
47
+ serialize<Hint extends string = never, Exclude extends string = never>(options?: SerializeOptions<Entity, Hint, Exclude>): SerializeDTO<Entity, Hint, Exclude>;
51
48
  toPOJO(): EntityDTO<Entity>;
52
49
  toJSON(...args: any[]): EntityDictionary<Entity>;
53
50
  assign<Naked extends FromEntityType<Entity> = FromEntityType<Entity>, Convert extends boolean = false, Data extends EntityData<Naked, Convert> | Partial<EntityDTO<Naked>> = EntityData<Naked, Convert> | Partial<EntityDTO<Naked>>>(data: Data & IsSubset<EntityData<Naked>, Data>, options?: AssignOptions<Convert>): MergeSelected<Entity, Naked, keyof Data & string>;
54
51
  init<Hint extends string = never, Fields extends string = '*', Excludes extends string = never>(options?: FindOneOptions<Entity, Hint, Fields, Excludes>): Promise<Loaded<Entity, Hint, Fields, Excludes> | null>;
55
- populate<Hint extends string = never>(populate: AutoPath<Entity, Hint, PopulatePath.ALL>[] | false, options?: EntityLoaderOptions<Entity>): Promise<Loaded<Entity, Hint>>;
52
+ populate<Hint extends string = never, Fields extends string = never>(populate: AutoPath<Entity, Hint, PopulatePath.ALL>[] | false, options?: EntityLoaderOptions<Entity, Fields>): Promise<Loaded<Entity, Hint>>;
56
53
  hasPrimaryKey(): boolean;
57
54
  getPrimaryKey(convertCustomTypes?: boolean): Primary<Entity> | null;
58
55
  getPrimaryKeys(convertCustomTypes?: boolean): Primary<Entity>[] | null;
@@ -64,6 +61,4 @@ export declare class WrappedEntity<Entity extends object> {
64
61
  get __platform(): import("../index.js").Platform;
65
62
  get __config(): import("../index.js").Configuration<import("../drivers/IDatabaseDriver.js").IDatabaseDriver<import("../index.js").Connection>, EntityManager<import("../drivers/IDatabaseDriver.js").IDatabaseDriver<import("../index.js").Connection>>>;
66
63
  get __primaryKeys(): Primary<Entity>[];
67
- /** @ignore */
68
- [inspect.custom](): string;
69
64
  }
@@ -1,4 +1,3 @@
1
- import { inspect } from 'node:util';
2
1
  import { Reference } from './Reference.js';
3
2
  import { EntityTransformer } from '../serialization/EntityTransformer.js';
4
3
  import { EntityAssigner } from './EntityAssigner.js';
@@ -15,7 +14,6 @@ export class WrappedEntity {
15
14
  this.pkSerializer = pkSerializer;
16
15
  this.pkGetterConverted = pkGetterConverted;
17
16
  this.__initialized = true;
18
- this.__touched = false;
19
17
  this.__serializationContext = {};
20
18
  this.__loadedProperties = new Set();
21
19
  this.__data = {};
@@ -24,9 +22,6 @@ export class WrappedEntity {
24
22
  isInitialized() {
25
23
  return this.__initialized;
26
24
  }
27
- isTouched() {
28
- return this.__touched;
29
- }
30
25
  isManaged() {
31
26
  return !!this.__managed;
32
27
  }
@@ -76,7 +71,7 @@ export class WrappedEntity {
76
71
  if (!this.__em) {
77
72
  throw ValidationError.entityNotManaged(this.entity);
78
73
  }
79
- return this.__em.findOne(this.entity.constructor.name, this.entity, { ...options, refresh: true, schema: this.__schema });
74
+ return this.__em.findOne(this.entity.constructor, this.entity, { ...options, refresh: true, schema: this.__schema });
80
75
  }
81
76
  async populate(populate, options = {}) {
82
77
  if (!this.__em) {
@@ -150,10 +145,10 @@ export class WrappedEntity {
150
145
  return this.__em?.config ?? this.entity.__config;
151
146
  }
152
147
  get __primaryKeys() {
153
- return Utils.getPrimaryKeyValues(this.entity, this.__meta.primaryKeys);
148
+ return Utils.getPrimaryKeyValues(this.entity, this.__meta);
154
149
  }
155
150
  /** @ignore */
156
- [inspect.custom]() {
151
+ [Symbol.for('nodejs.util.inspect.custom')]() {
157
152
  return `[WrappedEntity<${this.__meta.className}>]`;
158
153
  }
159
154
  }