@mikro-orm/core 7.2.12-dev.5 → 7.2.12-dev.7

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mikro-orm/core",
3
- "version": "7.2.12-dev.5",
3
+ "version": "7.2.12-dev.7",
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",
@@ -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.2.12-dev.5';
156
+ static #ORM_VERSION = '7.2.12-dev.7';
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}`;