@mikro-orm/core 7.0.0-dev.9 → 7.0.0-dev.90

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 (191) hide show
  1. package/EntityManager.d.ts +77 -48
  2. package/EntityManager.js +288 -225
  3. package/MikroORM.d.ts +40 -31
  4. package/MikroORM.js +98 -137
  5. package/README.md +3 -2
  6. package/cache/FileCacheAdapter.d.ts +1 -1
  7. package/cache/FileCacheAdapter.js +6 -5
  8. package/cache/GeneratedCacheAdapter.d.ts +0 -1
  9. package/cache/GeneratedCacheAdapter.js +0 -2
  10. package/cache/index.d.ts +0 -1
  11. package/cache/index.js +0 -1
  12. package/connections/Connection.d.ts +11 -7
  13. package/connections/Connection.js +16 -14
  14. package/drivers/DatabaseDriver.d.ts +11 -5
  15. package/drivers/DatabaseDriver.js +23 -11
  16. package/drivers/IDatabaseDriver.d.ts +25 -4
  17. package/entity/BaseEntity.d.ts +0 -1
  18. package/entity/BaseEntity.js +0 -3
  19. package/entity/Collection.d.ts +95 -30
  20. package/entity/Collection.js +432 -93
  21. package/entity/EntityAssigner.d.ts +1 -1
  22. package/entity/EntityAssigner.js +17 -9
  23. package/entity/EntityFactory.d.ts +7 -0
  24. package/entity/EntityFactory.js +63 -41
  25. package/entity/EntityHelper.js +26 -12
  26. package/entity/EntityLoader.d.ts +5 -4
  27. package/entity/EntityLoader.js +63 -38
  28. package/entity/EntityRepository.d.ts +1 -1
  29. package/entity/Reference.d.ts +6 -5
  30. package/entity/Reference.js +34 -9
  31. package/entity/WrappedEntity.d.ts +2 -7
  32. package/entity/WrappedEntity.js +2 -7
  33. package/entity/defineEntity.d.ts +568 -0
  34. package/entity/defineEntity.js +529 -0
  35. package/entity/index.d.ts +3 -2
  36. package/entity/index.js +3 -2
  37. package/entity/utils.d.ts +7 -0
  38. package/entity/utils.js +16 -4
  39. package/entity/validators.d.ts +11 -0
  40. package/entity/validators.js +65 -0
  41. package/enums.d.ts +21 -6
  42. package/enums.js +14 -1
  43. package/errors.d.ts +10 -2
  44. package/errors.js +29 -10
  45. package/events/EventManager.d.ts +2 -1
  46. package/events/EventManager.js +19 -11
  47. package/events/EventSubscriber.d.ts +3 -1
  48. package/hydration/Hydrator.js +1 -2
  49. package/hydration/ObjectHydrator.d.ts +4 -4
  50. package/hydration/ObjectHydrator.js +35 -25
  51. package/index.d.ts +2 -2
  52. package/index.js +1 -2
  53. package/logging/DefaultLogger.d.ts +1 -1
  54. package/logging/DefaultLogger.js +1 -0
  55. package/logging/SimpleLogger.d.ts +1 -1
  56. package/logging/index.d.ts +1 -0
  57. package/logging/index.js +1 -0
  58. package/logging/inspect.d.ts +2 -0
  59. package/logging/inspect.js +16 -0
  60. package/metadata/EntitySchema.d.ts +9 -13
  61. package/metadata/EntitySchema.js +44 -26
  62. package/metadata/MetadataDiscovery.d.ts +6 -9
  63. package/metadata/MetadataDiscovery.js +165 -205
  64. package/metadata/MetadataProvider.d.ts +11 -2
  65. package/metadata/MetadataProvider.js +44 -2
  66. package/metadata/MetadataStorage.d.ts +1 -6
  67. package/metadata/MetadataStorage.js +6 -18
  68. package/metadata/MetadataValidator.d.ts +0 -7
  69. package/metadata/MetadataValidator.js +0 -10
  70. package/metadata/discover-entities.d.ts +5 -0
  71. package/metadata/discover-entities.js +40 -0
  72. package/metadata/index.d.ts +1 -1
  73. package/metadata/index.js +1 -1
  74. package/metadata/types.d.ts +480 -0
  75. package/metadata/types.js +1 -0
  76. package/naming-strategy/AbstractNamingStrategy.d.ts +5 -1
  77. package/naming-strategy/AbstractNamingStrategy.js +8 -2
  78. package/naming-strategy/NamingStrategy.d.ts +11 -1
  79. package/not-supported.d.ts +2 -0
  80. package/not-supported.js +4 -0
  81. package/package.json +18 -10
  82. package/platforms/ExceptionConverter.js +1 -1
  83. package/platforms/Platform.d.ts +6 -13
  84. package/platforms/Platform.js +15 -41
  85. package/serialization/EntitySerializer.d.ts +2 -0
  86. package/serialization/EntitySerializer.js +32 -14
  87. package/serialization/EntityTransformer.js +22 -12
  88. package/serialization/SerializationContext.js +16 -13
  89. package/types/ArrayType.d.ts +1 -1
  90. package/types/ArrayType.js +2 -3
  91. package/types/BigIntType.d.ts +8 -6
  92. package/types/BigIntType.js +1 -1
  93. package/types/BlobType.d.ts +0 -1
  94. package/types/BlobType.js +0 -3
  95. package/types/BooleanType.d.ts +2 -1
  96. package/types/BooleanType.js +3 -0
  97. package/types/DecimalType.d.ts +6 -4
  98. package/types/DecimalType.js +3 -3
  99. package/types/DoubleType.js +2 -2
  100. package/types/EnumArrayType.js +1 -2
  101. package/types/JsonType.d.ts +1 -1
  102. package/types/JsonType.js +7 -2
  103. package/types/TinyIntType.js +1 -1
  104. package/types/Type.d.ts +2 -4
  105. package/types/Type.js +3 -3
  106. package/types/Uint8ArrayType.d.ts +0 -1
  107. package/types/Uint8ArrayType.js +1 -4
  108. package/types/index.d.ts +1 -1
  109. package/typings.d.ts +109 -73
  110. package/typings.js +38 -35
  111. package/unit-of-work/ChangeSet.d.ts +0 -3
  112. package/unit-of-work/ChangeSet.js +2 -2
  113. package/unit-of-work/ChangeSetComputer.d.ts +1 -3
  114. package/unit-of-work/ChangeSetComputer.js +11 -9
  115. package/unit-of-work/ChangeSetPersister.d.ts +5 -4
  116. package/unit-of-work/ChangeSetPersister.js +51 -19
  117. package/unit-of-work/UnitOfWork.d.ts +8 -1
  118. package/unit-of-work/UnitOfWork.js +91 -49
  119. package/utils/AbstractSchemaGenerator.d.ts +5 -5
  120. package/utils/AbstractSchemaGenerator.js +11 -9
  121. package/utils/Configuration.d.ts +757 -206
  122. package/utils/Configuration.js +140 -188
  123. package/utils/ConfigurationLoader.d.ts +1 -54
  124. package/utils/ConfigurationLoader.js +1 -352
  125. package/utils/Cursor.d.ts +0 -3
  126. package/utils/Cursor.js +6 -3
  127. package/utils/DataloaderUtils.d.ts +15 -5
  128. package/utils/DataloaderUtils.js +54 -8
  129. package/utils/EntityComparator.d.ts +8 -4
  130. package/utils/EntityComparator.js +52 -17
  131. package/utils/QueryHelper.d.ts +9 -1
  132. package/utils/QueryHelper.js +70 -9
  133. package/utils/RawQueryFragment.d.ts +36 -13
  134. package/utils/RawQueryFragment.js +36 -16
  135. package/utils/TransactionManager.d.ts +65 -0
  136. package/utils/TransactionManager.js +223 -0
  137. package/utils/Utils.d.ts +8 -97
  138. package/utils/Utils.js +82 -302
  139. package/utils/clone.js +2 -3
  140. package/utils/env-vars.d.ts +3 -0
  141. package/utils/env-vars.js +87 -0
  142. package/utils/fs-utils.d.ts +12 -0
  143. package/utils/fs-utils.js +97 -0
  144. package/utils/index.d.ts +2 -1
  145. package/utils/index.js +2 -1
  146. package/utils/upsert-utils.d.ts +7 -2
  147. package/utils/upsert-utils.js +55 -4
  148. package/decorators/Check.d.ts +0 -3
  149. package/decorators/Check.js +0 -13
  150. package/decorators/CreateRequestContext.d.ts +0 -3
  151. package/decorators/CreateRequestContext.js +0 -32
  152. package/decorators/Embeddable.d.ts +0 -8
  153. package/decorators/Embeddable.js +0 -11
  154. package/decorators/Embedded.d.ts +0 -18
  155. package/decorators/Embedded.js +0 -18
  156. package/decorators/Entity.d.ts +0 -18
  157. package/decorators/Entity.js +0 -12
  158. package/decorators/Enum.d.ts +0 -9
  159. package/decorators/Enum.js +0 -16
  160. package/decorators/Filter.d.ts +0 -2
  161. package/decorators/Filter.js +0 -8
  162. package/decorators/Formula.d.ts +0 -4
  163. package/decorators/Formula.js +0 -15
  164. package/decorators/Indexed.d.ts +0 -19
  165. package/decorators/Indexed.js +0 -20
  166. package/decorators/ManyToMany.d.ts +0 -40
  167. package/decorators/ManyToMany.js +0 -14
  168. package/decorators/ManyToOne.d.ts +0 -30
  169. package/decorators/ManyToOne.js +0 -14
  170. package/decorators/OneToMany.d.ts +0 -28
  171. package/decorators/OneToMany.js +0 -17
  172. package/decorators/OneToOne.d.ts +0 -24
  173. package/decorators/OneToOne.js +0 -7
  174. package/decorators/PrimaryKey.d.ts +0 -8
  175. package/decorators/PrimaryKey.js +0 -20
  176. package/decorators/Property.d.ts +0 -250
  177. package/decorators/Property.js +0 -32
  178. package/decorators/Transactional.d.ts +0 -13
  179. package/decorators/Transactional.js +0 -28
  180. package/decorators/hooks.d.ts +0 -16
  181. package/decorators/hooks.js +0 -47
  182. package/decorators/index.d.ts +0 -17
  183. package/decorators/index.js +0 -17
  184. package/entity/ArrayCollection.d.ts +0 -116
  185. package/entity/ArrayCollection.js +0 -402
  186. package/entity/EntityValidator.d.ts +0 -19
  187. package/entity/EntityValidator.js +0 -150
  188. package/metadata/ReflectMetadataProvider.d.ts +0 -8
  189. package/metadata/ReflectMetadataProvider.js +0 -44
  190. package/utils/resolveContextProvider.d.ts +0 -10
  191. package/utils/resolveContextProvider.js +0 -28
@@ -1,16 +1,29 @@
1
- import { ArrayCollection } from './ArrayCollection.js';
2
1
  import { Utils } from '../utils/Utils.js';
3
- import { ValidationError } from '../errors.js';
4
- import { ReferenceKind, DataloaderType } from '../enums.js';
2
+ import { MetadataError, ValidationError } from '../errors.js';
3
+ import { DataloaderType, ReferenceKind } from '../enums.js';
5
4
  import { Reference } from './Reference.js';
6
- import { helper } from './wrap.js';
7
- export class Collection extends ArrayCollection {
5
+ import { helper, wrap } from './wrap.js';
6
+ import { QueryHelper } from '../utils/QueryHelper.js';
7
+ import { inspect } from '../logging/inspect.js';
8
+ 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
8
15
  readonly;
16
+ _count;
17
+ _property;
9
18
  _populated;
10
- // this is for some reason needed for TS, otherwise it can fail with `Type instantiation is excessively deep and possibly infinite.`
11
- _snapshot;
12
19
  constructor(owner, items, initialized = true) {
13
- super(owner, items);
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
+ }
14
27
  this.initialized = !!items || initialized;
15
28
  }
16
29
  /**
@@ -32,6 +45,7 @@ export class Collection extends ArrayCollection {
32
45
  async load(options = {}) {
33
46
  if (this.isInitialized(true) && !options.refresh) {
34
47
  const em = this.getEntityManager(this.items, false);
48
+ options = { ...options, filters: QueryHelper.mergePropertyFilters(this.property.filters, options.filters) };
35
49
  await em?.populate(this.items, options.populate, options);
36
50
  this.setSerializationContext(options);
37
51
  }
@@ -52,7 +66,7 @@ export class Collection extends ArrayCollection {
52
66
  */
53
67
  async loadItems(options) {
54
68
  await this.load(options);
55
- return super.getItems();
69
+ return this.getItems(false);
56
70
  }
57
71
  /**
58
72
  * Gets the count of collection items from database instead of counting loaded items.
@@ -61,7 +75,7 @@ export class Collection extends ArrayCollection {
61
75
  async loadCount(options = {}) {
62
76
  options = typeof options === 'boolean' ? { refresh: options } : options;
63
77
  const { refresh, where, ...countOptions } = options;
64
- if (!refresh && !where && Utils.isDefined(this._count)) {
78
+ if (!refresh && !where && this._count != null) {
65
79
  return this._count;
66
80
  }
67
81
  const em = this.getEntityManager();
@@ -103,98 +117,97 @@ export class Collection extends ArrayCollection {
103
117
  if (check) {
104
118
  this.checkInitialized();
105
119
  }
106
- return super.getItems();
120
+ return [...this.items];
107
121
  }
108
122
  toJSON() {
109
123
  if (!this.isInitialized()) {
110
124
  return [];
111
125
  }
112
- return super.toJSON();
126
+ return this.toArray();
113
127
  }
114
128
  add(entity, ...entities) {
115
129
  entities = Utils.asArray(entity).concat(entities);
116
130
  const unwrapped = entities.map(i => Reference.unwrapReference(i));
117
- unwrapped.forEach(entity => this.validateItemType(entity));
118
- this.modify('add', unwrapped);
131
+ this.validateModification(unwrapped);
132
+ const em = this.getEntityManager(entities, false);
133
+ let added = 0;
134
+ for (const item of entities) {
135
+ const entity = Reference.unwrapReference(item);
136
+ if (!this.contains(entity, false)) {
137
+ this.incrementCount(1);
138
+ this[this.items.size] = entity;
139
+ this.items.add(entity);
140
+ added++;
141
+ this.dirty = true;
142
+ this.propagate(entity, 'add');
143
+ }
144
+ }
145
+ if (this.property.kind === ReferenceKind.ONE_TO_MANY && em) {
146
+ em.persist(entities);
147
+ }
119
148
  this.cancelOrphanRemoval(unwrapped);
149
+ return added;
120
150
  }
121
151
  /**
122
- * @inheritDoc
152
+ * Remove specified item(s) from the collection. Note that removing item from collection does not necessarily imply deleting the target entity,
153
+ * it means we are disconnecting the relation - removing items from collection, not removing entities from database - `Collection.remove()`
154
+ * 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`,
155
+ * which tells the ORM we don't want orphaned entities to exist, so we know those should be removed.
123
156
  */
124
157
  remove(entity, ...entities) {
125
158
  if (entity instanceof Function) {
159
+ let removed = 0;
126
160
  for (const item of this.items) {
127
161
  if (entity(item)) {
128
- this.remove(item);
162
+ removed += this.remove(item);
129
163
  }
130
164
  }
131
- return;
165
+ return removed;
132
166
  }
167
+ this.checkInitialized();
133
168
  entities = Utils.asArray(entity).concat(entities);
134
169
  const unwrapped = entities.map(i => Reference.unwrapReference(i));
135
- this.modify('remove', unwrapped);
136
- const em = this.getEntityManager(unwrapped, false);
137
- if (this.property.orphanRemoval && em) {
138
- for (const item of unwrapped) {
139
- em.getUnitOfWork().scheduleOrphanRemoval(item);
170
+ this.validateModification(unwrapped);
171
+ const em = this.getEntityManager(entities, false);
172
+ let removed = 0;
173
+ for (const item of entities) {
174
+ if (!item) {
175
+ continue;
176
+ }
177
+ const entity = Reference.unwrapReference(item);
178
+ if (this.items.delete(entity)) {
179
+ this.incrementCount(-1);
180
+ delete this[this.items.size]; // remove last item
181
+ this.propagate(entity, 'remove');
182
+ removed++;
183
+ this.dirty = true;
140
184
  }
185
+ if (this.property.orphanRemoval && em) {
186
+ em.getUnitOfWork().scheduleOrphanRemoval(entity);
187
+ }
188
+ }
189
+ if (this.property.kind === ReferenceKind.ONE_TO_MANY && !this.property.orphanRemoval && em) {
190
+ em.persist(entities);
191
+ }
192
+ if (removed > 0) {
193
+ Object.assign(this, [...this.items]); // reassign array access
141
194
  }
195
+ return removed;
142
196
  }
143
197
  contains(item, check = true) {
144
198
  if (check) {
145
199
  this.checkInitialized();
146
200
  }
147
- return super.contains(item);
201
+ const entity = Reference.unwrapReference(item);
202
+ return this.items.has(entity);
148
203
  }
149
204
  count() {
150
205
  this.checkInitialized();
151
- return super.count();
206
+ return this.items.size;
152
207
  }
153
208
  isEmpty() {
154
209
  this.checkInitialized();
155
- return super.isEmpty();
156
- }
157
- /**
158
- * @inheritDoc
159
- */
160
- slice(start, end) {
161
- this.checkInitialized();
162
- return super.slice(start, end);
163
- }
164
- /**
165
- * @inheritDoc
166
- */
167
- exists(cb) {
168
- this.checkInitialized();
169
- return super.exists(cb);
170
- }
171
- /**
172
- * @inheritDoc
173
- */
174
- find(cb) {
175
- this.checkInitialized();
176
- return super.find(cb);
177
- }
178
- /**
179
- * @inheritDoc
180
- */
181
- filter(cb) {
182
- this.checkInitialized();
183
- return super.filter(cb);
184
- }
185
- /**
186
- * @inheritDoc
187
- */
188
- map(mapper) {
189
- this.checkInitialized();
190
- return super.map(mapper);
191
- }
192
- /**
193
- * @inheritDoc
194
- */
195
- indexBy(key, valueKey) {
196
- this.checkInitialized();
197
- return super.indexBy(key, valueKey);
210
+ return this.count() === 0;
198
211
  }
199
212
  shouldPopulate(populated) {
200
213
  if (!this.isInitialized(true)) {
@@ -217,17 +230,21 @@ export class Collection extends ArrayCollection {
217
230
  return this;
218
231
  }
219
232
  const em = this.getEntityManager();
233
+ options = { ...options, filters: QueryHelper.mergePropertyFilters(this.property.filters, options.filters) };
220
234
  if (options.dataloader ?? [DataloaderType.ALL, DataloaderType.COLLECTION].includes(em.config.getDataloaderType())) {
221
235
  const order = [...this.items]; // copy order of references
222
236
  const orderBy = this.createOrderBy(options.orderBy);
223
237
  const customOrder = orderBy.length > 0;
224
- // eslint-disable-next-line dot-notation
225
- const items = await em['colLoader'].load([
226
- this,
227
- { ...options, orderBy },
228
- ]);
229
- if (!customOrder) {
230
- this.reorderItems(items, order);
238
+ const pivotTable = this.property.kind === ReferenceKind.MANY_TO_MANY && em.getPlatform().usesPivotTable();
239
+ const loader = await em.getDataLoader(pivotTable ? 'm:n' : '1:m');
240
+ const items = await loader.load([this, { ...options, orderBy }]);
241
+ if (this.property.kind === ReferenceKind.MANY_TO_MANY) {
242
+ this.initialized = true;
243
+ this.dirty = false;
244
+ if (!customOrder) {
245
+ this.reorderItems(items, order);
246
+ }
247
+ return this;
231
248
  }
232
249
  this.items.clear();
233
250
  let i = 0;
@@ -311,14 +328,6 @@ export class Collection extends ArrayCollection {
311
328
  }
312
329
  return cond;
313
330
  }
314
- modify(method, items) {
315
- if (method === 'remove') {
316
- this.checkInitialized();
317
- }
318
- this.validateModification(items);
319
- super[method](items);
320
- this.setDirty();
321
- }
322
331
  checkInitialized() {
323
332
  if (!this.isInitialized()) {
324
333
  throw new Error(`Collection<${this.property.type}> of entity ${this.owner.constructor.name}[${helper(this.owner).getSerializedPrimaryKey()}] not initialized`);
@@ -341,32 +350,362 @@ export class Collection extends ArrayCollection {
341
350
  em.getUnitOfWork().cancelOrphanRemoval(item);
342
351
  }
343
352
  }
344
- validateItemType(item) {
345
- if (!Utils.isEntity(item)) {
346
- throw ValidationError.notEntity(this.owner, this.property, item);
347
- }
348
- }
349
353
  validateModification(items) {
350
354
  if (this.readonly) {
351
355
  throw ValidationError.cannotModifyReadonlyCollection(this.owner, this.property);
352
356
  }
353
- // currently we allow persisting to inverse sides only in SQL drivers
354
- if (this.property.pivotTable || !this.property.mappedBy) {
355
- return;
356
- }
357
357
  const check = (item) => {
358
- if (!item || helper(item).__initialized) {
358
+ if (!item) {
359
+ return false;
360
+ }
361
+ if (!Utils.isEntity(item)) {
362
+ throw ValidationError.notEntity(this.owner, this.property, item);
363
+ }
364
+ // currently we allow persisting to inverse sides only in SQL drivers
365
+ if (this.property.pivotTable || !this.property.mappedBy) {
366
+ return false;
367
+ }
368
+ if (helper(item).__initialized) {
359
369
  return false;
360
370
  }
361
371
  return !item[this.property.mappedBy] && this.property.kind === ReferenceKind.MANY_TO_MANY;
362
372
  };
363
373
  // throw if we are modifying inverse side of M:N collection when owning side is initialized (would be ignored when persisting)
364
- if (items.find(item => check(item))) {
374
+ if (items.some(item => check(item))) {
365
375
  throw ValidationError.cannotModifyInverseCollection(this.owner, this.property);
366
376
  }
367
377
  }
378
+ toArray() {
379
+ if (this.items.size === 0) {
380
+ return [];
381
+ }
382
+ return this.map(item => wrap(item).toJSON());
383
+ }
384
+ getIdentifiers(field) {
385
+ const items = this.getItems();
386
+ const targetMeta = this.property.targetMeta;
387
+ if (items.length === 0) {
388
+ return [];
389
+ }
390
+ field ??= targetMeta.compositePK ? targetMeta.primaryKeys : (targetMeta.serializedPrimaryKey ?? targetMeta.primaryKeys[0]);
391
+ const cb = (i, f) => {
392
+ if (Utils.isEntity(i[f], true)) {
393
+ return wrap(i[f], true).getPrimaryKey();
394
+ }
395
+ return i[f];
396
+ };
397
+ return items.map(i => {
398
+ if (Array.isArray(field)) {
399
+ return field.map(f => cb(i, f));
400
+ }
401
+ return cb(i, field);
402
+ });
403
+ }
404
+ /**
405
+ * @internal
406
+ */
407
+ addWithoutPropagation(entity) {
408
+ if (!this.contains(entity, false)) {
409
+ this.incrementCount(1);
410
+ this[this.items.size] = entity;
411
+ this.items.add(entity);
412
+ this.dirty = true;
413
+ }
414
+ }
415
+ set(items) {
416
+ if (!this.initialized) {
417
+ this.initialized = true;
418
+ this.snapshot = undefined;
419
+ }
420
+ if (this.compare(Utils.asArray(items).map(item => Reference.unwrapReference(item)))) {
421
+ return;
422
+ }
423
+ this.remove(this.items);
424
+ this.add(items);
425
+ }
426
+ compare(items) {
427
+ if (items.length !== this.items.size) {
428
+ return false;
429
+ }
430
+ let idx = 0;
431
+ for (const item of this.items) {
432
+ if (item !== items[idx++]) {
433
+ return false;
434
+ }
435
+ }
436
+ return true;
437
+ }
438
+ /**
439
+ * @internal
440
+ */
441
+ hydrate(items, forcePropagate, partial) {
442
+ for (let i = 0; i < this.items.size; i++) {
443
+ delete this[i];
444
+ }
445
+ this.initialized = true;
446
+ this.partial = !!partial;
447
+ this.items.clear();
448
+ this._count = 0;
449
+ this.add(items);
450
+ this.takeSnapshot(forcePropagate);
451
+ }
452
+ /**
453
+ * Remove all items from the collection. Note that removing items from collection does not necessarily imply deleting the target entity,
454
+ * it means we are disconnecting the relation - removing items from collection, not removing entities from database - `Collection.remove()`
455
+ * 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`,
456
+ * which tells the ORM we don't want orphaned entities to exist, so we know those should be removed.
457
+ */
458
+ removeAll() {
459
+ if (!this.initialized) {
460
+ this.initialized = true;
461
+ this.snapshot = undefined;
462
+ }
463
+ this.remove(this.items);
464
+ this.dirty = true;
465
+ }
466
+ /**
467
+ * @internal
468
+ */
469
+ removeWithoutPropagation(entity) {
470
+ if (!this.items.delete(entity)) {
471
+ return;
472
+ }
473
+ this.incrementCount(-1);
474
+ delete this[this.items.size];
475
+ Object.assign(this, [...this.items]);
476
+ this.dirty = true;
477
+ }
478
+ /**
479
+ * Extracts a slice of the collection items starting at position start to end (exclusive) of the collection.
480
+ * If end is null it returns all elements from start to the end of the collection.
481
+ */
482
+ slice(start = 0, end) {
483
+ this.checkInitialized();
484
+ let index = 0;
485
+ end ??= this.items.size;
486
+ const items = [];
487
+ for (const item of this.items) {
488
+ if (index === end) {
489
+ break;
490
+ }
491
+ if (index >= start && index < end) {
492
+ items.push(item);
493
+ }
494
+ index++;
495
+ }
496
+ return items;
497
+ }
498
+ /**
499
+ * Tests for the existence of an element that satisfies the given predicate.
500
+ */
501
+ exists(cb) {
502
+ this.checkInitialized();
503
+ for (const item of this.items) {
504
+ if (cb(item)) {
505
+ return true;
506
+ }
507
+ }
508
+ return false;
509
+ }
510
+ /**
511
+ * Returns the first element of this collection that satisfies the predicate.
512
+ */
513
+ find(cb) {
514
+ this.checkInitialized();
515
+ let index = 0;
516
+ for (const item of this.items) {
517
+ if (cb(item, index++)) {
518
+ return item;
519
+ }
520
+ }
521
+ return undefined;
522
+ }
523
+ /**
524
+ * Extracts a subset of the collection items.
525
+ */
526
+ filter(cb) {
527
+ this.checkInitialized();
528
+ const items = [];
529
+ let index = 0;
530
+ for (const item of this.items) {
531
+ if (cb(item, index++)) {
532
+ items.push(item);
533
+ }
534
+ }
535
+ return items;
536
+ }
537
+ /**
538
+ * Maps the collection items based on your provided mapper function.
539
+ */
540
+ map(mapper) {
541
+ this.checkInitialized();
542
+ const items = [];
543
+ let index = 0;
544
+ for (const item of this.items) {
545
+ items.push(mapper(item, index++));
546
+ }
547
+ return items;
548
+ }
549
+ /**
550
+ * Maps the collection items based on your provided mapper function to a single object.
551
+ */
552
+ reduce(cb, initial = {}) {
553
+ this.checkInitialized();
554
+ let index = 0;
555
+ for (const item of this.items) {
556
+ initial = cb(initial, item, index++);
557
+ }
558
+ return initial;
559
+ }
560
+ /**
561
+ * Maps the collection items to a dictionary, indexed by the key you specify.
562
+ * If there are more items with the same key, only the first one will be present.
563
+ */
564
+ indexBy(key, valueKey) {
565
+ return this.reduce((obj, item) => {
566
+ obj[item[key]] ??= valueKey ? item[valueKey] : item;
567
+ return obj;
568
+ }, {});
569
+ }
570
+ isInitialized(fully = false) {
571
+ if (!this.initialized || !fully) {
572
+ return this.initialized;
573
+ }
574
+ for (const item of this.items) {
575
+ if (!helper(item).__initialized) {
576
+ return false;
577
+ }
578
+ }
579
+ return true;
580
+ }
581
+ isDirty() {
582
+ return this.dirty;
583
+ }
584
+ isPartial() {
585
+ return this.partial;
586
+ }
587
+ setDirty(dirty = true) {
588
+ this.dirty = dirty;
589
+ }
590
+ get length() {
591
+ return this.count();
592
+ }
593
+ *[Symbol.iterator]() {
594
+ for (const item of this.getItems()) {
595
+ yield item;
596
+ }
597
+ }
598
+ /**
599
+ * @internal
600
+ */
601
+ takeSnapshot(forcePropagate) {
602
+ this.snapshot = [...this.items];
603
+ this.dirty = false;
604
+ if (this.property.owner || forcePropagate) {
605
+ this.items.forEach(item => {
606
+ this.propagate(item, 'takeSnapshot');
607
+ });
608
+ }
609
+ }
610
+ /**
611
+ * @internal
612
+ */
613
+ getSnapshot() {
614
+ return this.snapshot;
615
+ }
616
+ /**
617
+ * @internal
618
+ */
619
+ get property() {
620
+ if (!this._property) {
621
+ const meta = wrap(this.owner, true).__meta;
622
+ /* v8 ignore next */
623
+ if (!meta) {
624
+ throw MetadataError.fromUnknownEntity(this.owner.constructor.name, 'Collection.property getter, maybe you just forgot to initialize the ORM?');
625
+ }
626
+ this._property = meta.relations.find(prop => this.owner[prop.name] === this);
627
+ }
628
+ return this._property;
629
+ }
630
+ /**
631
+ * @internal
632
+ */
633
+ set property(prop) {
634
+ this._property = prop;
635
+ }
636
+ propagate(item, method) {
637
+ if (this.property.owner && this.property.inversedBy) {
638
+ this.propagateToInverseSide(item, method);
639
+ }
640
+ else if (!this.property.owner && this.property.mappedBy) {
641
+ this.propagateToOwningSide(item, method);
642
+ }
643
+ }
644
+ propagateToInverseSide(item, method) {
645
+ const collection = item[this.property.inversedBy];
646
+ if (this.shouldPropagateToCollection(collection, method)) {
647
+ method = method === 'takeSnapshot' ? method : (method + 'WithoutPropagation');
648
+ collection[method](this.owner);
649
+ }
650
+ }
651
+ propagateToOwningSide(item, method) {
652
+ const mappedBy = this.property.mappedBy;
653
+ const collection = item[mappedBy];
654
+ if (this.property.kind === ReferenceKind.MANY_TO_MANY) {
655
+ if (this.shouldPropagateToCollection(collection, method)) {
656
+ collection[method](this.owner);
657
+ }
658
+ }
659
+ else if (this.property.kind === ReferenceKind.ONE_TO_MANY && method !== 'takeSnapshot') {
660
+ const prop2 = this.property.targetMeta.properties[mappedBy];
661
+ const owner = prop2.mapToPk ? helper(this.owner).getPrimaryKey() : this.owner;
662
+ const value = method === 'add' ? owner : null;
663
+ if (this.property.orphanRemoval && method === 'remove') {
664
+ // cache the PK before we propagate, as its value might be needed when flushing
665
+ helper(item).__pk = helper(item).getPrimaryKey();
666
+ }
667
+ if (!prop2.nullable && prop2.deleteRule !== 'cascade' && method === 'remove') {
668
+ if (!this.property.orphanRemoval) {
669
+ throw ValidationError.cannotRemoveFromCollectionWithoutOrphanRemoval(this.owner, this.property);
670
+ }
671
+ return;
672
+ }
673
+ // skip if already propagated
674
+ if (Reference.unwrapReference(item[mappedBy]) !== value) {
675
+ item[mappedBy] = value;
676
+ }
677
+ }
678
+ }
679
+ shouldPropagateToCollection(collection, method) {
680
+ if (!collection) {
681
+ return false;
682
+ }
683
+ switch (method) {
684
+ case 'add':
685
+ return !collection.contains(this.owner, false);
686
+ case 'remove':
687
+ return collection.isInitialized() && collection.contains(this.owner, false);
688
+ case 'takeSnapshot':
689
+ return collection.isDirty();
690
+ }
691
+ }
692
+ incrementCount(value) {
693
+ if (typeof this._count === 'number' && this.initialized) {
694
+ this._count += value;
695
+ }
696
+ }
697
+ /** @ignore */
698
+ [Symbol.for('nodejs.util.inspect.custom')](depth = 2) {
699
+ const object = { ...this };
700
+ const hidden = ['items', 'owner', '_property', '_count', 'snapshot', '_populated', '_lazyInitialized', '_em', 'readonly', 'partial'];
701
+ hidden.forEach(k => delete object[k]);
702
+ const ret = inspect(object, { depth });
703
+ const name = `${this.constructor.name}<${this.property?.type ?? 'unknown'}>`;
704
+ return ret === '[Object]' ? `[${name}]` : name + ' ' + ret;
705
+ }
368
706
  }
369
707
  Object.defineProperties(Collection.prototype, {
370
708
  $: { get() { return this; } },
371
709
  get: { get() { return () => this; } },
710
+ __collection: { value: true, enumerable: false, writable: false },
372
711
  });
@@ -36,7 +36,7 @@ export interface AssignOptions<Convert extends boolean> {
36
36
  */
37
37
  onlyProperties?: boolean;
38
38
  /**
39
- * With `onlyOwnProperties` enabled, to-many relations are skipped, and payloads of to-one relations are converted
39
+ * With `onlyOwnProperties` enabled, inverse sides of to-many relations are skipped, and payloads of other relations are converted
40
40
  * to foreign keys. Defaults to `false`.
41
41
  */
42
42
  onlyOwnProperties?: boolean;