@mikro-orm/core 7.0.0-dev.12 → 7.0.0-dev.120

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