@mikro-orm/core 7.2.9-dev.24 → 7.2.9-dev.25

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.
@@ -417,6 +417,7 @@ export declare class EntityManager<Driver extends IDatabaseDriver = IDatabaseDri
417
417
  * via second parameter. By default, it will return already loaded entities without modifying them.
418
418
  */
419
419
  merge<Entity extends object>(entityName: EntityName<Entity>, data: EntityData<Entity> | EntityDTO<Entity>, options?: MergeOptions): Entity;
420
+ private mergeData;
420
421
  /**
421
422
  * Creates new instance of given entity and populates it with given data.
422
423
  * The entity constructor will be used unless you provide `{ managed: true }` in the `options` parameter.
package/EntityManager.js CHANGED
@@ -560,6 +560,7 @@ export class EntityManager {
560
560
  return;
561
561
  }
562
562
  const ret = options.populate;
563
+ const hasGlobalFilters = Utils.hasObjectKeys(this.config.get('filters')) || Utils.hasObjectKeys(this.#filters);
563
564
  for (const prop of meta.relations) {
564
565
  if (prop.object ||
565
566
  ![ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(prop.kind) ||
@@ -570,20 +571,19 @@ export class EntityManager {
570
571
  }
571
572
  options = { ...options, filters: QueryHelper.mergePropertyFilters(prop.filters, options.filters) };
572
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
+ }
573
579
  let hasActiveFilter = false;
574
- if (prop.polymorphic && prop.polymorphTargets?.length) {
575
- for (const targetMeta of prop.polymorphTargets) {
576
- const cond = await this.applyFilters(targetMeta.class, {}, options.filters, 'read', options);
577
- if (!Utils.isEmpty(cond)) {
578
- hasActiveFilter = true;
579
- break;
580
- }
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;
581
585
  }
582
586
  }
583
- else {
584
- const cond = await this.applyFilters(prop.targetMeta.class, {}, options.filters, 'read', options);
585
- hasActiveFilter = !Utils.isEmpty(cond);
586
- }
587
587
  if (hasActiveFilter) {
588
588
  const populated = options.populate.filter(({ field }) => field.split(':')[0] === prop.name);
589
589
  let found = false;
@@ -1748,12 +1748,7 @@ export class EntityManager {
1748
1748
  validateProperty(prop, data[k], data);
1749
1749
  }
1750
1750
  }
1751
- return this.merge(entityName, data, {
1752
- convertCustomTypes: true,
1753
- refresh: true,
1754
- validate: false,
1755
- ...rest,
1756
- });
1751
+ return this.mergeData(entityName, data, { convertCustomTypes: true, refresh: true, validate: false, ...rest }, true);
1757
1752
  }
1758
1753
  /**
1759
1754
  * Merges given entity to this EntityManager so it becomes managed. You can force refreshing of existing entities
@@ -1763,6 +1758,9 @@ export class EntityManager {
1763
1758
  if (Utils.isEntity(entityName)) {
1764
1759
  return this.merge(entityName.constructor, entityName, data);
1765
1760
  }
1761
+ return this.mergeData(entityName, data, options, false);
1762
+ }
1763
+ mergeData(entityName, data, options, driverData) {
1766
1764
  const em = options.disableContextResolution ? this : this.getContext();
1767
1765
  options = { ...options };
1768
1766
  options.schema ??= em.#schema;
@@ -1774,10 +1772,12 @@ export class EntityManager {
1774
1772
  return entity;
1775
1773
  }
1776
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;
1777
1777
  entity = dataIsEntity
1778
1778
  ? data
1779
1779
  : em.#entityFactory.create(entityName, data, { merge: true, ...options });
1780
- const visited = options.cascade ? undefined : new Set([entity]);
1780
+ const visited = options.cascade ? (snapshotted ? new Set() : undefined) : new Set([entity]);
1781
1781
  em.#unitOfWork.merge(entity, visited);
1782
1782
  return entity;
1783
1783
  }
@@ -2013,19 +2013,20 @@ export class EntityManager {
2013
2013
  : options.cloneEventManager
2014
2014
  ? em.eventManager.clone()
2015
2015
  : em.eventManager;
2016
- // we need to allow global context here as forking from global EM is fine
2017
- const allowGlobalContext = em.config.get('allowGlobalContext');
2018
- em.config.set('allowGlobalContext', true);
2016
+ // forking from global EM is fine; toggled directly as `config.set()` also re-syncs env/logger state (hot path)
2017
+ const configOptions = em.config.getAll();
2018
+ const allowGlobalContext = configOptions.allowGlobalContext;
2019
+ configOptions.allowGlobalContext = true;
2019
2020
  const fork = new em.constructor(em.config, em.driver, em.metadata, options.useContext, eventManager);
2020
2021
  fork.setFlushMode(options.flushMode ?? em.#flushMode);
2021
2022
  fork.#disableTransactions =
2022
2023
  options.disableTransactions ?? this.#disableTransactions ?? this.config.get('disableTransactions');
2023
- em.config.set('allowGlobalContext', allowGlobalContext);
2024
+ configOptions.allowGlobalContext = allowGlobalContext;
2024
2025
  if (options.keepTransactionContext) {
2025
2026
  fork.#transactionContext = em.#transactionContext;
2026
2027
  }
2027
2028
  fork.#filters = { ...em.#filters };
2028
- fork.#filterParams = Utils.copy(em.#filterParams);
2029
+ fork.#filterParams = Utils.hasObjectKeys(em.#filterParams) ? Utils.copy(em.#filterParams) : {};
2029
2030
  if (options.session) {
2030
2031
  // the fork's session replaces the parent context, but the copied `rls` filter params must stay consistent with
2031
2032
  // it — re-stage their variables underneath the explicit `session.variables`, which win on any conflict
@@ -2038,7 +2039,8 @@ export class EntityManager {
2038
2039
  else if (em.#sessionContext) {
2039
2040
  fork.#sessionContext = Utils.copy(em.#sessionContext);
2040
2041
  }
2041
- fork.loggerContext = Utils.merge({}, em.loggerContext, options.loggerContext);
2042
+ fork.loggerContext =
2043
+ em.loggerContext || options.loggerContext ? Utils.merge({}, em.loggerContext, options.loggerContext) : {};
2042
2044
  fork.#schema = options.schema ?? em.#schema;
2043
2045
  fork.signal = options.signal ?? em.signal;
2044
2046
  fork.inflightQueryAbortStrategy = options.inflightQueryAbortStrategy ?? em.inflightQueryAbortStrategy;
@@ -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)`).
@@ -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, {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mikro-orm/core",
3
- "version": "7.2.9-dev.24",
3
+ "version": "7.2.9-dev.25",
4
4
  "description": "TypeScript ORM for Node.js based on Data Mapper, Unit of Work and Identity Map patterns. Supports MongoDB, MySQL, PostgreSQL and SQLite databases as well as usage with vanilla JavaScript.",
5
5
  "keywords": [
6
6
  "data-mapper",
@@ -111,6 +111,10 @@ export class UnitOfWork {
111
111
  });
112
112
  data[key] = prop.customType.convertToDatabaseValue(converted, this.#platform, { key, mode: 'hydration' });
113
113
  }
114
+ // the hydrator assigns this very instance to the entity, an in-place mutation would otherwise go unnoticed
115
+ if (data[key] instanceof Date) {
116
+ data[key] = new Date(data[key]);
117
+ }
114
118
  if (forceUndefined) {
115
119
  if (data[key] === null) {
116
120
  data[key] = undefined;
@@ -557,9 +561,13 @@ export class UnitOfWork {
557
561
  // the referrer's primary key contains the removed entity, so its identity cannot survive the removal
558
562
  this.unsetIdentity(referrer);
559
563
  }
560
- else {
564
+ else if ((prop.inversedBy || prop.mappedBy) && !prop.mapToPk) {
565
+ // relations with an inverse side are backed by `__data` to allow propagation
561
566
  delete helper(referrer).__data[prop.name];
562
567
  }
568
+ else {
569
+ delete referrer[prop.name];
570
+ }
563
571
  }
564
572
  }
565
573
  }
@@ -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.2.9-dev.24';
156
+ static #ORM_VERSION = '7.2.9-dev.25';
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}`;
@@ -919,11 +919,16 @@ export class Utils {
919
919
  }, {});
920
920
  }
921
921
  static getObjectQueryKeys(obj) {
922
- return Reflect.ownKeys(obj).filter(key => {
923
- if (!Object.prototype.propertyIsEnumerable.call(obj, key)) {
924
- return false;
922
+ const keys = Object.keys(obj);
923
+ const symbols = Object.getOwnPropertySymbols(obj);
924
+ if (symbols.length === 0) {
925
+ return keys;
926
+ }
927
+ for (const key of symbols) {
928
+ if (Raw.isKnownFragmentSymbol(key) && Object.prototype.propertyIsEnumerable.call(obj, key)) {
929
+ keys.push(key);
925
930
  }
926
- return typeof key === 'string' || Raw.isKnownFragmentSymbol(key);
927
- });
931
+ }
932
+ return keys;
928
933
  }
929
934
  }