@mikro-orm/core 7.3.0-dev.22 → 7.3.0-dev.24

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';
@@ -1782,7 +1782,10 @@ export class EntityManager {
1782
1782
  if (!options.cascade) {
1783
1783
  helper(entity).__managed = true;
1784
1784
  }
1785
- em.#unitOfWork.merge(entity, visited);
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
  /**
@@ -1929,13 +1932,15 @@ export class EntityManager {
1929
1932
  return em;
1930
1933
  }
1931
1934
  const entities = Utils.asArray(entity, true);
1932
- for (const ent of entities) {
1933
- if (!Utils.isEntity(ent, true)) {
1934
- throw new Error(`You need to pass entity instance or reference to 'em.remove()'. To remove entities by condition, use 'em.nativeDelete()'.`);
1935
+ em.#unitOfWork.batchRemovals(() => {
1936
+ for (const ent of entities) {
1937
+ if (!Utils.isEntity(ent, true)) {
1938
+ throw new Error(`You need to pass entity instance or reference to 'em.remove()'. To remove entities by condition, use 'em.nativeDelete()'.`);
1939
+ }
1940
+ // do not cascade just yet, cascading of entities in remove stack is done when flushing
1941
+ em.#unitOfWork.remove(Reference.unwrapReference(ent), undefined, { cascade: false });
1935
1942
  }
1936
- // do not cascade just yet, cascading of entities in remove stack is done when flushing
1937
- em.#unitOfWork.remove(Reference.unwrapReference(ent), undefined, { cascade: false });
1938
- }
1943
+ });
1939
1944
  return em;
1940
1945
  }
1941
1946
  /**
@@ -2453,6 +2458,11 @@ export class EntityManager {
2453
2458
  opts.signal ??= this.signal;
2454
2459
  opts.inflightQueryAbortStrategy ??= this.inflightQueryAbortStrategy;
2455
2460
  opts.logging = opts.loggerContext = Utils.merge({ id: this.id }, this.loggerContext, opts.loggerContext, opts.logging);
2461
+ for (const key of ['limit', 'offset', 'first', 'last']) {
2462
+ if (typeof opts[key] === 'string') {
2463
+ opts[key] = validatePaginationValue(opts[key], key);
2464
+ }
2465
+ }
2456
2466
  return opts;
2457
2467
  }
2458
2468
  /**
@@ -2479,6 +2489,11 @@ export class EntityManager {
2479
2489
  ? [meta.schema, meta.tableName, meta.discriminatorValue]
2480
2490
  : Utils.className(entityName);
2481
2491
  const key = [entityKey, method, opts, where];
2492
+ // filters of the root entity are part of `where`, but those of its relations are applied only when loading them
2493
+ const filterParams = this.getContext(false).#filterParams;
2494
+ if (options.filters !== false && Utils.hasObjectKeys(filterParams) && Utils.asArray(opts.populate).length > 0) {
2495
+ key.push({ filterParams });
2496
+ }
2482
2497
  // session context (row level security) scopes cached rows per tenant/role, avoiding cross-context serves
2483
2498
  const sessionContext = this.getContext(false).#sessionContext;
2484
2499
  if (sessionContext) {
@@ -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()`
@@ -107,7 +108,11 @@ export declare class Collection<T extends object, O extends object = object> {
107
108
  /**
108
109
  * @internal
109
110
  */
110
- removeWithoutPropagation(entity: T): void;
111
+ removeWithoutPropagation(entity: T, reindex?: boolean): boolean;
112
+ /**
113
+ * @internal
114
+ */
115
+ reindex(): void;
111
116
  /**
112
117
  * Extracts a slice of the collection items starting at position start to end (exclusive) of the collection.
113
118
  * If end is null it returns all elements from start to the end of the collection.
@@ -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;
@@ -513,14 +520,23 @@ export class Collection {
513
520
  /**
514
521
  * @internal
515
522
  */
516
- removeWithoutPropagation(entity) {
523
+ removeWithoutPropagation(entity, reindex = true) {
517
524
  if (!this.#items.delete(entity)) {
518
- return;
525
+ return false;
519
526
  }
520
527
  this.incrementCount(-1);
521
528
  delete this[this.#items.size];
522
- Object.assign(this, [...this.#items]);
529
+ if (reindex) {
530
+ this.reindex();
531
+ }
523
532
  this.#dirty = true;
533
+ return true;
534
+ }
535
+ /**
536
+ * @internal
537
+ */
538
+ reindex() {
539
+ Object.assign(this, [...this.#items]); // reassign array access
524
540
  }
525
541
  /**
526
542
  * Extracts a slice of the collection items starting at position start to end (exclusive) of the collection.
@@ -757,6 +773,7 @@ export class Collection {
757
773
  }
758
774
  }
759
775
  Object.defineProperties(Collection.prototype, {
776
+ [collectionSymbol]: { value: true },
760
777
  $: {
761
778
  get() {
762
779
  return this;
@@ -39,6 +39,10 @@ export class EntityAssigner {
39
39
  if (DANGEROUS_PROPERTY_NAMES.includes(propName)) {
40
40
  return;
41
41
  }
42
+ // keys that are not entity properties must not replace methods of the entity, e.g. `toJSON`
43
+ if (!Object.hasOwn(props, propName) && typeof entity[propName] === 'function') {
44
+ return;
45
+ }
42
46
  let value = data[propName];
43
47
  const onlyProperties = options.onlyProperties && !(propName in props);
44
48
  const ignoreUndefined = options.ignoreUndefined === true && value === undefined;
@@ -4,6 +4,7 @@ import { EventType, ReferenceKind } from '../enums.js';
4
4
  import { Reference } from './Reference.js';
5
5
  import { helper } from './wrap.js';
6
6
  import { EntityHelper } from './EntityHelper.js';
7
+ import { PolymorphicRef } from './PolymorphicRef.js';
7
8
  import { JsonType } from '../types/JsonType.js';
8
9
  import { isRaw } from '../utils/RawQueryFragment.js';
9
10
  /** @internal Factory responsible for creating, merging, and hydrating entity instances. */
@@ -52,8 +53,11 @@ export class EntityFactory {
52
53
  if (wrapped && !options.refresh) {
53
54
  const wasInitialized = wrapped.isInitialized();
54
55
  wrapped.__processing = true;
55
- Utils.dropUndefinedProperties(data);
56
- this.mergeData(meta2, exists, data, options);
56
+ // the no-op check rejects `undefined` values itself, so the recursive cleanup is only needed for a real merge
57
+ if (!this.isNoopMerge(meta2, exists, data, options)) {
58
+ Utils.dropUndefinedProperties(data);
59
+ this.mergeData(meta2, exists, data, options);
60
+ }
57
61
  wrapped.__processing = false;
58
62
  // index a merged `targetKey` value, `getByKey` ignores the old one as stale
59
63
  if (meta2.root.targetKeys) {
@@ -234,12 +238,20 @@ export class EntityFactory {
234
238
  const nullVal = (meta.forceUndefined ?? this.#config.get('forceUndefined')) ? undefined : null;
235
239
  Utils.keys(diff2).forEach(key => {
236
240
  const prop = meta.properties[key];
237
- if ([ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(prop.kind) &&
238
- Utils.isPlainObject(data[prop.name])) {
239
- // oxfmt-ignore
240
- diff2[key] = entity[prop.name] ? helper(entity[prop.name]).getPrimaryKey(options.convertCustomTypes) : null;
241
+ // a joined polymorphic row carries its target class in `constructor`, so it is not a plain object
242
+ const joined = Utils.isPlainObject(data[prop.name]) ||
243
+ (prop.polymorphic && Utils.isObject(data[prop.name]) && !(data[prop.name] instanceof PolymorphicRef));
244
+ if ([ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(prop.kind) && joined) {
245
+ const target = entity[prop.name] ? Reference.unwrapReference(entity[prop.name]) : null;
246
+ // use the actual target's meta, a polymorphic relation has several
247
+ let value = target ? EntityHelper.getForeignKeyValue(target, prop, helper(target).__meta) : null;
248
+ if (target && prop.polymorphic) {
249
+ const discriminator = QueryHelper.findDiscriminatorValue(prop.discriminatorMap, target.constructor);
250
+ value = new PolymorphicRef(discriminator, value);
251
+ }
252
+ diff2[key] = value;
241
253
  }
242
- if (!options.convertCustomTypes &&
254
+ else if (!options.convertCustomTypes &&
243
255
  [ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE, ReferenceKind.SCALAR].includes(prop.kind) &&
244
256
  prop.customType?.ensureComparable(meta, prop) &&
245
257
  diff2[key] != null) {
@@ -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 = [];
@@ -358,7 +358,11 @@ export class EntityLoader {
358
358
  // When targetKey is set, use it for FK lookup instead of the PK
359
359
  let fk = prop.targetKey ?? Utils.getPrimaryKeyHash(meta.primaryKeys);
360
360
  let schema = options.schema;
361
- const partial = !Utils.isEmpty(prop.where) || !Utils.isEmpty(options.where) || !Utils.isEmpty(options.populateFilter);
361
+ const childFilter = options.populateFilter ? await this.extractChildPopulateFilter(options, prop) : undefined;
362
+ // conditions on the populated entity itself have no sink in the child query (the joined strategy puts
363
+ // them on the join), only the nested relation ones can be forwarded as its own `populateFilter`
364
+ const [ownFilter, nestedFilter] = this.splitPopulateFilter(childFilter, meta);
365
+ const partial = !Utils.isEmpty(prop.where) || !Utils.isEmpty(options.where) || !!ownFilter;
362
366
  let polymorphicOwnerProp;
363
367
  const ownerProp = prop.kind === ReferenceKind.ONE_TO_MANY || (prop.kind === ReferenceKind.MANY_TO_MANY && !prop.owner)
364
368
  ? meta.properties[prop.mappedBy]
@@ -418,10 +422,6 @@ export class EntityLoader {
418
422
  if (!Utils.isEmpty(prop.where) || Raw.hasObjectFragments(prop.where)) {
419
423
  where = { $and: [where, prop.where] };
420
424
  }
421
- const childFilter = options.populateFilter ? await this.extractChildPopulateFilter(options, prop) : undefined;
422
- // conditions on the populated entity itself have no sink in the child query (the joined strategy puts
423
- // them on the join), only the nested relation ones can be forwarded as its own `populateFilter`
424
- const [ownFilter, nestedFilter] = this.splitPopulateFilter(childFilter, meta);
425
425
  if (ownFilter) {
426
426
  where = { $and: [where, ownFilter] };
427
427
  }
@@ -546,7 +546,49 @@ export class EntityLoader {
546
546
  return;
547
547
  }
548
548
  options = { ...options, filters: QueryHelper.mergePropertyFilters(prop.filters, options.filters) };
549
+ // collections with unflushed changes, their items would be lost when reloading
550
+ const dirty = options.refresh
551
+ ? []
552
+ : entities
553
+ .map(e => e[field])
554
+ .filter(coll => Utils.isCollection(coll) && coll.isDirty())
555
+ .map(coll => [coll, coll.getItems(false), coll.getSnapshot()]);
556
+ // grouped by type, as a polymorphic collection can hold references of several entity types
557
+ const references = new Map();
558
+ for (const [, items] of populate.field.includes(':') ? [] : dirty) {
559
+ for (const item of items.filter(i => !helper(i).__initialized)) {
560
+ const group = references.get(helper(item).__meta) ?? [];
561
+ group.push(item);
562
+ references.set(helper(item).__meta, group);
563
+ }
564
+ }
565
+ // loading the references directly keeps an initialized collection from being reloaded
566
+ for (const [meta, items] of references) {
567
+ await this.populateScalar(meta, items, {
568
+ ...options,
569
+ where: {},
570
+ populateWhere: undefined,
571
+ fields: this.buildFields(options.fields, prop),
572
+ });
573
+ }
549
574
  const populated = await this.populateMany(entityName, entities, populate, options);
575
+ for (const [coll, items, snapshot] of dirty) {
576
+ // partially loaded collections can be readonly
577
+ if (coll.isPartial()) {
578
+ continue;
579
+ }
580
+ const kept = new Set(items);
581
+ // only the diff against the snapshot is restored, a missing snapshot means the collection was overridden via `set()`
582
+ const known = snapshot && new Set(snapshot);
583
+ const lost = items.filter(item => !coll.contains(item, false) && !known?.has(item));
584
+ const removed = coll.getItems(false).filter(item => !kept.has(item) && (!known || known.has(item)));
585
+ if (lost.length > 0) {
586
+ coll.add(lost);
587
+ }
588
+ if (removed.length > 0) {
589
+ coll.remove(removed);
590
+ }
591
+ }
550
592
  if (!populate.children && !populate.all) {
551
593
  return;
552
594
  }
@@ -689,7 +731,8 @@ export class EntityLoader {
689
731
  convertCustomTypes: true,
690
732
  schema: options.schema ?? this.#em.config.get('schema'),
691
733
  });
692
- return this.#em.getUnitOfWork().register(entity, item, { refresh, loaded: true });
734
+ // the factory already registered the snapshot, the raw row is not comparable
735
+ return this.#em.getUnitOfWork().register(entity, undefined, { loaded: true });
693
736
  });
694
737
  const hasLimit = populate?.limit != null;
695
738
  entity[prop.name].hydrate(items, true, hasLimit, hasLimit);
@@ -863,14 +906,14 @@ export class EntityLoader {
863
906
  .map(c => c.field.split(':'))
864
907
  .filter(parts => parts[1] === 'ref')
865
908
  .map(parts => parts[0]));
909
+ const childFields = options.fields
910
+ .filter(f => f.startsWith(`${field}.`))
911
+ .map(f => f.substring(field.length + 1))
912
+ .filter(cf => !refChildren.has(cf.split('.')[0]));
866
913
  return children
867
914
  .map(e => Reference.unwrapReference(e[field]))
868
915
  .filter(target => {
869
916
  const wrapped = helper(target);
870
- const childFields = options.fields
871
- .filter(f => f.startsWith(`${field}.`))
872
- .map(f => f.substring(field.length + 1))
873
- .filter(cf => !refChildren.has(cf.split('.')[0]));
874
917
  return !wrapped.__initialized || !childFields.every(cf => this.isPropertyLoaded(target, cf));
875
918
  });
876
919
  }
@@ -884,6 +927,8 @@ export class EntityLoader {
884
927
  return entities;
885
928
  }
886
929
  const field = prop.name;
930
+ // the same for every entity, so compute it only once
931
+ let childFields;
887
932
  return entities.filter(e => {
888
933
  const value = e[field];
889
934
  if (value === null) {
@@ -905,7 +950,7 @@ export class EntityLoader {
905
950
  return false;
906
951
  }
907
952
  if (options.fields) {
908
- const childFields = options.fields
953
+ childFields ??= options.fields
909
954
  .filter(f => f.startsWith(`${prop.name}.`))
910
955
  .map(f => f.substring(prop.name.length + 1));
911
956
  return childFields.length > 0 && !childFields.every(f => this.isPropertyLoaded(target, f));
@@ -67,7 +67,7 @@ export declare class ScalarReference<Value> {
67
67
  load(options?: Omit<LoadReferenceOptions<any, any>, 'populate' | 'fields' | 'exclude'>): Promise<Value | undefined>;
68
68
  /**
69
69
  * Ensures the underlying entity is loaded first (without reloading it if it already is loaded).
70
- * Returns the entity or throws an error just like `em.findOneOrFail()` (and respects the same config options).
70
+ * Returns the value or throws an error naming the property, unless a `failHandler` is passed in the options.
71
71
  */
72
72
  loadOrFail(options?: Omit<LoadReferenceOrFailOptions<any, any>, 'populate' | 'fields' | 'exclude'>): Promise<Value>;
73
73
  /** Sets the scalar value and marks the reference as initialized. */
@@ -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`.
@@ -119,10 +119,10 @@ export class Reference {
119
119
  const ret = await this.load(options);
120
120
  if (!ret) {
121
121
  const wrapped = helper(this.entity);
122
- options.failHandler ??= wrapped.__em.config.get('findOneOrFailHandler');
122
+ const failHandler = options.failHandler ?? wrapped.__em.config.get('findOneOrFailHandler');
123
123
  const entityName = this.entity.constructor.name;
124
124
  const where = wrapped.getPrimaryKey();
125
- throw options.failHandler(entityName, where);
125
+ throw failHandler(entityName, where);
126
126
  }
127
127
  return ret;
128
128
  }
@@ -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
  /**
@@ -203,15 +202,16 @@ export class ScalarReference {
203
202
  }
204
203
  /**
205
204
  * Ensures the underlying entity is loaded first (without reloading it if it already is loaded).
206
- * Returns the entity or throws an error just like `em.findOneOrFail()` (and respects the same config options).
205
+ * Returns the value or throws an error naming the property, unless a `failHandler` is passed in the options.
207
206
  */
208
207
  async loadOrFail(options = {}) {
209
208
  const ret = await this.load(options);
210
209
  if (ret == null) {
211
210
  const wrapped = helper(this.entity);
212
- options.failHandler ??= wrapped.__em.config.get('findOneOrFailHandler');
213
211
  const entityName = this.entity.constructor.name;
214
- throw NotFoundError.failedToLoadProperty(entityName, this.#property, wrapped.getPrimaryKey());
212
+ const where = wrapped.getPrimaryKey();
213
+ throw (options.failHandler?.(entityName, where) ??
214
+ NotFoundError.failedToLoadProperty(entityName, this.#property, where));
215
215
  }
216
216
  return ret;
217
217
  }
@@ -235,7 +235,7 @@ export class ScalarReference {
235
235
  return this.#initialized;
236
236
  }
237
237
  static isScalarReference(data) {
238
- return data != null && typeof data === 'object' && Object.hasOwn(data, scalarReferenceSymbol);
238
+ return data != null && typeof data === 'object' && data[scalarReferenceSymbol] === true;
239
239
  }
240
240
  /** @ignore */
241
241
  /* v8 ignore next */
@@ -244,6 +244,7 @@ export class ScalarReference {
244
244
  }
245
245
  }
246
246
  Object.defineProperties(Reference.prototype, {
247
+ [referenceSymbol]: { value: true },
247
248
  __meta: {
248
249
  get() {
249
250
  return this.entity.__meta;
@@ -271,6 +272,7 @@ Object.defineProperties(Reference.prototype, {
271
272
  },
272
273
  });
273
274
  Object.defineProperties(ScalarReference.prototype, {
275
+ [scalarReferenceSymbol]: { value: true },
274
276
  $: {
275
277
  get() {
276
278
  return this.value;
@@ -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.getPrimaryProps()[0];
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] = 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 {