@mikro-orm/core 7.0.10 → 7.0.11-dev.1

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