@mikro-orm/core 7.2.9-dev.14 → 7.2.9-dev.16

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.
@@ -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,
@@ -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
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mikro-orm/core",
3
- "version": "7.2.9-dev.14",
3
+ "version": "7.2.9-dev.16",
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",
package/typings.d.ts CHANGED
@@ -1071,6 +1071,8 @@ export interface EntityProperty<Owner = any, Target = any> {
1071
1071
  referencedColumnNames: string[];
1072
1072
  referencedTableName: string;
1073
1073
  referencedPKs: EntityKey<Owner>[];
1074
+ /** @internal target properties behind a composite FK that references more than the target PK and owns all its columns */
1075
+ referencedProps?: EntityProperty[];
1074
1076
  targetKey?: string;
1075
1077
  serializer?: (value: any, options?: SerializeOptions<any>) => any;
1076
1078
  serializedName?: string;
@@ -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();
@@ -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.14';
156
+ static #ORM_VERSION = '7.2.9-dev.16';
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}`;