@mikro-orm/core 7.2.10-dev.0 → 7.2.10-dev.2

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 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';
@@ -2453,6 +2453,11 @@ export class EntityManager {
2453
2453
  opts.signal ??= this.signal;
2454
2454
  opts.inflightQueryAbortStrategy ??= this.inflightQueryAbortStrategy;
2455
2455
  opts.logging = opts.loggerContext = Utils.merge({ id: this.id }, this.loggerContext, opts.loggerContext, opts.logging);
2456
+ for (const key of ['limit', 'offset', 'first', 'last']) {
2457
+ if (typeof opts[key] === 'string') {
2458
+ opts[key] = validatePaginationValue(opts[key], key);
2459
+ }
2460
+ }
2456
2461
  return opts;
2457
2462
  }
2458
2463
  /**
@@ -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()`
@@ -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
- return item != null && Object.hasOwn(item, collectionSymbol);
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.validateModification(unwrapped);
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 item of entities) {
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
- this.add(items);
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;
@@ -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 = [];
@@ -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 = entities
550
- .map(e => e[field])
551
- .filter(coll => !options.refresh && Utils.isCollection(coll) && coll.isDirty())
552
- .map(coll => [coll, coll.getItems(false)]);
553
- const references = dirty.flatMap(([, items]) => items).filter(item => !helper(item).__initialized);
554
- if (references.length > 0 && !populate.field.includes(':')) {
555
- // loading the references directly keeps an initialized collection from being reloaded
556
- await this.populateScalar(prop.targetMeta, Utils.unique(references), {
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
- const lost = items.filter(item => !coll.contains(item, false));
566
- // partially loaded collections can be readonly, as well as those that were not reloaded
567
- if (lost.length > 0 && !coll.isPartial()) {
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;
@@ -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 != null && Object.hasOwn(data, referenceSymbol);
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' && Object.hasOwn(data, scalarReferenceSymbol);
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/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] = hint[key];
100
+ entry[key] =
101
+ key === 'limit' || key === 'offset' ? validatePaginationValue(hint[key], key) : hint[key];
100
102
  }
101
103
  }
102
104
  }
@@ -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 */
@@ -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 {
@@ -220,11 +220,11 @@ export class ObjectHydrator extends Hydrator {
220
220
  ret.push(` }`);
221
221
  ret.push(` if (Array.isArray(data${dataKey})) {`);
222
222
  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
223
  ret.push(` if (newEntity) {`);
225
- ret.push(` coll.setDirty();`);
224
+ ret.push(` Collection.create(entity, ${this.quote(prop.name)}, items, true).setDirty();`);
226
225
  ret.push(` } else {`);
227
- ret.push(` coll.takeSnapshot(true);`);
226
+ // loaded items go through `hydrate()`, as `set()` would persist them and queue an auto-flush; the count stays unset, joined results can be filtered
227
+ ret.push(` Collection.create(entity, ${this.quote(prop.name)}, undefined, false).hydrate(items, true, false, false, false);`);
228
228
  ret.push(` }`);
229
229
  ret.push(` } else if (!entity${entityKey} && data${dataKey} instanceof Collection) {`);
230
230
  ret.push(` entity${entityKey} = data${dataKey};`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mikro-orm/core",
3
- "version": "7.2.10-dev.0",
3
+ "version": "7.2.10-dev.2",
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",
@@ -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 (entityKeys.has(prop.name) || (prop.getter && prop.accessor === prop.name)) {
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 entityKeys) {
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 isVisible(meta, propName, ignoreFields = []) {
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
- const visible = prop && !prop.hidden;
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 props = new Set();
34
- if (meta.serializedPrimaryKey && !meta.compositePK) {
35
- props.add(meta.serializedPrimaryKey);
36
- }
37
- else {
38
- meta.primaryKeys.forEach(pk => props.add(pk));
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 (entityKeys.has(prop.name) || (prop.getter && prop.accessor === prop.name)) {
44
- props.add(prop.name);
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 prop of props) {
59
- const visible = raw ? meta.properties[prop] : isVisible(meta, prop, ignoreFields);
60
- if (!visible) {
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 && meta.properties[prop].primary;
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, prop, raw)] = val;
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.name, raw)] = this.processProperty(prop.getterName, entity, raw, populated);
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.name, raw)] = this.processProperty(prop.name, entity, raw, populated);
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 (meta.properties[prop].serializedName) {
129
- return meta.properties[prop].serializedName;
127
+ if (prop.serializedName) {
128
+ return prop.serializedName;
130
129
  }
131
- if (meta.properties[prop].primary && meta.serializedPrimaryKey) {
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
- delete helper(entity).__serializationContext.root;
46
+ helper(entity).__serializationContext.root = undefined;
47
47
  }
48
48
  }
49
49
  /**
package/typings.js CHANGED
@@ -217,7 +217,11 @@ export class EntityMetadata {
217
217
  return !prop.inherited && prop.hydrate !== false && !discriminator && !prop.embedded && !onlyGetter;
218
218
  });
219
219
  this.trackingProps = this.hydrateProps.filter(prop => {
220
- return !prop.getter && !prop.setter && [ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(prop.kind);
220
+ return (!prop.getter &&
221
+ !prop.setter &&
222
+ [ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(prop.kind) &&
223
+ (prop.inversedBy || prop.mappedBy) &&
224
+ !prop.mapToPk);
221
225
  });
222
226
  this.selfReferencing = this.relations.some(prop => {
223
227
  return this.root.uniqueName === prop.targetMeta?.root.uniqueName;
@@ -266,40 +270,37 @@ export class EntityMetadata {
266
270
  this.props.forEach(prop => this.initIndexes(prop));
267
271
  }
268
272
  this.definedProperties = this.trackingProps.reduce((o, prop) => {
269
- const hasInverse = (prop.inversedBy || prop.mappedBy) && !prop.mapToPk;
270
- if (hasInverse) {
271
- // eslint-disable-next-line @typescript-eslint/no-this-alias
272
- const meta = this;
273
- o[prop.name] = {
274
- get() {
275
- return this.__helper.__data[prop.name];
276
- },
277
- set(val) {
278
- const wrapped = this.__helper;
279
- const hydrator = wrapped.hydrator;
280
- const entity = Reference.unwrapReference(val ?? wrapped.__data[prop.name]);
281
- const old = Reference.unwrapReference(wrapped.__data[prop.name]);
282
- if (old &&
283
- old !== entity &&
284
- prop.kind === ReferenceKind.MANY_TO_ONE &&
285
- prop.inversedBy &&
286
- old[prop.inversedBy]) {
287
- old[prop.inversedBy].removeWithoutPropagation(this);
288
- }
289
- wrapped.__data[prop.name] = Reference.wrapReference(val, prop);
290
- // when propagation from inside hydration, we set the FK to the entity data immediately
291
- if (val && hydrator.isRunning() && wrapped.__originalEntityData && prop.owner) {
292
- const targetMeta = prop.targetMeta ?? helper(entity)?.__meta;
293
- if (targetMeta) {
294
- wrapped.__originalEntityData[prop.name] = EntityHelper.getForeignKeyValue(entity, prop, targetMeta);
295
- }
273
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
274
+ const meta = this;
275
+ o[prop.name] = {
276
+ get() {
277
+ return this.__helper.__data[prop.name];
278
+ },
279
+ set(val) {
280
+ const wrapped = this.__helper;
281
+ const hydrator = wrapped.hydrator;
282
+ const entity = Reference.unwrapReference(val ?? wrapped.__data[prop.name]);
283
+ const old = Reference.unwrapReference(wrapped.__data[prop.name]);
284
+ if (old &&
285
+ old !== entity &&
286
+ prop.kind === ReferenceKind.MANY_TO_ONE &&
287
+ prop.inversedBy &&
288
+ old[prop.inversedBy]) {
289
+ old[prop.inversedBy].removeWithoutPropagation(this);
290
+ }
291
+ wrapped.__data[prop.name] = Reference.wrapReference(val, prop);
292
+ // when propagation from inside hydration, we set the FK to the entity data immediately
293
+ if (val && hydrator.isRunning() && wrapped.__originalEntityData && prop.owner) {
294
+ const targetMeta = prop.targetMeta ?? helper(entity)?.__meta;
295
+ if (targetMeta) {
296
+ wrapped.__originalEntityData[prop.name] = EntityHelper.getForeignKeyValue(entity, prop, targetMeta);
296
297
  }
297
- EntityHelper.propagate(meta, entity, this, prop, Reference.unwrapReference(val), old);
298
- },
299
- enumerable: true,
300
- configurable: true,
301
- };
302
- }
298
+ }
299
+ EntityHelper.propagate(meta, entity, this, prop, Reference.unwrapReference(val), old);
300
+ },
301
+ enumerable: true,
302
+ configurable: true,
303
+ };
303
304
  return o;
304
305
  }, { __gettersDefined: { value: true, enumerable: false } });
305
306
  }
@@ -57,8 +57,10 @@ export class ChangeSetComputer {
57
57
  }
58
58
  const changeSet = new ChangeSet(entity, type, this.computePayload(entity), meta);
59
59
  changeSet.originalEntity = wrapped.__originalEntityData;
60
- for (const prop of meta.relations.filter(prop => prop.persist !== false || prop.userDefined === false)) {
61
- this.processProperty(changeSet, prop);
60
+ for (const prop of meta.relations) {
61
+ if (prop.persist !== false || prop.userDefined === false) {
62
+ this.processProperty(changeSet, prop);
63
+ }
62
64
  }
63
65
  if (changeSet.type === ChangeSetType.UPDATE && !Utils.hasObjectKeys(changeSet.payload)) {
64
66
  return null;
@@ -143,27 +145,27 @@ export class ChangeSetComputer {
143
145
  }
144
146
  return data;
145
147
  }
146
- processProperty(changeSet, prop, target) {
147
- // check for `null`/`undefined` explicitly, the target can be a falsy raw PK value like `0` (e.g. with `mapToPk`)
148
- if (target == null) {
149
- const targets = Utils.unwrapProperty(changeSet.entity, changeSet.meta, prop);
150
- targets.forEach(([t]) => this.processProperty(changeSet, prop, t));
148
+ processProperty(changeSet, prop) {
149
+ const targets = Utils.unwrapProperty(changeSet.entity, changeSet.meta, prop);
150
+ if (targets.length === 0) {
151
151
  return;
152
152
  }
153
- if (Utils.isCollection(target)) {
154
- // m:n or 1:m
155
- this.processToMany(prop, changeSet);
153
+ if (prop.kind === ReferenceKind.MANY_TO_ONE || prop.kind === ReferenceKind.ONE_TO_ONE) {
154
+ this.processToOne(prop, changeSet, targets);
155
+ return;
156
156
  }
157
- if ([ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(prop.kind)) {
158
- this.processToOne(prop, changeSet);
157
+ for (const [target] of targets) {
158
+ if (Utils.isCollection(target)) {
159
+ // m:n or 1:m
160
+ this.processToMany(prop, changeSet);
161
+ }
159
162
  }
160
163
  }
161
- processToOne(prop, changeSet) {
164
+ processToOne(prop, changeSet, targets) {
162
165
  const isToOneOwner = prop.kind === ReferenceKind.MANY_TO_ONE || (prop.kind === ReferenceKind.ONE_TO_ONE && prop.owner);
163
166
  if (!isToOneOwner || prop.mapToPk) {
164
167
  return;
165
168
  }
166
- const targets = Utils.unwrapProperty(changeSet.entity, changeSet.meta, prop);
167
169
  targets.forEach(([rawTarget, idx]) => {
168
170
  const target = Reference.unwrapReference(rawTarget);
169
171
  // a same-named scalar of another polymorphic embeddable variant is not a reference
@@ -704,6 +704,13 @@ export class UnitOfWork {
704
704
  wrapped.__schema ??= this.#em.schema;
705
705
  this.initIdentifier(entity);
706
706
  for (const prop of wrapped.__meta.relations) {
707
+ // perf: a relation outside of embeddables has a single target, so skip the allocations of `unwrapProperty`
708
+ if (!prop.object && !prop.array && !prop.embedded) {
709
+ if (entity[prop.name] != null) {
710
+ this.processReference(entity, prop, Reference.unwrapReference(entity[prop.name]), visited, processed, idx);
711
+ }
712
+ continue;
713
+ }
707
714
  const targets = Utils.unwrapProperty(entity, wrapped.__meta, prop);
708
715
  for (const [target] of targets) {
709
716
  const kind = Reference.unwrapReference(target);
@@ -915,7 +922,8 @@ export class UnitOfWork {
915
922
  for (const cs of this.#changeSets.values()) {
916
923
  const wrapped = helper(cs.entity);
917
924
  wrapped.__processing = false;
918
- delete wrapped.__pk;
925
+ // `delete` would switch the wrapper to dictionary mode for the rest of the entity's life
926
+ wrapped.__pk = undefined;
919
927
  }
920
928
  this.#persistStack.clear();
921
929
  this.#removeStack.clear();
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.0';
156
+ static #ORM_VERSION = '7.2.10-dev.2';
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}`;