@mikro-orm/core 7.2.9-dev.9 → 7.2.9

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.
@@ -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
@@ -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,10 +1772,16 @@ 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]);
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
+ }
1769
1785
  em.#unitOfWork.merge(entity, visited);
1770
1786
  return entity;
1771
1787
  }
@@ -2001,19 +2017,20 @@ export class EntityManager {
2001
2017
  : options.cloneEventManager
2002
2018
  ? em.eventManager.clone()
2003
2019
  : 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);
2020
+ // forking from global EM is fine; toggled directly as `config.set()` also re-syncs env/logger state (hot path)
2021
+ const configOptions = em.config.getAll();
2022
+ const allowGlobalContext = configOptions.allowGlobalContext;
2023
+ configOptions.allowGlobalContext = true;
2007
2024
  const fork = new em.constructor(em.config, em.driver, em.metadata, options.useContext, eventManager);
2008
2025
  fork.setFlushMode(options.flushMode ?? em.#flushMode);
2009
2026
  fork.#disableTransactions =
2010
2027
  options.disableTransactions ?? this.#disableTransactions ?? this.config.get('disableTransactions');
2011
- em.config.set('allowGlobalContext', allowGlobalContext);
2028
+ configOptions.allowGlobalContext = allowGlobalContext;
2012
2029
  if (options.keepTransactionContext) {
2013
2030
  fork.#transactionContext = em.#transactionContext;
2014
2031
  }
2015
2032
  fork.#filters = { ...em.#filters };
2016
- fork.#filterParams = Utils.copy(em.#filterParams);
2033
+ fork.#filterParams = Utils.hasObjectKeys(em.#filterParams) ? Utils.copy(em.#filterParams) : {};
2017
2034
  if (options.session) {
2018
2035
  // the fork's session replaces the parent context, but the copied `rls` filter params must stay consistent with
2019
2036
  // it — re-stage their variables underneath the explicit `session.variables`, which win on any conflict
@@ -2026,7 +2043,8 @@ export class EntityManager {
2026
2043
  else if (em.#sessionContext) {
2027
2044
  fork.#sessionContext = Utils.copy(em.#sessionContext);
2028
2045
  }
2029
- fork.loggerContext = Utils.merge({}, em.loggerContext, options.loggerContext);
2046
+ fork.loggerContext =
2047
+ em.loggerContext || options.loggerContext ? Utils.merge({}, em.loggerContext, options.loggerContext) : {};
2030
2048
  fork.#schema = options.schema ?? em.#schema;
2031
2049
  fork.signal = options.signal ?? em.signal;
2032
2050
  fork.inflightQueryAbortStrategy = options.inflightQueryAbortStrategy ?? em.inflightQueryAbortStrategy;
@@ -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 = [];
@@ -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);
@@ -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;
@@ -426,8 +426,18 @@ export class MetadataDiscovery {
426
426
  if (!prop.ownColumns || prop.ownColumns.length === 0) {
427
427
  prop.ownColumns = prop.joinColumns;
428
428
  }
429
+ if (prop.joinColumns.length !== prop.referencedColumnNames.length) {
430
+ throw MetadataError.fromWrongForeignKey(meta, prop, 'referencedColumnNames');
431
+ }
432
+ // the FK can reference other columns than the target PK, e.g. the PK plus a column of a composite unique key
433
+ const referencedProps = prop.referencedColumnNames.map(col => prop.targetMeta.props.find(p => p.fieldNames?.includes(col)));
429
434
  if (prop.joinColumns.length !== prop.columnTypes.length) {
430
- prop.columnTypes = prop.joinColumns.flatMap(field => {
435
+ prop.columnTypes = prop.joinColumns.flatMap((field, idx) => {
436
+ const referenced = referencedProps[idx];
437
+ // the PK columns are already typed by `initColumnType()` (e.g. without autoincrement)
438
+ if (referenced && !referenced.primary) {
439
+ return [referenced.columnTypes[referenced.fieldNames.indexOf(prop.referencedColumnNames[idx])]];
440
+ }
431
441
  const matched = meta.props.find(p => p.fieldNames?.includes(field));
432
442
  /* v8 ignore next */
433
443
  if (!matched) {
@@ -436,8 +446,13 @@ export class MetadataDiscovery {
436
446
  return matched.columnTypes;
437
447
  });
438
448
  }
439
- if (prop.joinColumns.length !== prop.referencedColumnNames.length) {
440
- throw MetadataError.fromWrongForeignKey(meta, prop, 'referencedColumnNames');
449
+ // when the relation owns all the FK columns, the extra ones are filled from the target entity on write
450
+ if (!prop.mapToPk &&
451
+ !prop.embedded &&
452
+ prop.ownColumns.length === prop.joinColumns.length &&
453
+ referencedProps.every((p) => p != null) &&
454
+ referencedProps.some(p => !p.primary)) {
455
+ prop.referencedProps = referencedProps;
441
456
  }
442
457
  }
443
458
  }
@@ -1125,7 +1140,9 @@ export class MetadataDiscovery {
1125
1140
  if (meta.inheritanceType !== 'tpt' || !meta.tptParent) {
1126
1141
  meta.indexes = Utils.unique([...base.indexes, ...meta.indexes], Utils.equals);
1127
1142
  meta.uniques = Utils.unique([...base.uniques, ...meta.uniques], Utils.equals);
1128
- meta.checks = Utils.unique([...base.checks, ...meta.checks], Utils.equals);
1143
+ // the STI root also collects checks bound to properties of other subtypes
1144
+ const baseChecks = base.checks.filter(check => !check.property || meta.properties[check.property]);
1145
+ meta.checks = Utils.unique([...baseChecks, ...meta.checks], Utils.equals);
1129
1146
  meta.triggers = Utils.unique([...base.triggers, ...meta.triggers], Utils.equals);
1130
1147
  }
1131
1148
  // Policies pass down only from inlined abstract bases; STI children share the root table
@@ -1484,11 +1501,15 @@ export class MetadataDiscovery {
1484
1501
  // that as matching so the rename branch below doesn't run (which would
1485
1502
  // crash — `targetMeta` is only populated later, in `initRelation`).
1486
1503
  const narrowedRelationOverride = rootProp != null && rootProp.type !== prop.type && this.sameRelationTargetRoot(rootProp, prop);
1504
+ // The root can hold another instance of the same custom type (e.g. the copy made for a polymorphic embeddable), so those are compared by class.
1505
+ const sameTypeClass = Type.isMappedType(rootProp?.type) &&
1506
+ Type.isMappedType(prop.type) &&
1507
+ rootProp.type.constructor === prop.type.constructor;
1487
1508
  // stiMerged is set during inlineProperties when a property was merged
1488
1509
  // from multiple polymorphic variants with different types. The flag is
1489
1510
  // cleared implicitly when the first child claims the root property via
1490
1511
  // addProperty below, so subsequent children correctly trigger renaming.
1491
- const typesMatch = rootProp?.type === prop.type || rootProp?.stiMerged === true || narrowedRelationOverride;
1512
+ const typesMatch = rootProp?.type === prop.type || sameTypeClass || rootProp?.stiMerged === true || narrowedRelationOverride;
1492
1513
  // Inverse-side relations (1:m, inverse m:n) have no FK column on this
1493
1514
  // entity, so the rename branch — which exists to disambiguate physical
1494
1515
  // columns shared across STI children — doesn't apply. Skipping it also
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mikro-orm/core",
3
- "version": "7.2.9-dev.9",
3
+ "version": "7.2.9",
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",
@@ -81,57 +81,66 @@ export class EntitySerializer {
81
81
  root = new SerializationContext();
82
82
  contextCreated = true;
83
83
  }
84
- SerializationContext.propagate(root, entity, (meta, prop) => meta.properties[prop]?.kind !== ReferenceKind.SCALAR);
85
84
  const ret = {};
86
- const props = new Set();
87
- if (meta.serializedPrimaryKey && !meta.compositePK) {
88
- props.add(meta.serializedPrimaryKey);
89
- }
90
- else {
91
- meta.primaryKeys.forEach(pk => props.add(pk));
92
- }
93
- if (wrapped.isInitialized() || !wrapped.hasPrimaryKey()) {
94
- const entityKeys = new Set(Object.keys(entity));
95
- for (const prop of meta.props) {
96
- if (entityKeys.has(prop.name) || (prop.getter && prop.accessor === prop.name)) {
97
- props.add(prop.name);
98
- }
85
+ try {
86
+ SerializationContext.propagate(root, entity, (meta, prop) => meta.properties[prop]?.kind !== ReferenceKind.SCALAR);
87
+ const props = new Set();
88
+ if (meta.serializedPrimaryKey && !meta.compositePK) {
89
+ props.add(meta.serializedPrimaryKey);
99
90
  }
100
- for (const key of entityKeys) {
101
- if (!meta.properties[key]) {
102
- props.add(key);
103
- }
104
- }
105
- }
106
- const visited = root.visited.has(entity);
107
- if (!visited) {
108
- root.visited.add(entity);
109
- }
110
- for (const prop of props) {
111
- if (!isVisible(meta, prop, options)) {
112
- continue;
113
- }
114
- const cycle = root.visit(meta.class, prop);
115
- if (cycle && visited) {
116
- continue;
117
- }
118
- const val = this.processProperty(prop, entity, options);
119
- if (!cycle) {
120
- root.leave(meta.class, prop);
91
+ else {
92
+ meta.primaryKeys.forEach(pk => props.add(pk));
121
93
  }
122
- if (options.skipNull && Utils.isPlainObject(val)) {
123
- Utils.dropUndefinedProperties(val, null);
94
+ if (wrapped.isInitialized() || !wrapped.hasPrimaryKey()) {
95
+ const entityKeys = new Set(Object.keys(entity));
96
+ for (const prop of meta.props) {
97
+ if (entityKeys.has(prop.name) || (prop.getter && prop.accessor === prop.name)) {
98
+ props.add(prop.name);
99
+ }
100
+ }
101
+ for (const key of entityKeys) {
102
+ if (!meta.properties[key]) {
103
+ props.add(key);
104
+ }
105
+ }
124
106
  }
125
- if (isRaw(val)) {
126
- throw new Error(`Trying to serialize raw SQL fragment: '${val.sql}'`);
107
+ const visited = root.visited.has(entity);
108
+ if (!visited) {
109
+ root.visited.add(entity);
127
110
  }
128
- const visible = typeof val !== 'undefined' && !(val === null && options.skipNull);
129
- if (visible) {
130
- ret[this.propertyName(meta, prop)] = val;
111
+ for (const prop of props) {
112
+ if (!isVisible(meta, prop, options)) {
113
+ continue;
114
+ }
115
+ const cycle = root.visit(meta.class, prop);
116
+ if (cycle && visited) {
117
+ continue;
118
+ }
119
+ let val;
120
+ try {
121
+ val = this.processProperty(prop, entity, options);
122
+ }
123
+ finally {
124
+ if (!cycle) {
125
+ root.leave(meta.class, prop);
126
+ }
127
+ }
128
+ if (options.skipNull && Utils.isPlainObject(val)) {
129
+ Utils.dropUndefinedProperties(val, null);
130
+ }
131
+ if (isRaw(val)) {
132
+ throw new Error(`Trying to serialize raw SQL fragment: '${val.sql}'`);
133
+ }
134
+ const visible = typeof val !== 'undefined' && !(val === null && options.skipNull);
135
+ if (visible) {
136
+ ret[this.propertyName(meta, prop)] = val;
137
+ }
131
138
  }
132
139
  }
133
- if (contextCreated) {
134
- root.close();
140
+ finally {
141
+ if (contextCreated) {
142
+ root.close();
143
+ }
135
144
  }
136
145
  if (!wrapped.isInitialized()) {
137
146
  return ret;
@@ -26,91 +26,100 @@ export class EntityTransformer {
26
26
  root = new SerializationContext(wrapped.__serializationContext.populate, wrapped.__serializationContext.fields, wrapped.__serializationContext.exclude);
27
27
  contextCreated = true;
28
28
  }
29
- SerializationContext.propagate(root, entity, isVisible);
30
- const meta = wrapped.__meta;
31
- const ret = {};
32
- const props = new Set();
33
- if (meta.serializedPrimaryKey && !meta.compositePK) {
34
- props.add(meta.serializedPrimaryKey);
35
- }
36
- else {
37
- meta.primaryKeys.forEach(pk => props.add(pk));
38
- }
39
- if (wrapped.isInitialized() || !wrapped.hasPrimaryKey()) {
40
- const entityKeys = new Set(Object.keys(entity));
41
- for (const prop of meta.props) {
42
- if (entityKeys.has(prop.name) || (prop.getter && prop.accessor === prop.name)) {
43
- props.add(prop.name);
44
- }
29
+ try {
30
+ SerializationContext.propagate(root, entity, isVisible);
31
+ const meta = wrapped.__meta;
32
+ 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));
45
39
  }
46
- for (const key of entityKeys) {
47
- if (!meta.properties[key]) {
48
- props.add(key);
40
+ if (wrapped.isInitialized() || !wrapped.hasPrimaryKey()) {
41
+ const entityKeys = new Set(Object.keys(entity));
42
+ 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);
50
+ }
49
51
  }
50
52
  }
51
- }
52
- const visited = root.visited.has(entity);
53
- const includePrimaryKeys = wrapped.__config.get('serialization').includePrimaryKeys;
54
- if (!visited) {
55
- root.visited.add(entity);
56
- }
57
- for (const prop of props) {
58
- const visible = raw ? meta.properties[prop] : isVisible(meta, prop, ignoreFields);
59
- if (!visible) {
60
- continue;
53
+ const visited = root.visited.has(entity);
54
+ const includePrimaryKeys = wrapped.__config.get('serialization').includePrimaryKeys;
55
+ if (!visited) {
56
+ root.visited.add(entity);
61
57
  }
62
- const populated = root.isMarkedAsPopulated(meta.class, prop);
63
- if (!raw) {
64
- const partiallyLoaded = root.isPartiallyLoaded(meta.class, prop);
65
- const isPrimary = includePrimaryKeys && meta.properties[prop].primary;
66
- if (!partiallyLoaded && !populated && !isPrimary) {
58
+ for (const prop of props) {
59
+ const visible = raw ? meta.properties[prop] : isVisible(meta, prop, ignoreFields);
60
+ if (!visible) {
67
61
  continue;
68
62
  }
69
- if (root.isExcluded(meta.class, prop) && !populated) {
63
+ const populated = root.isMarkedAsPopulated(meta.class, prop);
64
+ if (!raw) {
65
+ const partiallyLoaded = root.isPartiallyLoaded(meta.class, prop);
66
+ const isPrimary = includePrimaryKeys && meta.properties[prop].primary;
67
+ if (!partiallyLoaded && !populated && !isPrimary) {
68
+ continue;
69
+ }
70
+ if (root.isExcluded(meta.class, prop) && !populated) {
71
+ continue;
72
+ }
73
+ }
74
+ const cycle = root.visit(meta.class, prop);
75
+ if (cycle && visited) {
70
76
  continue;
71
77
  }
78
+ let val;
79
+ try {
80
+ val = EntityTransformer.processProperty(prop, entity, raw, populated);
81
+ }
82
+ finally {
83
+ if (!cycle) {
84
+ root.leave(meta.class, prop);
85
+ }
86
+ }
87
+ if (isRaw(val)) {
88
+ throw new Error(`Trying to serialize raw SQL fragment: '${val.sql}'`);
89
+ }
90
+ if (typeof val === 'undefined') {
91
+ continue;
92
+ }
93
+ ret[this.propertyName(meta, prop, raw)] = val;
72
94
  }
73
- const cycle = root.visit(meta.class, prop);
74
- if (cycle && visited) {
75
- continue;
76
- }
77
- const val = EntityTransformer.processProperty(prop, entity, raw, populated);
78
- if (!cycle) {
79
- root.leave(meta.class, prop);
80
- }
81
- if (isRaw(val)) {
82
- throw new Error(`Trying to serialize raw SQL fragment: '${val.sql}'`);
83
- }
84
- if (typeof val === 'undefined') {
85
- continue;
95
+ if (!wrapped.isInitialized() && wrapped.hasPrimaryKey()) {
96
+ return ret;
86
97
  }
87
- ret[this.propertyName(meta, prop, raw)] = val;
88
- }
89
- if (!wrapped.isInitialized() && wrapped.hasPrimaryKey()) {
90
- return ret;
91
- }
92
- for (const prop of meta.getterProps) {
93
- // decorated get methods
94
- if (prop.getterName != null) {
95
- const visible = !prop.hidden && entity[prop.getterName] instanceof Function;
96
- const populated = root.isMarkedAsPopulated(meta.class, prop.name);
97
- if (visible) {
98
- ret[this.propertyName(meta, prop.name, raw)] = this.processProperty(prop.getterName, entity, raw, populated);
98
+ for (const prop of meta.getterProps) {
99
+ // decorated get methods
100
+ if (prop.getterName != null) {
101
+ const visible = !prop.hidden && entity[prop.getterName] instanceof Function;
102
+ const populated = root.isMarkedAsPopulated(meta.class, prop.name);
103
+ if (visible) {
104
+ ret[this.propertyName(meta, prop.name, raw)] = this.processProperty(prop.getterName, entity, raw, populated);
105
+ }
99
106
  }
100
- }
101
- else {
102
- // decorated getters
103
- const visible = !prop.hidden && typeof entity[prop.name] !== 'undefined';
104
- const populated = root.isMarkedAsPopulated(meta.class, prop.name);
105
- if (visible) {
106
- ret[this.propertyName(meta, prop.name, raw)] = this.processProperty(prop.name, entity, raw, populated);
107
+ else {
108
+ // decorated getters
109
+ const visible = !prop.hidden && typeof entity[prop.name] !== 'undefined';
110
+ const populated = root.isMarkedAsPopulated(meta.class, prop.name);
111
+ if (visible) {
112
+ ret[this.propertyName(meta, prop.name, raw)] = this.processProperty(prop.name, entity, raw, populated);
113
+ }
107
114
  }
108
115
  }
116
+ return ret;
109
117
  }
110
- if (contextCreated) {
111
- root.close();
118
+ finally {
119
+ if (contextCreated) {
120
+ root.close();
121
+ }
112
122
  }
113
- return ret;
114
123
  }
115
124
  static propertyName(meta, prop, raw) {
116
125
  if (raw) {
package/typings.d.ts CHANGED
@@ -382,8 +382,9 @@ export type FilterQuery<T> = ObjectQuery<T> | NonNullable<ExpandScalar<Primary<T
382
382
  /**
383
383
  * `FilterQuery` restricted to only properties covered by the specified index(es).
384
384
  * Used when `using` option is set in `FindOptions` to enforce type-safe index usage.
385
+ * Falls back to `FilterQuery` when `Using` is not a specific index name (e.g. inferred from the options type).
385
386
  */
386
- export type IndexFilterQuery<T, Using extends string> = [Using] extends [never] ? FilterQuery<T> : (OperatorMap<T> & {
387
+ export type IndexFilterQuery<T, Using extends string> = [Using] extends [never] ? FilterQuery<T> : string extends Using ? FilterQuery<T> : (OperatorMap<T> & {
387
388
  -readonly [K in Extract<EntityKey<T>, IndexColumns<T, Using>>]?: ExpandQuery<ExpandProperty<FilterObjectProp<T, K>>> | ExpandQueryMerged<ExpandProperty<FilterObjectProp<T, K>>> | FilterValue<ExpandProperty<FilterObjectProp<T, K>>> | ArrayFilter<FilterObjectProp<T, K>> | null;
388
389
  }) | NonNullable<ExpandScalar<Primary<T>>> | IndexFilterQuery<T, Using>[];
389
390
  /** Replaces `where` and `using` on an options type with index-aware variants when `Using` is specified. */
@@ -1071,6 +1072,8 @@ export interface EntityProperty<Owner = any, Target = any> {
1071
1072
  referencedColumnNames: string[];
1072
1073
  referencedTableName: string;
1073
1074
  referencedPKs: EntityKey<Owner>[];
1075
+ /** @internal target properties behind a composite FK that references more than the target PK and owns all its columns */
1076
+ referencedProps?: EntityProperty[];
1074
1077
  targetKey?: string;
1075
1078
  serializer?: (value: any, options?: SerializeOptions<any>) => any;
1076
1079
  serializedName?: string;
package/typings.js CHANGED
@@ -291,7 +291,7 @@ export class EntityMetadata {
291
291
  if (val && hydrator.isRunning() && wrapped.__originalEntityData && prop.owner) {
292
292
  const targetMeta = prop.targetMeta ?? helper(entity)?.__meta;
293
293
  if (targetMeta) {
294
- wrapped.__originalEntityData[prop.name] = Utils.getPrimaryKeyValues(val, targetMeta, true);
294
+ wrapped.__originalEntityData[prop.name] = EntityHelper.getForeignKeyValue(entity, prop, targetMeta);
295
295
  }
296
296
  }
297
297
  EntityHelper.propagate(meta, entity, this, prop, Reference.unwrapReference(val), old);
@@ -4,6 +4,7 @@ import { ChangeSet, ChangeSetType } from './ChangeSet.js';
4
4
  import { helper } from '../entity/wrap.js';
5
5
  import { validateEntity } from '../entity/validators.js';
6
6
  import { Reference } from '../entity/Reference.js';
7
+ import { EntityHelper } from '../entity/EntityHelper.js';
7
8
  import { PolymorphicRef } from '../entity/PolymorphicRef.js';
8
9
  import { ReferenceKind } from '../enums.js';
9
10
  import { isRaw } from '../utils/RawQueryFragment.js';
@@ -172,14 +173,10 @@ export class ChangeSetComputer {
172
173
  if (!prop.targetKey && !target.__helper.__initialized) {
173
174
  throw ValidationError.referenceWithoutPK(target);
174
175
  }
175
- let value = prop.targetKey ? target[prop.targetKey] : target.__helper.__identifier;
176
176
  // use the actual target's meta, a polymorphic relation has several
177
- if (prop.targetKey) {
178
- const targetProp = target.__meta.properties[prop.targetKey];
179
- if (targetProp?.customType) {
180
- value = targetProp.customType.convertToDatabaseValue(value, this.#platform, { mode: 'serialization' });
181
- }
182
- }
177
+ let value = prop.targetKey
178
+ ? EntityHelper.getForeignKeyValue(target, prop, target.__meta)
179
+ : target.__helper.__identifier;
183
180
  if (prop.polymorphic) {
184
181
  const discriminator = QueryHelper.findDiscriminatorValue(prop.discriminatorMap, target.constructor);
185
182
  value = new PolymorphicRef(discriminator, value);
@@ -35,6 +35,8 @@ export declare class ChangeSetPersister {
35
35
  */
36
36
  private markAsPopulated;
37
37
  private updateEntity;
38
+ /** The payload (and so the entity snapshot) keeps the target PK, the driver gets the whole composite FK value. */
39
+ private getDriverPayload;
38
40
  private checkOptimisticLocks;
39
41
  private checkOptimisticLock;
40
42
  /**
@@ -1,5 +1,6 @@
1
1
  import { EntityIdentifier } from '../entity/EntityIdentifier.js';
2
2
  import { PolymorphicRef } from '../entity/PolymorphicRef.js';
3
+ import { QueryHelper } from '../utils/QueryHelper.js';
3
4
  import { helper } from '../entity/wrap.js';
4
5
  import { ChangeSetType } from './ChangeSet.js';
5
6
  import { isRaw } from '../utils/RawQueryFragment.js';
@@ -127,7 +128,7 @@ export class ChangeSetPersister {
127
128
  });
128
129
  this.resolveTPTIdentifiers(changeSet);
129
130
  // Use changeSet's own meta for STI entities to get correct field mappings
130
- const res = await this.#driver.nativeInsertMany(changeSet.meta.class, [changeSet.payload], options);
131
+ const res = await this.#driver.nativeInsertMany(changeSet.meta.class, [this.getDriverPayload(changeSet)], options);
131
132
  if (!wrapped.hasPrimaryKey()) {
132
133
  this.mapPrimaryKey(meta, res.insertId ?? res.row?.[meta.primaryKeys[0]], changeSet);
133
134
  }
@@ -168,7 +169,7 @@ export class ChangeSetPersister {
168
169
  for (const changeSet of changeSets) {
169
170
  this.resolveTPTIdentifiers(changeSet);
170
171
  }
171
- const res = await this.#driver.nativeInsertMany(meta.class, changeSets.map(cs => cs.payload), options);
172
+ const res = await this.#driver.nativeInsertMany(meta.class, changeSets.map(cs => this.getDriverPayload(cs)), options);
172
173
  for (let i = 0; i < changeSets.length; i++) {
173
174
  const changeSet = changeSets[i];
174
175
  const wrapped = helper(changeSet.entity);
@@ -239,7 +240,7 @@ export class ChangeSetPersister {
239
240
  where[meta.versionProperty] = this.#platform.convertVersionValue(changeSet.entity[meta.versionProperty], meta.properties[meta.versionProperty]);
240
241
  }
241
242
  cond.push(where);
242
- payload.push(changeSet.payload);
243
+ payload.push(this.getDriverPayload(changeSet));
243
244
  }
244
245
  const res = await this.#driver.nativeUpdateMany(meta.class, cond, payload, options);
245
246
  const map = new Map();
@@ -324,13 +325,17 @@ export class ChangeSetPersister {
324
325
  });
325
326
  if (meta.getOwnConcurrencyCheckKeys().length === 0 &&
326
327
  (!meta.ownsVersionProperty() || changeSet.entity[meta.versionProperty] == null)) {
327
- return this.#driver.nativeUpdate(changeSet.meta.class, cond, changeSet.payload, options);
328
+ return this.#driver.nativeUpdate(changeSet.meta.class, cond, this.getDriverPayload(changeSet), options);
328
329
  }
329
330
  if (meta.ownsVersionProperty()) {
330
331
  cond[meta.versionProperty] = this.#platform.convertVersionValue(changeSet.entity[meta.versionProperty], meta.properties[meta.versionProperty]);
331
332
  }
332
333
  this.checkConcurrencyKeys(meta, changeSet, cond);
333
- return this.#driver.nativeUpdate(changeSet.meta.class, cond, changeSet.payload, options);
334
+ return this.#driver.nativeUpdate(changeSet.meta.class, cond, this.getDriverPayload(changeSet), options);
335
+ }
336
+ /** The payload (and so the entity snapshot) keeps the target PK, the driver gets the whole composite FK value. */
337
+ getDriverPayload(changeSet) {
338
+ return QueryHelper.withReferencedValues(changeSet.meta, changeSet.payload, changeSet.entity, this.#platform);
334
339
  }
335
340
  async checkOptimisticLocks(meta, changeSets, options) {
336
341
  const concurrencyCheckKeys = meta.getOwnConcurrencyCheckKeys();
@@ -66,6 +66,7 @@ export class UnitOfWork {
66
66
  return;
67
67
  }
68
68
  this.#identityMap.store(entity);
69
+ wrapped.__managed = true;
69
70
  // if visited is available, we are cascading, and need to be careful when resetting the entity data
70
71
  // as there can be some entity with already changed state that is not yet flushed
71
72
  if (wrapped.__initialized && (!visited || !wrapped.__originalEntityData)) {
@@ -111,6 +112,10 @@ export class UnitOfWork {
111
112
  });
112
113
  data[key] = prop.customType.convertToDatabaseValue(converted, this.#platform, { key, mode: 'hydration' });
113
114
  }
115
+ // the hydrator assigns this very instance to the entity, an in-place mutation would otherwise go unnoticed
116
+ if (data[key] instanceof Date) {
117
+ data[key] = new Date(data[key]);
118
+ }
114
119
  if (forceUndefined) {
115
120
  if (data[key] === null) {
116
121
  data[key] = undefined;
@@ -557,9 +562,13 @@ export class UnitOfWork {
557
562
  // the referrer's primary key contains the removed entity, so its identity cannot survive the removal
558
563
  this.unsetIdentity(referrer);
559
564
  }
560
- else {
565
+ else if ((prop.inversedBy || prop.mappedBy) && !prop.mapToPk) {
566
+ // relations with an inverse side are backed by `__data` to allow propagation
561
567
  delete helper(referrer).__data[prop.name];
562
568
  }
569
+ else {
570
+ delete referrer[prop.name];
571
+ }
563
572
  }
564
573
  }
565
574
  }
@@ -6,6 +6,7 @@ import { JsonType } from '../types/JsonType.js';
6
6
  import { Raw } from './RawQueryFragment.js';
7
7
  import { EntityIdentifier } from '../entity/EntityIdentifier.js';
8
8
  import { PolymorphicRef } from '../entity/PolymorphicRef.js';
9
+ import { EntityHelper } from '../entity/EntityHelper.js';
9
10
  /** @internal Generates and caches JIT-compiled functions for comparing, snapshotting, and mapping entity data. */
10
11
  export class EntityComparator {
11
12
  #comparators = new Map();
@@ -663,15 +664,8 @@ export class EntityComparator {
663
664
  ret += ` }\n`;
664
665
  if (prop.targetKey) {
665
666
  // the FK holds the `targetKey` value in the format of the actual target's column
666
- const targetKey = prop.targetKey;
667
667
  const targetKeyValueKey = `targetKeyValue_${this.safeKey(prop.name)}`;
668
- context.set(targetKeyValueKey, (val) => {
669
- const customType = val.__meta.properties[targetKey]?.customType;
670
- const value = val[targetKey];
671
- return customType
672
- ? customType.convertToDatabaseValue(value, this.#platform, { mode: 'serialization' })
673
- : value;
674
- });
668
+ context.set(targetKeyValueKey, (val) => EntityHelper.getForeignKeyValue(val, prop, val.__meta));
675
669
  ret += ` const pk = ${targetKeyValueKey}(val${level});\n`;
676
670
  }
677
671
  else {
@@ -28,6 +28,12 @@ export declare class QueryHelper {
28
28
  */
29
29
  static findDiscriminatorValue<T>(discriminatorMap: Dictionary<T>, targetClass: T): string | undefined;
30
30
  static processParams(params: unknown): any;
31
+ /**
32
+ * @internal The data as sent to the driver: a composite FK referencing other target columns than its PK
33
+ * (`prop.referencedProps`) gets their values from the target, which is the relation value in `source` (the entity
34
+ * being written, or the data it was created from), or is looked up via `getTarget` when `data` holds a bare PK.
35
+ */
36
+ static withReferencedValues<T extends object, D extends Dictionary>(meta: EntityMetadata<T>, data: D, source: Dictionary | undefined, platform: Platform, getTarget?: (prop: EntityProperty<T>, pk: unknown) => object | undefined): D;
31
37
  static processObjectParams<T extends Dictionary>(params?: T): T;
32
38
  /**
33
39
  * converts `{ account: { $or: [ [Object], [Object] ] } }`
@@ -60,6 +60,48 @@ export class QueryHelper {
60
60
  }
61
61
  return params;
62
62
  }
63
+ /**
64
+ * @internal The data as sent to the driver: a composite FK referencing other target columns than its PK
65
+ * (`prop.referencedProps`) gets their values from the target, which is the relation value in `source` (the entity
66
+ * being written, or the data it was created from), or is looked up via `getTarget` when `data` holds a bare PK.
67
+ */
68
+ static withReferencedValues(meta, data, source, platform, getTarget) {
69
+ for (const prop of meta.relations) {
70
+ const value = data[prop.name];
71
+ // a ready tuple is the FK value already
72
+ if (!prop.referencedProps ||
73
+ value == null ||
74
+ isRaw(value) ||
75
+ (Array.isArray(value) && value.length === prop.fieldNames.length)) {
76
+ continue;
77
+ }
78
+ let target = Reference.unwrapReference(value);
79
+ if (!Utils.isEntity(target) && !Utils.isPlainObject(target)) {
80
+ const candidate = Reference.unwrapReference(source?.[prop.name]);
81
+ // the data created from the source may have changed since (e.g. in a hook), then the PK decides
82
+ const current = Utils.isEntity(candidate) &&
83
+ (Utils.isEntity(source) || Utils.equals(QueryHelper.processParams(candidate), value));
84
+ target = current ? candidate : getTarget?.(prop, value);
85
+ }
86
+ const tuple = prop.referencedProps.map((referencedProp, idx) => {
87
+ let val = Reference.unwrapReference(target?.[referencedProp.name]);
88
+ val = Utils.isScalarReference(val) ? val.unwrap() : val;
89
+ val = Utils.isEntity(val) ? helper(val).getPrimaryKey(true) : val;
90
+ if (val === undefined) {
91
+ // without the target, name the first value its PK does not give
92
+ const missing = target ? referencedProp : prop.referencedProps.find(p => !p.primary);
93
+ throw new ValidationError(`Cannot set ${meta.className}.${prop.name} to a reference of ${prop.targetMeta.className} without the value of ${prop.targetMeta.className}.${missing.name}, load it first`);
94
+ }
95
+ if (referencedProp.customType && val != null) {
96
+ val = referencedProp.customType.convertToDatabaseValue(val, platform, { mode: 'serialization' });
97
+ }
98
+ // a relation holding a composite PK yields a nested array, one entry per column
99
+ return Utils.flatten([val], true)[referencedProp.fieldNames.indexOf(prop.referencedColumnNames[idx])];
100
+ });
101
+ data = { ...data, [prop.name]: tuple };
102
+ }
103
+ return data;
104
+ }
63
105
  static processObjectParams(params = {}) {
64
106
  const ret = (Array.isArray(params) ? [...params] : { ...params });
65
107
  Utils.getObjectQueryKeys(params).forEach(k => {
@@ -182,7 +182,9 @@ export class TransactionManager {
182
182
  tracked.forEach(([key]) => this.restore(originalEntityData, parentSnapshot, key));
183
183
  continue;
184
184
  }
185
- if (prop.kind === ReferenceKind.SCALAR) {
185
+ // only to-one relations with an inverse side are backed by `__data`, other values live on the entity itself
186
+ if (![ReferenceKind.ONE_TO_MANY, ReferenceKind.MANY_TO_MANY].includes(prop.kind) &&
187
+ (!(prop.inversedBy || prop.mappedBy) || prop.mapToPk)) {
186
188
  parentEntity[prop.name] = entity[prop.name];
187
189
  }
188
190
  }
package/utils/Utils.js CHANGED
@@ -153,7 +153,7 @@ export function parseJsonSafe(value) {
153
153
  /** Collection of general-purpose utility methods used throughout the ORM. */
154
154
  export class Utils {
155
155
  static PK_SEPARATOR = '~~~';
156
- static #ORM_VERSION = '7.2.9-dev.9';
156
+ static #ORM_VERSION = '7.2.9';
157
157
  /** Default session variable name backing an RLS filter argument (`current_setting('mikro.<filter>.<arg>')`). */
158
158
  static getRlsSettingName(filterName, argName) {
159
159
  return `mikro.${filterName}.${argName}`;
@@ -450,6 +450,10 @@ export class Utils {
450
450
  let pk;
451
451
  if (Utils.isEntity(entity, true)) {
452
452
  pk = helper(entity).getPrimaryKey(convertCustomTypes);
453
+ // the converted PK of a relation to a composite PK target is an object keyed by the target PKs
454
+ if (convertCustomTypes && meta.getPrimaryProps()[0].targetMeta && Utils.isPlainObject(pk)) {
455
+ return toArray(pk);
456
+ }
453
457
  }
454
458
  else {
455
459
  pk = meta.primaryKeys.reduce((o, pk) => {
@@ -915,11 +919,16 @@ export class Utils {
915
919
  }, {});
916
920
  }
917
921
  static getObjectQueryKeys(obj) {
918
- return Reflect.ownKeys(obj).filter(key => {
919
- if (!Object.prototype.propertyIsEnumerable.call(obj, key)) {
920
- return false;
922
+ const keys = Object.keys(obj);
923
+ const symbols = Object.getOwnPropertySymbols(obj);
924
+ if (symbols.length === 0) {
925
+ return keys;
926
+ }
927
+ for (const key of symbols) {
928
+ if (Raw.isKnownFragmentSymbol(key) && Object.prototype.propertyIsEnumerable.call(obj, key)) {
929
+ keys.push(key);
921
930
  }
922
- return typeof key === 'string' || Raw.isKnownFragmentSymbol(key);
923
- });
931
+ }
932
+ return keys;
924
933
  }
925
934
  }
package/utils/clone.js CHANGED
@@ -123,7 +123,8 @@ export function clone(parent, respectCustomCloneMethod = true) {
123
123
  if (attrs && typeof attrs.get === 'function' && attrs.set == null) {
124
124
  continue;
125
125
  }
126
- child[i] = _clone(parent[i]);
126
+ // `Reflect.get` avoids V8's for-in enum cache load, which can fall into an endless deopt/reoptimize loop here
127
+ child[i] = _clone(Reflect.get(parent, i));
127
128
  }
128
129
  const symbols = Object.getOwnPropertySymbols(parent);
129
130
  for (let i = 0; i < symbols.length; i++) {