@mikro-orm/core 7.0.0-dev.3 → 7.0.0-dev.300

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