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

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