@mikro-orm/core 7.2.9-dev.2 → 7.2.9-dev.21

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
  */
package/EntityManager.js CHANGED
@@ -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,
@@ -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
  */
@@ -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;
@@ -192,7 +192,7 @@ export class EntityHelper {
192
192
  wrapped.__data[prop.name] = Reference.wrapReference(val, prop);
193
193
  // when propagation from inside hydration, we set the FK to the entity data immediately
194
194
  if (val && hydrator.isRunning() && wrapped.__originalEntityData && prop.owner) {
195
- wrapped.__originalEntityData[prop.name] = Utils.getPrimaryKeyValues(wrapped.__data[prop.name], prop.targetMeta, true);
195
+ wrapped.__originalEntityData[prop.name] = EntityHelper.getForeignKeyValue(entity, prop, prop.targetMeta);
196
196
  }
197
197
  EntityHelper.propagate(meta, entity, this, prop, Reference.unwrapReference(val), old);
198
198
  },
@@ -200,6 +200,21 @@ export class EntityHelper {
200
200
  configurable: true,
201
201
  });
202
202
  }
203
+ /**
204
+ * Returns the database value of the FK pointing to the given entity.
205
+ * @internal
206
+ */
207
+ static getForeignKeyValue(target, prop, targetMeta) {
208
+ if (!prop.targetKey) {
209
+ return Utils.getPrimaryKeyValues(target, targetMeta, true, true);
210
+ }
211
+ // with `targetKey`, the FK holds that value instead of the PK
212
+ const value = target[prop.targetKey];
213
+ const customType = targetMeta.properties[prop.targetKey]?.customType;
214
+ return customType
215
+ ? customType.convertToDatabaseValue(value, helper(target).__platform, { mode: 'serialization' })
216
+ : value;
217
+ }
203
218
  static propagate(meta, entity, owner, prop, value, old) {
204
219
  // For polymorphic relations, get bidirectional relations from the actual entity's metadata
205
220
  let bidirectionalRelations;
@@ -501,6 +501,11 @@ export class EntityLoader {
501
501
  for (const entity of entities) {
502
502
  const ref = entity[prop.name];
503
503
  if (ref == null) {
504
+ // an inverse 1:1 with no matching row is resolved as empty, mark it so it is not queried again
505
+ if (isInverseOneToOne && !partial && childrenMap.has(getKey(entity))) {
506
+ entity[prop.name] = nullVal;
507
+ helper(entity).__loadedProperties.add(prop.name);
508
+ }
504
509
  continue;
505
510
  }
506
511
  const refKey = getKey(ref);
@@ -883,7 +888,11 @@ export class EntityLoader {
883
888
  if (value === null) {
884
889
  return false;
885
890
  }
886
- if (value === undefined || !Utils.isEntity(value, true)) {
891
+ // with `forceUndefined`, an empty relation that was already loaded is `undefined` instead of `null`
892
+ if (value === undefined) {
893
+ return !helper(e).__loadedProperties.has(prop.name);
894
+ }
895
+ if (!Utils.isEntity(value, true)) {
887
896
  return true;
888
897
  }
889
898
  const target = Reference.unwrapReference(value);
@@ -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
  }
@@ -1484,11 +1499,15 @@ export class MetadataDiscovery {
1484
1499
  // that as matching so the rename branch below doesn't run (which would
1485
1500
  // crash — `targetMeta` is only populated later, in `initRelation`).
1486
1501
  const narrowedRelationOverride = rootProp != null && rootProp.type !== prop.type && this.sameRelationTargetRoot(rootProp, prop);
1502
+ // 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.
1503
+ const sameTypeClass = Type.isMappedType(rootProp?.type) &&
1504
+ Type.isMappedType(prop.type) &&
1505
+ rootProp.type.constructor === prop.type.constructor;
1487
1506
  // stiMerged is set during inlineProperties when a property was merged
1488
1507
  // from multiple polymorphic variants with different types. The flag is
1489
1508
  // cleared implicitly when the first child claims the root property via
1490
1509
  // addProperty below, so subsequent children correctly trigger renaming.
1491
- const typesMatch = rootProp?.type === prop.type || rootProp?.stiMerged === true || narrowedRelationOverride;
1510
+ const typesMatch = rootProp?.type === prop.type || sameTypeClass || rootProp?.stiMerged === true || narrowedRelationOverride;
1492
1511
  // Inverse-side relations (1:m, inverse m:n) have no FK column on this
1493
1512
  // entity, so the rename branch — which exists to disambiguate physical
1494
1513
  // 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.2",
3
+ "version": "7.2.9-dev.21",
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);
@@ -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();
@@ -141,7 +141,9 @@ export class UnitOfWork {
141
141
  wrapped.__loadedProperties.add(key);
142
142
  }
143
143
  }
144
- wrapped.__originalEntityData = data;
144
+ // a partial refresh must keep the snapshot of properties it did not reload
145
+ wrapped.__originalEntityData =
146
+ options?.refresh && wrapped.__originalEntityData ? { ...wrapped.__originalEntityData, ...data } : data;
145
147
  }
146
148
  return entity;
147
149
  }
@@ -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 => {
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.2';
156
+ static #ORM_VERSION = '7.2.9-dev.21';
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) => {