@mikro-orm/core 7.0.0-dev.2 → 7.0.0-dev.200

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 (210) hide show
  1. package/EntityManager.d.ts +111 -61
  2. package/EntityManager.js +346 -300
  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 +47 -17
  17. package/entity/BaseEntity.d.ts +2 -2
  18. package/entity/BaseEntity.js +0 -3
  19. package/entity/Collection.d.ts +95 -31
  20. package/entity/Collection.js +444 -102
  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 +88 -54
  25. package/entity/EntityHelper.d.ts +2 -2
  26. package/entity/EntityHelper.js +38 -15
  27. package/entity/EntityLoader.d.ts +8 -7
  28. package/entity/EntityLoader.js +134 -80
  29. package/entity/EntityRepository.d.ts +24 -4
  30. package/entity/EntityRepository.js +8 -2
  31. package/entity/Reference.d.ts +9 -12
  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 +585 -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 +22 -6
  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/events/EventSubscriber.d.ts +3 -1
  50. package/hydration/Hydrator.js +1 -2
  51. package/hydration/ObjectHydrator.d.ts +4 -4
  52. package/hydration/ObjectHydrator.js +53 -33
  53. package/index.d.ts +2 -2
  54. package/index.js +1 -2
  55. package/logging/DefaultLogger.d.ts +1 -1
  56. package/logging/DefaultLogger.js +1 -0
  57. package/logging/SimpleLogger.d.ts +1 -1
  58. package/logging/colors.d.ts +1 -1
  59. package/logging/colors.js +7 -6
  60. package/logging/index.d.ts +1 -0
  61. package/logging/index.js +1 -0
  62. package/logging/inspect.d.ts +2 -0
  63. package/logging/inspect.js +11 -0
  64. package/metadata/EntitySchema.d.ts +26 -26
  65. package/metadata/EntitySchema.js +82 -51
  66. package/metadata/MetadataDiscovery.d.ts +7 -10
  67. package/metadata/MetadataDiscovery.js +408 -335
  68. package/metadata/MetadataProvider.d.ts +11 -2
  69. package/metadata/MetadataProvider.js +46 -2
  70. package/metadata/MetadataStorage.d.ts +13 -11
  71. package/metadata/MetadataStorage.js +70 -37
  72. package/metadata/MetadataValidator.d.ts +17 -9
  73. package/metadata/MetadataValidator.js +100 -42
  74. package/metadata/discover-entities.d.ts +5 -0
  75. package/metadata/discover-entities.js +40 -0
  76. package/metadata/index.d.ts +1 -1
  77. package/metadata/index.js +1 -1
  78. package/metadata/types.d.ts +502 -0
  79. package/metadata/types.js +1 -0
  80. package/naming-strategy/AbstractNamingStrategy.d.ts +12 -4
  81. package/naming-strategy/AbstractNamingStrategy.js +14 -2
  82. package/naming-strategy/EntityCaseNamingStrategy.d.ts +3 -3
  83. package/naming-strategy/EntityCaseNamingStrategy.js +6 -5
  84. package/naming-strategy/MongoNamingStrategy.d.ts +3 -3
  85. package/naming-strategy/MongoNamingStrategy.js +6 -6
  86. package/naming-strategy/NamingStrategy.d.ts +24 -4
  87. package/naming-strategy/UnderscoreNamingStrategy.d.ts +3 -3
  88. package/naming-strategy/UnderscoreNamingStrategy.js +6 -6
  89. package/not-supported.d.ts +2 -0
  90. package/not-supported.js +4 -0
  91. package/package.json +19 -11
  92. package/platforms/ExceptionConverter.js +1 -1
  93. package/platforms/Platform.d.ts +7 -13
  94. package/platforms/Platform.js +20 -43
  95. package/serialization/EntitySerializer.d.ts +5 -0
  96. package/serialization/EntitySerializer.js +47 -27
  97. package/serialization/EntityTransformer.js +28 -18
  98. package/serialization/SerializationContext.d.ts +6 -6
  99. package/serialization/SerializationContext.js +16 -13
  100. package/types/ArrayType.d.ts +1 -1
  101. package/types/ArrayType.js +2 -3
  102. package/types/BigIntType.d.ts +9 -6
  103. package/types/BigIntType.js +4 -1
  104. package/types/BlobType.d.ts +0 -1
  105. package/types/BlobType.js +0 -3
  106. package/types/BooleanType.d.ts +2 -1
  107. package/types/BooleanType.js +3 -0
  108. package/types/DecimalType.d.ts +6 -4
  109. package/types/DecimalType.js +3 -3
  110. package/types/DoubleType.js +2 -2
  111. package/types/EnumArrayType.js +1 -2
  112. package/types/JsonType.d.ts +1 -1
  113. package/types/JsonType.js +7 -2
  114. package/types/TinyIntType.js +1 -1
  115. package/types/Type.d.ts +2 -4
  116. package/types/Type.js +3 -3
  117. package/types/Uint8ArrayType.d.ts +0 -1
  118. package/types/Uint8ArrayType.js +1 -4
  119. package/types/index.d.ts +1 -1
  120. package/typings.d.ts +300 -140
  121. package/typings.js +62 -44
  122. package/unit-of-work/ChangeSet.d.ts +2 -6
  123. package/unit-of-work/ChangeSet.js +4 -5
  124. package/unit-of-work/ChangeSetComputer.d.ts +1 -3
  125. package/unit-of-work/ChangeSetComputer.js +26 -13
  126. package/unit-of-work/ChangeSetPersister.d.ts +5 -4
  127. package/unit-of-work/ChangeSetPersister.js +77 -35
  128. package/unit-of-work/CommitOrderCalculator.d.ts +12 -10
  129. package/unit-of-work/CommitOrderCalculator.js +13 -13
  130. package/unit-of-work/IdentityMap.d.ts +12 -0
  131. package/unit-of-work/IdentityMap.js +39 -1
  132. package/unit-of-work/UnitOfWork.d.ts +23 -3
  133. package/unit-of-work/UnitOfWork.js +199 -106
  134. package/utils/AbstractSchemaGenerator.d.ts +5 -5
  135. package/utils/AbstractSchemaGenerator.js +22 -17
  136. package/utils/AsyncContext.d.ts +6 -0
  137. package/utils/AsyncContext.js +42 -0
  138. package/utils/Configuration.d.ts +779 -207
  139. package/utils/Configuration.js +146 -190
  140. package/utils/ConfigurationLoader.d.ts +1 -54
  141. package/utils/ConfigurationLoader.js +1 -352
  142. package/utils/Cursor.d.ts +3 -6
  143. package/utils/Cursor.js +27 -11
  144. package/utils/DataloaderUtils.d.ts +15 -5
  145. package/utils/DataloaderUtils.js +65 -17
  146. package/utils/EntityComparator.d.ts +13 -9
  147. package/utils/EntityComparator.js +164 -89
  148. package/utils/QueryHelper.d.ts +14 -6
  149. package/utils/QueryHelper.js +88 -26
  150. package/utils/RawQueryFragment.d.ts +48 -25
  151. package/utils/RawQueryFragment.js +67 -66
  152. package/utils/RequestContext.js +2 -2
  153. package/utils/TransactionContext.js +2 -2
  154. package/utils/TransactionManager.d.ts +65 -0
  155. package/utils/TransactionManager.js +223 -0
  156. package/utils/Utils.d.ts +13 -120
  157. package/utils/Utils.js +104 -375
  158. package/utils/clone.js +8 -23
  159. package/utils/env-vars.d.ts +7 -0
  160. package/utils/env-vars.js +97 -0
  161. package/utils/fs-utils.d.ts +32 -0
  162. package/utils/fs-utils.js +178 -0
  163. package/utils/index.d.ts +2 -1
  164. package/utils/index.js +2 -1
  165. package/utils/upsert-utils.d.ts +9 -4
  166. package/utils/upsert-utils.js +55 -4
  167. package/decorators/Check.d.ts +0 -3
  168. package/decorators/Check.js +0 -13
  169. package/decorators/CreateRequestContext.d.ts +0 -3
  170. package/decorators/CreateRequestContext.js +0 -29
  171. package/decorators/Embeddable.d.ts +0 -8
  172. package/decorators/Embeddable.js +0 -11
  173. package/decorators/Embedded.d.ts +0 -18
  174. package/decorators/Embedded.js +0 -18
  175. package/decorators/Entity.d.ts +0 -18
  176. package/decorators/Entity.js +0 -13
  177. package/decorators/Enum.d.ts +0 -9
  178. package/decorators/Enum.js +0 -16
  179. package/decorators/Filter.d.ts +0 -2
  180. package/decorators/Filter.js +0 -8
  181. package/decorators/Formula.d.ts +0 -5
  182. package/decorators/Formula.js +0 -15
  183. package/decorators/Indexed.d.ts +0 -17
  184. package/decorators/Indexed.js +0 -20
  185. package/decorators/ManyToMany.d.ts +0 -40
  186. package/decorators/ManyToMany.js +0 -14
  187. package/decorators/ManyToOne.d.ts +0 -30
  188. package/decorators/ManyToOne.js +0 -14
  189. package/decorators/OneToMany.d.ts +0 -28
  190. package/decorators/OneToMany.js +0 -17
  191. package/decorators/OneToOne.d.ts +0 -24
  192. package/decorators/OneToOne.js +0 -7
  193. package/decorators/PrimaryKey.d.ts +0 -9
  194. package/decorators/PrimaryKey.js +0 -20
  195. package/decorators/Property.d.ts +0 -250
  196. package/decorators/Property.js +0 -32
  197. package/decorators/Transactional.d.ts +0 -13
  198. package/decorators/Transactional.js +0 -28
  199. package/decorators/hooks.d.ts +0 -16
  200. package/decorators/hooks.js +0 -47
  201. package/decorators/index.d.ts +0 -17
  202. package/decorators/index.js +0 -17
  203. package/entity/ArrayCollection.d.ts +0 -116
  204. package/entity/ArrayCollection.js +0 -395
  205. package/entity/EntityValidator.d.ts +0 -19
  206. package/entity/EntityValidator.js +0 -150
  207. package/metadata/ReflectMetadataProvider.d.ts +0 -8
  208. package/metadata/ReflectMetadataProvider.js +0 -44
  209. package/utils/resolveContextProvider.d.ts +0 -10
  210. package/utils/resolveContextProvider.js +0 -28
@@ -1,17 +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
- _em;
11
- // this is for some reason needed for TS, otherwise it can fail with `Type instantiation is excessively deep and possibly infinite.`
12
- _snapshot;
13
20
  constructor(owner, items, initialized = true) {
14
- 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
+ }
15
28
  this.initialized = !!items || initialized;
16
29
  }
17
30
  /**
@@ -33,6 +46,7 @@ export class Collection extends ArrayCollection {
33
46
  async load(options = {}) {
34
47
  if (this.isInitialized(true) && !options.refresh) {
35
48
  const em = this.getEntityManager(this.items, false);
49
+ options = { ...options, filters: QueryHelper.mergePropertyFilters(this.property.filters, options.filters) };
36
50
  await em?.populate(this.items, options.populate, options);
37
51
  this.setSerializationContext(options);
38
52
  }
@@ -53,7 +67,7 @@ export class Collection extends ArrayCollection {
53
67
  */
54
68
  async loadItems(options) {
55
69
  await this.load(options);
56
- return super.getItems();
70
+ return this.getItems(false);
57
71
  }
58
72
  /**
59
73
  * Gets the count of collection items from database instead of counting loaded items.
@@ -62,7 +76,7 @@ export class Collection extends ArrayCollection {
62
76
  async loadCount(options = {}) {
63
77
  options = typeof options === 'boolean' ? { refresh: options } : options;
64
78
  const { refresh, where, ...countOptions } = options;
65
- if (!refresh && !where && Utils.isDefined(this._count)) {
79
+ if (!refresh && !where && this._count != null) {
66
80
  return this._count;
67
81
  }
68
82
  const em = this.getEntityManager();
@@ -70,7 +84,7 @@ export class Collection extends ArrayCollection {
70
84
  return this._count = this.length;
71
85
  }
72
86
  const cond = this.createLoadCountCondition(where ?? {});
73
- const count = await em.count(this.property.type, cond, countOptions);
87
+ const count = await em.count(this.property.targetMeta.class, cond, countOptions);
74
88
  if (!where) {
75
89
  this._count = count;
76
90
  }
@@ -82,12 +96,14 @@ export class Collection extends ArrayCollection {
82
96
  opts.orderBy = this.createOrderBy(opts.orderBy);
83
97
  let items;
84
98
  if (this.property.kind === ReferenceKind.MANY_TO_MANY && em.getPlatform().usesPivotTable()) {
85
- 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');
86
101
  const map = await em.getDriver().loadFromPivotTable(this.property, [helper(this.owner).__primaryKeys], cond, opts.orderBy, ctx, options);
87
- 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);
88
104
  }
89
105
  else {
90
- items = await em.find(this.property.type, this.createCondition(where), opts);
106
+ items = await em.find(this.property.targetMeta.class, this.createCondition(where), opts);
91
107
  }
92
108
  if (options.store) {
93
109
  this.hydrate(items, true);
@@ -104,98 +120,97 @@ export class Collection extends ArrayCollection {
104
120
  if (check) {
105
121
  this.checkInitialized();
106
122
  }
107
- return super.getItems();
123
+ return [...this.items];
108
124
  }
109
125
  toJSON() {
110
126
  if (!this.isInitialized()) {
111
127
  return [];
112
128
  }
113
- return super.toJSON();
129
+ return this.toArray();
114
130
  }
115
131
  add(entity, ...entities) {
116
132
  entities = Utils.asArray(entity).concat(entities);
117
133
  const unwrapped = entities.map(i => Reference.unwrapReference(i));
118
- unwrapped.forEach(entity => this.validateItemType(entity));
119
- 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
+ }
120
151
  this.cancelOrphanRemoval(unwrapped);
152
+ return added;
121
153
  }
122
154
  /**
123
- * @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.
124
159
  */
125
160
  remove(entity, ...entities) {
126
161
  if (entity instanceof Function) {
162
+ let removed = 0;
127
163
  for (const item of this.items) {
128
164
  if (entity(item)) {
129
- this.remove(item);
165
+ removed += this.remove(item);
130
166
  }
131
167
  }
132
- return;
168
+ return removed;
133
169
  }
170
+ this.checkInitialized();
134
171
  entities = Utils.asArray(entity).concat(entities);
135
172
  const unwrapped = entities.map(i => Reference.unwrapReference(i));
136
- this.modify('remove', unwrapped);
137
- const em = this.getEntityManager(unwrapped, false);
138
- if (this.property.orphanRemoval && em) {
139
- for (const item of unwrapped) {
140
- 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;
141
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
142
197
  }
198
+ return removed;
143
199
  }
144
200
  contains(item, check = true) {
145
201
  if (check) {
146
202
  this.checkInitialized();
147
203
  }
148
- return super.contains(item);
204
+ const entity = Reference.unwrapReference(item);
205
+ return this.items.has(entity);
149
206
  }
150
207
  count() {
151
208
  this.checkInitialized();
152
- return super.count();
209
+ return this.items.size;
153
210
  }
154
211
  isEmpty() {
155
212
  this.checkInitialized();
156
- return super.isEmpty();
157
- }
158
- /**
159
- * @inheritDoc
160
- */
161
- slice(start, end) {
162
- this.checkInitialized();
163
- return super.slice(start, end);
164
- }
165
- /**
166
- * @inheritDoc
167
- */
168
- exists(cb) {
169
- this.checkInitialized();
170
- return super.exists(cb);
171
- }
172
- /**
173
- * @inheritDoc
174
- */
175
- find(cb) {
176
- this.checkInitialized();
177
- return super.find(cb);
178
- }
179
- /**
180
- * @inheritDoc
181
- */
182
- filter(cb) {
183
- this.checkInitialized();
184
- return super.filter(cb);
185
- }
186
- /**
187
- * @inheritDoc
188
- */
189
- map(mapper) {
190
- this.checkInitialized();
191
- return super.map(mapper);
192
- }
193
- /**
194
- * @inheritDoc
195
- */
196
- indexBy(key, valueKey) {
197
- this.checkInitialized();
198
- return super.indexBy(key, valueKey);
213
+ return this.count() === 0;
199
214
  }
200
215
  shouldPopulate(populated) {
201
216
  if (!this.isInitialized(true)) {
@@ -218,13 +233,21 @@ export class Collection extends ArrayCollection {
218
233
  return this;
219
234
  }
220
235
  const em = this.getEntityManager();
236
+ options = { ...options, filters: QueryHelper.mergePropertyFilters(this.property.filters, options.filters) };
221
237
  if (options.dataloader ?? [DataloaderType.ALL, DataloaderType.COLLECTION].includes(em.config.getDataloaderType())) {
222
238
  const order = [...this.items]; // copy order of references
223
- const customOrder = !!options.orderBy;
224
- // eslint-disable-next-line dot-notation
225
- const items = await em['colLoader'].load([this, options]);
226
- if (!customOrder) {
227
- this.reorderItems(items, order);
239
+ const orderBy = this.createOrderBy(options.orderBy);
240
+ const customOrder = orderBy.length > 0;
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;
228
251
  }
229
252
  this.items.clear();
230
253
  let i = 0;
@@ -254,7 +277,7 @@ export class Collection extends ArrayCollection {
254
277
  }
255
278
  getEntityManager(items = [], required = true) {
256
279
  const wrapped = helper(this.owner);
257
- let em = (this._em ?? wrapped.__em);
280
+ let em = wrapped.__em;
258
281
  if (!em) {
259
282
  for (const i of items) {
260
283
  if (i && helper(i).__em) {
@@ -263,9 +286,6 @@ export class Collection extends ArrayCollection {
263
286
  }
264
287
  }
265
288
  }
266
- if (em) {
267
- Object.defineProperty(this, '_em', { value: em });
268
- }
269
289
  if (!em && required) {
270
290
  throw ValidationError.entityNotManaged(this.owner);
271
291
  }
@@ -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;