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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (207) hide show
  1. package/EntityManager.d.ts +883 -579
  2. package/EntityManager.js +1897 -1865
  3. package/MikroORM.d.ts +103 -72
  4. package/MikroORM.js +178 -177
  5. package/README.md +128 -294
  6. package/cache/CacheAdapter.d.ts +38 -36
  7. package/cache/FileCacheAdapter.d.ts +30 -24
  8. package/cache/FileCacheAdapter.js +80 -78
  9. package/cache/GeneratedCacheAdapter.d.ts +19 -20
  10. package/cache/GeneratedCacheAdapter.js +31 -30
  11. package/cache/MemoryCacheAdapter.d.ts +19 -20
  12. package/cache/MemoryCacheAdapter.js +36 -36
  13. package/cache/NullCacheAdapter.d.ts +17 -16
  14. package/cache/NullCacheAdapter.js +25 -24
  15. package/connections/Connection.d.ts +99 -75
  16. package/connections/Connection.js +166 -160
  17. package/drivers/DatabaseDriver.d.ts +187 -69
  18. package/drivers/DatabaseDriver.js +451 -432
  19. package/drivers/IDatabaseDriver.d.ts +464 -281
  20. package/drivers/IDatabaseDriver.js +1 -0
  21. package/entity/BaseEntity.d.ts +121 -73
  22. package/entity/BaseEntity.js +44 -33
  23. package/entity/Collection.d.ts +216 -157
  24. package/entity/Collection.js +728 -707
  25. package/entity/EntityAssigner.d.ts +90 -76
  26. package/entity/EntityAssigner.js +232 -229
  27. package/entity/EntityFactory.d.ts +68 -40
  28. package/entity/EntityFactory.js +427 -366
  29. package/entity/EntityHelper.d.ts +34 -22
  30. package/entity/EntityHelper.js +280 -267
  31. package/entity/EntityIdentifier.d.ts +4 -4
  32. package/entity/EntityIdentifier.js +10 -10
  33. package/entity/EntityLoader.d.ts +105 -56
  34. package/entity/EntityLoader.js +754 -722
  35. package/entity/EntityRepository.d.ts +317 -200
  36. package/entity/EntityRepository.js +214 -212
  37. package/entity/PolymorphicRef.d.ts +5 -5
  38. package/entity/PolymorphicRef.js +10 -10
  39. package/entity/Reference.d.ts +130 -66
  40. package/entity/Reference.js +280 -260
  41. package/entity/WrappedEntity.d.ts +116 -53
  42. package/entity/WrappedEntity.js +169 -147
  43. package/entity/defineEntity.d.ts +1290 -614
  44. package/entity/defineEntity.js +521 -511
  45. package/entity/utils.d.ts +13 -3
  46. package/entity/utils.js +71 -73
  47. package/entity/validators.js +43 -43
  48. package/entity/wrap.js +8 -8
  49. package/enums.d.ts +275 -138
  50. package/enums.js +268 -137
  51. package/errors.d.ts +120 -72
  52. package/errors.js +356 -253
  53. package/events/EventManager.d.ts +27 -10
  54. package/events/EventManager.js +80 -73
  55. package/events/EventSubscriber.d.ts +33 -29
  56. package/events/TransactionEventBroadcaster.d.ts +16 -7
  57. package/events/TransactionEventBroadcaster.js +15 -13
  58. package/exceptions.d.ts +23 -40
  59. package/exceptions.js +35 -52
  60. package/hydration/Hydrator.d.ts +43 -16
  61. package/hydration/Hydrator.js +44 -42
  62. package/hydration/ObjectHydrator.d.ts +51 -17
  63. package/hydration/ObjectHydrator.js +480 -416
  64. package/index.d.ts +116 -2
  65. package/index.js +10 -1
  66. package/logging/DefaultLogger.d.ts +35 -30
  67. package/logging/DefaultLogger.js +87 -84
  68. package/logging/Logger.d.ts +45 -40
  69. package/logging/SimpleLogger.d.ts +13 -11
  70. package/logging/SimpleLogger.js +22 -22
  71. package/logging/colors.d.ts +6 -6
  72. package/logging/colors.js +11 -10
  73. package/logging/inspect.js +7 -7
  74. package/metadata/EntitySchema.d.ts +214 -108
  75. package/metadata/EntitySchema.js +398 -379
  76. package/metadata/MetadataDiscovery.d.ts +115 -111
  77. package/metadata/MetadataDiscovery.js +1948 -1857
  78. package/metadata/MetadataProvider.d.ts +25 -14
  79. package/metadata/MetadataProvider.js +83 -77
  80. package/metadata/MetadataStorage.d.ts +39 -19
  81. package/metadata/MetadataStorage.js +119 -106
  82. package/metadata/MetadataValidator.d.ts +39 -39
  83. package/metadata/MetadataValidator.js +381 -338
  84. package/metadata/discover-entities.d.ts +5 -2
  85. package/metadata/discover-entities.js +27 -27
  86. package/metadata/types.d.ts +615 -531
  87. package/naming-strategy/AbstractNamingStrategy.d.ts +55 -39
  88. package/naming-strategy/AbstractNamingStrategy.js +91 -85
  89. package/naming-strategy/EntityCaseNamingStrategy.d.ts +6 -6
  90. package/naming-strategy/EntityCaseNamingStrategy.js +22 -22
  91. package/naming-strategy/MongoNamingStrategy.d.ts +7 -6
  92. package/naming-strategy/MongoNamingStrategy.js +19 -18
  93. package/naming-strategy/NamingStrategy.d.ts +109 -99
  94. package/naming-strategy/UnderscoreNamingStrategy.d.ts +8 -7
  95. package/naming-strategy/UnderscoreNamingStrategy.js +22 -21
  96. package/not-supported.js +7 -4
  97. package/package.json +1 -1
  98. package/platforms/ExceptionConverter.d.ts +2 -1
  99. package/platforms/ExceptionConverter.js +5 -4
  100. package/platforms/Platform.d.ts +310 -236
  101. package/platforms/Platform.js +661 -573
  102. package/serialization/EntitySerializer.d.ts +49 -25
  103. package/serialization/EntitySerializer.js +224 -216
  104. package/serialization/EntityTransformer.d.ts +11 -5
  105. package/serialization/EntityTransformer.js +220 -216
  106. package/serialization/SerializationContext.d.ts +27 -18
  107. package/serialization/SerializationContext.js +105 -100
  108. package/types/ArrayType.d.ts +9 -8
  109. package/types/ArrayType.js +34 -33
  110. package/types/BigIntType.d.ts +17 -10
  111. package/types/BigIntType.js +37 -37
  112. package/types/BlobType.d.ts +4 -3
  113. package/types/BlobType.js +14 -13
  114. package/types/BooleanType.d.ts +5 -4
  115. package/types/BooleanType.js +13 -12
  116. package/types/CharacterType.d.ts +3 -2
  117. package/types/CharacterType.js +7 -6
  118. package/types/DateTimeType.d.ts +6 -5
  119. package/types/DateTimeType.js +16 -15
  120. package/types/DateType.d.ts +6 -5
  121. package/types/DateType.js +16 -15
  122. package/types/DecimalType.d.ts +7 -7
  123. package/types/DecimalType.js +26 -26
  124. package/types/DoubleType.d.ts +3 -3
  125. package/types/DoubleType.js +12 -12
  126. package/types/EnumArrayType.d.ts +6 -5
  127. package/types/EnumArrayType.js +25 -24
  128. package/types/EnumType.d.ts +4 -3
  129. package/types/EnumType.js +12 -11
  130. package/types/FloatType.d.ts +4 -3
  131. package/types/FloatType.js +10 -9
  132. package/types/IntegerType.d.ts +4 -3
  133. package/types/IntegerType.js +10 -9
  134. package/types/IntervalType.d.ts +5 -4
  135. package/types/IntervalType.js +13 -12
  136. package/types/JsonType.d.ts +9 -8
  137. package/types/JsonType.js +33 -32
  138. package/types/MediumIntType.d.ts +2 -1
  139. package/types/MediumIntType.js +4 -3
  140. package/types/SmallIntType.d.ts +4 -3
  141. package/types/SmallIntType.js +10 -9
  142. package/types/StringType.d.ts +5 -4
  143. package/types/StringType.js +13 -12
  144. package/types/TextType.d.ts +4 -3
  145. package/types/TextType.js +10 -9
  146. package/types/TimeType.d.ts +6 -5
  147. package/types/TimeType.js +18 -17
  148. package/types/TinyIntType.d.ts +4 -3
  149. package/types/TinyIntType.js +11 -10
  150. package/types/Type.d.ts +88 -73
  151. package/types/Type.js +85 -74
  152. package/types/Uint8ArrayType.d.ts +5 -4
  153. package/types/Uint8ArrayType.js +22 -21
  154. package/types/UnknownType.d.ts +5 -4
  155. package/types/UnknownType.js +13 -12
  156. package/types/UuidType.d.ts +6 -5
  157. package/types/UuidType.js +20 -19
  158. package/types/index.d.ts +77 -49
  159. package/types/index.js +64 -26
  160. package/typings.d.ts +1388 -729
  161. package/typings.js +255 -231
  162. package/unit-of-work/ChangeSet.d.ts +28 -24
  163. package/unit-of-work/ChangeSet.js +58 -54
  164. package/unit-of-work/ChangeSetComputer.d.ts +13 -11
  165. package/unit-of-work/ChangeSetComputer.js +180 -159
  166. package/unit-of-work/ChangeSetPersister.d.ts +64 -41
  167. package/unit-of-work/ChangeSetPersister.js +443 -418
  168. package/unit-of-work/CommitOrderCalculator.d.ts +40 -40
  169. package/unit-of-work/CommitOrderCalculator.js +89 -88
  170. package/unit-of-work/IdentityMap.d.ts +32 -25
  171. package/unit-of-work/IdentityMap.js +106 -99
  172. package/unit-of-work/UnitOfWork.d.ts +182 -127
  173. package/unit-of-work/UnitOfWork.js +1201 -1169
  174. package/utils/AbstractMigrator.d.ts +111 -91
  175. package/utils/AbstractMigrator.js +275 -275
  176. package/utils/AbstractSchemaGenerator.d.ts +43 -34
  177. package/utils/AbstractSchemaGenerator.js +121 -122
  178. package/utils/AsyncContext.d.ts +3 -3
  179. package/utils/AsyncContext.js +34 -35
  180. package/utils/Configuration.d.ts +853 -801
  181. package/utils/Configuration.js +360 -337
  182. package/utils/Cursor.d.ts +40 -22
  183. package/utils/Cursor.js +135 -127
  184. package/utils/DataloaderUtils.d.ts +58 -43
  185. package/utils/DataloaderUtils.js +203 -198
  186. package/utils/EntityComparator.d.ts +99 -80
  187. package/utils/EntityComparator.js +825 -727
  188. package/utils/NullHighlighter.d.ts +2 -1
  189. package/utils/NullHighlighter.js +4 -3
  190. package/utils/QueryHelper.d.ts +79 -51
  191. package/utils/QueryHelper.js +372 -361
  192. package/utils/RawQueryFragment.d.ts +54 -28
  193. package/utils/RawQueryFragment.js +110 -99
  194. package/utils/RequestContext.d.ts +33 -32
  195. package/utils/RequestContext.js +52 -53
  196. package/utils/TransactionContext.d.ts +17 -16
  197. package/utils/TransactionContext.js +28 -27
  198. package/utils/TransactionManager.d.ts +58 -58
  199. package/utils/TransactionManager.js +199 -197
  200. package/utils/Utils.d.ts +210 -145
  201. package/utils/Utils.js +820 -813
  202. package/utils/clone.js +104 -113
  203. package/utils/env-vars.js +90 -88
  204. package/utils/fs-utils.d.ts +15 -15
  205. package/utils/fs-utils.js +180 -181
  206. package/utils/upsert-utils.d.ts +20 -5
  207. package/utils/upsert-utils.js +114 -116
@@ -15,1180 +15,1212 @@ import { IdentityMap } from './IdentityMap.js';
15
15
  import { createAsyncContext } from '../utils/AsyncContext.js';
16
16
  // to deal with validation for flush inside flush hooks and `Promise.all`
17
17
  const insideFlush = createAsyncContext();
18
+ /** Implements the Unit of Work pattern: tracks entity changes, computes change sets, and flushes them to the database. */
18
19
  export class UnitOfWork {
19
- /** map of references to managed entities */
20
- #identityMap;
21
- #persistStack = new Set();
22
- #removeStack = new Set();
23
- #orphanRemoveStack = new Set();
24
- #changeSets = new Map();
25
- #collectionUpdates = new Set();
26
- #extraUpdates = new Set();
27
- #metadata;
28
- #platform;
29
- #eventManager;
30
- #comparator;
31
- #changeSetComputer;
32
- #changeSetPersister;
33
- #queuedActions = new Set();
34
- #loadedEntities = new Set();
35
- #flushQueue = [];
36
- #working = false;
37
- #em;
38
- constructor(em) {
39
- this.#em = em;
40
- this.#metadata = this.#em.getMetadata();
41
- this.#platform = this.#em.getPlatform();
42
- this.#identityMap = new IdentityMap(this.#platform.getDefaultSchemaName());
43
- this.#eventManager = this.#em.getEventManager();
44
- this.#comparator = this.#em.getComparator();
45
- this.#changeSetComputer = new ChangeSetComputer(this.#em, this.#collectionUpdates);
46
- this.#changeSetPersister = new ChangeSetPersister(this.#em);
47
- }
48
- merge(entity, visited) {
49
- const wrapped = helper(entity);
50
- wrapped.__em = this.#em;
51
- if (!wrapped.hasPrimaryKey()) {
52
- return;
53
- }
54
- // skip new entities that could be linked from already persisted entity
55
- // that is being re-fetched (but allow calling `merge(e)` explicitly for those)
56
- if (!wrapped.__managed && visited) {
57
- return;
58
- }
59
- this.#identityMap.store(entity);
60
- // if visited is available, we are cascading, and need to be careful when resetting the entity data
61
- // as there can be some entity with already changed state that is not yet flushed
62
- if (wrapped.__initialized && (!visited || !wrapped.__originalEntityData)) {
63
- wrapped.__originalEntityData = this.#comparator.prepareEntity(entity);
64
- }
65
- this.cascade(entity, Cascade.MERGE, visited ?? new Set());
66
- }
67
- /**
68
- * Entity data can wary in its shape, e.g. we might get a deep relation graph with joined strategy, but for diffing,
69
- * we need to normalize the shape, so relation values are only raw FKs. This method handles that.
70
- * @internal
71
- */
72
- normalizeEntityData(meta, data) {
73
- const forceUndefined = this.#em.config.get('forceUndefined');
74
- for (const key of Utils.keys(data)) {
75
- const prop = meta.properties[key];
76
- if (!prop) {
77
- continue;
78
- }
79
- if ([ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(prop.kind) &&
80
- Utils.isPlainObject(data[prop.name])) {
81
- // Skip polymorphic relations - they use PolymorphicRef wrapper
82
- if (!prop.polymorphic) {
83
- data[prop.name] = Utils.getPrimaryKeyValues(data[prop.name], prop.targetMeta, true);
84
- }
85
- }
86
- else if (prop.kind === ReferenceKind.EMBEDDED && !prop.object && Utils.isPlainObject(data[prop.name])) {
87
- for (const p of prop.targetMeta.props) {
88
- /* v8 ignore next */
89
- const prefix = prop.prefix === false ? '' : prop.prefix === true ? prop.name + '_' : prop.prefix;
90
- data[(prefix + p.name)] = data[prop.name][p.name];
91
- }
92
- data[prop.name] = Utils.getPrimaryKeyValues(data[prop.name], prop.targetMeta, true);
93
- }
94
- if (prop.hydrate === false && prop.customType?.ensureComparable(meta, prop)) {
95
- const converted = prop.customType.convertToJSValue(data[key], this.#platform, {
96
- key,
97
- mode: 'hydration',
98
- force: true,
99
- });
100
- data[key] = prop.customType.convertToDatabaseValue(converted, this.#platform, { key, mode: 'hydration' });
101
- }
102
- if (forceUndefined) {
103
- if (data[key] === null) {
104
- data[key] = undefined;
105
- }
106
- }
107
- }
108
- }
109
- /**
110
- * @internal
111
- */
112
- register(entity, data, options) {
113
- this.#identityMap.store(entity);
114
- EntityHelper.ensurePropagation(entity);
115
- if (options?.newEntity) {
116
- return entity;
117
- }
118
- const forceUndefined = this.#em.config.get('forceUndefined');
119
- const wrapped = helper(entity);
120
- if (options?.loaded && wrapped.__initialized && !wrapped.__onLoadFired) {
121
- this.#loadedEntities.add(entity);
122
- }
123
- wrapped.__em ??= this.#em;
124
- wrapped.__managed = true;
125
- if (data && (options?.refresh || !wrapped.__originalEntityData)) {
126
- this.normalizeEntityData(wrapped.__meta, data);
127
- for (const key of Utils.keys(data)) {
128
- const prop = wrapped.__meta.properties[key];
129
- if (prop) {
130
- wrapped.__loadedProperties.add(key);
131
- }
132
- }
133
- wrapped.__originalEntityData = data;
134
- }
135
- return entity;
136
- }
137
- /**
138
- * @internal
139
- */
140
- async dispatchOnLoadEvent() {
141
- for (const entity of this.#loadedEntities) {
142
- if (this.#eventManager.hasListeners(EventType.onLoad, entity.__meta)) {
143
- await this.#eventManager.dispatchEvent(EventType.onLoad, { entity, meta: entity.__meta, em: this.#em });
144
- helper(entity).__onLoadFired = true;
145
- }
146
- }
147
- this.#loadedEntities.clear();
148
- }
149
- /**
150
- * @internal
151
- */
152
- unmarkAsLoaded(entity) {
153
- this.#loadedEntities.delete(entity);
154
- }
155
- /**
156
- * Returns entity from the identity map. For composite keys, you need to pass an array of PKs in the same order as they are defined in `meta.primaryKeys`.
157
- */
158
- getById(entityName, id, schema, convertCustomTypes) {
159
- if (id == null || (Array.isArray(id) && id.length === 0)) {
160
- return undefined;
161
- }
162
- const meta = this.#metadata.find(entityName).root;
163
- let hash;
164
- if (meta.simplePK) {
165
- hash = '' + id;
166
- }
167
- else {
168
- let keys = Array.isArray(id) ? Utils.flatten(id) : [id];
169
- keys = meta.getPrimaryProps(true).map((p, i) => {
170
- if (!convertCustomTypes && p.customType) {
171
- return p.customType.convertToDatabaseValue(keys[i], this.#platform, {
172
- key: p.name,
173
- mode: 'hydration',
174
- });
175
- }
176
- return keys[i];
177
- });
178
- hash = Utils.getPrimaryKeyHash(keys);
179
- }
180
- schema ??= meta.schema ?? this.#em.config.getSchema();
181
- if (schema) {
182
- hash = `${schema}:${hash}`;
183
- }
184
- return this.#identityMap.getByHash(meta, hash);
185
- }
186
- /**
187
- * Returns entity from the identity map by an alternate key (non-PK property).
188
- * @param convertCustomTypes - If true, the value is in database format and will be converted to JS format for lookup.
189
- * If false (default), the value is assumed to be in JS format already.
190
- */
191
- getByKey(entityName, key, value, schema, convertCustomTypes) {
192
- const meta = this.#metadata.find(entityName).root;
193
- schema ??= meta.schema ?? this.#em.config.getSchema();
194
- const prop = meta.properties[key];
195
- // Convert from DB format to JS format if needed
196
- if (convertCustomTypes && prop?.customType) {
197
- value = prop.customType.convertToJSValue(value, this.#platform, { mode: 'hydration' });
198
- }
199
- const hash = this.#identityMap.getKeyHash(key, '' + value, schema);
200
- return this.#identityMap.getByHash(meta, hash);
201
- }
202
- /**
203
- * Stores an entity in the identity map under an alternate key (non-PK property).
204
- * Also sets the property value on the entity.
205
- * @param convertCustomTypes - If true, the value is in database format and will be converted to JS format.
206
- * If false (default), the value is assumed to be in JS format already.
207
- */
208
- storeByKey(entity, key, value, schema, convertCustomTypes) {
209
- const meta = entity.__meta.root;
210
- schema ??= meta.schema ?? this.#em.config.getSchema();
211
- const prop = meta.properties[key];
212
- // Convert from DB format to JS format if needed
213
- if (convertCustomTypes && prop?.customType) {
214
- value = prop.customType.convertToJSValue(value, this.#platform, { mode: 'hydration' });
215
- }
216
- // Set the property on the entity
217
- entity[key] = value;
218
- this.#identityMap.storeByKey(entity, key, '' + value, schema);
219
- }
220
- tryGetById(entityName, where, schema, strict = true) {
221
- const pk = Utils.extractPK(where, this.#metadata.find(entityName), strict);
222
- if (!pk) {
223
- return null;
224
- }
225
- return this.getById(entityName, pk, schema);
226
- }
227
- /**
228
- * Returns map of all managed entities.
229
- */
230
- getIdentityMap() {
231
- return this.#identityMap;
232
- }
233
- /**
234
- * Returns stored snapshot of entity state that is used for change set computation.
235
- */
236
- getOriginalEntityData(entity) {
237
- return helper(entity).__originalEntityData;
238
- }
239
- getPersistStack() {
240
- return this.#persistStack;
241
- }
242
- getRemoveStack() {
243
- return this.#removeStack;
244
- }
245
- getChangeSets() {
246
- return [...this.#changeSets.values()];
247
- }
248
- getCollectionUpdates() {
249
- return [...this.#collectionUpdates];
250
- }
251
- getExtraUpdates() {
252
- return this.#extraUpdates;
253
- }
254
- shouldAutoFlush(meta) {
255
- if (insideFlush.getStore()) {
256
- return false;
257
- }
258
- if (this.#queuedActions.has(meta.class) || this.#queuedActions.has(meta.root.class)) {
259
- return true;
260
- }
261
- if (meta.discriminatorMap && Object.values(meta.discriminatorMap).some(v => this.#queuedActions.has(v))) {
262
- return true;
263
- }
264
- return false;
265
- }
266
- clearActionsQueue() {
267
- this.#queuedActions.clear();
268
- }
269
- computeChangeSet(entity, type) {
270
- const wrapped = helper(entity);
271
- if (type === ChangeSetType.DELETE || type === ChangeSetType.DELETE_EARLY) {
272
- this.#changeSets.set(entity, new ChangeSet(entity, type, {}, wrapped.__meta));
273
- return;
274
- }
275
- const cs = this.#changeSetComputer.computeChangeSet(entity);
276
- if (!cs || this.checkUniqueProps(cs)) {
277
- return;
278
- }
279
- /* v8 ignore next */
280
- if (type) {
281
- cs.type = type;
282
- }
283
- this.initIdentifier(entity);
284
- this.#changeSets.set(entity, cs);
285
- this.#persistStack.delete(entity);
286
- wrapped.__originalEntityData = this.#comparator.prepareEntity(entity);
287
- }
288
- recomputeSingleChangeSet(entity) {
289
- const changeSet = this.#changeSets.get(entity);
290
- if (!changeSet) {
291
- return;
292
- }
293
- const cs = this.#changeSetComputer.computeChangeSet(entity);
294
- if (cs && !this.checkUniqueProps(cs)) {
295
- Object.assign(changeSet.payload, cs.payload);
296
- helper(entity).__originalEntityData = this.#comparator.prepareEntity(entity);
297
- }
298
- }
299
- persist(entity, visited, options = {}) {
300
- EntityHelper.ensurePropagation(entity);
301
- if (options.checkRemoveStack && this.#removeStack.has(entity)) {
302
- return;
303
- }
304
- const wrapped = helper(entity);
305
- this.#persistStack.add(entity);
306
- this.#queuedActions.add(wrapped.__meta.class);
307
- this.#removeStack.delete(entity);
308
- if (!wrapped.__managed && wrapped.hasPrimaryKey()) {
309
- this.#identityMap.store(entity);
310
- }
311
- if (options.cascade ?? true) {
312
- this.cascade(entity, Cascade.PERSIST, visited, options);
313
- }
314
- }
315
- remove(entity, visited, options = {}) {
316
- // allow removing not managed entities if they are not part of the persist stack
317
- if (helper(entity).__managed || !this.#persistStack.has(entity)) {
318
- this.#removeStack.add(entity);
319
- this.#queuedActions.add(helper(entity).__meta.class);
320
- }
321
- else {
322
- this.#persistStack.delete(entity);
323
- this.#identityMap.delete(entity);
324
- }
325
- // remove from referencing relations that are nullable
326
- for (const prop of helper(entity).__meta.bidirectionalRelations) {
327
- const inverseProp = prop.mappedBy || prop.inversedBy;
328
- const relation = Reference.unwrapReference(entity[prop.name]);
329
- const prop2 = prop.targetMeta.properties[inverseProp];
330
- if (prop.kind === ReferenceKind.ONE_TO_MANY && prop2.nullable && Utils.isCollection(relation)) {
331
- for (const item of relation.getItems(false)) {
332
- delete item[inverseProp];
333
- }
334
- continue;
335
- }
336
- const target = relation?.[inverseProp];
337
- if (relation && Utils.isCollection(target)) {
338
- target.removeWithoutPropagation(entity);
339
- }
340
- }
341
- if (options.cascade ?? true) {
342
- this.cascade(entity, Cascade.REMOVE, visited);
343
- }
344
- }
345
- async commit() {
346
- if (this.#working) {
347
- if (insideFlush.getStore()) {
348
- throw ValidationError.cannotCommit();
349
- }
350
- return new Promise((resolve, reject) => {
351
- this.#flushQueue.push(() => {
352
- return insideFlush.run(true, () => {
353
- return this.doCommit().then(resolve, reject);
354
- });
355
- });
356
- });
357
- }
358
- try {
359
- this.#working = true;
360
- await insideFlush.run(true, () => this.doCommit());
361
- while (this.#flushQueue.length) {
362
- await this.#flushQueue.shift()();
363
- }
364
- }
365
- finally {
366
- this.postCommitCleanup();
367
- this.#working = false;
368
- }
369
- }
370
- async doCommit() {
371
- const oldTx = this.#em.getTransactionContext();
372
- try {
373
- await this.#eventManager.dispatchEvent(EventType.beforeFlush, { em: this.#em, uow: this });
374
- this.computeChangeSets();
375
- for (const cs of this.#changeSets.values()) {
376
- cs.entity.__helper.__processing = true;
377
- }
378
- await this.#eventManager.dispatchEvent(EventType.onFlush, { em: this.#em, uow: this });
379
- this.filterCollectionUpdates();
380
- // nothing to do, do not start transaction
381
- if (this.#changeSets.size === 0 && this.#collectionUpdates.size === 0 && this.#extraUpdates.size === 0) {
382
- await this.#eventManager.dispatchEvent(EventType.afterFlush, { em: this.#em, uow: this });
383
- return;
384
- }
385
- const groups = this.getChangeSetGroups();
386
- const platform = this.#em.getPlatform();
387
- const runInTransaction = !this.#em.isInTransaction() && platform.supportsTransactions() && this.#em.config.get('implicitTransactions');
388
- if (runInTransaction) {
389
- const loggerContext = Utils.merge({ id: this.#em._id }, this.#em.getLoggerContext({ disableContextResolution: true }));
390
- await this.#em.getConnection('write').transactional(trx => this.persistToDatabase(groups, trx), {
391
- ctx: oldTx,
392
- eventBroadcaster: new TransactionEventBroadcaster(this.#em),
393
- loggerContext,
394
- });
395
- }
396
- else {
397
- await this.persistToDatabase(groups, this.#em.getTransactionContext());
398
- }
399
- this.resetTransaction(oldTx);
400
- for (const cs of this.#changeSets.values()) {
401
- cs.entity.__helper.__processing = false;
402
- }
403
- await this.#eventManager.dispatchEvent(EventType.afterFlush, { em: this.#em, uow: this });
404
- }
405
- finally {
406
- this.resetTransaction(oldTx);
407
- }
408
- }
409
- async lock(entity, options) {
410
- if (!this.getById(entity.constructor, helper(entity).__primaryKeys, helper(entity).__schema)) {
411
- throw ValidationError.entityNotManaged(entity);
412
- }
413
- const meta = this.#metadata.find(entity.constructor);
414
- if (options.lockMode === LockMode.OPTIMISTIC) {
415
- await this.lockOptimistic(entity, meta, options.lockVersion);
416
- }
417
- else if (options.lockMode != null) {
418
- await this.lockPessimistic(entity, options);
419
- }
420
- }
421
- clear() {
422
- this.#identityMap.clear();
423
- this.#loadedEntities.clear();
424
- this.postCommitCleanup();
425
- }
426
- unsetIdentity(entity) {
427
- this.#identityMap.delete(entity);
428
- const wrapped = helper(entity);
429
- const serializedPK = wrapped.getSerializedPrimaryKey();
430
- // remove references of this entity in all managed entities, otherwise flushing could reinsert the entity
431
- for (const { meta, prop } of wrapped.__meta.referencingProperties) {
432
- for (const referrer of this.#identityMap.getStore(meta).values()) {
433
- const rel = Reference.unwrapReference(referrer[prop.name]);
434
- if (Utils.isCollection(rel)) {
435
- rel.removeWithoutPropagation(entity);
436
- }
437
- else if (rel &&
438
- (prop.mapToPk
439
- ? helper(this.#em.getReference(prop.targetMeta.class, rel)).getSerializedPrimaryKey() === serializedPK
440
- : rel === entity)) {
441
- if (prop.formula) {
442
- delete referrer[prop.name];
443
- }
444
- else {
445
- delete helper(referrer).__data[prop.name];
446
- }
447
- }
448
- }
449
- }
450
- delete wrapped.__identifier;
451
- delete wrapped.__originalEntityData;
452
- wrapped.__managed = false;
453
- }
454
- computeChangeSets() {
455
- this.#changeSets.clear();
456
- const visited = new Set();
457
- for (const entity of this.#removeStack) {
458
- this.cascade(entity, Cascade.REMOVE, visited);
459
- }
460
- visited.clear();
461
- for (const entity of this.#identityMap) {
462
- if (!this.#removeStack.has(entity) && !this.#persistStack.has(entity) && !this.#orphanRemoveStack.has(entity)) {
463
- this.cascade(entity, Cascade.PERSIST, visited, { checkRemoveStack: true });
464
- }
465
- }
466
- for (const entity of this.#persistStack) {
467
- this.cascade(entity, Cascade.PERSIST, visited, { checkRemoveStack: true });
468
- }
469
- visited.clear();
470
- for (const entity of this.#persistStack) {
471
- this.findNewEntities(entity, visited);
472
- }
473
- for (const entity of this.#orphanRemoveStack) {
474
- if (!helper(entity).__processing) {
475
- this.#removeStack.add(entity);
476
- }
477
- }
478
- // Check insert stack if there are any entities matching something from delete stack. This can happen when recreating entities.
479
- const inserts = {};
480
- for (const cs of this.#changeSets.values()) {
481
- if (cs.type === ChangeSetType.CREATE) {
482
- inserts[cs.meta.uniqueName] ??= [];
483
- inserts[cs.meta.uniqueName].push(cs);
484
- }
485
- }
486
- for (const cs of this.#changeSets.values()) {
487
- if (cs.type === ChangeSetType.UPDATE) {
488
- this.findEarlyUpdates(cs, inserts[cs.meta.uniqueName]);
489
- }
490
- }
491
- for (const entity of this.#removeStack) {
492
- const wrapped = helper(entity);
493
- /* v8 ignore next */
494
- if (wrapped.__processing) {
495
- continue;
496
- }
497
- const deletePkHash = [wrapped.getSerializedPrimaryKey(), ...this.expandUniqueProps(entity)];
498
- let type = ChangeSetType.DELETE;
499
- for (const cs of inserts[wrapped.__meta.uniqueName] ?? []) {
500
- if (deletePkHash.some(hash => hash === cs.getSerializedPrimaryKey() || this.expandUniqueProps(cs.entity).find(child => hash === child))) {
501
- type = ChangeSetType.DELETE_EARLY;
502
- }
503
- }
504
- this.computeChangeSet(entity, type);
505
- }
506
- }
507
- scheduleExtraUpdate(changeSet, props) {
508
- if (props.length === 0) {
509
- return;
510
- }
511
- let conflicts = false;
512
- let type = ChangeSetType.UPDATE;
513
- if (!props.some(prop => prop.name in changeSet.payload)) {
514
- return;
515
- }
516
- for (const cs of this.#changeSets.values()) {
517
- for (const prop of props) {
518
- if (prop.name in cs.payload && cs.rootMeta === changeSet.rootMeta && cs.type === changeSet.type) {
519
- conflicts = true;
520
- if (changeSet.payload[prop.name] == null) {
521
- type = ChangeSetType.UPDATE_EARLY;
522
- }
523
- }
524
- }
525
- }
526
- if (!conflicts) {
527
- return;
528
- }
529
- this.#extraUpdates.add([
530
- changeSet.entity,
531
- props.map(p => p.name),
532
- props.map(p => changeSet.entity[p.name]),
533
- changeSet,
534
- type,
535
- ]);
536
- for (const p of props) {
537
- delete changeSet.entity[p.name];
538
- delete changeSet.payload[p.name];
539
- }
540
- }
541
- scheduleOrphanRemoval(entity, visited) {
542
- if (entity) {
543
- const wrapped = helper(entity);
544
- wrapped.__em = this.#em;
545
- this.#orphanRemoveStack.add(entity);
546
- this.#queuedActions.add(wrapped.__meta.class);
547
- this.cascade(entity, Cascade.SCHEDULE_ORPHAN_REMOVAL, visited);
548
- }
549
- }
550
- cancelOrphanRemoval(entity, visited) {
551
- this.#orphanRemoveStack.delete(entity);
552
- this.cascade(entity, Cascade.CANCEL_ORPHAN_REMOVAL, visited);
553
- }
554
- getOrphanRemoveStack() {
555
- return this.#orphanRemoveStack;
556
- }
557
- getChangeSetPersister() {
558
- return this.#changeSetPersister;
559
- }
560
- findNewEntities(entity, visited, idx = 0, processed = new Set()) {
561
- if (visited.has(entity)) {
562
- return;
563
- }
564
- visited.add(entity);
565
- processed.add(entity);
566
- const wrapped = helper(entity);
567
- if (wrapped.__processing || this.#removeStack.has(entity) || this.#orphanRemoveStack.has(entity)) {
568
- return;
569
- }
570
- // Set entityManager default schema
571
- wrapped.__schema ??= this.#em.schema;
572
- this.initIdentifier(entity);
573
- for (const prop of wrapped.__meta.relations) {
574
- const targets = Utils.unwrapProperty(entity, wrapped.__meta, prop);
575
- for (const [target] of targets) {
576
- const kind = Reference.unwrapReference(target);
577
- this.processReference(entity, prop, kind, visited, processed, idx);
578
- }
579
- }
580
- const changeSet = this.#changeSetComputer.computeChangeSet(entity);
581
- if (changeSet && !this.checkUniqueProps(changeSet)) {
582
- // For TPT child entities, create changesets for each table in hierarchy
583
- if (wrapped.__meta.inheritanceType === 'tpt' && wrapped.__meta.tptParent) {
584
- this.createTPTChangeSets(entity, changeSet);
585
- }
586
- else {
587
- this.#changeSets.set(entity, changeSet);
588
- }
589
- }
590
- }
591
- /**
592
- * For TPT inheritance, creates separate changesets for each table in the hierarchy.
593
- * Uses the same entity instance for all changesets - only the metadata and payload differ.
594
- */
595
- createTPTChangeSets(entity, originalChangeSet) {
596
- const meta = helper(entity).__meta;
597
- const isCreate = originalChangeSet.type === ChangeSetType.CREATE;
598
- let current = meta;
599
- let leafCs;
600
- const parentChangeSets = [];
601
- while (current) {
602
- const isRoot = !current.tptParent;
603
- const payload = {};
604
- for (const prop of current.ownProps) {
605
- if (prop.name in originalChangeSet.payload) {
606
- payload[prop.name] = originalChangeSet.payload[prop.name];
607
- }
608
- }
609
- // For CREATE on non-root tables, include the PK (EntityIdentifier for deferred resolution)
610
- if (isCreate && !isRoot) {
611
- const wrapped = helper(entity);
612
- const identifier = wrapped.__identifier;
613
- const identifiers = Array.isArray(identifier) ? identifier : [identifier];
614
- for (let i = 0; i < current.primaryKeys.length; i++) {
615
- const pk = current.primaryKeys[i];
616
- payload[pk] = identifiers[i] ?? originalChangeSet.payload[pk];
617
- }
618
- }
619
- if (!isCreate && Object.keys(payload).length === 0) {
620
- current = current.tptParent;
621
- continue;
622
- }
623
- const cs = new ChangeSet(entity, originalChangeSet.type, payload, current);
624
- if (current === meta) {
625
- cs.originalEntity = originalChangeSet.originalEntity;
626
- leafCs = cs;
627
- }
628
- else {
629
- parentChangeSets.push(cs);
630
- }
631
- current = current.tptParent;
632
- }
633
- // When only parent properties changed (UPDATE), leaf payload is empty—create a stub anchor
634
- if (!leafCs && parentChangeSets.length > 0) {
635
- leafCs = new ChangeSet(entity, originalChangeSet.type, {}, meta);
636
- leafCs.originalEntity = originalChangeSet.originalEntity;
637
- }
638
- // Store the leaf changeset in the main map (entity as key), with parent CSs attached
639
- if (leafCs) {
640
- if (parentChangeSets.length > 0) {
641
- leafCs.tptChangeSets = parentChangeSets;
642
- }
643
- this.#changeSets.set(entity, leafCs);
644
- }
645
- }
646
- /**
647
- * Returns `true` when the change set should be skipped as it will be empty after the extra update.
648
- */
649
- checkUniqueProps(changeSet) {
650
- if (changeSet.type !== ChangeSetType.UPDATE) {
651
- return false;
652
- }
653
- // when changing a unique nullable property (or a 1:1 relation), we can't do it in a single
654
- // query as it would cause unique constraint violations
655
- const uniqueProps = changeSet.meta.uniqueProps.filter(prop => {
656
- return prop.nullable || changeSet.type !== ChangeSetType.CREATE;
20
+ /** map of references to managed entities */
21
+ #identityMap;
22
+ #persistStack = new Set();
23
+ #removeStack = new Set();
24
+ #orphanRemoveStack = new Set();
25
+ #changeSets = new Map();
26
+ #collectionUpdates = new Set();
27
+ #extraUpdates = new Set();
28
+ #metadata;
29
+ #platform;
30
+ #eventManager;
31
+ #comparator;
32
+ #changeSetComputer;
33
+ #changeSetPersister;
34
+ #queuedActions = new Set();
35
+ #loadedEntities = new Set();
36
+ #flushQueue = [];
37
+ #working = false;
38
+ #em;
39
+ constructor(em) {
40
+ this.#em = em;
41
+ this.#metadata = this.#em.getMetadata();
42
+ this.#platform = this.#em.getPlatform();
43
+ this.#identityMap = new IdentityMap(this.#platform.getDefaultSchemaName());
44
+ this.#eventManager = this.#em.getEventManager();
45
+ this.#comparator = this.#em.getComparator();
46
+ this.#changeSetComputer = new ChangeSetComputer(this.#em, this.#collectionUpdates);
47
+ this.#changeSetPersister = new ChangeSetPersister(this.#em);
48
+ }
49
+ /** Merges an entity into the identity map, taking a snapshot of its current state. */
50
+ merge(entity, visited) {
51
+ const wrapped = helper(entity);
52
+ wrapped.__em = this.#em;
53
+ if (!wrapped.hasPrimaryKey()) {
54
+ return;
55
+ }
56
+ // skip new entities that could be linked from already persisted entity
57
+ // that is being re-fetched (but allow calling `merge(e)` explicitly for those)
58
+ if (!wrapped.__managed && visited) {
59
+ return;
60
+ }
61
+ this.#identityMap.store(entity);
62
+ // if visited is available, we are cascading, and need to be careful when resetting the entity data
63
+ // as there can be some entity with already changed state that is not yet flushed
64
+ if (wrapped.__initialized && (!visited || !wrapped.__originalEntityData)) {
65
+ wrapped.__originalEntityData = this.#comparator.prepareEntity(entity);
66
+ }
67
+ this.cascade(entity, Cascade.MERGE, visited ?? new Set());
68
+ }
69
+ /**
70
+ * Entity data can wary in its shape, e.g. we might get a deep relation graph with joined strategy, but for diffing,
71
+ * we need to normalize the shape, so relation values are only raw FKs. This method handles that.
72
+ * @internal
73
+ */
74
+ normalizeEntityData(meta, data) {
75
+ const forceUndefined = this.#em.config.get('forceUndefined');
76
+ for (const key of Utils.keys(data)) {
77
+ const prop = meta.properties[key];
78
+ if (!prop) {
79
+ continue;
80
+ }
81
+ if (
82
+ [ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(prop.kind) &&
83
+ Utils.isPlainObject(data[prop.name])
84
+ ) {
85
+ // Skip polymorphic relations - they use PolymorphicRef wrapper
86
+ if (!prop.polymorphic) {
87
+ data[prop.name] = Utils.getPrimaryKeyValues(data[prop.name], prop.targetMeta, true);
88
+ }
89
+ } else if (prop.kind === ReferenceKind.EMBEDDED && !prop.object && Utils.isPlainObject(data[prop.name])) {
90
+ for (const p of prop.targetMeta.props) {
91
+ /* v8 ignore next */
92
+ const prefix = prop.prefix === false ? '' : prop.prefix === true ? prop.name + '_' : prop.prefix;
93
+ data[prefix + p.name] = data[prop.name][p.name];
94
+ }
95
+ data[prop.name] = Utils.getPrimaryKeyValues(data[prop.name], prop.targetMeta, true);
96
+ }
97
+ if (prop.hydrate === false && prop.customType?.ensureComparable(meta, prop)) {
98
+ const converted = prop.customType.convertToJSValue(data[key], this.#platform, {
99
+ key,
100
+ mode: 'hydration',
101
+ force: true,
657
102
  });
658
- this.scheduleExtraUpdate(changeSet, uniqueProps);
659
- return changeSet.type === ChangeSetType.UPDATE && !Utils.hasObjectKeys(changeSet.payload);
660
- }
661
- expandUniqueProps(entity) {
662
- const wrapped = helper(entity);
663
- if (!wrapped.__meta.hasUniqueProps) {
664
- return [];
665
- }
666
- const simpleUniqueHashes = wrapped.__meta.uniqueProps
667
- .map(prop => {
668
- if (entity[prop.name] != null) {
669
- return prop.kind === ReferenceKind.SCALAR || prop.mapToPk
670
- ? entity[prop.name]
671
- : helper(entity[prop.name]).getSerializedPrimaryKey();
672
- }
673
- if (wrapped.__originalEntityData?.[prop.name] != null) {
674
- return Utils.getPrimaryKeyHash(Utils.asArray(wrapped.__originalEntityData[prop.name]));
675
- }
676
- return undefined;
677
- })
678
- .filter(i => i);
679
- const compoundUniqueHashes = wrapped.__meta.uniques
680
- .map(unique => {
681
- const props = Utils.asArray(unique.properties);
682
- if (props.every(prop => entity[prop] != null)) {
683
- return Utils.getPrimaryKeyHash(props.map(p => {
684
- const prop = wrapped.__meta.properties[p];
685
- return prop.kind === ReferenceKind.SCALAR || prop.mapToPk
686
- ? entity[prop.name]
687
- : helper(entity[prop.name]).getSerializedPrimaryKey();
688
- }));
689
- }
690
- return undefined;
691
- })
692
- .filter(i => i);
693
- return simpleUniqueHashes.concat(compoundUniqueHashes);
694
- }
695
- initIdentifier(entity) {
696
- const wrapped = entity && helper(entity);
697
- if (!wrapped || wrapped.__identifier || wrapped.hasPrimaryKey()) {
698
- return;
699
- }
700
- const pks = wrapped.__meta.getPrimaryProps();
701
- const idents = [];
702
- for (const pk of pks) {
703
- if (pk.kind === ReferenceKind.SCALAR) {
704
- idents.push(new EntityIdentifier(entity[pk.name]));
705
- }
706
- else if (entity[pk.name]) {
707
- this.initIdentifier(entity[pk.name]);
708
- idents.push(helper(entity[pk.name])?.__identifier);
709
- }
710
- }
711
- if (pks.length === 1) {
712
- wrapped.__identifier = idents[0];
713
- }
714
- else {
715
- wrapped.__identifier = idents;
716
- }
717
- }
718
- processReference(parent, prop, kind, visited, processed, idx) {
719
- const isToOne = prop.kind === ReferenceKind.MANY_TO_ONE || prop.kind === ReferenceKind.ONE_TO_ONE;
720
- if (isToOne && Utils.isEntity(kind)) {
721
- return this.processToOneReference(kind, visited, processed, idx);
722
- }
723
- if (Utils.isCollection(kind)) {
724
- kind
725
- .getItems(false)
726
- .filter(item => !item.__helper.__originalEntityData)
727
- .forEach(item => {
728
- // propagate schema from parent
729
- item.__helper.__schema ??= helper(parent).__schema;
730
- });
731
- if (prop.kind === ReferenceKind.MANY_TO_MANY && kind.isDirty()) {
732
- this.processToManyReference(kind, visited, processed, parent, prop);
733
- }
734
- }
735
- }
736
- processToOneReference(kind, visited, processed, idx) {
737
- if (!kind.__helper.__managed) {
738
- this.findNewEntities(kind, visited, idx, processed);
739
- }
740
- }
741
- processToManyReference(collection, visited, processed, parent, prop) {
742
- if (this.isCollectionSelfReferenced(collection, processed)) {
743
- this.#extraUpdates.add([parent, prop.name, collection, undefined, ChangeSetType.UPDATE]);
744
- const coll = new Collection(parent);
745
- coll.property = prop;
746
- parent[prop.name] = coll;
747
- return;
748
- }
749
- collection
750
- .getItems(false)
751
- .filter(item => !item.__helper.__originalEntityData)
752
- .forEach(item => this.findNewEntities(item, visited, 0, processed));
753
- }
754
- async runHooks(type, changeSet, sync = false) {
755
- const meta = changeSet.meta;
756
- if (!this.#eventManager.hasListeners(type, meta)) {
757
- return;
758
- }
759
- if (!sync) {
760
- await this.#eventManager.dispatchEvent(type, { entity: changeSet.entity, meta, em: this.#em, changeSet });
761
- return;
762
- }
763
- const copy = this.#comparator.prepareEntity(changeSet.entity);
764
- await this.#eventManager.dispatchEvent(type, { entity: changeSet.entity, meta, em: this.#em, changeSet });
765
- const current = this.#comparator.prepareEntity(changeSet.entity);
766
- const diff = this.#comparator.diffEntities(changeSet.meta.class, copy, current);
767
- Object.assign(changeSet.payload, diff);
768
- const wrapped = helper(changeSet.entity);
769
- if (wrapped.__identifier) {
770
- const idents = Utils.asArray(wrapped.__identifier);
771
- let i = 0;
772
- for (const pk of wrapped.__meta.primaryKeys) {
773
- if (diff[pk]) {
774
- idents[i].setValue(diff[pk]);
775
- }
776
- i++;
777
- }
778
- }
779
- }
780
- postCommitCleanup() {
781
- for (const cs of this.#changeSets.values()) {
782
- const wrapped = helper(cs.entity);
783
- wrapped.__processing = false;
784
- delete wrapped.__pk;
785
- }
786
- this.#persistStack.clear();
787
- this.#removeStack.clear();
788
- this.#orphanRemoveStack.clear();
789
- this.#changeSets.clear();
790
- this.#collectionUpdates.clear();
791
- this.#extraUpdates.clear();
792
- this.#queuedActions.clear();
793
- this.#working = false;
794
- }
795
- cascade(entity, type, visited = new Set(), options = {}) {
796
- if (visited.has(entity)) {
797
- return;
798
- }
799
- visited.add(entity);
800
- switch (type) {
801
- case Cascade.PERSIST:
802
- this.persist(entity, visited, options);
803
- break;
804
- case Cascade.MERGE:
805
- this.merge(entity, visited);
806
- break;
807
- case Cascade.REMOVE:
808
- this.remove(entity, visited, options);
809
- break;
810
- case Cascade.SCHEDULE_ORPHAN_REMOVAL:
811
- this.scheduleOrphanRemoval(entity, visited);
812
- break;
813
- case Cascade.CANCEL_ORPHAN_REMOVAL:
814
- this.cancelOrphanRemoval(entity, visited);
815
- break;
816
- }
817
- for (const prop of helper(entity).__meta.relations) {
818
- this.cascadeReference(entity, prop, type, visited, options);
819
- }
820
- }
821
- cascadeReference(entity, prop, type, visited, options) {
822
- this.fixMissingReference(entity, prop);
823
- if (!this.shouldCascade(prop, type)) {
824
- return;
825
- }
826
- const kind = Reference.unwrapReference(entity[prop.name]);
827
- if ([ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(prop.kind) && Utils.isEntity(kind)) {
828
- return this.cascade(kind, type, visited, options);
829
- }
830
- const collection = kind;
831
- if ([ReferenceKind.ONE_TO_MANY, ReferenceKind.MANY_TO_MANY].includes(prop.kind) && collection) {
832
- for (const item of collection.getItems(false)) {
833
- this.cascade(item, type, visited, options);
834
- }
835
- }
836
- }
837
- isCollectionSelfReferenced(collection, processed) {
838
- const filtered = collection.getItems(false).filter(item => !helper(item).__originalEntityData);
839
- return filtered.some(items => processed.has(items));
840
- }
841
- shouldCascade(prop, type) {
842
- if ([Cascade.REMOVE, Cascade.SCHEDULE_ORPHAN_REMOVAL, Cascade.CANCEL_ORPHAN_REMOVAL, Cascade.ALL].includes(type) &&
843
- prop.orphanRemoval) {
844
- return true;
845
- }
846
- // ignore user settings for merge, it is kept only for back compatibility, this should have never been configurable
847
- if (type === Cascade.MERGE) {
848
- return true;
849
- }
850
- return prop.cascade && (prop.cascade.includes(type) || prop.cascade.includes(Cascade.ALL));
851
- }
852
- async lockPessimistic(entity, options) {
853
- if (!this.#em.isInTransaction()) {
854
- throw ValidationError.transactionRequired();
855
- }
856
- await this.#em.getDriver().lockPessimistic(entity, { ctx: this.#em.getTransactionContext(), ...options });
857
- }
858
- async lockOptimistic(entity, meta, version) {
859
- if (!meta.versionProperty) {
860
- throw OptimisticLockError.notVersioned(meta);
861
- }
862
- if (typeof version === 'undefined') {
863
- return;
864
- }
103
+ data[key] = prop.customType.convertToDatabaseValue(converted, this.#platform, { key, mode: 'hydration' });
104
+ }
105
+ if (forceUndefined) {
106
+ if (data[key] === null) {
107
+ data[key] = undefined;
108
+ }
109
+ }
110
+ }
111
+ }
112
+ /**
113
+ * @internal
114
+ */
115
+ register(entity, data, options) {
116
+ this.#identityMap.store(entity);
117
+ EntityHelper.ensurePropagation(entity);
118
+ if (options?.newEntity) {
119
+ return entity;
120
+ }
121
+ const forceUndefined = this.#em.config.get('forceUndefined');
122
+ const wrapped = helper(entity);
123
+ if (options?.loaded && wrapped.__initialized && !wrapped.__onLoadFired) {
124
+ this.#loadedEntities.add(entity);
125
+ }
126
+ wrapped.__em ??= this.#em;
127
+ wrapped.__managed = true;
128
+ if (data && (options?.refresh || !wrapped.__originalEntityData)) {
129
+ this.normalizeEntityData(wrapped.__meta, data);
130
+ for (const key of Utils.keys(data)) {
131
+ const prop = wrapped.__meta.properties[key];
132
+ if (prop) {
133
+ wrapped.__loadedProperties.add(key);
134
+ }
135
+ }
136
+ wrapped.__originalEntityData = data;
137
+ }
138
+ return entity;
139
+ }
140
+ /**
141
+ * @internal
142
+ */
143
+ async dispatchOnLoadEvent() {
144
+ for (const entity of this.#loadedEntities) {
145
+ if (this.#eventManager.hasListeners(EventType.onLoad, entity.__meta)) {
146
+ await this.#eventManager.dispatchEvent(EventType.onLoad, { entity, meta: entity.__meta, em: this.#em });
147
+ helper(entity).__onLoadFired = true;
148
+ }
149
+ }
150
+ this.#loadedEntities.clear();
151
+ }
152
+ /**
153
+ * @internal
154
+ */
155
+ unmarkAsLoaded(entity) {
156
+ this.#loadedEntities.delete(entity);
157
+ }
158
+ /**
159
+ * Returns entity from the identity map. For composite keys, you need to pass an array of PKs in the same order as they are defined in `meta.primaryKeys`.
160
+ */
161
+ getById(entityName, id, schema, convertCustomTypes) {
162
+ if (id == null || (Array.isArray(id) && id.length === 0)) {
163
+ return undefined;
164
+ }
165
+ const meta = this.#metadata.find(entityName).root;
166
+ let hash;
167
+ if (meta.simplePK) {
168
+ hash = '' + id;
169
+ } else {
170
+ let keys = Array.isArray(id) ? Utils.flatten(id) : [id];
171
+ keys = meta.getPrimaryProps(true).map((p, i) => {
172
+ if (!convertCustomTypes && p.customType) {
173
+ return p.customType.convertToDatabaseValue(keys[i], this.#platform, {
174
+ key: p.name,
175
+ mode: 'hydration',
176
+ });
177
+ }
178
+ return keys[i];
179
+ });
180
+ hash = Utils.getPrimaryKeyHash(keys);
181
+ }
182
+ schema ??= meta.schema ?? this.#em.config.getSchema();
183
+ if (schema) {
184
+ hash = `${schema}:${hash}`;
185
+ }
186
+ return this.#identityMap.getByHash(meta, hash);
187
+ }
188
+ /**
189
+ * Returns entity from the identity map by an alternate key (non-PK property).
190
+ * @param convertCustomTypes - If true, the value is in database format and will be converted to JS format for lookup.
191
+ * If false (default), the value is assumed to be in JS format already.
192
+ */
193
+ getByKey(entityName, key, value, schema, convertCustomTypes) {
194
+ const meta = this.#metadata.find(entityName).root;
195
+ schema ??= meta.schema ?? this.#em.config.getSchema();
196
+ const prop = meta.properties[key];
197
+ // Convert from DB format to JS format if needed
198
+ if (convertCustomTypes && prop?.customType) {
199
+ value = prop.customType.convertToJSValue(value, this.#platform, { mode: 'hydration' });
200
+ }
201
+ const hash = this.#identityMap.getKeyHash(key, '' + value, schema);
202
+ return this.#identityMap.getByHash(meta, hash);
203
+ }
204
+ /**
205
+ * Stores an entity in the identity map under an alternate key (non-PK property).
206
+ * Also sets the property value on the entity.
207
+ * @param convertCustomTypes - If true, the value is in database format and will be converted to JS format.
208
+ * If false (default), the value is assumed to be in JS format already.
209
+ */
210
+ storeByKey(entity, key, value, schema, convertCustomTypes) {
211
+ const meta = entity.__meta.root;
212
+ schema ??= meta.schema ?? this.#em.config.getSchema();
213
+ const prop = meta.properties[key];
214
+ // Convert from DB format to JS format if needed
215
+ if (convertCustomTypes && prop?.customType) {
216
+ value = prop.customType.convertToJSValue(value, this.#platform, { mode: 'hydration' });
217
+ }
218
+ // Set the property on the entity
219
+ entity[key] = value;
220
+ this.#identityMap.storeByKey(entity, key, '' + value, schema);
221
+ }
222
+ /** Attempts to extract a primary key from the where condition and look up the entity in the identity map. */
223
+ tryGetById(entityName, where, schema, strict = true) {
224
+ const pk = Utils.extractPK(where, this.#metadata.find(entityName), strict);
225
+ if (!pk) {
226
+ return null;
227
+ }
228
+ return this.getById(entityName, pk, schema);
229
+ }
230
+ /**
231
+ * Returns map of all managed entities.
232
+ */
233
+ getIdentityMap() {
234
+ return this.#identityMap;
235
+ }
236
+ /**
237
+ * Returns stored snapshot of entity state that is used for change set computation.
238
+ */
239
+ getOriginalEntityData(entity) {
240
+ return helper(entity).__originalEntityData;
241
+ }
242
+ /** Returns the set of entities scheduled for persistence. */
243
+ getPersistStack() {
244
+ return this.#persistStack;
245
+ }
246
+ /** Returns the set of entities scheduled for removal. */
247
+ getRemoveStack() {
248
+ return this.#removeStack;
249
+ }
250
+ /** Returns all computed change sets for the current flush. */
251
+ getChangeSets() {
252
+ return [...this.#changeSets.values()];
253
+ }
254
+ /** Returns all M:N collections that need synchronization. */
255
+ getCollectionUpdates() {
256
+ return [...this.#collectionUpdates];
257
+ }
258
+ /** Returns extra updates needed for relations that could not be resolved in the initial pass. */
259
+ getExtraUpdates() {
260
+ return this.#extraUpdates;
261
+ }
262
+ /** Checks whether an auto-flush is needed before querying the given entity type. */
263
+ shouldAutoFlush(meta) {
264
+ if (insideFlush.getStore()) {
265
+ return false;
266
+ }
267
+ if (this.#queuedActions.has(meta.class) || this.#queuedActions.has(meta.root.class)) {
268
+ return true;
269
+ }
270
+ if (meta.discriminatorMap && Object.values(meta.discriminatorMap).some(v => this.#queuedActions.has(v))) {
271
+ return true;
272
+ }
273
+ return false;
274
+ }
275
+ /** Clears the queue of entity types that triggered auto-flush detection. */
276
+ clearActionsQueue() {
277
+ this.#queuedActions.clear();
278
+ }
279
+ /** Computes and registers a change set for the given entity. */
280
+ computeChangeSet(entity, type) {
281
+ const wrapped = helper(entity);
282
+ if (type === ChangeSetType.DELETE || type === ChangeSetType.DELETE_EARLY) {
283
+ this.#changeSets.set(entity, new ChangeSet(entity, type, {}, wrapped.__meta));
284
+ return;
285
+ }
286
+ const cs = this.#changeSetComputer.computeChangeSet(entity);
287
+ if (!cs || this.checkUniqueProps(cs)) {
288
+ return;
289
+ }
290
+ /* v8 ignore next */
291
+ if (type) {
292
+ cs.type = type;
293
+ }
294
+ this.initIdentifier(entity);
295
+ this.#changeSets.set(entity, cs);
296
+ this.#persistStack.delete(entity);
297
+ wrapped.__originalEntityData = this.#comparator.prepareEntity(entity);
298
+ }
299
+ /** Recomputes and merges the change set for an already-tracked entity. */
300
+ recomputeSingleChangeSet(entity) {
301
+ const changeSet = this.#changeSets.get(entity);
302
+ if (!changeSet) {
303
+ return;
304
+ }
305
+ const cs = this.#changeSetComputer.computeChangeSet(entity);
306
+ if (cs && !this.checkUniqueProps(cs)) {
307
+ Object.assign(changeSet.payload, cs.payload);
308
+ helper(entity).__originalEntityData = this.#comparator.prepareEntity(entity);
309
+ }
310
+ }
311
+ /** Marks an entity for persistence, cascading to related entities. */
312
+ persist(entity, visited, options = {}) {
313
+ EntityHelper.ensurePropagation(entity);
314
+ if (options.checkRemoveStack && this.#removeStack.has(entity)) {
315
+ return;
316
+ }
317
+ const wrapped = helper(entity);
318
+ this.#persistStack.add(entity);
319
+ this.#queuedActions.add(wrapped.__meta.class);
320
+ this.#removeStack.delete(entity);
321
+ if (!wrapped.__managed && wrapped.hasPrimaryKey()) {
322
+ this.#identityMap.store(entity);
323
+ }
324
+ if (options.cascade ?? true) {
325
+ this.cascade(entity, Cascade.PERSIST, visited, options);
326
+ }
327
+ }
328
+ /** Marks an entity for removal, cascading to related entities. */
329
+ remove(entity, visited, options = {}) {
330
+ // allow removing not managed entities if they are not part of the persist stack
331
+ if (helper(entity).__managed || !this.#persistStack.has(entity)) {
332
+ this.#removeStack.add(entity);
333
+ this.#queuedActions.add(helper(entity).__meta.class);
334
+ } else {
335
+ this.#persistStack.delete(entity);
336
+ this.#identityMap.delete(entity);
337
+ }
338
+ // remove from referencing relations that are nullable
339
+ for (const prop of helper(entity).__meta.bidirectionalRelations) {
340
+ const inverseProp = prop.mappedBy || prop.inversedBy;
341
+ const relation = Reference.unwrapReference(entity[prop.name]);
342
+ const prop2 = prop.targetMeta.properties[inverseProp];
343
+ if (prop.kind === ReferenceKind.ONE_TO_MANY && prop2.nullable && Utils.isCollection(relation)) {
344
+ for (const item of relation.getItems(false)) {
345
+ delete item[inverseProp];
346
+ }
347
+ continue;
348
+ }
349
+ const target = relation?.[inverseProp];
350
+ if (relation && Utils.isCollection(target)) {
351
+ target.removeWithoutPropagation(entity);
352
+ }
353
+ }
354
+ if (options.cascade ?? true) {
355
+ this.cascade(entity, Cascade.REMOVE, visited);
356
+ }
357
+ }
358
+ /** Flushes all pending changes to the database within a transaction. */
359
+ async commit() {
360
+ if (this.#working) {
361
+ if (insideFlush.getStore()) {
362
+ throw ValidationError.cannotCommit();
363
+ }
364
+ return new Promise((resolve, reject) => {
365
+ this.#flushQueue.push(() => {
366
+ return insideFlush.run(true, () => {
367
+ return this.doCommit().then(resolve, reject);
368
+ });
369
+ });
370
+ });
371
+ }
372
+ try {
373
+ this.#working = true;
374
+ await insideFlush.run(true, () => this.doCommit());
375
+ while (this.#flushQueue.length) {
376
+ await this.#flushQueue.shift()();
377
+ }
378
+ } finally {
379
+ this.postCommitCleanup();
380
+ this.#working = false;
381
+ }
382
+ }
383
+ async doCommit() {
384
+ const oldTx = this.#em.getTransactionContext();
385
+ try {
386
+ await this.#eventManager.dispatchEvent(EventType.beforeFlush, { em: this.#em, uow: this });
387
+ this.computeChangeSets();
388
+ for (const cs of this.#changeSets.values()) {
389
+ cs.entity.__helper.__processing = true;
390
+ }
391
+ await this.#eventManager.dispatchEvent(EventType.onFlush, { em: this.#em, uow: this });
392
+ this.filterCollectionUpdates();
393
+ // nothing to do, do not start transaction
394
+ if (this.#changeSets.size === 0 && this.#collectionUpdates.size === 0 && this.#extraUpdates.size === 0) {
395
+ await this.#eventManager.dispatchEvent(EventType.afterFlush, { em: this.#em, uow: this });
396
+ return;
397
+ }
398
+ const groups = this.getChangeSetGroups();
399
+ const platform = this.#em.getPlatform();
400
+ const runInTransaction =
401
+ !this.#em.isInTransaction() && platform.supportsTransactions() && this.#em.config.get('implicitTransactions');
402
+ if (runInTransaction) {
403
+ const loggerContext = Utils.merge(
404
+ { id: this.#em._id },
405
+ this.#em.getLoggerContext({ disableContextResolution: true }),
406
+ );
407
+ await this.#em.getConnection('write').transactional(trx => this.persistToDatabase(groups, trx), {
408
+ ctx: oldTx,
409
+ eventBroadcaster: new TransactionEventBroadcaster(this.#em),
410
+ loggerContext,
411
+ });
412
+ } else {
413
+ await this.persistToDatabase(groups, this.#em.getTransactionContext());
414
+ }
415
+ this.resetTransaction(oldTx);
416
+ for (const cs of this.#changeSets.values()) {
417
+ cs.entity.__helper.__processing = false;
418
+ }
419
+ await this.#eventManager.dispatchEvent(EventType.afterFlush, { em: this.#em, uow: this });
420
+ } finally {
421
+ this.resetTransaction(oldTx);
422
+ }
423
+ }
424
+ async lock(entity, options) {
425
+ if (!this.getById(entity.constructor, helper(entity).__primaryKeys, helper(entity).__schema)) {
426
+ throw ValidationError.entityNotManaged(entity);
427
+ }
428
+ const meta = this.#metadata.find(entity.constructor);
429
+ if (options.lockMode === LockMode.OPTIMISTIC) {
430
+ await this.lockOptimistic(entity, meta, options.lockVersion);
431
+ } else if (options.lockMode != null) {
432
+ await this.lockPessimistic(entity, options);
433
+ }
434
+ }
435
+ clear() {
436
+ this.#identityMap.clear();
437
+ this.#loadedEntities.clear();
438
+ this.postCommitCleanup();
439
+ }
440
+ unsetIdentity(entity) {
441
+ this.#identityMap.delete(entity);
442
+ const wrapped = helper(entity);
443
+ const serializedPK = wrapped.getSerializedPrimaryKey();
444
+ // remove references of this entity in all managed entities, otherwise flushing could reinsert the entity
445
+ for (const { meta, prop } of wrapped.__meta.referencingProperties) {
446
+ for (const referrer of this.#identityMap.getStore(meta).values()) {
447
+ const rel = Reference.unwrapReference(referrer[prop.name]);
448
+ if (Utils.isCollection(rel)) {
449
+ rel.removeWithoutPropagation(entity);
450
+ } else if (
451
+ rel &&
452
+ (prop.mapToPk
453
+ ? helper(this.#em.getReference(prop.targetMeta.class, rel)).getSerializedPrimaryKey() === serializedPK
454
+ : rel === entity)
455
+ ) {
456
+ if (prop.formula) {
457
+ delete referrer[prop.name];
458
+ } else {
459
+ delete helper(referrer).__data[prop.name];
460
+ }
461
+ }
462
+ }
463
+ }
464
+ delete wrapped.__identifier;
465
+ delete wrapped.__originalEntityData;
466
+ wrapped.__managed = false;
467
+ }
468
+ computeChangeSets() {
469
+ this.#changeSets.clear();
470
+ const visited = new Set();
471
+ for (const entity of this.#removeStack) {
472
+ this.cascade(entity, Cascade.REMOVE, visited);
473
+ }
474
+ visited.clear();
475
+ for (const entity of this.#identityMap) {
476
+ if (!this.#removeStack.has(entity) && !this.#persistStack.has(entity) && !this.#orphanRemoveStack.has(entity)) {
477
+ this.cascade(entity, Cascade.PERSIST, visited, { checkRemoveStack: true });
478
+ }
479
+ }
480
+ for (const entity of this.#persistStack) {
481
+ this.cascade(entity, Cascade.PERSIST, visited, { checkRemoveStack: true });
482
+ }
483
+ visited.clear();
484
+ for (const entity of this.#persistStack) {
485
+ this.findNewEntities(entity, visited);
486
+ }
487
+ for (const entity of this.#orphanRemoveStack) {
488
+ if (!helper(entity).__processing) {
489
+ this.#removeStack.add(entity);
490
+ }
491
+ }
492
+ // Check insert stack if there are any entities matching something from delete stack. This can happen when recreating entities.
493
+ const inserts = {};
494
+ for (const cs of this.#changeSets.values()) {
495
+ if (cs.type === ChangeSetType.CREATE) {
496
+ inserts[cs.meta.uniqueName] ??= [];
497
+ inserts[cs.meta.uniqueName].push(cs);
498
+ }
499
+ }
500
+ for (const cs of this.#changeSets.values()) {
501
+ if (cs.type === ChangeSetType.UPDATE) {
502
+ this.findEarlyUpdates(cs, inserts[cs.meta.uniqueName]);
503
+ }
504
+ }
505
+ for (const entity of this.#removeStack) {
506
+ const wrapped = helper(entity);
507
+ /* v8 ignore next */
508
+ if (wrapped.__processing) {
509
+ continue;
510
+ }
511
+ const deletePkHash = [wrapped.getSerializedPrimaryKey(), ...this.expandUniqueProps(entity)];
512
+ let type = ChangeSetType.DELETE;
513
+ for (const cs of inserts[wrapped.__meta.uniqueName] ?? []) {
514
+ if (
515
+ deletePkHash.some(
516
+ hash =>
517
+ hash === cs.getSerializedPrimaryKey() || this.expandUniqueProps(cs.entity).find(child => hash === child),
518
+ )
519
+ ) {
520
+ type = ChangeSetType.DELETE_EARLY;
521
+ }
522
+ }
523
+ this.computeChangeSet(entity, type);
524
+ }
525
+ }
526
+ scheduleExtraUpdate(changeSet, props) {
527
+ if (props.length === 0) {
528
+ return;
529
+ }
530
+ let conflicts = false;
531
+ let type = ChangeSetType.UPDATE;
532
+ if (!props.some(prop => prop.name in changeSet.payload)) {
533
+ return;
534
+ }
535
+ for (const cs of this.#changeSets.values()) {
536
+ for (const prop of props) {
537
+ if (prop.name in cs.payload && cs.rootMeta === changeSet.rootMeta && cs.type === changeSet.type) {
538
+ conflicts = true;
539
+ if (changeSet.payload[prop.name] == null) {
540
+ type = ChangeSetType.UPDATE_EARLY;
541
+ }
542
+ }
543
+ }
544
+ }
545
+ if (!conflicts) {
546
+ return;
547
+ }
548
+ this.#extraUpdates.add([
549
+ changeSet.entity,
550
+ props.map(p => p.name),
551
+ props.map(p => changeSet.entity[p.name]),
552
+ changeSet,
553
+ type,
554
+ ]);
555
+ for (const p of props) {
556
+ delete changeSet.entity[p.name];
557
+ delete changeSet.payload[p.name];
558
+ }
559
+ }
560
+ scheduleOrphanRemoval(entity, visited) {
561
+ if (entity) {
562
+ const wrapped = helper(entity);
563
+ wrapped.__em = this.#em;
564
+ this.#orphanRemoveStack.add(entity);
565
+ this.#queuedActions.add(wrapped.__meta.class);
566
+ this.cascade(entity, Cascade.SCHEDULE_ORPHAN_REMOVAL, visited);
567
+ }
568
+ }
569
+ cancelOrphanRemoval(entity, visited) {
570
+ this.#orphanRemoveStack.delete(entity);
571
+ this.cascade(entity, Cascade.CANCEL_ORPHAN_REMOVAL, visited);
572
+ }
573
+ getOrphanRemoveStack() {
574
+ return this.#orphanRemoveStack;
575
+ }
576
+ getChangeSetPersister() {
577
+ return this.#changeSetPersister;
578
+ }
579
+ findNewEntities(entity, visited, idx = 0, processed = new Set()) {
580
+ if (visited.has(entity)) {
581
+ return;
582
+ }
583
+ visited.add(entity);
584
+ processed.add(entity);
585
+ const wrapped = helper(entity);
586
+ if (wrapped.__processing || this.#removeStack.has(entity) || this.#orphanRemoveStack.has(entity)) {
587
+ return;
588
+ }
589
+ // Set entityManager default schema
590
+ wrapped.__schema ??= this.#em.schema;
591
+ this.initIdentifier(entity);
592
+ for (const prop of wrapped.__meta.relations) {
593
+ const targets = Utils.unwrapProperty(entity, wrapped.__meta, prop);
594
+ for (const [target] of targets) {
595
+ const kind = Reference.unwrapReference(target);
596
+ this.processReference(entity, prop, kind, visited, processed, idx);
597
+ }
598
+ }
599
+ const changeSet = this.#changeSetComputer.computeChangeSet(entity);
600
+ if (changeSet && !this.checkUniqueProps(changeSet)) {
601
+ // For TPT child entities, create changesets for each table in hierarchy
602
+ if (wrapped.__meta.inheritanceType === 'tpt' && wrapped.__meta.tptParent) {
603
+ this.createTPTChangeSets(entity, changeSet);
604
+ } else {
605
+ this.#changeSets.set(entity, changeSet);
606
+ }
607
+ }
608
+ }
609
+ /**
610
+ * For TPT inheritance, creates separate changesets for each table in the hierarchy.
611
+ * Uses the same entity instance for all changesets - only the metadata and payload differ.
612
+ */
613
+ createTPTChangeSets(entity, originalChangeSet) {
614
+ const meta = helper(entity).__meta;
615
+ const isCreate = originalChangeSet.type === ChangeSetType.CREATE;
616
+ let current = meta;
617
+ let leafCs;
618
+ const parentChangeSets = [];
619
+ while (current) {
620
+ const isRoot = !current.tptParent;
621
+ const payload = {};
622
+ for (const prop of current.ownProps) {
623
+ if (prop.name in originalChangeSet.payload) {
624
+ payload[prop.name] = originalChangeSet.payload[prop.name];
625
+ }
626
+ }
627
+ // For CREATE on non-root tables, include the PK (EntityIdentifier for deferred resolution)
628
+ if (isCreate && !isRoot) {
865
629
  const wrapped = helper(entity);
866
- if (!wrapped.__initialized) {
867
- await wrapped.init();
868
- }
869
- const previousVersion = entity[meta.versionProperty];
870
- if (previousVersion !== version) {
871
- throw OptimisticLockError.lockFailedVersionMismatch(entity, version, previousVersion);
872
- }
873
- }
874
- fixMissingReference(entity, prop) {
875
- const reference = entity[prop.name];
876
- const target = Reference.unwrapReference(reference);
877
- if ([ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(prop.kind) && target && !prop.mapToPk) {
878
- if (!Utils.isEntity(target)) {
879
- entity[prop.name] = this.#em.getReference(prop.targetMeta.class, target, {
880
- wrapped: !!prop.ref,
881
- });
882
- }
883
- else if (!helper(target).__initialized && !helper(target).__em) {
884
- const pk = helper(target).getPrimaryKey();
885
- entity[prop.name] = this.#em.getReference(prop.targetMeta.class, pk, {
886
- wrapped: !!prop.ref,
887
- });
888
- }
889
- }
890
- // perf: set the `Collection._property` to skip the getter, as it can be slow when there are a lot of relations
891
- if (Utils.isCollection(target)) {
892
- target.property = prop;
893
- }
894
- const isCollection = [ReferenceKind.ONE_TO_MANY, ReferenceKind.MANY_TO_MANY].includes(prop.kind);
895
- if (isCollection && Array.isArray(target)) {
896
- const collection = new Collection(entity);
897
- collection.property = prop;
898
- entity[prop.name] = collection;
899
- collection.set(target);
900
- }
901
- }
902
- async persistToDatabase(groups, ctx) {
903
- if (ctx) {
904
- this.#em.setTransactionContext(ctx);
905
- }
906
- const commitOrder = this.getCommitOrder();
907
- const commitOrderReversed = [...commitOrder].reverse();
908
- // early delete - when we recreate entity in the same UoW, we need to issue those delete queries before inserts
909
- for (const meta of commitOrderReversed) {
910
- await this.commitDeleteChangeSets(groups[ChangeSetType.DELETE_EARLY].get(meta) ?? [], ctx);
911
- }
912
- // early update - when we recreate entity in the same UoW, we need to issue those delete queries before inserts
913
- for (const meta of commitOrder) {
914
- await this.commitUpdateChangeSets(groups[ChangeSetType.UPDATE_EARLY].get(meta) ?? [], ctx);
915
- }
916
- // extra updates
917
- await this.commitExtraUpdates(ChangeSetType.UPDATE_EARLY, ctx);
918
- // create
919
- for (const meta of commitOrder) {
920
- await this.commitCreateChangeSets(groups[ChangeSetType.CREATE].get(meta) ?? [], ctx);
921
- }
922
- // update
923
- for (const meta of commitOrder) {
924
- await this.commitUpdateChangeSets(groups[ChangeSetType.UPDATE].get(meta) ?? [], ctx);
925
- }
926
- // extra updates
927
- await this.commitExtraUpdates(ChangeSetType.UPDATE, ctx);
928
- // collection updates
929
- await this.commitCollectionUpdates(ctx);
930
- // delete - entity deletions need to be in reverse commit order
931
- for (const meta of commitOrderReversed) {
932
- await this.commitDeleteChangeSets(groups[ChangeSetType.DELETE].get(meta) ?? [], ctx);
933
- }
934
- // take snapshots of all persisted collections
935
- const visited = new Set();
936
- for (const changeSet of this.#changeSets.values()) {
937
- this.takeCollectionSnapshots(changeSet.entity, visited);
938
- }
939
- }
940
- async commitCreateChangeSets(changeSets, ctx) {
941
- if (changeSets.length === 0) {
942
- return;
943
- }
944
- const props = changeSets[0].meta.root.relations.filter(prop => {
945
- return ((prop.kind === ReferenceKind.ONE_TO_ONE && prop.owner) ||
946
- prop.kind === ReferenceKind.MANY_TO_ONE ||
947
- (prop.kind === ReferenceKind.MANY_TO_MANY && prop.owner && !this.#platform.usesPivotTable()));
630
+ const identifier = wrapped.__identifier;
631
+ const identifiers = Array.isArray(identifier) ? identifier : [identifier];
632
+ for (let i = 0; i < current.primaryKeys.length; i++) {
633
+ const pk = current.primaryKeys[i];
634
+ payload[pk] = identifiers[i] ?? originalChangeSet.payload[pk];
635
+ }
636
+ }
637
+ if (!isCreate && Object.keys(payload).length === 0) {
638
+ current = current.tptParent;
639
+ continue;
640
+ }
641
+ const cs = new ChangeSet(entity, originalChangeSet.type, payload, current);
642
+ if (current === meta) {
643
+ cs.originalEntity = originalChangeSet.originalEntity;
644
+ leafCs = cs;
645
+ } else {
646
+ parentChangeSets.push(cs);
647
+ }
648
+ current = current.tptParent;
649
+ }
650
+ // When only parent properties changed (UPDATE), leaf payload is empty—create a stub anchor
651
+ if (!leafCs && parentChangeSets.length > 0) {
652
+ leafCs = new ChangeSet(entity, originalChangeSet.type, {}, meta);
653
+ leafCs.originalEntity = originalChangeSet.originalEntity;
654
+ }
655
+ // Store the leaf changeset in the main map (entity as key), with parent CSs attached
656
+ if (leafCs) {
657
+ if (parentChangeSets.length > 0) {
658
+ leafCs.tptChangeSets = parentChangeSets;
659
+ }
660
+ this.#changeSets.set(entity, leafCs);
661
+ }
662
+ }
663
+ /**
664
+ * Returns `true` when the change set should be skipped as it will be empty after the extra update.
665
+ */
666
+ checkUniqueProps(changeSet) {
667
+ if (changeSet.type !== ChangeSetType.UPDATE) {
668
+ return false;
669
+ }
670
+ // when changing a unique nullable property (or a 1:1 relation), we can't do it in a single
671
+ // query as it would cause unique constraint violations
672
+ const uniqueProps = changeSet.meta.uniqueProps.filter(prop => {
673
+ return prop.nullable || changeSet.type !== ChangeSetType.CREATE;
674
+ });
675
+ this.scheduleExtraUpdate(changeSet, uniqueProps);
676
+ return changeSet.type === ChangeSetType.UPDATE && !Utils.hasObjectKeys(changeSet.payload);
677
+ }
678
+ expandUniqueProps(entity) {
679
+ const wrapped = helper(entity);
680
+ if (!wrapped.__meta.hasUniqueProps) {
681
+ return [];
682
+ }
683
+ const simpleUniqueHashes = wrapped.__meta.uniqueProps
684
+ .map(prop => {
685
+ if (entity[prop.name] != null) {
686
+ return prop.kind === ReferenceKind.SCALAR || prop.mapToPk
687
+ ? entity[prop.name]
688
+ : helper(entity[prop.name]).getSerializedPrimaryKey();
689
+ }
690
+ if (wrapped.__originalEntityData?.[prop.name] != null) {
691
+ return Utils.getPrimaryKeyHash(Utils.asArray(wrapped.__originalEntityData[prop.name]));
692
+ }
693
+ return undefined;
694
+ })
695
+ .filter(i => i);
696
+ const compoundUniqueHashes = wrapped.__meta.uniques
697
+ .map(unique => {
698
+ const props = Utils.asArray(unique.properties);
699
+ if (props.every(prop => entity[prop] != null)) {
700
+ return Utils.getPrimaryKeyHash(
701
+ props.map(p => {
702
+ const prop = wrapped.__meta.properties[p];
703
+ return prop.kind === ReferenceKind.SCALAR || prop.mapToPk
704
+ ? entity[prop.name]
705
+ : helper(entity[prop.name]).getSerializedPrimaryKey();
706
+ }),
707
+ );
708
+ }
709
+ return undefined;
710
+ })
711
+ .filter(i => i);
712
+ return simpleUniqueHashes.concat(compoundUniqueHashes);
713
+ }
714
+ initIdentifier(entity) {
715
+ const wrapped = entity && helper(entity);
716
+ if (!wrapped || wrapped.__identifier || wrapped.hasPrimaryKey()) {
717
+ return;
718
+ }
719
+ const pks = wrapped.__meta.getPrimaryProps();
720
+ const idents = [];
721
+ for (const pk of pks) {
722
+ if (pk.kind === ReferenceKind.SCALAR) {
723
+ idents.push(new EntityIdentifier(entity[pk.name]));
724
+ } else if (entity[pk.name]) {
725
+ this.initIdentifier(entity[pk.name]);
726
+ idents.push(helper(entity[pk.name])?.__identifier);
727
+ }
728
+ }
729
+ if (pks.length === 1) {
730
+ wrapped.__identifier = idents[0];
731
+ } else {
732
+ wrapped.__identifier = idents;
733
+ }
734
+ }
735
+ processReference(parent, prop, kind, visited, processed, idx) {
736
+ const isToOne = prop.kind === ReferenceKind.MANY_TO_ONE || prop.kind === ReferenceKind.ONE_TO_ONE;
737
+ if (isToOne && Utils.isEntity(kind)) {
738
+ return this.processToOneReference(kind, visited, processed, idx);
739
+ }
740
+ if (Utils.isCollection(kind)) {
741
+ kind
742
+ .getItems(false)
743
+ .filter(item => !item.__helper.__originalEntityData)
744
+ .forEach(item => {
745
+ // propagate schema from parent
746
+ item.__helper.__schema ??= helper(parent).__schema;
948
747
  });
949
- for (const changeSet of changeSets) {
950
- this.findExtraUpdates(changeSet, props);
951
- await this.runHooks(EventType.beforeCreate, changeSet, true);
952
- }
953
- await this.#changeSetPersister.executeInserts(changeSets, { ctx });
954
- for (const changeSet of changeSets) {
955
- this.register(changeSet.entity, changeSet.payload, { refresh: true });
956
- await this.runHooks(EventType.afterCreate, changeSet);
957
- }
958
- }
959
- findExtraUpdates(changeSet, props) {
960
- for (const prop of props) {
961
- const ref = changeSet.entity[prop.name];
962
- if (!ref || prop.deferMode === DeferMode.INITIALLY_DEFERRED) {
963
- continue;
964
- }
965
- if (Utils.isCollection(ref)) {
966
- ref.getItems(false).some(item => {
967
- const cs = this.#changeSets.get(Reference.unwrapReference(item));
968
- const isScheduledForInsert = cs?.type === ChangeSetType.CREATE && !cs.persisted;
969
- if (isScheduledForInsert) {
970
- this.scheduleExtraUpdate(changeSet, [prop]);
971
- return true;
972
- }
973
- return false;
974
- });
975
- continue;
976
- }
977
- const refEntity = Reference.unwrapReference(ref);
978
- // For mapToPk properties, the value is a primitive (string/array), not an entity
979
- if (!Utils.isEntity(refEntity)) {
980
- continue;
981
- }
982
- // For TPT entities, check if the ROOT table's changeset has been persisted
983
- // (since the FK is to the root table, not the concrete entity's table)
984
- let cs = this.#changeSets.get(refEntity);
985
- if (cs?.tptChangeSets?.length) {
986
- // Root table changeset is the last one (ordered immediate parent → root)
987
- cs = cs.tptChangeSets[cs.tptChangeSets.length - 1];
988
- }
989
- const isScheduledForInsert = cs?.type === ChangeSetType.CREATE && !cs.persisted;
990
- if (isScheduledForInsert) {
991
- this.scheduleExtraUpdate(changeSet, [prop]);
992
- }
993
- }
994
- }
995
- findEarlyUpdates(changeSet, inserts = []) {
996
- const props = changeSet.meta.uniqueProps;
997
- for (const prop of props) {
998
- const insert = inserts.find(c => Utils.equals(c.payload[prop.name], changeSet.originalEntity[prop.name]));
999
- const propEmpty = changeSet.payload[prop.name] === null || changeSet.payload[prop.name] === undefined;
1000
- if (prop.name in changeSet.payload &&
1001
- insert &&
1002
- // We only want to update early if the unique property on the changeset is going to be empty, so that
1003
- // the previous unique value can be set on a different entity without constraint issues
1004
- propEmpty) {
1005
- changeSet.type = ChangeSetType.UPDATE_EARLY;
1006
- }
1007
- }
1008
- }
1009
- async commitUpdateChangeSets(changeSets, ctx, batched = true) {
1010
- if (changeSets.length === 0) {
1011
- return;
1012
- }
1013
- for (const changeSet of changeSets) {
1014
- await this.runHooks(EventType.beforeUpdate, changeSet, true);
1015
- }
1016
- await this.#changeSetPersister.executeUpdates(changeSets, batched, { ctx });
1017
- for (const changeSet of changeSets) {
1018
- const wrapped = helper(changeSet.entity);
1019
- wrapped.__originalEntityData = this.#comparator.prepareEntity(changeSet.entity);
1020
- if (!wrapped.__initialized) {
1021
- for (const prop of changeSet.meta.relations) {
1022
- if ([ReferenceKind.MANY_TO_MANY, ReferenceKind.ONE_TO_MANY].includes(prop.kind) &&
1023
- changeSet.entity[prop.name] == null) {
1024
- changeSet.entity[prop.name] = Collection.create(changeSet.entity, prop.name, undefined, wrapped.isInitialized());
1025
- }
1026
- }
1027
- wrapped.__initialized = true;
1028
- }
1029
- await this.runHooks(EventType.afterUpdate, changeSet);
1030
- }
1031
- }
1032
- async commitDeleteChangeSets(changeSets, ctx) {
1033
- if (changeSets.length === 0) {
1034
- return;
1035
- }
1036
- for (const changeSet of changeSets) {
1037
- await this.runHooks(EventType.beforeDelete, changeSet, true);
1038
- }
1039
- await this.#changeSetPersister.executeDeletes(changeSets, { ctx });
1040
- for (const changeSet of changeSets) {
1041
- this.unsetIdentity(changeSet.entity);
1042
- await this.runHooks(EventType.afterDelete, changeSet);
1043
- }
1044
- }
1045
- async commitExtraUpdates(type, ctx) {
1046
- const extraUpdates = [];
1047
- for (const extraUpdate of this.#extraUpdates) {
1048
- if (extraUpdate[4] !== type) {
1049
- continue;
1050
- }
1051
- if (Array.isArray(extraUpdate[1])) {
1052
- extraUpdate[1].forEach((p, i) => (extraUpdate[0][p] = extraUpdate[2][i]));
1053
- }
1054
- else {
1055
- extraUpdate[0][extraUpdate[1]] = extraUpdate[2];
1056
- }
1057
- const changeSet = this.#changeSetComputer.computeChangeSet(extraUpdate[0]);
1058
- if (changeSet) {
1059
- extraUpdates.push([changeSet, extraUpdate[3]]);
1060
- }
1061
- }
1062
- await this.commitUpdateChangeSets(extraUpdates.map(u => u[0]), ctx, false);
1063
- // propagate the new values to the original changeset
1064
- for (const extraUpdate of extraUpdates) {
1065
- if (extraUpdate[1]) {
1066
- Object.assign(extraUpdate[1].payload, extraUpdate[0].payload);
1067
- }
1068
- }
1069
- }
1070
- async commitCollectionUpdates(ctx) {
1071
- this.filterCollectionUpdates();
1072
- const loggerContext = Utils.merge({ id: this.#em._id }, this.#em.getLoggerContext({ disableContextResolution: true }));
1073
- await this.#em.getDriver().syncCollections(this.#collectionUpdates, {
1074
- ctx,
1075
- schema: this.#em.schema,
1076
- loggerContext,
748
+ if (prop.kind === ReferenceKind.MANY_TO_MANY && kind.isDirty()) {
749
+ this.processToManyReference(kind, visited, processed, parent, prop);
750
+ }
751
+ }
752
+ }
753
+ processToOneReference(kind, visited, processed, idx) {
754
+ if (!kind.__helper.__managed) {
755
+ this.findNewEntities(kind, visited, idx, processed);
756
+ }
757
+ }
758
+ processToManyReference(collection, visited, processed, parent, prop) {
759
+ if (this.isCollectionSelfReferenced(collection, processed)) {
760
+ this.#extraUpdates.add([parent, prop.name, collection, undefined, ChangeSetType.UPDATE]);
761
+ const coll = new Collection(parent);
762
+ coll.property = prop;
763
+ parent[prop.name] = coll;
764
+ return;
765
+ }
766
+ collection
767
+ .getItems(false)
768
+ .filter(item => !item.__helper.__originalEntityData)
769
+ .forEach(item => this.findNewEntities(item, visited, 0, processed));
770
+ }
771
+ async runHooks(type, changeSet, sync = false) {
772
+ const meta = changeSet.meta;
773
+ if (!this.#eventManager.hasListeners(type, meta)) {
774
+ return;
775
+ }
776
+ if (!sync) {
777
+ await this.#eventManager.dispatchEvent(type, { entity: changeSet.entity, meta, em: this.#em, changeSet });
778
+ return;
779
+ }
780
+ const copy = this.#comparator.prepareEntity(changeSet.entity);
781
+ await this.#eventManager.dispatchEvent(type, { entity: changeSet.entity, meta, em: this.#em, changeSet });
782
+ const current = this.#comparator.prepareEntity(changeSet.entity);
783
+ const diff = this.#comparator.diffEntities(changeSet.meta.class, copy, current);
784
+ Object.assign(changeSet.payload, diff);
785
+ const wrapped = helper(changeSet.entity);
786
+ if (wrapped.__identifier) {
787
+ const idents = Utils.asArray(wrapped.__identifier);
788
+ let i = 0;
789
+ for (const pk of wrapped.__meta.primaryKeys) {
790
+ if (diff[pk]) {
791
+ idents[i].setValue(diff[pk]);
792
+ }
793
+ i++;
794
+ }
795
+ }
796
+ }
797
+ postCommitCleanup() {
798
+ for (const cs of this.#changeSets.values()) {
799
+ const wrapped = helper(cs.entity);
800
+ wrapped.__processing = false;
801
+ delete wrapped.__pk;
802
+ }
803
+ this.#persistStack.clear();
804
+ this.#removeStack.clear();
805
+ this.#orphanRemoveStack.clear();
806
+ this.#changeSets.clear();
807
+ this.#collectionUpdates.clear();
808
+ this.#extraUpdates.clear();
809
+ this.#queuedActions.clear();
810
+ this.#working = false;
811
+ }
812
+ cascade(entity, type, visited = new Set(), options = {}) {
813
+ if (visited.has(entity)) {
814
+ return;
815
+ }
816
+ visited.add(entity);
817
+ switch (type) {
818
+ case Cascade.PERSIST:
819
+ this.persist(entity, visited, options);
820
+ break;
821
+ case Cascade.MERGE:
822
+ this.merge(entity, visited);
823
+ break;
824
+ case Cascade.REMOVE:
825
+ this.remove(entity, visited, options);
826
+ break;
827
+ case Cascade.SCHEDULE_ORPHAN_REMOVAL:
828
+ this.scheduleOrphanRemoval(entity, visited);
829
+ break;
830
+ case Cascade.CANCEL_ORPHAN_REMOVAL:
831
+ this.cancelOrphanRemoval(entity, visited);
832
+ break;
833
+ }
834
+ for (const prop of helper(entity).__meta.relations) {
835
+ this.cascadeReference(entity, prop, type, visited, options);
836
+ }
837
+ }
838
+ cascadeReference(entity, prop, type, visited, options) {
839
+ this.fixMissingReference(entity, prop);
840
+ if (!this.shouldCascade(prop, type)) {
841
+ return;
842
+ }
843
+ const kind = Reference.unwrapReference(entity[prop.name]);
844
+ if ([ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(prop.kind) && Utils.isEntity(kind)) {
845
+ return this.cascade(kind, type, visited, options);
846
+ }
847
+ const collection = kind;
848
+ if ([ReferenceKind.ONE_TO_MANY, ReferenceKind.MANY_TO_MANY].includes(prop.kind) && collection) {
849
+ for (const item of collection.getItems(false)) {
850
+ this.cascade(item, type, visited, options);
851
+ }
852
+ }
853
+ }
854
+ isCollectionSelfReferenced(collection, processed) {
855
+ const filtered = collection.getItems(false).filter(item => !helper(item).__originalEntityData);
856
+ return filtered.some(items => processed.has(items));
857
+ }
858
+ shouldCascade(prop, type) {
859
+ if (
860
+ [Cascade.REMOVE, Cascade.SCHEDULE_ORPHAN_REMOVAL, Cascade.CANCEL_ORPHAN_REMOVAL, Cascade.ALL].includes(type) &&
861
+ prop.orphanRemoval
862
+ ) {
863
+ return true;
864
+ }
865
+ // ignore user settings for merge, it is kept only for back compatibility, this should have never been configurable
866
+ if (type === Cascade.MERGE) {
867
+ return true;
868
+ }
869
+ return prop.cascade && (prop.cascade.includes(type) || prop.cascade.includes(Cascade.ALL));
870
+ }
871
+ async lockPessimistic(entity, options) {
872
+ if (!this.#em.isInTransaction()) {
873
+ throw ValidationError.transactionRequired();
874
+ }
875
+ await this.#em.getDriver().lockPessimistic(entity, { ctx: this.#em.getTransactionContext(), ...options });
876
+ }
877
+ async lockOptimistic(entity, meta, version) {
878
+ if (!meta.versionProperty) {
879
+ throw OptimisticLockError.notVersioned(meta);
880
+ }
881
+ if (typeof version === 'undefined') {
882
+ return;
883
+ }
884
+ const wrapped = helper(entity);
885
+ if (!wrapped.__initialized) {
886
+ await wrapped.init();
887
+ }
888
+ const previousVersion = entity[meta.versionProperty];
889
+ if (previousVersion !== version) {
890
+ throw OptimisticLockError.lockFailedVersionMismatch(entity, version, previousVersion);
891
+ }
892
+ }
893
+ fixMissingReference(entity, prop) {
894
+ const reference = entity[prop.name];
895
+ const target = Reference.unwrapReference(reference);
896
+ if ([ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(prop.kind) && target && !prop.mapToPk) {
897
+ if (!Utils.isEntity(target)) {
898
+ entity[prop.name] = this.#em.getReference(prop.targetMeta.class, target, {
899
+ wrapped: !!prop.ref,
1077
900
  });
1078
- for (const coll of this.#collectionUpdates) {
1079
- coll.takeSnapshot();
1080
- }
1081
- }
1082
- filterCollectionUpdates() {
1083
- for (const coll of this.#collectionUpdates) {
1084
- let skip = true;
1085
- if (coll.property.owner || coll.getItems(false).filter(item => !item.__helper.__initialized).length > 0) {
1086
- if (this.#platform.usesPivotTable()) {
1087
- skip = false;
1088
- }
1089
- }
1090
- else if (coll.property.kind === ReferenceKind.ONE_TO_MANY && coll.getSnapshot() === undefined) {
1091
- skip = false;
1092
- }
1093
- else if (coll.property.kind === ReferenceKind.MANY_TO_MANY && !coll.property.owner) {
1094
- skip = false;
1095
- }
1096
- if (skip) {
1097
- this.#collectionUpdates.delete(coll);
1098
- }
1099
- }
1100
- }
1101
- /**
1102
- * Orders change sets so FK constrains are maintained, ensures stable order (needed for node < 11)
1103
- */
1104
- getChangeSetGroups() {
1105
- const groups = {
1106
- [ChangeSetType.CREATE]: new Map(),
1107
- [ChangeSetType.UPDATE]: new Map(),
1108
- [ChangeSetType.DELETE]: new Map(),
1109
- [ChangeSetType.UPDATE_EARLY]: new Map(),
1110
- [ChangeSetType.DELETE_EARLY]: new Map(),
1111
- };
1112
- const addToGroup = (cs) => {
1113
- // Skip stub TPT changesets with empty payload (e.g. leaf with no own-property changes on UPDATE)
1114
- if ((cs.type === ChangeSetType.UPDATE || cs.type === ChangeSetType.UPDATE_EARLY) &&
1115
- !Utils.hasObjectKeys(cs.payload)) {
1116
- return;
1117
- }
1118
- const group = groups[cs.type];
1119
- const groupKey = cs.meta.inheritanceType === 'tpt' ? cs.meta : cs.rootMeta;
1120
- const classGroup = group.get(groupKey) ?? [];
1121
- classGroup.push(cs);
1122
- if (!group.has(groupKey)) {
1123
- group.set(groupKey, classGroup);
1124
- }
1125
- };
1126
- for (const cs of this.#changeSets.values()) {
1127
- addToGroup(cs);
1128
- for (const parentCs of cs.tptChangeSets ?? []) {
1129
- addToGroup(parentCs);
1130
- }
1131
- }
1132
- return groups;
1133
- }
1134
- getCommitOrder() {
1135
- const calc = new CommitOrderCalculator();
1136
- const set = new Set();
1137
- this.#changeSets.forEach(cs => {
1138
- if (cs.meta.inheritanceType === 'tpt') {
1139
- set.add(cs.meta);
1140
- for (const parentCs of cs.tptChangeSets ?? []) {
1141
- set.add(parentCs.meta);
1142
- }
1143
- }
1144
- else {
1145
- set.add(cs.rootMeta);
1146
- }
901
+ } else if (!helper(target).__initialized && !helper(target).__em) {
902
+ const pk = helper(target).getPrimaryKey();
903
+ entity[prop.name] = this.#em.getReference(prop.targetMeta.class, pk, {
904
+ wrapped: !!prop.ref,
1147
905
  });
1148
- set.forEach(meta => calc.addNode(meta._id));
1149
- for (const meta of set) {
1150
- for (const prop of meta.relations) {
1151
- if (prop.polymorphTargets) {
1152
- for (const targetMeta of prop.polymorphTargets) {
1153
- calc.discoverProperty({ ...prop, targetMeta }, meta._id);
1154
- }
1155
- }
1156
- else {
1157
- calc.discoverProperty(prop, meta._id);
1158
- }
1159
- }
1160
- // For TPT, parent table must be inserted BEFORE child tables
1161
- if (meta.inheritanceType === 'tpt' && meta.tptParent && set.has(meta.tptParent)) {
1162
- calc.addDependency(meta.tptParent._id, meta._id, 1);
1163
- }
1164
- }
1165
- return calc.sort().map(id => this.#metadata.getById(id));
1166
- }
1167
- resetTransaction(oldTx) {
1168
- if (oldTx) {
1169
- this.#em.setTransactionContext(oldTx);
1170
- }
1171
- else {
1172
- this.#em.resetTransactionContext();
1173
- }
1174
- }
1175
- /**
1176
- * Takes snapshots of all processed collections
1177
- */
1178
- takeCollectionSnapshots(entity, visited) {
1179
- if (visited.has(entity)) {
1180
- return;
1181
- }
1182
- visited.add(entity);
1183
- helper(entity)?.__meta.relations.forEach(prop => {
1184
- const value = entity[prop.name];
1185
- if (Utils.isCollection(value)) {
1186
- value.takeSnapshot();
1187
- }
1188
- // cascade to m:1 relations as we need to snapshot the 1:m inverse side (for `removeAll()` with orphan removal)
1189
- if (prop.kind === ReferenceKind.MANY_TO_ONE && value) {
1190
- this.takeCollectionSnapshots(Reference.unwrapReference(value), visited);
1191
- }
906
+ }
907
+ }
908
+ // perf: set the `Collection._property` to skip the getter, as it can be slow when there are a lot of relations
909
+ if (Utils.isCollection(target)) {
910
+ target.property = prop;
911
+ }
912
+ const isCollection = [ReferenceKind.ONE_TO_MANY, ReferenceKind.MANY_TO_MANY].includes(prop.kind);
913
+ if (isCollection && Array.isArray(target)) {
914
+ const collection = new Collection(entity);
915
+ collection.property = prop;
916
+ entity[prop.name] = collection;
917
+ collection.set(target);
918
+ }
919
+ }
920
+ async persistToDatabase(groups, ctx) {
921
+ if (ctx) {
922
+ this.#em.setTransactionContext(ctx);
923
+ }
924
+ const commitOrder = this.getCommitOrder();
925
+ const commitOrderReversed = [...commitOrder].reverse();
926
+ // early delete - when we recreate entity in the same UoW, we need to issue those delete queries before inserts
927
+ for (const meta of commitOrderReversed) {
928
+ await this.commitDeleteChangeSets(groups[ChangeSetType.DELETE_EARLY].get(meta) ?? [], ctx);
929
+ }
930
+ // early update - when we recreate entity in the same UoW, we need to issue those delete queries before inserts
931
+ for (const meta of commitOrder) {
932
+ await this.commitUpdateChangeSets(groups[ChangeSetType.UPDATE_EARLY].get(meta) ?? [], ctx);
933
+ }
934
+ // extra updates
935
+ await this.commitExtraUpdates(ChangeSetType.UPDATE_EARLY, ctx);
936
+ // create
937
+ for (const meta of commitOrder) {
938
+ await this.commitCreateChangeSets(groups[ChangeSetType.CREATE].get(meta) ?? [], ctx);
939
+ }
940
+ // update
941
+ for (const meta of commitOrder) {
942
+ await this.commitUpdateChangeSets(groups[ChangeSetType.UPDATE].get(meta) ?? [], ctx);
943
+ }
944
+ // extra updates
945
+ await this.commitExtraUpdates(ChangeSetType.UPDATE, ctx);
946
+ // collection updates
947
+ await this.commitCollectionUpdates(ctx);
948
+ // delete - entity deletions need to be in reverse commit order
949
+ for (const meta of commitOrderReversed) {
950
+ await this.commitDeleteChangeSets(groups[ChangeSetType.DELETE].get(meta) ?? [], ctx);
951
+ }
952
+ // take snapshots of all persisted collections
953
+ const visited = new Set();
954
+ for (const changeSet of this.#changeSets.values()) {
955
+ this.takeCollectionSnapshots(changeSet.entity, visited);
956
+ }
957
+ }
958
+ async commitCreateChangeSets(changeSets, ctx) {
959
+ if (changeSets.length === 0) {
960
+ return;
961
+ }
962
+ const props = changeSets[0].meta.root.relations.filter(prop => {
963
+ return (
964
+ (prop.kind === ReferenceKind.ONE_TO_ONE && prop.owner) ||
965
+ prop.kind === ReferenceKind.MANY_TO_ONE ||
966
+ (prop.kind === ReferenceKind.MANY_TO_MANY && prop.owner && !this.#platform.usesPivotTable())
967
+ );
968
+ });
969
+ for (const changeSet of changeSets) {
970
+ this.findExtraUpdates(changeSet, props);
971
+ await this.runHooks(EventType.beforeCreate, changeSet, true);
972
+ }
973
+ await this.#changeSetPersister.executeInserts(changeSets, { ctx });
974
+ for (const changeSet of changeSets) {
975
+ this.register(changeSet.entity, changeSet.payload, { refresh: true });
976
+ await this.runHooks(EventType.afterCreate, changeSet);
977
+ }
978
+ }
979
+ findExtraUpdates(changeSet, props) {
980
+ for (const prop of props) {
981
+ const ref = changeSet.entity[prop.name];
982
+ if (!ref || prop.deferMode === DeferMode.INITIALLY_DEFERRED) {
983
+ continue;
984
+ }
985
+ if (Utils.isCollection(ref)) {
986
+ ref.getItems(false).some(item => {
987
+ const cs = this.#changeSets.get(Reference.unwrapReference(item));
988
+ const isScheduledForInsert = cs?.type === ChangeSetType.CREATE && !cs.persisted;
989
+ if (isScheduledForInsert) {
990
+ this.scheduleExtraUpdate(changeSet, [prop]);
991
+ return true;
992
+ }
993
+ return false;
1192
994
  });
1193
- }
995
+ continue;
996
+ }
997
+ const refEntity = Reference.unwrapReference(ref);
998
+ // For mapToPk properties, the value is a primitive (string/array), not an entity
999
+ if (!Utils.isEntity(refEntity)) {
1000
+ continue;
1001
+ }
1002
+ // For TPT entities, check if the ROOT table's changeset has been persisted
1003
+ // (since the FK is to the root table, not the concrete entity's table)
1004
+ let cs = this.#changeSets.get(refEntity);
1005
+ if (cs?.tptChangeSets?.length) {
1006
+ // Root table changeset is the last one (ordered immediate parent → root)
1007
+ cs = cs.tptChangeSets[cs.tptChangeSets.length - 1];
1008
+ }
1009
+ const isScheduledForInsert = cs?.type === ChangeSetType.CREATE && !cs.persisted;
1010
+ if (isScheduledForInsert) {
1011
+ this.scheduleExtraUpdate(changeSet, [prop]);
1012
+ }
1013
+ }
1014
+ }
1015
+ findEarlyUpdates(changeSet, inserts = []) {
1016
+ const props = changeSet.meta.uniqueProps;
1017
+ for (const prop of props) {
1018
+ const insert = inserts.find(c => Utils.equals(c.payload[prop.name], changeSet.originalEntity[prop.name]));
1019
+ const propEmpty = changeSet.payload[prop.name] === null || changeSet.payload[prop.name] === undefined;
1020
+ if (
1021
+ prop.name in changeSet.payload &&
1022
+ insert &&
1023
+ // We only want to update early if the unique property on the changeset is going to be empty, so that
1024
+ // the previous unique value can be set on a different entity without constraint issues
1025
+ propEmpty
1026
+ ) {
1027
+ changeSet.type = ChangeSetType.UPDATE_EARLY;
1028
+ }
1029
+ }
1030
+ }
1031
+ async commitUpdateChangeSets(changeSets, ctx, batched = true) {
1032
+ if (changeSets.length === 0) {
1033
+ return;
1034
+ }
1035
+ for (const changeSet of changeSets) {
1036
+ await this.runHooks(EventType.beforeUpdate, changeSet, true);
1037
+ }
1038
+ await this.#changeSetPersister.executeUpdates(changeSets, batched, { ctx });
1039
+ for (const changeSet of changeSets) {
1040
+ const wrapped = helper(changeSet.entity);
1041
+ wrapped.__originalEntityData = this.#comparator.prepareEntity(changeSet.entity);
1042
+ if (!wrapped.__initialized) {
1043
+ for (const prop of changeSet.meta.relations) {
1044
+ if (
1045
+ [ReferenceKind.MANY_TO_MANY, ReferenceKind.ONE_TO_MANY].includes(prop.kind) &&
1046
+ changeSet.entity[prop.name] == null
1047
+ ) {
1048
+ changeSet.entity[prop.name] = Collection.create(
1049
+ changeSet.entity,
1050
+ prop.name,
1051
+ undefined,
1052
+ wrapped.isInitialized(),
1053
+ );
1054
+ }
1055
+ }
1056
+ wrapped.__initialized = true;
1057
+ }
1058
+ await this.runHooks(EventType.afterUpdate, changeSet);
1059
+ }
1060
+ }
1061
+ async commitDeleteChangeSets(changeSets, ctx) {
1062
+ if (changeSets.length === 0) {
1063
+ return;
1064
+ }
1065
+ for (const changeSet of changeSets) {
1066
+ await this.runHooks(EventType.beforeDelete, changeSet, true);
1067
+ }
1068
+ await this.#changeSetPersister.executeDeletes(changeSets, { ctx });
1069
+ for (const changeSet of changeSets) {
1070
+ this.unsetIdentity(changeSet.entity);
1071
+ await this.runHooks(EventType.afterDelete, changeSet);
1072
+ }
1073
+ }
1074
+ async commitExtraUpdates(type, ctx) {
1075
+ const extraUpdates = [];
1076
+ for (const extraUpdate of this.#extraUpdates) {
1077
+ if (extraUpdate[4] !== type) {
1078
+ continue;
1079
+ }
1080
+ if (Array.isArray(extraUpdate[1])) {
1081
+ extraUpdate[1].forEach((p, i) => (extraUpdate[0][p] = extraUpdate[2][i]));
1082
+ } else {
1083
+ extraUpdate[0][extraUpdate[1]] = extraUpdate[2];
1084
+ }
1085
+ const changeSet = this.#changeSetComputer.computeChangeSet(extraUpdate[0]);
1086
+ if (changeSet) {
1087
+ extraUpdates.push([changeSet, extraUpdate[3]]);
1088
+ }
1089
+ }
1090
+ await this.commitUpdateChangeSets(
1091
+ extraUpdates.map(u => u[0]),
1092
+ ctx,
1093
+ false,
1094
+ );
1095
+ // propagate the new values to the original changeset
1096
+ for (const extraUpdate of extraUpdates) {
1097
+ if (extraUpdate[1]) {
1098
+ Object.assign(extraUpdate[1].payload, extraUpdate[0].payload);
1099
+ }
1100
+ }
1101
+ }
1102
+ async commitCollectionUpdates(ctx) {
1103
+ this.filterCollectionUpdates();
1104
+ const loggerContext = Utils.merge(
1105
+ { id: this.#em._id },
1106
+ this.#em.getLoggerContext({ disableContextResolution: true }),
1107
+ );
1108
+ await this.#em.getDriver().syncCollections(this.#collectionUpdates, {
1109
+ ctx,
1110
+ schema: this.#em.schema,
1111
+ loggerContext,
1112
+ });
1113
+ for (const coll of this.#collectionUpdates) {
1114
+ coll.takeSnapshot();
1115
+ }
1116
+ }
1117
+ filterCollectionUpdates() {
1118
+ for (const coll of this.#collectionUpdates) {
1119
+ let skip = true;
1120
+ if (coll.property.owner || coll.getItems(false).filter(item => !item.__helper.__initialized).length > 0) {
1121
+ if (this.#platform.usesPivotTable()) {
1122
+ skip = false;
1123
+ }
1124
+ } else if (coll.property.kind === ReferenceKind.ONE_TO_MANY && coll.getSnapshot() === undefined) {
1125
+ skip = false;
1126
+ } else if (coll.property.kind === ReferenceKind.MANY_TO_MANY && !coll.property.owner) {
1127
+ skip = false;
1128
+ }
1129
+ if (skip) {
1130
+ this.#collectionUpdates.delete(coll);
1131
+ }
1132
+ }
1133
+ }
1134
+ /**
1135
+ * Orders change sets so FK constrains are maintained, ensures stable order (needed for node < 11)
1136
+ */
1137
+ getChangeSetGroups() {
1138
+ const groups = {
1139
+ [ChangeSetType.CREATE]: new Map(),
1140
+ [ChangeSetType.UPDATE]: new Map(),
1141
+ [ChangeSetType.DELETE]: new Map(),
1142
+ [ChangeSetType.UPDATE_EARLY]: new Map(),
1143
+ [ChangeSetType.DELETE_EARLY]: new Map(),
1144
+ };
1145
+ const addToGroup = cs => {
1146
+ // Skip stub TPT changesets with empty payload (e.g. leaf with no own-property changes on UPDATE)
1147
+ if (
1148
+ (cs.type === ChangeSetType.UPDATE || cs.type === ChangeSetType.UPDATE_EARLY) &&
1149
+ !Utils.hasObjectKeys(cs.payload)
1150
+ ) {
1151
+ return;
1152
+ }
1153
+ const group = groups[cs.type];
1154
+ const groupKey = cs.meta.inheritanceType === 'tpt' ? cs.meta : cs.rootMeta;
1155
+ const classGroup = group.get(groupKey) ?? [];
1156
+ classGroup.push(cs);
1157
+ if (!group.has(groupKey)) {
1158
+ group.set(groupKey, classGroup);
1159
+ }
1160
+ };
1161
+ for (const cs of this.#changeSets.values()) {
1162
+ addToGroup(cs);
1163
+ for (const parentCs of cs.tptChangeSets ?? []) {
1164
+ addToGroup(parentCs);
1165
+ }
1166
+ }
1167
+ return groups;
1168
+ }
1169
+ getCommitOrder() {
1170
+ const calc = new CommitOrderCalculator();
1171
+ const set = new Set();
1172
+ this.#changeSets.forEach(cs => {
1173
+ if (cs.meta.inheritanceType === 'tpt') {
1174
+ set.add(cs.meta);
1175
+ for (const parentCs of cs.tptChangeSets ?? []) {
1176
+ set.add(parentCs.meta);
1177
+ }
1178
+ } else {
1179
+ set.add(cs.rootMeta);
1180
+ }
1181
+ });
1182
+ set.forEach(meta => calc.addNode(meta._id));
1183
+ for (const meta of set) {
1184
+ for (const prop of meta.relations) {
1185
+ if (prop.polymorphTargets) {
1186
+ for (const targetMeta of prop.polymorphTargets) {
1187
+ calc.discoverProperty({ ...prop, targetMeta }, meta._id);
1188
+ }
1189
+ } else {
1190
+ calc.discoverProperty(prop, meta._id);
1191
+ }
1192
+ }
1193
+ // For TPT, parent table must be inserted BEFORE child tables
1194
+ if (meta.inheritanceType === 'tpt' && meta.tptParent && set.has(meta.tptParent)) {
1195
+ calc.addDependency(meta.tptParent._id, meta._id, 1);
1196
+ }
1197
+ }
1198
+ return calc.sort().map(id => this.#metadata.getById(id));
1199
+ }
1200
+ resetTransaction(oldTx) {
1201
+ if (oldTx) {
1202
+ this.#em.setTransactionContext(oldTx);
1203
+ } else {
1204
+ this.#em.resetTransactionContext();
1205
+ }
1206
+ }
1207
+ /**
1208
+ * Takes snapshots of all processed collections
1209
+ */
1210
+ takeCollectionSnapshots(entity, visited) {
1211
+ if (visited.has(entity)) {
1212
+ return;
1213
+ }
1214
+ visited.add(entity);
1215
+ helper(entity)?.__meta.relations.forEach(prop => {
1216
+ const value = entity[prop.name];
1217
+ if (Utils.isCollection(value)) {
1218
+ value.takeSnapshot();
1219
+ }
1220
+ // cascade to m:1 relations as we need to snapshot the 1:m inverse side (for `removeAll()` with orphan removal)
1221
+ if (prop.kind === ReferenceKind.MANY_TO_ONE && value) {
1222
+ this.takeCollectionSnapshots(Reference.unwrapReference(value), visited);
1223
+ }
1224
+ });
1225
+ }
1194
1226
  }