@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.
@@ -66,7 +66,7 @@ export declare class EntityManager<Driver extends IDatabaseDriver = IDatabaseDri
66
66
  /**
67
67
  * Finds all entities matching your `where` query. You can pass additional options via the `options` parameter.
68
68
  */
69
- find<Entity extends object, Hint extends string = never, Fields extends string = never, Excludes extends string = never, Using extends string = never>(entityName: EntityName<Entity>, where: [Using] extends [never] ? FilterQuery<NoInfer<Entity>> : IndexFilterQuery<NoInfer<Entity>, Using>, options?: FindOptions<Entity, Hint, Fields, Excludes> & {
69
+ find<Entity extends object, Hint extends string = never, Fields extends string = never, Excludes extends string = never, Using extends string = never>(entityName: EntityName<Entity>, where: NoInfer<[Using] extends [never] ? FilterQuery<Entity> : IndexFilterQuery<Entity, Using>>, options?: FindOptions<Entity, Hint, Fields, Excludes> & {
70
70
  using?: Using | Using[];
71
71
  }): Promise<Loaded<Entity, Hint, Fields, Excludes>[]>;
72
72
  /**
@@ -86,11 +86,11 @@ export declare class EntityManager<Driver extends IDatabaseDriver = IDatabaseDri
86
86
  * }
87
87
  * ```
88
88
  */
89
- stream<Entity extends object, Hint extends string = never, Fields extends string = never, Excludes extends string = never, Using extends string = never>(entityName: EntityName<Entity>, options?: WithUsingOptions<StreamOptions<NoInfer<Entity>, Hint, Fields, Excludes>, NoInfer<Entity>, Using>): AsyncIterableIterator<Loaded<Entity, Hint, Fields, Excludes>>;
89
+ stream<Entity extends object, Hint extends string = never, Fields extends string = never, Excludes extends string = never, Using extends string = never>(entityName: EntityName<Entity>, options?: WithUsingOptions<StreamOptions<Entity, Hint, Fields, Excludes>, NoInfer<Entity>, Using>): AsyncIterableIterator<Loaded<Entity, Hint, Fields, Excludes>>;
90
90
  /**
91
91
  * Finds all entities of given type, optionally matching the `where` condition provided in the `options` parameter.
92
92
  */
93
- findAll<Entity extends object, Hint extends string = never, Fields extends string = never, Excludes extends string = never, Using extends string = never>(entityName: EntityName<Entity>, options?: WithUsingOptions<FindAllOptions<NoInfer<Entity>, Hint, Fields, Excludes>, NoInfer<Entity>, Using>): Promise<Loaded<Entity, Hint, Fields, Excludes>[]>;
93
+ findAll<Entity extends object, Hint extends string = never, Fields extends string = never, Excludes extends string = never, Using extends string = never>(entityName: EntityName<Entity>, options?: WithUsingOptions<FindAllOptions<Entity, Hint, Fields, Excludes>, NoInfer<Entity>, Using>): Promise<Loaded<Entity, Hint, Fields, Excludes>[]>;
94
94
  private getPopulateWhere;
95
95
  /**
96
96
  * Registers global filter to this entity manager. Global filters are enabled by default (unless disabled via last parameter).
@@ -163,7 +163,7 @@ export declare class EntityManager<Driver extends IDatabaseDriver = IDatabaseDri
163
163
  * Calls `em.find()` and `em.count()` with the same arguments (where applicable) and returns the results as tuple
164
164
  * where the first element is the array of entities, and the second is the count.
165
165
  */
166
- findAndCount<Entity extends object, Hint extends string = never, Fields extends string = never, Excludes extends string = never, Using extends string = never>(entityName: EntityName<Entity>, where: [Using] extends [never] ? FilterQuery<NoInfer<Entity>> : IndexFilterQuery<NoInfer<Entity>, Using>, options?: FindOptions<Entity, Hint, Fields, Excludes> & {
166
+ findAndCount<Entity extends object, Hint extends string = never, Fields extends string = never, Excludes extends string = never, Using extends string = never>(entityName: EntityName<Entity>, where: NoInfer<[Using] extends [never] ? FilterQuery<Entity> : IndexFilterQuery<Entity, Using>>, options?: FindOptions<Entity, Hint, Fields, Excludes> & {
167
167
  using?: Using | Using[];
168
168
  }): Promise<[Loaded<Entity, Hint, Fields, Excludes>[], number]>;
169
169
  /**
@@ -222,7 +222,7 @@ export declare class EntityManager<Driver extends IDatabaseDriver = IDatabaseDri
222
222
  * }
223
223
  * ```
224
224
  */
225
- findByCursor<Entity extends object, Hint extends string = never, Fields extends string = never, Excludes extends string = never, IncludeCount extends boolean = true, Using extends string = never>(entityName: EntityName<Entity>, options: WithUsingOptions<FindByCursorOptions<NoInfer<Entity>, Hint, Fields, Excludes, IncludeCount>, NoInfer<Entity>, Using>): Promise<Cursor<Entity, Hint, Fields, Excludes, IncludeCount>>;
225
+ findByCursor<Entity extends object, Hint extends string = never, Fields extends string = never, Excludes extends string = never, IncludeCount extends boolean = true, Using extends string = never>(entityName: EntityName<Entity>, options: WithUsingOptions<FindByCursorOptions<Entity, Hint, Fields, Excludes, IncludeCount>, NoInfer<Entity>, Using>): Promise<Cursor<Entity, Hint, Fields, Excludes, IncludeCount>>;
226
226
  /**
227
227
  * Refreshes the persistent state of an entity from the database, overriding any local changes that have not yet been
228
228
  * persisted. Returns the same entity instance (same object reference), but re-hydrated. If the entity is no longer
@@ -238,7 +238,7 @@ export declare class EntityManager<Driver extends IDatabaseDriver = IDatabaseDri
238
238
  /**
239
239
  * Finds first entity matching your `where` query.
240
240
  */
241
- findOne<Entity extends object, Hint extends string = never, Fields extends string = never, Excludes extends string = never, Using extends string = never>(entityName: EntityName<Entity>, where: [Using] extends [never] ? FilterQuery<NoInfer<Entity>> : IndexFilterQuery<NoInfer<Entity>, Using>, options?: FindOneOptions<Entity, Hint, Fields, Excludes> & {
241
+ findOne<Entity extends object, Hint extends string = never, Fields extends string = never, Excludes extends string = never, Using extends string = never>(entityName: EntityName<Entity>, where: NoInfer<[Using] extends [never] ? FilterQuery<Entity> : IndexFilterQuery<Entity, Using>>, options?: FindOneOptions<Entity, Hint, Fields, Excludes> & {
242
242
  using?: Using | Using[];
243
243
  }): Promise<Loaded<Entity, Hint, Fields, Excludes> | null>;
244
244
  /**
@@ -247,7 +247,7 @@ export declare class EntityManager<Driver extends IDatabaseDriver = IDatabaseDri
247
247
  * You can override the factory for creating this method via `options.failHandler` locally
248
248
  * or via `Configuration.findOneOrFailHandler` (`findExactlyOneOrFailHandler` when specifying `strict`) globally.
249
249
  */
250
- findOneOrFail<Entity extends object, Hint extends string = never, Fields extends string = never, Excludes extends string = never, Using extends string = never>(entityName: EntityName<Entity>, where: [Using] extends [never] ? FilterQuery<NoInfer<Entity>> : IndexFilterQuery<NoInfer<Entity>, Using>, options?: FindOneOrFailOptions<Entity, Hint, Fields, Excludes> & {
250
+ findOneOrFail<Entity extends object, Hint extends string = never, Fields extends string = never, Excludes extends string = never, Using extends string = never>(entityName: EntityName<Entity>, where: NoInfer<[Using] extends [never] ? FilterQuery<Entity> : IndexFilterQuery<Entity, Using>>, options?: FindOneOrFailOptions<Entity, Hint, Fields, Excludes> & {
251
251
  using?: Using | Using[];
252
252
  }): Promise<Loaded<Entity, Hint, Fields, Excludes>>;
253
253
  /**
@@ -342,6 +342,8 @@ export declare class EntityManager<Driver extends IDatabaseDriver = IDatabaseDri
342
342
  * Runs your callback wrapped inside a database transaction.
343
343
  */
344
344
  lock<T extends object>(entity: T, lockMode: LockMode, options?: LockOptions | number | Date): Promise<void>;
345
+ /** The data as sent to the driver, a target given only by its PK is looked up in the identity map. */
346
+ private withReferencedValues;
345
347
  /**
346
348
  * Fires native insert query. Calling this has no side effects on the context (identity map).
347
349
  */
@@ -415,6 +417,7 @@ export declare class EntityManager<Driver extends IDatabaseDriver = IDatabaseDri
415
417
  * via second parameter. By default, it will return already loaded entities without modifying them.
416
418
  */
417
419
  merge<Entity extends object>(entityName: EntityName<Entity>, data: EntityData<Entity> | EntityDTO<Entity>, options?: MergeOptions): Entity;
420
+ private mergeData;
418
421
  /**
419
422
  * Creates new instance of given entity and populates it with given data.
420
423
  * The entity constructor will be used unless you provide `{ managed: true }` in the `options` parameter.
package/EntityManager.js CHANGED
@@ -19,6 +19,7 @@ import { TransactionEventBroadcaster } from './events/TransactionEventBroadcaste
19
19
  import { MetadataError, OptimisticLockError, ValidationError } from './errors.js';
20
20
  import { applyPopulateHints, getLoadingStrategy } from './entity/utils.js';
21
21
  import { TransactionManager } from './utils/TransactionManager.js';
22
+ import { scopeCacheKey, stringifyCacheKey } from './cache/cache-key.js';
22
23
  /**
23
24
  * The EntityManager is the central access point to ORM functionality. It is a facade to all different ORM subsystems
24
25
  * such as UnitOfWork, Query Language, and Repository API.
@@ -211,9 +212,14 @@ export class EntityManager {
211
212
  await em.tryFlush(entityName, options);
212
213
  const where = (await em.processWhere(entityName, options.where ?? {}, options, 'read'));
213
214
  validateParams(where);
214
- options.orderBy = options.orderBy || {};
215
- options.populate = (await em.preparePopulate(entityName, options));
216
215
  const meta = this.metadata.get(entityName);
216
+ if (meta.orderBy) {
217
+ options.orderBy = QueryHelper.mergeOrderBy(options.orderBy, meta.orderBy);
218
+ }
219
+ else {
220
+ options.orderBy ??= {};
221
+ }
222
+ options.populate = (await em.preparePopulate(entityName, options));
217
223
  em.validateIndexUsage(meta, options.where ?? {}, options);
218
224
  options = { ...options };
219
225
  // save the original hint value so we know it was infer/all
@@ -554,6 +560,7 @@ export class EntityManager {
554
560
  return;
555
561
  }
556
562
  const ret = options.populate;
563
+ const hasGlobalFilters = Utils.hasObjectKeys(this.config.get('filters')) || Utils.hasObjectKeys(this.#filters);
557
564
  for (const prop of meta.relations) {
558
565
  if (prop.object ||
559
566
  ![ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(prop.kind) ||
@@ -564,20 +571,19 @@ export class EntityManager {
564
571
  }
565
572
  options = { ...options, filters: QueryHelper.mergePropertyFilters(prop.filters, options.filters) };
566
573
  // For polymorphic relations, check all targets for filters (not just the first targetMeta)
574
+ const targets = prop.polymorphic && prop.polymorphTargets?.length ? prop.polymorphTargets : [prop.targetMeta];
575
+ // `applyFilters()` can only return a condition when some filter is registered globally or on the target
576
+ if (!hasGlobalFilters && !targets.some(t => Utils.hasObjectKeys(t.filters))) {
577
+ continue;
578
+ }
567
579
  let hasActiveFilter = false;
568
- if (prop.polymorphic && prop.polymorphTargets?.length) {
569
- for (const targetMeta of prop.polymorphTargets) {
570
- const cond = await this.applyFilters(targetMeta.class, {}, options.filters, 'read', options);
571
- if (!Utils.isEmpty(cond)) {
572
- hasActiveFilter = true;
573
- break;
574
- }
580
+ for (const targetMeta of targets) {
581
+ const cond = await this.applyFilters(targetMeta.class, {}, options.filters, 'read', options);
582
+ if (!Utils.isEmpty(cond)) {
583
+ hasActiveFilter = true;
584
+ break;
575
585
  }
576
586
  }
577
- else {
578
- const cond = await this.applyFilters(prop.targetMeta.class, {}, options.filters, 'read', options);
579
- hasActiveFilter = !Utils.isEmpty(cond);
580
- }
581
587
  if (hasActiveFilter) {
582
588
  const populated = options.populate.filter(({ field }) => field.split(':')[0] === prop.name);
583
589
  let found = false;
@@ -857,6 +863,10 @@ export class EntityManager {
857
863
  return em.lockAndPopulate(meta, entity, where, options);
858
864
  }
859
865
  validateParams(where);
866
+ // before the cache key so cached results share the merged orderBy
867
+ if (meta.orderBy) {
868
+ options.orderBy = QueryHelper.mergeOrderBy(options.orderBy, meta.orderBy);
869
+ }
860
870
  options.populate = (await em.preparePopulate(entityName, options));
861
871
  const cacheKey = em.cacheKey(entityName, options, 'em.findOne', where);
862
872
  const cached = await em.tryCache(entityName, options.cache, cacheKey, options.refresh, true, options.schema);
@@ -962,6 +972,7 @@ export class EntityManager {
962
972
  }
963
973
  const meta = this.metadata.get(entityName);
964
974
  const convertCustomTypes = !Utils.isEntity(data);
975
+ const source = data;
965
976
  let generatedFields = [];
966
977
  if (Utils.isEntity(data)) {
967
978
  entity = data;
@@ -1005,7 +1016,7 @@ export class EntityManager {
1005
1016
  data = em.#comparator.prepareEntity(entity);
1006
1017
  }
1007
1018
  }
1008
- 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), {
1009
1020
  upsert: true,
1010
1021
  convertCustomTypes,
1011
1022
  ...options,
@@ -1165,6 +1176,7 @@ export class EntityManager {
1165
1176
  }
1166
1177
  }
1167
1178
  // the rows are replaced with their processed copies below, keep the caller's array intact
1179
+ const sources = data;
1168
1180
  data = [...data];
1169
1181
  const meta = this.metadata.get(entityName);
1170
1182
  const convertCustomTypes = !Utils.isEntity(data[0]);
@@ -1271,7 +1283,7 @@ export class EntityManager {
1271
1283
  }
1272
1284
  });
1273
1285
  }
1274
- 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)), {
1275
1287
  upsert: true,
1276
1288
  convertCustomTypes,
1277
1289
  ...options,
@@ -1308,7 +1320,7 @@ export class EntityManager {
1308
1320
  // an empty condition identifies no row, it must not turn into a reload condition matching every row
1309
1321
  const getRowUniqueFields = (where) => Utils.isPlainObject(where) && !Utils.hasObjectKeys(where) ? uniqueFields : getUniqueFields(where);
1310
1322
  const platform = this.getPlatform();
1311
- const returning = getOnConflictReturningFields(meta, data[dataIndexes[0]], uniqueFields, options, platform);
1323
+ const returning = getOnConflictReturningFields(meta, allData[0], uniqueFields, options, platform);
1312
1324
  if (options.onConflictWhere && res.rows?.length !== allData.length) {
1313
1325
  returning.push(...meta.comparableProps.filter(p => !p.lazy && !p.embeddable).map(p => p.name));
1314
1326
  }
@@ -1520,6 +1532,10 @@ export class EntityManager {
1520
1532
  options = this.getContext(false).prepareOptions(options);
1521
1533
  await this.getUnitOfWork().lock(entity, { lockMode, ...options });
1522
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
+ }
1523
1539
  /**
1524
1540
  * Fires native insert query. Calling this has no side effects on the context (identity map).
1525
1541
  */
@@ -1547,9 +1563,11 @@ export class EntityManager {
1547
1563
  await em.withSessionContext(options.ctx ?? em.#transactionContext, ctx => em.#unitOfWork.getChangeSetPersister().executeInserts([cs], { ...options, ctx }));
1548
1564
  return cs.getPrimaryKey();
1549
1565
  }
1566
+ const source = data;
1550
1567
  data = QueryHelper.processObjectParams(data);
1551
1568
  validateParams(data, 'insert data');
1552
- 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 }));
1553
1571
  return res.insertId;
1554
1572
  }
1555
1573
  /**
@@ -1629,9 +1647,12 @@ export class EntityManager {
1629
1647
  await em.withSessionContext(options.ctx ?? em.#transactionContext, ctx => em.#unitOfWork.getChangeSetPersister().executeInserts(css, { ...options, ctx }));
1630
1648
  return css.map(cs => cs.getPrimaryKey());
1631
1649
  }
1650
+ const sources = data;
1632
1651
  data = data.map(row => QueryHelper.processObjectParams(row));
1633
1652
  data.forEach(row => validateParams(row, 'insert data'));
1634
- 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 }));
1635
1656
  if (res.insertedIds) {
1636
1657
  return res.insertedIds;
1637
1658
  }
@@ -1644,11 +1665,12 @@ export class EntityManager {
1644
1665
  const em = this.getContext(false);
1645
1666
  options = em.prepareOptions(options);
1646
1667
  await em.processUnionWhere(entityName, options, 'update');
1668
+ const source = data;
1647
1669
  data = QueryHelper.processObjectParams(data);
1648
1670
  where = await em.processWhere(entityName, where, { ...options, convertCustomTypes: false }, 'update');
1649
1671
  validateParams(data, 'update data');
1650
1672
  validateParams(where, 'update condition');
1651
- 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), {
1652
1674
  em,
1653
1675
  ...options,
1654
1676
  ctx,
@@ -1726,12 +1748,7 @@ export class EntityManager {
1726
1748
  validateProperty(prop, data[k], data);
1727
1749
  }
1728
1750
  }
1729
- return this.merge(entityName, data, {
1730
- convertCustomTypes: true,
1731
- refresh: true,
1732
- validate: false,
1733
- ...rest,
1734
- });
1751
+ return this.mergeData(entityName, data, { convertCustomTypes: true, refresh: true, validate: false, ...rest }, true);
1735
1752
  }
1736
1753
  /**
1737
1754
  * Merges given entity to this EntityManager so it becomes managed. You can force refreshing of existing entities
@@ -1741,6 +1758,9 @@ export class EntityManager {
1741
1758
  if (Utils.isEntity(entityName)) {
1742
1759
  return this.merge(entityName.constructor, entityName, data);
1743
1760
  }
1761
+ return this.mergeData(entityName, data, options, false);
1762
+ }
1763
+ mergeData(entityName, data, options, driverData) {
1744
1764
  const em = options.disableContextResolution ? this : this.getContext();
1745
1765
  options = { ...options };
1746
1766
  options.schema ??= em.#schema;
@@ -1752,10 +1772,16 @@ export class EntityManager {
1752
1772
  return entity;
1753
1773
  }
1754
1774
  const dataIsEntity = Utils.isEntity(data);
1775
+ // the factory snapshots a new entity from driver data like `em.find()` does, an empty `visited` skips the re-snapshot
1776
+ const snapshotted = driverData && !entity;
1755
1777
  entity = dataIsEntity
1756
1778
  ? data
1757
1779
  : em.#entityFactory.create(entityName, data, { merge: true, ...options });
1758
- const visited = options.cascade ? undefined : new Set([entity]);
1780
+ const visited = options.cascade ? (snapshotted ? new Set() : undefined) : new Set([entity]);
1781
+ // with `visited` set, the unit of work would skip the explicitly merged entity as if it was a cascaded one
1782
+ if (!options.cascade) {
1783
+ helper(entity).__managed = true;
1784
+ }
1759
1785
  em.#unitOfWork.merge(entity, visited);
1760
1786
  return entity;
1761
1787
  }
@@ -1831,6 +1857,7 @@ export class EntityManager {
1831
1857
  options.populateWhere = this.createPopulateWhere({ ...where }, options);
1832
1858
  options.populateFilter = await this.getJoinedFilters(meta, options);
1833
1859
  validateParams(where);
1860
+ em.validateIndexUsage(meta, where, options);
1834
1861
  delete options.orderBy;
1835
1862
  await em.processUnionWhere(entityName, options, 'read');
1836
1863
  const cacheKey = em.cacheKey(entityName, options, 'em.count', where);
@@ -1990,19 +2017,20 @@ export class EntityManager {
1990
2017
  : options.cloneEventManager
1991
2018
  ? em.eventManager.clone()
1992
2019
  : em.eventManager;
1993
- // we need to allow global context here as forking from global EM is fine
1994
- const allowGlobalContext = em.config.get('allowGlobalContext');
1995
- em.config.set('allowGlobalContext', true);
2020
+ // forking from global EM is fine; toggled directly as `config.set()` also re-syncs env/logger state (hot path)
2021
+ const configOptions = em.config.getAll();
2022
+ const allowGlobalContext = configOptions.allowGlobalContext;
2023
+ configOptions.allowGlobalContext = true;
1996
2024
  const fork = new em.constructor(em.config, em.driver, em.metadata, options.useContext, eventManager);
1997
2025
  fork.setFlushMode(options.flushMode ?? em.#flushMode);
1998
2026
  fork.#disableTransactions =
1999
2027
  options.disableTransactions ?? this.#disableTransactions ?? this.config.get('disableTransactions');
2000
- em.config.set('allowGlobalContext', allowGlobalContext);
2028
+ configOptions.allowGlobalContext = allowGlobalContext;
2001
2029
  if (options.keepTransactionContext) {
2002
2030
  fork.#transactionContext = em.#transactionContext;
2003
2031
  }
2004
2032
  fork.#filters = { ...em.#filters };
2005
- fork.#filterParams = Utils.copy(em.#filterParams);
2033
+ fork.#filterParams = Utils.hasObjectKeys(em.#filterParams) ? Utils.copy(em.#filterParams) : {};
2006
2034
  if (options.session) {
2007
2035
  // the fork's session replaces the parent context, but the copied `rls` filter params must stay consistent with
2008
2036
  // it — re-stage their variables underneath the explicit `session.variables`, which win on any conflict
@@ -2015,7 +2043,8 @@ export class EntityManager {
2015
2043
  else if (em.#sessionContext) {
2016
2044
  fork.#sessionContext = Utils.copy(em.#sessionContext);
2017
2045
  }
2018
- fork.loggerContext = Utils.merge({}, em.loggerContext, options.loggerContext);
2046
+ fork.loggerContext =
2047
+ em.loggerContext || options.loggerContext ? Utils.merge({}, em.loggerContext, options.loggerContext) : {};
2019
2048
  fork.#schema = options.schema ?? em.#schema;
2020
2049
  fork.signal = options.signal ?? em.signal;
2021
2050
  fork.inflightQueryAbortStrategy = options.inflightQueryAbortStrategy ?? em.inflightQueryAbortStrategy;
@@ -2388,7 +2417,17 @@ export class EntityManager {
2388
2417
  }
2389
2418
  let autoRefresh;
2390
2419
  if (options.fields) {
2391
- autoRefresh = options.fields.some(field => !helper(entity).__loadedProperties.has(field));
2420
+ // inline embeddables track only their leaf properties as loaded, not the parent
2421
+ const isLoaded = (prop) => helper(entity).__loadedProperties.has(prop.name) ||
2422
+ (prop.kind === ReferenceKind.EMBEDDED && !prop.object && Object.values(prop.embeddedProps).every(isLoaded));
2423
+ autoRefresh = options.fields.some(field => {
2424
+ const [first, ...rest] = field.split('.');
2425
+ let prop = meta.properties[first];
2426
+ for (const part of rest) {
2427
+ prop = prop?.kind === ReferenceKind.EMBEDDED && !prop.object ? prop.embeddedProps[part] : undefined;
2428
+ }
2429
+ return !prop || !isLoaded(prop);
2430
+ });
2392
2431
  }
2393
2432
  else {
2394
2433
  autoRefresh = meta.comparableProps.some(prop => {
@@ -2458,11 +2497,7 @@ export class EntityManager {
2458
2497
  const em = this.getContext();
2459
2498
  // a named cache key (`config[0]`) discards the computed `key`, which already carries the session context — so
2460
2499
  // scope it here too, otherwise a fork's rows would be served to another session context under the same name
2461
- const cacheKey = Array.isArray(config)
2462
- ? em.#sessionContext
2463
- ? `${config[0]}|${JSON.stringify(em.#sessionContext)}`
2464
- : config[0]
2465
- : JSON.stringify(key);
2500
+ const cacheKey = Array.isArray(config) ? scopeCacheKey(config[0], em.#sessionContext) : stringifyCacheKey(key);
2466
2501
  const cached = await em.#resultCache.get(cacheKey);
2467
2502
  if (!cached) {
2468
2503
  return { key: cacheKey, data: cached };
@@ -2515,7 +2550,7 @@ export class EntityManager {
2515
2550
  await em.#resultCache.remove(cacheKey);
2516
2551
  // named keys are scoped by the session context (see `tryCache`), so clear this context's variant too
2517
2552
  if (em.#sessionContext) {
2518
- await em.#resultCache.remove(`${cacheKey}|${JSON.stringify(em.#sessionContext)}`);
2553
+ await em.#resultCache.remove(scopeCacheKey(cacheKey, em.#sessionContext));
2519
2554
  }
2520
2555
  }
2521
2556
  /**
@@ -0,0 +1,5 @@
1
+ import type { SessionContext } from '../typings.js';
2
+ /** Serializes a result cache or dataloader batch key, telling apart all values a query can contain. */
3
+ export declare function stringifyCacheKey(key: unknown): string;
4
+ /** Scopes a named result cache key by the session context, so rows are not served across session contexts. */
5
+ export declare function scopeCacheKey(name: string, sessionContext?: SessionContext): string;
@@ -0,0 +1,30 @@
1
+ import { isRaw, isSubquery, Raw } from '../utils/RawQueryFragment.js';
2
+ import { Utils } from '../utils/Utils.js';
3
+ // JSON loses RegExp patterns, `raw()` params and `raw()` keys (symbols), and throws on bigints and sub-queries; `this[key]` is the value before `toJSON()`
4
+ function replacer(key, value) {
5
+ const original = isSubquery(this[key]) ? this[key].toRaw() : this[key];
6
+ if (typeof original === 'bigint') {
7
+ return { bigint: original.toString() };
8
+ }
9
+ if (original instanceof RegExp) {
10
+ return { regexp: original.source, flags: original.flags };
11
+ }
12
+ if (isRaw(original)) {
13
+ return { sql: original.sql, params: original.params };
14
+ }
15
+ if (Raw.hasObjectFragments(value)) {
16
+ return Utils.getObjectQueryKeys(value).map(k => [
17
+ Raw.getKnownFragment(k) ?? k,
18
+ value[k],
19
+ ]);
20
+ }
21
+ return value;
22
+ }
23
+ /** Serializes a result cache or dataloader batch key, telling apart all values a query can contain. */
24
+ export function stringifyCacheKey(key) {
25
+ return JSON.stringify(key, replacer);
26
+ }
27
+ /** Scopes a named result cache key by the session context, so rows are not served across session contexts. */
28
+ export function scopeCacheKey(name, sessionContext) {
29
+ return sessionContext ? `${name}|${JSON.stringify(sessionContext)}` : name;
30
+ }
@@ -87,6 +87,8 @@ export declare abstract class DatabaseDriver<C extends Connection> implements ID
87
87
  mapDataToFieldNames(data: Dictionary, stringifyJsonArrays: boolean, properties?: Record<string, EntityProperty>, convertCustomTypes?: boolean, object?: boolean): Dictionary;
88
88
  protected inlineEmbeddables<T extends object>(meta: EntityMetadata<T>, data: T, where?: boolean): void;
89
89
  protected getPrimaryKeyFields<T>(meta: EntityMetadata<T>): string[];
90
+ /** Column a scalar value of the property maps to; a composite FK given as a scalar holds only the target PK, which belongs to the column referencing it. */
91
+ protected getScalarFieldName(prop: EntityProperty): string;
90
92
  protected createReplicas(cb: (c: ConnectionOptions) => C): C[];
91
93
  /** Acquires a pessimistic lock on the given entity. */
92
94
  lockPessimistic<T extends object>(entity: T, options: LockOptions): Promise<void>;
@@ -511,7 +511,7 @@ export class DatabaseDriver {
511
511
  data[k] = raw(sql.replace(/\?/g, '\\?'));
512
512
  }
513
513
  if (prop.fieldNames) {
514
- Utils.renameKey(data, k, prop.fieldNames[0]);
514
+ Utils.renameKey(data, k, this.getScalarFieldName(prop));
515
515
  }
516
516
  });
517
517
  return data;
@@ -580,6 +580,14 @@ export class DatabaseDriver {
580
580
  getPrimaryKeyFields(meta) {
581
581
  return meta.getPrimaryProps().flatMap(pk => pk.fieldNames);
582
582
  }
583
+ /** Column a scalar value of the property maps to; a composite FK given as a scalar holds only the target PK, which belongs to the column referencing it. */
584
+ getScalarFieldName(prop) {
585
+ if (prop.fieldNames.length < 2 || prop.polymorphic || !prop.targetMeta) {
586
+ return prop.fieldNames[0];
587
+ }
588
+ const idx = prop.referencedColumnNames.indexOf(prop.targetMeta.getPrimaryProps()[0]?.fieldNames[0]);
589
+ return prop.fieldNames[idx === -1 ? 0 : idx];
590
+ }
583
591
  createReplicas(cb) {
584
592
  const replicas = this.config.get('replicas', []);
585
593
  const ret = [];
@@ -326,6 +326,8 @@ export interface CountOptions<T extends object, P extends string = never> extend
326
326
  flushMode?: FlushMode | `${FlushMode}`;
327
327
  /** SQL: appended to FROM clause (e.g. `'force index(my_index)'`); MongoDB: index name or spec passed as `hint`. */
328
328
  indexHint?: string | Dictionary;
329
+ /** @see FindOptions.using */
330
+ using?: IndexName<T> | IndexName<T>[];
329
331
  /** sql only */
330
332
  comments?: string | string[];
331
333
  /** sql only */
@@ -109,7 +109,10 @@ export class EntityAssigner {
109
109
  value != null &&
110
110
  !(value instanceof Date) &&
111
111
  (typeof value === 'string' || typeof value === 'number')) {
112
- value = new Date(value);
112
+ const date = new Date(value);
113
+ if (!isNaN(date.getTime())) {
114
+ value = date;
115
+ }
113
116
  }
114
117
  validateProperty(prop, value, entity);
115
118
  return (entity[prop.name] = value);
@@ -1,5 +1,5 @@
1
1
  import type { EntityManager } from '../EntityManager.js';
2
- import { type EntityMetadata, type EntityProperty, type IHydrator } from '../typings.js';
2
+ import { type AnyEntity, type EntityMetadata, type EntityProperty, type IHydrator } from '../typings.js';
3
3
  /**
4
4
  * @internal
5
5
  */
@@ -15,8 +15,8 @@ export declare class EntityHelper {
15
15
  private static defineBaseProperties;
16
16
  /**
17
17
  * Defines getter and setter for every owning side of m:1 and 1:1 relation. This is then used for propagation of
18
- * changes to the inverse side of bi-directional relations. Rest of the properties are also defined this way to
19
- * achieve dirtiness, which is then used for fast checks whether we need to auto-flush because of managed entities.
18
+ * changes to the inverse side of bi-directional relations. Other properties stay plain data properties on the instance,
19
+ * unless the prototype already has an accessor for them (e.g. a getter-only property the hydrator needs to write to).
20
20
  *
21
21
  * First defines a setter on the prototype, once called, actual get/set handlers are registered on the instance rather
22
22
  * than on its prototype. Thanks to this we still have those properties enumerable (e.g. part of `Object.keys(entity)`).
@@ -24,6 +24,11 @@ export declare class EntityHelper {
24
24
  private static defineProperties;
25
25
  static defineCustomInspect<T extends object>(meta: EntityMetadata<T>): void;
26
26
  static defineReferenceProperty<T extends object>(meta: EntityMetadata<T>, prop: EntityProperty<T>, ref: T, hydrator: IHydrator): void;
27
+ /**
28
+ * Returns the database value of the FK pointing to the given entity.
29
+ * @internal
30
+ */
31
+ static getForeignKeyValue(target: AnyEntity, prop: EntityProperty<any>, targetMeta: EntityMetadata): any;
27
32
  static propagate<T extends object>(meta: EntityMetadata<T>, entity: T, owner: T, prop: EntityProperty<T>, value?: T[keyof T & string], old?: T): void;
28
33
  private static propagateOneToOne;
29
34
  static ensurePropagation<T extends object>(entity: T): void;
@@ -98,8 +98,8 @@ export class EntityHelper {
98
98
  }
99
99
  /**
100
100
  * Defines getter and setter for every owning side of m:1 and 1:1 relation. This is then used for propagation of
101
- * changes to the inverse side of bi-directional relations. Rest of the properties are also defined this way to
102
- * achieve dirtiness, which is then used for fast checks whether we need to auto-flush because of managed entities.
101
+ * changes to the inverse side of bi-directional relations. Other properties stay plain data properties on the instance,
102
+ * unless the prototype already has an accessor for them (e.g. a getter-only property the hydrator needs to write to).
103
103
  *
104
104
  * First defines a setter on the prototype, once called, actual get/set handlers are registered on the instance rather
105
105
  * than on its prototype. Thanks to this we still have those properties enumerable (e.g. part of `Object.keys(entity)`).
@@ -122,6 +122,12 @@ export class EntityHelper {
122
122
  if (prop.inherited || prop.primary || prop.accessor || prop.persist === false || prop.embedded || isCollection) {
123
123
  return;
124
124
  }
125
+ const desc = Object.getOwnPropertyDescriptor(meta.prototype, prop.name);
126
+ // a writable placeholder keeps `prop in entity` working, while assignments create plain own properties
127
+ if (!desc?.get && !desc?.set) {
128
+ Object.defineProperty(meta.prototype, prop.name, { value: undefined, writable: true, configurable: true });
129
+ return;
130
+ }
125
131
  Object.defineProperty(meta.prototype, prop.name, {
126
132
  set(val) {
127
133
  Object.defineProperty(this, prop.name, {
@@ -192,7 +198,7 @@ export class EntityHelper {
192
198
  wrapped.__data[prop.name] = Reference.wrapReference(val, prop);
193
199
  // when propagation from inside hydration, we set the FK to the entity data immediately
194
200
  if (val && hydrator.isRunning() && wrapped.__originalEntityData && prop.owner) {
195
- wrapped.__originalEntityData[prop.name] = Utils.getPrimaryKeyValues(wrapped.__data[prop.name], prop.targetMeta, true);
201
+ wrapped.__originalEntityData[prop.name] = EntityHelper.getForeignKeyValue(entity, prop, prop.targetMeta);
196
202
  }
197
203
  EntityHelper.propagate(meta, entity, this, prop, Reference.unwrapReference(val), old);
198
204
  },
@@ -200,6 +206,21 @@ export class EntityHelper {
200
206
  configurable: true,
201
207
  });
202
208
  }
209
+ /**
210
+ * Returns the database value of the FK pointing to the given entity.
211
+ * @internal
212
+ */
213
+ static getForeignKeyValue(target, prop, targetMeta) {
214
+ if (!prop.targetKey) {
215
+ return Utils.getPrimaryKeyValues(target, targetMeta, true, true);
216
+ }
217
+ // with `targetKey`, the FK holds that value instead of the PK
218
+ const value = target[prop.targetKey];
219
+ const customType = targetMeta.properties[prop.targetKey]?.customType;
220
+ return customType
221
+ ? customType.convertToDatabaseValue(value, helper(target).__platform, { mode: 'serialization' })
222
+ : value;
223
+ }
203
224
  static propagate(meta, entity, owner, prop, value, old) {
204
225
  // For polymorphic relations, get bidirectional relations from the actual entity's metadata
205
226
  let bidirectionalRelations;
@@ -73,6 +73,7 @@ export declare class EntityLoader {
73
73
  private initializeCollections;
74
74
  private initializeOneToMany;
75
75
  private initializeManyToMany;
76
+ private initializePartitions;
76
77
  private findChildren;
77
78
  private mergePrimaryCondition;
78
79
  private populateField;