@mikro-orm/core 7.0.4-dev.9 → 7.0.4
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.
- package/EntityManager.d.ts +884 -583
- package/EntityManager.js +1922 -1895
- package/MikroORM.d.ts +103 -74
- package/MikroORM.js +178 -179
- package/README.md +1 -1
- package/cache/CacheAdapter.d.ts +36 -36
- package/cache/FileCacheAdapter.d.ts +30 -24
- package/cache/FileCacheAdapter.js +80 -78
- package/cache/GeneratedCacheAdapter.d.ts +18 -20
- package/cache/GeneratedCacheAdapter.js +30 -30
- package/cache/MemoryCacheAdapter.d.ts +18 -20
- package/cache/MemoryCacheAdapter.js +35 -36
- package/cache/NullCacheAdapter.d.ts +16 -16
- package/cache/NullCacheAdapter.js +24 -24
- package/connections/Connection.d.ts +95 -84
- package/connections/Connection.js +165 -168
- package/drivers/DatabaseDriver.d.ts +186 -80
- package/drivers/DatabaseDriver.js +450 -443
- package/drivers/IDatabaseDriver.d.ts +440 -301
- package/entity/BaseEntity.d.ts +120 -83
- package/entity/BaseEntity.js +43 -43
- package/entity/Collection.d.ts +212 -179
- package/entity/Collection.js +727 -721
- package/entity/EntityAssigner.d.ts +88 -77
- package/entity/EntityAssigner.js +231 -230
- package/entity/EntityFactory.d.ts +66 -54
- package/entity/EntityFactory.js +425 -383
- package/entity/EntityHelper.d.ts +34 -22
- package/entity/EntityHelper.js +280 -267
- package/entity/EntityIdentifier.d.ts +4 -4
- package/entity/EntityIdentifier.js +10 -10
- package/entity/EntityLoader.d.ts +98 -72
- package/entity/EntityLoader.js +753 -723
- package/entity/EntityRepository.d.ts +316 -201
- package/entity/EntityRepository.js +213 -213
- package/entity/PolymorphicRef.d.ts +5 -5
- package/entity/PolymorphicRef.js +10 -10
- package/entity/Reference.d.ts +126 -82
- package/entity/Reference.js +278 -274
- package/entity/WrappedEntity.d.ts +115 -72
- package/entity/WrappedEntity.js +168 -166
- package/entity/defineEntity.d.ts +1315 -636
- package/entity/defineEntity.js +527 -518
- package/entity/utils.d.ts +13 -3
- package/entity/utils.js +71 -73
- package/entity/validators.js +43 -43
- package/entity/wrap.js +8 -8
- package/enums.d.ts +258 -253
- package/enums.js +251 -252
- package/errors.d.ts +114 -72
- package/errors.js +350 -253
- package/events/EventManager.d.ts +26 -14
- package/events/EventManager.js +79 -77
- package/events/EventSubscriber.d.ts +29 -29
- package/events/TransactionEventBroadcaster.d.ts +15 -8
- package/events/TransactionEventBroadcaster.js +14 -14
- package/exceptions.d.ts +23 -40
- package/exceptions.js +35 -52
- package/hydration/Hydrator.d.ts +42 -17
- package/hydration/Hydrator.js +43 -43
- package/hydration/ObjectHydrator.d.ts +50 -17
- package/hydration/ObjectHydrator.js +481 -416
- package/index.d.ts +116 -2
- package/index.js +10 -1
- package/logging/DefaultLogger.d.ts +34 -32
- package/logging/DefaultLogger.js +86 -86
- package/logging/Logger.d.ts +41 -41
- package/logging/SimpleLogger.d.ts +13 -11
- package/logging/SimpleLogger.js +22 -22
- package/logging/colors.d.ts +6 -6
- package/logging/colors.js +11 -10
- package/logging/inspect.js +7 -7
- package/metadata/EntitySchema.d.ts +211 -127
- package/metadata/EntitySchema.js +397 -398
- package/metadata/MetadataDiscovery.d.ts +114 -114
- package/metadata/MetadataDiscovery.js +1951 -1863
- package/metadata/MetadataProvider.d.ts +24 -21
- package/metadata/MetadataProvider.js +82 -84
- package/metadata/MetadataStorage.d.ts +38 -32
- package/metadata/MetadataStorage.js +118 -118
- package/metadata/MetadataValidator.d.ts +39 -39
- package/metadata/MetadataValidator.js +381 -338
- package/metadata/discover-entities.d.ts +5 -2
- package/metadata/discover-entities.js +35 -27
- package/metadata/types.d.ts +615 -531
- package/naming-strategy/AbstractNamingStrategy.d.ts +54 -39
- package/naming-strategy/AbstractNamingStrategy.js +90 -85
- package/naming-strategy/EntityCaseNamingStrategy.d.ts +6 -6
- package/naming-strategy/EntityCaseNamingStrategy.js +22 -22
- package/naming-strategy/MongoNamingStrategy.d.ts +6 -6
- package/naming-strategy/MongoNamingStrategy.js +18 -18
- package/naming-strategy/NamingStrategy.d.ts +109 -99
- package/naming-strategy/UnderscoreNamingStrategy.d.ts +7 -7
- package/naming-strategy/UnderscoreNamingStrategy.js +21 -21
- package/not-supported.js +7 -4
- package/package.json +1 -1
- package/platforms/ExceptionConverter.d.ts +1 -1
- package/platforms/ExceptionConverter.js +4 -4
- package/platforms/Platform.d.ts +310 -299
- package/platforms/Platform.js +663 -636
- package/serialization/EntitySerializer.d.ts +49 -26
- package/serialization/EntitySerializer.js +224 -218
- package/serialization/EntityTransformer.d.ts +10 -6
- package/serialization/EntityTransformer.js +219 -217
- package/serialization/SerializationContext.d.ts +27 -23
- package/serialization/SerializationContext.js +105 -105
- package/types/ArrayType.d.ts +8 -8
- package/types/ArrayType.js +33 -33
- package/types/BigIntType.d.ts +17 -10
- package/types/BigIntType.js +37 -37
- package/types/BlobType.d.ts +3 -3
- package/types/BlobType.js +13 -13
- package/types/BooleanType.d.ts +4 -4
- package/types/BooleanType.js +12 -12
- package/types/CharacterType.d.ts +2 -2
- package/types/CharacterType.js +6 -6
- package/types/DateTimeType.d.ts +5 -5
- package/types/DateTimeType.js +15 -15
- package/types/DateType.d.ts +5 -5
- package/types/DateType.js +15 -15
- package/types/DecimalType.d.ts +7 -7
- package/types/DecimalType.js +26 -26
- package/types/DoubleType.d.ts +3 -3
- package/types/DoubleType.js +12 -12
- package/types/EnumArrayType.d.ts +5 -5
- package/types/EnumArrayType.js +24 -24
- package/types/EnumType.d.ts +3 -3
- package/types/EnumType.js +11 -11
- package/types/FloatType.d.ts +3 -3
- package/types/FloatType.js +9 -9
- package/types/IntegerType.d.ts +3 -3
- package/types/IntegerType.js +9 -9
- package/types/IntervalType.d.ts +4 -4
- package/types/IntervalType.js +12 -12
- package/types/JsonType.d.ts +8 -8
- package/types/JsonType.js +32 -32
- package/types/MediumIntType.d.ts +1 -1
- package/types/MediumIntType.js +3 -3
- package/types/SmallIntType.d.ts +3 -3
- package/types/SmallIntType.js +9 -9
- package/types/StringType.d.ts +4 -4
- package/types/StringType.js +12 -12
- package/types/TextType.d.ts +3 -3
- package/types/TextType.js +9 -9
- package/types/TimeType.d.ts +5 -5
- package/types/TimeType.js +17 -17
- package/types/TinyIntType.d.ts +3 -3
- package/types/TinyIntType.js +10 -10
- package/types/Type.d.ts +83 -79
- package/types/Type.js +82 -82
- package/types/Uint8ArrayType.d.ts +4 -4
- package/types/Uint8ArrayType.js +21 -21
- package/types/UnknownType.d.ts +4 -4
- package/types/UnknownType.js +12 -12
- package/types/UuidType.d.ts +5 -5
- package/types/UuidType.js +19 -19
- package/types/index.d.ts +75 -49
- package/types/index.js +52 -26
- package/typings.d.ts +1250 -737
- package/typings.js +244 -231
- package/unit-of-work/ChangeSet.d.ts +26 -26
- package/unit-of-work/ChangeSet.js +56 -56
- package/unit-of-work/ChangeSetComputer.d.ts +12 -12
- package/unit-of-work/ChangeSetComputer.js +178 -170
- package/unit-of-work/ChangeSetPersister.d.ts +63 -44
- package/unit-of-work/ChangeSetPersister.js +442 -421
- package/unit-of-work/CommitOrderCalculator.d.ts +40 -40
- package/unit-of-work/CommitOrderCalculator.js +89 -88
- package/unit-of-work/IdentityMap.d.ts +31 -31
- package/unit-of-work/IdentityMap.js +105 -105
- package/unit-of-work/UnitOfWork.d.ts +181 -141
- package/unit-of-work/UnitOfWork.js +1200 -1183
- package/utils/AbstractMigrator.d.ts +111 -91
- package/utils/AbstractMigrator.js +275 -275
- package/utils/AbstractSchemaGenerator.d.ts +43 -34
- package/utils/AbstractSchemaGenerator.js +121 -122
- package/utils/AsyncContext.d.ts +3 -3
- package/utils/AsyncContext.js +34 -35
- package/utils/Configuration.d.ts +852 -808
- package/utils/Configuration.js +359 -344
- package/utils/Cursor.d.ts +40 -22
- package/utils/Cursor.js +135 -127
- package/utils/DataloaderUtils.d.ts +58 -43
- package/utils/DataloaderUtils.js +203 -198
- package/utils/EntityComparator.d.ts +98 -81
- package/utils/EntityComparator.js +828 -728
- package/utils/NullHighlighter.d.ts +1 -1
- package/utils/NullHighlighter.js +3 -3
- package/utils/QueryHelper.d.ts +79 -51
- package/utils/QueryHelper.js +372 -361
- package/utils/RawQueryFragment.d.ts +50 -34
- package/utils/RawQueryFragment.js +107 -105
- package/utils/RequestContext.d.ts +32 -32
- package/utils/RequestContext.js +52 -53
- package/utils/TransactionContext.d.ts +16 -16
- package/utils/TransactionContext.js +27 -27
- package/utils/TransactionManager.d.ts +58 -58
- package/utils/TransactionManager.js +199 -197
- package/utils/Utils.d.ts +204 -145
- package/utils/Utils.js +812 -810
- package/utils/clone.js +104 -113
- package/utils/env-vars.js +90 -88
- package/utils/fs-utils.d.ts +15 -15
- package/utils/fs-utils.js +180 -181
- package/utils/upsert-utils.d.ts +20 -5
- package/utils/upsert-utils.js +114 -116
package/entity/EntityLoader.js
CHANGED
|
@@ -1,757 +1,787 @@
|
|
|
1
1
|
import { QueryHelper } from '../utils/QueryHelper.js';
|
|
2
2
|
import { Utils } from '../utils/Utils.js';
|
|
3
3
|
import { ValidationError } from '../errors.js';
|
|
4
|
-
import { LoadStrategy, PopulatePath, ReferenceKind
|
|
4
|
+
import { LoadStrategy, PopulatePath, ReferenceKind } from '../enums.js';
|
|
5
5
|
import { Reference } from './Reference.js';
|
|
6
6
|
import { helper } from './wrap.js';
|
|
7
7
|
import { expandDotPaths } from './utils.js';
|
|
8
8
|
import { Raw } from '../utils/RawQueryFragment.js';
|
|
9
9
|
/** Responsible for batch-loading entity relations using either select-in or joined loading strategies. */
|
|
10
10
|
export class EntityLoader {
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
}
|
|
27
|
-
const meta = this.#metadata.find(entityName);
|
|
28
|
-
if (entities.some(e => !e.__helper)) {
|
|
29
|
-
const entity = entities.find(e => !Utils.isEntity(e));
|
|
30
|
-
throw ValidationError.notDiscoveredEntity(entity, meta, 'populate');
|
|
31
|
-
}
|
|
32
|
-
const references = entities.filter(e => !helper(e).isInitialized());
|
|
33
|
-
const visited = (options.visited ??= new Set());
|
|
34
|
-
options.where ??= {};
|
|
35
|
-
options.orderBy ??= {};
|
|
36
|
-
options.lookup ??= true;
|
|
37
|
-
options.validate ??= true;
|
|
38
|
-
options.refresh ??= false;
|
|
39
|
-
options.convertCustomTypes ??= true;
|
|
40
|
-
if (references.length > 0) {
|
|
41
|
-
await this.populateScalar(meta, references, { ...options, populateWhere: undefined });
|
|
42
|
-
}
|
|
43
|
-
populate = this.normalizePopulate(entityName, populate, options.strategy, options.lookup, options.exclude);
|
|
44
|
-
const invalid = populate.find(({ field }) => !this.#em.canPopulate(entityName, field));
|
|
45
|
-
/* v8 ignore next */
|
|
46
|
-
if (options.validate && invalid) {
|
|
47
|
-
throw ValidationError.invalidPropertyName(entityName, invalid.field);
|
|
48
|
-
}
|
|
49
|
-
this.setSerializationContext(entities, populate, options);
|
|
50
|
-
for (const entity of entities) {
|
|
51
|
-
visited.add(entity);
|
|
52
|
-
}
|
|
53
|
-
for (const pop of populate) {
|
|
54
|
-
await this.populateField(entityName, entities, pop, options);
|
|
55
|
-
}
|
|
56
|
-
for (const entity of entities) {
|
|
57
|
-
visited.delete(entity);
|
|
58
|
-
}
|
|
11
|
+
#metadata;
|
|
12
|
+
#driver;
|
|
13
|
+
#em;
|
|
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.isEmpty(populate)) {
|
|
25
|
+
return this.setSerializationContext(entities, populate, options);
|
|
59
26
|
}
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
// oxfmt-ignore
|
|
65
|
-
return typeof field === 'boolean' || field.field === PopulatePath.ALL ? { all: !!field, field: meta.primaryKeys[0] } : field;
|
|
66
|
-
});
|
|
67
|
-
if (normalized.some(p => p.all)) {
|
|
68
|
-
normalized = this.lookupAllRelationships(entityName);
|
|
69
|
-
}
|
|
70
|
-
// convert nested `field` with dot syntax to PopulateOptions with `children` array
|
|
71
|
-
expandDotPaths(meta, normalized, true);
|
|
72
|
-
if (lookup && populate !== false) {
|
|
73
|
-
normalized = this.lookupEagerLoadedRelationships(entityName, normalized, strategy, '', [], exclude);
|
|
74
|
-
// convert nested `field` with dot syntax produced by eager relations
|
|
75
|
-
expandDotPaths(meta, normalized, true);
|
|
76
|
-
}
|
|
77
|
-
// merge same fields
|
|
78
|
-
return this.mergeNestedPopulate(normalized);
|
|
79
|
-
}
|
|
80
|
-
setSerializationContext(entities, populate, options) {
|
|
81
|
-
for (const entity of entities) {
|
|
82
|
-
helper(entity).setSerializationContext({
|
|
83
|
-
populate,
|
|
84
|
-
fields: options.fields,
|
|
85
|
-
exclude: options.exclude,
|
|
86
|
-
});
|
|
87
|
-
}
|
|
27
|
+
const meta = this.#metadata.find(entityName);
|
|
28
|
+
if (entities.some(e => !e.__helper)) {
|
|
29
|
+
const entity = entities.find(e => !Utils.isEntity(e));
|
|
30
|
+
throw ValidationError.notDiscoveredEntity(entity, meta, 'populate');
|
|
88
31
|
}
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
if (!ret[item.field]) {
|
|
100
|
-
ret[item.field] = item;
|
|
101
|
-
return ret;
|
|
102
|
-
}
|
|
103
|
-
if (!ret[item.field].children && item.children) {
|
|
104
|
-
ret[item.field].children = item.children;
|
|
105
|
-
}
|
|
106
|
-
else if (ret[item.field].children && item.children) {
|
|
107
|
-
ret[item.field].children.push(...item.children);
|
|
108
|
-
}
|
|
109
|
-
return ret;
|
|
110
|
-
}, {});
|
|
111
|
-
return Object.values(tmp).map(item => {
|
|
112
|
-
if (item.children) {
|
|
113
|
-
item.children = this.mergeNestedPopulate(item.children);
|
|
114
|
-
}
|
|
115
|
-
return item;
|
|
116
|
-
});
|
|
32
|
+
const references = entities.filter(e => !helper(e).isInitialized());
|
|
33
|
+
const visited = (options.visited ??= new Set());
|
|
34
|
+
options.where ??= {};
|
|
35
|
+
options.orderBy ??= {};
|
|
36
|
+
options.lookup ??= true;
|
|
37
|
+
options.validate ??= true;
|
|
38
|
+
options.refresh ??= false;
|
|
39
|
+
options.convertCustomTypes ??= true;
|
|
40
|
+
if (references.length > 0) {
|
|
41
|
+
await this.populateScalar(meta, references, { ...options, populateWhere: undefined });
|
|
117
42
|
}
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
const meta = this.#metadata.find(entityName);
|
|
124
|
-
const prop = meta.properties[field];
|
|
125
|
-
if (prop.kind === ReferenceKind.MANY_TO_MANY && prop.owner && !this.#driver.getPlatform().usesPivotTable()) {
|
|
126
|
-
const filtered = entities.filter(e => !e[prop.name]?.isInitialized());
|
|
127
|
-
if (filtered.length > 0) {
|
|
128
|
-
await this.populateScalar(meta, filtered, { ...options, fields: [prop.name] });
|
|
129
|
-
}
|
|
130
|
-
}
|
|
131
|
-
if (prop.kind === ReferenceKind.SCALAR && prop.lazy) {
|
|
132
|
-
const filtered = entities.filter(e => options.refresh ||
|
|
133
|
-
(prop.ref ? !e[prop.name]?.isInitialized() : e[prop.name] === undefined));
|
|
134
|
-
if (options.ignoreLazyScalarProperties || filtered.length === 0) {
|
|
135
|
-
return entities;
|
|
136
|
-
}
|
|
137
|
-
await this.populateScalar(meta, filtered, { ...options, fields: [prop.name] });
|
|
138
|
-
return entities;
|
|
139
|
-
}
|
|
140
|
-
if (prop.kind === ReferenceKind.EMBEDDED) {
|
|
141
|
-
return [];
|
|
142
|
-
}
|
|
143
|
-
const filtered = this.filterCollections(entities, field, options, ref);
|
|
144
|
-
const innerOrderBy = Utils.asArray(options.orderBy)
|
|
145
|
-
.filter(orderBy => (Array.isArray(orderBy[prop.name]) && orderBy[prop.name].length > 0) ||
|
|
146
|
-
Utils.isObject(orderBy[prop.name]))
|
|
147
|
-
.flatMap(orderBy => orderBy[prop.name]);
|
|
148
|
-
const where = await this.extractChildCondition(options, prop);
|
|
149
|
-
if (prop.kind === ReferenceKind.MANY_TO_MANY && this.#driver.getPlatform().usesPivotTable()) {
|
|
150
|
-
const pivotOrderBy = QueryHelper.mergeOrderBy(innerOrderBy, prop.orderBy, prop.targetMeta?.orderBy);
|
|
151
|
-
const res = await this.findChildrenFromPivotTable(filtered, prop, options, pivotOrderBy, populate, !!ref);
|
|
152
|
-
return Utils.flatten(res);
|
|
153
|
-
}
|
|
154
|
-
if (prop.polymorphic && prop.polymorphTargets) {
|
|
155
|
-
return this.populatePolymorphic(entities, prop, options, !!ref);
|
|
156
|
-
}
|
|
157
|
-
const { items, partial } = await this.findChildren(options.filtered ?? entities, prop, populate, {
|
|
158
|
-
...options,
|
|
159
|
-
where,
|
|
160
|
-
orderBy: innerOrderBy,
|
|
161
|
-
}, !!(ref || prop.mapToPk));
|
|
162
|
-
const customOrder = innerOrderBy.length > 0 || !!prop.orderBy || !!prop.targetMeta?.orderBy;
|
|
163
|
-
this.initializeCollections(filtered, prop, field, items, customOrder, partial);
|
|
164
|
-
return items;
|
|
165
|
-
}
|
|
166
|
-
async populateScalar(meta, filtered, options) {
|
|
167
|
-
const pk = Utils.getPrimaryKeyHash(meta.primaryKeys);
|
|
168
|
-
const ids = Utils.unique(filtered.map(e => Utils.getPrimaryKeyValues(e, meta, true)));
|
|
169
|
-
const where = this.mergePrimaryCondition(ids, pk, options, meta, this.#metadata, this.#driver.getPlatform());
|
|
170
|
-
const { filters, convertCustomTypes, lockMode, strategy, populateWhere, connectionType, logging, fields } = options;
|
|
171
|
-
await this.#em.find(meta.class, where, {
|
|
172
|
-
filters,
|
|
173
|
-
convertCustomTypes,
|
|
174
|
-
lockMode,
|
|
175
|
-
strategy,
|
|
176
|
-
populateWhere,
|
|
177
|
-
connectionType,
|
|
178
|
-
logging,
|
|
179
|
-
fields: fields,
|
|
180
|
-
populate: [],
|
|
181
|
-
});
|
|
43
|
+
populate = this.normalizePopulate(entityName, populate, options.strategy, options.lookup, options.exclude);
|
|
44
|
+
const invalid = populate.find(({ field }) => !this.#em.canPopulate(entityName, field));
|
|
45
|
+
/* v8 ignore next */
|
|
46
|
+
if (options.validate && invalid) {
|
|
47
|
+
throw ValidationError.invalidPropertyName(entityName, invalid.field);
|
|
182
48
|
}
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
const toPopulate = [];
|
|
187
|
-
const needsFkLoad = [];
|
|
188
|
-
for (const entity of entities) {
|
|
189
|
-
const refValue = entity[prop.name];
|
|
190
|
-
if (refValue && helper(refValue).hasPrimaryKey()) {
|
|
191
|
-
if ((ref && !options.refresh) || // :ref hint - already have reference
|
|
192
|
-
(!ref && helper(refValue).__initialized && !options.refresh) // already loaded
|
|
193
|
-
) {
|
|
194
|
-
continue;
|
|
195
|
-
}
|
|
196
|
-
toPopulate.push(entity);
|
|
197
|
-
}
|
|
198
|
-
else if (refValue == null && !helper(entity).__loadedProperties.has(prop.name)) {
|
|
199
|
-
// FK columns weren't loaded (partial loading) — need to re-fetch them.
|
|
200
|
-
// If the property IS in __loadedProperties, the FK was loaded and is genuinely null.
|
|
201
|
-
needsFkLoad.push(entity);
|
|
202
|
-
}
|
|
203
|
-
}
|
|
204
|
-
// Load FK columns using populateScalar pattern
|
|
205
|
-
if (needsFkLoad.length > 0) {
|
|
206
|
-
await this.populateScalar(ownerMeta, needsFkLoad, {
|
|
207
|
-
...options,
|
|
208
|
-
fields: [...ownerMeta.primaryKeys, prop.name],
|
|
209
|
-
});
|
|
210
|
-
// After loading FKs, add to toPopulate if not using :ref hint
|
|
211
|
-
if (!ref) {
|
|
212
|
-
for (const entity of needsFkLoad) {
|
|
213
|
-
const refValue = entity[prop.name];
|
|
214
|
-
if (refValue && helper(refValue).hasPrimaryKey()) {
|
|
215
|
-
toPopulate.push(entity);
|
|
216
|
-
}
|
|
217
|
-
}
|
|
218
|
-
}
|
|
219
|
-
}
|
|
220
|
-
if (toPopulate.length === 0) {
|
|
221
|
-
return [];
|
|
222
|
-
}
|
|
223
|
-
// Group references by target class for batch loading
|
|
224
|
-
const groups = new Map();
|
|
225
|
-
for (const entity of toPopulate) {
|
|
226
|
-
const refValue = Reference.unwrapReference(entity[prop.name]);
|
|
227
|
-
const discriminator = QueryHelper.findDiscriminatorValue(prop.discriminatorMap, helper(refValue).__meta.class);
|
|
228
|
-
const group = groups.get(discriminator) ?? [];
|
|
229
|
-
group.push(refValue);
|
|
230
|
-
groups.set(discriminator, group);
|
|
231
|
-
}
|
|
232
|
-
// Load each group concurrently - identity map handles merging with existing references
|
|
233
|
-
const allItems = [];
|
|
234
|
-
await Promise.all([...groups].map(async ([discriminator, children]) => {
|
|
235
|
-
const targetMeta = this.#metadata.find(prop.discriminatorMap[discriminator]);
|
|
236
|
-
await this.populateScalar(targetMeta, children, options);
|
|
237
|
-
allItems.push(...children);
|
|
238
|
-
}));
|
|
239
|
-
return allItems;
|
|
240
|
-
}
|
|
241
|
-
initializeCollections(filtered, prop, field, children, customOrder, partial) {
|
|
242
|
-
if (prop.kind === ReferenceKind.ONE_TO_MANY) {
|
|
243
|
-
this.initializeOneToMany(filtered, children, prop, field, partial);
|
|
244
|
-
}
|
|
245
|
-
if (prop.kind === ReferenceKind.MANY_TO_MANY && !this.#driver.getPlatform().usesPivotTable()) {
|
|
246
|
-
this.initializeManyToMany(filtered, children, prop, field, customOrder, partial);
|
|
247
|
-
}
|
|
49
|
+
this.setSerializationContext(entities, populate, options);
|
|
50
|
+
for (const entity of entities) {
|
|
51
|
+
visited.add(entity);
|
|
248
52
|
}
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
const map = {};
|
|
252
|
-
for (const entity of filtered) {
|
|
253
|
-
const key = helper(entity).getSerializedPrimaryKey();
|
|
254
|
-
map[key] = [];
|
|
255
|
-
}
|
|
256
|
-
for (const child of children) {
|
|
257
|
-
const pk = child.__helper.__data[prop.mappedBy] ?? child[prop.mappedBy];
|
|
258
|
-
if (pk) {
|
|
259
|
-
const key = helper(mapToPk ? this.#em.getReference(prop.targetMeta.class, pk) : pk).getSerializedPrimaryKey();
|
|
260
|
-
map[key]?.push(child);
|
|
261
|
-
}
|
|
262
|
-
}
|
|
263
|
-
for (const entity of filtered) {
|
|
264
|
-
const key = helper(entity).getSerializedPrimaryKey();
|
|
265
|
-
entity[field].hydrate(map[key], undefined, partial);
|
|
266
|
-
}
|
|
53
|
+
for (const pop of populate) {
|
|
54
|
+
await this.populateField(entityName, entities, pop, options);
|
|
267
55
|
}
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
for (const entity of filtered) {
|
|
271
|
-
const items = children.filter(child => child[prop.mappedBy].contains(entity, false));
|
|
272
|
-
entity[field].hydrate(items, true, partial);
|
|
273
|
-
}
|
|
274
|
-
}
|
|
275
|
-
else {
|
|
276
|
-
// owning side of M:N without pivot table needs to be reordered
|
|
277
|
-
for (const entity of filtered) {
|
|
278
|
-
const order = !customOrder ? [...entity[prop.name].getItems(false)] : []; // copy order of references
|
|
279
|
-
const items = children.filter(child => entity[prop.name].contains(child, false));
|
|
280
|
-
if (!customOrder) {
|
|
281
|
-
items.sort((a, b) => order.indexOf(a) - order.indexOf(b));
|
|
282
|
-
}
|
|
283
|
-
entity[field].hydrate(items, true, partial);
|
|
284
|
-
}
|
|
285
|
-
}
|
|
56
|
+
for (const entity of entities) {
|
|
57
|
+
visited.delete(entity);
|
|
286
58
|
}
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
59
|
+
}
|
|
60
|
+
/** Normalizes populate hints into a structured array of PopulateOptions, expanding dot paths and eager relations. */
|
|
61
|
+
normalizePopulate(entityName, populate, strategy, lookup = true, exclude) {
|
|
62
|
+
const meta = this.#metadata.find(entityName);
|
|
63
|
+
let normalized = Utils.asArray(populate).map(field => {
|
|
64
|
+
// oxfmt-ignore
|
|
65
|
+
return typeof field === 'boolean' || field.field === PopulatePath.ALL ? { all: !!field, field: meta.primaryKeys[0] } : field;
|
|
66
|
+
});
|
|
67
|
+
if (normalized.some(p => p.all)) {
|
|
68
|
+
normalized = this.lookupAllRelationships(entityName);
|
|
69
|
+
}
|
|
70
|
+
// convert nested `field` with dot syntax to PopulateOptions with `children` array
|
|
71
|
+
expandDotPaths(meta, normalized, true);
|
|
72
|
+
if (lookup && populate !== false) {
|
|
73
|
+
normalized = this.lookupEagerLoadedRelationships(entityName, normalized, strategy, '', [], exclude);
|
|
74
|
+
// convert nested `field` with dot syntax produced by eager relations
|
|
75
|
+
expandDotPaths(meta, normalized, true);
|
|
76
|
+
}
|
|
77
|
+
// merge same fields
|
|
78
|
+
return this.mergeNestedPopulate(normalized);
|
|
79
|
+
}
|
|
80
|
+
setSerializationContext(entities, populate, options) {
|
|
81
|
+
for (const entity of entities) {
|
|
82
|
+
helper(entity).setSerializationContext({
|
|
83
|
+
populate,
|
|
84
|
+
fields: options.fields,
|
|
85
|
+
exclude: options.exclude,
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Merge multiple populates for the same entity with different children. Also skips `*` fields, those can come from
|
|
91
|
+
* partial loading hints (`fields`) that are used to infer the `populate` hint if missing.
|
|
92
|
+
*/
|
|
93
|
+
mergeNestedPopulate(populate) {
|
|
94
|
+
const tmp = populate.reduce((ret, item) => {
|
|
95
|
+
/* v8 ignore next */
|
|
96
|
+
if (item.field === PopulatePath.ALL) {
|
|
97
|
+
return ret;
|
|
98
|
+
}
|
|
99
|
+
if (!ret[item.field]) {
|
|
100
|
+
ret[item.field] = item;
|
|
101
|
+
return ret;
|
|
102
|
+
}
|
|
103
|
+
if (!ret[item.field].children && item.children) {
|
|
104
|
+
ret[item.field].children = item.children;
|
|
105
|
+
} else if (ret[item.field].children && item.children) {
|
|
106
|
+
ret[item.field].children.push(...item.children);
|
|
107
|
+
}
|
|
108
|
+
return ret;
|
|
109
|
+
}, {});
|
|
110
|
+
return Object.values(tmp).map(item => {
|
|
111
|
+
if (item.children) {
|
|
112
|
+
item.children = this.mergeNestedPopulate(item.children);
|
|
113
|
+
}
|
|
114
|
+
return item;
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* preload everything in one call (this will update already existing references in IM)
|
|
119
|
+
*/
|
|
120
|
+
async populateMany(entityName, entities, populate, options) {
|
|
121
|
+
const [field, ref] = populate.field.split(':', 2);
|
|
122
|
+
const meta = this.#metadata.find(entityName);
|
|
123
|
+
const prop = meta.properties[field];
|
|
124
|
+
if (prop.kind === ReferenceKind.MANY_TO_MANY && prop.owner && !this.#driver.getPlatform().usesPivotTable()) {
|
|
125
|
+
const filtered = entities.filter(e => !e[prop.name]?.isInitialized());
|
|
126
|
+
if (filtered.length > 0) {
|
|
127
|
+
await this.populateScalar(meta, filtered, { ...options, fields: [prop.name] });
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
if (prop.kind === ReferenceKind.SCALAR && prop.lazy) {
|
|
131
|
+
const filtered = entities.filter(
|
|
132
|
+
e => options.refresh || (prop.ref ? !e[prop.name]?.isInitialized() : e[prop.name] === undefined),
|
|
133
|
+
);
|
|
134
|
+
if (options.ignoreLazyScalarProperties || filtered.length === 0) {
|
|
135
|
+
return entities;
|
|
136
|
+
}
|
|
137
|
+
await this.populateScalar(meta, filtered, { ...options, fields: [prop.name] });
|
|
138
|
+
return entities;
|
|
139
|
+
}
|
|
140
|
+
if (prop.kind === ReferenceKind.EMBEDDED) {
|
|
141
|
+
return [];
|
|
142
|
+
}
|
|
143
|
+
const filtered = this.filterCollections(entities, field, options, ref);
|
|
144
|
+
const innerOrderBy = Utils.asArray(options.orderBy)
|
|
145
|
+
.filter(
|
|
146
|
+
orderBy =>
|
|
147
|
+
(Array.isArray(orderBy[prop.name]) && orderBy[prop.name].length > 0) || Utils.isObject(orderBy[prop.name]),
|
|
148
|
+
)
|
|
149
|
+
.flatMap(orderBy => orderBy[prop.name]);
|
|
150
|
+
const where = await this.extractChildCondition(options, prop);
|
|
151
|
+
if (prop.kind === ReferenceKind.MANY_TO_MANY && this.#driver.getPlatform().usesPivotTable()) {
|
|
152
|
+
const pivotOrderBy = QueryHelper.mergeOrderBy(innerOrderBy, prop.orderBy, prop.targetMeta?.orderBy);
|
|
153
|
+
const res = await this.findChildrenFromPivotTable(filtered, prop, options, pivotOrderBy, populate, !!ref);
|
|
154
|
+
return Utils.flatten(res);
|
|
155
|
+
}
|
|
156
|
+
if (prop.polymorphic && prop.polymorphTargets) {
|
|
157
|
+
return this.populatePolymorphic(entities, prop, options, !!ref);
|
|
158
|
+
}
|
|
159
|
+
const { items, partial } = await this.findChildren(
|
|
160
|
+
options.filtered ?? entities,
|
|
161
|
+
prop,
|
|
162
|
+
populate,
|
|
163
|
+
{
|
|
164
|
+
...options,
|
|
165
|
+
where,
|
|
166
|
+
orderBy: innerOrderBy,
|
|
167
|
+
},
|
|
168
|
+
!!(ref || prop.mapToPk),
|
|
169
|
+
);
|
|
170
|
+
const customOrder = innerOrderBy.length > 0 || !!prop.orderBy || !!prop.targetMeta?.orderBy;
|
|
171
|
+
this.initializeCollections(filtered, prop, field, items, customOrder, partial);
|
|
172
|
+
return items;
|
|
173
|
+
}
|
|
174
|
+
async populateScalar(meta, filtered, options) {
|
|
175
|
+
const pk = Utils.getPrimaryKeyHash(meta.primaryKeys);
|
|
176
|
+
const ids = Utils.unique(filtered.map(e => Utils.getPrimaryKeyValues(e, meta, true)));
|
|
177
|
+
const where = this.mergePrimaryCondition(ids, pk, options, meta, this.#metadata, this.#driver.getPlatform());
|
|
178
|
+
const { filters, convertCustomTypes, lockMode, strategy, populateWhere, connectionType, logging, fields } = options;
|
|
179
|
+
await this.#em.find(meta.class, where, {
|
|
180
|
+
filters,
|
|
181
|
+
convertCustomTypes,
|
|
182
|
+
lockMode,
|
|
183
|
+
strategy,
|
|
184
|
+
populateWhere,
|
|
185
|
+
connectionType,
|
|
186
|
+
logging,
|
|
187
|
+
fields: fields,
|
|
188
|
+
populate: [],
|
|
189
|
+
});
|
|
190
|
+
}
|
|
191
|
+
async populatePolymorphic(entities, prop, options, ref) {
|
|
192
|
+
const ownerMeta = this.#metadata.get(entities[0].constructor);
|
|
193
|
+
// Separate entities: those with loaded refs vs those needing FK load
|
|
194
|
+
const toPopulate = [];
|
|
195
|
+
const needsFkLoad = [];
|
|
196
|
+
for (const entity of entities) {
|
|
197
|
+
const refValue = entity[prop.name];
|
|
198
|
+
if (refValue && helper(refValue).hasPrimaryKey()) {
|
|
199
|
+
if (
|
|
200
|
+
(ref && !options.refresh) || // :ref hint - already have reference
|
|
201
|
+
(!ref && helper(refValue).__initialized && !options.refresh) // already loaded
|
|
202
|
+
) {
|
|
203
|
+
continue;
|
|
204
|
+
}
|
|
205
|
+
toPopulate.push(entity);
|
|
206
|
+
} else if (refValue == null && !helper(entity).__loadedProperties.has(prop.name)) {
|
|
207
|
+
// FK columns weren't loaded (partial loading) — need to re-fetch them.
|
|
208
|
+
// If the property IS in __loadedProperties, the FK was loaded and is genuinely null.
|
|
209
|
+
needsFkLoad.push(entity);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
// Load FK columns using populateScalar pattern
|
|
213
|
+
if (needsFkLoad.length > 0) {
|
|
214
|
+
await this.populateScalar(ownerMeta, needsFkLoad, {
|
|
215
|
+
...options,
|
|
216
|
+
fields: [...ownerMeta.primaryKeys, prop.name],
|
|
217
|
+
});
|
|
218
|
+
// After loading FKs, add to toPopulate if not using :ref hint
|
|
219
|
+
if (!ref) {
|
|
220
|
+
for (const entity of needsFkLoad) {
|
|
221
|
+
const refValue = entity[prop.name];
|
|
222
|
+
if (refValue && helper(refValue).hasPrimaryKey()) {
|
|
223
|
+
toPopulate.push(entity);
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
if (toPopulate.length === 0) {
|
|
229
|
+
return [];
|
|
230
|
+
}
|
|
231
|
+
// Group references by target class for batch loading
|
|
232
|
+
const groups = new Map();
|
|
233
|
+
for (const entity of toPopulate) {
|
|
234
|
+
const refValue = Reference.unwrapReference(entity[prop.name]);
|
|
235
|
+
const discriminator = QueryHelper.findDiscriminatorValue(prop.discriminatorMap, helper(refValue).__meta.class);
|
|
236
|
+
const group = groups.get(discriminator) ?? [];
|
|
237
|
+
group.push(refValue);
|
|
238
|
+
groups.set(discriminator, group);
|
|
239
|
+
}
|
|
240
|
+
// Load each group concurrently - identity map handles merging with existing references
|
|
241
|
+
const allItems = [];
|
|
242
|
+
await Promise.all(
|
|
243
|
+
[...groups].map(async ([discriminator, children]) => {
|
|
244
|
+
const targetMeta = this.#metadata.find(prop.discriminatorMap[discriminator]);
|
|
245
|
+
await this.populateScalar(targetMeta, children, options);
|
|
246
|
+
allItems.push(...children);
|
|
247
|
+
}),
|
|
248
|
+
);
|
|
249
|
+
return allItems;
|
|
250
|
+
}
|
|
251
|
+
initializeCollections(filtered, prop, field, children, customOrder, partial) {
|
|
252
|
+
if (prop.kind === ReferenceKind.ONE_TO_MANY) {
|
|
253
|
+
this.initializeOneToMany(filtered, children, prop, field, partial);
|
|
254
|
+
}
|
|
255
|
+
if (prop.kind === ReferenceKind.MANY_TO_MANY && !this.#driver.getPlatform().usesPivotTable()) {
|
|
256
|
+
this.initializeManyToMany(filtered, children, prop, field, customOrder, partial);
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
initializeOneToMany(filtered, children, prop, field, partial) {
|
|
260
|
+
const mapToPk = prop.targetMeta.properties[prop.mappedBy].mapToPk;
|
|
261
|
+
const map = {};
|
|
262
|
+
for (const entity of filtered) {
|
|
263
|
+
const key = helper(entity).getSerializedPrimaryKey();
|
|
264
|
+
map[key] = [];
|
|
265
|
+
}
|
|
266
|
+
for (const child of children) {
|
|
267
|
+
const pk = child.__helper.__data[prop.mappedBy] ?? child[prop.mappedBy];
|
|
268
|
+
if (pk) {
|
|
269
|
+
const key = helper(mapToPk ? this.#em.getReference(prop.targetMeta.class, pk) : pk).getSerializedPrimaryKey();
|
|
270
|
+
map[key]?.push(child);
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
for (const entity of filtered) {
|
|
274
|
+
const key = helper(entity).getSerializedPrimaryKey();
|
|
275
|
+
entity[field].hydrate(map[key], undefined, partial);
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
initializeManyToMany(filtered, children, prop, field, customOrder, partial) {
|
|
279
|
+
if (prop.mappedBy) {
|
|
280
|
+
for (const entity of filtered) {
|
|
281
|
+
const items = children.filter(child => child[prop.mappedBy].contains(entity, false));
|
|
282
|
+
entity[field].hydrate(items, true, partial);
|
|
283
|
+
}
|
|
284
|
+
} else {
|
|
285
|
+
// owning side of M:N without pivot table needs to be reordered
|
|
286
|
+
for (const entity of filtered) {
|
|
287
|
+
const order = !customOrder ? [...entity[prop.name].getItems(false)] : []; // copy order of references
|
|
288
|
+
const items = children.filter(child => entity[prop.name].contains(child, false));
|
|
289
|
+
if (!customOrder) {
|
|
290
|
+
items.sort((a, b) => order.indexOf(a) - order.indexOf(b));
|
|
291
|
+
}
|
|
292
|
+
entity[field].hydrate(items, true, partial);
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
async findChildren(entities, prop, populate, options, ref) {
|
|
297
|
+
const children = Utils.unique(this.getChildReferences(entities, prop, options, ref));
|
|
298
|
+
const meta = prop.targetMeta;
|
|
299
|
+
// When targetKey is set, use it for FK lookup instead of the PK
|
|
300
|
+
let fk = prop.targetKey ?? Utils.getPrimaryKeyHash(meta.primaryKeys);
|
|
301
|
+
let schema = options.schema;
|
|
302
|
+
const partial = !Utils.isEmpty(prop.where) || !Utils.isEmpty(options.where);
|
|
303
|
+
let polymorphicOwnerProp;
|
|
304
|
+
if (prop.kind === ReferenceKind.ONE_TO_MANY || (prop.kind === ReferenceKind.MANY_TO_MANY && !prop.owner)) {
|
|
305
|
+
const ownerProp = meta.properties[prop.mappedBy];
|
|
306
|
+
if (ownerProp.polymorphic && ownerProp.fieldNames.length >= 2) {
|
|
307
|
+
const idColumns = ownerProp.fieldNames.slice(1);
|
|
308
|
+
fk = idColumns.length === 1 ? idColumns[0] : idColumns;
|
|
309
|
+
polymorphicOwnerProp = ownerProp;
|
|
310
|
+
} else {
|
|
311
|
+
fk = ownerProp.name;
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
if (prop.kind === ReferenceKind.ONE_TO_ONE && !prop.owner && !ref) {
|
|
315
|
+
children.length = 0;
|
|
316
|
+
fk = meta.properties[prop.mappedBy].name;
|
|
317
|
+
children.push(...this.filterByReferences(entities, prop.name, options.refresh));
|
|
318
|
+
}
|
|
319
|
+
if (children.length === 0) {
|
|
320
|
+
return { items: [], partial };
|
|
321
|
+
}
|
|
322
|
+
if (!schema && [ReferenceKind.ONE_TO_ONE, ReferenceKind.MANY_TO_ONE].includes(prop.kind)) {
|
|
323
|
+
schema = children.find(e => e.__helper.__schema)?.__helper.__schema;
|
|
324
|
+
}
|
|
325
|
+
const ids = Utils.unique(children.map(e => (prop.targetKey ? e[prop.targetKey] : e.__helper.getPrimaryKey())));
|
|
326
|
+
let where;
|
|
327
|
+
if (polymorphicOwnerProp && Array.isArray(fk)) {
|
|
328
|
+
const conditions = ids.map(id => {
|
|
329
|
+
const pkValues = Object.values(id);
|
|
330
|
+
return Object.fromEntries(fk.map((col, idx) => [col, pkValues[idx]]));
|
|
331
|
+
});
|
|
332
|
+
where = conditions.length === 1 ? conditions[0] : { $or: conditions };
|
|
333
|
+
} else {
|
|
334
|
+
where = this.mergePrimaryCondition(ids, fk, options, meta, this.#metadata, this.#driver.getPlatform());
|
|
335
|
+
}
|
|
336
|
+
if (polymorphicOwnerProp) {
|
|
337
|
+
const parentMeta = this.#metadata.find(entities[0].constructor);
|
|
338
|
+
const discriminatorValue =
|
|
339
|
+
QueryHelper.findDiscriminatorValue(polymorphicOwnerProp.discriminatorMap, parentMeta.class) ??
|
|
340
|
+
parentMeta.tableName;
|
|
341
|
+
const discriminatorColumn = polymorphicOwnerProp.fieldNames[0];
|
|
342
|
+
where = { $and: [where, { [discriminatorColumn]: discriminatorValue }] };
|
|
343
|
+
}
|
|
344
|
+
const fields = this.buildFields(options.fields, prop, ref);
|
|
345
|
+
/* eslint-disable prefer-const */
|
|
346
|
+
let {
|
|
347
|
+
refresh,
|
|
348
|
+
filters,
|
|
349
|
+
convertCustomTypes,
|
|
350
|
+
lockMode,
|
|
351
|
+
strategy,
|
|
352
|
+
populateWhere = 'infer',
|
|
353
|
+
connectionType,
|
|
354
|
+
logging,
|
|
355
|
+
} = options;
|
|
356
|
+
/* eslint-enable prefer-const */
|
|
357
|
+
if (typeof populateWhere === 'object') {
|
|
358
|
+
populateWhere = await this.extractChildCondition({ where: populateWhere }, prop);
|
|
359
|
+
}
|
|
360
|
+
if (!Utils.isEmpty(prop.where) || Raw.hasObjectFragments(prop.where)) {
|
|
361
|
+
where = { $and: [where, prop.where] };
|
|
362
|
+
}
|
|
363
|
+
const orderBy = QueryHelper.mergeOrderBy(options.orderBy, prop.orderBy);
|
|
364
|
+
const items = await this.#em.find(meta.class, where, {
|
|
365
|
+
filters,
|
|
366
|
+
convertCustomTypes,
|
|
367
|
+
lockMode,
|
|
368
|
+
populateWhere,
|
|
369
|
+
logging,
|
|
370
|
+
orderBy,
|
|
371
|
+
populate: populate.children ?? populate.all ?? [],
|
|
372
|
+
exclude: Array.isArray(options.exclude)
|
|
373
|
+
? Utils.extractChildElements(options.exclude, prop.name)
|
|
374
|
+
: options.exclude,
|
|
375
|
+
strategy,
|
|
376
|
+
fields,
|
|
377
|
+
schema,
|
|
378
|
+
connectionType,
|
|
379
|
+
// @ts-ignore not a public option, will be propagated to the populate call
|
|
380
|
+
refresh: refresh && !children.every(item => options.visited.has(item)),
|
|
381
|
+
// @ts-ignore not a public option, will be propagated to the populate call
|
|
382
|
+
visited: options.visited,
|
|
383
|
+
});
|
|
384
|
+
// For targetKey relations, wire up loaded entities to parent references
|
|
385
|
+
// This is needed because the references were created under alternate key,
|
|
386
|
+
// but loaded entities are stored under PK, so they don't automatically merge
|
|
387
|
+
if (prop.targetKey && [ReferenceKind.ONE_TO_ONE, ReferenceKind.MANY_TO_ONE].includes(prop.kind)) {
|
|
388
|
+
const itemsByKey = new Map();
|
|
389
|
+
for (const item of items) {
|
|
390
|
+
itemsByKey.set('' + item[prop.targetKey], item);
|
|
391
|
+
}
|
|
392
|
+
for (const entity of entities) {
|
|
393
|
+
const ref = entity[prop.name];
|
|
394
|
+
/* v8 ignore next */
|
|
395
|
+
if (!ref) {
|
|
396
|
+
continue;
|
|
460
397
|
}
|
|
461
|
-
const fields = this.buildFields(options.fields, prop);
|
|
462
|
-
const innerOrderBy = Utils.asArray(options.orderBy)
|
|
463
|
-
.filter(orderBy => Utils.isObject(orderBy[prop.name]))
|
|
464
|
-
.map(orderBy => orderBy[prop.name]);
|
|
465
|
-
const { refresh, filters, ignoreLazyScalarProperties, populateWhere, connectionType, logging, schema } = options;
|
|
466
398
|
// oxfmt-ignore
|
|
467
|
-
const
|
|
468
|
-
const
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
}
|
|
472
|
-
const unique = Utils.unique(children);
|
|
473
|
-
const filtered = unique.filter(e => !visited.has(e));
|
|
474
|
-
for (const entity of entities) {
|
|
475
|
-
visited.add(entity);
|
|
476
|
-
}
|
|
477
|
-
if (!prop.targetMeta) {
|
|
478
|
-
return;
|
|
479
|
-
}
|
|
480
|
-
const populateChildren = async (targetMeta, items) => {
|
|
481
|
-
await this.populate(targetMeta.class, items, populate.children ?? populate.all, {
|
|
482
|
-
where: (await this.extractChildCondition(options, prop, false)),
|
|
483
|
-
orderBy: innerOrderBy,
|
|
484
|
-
fields,
|
|
485
|
-
exclude,
|
|
486
|
-
validate: false,
|
|
487
|
-
lookup: false,
|
|
488
|
-
filters,
|
|
489
|
-
ignoreLazyScalarProperties,
|
|
490
|
-
populateWhere,
|
|
491
|
-
connectionType,
|
|
492
|
-
logging,
|
|
493
|
-
schema,
|
|
494
|
-
// @ts-ignore not a public option, will be propagated to the populate call
|
|
495
|
-
refresh: refresh && !filtered.every(item => options.visited.has(item)),
|
|
496
|
-
// @ts-ignore not a public option, will be propagated to the populate call
|
|
497
|
-
visited: options.visited,
|
|
498
|
-
// @ts-ignore not a public option
|
|
499
|
-
filtered,
|
|
500
|
-
});
|
|
501
|
-
};
|
|
502
|
-
if (prop.polymorphic && prop.polymorphTargets) {
|
|
503
|
-
await Promise.all(prop.polymorphTargets.map(async (targetMeta) => {
|
|
504
|
-
const targetChildren = unique.filter(child => helper(child).__meta.className === targetMeta.className);
|
|
505
|
-
if (targetChildren.length > 0) {
|
|
506
|
-
await populateChildren(targetMeta, targetChildren);
|
|
507
|
-
}
|
|
508
|
-
}));
|
|
509
|
-
}
|
|
510
|
-
else {
|
|
511
|
-
await populateChildren(prop.targetMeta, unique);
|
|
399
|
+
const keyValue = '' + (Reference.isReference(ref) ? ref.unwrap()[prop.targetKey] : ref[prop.targetKey]);
|
|
400
|
+
const loadedItem = itemsByKey.get(keyValue);
|
|
401
|
+
if (loadedItem) {
|
|
402
|
+
entity[prop.name] = Reference.isReference(ref) ? Reference.create(loadedItem) : loadedItem;
|
|
512
403
|
}
|
|
404
|
+
}
|
|
513
405
|
}
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
}
|
|
529
|
-
const
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
}
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
406
|
+
if ([ReferenceKind.ONE_TO_ONE, ReferenceKind.MANY_TO_ONE].includes(prop.kind) && items.length !== children.length) {
|
|
407
|
+
const nullVal = this.#em.config.get('forceUndefined') ? undefined : null;
|
|
408
|
+
const itemsMap = new Set();
|
|
409
|
+
const childrenMap = new Set();
|
|
410
|
+
// Use targetKey value if set, otherwise use serialized PK
|
|
411
|
+
const getKey = e => (prop.targetKey ? '' + e[prop.targetKey] : helper(e).getSerializedPrimaryKey());
|
|
412
|
+
for (const item of items) {
|
|
413
|
+
/* v8 ignore next */
|
|
414
|
+
itemsMap.add(getKey(item));
|
|
415
|
+
}
|
|
416
|
+
for (const child of children) {
|
|
417
|
+
childrenMap.add(getKey(child));
|
|
418
|
+
}
|
|
419
|
+
for (const entity of entities) {
|
|
420
|
+
const ref = entity[prop.name] ?? {};
|
|
421
|
+
const key = helper(ref) ? getKey(ref) : undefined;
|
|
422
|
+
if (key && childrenMap.has(key) && !itemsMap.has(key)) {
|
|
423
|
+
entity[prop.name] = nullVal;
|
|
424
|
+
helper(entity).__originalEntityData[prop.name] = null;
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
for (const item of items) {
|
|
429
|
+
if (ref && !helper(item).__onLoadFired) {
|
|
430
|
+
helper(item).__initialized = false;
|
|
431
|
+
this.#em.getUnitOfWork().unmarkAsLoaded(item);
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
return { items, partial };
|
|
435
|
+
}
|
|
436
|
+
mergePrimaryCondition(ids, pk, options, meta, metadata, platform) {
|
|
437
|
+
const cond1 = QueryHelper.processWhere({
|
|
438
|
+
where: { [pk]: { $in: ids } },
|
|
439
|
+
entityName: meta.class,
|
|
440
|
+
metadata,
|
|
441
|
+
platform,
|
|
442
|
+
convertCustomTypes: !options.convertCustomTypes,
|
|
443
|
+
});
|
|
444
|
+
const where = { ...options.where };
|
|
445
|
+
Utils.dropUndefinedProperties(where);
|
|
446
|
+
return where[pk] ? { $and: [cond1, where] } : { ...cond1, ...where };
|
|
447
|
+
}
|
|
448
|
+
async populateField(entityName, entities, populate, options) {
|
|
449
|
+
const field = populate.field.split(':')[0];
|
|
450
|
+
const prop = this.#metadata.find(entityName).properties[field];
|
|
451
|
+
if (prop.kind === ReferenceKind.SCALAR && !prop.lazy) {
|
|
452
|
+
return;
|
|
453
|
+
}
|
|
454
|
+
options = { ...options, filters: QueryHelper.mergePropertyFilters(prop.filters, options.filters) };
|
|
455
|
+
const populated = await this.populateMany(entityName, entities, populate, options);
|
|
456
|
+
if (!populate.children && !populate.all) {
|
|
457
|
+
return;
|
|
458
|
+
}
|
|
459
|
+
const children = [];
|
|
460
|
+
for (const entity of entities) {
|
|
461
|
+
const ref = entity[field];
|
|
462
|
+
if (Utils.isEntity(ref)) {
|
|
463
|
+
children.push(ref);
|
|
464
|
+
} else if (Reference.isReference(ref)) {
|
|
465
|
+
children.push(ref.unwrap());
|
|
466
|
+
} else if (Utils.isCollection(ref)) {
|
|
467
|
+
children.push(...ref.getItems());
|
|
468
|
+
} else if (ref && prop.kind === ReferenceKind.EMBEDDED) {
|
|
469
|
+
children.push(...Utils.asArray(ref));
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
if (populated.length === 0 && !populate.children) {
|
|
473
|
+
return;
|
|
474
|
+
}
|
|
475
|
+
const fields = this.buildFields(options.fields, prop);
|
|
476
|
+
const innerOrderBy = Utils.asArray(options.orderBy)
|
|
477
|
+
.filter(orderBy => Utils.isObject(orderBy[prop.name]))
|
|
478
|
+
.map(orderBy => orderBy[prop.name]);
|
|
479
|
+
const { refresh, filters, ignoreLazyScalarProperties, populateWhere, connectionType, logging, schema } = options;
|
|
480
|
+
// oxfmt-ignore
|
|
481
|
+
const exclude = Array.isArray(options.exclude) ? Utils.extractChildElements(options.exclude, prop.name) : options.exclude;
|
|
482
|
+
const visited = options.visited;
|
|
483
|
+
for (const entity of entities) {
|
|
484
|
+
visited.delete(entity);
|
|
485
|
+
}
|
|
486
|
+
const unique = Utils.unique(children);
|
|
487
|
+
const filtered = unique.filter(e => !visited.has(e));
|
|
488
|
+
for (const entity of entities) {
|
|
489
|
+
visited.add(entity);
|
|
490
|
+
}
|
|
491
|
+
if (!prop.targetMeta) {
|
|
492
|
+
return;
|
|
493
|
+
}
|
|
494
|
+
const populateChildren = async (targetMeta, items) => {
|
|
495
|
+
await this.populate(targetMeta.class, items, populate.children ?? populate.all, {
|
|
496
|
+
where: await this.extractChildCondition(options, prop, false),
|
|
497
|
+
orderBy: innerOrderBy,
|
|
498
|
+
fields,
|
|
499
|
+
exclude,
|
|
500
|
+
validate: false,
|
|
501
|
+
lookup: false,
|
|
502
|
+
filters,
|
|
503
|
+
ignoreLazyScalarProperties,
|
|
504
|
+
populateWhere,
|
|
505
|
+
connectionType,
|
|
506
|
+
logging,
|
|
507
|
+
schema,
|
|
508
|
+
// @ts-ignore not a public option, will be propagated to the populate call
|
|
509
|
+
refresh: refresh && !filtered.every(item => options.visited.has(item)),
|
|
510
|
+
// @ts-ignore not a public option, will be propagated to the populate call
|
|
511
|
+
visited: options.visited,
|
|
512
|
+
// @ts-ignore not a public option
|
|
513
|
+
filtered,
|
|
514
|
+
});
|
|
515
|
+
};
|
|
516
|
+
if (prop.polymorphic && prop.polymorphTargets) {
|
|
517
|
+
await Promise.all(
|
|
518
|
+
prop.polymorphTargets.map(async targetMeta => {
|
|
519
|
+
const targetChildren = unique.filter(child => helper(child).__meta.className === targetMeta.className);
|
|
520
|
+
if (targetChildren.length > 0) {
|
|
521
|
+
await populateChildren(targetMeta, targetChildren);
|
|
522
|
+
}
|
|
523
|
+
}),
|
|
524
|
+
);
|
|
525
|
+
} else {
|
|
526
|
+
await populateChildren(prop.targetMeta, unique);
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
/** @internal */
|
|
530
|
+
async findChildrenFromPivotTable(filtered, prop, options, orderBy, populate, pivotJoin) {
|
|
531
|
+
const ids = filtered.map(e => e.__helper.__primaryKeys);
|
|
532
|
+
const refresh = options.refresh;
|
|
533
|
+
let where = await this.extractChildCondition(options, prop, true);
|
|
534
|
+
const fields = this.buildFields(options.fields, prop);
|
|
535
|
+
// oxfmt-ignore
|
|
536
|
+
const exclude = Array.isArray(options.exclude) ? Utils.extractChildElements(options.exclude, prop.name) : options.exclude;
|
|
537
|
+
const populateFilter = options.populateFilter?.[prop.name];
|
|
538
|
+
const options2 = { ...options, fields, exclude, populateFilter };
|
|
539
|
+
['limit', 'offset', 'first', 'last', 'before', 'after', 'overfetch'].forEach(prop => delete options2[prop]);
|
|
540
|
+
options2.populate = populate?.children ?? [];
|
|
541
|
+
if (!Utils.isEmpty(prop.where)) {
|
|
542
|
+
where = { $and: [where, prop.where] };
|
|
543
|
+
}
|
|
544
|
+
const map = await this.#driver.loadFromPivotTable(
|
|
545
|
+
prop,
|
|
546
|
+
ids,
|
|
547
|
+
where,
|
|
548
|
+
orderBy,
|
|
549
|
+
this.#em.getTransactionContext(),
|
|
550
|
+
options2,
|
|
551
|
+
pivotJoin,
|
|
552
|
+
);
|
|
553
|
+
const children = [];
|
|
554
|
+
for (let i = 0; i < filtered.length; i++) {
|
|
555
|
+
const entity = filtered[i];
|
|
556
|
+
const items = map[Utils.getPrimaryKeyHash(ids[i])].map(item => {
|
|
557
|
+
if (pivotJoin) {
|
|
558
|
+
return this.#em.getReference(prop.targetMeta.class, item, {
|
|
559
|
+
convertCustomTypes: true,
|
|
560
|
+
schema: options.schema ?? this.#em.config.get('schema'),
|
|
561
|
+
});
|
|
562
|
+
}
|
|
563
|
+
const entity = this.#em.getEntityFactory().create(prop.targetMeta.class, item, {
|
|
564
|
+
refresh,
|
|
565
|
+
merge: true,
|
|
566
|
+
convertCustomTypes: true,
|
|
567
|
+
schema: options.schema ?? this.#em.config.get('schema'),
|
|
574
568
|
});
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
subCond[pk][op] = subCond[op];
|
|
580
|
-
delete subCond[op];
|
|
581
|
-
});
|
|
582
|
-
}
|
|
583
|
-
if (filters) {
|
|
584
|
-
return this.#em.applyFilters(meta2.class, subCond, options.filters, 'read', options);
|
|
585
|
-
}
|
|
586
|
-
return subCond;
|
|
569
|
+
return this.#em.getUnitOfWork().register(entity, item, { refresh, loaded: true });
|
|
570
|
+
});
|
|
571
|
+
entity[prop.name].hydrate(items, true);
|
|
572
|
+
children.push(items);
|
|
587
573
|
}
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
574
|
+
return children;
|
|
575
|
+
}
|
|
576
|
+
async extractChildCondition(options, prop, filters = false) {
|
|
577
|
+
const where = options.where;
|
|
578
|
+
const subCond = Utils.isPlainObject(where[prop.name]) ? where[prop.name] : {};
|
|
579
|
+
const meta2 = prop.targetMeta;
|
|
580
|
+
const pk = Utils.getPrimaryKeyHash(meta2.primaryKeys);
|
|
581
|
+
['$and', '$or'].forEach(op => {
|
|
582
|
+
if (where[op]) {
|
|
583
|
+
const child = where[op]
|
|
584
|
+
.map(cond => cond[prop.name])
|
|
585
|
+
.filter(
|
|
586
|
+
sub =>
|
|
587
|
+
sub != null &&
|
|
588
|
+
!(Utils.isPlainObject(sub) && Utils.getObjectQueryKeys(sub).every(key => Utils.isOperator(key, false))),
|
|
589
|
+
)
|
|
590
|
+
.map(cond => {
|
|
591
|
+
if (Utils.isPrimaryKey(cond)) {
|
|
592
|
+
return { [pk]: cond };
|
|
606
593
|
}
|
|
607
|
-
return
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
}
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
return ret;
|
|
594
|
+
return cond;
|
|
595
|
+
});
|
|
596
|
+
if (child.length > 0) {
|
|
597
|
+
subCond[op] = child;
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
});
|
|
601
|
+
const operators = Object.keys(subCond).filter(key => Utils.isOperator(key, false));
|
|
602
|
+
if (operators.length > 0) {
|
|
603
|
+
operators.forEach(op => {
|
|
604
|
+
subCond[pk] ??= {};
|
|
605
|
+
subCond[pk][op] = subCond[op];
|
|
606
|
+
delete subCond[op];
|
|
607
|
+
});
|
|
622
608
|
}
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
if (prop.kind === ReferenceKind.ONE_TO_MANY) {
|
|
626
|
-
return filtered.map(e => e[prop.name].owner);
|
|
627
|
-
}
|
|
628
|
-
if (prop.kind === ReferenceKind.MANY_TO_MANY && prop.owner) {
|
|
629
|
-
return filtered.reduce((a, b) => {
|
|
630
|
-
a.push(...b[prop.name].getItems());
|
|
631
|
-
return a;
|
|
632
|
-
}, []);
|
|
633
|
-
}
|
|
634
|
-
if (prop.kind === ReferenceKind.MANY_TO_MANY) {
|
|
635
|
-
// inverse side
|
|
636
|
-
return filtered;
|
|
637
|
-
}
|
|
638
|
-
// MANY_TO_ONE or ONE_TO_ONE
|
|
639
|
-
return this.filterReferences(entities, prop.name, options, ref);
|
|
609
|
+
if (filters) {
|
|
610
|
+
return this.#em.applyFilters(meta2.class, subCond, options.filters, 'read', options);
|
|
640
611
|
}
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
612
|
+
return subCond;
|
|
613
|
+
}
|
|
614
|
+
buildFields(fields = [], prop, ref) {
|
|
615
|
+
if (ref) {
|
|
616
|
+
fields = prop.targetMeta.primaryKeys.map(targetPkName => `${prop.name}.${targetPkName}`);
|
|
646
617
|
}
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
const
|
|
618
|
+
const ret = fields.reduce((ret, f) => {
|
|
619
|
+
if (Utils.isPlainObject(f)) {
|
|
620
|
+
Utils.keys(f)
|
|
621
|
+
.filter(ff => ff === prop.name)
|
|
622
|
+
.forEach(ff => ret.push(...f[ff]));
|
|
623
|
+
} else if (f.toString().includes('.')) {
|
|
624
|
+
const parts = f.toString().split('.');
|
|
625
|
+
const propName = parts.shift();
|
|
626
|
+
const childPropName = parts.join('.');
|
|
656
627
|
/* v8 ignore next */
|
|
657
|
-
if (
|
|
658
|
-
|
|
659
|
-
}
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
628
|
+
if (propName === prop.name) {
|
|
629
|
+
ret.push(childPropName);
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
return ret;
|
|
633
|
+
}, []);
|
|
634
|
+
// we need to automatically select the FKs too, e.g. for 1:m relations to be able to wire them with the items
|
|
635
|
+
if (prop.kind === ReferenceKind.ONE_TO_MANY || prop.kind === ReferenceKind.MANY_TO_MANY) {
|
|
636
|
+
const owner = prop.targetMeta.properties[prop.mappedBy];
|
|
637
|
+
// when the owning FK is lazy, we need to explicitly select it even without user-provided fields,
|
|
638
|
+
// otherwise the driver will exclude it and we won't be able to map children to their parent collections
|
|
639
|
+
if (owner && !ret.includes(owner.name) && (ret.length > 0 || owner.lazy)) {
|
|
640
|
+
ret.push(owner.name);
|
|
641
|
+
}
|
|
664
642
|
}
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
return [];
|
|
668
|
-
}
|
|
669
|
-
const children = entities.filter(e => Utils.isEntity(e[field], true));
|
|
670
|
-
if (options.refresh) {
|
|
671
|
-
return children.map(e => Reference.unwrapReference(e[field]));
|
|
672
|
-
}
|
|
673
|
-
if (options.fields) {
|
|
674
|
-
return children
|
|
675
|
-
.map(e => Reference.unwrapReference(e[field]))
|
|
676
|
-
.filter(target => {
|
|
677
|
-
const wrapped = helper(target);
|
|
678
|
-
const childFields = options.fields
|
|
679
|
-
.filter(f => f.startsWith(`${field}.`))
|
|
680
|
-
.map(f => f.substring(field.length + 1));
|
|
681
|
-
return !wrapped.__initialized || !childFields.every(cf => this.isPropertyLoaded(target, cf));
|
|
682
|
-
});
|
|
683
|
-
}
|
|
684
|
-
return children
|
|
685
|
-
.filter(e => !e[field].__helper.__initialized)
|
|
686
|
-
.map(e => Reference.unwrapReference(e[field]));
|
|
643
|
+
if (ret.length === 0) {
|
|
644
|
+
return undefined;
|
|
687
645
|
}
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
}
|
|
695
|
-
lookupAllRelationships(entityName) {
|
|
696
|
-
const ret = [];
|
|
697
|
-
const meta = this.#metadata.find(entityName);
|
|
698
|
-
meta.relations.forEach(prop => {
|
|
699
|
-
ret.push({
|
|
700
|
-
field: this.getRelationName(meta, prop),
|
|
701
|
-
// force select-in strategy when populating all relations as otherwise we could cause infinite loops when self-referencing
|
|
702
|
-
strategy: LoadStrategy.SELECT_IN,
|
|
703
|
-
// no need to look up populate children recursively as we just pass `all: true` here
|
|
704
|
-
all: true,
|
|
705
|
-
});
|
|
706
|
-
});
|
|
707
|
-
return ret;
|
|
646
|
+
return ret;
|
|
647
|
+
}
|
|
648
|
+
getChildReferences(entities, prop, options, ref) {
|
|
649
|
+
const filtered = this.filterCollections(entities, prop.name, options, ref);
|
|
650
|
+
if (prop.kind === ReferenceKind.ONE_TO_MANY) {
|
|
651
|
+
return filtered.map(e => e[prop.name].owner);
|
|
708
652
|
}
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
653
|
+
if (prop.kind === ReferenceKind.MANY_TO_MANY && prop.owner) {
|
|
654
|
+
return filtered.reduce((a, b) => {
|
|
655
|
+
a.push(...b[prop.name].getItems());
|
|
656
|
+
return a;
|
|
657
|
+
}, []);
|
|
714
658
|
}
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
659
|
+
if (prop.kind === ReferenceKind.MANY_TO_MANY) {
|
|
660
|
+
// inverse side
|
|
661
|
+
return filtered;
|
|
662
|
+
}
|
|
663
|
+
// MANY_TO_ONE or ONE_TO_ONE
|
|
664
|
+
return this.filterReferences(entities, prop.name, options, ref);
|
|
665
|
+
}
|
|
666
|
+
filterCollections(entities, field, options, ref) {
|
|
667
|
+
if (options.refresh) {
|
|
668
|
+
return entities.filter(e => e[field]);
|
|
669
|
+
}
|
|
670
|
+
return entities.filter(e => Utils.isCollection(e[field]) && !e[field].isInitialized(!ref));
|
|
671
|
+
}
|
|
672
|
+
isPropertyLoaded(entity, field) {
|
|
673
|
+
if (!entity || field === '*') {
|
|
674
|
+
return true;
|
|
675
|
+
}
|
|
676
|
+
const wrapped = helper(entity);
|
|
677
|
+
if (!field.includes('.')) {
|
|
678
|
+
return wrapped.__loadedProperties.has(field);
|
|
679
|
+
}
|
|
680
|
+
const [f, ...r] = field.split('.');
|
|
681
|
+
/* v8 ignore next */
|
|
682
|
+
if (!wrapped.__loadedProperties.has(f) || !wrapped.__meta.properties[f]?.targetMeta) {
|
|
683
|
+
return false;
|
|
684
|
+
}
|
|
685
|
+
if ([ReferenceKind.ONE_TO_MANY, ReferenceKind.MANY_TO_MANY].includes(wrapped.__meta.properties[f].kind)) {
|
|
686
|
+
return entity[f].getItems(false).every(item => this.isPropertyLoaded(item, r.join('.')));
|
|
687
|
+
}
|
|
688
|
+
return this.isPropertyLoaded(entity[f], r.join('.'));
|
|
689
|
+
}
|
|
690
|
+
filterReferences(entities, field, options, ref) {
|
|
691
|
+
if (ref) {
|
|
692
|
+
return [];
|
|
693
|
+
}
|
|
694
|
+
const children = entities.filter(e => Utils.isEntity(e[field], true));
|
|
695
|
+
if (options.refresh) {
|
|
696
|
+
return children.map(e => Reference.unwrapReference(e[field]));
|
|
697
|
+
}
|
|
698
|
+
if (options.fields) {
|
|
699
|
+
return children
|
|
700
|
+
.map(e => Reference.unwrapReference(e[field]))
|
|
701
|
+
.filter(target => {
|
|
702
|
+
const wrapped = helper(target);
|
|
703
|
+
const childFields = options.fields
|
|
704
|
+
.filter(f => f.startsWith(`${field}.`))
|
|
705
|
+
.map(f => f.substring(field.length + 1));
|
|
706
|
+
return !wrapped.__initialized || !childFields.every(cf => this.isPropertyLoaded(target, cf));
|
|
754
707
|
});
|
|
755
|
-
return ret;
|
|
756
708
|
}
|
|
709
|
+
return children.filter(e => !e[field].__helper.__initialized).map(e => Reference.unwrapReference(e[field]));
|
|
710
|
+
}
|
|
711
|
+
filterByReferences(entities, field, refresh) {
|
|
712
|
+
/* v8 ignore next */
|
|
713
|
+
if (refresh) {
|
|
714
|
+
return entities;
|
|
715
|
+
}
|
|
716
|
+
return entities.filter(e => e[field] !== null && !e[field]?.__helper?.__initialized);
|
|
717
|
+
}
|
|
718
|
+
lookupAllRelationships(entityName) {
|
|
719
|
+
const ret = [];
|
|
720
|
+
const meta = this.#metadata.find(entityName);
|
|
721
|
+
meta.relations.forEach(prop => {
|
|
722
|
+
ret.push({
|
|
723
|
+
field: this.getRelationName(meta, prop),
|
|
724
|
+
// force select-in strategy when populating all relations as otherwise we could cause infinite loops when self-referencing
|
|
725
|
+
strategy: LoadStrategy.SELECT_IN,
|
|
726
|
+
// no need to look up populate children recursively as we just pass `all: true` here
|
|
727
|
+
all: true,
|
|
728
|
+
});
|
|
729
|
+
});
|
|
730
|
+
return ret;
|
|
731
|
+
}
|
|
732
|
+
getRelationName(meta, prop) {
|
|
733
|
+
if (!prop.embedded) {
|
|
734
|
+
return prop.name;
|
|
735
|
+
}
|
|
736
|
+
return `${this.getRelationName(meta, meta.properties[prop.embedded[0]])}.${prop.embedded[1]}`;
|
|
737
|
+
}
|
|
738
|
+
lookupEagerLoadedRelationships(entityName, populate, strategy, prefix = '', visited = [], exclude) {
|
|
739
|
+
const meta = this.#metadata.find(entityName);
|
|
740
|
+
if (!meta && !prefix) {
|
|
741
|
+
return populate;
|
|
742
|
+
}
|
|
743
|
+
if (!meta || visited.includes(meta)) {
|
|
744
|
+
return [];
|
|
745
|
+
}
|
|
746
|
+
visited.push(meta);
|
|
747
|
+
const ret = prefix === '' ? [...populate] : [];
|
|
748
|
+
meta.relations
|
|
749
|
+
.filter(prop => {
|
|
750
|
+
const field = this.getRelationName(meta, prop);
|
|
751
|
+
const prefixed = prefix ? `${prefix}.${field}` : field;
|
|
752
|
+
const isExcluded = exclude?.includes(prefixed);
|
|
753
|
+
const eager = prop.eager && !populate.some(p => p.field === `${prop.name}:ref`);
|
|
754
|
+
const populated = populate.some(p => p.field === prop.name);
|
|
755
|
+
const disabled = populate.some(p => p.field === prop.name && p.all === false);
|
|
756
|
+
return !disabled && !isExcluded && (eager || populated);
|
|
757
|
+
})
|
|
758
|
+
.forEach(prop => {
|
|
759
|
+
const field = this.getRelationName(meta, prop);
|
|
760
|
+
const prefixed = prefix ? `${prefix}.${field}` : field;
|
|
761
|
+
const nestedPopulate = populate
|
|
762
|
+
.filter(p => p.field === prop.name)
|
|
763
|
+
.flatMap(p => p.children)
|
|
764
|
+
.filter(Boolean);
|
|
765
|
+
const nested = this.lookupEagerLoadedRelationships(
|
|
766
|
+
prop.targetMeta.class,
|
|
767
|
+
nestedPopulate,
|
|
768
|
+
strategy,
|
|
769
|
+
prefixed,
|
|
770
|
+
visited.slice(),
|
|
771
|
+
exclude,
|
|
772
|
+
);
|
|
773
|
+
if (nested.length > 0) {
|
|
774
|
+
ret.push(...nested);
|
|
775
|
+
} else {
|
|
776
|
+
const selfReferencing =
|
|
777
|
+
[meta.tableName, ...visited.map(m => m.tableName)].includes(prop.targetMeta.tableName) && prop.eager;
|
|
778
|
+
ret.push({
|
|
779
|
+
field: prefixed,
|
|
780
|
+
// enforce select-in strategy for self-referencing relations
|
|
781
|
+
strategy: selfReferencing ? LoadStrategy.SELECT_IN : (strategy ?? prop.strategy),
|
|
782
|
+
});
|
|
783
|
+
}
|
|
784
|
+
});
|
|
785
|
+
return ret;
|
|
786
|
+
}
|
|
757
787
|
}
|