@mikro-orm/core 7.3.0-dev.20 → 7.3.0-dev.22
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 +10 -7
- package/EntityManager.js +74 -39
- package/cache/cache-key.d.ts +5 -0
- package/cache/cache-key.js +30 -0
- package/drivers/DatabaseDriver.d.ts +2 -0
- package/drivers/DatabaseDriver.js +9 -1
- package/drivers/IDatabaseDriver.d.ts +2 -0
- package/entity/EntityAssigner.js +4 -1
- package/entity/EntityHelper.d.ts +8 -3
- package/entity/EntityHelper.js +24 -3
- package/entity/EntityLoader.d.ts +1 -0
- package/entity/EntityLoader.js +35 -8
- package/metadata/MetadataDiscovery.js +26 -5
- package/package.json +1 -1
- package/serialization/EntitySerializer.js +56 -47
- package/serialization/EntityTransformer.js +82 -73
- package/serialization/SerializationContext.d.ts +2 -1
- package/serialization/SerializationContext.js +4 -3
- package/typings.d.ts +4 -1
- package/typings.js +1 -1
- package/unit-of-work/ChangeSetComputer.js +4 -7
- package/unit-of-work/ChangeSetPersister.d.ts +2 -0
- package/unit-of-work/ChangeSetPersister.js +10 -5
- package/unit-of-work/UnitOfWork.js +17 -4
- package/utils/DataloaderUtils.js +19 -8
- package/utils/EntityComparator.js +2 -8
- package/utils/QueryHelper.d.ts +6 -0
- package/utils/QueryHelper.js +42 -0
- package/utils/TransactionManager.js +3 -1
- package/utils/Utils.js +15 -6
- package/utils/clone.js +2 -1
|
@@ -66,6 +66,7 @@ export class UnitOfWork {
|
|
|
66
66
|
return;
|
|
67
67
|
}
|
|
68
68
|
this.#identityMap.store(entity);
|
|
69
|
+
wrapped.__managed = true;
|
|
69
70
|
// if visited is available, we are cascading, and need to be careful when resetting the entity data
|
|
70
71
|
// as there can be some entity with already changed state that is not yet flushed
|
|
71
72
|
if (wrapped.__initialized && (!visited || !wrapped.__originalEntityData)) {
|
|
@@ -111,6 +112,10 @@ export class UnitOfWork {
|
|
|
111
112
|
});
|
|
112
113
|
data[key] = prop.customType.convertToDatabaseValue(converted, this.#platform, { key, mode: 'hydration' });
|
|
113
114
|
}
|
|
115
|
+
// the hydrator assigns this very instance to the entity, an in-place mutation would otherwise go unnoticed
|
|
116
|
+
if (data[key] instanceof Date) {
|
|
117
|
+
data[key] = new Date(data[key]);
|
|
118
|
+
}
|
|
114
119
|
if (forceUndefined) {
|
|
115
120
|
if (data[key] === null) {
|
|
116
121
|
data[key] = undefined;
|
|
@@ -141,7 +146,9 @@ export class UnitOfWork {
|
|
|
141
146
|
wrapped.__loadedProperties.add(key);
|
|
142
147
|
}
|
|
143
148
|
}
|
|
144
|
-
|
|
149
|
+
// a partial refresh must keep the snapshot of properties it did not reload
|
|
150
|
+
wrapped.__originalEntityData =
|
|
151
|
+
options?.refresh && wrapped.__originalEntityData ? { ...wrapped.__originalEntityData, ...data } : data;
|
|
145
152
|
}
|
|
146
153
|
return entity;
|
|
147
154
|
}
|
|
@@ -395,7 +402,7 @@ export class UnitOfWork {
|
|
|
395
402
|
this.#persistStack.delete(entity);
|
|
396
403
|
this.#identityMap.delete(entity);
|
|
397
404
|
}
|
|
398
|
-
//
|
|
405
|
+
// unlink loaded inverse-side items only when the FK is `set null`, other delete rules are left to the database
|
|
399
406
|
const entityMeta = helper(entity).__meta;
|
|
400
407
|
for (const prop of entityMeta.bidirectionalRelations) {
|
|
401
408
|
const inverseProp = prop.mappedBy || prop.inversedBy;
|
|
@@ -410,7 +417,9 @@ export class UnitOfWork {
|
|
|
410
417
|
: inverseTarget.class !== entityMeta.class) {
|
|
411
418
|
continue;
|
|
412
419
|
}
|
|
413
|
-
if (prop.kind === ReferenceKind.ONE_TO_MANY &&
|
|
420
|
+
if (prop.kind === ReferenceKind.ONE_TO_MANY &&
|
|
421
|
+
prop2.deleteRule === 'set null' &&
|
|
422
|
+
Utils.isCollection(relation)) {
|
|
414
423
|
for (const item of relation.getItems(false)) {
|
|
415
424
|
delete item[inverseProp];
|
|
416
425
|
}
|
|
@@ -553,9 +562,13 @@ export class UnitOfWork {
|
|
|
553
562
|
// the referrer's primary key contains the removed entity, so its identity cannot survive the removal
|
|
554
563
|
this.unsetIdentity(referrer);
|
|
555
564
|
}
|
|
556
|
-
else {
|
|
565
|
+
else if ((prop.inversedBy || prop.mappedBy) && !prop.mapToPk) {
|
|
566
|
+
// relations with an inverse side are backed by `__data` to allow propagation
|
|
557
567
|
delete helper(referrer).__data[prop.name];
|
|
558
568
|
}
|
|
569
|
+
else {
|
|
570
|
+
delete referrer[prop.name];
|
|
571
|
+
}
|
|
559
572
|
}
|
|
560
573
|
}
|
|
561
574
|
}
|
package/utils/DataloaderUtils.js
CHANGED
|
@@ -3,6 +3,9 @@ import { helper } from '../entity/wrap.js';
|
|
|
3
3
|
import { Reference } from '../entity/Reference.js';
|
|
4
4
|
import { ReferenceKind } from '../enums.js';
|
|
5
5
|
import { Utils } from './Utils.js';
|
|
6
|
+
import { stringifyCacheKey } from '../cache/cache-key.js';
|
|
7
|
+
// the original options of each group key, JSON cannot restore values like RegExp or `raw()` from the key
|
|
8
|
+
const groupOptions = new WeakMap();
|
|
6
9
|
export class DataloaderUtils {
|
|
7
10
|
static DataLoader;
|
|
8
11
|
/**
|
|
@@ -11,6 +14,8 @@ export class DataloaderUtils {
|
|
|
11
14
|
*/
|
|
12
15
|
static groupPrimaryKeysByEntityAndOpts(refsWithOpts) {
|
|
13
16
|
const map = new Map();
|
|
17
|
+
const options = new Map();
|
|
18
|
+
groupOptions.set(map, options);
|
|
14
19
|
for (const [ref, opts] of refsWithOpts) {
|
|
15
20
|
/* The key is a combination of the uniqueName (a unique table name based identifier) and a stringified version if the load options because we want
|
|
16
21
|
to map each combination of entities/options into separate find queries in order to return accurate results.
|
|
@@ -25,7 +30,8 @@ export class DataloaderUtils {
|
|
|
25
30
|
Thus such approach should probably be configurable, if not opt-in.
|
|
26
31
|
NOTE: meta + opts multi maps (https://github.com/martian17/ds-js) might be a more elegant way
|
|
27
32
|
to implement this but not necessarily faster. */
|
|
28
|
-
const key = `${helper(ref).__meta.uniqueName}|${
|
|
33
|
+
const key = `${helper(ref).__meta.uniqueName}|${stringifyCacheKey(opts ?? {})}`;
|
|
34
|
+
options.set(key, opts ?? {});
|
|
29
35
|
let primaryKeysSet = map.get(key);
|
|
30
36
|
if (primaryKeysSet == null) {
|
|
31
37
|
primaryKeysSet = new Set();
|
|
@@ -44,7 +50,7 @@ export class DataloaderUtils {
|
|
|
44
50
|
const groupedIdsMap = DataloaderUtils.groupPrimaryKeysByEntityAndOpts(refsWithOpts);
|
|
45
51
|
const promises = Array.from(groupedIdsMap).map(([key, idsSet]) => {
|
|
46
52
|
const uniqueName = key.substring(0, key.indexOf('|'));
|
|
47
|
-
const opts =
|
|
53
|
+
const opts = groupOptions.get(groupedIdsMap).get(key);
|
|
48
54
|
const meta = em.getMetadata().getByUniqueName(uniqueName);
|
|
49
55
|
return em.find(meta.class, Array.from(idsSet), opts);
|
|
50
56
|
});
|
|
@@ -64,6 +70,8 @@ export class DataloaderUtils {
|
|
|
64
70
|
*/
|
|
65
71
|
static groupInversedOrMappedKeysByEntityAndOpts(collsWithOpts) {
|
|
66
72
|
const entitiesMap = new Map();
|
|
73
|
+
const options = new Map();
|
|
74
|
+
groupOptions.set(entitiesMap, options);
|
|
67
75
|
for (const [col, opts] of collsWithOpts) {
|
|
68
76
|
/*
|
|
69
77
|
We first get the entity name of the Collection and together with its options (see groupPrimaryKeysByEntityAndOpts
|
|
@@ -72,7 +80,8 @@ export class DataloaderUtils {
|
|
|
72
80
|
The value is another Map which we can use to filter the find query to get results pertaining to the collections that have been dataloaded:
|
|
73
81
|
its keys are the props we are going to filter to and its values are the corresponding PKs.
|
|
74
82
|
*/
|
|
75
|
-
const key = `${col.property.targetMeta.uniqueName}|${
|
|
83
|
+
const key = `${col.property.targetMeta.uniqueName}|${stringifyCacheKey(opts ?? {})}`;
|
|
84
|
+
options.set(key, opts ?? {});
|
|
76
85
|
let filterMap = entitiesMap.get(key); // We are going to use this map to filter the entities pertaining to the collections that have been dataloaded.
|
|
77
86
|
if (filterMap == null) {
|
|
78
87
|
filterMap = new Map();
|
|
@@ -100,7 +109,9 @@ export class DataloaderUtils {
|
|
|
100
109
|
static entitiesAndOptsMapToQueries(entitiesAndOptsMap, em) {
|
|
101
110
|
return Array.from(entitiesAndOptsMap, async ([key, filterMap]) => {
|
|
102
111
|
const uniqueName = key.substring(0, key.indexOf('|'));
|
|
103
|
-
const opts =
|
|
112
|
+
const opts = groupOptions
|
|
113
|
+
.get(entitiesAndOptsMap)
|
|
114
|
+
?.get(key) ?? JSON.parse(key.substring(key.indexOf('|') + 1));
|
|
104
115
|
const meta = em.getMetadata().getByUniqueName(uniqueName);
|
|
105
116
|
const res = await em.find(meta.class, opts?.where != null && Object.keys(opts.where).length > 0
|
|
106
117
|
? {
|
|
@@ -168,7 +179,7 @@ export class DataloaderUtils {
|
|
|
168
179
|
// We need to filter the results in order to map each input collection
|
|
169
180
|
// to a subset of each query matching the collection items.
|
|
170
181
|
return collsWithOpts.map(([col, opts]) => {
|
|
171
|
-
const key = `${col.property.targetMeta.uniqueName}|${
|
|
182
|
+
const key = `${col.property.targetMeta.uniqueName}|${stringifyCacheKey(opts ?? {})}`;
|
|
172
183
|
const entities = resultsMap.get(key);
|
|
173
184
|
if (entities == null) {
|
|
174
185
|
// Should never happen
|
|
@@ -187,7 +198,7 @@ export class DataloaderUtils {
|
|
|
187
198
|
return async (collsWithOpts) => {
|
|
188
199
|
const groups = new Map();
|
|
189
200
|
for (const [col, opts] of collsWithOpts) {
|
|
190
|
-
const key = `${col.property.targetMeta.uniqueName}.${col.property.name}|${
|
|
201
|
+
const key = `${col.property.targetMeta.uniqueName}.${col.property.name}|${stringifyCacheKey(opts ?? {})}`;
|
|
191
202
|
const value = groups.get(key) ?? [];
|
|
192
203
|
value.push([col, opts ?? {}]);
|
|
193
204
|
groups.set(key, value);
|
|
@@ -252,7 +263,7 @@ export class DataloaderUtils {
|
|
|
252
263
|
// sharing a relation with the same property name (e.g. `Author.books` and `Publisher.books`)
|
|
253
264
|
// don't collide into a single batch that would use one owner's FK mapping for the other.
|
|
254
265
|
const ownerUniqueName = helper(col.owner).__meta.uniqueName;
|
|
255
|
-
const key = `${ownerUniqueName}.${prop.name}|${
|
|
266
|
+
const key = `${ownerUniqueName}.${prop.name}|${stringifyCacheKey(opts ?? {})}`;
|
|
256
267
|
keys.push(key);
|
|
257
268
|
let group = groups.get(key);
|
|
258
269
|
if (!group) {
|
|
@@ -260,7 +271,7 @@ export class DataloaderUtils {
|
|
|
260
271
|
groups.set(key, group);
|
|
261
272
|
}
|
|
262
273
|
const pk = helper(col.owner).getPrimaryKey();
|
|
263
|
-
group.ownerPKs.set(
|
|
274
|
+
group.ownerPKs.set(stringifyCacheKey(pk), pk);
|
|
264
275
|
}
|
|
265
276
|
const promises = Array.from(groups.entries()).map(async ([key, group]) => {
|
|
266
277
|
const allPKs = Array.from(group.ownerPKs.values());
|
|
@@ -6,6 +6,7 @@ import { JsonType } from '../types/JsonType.js';
|
|
|
6
6
|
import { Raw } from './RawQueryFragment.js';
|
|
7
7
|
import { EntityIdentifier } from '../entity/EntityIdentifier.js';
|
|
8
8
|
import { PolymorphicRef } from '../entity/PolymorphicRef.js';
|
|
9
|
+
import { EntityHelper } from '../entity/EntityHelper.js';
|
|
9
10
|
/** @internal Generates and caches JIT-compiled functions for comparing, snapshotting, and mapping entity data. */
|
|
10
11
|
export class EntityComparator {
|
|
11
12
|
#comparators = new Map();
|
|
@@ -663,15 +664,8 @@ export class EntityComparator {
|
|
|
663
664
|
ret += ` }\n`;
|
|
664
665
|
if (prop.targetKey) {
|
|
665
666
|
// the FK holds the `targetKey` value in the format of the actual target's column
|
|
666
|
-
const targetKey = prop.targetKey;
|
|
667
667
|
const targetKeyValueKey = `targetKeyValue_${this.safeKey(prop.name)}`;
|
|
668
|
-
context.set(targetKeyValueKey, (val) =>
|
|
669
|
-
const customType = val.__meta.properties[targetKey]?.customType;
|
|
670
|
-
const value = val[targetKey];
|
|
671
|
-
return customType
|
|
672
|
-
? customType.convertToDatabaseValue(value, this.#platform, { mode: 'serialization' })
|
|
673
|
-
: value;
|
|
674
|
-
});
|
|
668
|
+
context.set(targetKeyValueKey, (val) => EntityHelper.getForeignKeyValue(val, prop, val.__meta));
|
|
675
669
|
ret += ` const pk = ${targetKeyValueKey}(val${level});\n`;
|
|
676
670
|
}
|
|
677
671
|
else {
|
package/utils/QueryHelper.d.ts
CHANGED
|
@@ -28,6 +28,12 @@ export declare class QueryHelper {
|
|
|
28
28
|
*/
|
|
29
29
|
static findDiscriminatorValue<T>(discriminatorMap: Dictionary<T>, targetClass: T): string | undefined;
|
|
30
30
|
static processParams(params: unknown): any;
|
|
31
|
+
/**
|
|
32
|
+
* @internal The data as sent to the driver: a composite FK referencing other target columns than its PK
|
|
33
|
+
* (`prop.referencedProps`) gets their values from the target, which is the relation value in `source` (the entity
|
|
34
|
+
* being written, or the data it was created from), or is looked up via `getTarget` when `data` holds a bare PK.
|
|
35
|
+
*/
|
|
36
|
+
static withReferencedValues<T extends object, D extends Dictionary>(meta: EntityMetadata<T>, data: D, source: Dictionary | undefined, platform: Platform, getTarget?: (prop: EntityProperty<T>, pk: unknown) => object | undefined): D;
|
|
31
37
|
static processObjectParams<T extends Dictionary>(params?: T): T;
|
|
32
38
|
/**
|
|
33
39
|
* converts `{ account: { $or: [ [Object], [Object] ] } }`
|
package/utils/QueryHelper.js
CHANGED
|
@@ -60,6 +60,48 @@ export class QueryHelper {
|
|
|
60
60
|
}
|
|
61
61
|
return params;
|
|
62
62
|
}
|
|
63
|
+
/**
|
|
64
|
+
* @internal The data as sent to the driver: a composite FK referencing other target columns than its PK
|
|
65
|
+
* (`prop.referencedProps`) gets their values from the target, which is the relation value in `source` (the entity
|
|
66
|
+
* being written, or the data it was created from), or is looked up via `getTarget` when `data` holds a bare PK.
|
|
67
|
+
*/
|
|
68
|
+
static withReferencedValues(meta, data, source, platform, getTarget) {
|
|
69
|
+
for (const prop of meta.relations) {
|
|
70
|
+
const value = data[prop.name];
|
|
71
|
+
// a ready tuple is the FK value already
|
|
72
|
+
if (!prop.referencedProps ||
|
|
73
|
+
value == null ||
|
|
74
|
+
isRaw(value) ||
|
|
75
|
+
(Array.isArray(value) && value.length === prop.fieldNames.length)) {
|
|
76
|
+
continue;
|
|
77
|
+
}
|
|
78
|
+
let target = Reference.unwrapReference(value);
|
|
79
|
+
if (!Utils.isEntity(target) && !Utils.isPlainObject(target)) {
|
|
80
|
+
const candidate = Reference.unwrapReference(source?.[prop.name]);
|
|
81
|
+
// the data created from the source may have changed since (e.g. in a hook), then the PK decides
|
|
82
|
+
const current = Utils.isEntity(candidate) &&
|
|
83
|
+
(Utils.isEntity(source) || Utils.equals(QueryHelper.processParams(candidate), value));
|
|
84
|
+
target = current ? candidate : getTarget?.(prop, value);
|
|
85
|
+
}
|
|
86
|
+
const tuple = prop.referencedProps.map((referencedProp, idx) => {
|
|
87
|
+
let val = Reference.unwrapReference(target?.[referencedProp.name]);
|
|
88
|
+
val = Utils.isScalarReference(val) ? val.unwrap() : val;
|
|
89
|
+
val = Utils.isEntity(val) ? helper(val).getPrimaryKey(true) : val;
|
|
90
|
+
if (val === undefined) {
|
|
91
|
+
// without the target, name the first value its PK does not give
|
|
92
|
+
const missing = target ? referencedProp : prop.referencedProps.find(p => !p.primary);
|
|
93
|
+
throw new ValidationError(`Cannot set ${meta.className}.${prop.name} to a reference of ${prop.targetMeta.className} without the value of ${prop.targetMeta.className}.${missing.name}, load it first`);
|
|
94
|
+
}
|
|
95
|
+
if (referencedProp.customType && val != null) {
|
|
96
|
+
val = referencedProp.customType.convertToDatabaseValue(val, platform, { mode: 'serialization' });
|
|
97
|
+
}
|
|
98
|
+
// a relation holding a composite PK yields a nested array, one entry per column
|
|
99
|
+
return Utils.flatten([val], true)[referencedProp.fieldNames.indexOf(prop.referencedColumnNames[idx])];
|
|
100
|
+
});
|
|
101
|
+
data = { ...data, [prop.name]: tuple };
|
|
102
|
+
}
|
|
103
|
+
return data;
|
|
104
|
+
}
|
|
63
105
|
static processObjectParams(params = {}) {
|
|
64
106
|
const ret = (Array.isArray(params) ? [...params] : { ...params });
|
|
65
107
|
Utils.getObjectQueryKeys(params).forEach(k => {
|
|
@@ -182,7 +182,9 @@ export class TransactionManager {
|
|
|
182
182
|
tracked.forEach(([key]) => this.restore(originalEntityData, parentSnapshot, key));
|
|
183
183
|
continue;
|
|
184
184
|
}
|
|
185
|
-
|
|
185
|
+
// only to-one relations with an inverse side are backed by `__data`, other values live on the entity itself
|
|
186
|
+
if (![ReferenceKind.ONE_TO_MANY, ReferenceKind.MANY_TO_MANY].includes(prop.kind) &&
|
|
187
|
+
(!(prop.inversedBy || prop.mappedBy) || prop.mapToPk)) {
|
|
186
188
|
parentEntity[prop.name] = entity[prop.name];
|
|
187
189
|
}
|
|
188
190
|
}
|
package/utils/Utils.js
CHANGED
|
@@ -153,7 +153,7 @@ export function parseJsonSafe(value) {
|
|
|
153
153
|
/** Collection of general-purpose utility methods used throughout the ORM. */
|
|
154
154
|
export class Utils {
|
|
155
155
|
static PK_SEPARATOR = '~~~';
|
|
156
|
-
static #ORM_VERSION = '7.3.0-dev.
|
|
156
|
+
static #ORM_VERSION = '7.3.0-dev.22';
|
|
157
157
|
/** Default session variable name backing an RLS filter argument (`current_setting('mikro.<filter>.<arg>')`). */
|
|
158
158
|
static getRlsSettingName(filterName, argName) {
|
|
159
159
|
return `mikro.${filterName}.${argName}`;
|
|
@@ -450,6 +450,10 @@ export class Utils {
|
|
|
450
450
|
let pk;
|
|
451
451
|
if (Utils.isEntity(entity, true)) {
|
|
452
452
|
pk = helper(entity).getPrimaryKey(convertCustomTypes);
|
|
453
|
+
// the converted PK of a relation to a composite PK target is an object keyed by the target PKs
|
|
454
|
+
if (convertCustomTypes && meta.getPrimaryProps()[0].targetMeta && Utils.isPlainObject(pk)) {
|
|
455
|
+
return toArray(pk);
|
|
456
|
+
}
|
|
453
457
|
}
|
|
454
458
|
else {
|
|
455
459
|
pk = meta.primaryKeys.reduce((o, pk) => {
|
|
@@ -915,11 +919,16 @@ export class Utils {
|
|
|
915
919
|
}, {});
|
|
916
920
|
}
|
|
917
921
|
static getObjectQueryKeys(obj) {
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
922
|
+
const keys = Object.keys(obj);
|
|
923
|
+
const symbols = Object.getOwnPropertySymbols(obj);
|
|
924
|
+
if (symbols.length === 0) {
|
|
925
|
+
return keys;
|
|
926
|
+
}
|
|
927
|
+
for (const key of symbols) {
|
|
928
|
+
if (Raw.isKnownFragmentSymbol(key) && Object.prototype.propertyIsEnumerable.call(obj, key)) {
|
|
929
|
+
keys.push(key);
|
|
921
930
|
}
|
|
922
|
-
|
|
923
|
-
|
|
931
|
+
}
|
|
932
|
+
return keys;
|
|
924
933
|
}
|
|
925
934
|
}
|
package/utils/clone.js
CHANGED
|
@@ -123,7 +123,8 @@ export function clone(parent, respectCustomCloneMethod = true) {
|
|
|
123
123
|
if (attrs && typeof attrs.get === 'function' && attrs.set == null) {
|
|
124
124
|
continue;
|
|
125
125
|
}
|
|
126
|
-
|
|
126
|
+
// `Reflect.get` avoids V8's for-in enum cache load, which can fall into an endless deopt/reoptimize loop here
|
|
127
|
+
child[i] = _clone(Reflect.get(parent, i));
|
|
127
128
|
}
|
|
128
129
|
const symbols = Object.getOwnPropertySymbols(parent);
|
|
129
130
|
for (let i = 0; i < symbols.length; i++) {
|