@mikro-orm/core 7.2.10-dev.0 → 7.2.10-dev.10
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.js +10 -2
- package/entity/Collection.d.ts +2 -1
- package/entity/Collection.js +21 -13
- package/entity/EntityFactory.js +5 -2
- package/entity/EntityHelper.js +4 -0
- package/entity/EntityLoader.js +32 -12
- package/entity/Reference.js +6 -5
- package/entity/WrappedEntity.js +1 -1
- package/entity/utils.js +3 -1
- package/entity/validators.d.ts +6 -0
- package/entity/validators.js +14 -0
- package/errors.d.ts +1 -0
- package/errors.js +3 -0
- package/hydration/ObjectHydrator.js +16 -10
- package/package.json +1 -1
- package/platforms/Platform.js +4 -1
- package/serialization/EntitySerializer.js +3 -3
- package/serialization/EntityTransformer.js +29 -30
- package/serialization/SerializationContext.js +1 -1
- package/typings.d.ts +1 -0
- package/typings.js +36 -34
- package/unit-of-work/ChangeSetComputer.js +55 -50
- package/unit-of-work/UnitOfWork.js +40 -21
- package/utils/Configuration.js +2 -1
- package/utils/Utils.js +13 -1
- package/utils/clone.js +4 -0
- package/utils/upsert-utils.js +13 -6
package/EntityManager.js
CHANGED
|
@@ -7,7 +7,7 @@ import { TransactionContext } from './utils/TransactionContext.js';
|
|
|
7
7
|
import { isRaw, Raw } from './utils/RawQueryFragment.js';
|
|
8
8
|
import { EntityFactory } from './entity/EntityFactory.js';
|
|
9
9
|
import { EntityAssigner } from './entity/EntityAssigner.js';
|
|
10
|
-
import { validateEmptyWhere, validateParams, validatePrimaryKey, validateProperty } from './entity/validators.js';
|
|
10
|
+
import { validateEmptyWhere, validatePaginationValue, validateParams, validatePrimaryKey, validateProperty, } from './entity/validators.js';
|
|
11
11
|
import { EntityLoader } from './entity/EntityLoader.js';
|
|
12
12
|
import { Reference } from './entity/Reference.js';
|
|
13
13
|
import { helper } from './entity/wrap.js';
|
|
@@ -1782,7 +1782,10 @@ export class EntityManager {
|
|
|
1782
1782
|
if (!options.cascade) {
|
|
1783
1783
|
helper(entity).__managed = true;
|
|
1784
1784
|
}
|
|
1785
|
-
em
|
|
1785
|
+
// the factory already registered it with everything it hydrated, and `em.find()` does not cascade a merge either
|
|
1786
|
+
if (!(snapshotted && helper(entity).__managed)) {
|
|
1787
|
+
em.#unitOfWork.merge(entity, visited);
|
|
1788
|
+
}
|
|
1786
1789
|
return entity;
|
|
1787
1790
|
}
|
|
1788
1791
|
/**
|
|
@@ -2453,6 +2456,11 @@ export class EntityManager {
|
|
|
2453
2456
|
opts.signal ??= this.signal;
|
|
2454
2457
|
opts.inflightQueryAbortStrategy ??= this.inflightQueryAbortStrategy;
|
|
2455
2458
|
opts.logging = opts.loggerContext = Utils.merge({ id: this.id }, this.loggerContext, opts.loggerContext, opts.logging);
|
|
2459
|
+
for (const key of ['limit', 'offset', 'first', 'last']) {
|
|
2460
|
+
if (typeof opts[key] === 'string') {
|
|
2461
|
+
opts[key] = validatePaginationValue(opts[key], key);
|
|
2462
|
+
}
|
|
2463
|
+
}
|
|
2456
2464
|
return opts;
|
|
2457
2465
|
}
|
|
2458
2466
|
/**
|
package/entity/Collection.d.ts
CHANGED
|
@@ -50,6 +50,7 @@ export declare class Collection<T extends object, O extends object = object> {
|
|
|
50
50
|
toJSON<TT extends T>(): EntityDTO<TT>[];
|
|
51
51
|
/** Adds one or more items to the collection, propagating the change to the inverse side. Returns the number of items added. */
|
|
52
52
|
add<TT extends T>(entity: TT | Reference<TT> | Iterable<TT | Reference<TT>>, ...entities: (T | Reference<T>)[]): number;
|
|
53
|
+
private addItems;
|
|
53
54
|
/**
|
|
54
55
|
* Remove specified item(s) from the collection. Note that removing item from collection does not necessarily imply deleting the target entity,
|
|
55
56
|
* it means we are disconnecting the relation - removing items from collection, not removing entities from database - `Collection.remove()`
|
|
@@ -96,7 +97,7 @@ export declare class Collection<T extends object, O extends object = object> {
|
|
|
96
97
|
/**
|
|
97
98
|
* @internal
|
|
98
99
|
*/
|
|
99
|
-
hydrate(items: T[], forcePropagate?: boolean, partial?: boolean, readonly?: boolean): void;
|
|
100
|
+
hydrate(items: T[], forcePropagate?: boolean, partial?: boolean, readonly?: boolean, count?: boolean): void;
|
|
100
101
|
/**
|
|
101
102
|
* Remove all items from the collection. Note that removing items from collection does not necessarily imply deleting the target entity,
|
|
102
103
|
* it means we are disconnecting the relation - removing items from collection, not removing entities from database - `Collection.remove()`
|
package/entity/Collection.js
CHANGED
|
@@ -6,7 +6,8 @@ import { helper, wrap } from './wrap.js';
|
|
|
6
6
|
import { QueryHelper } from '../utils/QueryHelper.js';
|
|
7
7
|
import { inspect } from '../logging/inspect.js';
|
|
8
8
|
// Globally registered so the marker survives the CJS/ESM dual-package hazard
|
|
9
|
-
// (see entitySymbol rationale in EntityHelper.ts and #7515/#7534).
|
|
9
|
+
// (see entitySymbol rationale in EntityHelper.ts and #7515/#7534). Lives on the
|
|
10
|
+
// prototype; JSON payloads cannot produce symbol keys, so they cannot forge it.
|
|
10
11
|
const collectionSymbol = Symbol.for('@mikro-orm/core/Collection');
|
|
11
12
|
/** Represents a to-many relation (1:m or m:n) as an iterable, managed collection of entities. */
|
|
12
13
|
export class Collection {
|
|
@@ -22,7 +23,6 @@ export class Collection {
|
|
|
22
23
|
#populated;
|
|
23
24
|
constructor(owner, items, initialized = true) {
|
|
24
25
|
this.owner = owner;
|
|
25
|
-
Object.defineProperty(this, collectionSymbol, { value: true, enumerable: false });
|
|
26
26
|
/* v8 ignore next */
|
|
27
27
|
if (items) {
|
|
28
28
|
let i = 0;
|
|
@@ -35,7 +35,8 @@ export class Collection {
|
|
|
35
35
|
* Creates new Collection instance, assigns it to the owning entity and sets the items to it (propagating them to their inverse sides)
|
|
36
36
|
*/
|
|
37
37
|
static isCollection(item) {
|
|
38
|
-
|
|
38
|
+
// skipping primitives keeps the symbol lookup off their wrapper prototypes, which goes megamorphic
|
|
39
|
+
return typeof item === 'object' && item !== null && item[collectionSymbol] === true;
|
|
39
40
|
}
|
|
40
41
|
static create(owner, prop, items, initialized) {
|
|
41
42
|
const coll = new Collection(owner, undefined, initialized);
|
|
@@ -158,11 +159,18 @@ export class Collection {
|
|
|
158
159
|
add(entity, ...entities) {
|
|
159
160
|
entities = Utils.asArray(entity).concat(entities);
|
|
160
161
|
const unwrapped = entities.map(i => Reference.unwrapReference(i));
|
|
161
|
-
this.
|
|
162
|
+
const added = this.addItems(unwrapped);
|
|
162
163
|
const em = this.getEntityManager(entities, false);
|
|
164
|
+
if (this.property.kind === ReferenceKind.ONE_TO_MANY && em) {
|
|
165
|
+
em.persist(entities);
|
|
166
|
+
}
|
|
167
|
+
this.cancelOrphanRemoval(unwrapped);
|
|
168
|
+
return added;
|
|
169
|
+
}
|
|
170
|
+
addItems(items) {
|
|
171
|
+
this.validateModification(items);
|
|
163
172
|
let added = 0;
|
|
164
|
-
for (const
|
|
165
|
-
const entity = Reference.unwrapReference(item);
|
|
173
|
+
for (const entity of items) {
|
|
166
174
|
if (!this.contains(entity, false)) {
|
|
167
175
|
this.incrementCount(1);
|
|
168
176
|
this[this.#items.size] = entity;
|
|
@@ -172,10 +180,6 @@ export class Collection {
|
|
|
172
180
|
this.propagate(entity, 'add');
|
|
173
181
|
}
|
|
174
182
|
}
|
|
175
|
-
if (this.property.kind === ReferenceKind.ONE_TO_MANY && em) {
|
|
176
|
-
em.persist(entities);
|
|
177
|
-
}
|
|
178
|
-
this.cancelOrphanRemoval(unwrapped);
|
|
179
183
|
return added;
|
|
180
184
|
}
|
|
181
185
|
/**
|
|
@@ -482,15 +486,18 @@ export class Collection {
|
|
|
482
486
|
/**
|
|
483
487
|
* @internal
|
|
484
488
|
*/
|
|
485
|
-
hydrate(items, forcePropagate, partial, readonly) {
|
|
489
|
+
hydrate(items, forcePropagate, partial, readonly, count = true) {
|
|
486
490
|
for (let i = 0; i < this.#items.size; i++) {
|
|
487
491
|
delete this[i];
|
|
488
492
|
}
|
|
489
493
|
this.#initialized = true;
|
|
490
494
|
this.#partial = !!partial;
|
|
491
495
|
this.#items.clear();
|
|
492
|
-
this.#count = 0;
|
|
493
|
-
|
|
496
|
+
this.#count = count ? 0 : undefined;
|
|
497
|
+
// loaded items are not persisted, that would queue an auto-flush of their type on a read-only path
|
|
498
|
+
const unwrapped = items.map(i => Reference.unwrapReference(i));
|
|
499
|
+
this.addItems(unwrapped);
|
|
500
|
+
this.cancelOrphanRemoval(unwrapped);
|
|
494
501
|
this.takeSnapshot(forcePropagate);
|
|
495
502
|
if (readonly) {
|
|
496
503
|
this.#readonly = true;
|
|
@@ -757,6 +764,7 @@ export class Collection {
|
|
|
757
764
|
}
|
|
758
765
|
}
|
|
759
766
|
Object.defineProperties(Collection.prototype, {
|
|
767
|
+
[collectionSymbol]: { value: true },
|
|
760
768
|
$: {
|
|
761
769
|
get() {
|
|
762
770
|
return this;
|
package/entity/EntityFactory.js
CHANGED
|
@@ -52,8 +52,11 @@ export class EntityFactory {
|
|
|
52
52
|
if (wrapped && !options.refresh) {
|
|
53
53
|
const wasInitialized = wrapped.isInitialized();
|
|
54
54
|
wrapped.__processing = true;
|
|
55
|
-
|
|
56
|
-
this.
|
|
55
|
+
// the no-op check rejects `undefined` values itself, so the recursive cleanup is only needed for a real merge
|
|
56
|
+
if (!this.isNoopMerge(meta2, exists, data, options)) {
|
|
57
|
+
Utils.dropUndefinedProperties(data);
|
|
58
|
+
this.mergeData(meta2, exists, data, options);
|
|
59
|
+
}
|
|
57
60
|
wrapped.__processing = false;
|
|
58
61
|
// index a merged `targetKey` value, `getByKey` ignores the old one as stale
|
|
59
62
|
if (meta2.root.targetKeys) {
|
package/entity/EntityHelper.js
CHANGED
|
@@ -317,6 +317,10 @@ export class EntityHelper {
|
|
|
317
317
|
}
|
|
318
318
|
const wrapped = helper(entity);
|
|
319
319
|
const meta = wrapped.__meta;
|
|
320
|
+
// nothing to define on the instance
|
|
321
|
+
if (meta.trackingProps.length === 0 && !meta.serializedPrimaryKey) {
|
|
322
|
+
return;
|
|
323
|
+
}
|
|
320
324
|
const platform = wrapped.__platform;
|
|
321
325
|
const serializedPrimaryKey = meta.props.find(p => p.serializedPrimaryKey);
|
|
322
326
|
const values = [];
|
package/entity/EntityLoader.js
CHANGED
|
@@ -546,14 +546,24 @@ export class EntityLoader {
|
|
|
546
546
|
}
|
|
547
547
|
options = { ...options, filters: QueryHelper.mergePropertyFilters(prop.filters, options.filters) };
|
|
548
548
|
// collections with unflushed changes, their items would be lost when reloading
|
|
549
|
-
const dirty =
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
549
|
+
const dirty = options.refresh
|
|
550
|
+
? []
|
|
551
|
+
: entities
|
|
552
|
+
.map(e => e[field])
|
|
553
|
+
.filter(coll => Utils.isCollection(coll) && coll.isDirty())
|
|
554
|
+
.map(coll => [coll, coll.getItems(false), coll.getSnapshot()]);
|
|
555
|
+
// grouped by type, as a polymorphic collection can hold references of several entity types
|
|
556
|
+
const references = new Map();
|
|
557
|
+
for (const [, items] of populate.field.includes(':') ? [] : dirty) {
|
|
558
|
+
for (const item of items.filter(i => !helper(i).__initialized)) {
|
|
559
|
+
const group = references.get(helper(item).__meta) ?? [];
|
|
560
|
+
group.push(item);
|
|
561
|
+
references.set(helper(item).__meta, group);
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
// loading the references directly keeps an initialized collection from being reloaded
|
|
565
|
+
for (const [meta, items] of references) {
|
|
566
|
+
await this.populateScalar(meta, items, {
|
|
557
567
|
...options,
|
|
558
568
|
where: {},
|
|
559
569
|
populateWhere: undefined,
|
|
@@ -561,12 +571,22 @@ export class EntityLoader {
|
|
|
561
571
|
});
|
|
562
572
|
}
|
|
563
573
|
const populated = await this.populateMany(entityName, entities, populate, options);
|
|
564
|
-
for (const [coll, items] of dirty) {
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
574
|
+
for (const [coll, items, snapshot] of dirty) {
|
|
575
|
+
// partially loaded collections can be readonly
|
|
576
|
+
if (coll.isPartial()) {
|
|
577
|
+
continue;
|
|
578
|
+
}
|
|
579
|
+
const kept = new Set(items);
|
|
580
|
+
// only the diff against the snapshot is restored, a missing snapshot means the collection was overridden via `set()`
|
|
581
|
+
const known = snapshot && new Set(snapshot);
|
|
582
|
+
const lost = items.filter(item => !coll.contains(item, false) && !known?.has(item));
|
|
583
|
+
const removed = coll.getItems(false).filter(item => !kept.has(item) && (!known || known.has(item)));
|
|
584
|
+
if (lost.length > 0) {
|
|
568
585
|
coll.add(lost);
|
|
569
586
|
}
|
|
587
|
+
if (removed.length > 0) {
|
|
588
|
+
coll.remove(removed);
|
|
589
|
+
}
|
|
570
590
|
}
|
|
571
591
|
if (!populate.children && !populate.all) {
|
|
572
592
|
return;
|
package/entity/Reference.js
CHANGED
|
@@ -5,7 +5,8 @@ import { QueryHelper } from '../utils/QueryHelper.js';
|
|
|
5
5
|
import { NotFoundError } from '../errors.js';
|
|
6
6
|
import { inspect } from '../logging/inspect.js';
|
|
7
7
|
// Globally registered so the markers survive the CJS/ESM dual-package hazard
|
|
8
|
-
// (see entitySymbol rationale in EntityHelper.ts and #7515/#7534).
|
|
8
|
+
// (see entitySymbol rationale in EntityHelper.ts and #7515/#7534). Live on the
|
|
9
|
+
// prototypes; JSON payloads cannot produce symbol keys, so they cannot forge them.
|
|
9
10
|
const referenceSymbol = Symbol.for('@mikro-orm/core/Reference');
|
|
10
11
|
const scalarReferenceSymbol = Symbol.for('@mikro-orm/core/ScalarReference');
|
|
11
12
|
/** Wrapper around an entity that provides lazy loading capabilities and identity-preserving reference semantics. */
|
|
@@ -14,7 +15,6 @@ export class Reference {
|
|
|
14
15
|
property;
|
|
15
16
|
constructor(entity) {
|
|
16
17
|
this.entity = entity;
|
|
17
|
-
Object.defineProperty(this, referenceSymbol, { value: true, enumerable: false });
|
|
18
18
|
this.set(entity);
|
|
19
19
|
const meta = helper(this.entity).__meta;
|
|
20
20
|
meta.primaryKeys.forEach(primaryKey => {
|
|
@@ -68,7 +68,7 @@ export class Reference {
|
|
|
68
68
|
* Checks whether the argument is instance of `Reference` wrapper.
|
|
69
69
|
*/
|
|
70
70
|
static isReference(data) {
|
|
71
|
-
return data
|
|
71
|
+
return typeof data === 'object' && data !== null && data[referenceSymbol] === true;
|
|
72
72
|
}
|
|
73
73
|
/**
|
|
74
74
|
* Wraps the entity in a `Reference` wrapper if the property is defined as `ref`.
|
|
@@ -184,7 +184,6 @@ export class ScalarReference {
|
|
|
184
184
|
#initialized;
|
|
185
185
|
constructor(value, initialized = value != null) {
|
|
186
186
|
this.value = value;
|
|
187
|
-
Object.defineProperty(this, scalarReferenceSymbol, { value: true, enumerable: false });
|
|
188
187
|
this.#initialized = initialized;
|
|
189
188
|
}
|
|
190
189
|
/**
|
|
@@ -235,7 +234,7 @@ export class ScalarReference {
|
|
|
235
234
|
return this.#initialized;
|
|
236
235
|
}
|
|
237
236
|
static isScalarReference(data) {
|
|
238
|
-
return data != null && typeof data === 'object' &&
|
|
237
|
+
return data != null && typeof data === 'object' && data[scalarReferenceSymbol] === true;
|
|
239
238
|
}
|
|
240
239
|
/** @ignore */
|
|
241
240
|
/* v8 ignore next */
|
|
@@ -244,6 +243,7 @@ export class ScalarReference {
|
|
|
244
243
|
}
|
|
245
244
|
}
|
|
246
245
|
Object.defineProperties(Reference.prototype, {
|
|
246
|
+
[referenceSymbol]: { value: true },
|
|
247
247
|
__meta: {
|
|
248
248
|
get() {
|
|
249
249
|
return this.entity.__meta;
|
|
@@ -271,6 +271,7 @@ Object.defineProperties(Reference.prototype, {
|
|
|
271
271
|
},
|
|
272
272
|
});
|
|
273
273
|
Object.defineProperties(ScalarReference.prototype, {
|
|
274
|
+
[scalarReferenceSymbol]: { value: true },
|
|
274
275
|
$: {
|
|
275
276
|
get() {
|
|
276
277
|
return this.value;
|
package/entity/WrappedEntity.js
CHANGED
|
@@ -110,7 +110,7 @@ export class WrappedEntity {
|
|
|
110
110
|
}
|
|
111
111
|
/** Returns the primary key value, optionally converting custom types to their database representation. */
|
|
112
112
|
getPrimaryKey(convertCustomTypes = false) {
|
|
113
|
-
const prop = this.__meta.
|
|
113
|
+
const prop = this.__meta.getPrimaryProp();
|
|
114
114
|
if (!prop) {
|
|
115
115
|
return null;
|
|
116
116
|
}
|
package/entity/utils.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { LoadStrategy, PopulatePath, ReferenceKind } from '../enums.js';
|
|
2
2
|
import { Utils } from '../utils/Utils.js';
|
|
3
|
+
import { validatePaginationValue } from './validators.js';
|
|
3
4
|
/**
|
|
4
5
|
* Expands `books.perex` like populate to use `children` array instead of the dot syntax
|
|
5
6
|
*/
|
|
@@ -96,7 +97,8 @@ export function applyPopulateHints(populate, hints) {
|
|
|
96
97
|
}
|
|
97
98
|
for (const key of Object.keys(hint)) {
|
|
98
99
|
if (hint[key] != null) {
|
|
99
|
-
entry[key] =
|
|
100
|
+
entry[key] =
|
|
101
|
+
key === 'limit' || key === 'offset' ? validatePaginationValue(hint[key], key) : hint[key];
|
|
100
102
|
}
|
|
101
103
|
}
|
|
102
104
|
}
|
package/entity/validators.d.ts
CHANGED
|
@@ -5,6 +5,12 @@ export declare function validateProperty<T extends object>(prop: EntityProperty,
|
|
|
5
5
|
export declare function validateEntity<T extends object>(entity: T, meta: EntityMetadata<T>): void;
|
|
6
6
|
/** @internal */
|
|
7
7
|
export declare function validateParams(params: any, type?: string, field?: string): void;
|
|
8
|
+
/**
|
|
9
|
+
* Converts a numeric string passed as `limit`/`offset`-like value (e.g. from a query string) to a number,
|
|
10
|
+
* other strings are rejected, non-string values are returned as is.
|
|
11
|
+
* @internal
|
|
12
|
+
*/
|
|
13
|
+
export declare function validatePaginationValue<T>(value: T, option: string): T;
|
|
8
14
|
/** @internal */
|
|
9
15
|
export declare function validatePrimaryKey<T>(entity: EntityData<T>, meta: EntityMetadata<T>): void;
|
|
10
16
|
/** @internal */
|
package/entity/validators.js
CHANGED
|
@@ -53,6 +53,20 @@ export function validateParams(params, type = 'search condition', field) {
|
|
|
53
53
|
Object.keys(params).forEach(k => validateParams(params[k], type, k));
|
|
54
54
|
}
|
|
55
55
|
}
|
|
56
|
+
/**
|
|
57
|
+
* Converts a numeric string passed as `limit`/`offset`-like value (e.g. from a query string) to a number,
|
|
58
|
+
* other strings are rejected, non-string values are returned as is.
|
|
59
|
+
* @internal
|
|
60
|
+
*/
|
|
61
|
+
export function validatePaginationValue(value, option) {
|
|
62
|
+
if (typeof value !== 'string') {
|
|
63
|
+
return value;
|
|
64
|
+
}
|
|
65
|
+
if (!/^\d+$/.test(value)) {
|
|
66
|
+
throw ValidationError.invalidPaginationValue(option, value);
|
|
67
|
+
}
|
|
68
|
+
return +value;
|
|
69
|
+
}
|
|
56
70
|
/** @internal */
|
|
57
71
|
export function validatePrimaryKey(entity, meta) {
|
|
58
72
|
const pkExists = meta.primaryKeys.every(pk => entity[pk] != null) ||
|
package/errors.d.ts
CHANGED
|
@@ -37,6 +37,7 @@ export declare class ValidationError<T extends AnyEntity = AnyEntity> extends Er
|
|
|
37
37
|
static cannotUseGroupOperatorsInsideScalars(entityName: EntityName, propName: string, payload: unknown): ValidationError;
|
|
38
38
|
static invalidEmbeddableQuery(entityName: EntityName, propName: string, embeddableType: string): ValidationError;
|
|
39
39
|
static invalidQueryCondition(cond: unknown): ValidationError;
|
|
40
|
+
static invalidPaginationValue(option: string, value: unknown): ValidationError;
|
|
40
41
|
}
|
|
41
42
|
/** Error thrown when cursor-based pagination encounters missing or invalid cursor values. */
|
|
42
43
|
export declare class CursorError<T extends AnyEntity = AnyEntity> extends ValidationError<T> {
|
package/errors.js
CHANGED
|
@@ -134,6 +134,9 @@ export class ValidationError extends Error {
|
|
|
134
134
|
static invalidQueryCondition(cond) {
|
|
135
135
|
return new ValidationError(`Invalid query condition: ${inspect(cond, { depth: 5 })}`);
|
|
136
136
|
}
|
|
137
|
+
static invalidPaginationValue(option, value) {
|
|
138
|
+
return new ValidationError(`Invalid '${option}' value ${inspect(value)}, expected a number or a string with a non-negative integer.`);
|
|
139
|
+
}
|
|
137
140
|
}
|
|
138
141
|
/** Error thrown when cursor-based pagination encounters missing or invalid cursor values. */
|
|
139
142
|
export class CursorError extends ValidationError {
|
|
@@ -9,11 +9,13 @@ import { Raw } from '../utils/RawQueryFragment.js';
|
|
|
9
9
|
import { ValidationError } from '../errors.js';
|
|
10
10
|
/** @internal JIT-compiled hydrator that converts raw database rows into entity instances with optimized generated code. */
|
|
11
11
|
export class ObjectHydrator extends Hydrator {
|
|
12
|
+
// keyed by type and `normalizeAccessors` without building a string key on every lookup
|
|
12
13
|
#hydrators = {
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
14
|
+
full: { normalized: new Map(), raw: new Map() },
|
|
15
|
+
reference: {
|
|
16
|
+
normalized: new Map(),
|
|
17
|
+
raw: new Map(),
|
|
18
|
+
},
|
|
17
19
|
};
|
|
18
20
|
#tmpIndex = 0;
|
|
19
21
|
/**
|
|
@@ -42,8 +44,8 @@ export class ObjectHydrator extends Hydrator {
|
|
|
42
44
|
* @internal Highly performance-sensitive method.
|
|
43
45
|
*/
|
|
44
46
|
getEntityHydrator(meta, type, normalizeAccessors = false) {
|
|
45
|
-
const
|
|
46
|
-
const exists =
|
|
47
|
+
const cache = this.#hydrators[type][normalizeAccessors ? 'normalized' : 'raw'];
|
|
48
|
+
const exists = cache.get(meta.class);
|
|
47
49
|
if (exists) {
|
|
48
50
|
return exists;
|
|
49
51
|
}
|
|
@@ -106,6 +108,10 @@ export class ObjectHydrator extends Hydrator {
|
|
|
106
108
|
else if (prop.runtimeType === 'boolean') {
|
|
107
109
|
ret.push(` entity${entityKey} = !!data${dataKey};`);
|
|
108
110
|
}
|
|
111
|
+
else if (prop.formula && prop.runtimeType === 'number') {
|
|
112
|
+
// drivers can return numeric expressions as strings, e.g. `count(*)` is a bigint in postgres
|
|
113
|
+
ret.push(` entity${entityKey} = Number(data${dataKey});`);
|
|
114
|
+
}
|
|
109
115
|
else if (prop.runtimeType === 'Date' && !this.platform.isNumericProperty(prop)) {
|
|
110
116
|
ret.push(` if (data${dataKey} instanceof Date) {`);
|
|
111
117
|
ret.push(` entity${entityKey} = data${dataKey};`);
|
|
@@ -220,11 +226,11 @@ export class ObjectHydrator extends Hydrator {
|
|
|
220
226
|
ret.push(` }`);
|
|
221
227
|
ret.push(` if (Array.isArray(data${dataKey})) {`);
|
|
222
228
|
ret.push(` const items = data${dataKey}.map(value => createCollectionItem_${this.safeKey(prop.name)}(value, entity));`);
|
|
223
|
-
ret.push(` const coll = Collection.create(entity, ${this.quote(prop.name)}, items, newEntity);`);
|
|
224
229
|
ret.push(` if (newEntity) {`);
|
|
225
|
-
ret.push(`
|
|
230
|
+
ret.push(` Collection.create(entity, ${this.quote(prop.name)}, items, true).setDirty();`);
|
|
226
231
|
ret.push(` } else {`);
|
|
227
|
-
|
|
232
|
+
// loaded items go through `hydrate()`, as `set()` would persist them and queue an auto-flush; the count stays unset, joined results can be filtered
|
|
233
|
+
ret.push(` Collection.create(entity, ${this.quote(prop.name)}, undefined, false).hydrate(items, true, false, false, false);`);
|
|
228
234
|
ret.push(` }`);
|
|
229
235
|
ret.push(` } else if (!entity${entityKey} && data${dataKey} instanceof Collection) {`);
|
|
230
236
|
ret.push(` entity${entityKey} = data${dataKey};`);
|
|
@@ -413,7 +419,7 @@ export class ObjectHydrator extends Hydrator {
|
|
|
413
419
|
`${lines.join('\n')}\n}`;
|
|
414
420
|
const fnKey = `hydrator-${meta.compiledName}-${type}-${normalizeAccessors}`;
|
|
415
421
|
const hydrator = Utils.createFunction(context, code, this.config.get('compiledFunctions'), fnKey);
|
|
416
|
-
|
|
422
|
+
cache.set(meta.class, hydrator);
|
|
417
423
|
return hydrator;
|
|
418
424
|
}
|
|
419
425
|
createCollectionItemMapper(prop, context) {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mikro-orm/core",
|
|
3
|
-
"version": "7.2.10-dev.
|
|
3
|
+
"version": "7.2.10-dev.10",
|
|
4
4
|
"description": "TypeScript ORM for Node.js based on Data Mapper, Unit of Work and Identity Map patterns. Supports MongoDB, MySQL, PostgreSQL and SQLite databases as well as usage with vanilla JavaScript.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"data-mapper",
|
package/platforms/Platform.js
CHANGED
|
@@ -366,7 +366,7 @@ export class Platform {
|
|
|
366
366
|
}
|
|
367
367
|
/** Serializes a string array into its database storage format. */
|
|
368
368
|
marshallArray(values) {
|
|
369
|
-
return values.map(v => (/[,",\\]/.test(v) ? JSON.stringify(v) : v)).join(',');
|
|
369
|
+
return values.map(v => (/[,",\\]/.test(v) || (v === '' && values.length === 1) ? JSON.stringify(v) : v)).join(',');
|
|
370
370
|
}
|
|
371
371
|
/** Deserializes a database-stored array string back into a string array. */
|
|
372
372
|
unmarshallArray(value) {
|
|
@@ -406,6 +406,9 @@ export class Platform {
|
|
|
406
406
|
i = comma + 1;
|
|
407
407
|
}
|
|
408
408
|
}
|
|
409
|
+
if (value.endsWith(',')) {
|
|
410
|
+
result.push('');
|
|
411
|
+
}
|
|
409
412
|
return result;
|
|
410
413
|
}
|
|
411
414
|
getBlobDeclarationSQL() {
|
|
@@ -92,13 +92,13 @@ export class EntitySerializer {
|
|
|
92
92
|
meta.primaryKeys.forEach(pk => props.add(pk));
|
|
93
93
|
}
|
|
94
94
|
if (wrapped.isInitialized() || !wrapped.hasPrimaryKey()) {
|
|
95
|
-
const entityKeys = new Set(Object.keys(entity));
|
|
96
95
|
for (const prop of meta.props) {
|
|
97
|
-
if (
|
|
96
|
+
if (Object.prototype.propertyIsEnumerable.call(entity, prop.name) ||
|
|
97
|
+
(prop.getter && prop.accessor === prop.name)) {
|
|
98
98
|
props.add(prop.name);
|
|
99
99
|
}
|
|
100
100
|
}
|
|
101
|
-
for (const key of
|
|
101
|
+
for (const key of Object.keys(entity)) {
|
|
102
102
|
if (!meta.properties[key]) {
|
|
103
103
|
props.add(key);
|
|
104
104
|
}
|
|
@@ -3,11 +3,13 @@ import { Utils } from '../utils/Utils.js';
|
|
|
3
3
|
import { ReferenceKind } from '../enums.js';
|
|
4
4
|
import { SerializationContext } from './SerializationContext.js';
|
|
5
5
|
import { isRaw } from '../utils/RawQueryFragment.js';
|
|
6
|
-
function
|
|
6
|
+
function isPropertyVisible(prop, ignoreFields) {
|
|
7
|
+
const prefixed = !prop.primary && !prop.accessor && prop.name.startsWith('_'); // ignore prefixed properties, if it's not a PK
|
|
8
|
+
return !prop.hidden && !prefixed && !ignoreFields?.includes(prop.name);
|
|
9
|
+
}
|
|
10
|
+
function isVisible(meta, propName) {
|
|
7
11
|
const prop = meta.properties[propName];
|
|
8
|
-
|
|
9
|
-
const prefixed = prop && !prop.primary && !prop.accessor && propName.startsWith('_'); // ignore prefixed properties, if it's not a PK
|
|
10
|
-
return visible && !prefixed && !ignoreFields.includes(propName);
|
|
12
|
+
return !!prop && isPropertyVisible(prop);
|
|
11
13
|
}
|
|
12
14
|
/** Converts entity instances to plain objects via `toObject()`, respecting populate hints, hidden fields, and serialization context. */
|
|
13
15
|
export class EntityTransformer {
|
|
@@ -30,23 +32,20 @@ export class EntityTransformer {
|
|
|
30
32
|
SerializationContext.propagate(root, entity, isVisible);
|
|
31
33
|
const meta = wrapped.__meta;
|
|
32
34
|
const ret = {};
|
|
33
|
-
const
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
35
|
+
const pks = meta.serializedPrimaryKey && !meta.compositePK ? [meta.serializedPrimaryKey] : meta.primaryKeys;
|
|
36
|
+
const props = [];
|
|
37
|
+
for (const pk of pks) {
|
|
38
|
+
if (meta.properties[pk]) {
|
|
39
|
+
props.push(meta.properties[pk]);
|
|
40
|
+
}
|
|
39
41
|
}
|
|
42
|
+
// own keys that are not entity properties are never visible, so only the metadata properties are collected
|
|
40
43
|
if (wrapped.isInitialized() || !wrapped.hasPrimaryKey()) {
|
|
41
|
-
const entityKeys = new Set(Object.keys(entity));
|
|
42
44
|
for (const prop of meta.props) {
|
|
43
|
-
if (
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
for (const key of entityKeys) {
|
|
48
|
-
if (!meta.properties[key]) {
|
|
49
|
-
props.add(key);
|
|
45
|
+
if ((Object.prototype.propertyIsEnumerable.call(entity, prop.name) ||
|
|
46
|
+
(prop.getter && prop.accessor === prop.name)) &&
|
|
47
|
+
!pks.includes(prop.name)) {
|
|
48
|
+
props.push(prop);
|
|
50
49
|
}
|
|
51
50
|
}
|
|
52
51
|
}
|
|
@@ -55,15 +54,15 @@ export class EntityTransformer {
|
|
|
55
54
|
if (!visited) {
|
|
56
55
|
root.visited.add(entity);
|
|
57
56
|
}
|
|
58
|
-
for (const
|
|
59
|
-
const
|
|
60
|
-
if (!
|
|
57
|
+
for (const property of props) {
|
|
58
|
+
const prop = property.name;
|
|
59
|
+
if (!raw && !isPropertyVisible(property, ignoreFields)) {
|
|
61
60
|
continue;
|
|
62
61
|
}
|
|
63
62
|
const populated = root.isMarkedAsPopulated(meta.class, prop);
|
|
64
63
|
if (!raw) {
|
|
65
64
|
const partiallyLoaded = root.isPartiallyLoaded(meta.class, prop);
|
|
66
|
-
const isPrimary = includePrimaryKeys &&
|
|
65
|
+
const isPrimary = includePrimaryKeys && property.primary;
|
|
67
66
|
if (!partiallyLoaded && !populated && !isPrimary) {
|
|
68
67
|
continue;
|
|
69
68
|
}
|
|
@@ -90,7 +89,7 @@ export class EntityTransformer {
|
|
|
90
89
|
if (typeof val === 'undefined') {
|
|
91
90
|
continue;
|
|
92
91
|
}
|
|
93
|
-
ret[this.propertyName(meta,
|
|
92
|
+
ret[this.propertyName(meta, property, raw)] = val;
|
|
94
93
|
}
|
|
95
94
|
if (!wrapped.isInitialized() && wrapped.hasPrimaryKey()) {
|
|
96
95
|
return ret;
|
|
@@ -101,7 +100,7 @@ export class EntityTransformer {
|
|
|
101
100
|
const visible = !prop.hidden && entity[prop.getterName] instanceof Function;
|
|
102
101
|
const populated = root.isMarkedAsPopulated(meta.class, prop.name);
|
|
103
102
|
if (visible) {
|
|
104
|
-
ret[this.propertyName(meta, prop
|
|
103
|
+
ret[this.propertyName(meta, prop, raw)] = this.processProperty(prop.getterName, entity, raw, populated);
|
|
105
104
|
}
|
|
106
105
|
}
|
|
107
106
|
else {
|
|
@@ -109,7 +108,7 @@ export class EntityTransformer {
|
|
|
109
108
|
const visible = !prop.hidden && typeof entity[prop.name] !== 'undefined';
|
|
110
109
|
const populated = root.isMarkedAsPopulated(meta.class, prop.name);
|
|
111
110
|
if (visible) {
|
|
112
|
-
ret[this.propertyName(meta, prop
|
|
111
|
+
ret[this.propertyName(meta, prop, raw)] = this.processProperty(prop.name, entity, raw, populated);
|
|
113
112
|
}
|
|
114
113
|
}
|
|
115
114
|
}
|
|
@@ -123,15 +122,15 @@ export class EntityTransformer {
|
|
|
123
122
|
}
|
|
124
123
|
static propertyName(meta, prop, raw) {
|
|
125
124
|
if (raw) {
|
|
126
|
-
return prop;
|
|
125
|
+
return prop.name;
|
|
127
126
|
}
|
|
128
|
-
if (
|
|
129
|
-
return
|
|
127
|
+
if (prop.serializedName) {
|
|
128
|
+
return prop.serializedName;
|
|
130
129
|
}
|
|
131
|
-
if (
|
|
130
|
+
if (prop.primary && meta.serializedPrimaryKey) {
|
|
132
131
|
return meta.serializedPrimaryKey;
|
|
133
132
|
}
|
|
134
|
-
return prop;
|
|
133
|
+
return prop.name;
|
|
135
134
|
}
|
|
136
135
|
static processProperty(prop, entity, raw, populated) {
|
|
137
136
|
const wrapped = helper(entity);
|
|
@@ -43,7 +43,7 @@ export class SerializationContext {
|
|
|
43
43
|
/** Cleans up the serialization context by removing root references from all tracked entities. */
|
|
44
44
|
close() {
|
|
45
45
|
for (const entity of this.#entities) {
|
|
46
|
-
|
|
46
|
+
helper(entity).__serializationContext.root = undefined;
|
|
47
47
|
}
|
|
48
48
|
}
|
|
49
49
|
/**
|
package/typings.d.ts
CHANGED
|
@@ -1190,6 +1190,7 @@ export interface EntityMetadata<Entity = any, Class extends EntityCtor<Entity> =
|
|
|
1190
1190
|
comparableProps: EntityProperty<Entity>[];
|
|
1191
1191
|
trackingProps: EntityProperty<Entity>[];
|
|
1192
1192
|
hydrateProps: EntityProperty<Entity>[];
|
|
1193
|
+
updateHookProps: EntityProperty<Entity>[];
|
|
1193
1194
|
validateProps: EntityProperty<Entity>[];
|
|
1194
1195
|
uniqueProps: EntityProperty<Entity>[];
|
|
1195
1196
|
getterProps: EntityProperty<Entity>[];
|
package/typings.js
CHANGED
|
@@ -216,8 +216,13 @@ export class EntityMetadata {
|
|
|
216
216
|
const onlyGetter = prop.getter && !prop.setter && prop.persist === false;
|
|
217
217
|
return !prop.inherited && prop.hydrate !== false && !discriminator && !prop.embedded && !onlyGetter;
|
|
218
218
|
});
|
|
219
|
+
this.updateHookProps = this.hydrateProps.filter(prop => prop.onUpdate || prop.kind === ReferenceKind.EMBEDDED);
|
|
219
220
|
this.trackingProps = this.hydrateProps.filter(prop => {
|
|
220
|
-
return !prop.getter &&
|
|
221
|
+
return (!prop.getter &&
|
|
222
|
+
!prop.setter &&
|
|
223
|
+
[ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(prop.kind) &&
|
|
224
|
+
(prop.inversedBy || prop.mappedBy) &&
|
|
225
|
+
!prop.mapToPk);
|
|
221
226
|
});
|
|
222
227
|
this.selfReferencing = this.relations.some(prop => {
|
|
223
228
|
return this.root.uniqueName === prop.targetMeta?.root.uniqueName;
|
|
@@ -266,40 +271,37 @@ export class EntityMetadata {
|
|
|
266
271
|
this.props.forEach(prop => this.initIndexes(prop));
|
|
267
272
|
}
|
|
268
273
|
this.definedProperties = this.trackingProps.reduce((o, prop) => {
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
if (
|
|
292
|
-
|
|
293
|
-
if (targetMeta) {
|
|
294
|
-
wrapped.__originalEntityData[prop.name] = EntityHelper.getForeignKeyValue(entity, prop, targetMeta);
|
|
295
|
-
}
|
|
274
|
+
// eslint-disable-next-line @typescript-eslint/no-this-alias
|
|
275
|
+
const meta = this;
|
|
276
|
+
o[prop.name] = {
|
|
277
|
+
get() {
|
|
278
|
+
return this.__helper.__data[prop.name];
|
|
279
|
+
},
|
|
280
|
+
set(val) {
|
|
281
|
+
const wrapped = this.__helper;
|
|
282
|
+
const hydrator = wrapped.hydrator;
|
|
283
|
+
const entity = Reference.unwrapReference(val ?? wrapped.__data[prop.name]);
|
|
284
|
+
const old = Reference.unwrapReference(wrapped.__data[prop.name]);
|
|
285
|
+
if (old &&
|
|
286
|
+
old !== entity &&
|
|
287
|
+
prop.kind === ReferenceKind.MANY_TO_ONE &&
|
|
288
|
+
prop.inversedBy &&
|
|
289
|
+
old[prop.inversedBy]) {
|
|
290
|
+
old[prop.inversedBy].removeWithoutPropagation(this);
|
|
291
|
+
}
|
|
292
|
+
wrapped.__data[prop.name] = Reference.wrapReference(val, prop);
|
|
293
|
+
// when propagation from inside hydration, we set the FK to the entity data immediately
|
|
294
|
+
if (val && hydrator.isRunning() && wrapped.__originalEntityData && prop.owner) {
|
|
295
|
+
const targetMeta = prop.targetMeta ?? helper(entity)?.__meta;
|
|
296
|
+
if (targetMeta) {
|
|
297
|
+
wrapped.__originalEntityData[prop.name] = EntityHelper.getForeignKeyValue(entity, prop, targetMeta);
|
|
296
298
|
}
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
}
|
|
299
|
+
}
|
|
300
|
+
EntityHelper.propagate(meta, entity, this, prop, Reference.unwrapReference(val), old);
|
|
301
|
+
},
|
|
302
|
+
enumerable: true,
|
|
303
|
+
configurable: true,
|
|
304
|
+
};
|
|
303
305
|
return o;
|
|
304
306
|
}, { __gettersDefined: { value: true, enumerable: false } });
|
|
305
307
|
}
|
|
@@ -33,13 +33,10 @@ export class ChangeSetComputer {
|
|
|
33
33
|
}
|
|
34
34
|
const wrapped = helper(entity);
|
|
35
35
|
const type = wrapped.__originalEntityData ? ChangeSetType.UPDATE : ChangeSetType.CREATE;
|
|
36
|
-
|
|
37
|
-
// Execute `onCreate` and `onUpdate` on properties recursively, saves `onUpdate` results
|
|
38
|
-
// to the `map` as we want to apply those only if something else changed.
|
|
36
|
+
// execute `onCreate` on properties recursively, update hooks run only after we know there are other changes
|
|
39
37
|
if (type === ChangeSetType.CREATE) {
|
|
40
|
-
// run update hooks only after we know there are other changes
|
|
41
38
|
for (const prop of meta.hydrateProps) {
|
|
42
|
-
this.processPropertyInitializers(entity, prop, type
|
|
39
|
+
this.processPropertyInitializers(entity, prop, type);
|
|
43
40
|
}
|
|
44
41
|
}
|
|
45
42
|
if (type === ChangeSetType.UPDATE && !wrapped.__initialized) {
|
|
@@ -57,17 +54,20 @@ export class ChangeSetComputer {
|
|
|
57
54
|
}
|
|
58
55
|
const changeSet = new ChangeSet(entity, type, this.computePayload(entity), meta);
|
|
59
56
|
changeSet.originalEntity = wrapped.__originalEntityData;
|
|
60
|
-
for (const prop of meta.relations
|
|
61
|
-
|
|
57
|
+
for (const prop of meta.relations) {
|
|
58
|
+
if (prop.persist !== false || prop.userDefined === false) {
|
|
59
|
+
this.processProperty(changeSet, prop);
|
|
60
|
+
}
|
|
62
61
|
}
|
|
63
62
|
if (changeSet.type === ChangeSetType.UPDATE && !Utils.hasObjectKeys(changeSet.payload)) {
|
|
64
63
|
return null;
|
|
65
64
|
}
|
|
66
65
|
validateEntity(changeSet.entity, meta);
|
|
66
|
+
const map = new Map();
|
|
67
67
|
// Execute `onCreate` and `onUpdate` on properties recursively, saves `onUpdate` results
|
|
68
68
|
// to the `map` as we want to apply those only if something else changed.
|
|
69
69
|
if (type === ChangeSetType.UPDATE) {
|
|
70
|
-
for (const prop of meta.
|
|
70
|
+
for (const prop of meta.updateHookProps) {
|
|
71
71
|
this.processPropertyInitializers(entity, prop, type, map);
|
|
72
72
|
}
|
|
73
73
|
}
|
|
@@ -107,8 +107,9 @@ export class ChangeSetComputer {
|
|
|
107
107
|
}
|
|
108
108
|
if (prop.kind === ReferenceKind.EMBEDDED && entity[prop.name]) {
|
|
109
109
|
const items = prop.array ? entity[prop.name] : [entity[prop.name]];
|
|
110
|
+
const embeddedProps = type === ChangeSetType.UPDATE ? prop.targetMeta.updateHookProps : prop.targetMeta.hydrateProps;
|
|
110
111
|
for (const item of items) {
|
|
111
|
-
for (const embeddedProp of
|
|
112
|
+
for (const embeddedProp of embeddedProps) {
|
|
112
113
|
this.processPropertyInitializers(item, embeddedProp, type, map, nested || prop.object);
|
|
113
114
|
}
|
|
114
115
|
}
|
|
@@ -143,54 +144,58 @@ export class ChangeSetComputer {
|
|
|
143
144
|
}
|
|
144
145
|
return data;
|
|
145
146
|
}
|
|
146
|
-
processProperty(changeSet, prop
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
147
|
+
processProperty(changeSet, prop) {
|
|
148
|
+
if (prop.kind !== ReferenceKind.MANY_TO_ONE && prop.kind !== ReferenceKind.ONE_TO_ONE) {
|
|
149
|
+
// m:n or 1:m
|
|
150
|
+
if (Utils.isCollection(changeSet.entity[prop.name])) {
|
|
151
|
+
this.processToMany(prop, changeSet);
|
|
152
|
+
}
|
|
151
153
|
return;
|
|
152
154
|
}
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
155
|
+
// only owning to-one sides referencing an entity can add an FK value to the payload
|
|
156
|
+
if ((prop.kind === ReferenceKind.ONE_TO_ONE && !prop.owner) || prop.mapToPk) {
|
|
157
|
+
return;
|
|
156
158
|
}
|
|
157
|
-
|
|
158
|
-
|
|
159
|
+
// perf: a relation outside of embeddables has a single target, so skip the allocations of `unwrapProperty`
|
|
160
|
+
if (!prop.object && !prop.array && !prop.embedded) {
|
|
161
|
+
const target = changeSet.entity[prop.name];
|
|
162
|
+
if (target != null) {
|
|
163
|
+
this.processToOne(prop, changeSet, target, []);
|
|
164
|
+
}
|
|
165
|
+
return;
|
|
166
|
+
}
|
|
167
|
+
const targets = Utils.unwrapProperty(changeSet.entity, changeSet.meta, prop);
|
|
168
|
+
for (const [target, idx] of targets) {
|
|
169
|
+
this.processToOne(prop, changeSet, target, idx);
|
|
159
170
|
}
|
|
160
171
|
}
|
|
161
|
-
processToOne(prop, changeSet) {
|
|
162
|
-
const
|
|
163
|
-
|
|
172
|
+
processToOne(prop, changeSet, rawTarget, idx) {
|
|
173
|
+
const target = Reference.unwrapReference(rawTarget);
|
|
174
|
+
// a same-named scalar of another polymorphic embeddable variant is not a reference
|
|
175
|
+
const needsProcessing = Utils.isEntity(target) && (prop.targetKey != null || !target.__helper.hasPrimaryKey());
|
|
176
|
+
if (!needsProcessing) {
|
|
164
177
|
return;
|
|
165
178
|
}
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
changeSet.type === ChangeSetType.UPDATE &&
|
|
187
|
-
!(prop.name in changeSet.payload) &&
|
|
188
|
-
Utils.equals(changeSet.originalEntity?.[prop.name], value)) {
|
|
189
|
-
return;
|
|
190
|
-
}
|
|
191
|
-
Utils.setPayloadProperty(changeSet.payload, changeSet.meta, prop, value, idx);
|
|
192
|
-
}
|
|
193
|
-
});
|
|
179
|
+
// a reference known only by its `targetKey` has no PK, and is never inserted to generate one
|
|
180
|
+
if (!prop.targetKey && !target.__helper.__initialized) {
|
|
181
|
+
throw ValidationError.referenceWithoutPK(target);
|
|
182
|
+
}
|
|
183
|
+
// use the actual target's meta, a polymorphic relation has several
|
|
184
|
+
let value = prop.targetKey
|
|
185
|
+
? EntityHelper.getForeignKeyValue(target, prop, target.__meta)
|
|
186
|
+
: target.__helper.__identifier;
|
|
187
|
+
if (prop.polymorphic) {
|
|
188
|
+
const discriminator = QueryHelper.findDiscriminatorValue(prop.discriminatorMap, target.constructor);
|
|
189
|
+
value = new PolymorphicRef(discriminator, value);
|
|
190
|
+
}
|
|
191
|
+
// an unchanged `targetKey` FK is not part of the diff
|
|
192
|
+
if (prop.targetKey &&
|
|
193
|
+
changeSet.type === ChangeSetType.UPDATE &&
|
|
194
|
+
!(prop.name in changeSet.payload) &&
|
|
195
|
+
Utils.equals(changeSet.originalEntity?.[prop.name], value)) {
|
|
196
|
+
return;
|
|
197
|
+
}
|
|
198
|
+
Utils.setPayloadProperty(changeSet.payload, changeSet.meta, prop, value, idx);
|
|
194
199
|
}
|
|
195
200
|
processToMany(prop, changeSet) {
|
|
196
201
|
const target = changeSet.entity[prop.name];
|
|
@@ -572,8 +572,9 @@ export class UnitOfWork {
|
|
|
572
572
|
}
|
|
573
573
|
}
|
|
574
574
|
}
|
|
575
|
-
delete
|
|
576
|
-
|
|
575
|
+
// `delete` would switch the wrapper to dictionary mode
|
|
576
|
+
wrapped.__identifier = undefined;
|
|
577
|
+
wrapped.__originalEntityData = undefined;
|
|
577
578
|
wrapped.__managed = false;
|
|
578
579
|
}
|
|
579
580
|
computeChangeSets() {
|
|
@@ -583,17 +584,21 @@ export class UnitOfWork {
|
|
|
583
584
|
this.cascade(entity, Cascade.REMOVE, visited);
|
|
584
585
|
}
|
|
585
586
|
visited.clear();
|
|
587
|
+
const persistOptions = { checkRemoveStack: true };
|
|
586
588
|
for (const entity of this.#identityMap) {
|
|
587
589
|
if (!this.#removeStack.has(entity) && !this.#persistStack.has(entity) && !this.#orphanRemoveStack.has(entity)) {
|
|
588
|
-
this.cascade(entity, Cascade.PERSIST, visited,
|
|
590
|
+
this.cascade(entity, Cascade.PERSIST, visited, persistOptions);
|
|
589
591
|
}
|
|
590
592
|
}
|
|
591
593
|
for (const entity of this.#persistStack) {
|
|
592
|
-
this.cascade(entity, Cascade.PERSIST, visited,
|
|
594
|
+
this.cascade(entity, Cascade.PERSIST, visited, persistOptions);
|
|
593
595
|
}
|
|
594
596
|
visited.clear();
|
|
597
|
+
// perf: every traversal starts with an empty `processed` set, reuse one instead of allocating it per entity
|
|
598
|
+
const processed = new Set();
|
|
595
599
|
for (const entity of this.#persistStack) {
|
|
596
|
-
|
|
600
|
+
processed.clear();
|
|
601
|
+
this.findNewEntities(entity, visited, 0, processed);
|
|
597
602
|
}
|
|
598
603
|
for (const entity of this.#orphanRemoveStack) {
|
|
599
604
|
if (!helper(entity).__processing) {
|
|
@@ -632,8 +637,10 @@ export class UnitOfWork {
|
|
|
632
637
|
}
|
|
633
638
|
}
|
|
634
639
|
}
|
|
635
|
-
|
|
636
|
-
const
|
|
640
|
+
// without inserts of this type (the common case), there is nothing to match the removed entity against
|
|
641
|
+
const early = hashes.size > 0 &&
|
|
642
|
+
[wrapped.getSerializedPrimaryKey(), ...this.expandUniqueProps(entity)].some(hash => hashes.has(hash));
|
|
643
|
+
const type = early ? ChangeSetType.DELETE_EARLY : ChangeSetType.DELETE;
|
|
637
644
|
this.computeChangeSet(entity, type);
|
|
638
645
|
}
|
|
639
646
|
}
|
|
@@ -690,7 +697,7 @@ export class UnitOfWork {
|
|
|
690
697
|
getChangeSetPersister() {
|
|
691
698
|
return this.#changeSetPersister;
|
|
692
699
|
}
|
|
693
|
-
findNewEntities(entity, visited, idx
|
|
700
|
+
findNewEntities(entity, visited, idx, processed) {
|
|
694
701
|
if (visited.has(entity)) {
|
|
695
702
|
return;
|
|
696
703
|
}
|
|
@@ -704,6 +711,13 @@ export class UnitOfWork {
|
|
|
704
711
|
wrapped.__schema ??= this.#em.schema;
|
|
705
712
|
this.initIdentifier(entity);
|
|
706
713
|
for (const prop of wrapped.__meta.relations) {
|
|
714
|
+
// perf: a relation outside of embeddables has a single target, so skip the allocations of `unwrapProperty`
|
|
715
|
+
if (!prop.object && !prop.array && !prop.embedded) {
|
|
716
|
+
if (entity[prop.name] != null) {
|
|
717
|
+
this.processReference(entity, prop, Reference.unwrapReference(entity[prop.name]), visited, processed, idx);
|
|
718
|
+
}
|
|
719
|
+
continue;
|
|
720
|
+
}
|
|
707
721
|
const targets = Utils.unwrapProperty(entity, wrapped.__meta, prop);
|
|
708
722
|
for (const [target] of targets) {
|
|
709
723
|
const kind = Reference.unwrapReference(target);
|
|
@@ -855,13 +869,12 @@ export class UnitOfWork {
|
|
|
855
869
|
return this.processToOneReference(kind, visited, processed, idx);
|
|
856
870
|
}
|
|
857
871
|
if (Utils.isCollection(kind)) {
|
|
858
|
-
kind
|
|
859
|
-
.getItems(false)
|
|
860
|
-
.filter(item => !item.__helper.__originalEntityData)
|
|
861
|
-
.forEach(item => {
|
|
872
|
+
for (const item of kind.getItems(false)) {
|
|
862
873
|
// propagate schema from parent
|
|
863
|
-
item.__helper.
|
|
864
|
-
|
|
874
|
+
if (!item.__helper.__originalEntityData) {
|
|
875
|
+
item.__helper.__schema ??= helper(parent).__schema;
|
|
876
|
+
}
|
|
877
|
+
}
|
|
865
878
|
if (prop.kind === ReferenceKind.MANY_TO_MANY && kind.isDirty()) {
|
|
866
879
|
this.processToManyReference(kind, visited, processed, parent, prop);
|
|
867
880
|
}
|
|
@@ -915,7 +928,8 @@ export class UnitOfWork {
|
|
|
915
928
|
for (const cs of this.#changeSets.values()) {
|
|
916
929
|
const wrapped = helper(cs.entity);
|
|
917
930
|
wrapped.__processing = false;
|
|
918
|
-
delete
|
|
931
|
+
// `delete` would switch the wrapper to dictionary mode for the rest of the entity's life
|
|
932
|
+
wrapped.__pk = undefined;
|
|
919
933
|
}
|
|
920
934
|
this.#persistStack.clear();
|
|
921
935
|
this.#removeStack.clear();
|
|
@@ -958,11 +972,11 @@ export class UnitOfWork {
|
|
|
958
972
|
return;
|
|
959
973
|
}
|
|
960
974
|
const kind = Reference.unwrapReference(entity[prop.name]);
|
|
961
|
-
if (
|
|
975
|
+
if ((prop.kind === ReferenceKind.MANY_TO_ONE || prop.kind === ReferenceKind.ONE_TO_ONE) && Utils.isEntity(kind)) {
|
|
962
976
|
return this.cascade(kind, type, visited, options);
|
|
963
977
|
}
|
|
964
978
|
const collection = kind;
|
|
965
|
-
if (
|
|
979
|
+
if ((prop.kind === ReferenceKind.ONE_TO_MANY || prop.kind === ReferenceKind.MANY_TO_MANY) && collection) {
|
|
966
980
|
for (const item of collection.getItems(false)) {
|
|
967
981
|
this.cascade(item, type, visited, options);
|
|
968
982
|
}
|
|
@@ -973,8 +987,11 @@ export class UnitOfWork {
|
|
|
973
987
|
return filtered.some(items => processed.has(items));
|
|
974
988
|
}
|
|
975
989
|
shouldCascade(prop, type) {
|
|
976
|
-
if (
|
|
977
|
-
|
|
990
|
+
if (prop.orphanRemoval &&
|
|
991
|
+
(type === Cascade.REMOVE ||
|
|
992
|
+
type === Cascade.SCHEDULE_ORPHAN_REMOVAL ||
|
|
993
|
+
type === Cascade.CANCEL_ORPHAN_REMOVAL ||
|
|
994
|
+
type === Cascade.ALL)) {
|
|
978
995
|
return true;
|
|
979
996
|
}
|
|
980
997
|
// ignore user settings for merge, it is kept only for back compatibility, this should have never been configurable
|
|
@@ -1008,7 +1025,9 @@ export class UnitOfWork {
|
|
|
1008
1025
|
fixMissingReference(entity, prop) {
|
|
1009
1026
|
const reference = entity[prop.name];
|
|
1010
1027
|
const target = Reference.unwrapReference(reference);
|
|
1011
|
-
if (
|
|
1028
|
+
if ((prop.kind === ReferenceKind.MANY_TO_ONE || prop.kind === ReferenceKind.ONE_TO_ONE) &&
|
|
1029
|
+
target &&
|
|
1030
|
+
!prop.mapToPk) {
|
|
1012
1031
|
if (!Utils.isEntity(target)) {
|
|
1013
1032
|
entity[prop.name] = this.#em.getReference(prop.targetMeta.class, target, {
|
|
1014
1033
|
wrapped: !!prop.ref,
|
|
@@ -1025,7 +1044,7 @@ export class UnitOfWork {
|
|
|
1025
1044
|
if (Utils.isCollection(target)) {
|
|
1026
1045
|
target.property = prop;
|
|
1027
1046
|
}
|
|
1028
|
-
const isCollection =
|
|
1047
|
+
const isCollection = prop.kind === ReferenceKind.ONE_TO_MANY || prop.kind === ReferenceKind.MANY_TO_MANY;
|
|
1029
1048
|
if (isCollection && Array.isArray(target)) {
|
|
1030
1049
|
const collection = new Collection(entity);
|
|
1031
1050
|
collection.property = prop;
|
package/utils/Configuration.js
CHANGED
|
@@ -149,7 +149,8 @@ export class Configuration {
|
|
|
149
149
|
#routines = [];
|
|
150
150
|
#routinesNormalised = false;
|
|
151
151
|
constructor(options, validate = true) {
|
|
152
|
-
|
|
152
|
+
// the default is present when re-creating from `getAll()`, it must not override an already registered provider
|
|
153
|
+
if (options.dynamicImportProvider && options.dynamicImportProvider !== DEFAULTS.dynamicImportProvider) {
|
|
153
154
|
globalThis.dynamicImportProvider = options.dynamicImportProvider;
|
|
154
155
|
}
|
|
155
156
|
this.#options = Utils.mergeConfig({}, DEFAULTS, options);
|
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.2.10-dev.
|
|
156
|
+
static #ORM_VERSION = '7.2.10-dev.10';
|
|
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}`;
|
|
@@ -640,6 +640,18 @@ export class Utils {
|
|
|
640
640
|
* Checks whether the value is POJO (e.g. `{ foo: 'bar' }`, and not instance of `Foo`)
|
|
641
641
|
*/
|
|
642
642
|
static isPlainObject(value) {
|
|
643
|
+
// primitives and object literals short-circuit with the full check's result, functions can still be null-prototype objects
|
|
644
|
+
if (typeof value === 'object') {
|
|
645
|
+
if (value === null) {
|
|
646
|
+
return false;
|
|
647
|
+
}
|
|
648
|
+
if (value.constructor === Object) {
|
|
649
|
+
return true;
|
|
650
|
+
}
|
|
651
|
+
}
|
|
652
|
+
else if (typeof value !== 'function') {
|
|
653
|
+
return false;
|
|
654
|
+
}
|
|
643
655
|
return ((value !== null &&
|
|
644
656
|
typeof value === 'object' &&
|
|
645
657
|
typeof value.constructor === 'function' &&
|
package/utils/clone.js
CHANGED
|
@@ -22,6 +22,10 @@ function getPropertyDescriptor(obj, prop) {
|
|
|
22
22
|
}
|
|
23
23
|
const TypedArray = Object.getPrototypeOf(Uint8Array);
|
|
24
24
|
export function clone(parent, respectCustomCloneMethod = true) {
|
|
25
|
+
// perf: snapshots clone every scalar, skip the cycle map for primitives
|
|
26
|
+
if (parent === null || typeof parent !== 'object') {
|
|
27
|
+
return parent;
|
|
28
|
+
}
|
|
25
29
|
// already cloned objects, so shared references and cycles map to a single clone
|
|
26
30
|
const clones = new Map();
|
|
27
31
|
function _clone(parent) {
|
package/utils/upsert-utils.js
CHANGED
|
@@ -155,14 +155,21 @@ export function getWhereCondition(meta, onConflictFields, data, where) {
|
|
|
155
155
|
unique.findIndex(p => data[p] ?? data[p.substring(0, p.indexOf('.'))] != null);
|
|
156
156
|
if (onConflictFields || where == null) {
|
|
157
157
|
if (propIndex !== false && propIndex >= 0) {
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
158
|
+
// `onConflictFields` form one composite key, while the unique props are each unique on their own
|
|
159
|
+
const keys = onConflictFields
|
|
160
|
+
? unique.filter(p => (data[p] ?? data[p.substring(0, p.indexOf('.'))]) != null)
|
|
161
|
+
: [unique[propIndex]];
|
|
162
|
+
where = {};
|
|
163
|
+
for (const field of keys) {
|
|
164
|
+
let key = field;
|
|
165
|
+
if (key.includes('.')) {
|
|
166
|
+
const prop = meta.properties[key.substring(0, key.indexOf('.'))];
|
|
167
|
+
if (prop) {
|
|
168
|
+
key = `${prop.fieldNames[0]}${key.substring(key.indexOf('.'))}`;
|
|
169
|
+
}
|
|
163
170
|
}
|
|
171
|
+
where[key] = getPropertyValue(data, field);
|
|
164
172
|
}
|
|
165
|
-
where = { [key]: getPropertyValue(data, unique[propIndex]) };
|
|
166
173
|
}
|
|
167
174
|
else {
|
|
168
175
|
for (const u of uniques) {
|