@yandjin-mikro-orm/core 6.1.4-rc-sti-changes-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 (264) hide show
  1. package/EntityManager.d.ts +553 -0
  2. package/EntityManager.js +1736 -0
  3. package/LICENSE +21 -0
  4. package/MikroORM.d.ts +102 -0
  5. package/MikroORM.js +258 -0
  6. package/README.md +383 -0
  7. package/cache/CacheAdapter.d.ts +40 -0
  8. package/cache/CacheAdapter.js +2 -0
  9. package/cache/FileCacheAdapter.d.ts +31 -0
  10. package/cache/FileCacheAdapter.js +90 -0
  11. package/cache/GeneratedCacheAdapter.d.ts +25 -0
  12. package/cache/GeneratedCacheAdapter.js +38 -0
  13. package/cache/MemoryCacheAdapter.d.ts +24 -0
  14. package/cache/MemoryCacheAdapter.js +44 -0
  15. package/cache/NullCacheAdapter.d.ts +19 -0
  16. package/cache/NullCacheAdapter.js +30 -0
  17. package/cache/index.d.ts +5 -0
  18. package/cache/index.js +21 -0
  19. package/connections/Connection.d.ts +85 -0
  20. package/connections/Connection.js +128 -0
  21. package/connections/index.d.ts +1 -0
  22. package/connections/index.js +17 -0
  23. package/decorators/Check.d.ts +3 -0
  24. package/decorators/Check.js +17 -0
  25. package/decorators/CreateRequestContext.d.ts +2 -0
  26. package/decorators/CreateRequestContext.js +31 -0
  27. package/decorators/Embeddable.d.ts +8 -0
  28. package/decorators/Embeddable.js +15 -0
  29. package/decorators/Embedded.d.ts +13 -0
  30. package/decorators/Embedded.js +21 -0
  31. package/decorators/EnsureRequestContext.d.ts +2 -0
  32. package/decorators/EnsureRequestContext.js +26 -0
  33. package/decorators/Entity.d.ts +18 -0
  34. package/decorators/Entity.js +17 -0
  35. package/decorators/Enum.d.ts +9 -0
  36. package/decorators/Enum.js +20 -0
  37. package/decorators/Filter.d.ts +2 -0
  38. package/decorators/Filter.js +12 -0
  39. package/decorators/Formula.d.ts +5 -0
  40. package/decorators/Formula.js +19 -0
  41. package/decorators/Indexed.d.ts +12 -0
  42. package/decorators/Indexed.js +25 -0
  43. package/decorators/ManyToMany.d.ts +21 -0
  44. package/decorators/ManyToMany.js +17 -0
  45. package/decorators/ManyToOne.d.ts +15 -0
  46. package/decorators/ManyToOne.js +17 -0
  47. package/decorators/OneToMany.d.ts +18 -0
  48. package/decorators/OneToMany.js +21 -0
  49. package/decorators/OneToOne.d.ts +12 -0
  50. package/decorators/OneToOne.js +11 -0
  51. package/decorators/PrimaryKey.d.ts +8 -0
  52. package/decorators/PrimaryKey.js +24 -0
  53. package/decorators/Property.d.ts +218 -0
  54. package/decorators/Property.js +35 -0
  55. package/decorators/Subscriber.d.ts +1 -0
  56. package/decorators/Subscriber.js +2 -0
  57. package/decorators/hooks.d.ts +16 -0
  58. package/decorators/hooks.js +60 -0
  59. package/decorators/index.d.ts +17 -0
  60. package/decorators/index.js +36 -0
  61. package/drivers/DatabaseDriver.d.ts +72 -0
  62. package/drivers/DatabaseDriver.js +358 -0
  63. package/drivers/IDatabaseDriver.d.ts +193 -0
  64. package/drivers/IDatabaseDriver.js +4 -0
  65. package/drivers/index.d.ts +2 -0
  66. package/drivers/index.js +18 -0
  67. package/entity/ArrayCollection.d.ts +113 -0
  68. package/entity/ArrayCollection.js +386 -0
  69. package/entity/BaseEntity.d.ts +22 -0
  70. package/entity/BaseEntity.js +47 -0
  71. package/entity/Collection.d.ts +104 -0
  72. package/entity/Collection.js +373 -0
  73. package/entity/EntityAssigner.d.ts +28 -0
  74. package/entity/EntityAssigner.js +226 -0
  75. package/entity/EntityFactory.d.ts +41 -0
  76. package/entity/EntityFactory.js +302 -0
  77. package/entity/EntityHelper.d.ts +29 -0
  78. package/entity/EntityHelper.js +250 -0
  79. package/entity/EntityIdentifier.d.ts +10 -0
  80. package/entity/EntityIdentifier.js +19 -0
  81. package/entity/EntityLoader.d.ts +65 -0
  82. package/entity/EntityLoader.js +579 -0
  83. package/entity/EntityRepository.d.ts +161 -0
  84. package/entity/EntityRepository.js +207 -0
  85. package/entity/EntityValidator.d.ts +19 -0
  86. package/entity/EntityValidator.js +152 -0
  87. package/entity/Reference.d.ts +89 -0
  88. package/entity/Reference.js +242 -0
  89. package/entity/WrappedEntity.d.ts +67 -0
  90. package/entity/WrappedEntity.js +146 -0
  91. package/entity/index.d.ts +13 -0
  92. package/entity/index.js +29 -0
  93. package/entity/wrap.d.ts +15 -0
  94. package/entity/wrap.js +26 -0
  95. package/enums.d.ts +160 -0
  96. package/enums.js +169 -0
  97. package/errors.d.ts +65 -0
  98. package/errors.js +222 -0
  99. package/events/EventManager.d.ts +17 -0
  100. package/events/EventManager.js +77 -0
  101. package/events/EventSubscriber.d.ts +39 -0
  102. package/events/EventSubscriber.js +2 -0
  103. package/events/TransactionEventBroadcaster.d.ts +11 -0
  104. package/events/TransactionEventBroadcaster.js +17 -0
  105. package/events/index.d.ts +3 -0
  106. package/events/index.js +19 -0
  107. package/exceptions.d.ts +104 -0
  108. package/exceptions.js +130 -0
  109. package/hydration/Hydrator.d.ts +23 -0
  110. package/hydration/Hydrator.js +51 -0
  111. package/hydration/ObjectHydrator.d.ts +24 -0
  112. package/hydration/ObjectHydrator.js +332 -0
  113. package/hydration/index.d.ts +2 -0
  114. package/hydration/index.js +18 -0
  115. package/index.d.ts +25 -0
  116. package/index.js +50 -0
  117. package/index.mjs +192 -0
  118. package/logging/DefaultLogger.d.ts +32 -0
  119. package/logging/DefaultLogger.js +90 -0
  120. package/logging/Logger.d.ts +56 -0
  121. package/logging/Logger.js +2 -0
  122. package/logging/SimpleLogger.d.ts +17 -0
  123. package/logging/SimpleLogger.js +31 -0
  124. package/logging/colors.d.ts +9 -0
  125. package/logging/colors.js +20 -0
  126. package/logging/index.d.ts +4 -0
  127. package/logging/index.js +20 -0
  128. package/metadata/EntitySchema.d.ts +74 -0
  129. package/metadata/EntitySchema.js +293 -0
  130. package/metadata/MetadataDiscovery.d.ts +71 -0
  131. package/metadata/MetadataDiscovery.js +1244 -0
  132. package/metadata/MetadataProvider.d.ts +11 -0
  133. package/metadata/MetadataProvider.js +23 -0
  134. package/metadata/MetadataStorage.d.ts +22 -0
  135. package/metadata/MetadataStorage.js +87 -0
  136. package/metadata/MetadataValidator.d.ts +24 -0
  137. package/metadata/MetadataValidator.js +213 -0
  138. package/metadata/ReflectMetadataProvider.d.ts +8 -0
  139. package/metadata/ReflectMetadataProvider.js +48 -0
  140. package/metadata/index.d.ts +6 -0
  141. package/metadata/index.js +22 -0
  142. package/naming-strategy/AbstractNamingStrategy.d.ts +18 -0
  143. package/naming-strategy/AbstractNamingStrategy.js +48 -0
  144. package/naming-strategy/EntityCaseNamingStrategy.d.ts +12 -0
  145. package/naming-strategy/EntityCaseNamingStrategy.js +32 -0
  146. package/naming-strategy/MongoNamingStrategy.d.ts +9 -0
  147. package/naming-strategy/MongoNamingStrategy.js +25 -0
  148. package/naming-strategy/NamingStrategy.d.ts +52 -0
  149. package/naming-strategy/NamingStrategy.js +2 -0
  150. package/naming-strategy/UnderscoreNamingStrategy.d.ts +10 -0
  151. package/naming-strategy/UnderscoreNamingStrategy.js +28 -0
  152. package/naming-strategy/index.d.ts +5 -0
  153. package/naming-strategy/index.js +21 -0
  154. package/package.json +70 -0
  155. package/platforms/ExceptionConverter.d.ts +5 -0
  156. package/platforms/ExceptionConverter.js +11 -0
  157. package/platforms/Platform.d.ts +201 -0
  158. package/platforms/Platform.js +452 -0
  159. package/platforms/index.d.ts +2 -0
  160. package/platforms/index.js +18 -0
  161. package/serialization/EntitySerializer.d.ts +34 -0
  162. package/serialization/EntitySerializer.js +206 -0
  163. package/serialization/EntityTransformer.d.ts +8 -0
  164. package/serialization/EntityTransformer.js +192 -0
  165. package/serialization/SerializationContext.d.ts +30 -0
  166. package/serialization/SerializationContext.js +111 -0
  167. package/serialization/index.d.ts +3 -0
  168. package/serialization/index.js +19 -0
  169. package/types/ArrayType.d.ts +13 -0
  170. package/types/ArrayType.js +47 -0
  171. package/types/BigIntType.d.ts +16 -0
  172. package/types/BigIntType.js +45 -0
  173. package/types/BlobType.d.ts +10 -0
  174. package/types/BlobType.js +27 -0
  175. package/types/BooleanType.d.ts +8 -0
  176. package/types/BooleanType.js +16 -0
  177. package/types/DateTimeType.d.ts +8 -0
  178. package/types/DateTimeType.js +16 -0
  179. package/types/DateType.d.ts +8 -0
  180. package/types/DateType.js +16 -0
  181. package/types/DecimalType.d.ts +11 -0
  182. package/types/DecimalType.js +22 -0
  183. package/types/DoubleType.d.ts +11 -0
  184. package/types/DoubleType.js +22 -0
  185. package/types/EnumArrayType.d.ts +9 -0
  186. package/types/EnumArrayType.js +32 -0
  187. package/types/EnumType.d.ts +8 -0
  188. package/types/EnumType.js +16 -0
  189. package/types/FloatType.d.ts +8 -0
  190. package/types/FloatType.js +16 -0
  191. package/types/IntegerType.d.ts +8 -0
  192. package/types/IntegerType.js +16 -0
  193. package/types/IntervalType.d.ts +8 -0
  194. package/types/IntervalType.js +16 -0
  195. package/types/JsonType.d.ts +13 -0
  196. package/types/JsonType.js +34 -0
  197. package/types/MediumIntType.d.ts +6 -0
  198. package/types/MediumIntType.js +10 -0
  199. package/types/SmallIntType.d.ts +8 -0
  200. package/types/SmallIntType.js +16 -0
  201. package/types/StringType.d.ts +8 -0
  202. package/types/StringType.js +16 -0
  203. package/types/TextType.d.ts +8 -0
  204. package/types/TextType.js +16 -0
  205. package/types/TimeType.d.ts +9 -0
  206. package/types/TimeType.js +23 -0
  207. package/types/TinyIntType.d.ts +8 -0
  208. package/types/TinyIntType.js +16 -0
  209. package/types/Type.d.ts +64 -0
  210. package/types/Type.js +84 -0
  211. package/types/Uint8ArrayType.d.ts +11 -0
  212. package/types/Uint8ArrayType.js +37 -0
  213. package/types/UnknownType.d.ts +7 -0
  214. package/types/UnknownType.js +13 -0
  215. package/types/UuidType.d.ts +7 -0
  216. package/types/UuidType.js +13 -0
  217. package/types/index.d.ts +75 -0
  218. package/types/index.js +77 -0
  219. package/typings.d.ts +767 -0
  220. package/typings.js +198 -0
  221. package/unit-of-work/ChangeSet.d.ts +34 -0
  222. package/unit-of-work/ChangeSet.js +62 -0
  223. package/unit-of-work/ChangeSetComputer.d.ts +26 -0
  224. package/unit-of-work/ChangeSetComputer.js +153 -0
  225. package/unit-of-work/ChangeSetPersister.d.ts +50 -0
  226. package/unit-of-work/ChangeSetPersister.js +361 -0
  227. package/unit-of-work/CommitOrderCalculator.d.ts +62 -0
  228. package/unit-of-work/CommitOrderCalculator.js +113 -0
  229. package/unit-of-work/IdentityMap.d.ts +17 -0
  230. package/unit-of-work/IdentityMap.js +84 -0
  231. package/unit-of-work/UnitOfWork.d.ts +124 -0
  232. package/unit-of-work/UnitOfWork.js +1013 -0
  233. package/unit-of-work/index.d.ts +6 -0
  234. package/unit-of-work/index.js +22 -0
  235. package/utils/AbstractSchemaGenerator.d.ts +38 -0
  236. package/utils/AbstractSchemaGenerator.js +101 -0
  237. package/utils/Configuration.d.ts +390 -0
  238. package/utils/Configuration.js +357 -0
  239. package/utils/ConfigurationLoader.d.ts +29 -0
  240. package/utils/ConfigurationLoader.js +282 -0
  241. package/utils/Cursor.d.ts +77 -0
  242. package/utils/Cursor.js +169 -0
  243. package/utils/DataloaderUtils.d.ts +43 -0
  244. package/utils/DataloaderUtils.js +194 -0
  245. package/utils/EntityComparator.d.ts +73 -0
  246. package/utils/EntityComparator.js +568 -0
  247. package/utils/NullHighlighter.d.ts +4 -0
  248. package/utils/NullHighlighter.js +9 -0
  249. package/utils/QueryHelper.d.ts +28 -0
  250. package/utils/QueryHelper.js +228 -0
  251. package/utils/RawQueryFragment.d.ts +96 -0
  252. package/utils/RawQueryFragment.js +188 -0
  253. package/utils/RequestContext.d.ts +34 -0
  254. package/utils/RequestContext.js +54 -0
  255. package/utils/TransactionContext.d.ts +19 -0
  256. package/utils/TransactionContext.js +34 -0
  257. package/utils/Utils.d.ts +274 -0
  258. package/utils/Utils.js +1073 -0
  259. package/utils/clone.d.ts +6 -0
  260. package/utils/clone.js +127 -0
  261. package/utils/index.d.ts +13 -0
  262. package/utils/index.js +29 -0
  263. package/utils/upsert-utils.d.ts +6 -0
  264. package/utils/upsert-utils.js +33 -0
@@ -0,0 +1,579 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.EntityLoader = void 0;
4
+ const QueryHelper_1 = require("../utils/QueryHelper");
5
+ const Utils_1 = require("../utils/Utils");
6
+ const errors_1 = require("../errors");
7
+ const enums_1 = require("../enums");
8
+ const Reference_1 = require("./Reference");
9
+ const wrap_1 = require("./wrap");
10
+ class EntityLoader {
11
+ em;
12
+ metadata;
13
+ driver;
14
+ constructor(em) {
15
+ this.em = em;
16
+ this.metadata = this.em.getMetadata();
17
+ this.driver = this.em.getDriver();
18
+ }
19
+ /**
20
+ * Loads specified relations in batch.
21
+ * This will execute one query for each relation, that will populate it on all the specified entities.
22
+ */
23
+ async populate(entityName, entities, populate, options) {
24
+ if (entities.length === 0 || Utils_1.Utils.isEmpty(populate)) {
25
+ return;
26
+ }
27
+ const meta = this.metadata.find(entityName);
28
+ if (entities.some(e => !e.__helper)) {
29
+ const entity = entities.find(e => !Utils_1.Utils.isEntity(e));
30
+ throw errors_1.ValidationError.notDiscoveredEntity(entity, meta, 'populate');
31
+ }
32
+ const visited = options.visited ??= new Set();
33
+ options.where ??= {};
34
+ options.orderBy ??= {};
35
+ options.filters ??= {};
36
+ options.lookup ??= true;
37
+ options.validate ??= true;
38
+ options.refresh ??= false;
39
+ options.convertCustomTypes ??= true;
40
+ populate = this.normalizePopulate(entityName, populate, options.strategy, options.lookup);
41
+ const exclude = options.exclude ?? [];
42
+ const extending = this.em.getSTIExtendingMetadata(meta);
43
+ const invalid = populate.find(({ field }) => extending.every(meta => !this.em.canPopulate(meta.className, field)));
44
+ /* istanbul ignore next */
45
+ if (options.validate && invalid) {
46
+ throw errors_1.ValidationError.invalidPropertyName(entityName, invalid.field);
47
+ }
48
+ for (const entity of entities) {
49
+ const context = (0, wrap_1.helper)(entity).__serializationContext;
50
+ context.populate = context.populate ? context.populate.concat(populate) : populate;
51
+ if (context.fields && options.fields) {
52
+ options.fields.forEach(f => context.fields.add(f));
53
+ }
54
+ else if (options.fields) {
55
+ context.fields = new Set(options.fields);
56
+ }
57
+ context.exclude = context.exclude ? context.exclude.concat(exclude) : exclude;
58
+ visited.add(entity);
59
+ }
60
+ // group entities by sub type (STI)
61
+ const entitiesByType = entities.reduce((groups, entity) => {
62
+ const className = (0, wrap_1.helper)(entity).__meta.className;
63
+ return {
64
+ ...groups,
65
+ [className]: [...(groups[className] ?? []), entity],
66
+ };
67
+ }, {});
68
+ for (const pop of populate) {
69
+ for (const [entityClassName, entities] of Object.entries(entitiesByType)) {
70
+ await this.populateField(entityClassName, entities, pop, options);
71
+ }
72
+ }
73
+ }
74
+ normalizePopulate(entityName, populate, strategy, lookup = true) {
75
+ const meta = this.metadata.find(entityName);
76
+ let normalized = Utils_1.Utils.asArray(populate).map(field => {
77
+ return typeof field === 'boolean' || field.field === '*' ? { all: !!field, field: meta.primaryKeys[0] } : field;
78
+ });
79
+ if (normalized.some(p => p.all)) {
80
+ normalized = this.lookupAllRelationships(entityName);
81
+ }
82
+ // convert nested `field` with dot syntax to PopulateOptions with `children` array
83
+ this.expandDotPaths(normalized, meta);
84
+ if (lookup && populate !== false) {
85
+ normalized = this.lookupEagerLoadedRelationships(entityName, normalized, strategy);
86
+ // convert nested `field` with dot syntax produced by eager relations
87
+ this.expandDotPaths(normalized, meta);
88
+ }
89
+ // merge same fields
90
+ return this.mergeNestedPopulate(normalized);
91
+ }
92
+ expandDotPaths(normalized, meta) {
93
+ normalized.forEach(p => {
94
+ if (!p.field.includes('.')) {
95
+ return;
96
+ }
97
+ const [f, ...parts] = p.field.split('.');
98
+ p.field = f;
99
+ p.children ??= [];
100
+ const prop = meta.properties[f];
101
+ p.strategy ??= prop.strategy;
102
+ if (parts[0] === '*') {
103
+ prop.targetMeta.props
104
+ .filter(prop => prop.lazy || prop.kind !== enums_1.ReferenceKind.SCALAR)
105
+ .forEach(prop => p.children.push({ field: prop.name, strategy: p.strategy }));
106
+ }
107
+ else {
108
+ p.children.push(this.expandNestedPopulate(prop.type, parts, p.strategy, p.all));
109
+ }
110
+ });
111
+ }
112
+ /**
113
+ * Merge multiple populates for the same entity with different children. Also skips `*` fields, those can come from
114
+ * partial loading hints (`fields`) that are used to infer the `populate` hint if missing.
115
+ */
116
+ mergeNestedPopulate(populate) {
117
+ const tmp = populate.reduce((ret, item) => {
118
+ if (item.field === '*') {
119
+ return ret;
120
+ }
121
+ if (!ret[item.field]) {
122
+ ret[item.field] = item;
123
+ return ret;
124
+ }
125
+ if (!ret[item.field].children && item.children) {
126
+ ret[item.field].children = item.children;
127
+ }
128
+ else if (ret[item.field].children && item.children) {
129
+ ret[item.field].children.push(...item.children);
130
+ }
131
+ return ret;
132
+ }, {});
133
+ return Object.values(tmp).map(item => {
134
+ if (item.children) {
135
+ item.children = this.mergeNestedPopulate(item.children);
136
+ }
137
+ return item;
138
+ });
139
+ }
140
+ /**
141
+ * Expands `books.perex` like populate to use `children` array instead of the dot syntax
142
+ */
143
+ expandNestedPopulate(entityName, parts, strategy, all) {
144
+ const meta = this.metadata.find(entityName);
145
+ const field = parts.shift();
146
+ const prop = meta.properties[field];
147
+ const ret = { field, strategy, all };
148
+ if (parts.length > 0) {
149
+ ret.children = [this.expandNestedPopulate(prop.type, parts, strategy)];
150
+ }
151
+ return ret;
152
+ }
153
+ /**
154
+ * preload everything in one call (this will update already existing references in IM)
155
+ */
156
+ async populateMany(entityName, entities, populate, options) {
157
+ const [field, ref] = populate.field.split(':', 2);
158
+ const meta = this.metadata.find(entityName);
159
+ const prop = meta.properties[field];
160
+ if (prop.kind === enums_1.ReferenceKind.SCALAR && prop.lazy) {
161
+ const filtered = entities.filter(e => options.refresh || (prop.ref ? !e[prop.name]?.isInitialized() : e[prop.name] === undefined));
162
+ if (options.ignoreLazyScalarProperties || filtered.length === 0) {
163
+ return entities;
164
+ }
165
+ const pk = Utils_1.Utils.getPrimaryKeyHash(meta.primaryKeys);
166
+ const ids = Utils_1.Utils.unique(filtered.map(e => Utils_1.Utils.getPrimaryKeyValues(e, meta.primaryKeys, true)));
167
+ const where = this.mergePrimaryCondition(ids, pk, options, meta, this.metadata, this.driver.getPlatform());
168
+ const { filters, convertCustomTypes, lockMode, strategy, populateWhere, connectionType, logging } = options;
169
+ await this.em.find(meta.className, where, {
170
+ filters, convertCustomTypes, lockMode, strategy, populateWhere, connectionType, logging,
171
+ fields: [prop.name],
172
+ populate: [],
173
+ });
174
+ return entities;
175
+ }
176
+ if (prop.kind === enums_1.ReferenceKind.EMBEDDED) {
177
+ return [];
178
+ }
179
+ const filtered = this.filterCollections(entities, field, options, ref);
180
+ const innerOrderBy = Utils_1.Utils.asArray(options.orderBy)
181
+ .filter(orderBy => (Array.isArray(orderBy[prop.name]) && orderBy[prop.name].length > 0) || Utils_1.Utils.isObject(orderBy[prop.name]))
182
+ .flatMap(orderBy => orderBy[prop.name]);
183
+ if (prop.kind === enums_1.ReferenceKind.MANY_TO_MANY && this.driver.getPlatform().usesPivotTable()) {
184
+ return this.findChildrenFromPivotTable(filtered, prop, options, innerOrderBy, populate, !!ref);
185
+ }
186
+ const where = await this.extractChildCondition(options, prop);
187
+ const data = await this.findChildren(entities, prop, populate, { ...options, where, orderBy: innerOrderBy }, !!ref);
188
+ this.initializeCollections(filtered, prop, field, data, innerOrderBy.length > 0);
189
+ return data;
190
+ }
191
+ initializeCollections(filtered, prop, field, children, customOrder) {
192
+ if (prop.kind === enums_1.ReferenceKind.ONE_TO_MANY) {
193
+ this.initializeOneToMany(filtered, children, prop, field);
194
+ }
195
+ if (prop.kind === enums_1.ReferenceKind.MANY_TO_MANY && !this.driver.getPlatform().usesPivotTable()) {
196
+ this.initializeManyToMany(filtered, children, prop, field, customOrder);
197
+ }
198
+ }
199
+ initializeOneToMany(filtered, children, prop, field) {
200
+ const mapToPk = prop.targetMeta.properties[prop.mappedBy].mapToPk;
201
+ const map = {};
202
+ filtered.forEach(entity => {
203
+ const key = (0, wrap_1.helper)(entity).getSerializedPrimaryKey();
204
+ return map[key] = [];
205
+ });
206
+ if (mapToPk) {
207
+ children.forEach(child => {
208
+ const pk = child.__helper.__data[prop.mappedBy] ?? child[prop.mappedBy];
209
+ if (pk) {
210
+ const key = (0, wrap_1.helper)(this.em.getReference(prop.type, pk)).getSerializedPrimaryKey();
211
+ map[key]?.push(child);
212
+ }
213
+ });
214
+ }
215
+ else {
216
+ children.forEach(child => {
217
+ const entity = child.__helper.__data[prop.mappedBy] ?? child[prop.mappedBy];
218
+ if (entity) {
219
+ const key = (0, wrap_1.helper)(entity).getSerializedPrimaryKey();
220
+ map[key]?.push(child);
221
+ }
222
+ });
223
+ }
224
+ filtered.forEach(entity => {
225
+ const key = (0, wrap_1.helper)(entity).getSerializedPrimaryKey();
226
+ entity[field].hydrate(map[key]);
227
+ });
228
+ }
229
+ initializeManyToMany(filtered, children, prop, field, customOrder) {
230
+ if (prop.mappedBy) {
231
+ for (const entity of filtered) {
232
+ const items = children.filter(child => child[prop.mappedBy].contains(entity, false));
233
+ entity[field].hydrate(items, true);
234
+ }
235
+ }
236
+ else { // owning side of M:N without pivot table needs to be reordered
237
+ for (const entity of filtered) {
238
+ const order = !customOrder ? [...entity[prop.name].getItems(false)] : []; // copy order of references
239
+ const items = children.filter(child => entity[prop.name].contains(child, false));
240
+ if (!customOrder) {
241
+ items.sort((a, b) => order.indexOf(a) - order.indexOf(b));
242
+ }
243
+ entity[field].hydrate(items, true);
244
+ }
245
+ }
246
+ }
247
+ async findChildren(entities, prop, populate, options, ref) {
248
+ const children = this.getChildReferences(entities, prop, options, ref);
249
+ const meta = prop.targetMeta;
250
+ let fk = Utils_1.Utils.getPrimaryKeyHash(meta.primaryKeys);
251
+ let schema = options.schema;
252
+ if (prop.kind === enums_1.ReferenceKind.ONE_TO_MANY || (prop.kind === enums_1.ReferenceKind.MANY_TO_MANY && !prop.owner)) {
253
+ fk = meta.properties[prop.mappedBy].name;
254
+ }
255
+ if (prop.kind === enums_1.ReferenceKind.ONE_TO_ONE && !prop.owner) {
256
+ children.length = 0;
257
+ fk = meta.properties[prop.mappedBy].name;
258
+ children.push(...this.filterByReferences(entities, prop.name, options.refresh));
259
+ }
260
+ if (children.length === 0) {
261
+ return [];
262
+ }
263
+ if (!schema && [enums_1.ReferenceKind.ONE_TO_ONE, enums_1.ReferenceKind.MANY_TO_ONE].includes(prop.kind)) {
264
+ schema = children.find(e => e.__helper.__schema)?.__helper.__schema;
265
+ }
266
+ const ids = Utils_1.Utils.unique(children.map(e => e.__helper.getPrimaryKey()));
267
+ let where = this.mergePrimaryCondition(ids, fk, options, meta, this.metadata, this.driver.getPlatform());
268
+ const fields = this.buildFields(options.fields, prop, ref);
269
+ /* eslint-disable prefer-const */
270
+ let { refresh, filters, convertCustomTypes, lockMode, strategy, populateWhere, connectionType, logging, } = options;
271
+ /* eslint-enable prefer-const */
272
+ if (typeof populateWhere === 'object') {
273
+ populateWhere = await this.extractChildCondition({ where: populateWhere }, prop);
274
+ }
275
+ if (!Utils_1.Utils.isEmpty(prop.where)) {
276
+ where = { $and: [where, prop.where] };
277
+ }
278
+ const items = await this.em.find(prop.type, where, {
279
+ filters, convertCustomTypes, lockMode, populateWhere, logging,
280
+ orderBy: [...Utils_1.Utils.asArray(options.orderBy), ...Utils_1.Utils.asArray(prop.orderBy)],
281
+ populate: populate.children ?? populate.all ?? [],
282
+ exclude: Array.isArray(options.exclude) ? Utils_1.Utils.extractChildElements(options.exclude, prop.name) : options.exclude,
283
+ strategy, fields, schema, connectionType,
284
+ // @ts-ignore not a public option, will be propagated to the populate call
285
+ refresh: refresh && !children.every(item => options.visited.has(item)),
286
+ // @ts-ignore not a public option, will be propagated to the populate call
287
+ visited: options.visited,
288
+ });
289
+ for (const item of items) {
290
+ if (ref && !(0, wrap_1.helper)(item).__onLoadFired) {
291
+ (0, wrap_1.helper)(item).__initialized = false;
292
+ // eslint-disable-next-line dot-notation
293
+ this.em.getUnitOfWork()['loadedEntities'].delete(item);
294
+ }
295
+ }
296
+ return items;
297
+ }
298
+ mergePrimaryCondition(ids, pk, options, meta, metadata, platform) {
299
+ const cond1 = QueryHelper_1.QueryHelper.processWhere({ where: { [pk]: { $in: ids } }, entityName: meta.className, metadata, platform, convertCustomTypes: !options.convertCustomTypes });
300
+ return options.where[pk]
301
+ ? { $and: [cond1, options.where] }
302
+ : { ...cond1, ...options.where };
303
+ }
304
+ async populateField(entityName, entities, populate, options) {
305
+ const field = populate.field.split(':')[0];
306
+ const prop = this.metadata.find(entityName).properties[field];
307
+ if (!prop) {
308
+ return;
309
+ }
310
+ if (prop.kind === enums_1.ReferenceKind.SCALAR && !prop.lazy) {
311
+ return;
312
+ }
313
+ const populated = await this.populateMany(entityName, entities, populate, options);
314
+ if (!populate.children && !populate.all) {
315
+ return;
316
+ }
317
+ const children = [];
318
+ for (const entity of entities) {
319
+ const ref = entity[field];
320
+ if (Utils_1.Utils.isEntity(ref)) {
321
+ children.push(ref);
322
+ }
323
+ else if (Reference_1.Reference.isReference(ref)) {
324
+ children.push(ref.unwrap());
325
+ }
326
+ else if (Utils_1.Utils.isCollection(ref)) {
327
+ children.push(...ref.getItems());
328
+ }
329
+ else if (ref && prop.kind === enums_1.ReferenceKind.EMBEDDED) {
330
+ children.push(...Utils_1.Utils.asArray(ref));
331
+ }
332
+ }
333
+ if (populated.length === 0 && !populate.children) {
334
+ return;
335
+ }
336
+ const fields = this.buildFields(options.fields, prop);
337
+ const innerOrderBy = Utils_1.Utils.asArray(options.orderBy)
338
+ .filter(orderBy => Utils_1.Utils.isObject(orderBy[prop.name]))
339
+ .map(orderBy => orderBy[prop.name]);
340
+ const { refresh, filters, ignoreLazyScalarProperties, populateWhere, connectionType, logging } = options;
341
+ const exclude = Array.isArray(options.exclude) ? Utils_1.Utils.extractChildElements(options.exclude, prop.name) : options.exclude;
342
+ const filtered = Utils_1.Utils.unique(children.filter(e => !options.visited.has(e)));
343
+ await this.populate(prop.type, filtered, populate.children ?? populate.all, {
344
+ where: await this.extractChildCondition(options, prop, false),
345
+ orderBy: innerOrderBy,
346
+ fields,
347
+ exclude,
348
+ validate: false,
349
+ lookup: false,
350
+ filters,
351
+ ignoreLazyScalarProperties,
352
+ populateWhere,
353
+ connectionType,
354
+ logging,
355
+ // @ts-ignore not a public option, will be propagated to the populate call
356
+ refresh: refresh && !filtered.every(item => options.visited.has(item)),
357
+ // @ts-ignore not a public option, will be propagated to the populate call
358
+ visited: options.visited,
359
+ });
360
+ }
361
+ async findChildrenFromPivotTable(filtered, prop, options, orderBy, populate, pivotJoin) {
362
+ const ids = filtered.map(e => e.__helper.__primaryKeys);
363
+ const refresh = options.refresh;
364
+ let where = await this.extractChildCondition(options, prop, true);
365
+ const fields = this.buildFields(options.fields, prop);
366
+ const exclude = Array.isArray(options.exclude) ? Utils_1.Utils.extractChildElements(options.exclude, prop.name) : options.exclude;
367
+ const options2 = { ...options };
368
+ delete options2.limit;
369
+ delete options2.offset;
370
+ options2.fields = fields;
371
+ options2.exclude = exclude;
372
+ options2.populate = (populate?.children ?? []);
373
+ if (prop.customType) {
374
+ ids.forEach((id, idx) => ids[idx] = QueryHelper_1.QueryHelper.processCustomType(prop, id, this.driver.getPlatform()));
375
+ }
376
+ if (!Utils_1.Utils.isEmpty(prop.where)) {
377
+ where = { $and: [where, prop.where] };
378
+ }
379
+ const map = await this.driver.loadFromPivotTable(prop, ids, where, orderBy, this.em.getTransactionContext(), options2, pivotJoin);
380
+ const children = [];
381
+ for (const entity of filtered) {
382
+ const items = map[entity.__helper.getSerializedPrimaryKey()].map(item => {
383
+ if (pivotJoin) {
384
+ return this.em.getReference(prop.type, item, {
385
+ convertCustomTypes: true,
386
+ schema: options.schema ?? this.em.config.get('schema'),
387
+ });
388
+ }
389
+ const entity = this.em.getEntityFactory().create(prop.type, item, {
390
+ refresh,
391
+ merge: true,
392
+ convertCustomTypes: true,
393
+ schema: options.schema ?? this.em.config.get('schema'),
394
+ });
395
+ return this.em.getUnitOfWork().register(entity, item, { refresh, loaded: true });
396
+ });
397
+ entity[prop.name].hydrate(items, true);
398
+ children.push(...items);
399
+ }
400
+ return children;
401
+ }
402
+ async extractChildCondition(options, prop, filters = false) {
403
+ const where = options.where;
404
+ const subCond = Utils_1.Utils.isPlainObject(where[prop.name]) ? where[prop.name] : {};
405
+ const meta2 = this.metadata.find(prop.type);
406
+ const pk = Utils_1.Utils.getPrimaryKeyHash(meta2.primaryKeys);
407
+ ['$and', '$or'].forEach(op => {
408
+ if (where[op]) {
409
+ const child = where[op]
410
+ .map((cond) => cond[prop.name])
411
+ .filter((sub) => sub != null && !(Utils_1.Utils.isPlainObject(sub) && Object.keys(sub).every(key => Utils_1.Utils.isOperator(key, false))))
412
+ .map((cond) => {
413
+ if (Utils_1.Utils.isPrimaryKey(cond)) {
414
+ return { [pk]: cond };
415
+ }
416
+ return cond;
417
+ });
418
+ if (child.length > 0) {
419
+ subCond[op] = child;
420
+ }
421
+ }
422
+ });
423
+ const operators = Object.keys(subCond).filter(key => Utils_1.Utils.isOperator(key, false));
424
+ if (operators.length > 0) {
425
+ operators.forEach(op => {
426
+ subCond[pk] ??= {};
427
+ subCond[pk][op] = subCond[op];
428
+ delete subCond[op];
429
+ });
430
+ }
431
+ if (filters) {
432
+ return this.em.applyFilters(prop.type, subCond, options.filters, 'read', options);
433
+ }
434
+ return subCond;
435
+ }
436
+ buildFields(fields = [], prop, ref) {
437
+ if (ref) {
438
+ fields = prop.targetMeta.primaryKeys.map(targetPkName => `${prop.name}.${targetPkName}`);
439
+ }
440
+ const ret = fields.reduce((ret, f) => {
441
+ if (Utils_1.Utils.isPlainObject(f)) {
442
+ Utils_1.Utils.keys(f)
443
+ .filter(ff => ff === prop.name)
444
+ .forEach(ff => ret.push(...f[ff]));
445
+ }
446
+ else if (f.toString().includes('.')) {
447
+ const parts = f.toString().split('.');
448
+ const propName = parts.shift();
449
+ const childPropName = parts.join('.');
450
+ /* istanbul ignore else */
451
+ if (propName === prop.name) {
452
+ ret.push(childPropName);
453
+ }
454
+ }
455
+ return ret;
456
+ }, []);
457
+ if (ret.length === 0) {
458
+ return undefined;
459
+ }
460
+ // we need to automatically select the FKs too, e.g. for 1:m relations to be able to wire them with the items
461
+ if (prop.kind === enums_1.ReferenceKind.ONE_TO_MANY || prop.kind === enums_1.ReferenceKind.MANY_TO_MANY) {
462
+ const owner = prop.targetMeta.properties[prop.mappedBy];
463
+ if (owner && !ret.includes(owner.name)) {
464
+ ret.push(owner.name);
465
+ }
466
+ }
467
+ return ret;
468
+ }
469
+ getChildReferences(entities, prop, options, ref) {
470
+ const filtered = this.filterCollections(entities, prop.name, options, ref);
471
+ const children = [];
472
+ if (prop.kind === enums_1.ReferenceKind.ONE_TO_MANY) {
473
+ children.push(...filtered.map(e => e[prop.name].owner));
474
+ }
475
+ else if (prop.kind === enums_1.ReferenceKind.MANY_TO_MANY && prop.owner) {
476
+ children.push(...filtered.reduce((a, b) => [...a, ...b[prop.name].getItems()], []));
477
+ }
478
+ else if (prop.kind === enums_1.ReferenceKind.MANY_TO_MANY) { // inverse side
479
+ children.push(...filtered);
480
+ }
481
+ else { // MANY_TO_ONE or ONE_TO_ONE
482
+ children.push(...this.filterReferences(entities, prop.name, options, ref));
483
+ }
484
+ return children;
485
+ }
486
+ filterCollections(entities, field, options, ref) {
487
+ if (options.refresh) {
488
+ return entities.filter(e => e[field]);
489
+ }
490
+ return entities.filter(e => Utils_1.Utils.isCollection(e[field]) && !e[field].isInitialized(!ref));
491
+ }
492
+ filterReferences(entities, field, options, ref) {
493
+ if (ref) {
494
+ return [];
495
+ }
496
+ const children = entities.filter(e => Utils_1.Utils.isEntity(e[field], true));
497
+ if (options.refresh) {
498
+ return children.map(e => Reference_1.Reference.unwrapReference(e[field]));
499
+ }
500
+ if (options.fields) {
501
+ return children
502
+ .filter(e => {
503
+ const wrapped = (0, wrap_1.helper)(e[field]);
504
+ const childFields = options.fields
505
+ .filter(f => f.startsWith(`${field}.`))
506
+ .map(f => f.substring(field.length + 1));
507
+ return !wrapped.__initialized || !childFields.every(field => wrapped.__loadedProperties.has(field));
508
+ })
509
+ .map(e => Reference_1.Reference.unwrapReference(e[field]));
510
+ }
511
+ return children
512
+ .filter(e => !e[field].__helper.__initialized)
513
+ .map(e => Reference_1.Reference.unwrapReference(e[field]));
514
+ }
515
+ filterByReferences(entities, field, refresh) {
516
+ /* istanbul ignore next */
517
+ if (refresh) {
518
+ return entities;
519
+ }
520
+ return entities.filter(e => !e[field]?.__helper?.__initialized);
521
+ }
522
+ lookupAllRelationships(entityName) {
523
+ const ret = [];
524
+ const meta = this.metadata.find(entityName);
525
+ meta.relations.forEach(prop => {
526
+ ret.push({
527
+ field: this.getRelationName(meta, prop),
528
+ // force select-in strategy when populating all relations as otherwise we could cause infinite loops when self-referencing
529
+ strategy: enums_1.LoadStrategy.SELECT_IN,
530
+ // no need to look up populate children recursively as we just pass `all: true` here
531
+ all: true,
532
+ });
533
+ });
534
+ return ret;
535
+ }
536
+ getRelationName(meta, prop) {
537
+ if (!prop.embedded) {
538
+ return prop.name;
539
+ }
540
+ return `${this.getRelationName(meta, meta.properties[prop.embedded[0]])}.${prop.embedded[1]}`;
541
+ }
542
+ lookupEagerLoadedRelationships(entityName, populate, strategy, prefix = '', visited = []) {
543
+ const meta = this.metadata.find(entityName);
544
+ if (!meta && !prefix) {
545
+ return populate;
546
+ }
547
+ if (visited.includes(entityName) || !meta) {
548
+ return [];
549
+ }
550
+ visited.push(entityName);
551
+ const ret = prefix === '' ? [...populate] : [];
552
+ meta.relations
553
+ .filter(prop => {
554
+ const eager = prop.eager && !populate.some(p => p.field === `${prop.name}:ref`);
555
+ const populated = populate.some(p => p.field === prop.name);
556
+ const disabled = populate.some(p => p.field === prop.name && p.all === false);
557
+ return !disabled && (eager || populated);
558
+ })
559
+ .forEach(prop => {
560
+ const field = this.getRelationName(meta, prop);
561
+ const prefixed = prefix ? `${prefix}.${field}` : field;
562
+ const nestedPopulate = populate.filter(p => p.field === prop.name).flatMap(p => p.children).filter(Boolean);
563
+ const nested = this.lookupEagerLoadedRelationships(prop.type, nestedPopulate, strategy, prefixed, visited.slice());
564
+ if (nested.length > 0) {
565
+ ret.push(...nested);
566
+ }
567
+ else {
568
+ const selfReferencing = [meta.className, meta.root.className, ...visited].includes(prop.type) && prop.eager;
569
+ ret.push({
570
+ field: prefixed,
571
+ // enforce select-in strategy for self-referencing relations
572
+ strategy: selfReferencing ? enums_1.LoadStrategy.SELECT_IN : strategy ?? prop.strategy,
573
+ });
574
+ }
575
+ });
576
+ return ret;
577
+ }
578
+ }
579
+ exports.EntityLoader = EntityLoader;