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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/EntityManager.d.ts +10 -7
  2. package/EntityManager.js +57 -31
  3. package/drivers/DatabaseDriver.d.ts +2 -0
  4. package/drivers/DatabaseDriver.js +9 -1
  5. package/entity/Collection.d.ts +2 -1
  6. package/entity/Collection.js +21 -13
  7. package/entity/EntityAssigner.js +4 -1
  8. package/entity/EntityFactory.js +19 -7
  9. package/entity/EntityHelper.d.ts +8 -3
  10. package/entity/EntityHelper.js +28 -3
  11. package/entity/EntityLoader.js +44 -1
  12. package/entity/Reference.js +6 -5
  13. package/entity/WrappedEntity.js +1 -1
  14. package/entity/utils.js +3 -1
  15. package/entity/validators.d.ts +6 -0
  16. package/entity/validators.js +14 -0
  17. package/errors.d.ts +1 -0
  18. package/errors.js +3 -0
  19. package/hydration/ObjectHydrator.js +16 -10
  20. package/metadata/MetadataDiscovery.js +26 -5
  21. package/package.json +1 -1
  22. package/platforms/Platform.js +4 -1
  23. package/serialization/EntitySerializer.js +53 -44
  24. package/serialization/EntityTransformer.js +86 -78
  25. package/serialization/SerializationContext.js +1 -1
  26. package/typings.d.ts +5 -1
  27. package/typings.js +36 -34
  28. package/unit-of-work/ChangeSetComputer.js +56 -54
  29. package/unit-of-work/ChangeSetPersister.d.ts +2 -0
  30. package/unit-of-work/ChangeSetPersister.js +10 -5
  31. package/unit-of-work/UnitOfWork.js +53 -23
  32. package/utils/Configuration.d.ts +2 -2
  33. package/utils/Configuration.js +2 -2
  34. package/utils/EntityComparator.js +2 -8
  35. package/utils/QueryHelper.d.ts +6 -0
  36. package/utils/QueryHelper.js +42 -0
  37. package/utils/TransactionManager.js +3 -1
  38. package/utils/Utils.js +27 -6
  39. package/utils/clone.js +6 -1
  40. package/utils/upsert-utils.js +13 -6
@@ -66,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;
@@ -141,7 +146,9 @@ export class UnitOfWork {
141
146
  wrapped.__loadedProperties.add(key);
142
147
  }
143
148
  }
144
- wrapped.__originalEntityData = data;
149
+ // a partial refresh must keep the snapshot of properties it did not reload
150
+ wrapped.__originalEntityData =
151
+ options?.refresh && wrapped.__originalEntityData ? { ...wrapped.__originalEntityData, ...data } : data;
145
152
  }
146
153
  return entity;
147
154
  }
@@ -555,14 +562,19 @@ export class UnitOfWork {
555
562
  // the referrer's primary key contains the removed entity, so its identity cannot survive the removal
556
563
  this.unsetIdentity(referrer);
557
564
  }
558
- else {
565
+ else if ((prop.inversedBy || prop.mappedBy) && !prop.mapToPk) {
566
+ // relations with an inverse side are backed by `__data` to allow propagation
559
567
  delete helper(referrer).__data[prop.name];
560
568
  }
569
+ else {
570
+ delete referrer[prop.name];
571
+ }
561
572
  }
562
573
  }
563
574
  }
564
- delete wrapped.__identifier;
565
- delete wrapped.__originalEntityData;
575
+ // `delete` would switch the wrapper to dictionary mode
576
+ wrapped.__identifier = undefined;
577
+ wrapped.__originalEntityData = undefined;
566
578
  wrapped.__managed = false;
567
579
  }
568
580
  computeChangeSets() {
@@ -572,17 +584,21 @@ export class UnitOfWork {
572
584
  this.cascade(entity, Cascade.REMOVE, visited);
573
585
  }
574
586
  visited.clear();
587
+ const persistOptions = { checkRemoveStack: true };
575
588
  for (const entity of this.#identityMap) {
576
589
  if (!this.#removeStack.has(entity) && !this.#persistStack.has(entity) && !this.#orphanRemoveStack.has(entity)) {
577
- this.cascade(entity, Cascade.PERSIST, visited, { checkRemoveStack: true });
590
+ this.cascade(entity, Cascade.PERSIST, visited, persistOptions);
578
591
  }
579
592
  }
580
593
  for (const entity of this.#persistStack) {
581
- this.cascade(entity, Cascade.PERSIST, visited, { checkRemoveStack: true });
594
+ this.cascade(entity, Cascade.PERSIST, visited, persistOptions);
582
595
  }
583
596
  visited.clear();
597
+ // perf: every traversal starts with an empty `processed` set, reuse one instead of allocating it per entity
598
+ const processed = new Set();
584
599
  for (const entity of this.#persistStack) {
585
- this.findNewEntities(entity, visited);
600
+ processed.clear();
601
+ this.findNewEntities(entity, visited, 0, processed);
586
602
  }
587
603
  for (const entity of this.#orphanRemoveStack) {
588
604
  if (!helper(entity).__processing) {
@@ -621,8 +637,10 @@ export class UnitOfWork {
621
637
  }
622
638
  }
623
639
  }
624
- const deletePkHash = [wrapped.getSerializedPrimaryKey(), ...this.expandUniqueProps(entity)];
625
- const type = deletePkHash.some(hash => hashes.has(hash)) ? ChangeSetType.DELETE_EARLY : ChangeSetType.DELETE;
640
+ // without inserts of this type (the common case), there is nothing to match the removed entity against
641
+ const early = hashes.size > 0 &&
642
+ [wrapped.getSerializedPrimaryKey(), ...this.expandUniqueProps(entity)].some(hash => hashes.has(hash));
643
+ const type = early ? ChangeSetType.DELETE_EARLY : ChangeSetType.DELETE;
626
644
  this.computeChangeSet(entity, type);
627
645
  }
628
646
  }
@@ -679,7 +697,7 @@ export class UnitOfWork {
679
697
  getChangeSetPersister() {
680
698
  return this.#changeSetPersister;
681
699
  }
682
- findNewEntities(entity, visited, idx = 0, processed = new Set()) {
700
+ findNewEntities(entity, visited, idx, processed) {
683
701
  if (visited.has(entity)) {
684
702
  return;
685
703
  }
@@ -693,6 +711,13 @@ export class UnitOfWork {
693
711
  wrapped.__schema ??= this.#em.schema;
694
712
  this.initIdentifier(entity);
695
713
  for (const prop of wrapped.__meta.relations) {
714
+ // perf: a relation outside of embeddables has a single target, so skip the allocations of `unwrapProperty`
715
+ if (!prop.object && !prop.array && !prop.embedded) {
716
+ if (entity[prop.name] != null) {
717
+ this.processReference(entity, prop, Reference.unwrapReference(entity[prop.name]), visited, processed, idx);
718
+ }
719
+ continue;
720
+ }
696
721
  const targets = Utils.unwrapProperty(entity, wrapped.__meta, prop);
697
722
  for (const [target] of targets) {
698
723
  const kind = Reference.unwrapReference(target);
@@ -844,13 +869,12 @@ export class UnitOfWork {
844
869
  return this.processToOneReference(kind, visited, processed, idx);
845
870
  }
846
871
  if (Utils.isCollection(kind)) {
847
- kind
848
- .getItems(false)
849
- .filter(item => !item.__helper.__originalEntityData)
850
- .forEach(item => {
872
+ for (const item of kind.getItems(false)) {
851
873
  // propagate schema from parent
852
- item.__helper.__schema ??= helper(parent).__schema;
853
- });
874
+ if (!item.__helper.__originalEntityData) {
875
+ item.__helper.__schema ??= helper(parent).__schema;
876
+ }
877
+ }
854
878
  if (prop.kind === ReferenceKind.MANY_TO_MANY && kind.isDirty()) {
855
879
  this.processToManyReference(kind, visited, processed, parent, prop);
856
880
  }
@@ -904,7 +928,8 @@ export class UnitOfWork {
904
928
  for (const cs of this.#changeSets.values()) {
905
929
  const wrapped = helper(cs.entity);
906
930
  wrapped.__processing = false;
907
- delete wrapped.__pk;
931
+ // `delete` would switch the wrapper to dictionary mode for the rest of the entity's life
932
+ wrapped.__pk = undefined;
908
933
  }
909
934
  this.#persistStack.clear();
910
935
  this.#removeStack.clear();
@@ -947,11 +972,11 @@ export class UnitOfWork {
947
972
  return;
948
973
  }
949
974
  const kind = Reference.unwrapReference(entity[prop.name]);
950
- if ([ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(prop.kind) && Utils.isEntity(kind)) {
975
+ if ((prop.kind === ReferenceKind.MANY_TO_ONE || prop.kind === ReferenceKind.ONE_TO_ONE) && Utils.isEntity(kind)) {
951
976
  return this.cascade(kind, type, visited, options);
952
977
  }
953
978
  const collection = kind;
954
- if ([ReferenceKind.ONE_TO_MANY, ReferenceKind.MANY_TO_MANY].includes(prop.kind) && collection) {
979
+ if ((prop.kind === ReferenceKind.ONE_TO_MANY || prop.kind === ReferenceKind.MANY_TO_MANY) && collection) {
955
980
  for (const item of collection.getItems(false)) {
956
981
  this.cascade(item, type, visited, options);
957
982
  }
@@ -962,8 +987,11 @@ export class UnitOfWork {
962
987
  return filtered.some(items => processed.has(items));
963
988
  }
964
989
  shouldCascade(prop, type) {
965
- if ([Cascade.REMOVE, Cascade.SCHEDULE_ORPHAN_REMOVAL, Cascade.CANCEL_ORPHAN_REMOVAL, Cascade.ALL].includes(type) &&
966
- prop.orphanRemoval) {
990
+ if (prop.orphanRemoval &&
991
+ (type === Cascade.REMOVE ||
992
+ type === Cascade.SCHEDULE_ORPHAN_REMOVAL ||
993
+ type === Cascade.CANCEL_ORPHAN_REMOVAL ||
994
+ type === Cascade.ALL)) {
967
995
  return true;
968
996
  }
969
997
  // ignore user settings for merge, it is kept only for back compatibility, this should have never been configurable
@@ -997,7 +1025,9 @@ export class UnitOfWork {
997
1025
  fixMissingReference(entity, prop) {
998
1026
  const reference = entity[prop.name];
999
1027
  const target = Reference.unwrapReference(reference);
1000
- if ([ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(prop.kind) && target && !prop.mapToPk) {
1028
+ if ((prop.kind === ReferenceKind.MANY_TO_ONE || prop.kind === ReferenceKind.ONE_TO_ONE) &&
1029
+ target &&
1030
+ !prop.mapToPk) {
1001
1031
  if (!Utils.isEntity(target)) {
1002
1032
  entity[prop.name] = this.#em.getReference(prop.targetMeta.class, target, {
1003
1033
  wrapped: !!prop.ref,
@@ -1014,7 +1044,7 @@ export class UnitOfWork {
1014
1044
  if (Utils.isCollection(target)) {
1015
1045
  target.property = prop;
1016
1046
  }
1017
- const isCollection = [ReferenceKind.ONE_TO_MANY, ReferenceKind.MANY_TO_MANY].includes(prop.kind);
1047
+ const isCollection = prop.kind === ReferenceKind.ONE_TO_MANY || prop.kind === ReferenceKind.MANY_TO_MANY;
1018
1048
  if (isCollection && Array.isArray(target)) {
1019
1049
  const collection = new Collection(entity);
1020
1050
  collection.property = prop;
@@ -972,8 +972,8 @@ export interface Options<Driver extends IDatabaseDriver = IDatabaseDriver, EM ex
972
972
  };
973
973
  /**
974
974
  * Metadata provider class for entity discovery.
975
- * Built-in options: `ReflectMetadataProvider` (default), `TsMorphMetadataProvider`.
976
- * @default ReflectMetadataProvider
975
+ * Built-in options: `MetadataProvider` (default), `ReflectMetadataProvider` (from `@mikro-orm/decorators/legacy`), `TsMorphMetadataProvider`.
976
+ * @default MetadataProvider
977
977
  * @see https://mikro-orm.io/docs/metadata-providers
978
978
  */
979
979
  metadataProvider: {
@@ -25,7 +25,6 @@ const DEFAULTS = {
25
25
  warnWhenNoEntities: true,
26
26
  checkDuplicateTableNames: true,
27
27
  checkDuplicateFieldNames: true,
28
- checkDuplicateEntities: true,
29
28
  checkNonPersistentCompositeProps: true,
30
29
  inferDefaultValues: true,
31
30
  },
@@ -149,7 +148,8 @@ export class Configuration {
149
148
  #routines = [];
150
149
  #routinesNormalised = false;
151
150
  constructor(options, validate = true) {
152
- if (options.dynamicImportProvider) {
151
+ // the default is present when re-creating from `getAll()`, it must not override an already registered provider
152
+ if (options.dynamicImportProvider && options.dynamicImportProvider !== DEFAULTS.dynamicImportProvider) {
153
153
  globalThis.dynamicImportProvider = options.dynamicImportProvider;
154
154
  }
155
155
  this.#options = Utils.mergeConfig({}, DEFAULTS, options);
@@ -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.3.0-dev.21';
156
+ static #ORM_VERSION = '7.3.0-dev.23';
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) => {
@@ -636,6 +640,18 @@ export class Utils {
636
640
  * Checks whether the value is POJO (e.g. `{ foo: 'bar' }`, and not instance of `Foo`)
637
641
  */
638
642
  static isPlainObject(value) {
643
+ // primitives and object literals short-circuit with the full check's result, functions can still be null-prototype objects
644
+ if (typeof value === 'object') {
645
+ if (value === null) {
646
+ return false;
647
+ }
648
+ if (value.constructor === Object) {
649
+ return true;
650
+ }
651
+ }
652
+ else if (typeof value !== 'function') {
653
+ return false;
654
+ }
639
655
  return ((value !== null &&
640
656
  typeof value === 'object' &&
641
657
  typeof value.constructor === 'function' &&
@@ -915,11 +931,16 @@ export class Utils {
915
931
  }, {});
916
932
  }
917
933
  static getObjectQueryKeys(obj) {
918
- return Reflect.ownKeys(obj).filter(key => {
919
- if (!Object.prototype.propertyIsEnumerable.call(obj, key)) {
920
- return false;
934
+ const keys = Object.keys(obj);
935
+ const symbols = Object.getOwnPropertySymbols(obj);
936
+ if (symbols.length === 0) {
937
+ return keys;
938
+ }
939
+ for (const key of symbols) {
940
+ if (Raw.isKnownFragmentSymbol(key) && Object.prototype.propertyIsEnumerable.call(obj, key)) {
941
+ keys.push(key);
921
942
  }
922
- return typeof key === 'string' || Raw.isKnownFragmentSymbol(key);
923
- });
943
+ }
944
+ return keys;
924
945
  }
925
946
  }
package/utils/clone.js CHANGED
@@ -22,6 +22,10 @@ function getPropertyDescriptor(obj, prop) {
22
22
  }
23
23
  const TypedArray = Object.getPrototypeOf(Uint8Array);
24
24
  export function clone(parent, respectCustomCloneMethod = true) {
25
+ // perf: snapshots clone every scalar, skip the cycle map for primitives
26
+ if (parent === null || typeof parent !== 'object') {
27
+ return parent;
28
+ }
25
29
  // already cloned objects, so shared references and cycles map to a single clone
26
30
  const clones = new Map();
27
31
  function _clone(parent) {
@@ -123,7 +127,8 @@ export function clone(parent, respectCustomCloneMethod = true) {
123
127
  if (attrs && typeof attrs.get === 'function' && attrs.set == null) {
124
128
  continue;
125
129
  }
126
- child[i] = _clone(parent[i]);
130
+ // `Reflect.get` avoids V8's for-in enum cache load, which can fall into an endless deopt/reoptimize loop here
131
+ child[i] = _clone(Reflect.get(parent, i));
127
132
  }
128
133
  const symbols = Object.getOwnPropertySymbols(parent);
129
134
  for (let i = 0; i < symbols.length; i++) {
@@ -155,14 +155,21 @@ export function getWhereCondition(meta, onConflictFields, data, where) {
155
155
  unique.findIndex(p => data[p] ?? data[p.substring(0, p.indexOf('.'))] != null);
156
156
  if (onConflictFields || where == null) {
157
157
  if (propIndex !== false && propIndex >= 0) {
158
- let key = unique[propIndex];
159
- if (key.includes('.')) {
160
- const prop = meta.properties[key.substring(0, key.indexOf('.'))];
161
- if (prop) {
162
- key = `${prop.fieldNames[0]}${key.substring(key.indexOf('.'))}`;
158
+ // `onConflictFields` form one composite key, while the unique props are each unique on their own
159
+ const keys = onConflictFields
160
+ ? unique.filter(p => (data[p] ?? data[p.substring(0, p.indexOf('.'))]) != null)
161
+ : [unique[propIndex]];
162
+ where = {};
163
+ for (const field of keys) {
164
+ let key = field;
165
+ if (key.includes('.')) {
166
+ const prop = meta.properties[key.substring(0, key.indexOf('.'))];
167
+ if (prop) {
168
+ key = `${prop.fieldNames[0]}${key.substring(key.indexOf('.'))}`;
169
+ }
163
170
  }
171
+ where[key] = getPropertyValue(data, field);
164
172
  }
165
- where = { [key]: getPropertyValue(data, unique[propIndex]) };
166
173
  }
167
174
  else {
168
175
  for (const u of uniques) {