@mikro-orm/core 7.0.0-dev.21 → 7.0.0-dev.210

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 (211) hide show
  1. package/EntityManager.d.ts +99 -57
  2. package/EntityManager.js +302 -276
  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 +44 -17
  17. package/entity/BaseEntity.d.ts +2 -2
  18. package/entity/BaseEntity.js +0 -3
  19. package/entity/Collection.d.ts +94 -29
  20. package/entity/Collection.js +434 -97
  21. package/entity/EntityAssigner.d.ts +1 -1
  22. package/entity/EntityAssigner.js +26 -18
  23. package/entity/EntityFactory.d.ts +13 -1
  24. package/entity/EntityFactory.js +84 -53
  25. package/entity/EntityHelper.d.ts +2 -2
  26. package/entity/EntityHelper.js +35 -15
  27. package/entity/EntityLoader.d.ts +6 -6
  28. package/entity/EntityLoader.js +119 -82
  29. package/entity/EntityRepository.d.ts +24 -4
  30. package/entity/EntityRepository.js +8 -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 +594 -0
  36. package/entity/defineEntity.js +533 -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 +21 -5
  44. package/enums.js +15 -1
  45. package/errors.d.ts +23 -9
  46. package/errors.js +59 -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 +52 -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 +40 -23
  64. package/metadata/EntitySchema.js +81 -34
  65. package/metadata/MetadataDiscovery.d.ts +7 -10
  66. package/metadata/MetadataDiscovery.js +391 -331
  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 +17 -9
  72. package/metadata/MetadataValidator.js +97 -40
  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 +502 -0
  78. package/metadata/types.js +1 -0
  79. package/naming-strategy/AbstractNamingStrategy.d.ts +12 -4
  80. package/naming-strategy/AbstractNamingStrategy.js +14 -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 +24 -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 +18 -11
  91. package/platforms/ExceptionConverter.js +1 -1
  92. package/platforms/Platform.d.ts +7 -13
  93. package/platforms/Platform.js +20 -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 +290 -137
  120. package/typings.js +59 -44
  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 +26 -13
  125. package/unit-of-work/ChangeSetPersister.d.ts +5 -4
  126. package/unit-of-work/ChangeSetPersister.js +70 -34
  127. package/unit-of-work/CommitOrderCalculator.d.ts +12 -10
  128. package/unit-of-work/CommitOrderCalculator.js +13 -13
  129. package/unit-of-work/IdentityMap.d.ts +12 -0
  130. package/unit-of-work/IdentityMap.js +39 -1
  131. package/unit-of-work/UnitOfWork.d.ts +23 -3
  132. package/unit-of-work/UnitOfWork.js +175 -98
  133. package/utils/AbstractSchemaGenerator.d.ts +5 -5
  134. package/utils/AbstractSchemaGenerator.js +18 -16
  135. package/utils/AsyncContext.d.ts +6 -0
  136. package/utils/AsyncContext.js +42 -0
  137. package/utils/Configuration.d.ts +785 -207
  138. package/utils/Configuration.js +147 -190
  139. package/utils/ConfigurationLoader.d.ts +1 -54
  140. package/utils/ConfigurationLoader.js +1 -352
  141. package/utils/Cursor.d.ts +0 -3
  142. package/utils/Cursor.js +27 -11
  143. package/utils/DataloaderUtils.d.ts +15 -5
  144. package/utils/DataloaderUtils.js +64 -30
  145. package/utils/EntityComparator.d.ts +13 -9
  146. package/utils/EntityComparator.js +101 -42
  147. package/utils/QueryHelper.d.ts +14 -6
  148. package/utils/QueryHelper.js +87 -25
  149. package/utils/RawQueryFragment.d.ts +48 -25
  150. package/utils/RawQueryFragment.js +66 -70
  151. package/utils/RequestContext.js +2 -2
  152. package/utils/TransactionContext.js +2 -2
  153. package/utils/TransactionManager.d.ts +65 -0
  154. package/utils/TransactionManager.js +223 -0
  155. package/utils/Utils.d.ts +13 -126
  156. package/utils/Utils.js +100 -391
  157. package/utils/clone.js +8 -23
  158. package/utils/env-vars.d.ts +7 -0
  159. package/utils/env-vars.js +97 -0
  160. package/utils/fs-utils.d.ts +32 -0
  161. package/utils/fs-utils.js +178 -0
  162. package/utils/index.d.ts +2 -1
  163. package/utils/index.js +2 -1
  164. package/utils/upsert-utils.d.ts +9 -4
  165. package/utils/upsert-utils.js +55 -4
  166. package/decorators/Check.d.ts +0 -3
  167. package/decorators/Check.js +0 -13
  168. package/decorators/CreateRequestContext.d.ts +0 -3
  169. package/decorators/CreateRequestContext.js +0 -32
  170. package/decorators/Embeddable.d.ts +0 -8
  171. package/decorators/Embeddable.js +0 -11
  172. package/decorators/Embedded.d.ts +0 -12
  173. package/decorators/Embedded.js +0 -18
  174. package/decorators/Entity.d.ts +0 -18
  175. package/decorators/Entity.js +0 -12
  176. package/decorators/Enum.d.ts +0 -9
  177. package/decorators/Enum.js +0 -16
  178. package/decorators/Filter.d.ts +0 -2
  179. package/decorators/Filter.js +0 -8
  180. package/decorators/Formula.d.ts +0 -4
  181. package/decorators/Formula.js +0 -15
  182. package/decorators/Indexed.d.ts +0 -19
  183. package/decorators/Indexed.js +0 -20
  184. package/decorators/ManyToMany.d.ts +0 -40
  185. package/decorators/ManyToMany.js +0 -14
  186. package/decorators/ManyToOne.d.ts +0 -32
  187. package/decorators/ManyToOne.js +0 -14
  188. package/decorators/OneToMany.d.ts +0 -28
  189. package/decorators/OneToMany.js +0 -17
  190. package/decorators/OneToOne.d.ts +0 -26
  191. package/decorators/OneToOne.js +0 -7
  192. package/decorators/PrimaryKey.d.ts +0 -8
  193. package/decorators/PrimaryKey.js +0 -20
  194. package/decorators/Property.d.ts +0 -250
  195. package/decorators/Property.js +0 -32
  196. package/decorators/Transactional.d.ts +0 -13
  197. package/decorators/Transactional.js +0 -28
  198. package/decorators/hooks.d.ts +0 -16
  199. package/decorators/hooks.js +0 -47
  200. package/decorators/index.d.ts +0 -17
  201. package/decorators/index.js +0 -17
  202. package/entity/ArrayCollection.d.ts +0 -116
  203. package/entity/ArrayCollection.js +0 -402
  204. package/entity/EntityValidator.d.ts +0 -19
  205. package/entity/EntityValidator.js +0 -150
  206. package/exports.d.ts +0 -24
  207. package/exports.js +0 -23
  208. package/metadata/ReflectMetadataProvider.d.ts +0 -8
  209. package/metadata/ReflectMetadataProvider.js +0 -44
  210. package/utils/resolveContextProvider.d.ts +0 -10
  211. 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,15 +233,14 @@ 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
- ]);
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 }]);
229
244
  if (this.property.kind === ReferenceKind.MANY_TO_MANY) {
230
245
  this.initialized = true;
231
246
  this.dirty = false;
@@ -286,7 +301,7 @@ export class Collection extends ArrayCollection {
286
301
  return cond;
287
302
  }
288
303
  createOrderBy(orderBy = []) {
289
- if (Utils.isEmpty(orderBy) && this.property.orderBy) {
304
+ if (Utils.isEmpty(orderBy) && !Raw.hasObjectFragments(orderBy) && this.property.orderBy) {
290
305
  orderBy = this.property.orderBy;
291
306
  }
292
307
  return Utils.asArray(orderBy);
@@ -316,17 +331,9 @@ export class Collection extends ArrayCollection {
316
331
  }
317
332
  return cond;
318
333
  }
319
- modify(method, items) {
320
- if (method === 'remove') {
321
- this.checkInitialized();
322
- }
323
- this.validateModification(items);
324
- super[method](items);
325
- this.setDirty();
326
- }
327
334
  checkInitialized() {
328
335
  if (!this.isInitialized()) {
329
- 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`);
330
337
  }
331
338
  }
332
339
  /**
@@ -346,32 +353,362 @@ export class Collection extends ArrayCollection {
346
353
  em.getUnitOfWork().cancelOrphanRemoval(item);
347
354
  }
348
355
  }
349
- validateItemType(item) {
350
- if (!Utils.isEntity(item)) {
351
- throw ValidationError.notEntity(this.owner, this.property, item);
352
- }
353
- }
354
356
  validateModification(items) {
355
357
  if (this.readonly) {
356
358
  throw ValidationError.cannotModifyReadonlyCollection(this.owner, this.property);
357
359
  }
358
- // currently we allow persisting to inverse sides only in SQL drivers
359
- if (this.property.pivotTable || !this.property.mappedBy) {
360
- return;
361
- }
362
360
  const check = (item) => {
363
- 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) {
364
372
  return false;
365
373
  }
366
374
  return !item[this.property.mappedBy] && this.property.kind === ReferenceKind.MANY_TO_MANY;
367
375
  };
368
376
  // throw if we are modifying inverse side of M:N collection when owning side is initialized (would be ignored when persisting)
369
- if (items.find(item => check(item))) {
377
+ if (items.some(item => check(item))) {
370
378
  throw ValidationError.cannotModifyInverseCollection(this.owner, this.property);
371
379
  }
372
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
+ }
373
709
  }
374
710
  Object.defineProperties(Collection.prototype, {
375
711
  $: { get() { return this; } },
376
712
  get: { get() { return () => this; } },
713
+ __collection: { value: true, enumerable: false, writable: false },
377
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;