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

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 +1922 -1895
  3. package/MikroORM.d.ts +103 -74
  4. package/MikroORM.js +178 -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 +186 -80
  18. package/drivers/DatabaseDriver.js +450 -443
  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 +212 -179
  23. package/entity/Collection.js +727 -721
  24. package/entity/EntityAssigner.d.ts +88 -77
  25. package/entity/EntityAssigner.js +231 -230
  26. package/entity/EntityFactory.d.ts +66 -54
  27. package/entity/EntityFactory.js +425 -383
  28. package/entity/EntityHelper.d.ts +34 -22
  29. package/entity/EntityHelper.js +280 -267
  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 +753 -723
  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 +126 -82
  39. package/entity/Reference.js +278 -274
  40. package/entity/WrappedEntity.d.ts +115 -72
  41. package/entity/WrappedEntity.js +168 -166
  42. package/entity/defineEntity.d.ts +1315 -636
  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 +481 -416
  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 +211 -127
  74. package/metadata/EntitySchema.js +397 -398
  75. package/metadata/MetadataDiscovery.d.ts +114 -114
  76. package/metadata/MetadataDiscovery.js +1951 -1863
  77. package/metadata/MetadataProvider.d.ts +24 -21
  78. package/metadata/MetadataProvider.js +82 -84
  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 -27
  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 +310 -299
  100. package/platforms/Platform.js +663 -636
  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 +1250 -737
  160. package/typings.js +244 -231
  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 +178 -170
  165. package/unit-of-work/ChangeSetPersister.d.ts +63 -44
  166. package/unit-of-work/ChangeSetPersister.js +442 -421
  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 +1200 -1183
  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 +98 -81
  186. package/utils/EntityComparator.js +828 -728
  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 +812 -810
  201. package/utils/clone.js +104 -113
  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
@@ -7,735 +7,741 @@ import { QueryHelper } from '../utils/QueryHelper.js';
7
7
  import { inspect } from '../logging/inspect.js';
8
8
  /** Represents a to-many relation (1:m or m:n) as an iterable, managed collection of entities. */
9
9
  export class Collection {
10
- owner;
11
- #items = new Set();
12
- #initialized = true;
13
- #dirty = false;
14
- #partial = false; // mark partially loaded collections, propagation is disabled for those
15
- #snapshot = []; // used to create a diff of the collection at commit time, undefined marks overridden values so we need to wipe when flushing
16
- #readonly;
17
- #count;
18
- #property;
19
- #populated;
20
- constructor(owner, items, initialized = true) {
21
- this.owner = owner;
22
- /* v8 ignore next */
23
- if (items) {
24
- let i = 0;
25
- this.#items = new Set(items);
26
- this.#items.forEach(item => (this[i++] = item));
27
- }
28
- this.#initialized = !!items || initialized;
29
- }
30
- /**
31
- * Creates new Collection instance, assigns it to the owning entity and sets the items to it (propagating them to their inverse sides)
32
- */
33
- static create(owner, prop, items, initialized) {
34
- const coll = new Collection(owner, undefined, initialized);
35
- coll.property = helper(owner).__meta.properties[prop];
36
- owner[prop] = coll;
37
- if (items) {
38
- coll.set(items);
39
- }
40
- return coll;
41
- }
42
- /**
43
- * Ensures the collection is loaded first (without reloading it if it already is loaded).
44
- * Returns the Collection instance (itself), works the same as `Reference.load()`.
45
- */
46
- async load(options = {}) {
47
- if (this.isInitialized(true) && !options.refresh) {
48
- const em = this.getEntityManager(this.#items, false);
49
- options = { ...options, filters: QueryHelper.mergePropertyFilters(this.property.filters, options.filters) };
50
- await em?.populate(this.#items, options.populate, options);
51
- this.setSerializationContext(options);
52
- }
53
- else {
54
- await this.init({ refresh: false, ...options });
55
- }
56
- return this;
57
- }
58
- setSerializationContext(options) {
59
- helper(this.owner).setSerializationContext({
60
- populate: Array.isArray(options.populate)
61
- ? options.populate.map(hint => `${this.property.name}.${hint}`)
62
- : (options.populate ?? [this.property.name]),
63
- });
64
- }
65
- /**
66
- * Initializes the collection and returns the items
67
- */
68
- async loadItems(options) {
69
- await this.load(options);
70
- return this.getItems(false);
71
- }
72
- /**
73
- * Gets the count of collection items from database instead of counting loaded items.
74
- * The value is cached (unless you use the `where` option), use `refresh: true` to force reload it.
75
- */
76
- async loadCount(options = {}) {
77
- options = typeof options === 'boolean' ? { refresh: options } : options;
78
- const { refresh, where, ...countOptions } = options;
79
- if (!refresh && !where && this.#count != null) {
80
- return this.#count;
81
- }
82
- const em = this.getEntityManager();
83
- if (!em.getPlatform().usesPivotTable() &&
84
- this.property.kind === ReferenceKind.MANY_TO_MANY &&
85
- this.property.owner) {
86
- return (this.#count = this.length);
87
- }
88
- const cond = this.createLoadCountCondition(where ?? {});
89
- const count = await em.count(this.property.targetMeta.class, cond, countOptions);
90
- if (!where) {
91
- this.#count = count;
92
- }
93
- return count;
94
- }
95
- /** Queries a subset of the collection items from the database with custom filtering, ordering, and pagination. */
96
- async matching(options) {
97
- const em = this.getEntityManager();
98
- const { where, ctx, ...opts } = options;
99
- let items;
100
- if (this.property.kind === ReferenceKind.MANY_TO_MANY && em.getPlatform().usesPivotTable()) {
101
- // M:N via pivot table bypasses em.find(), so merge all 3 levels here
102
- opts.orderBy = QueryHelper.mergeOrderBy(opts.orderBy, this.property.orderBy, this.property.targetMeta?.orderBy);
103
- options.populate = (await em.preparePopulate(this.property.targetMeta.class, options));
104
- const cond = (await em.applyFilters(this.property.targetMeta.class, where, options.filters ?? {}, 'read'));
105
- const map = await em
106
- .getDriver()
107
- .loadFromPivotTable(this.property, [helper(this.owner).__primaryKeys], cond, opts.orderBy, ctx, options);
108
- items = map[helper(this.owner).getSerializedPrimaryKey()].map((item) => em.merge(this.property.targetMeta.class, item, { convertCustomTypes: true }));
109
- await em.populate(items, options.populate, options);
110
- }
111
- else {
112
- // em.find() merges entity-level orderBy, so only merge runtime + relation here
113
- opts.orderBy = QueryHelper.mergeOrderBy(opts.orderBy, this.property.orderBy);
114
- items = (await em.find(this.property.targetMeta.class, this.createCondition(where), opts));
115
- }
116
- if (options.store) {
117
- this.hydrate(items, true);
118
- this.setSerializationContext(options);
119
- this.populated();
120
- this.#readonly = true;
121
- }
122
- return items;
123
- }
124
- /**
125
- * Returns the items (the collection must be initialized)
126
- */
127
- getItems(check = true) {
128
- if (check) {
129
- this.checkInitialized();
130
- }
131
- return [...this.#items];
132
- }
133
- /** Serializes the collection items to plain JSON objects. Returns an empty array if not initialized. */
134
- toJSON() {
135
- if (!this.isInitialized()) {
136
- return [];
137
- }
138
- return this.toArray();
139
- }
140
- /** Adds one or more items to the collection, propagating the change to the inverse side. Returns the number of items added. */
141
- add(entity, ...entities) {
142
- entities = Utils.asArray(entity).concat(entities);
143
- const unwrapped = entities.map(i => Reference.unwrapReference(i));
144
- this.validateModification(unwrapped);
145
- const em = this.getEntityManager(entities, false);
146
- let added = 0;
147
- for (const item of entities) {
148
- const entity = Reference.unwrapReference(item);
149
- if (!this.contains(entity, false)) {
150
- this.incrementCount(1);
151
- this[this.#items.size] = entity;
152
- this.#items.add(entity);
153
- added++;
154
- this.#dirty = true;
155
- this.propagate(entity, 'add');
156
- }
157
- }
158
- if (this.property.kind === ReferenceKind.ONE_TO_MANY && em) {
159
- em.persist(entities);
160
- }
161
- this.cancelOrphanRemoval(unwrapped);
162
- return added;
163
- }
164
- /**
165
- * Remove specified item(s) from the collection. Note that removing item from collection does not necessarily imply deleting the target entity,
166
- * it means we are disconnecting the relation - removing items from collection, not removing entities from database - `Collection.remove()`
167
- * is not the same as `em.remove()`. If we want to delete the entity by removing it from collection, we need to enable `orphanRemoval: true`,
168
- * which tells the ORM we don't want orphaned entities to exist, so we know those should be removed.
169
- */
170
- remove(entity, ...entities) {
171
- if (entity instanceof Function) {
172
- let removed = 0;
173
- for (const item of this.#items) {
174
- if (entity(item)) {
175
- removed += this.remove(item);
176
- }
177
- }
178
- return removed;
179
- }
180
- this.checkInitialized();
181
- entities = Utils.asArray(entity).concat(entities);
182
- const unwrapped = entities.map(i => Reference.unwrapReference(i));
183
- this.validateModification(unwrapped);
184
- const em = this.getEntityManager(entities, false);
185
- let removed = 0;
186
- for (const item of entities) {
187
- if (!item) {
188
- continue;
189
- }
190
- const entity = Reference.unwrapReference(item);
191
- if (this.#items.delete(entity)) {
192
- this.incrementCount(-1);
193
- delete this[this.#items.size]; // remove last item
194
- this.propagate(entity, 'remove');
195
- removed++;
196
- this.#dirty = true;
197
- }
198
- if (this.property.orphanRemoval && em) {
199
- em.getUnitOfWork().scheduleOrphanRemoval(entity);
200
- }
201
- }
202
- if (this.property.kind === ReferenceKind.ONE_TO_MANY && !this.property.orphanRemoval && em) {
203
- em.persist(entities);
204
- }
205
- if (removed > 0) {
206
- Object.assign(this, [...this.#items]); // reassign array access
207
- }
208
- return removed;
209
- }
210
- /** Checks whether the collection contains the given item. */
211
- contains(item, check = true) {
212
- if (check) {
213
- this.checkInitialized();
214
- }
215
- const entity = Reference.unwrapReference(item);
216
- return this.#items.has(entity);
217
- }
218
- /** Returns the number of items in the collection. Throws if the collection is not initialized. */
219
- count() {
220
- this.checkInitialized();
221
- return this.#items.size;
222
- }
223
- /** Returns true if the collection has no items. Throws if the collection is not initialized. */
224
- isEmpty() {
225
- this.checkInitialized();
226
- return this.count() === 0;
227
- }
228
- /** Returns whether this collection should be included in serialization based on its populated state. */
229
- shouldPopulate(populated) {
230
- if (!this.isInitialized(true)) {
231
- return false;
232
- }
233
- if (this.#populated != null) {
234
- return this.#populated;
235
- }
236
- return !!populated;
237
- }
238
- /** Marks the collection as populated or not for serialization purposes. */
239
- populated(populated = true) {
240
- this.#populated = populated;
241
- }
242
- /** Initializes the collection by loading its items from the database. */
243
- async init(options = {}) {
244
- if (this.#dirty) {
245
- const items = [...this.#items];
246
- this.#dirty = false;
247
- await this.init(options);
248
- items.forEach(i => this.add(i));
249
- return this;
250
- }
251
- const em = this.getEntityManager();
252
- options = { ...options, filters: QueryHelper.mergePropertyFilters(this.property.filters, options.filters) };
253
- if (options.dataloader ?? [DataloaderType.ALL, DataloaderType.COLLECTION].includes(em.config.getDataloaderType())) {
254
- const order = [...this.#items]; // copy order of references
255
- const orderBy = QueryHelper.mergeOrderBy(options.orderBy, this.property.orderBy, this.property.targetMeta?.orderBy);
256
- const customOrder = orderBy.length > 0;
257
- const pivotTable = this.property.kind === ReferenceKind.MANY_TO_MANY && em.getPlatform().usesPivotTable();
258
- const loader = await em.getDataLoader(pivotTable ? 'm:n' : '1:m');
259
- const items = await loader.load([this, { ...options, orderBy }]);
260
- if (this.property.kind === ReferenceKind.MANY_TO_MANY) {
261
- this.#initialized = true;
262
- this.#dirty = false;
263
- if (!customOrder) {
264
- this.reorderItems(items, order);
265
- }
266
- return this;
267
- }
268
- this.#items.clear();
269
- let i = 0;
270
- for (const item of items) {
271
- this.#items.add(item);
272
- this[i++] = item;
273
- }
274
- this.#initialized = true;
275
- this.#dirty = false;
276
- return this;
277
- }
278
- const populate = Array.isArray(options.populate)
279
- ? options.populate.map(f => (f === '*' ? f : `${this.property.name}.${f}`))
280
- : [`${this.property.name}${options.ref ? ':ref' : ''}`];
281
- const schema = this.property.targetMeta.schema === '*' ? helper(this.owner).__schema : undefined;
282
- await em.populate(this.owner, populate, {
283
- refresh: true,
284
- ...options,
285
- connectionType: options.connectionType,
286
- schema,
287
- where: { [this.property.name]: options.where },
288
- orderBy: { [this.property.name]: options.orderBy },
289
- });
290
- return this;
291
- }
292
- getEntityManager(items = [], required = true) {
293
- const wrapped = helper(this.owner);
294
- let em = wrapped.__em;
295
- if (!em) {
296
- for (const i of items) {
297
- if (i && helper(i).__em) {
298
- em = helper(i).__em;
299
- break;
300
- }
301
- }
302
- }
303
- if (!em && required) {
304
- throw ValidationError.entityNotManaged(this.owner);
305
- }
306
- return em;
307
- }
308
- createCondition(cond = {}) {
309
- if (this.property.kind === ReferenceKind.ONE_TO_MANY) {
310
- cond[this.property.mappedBy] = helper(this.owner).getPrimaryKey();
311
- }
312
- else {
313
- // MANY_TO_MANY
314
- this.createManyToManyCondition(cond);
315
- }
316
- return cond;
317
- }
318
- createManyToManyCondition(cond) {
319
- const dict = cond;
320
- if (this.property.owner || this.property.pivotTable) {
321
- // we know there is at least one item as it was checked in load method
322
- const pk = this.property.targetMeta.primaryKeys[0];
323
- dict[pk] = { $in: [] };
324
- this.#items.forEach(item => dict[pk].$in.push(helper(item).getPrimaryKey()));
325
- }
326
- else {
327
- dict[this.property.mappedBy] = helper(this.owner).getPrimaryKey();
328
- }
329
- }
330
- createLoadCountCondition(cond) {
331
- const wrapped = helper(this.owner);
332
- const val = wrapped.__meta.compositePK ? { $in: wrapped.__primaryKeys } : wrapped.getPrimaryKey();
333
- const dict = cond;
334
- if (this.property.kind === ReferenceKind.ONE_TO_MANY) {
335
- dict[this.property.mappedBy] = val;
336
- }
337
- else {
338
- const key = this.property.owner ? this.property.inversedBy : this.property.mappedBy;
339
- dict[key] = val;
340
- }
341
- return cond;
342
- }
343
- checkInitialized() {
344
- if (!this.isInitialized()) {
345
- throw new Error(`Collection<${this.property.type}> of entity ${helper(this.owner).__meta.name}[${helper(this.owner).getSerializedPrimaryKey()}] not initialized`);
346
- }
347
- }
348
- /**
349
- * re-orders items after searching with `$in` operator
350
- */
351
- reorderItems(items, order) {
352
- if (this.property.kind === ReferenceKind.MANY_TO_MANY && this.property.owner) {
353
- items.sort((a, b) => order.indexOf(a) - order.indexOf(b));
354
- }
355
- }
356
- cancelOrphanRemoval(items) {
357
- const em = this.getEntityManager(items, false);
358
- if (!em) {
359
- return;
360
- }
361
- for (const item of items) {
362
- em.getUnitOfWork().cancelOrphanRemoval(item);
363
- }
364
- }
365
- validateModification(items) {
366
- if (this.#readonly) {
367
- throw ValidationError.cannotModifyReadonlyCollection(this.owner, this.property);
368
- }
369
- const check = (item) => {
370
- if (!item) {
371
- return false;
372
- }
373
- if (!Utils.isEntity(item)) {
374
- throw ValidationError.notEntity(this.owner, this.property, item);
375
- }
376
- // currently we allow persisting to inverse sides only in SQL drivers
377
- if (this.property.pivotTable || !this.property.mappedBy) {
378
- return false;
379
- }
380
- if (helper(item).__initialized) {
381
- return false;
382
- }
383
- return !item[this.property.mappedBy] && this.property.kind === ReferenceKind.MANY_TO_MANY;
384
- };
385
- // throw if we are modifying inverse side of M:N collection when owning side is initialized (would be ignored when persisting)
386
- if (items.some(item => check(item))) {
387
- throw ValidationError.cannotModifyInverseCollection(this.owner, this.property);
388
- }
389
- }
390
- /** Converts all items in the collection to plain DTO objects. */
391
- toArray() {
392
- if (this.#items.size === 0) {
393
- return [];
394
- }
395
- return this.map(item => wrap(item).toJSON());
396
- }
397
- /** Returns the primary key values (or a specific field) of all items in the collection. */
398
- getIdentifiers(field) {
399
- const items = this.getItems();
400
- const targetMeta = this.property.targetMeta;
401
- if (items.length === 0) {
402
- return [];
403
- }
404
- field ??= targetMeta.compositePK
405
- ? targetMeta.primaryKeys
406
- : (targetMeta.serializedPrimaryKey ?? targetMeta.primaryKeys[0]);
407
- const cb = (i, f) => {
408
- if (Utils.isEntity(i[f], true)) {
409
- return wrap(i[f], true).getPrimaryKey();
410
- }
411
- return i[f];
412
- };
413
- return items.map(i => {
414
- if (Array.isArray(field)) {
415
- return field.map(f => cb(i, f));
416
- }
417
- return cb(i, field);
418
- });
419
- }
420
- /**
421
- * @internal
422
- */
423
- addWithoutPropagation(entity) {
424
- if (!this.contains(entity, false)) {
425
- this.incrementCount(1);
426
- this[this.#items.size] = entity;
427
- this.#items.add(entity);
428
- this.#dirty = true;
429
- }
430
- }
431
- /** Replaces all items in the collection with the given items. */
432
- set(items) {
433
- if (!this.#initialized) {
434
- this.#initialized = true;
435
- this.#snapshot = undefined;
436
- }
437
- if (this.compare(Utils.asArray(items).map(item => Reference.unwrapReference(item)))) {
438
- return;
439
- }
440
- this.remove(this.#items);
441
- this.add(items);
442
- }
443
- compare(items) {
444
- if (items.length !== this.#items.size) {
445
- return false;
446
- }
447
- let idx = 0;
448
- for (const item of this.#items) {
449
- if (item !== items[idx++]) {
450
- return false;
451
- }
452
- }
453
- return true;
454
- }
455
- /**
456
- * @internal
457
- */
458
- hydrate(items, forcePropagate, partial) {
459
- for (let i = 0; i < this.#items.size; i++) {
460
- delete this[i];
461
- }
462
- this.#initialized = true;
463
- this.#partial = !!partial;
464
- this.#items.clear();
465
- this.#count = 0;
466
- this.add(items);
467
- this.takeSnapshot(forcePropagate);
468
- }
469
- /**
470
- * Remove all items from the collection. Note that removing items from collection does not necessarily imply deleting the target entity,
471
- * it means we are disconnecting the relation - removing items from collection, not removing entities from database - `Collection.remove()`
472
- * is not the same as `em.remove()`. If we want to delete the entity by removing it from collection, we need to enable `orphanRemoval: true`,
473
- * which tells the ORM we don't want orphaned entities to exist, so we know those should be removed.
474
- */
475
- removeAll() {
476
- if (!this.#initialized) {
477
- this.#initialized = true;
478
- this.#snapshot = undefined;
479
- }
480
- this.remove(this.#items);
10
+ owner;
11
+ #items = new Set();
12
+ #initialized = true;
13
+ #dirty = false;
14
+ #partial = false; // mark partially loaded collections, propagation is disabled for those
15
+ #snapshot = []; // used to create a diff of the collection at commit time, undefined marks overridden values so we need to wipe when flushing
16
+ #readonly;
17
+ #count;
18
+ #property;
19
+ #populated;
20
+ constructor(owner, items, initialized = true) {
21
+ this.owner = owner;
22
+ /* v8 ignore next */
23
+ if (items) {
24
+ let i = 0;
25
+ this.#items = new Set(items);
26
+ this.#items.forEach(item => (this[i++] = item));
27
+ }
28
+ this.#initialized = !!items || initialized;
29
+ }
30
+ /**
31
+ * Creates new Collection instance, assigns it to the owning entity and sets the items to it (propagating them to their inverse sides)
32
+ */
33
+ static create(owner, prop, items, initialized) {
34
+ const coll = new Collection(owner, undefined, initialized);
35
+ coll.property = helper(owner).__meta.properties[prop];
36
+ owner[prop] = coll;
37
+ if (items) {
38
+ coll.set(items);
39
+ }
40
+ return coll;
41
+ }
42
+ /**
43
+ * Ensures the collection is loaded first (without reloading it if it already is loaded).
44
+ * Returns the Collection instance (itself), works the same as `Reference.load()`.
45
+ */
46
+ async load(options = {}) {
47
+ if (this.isInitialized(true) && !options.refresh) {
48
+ const em = this.getEntityManager(this.#items, false);
49
+ options = { ...options, filters: QueryHelper.mergePropertyFilters(this.property.filters, options.filters) };
50
+ await em?.populate(this.#items, options.populate, options);
51
+ this.setSerializationContext(options);
52
+ } else {
53
+ await this.init({ refresh: false, ...options });
54
+ }
55
+ return this;
56
+ }
57
+ setSerializationContext(options) {
58
+ helper(this.owner).setSerializationContext({
59
+ populate: Array.isArray(options.populate)
60
+ ? options.populate.map(hint => `${this.property.name}.${hint}`)
61
+ : (options.populate ?? [this.property.name]),
62
+ });
63
+ }
64
+ /**
65
+ * Initializes the collection and returns the items
66
+ */
67
+ async loadItems(options) {
68
+ await this.load(options);
69
+ return this.getItems(false);
70
+ }
71
+ /**
72
+ * Gets the count of collection items from database instead of counting loaded items.
73
+ * The value is cached (unless you use the `where` option), use `refresh: true` to force reload it.
74
+ */
75
+ async loadCount(options = {}) {
76
+ options = typeof options === 'boolean' ? { refresh: options } : options;
77
+ const { refresh, where, ...countOptions } = options;
78
+ if (!refresh && !where && this.#count != null) {
79
+ return this.#count;
80
+ }
81
+ const em = this.getEntityManager();
82
+ if (
83
+ !em.getPlatform().usesPivotTable() &&
84
+ this.property.kind === ReferenceKind.MANY_TO_MANY &&
85
+ this.property.owner
86
+ ) {
87
+ return (this.#count = this.length);
88
+ }
89
+ const cond = this.createLoadCountCondition(where ?? {});
90
+ const count = await em.count(this.property.targetMeta.class, cond, countOptions);
91
+ if (!where) {
92
+ this.#count = count;
93
+ }
94
+ return count;
95
+ }
96
+ /** Queries a subset of the collection items from the database with custom filtering, ordering, and pagination. */
97
+ async matching(options) {
98
+ const em = this.getEntityManager();
99
+ const { where, ctx, ...opts } = options;
100
+ let items;
101
+ if (this.property.kind === ReferenceKind.MANY_TO_MANY && em.getPlatform().usesPivotTable()) {
102
+ // M:N via pivot table bypasses em.find(), so merge all 3 levels here
103
+ opts.orderBy = QueryHelper.mergeOrderBy(opts.orderBy, this.property.orderBy, this.property.targetMeta?.orderBy);
104
+ options.populate = await em.preparePopulate(this.property.targetMeta.class, options);
105
+ const cond = await em.applyFilters(this.property.targetMeta.class, where, options.filters ?? {}, 'read');
106
+ const map = await em
107
+ .getDriver()
108
+ .loadFromPivotTable(this.property, [helper(this.owner).__primaryKeys], cond, opts.orderBy, ctx, options);
109
+ items = map[helper(this.owner).getSerializedPrimaryKey()].map(item =>
110
+ em.merge(this.property.targetMeta.class, item, { convertCustomTypes: true }),
111
+ );
112
+ await em.populate(items, options.populate, options);
113
+ } else {
114
+ // em.find() merges entity-level orderBy, so only merge runtime + relation here
115
+ opts.orderBy = QueryHelper.mergeOrderBy(opts.orderBy, this.property.orderBy);
116
+ items = await em.find(this.property.targetMeta.class, this.createCondition(where), opts);
117
+ }
118
+ if (options.store) {
119
+ this.hydrate(items, true);
120
+ this.setSerializationContext(options);
121
+ this.populated();
122
+ this.#readonly = true;
123
+ }
124
+ return items;
125
+ }
126
+ /**
127
+ * Returns the items (the collection must be initialized)
128
+ */
129
+ getItems(check = true) {
130
+ if (check) {
131
+ this.checkInitialized();
132
+ }
133
+ return [...this.#items];
134
+ }
135
+ /** Serializes the collection items to plain JSON objects. Returns an empty array if not initialized. */
136
+ toJSON() {
137
+ if (!this.isInitialized()) {
138
+ return [];
139
+ }
140
+ return this.toArray();
141
+ }
142
+ /** Adds one or more items to the collection, propagating the change to the inverse side. Returns the number of items added. */
143
+ add(entity, ...entities) {
144
+ entities = Utils.asArray(entity).concat(entities);
145
+ const unwrapped = entities.map(i => Reference.unwrapReference(i));
146
+ this.validateModification(unwrapped);
147
+ const em = this.getEntityManager(entities, false);
148
+ let added = 0;
149
+ for (const item of entities) {
150
+ const entity = Reference.unwrapReference(item);
151
+ if (!this.contains(entity, false)) {
152
+ this.incrementCount(1);
153
+ this[this.#items.size] = entity;
154
+ this.#items.add(entity);
155
+ added++;
481
156
  this.#dirty = true;
482
- }
483
- /**
484
- * @internal
485
- */
486
- removeWithoutPropagation(entity) {
487
- if (!this.#items.delete(entity)) {
488
- return;
489
- }
157
+ this.propagate(entity, 'add');
158
+ }
159
+ }
160
+ if (this.property.kind === ReferenceKind.ONE_TO_MANY && em) {
161
+ em.persist(entities);
162
+ }
163
+ this.cancelOrphanRemoval(unwrapped);
164
+ return added;
165
+ }
166
+ /**
167
+ * Remove specified item(s) from the collection. Note that removing item from collection does not necessarily imply deleting the target entity,
168
+ * it means we are disconnecting the relation - removing items from collection, not removing entities from database - `Collection.remove()`
169
+ * is not the same as `em.remove()`. If we want to delete the entity by removing it from collection, we need to enable `orphanRemoval: true`,
170
+ * which tells the ORM we don't want orphaned entities to exist, so we know those should be removed.
171
+ */
172
+ remove(entity, ...entities) {
173
+ if (entity instanceof Function) {
174
+ let removed = 0;
175
+ for (const item of this.#items) {
176
+ if (entity(item)) {
177
+ removed += this.remove(item);
178
+ }
179
+ }
180
+ return removed;
181
+ }
182
+ this.checkInitialized();
183
+ entities = Utils.asArray(entity).concat(entities);
184
+ const unwrapped = entities.map(i => Reference.unwrapReference(i));
185
+ this.validateModification(unwrapped);
186
+ const em = this.getEntityManager(entities, false);
187
+ let removed = 0;
188
+ for (const item of entities) {
189
+ if (!item) {
190
+ continue;
191
+ }
192
+ const entity = Reference.unwrapReference(item);
193
+ if (this.#items.delete(entity)) {
490
194
  this.incrementCount(-1);
491
- delete this[this.#items.size];
492
- Object.assign(this, [...this.#items]);
195
+ delete this[this.#items.size]; // remove last item
196
+ this.propagate(entity, 'remove');
197
+ removed++;
493
198
  this.#dirty = true;
494
- }
495
- /**
496
- * Extracts a slice of the collection items starting at position start to end (exclusive) of the collection.
497
- * If end is null it returns all elements from start to the end of the collection.
498
- */
499
- slice(start = 0, end) {
500
- this.checkInitialized();
501
- let index = 0;
502
- end ??= this.#items.size;
503
- const items = [];
504
- for (const item of this.#items) {
505
- if (index === end) {
506
- break;
507
- }
508
- if (index >= start && index < end) {
509
- items.push(item);
510
- }
511
- index++;
512
- }
513
- return items;
514
- }
515
- /**
516
- * Tests for the existence of an element that satisfies the given predicate.
517
- */
518
- exists(cb) {
519
- this.checkInitialized();
520
- for (const item of this.#items) {
521
- if (cb(item)) {
522
- return true;
523
- }
199
+ }
200
+ if (this.property.orphanRemoval && em) {
201
+ em.getUnitOfWork().scheduleOrphanRemoval(entity);
202
+ }
203
+ }
204
+ if (this.property.kind === ReferenceKind.ONE_TO_MANY && !this.property.orphanRemoval && em) {
205
+ em.persist(entities);
206
+ }
207
+ if (removed > 0) {
208
+ Object.assign(this, [...this.#items]); // reassign array access
209
+ }
210
+ return removed;
211
+ }
212
+ /** Checks whether the collection contains the given item. */
213
+ contains(item, check = true) {
214
+ if (check) {
215
+ this.checkInitialized();
216
+ }
217
+ const entity = Reference.unwrapReference(item);
218
+ return this.#items.has(entity);
219
+ }
220
+ /** Returns the number of items in the collection. Throws if the collection is not initialized. */
221
+ count() {
222
+ this.checkInitialized();
223
+ return this.#items.size;
224
+ }
225
+ /** Returns true if the collection has no items. Throws if the collection is not initialized. */
226
+ isEmpty() {
227
+ this.checkInitialized();
228
+ return this.count() === 0;
229
+ }
230
+ /** Returns whether this collection should be included in serialization based on its populated state. */
231
+ shouldPopulate(populated) {
232
+ if (!this.isInitialized(true)) {
233
+ return false;
234
+ }
235
+ if (this.#populated != null) {
236
+ return this.#populated;
237
+ }
238
+ return !!populated;
239
+ }
240
+ /** Marks the collection as populated or not for serialization purposes. */
241
+ populated(populated = true) {
242
+ this.#populated = populated;
243
+ }
244
+ /** Initializes the collection by loading its items from the database. */
245
+ async init(options = {}) {
246
+ if (this.#dirty) {
247
+ const items = [...this.#items];
248
+ this.#dirty = false;
249
+ await this.init(options);
250
+ items.forEach(i => this.add(i));
251
+ return this;
252
+ }
253
+ const em = this.getEntityManager();
254
+ options = { ...options, filters: QueryHelper.mergePropertyFilters(this.property.filters, options.filters) };
255
+ if (options.dataloader ?? [DataloaderType.ALL, DataloaderType.COLLECTION].includes(em.config.getDataloaderType())) {
256
+ const order = [...this.#items]; // copy order of references
257
+ const orderBy = QueryHelper.mergeOrderBy(
258
+ options.orderBy,
259
+ this.property.orderBy,
260
+ this.property.targetMeta?.orderBy,
261
+ );
262
+ const customOrder = orderBy.length > 0;
263
+ const pivotTable = this.property.kind === ReferenceKind.MANY_TO_MANY && em.getPlatform().usesPivotTable();
264
+ const loader = await em.getDataLoader(pivotTable ? 'm:n' : '1:m');
265
+ const items = await loader.load([this, { ...options, orderBy }]);
266
+ if (this.property.kind === ReferenceKind.MANY_TO_MANY) {
267
+ this.#initialized = true;
268
+ this.#dirty = false;
269
+ if (!customOrder) {
270
+ this.reorderItems(items, order);
524
271
  }
272
+ return this;
273
+ }
274
+ this.#items.clear();
275
+ let i = 0;
276
+ for (const item of items) {
277
+ this.#items.add(item);
278
+ this[i++] = item;
279
+ }
280
+ this.#initialized = true;
281
+ this.#dirty = false;
282
+ return this;
283
+ }
284
+ const populate = Array.isArray(options.populate)
285
+ ? options.populate.map(f => (f === '*' ? f : `${this.property.name}.${f}`))
286
+ : [`${this.property.name}${options.ref ? ':ref' : ''}`];
287
+ const schema = this.property.targetMeta.schema === '*' ? helper(this.owner).__schema : undefined;
288
+ await em.populate(this.owner, populate, {
289
+ refresh: true,
290
+ ...options,
291
+ connectionType: options.connectionType,
292
+ schema,
293
+ where: { [this.property.name]: options.where },
294
+ orderBy: { [this.property.name]: options.orderBy },
295
+ });
296
+ return this;
297
+ }
298
+ getEntityManager(items = [], required = true) {
299
+ const wrapped = helper(this.owner);
300
+ let em = wrapped.__em;
301
+ if (!em) {
302
+ for (const i of items) {
303
+ if (i && helper(i).__em) {
304
+ em = helper(i).__em;
305
+ break;
306
+ }
307
+ }
308
+ }
309
+ if (!em && required) {
310
+ throw ValidationError.entityNotManaged(this.owner);
311
+ }
312
+ return em;
313
+ }
314
+ createCondition(cond = {}) {
315
+ if (this.property.kind === ReferenceKind.ONE_TO_MANY) {
316
+ cond[this.property.mappedBy] = helper(this.owner).getPrimaryKey();
317
+ } else {
318
+ // MANY_TO_MANY
319
+ this.createManyToManyCondition(cond);
320
+ }
321
+ return cond;
322
+ }
323
+ createManyToManyCondition(cond) {
324
+ const dict = cond;
325
+ if (this.property.owner || this.property.pivotTable) {
326
+ // we know there is at least one item as it was checked in load method
327
+ const pk = this.property.targetMeta.primaryKeys[0];
328
+ dict[pk] = { $in: [] };
329
+ this.#items.forEach(item => dict[pk].$in.push(helper(item).getPrimaryKey()));
330
+ } else {
331
+ dict[this.property.mappedBy] = helper(this.owner).getPrimaryKey();
332
+ }
333
+ }
334
+ createLoadCountCondition(cond) {
335
+ const wrapped = helper(this.owner);
336
+ const val = wrapped.__meta.compositePK ? { $in: wrapped.__primaryKeys } : wrapped.getPrimaryKey();
337
+ const dict = cond;
338
+ if (this.property.kind === ReferenceKind.ONE_TO_MANY) {
339
+ dict[this.property.mappedBy] = val;
340
+ } else {
341
+ const key = this.property.owner ? this.property.inversedBy : this.property.mappedBy;
342
+ dict[key] = val;
343
+ }
344
+ return cond;
345
+ }
346
+ checkInitialized() {
347
+ if (!this.isInitialized()) {
348
+ throw new Error(
349
+ `Collection<${this.property.type}> of entity ${helper(this.owner).__meta.name}[${helper(this.owner).getSerializedPrimaryKey()}] not initialized`,
350
+ );
351
+ }
352
+ }
353
+ /**
354
+ * re-orders items after searching with `$in` operator
355
+ */
356
+ reorderItems(items, order) {
357
+ if (this.property.kind === ReferenceKind.MANY_TO_MANY && this.property.owner) {
358
+ items.sort((a, b) => order.indexOf(a) - order.indexOf(b));
359
+ }
360
+ }
361
+ cancelOrphanRemoval(items) {
362
+ const em = this.getEntityManager(items, false);
363
+ if (!em) {
364
+ return;
365
+ }
366
+ for (const item of items) {
367
+ em.getUnitOfWork().cancelOrphanRemoval(item);
368
+ }
369
+ }
370
+ validateModification(items) {
371
+ if (this.#readonly) {
372
+ throw ValidationError.cannotModifyReadonlyCollection(this.owner, this.property);
373
+ }
374
+ const check = item => {
375
+ if (!item) {
525
376
  return false;
526
- }
527
- /**
528
- * Returns the first element of this collection that satisfies the predicate.
529
- */
530
- find(cb) {
531
- this.checkInitialized();
532
- let index = 0;
533
- for (const item of this.#items) {
534
- if (cb(item, index++)) {
535
- return item;
536
- }
537
- }
538
- return undefined;
539
- }
540
- /**
541
- * Extracts a subset of the collection items.
542
- */
543
- filter(cb) {
544
- this.checkInitialized();
545
- const items = [];
546
- let index = 0;
547
- for (const item of this.#items) {
548
- if (cb(item, index++)) {
549
- items.push(item);
550
- }
551
- }
552
- return items;
553
- }
554
- /**
555
- * Maps the collection items based on your provided mapper function.
556
- */
557
- map(mapper) {
558
- this.checkInitialized();
559
- const items = [];
560
- let index = 0;
561
- for (const item of this.#items) {
562
- items.push(mapper(item, index++));
563
- }
564
- return items;
565
- }
566
- /**
567
- * Maps the collection items based on your provided mapper function to a single object.
568
- */
569
- reduce(cb, initial = {}) {
570
- this.checkInitialized();
571
- let index = 0;
572
- for (const item of this.#items) {
573
- initial = cb(initial, item, index++);
574
- }
575
- return initial;
576
- }
577
- /**
578
- * Maps the collection items to a dictionary, indexed by the key you specify.
579
- * If there are more items with the same key, only the first one will be present.
580
- */
581
- indexBy(key, valueKey) {
582
- return this.reduce((obj, item) => {
583
- obj[item[key]] ??= valueKey ? item[valueKey] : item;
584
- return obj;
585
- }, {});
586
- }
587
- /** Returns whether the collection has been initialized. Pass `fully = true` to also check that all items are initialized. */
588
- isInitialized(fully = false) {
589
- if (!this.#initialized || !fully) {
590
- return this.#initialized;
591
- }
592
- for (const item of this.#items) {
593
- if (!helper(item).__initialized) {
594
- return false;
595
- }
596
- }
377
+ }
378
+ if (!Utils.isEntity(item)) {
379
+ throw ValidationError.notEntity(this.owner, this.property, item);
380
+ }
381
+ // currently we allow persisting to inverse sides only in SQL drivers
382
+ if (this.property.pivotTable || !this.property.mappedBy) {
383
+ return false;
384
+ }
385
+ if (helper(item).__initialized) {
386
+ return false;
387
+ }
388
+ return !item[this.property.mappedBy] && this.property.kind === ReferenceKind.MANY_TO_MANY;
389
+ };
390
+ // throw if we are modifying inverse side of M:N collection when owning side is initialized (would be ignored when persisting)
391
+ if (items.some(item => check(item))) {
392
+ throw ValidationError.cannotModifyInverseCollection(this.owner, this.property);
393
+ }
394
+ }
395
+ /** Converts all items in the collection to plain DTO objects. */
396
+ toArray() {
397
+ if (this.#items.size === 0) {
398
+ return [];
399
+ }
400
+ return this.map(item => wrap(item).toJSON());
401
+ }
402
+ /** Returns the primary key values (or a specific field) of all items in the collection. */
403
+ getIdentifiers(field) {
404
+ const items = this.getItems();
405
+ const targetMeta = this.property.targetMeta;
406
+ if (items.length === 0) {
407
+ return [];
408
+ }
409
+ field ??= targetMeta.compositePK
410
+ ? targetMeta.primaryKeys
411
+ : (targetMeta.serializedPrimaryKey ?? targetMeta.primaryKeys[0]);
412
+ const cb = (i, f) => {
413
+ if (Utils.isEntity(i[f], true)) {
414
+ return wrap(i[f], true).getPrimaryKey();
415
+ }
416
+ return i[f];
417
+ };
418
+ return items.map(i => {
419
+ if (Array.isArray(field)) {
420
+ return field.map(f => cb(i, f));
421
+ }
422
+ return cb(i, field);
423
+ });
424
+ }
425
+ /**
426
+ * @internal
427
+ */
428
+ addWithoutPropagation(entity) {
429
+ if (!this.contains(entity, false)) {
430
+ this.incrementCount(1);
431
+ this[this.#items.size] = entity;
432
+ this.#items.add(entity);
433
+ this.#dirty = true;
434
+ }
435
+ }
436
+ /** Replaces all items in the collection with the given items. */
437
+ set(items) {
438
+ if (!this.#initialized) {
439
+ this.#initialized = true;
440
+ this.#snapshot = undefined;
441
+ }
442
+ if (this.compare(Utils.asArray(items).map(item => Reference.unwrapReference(item)))) {
443
+ return;
444
+ }
445
+ this.remove(this.#items);
446
+ this.add(items);
447
+ }
448
+ compare(items) {
449
+ if (items.length !== this.#items.size) {
450
+ return false;
451
+ }
452
+ let idx = 0;
453
+ for (const item of this.#items) {
454
+ if (item !== items[idx++]) {
455
+ return false;
456
+ }
457
+ }
458
+ return true;
459
+ }
460
+ /**
461
+ * @internal
462
+ */
463
+ hydrate(items, forcePropagate, partial) {
464
+ for (let i = 0; i < this.#items.size; i++) {
465
+ delete this[i];
466
+ }
467
+ this.#initialized = true;
468
+ this.#partial = !!partial;
469
+ this.#items.clear();
470
+ this.#count = 0;
471
+ this.add(items);
472
+ this.takeSnapshot(forcePropagate);
473
+ }
474
+ /**
475
+ * Remove all items from the collection. Note that removing items from collection does not necessarily imply deleting the target entity,
476
+ * it means we are disconnecting the relation - removing items from collection, not removing entities from database - `Collection.remove()`
477
+ * is not the same as `em.remove()`. If we want to delete the entity by removing it from collection, we need to enable `orphanRemoval: true`,
478
+ * which tells the ORM we don't want orphaned entities to exist, so we know those should be removed.
479
+ */
480
+ removeAll() {
481
+ if (!this.#initialized) {
482
+ this.#initialized = true;
483
+ this.#snapshot = undefined;
484
+ }
485
+ this.remove(this.#items);
486
+ this.#dirty = true;
487
+ }
488
+ /**
489
+ * @internal
490
+ */
491
+ removeWithoutPropagation(entity) {
492
+ if (!this.#items.delete(entity)) {
493
+ return;
494
+ }
495
+ this.incrementCount(-1);
496
+ delete this[this.#items.size];
497
+ Object.assign(this, [...this.#items]);
498
+ this.#dirty = true;
499
+ }
500
+ /**
501
+ * Extracts a slice of the collection items starting at position start to end (exclusive) of the collection.
502
+ * If end is null it returns all elements from start to the end of the collection.
503
+ */
504
+ slice(start = 0, end) {
505
+ this.checkInitialized();
506
+ let index = 0;
507
+ end ??= this.#items.size;
508
+ const items = [];
509
+ for (const item of this.#items) {
510
+ if (index === end) {
511
+ break;
512
+ }
513
+ if (index >= start && index < end) {
514
+ items.push(item);
515
+ }
516
+ index++;
517
+ }
518
+ return items;
519
+ }
520
+ /**
521
+ * Tests for the existence of an element that satisfies the given predicate.
522
+ */
523
+ exists(cb) {
524
+ this.checkInitialized();
525
+ for (const item of this.#items) {
526
+ if (cb(item)) {
597
527
  return true;
598
- }
599
- isDirty() {
600
- return this.#dirty;
601
- }
602
- /** Returns whether the collection was partially loaded (propagation is disabled for partial collections). */
603
- isPartial() {
604
- return this.#partial;
605
- }
606
- setDirty(dirty = true) {
607
- this.#dirty = dirty;
608
- }
609
- get length() {
610
- return this.count();
611
- }
612
- *[Symbol.iterator]() {
613
- for (const item of this.getItems()) {
614
- yield item;
615
- }
616
- }
617
- /**
618
- * @internal
619
- */
620
- takeSnapshot(forcePropagate) {
621
- this.#snapshot = [...this.#items];
622
- this.#dirty = false;
623
- if (this.property.owner || forcePropagate) {
624
- this.#items.forEach(item => {
625
- this.propagate(item, 'takeSnapshot');
626
- });
627
- }
628
- }
629
- /**
630
- * @internal
631
- */
632
- getSnapshot() {
633
- return this.#snapshot;
634
- }
635
- /**
636
- * @internal
637
- */
638
- get property() {
639
- // cannot be typed to `EntityProperty<O, T>` as it causes issues in assignability of `Loaded` type
640
- if (!this.#property) {
641
- const meta = wrap(this.owner, true).__meta;
642
- /* v8 ignore next */
643
- if (!meta) {
644
- throw MetadataError.fromUnknownEntity(this.owner.constructor.name, 'Collection.property getter, maybe you just forgot to initialize the ORM?');
645
- }
646
- this.#property = meta.relations.find(prop => this.owner[prop.name] === this);
647
- }
648
- return this.#property;
649
- }
650
- /**
651
- * @internal
652
- */
653
- set property(prop) {
654
- // cannot be typed to `EntityProperty<O, T>` as it causes issues in assignability of `Loaded` type
655
- this.#property = prop;
656
- }
657
- propagate(item, method) {
658
- if (this.property.owner && this.property.inversedBy) {
659
- this.propagateToInverseSide(item, method);
660
- }
661
- else if (!this.property.owner && this.property.mappedBy) {
662
- this.propagateToOwningSide(item, method);
663
- }
664
- }
665
- propagateToInverseSide(item, method) {
666
- const collection = item[this.property.inversedBy];
667
- if (this.shouldPropagateToCollection(collection, method)) {
668
- method = method === 'takeSnapshot' ? method : (method + 'WithoutPropagation');
669
- collection[method](this.owner);
670
- }
671
- }
672
- propagateToOwningSide(item, method) {
673
- const mappedBy = this.property.mappedBy;
674
- const collection = item[mappedBy];
675
- if (this.property.kind === ReferenceKind.MANY_TO_MANY) {
676
- if (this.shouldPropagateToCollection(collection, method)) {
677
- collection[method](this.owner);
678
- }
679
- }
680
- else if (this.property.kind === ReferenceKind.ONE_TO_MANY && method !== 'takeSnapshot') {
681
- const prop2 = this.property.targetMeta.properties[mappedBy];
682
- const owner = prop2.mapToPk ? helper(this.owner).getPrimaryKey() : this.owner;
683
- const value = method === 'add' ? owner : null;
684
- if (this.property.orphanRemoval && method === 'remove') {
685
- // cache the PK before we propagate, as its value might be needed when flushing
686
- helper(item).__pk = helper(item).getPrimaryKey();
687
- }
688
- if (!prop2.nullable && prop2.deleteRule !== 'cascade' && method === 'remove') {
689
- if (!this.property.orphanRemoval) {
690
- throw ValidationError.cannotRemoveFromCollectionWithoutOrphanRemoval(this.owner, this.property);
691
- }
692
- return;
693
- }
694
- // skip if already propagated
695
- if (Reference.unwrapReference(item[mappedBy]) !== value) {
696
- item[mappedBy] = value;
697
- }
698
- }
699
- }
700
- shouldPropagateToCollection(collection, method) {
701
- if (!collection) {
702
- return false;
703
- }
704
- switch (method) {
705
- case 'add':
706
- return !collection.contains(this.owner, false);
707
- case 'remove':
708
- return collection.isInitialized() && collection.contains(this.owner, false);
709
- case 'takeSnapshot':
710
- return collection.isDirty();
711
- }
712
- }
713
- incrementCount(value) {
714
- if (typeof this.#count === 'number' && this.#initialized) {
715
- this.#count += value;
716
- }
717
- }
718
- /** @ignore */
719
- [Symbol.for('nodejs.util.inspect.custom')](depth = 2) {
720
- const object = { ...this };
721
- delete object.owner;
722
- object.initialized = this.#initialized;
723
- object.dirty = this.#dirty;
724
- const ret = inspect(object, { depth });
725
- const name = `${this.constructor.name}<${this.property?.type ?? 'unknown'}>`;
726
- return ret === '[Object]' ? `[${name}]` : name + ' ' + ret;
727
- }
528
+ }
529
+ }
530
+ return false;
531
+ }
532
+ /**
533
+ * Returns the first element of this collection that satisfies the predicate.
534
+ */
535
+ find(cb) {
536
+ this.checkInitialized();
537
+ let index = 0;
538
+ for (const item of this.#items) {
539
+ if (cb(item, index++)) {
540
+ return item;
541
+ }
542
+ }
543
+ return undefined;
544
+ }
545
+ /**
546
+ * Extracts a subset of the collection items.
547
+ */
548
+ filter(cb) {
549
+ this.checkInitialized();
550
+ const items = [];
551
+ let index = 0;
552
+ for (const item of this.#items) {
553
+ if (cb(item, index++)) {
554
+ items.push(item);
555
+ }
556
+ }
557
+ return items;
558
+ }
559
+ /**
560
+ * Maps the collection items based on your provided mapper function.
561
+ */
562
+ map(mapper) {
563
+ this.checkInitialized();
564
+ const items = [];
565
+ let index = 0;
566
+ for (const item of this.#items) {
567
+ items.push(mapper(item, index++));
568
+ }
569
+ return items;
570
+ }
571
+ /**
572
+ * Maps the collection items based on your provided mapper function to a single object.
573
+ */
574
+ reduce(cb, initial = {}) {
575
+ this.checkInitialized();
576
+ let index = 0;
577
+ for (const item of this.#items) {
578
+ initial = cb(initial, item, index++);
579
+ }
580
+ return initial;
581
+ }
582
+ /**
583
+ * Maps the collection items to a dictionary, indexed by the key you specify.
584
+ * If there are more items with the same key, only the first one will be present.
585
+ */
586
+ indexBy(key, valueKey) {
587
+ return this.reduce((obj, item) => {
588
+ obj[item[key]] ??= valueKey ? item[valueKey] : item;
589
+ return obj;
590
+ }, {});
591
+ }
592
+ /** Returns whether the collection has been initialized. Pass `fully = true` to also check that all items are initialized. */
593
+ isInitialized(fully = false) {
594
+ if (!this.#initialized || !fully) {
595
+ return this.#initialized;
596
+ }
597
+ for (const item of this.#items) {
598
+ if (!helper(item).__initialized) {
599
+ return false;
600
+ }
601
+ }
602
+ return true;
603
+ }
604
+ isDirty() {
605
+ return this.#dirty;
606
+ }
607
+ /** Returns whether the collection was partially loaded (propagation is disabled for partial collections). */
608
+ isPartial() {
609
+ return this.#partial;
610
+ }
611
+ setDirty(dirty = true) {
612
+ this.#dirty = dirty;
613
+ }
614
+ get length() {
615
+ return this.count();
616
+ }
617
+ *[Symbol.iterator]() {
618
+ for (const item of this.getItems()) {
619
+ yield item;
620
+ }
621
+ }
622
+ /**
623
+ * @internal
624
+ */
625
+ takeSnapshot(forcePropagate) {
626
+ this.#snapshot = [...this.#items];
627
+ this.#dirty = false;
628
+ if (this.property.owner || forcePropagate) {
629
+ this.#items.forEach(item => {
630
+ this.propagate(item, 'takeSnapshot');
631
+ });
632
+ }
633
+ }
634
+ /**
635
+ * @internal
636
+ */
637
+ getSnapshot() {
638
+ return this.#snapshot;
639
+ }
640
+ /**
641
+ * @internal
642
+ */
643
+ get property() {
644
+ // cannot be typed to `EntityProperty<O, T>` as it causes issues in assignability of `Loaded` type
645
+ if (!this.#property) {
646
+ const meta = wrap(this.owner, true).__meta;
647
+ /* v8 ignore next */
648
+ if (!meta) {
649
+ throw MetadataError.fromUnknownEntity(
650
+ this.owner.constructor.name,
651
+ 'Collection.property getter, maybe you just forgot to initialize the ORM?',
652
+ );
653
+ }
654
+ this.#property = meta.relations.find(prop => this.owner[prop.name] === this);
655
+ }
656
+ return this.#property;
657
+ }
658
+ /**
659
+ * @internal
660
+ */
661
+ set property(prop) {
662
+ // cannot be typed to `EntityProperty<O, T>` as it causes issues in assignability of `Loaded` type
663
+ this.#property = prop;
664
+ }
665
+ propagate(item, method) {
666
+ if (this.property.owner && this.property.inversedBy) {
667
+ this.propagateToInverseSide(item, method);
668
+ } else if (!this.property.owner && this.property.mappedBy) {
669
+ this.propagateToOwningSide(item, method);
670
+ }
671
+ }
672
+ propagateToInverseSide(item, method) {
673
+ const collection = item[this.property.inversedBy];
674
+ if (this.shouldPropagateToCollection(collection, method)) {
675
+ method = method === 'takeSnapshot' ? method : method + 'WithoutPropagation';
676
+ collection[method](this.owner);
677
+ }
678
+ }
679
+ propagateToOwningSide(item, method) {
680
+ const mappedBy = this.property.mappedBy;
681
+ const collection = item[mappedBy];
682
+ if (this.property.kind === ReferenceKind.MANY_TO_MANY) {
683
+ if (this.shouldPropagateToCollection(collection, method)) {
684
+ collection[method](this.owner);
685
+ }
686
+ } else if (this.property.kind === ReferenceKind.ONE_TO_MANY && method !== 'takeSnapshot') {
687
+ const prop2 = this.property.targetMeta.properties[mappedBy];
688
+ const owner = prop2.mapToPk ? helper(this.owner).getPrimaryKey() : this.owner;
689
+ const value = method === 'add' ? owner : null;
690
+ if (this.property.orphanRemoval && method === 'remove') {
691
+ // cache the PK before we propagate, as its value might be needed when flushing
692
+ helper(item).__pk = helper(item).getPrimaryKey();
693
+ }
694
+ if (!prop2.nullable && prop2.deleteRule !== 'cascade' && method === 'remove') {
695
+ if (!this.property.orphanRemoval) {
696
+ throw ValidationError.cannotRemoveFromCollectionWithoutOrphanRemoval(this.owner, this.property);
697
+ }
698
+ return;
699
+ }
700
+ // skip if already propagated
701
+ if (Reference.unwrapReference(item[mappedBy]) !== value) {
702
+ item[mappedBy] = value;
703
+ }
704
+ }
705
+ }
706
+ shouldPropagateToCollection(collection, method) {
707
+ if (!collection) {
708
+ return false;
709
+ }
710
+ switch (method) {
711
+ case 'add':
712
+ return !collection.contains(this.owner, false);
713
+ case 'remove':
714
+ return collection.isInitialized() && collection.contains(this.owner, false);
715
+ case 'takeSnapshot':
716
+ return collection.isDirty();
717
+ }
718
+ }
719
+ incrementCount(value) {
720
+ if (typeof this.#count === 'number' && this.#initialized) {
721
+ this.#count += value;
722
+ }
723
+ }
724
+ /** @ignore */
725
+ [Symbol.for('nodejs.util.inspect.custom')](depth = 2) {
726
+ const object = { ...this };
727
+ delete object.owner;
728
+ object.initialized = this.#initialized;
729
+ object.dirty = this.#dirty;
730
+ const ret = inspect(object, { depth });
731
+ const name = `${this.constructor.name}<${this.property?.type ?? 'unknown'}>`;
732
+ return ret === '[Object]' ? `[${name}]` : name + ' ' + ret;
733
+ }
728
734
  }
729
735
  Object.defineProperties(Collection.prototype, {
730
- $: {
731
- get() {
732
- return this;
733
- },
736
+ $: {
737
+ get() {
738
+ return this;
734
739
  },
735
- get: {
736
- get() {
737
- return () => this;
738
- },
740
+ },
741
+ get: {
742
+ get() {
743
+ return () => this;
739
744
  },
740
- __collection: { value: true, enumerable: false, writable: false },
745
+ },
746
+ __collection: { value: true, enumerable: false, writable: false },
741
747
  });