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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (207) hide show
  1. package/EntityManager.d.ts +883 -579
  2. package/EntityManager.js +1897 -1865
  3. package/MikroORM.d.ts +103 -72
  4. package/MikroORM.js +178 -177
  5. package/README.md +128 -294
  6. package/cache/CacheAdapter.d.ts +38 -36
  7. package/cache/FileCacheAdapter.d.ts +30 -24
  8. package/cache/FileCacheAdapter.js +80 -78
  9. package/cache/GeneratedCacheAdapter.d.ts +19 -20
  10. package/cache/GeneratedCacheAdapter.js +31 -30
  11. package/cache/MemoryCacheAdapter.d.ts +19 -20
  12. package/cache/MemoryCacheAdapter.js +36 -36
  13. package/cache/NullCacheAdapter.d.ts +17 -16
  14. package/cache/NullCacheAdapter.js +25 -24
  15. package/connections/Connection.d.ts +99 -75
  16. package/connections/Connection.js +166 -160
  17. package/drivers/DatabaseDriver.d.ts +187 -69
  18. package/drivers/DatabaseDriver.js +451 -432
  19. package/drivers/IDatabaseDriver.d.ts +464 -281
  20. package/drivers/IDatabaseDriver.js +1 -0
  21. package/entity/BaseEntity.d.ts +121 -73
  22. package/entity/BaseEntity.js +44 -33
  23. package/entity/Collection.d.ts +216 -157
  24. package/entity/Collection.js +728 -707
  25. package/entity/EntityAssigner.d.ts +90 -76
  26. package/entity/EntityAssigner.js +232 -229
  27. package/entity/EntityFactory.d.ts +68 -40
  28. package/entity/EntityFactory.js +427 -366
  29. package/entity/EntityHelper.d.ts +34 -22
  30. package/entity/EntityHelper.js +280 -267
  31. package/entity/EntityIdentifier.d.ts +4 -4
  32. package/entity/EntityIdentifier.js +10 -10
  33. package/entity/EntityLoader.d.ts +105 -56
  34. package/entity/EntityLoader.js +754 -722
  35. package/entity/EntityRepository.d.ts +317 -200
  36. package/entity/EntityRepository.js +214 -212
  37. package/entity/PolymorphicRef.d.ts +5 -5
  38. package/entity/PolymorphicRef.js +10 -10
  39. package/entity/Reference.d.ts +130 -66
  40. package/entity/Reference.js +280 -260
  41. package/entity/WrappedEntity.d.ts +116 -53
  42. package/entity/WrappedEntity.js +169 -147
  43. package/entity/defineEntity.d.ts +1290 -614
  44. package/entity/defineEntity.js +521 -511
  45. package/entity/utils.d.ts +13 -3
  46. package/entity/utils.js +71 -73
  47. package/entity/validators.js +43 -43
  48. package/entity/wrap.js +8 -8
  49. package/enums.d.ts +275 -138
  50. package/enums.js +268 -137
  51. package/errors.d.ts +120 -72
  52. package/errors.js +356 -253
  53. package/events/EventManager.d.ts +27 -10
  54. package/events/EventManager.js +80 -73
  55. package/events/EventSubscriber.d.ts +33 -29
  56. package/events/TransactionEventBroadcaster.d.ts +16 -7
  57. package/events/TransactionEventBroadcaster.js +15 -13
  58. package/exceptions.d.ts +23 -40
  59. package/exceptions.js +35 -52
  60. package/hydration/Hydrator.d.ts +43 -16
  61. package/hydration/Hydrator.js +44 -42
  62. package/hydration/ObjectHydrator.d.ts +51 -17
  63. package/hydration/ObjectHydrator.js +480 -416
  64. package/index.d.ts +116 -2
  65. package/index.js +10 -1
  66. package/logging/DefaultLogger.d.ts +35 -30
  67. package/logging/DefaultLogger.js +87 -84
  68. package/logging/Logger.d.ts +45 -40
  69. package/logging/SimpleLogger.d.ts +13 -11
  70. package/logging/SimpleLogger.js +22 -22
  71. package/logging/colors.d.ts +6 -6
  72. package/logging/colors.js +11 -10
  73. package/logging/inspect.js +7 -7
  74. package/metadata/EntitySchema.d.ts +214 -108
  75. package/metadata/EntitySchema.js +398 -379
  76. package/metadata/MetadataDiscovery.d.ts +115 -111
  77. package/metadata/MetadataDiscovery.js +1948 -1857
  78. package/metadata/MetadataProvider.d.ts +25 -14
  79. package/metadata/MetadataProvider.js +83 -77
  80. package/metadata/MetadataStorage.d.ts +39 -19
  81. package/metadata/MetadataStorage.js +119 -106
  82. package/metadata/MetadataValidator.d.ts +39 -39
  83. package/metadata/MetadataValidator.js +381 -338
  84. package/metadata/discover-entities.d.ts +5 -2
  85. package/metadata/discover-entities.js +27 -27
  86. package/metadata/types.d.ts +615 -531
  87. package/naming-strategy/AbstractNamingStrategy.d.ts +55 -39
  88. package/naming-strategy/AbstractNamingStrategy.js +91 -85
  89. package/naming-strategy/EntityCaseNamingStrategy.d.ts +6 -6
  90. package/naming-strategy/EntityCaseNamingStrategy.js +22 -22
  91. package/naming-strategy/MongoNamingStrategy.d.ts +7 -6
  92. package/naming-strategy/MongoNamingStrategy.js +19 -18
  93. package/naming-strategy/NamingStrategy.d.ts +109 -99
  94. package/naming-strategy/UnderscoreNamingStrategy.d.ts +8 -7
  95. package/naming-strategy/UnderscoreNamingStrategy.js +22 -21
  96. package/not-supported.js +7 -4
  97. package/package.json +1 -1
  98. package/platforms/ExceptionConverter.d.ts +2 -1
  99. package/platforms/ExceptionConverter.js +5 -4
  100. package/platforms/Platform.d.ts +310 -236
  101. package/platforms/Platform.js +661 -573
  102. package/serialization/EntitySerializer.d.ts +49 -25
  103. package/serialization/EntitySerializer.js +224 -216
  104. package/serialization/EntityTransformer.d.ts +11 -5
  105. package/serialization/EntityTransformer.js +220 -216
  106. package/serialization/SerializationContext.d.ts +27 -18
  107. package/serialization/SerializationContext.js +105 -100
  108. package/types/ArrayType.d.ts +9 -8
  109. package/types/ArrayType.js +34 -33
  110. package/types/BigIntType.d.ts +17 -10
  111. package/types/BigIntType.js +37 -37
  112. package/types/BlobType.d.ts +4 -3
  113. package/types/BlobType.js +14 -13
  114. package/types/BooleanType.d.ts +5 -4
  115. package/types/BooleanType.js +13 -12
  116. package/types/CharacterType.d.ts +3 -2
  117. package/types/CharacterType.js +7 -6
  118. package/types/DateTimeType.d.ts +6 -5
  119. package/types/DateTimeType.js +16 -15
  120. package/types/DateType.d.ts +6 -5
  121. package/types/DateType.js +16 -15
  122. package/types/DecimalType.d.ts +7 -7
  123. package/types/DecimalType.js +26 -26
  124. package/types/DoubleType.d.ts +3 -3
  125. package/types/DoubleType.js +12 -12
  126. package/types/EnumArrayType.d.ts +6 -5
  127. package/types/EnumArrayType.js +25 -24
  128. package/types/EnumType.d.ts +4 -3
  129. package/types/EnumType.js +12 -11
  130. package/types/FloatType.d.ts +4 -3
  131. package/types/FloatType.js +10 -9
  132. package/types/IntegerType.d.ts +4 -3
  133. package/types/IntegerType.js +10 -9
  134. package/types/IntervalType.d.ts +5 -4
  135. package/types/IntervalType.js +13 -12
  136. package/types/JsonType.d.ts +9 -8
  137. package/types/JsonType.js +33 -32
  138. package/types/MediumIntType.d.ts +2 -1
  139. package/types/MediumIntType.js +4 -3
  140. package/types/SmallIntType.d.ts +4 -3
  141. package/types/SmallIntType.js +10 -9
  142. package/types/StringType.d.ts +5 -4
  143. package/types/StringType.js +13 -12
  144. package/types/TextType.d.ts +4 -3
  145. package/types/TextType.js +10 -9
  146. package/types/TimeType.d.ts +6 -5
  147. package/types/TimeType.js +18 -17
  148. package/types/TinyIntType.d.ts +4 -3
  149. package/types/TinyIntType.js +11 -10
  150. package/types/Type.d.ts +88 -73
  151. package/types/Type.js +85 -74
  152. package/types/Uint8ArrayType.d.ts +5 -4
  153. package/types/Uint8ArrayType.js +22 -21
  154. package/types/UnknownType.d.ts +5 -4
  155. package/types/UnknownType.js +13 -12
  156. package/types/UuidType.d.ts +6 -5
  157. package/types/UuidType.js +20 -19
  158. package/types/index.d.ts +77 -49
  159. package/types/index.js +64 -26
  160. package/typings.d.ts +1388 -729
  161. package/typings.js +255 -231
  162. package/unit-of-work/ChangeSet.d.ts +28 -24
  163. package/unit-of-work/ChangeSet.js +58 -54
  164. package/unit-of-work/ChangeSetComputer.d.ts +13 -11
  165. package/unit-of-work/ChangeSetComputer.js +180 -159
  166. package/unit-of-work/ChangeSetPersister.d.ts +64 -41
  167. package/unit-of-work/ChangeSetPersister.js +443 -418
  168. package/unit-of-work/CommitOrderCalculator.d.ts +40 -40
  169. package/unit-of-work/CommitOrderCalculator.js +89 -88
  170. package/unit-of-work/IdentityMap.d.ts +32 -25
  171. package/unit-of-work/IdentityMap.js +106 -99
  172. package/unit-of-work/UnitOfWork.d.ts +182 -127
  173. package/unit-of-work/UnitOfWork.js +1201 -1169
  174. package/utils/AbstractMigrator.d.ts +111 -91
  175. package/utils/AbstractMigrator.js +275 -275
  176. package/utils/AbstractSchemaGenerator.d.ts +43 -34
  177. package/utils/AbstractSchemaGenerator.js +121 -122
  178. package/utils/AsyncContext.d.ts +3 -3
  179. package/utils/AsyncContext.js +34 -35
  180. package/utils/Configuration.d.ts +853 -801
  181. package/utils/Configuration.js +360 -337
  182. package/utils/Cursor.d.ts +40 -22
  183. package/utils/Cursor.js +135 -127
  184. package/utils/DataloaderUtils.d.ts +58 -43
  185. package/utils/DataloaderUtils.js +203 -198
  186. package/utils/EntityComparator.d.ts +99 -80
  187. package/utils/EntityComparator.js +825 -727
  188. package/utils/NullHighlighter.d.ts +2 -1
  189. package/utils/NullHighlighter.js +4 -3
  190. package/utils/QueryHelper.d.ts +79 -51
  191. package/utils/QueryHelper.js +372 -361
  192. package/utils/RawQueryFragment.d.ts +54 -28
  193. package/utils/RawQueryFragment.js +110 -99
  194. package/utils/RequestContext.d.ts +33 -32
  195. package/utils/RequestContext.js +52 -53
  196. package/utils/TransactionContext.d.ts +17 -16
  197. package/utils/TransactionContext.js +28 -27
  198. package/utils/TransactionManager.d.ts +58 -58
  199. package/utils/TransactionManager.js +199 -197
  200. package/utils/Utils.d.ts +210 -145
  201. package/utils/Utils.js +820 -813
  202. package/utils/clone.js +104 -113
  203. package/utils/env-vars.js +90 -88
  204. package/utils/fs-utils.d.ts +15 -15
  205. package/utils/fs-utils.js +180 -181
  206. package/utils/upsert-utils.d.ts +20 -5
  207. package/utils/upsert-utils.js +114 -116
@@ -6,243 +6,246 @@ import { validateProperty } from './validators.js';
6
6
  import { helper, wrap } from './wrap.js';
7
7
  import { EntityHelper } from './EntityHelper.js';
8
8
  import { ValidationError } from '../errors.js';
9
+ /** Handles assigning data to entities, resolving relations, and propagating changes. */
9
10
  export class EntityAssigner {
10
- static assign(entity, data, options = {}) {
11
- let opts = options;
12
- if (opts.visited?.has(entity)) {
13
- return entity;
14
- }
15
- EntityHelper.ensurePropagation(entity);
16
- opts.visited ??= new Set();
17
- opts.visited.add(entity);
18
- const wrapped = helper(entity);
19
- opts = {
20
- ...wrapped.__config.get('assign'),
21
- schema: wrapped.__schema,
22
- ...opts, // allow overriding the defaults
23
- };
24
- const meta = wrapped.__meta;
25
- const props = meta.properties;
26
- Object.keys(data).forEach(prop => {
27
- return EntityAssigner.assignProperty(entity, prop, props, data, {
28
- ...opts,
29
- em: opts.em || wrapped.__em,
30
- platform: wrapped.__platform,
31
- });
32
- });
33
- return entity;
34
- }
35
- static assignProperty(entity, propName, props, data, options) {
36
- let value = data[propName];
37
- const onlyProperties = options.onlyProperties && !(propName in props);
38
- const ignoreUndefined = options.ignoreUndefined === true && value === undefined;
39
- if (onlyProperties || ignoreUndefined) {
40
- return;
41
- }
42
- const prop = { ...props[propName], name: propName };
43
- if (prop && options.onlyOwnProperties) {
44
- if ([ReferenceKind.ONE_TO_MANY].includes(prop.kind)) {
45
- return;
46
- }
47
- if ([ReferenceKind.MANY_TO_MANY].includes(prop.kind)) {
48
- if (!prop.owner) {
49
- return;
50
- }
51
- else if (value?.map) {
52
- value = value.map((v) => Utils.extractPK(v, prop.targetMeta));
53
- }
54
- }
55
- if ([ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(prop.kind)) {
56
- value = Utils.extractPK(value, prop.targetMeta);
57
- }
58
- }
59
- if (propName in props && !prop.nullable && value == null) {
60
- throw new Error(`You must pass a non-${value} value to the property ${propName} of entity ${entity.constructor.name}.`);
61
- }
62
- // create collection instance if its missing so old items can be deleted with orphan removal
63
- if ([ReferenceKind.MANY_TO_MANY, ReferenceKind.ONE_TO_MANY].includes(prop?.kind) && entity[prop.name] == null) {
64
- entity[prop.name] = Collection.create(entity, prop.name, undefined, helper(entity).isInitialized());
65
- }
66
- if (prop && Utils.isCollection(entity[prop.name])) {
67
- return EntityAssigner.assignCollection(entity, entity[prop.name], value, prop, options.em, options);
68
- }
69
- const customType = prop?.customType;
70
- if (options.convertCustomTypes && customType && prop.kind === ReferenceKind.SCALAR && !Utils.isEntity(data)) {
71
- value = customType.convertToJSValue(value, options.platform);
72
- }
73
- if ([ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(prop?.kind) && value != null) {
74
- if (options.updateNestedEntities &&
75
- Object.hasOwn(entity, propName) &&
76
- Utils.isEntity(entity[propName], true) &&
77
- Utils.isPlainObject(value)) {
78
- const unwrappedEntity = Reference.unwrapReference(entity[propName]);
79
- const wrapped = helper(unwrappedEntity);
80
- if (options.updateByPrimaryKey) {
81
- const pk = Utils.extractPK(value, prop.targetMeta);
82
- if (pk) {
83
- const ref = options.em.getReference(prop.targetMeta.class, pk, options);
84
- // if the PK differs, we want to change the target entity, not update it
85
- const wrappedChild = helper(ref);
86
- const sameTarget = wrappedChild.getSerializedPrimaryKey() === wrapped.getSerializedPrimaryKey();
87
- if (wrappedChild.__managed && wrappedChild.isInitialized() && sameTarget) {
88
- return EntityAssigner.assign(ref, value, options);
89
- }
90
- }
91
- return EntityAssigner.assignReference(entity, value, prop, options.em, options);
92
- }
93
- if (wrapped.__managed && wrap(unwrappedEntity).isInitialized()) {
94
- return EntityAssigner.assign(unwrappedEntity, value, options);
95
- }
96
- }
97
- return EntityAssigner.assignReference(entity, value, prop, options.em, options);
98
- }
99
- if (prop.kind === ReferenceKind.SCALAR && SCALAR_TYPES.has(prop.runtimeType) && (prop.setter || !prop.getter)) {
100
- validateProperty(prop, value, entity);
101
- return (entity[prop.name] = value);
102
- }
103
- if (prop.kind === ReferenceKind.EMBEDDED && EntityAssigner.validateEM(options.em)) {
104
- return EntityAssigner.assignEmbeddable(entity, value, prop, options.em, options);
105
- }
106
- if (options.mergeObjectProperties &&
107
- Utils.isPlainObject(entity[propName]) &&
108
- Utils.isPlainObject(value)) {
109
- entity[propName] ??= {};
110
- entity[propName] = Utils.merge({}, entity[propName], value);
111
- }
112
- else if (!prop || prop.setter || !prop.getter) {
113
- entity[propName] = value;
114
- }
11
+ /** Assigns the given data to the entity, resolving relations and handling custom types. */
12
+ static assign(entity, data, options = {}) {
13
+ let opts = options;
14
+ if (opts.visited?.has(entity)) {
15
+ return entity;
115
16
  }
116
- /**
117
- * auto-wire 1:1 inverse side with owner as in no-sql drivers it can't be joined
118
- * also makes sure the link is bidirectional when creating new entities from nested structures
119
- * @internal
120
- */
121
- static autoWireOneToOne(prop, entity) {
122
- const ref = entity[prop.name];
123
- if (prop.kind !== ReferenceKind.ONE_TO_ONE || !Utils.isEntity(ref)) {
124
- return;
125
- }
126
- const meta2 = helper(ref).__meta;
127
- const prop2 = meta2.properties[prop.inversedBy || prop.mappedBy];
128
- /* v8 ignore next */
129
- if (prop2 && !ref[prop2.name]) {
130
- if (Reference.isReference(ref)) {
131
- ref.unwrap()[prop2.name] = Reference.wrapReference(entity, prop2);
132
- }
133
- else {
134
- ref[prop2.name] = Reference.wrapReference(entity, prop2);
135
- }
136
- }
17
+ EntityHelper.ensurePropagation(entity);
18
+ opts.visited ??= new Set();
19
+ opts.visited.add(entity);
20
+ const wrapped = helper(entity);
21
+ opts = {
22
+ ...wrapped.__config.get('assign'),
23
+ schema: wrapped.__schema,
24
+ ...opts, // allow overriding the defaults
25
+ };
26
+ const meta = wrapped.__meta;
27
+ const props = meta.properties;
28
+ Object.keys(data).forEach(prop => {
29
+ return EntityAssigner.assignProperty(entity, prop, props, data, {
30
+ ...opts,
31
+ em: opts.em || wrapped.__em,
32
+ platform: wrapped.__platform,
33
+ });
34
+ });
35
+ return entity;
36
+ }
37
+ static assignProperty(entity, propName, props, data, options) {
38
+ let value = data[propName];
39
+ const onlyProperties = options.onlyProperties && !(propName in props);
40
+ const ignoreUndefined = options.ignoreUndefined === true && value === undefined;
41
+ if (onlyProperties || ignoreUndefined) {
42
+ return;
137
43
  }
138
- static validateEM(em) {
139
- if (!em) {
140
- throw new Error(`To use assign() on not managed entities, explicitly provide EM instance: wrap(entity).assign(data, { em: orm.em })`);
141
- }
142
- return true;
44
+ const prop = { ...props[propName], name: propName };
45
+ if (prop && options.onlyOwnProperties) {
46
+ if ([ReferenceKind.ONE_TO_MANY].includes(prop.kind)) {
47
+ return;
48
+ }
49
+ if ([ReferenceKind.MANY_TO_MANY].includes(prop.kind)) {
50
+ if (!prop.owner) {
51
+ return;
52
+ } else if (value?.map) {
53
+ value = value.map(v => Utils.extractPK(v, prop.targetMeta));
54
+ }
55
+ }
56
+ if ([ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(prop.kind)) {
57
+ value = Utils.extractPK(value, prop.targetMeta);
58
+ }
143
59
  }
144
- static assignReference(entity, value, prop, em, options) {
145
- if (Utils.isEntity(value, true)) {
146
- entity[prop.name] = Reference.wrapReference(value, prop);
147
- }
148
- else if (Utils.isPrimaryKey(value, true) && EntityAssigner.validateEM(em)) {
149
- entity[prop.name] = prop.mapToPk
150
- ? value
151
- : Reference.wrapReference(em.getReference(prop.targetMeta.class, value, options), prop);
152
- }
153
- else if (Utils.isPlainObject(value) && options.merge && EntityAssigner.validateEM(em)) {
154
- entity[prop.name] = Reference.wrapReference(em.merge(prop.targetMeta.class, value, options), prop);
155
- }
156
- else if (Utils.isPlainObject(value) && EntityAssigner.validateEM(em)) {
157
- entity[prop.name] = Reference.wrapReference(em.create(prop.targetMeta.class, value, options), prop);
158
- }
159
- else {
160
- const name = entity.constructor.name;
161
- throw new Error(`Invalid reference value provided for '${name}.${prop.name}' in ${name}.assign(): ${JSON.stringify(value)}`);
162
- }
163
- EntityAssigner.autoWireOneToOne(prop, entity);
164
- }
165
- static assignCollection(entity, collection, value, prop, em, options) {
166
- const invalid = [];
167
- const items = Utils.asArray(value).map((item, idx) => {
168
- // try to propagate missing owning side reference to the payload first
169
- const prop2 = prop.targetMeta?.properties[prop.mappedBy];
170
- if (Utils.isPlainObject(item) && prop2 && item[prop2.name] == null) {
171
- item = { ...item, [prop2.name]: Reference.wrapReference(entity, prop2) };
172
- }
173
- if (options.updateNestedEntities && options.updateByPrimaryKey && Utils.isPlainObject(item)) {
174
- const pk = Utils.extractPK(item, prop.targetMeta);
175
- if (pk && EntityAssigner.validateEM(em)) {
176
- const ref = em.getUnitOfWork().getById(prop.targetMeta.class, pk, options.schema);
177
- if (ref) {
178
- return EntityAssigner.assign(ref, item, options);
179
- }
180
- }
181
- return this.createCollectionItem(item, em, prop, invalid, options);
182
- }
183
- /* v8 ignore next */
184
- if (options.updateNestedEntities &&
185
- !options.updateByPrimaryKey &&
186
- collection[idx] &&
187
- helper(collection[idx])?.isInitialized()) {
188
- return EntityAssigner.assign(collection[idx], item, options);
60
+ if (propName in props && !prop.nullable && value == null) {
61
+ throw new Error(
62
+ `You must pass a non-${value} value to the property ${propName} of entity ${entity.constructor.name}.`,
63
+ );
64
+ }
65
+ // create collection instance if its missing so old items can be deleted with orphan removal
66
+ if ([ReferenceKind.MANY_TO_MANY, ReferenceKind.ONE_TO_MANY].includes(prop?.kind) && entity[prop.name] == null) {
67
+ entity[prop.name] = Collection.create(entity, prop.name, undefined, helper(entity).isInitialized());
68
+ }
69
+ if (prop && Utils.isCollection(entity[prop.name])) {
70
+ return EntityAssigner.assignCollection(entity, entity[prop.name], value, prop, options.em, options);
71
+ }
72
+ const customType = prop?.customType;
73
+ if (options.convertCustomTypes && customType && prop.kind === ReferenceKind.SCALAR && !Utils.isEntity(data)) {
74
+ value = customType.convertToJSValue(value, options.platform);
75
+ }
76
+ if ([ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(prop?.kind) && value != null) {
77
+ if (
78
+ options.updateNestedEntities &&
79
+ Object.hasOwn(entity, propName) &&
80
+ Utils.isEntity(entity[propName], true) &&
81
+ Utils.isPlainObject(value)
82
+ ) {
83
+ const unwrappedEntity = Reference.unwrapReference(entity[propName]);
84
+ const wrapped = helper(unwrappedEntity);
85
+ if (options.updateByPrimaryKey) {
86
+ const pk = Utils.extractPK(value, prop.targetMeta);
87
+ if (pk) {
88
+ const ref = options.em.getReference(prop.targetMeta.class, pk, options);
89
+ // if the PK differs, we want to change the target entity, not update it
90
+ const wrappedChild = helper(ref);
91
+ const sameTarget = wrappedChild.getSerializedPrimaryKey() === wrapped.getSerializedPrimaryKey();
92
+ if (wrappedChild.__managed && wrappedChild.isInitialized() && sameTarget) {
93
+ return EntityAssigner.assign(ref, value, options);
189
94
  }
190
- return this.createCollectionItem(item, em, prop, invalid, options);
191
- });
192
- if (invalid.length > 0) {
193
- const name = entity.constructor.name;
194
- throw ValidationError.invalidCollectionValues(name, prop.name, invalid);
95
+ }
96
+ return EntityAssigner.assignReference(entity, value, prop, options.em, options);
195
97
  }
196
- if (Array.isArray(value)) {
197
- collection.set(items);
198
- }
199
- else {
200
- // append to the collection in case of assigning a single value instead of array
201
- collection.add(items);
98
+ if (wrapped.__managed && wrap(unwrappedEntity).isInitialized()) {
99
+ return EntityAssigner.assign(unwrappedEntity, value, options);
202
100
  }
101
+ }
102
+ return EntityAssigner.assignReference(entity, value, prop, options.em, options);
203
103
  }
204
- static assignEmbeddable(entity, value, prop, em, options) {
205
- const propName = prop.embedded ? prop.embedded[1] : prop.name;
206
- if (value == null) {
207
- entity[propName] = value;
208
- return;
209
- }
210
- // if the value is not an array, we just push, otherwise we replace the array
211
- if (prop.array && (Array.isArray(value) || entity[propName] == null)) {
212
- entity[propName] = [];
213
- }
214
- if (prop.array) {
215
- return Utils.asArray(value).forEach(item => {
216
- const tmp = {};
217
- this.assignEmbeddable(tmp, item, { ...prop, array: false }, em, options);
218
- entity[propName].push(...Object.values(tmp));
219
- });
220
- }
221
- const create = () => EntityAssigner.validateEM(em) &&
222
- em.getEntityFactory().createEmbeddable(prop.targetMeta.class, value, {
223
- convertCustomTypes: options.convertCustomTypes,
224
- newEntity: options.mergeEmbeddedProperties ? !('propName' in entity) : true,
225
- });
226
- entity[propName] = (options.mergeEmbeddedProperties ? entity[propName] || create() : create());
227
- Object.keys(value).forEach(key => {
228
- EntityAssigner.assignProperty(entity[propName], key, prop.embeddedProps, value, options);
229
- });
230
- }
231
- static createCollectionItem(item, em, prop, invalid, options) {
232
- if (Utils.isEntity(item)) {
233
- return item;
234
- }
235
- if (Utils.isPrimaryKey(item) && EntityAssigner.validateEM(em)) {
236
- return em.getReference(prop.targetMeta.class, item, options);
237
- }
238
- if (Utils.isPlainObject(item) && options.merge && EntityAssigner.validateEM(em)) {
239
- return em.merge(prop.targetMeta.class, item, options);
240
- }
241
- if (Utils.isPlainObject(item) && EntityAssigner.validateEM(em)) {
242
- return em.create(prop.targetMeta.class, item, options);
243
- }
244
- invalid.push(item);
245
- return item;
104
+ if (prop.kind === ReferenceKind.SCALAR && SCALAR_TYPES.has(prop.runtimeType) && (prop.setter || !prop.getter)) {
105
+ validateProperty(prop, value, entity);
106
+ return (entity[prop.name] = value);
107
+ }
108
+ if (prop.kind === ReferenceKind.EMBEDDED && EntityAssigner.validateEM(options.em)) {
109
+ return EntityAssigner.assignEmbeddable(entity, value, prop, options.em, options);
110
+ }
111
+ if (options.mergeObjectProperties && Utils.isPlainObject(entity[propName]) && Utils.isPlainObject(value)) {
112
+ entity[propName] ??= {};
113
+ entity[propName] = Utils.merge({}, entity[propName], value);
114
+ } else if (!prop || prop.setter || !prop.getter) {
115
+ entity[propName] = value;
116
+ }
117
+ }
118
+ /**
119
+ * auto-wire 1:1 inverse side with owner as in no-sql drivers it can't be joined
120
+ * also makes sure the link is bidirectional when creating new entities from nested structures
121
+ * @internal
122
+ */
123
+ static autoWireOneToOne(prop, entity) {
124
+ const ref = entity[prop.name];
125
+ if (prop.kind !== ReferenceKind.ONE_TO_ONE || !Utils.isEntity(ref)) {
126
+ return;
127
+ }
128
+ const meta2 = helper(ref).__meta;
129
+ const prop2 = meta2.properties[prop.inversedBy || prop.mappedBy];
130
+ /* v8 ignore next */
131
+ if (prop2 && !ref[prop2.name]) {
132
+ if (Reference.isReference(ref)) {
133
+ ref.unwrap()[prop2.name] = Reference.wrapReference(entity, prop2);
134
+ } else {
135
+ ref[prop2.name] = Reference.wrapReference(entity, prop2);
136
+ }
137
+ }
138
+ }
139
+ static validateEM(em) {
140
+ if (!em) {
141
+ throw new Error(
142
+ `To use assign() on not managed entities, explicitly provide EM instance: wrap(entity).assign(data, { em: orm.em })`,
143
+ );
144
+ }
145
+ return true;
146
+ }
147
+ static assignReference(entity, value, prop, em, options) {
148
+ if (Utils.isEntity(value, true)) {
149
+ entity[prop.name] = Reference.wrapReference(value, prop);
150
+ } else if (Utils.isPrimaryKey(value, true) && EntityAssigner.validateEM(em)) {
151
+ entity[prop.name] = prop.mapToPk
152
+ ? value
153
+ : Reference.wrapReference(em.getReference(prop.targetMeta.class, value, options), prop);
154
+ } else if (Utils.isPlainObject(value) && options.merge && EntityAssigner.validateEM(em)) {
155
+ entity[prop.name] = Reference.wrapReference(em.merge(prop.targetMeta.class, value, options), prop);
156
+ } else if (Utils.isPlainObject(value) && EntityAssigner.validateEM(em)) {
157
+ entity[prop.name] = Reference.wrapReference(em.create(prop.targetMeta.class, value, options), prop);
158
+ } else {
159
+ const name = entity.constructor.name;
160
+ throw new Error(
161
+ `Invalid reference value provided for '${name}.${prop.name}' in ${name}.assign(): ${JSON.stringify(value)}`,
162
+ );
163
+ }
164
+ EntityAssigner.autoWireOneToOne(prop, entity);
165
+ }
166
+ static assignCollection(entity, collection, value, prop, em, options) {
167
+ const invalid = [];
168
+ const items = Utils.asArray(value).map((item, idx) => {
169
+ // try to propagate missing owning side reference to the payload first
170
+ const prop2 = prop.targetMeta?.properties[prop.mappedBy];
171
+ if (Utils.isPlainObject(item) && prop2 && item[prop2.name] == null) {
172
+ item = { ...item, [prop2.name]: Reference.wrapReference(entity, prop2) };
173
+ }
174
+ if (options.updateNestedEntities && options.updateByPrimaryKey && Utils.isPlainObject(item)) {
175
+ const pk = Utils.extractPK(item, prop.targetMeta);
176
+ if (pk && EntityAssigner.validateEM(em)) {
177
+ const ref = em.getUnitOfWork().getById(prop.targetMeta.class, pk, options.schema);
178
+ if (ref) {
179
+ return EntityAssigner.assign(ref, item, options);
180
+ }
181
+ }
182
+ return this.createCollectionItem(item, em, prop, invalid, options);
183
+ }
184
+ /* v8 ignore next */
185
+ if (
186
+ options.updateNestedEntities &&
187
+ !options.updateByPrimaryKey &&
188
+ collection[idx] &&
189
+ helper(collection[idx])?.isInitialized()
190
+ ) {
191
+ return EntityAssigner.assign(collection[idx], item, options);
192
+ }
193
+ return this.createCollectionItem(item, em, prop, invalid, options);
194
+ });
195
+ if (invalid.length > 0) {
196
+ const name = entity.constructor.name;
197
+ throw ValidationError.invalidCollectionValues(name, prop.name, invalid);
198
+ }
199
+ if (Array.isArray(value)) {
200
+ collection.set(items);
201
+ } else {
202
+ // append to the collection in case of assigning a single value instead of array
203
+ collection.add(items);
204
+ }
205
+ }
206
+ static assignEmbeddable(entity, value, prop, em, options) {
207
+ const propName = prop.embedded ? prop.embedded[1] : prop.name;
208
+ if (value == null) {
209
+ entity[propName] = value;
210
+ return;
211
+ }
212
+ // if the value is not an array, we just push, otherwise we replace the array
213
+ if (prop.array && (Array.isArray(value) || entity[propName] == null)) {
214
+ entity[propName] = [];
215
+ }
216
+ if (prop.array) {
217
+ return Utils.asArray(value).forEach(item => {
218
+ const tmp = {};
219
+ this.assignEmbeddable(tmp, item, { ...prop, array: false }, em, options);
220
+ entity[propName].push(...Object.values(tmp));
221
+ });
222
+ }
223
+ const create = () =>
224
+ EntityAssigner.validateEM(em) &&
225
+ em.getEntityFactory().createEmbeddable(prop.targetMeta.class, value, {
226
+ convertCustomTypes: options.convertCustomTypes,
227
+ newEntity: options.mergeEmbeddedProperties ? !('propName' in entity) : true,
228
+ });
229
+ entity[propName] = options.mergeEmbeddedProperties ? entity[propName] || create() : create();
230
+ Object.keys(value).forEach(key => {
231
+ EntityAssigner.assignProperty(entity[propName], key, prop.embeddedProps, value, options);
232
+ });
233
+ }
234
+ static createCollectionItem(item, em, prop, invalid, options) {
235
+ if (Utils.isEntity(item)) {
236
+ return item;
237
+ }
238
+ if (Utils.isPrimaryKey(item) && EntityAssigner.validateEM(em)) {
239
+ return em.getReference(prop.targetMeta.class, item, options);
240
+ }
241
+ if (Utils.isPlainObject(item) && options.merge && EntityAssigner.validateEM(em)) {
242
+ return em.merge(prop.targetMeta.class, item, options);
243
+ }
244
+ if (Utils.isPlainObject(item) && EntityAssigner.validateEM(em)) {
245
+ return em.create(prop.targetMeta.class, item, options);
246
246
  }
247
+ invalid.push(item);
248
+ return item;
249
+ }
247
250
  }
248
251
  export const assign = EntityAssigner.assign;
@@ -1,47 +1,75 @@
1
1
  import type { EntityData, EntityMetadata, EntityName, New, Primary } from '../typings.js';
2
2
  import type { EntityManager } from '../EntityManager.js';
3
3
  import type { EntityComparator } from '../utils/EntityComparator.js';
4
+ /** @internal Options for creating and merging entities via the EntityFactory. */
4
5
  export interface FactoryOptions {
5
- initialized?: boolean;
6
- newEntity?: boolean;
7
- /**
8
- * Property `onCreate` hooks are normally executed during `flush` operation.
9
- * With this option, they will be processed early inside `em.create()` method.
10
- */
11
- processOnCreateHooksEarly?: boolean;
12
- merge?: boolean;
13
- refresh?: boolean;
14
- convertCustomTypes?: boolean;
15
- recomputeSnapshot?: boolean;
16
- schema?: string;
17
- parentSchema?: string;
18
- normalizeAccessors?: boolean;
19
- /**
20
- * Property name to use for identity map lookup instead of the primary key.
21
- * This is useful for creating references by unique non-PK properties.
22
- */
23
- key?: string;
6
+ /** Whether the entity should be marked as initialized. */
7
+ initialized?: boolean;
8
+ /** Whether the entity is being newly created (uses constructor). */
9
+ newEntity?: boolean;
10
+ /**
11
+ * Property `onCreate` hooks are normally executed during `flush` operation.
12
+ * With this option, they will be processed early inside `em.create()` method.
13
+ */
14
+ processOnCreateHooksEarly?: boolean;
15
+ /** Whether to merge the entity into the identity map. */
16
+ merge?: boolean;
17
+ /** Whether to refresh an already loaded entity with new data. */
18
+ refresh?: boolean;
19
+ /** Whether to convert custom types during hydration. */
20
+ convertCustomTypes?: boolean;
21
+ /** Whether to recompute the entity snapshot after creation. */
22
+ recomputeSnapshot?: boolean;
23
+ /** Schema from FindOptions, overrides default schema. */
24
+ schema?: string;
25
+ /** Parent entity schema for nested entity creation. */
26
+ parentSchema?: string;
27
+ /** Whether to normalize accessors to the correct property names (normally handled via result mapper). */
28
+ normalizeAccessors?: boolean;
29
+ /**
30
+ * Property name to use for identity map lookup instead of the primary key.
31
+ * This is useful for creating references by unique non-PK properties.
32
+ */
33
+ key?: string;
24
34
  }
35
+ /** @internal Factory responsible for creating, merging, and hydrating entity instances. */
25
36
  export declare class EntityFactory {
26
- #private;
27
- constructor(em: EntityManager);
28
- create<T extends object, P extends string = string>(entityName: EntityName<T>, data: EntityData<T>, options?: FactoryOptions): New<T, P>;
29
- mergeData<T extends object>(meta: EntityMetadata<T>, entity: T, data: EntityData<T>, options?: FactoryOptions): void;
30
- createReference<T extends object>(entityName: EntityName<T>, id: Primary<T> | Primary<T>[] | Record<string, Primary<T>>, options?: Pick<FactoryOptions, 'merge' | 'convertCustomTypes' | 'schema' | 'key'>): T;
31
- createEmbeddable<T extends object>(entityName: EntityName<T>, data: EntityData<T>, options?: Pick<FactoryOptions, 'newEntity' | 'convertCustomTypes'>): T;
32
- getComparator(): EntityComparator;
33
- private createEntity;
34
- private assignDefaultValues;
35
- private hydrate;
36
- private findEntity;
37
- private processDiscriminatorColumn;
38
- /**
39
- * denormalize PK to value required by driver (e.g. ObjectId)
40
- */
41
- private denormalizePrimaryKey;
42
- /**
43
- * returns parameters for entity constructor, creating references from plain ids
44
- */
45
- private extractConstructorParams;
46
- private get unitOfWork();
37
+ #private;
38
+ constructor(em: EntityManager);
39
+ /** Creates a new entity instance or returns an existing one from the identity map, hydrating it with the provided data. */
40
+ create<T extends object, P extends string = string>(
41
+ entityName: EntityName<T>,
42
+ data: EntityData<T>,
43
+ options?: FactoryOptions,
44
+ ): New<T, P>;
45
+ /** Merges new data into an existing entity, preserving user-modified properties. */
46
+ mergeData<T extends object>(meta: EntityMetadata<T>, entity: T, data: EntityData<T>, options?: FactoryOptions): void;
47
+ /** Creates or retrieves an uninitialized entity reference by its primary key or alternate key. */
48
+ createReference<T extends object>(
49
+ entityName: EntityName<T>,
50
+ id: Primary<T> | Primary<T>[] | Record<string, Primary<T>>,
51
+ options?: Pick<FactoryOptions, 'merge' | 'convertCustomTypes' | 'schema' | 'key'>,
52
+ ): T;
53
+ /** Creates an embeddable entity instance from the provided data. */
54
+ createEmbeddable<T extends object>(
55
+ entityName: EntityName<T>,
56
+ data: EntityData<T>,
57
+ options?: Pick<FactoryOptions, 'newEntity' | 'convertCustomTypes'>,
58
+ ): T;
59
+ /** Returns the EntityComparator instance used for diffing entities. */
60
+ getComparator(): EntityComparator;
61
+ private createEntity;
62
+ private assignDefaultValues;
63
+ private hydrate;
64
+ private findEntity;
65
+ private processDiscriminatorColumn;
66
+ /**
67
+ * denormalize PK to value required by driver (e.g. ObjectId)
68
+ */
69
+ private denormalizePrimaryKey;
70
+ /**
71
+ * returns parameters for entity constructor, creating references from plain ids
72
+ */
73
+ private extractConstructorParams;
74
+ private get unitOfWork();
47
75
  }