@mikro-orm/core 7.3.0-dev.21 → 7.3.0-dev.23

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.
Files changed (40) hide show
  1. package/EntityManager.d.ts +10 -7
  2. package/EntityManager.js +57 -31
  3. package/drivers/DatabaseDriver.d.ts +2 -0
  4. package/drivers/DatabaseDriver.js +9 -1
  5. package/entity/Collection.d.ts +2 -1
  6. package/entity/Collection.js +21 -13
  7. package/entity/EntityAssigner.js +4 -1
  8. package/entity/EntityFactory.js +19 -7
  9. package/entity/EntityHelper.d.ts +8 -3
  10. package/entity/EntityHelper.js +28 -3
  11. package/entity/EntityLoader.js +44 -1
  12. package/entity/Reference.js +6 -5
  13. package/entity/WrappedEntity.js +1 -1
  14. package/entity/utils.js +3 -1
  15. package/entity/validators.d.ts +6 -0
  16. package/entity/validators.js +14 -0
  17. package/errors.d.ts +1 -0
  18. package/errors.js +3 -0
  19. package/hydration/ObjectHydrator.js +16 -10
  20. package/metadata/MetadataDiscovery.js +26 -5
  21. package/package.json +1 -1
  22. package/platforms/Platform.js +4 -1
  23. package/serialization/EntitySerializer.js +53 -44
  24. package/serialization/EntityTransformer.js +86 -78
  25. package/serialization/SerializationContext.js +1 -1
  26. package/typings.d.ts +5 -1
  27. package/typings.js +36 -34
  28. package/unit-of-work/ChangeSetComputer.js +56 -54
  29. package/unit-of-work/ChangeSetPersister.d.ts +2 -0
  30. package/unit-of-work/ChangeSetPersister.js +10 -5
  31. package/unit-of-work/UnitOfWork.js +53 -23
  32. package/utils/Configuration.d.ts +2 -2
  33. package/utils/Configuration.js +2 -2
  34. package/utils/EntityComparator.js +2 -8
  35. package/utils/QueryHelper.d.ts +6 -0
  36. package/utils/QueryHelper.js +42 -0
  37. package/utils/TransactionManager.js +3 -1
  38. package/utils/Utils.js +27 -6
  39. package/utils/clone.js +6 -1
  40. package/utils/upsert-utils.js +13 -6
@@ -66,7 +66,7 @@ export declare class EntityManager<Driver extends IDatabaseDriver = IDatabaseDri
66
66
  /**
67
67
  * Finds all entities matching your `where` query. You can pass additional options via the `options` parameter.
68
68
  */
69
- find<Entity extends object, Hint extends string = never, Fields extends string = never, Excludes extends string = never, Using extends string = never>(entityName: EntityName<Entity>, where: [Using] extends [never] ? FilterQuery<NoInfer<Entity>> : IndexFilterQuery<NoInfer<Entity>, Using>, options?: FindOptions<Entity, Hint, Fields, Excludes> & {
69
+ find<Entity extends object, Hint extends string = never, Fields extends string = never, Excludes extends string = never, Using extends string = never>(entityName: EntityName<Entity>, where: NoInfer<[Using] extends [never] ? FilterQuery<Entity> : IndexFilterQuery<Entity, Using>>, options?: FindOptions<Entity, Hint, Fields, Excludes> & {
70
70
  using?: Using | Using[];
71
71
  }): Promise<Loaded<Entity, Hint, Fields, Excludes>[]>;
72
72
  /**
@@ -86,11 +86,11 @@ export declare class EntityManager<Driver extends IDatabaseDriver = IDatabaseDri
86
86
  * }
87
87
  * ```
88
88
  */
89
- stream<Entity extends object, Hint extends string = never, Fields extends string = never, Excludes extends string = never, Using extends string = never>(entityName: EntityName<Entity>, options?: WithUsingOptions<StreamOptions<NoInfer<Entity>, Hint, Fields, Excludes>, NoInfer<Entity>, Using>): AsyncIterableIterator<Loaded<Entity, Hint, Fields, Excludes>>;
89
+ stream<Entity extends object, Hint extends string = never, Fields extends string = never, Excludes extends string = never, Using extends string = never>(entityName: EntityName<Entity>, options?: WithUsingOptions<StreamOptions<Entity, Hint, Fields, Excludes>, NoInfer<Entity>, Using>): AsyncIterableIterator<Loaded<Entity, Hint, Fields, Excludes>>;
90
90
  /**
91
91
  * Finds all entities of given type, optionally matching the `where` condition provided in the `options` parameter.
92
92
  */
93
- findAll<Entity extends object, Hint extends string = never, Fields extends string = never, Excludes extends string = never, Using extends string = never>(entityName: EntityName<Entity>, options?: WithUsingOptions<FindAllOptions<NoInfer<Entity>, Hint, Fields, Excludes>, NoInfer<Entity>, Using>): Promise<Loaded<Entity, Hint, Fields, Excludes>[]>;
93
+ findAll<Entity extends object, Hint extends string = never, Fields extends string = never, Excludes extends string = never, Using extends string = never>(entityName: EntityName<Entity>, options?: WithUsingOptions<FindAllOptions<Entity, Hint, Fields, Excludes>, NoInfer<Entity>, Using>): Promise<Loaded<Entity, Hint, Fields, Excludes>[]>;
94
94
  private getPopulateWhere;
95
95
  /**
96
96
  * Registers global filter to this entity manager. Global filters are enabled by default (unless disabled via last parameter).
@@ -163,7 +163,7 @@ export declare class EntityManager<Driver extends IDatabaseDriver = IDatabaseDri
163
163
  * Calls `em.find()` and `em.count()` with the same arguments (where applicable) and returns the results as tuple
164
164
  * where the first element is the array of entities, and the second is the count.
165
165
  */
166
- findAndCount<Entity extends object, Hint extends string = never, Fields extends string = never, Excludes extends string = never, Using extends string = never>(entityName: EntityName<Entity>, where: [Using] extends [never] ? FilterQuery<NoInfer<Entity>> : IndexFilterQuery<NoInfer<Entity>, Using>, options?: FindOptions<Entity, Hint, Fields, Excludes> & {
166
+ findAndCount<Entity extends object, Hint extends string = never, Fields extends string = never, Excludes extends string = never, Using extends string = never>(entityName: EntityName<Entity>, where: NoInfer<[Using] extends [never] ? FilterQuery<Entity> : IndexFilterQuery<Entity, Using>>, options?: FindOptions<Entity, Hint, Fields, Excludes> & {
167
167
  using?: Using | Using[];
168
168
  }): Promise<[Loaded<Entity, Hint, Fields, Excludes>[], number]>;
169
169
  /**
@@ -222,7 +222,7 @@ export declare class EntityManager<Driver extends IDatabaseDriver = IDatabaseDri
222
222
  * }
223
223
  * ```
224
224
  */
225
- findByCursor<Entity extends object, Hint extends string = never, Fields extends string = never, Excludes extends string = never, IncludeCount extends boolean = true, Using extends string = never>(entityName: EntityName<Entity>, options: WithUsingOptions<FindByCursorOptions<NoInfer<Entity>, Hint, Fields, Excludes, IncludeCount>, NoInfer<Entity>, Using>): Promise<Cursor<Entity, Hint, Fields, Excludes, IncludeCount>>;
225
+ findByCursor<Entity extends object, Hint extends string = never, Fields extends string = never, Excludes extends string = never, IncludeCount extends boolean = true, Using extends string = never>(entityName: EntityName<Entity>, options: WithUsingOptions<FindByCursorOptions<Entity, Hint, Fields, Excludes, IncludeCount>, NoInfer<Entity>, Using>): Promise<Cursor<Entity, Hint, Fields, Excludes, IncludeCount>>;
226
226
  /**
227
227
  * Refreshes the persistent state of an entity from the database, overriding any local changes that have not yet been
228
228
  * persisted. Returns the same entity instance (same object reference), but re-hydrated. If the entity is no longer
@@ -238,7 +238,7 @@ export declare class EntityManager<Driver extends IDatabaseDriver = IDatabaseDri
238
238
  /**
239
239
  * Finds first entity matching your `where` query.
240
240
  */
241
- findOne<Entity extends object, Hint extends string = never, Fields extends string = never, Excludes extends string = never, Using extends string = never>(entityName: EntityName<Entity>, where: [Using] extends [never] ? FilterQuery<NoInfer<Entity>> : IndexFilterQuery<NoInfer<Entity>, Using>, options?: FindOneOptions<Entity, Hint, Fields, Excludes> & {
241
+ findOne<Entity extends object, Hint extends string = never, Fields extends string = never, Excludes extends string = never, Using extends string = never>(entityName: EntityName<Entity>, where: NoInfer<[Using] extends [never] ? FilterQuery<Entity> : IndexFilterQuery<Entity, Using>>, options?: FindOneOptions<Entity, Hint, Fields, Excludes> & {
242
242
  using?: Using | Using[];
243
243
  }): Promise<Loaded<Entity, Hint, Fields, Excludes> | null>;
244
244
  /**
@@ -247,7 +247,7 @@ export declare class EntityManager<Driver extends IDatabaseDriver = IDatabaseDri
247
247
  * You can override the factory for creating this method via `options.failHandler` locally
248
248
  * or via `Configuration.findOneOrFailHandler` (`findExactlyOneOrFailHandler` when specifying `strict`) globally.
249
249
  */
250
- findOneOrFail<Entity extends object, Hint extends string = never, Fields extends string = never, Excludes extends string = never, Using extends string = never>(entityName: EntityName<Entity>, where: [Using] extends [never] ? FilterQuery<NoInfer<Entity>> : IndexFilterQuery<NoInfer<Entity>, Using>, options?: FindOneOrFailOptions<Entity, Hint, Fields, Excludes> & {
250
+ findOneOrFail<Entity extends object, Hint extends string = never, Fields extends string = never, Excludes extends string = never, Using extends string = never>(entityName: EntityName<Entity>, where: NoInfer<[Using] extends [never] ? FilterQuery<Entity> : IndexFilterQuery<Entity, Using>>, options?: FindOneOrFailOptions<Entity, Hint, Fields, Excludes> & {
251
251
  using?: Using | Using[];
252
252
  }): Promise<Loaded<Entity, Hint, Fields, Excludes>>;
253
253
  /**
@@ -342,6 +342,8 @@ export declare class EntityManager<Driver extends IDatabaseDriver = IDatabaseDri
342
342
  * Runs your callback wrapped inside a database transaction.
343
343
  */
344
344
  lock<T extends object>(entity: T, lockMode: LockMode, options?: LockOptions | number | Date): Promise<void>;
345
+ /** The data as sent to the driver, a target given only by its PK is looked up in the identity map. */
346
+ private withReferencedValues;
345
347
  /**
346
348
  * Fires native insert query. Calling this has no side effects on the context (identity map).
347
349
  */
@@ -415,6 +417,7 @@ export declare class EntityManager<Driver extends IDatabaseDriver = IDatabaseDri
415
417
  * via second parameter. By default, it will return already loaded entities without modifying them.
416
418
  */
417
419
  merge<Entity extends object>(entityName: EntityName<Entity>, data: EntityData<Entity> | EntityDTO<Entity>, options?: MergeOptions): Entity;
420
+ private mergeData;
418
421
  /**
419
422
  * Creates new instance of given entity and populates it with given data.
420
423
  * The entity constructor will be used unless you provide `{ managed: true }` in the `options` parameter.
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';
@@ -560,6 +560,7 @@ export class EntityManager {
560
560
  return;
561
561
  }
562
562
  const ret = options.populate;
563
+ const hasGlobalFilters = Utils.hasObjectKeys(this.config.get('filters')) || Utils.hasObjectKeys(this.#filters);
563
564
  for (const prop of meta.relations) {
564
565
  if (prop.object ||
565
566
  ![ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(prop.kind) ||
@@ -570,20 +571,19 @@ export class EntityManager {
570
571
  }
571
572
  options = { ...options, filters: QueryHelper.mergePropertyFilters(prop.filters, options.filters) };
572
573
  // For polymorphic relations, check all targets for filters (not just the first targetMeta)
574
+ const targets = prop.polymorphic && prop.polymorphTargets?.length ? prop.polymorphTargets : [prop.targetMeta];
575
+ // `applyFilters()` can only return a condition when some filter is registered globally or on the target
576
+ if (!hasGlobalFilters && !targets.some(t => Utils.hasObjectKeys(t.filters))) {
577
+ continue;
578
+ }
573
579
  let hasActiveFilter = false;
574
- if (prop.polymorphic && prop.polymorphTargets?.length) {
575
- for (const targetMeta of prop.polymorphTargets) {
576
- const cond = await this.applyFilters(targetMeta.class, {}, options.filters, 'read', options);
577
- if (!Utils.isEmpty(cond)) {
578
- hasActiveFilter = true;
579
- break;
580
- }
580
+ for (const targetMeta of targets) {
581
+ const cond = await this.applyFilters(targetMeta.class, {}, options.filters, 'read', options);
582
+ if (!Utils.isEmpty(cond)) {
583
+ hasActiveFilter = true;
584
+ break;
581
585
  }
582
586
  }
583
- else {
584
- const cond = await this.applyFilters(prop.targetMeta.class, {}, options.filters, 'read', options);
585
- hasActiveFilter = !Utils.isEmpty(cond);
586
- }
587
587
  if (hasActiveFilter) {
588
588
  const populated = options.populate.filter(({ field }) => field.split(':')[0] === prop.name);
589
589
  let found = false;
@@ -972,6 +972,7 @@ export class EntityManager {
972
972
  }
973
973
  const meta = this.metadata.get(entityName);
974
974
  const convertCustomTypes = !Utils.isEntity(data);
975
+ const source = data;
975
976
  let generatedFields = [];
976
977
  if (Utils.isEntity(data)) {
977
978
  entity = data;
@@ -1015,7 +1016,7 @@ export class EntityManager {
1015
1016
  data = em.#comparator.prepareEntity(entity);
1016
1017
  }
1017
1018
  }
1018
- const ret = await em.withSessionContext(options.ctx ?? em.#transactionContext, ctx => em.driver.nativeUpdate(entityName, where, data, {
1019
+ const ret = await em.withSessionContext(options.ctx ?? em.#transactionContext, ctx => em.driver.nativeUpdate(entityName, where, em.withReferencedValues(meta, data, source, options.schema), {
1019
1020
  upsert: true,
1020
1021
  convertCustomTypes,
1021
1022
  ...options,
@@ -1175,6 +1176,7 @@ export class EntityManager {
1175
1176
  }
1176
1177
  }
1177
1178
  // the rows are replaced with their processed copies below, keep the caller's array intact
1179
+ const sources = data;
1178
1180
  data = [...data];
1179
1181
  const meta = this.metadata.get(entityName);
1180
1182
  const convertCustomTypes = !Utils.isEntity(data[0]);
@@ -1281,7 +1283,7 @@ export class EntityManager {
1281
1283
  }
1282
1284
  });
1283
1285
  }
1284
- const res = await em.withSessionContext(options.ctx ?? em.#transactionContext, ctx => em.driver.nativeUpdateMany(entityName, allWhere, allData, {
1286
+ const res = await em.withSessionContext(options.ctx ?? em.#transactionContext, ctx => em.driver.nativeUpdateMany(entityName, allWhere, allData.map((row, idx) => em.withReferencedValues(meta, row, sources[dataIndexes[idx]], options.schema)), {
1285
1287
  upsert: true,
1286
1288
  convertCustomTypes,
1287
1289
  ...options,
@@ -1530,6 +1532,10 @@ export class EntityManager {
1530
1532
  options = this.getContext(false).prepareOptions(options);
1531
1533
  await this.getUnitOfWork().lock(entity, { lockMode, ...options });
1532
1534
  }
1535
+ /** The data as sent to the driver, a target given only by its PK is looked up in the identity map. */
1536
+ withReferencedValues(meta, data, source, schema) {
1537
+ return QueryHelper.withReferencedValues(meta, data, source, this.getPlatform(), (prop, pk) => this.#unitOfWork.getById(prop.targetMeta.class, pk, schema));
1538
+ }
1533
1539
  /**
1534
1540
  * Fires native insert query. Calling this has no side effects on the context (identity map).
1535
1541
  */
@@ -1557,9 +1563,11 @@ export class EntityManager {
1557
1563
  await em.withSessionContext(options.ctx ?? em.#transactionContext, ctx => em.#unitOfWork.getChangeSetPersister().executeInserts([cs], { ...options, ctx }));
1558
1564
  return cs.getPrimaryKey();
1559
1565
  }
1566
+ const source = data;
1560
1567
  data = QueryHelper.processObjectParams(data);
1561
1568
  validateParams(data, 'insert data');
1562
- const res = await em.withSessionContext(options.ctx ?? em.#transactionContext, ctx => em.driver.nativeInsert(entityName, data, { ...options, ctx }));
1569
+ const insertData = em.withReferencedValues(em.metadata.get(entityName), data, source, options.schema);
1570
+ const res = await em.withSessionContext(options.ctx ?? em.#transactionContext, ctx => em.driver.nativeInsert(entityName, insertData, { ...options, ctx }));
1563
1571
  return res.insertId;
1564
1572
  }
1565
1573
  /**
@@ -1639,9 +1647,12 @@ export class EntityManager {
1639
1647
  await em.withSessionContext(options.ctx ?? em.#transactionContext, ctx => em.#unitOfWork.getChangeSetPersister().executeInserts(css, { ...options, ctx }));
1640
1648
  return css.map(cs => cs.getPrimaryKey());
1641
1649
  }
1650
+ const sources = data;
1642
1651
  data = data.map(row => QueryHelper.processObjectParams(row));
1643
1652
  data.forEach(row => validateParams(row, 'insert data'));
1644
- const res = await em.withSessionContext(options.ctx ?? em.#transactionContext, ctx => em.driver.nativeInsertMany(entityName, data, { ...options, ctx }));
1653
+ const meta = em.metadata.get(entityName);
1654
+ const insertData = data.map((row, idx) => em.withReferencedValues(meta, row, sources[idx], options.schema));
1655
+ const res = await em.withSessionContext(options.ctx ?? em.#transactionContext, ctx => em.driver.nativeInsertMany(entityName, insertData, { ...options, ctx }));
1645
1656
  if (res.insertedIds) {
1646
1657
  return res.insertedIds;
1647
1658
  }
@@ -1654,11 +1665,12 @@ export class EntityManager {
1654
1665
  const em = this.getContext(false);
1655
1666
  options = em.prepareOptions(options);
1656
1667
  await em.processUnionWhere(entityName, options, 'update');
1668
+ const source = data;
1657
1669
  data = QueryHelper.processObjectParams(data);
1658
1670
  where = await em.processWhere(entityName, where, { ...options, convertCustomTypes: false }, 'update');
1659
1671
  validateParams(data, 'update data');
1660
1672
  validateParams(where, 'update condition');
1661
- const res = await em.withSessionContext(options.ctx ?? em.#transactionContext, ctx => em.driver.nativeUpdate(entityName, where, data, {
1673
+ const res = await em.withSessionContext(options.ctx ?? em.#transactionContext, ctx => em.driver.nativeUpdate(entityName, where, em.withReferencedValues(em.metadata.get(entityName), data, source, options.schema), {
1662
1674
  em,
1663
1675
  ...options,
1664
1676
  ctx,
@@ -1736,12 +1748,7 @@ export class EntityManager {
1736
1748
  validateProperty(prop, data[k], data);
1737
1749
  }
1738
1750
  }
1739
- return this.merge(entityName, data, {
1740
- convertCustomTypes: true,
1741
- refresh: true,
1742
- validate: false,
1743
- ...rest,
1744
- });
1751
+ return this.mergeData(entityName, data, { convertCustomTypes: true, refresh: true, validate: false, ...rest }, true);
1745
1752
  }
1746
1753
  /**
1747
1754
  * Merges given entity to this EntityManager so it becomes managed. You can force refreshing of existing entities
@@ -1751,6 +1758,9 @@ export class EntityManager {
1751
1758
  if (Utils.isEntity(entityName)) {
1752
1759
  return this.merge(entityName.constructor, entityName, data);
1753
1760
  }
1761
+ return this.mergeData(entityName, data, options, false);
1762
+ }
1763
+ mergeData(entityName, data, options, driverData) {
1754
1764
  const em = options.disableContextResolution ? this : this.getContext();
1755
1765
  options = { ...options };
1756
1766
  options.schema ??= em.#schema;
@@ -1762,11 +1772,20 @@ export class EntityManager {
1762
1772
  return entity;
1763
1773
  }
1764
1774
  const dataIsEntity = Utils.isEntity(data);
1775
+ // the factory snapshots a new entity from driver data like `em.find()` does, an empty `visited` skips the re-snapshot
1776
+ const snapshotted = driverData && !entity;
1765
1777
  entity = dataIsEntity
1766
1778
  ? data
1767
1779
  : em.#entityFactory.create(entityName, data, { merge: true, ...options });
1768
- const visited = options.cascade ? undefined : new Set([entity]);
1769
- em.#unitOfWork.merge(entity, visited);
1780
+ const visited = options.cascade ? (snapshotted ? new Set() : undefined) : new Set([entity]);
1781
+ // with `visited` set, the unit of work would skip the explicitly merged entity as if it was a cascaded one
1782
+ if (!options.cascade) {
1783
+ helper(entity).__managed = true;
1784
+ }
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
+ }
1770
1789
  return entity;
1771
1790
  }
1772
1791
  /**
@@ -2001,19 +2020,20 @@ export class EntityManager {
2001
2020
  : options.cloneEventManager
2002
2021
  ? em.eventManager.clone()
2003
2022
  : em.eventManager;
2004
- // we need to allow global context here as forking from global EM is fine
2005
- const allowGlobalContext = em.config.get('allowGlobalContext');
2006
- em.config.set('allowGlobalContext', true);
2023
+ // forking from global EM is fine; toggled directly as `config.set()` also re-syncs env/logger state (hot path)
2024
+ const configOptions = em.config.getAll();
2025
+ const allowGlobalContext = configOptions.allowGlobalContext;
2026
+ configOptions.allowGlobalContext = true;
2007
2027
  const fork = new em.constructor(em.config, em.driver, em.metadata, options.useContext, eventManager);
2008
2028
  fork.setFlushMode(options.flushMode ?? em.#flushMode);
2009
2029
  fork.#disableTransactions =
2010
2030
  options.disableTransactions ?? this.#disableTransactions ?? this.config.get('disableTransactions');
2011
- em.config.set('allowGlobalContext', allowGlobalContext);
2031
+ configOptions.allowGlobalContext = allowGlobalContext;
2012
2032
  if (options.keepTransactionContext) {
2013
2033
  fork.#transactionContext = em.#transactionContext;
2014
2034
  }
2015
2035
  fork.#filters = { ...em.#filters };
2016
- fork.#filterParams = Utils.copy(em.#filterParams);
2036
+ fork.#filterParams = Utils.hasObjectKeys(em.#filterParams) ? Utils.copy(em.#filterParams) : {};
2017
2037
  if (options.session) {
2018
2038
  // the fork's session replaces the parent context, but the copied `rls` filter params must stay consistent with
2019
2039
  // it — re-stage their variables underneath the explicit `session.variables`, which win on any conflict
@@ -2026,7 +2046,8 @@ export class EntityManager {
2026
2046
  else if (em.#sessionContext) {
2027
2047
  fork.#sessionContext = Utils.copy(em.#sessionContext);
2028
2048
  }
2029
- fork.loggerContext = Utils.merge({}, em.loggerContext, options.loggerContext);
2049
+ fork.loggerContext =
2050
+ em.loggerContext || options.loggerContext ? Utils.merge({}, em.loggerContext, options.loggerContext) : {};
2030
2051
  fork.#schema = options.schema ?? em.#schema;
2031
2052
  fork.signal = options.signal ?? em.signal;
2032
2053
  fork.inflightQueryAbortStrategy = options.inflightQueryAbortStrategy ?? em.inflightQueryAbortStrategy;
@@ -2435,6 +2456,11 @@ export class EntityManager {
2435
2456
  opts.signal ??= this.signal;
2436
2457
  opts.inflightQueryAbortStrategy ??= this.inflightQueryAbortStrategy;
2437
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
+ }
2438
2464
  return opts;
2439
2465
  }
2440
2466
  /**
@@ -87,6 +87,8 @@ export declare abstract class DatabaseDriver<C extends Connection> implements ID
87
87
  mapDataToFieldNames(data: Dictionary, stringifyJsonArrays: boolean, properties?: Record<string, EntityProperty>, convertCustomTypes?: boolean, object?: boolean): Dictionary;
88
88
  protected inlineEmbeddables<T extends object>(meta: EntityMetadata<T>, data: T, where?: boolean): void;
89
89
  protected getPrimaryKeyFields<T>(meta: EntityMetadata<T>): string[];
90
+ /** Column a scalar value of the property maps to; a composite FK given as a scalar holds only the target PK, which belongs to the column referencing it. */
91
+ protected getScalarFieldName(prop: EntityProperty): string;
90
92
  protected createReplicas(cb: (c: ConnectionOptions) => C): C[];
91
93
  /** Acquires a pessimistic lock on the given entity. */
92
94
  lockPessimistic<T extends object>(entity: T, options: LockOptions): Promise<void>;
@@ -511,7 +511,7 @@ export class DatabaseDriver {
511
511
  data[k] = raw(sql.replace(/\?/g, '\\?'));
512
512
  }
513
513
  if (prop.fieldNames) {
514
- Utils.renameKey(data, k, prop.fieldNames[0]);
514
+ Utils.renameKey(data, k, this.getScalarFieldName(prop));
515
515
  }
516
516
  });
517
517
  return data;
@@ -580,6 +580,14 @@ export class DatabaseDriver {
580
580
  getPrimaryKeyFields(meta) {
581
581
  return meta.getPrimaryProps().flatMap(pk => pk.fieldNames);
582
582
  }
583
+ /** Column a scalar value of the property maps to; a composite FK given as a scalar holds only the target PK, which belongs to the column referencing it. */
584
+ getScalarFieldName(prop) {
585
+ if (prop.fieldNames.length < 2 || prop.polymorphic || !prop.targetMeta) {
586
+ return prop.fieldNames[0];
587
+ }
588
+ const idx = prop.referencedColumnNames.indexOf(prop.targetMeta.getPrimaryProps()[0]?.fieldNames[0]);
589
+ return prop.fieldNames[idx === -1 ? 0 : idx];
590
+ }
583
591
  createReplicas(cb) {
584
592
  const replicas = this.config.get('replicas', []);
585
593
  const ret = [];
@@ -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;
@@ -109,7 +109,10 @@ export class EntityAssigner {
109
109
  value != null &&
110
110
  !(value instanceof Date) &&
111
111
  (typeof value === 'string' || typeof value === 'number')) {
112
- value = new Date(value);
112
+ const date = new Date(value);
113
+ if (!isNaN(date.getTime())) {
114
+ value = date;
115
+ }
113
116
  }
114
117
  validateProperty(prop, value, entity);
115
118
  return (entity[prop.name] = value);
@@ -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) {
@@ -1,5 +1,5 @@
1
1
  import type { EntityManager } from '../EntityManager.js';
2
- import { type EntityMetadata, type EntityProperty, type IHydrator } from '../typings.js';
2
+ import { type AnyEntity, type EntityMetadata, type EntityProperty, type IHydrator } from '../typings.js';
3
3
  /**
4
4
  * @internal
5
5
  */
@@ -15,8 +15,8 @@ export declare class EntityHelper {
15
15
  private static defineBaseProperties;
16
16
  /**
17
17
  * Defines getter and setter for every owning side of m:1 and 1:1 relation. This is then used for propagation of
18
- * changes to the inverse side of bi-directional relations. Rest of the properties are also defined this way to
19
- * achieve dirtiness, which is then used for fast checks whether we need to auto-flush because of managed entities.
18
+ * changes to the inverse side of bi-directional relations. Other properties stay plain data properties on the instance,
19
+ * unless the prototype already has an accessor for them (e.g. a getter-only property the hydrator needs to write to).
20
20
  *
21
21
  * First defines a setter on the prototype, once called, actual get/set handlers are registered on the instance rather
22
22
  * than on its prototype. Thanks to this we still have those properties enumerable (e.g. part of `Object.keys(entity)`).
@@ -24,6 +24,11 @@ export declare class EntityHelper {
24
24
  private static defineProperties;
25
25
  static defineCustomInspect<T extends object>(meta: EntityMetadata<T>): void;
26
26
  static defineReferenceProperty<T extends object>(meta: EntityMetadata<T>, prop: EntityProperty<T>, ref: T, hydrator: IHydrator): void;
27
+ /**
28
+ * Returns the database value of the FK pointing to the given entity.
29
+ * @internal
30
+ */
31
+ static getForeignKeyValue(target: AnyEntity, prop: EntityProperty<any>, targetMeta: EntityMetadata): any;
27
32
  static propagate<T extends object>(meta: EntityMetadata<T>, entity: T, owner: T, prop: EntityProperty<T>, value?: T[keyof T & string], old?: T): void;
28
33
  private static propagateOneToOne;
29
34
  static ensurePropagation<T extends object>(entity: T): void;
@@ -98,8 +98,8 @@ export class EntityHelper {
98
98
  }
99
99
  /**
100
100
  * Defines getter and setter for every owning side of m:1 and 1:1 relation. This is then used for propagation of
101
- * changes to the inverse side of bi-directional relations. Rest of the properties are also defined this way to
102
- * achieve dirtiness, which is then used for fast checks whether we need to auto-flush because of managed entities.
101
+ * changes to the inverse side of bi-directional relations. Other properties stay plain data properties on the instance,
102
+ * unless the prototype already has an accessor for them (e.g. a getter-only property the hydrator needs to write to).
103
103
  *
104
104
  * First defines a setter on the prototype, once called, actual get/set handlers are registered on the instance rather
105
105
  * than on its prototype. Thanks to this we still have those properties enumerable (e.g. part of `Object.keys(entity)`).
@@ -122,6 +122,12 @@ export class EntityHelper {
122
122
  if (prop.inherited || prop.primary || prop.accessor || prop.persist === false || prop.embedded || isCollection) {
123
123
  return;
124
124
  }
125
+ const desc = Object.getOwnPropertyDescriptor(meta.prototype, prop.name);
126
+ // a writable placeholder keeps `prop in entity` working, while assignments create plain own properties
127
+ if (!desc?.get && !desc?.set) {
128
+ Object.defineProperty(meta.prototype, prop.name, { value: undefined, writable: true, configurable: true });
129
+ return;
130
+ }
125
131
  Object.defineProperty(meta.prototype, prop.name, {
126
132
  set(val) {
127
133
  Object.defineProperty(this, prop.name, {
@@ -192,7 +198,7 @@ export class EntityHelper {
192
198
  wrapped.__data[prop.name] = Reference.wrapReference(val, prop);
193
199
  // when propagation from inside hydration, we set the FK to the entity data immediately
194
200
  if (val && hydrator.isRunning() && wrapped.__originalEntityData && prop.owner) {
195
- wrapped.__originalEntityData[prop.name] = Utils.getPrimaryKeyValues(wrapped.__data[prop.name], prop.targetMeta, true);
201
+ wrapped.__originalEntityData[prop.name] = EntityHelper.getForeignKeyValue(entity, prop, prop.targetMeta);
196
202
  }
197
203
  EntityHelper.propagate(meta, entity, this, prop, Reference.unwrapReference(val), old);
198
204
  },
@@ -200,6 +206,21 @@ export class EntityHelper {
200
206
  configurable: true,
201
207
  });
202
208
  }
209
+ /**
210
+ * Returns the database value of the FK pointing to the given entity.
211
+ * @internal
212
+ */
213
+ static getForeignKeyValue(target, prop, targetMeta) {
214
+ if (!prop.targetKey) {
215
+ return Utils.getPrimaryKeyValues(target, targetMeta, true, true);
216
+ }
217
+ // with `targetKey`, the FK holds that value instead of the PK
218
+ const value = target[prop.targetKey];
219
+ const customType = targetMeta.properties[prop.targetKey]?.customType;
220
+ return customType
221
+ ? customType.convertToDatabaseValue(value, helper(target).__platform, { mode: 'serialization' })
222
+ : value;
223
+ }
203
224
  static propagate(meta, entity, owner, prop, value, old) {
204
225
  // For polymorphic relations, get bidirectional relations from the actual entity's metadata
205
226
  let bidirectionalRelations;
@@ -296,6 +317,10 @@ export class EntityHelper {
296
317
  }
297
318
  const wrapped = helper(entity);
298
319
  const meta = wrapped.__meta;
320
+ // nothing to define on the instance
321
+ if (meta.trackingProps.length === 0 && !meta.serializedPrimaryKey) {
322
+ return;
323
+ }
299
324
  const platform = wrapped.__platform;
300
325
  const serializedPrimaryKey = meta.props.find(p => p.serializedPrimaryKey);
301
326
  const values = [];