@mikro-orm/core 7.3.0-dev.24 → 7.3.0-dev.26

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.
package/EntityManager.js CHANGED
@@ -569,7 +569,7 @@ export class EntityManager {
569
569
  (parent?.class === prop.targetMeta.root.class && parent.propName === prop.inversedBy)) {
570
570
  continue;
571
571
  }
572
- options = { ...options, filters: QueryHelper.mergePropertyFilters(prop.filters, options.filters) };
572
+ const propOptions = { ...options, filters: QueryHelper.mergePropertyFilters(prop.filters, options.filters) };
573
573
  // For polymorphic relations, check all targets for filters (not just the first targetMeta)
574
574
  const targets = prop.polymorphic && prop.polymorphTargets?.length ? prop.polymorphTargets : [prop.targetMeta];
575
575
  // `applyFilters()` can only return a condition when some filter is registered globally or on the target
@@ -578,7 +578,7 @@ export class EntityManager {
578
578
  }
579
579
  let hasActiveFilter = false;
580
580
  for (const targetMeta of targets) {
581
- const cond = await this.applyFilters(targetMeta.class, {}, options.filters, 'read', options);
581
+ const cond = await this.applyFilters(targetMeta.class, {}, propOptions.filters, 'read', propOptions);
582
582
  if (!Utils.isEmpty(cond)) {
583
583
  hasActiveFilter = true;
584
584
  break;
@@ -611,7 +611,11 @@ export class EntityManager {
611
611
  const targets = prop.polymorphic && prop.polymorphTargets?.length ? prop.polymorphTargets : [prop.targetMeta];
612
612
  for (const targetMeta of targets) {
613
613
  const before = hint.children.length;
614
- await this.autoJoinRefsForFilters(targetMeta, { ...options, populate: hint.children }, { class: meta.root.class, propName: prop.name });
614
+ await this.autoJoinRefsForFilters(targetMeta, {
615
+ ...options,
616
+ populate: hint.children,
617
+ filters: QueryHelper.mergePropertyFilters(prop.filters, options.filters),
618
+ }, { class: meta.root.class, propName: prop.name });
615
619
  // For polymorphic relations, `hint.children` is applied to every polymorph target during
616
620
  // population, so drop any auto-added hint whose field does not exist on every target —
617
621
  // otherwise the shared `:ref` would crash when applied to a target lacking it (GH #7722).
package/README.md CHANGED
@@ -201,6 +201,10 @@ You can find example integrations for some popular frameworks in the [`mikro-orm
201
201
 
202
202
  - [Express + SQLite](https://github.com/mikro-orm/express-js-example-app)
203
203
 
204
+ ## Supported Versions
205
+
206
+ New features and bug fixes land in the latest major version. The previous major version keeps receiving fixes for high and critical severity vulnerabilities for 12 months after the next major is released, and reaches end of life after that. See the [security policy](SECURITY.md) for the current status of each version and for how to report a vulnerability.
207
+
204
208
  ## Contributing
205
209
 
206
210
  Contributions, issues and feature requests are welcome. Please read [CONTRIBUTING.md](CONTRIBUTING.md) for details on the process for submitting pull requests to us.
@@ -97,7 +97,7 @@ export declare class Collection<T extends object, O extends object = object> {
97
97
  /**
98
98
  * @internal
99
99
  */
100
- hydrate(items: T[], forcePropagate?: boolean, partial?: boolean, readonly?: boolean, count?: boolean): void;
100
+ hydrate(items: T[], forcePropagate?: boolean, partial?: boolean, readonly?: boolean, count?: boolean, hydration?: boolean): void;
101
101
  /**
102
102
  * Remove all items from the collection. Note that removing items from collection does not necessarily imply deleting the target entity,
103
103
  * it means we are disconnecting the relation - removing items from collection, not removing entities from database - `Collection.remove()`
@@ -180,9 +180,9 @@ export declare class Collection<T extends object, O extends object = object> {
180
180
  * @internal
181
181
  */
182
182
  set property(prop: EntityProperty);
183
- protected propagate(item: T, method: 'add' | 'remove' | 'takeSnapshot'): void;
183
+ protected propagate(item: T, method: 'add' | 'remove' | 'takeSnapshot', hydration?: boolean): void;
184
184
  protected propagateToInverseSide(item: T, method: 'add' | 'remove' | 'takeSnapshot'): void;
185
- protected propagateToOwningSide(item: T, method: 'add' | 'remove' | 'takeSnapshot'): void;
185
+ protected propagateToOwningSide(item: T, method: 'add' | 'remove' | 'takeSnapshot', hydration?: boolean): void;
186
186
  protected shouldPropagateToCollection(collection: Collection<O, T>, method: 'add' | 'remove' | 'takeSnapshot'): boolean;
187
187
  protected incrementCount(value: number): void;
188
188
  }
@@ -3,6 +3,7 @@ import { MetadataError, ValidationError } from '../errors.js';
3
3
  import { DataloaderType, ReferenceKind } from '../enums.js';
4
4
  import { Reference } from './Reference.js';
5
5
  import { helper, wrap } from './wrap.js';
6
+ import { EntityHelper } from './EntityHelper.js';
6
7
  import { QueryHelper } from '../utils/QueryHelper.js';
7
8
  import { inspect } from '../logging/inspect.js';
8
9
  // Globally registered so the marker survives the CJS/ESM dual-package hazard
@@ -167,7 +168,7 @@ export class Collection {
167
168
  this.cancelOrphanRemoval(unwrapped);
168
169
  return added;
169
170
  }
170
- addItems(items) {
171
+ addItems(items, hydration) {
171
172
  this.validateModification(items);
172
173
  let added = 0;
173
174
  for (const entity of items) {
@@ -177,7 +178,7 @@ export class Collection {
177
178
  this.#items.add(entity);
178
179
  added++;
179
180
  this.#dirty = true;
180
- this.propagate(entity, 'add');
181
+ this.propagate(entity, 'add', hydration);
181
182
  }
182
183
  }
183
184
  return added;
@@ -486,7 +487,7 @@ export class Collection {
486
487
  /**
487
488
  * @internal
488
489
  */
489
- hydrate(items, forcePropagate, partial, readonly, count = true) {
490
+ hydrate(items, forcePropagate, partial, readonly, count = true, hydration) {
490
491
  for (let i = 0; i < this.#items.size; i++) {
491
492
  delete this[i];
492
493
  }
@@ -496,7 +497,7 @@ export class Collection {
496
497
  this.#count = count ? 0 : undefined;
497
498
  // loaded items are not persisted, that would queue an auto-flush of their type on a read-only path
498
499
  const unwrapped = items.map(i => Reference.unwrapReference(i));
499
- this.addItems(unwrapped);
500
+ this.addItems(unwrapped, hydration);
500
501
  this.cancelOrphanRemoval(unwrapped);
501
502
  this.takeSnapshot(forcePropagate);
502
503
  if (readonly) {
@@ -700,12 +701,12 @@ export class Collection {
700
701
  // cannot be typed to `EntityProperty<O, T>` as it causes issues in assignability of `Loaded` type
701
702
  this.#property = prop;
702
703
  }
703
- propagate(item, method) {
704
+ propagate(item, method, hydration) {
704
705
  if (this.property.owner && this.property.inversedBy) {
705
706
  this.propagateToInverseSide(item, method);
706
707
  }
707
708
  else if (!this.property.owner && this.property.mappedBy) {
708
- this.propagateToOwningSide(item, method);
709
+ this.propagateToOwningSide(item, method, hydration);
709
710
  }
710
711
  }
711
712
  propagateToInverseSide(item, method) {
@@ -715,7 +716,7 @@ export class Collection {
715
716
  collection[method](this.owner);
716
717
  }
717
718
  }
718
- propagateToOwningSide(item, method) {
719
+ propagateToOwningSide(item, method, hydration) {
719
720
  const mappedBy = this.property.mappedBy;
720
721
  const collection = item[mappedBy];
721
722
  if (this.property.kind === ReferenceKind.MANY_TO_MANY) {
@@ -740,6 +741,10 @@ export class Collection {
740
741
  // skip if already propagated
741
742
  if (Reference.unwrapReference(item[mappedBy]) !== value) {
742
743
  item[mappedBy] = value;
744
+ // propagation of a loaded relation is not a change, the FK goes straight to the snapshot
745
+ if (hydration && !prop2.mapToPk) {
746
+ EntityHelper.syncSnapshot(item, prop2, this.owner);
747
+ }
743
748
  }
744
749
  }
745
750
  }
@@ -89,7 +89,7 @@ export class EntityAssigner {
89
89
  const wrapped = helper(unwrappedEntity);
90
90
  if (options.updateByPrimaryKey) {
91
91
  const pk = Utils.extractPK(value, prop.targetMeta);
92
- if (pk) {
92
+ if (pk != null) {
93
93
  const ref = options.em.getReference(prop.targetMeta.class, pk, options);
94
94
  // if the PK differs, we want to change the target entity, not update it
95
95
  const wrappedChild = helper(ref);
@@ -193,7 +193,7 @@ export class EntityAssigner {
193
193
  }
194
194
  if (options.updateNestedEntities && options.updateByPrimaryKey && Utils.isPlainObject(item)) {
195
195
  const pk = Utils.extractPK(item, prop.targetMeta);
196
- if (pk && EntityAssigner.validateEM(em)) {
196
+ if (pk != null && EntityAssigner.validateEM(em)) {
197
197
  const ref = em
198
198
  .getUnitOfWork()
199
199
  .getById(prop.targetMeta.class, pk, options.schema, options.convertCustomTypes);
@@ -45,6 +45,8 @@ export declare class EntityFactory {
45
45
  private isNoopMerge;
46
46
  /** Whether hydrating `value` into `prop` would leave `current` as is, mirroring the hydrator's Date and boolean coercion. */
47
47
  private holdsValue;
48
+ /** Whether the owning side of an inverse 1:1 `prop` carries an unflushed change on the given target. */
49
+ private hasPendingOwner;
48
50
  /** Merges new data into an existing entity, preserving user-modified properties. */
49
51
  mergeData<T extends object>(meta: EntityMetadata<T>, entity: T, data: EntityData<T>, options?: FactoryOptions): void;
50
52
  /** Creates or retrieves an uninitialized entity reference by its primary key or alternate key. */
@@ -186,6 +186,18 @@ export class EntityFactory {
186
186
  }
187
187
  return current === value;
188
188
  }
189
+ /** Whether the owning side of an inverse 1:1 `prop` carries an unflushed change on the given target. */
190
+ hasPendingOwner(target, prop) {
191
+ // a reference gets its owning side set during hydration, that is not a change
192
+ if (!target || !helper(target).__initialized) {
193
+ return false;
194
+ }
195
+ const owner = target[prop.mappedBy];
196
+ const fk = Utils.isEntity(owner, true)
197
+ ? Utils.getPrimaryKeyValues(Reference.unwrapReference(owner), prop.targetMeta.properties[prop.mappedBy].targetMeta, true, true)
198
+ : owner;
199
+ return !Utils.equals(fk ?? null, helper(target).__originalEntityData?.[prop.mappedBy] ?? null);
200
+ }
189
201
  /** Merges new data into an existing entity, preserving user-modified properties. */
190
202
  mergeData(meta, entity, data, options = {}) {
191
203
  // joined rows often repeat exactly what the entity already holds, skip the snapshot and diffing then
@@ -210,6 +222,18 @@ export class EntityFactory {
210
222
  }
211
223
  });
212
224
  }
225
+ // inverse 1:1 sides are not snapshotted, their pending changes are visible only on the owning side
226
+ Utils.keys(diff2)
227
+ .filter(key => meta.properties[key].kind === ReferenceKind.ONE_TO_ONE && !meta.properties[key].owner)
228
+ .filter(key => {
229
+ const prop = meta.properties[key];
230
+ const current = entity[key] ? Reference.unwrapReference(entity[key]) : undefined;
231
+ const loaded = Utils.isPlainObject(diff2[key])
232
+ ? this.findEntity(diff2[key], prop.targetMeta, options)
233
+ : undefined;
234
+ return this.hasPendingOwner(current, prop) || (loaded !== current && this.hasPendingOwner(loaded, prop));
235
+ })
236
+ .forEach(key => delete diff2[key]);
213
237
  Utils.keys(diff2)
214
238
  .filter(key => {
215
239
  // ignore null values if there is already present non-null value
@@ -1,5 +1,5 @@
1
1
  import type { EntityManager } from '../EntityManager.js';
2
- import { type AnyEntity, type EntityMetadata, type EntityProperty, type IHydrator } from '../typings.js';
2
+ import { type AnyEntity, type EntityMetadata, type EntityProperty } from '../typings.js';
3
3
  /**
4
4
  * @internal
5
5
  */
@@ -23,7 +23,12 @@ export declare class EntityHelper {
23
23
  */
24
24
  private static defineProperties;
25
25
  static defineCustomInspect<T extends object>(meta: EntityMetadata<T>): void;
26
- static defineReferenceProperty<T extends object>(meta: EntityMetadata<T>, prop: EntityProperty<T>, ref: T, hydrator: IHydrator): void;
26
+ static defineReferenceProperty<T extends object>(meta: EntityMetadata<T>, prop: EntityProperty<T>, ref: T): void;
27
+ /**
28
+ * Stores the FK of a relation set during hydration in the snapshot of its owning side, so it is not seen as a change.
29
+ * @internal
30
+ */
31
+ static syncSnapshot(owner: AnyEntity, prop: EntityProperty<any>, target: AnyEntity): void;
27
32
  /**
28
33
  * Returns the database value of the FK pointing to the given entity.
29
34
  * @internal
@@ -86,7 +86,7 @@ export class EntityHelper {
86
86
  __helper: {
87
87
  get() {
88
88
  Object.defineProperty(this, '__helper', {
89
- value: new WrappedEntity(this, em.getHydrator(), ...helperParams),
89
+ value: new WrappedEntity(this, ...helperParams),
90
90
  enumerable: false,
91
91
  configurable: true,
92
92
  });
@@ -112,7 +112,7 @@ export class EntityHelper {
112
112
  if (isReference) {
113
113
  Object.defineProperty(meta.prototype, prop.name, {
114
114
  set(val) {
115
- EntityHelper.defineReferenceProperty(meta, prop, this, em.getHydrator());
115
+ EntityHelper.defineReferenceProperty(meta, prop, this);
116
116
  this[prop.name] = val;
117
117
  },
118
118
  configurable: true,
@@ -182,7 +182,7 @@ export class EntityHelper {
182
182
  return ret === '[Object]' ? `[${name}]` : name + ' ' + ret;
183
183
  };
184
184
  }
185
- static defineReferenceProperty(meta, prop, ref, hydrator) {
185
+ static defineReferenceProperty(meta, prop, ref) {
186
186
  const wrapped = helper(ref);
187
187
  Object.defineProperty(ref, prop.name, {
188
188
  get() {
@@ -196,16 +196,23 @@ export class EntityHelper {
196
196
  old[prop.inversedBy].removeWithoutPropagation(this);
197
197
  }
198
198
  wrapped.__data[prop.name] = Reference.wrapReference(val, prop);
199
- // when propagation from inside hydration, we set the FK to the entity data immediately
200
- if (val && hydrator.isRunning() && wrapped.__originalEntityData && prop.owner) {
201
- wrapped.__originalEntityData[prop.name] = EntityHelper.getForeignKeyValue(entity, prop, prop.targetMeta);
202
- }
203
199
  EntityHelper.propagate(meta, entity, this, prop, Reference.unwrapReference(val), old);
204
200
  },
205
201
  enumerable: true,
206
202
  configurable: true,
207
203
  });
208
204
  }
205
+ /**
206
+ * Stores the FK of a relation set during hydration in the snapshot of its owning side, so it is not seen as a change.
207
+ * @internal
208
+ */
209
+ static syncSnapshot(owner, prop, target) {
210
+ const snapshot = helper(owner).__originalEntityData;
211
+ const targetMeta = prop.targetMeta ?? helper(target)?.__meta;
212
+ if (snapshot && targetMeta) {
213
+ snapshot[prop.name] = EntityHelper.getForeignKeyValue(target, prop, targetMeta);
214
+ }
215
+ }
209
216
  /**
210
217
  * Returns the database value of the FK pointing to the given entity.
211
218
  * @internal
@@ -1,6 +1,6 @@
1
1
  import type { PopulatePath } from '../enums.js';
2
2
  import type { EntityManager } from '../EntityManager.js';
3
- import type { Dictionary, EntityData, EntityDictionary, EntityMetadata, IHydrator, EntityKey, PopulateOptions, Primary, AutoPath, Ref, AddEager, LoadedReference, EntityDTO, Loaded, ExtractFieldsHint, ResolveSerializeFields, SerializeDTO, SerializeFieldsKeepPK, FromEntityType, IsSubset, MergeSelected } from '../typings.js';
3
+ import type { Dictionary, EntityData, EntityDictionary, EntityMetadata, EntityKey, PopulateOptions, Primary, AutoPath, Ref, AddEager, LoadedReference, EntityDTO, Loaded, ExtractFieldsHint, ResolveSerializeFields, SerializeDTO, SerializeFieldsKeepPK, FromEntityType, IsSubset, MergeSelected } from '../typings.js';
4
4
  import { Reference } from './Reference.js';
5
5
  import { type AssignOptions } from './EntityAssigner.js';
6
6
  import type { EntityLoaderOptions } from './EntityLoader.js';
@@ -36,11 +36,10 @@ export declare class WrappedEntity<Entity extends object> {
36
36
  /** holds wrapped primary key, so we can compute change set without eager commit */
37
37
  __identifier?: EntityIdentifier;
38
38
  private readonly entity;
39
- private readonly hydrator;
40
39
  private readonly pkGetter?;
41
40
  private readonly pkSerializer?;
42
41
  private readonly pkGetterConverted?;
43
- constructor(entity: Entity, hydrator: IHydrator, pkGetter?: (e: Entity) => Primary<Entity>, pkSerializer?: (e: Entity) => string, pkGetterConverted?: (e: Entity) => Primary<Entity>);
42
+ constructor(entity: Entity, pkGetter?: (e: Entity) => Primary<Entity>, pkSerializer?: (e: Entity) => string, pkGetterConverted?: (e: Entity) => Primary<Entity>);
44
43
  /** Returns whether the entity has been fully loaded from the database. */
45
44
  isInitialized(): boolean;
46
45
  /** Returns whether the entity is managed by an EntityManager (tracked in the identity map). */
@@ -8,9 +8,8 @@ import { EntitySerializer } from '../serialization/EntitySerializer.js';
8
8
  import { expandDotPaths } from './utils.js';
9
9
  /** @internal Wrapper attached to every managed entity, holding ORM state such as initialization flags, identity map references, and change tracking snapshots. */
10
10
  export class WrappedEntity {
11
- constructor(entity, hydrator, pkGetter, pkSerializer, pkGetterConverted) {
11
+ constructor(entity, pkGetter, pkSerializer, pkGetterConverted) {
12
12
  this.entity = entity;
13
- this.hydrator = hydrator;
14
13
  this.pkGetter = pkGetter;
15
14
  this.pkSerializer = pkSerializer;
16
15
  this.pkGetterConverted = pkGetterConverted;
@@ -8,7 +8,6 @@ export declare abstract class Hydrator implements IHydrator {
8
8
  protected readonly metadata: MetadataStorage;
9
9
  protected readonly platform: Platform;
10
10
  protected readonly config: Configuration;
11
- protected running: boolean;
12
11
  constructor(metadata: MetadataStorage, platform: Platform, config: Configuration);
13
12
  /**
14
13
  * @inheritDoc
@@ -18,8 +17,6 @@ export declare abstract class Hydrator implements IHydrator {
18
17
  * @inheritDoc
19
18
  */
20
19
  hydrateReference<T extends object>(entity: T, meta: EntityMetadata<T>, data: EntityData<T>, factory: EntityFactory, convertCustomTypes?: boolean, schema?: string, parentSchema?: string): void;
21
- /** Returns whether the hydrator is currently in the middle of hydrating an entity. */
22
- isRunning(): boolean;
23
20
  protected getProperties<T extends object>(meta: EntityMetadata<T>, type: 'full' | 'reference'): EntityProperty<T>[];
24
21
  protected hydrateProperty<T extends object>(entity: T, prop: EntityProperty<T>, data: EntityData<T>, factory: EntityFactory, newEntity?: boolean, convertCustomTypes?: boolean): void;
25
22
  }
@@ -4,7 +4,6 @@ export class Hydrator {
4
4
  metadata;
5
5
  platform;
6
6
  config;
7
- running = false;
8
7
  constructor(metadata, platform, config) {
9
8
  this.metadata = metadata;
10
9
  this.platform = platform;
@@ -14,28 +13,18 @@ export class Hydrator {
14
13
  * @inheritDoc
15
14
  */
16
15
  hydrate(entity, meta, data, factory, type, newEntity = false, convertCustomTypes = false, schema, parentSchema) {
17
- // the running state is used to consider propagation as hydration, saving the values directly to the entity data,
18
- // but we don't want that for new entities, their propagation should result in entity updates when flushing
19
- this.running = !newEntity;
20
16
  const props = this.getProperties(meta, type);
21
17
  for (const prop of props) {
22
18
  this.hydrateProperty(entity, prop, data, factory, newEntity, convertCustomTypes);
23
19
  }
24
- this.running = false;
25
20
  }
26
21
  /**
27
22
  * @inheritDoc
28
23
  */
29
24
  hydrateReference(entity, meta, data, factory, convertCustomTypes, schema, parentSchema) {
30
- this.running = true;
31
25
  meta.primaryKeys.forEach(pk => {
32
26
  this.hydrateProperty(entity, meta.properties[pk], data, factory, false, convertCustomTypes);
33
27
  });
34
- this.running = false;
35
- }
36
- /** Returns whether the hydrator is currently in the middle of hydrating an entity. */
37
- isRunning() {
38
- return this.running;
39
28
  }
40
29
  getProperties(meta, type) {
41
30
  if (type === 'reference') {
@@ -23,22 +23,14 @@ export class ObjectHydrator extends Hydrator {
23
23
  */
24
24
  hydrate(entity, meta, data, factory, type, newEntity = false, convertCustomTypes = false, schema, parentSchema, normalizeAccessors) {
25
25
  const hydrate = this.getEntityHydrator(meta, type, normalizeAccessors);
26
- const running = this.running;
27
- // the running state is used to consider propagation as hydration, saving the values directly to the entity data,
28
- // but we don't want that for new entities, their propagation should result in entity updates when flushing
29
- this.running = !newEntity;
30
26
  Utils.callCompiledFunction(hydrate, entity, data, factory, newEntity, convertCustomTypes, schema, parentSchema, normalizeAccessors);
31
- this.running = running;
32
27
  }
33
28
  /**
34
29
  * @inheritDoc
35
30
  */
36
31
  hydrateReference(entity, meta, data, factory, convertCustomTypes = false, schema, parentSchema, normalizeAccessors) {
37
32
  const hydrate = this.getEntityHydrator(meta, 'reference', normalizeAccessors);
38
- const running = this.running;
39
- this.running = true;
40
33
  Utils.callCompiledFunction(hydrate, entity, data, factory, false, convertCustomTypes, schema, parentSchema, normalizeAccessors);
41
- this.running = running;
42
34
  }
43
35
  /**
44
36
  * @internal Highly performance-sensitive method.
@@ -210,6 +202,25 @@ export class ObjectHydrator extends Hydrator {
210
202
  ret.push(` }`);
211
203
  }
212
204
  }
205
+ // propagation of a loaded relation is not a change, the FK goes straight to the snapshot of the owning side
206
+ const prop2 = prop.targetMeta?.properties[prop.mappedBy];
207
+ const owner = prop.owner ? prop : prop2;
208
+ if ((prop.inversedBy || prop.mappedBy) && !prop.mapToPk && owner?.owner && !owner.mapToPk) {
209
+ const ownerKey = this.safeKey(`prop_${owner.name}_${this.#tmpIndex++}`);
210
+ context.set(ownerKey, owner);
211
+ context.set('syncSnapshot', EntityHelper.syncSnapshot);
212
+ ret.push(` if (!newEntity && data${dataKey} != null && entity${entityKey}) {`);
213
+ if (prop.owner) {
214
+ ret.push(` syncSnapshot(entity, ${ownerKey}, Reference.unwrapReference(entity${entityKey}));`);
215
+ }
216
+ else {
217
+ ret.push(` const target = Reference.unwrapReference(entity${entityKey});`);
218
+ ret.push(` if (Reference.unwrapReference(target${this.wrap(owner.name)}) === entity) {`);
219
+ ret.push(` syncSnapshot(target, ${ownerKey}, entity);`);
220
+ ret.push(` }`);
221
+ }
222
+ ret.push(` }`);
223
+ }
213
224
  if (prop.customType?.ensureComparable(meta, prop)) {
214
225
  registerCustomType(prop, this.safeKey(prop.name), 'convertToDatabaseValue', context);
215
226
  ret.push(` if (data${dataKey} != null && typeof data${dataKey} !== 'object' && convertCustomTypes) {`);
@@ -230,7 +241,7 @@ export class ObjectHydrator extends Hydrator {
230
241
  ret.push(` Collection.create(entity, ${this.quote(prop.name)}, items, true).setDirty();`);
231
242
  ret.push(` } else {`);
232
243
  // loaded items go through `hydrate()`, as `set()` would persist them and queue an auto-flush; the count stays unset, joined results can be filtered
233
- ret.push(` Collection.create(entity, ${this.quote(prop.name)}, undefined, false).hydrate(items, true, false, false, false);`);
244
+ ret.push(` Collection.create(entity, ${this.quote(prop.name)}, undefined, false).hydrate(items, true, false, false, false, true);`);
234
245
  ret.push(` }`);
235
246
  ret.push(` } else if (!entity${entityKey} && data${dataKey} instanceof Collection) {`);
236
247
  ret.push(` entity${entityKey} = data${dataKey};`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mikro-orm/core",
3
- "version": "7.3.0-dev.24",
3
+ "version": "7.3.0-dev.26",
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",
@@ -629,7 +629,10 @@ export class Platform {
629
629
  pos = idx + 2;
630
630
  }
631
631
  else {
632
- ret += sql.substring(pos, idx) + this.quoteValue(params[j++]);
632
+ const value = this.quoteValue(params[j++]);
633
+ // a negative value right after a minus would otherwise form a `--` line comment
634
+ const gap = sql[idx - 1] === '-' && String(value).startsWith('-') ? ' ' : '';
635
+ ret += sql.substring(pos, idx) + gap + value;
633
636
  pos = idx + 1;
634
637
  }
635
638
  }
@@ -1,7 +1,7 @@
1
1
  import { Type } from './Type.js';
2
2
  import type { Platform } from '../platforms/Platform.js';
3
3
  import type { EntityProperty } from '../typings.js';
4
- /** Maps a database TIME column to a JS `string` in HH:MM:SS format. */
4
+ /** Maps a database TIME column to a JS `string` in HH:MM:SS format with optional fractional seconds. */
5
5
  export declare class TimeType extends Type<string | null | undefined, string | null | undefined> {
6
6
  convertToDatabaseValue(value: string | null | undefined, platform: Platform): string | null | undefined;
7
7
  compareAsType(): string;
package/types/TimeType.js CHANGED
@@ -1,9 +1,9 @@
1
1
  import { Type } from './Type.js';
2
2
  import { ValidationError } from '../errors.js';
3
- /** Maps a database TIME column to a JS `string` in HH:MM:SS format. */
3
+ /** Maps a database TIME column to a JS `string` in HH:MM:SS format with optional fractional seconds. */
4
4
  export class TimeType extends Type {
5
5
  convertToDatabaseValue(value, platform) {
6
- if (value && !/^\d{2,}:(?:[0-5]\d):(?:[0-5]\d)$/.test(value)) {
6
+ if (value && !/^\d{2,}:(?:[0-5]\d):(?:[0-5]\d)(?:\.\d+)?$/.test(value)) {
7
7
  throw ValidationError.invalidType(TimeType, value, 'JS');
8
8
  }
9
9
  return super.convertToDatabaseValue(value, platform);
package/typings.d.ts CHANGED
@@ -428,7 +428,6 @@ export interface IWrappedEntityInternal<Entity extends object> extends IWrappedE
428
428
  __platform: Platform;
429
429
  __config: Configuration;
430
430
  __factory: EntityFactory;
431
- __hydrator: IHydrator;
432
431
  __initialized: boolean;
433
432
  __originalEntityData?: EntityData<Entity>;
434
433
  __loadedProperties: Set<string>;
@@ -1758,7 +1757,6 @@ export interface IHydrator {
1758
1757
  * Hydrates primary keys only
1759
1758
  */
1760
1759
  hydrateReference<T extends object>(entity: T, meta: EntityMetadata<T>, data: EntityData<T>, factory: EntityFactory, convertCustomTypes?: boolean, schema?: string, parentSchema?: string, normalizeAccessors?: boolean): void;
1761
- isRunning(): boolean;
1762
1760
  }
1763
1761
  /** Constructor signature for hydrator implementations. */
1764
1762
  export interface HydratorConstructor {
package/typings.js CHANGED
@@ -1,7 +1,6 @@
1
1
  import { ReferenceKind, } from './enums.js';
2
2
  import { Reference } from './entity/Reference.js';
3
3
  import { EntityHelper } from './entity/EntityHelper.js';
4
- import { helper } from './entity/wrap.js';
5
4
  import { Utils } from './utils/Utils.js';
6
5
  import { EntityComparator } from './utils/EntityComparator.js';
7
6
  /** Symbol used to declare a custom repository type on an entity class (e.g., `[EntityRepositoryType]?: BookRepository`). */
@@ -279,7 +278,6 @@ export class EntityMetadata {
279
278
  },
280
279
  set(val) {
281
280
  const wrapped = this.__helper;
282
- const hydrator = wrapped.hydrator;
283
281
  const entity = Reference.unwrapReference(val ?? wrapped.__data[prop.name]);
284
282
  const old = Reference.unwrapReference(wrapped.__data[prop.name]);
285
283
  if (old &&
@@ -290,13 +288,6 @@ export class EntityMetadata {
290
288
  old[prop.inversedBy].removeWithoutPropagation(this);
291
289
  }
292
290
  wrapped.__data[prop.name] = Reference.wrapReference(val, prop);
293
- // when propagation from inside hydration, we set the FK to the entity data immediately
294
- if (val && hydrator.isRunning() && wrapped.__originalEntityData && prop.owner) {
295
- const targetMeta = prop.targetMeta ?? helper(entity)?.__meta;
296
- if (targetMeta) {
297
- wrapped.__originalEntityData[prop.name] = EntityHelper.getForeignKeyValue(entity, prop, targetMeta);
298
- }
299
- }
300
291
  EntityHelper.propagate(meta, entity, this, prop, Reference.unwrapReference(val), old);
301
292
  },
302
293
  enumerable: true,
@@ -320,11 +320,10 @@ export class UnitOfWork {
320
320
  cs.type = type;
321
321
  }
322
322
  this.initIdentifier(entity);
323
- if (wrapped.__meta.inheritanceType === 'tpt' && wrapped.__meta.tptParent) {
324
- this.createTPTChangeSets(entity, cs);
325
- }
326
- else {
327
- this.#changeSets.set(entity, cs);
323
+ const isTPT = wrapped.__meta.inheritanceType === 'tpt' && wrapped.__meta.tptParent;
324
+ const leafCs = isTPT ? this.createTPTChangeSets(entity, cs) : cs;
325
+ if (leafCs) {
326
+ this.#changeSets.set(entity, leafCs);
328
327
  }
329
328
  this.#persistStack.delete(entity);
330
329
  wrapped.__originalEntityData = this.#comparator.prepareEntity(entity);
@@ -678,7 +677,7 @@ export class UnitOfWork {
678
677
  if (!props.some(prop => prop.name in changeSet.payload)) {
679
678
  return;
680
679
  }
681
- for (const cs of this.#changeSets.values()) {
680
+ const check = (cs) => {
682
681
  for (const prop of props) {
683
682
  if (prop.name in cs.payload && cs.rootMeta === changeSet.rootMeta && cs.type === changeSet.type) {
684
683
  conflicts = true;
@@ -687,6 +686,11 @@ export class UnitOfWork {
687
686
  }
688
687
  }
689
688
  }
689
+ };
690
+ for (const cs of this.#changeSets.values()) {
691
+ check(cs);
692
+ // TPT parent table change sets are not in the map, only attached to the leaf one
693
+ cs.tptChangeSets?.forEach(check);
690
694
  }
691
695
  if (!conflicts) {
692
696
  return;
@@ -752,11 +756,10 @@ export class UnitOfWork {
752
756
  const changeSet = this.#changeSetComputer.computeChangeSet(entity);
753
757
  if (changeSet && !this.checkUniqueProps(changeSet)) {
754
758
  // For TPT child entities, create changesets for each table in hierarchy
755
- if (wrapped.__meta.inheritanceType === 'tpt' && wrapped.__meta.tptParent) {
756
- this.createTPTChangeSets(entity, changeSet);
757
- }
758
- else {
759
- this.#changeSets.set(entity, changeSet);
759
+ const isTPT = wrapped.__meta.inheritanceType === 'tpt' && wrapped.__meta.tptParent;
760
+ const leafCs = isTPT ? this.createTPTChangeSets(entity, changeSet) : changeSet;
761
+ if (leafCs) {
762
+ this.#changeSets.set(entity, leafCs);
760
763
  }
761
764
  }
762
765
  }
@@ -808,13 +811,11 @@ export class UnitOfWork {
808
811
  leafCs = new ChangeSet(entity, originalChangeSet.type, {}, meta);
809
812
  leafCs.originalEntity = originalChangeSet.originalEntity;
810
813
  }
811
- // Store the leaf changeset in the main map (entity as key), with parent CSs attached
812
- if (leafCs) {
813
- if (parentChangeSets.length > 0) {
814
- leafCs.tptChangeSets = parentChangeSets;
815
- }
816
- this.#changeSets.set(entity, leafCs);
814
+ // parent table change sets are not registered on their own, only attached to the leaf one
815
+ if (leafCs && parentChangeSets.length > 0) {
816
+ leafCs.tptChangeSets = parentChangeSets;
817
817
  }
818
+ return leafCs;
818
819
  }
819
820
  /**
820
821
  * Returns `true` when the change set should be skipped as it will be empty after the extra update.
@@ -1244,8 +1245,15 @@ export class UnitOfWork {
1244
1245
  extraUpdate[0][extraUpdate[1]] = extraUpdate[2];
1245
1246
  }
1246
1247
  const changeSet = this.#changeSetComputer.computeChangeSet(extraUpdate[0]);
1247
- if (changeSet) {
1248
- extraUpdates.push([changeSet, extraUpdate[3]]);
1248
+ if (!changeSet) {
1249
+ continue;
1250
+ }
1251
+ const isTPT = changeSet.meta.inheritanceType === 'tpt' && changeSet.meta.tptParent;
1252
+ const leafCs = isTPT ? this.createTPTChangeSets(extraUpdate[0], changeSet) : changeSet;
1253
+ for (const cs of [leafCs, ...(leafCs.tptChangeSets ?? [])]) {
1254
+ if (Utils.hasObjectKeys(cs.payload) || cs.meta.hasOptimisticLock()) {
1255
+ extraUpdates.push([cs, extraUpdate[3]]);
1256
+ }
1249
1257
  }
1250
1258
  }
1251
1259
  await this.commitUpdateChangeSets(extraUpdates.map(u => u[0]), ctx, false);
@@ -1352,7 +1360,14 @@ export class UnitOfWork {
1352
1360
  calc.discoverProperty(prop, meta._id);
1353
1361
  // 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
1354
1362
  for (const targetMeta of this.#metadata.find(prop.targetMeta.class).allTPTDescendants ?? []) {
1355
- calc.discoverProperty({ ...prop, targetMeta, nullable: true }, meta._id);
1363
+ let parent = targetMeta.tptParent;
1364
+ while (parent && parent._id !== meta._id && metaById.has(parent._id)) {
1365
+ parent = parent.tptParent;
1366
+ }
1367
+ // an own subclass linked via scheduled parent tables already goes after this one, an edge back would be a cycle
1368
+ if (parent?._id !== meta._id) {
1369
+ calc.discoverProperty({ ...prop, targetMeta, nullable: true }, meta._id);
1370
+ }
1356
1371
  }
1357
1372
  }
1358
1373
  else {
@@ -29,11 +29,10 @@ export declare class DataloaderUtils {
29
29
  */
30
30
  static entitiesAndOptsMapToQueries(entitiesAndOptsMap: Map<string, Map<string, Set<Primary<any>>>>, em: EntityManager): Promise<[string, any[]]>[];
31
31
  /**
32
- * Creates a filter which returns the results pertaining to a certain collection.
33
- * First checks if the Entity type matches, then retrieves the inverse side of the relationship
34
- * where the filtering will be done in order to match the target collection.
32
+ * Groups the results of a query by the entities found on their inverse side property,
33
+ * so each collection can pick its items without scanning all the results.
35
34
  */
36
- static getColFilter<T, S extends T>(collection: Collection<any>): (result: T) => result is S;
35
+ static groupByOwner<T extends object>(entities: T[], inverseProp: string): Map<object, T[]>;
37
36
  /**
38
37
  * Returns the 1:M collection dataloader batchLoadFn, which aggregates collections by entity,
39
38
  * makes one query per entity and maps each input collection to the corresponding result.
@@ -143,29 +143,25 @@ export class DataloaderUtils {
143
143
  });
144
144
  }
145
145
  /**
146
- * Creates a filter which returns the results pertaining to a certain collection.
147
- * First checks if the Entity type matches, then retrieves the inverse side of the relationship
148
- * where the filtering will be done in order to match the target collection.
146
+ * Groups the results of a query by the entities found on their inverse side property,
147
+ * so each collection can pick its items without scanning all the results.
149
148
  */
150
- static getColFilter(collection) {
151
- return (result) => {
152
- // There is no need to check if Entity matches because we already matched the key which is entity+options.
153
- // This is the inverse side of the relationship where the filtering will be done in order to match the target collection
154
- // Either inversedBy or mappedBy exist because we already checked in groupInversedOrMappedKeysByEntity
155
- const inverseProp = collection.property.inversedBy ?? collection.property.mappedBy;
156
- const target = Reference.unwrapReference(result[inverseProp]);
157
- if (target instanceof Collection) {
158
- for (const item of target) {
159
- if (item === collection.owner) {
160
- return true;
161
- }
149
+ static groupByOwner(entities, inverseProp) {
150
+ const groups = new Map();
151
+ for (const entity of entities) {
152
+ const target = Reference.unwrapReference(entity[inverseProp]);
153
+ const owners = target instanceof Collection ? target : target ? [target] : [];
154
+ for (const owner of owners) {
155
+ const items = groups.get(owner);
156
+ if (items) {
157
+ items.push(entity);
158
+ }
159
+ else {
160
+ groups.set(owner, [entity]);
162
161
  }
163
162
  }
164
- else if (target) {
165
- return target === collection.owner;
166
- }
167
- return false;
168
- };
163
+ }
164
+ return groups;
169
165
  }
170
166
  /**
171
167
  * Returns the 1:M collection dataloader batchLoadFn, which aggregates collections by entity,
@@ -176,8 +172,8 @@ export class DataloaderUtils {
176
172
  const entitiesAndOptsMap = DataloaderUtils.groupInversedOrMappedKeysByEntityAndOpts(collsWithOpts);
177
173
  const promises = DataloaderUtils.entitiesAndOptsMapToQueries(entitiesAndOptsMap, em);
178
174
  const resultsMap = new Map(await Promise.all(promises));
179
- // We need to filter the results in order to map each input collection
180
- // to a subset of each query matching the collection items.
175
+ // Group the results by owner once per query and inverse prop, instead of filtering them for each collection.
176
+ const groups = new Map();
181
177
  return collsWithOpts.map(([col, opts]) => {
182
178
  const key = `${col.property.targetMeta.uniqueName}|${stringifyCacheKey(opts ?? {})}`;
183
179
  const entities = resultsMap.get(key);
@@ -186,7 +182,14 @@ export class DataloaderUtils {
186
182
  /* v8 ignore next */
187
183
  throw new Error('Cannot match results');
188
184
  }
189
- return entities.filter(DataloaderUtils.getColFilter(col));
185
+ const inverseProp = col.property.inversedBy ?? col.property.mappedBy;
186
+ const groupKey = `${key}|${inverseProp}`;
187
+ let byOwner = groups.get(groupKey);
188
+ if (!byOwner) {
189
+ byOwner = DataloaderUtils.groupByOwner(entities, inverseProp);
190
+ groups.set(groupKey, byOwner);
191
+ }
192
+ return byOwner.get(col.owner) ?? [];
190
193
  });
191
194
  };
192
195
  }
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.24';
156
+ static #ORM_VERSION = '7.3.0-dev.26';
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}`;