@mikro-orm/core 7.3.0-dev.2 → 7.3.0-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.
Files changed (57) hide show
  1. package/EntityManager.js +158 -42
  2. package/cache/cache-key.d.ts +5 -0
  3. package/cache/cache-key.js +30 -0
  4. package/drivers/DatabaseDriver.d.ts +2 -0
  5. package/drivers/DatabaseDriver.js +16 -3
  6. package/drivers/IDatabaseDriver.d.ts +2 -0
  7. package/entity/EntityAssigner.js +15 -3
  8. package/entity/EntityFactory.d.ts +8 -0
  9. package/entity/EntityFactory.js +69 -3
  10. package/entity/EntityLoader.d.ts +1 -0
  11. package/entity/EntityLoader.js +66 -23
  12. package/entity/WrappedEntity.js +6 -1
  13. package/entity/defineEntity.d.ts +32 -19
  14. package/entity/defineEntity.js +9 -0
  15. package/entity/validators.js +4 -1
  16. package/errors.d.ts +7 -0
  17. package/errors.js +15 -0
  18. package/hydration/ObjectHydrator.js +6 -2
  19. package/metadata/MetadataDiscovery.d.ts +10 -0
  20. package/metadata/MetadataDiscovery.js +178 -30
  21. package/metadata/MetadataStorage.d.ts +8 -0
  22. package/metadata/MetadataStorage.js +47 -3
  23. package/metadata/MetadataValidator.js +2 -1
  24. package/metadata/types.d.ts +12 -0
  25. package/package.json +1 -1
  26. package/platforms/Platform.d.ts +6 -0
  27. package/platforms/Platform.js +26 -0
  28. package/serialization/EntitySerializer.js +56 -16
  29. package/serialization/EntityTransformer.js +4 -4
  30. package/serialization/SerializationContext.d.ts +2 -1
  31. package/serialization/SerializationContext.js +4 -3
  32. package/types/DecimalType.js +34 -1
  33. package/types/DoubleType.d.ts +7 -3
  34. package/types/DoubleType.js +8 -3
  35. package/typings.d.ts +26 -6
  36. package/typings.js +5 -2
  37. package/unit-of-work/ChangeSetComputer.js +22 -7
  38. package/unit-of-work/ChangeSetPersister.js +24 -5
  39. package/unit-of-work/CommitOrderCalculator.js +2 -1
  40. package/unit-of-work/IdentityMap.d.ts +3 -2
  41. package/unit-of-work/IdentityMap.js +30 -7
  42. package/unit-of-work/UnitOfWork.js +49 -9
  43. package/utils/Configuration.d.ts +12 -1
  44. package/utils/DataloaderUtils.js +19 -8
  45. package/utils/EntityComparator.d.ts +5 -0
  46. package/utils/EntityComparator.js +87 -19
  47. package/utils/QueryHelper.d.ts +14 -0
  48. package/utils/QueryHelper.js +90 -13
  49. package/utils/RawQueryFragment.d.ts +5 -1
  50. package/utils/RawQueryFragment.js +27 -19
  51. package/utils/TransactionManager.js +4 -0
  52. package/utils/Utils.d.ts +2 -0
  53. package/utils/Utils.js +24 -8
  54. package/utils/clone.js +5 -7
  55. package/utils/env-vars.js +2 -0
  56. package/utils/fs-utils.js +19 -15
  57. package/utils/upsert-utils.js +2 -1
@@ -89,7 +89,10 @@ export class UnitOfWork {
89
89
  Utils.isPlainObject(data[prop.name])) {
90
90
  // Skip polymorphic relations - they use PolymorphicRef wrapper
91
91
  if (!prop.polymorphic) {
92
- data[prop.name] = Utils.getPrimaryKeyValues(data[prop.name], prop.targetMeta, true);
92
+ // with `targetKey`, the FK holds that value instead of the PK
93
+ data[prop.name] = prop.targetKey
94
+ ? data[prop.name][prop.targetKey]
95
+ : Utils.getPrimaryKeyValues(data[prop.name], prop.targetMeta, true);
93
96
  }
94
97
  }
95
98
  else if (prop.kind === ReferenceKind.EMBEDDED && !prop.object && Utils.isPlainObject(data[prop.name])) {
@@ -205,7 +208,18 @@ export class UnitOfWork {
205
208
  value = prop.customType.convertToJSValue(value, this.#platform, { mode: 'hydration' });
206
209
  }
207
210
  const hash = this.#identityMap.getKeyHash(key, '' + value, schema);
208
- return this.#identityMap.getByHash(meta, hash);
211
+ const entity = this.#identityMap.getByHash(meta, hash);
212
+ // the entry is stale when the key changed via refresh or merge, unless only the unflushed value differs
213
+ if (entity && '' + entity[key] !== '' + value) {
214
+ // the snapshot holds the database value
215
+ const dbValue = prop?.customType
216
+ ? prop.customType.convertToDatabaseValue(value, this.#platform, { mode: 'serialization' })
217
+ : value;
218
+ if ('' + helper(entity).__originalEntityData?.[key] !== '' + dbValue) {
219
+ return undefined;
220
+ }
221
+ }
222
+ return entity;
209
223
  }
210
224
  /**
211
225
  * Stores an entity in the identity map under an alternate key (non-PK property).
@@ -368,6 +382,10 @@ export class UnitOfWork {
368
382
  }
369
383
  /** Marks an entity for removal, cascading to related entities. */
370
384
  remove(entity, visited, options = {}) {
385
+ // a reference known only by its `targetKey` has no PK, so the delete would match nothing
386
+ if (!helper(entity).__initialized && !helper(entity).hasPrimaryKey()) {
387
+ throw ValidationError.referenceWithoutPK(entity);
388
+ }
371
389
  // allow removing not managed entities if they are not part of the persist stack
372
390
  if (helper(entity).__managed || !this.#persistStack.has(entity)) {
373
391
  this.#removeStack.add(entity);
@@ -377,7 +395,7 @@ export class UnitOfWork {
377
395
  this.#persistStack.delete(entity);
378
396
  this.#identityMap.delete(entity);
379
397
  }
380
- // remove from referencing relations that are nullable
398
+ // unlink loaded inverse-side items only when the FK is `set null`, other delete rules are left to the database
381
399
  const entityMeta = helper(entity).__meta;
382
400
  for (const prop of entityMeta.bidirectionalRelations) {
383
401
  const inverseProp = prop.mappedBy || prop.inversedBy;
@@ -392,7 +410,9 @@ export class UnitOfWork {
392
410
  : inverseTarget.class !== entityMeta.class) {
393
411
  continue;
394
412
  }
395
- if (prop.kind === ReferenceKind.ONE_TO_MANY && prop2.nullable && Utils.isCollection(relation)) {
413
+ if (prop.kind === ReferenceKind.ONE_TO_MANY &&
414
+ prop2.deleteRule === 'set null' &&
415
+ Utils.isCollection(relation)) {
396
416
  for (const item of relation.getItems(false)) {
397
417
  delete item[inverseProp];
398
418
  }
@@ -582,19 +602,27 @@ export class UnitOfWork {
582
602
  this.findEarlyUpdates(cs, inserts[cs.meta.uniqueName]);
583
603
  }
584
604
  }
605
+ // hashes of the inserts' PKs and unique values per type, built lazily, so matching a removed entity is a set lookup
606
+ const insertHashes = {};
585
607
  for (const entity of this.#removeStack) {
586
608
  const wrapped = helper(entity);
587
609
  /* v8 ignore next */
588
610
  if (wrapped.__processing) {
589
611
  continue;
590
612
  }
591
- const deletePkHash = [wrapped.getSerializedPrimaryKey(), ...this.expandUniqueProps(entity)];
592
- let type = ChangeSetType.DELETE;
593
- for (const cs of inserts[wrapped.__meta.uniqueName] ?? []) {
594
- if (deletePkHash.some(hash => hash === cs.getSerializedPrimaryKey() || this.expandUniqueProps(cs.entity).find(child => hash === child))) {
595
- type = ChangeSetType.DELETE_EARLY;
613
+ const uniqueName = wrapped.__meta.uniqueName;
614
+ let hashes = insertHashes[uniqueName];
615
+ if (!hashes) {
616
+ hashes = insertHashes[uniqueName] = new Set();
617
+ for (const cs of inserts[uniqueName] ?? []) {
618
+ hashes.add(cs.getSerializedPrimaryKey());
619
+ for (const hash of this.expandUniqueProps(cs.entity)) {
620
+ hashes.add(hash);
621
+ }
596
622
  }
597
623
  }
624
+ const deletePkHash = [wrapped.getSerializedPrimaryKey(), ...this.expandUniqueProps(entity)];
625
+ const type = deletePkHash.some(hash => hashes.has(hash)) ? ChangeSetType.DELETE_EARLY : ChangeSetType.DELETE;
598
626
  this.computeChangeSet(entity, type);
599
627
  }
600
628
  }
@@ -1118,6 +1146,11 @@ export class UnitOfWork {
1118
1146
  for (const changeSet of changeSets) {
1119
1147
  const wrapped = helper(changeSet.entity);
1120
1148
  wrapped.__originalEntityData = this.#comparator.prepareEntity(changeSet.entity);
1149
+ // re-index so the entity is found by its new `targetKey` values instead of the old ones
1150
+ if (changeSet.meta.root.targetKeys?.some(key => key in changeSet.payload)) {
1151
+ this.#identityMap.delete(changeSet.entity);
1152
+ this.#identityMap.store(changeSet.entity);
1153
+ }
1121
1154
  if (!wrapped.__initialized) {
1122
1155
  for (const prop of changeSet.meta.relations) {
1123
1156
  if ([ReferenceKind.MANY_TO_MANY, ReferenceKind.ONE_TO_MANY].includes(prop.kind) &&
@@ -1260,6 +1293,13 @@ export class UnitOfWork {
1260
1293
  calc.discoverProperty({ ...prop, targetMeta }, meta._id);
1261
1294
  }
1262
1295
  }
1296
+ else if (prop.targetMeta?.inheritanceType === 'tpt') {
1297
+ calc.discoverProperty(prop, meta._id);
1298
+ // a TPT subclass delete has only a leaf change set that also removes the target row; weak edge so it can't break insert order
1299
+ for (const targetMeta of this.#metadata.find(prop.targetMeta.class).allTPTDescendants ?? []) {
1300
+ calc.discoverProperty({ ...prop, targetMeta, nullable: true }, meta._id);
1301
+ }
1302
+ }
1263
1303
  else {
1264
1304
  calc.discoverProperty(prop, meta._id);
1265
1305
  }
@@ -218,6 +218,17 @@ export type MigrationsOptions = {
218
218
  * @default true
219
219
  */
220
220
  allOrNothing?: boolean;
221
+ /**
222
+ * Serialize concurrent `migrator.up()`/`migrator.down()` runs (e.g. several replicas migrating on start) with a
223
+ * database lock, held on a pooled connection of its own for the whole run (so `pool.max` needs to be at least 2).
224
+ * Supported on PostgreSQL, MySQL, MariaDB and MSSQL, ignored elsewhere.
225
+ * @default false
226
+ */
227
+ lock?: boolean;
228
+ /**
229
+ * How long to wait for the migration lock (in milliseconds) before failing. Waits indefinitely by default.
230
+ */
231
+ lockTimeout?: number;
221
232
  /**
222
233
  * Allow dropping tables during schema diff.
223
234
  * @default true
@@ -593,7 +604,7 @@ export interface Options<Driver extends IDatabaseDriver = IDatabaseDriver, EM ex
593
604
  /**
594
605
  * Force `Date` values to be stored in UTC for datetime columns without timezone.
595
606
  * Works for MySQL (`datetime` type), PostgreSQL (`timestamp` type), and MSSQL (`datetime`/`datetime2` types).
596
- * SQLite does this by default.
607
+ * SQLite does this by default. MySQL and MariaDB also get their session time zone set on every new connection.
597
608
  * @default true
598
609
  */
599
610
  forceUtcTimezone: boolean;
@@ -3,6 +3,9 @@ import { helper } from '../entity/wrap.js';
3
3
  import { Reference } from '../entity/Reference.js';
4
4
  import { ReferenceKind } from '../enums.js';
5
5
  import { Utils } from './Utils.js';
6
+ import { stringifyCacheKey } from '../cache/cache-key.js';
7
+ // the original options of each group key, JSON cannot restore values like RegExp or `raw()` from the key
8
+ const groupOptions = new WeakMap();
6
9
  export class DataloaderUtils {
7
10
  static DataLoader;
8
11
  /**
@@ -11,6 +14,8 @@ export class DataloaderUtils {
11
14
  */
12
15
  static groupPrimaryKeysByEntityAndOpts(refsWithOpts) {
13
16
  const map = new Map();
17
+ const options = new Map();
18
+ groupOptions.set(map, options);
14
19
  for (const [ref, opts] of refsWithOpts) {
15
20
  /* The key is a combination of the uniqueName (a unique table name based identifier) and a stringified version if the load options because we want
16
21
  to map each combination of entities/options into separate find queries in order to return accurate results.
@@ -25,7 +30,8 @@ export class DataloaderUtils {
25
30
  Thus such approach should probably be configurable, if not opt-in.
26
31
  NOTE: meta + opts multi maps (https://github.com/martian17/ds-js) might be a more elegant way
27
32
  to implement this but not necessarily faster. */
28
- const key = `${helper(ref).__meta.uniqueName}|${JSON.stringify(opts ?? {})}`;
33
+ const key = `${helper(ref).__meta.uniqueName}|${stringifyCacheKey(opts ?? {})}`;
34
+ options.set(key, opts ?? {});
29
35
  let primaryKeysSet = map.get(key);
30
36
  if (primaryKeysSet == null) {
31
37
  primaryKeysSet = new Set();
@@ -44,7 +50,7 @@ export class DataloaderUtils {
44
50
  const groupedIdsMap = DataloaderUtils.groupPrimaryKeysByEntityAndOpts(refsWithOpts);
45
51
  const promises = Array.from(groupedIdsMap).map(([key, idsSet]) => {
46
52
  const uniqueName = key.substring(0, key.indexOf('|'));
47
- const opts = JSON.parse(key.substring(key.indexOf('|') + 1));
53
+ const opts = groupOptions.get(groupedIdsMap).get(key);
48
54
  const meta = em.getMetadata().getByUniqueName(uniqueName);
49
55
  return em.find(meta.class, Array.from(idsSet), opts);
50
56
  });
@@ -64,6 +70,8 @@ export class DataloaderUtils {
64
70
  */
65
71
  static groupInversedOrMappedKeysByEntityAndOpts(collsWithOpts) {
66
72
  const entitiesMap = new Map();
73
+ const options = new Map();
74
+ groupOptions.set(entitiesMap, options);
67
75
  for (const [col, opts] of collsWithOpts) {
68
76
  /*
69
77
  We first get the entity name of the Collection and together with its options (see groupPrimaryKeysByEntityAndOpts
@@ -72,7 +80,8 @@ export class DataloaderUtils {
72
80
  The value is another Map which we can use to filter the find query to get results pertaining to the collections that have been dataloaded:
73
81
  its keys are the props we are going to filter to and its values are the corresponding PKs.
74
82
  */
75
- const key = `${col.property.targetMeta.uniqueName}|${JSON.stringify(opts ?? {})}`;
83
+ const key = `${col.property.targetMeta.uniqueName}|${stringifyCacheKey(opts ?? {})}`;
84
+ options.set(key, opts ?? {});
76
85
  let filterMap = entitiesMap.get(key); // We are going to use this map to filter the entities pertaining to the collections that have been dataloaded.
77
86
  if (filterMap == null) {
78
87
  filterMap = new Map();
@@ -100,7 +109,9 @@ export class DataloaderUtils {
100
109
  static entitiesAndOptsMapToQueries(entitiesAndOptsMap, em) {
101
110
  return Array.from(entitiesAndOptsMap, async ([key, filterMap]) => {
102
111
  const uniqueName = key.substring(0, key.indexOf('|'));
103
- const opts = JSON.parse(key.substring(key.indexOf('|') + 1));
112
+ const opts = groupOptions
113
+ .get(entitiesAndOptsMap)
114
+ ?.get(key) ?? JSON.parse(key.substring(key.indexOf('|') + 1));
104
115
  const meta = em.getMetadata().getByUniqueName(uniqueName);
105
116
  const res = await em.find(meta.class, opts?.where != null && Object.keys(opts.where).length > 0
106
117
  ? {
@@ -168,7 +179,7 @@ export class DataloaderUtils {
168
179
  // We need to filter the results in order to map each input collection
169
180
  // to a subset of each query matching the collection items.
170
181
  return collsWithOpts.map(([col, opts]) => {
171
- const key = `${col.property.targetMeta.uniqueName}|${JSON.stringify(opts ?? {})}`;
182
+ const key = `${col.property.targetMeta.uniqueName}|${stringifyCacheKey(opts ?? {})}`;
172
183
  const entities = resultsMap.get(key);
173
184
  if (entities == null) {
174
185
  // Should never happen
@@ -187,7 +198,7 @@ export class DataloaderUtils {
187
198
  return async (collsWithOpts) => {
188
199
  const groups = new Map();
189
200
  for (const [col, opts] of collsWithOpts) {
190
- const key = `${col.property.targetMeta.uniqueName}.${col.property.name}|${JSON.stringify(opts ?? {})}`;
201
+ const key = `${col.property.targetMeta.uniqueName}.${col.property.name}|${stringifyCacheKey(opts ?? {})}`;
191
202
  const value = groups.get(key) ?? [];
192
203
  value.push([col, opts ?? {}]);
193
204
  groups.set(key, value);
@@ -252,7 +263,7 @@ export class DataloaderUtils {
252
263
  // sharing a relation with the same property name (e.g. `Author.books` and `Publisher.books`)
253
264
  // don't collide into a single batch that would use one owner's FK mapping for the other.
254
265
  const ownerUniqueName = helper(col.owner).__meta.uniqueName;
255
- const key = `${ownerUniqueName}.${prop.name}|${JSON.stringify(opts ?? {})}`;
266
+ const key = `${ownerUniqueName}.${prop.name}|${stringifyCacheKey(opts ?? {})}`;
256
267
  keys.push(key);
257
268
  let group = groups.get(key);
258
269
  if (!group) {
@@ -260,7 +271,7 @@ export class DataloaderUtils {
260
271
  groups.set(key, group);
261
272
  }
262
273
  const pk = helper(col.owner).getPrimaryKey();
263
- group.ownerPKs.set(JSON.stringify(pk), pk);
274
+ group.ownerPKs.set(stringifyCacheKey(pk), pk);
264
275
  }
265
276
  const promises = Array.from(groups.entries()).map(async ([key, group]) => {
266
277
  const allPKs = Array.from(group.ownerPKs.values());
@@ -19,6 +19,11 @@ export declare class EntityComparator {
19
19
  diffEntities<T extends object>(entityName: EntityName<T>, a: EntityData<T>, b: EntityData<T>, options?: {
20
20
  includeInverseSides?: boolean;
21
21
  }): EntityData<T>;
22
+ /**
23
+ * Returns true if the comparator checks this property with `!==`, so matching values are identical primitives.
24
+ * @internal
25
+ */
26
+ isStrictlyCompared<T>(prop: EntityProperty<T>): boolean;
22
27
  /** Returns true if two entity snapshots are identical (no differences). */
23
28
  matching<T extends object>(entityName: EntityName<T>, a: EntityData<T>, b: EntityData<T>): boolean;
24
29
  /**
@@ -1,6 +1,7 @@
1
1
  import { clone } from './clone.js';
2
2
  import { ReferenceKind } from '../enums.js';
3
3
  import { compareArrays, compareBooleans, compareBuffers, compareObjects, equals, parseJsonSafe, Utils, } from './Utils.js';
4
+ import { DateType } from '../types/DateType.js';
4
5
  import { JsonType } from '../types/JsonType.js';
5
6
  import { Raw } from './RawQueryFragment.js';
6
7
  import { EntityIdentifier } from '../entity/EntityIdentifier.js';
@@ -29,6 +30,17 @@ export class EntityComparator {
29
30
  const comparator = this.getEntityComparator(entityName);
30
31
  return Utils.callCompiledFunction(comparator, a, b, options);
31
32
  }
33
+ /**
34
+ * Returns true if the comparator checks this property with `!==`, so matching values are identical primitives.
35
+ * @internal
36
+ */
37
+ isStrictlyCompared(prop) {
38
+ if (prop.kind !== ReferenceKind.SCALAR || prop.customType?.compareValues) {
39
+ return false;
40
+ }
41
+ const type = (prop.customType ? prop.customType.compareAsType() : prop.type).toLowerCase();
42
+ return ['string', 'number', 'bigint'].includes(type);
43
+ }
32
44
  /** Returns true if two entity snapshots are identical (no differences). */
33
45
  matching(entityName, a, b) {
34
46
  const diff = this.diffEntities(entityName, a, b);
@@ -95,7 +107,7 @@ export class EntityComparator {
95
107
  lines.push(` return entity${this.wrap(pk)};`);
96
108
  }
97
109
  const code = `// compiled pk getter for entity ${meta.className}\n` + `return function(entity) {\n${lines.join('\n')}\n}`;
98
- const fnKey = `pkGetter-${meta.uniqueName}`;
110
+ const fnKey = `pkGetter-${meta.compiledName}`;
99
111
  const pkSerializer = Utils.createFunction(context, code, this.#config?.get('compiledFunctions'), fnKey);
100
112
  this.#pkGetters.set(meta, pkSerializer);
101
113
  return pkSerializer;
@@ -147,7 +159,7 @@ export class EntityComparator {
147
159
  }
148
160
  const code = `// compiled pk getter (with converted custom types) for entity ${meta.className}\n` +
149
161
  `return function(entity) {\n${lines.join('\n')}\n}`;
150
- const fnKey = `pkGetterConverted-${meta.uniqueName}`;
162
+ const fnKey = `pkGetterConverted-${meta.compiledName}`;
151
163
  const pkSerializer = Utils.createFunction(context, code, this.#config?.get('compiledFunctions'), fnKey);
152
164
  this.#pkGettersConverted.set(meta, pkSerializer);
153
165
  return pkSerializer;
@@ -206,7 +218,7 @@ export class EntityComparator {
206
218
  }
207
219
  }
208
220
  const code = `// compiled pk serializer for entity ${meta.className}\n` + `return function(entity) {\n${lines.join('\n')}\n}`;
209
- const fnKey = `pkSerializer-${meta.uniqueName}`;
221
+ const fnKey = `pkSerializer-${meta.compiledName}`;
210
222
  const pkSerializer = Utils.createFunction(context, code, this.#config?.get('compiledFunctions'), fnKey);
211
223
  this.#pkSerializers.set(meta, pkSerializer);
212
224
  return pkSerializer;
@@ -236,7 +248,7 @@ export class EntityComparator {
236
248
  })
237
249
  .forEach(prop => lines.push(this.getPropertySnapshot(meta, prop, context, this.wrap(prop.name), this.wrap(prop.name), [prop.name])));
238
250
  const code = `return function(entity) {\n const ret = {};\n${lines.join('\n')}\n return ret;\n}`;
239
- const fnKey = `snapshotGenerator-${meta.uniqueName}`;
251
+ const fnKey = `snapshotGenerator-${meta.compiledName}`;
240
252
  const snapshotGenerator = Utils.createFunction(context, code, this.#config?.get('compiledFunctions'), fnKey);
241
253
  this.#snapshotGenerators.set(meta, snapshotGenerator);
242
254
  return snapshotGenerator;
@@ -350,19 +362,48 @@ export class EntityComparator {
350
362
  if (prop.embedded && (meta.embeddable || meta.properties[prop.embedded[0]].object)) {
351
363
  continue;
352
364
  }
365
+ let defined = `typeof ${this.propName(prop.fieldNames[0])} !== 'undefined'`;
366
+ // STI subtypes with conflicting columns share the property, so another subtype's null column must not override it
367
+ if (prop.renamedFrom) {
368
+ lines.push(`${padding} ${this.propName(prop.fieldNames[0], 'mapped')} = true;`);
369
+ defined = `${this.propName(prop.fieldNames[0])} != null`;
370
+ const sharesColumn = meta.props.some(p => p !== prop && p.name === prop.name && p.fieldNames?.[0] === prop.fieldNames[0]);
371
+ // hydrators expect mapped embeddable keys, so a shared object embeddable is mapped only for its own subtypes
372
+ if (sharesColumn && prop.kind === ReferenceKind.EMBEDDED && prop.object && meta.discriminatorMap) {
373
+ const owners = Object.entries(meta.discriminatorMap)
374
+ .filter(([, cls]) => this.#metadata.find(cls)?.properties[prop.name]?.targetMeta === prop.targetMeta)
375
+ .map(([value]) => `${this.propName(meta.discriminatorColumn)} == ${JSON.stringify(value)}`);
376
+ defined += ` && (${owners.join(' || ')})`;
377
+ }
378
+ else if (sharesColumn) {
379
+ // a column shared with a differently typed subtype is left for each subtype's hydrator to convert
380
+ lines.push(`${padding} if (${defined}) {`);
381
+ lines.push(`${padding} ret${this.wrap(prop.name)} = ${this.propName(prop.fieldNames[0])};`);
382
+ lines.push(`${padding} }`);
383
+ continue;
384
+ }
385
+ }
353
386
  if (prop.runtimeType === 'boolean') {
354
- lines.push(`${padding} if (typeof ${this.propName(prop.fieldNames[0])} !== 'undefined') {`);
387
+ lines.push(`${padding} if (${defined}) {`);
355
388
  lines.push(`${padding} ret${this.wrap(prop.name)} = ${this.propName(prop.fieldNames[0])} == null ? ${this.propName(prop.fieldNames[0])} : !!${this.propName(prop.fieldNames[0])};`);
356
389
  lines.push(`${padding} ${this.propName(prop.fieldNames[0], 'mapped')} = true;`);
357
390
  lines.push(`${padding} }`);
358
391
  }
359
392
  else if (prop.runtimeType === 'Date' && !this.#platform.isNumericProperty(prop)) {
360
- lines.push(`${padding} if (typeof ${this.propName(prop.fieldNames[0])} !== 'undefined') {`);
393
+ lines.push(`${padding} if (${defined}) {`);
361
394
  context.set('parseDate', (value) => this.#platform.parseDate(value));
362
395
  parseDate('ret' + this.wrap(prop.name), this.propName(prop.fieldNames[0]), padding);
363
396
  lines.push(`${padding} ${this.propName(prop.fieldNames[0], 'mapped')} = true;`);
364
397
  lines.push(`${padding} }`);
365
398
  }
399
+ else if (prop.customType instanceof DateType) {
400
+ // tedious returns DATE columns as `Date`, map them to the string the entity holds, so the snapshot matches it
401
+ context.set('convertDateToJSValue', (value) => this.#platform.convertDateToJSValue(value));
402
+ lines.push(`${padding} if (${defined}) {`);
403
+ lines.push(`${padding} ret${this.wrap(prop.name)} = ${this.propName(prop.fieldNames[0])} instanceof Date ? convertDateToJSValue(${this.propName(prop.fieldNames[0])}) : ${this.propName(prop.fieldNames[0])};`);
404
+ lines.push(`${padding} ${this.propName(prop.fieldNames[0], 'mapped')} = true;`);
405
+ lines.push(`${padding} }`);
406
+ }
366
407
  else if (prop.kind === ReferenceKind.EMBEDDED && (prop.object || meta.embeddable)) {
367
408
  const idx = this.#tmpIndex++;
368
409
  context.set(`mapEmbeddedResult_${idx}`, (data) => {
@@ -372,13 +413,13 @@ export class EntityComparator {
372
413
  }
373
414
  return item == null ? item : this.getResultMapper(prop.targetMeta)(item);
374
415
  });
375
- lines.push(`${padding} if (typeof ${this.propName(prop.fieldNames[0])} !== 'undefined') {`);
416
+ lines.push(`${padding} if (${defined}) {`);
376
417
  lines.push(`${padding} ret${this.wrap(prop.name)} = ${this.propName(prop.fieldNames[0])} == null ? ${this.propName(prop.fieldNames[0])} : mapEmbeddedResult_${idx}(${this.propName(prop.fieldNames[0])});`);
377
418
  lines.push(`${padding} ${this.propName(prop.fieldNames[0], 'mapped')} = true;`);
378
419
  lines.push(`${padding} }`);
379
420
  }
380
421
  else if (prop.kind !== ReferenceKind.EMBEDDED) {
381
- lines.push(`${padding} if (typeof ${this.propName(prop.fieldNames[0])} !== 'undefined') {`);
422
+ lines.push(`${padding} if (${defined}) {`);
382
423
  lines.push(`${padding} ret${this.wrap(prop.name)} = ${this.propName(prop.fieldNames[0])};`);
383
424
  lines.push(`${padding} ${this.propName(prop.fieldNames[0], 'mapped')} = true;`);
384
425
  lines.push(`${padding} }`);
@@ -420,7 +461,7 @@ export class EntityComparator {
420
461
  lines.push(` for (let k in result) { if (Object.hasOwn(result, k) && !mapped[k] && ret[k] === undefined${knownKeysGuard}) ret[k] = result[k]; }`);
421
462
  const code = `// compiled mapper for entity ${meta.className}\n` +
422
463
  `return function(result) {\n const ret = {};\n${lines.join('\n')}\n return ret;\n}`;
423
- const fnKey = `resultMapper-${meta.uniqueName}`;
464
+ const fnKey = `resultMapper-${meta.compiledName}`;
424
465
  const resultMapper = Utils.createFunction(context, code, this.#config?.get('compiledFunctions'), fnKey);
425
466
  this.#mappers.set(meta, resultMapper);
426
467
  return resultMapper;
@@ -499,11 +540,22 @@ export class EntityComparator {
499
540
  }
500
541
  return true;
501
542
  }
543
+ // a same-named property of a different kind in another polymorphic variant applies only to its own variants
544
+ const guard = (childProp, code) => {
545
+ const variants = prop.targetMeta?.polymorphs?.filter(m => m.properties[childProp.embedded[1]]) ?? [];
546
+ const owners = variants.filter(m => Utils.isSameKind(m.properties[childProp.embedded[1]], childProp));
547
+ if (owners.length === variants.length) {
548
+ return code;
549
+ }
550
+ const discriminator = `entity${[...path, prop.targetMeta.discriminatorColumn].map(k => this.wrap(k)).join('')}`;
551
+ const conds = owners.map(m => `${discriminator} == ${JSON.stringify(m.discriminatorValue)}`);
552
+ return `${padding} if (${conds.join(' || ')}) {\n${code}\n${padding} }`;
553
+ };
554
+ const childProps = meta.props.filter(p => p.embedded?.[0] === prop.name &&
555
+ // object for JSON embeddable
556
+ (p.object || p.persist !== false));
502
557
  ret +=
503
- meta.props
504
- .filter(p => p.embedded?.[0] === prop.name &&
505
- // object for JSON embeddable
506
- (p.object || p.persist !== false))
558
+ childProps
507
559
  .map(childProp => {
508
560
  const childDataKey = meta.embeddable || prop.object ? dataKey + this.wrap(childProp.embedded[1]) : this.wrap(childProp.name);
509
561
  const childEntityKey = [...path, childProp.embedded[1]].map(k => this.wrap(k)).join('');
@@ -526,6 +578,7 @@ export class EntityComparator {
526
578
  }
527
579
  return `${padding} if (${childCond}) ret${childDataKey} = clone(entity${childEntityKey});`;
528
580
  })
581
+ .map((code, i) => guard(childProps[i], code))
529
582
  .join('\n') + `\n`;
530
583
  if (this.shouldSerialize(prop, dataKey)) {
531
584
  return `${ret + padding} ret${dataKey} = cloneEmbeddable(ret${dataKey});\n${padding}}`;
@@ -608,9 +661,24 @@ export class EntityComparator {
608
661
  ret += ` if (discriminator !== undefined) break;\n`;
609
662
  ret += ` __cls${level} = Object.getPrototypeOf(__cls${level});\n`;
610
663
  ret += ` }\n`;
611
- ret += ` const pk = val${level}?.__helper?.__identifier && !val${level}?.__helper?.hasPrimaryKey()\n`;
612
- ret += ` ? val${level}.__helper.__identifier\n`;
613
- ret += ` : toArray(val${level}?.__helper?.getPrimaryKey(true));\n`;
664
+ if (prop.targetKey) {
665
+ // the FK holds the `targetKey` value in the format of the actual target's column
666
+ const targetKey = prop.targetKey;
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
+ });
675
+ ret += ` const pk = ${targetKeyValueKey}(val${level});\n`;
676
+ }
677
+ else {
678
+ ret += ` const pk = val${level}?.__helper?.__identifier && !val${level}?.__helper?.hasPrimaryKey()\n`;
679
+ ret += ` ? val${level}.__helper.__identifier\n`;
680
+ ret += ` : toArray(val${level}?.__helper?.getPrimaryKey(true));\n`;
681
+ }
614
682
  ret += ` ret${dataKey} = new PolymorphicRef(discriminator, pk);\n`;
615
683
  ret += ` }\n`;
616
684
  }
@@ -624,8 +692,8 @@ export class EntityComparator {
624
692
  ret += ` } else if (typeof entity${entityKey} !== 'undefined') {\n`;
625
693
  ret += ` const val${level} = entity${entityKey}${unwrap};\n`;
626
694
  if (targetProp?.customType) {
627
- // If targetKey property has a custom type, convert to database value
628
- const convertorKey = this.registerCustomType(targetProp, context);
695
+ // keyed by the relation name to avoid clashing with a same-named owner prop, the relation itself lacks the custom type with an explicit `columnType`
696
+ const convertorKey = this.registerCustomType({ ...prop, customType: targetProp.customType }, context);
629
697
  ret += ` ret${dataKey} = convertToDatabaseValue_${convertorKey}(val${level}${targetAccess});\n`;
630
698
  }
631
699
  else {
@@ -688,7 +756,7 @@ export class EntityComparator {
688
756
  lines.push(`}`);
689
757
  const code = `// compiled comparator for entity ${meta.className}\n` +
690
758
  `return function(last, current, options) {\n const diff = {};\n${lines.join('\n')}\n return diff;\n}`;
691
- const fnKey = `comparator-${meta.uniqueName}`;
759
+ const fnKey = `comparator-${meta.compiledName}`;
692
760
  const comparator = Utils.createFunction(context, code, this.#config?.get('compiledFunctions'), fnKey);
693
761
  this.#comparators.set(meta, comparator);
694
762
  return comparator;
@@ -35,11 +35,19 @@ export declare class QueryHelper {
35
35
  */
36
36
  static liftGroupOperators<T extends object>(where: Dictionary, meta: EntityMetadata<T>, metadata: MetadataStorage, key?: string): string | undefined;
37
37
  static inlinePrimaryKeyObjects<T extends object>(where: Dictionary, meta: EntityMetadata<T>, metadata: MetadataStorage, key?: string): boolean;
38
+ /**
39
+ * A bare value on a polymorphic relation would be compared to the discriminator column, so PK values are turned
40
+ * into a PK condition instead, e.g. `1` becomes `{ id: 1 }` and `[{ id: 1 }, { id: 2 }]` becomes `{ id: { $in: [1, 2] } }`.
41
+ * Null checks and `[type, id]` tuples keep their meaning.
42
+ */
43
+ private static inlinePolymorphicPrimaryKeys;
38
44
  /** Copies the plain object and array structure of the condition, keeping the leaf values (e.g. entities) by reference. */
39
45
  private static cloneWhere;
40
46
  static processWhere<T extends object>(options: ProcessWhereOptions<T>): FilterQuery<T>;
41
47
  /** @internal Splits a polymorphic target key like `imageable[Article]` into the property and target class names. */
42
48
  static splitPolymorphicKey(key: string): [string, string?];
49
+ /** @internal Resolves the targets of a polymorphic target key like `imageable[Article]` or `imageable[Product,Article]`. */
50
+ static findTargetMetas(prop: EntityProperty | null | undefined, key: string): EntityMetadata[];
43
51
  /** @internal Resolves the target entity of a condition key, including polymorphic target keys like `imageable[Article]`. */
44
52
  static findTargetMeta(prop: EntityProperty | null | undefined, key: string): EntityMetadata | undefined;
45
53
  /**
@@ -48,6 +56,12 @@ export declare class QueryHelper {
48
56
  * when more targets match. The first target alone keeps the regular relation join.
49
57
  */
50
58
  private static splitPolymorphicConditions;
59
+ /**
60
+ * Routes ordering by properties of polymorphic to-one relations to the targets that define them, e.g.
61
+ * `{ imageable: { name: 'asc' } }` becomes `{ 'imageable[Product,Article]': { name: 'asc' } }`, ordered by
62
+ * the first non-null value. Nested relations and formulas are ordered via the first target defining them.
63
+ */
64
+ private static splitPolymorphicOrderBy;
51
65
  /** Property names used in a condition, including those nested in group operators. */
52
66
  private static collectConditionKeys;
53
67
  static getActiveFilters<T>(meta: EntityMetadata<T>, options: FilterOptions | undefined, filters: Dictionary<FilterDef>): FilterDef[];