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

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.
@@ -186,7 +186,7 @@ export class EntityLoader {
186
186
  if (prop.polymorphic && prop.polymorphTargets) {
187
187
  return this.populatePolymorphic(entities, prop, options, !!ref);
188
188
  }
189
- const { items, partial } = await this.findChildren(options.filtered ?? entities, prop, populate, {
189
+ const { items, partial, partitions } = await this.findChildren(options.filtered ?? entities, prop, populate, {
190
190
  ...options,
191
191
  where,
192
192
  orderBy: mergedOrderBy,
@@ -194,6 +194,10 @@ export class EntityLoader {
194
194
  const hasLimit = populate.limit != null;
195
195
  const isPartial = partial || hasLimit;
196
196
  const customOrder = mergedOrderBy.length > 0 || !!prop.orderBy || !!prop.targetMeta?.orderBy;
197
+ if (partitions) {
198
+ this.initializePartitions(filtered, items, field, partitions);
199
+ return items;
200
+ }
197
201
  this.initializeCollections(filtered, prop, field, items, customOrder, isPartial, hasLimit);
198
202
  return items;
199
203
  }
@@ -336,6 +340,18 @@ export class EntityLoader {
336
340
  }
337
341
  }
338
342
  }
343
+ initializePartitions(filtered, children, field, partitions) {
344
+ // a child belongs only to the owners whose slice returned it, not to every owner in its array
345
+ const key = (entity) => helper(entity).getSerializedPrimaryKey();
346
+ const owners = new Map(filtered.map(entity => [key(entity), []]));
347
+ const items = new Map(children.map(child => [key(child), child]));
348
+ for (const [owner, child] of partitions) {
349
+ owners.get('' + owner)?.push(items.get('' + child));
350
+ }
351
+ for (const entity of filtered) {
352
+ entity[field].hydrate(owners.get(key(entity)), true, true, true);
353
+ }
354
+ }
339
355
  async findChildren(entities, prop, populate, options, ref) {
340
356
  const children = Utils.unique(this.getChildReferences(entities, prop, options, ref, populate));
341
357
  const meta = prop.targetMeta;
@@ -434,11 +450,13 @@ export class EntityLoader {
434
450
  visited: options.visited,
435
451
  };
436
452
  if (populate.limit != null) {
437
- findOptions._partitionLimit = {
438
- partitionBy: fk,
439
- limit: populate.limit,
440
- offset: populate.offset,
441
- };
453
+ // the owners of an M:N without a pivot table are stored as an array, the driver slices per owner
454
+ const owners = prop.kind === ReferenceKind.MANY_TO_MANY && ownerProp ? ids : undefined;
455
+ findOptions._partitionLimit = { partitionBy: fk, limit: populate.limit, offset: populate.offset, owners };
456
+ // a cached result would not carry the per-owner partitions the driver writes back
457
+ if (owners) {
458
+ findOptions.cache = false;
459
+ }
442
460
  }
443
461
  const items = await this.#em.find(meta.class, where, findOptions);
444
462
  // For targetKey relations, wire up loaded entities to parent references
@@ -484,6 +502,11 @@ export class EntityLoader {
484
502
  for (const entity of entities) {
485
503
  const ref = entity[prop.name];
486
504
  if (ref == null) {
505
+ // an inverse 1:1 with no matching row is resolved as empty, mark it so it is not queried again
506
+ if (isInverseOneToOne && !partial && childrenMap.has(getKey(entity))) {
507
+ entity[prop.name] = nullVal;
508
+ helper(entity).__loadedProperties.add(prop.name);
509
+ }
487
510
  continue;
488
511
  }
489
512
  const refKey = getKey(ref);
@@ -502,7 +525,7 @@ export class EntityLoader {
502
525
  this.#em.getUnitOfWork().unmarkAsLoaded(item);
503
526
  }
504
527
  }
505
- return { items, partial };
528
+ return { items, partial, partitions: findOptions._partitionLimit?.partitions };
506
529
  }
507
530
  mergePrimaryCondition(ids, pk, options, meta, metadata, platform) {
508
531
  const cond1 = QueryHelper.processWhere({
@@ -866,7 +889,11 @@ export class EntityLoader {
866
889
  if (value === null) {
867
890
  return false;
868
891
  }
869
- if (value === undefined || !Utils.isEntity(value, true)) {
892
+ // with `forceUndefined`, an empty relation that was already loaded is `undefined` instead of `null`
893
+ if (value === undefined) {
894
+ return !helper(e).__loadedProperties.has(prop.name);
895
+ }
896
+ if (!Utils.isEntity(value, true)) {
870
897
  return true;
871
898
  }
872
899
  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
  }
@@ -1193,7 +1208,9 @@ export class MetadataDiscovery {
1193
1208
  if (meta.inheritanceType !== 'tpt' || !meta.tptParent) {
1194
1209
  meta.indexes = Utils.unique([...base.indexes, ...meta.indexes], Utils.equals);
1195
1210
  meta.uniques = Utils.unique([...base.uniques, ...meta.uniques], Utils.equals);
1196
- meta.checks = Utils.unique([...base.checks, ...meta.checks], Utils.equals);
1211
+ // the STI root also collects checks bound to properties of other subtypes
1212
+ const baseChecks = base.checks.filter(check => !check.property || meta.properties[check.property]);
1213
+ meta.checks = Utils.unique([...baseChecks, ...meta.checks], Utils.equals);
1197
1214
  meta.triggers = Utils.unique([...base.triggers, ...meta.triggers], Utils.equals);
1198
1215
  }
1199
1216
  // Policies pass down only from inlined abstract bases; STI children share the root table
@@ -1552,11 +1569,15 @@ export class MetadataDiscovery {
1552
1569
  // that as matching so the rename branch below doesn't run (which would
1553
1570
  // crash — `targetMeta` is only populated later, in `initRelation`).
1554
1571
  const narrowedRelationOverride = rootProp != null && rootProp.type !== prop.type && this.sameRelationTargetRoot(rootProp, prop);
1572
+ // 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.
1573
+ const sameTypeClass = Type.isMappedType(rootProp?.type) &&
1574
+ Type.isMappedType(prop.type) &&
1575
+ rootProp.type.constructor === prop.type.constructor;
1555
1576
  // stiMerged is set during inlineProperties when a property was merged
1556
1577
  // from multiple polymorphic variants with different types. The flag is
1557
1578
  // cleared implicitly when the first child claims the root property via
1558
1579
  // addProperty below, so subsequent children correctly trigger renaming.
1559
- const typesMatch = rootProp?.type === prop.type || rootProp?.stiMerged === true || narrowedRelationOverride;
1580
+ const typesMatch = rootProp?.type === prop.type || sameTypeClass || rootProp?.stiMerged === true || narrowedRelationOverride;
1560
1581
  // Inverse-side relations (1:m, inverse m:n) have no FK column on this
1561
1582
  // entity, so the rename branch — which exists to disambiguate physical
1562
1583
  // 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.3.0-dev.20",
3
+ "version": "7.3.0-dev.22",
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",
@@ -76,62 +76,71 @@ export class EntitySerializer {
76
76
  const meta = wrapped.__meta;
77
77
  let contextCreated = false;
78
78
  options = prepareOptions(options);
79
- if (!wrapped.__serializationContext.root) {
80
- const root = new SerializationContext();
81
- SerializationContext.propagate(root, entity, (meta, prop) => meta.properties[prop]?.kind !== ReferenceKind.SCALAR);
79
+ let root = wrapped.__serializationContext.root;
80
+ if (!root) {
81
+ root = new SerializationContext();
82
82
  contextCreated = true;
83
83
  }
84
- const root = wrapped.__serializationContext.root;
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
- }
99
- }
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;
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);
117
90
  }
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;
@@ -21,96 +21,105 @@ export class EntityTransformer {
21
21
  if (!wrapped) {
22
22
  return entity;
23
23
  }
24
- if (!wrapped.__serializationContext.root) {
25
- const root = new SerializationContext(wrapped.__serializationContext.populate, wrapped.__serializationContext.fields, wrapped.__serializationContext.exclude);
26
- SerializationContext.propagate(root, entity, isVisible);
24
+ let root = wrapped.__serializationContext.root;
25
+ if (!root) {
26
+ root = new SerializationContext(wrapped.__serializationContext.populate, wrapped.__serializationContext.fields, wrapped.__serializationContext.exclude);
27
27
  contextCreated = true;
28
28
  }
29
- const root = wrapped.__serializationContext.root;
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);
45
36
  }
46
- for (const key of entityKeys) {
47
- if (!meta.properties[key]) {
48
- props.add(key);
37
+ else {
38
+ meta.primaryKeys.forEach(pk => props.add(pk));
39
+ }
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) {
@@ -18,7 +18,8 @@ export declare class SerializationContext<T extends object> {
18
18
  /** Cleans up the serialization context by removing root references from all tracked entities. */
19
19
  close(): void;
20
20
  /**
21
- * When initializing new context, we need to propagate it to the whole entity graph recursively.
21
+ * Propagates the context to the entity and its direct relations, so nested serialization calls pick it up.
22
+ * Runs for every serialized entity, so the context spreads along the serialized path instead of the whole graph.
22
23
  */
23
24
  static propagate(root: SerializationContext<any>, entity: AnyEntity, isVisible: (meta: EntityMetadata, prop: string) => boolean): void;
24
25
  /** Checks whether a property is explicitly listed in the populate hints for the current path. */
@@ -47,7 +47,8 @@ export class SerializationContext {
47
47
  }
48
48
  }
49
49
  /**
50
- * When initializing new context, we need to propagate it to the whole entity graph recursively.
50
+ * Propagates the context to the entity and its direct relations, so nested serialization calls pick it up.
51
+ * Runs for every serialized entity, so the context spreads along the serialized path instead of the whole graph.
51
52
  */
52
53
  static propagate(root, entity, isVisible) {
53
54
  root.register(entity);
@@ -59,14 +60,14 @@ export class SerializationContext {
59
60
  const target = entity[key];
60
61
  if (Utils.isEntity(target, true)) {
61
62
  if (!target.__helper.__serializationContext.root) {
62
- this.propagate(root, target, isVisible);
63
+ root.register(target);
63
64
  }
64
65
  continue;
65
66
  }
66
67
  if (Utils.isCollection(target)) {
67
68
  for (const item of target.getItems(false)) {
68
69
  if (!item.__helper.__serializationContext.root) {
69
- this.propagate(root, item, isVisible);
70
+ root.register(item);
70
71
  }
71
72
  }
72
73
  }
package/typings.d.ts CHANGED
@@ -384,8 +384,9 @@ export type FilterQuery<T> = ObjectQuery<T> | NonNullable<ExpandScalar<Primary<T
384
384
  /**
385
385
  * `FilterQuery` restricted to only properties covered by the specified index(es).
386
386
  * Used when `using` option is set in `FindOptions` to enforce type-safe index usage.
387
+ * Falls back to `FilterQuery` when `Using` is not a specific index name (e.g. inferred from the options type).
387
388
  */
388
- export type IndexFilterQuery<T, Using extends string> = [Using] extends [never] ? FilterQuery<T> : (OperatorMap<T> & {
389
+ export type IndexFilterQuery<T, Using extends string> = [Using] extends [never] ? FilterQuery<T> : string extends Using ? FilterQuery<T> : (OperatorMap<T> & {
389
390
  -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;
390
391
  }) | NonNullable<ExpandScalar<Primary<T>>> | IndexFilterQuery<T, Using>[];
391
392
  /** Replaces `where` and `using` on an options type with index-aware variants when `Using` is specified. */
@@ -1074,6 +1075,8 @@ export interface EntityProperty<Owner = any, Target = any> {
1074
1075
  referencedColumnNames: string[];
1075
1076
  referencedTableName: string;
1076
1077
  referencedPKs: EntityKey<Owner>[];
1078
+ /** @internal target properties behind a composite FK that references more than the target PK and owns all its columns */
1079
+ referencedProps?: EntityProperty[];
1077
1080
  targetKey?: string;
1078
1081
  serializer?: (value: any, options?: SerializeOptions<any>) => any;
1079
1082
  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();