@mikro-orm/core 7.0.0-dev.14 → 7.0.0-dev.141

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