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

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