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