@mikro-orm/core 7.2.4-dev.1 → 7.2.4-dev.11

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
@@ -1283,8 +1283,8 @@ export class EntityManager {
1283
1283
  connectionType: 'write',
1284
1284
  schema: options.schema,
1285
1285
  }));
1286
- for (const [entity, cond] of loadPK.entries()) {
1287
- const row = data2.find(row => {
1286
+ if (loadPK.size > 0) {
1287
+ const comparableRows = data2.map(row => {
1288
1288
  const tmp = {};
1289
1289
  add.forEach(k => {
1290
1290
  const prop = meta.properties[k];
@@ -1292,13 +1292,43 @@ export class EntityManager {
1292
1292
  tmp[k] = prop?.customType ? prop.customType.convertToDatabaseValue(row[k], this.getPlatform()) : row[k];
1293
1293
  }
1294
1294
  });
1295
- return this.#comparator.matching(entityName, cond, tmp);
1295
+ return tmp;
1296
1296
  });
1297
- /* v8 ignore next */
1298
- if (!row) {
1299
- throw new Error(`Cannot find matching entity for condition ${JSON.stringify(cond)}`);
1297
+ const isMatch = (cond, idx) => this.#comparator.matching(entityName, cond, comparableRows[idx]);
1298
+ // When every condition key is a comparable prop checked with `!==`, a matching row has the same primitive
1299
+ // values, so rows can be grouped by those values once instead of comparing every row for every entity.
1300
+ // Props outside `comparableProps` are skipped by the comparator, so they never qualify for grouping.
1301
+ const groupableProps = new Set(meta.comparableProps.filter(prop => this.#comparator.isStrictlyCompared(prop)));
1302
+ const groups = new Map();
1303
+ // `null` and `undefined` share a key, which can only make a group wider than what `matching` accepts
1304
+ const groupKey = (data, keys) => keys.map(k => (data[k] == null ? 'null' : `${typeof data[k]}:${data[k]}`)).join('\0');
1305
+ const findRowIndex = (cond) => {
1306
+ const keys = Utils.keys(cond);
1307
+ if (!keys.every(k => groupableProps.has(meta.properties[k]))) {
1308
+ return comparableRows.findIndex((_, idx) => isMatch(cond, idx));
1309
+ }
1310
+ const signature = keys.join('\0');
1311
+ if (!groups.has(signature)) {
1312
+ const rowsByKey = new Map();
1313
+ comparableRows.forEach((tmp, idx) => {
1314
+ const rowKey = groupKey(tmp, keys);
1315
+ const indexes = rowsByKey.get(rowKey) ?? [];
1316
+ indexes.push(idx);
1317
+ rowsByKey.set(rowKey, indexes);
1318
+ });
1319
+ groups.set(signature, rowsByKey);
1320
+ }
1321
+ const group = groups.get(signature);
1322
+ return group.get(groupKey(cond, keys))?.find(idx => isMatch(cond, idx)) ?? -1;
1323
+ };
1324
+ for (const [entity, cond] of loadPK.entries()) {
1325
+ const row = data2[findRowIndex(cond)];
1326
+ /* v8 ignore next */
1327
+ if (!row) {
1328
+ throw new Error(`Cannot find matching entity for condition ${JSON.stringify(cond)}`);
1329
+ }
1330
+ em.getHydrator().hydrate(entity, meta, row, em.#entityFactory, 'full', false, true);
1300
1331
  }
1301
- em.getHydrator().hydrate(entity, meta, row, em.#entityFactory, 'full', false, true);
1302
1332
  }
1303
1333
  if (loadPK.size !== data2.length && Array.isArray(uniqueFields)) {
1304
1334
  for (let i = 0; i < allData.length; i++) {
@@ -312,18 +312,25 @@ export class EntityLoader {
312
312
  }
313
313
  initializeManyToMany(filtered, children, prop, field, customOrder, partial, readonly) {
314
314
  if (prop.mappedBy) {
315
+ // group children by owner in one pass
316
+ const map = new Map(filtered.map(entity => [entity, []]));
317
+ for (const child of children) {
318
+ for (const owner of child[prop.mappedBy].getItems(false)) {
319
+ map.get(owner)?.push(child);
320
+ }
321
+ }
315
322
  for (const entity of filtered) {
316
- const items = children.filter(child => child[prop.mappedBy].contains(entity, false));
317
- entity[field].hydrate(items, true, partial, readonly);
323
+ entity[field].hydrate(map.get(entity), true, partial, readonly);
318
324
  }
319
325
  }
320
326
  else {
321
327
  // owning side of M:N without pivot table needs to be reordered
328
+ const childIndex = new Map(children.map((child, idx) => [child, idx]));
322
329
  for (const entity of filtered) {
323
- const order = !customOrder ? [...entity[prop.name].getItems(false)] : []; // copy order of references
324
- const items = children.filter(child => entity[prop.name].contains(child, false));
325
- if (!customOrder) {
326
- items.sort((a, b) => order.indexOf(a) - order.indexOf(b));
330
+ // keep the order of references, or the order of loaded children when a custom order is used
331
+ const items = entity[prop.name].getItems(false).filter(item => childIndex.has(item));
332
+ if (customOrder) {
333
+ items.sort((a, b) => childIndex.get(a) - childIndex.get(b));
327
334
  }
328
335
  entity[field].hydrate(items, true, partial, readonly);
329
336
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mikro-orm/core",
3
- "version": "7.2.4-dev.1",
3
+ "version": "7.2.4-dev.11",
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",
@@ -196,10 +196,17 @@ export class ChangeSetPersister {
196
196
  }
197
197
  async persistManagedEntities(meta, changeSets, options) {
198
198
  const size = this.#config.get('batchSize');
199
- for (let i = 0; i < changeSets.length; i += size) {
200
- const chunk = changeSets.slice(i, i + size);
201
- await this.persistManagedEntitiesBatch(meta, chunk, options);
202
- await this.reloadVersionValues(meta, chunk, options);
199
+ // a batch checks the version in all rows or none, so references without a loaded version go separately
200
+ const hasVersion = (cs) => cs.entity[meta.versionProperty] != null;
201
+ const groups = meta.ownsVersionProperty()
202
+ ? [changeSets.filter(hasVersion), changeSets.filter(cs => !hasVersion(cs))]
203
+ : [changeSets];
204
+ for (const group of groups) {
205
+ for (let i = 0; i < group.length; i += size) {
206
+ const chunk = group.slice(i, i + size);
207
+ await this.persistManagedEntitiesBatch(meta, chunk, options);
208
+ await this.reloadVersionValues(meta, chunk, options);
209
+ }
203
210
  }
204
211
  }
205
212
  checkConcurrencyKeys(meta, changeSet, cond) {
@@ -223,9 +230,14 @@ export class ChangeSetPersister {
223
230
  });
224
231
  const cond = [];
225
232
  const payload = [];
233
+ // like in `updateEntity()`, but the batch needs the version in all rows or none
234
+ const versioned = meta.ownsVersionProperty() && changeSets.every(cs => cs.entity[meta.versionProperty] != null);
226
235
  for (const changeSet of changeSets) {
227
236
  const where = changeSet.getPrimaryKey(true);
228
237
  this.checkConcurrencyKeys(meta, changeSet, where);
238
+ if (versioned) {
239
+ where[meta.versionProperty] = this.#platform.convertVersionValue(changeSet.entity[meta.versionProperty], meta.properties[meta.versionProperty]);
240
+ }
229
241
  cond.push(where);
230
242
  payload.push(changeSet.payload);
231
243
  }
@@ -235,6 +247,12 @@ export class ChangeSetPersister {
235
247
  // from those to be able to match them with `getSerializedPrimaryKey()` of the entity
236
248
  const pkFields = meta.getPrimaryProps().flatMap(prop => prop.fieldNames);
237
249
  res.rows?.forEach(item => map.set(Utils.getPrimaryKeyHash(pkFields.map(field => item[field])), item));
250
+ if ((meta.ownsVersionProperty() || meta.getOwnConcurrencyCheckKeys().length > 0) &&
251
+ res.affectedRows < changeSets.length) {
252
+ // without `returning`, the stale entity can't be identified, so we report the first one
253
+ const failed = changeSets.find(cs => !map.has(helper(cs.entity).getSerializedPrimaryKey())) ?? changeSets[0];
254
+ throw OptimisticLockError.lockFailed(failed.entity);
255
+ }
238
256
  for (const changeSet of changeSets) {
239
257
  if (res.rows) {
240
258
  const row = map.get(helper(changeSet.entity).getSerializedPrimaryKey());
@@ -19,6 +19,11 @@ export declare class EntityComparator {
19
19
  diffEntities<T extends object>(entityName: EntityName<T>, a: EntityData<T>, b: EntityData<T>, options?: {
20
20
  includeInverseSides?: boolean;
21
21
  }): EntityData<T>;
22
+ /**
23
+ * Returns true if the comparator checks this property with `!==`, so matching values are identical primitives.
24
+ * @internal
25
+ */
26
+ isStrictlyCompared<T>(prop: EntityProperty<T>): boolean;
22
27
  /** Returns true if two entity snapshots are identical (no differences). */
23
28
  matching<T extends object>(entityName: EntityName<T>, a: EntityData<T>, b: EntityData<T>): boolean;
24
29
  /**
@@ -29,6 +29,17 @@ export class EntityComparator {
29
29
  const comparator = this.getEntityComparator(entityName);
30
30
  return Utils.callCompiledFunction(comparator, a, b, options);
31
31
  }
32
+ /**
33
+ * Returns true if the comparator checks this property with `!==`, so matching values are identical primitives.
34
+ * @internal
35
+ */
36
+ isStrictlyCompared(prop) {
37
+ if (prop.kind !== ReferenceKind.SCALAR || prop.customType?.compareValues) {
38
+ return false;
39
+ }
40
+ const type = (prop.customType ? prop.customType.compareAsType() : prop.type).toLowerCase();
41
+ return ['string', 'number', 'bigint'].includes(type);
42
+ }
32
43
  /** Returns true if two entity snapshots are identical (no differences). */
33
44
  matching(entityName, a, b) {
34
45
  const diff = this.diffEntities(entityName, a, b);
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.4-dev.1';
156
+ static #ORM_VERSION = '7.2.4-dev.11';
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}`;
package/utils/fs-utils.js CHANGED
@@ -5,7 +5,8 @@ import { fileURLToPath, pathToFileURL } from 'node:url';
5
5
  import { Utils } from './Utils.js';
6
6
  import { colors } from '../logging/colors.js';
7
7
  let globSync = (patterns, options) => {
8
- const files = nodeGlobSync(patterns, { ...options, withFileTypes: true });
8
+ const cwd = options?.dir ? join(options.cwd ?? '', options.dir) : options?.cwd;
9
+ const files = nodeGlobSync(patterns, { cwd, withFileTypes: true });
9
10
  return files.filter(f => f.isFile()).map(f => join(f.parentPath, f.name));
10
11
  };
11
12
  export const fs = {
@@ -13,7 +14,8 @@ export const fs = {
13
14
  const tinyGlobby = await import('tinyglobby').catch(() => null);
14
15
  if (tinyGlobby) {
15
16
  globSync = (patterns, options) => {
16
- patterns = Utils.asArray(patterns).map(p => p.replace(/\\/g, '/'));
17
+ const dir = options?.dir ? tinyGlobby.escapePath(options.dir.replace(/\\/g, '/')) + '/' : '';
18
+ patterns = Utils.asArray(patterns).map(p => dir + p.replace(/\\/g, '/'));
17
19
  // never forward `cwd: undefined` — tinyglobby >= 0.2.16 calls `path.resolve(undefined)` and throws
18
20
  return tinyGlobby.globSync(patterns, {
19
21
  expandDirectories: false,
@@ -23,10 +25,10 @@ export const fs = {
23
25
  }
24
26
  },
25
27
  pathExists(path) {
26
- if (/[*?[\]]/.test(path)) {
27
- return globSync(path).length > 0;
28
+ if (existsSync(path)) {
29
+ return true;
28
30
  }
29
- return existsSync(path);
31
+ return /[*?[\]]/.test(path) && this.resolveGlob(path).length > 0;
30
32
  },
31
33
  ensureDir(path) {
32
34
  if (!existsSync(path)) {
@@ -62,18 +64,20 @@ export const fs = {
62
64
  if (Array.isArray(input)) {
63
65
  return input.flatMap(paths => this.resolveGlob(paths, cwd));
64
66
  }
65
- const hasGlobChars = /[*?[\]]/.test(input);
66
- if (!hasGlobChars) {
67
- try {
68
- const s = statSync(cwd ? this.normalizePath(cwd, input) : input);
69
- if (s.isDirectory()) {
70
- return globSync(join(input, '**'), { cwd });
71
- }
72
- }
73
- catch {
74
- // ignore
67
+ // an absolute path repeats the cwd, which may contain glob characters (e.g. `~/Dropbox (Team)/app`)
68
+ if (isAbsolute(input)) {
69
+ cwd ??= process.cwd();
70
+ input = relative(cwd, input).replace(/\\/g, '/') || '.';
71
+ }
72
+ try {
73
+ const s = statSync(cwd ? this.normalizePath(cwd, input) : input);
74
+ if (s.isDirectory()) {
75
+ return globSync('**', { cwd, dir: input });
75
76
  }
76
77
  }
78
+ catch {
79
+ // ignore
80
+ }
77
81
  return globSync(input, { cwd });
78
82
  },
79
83
  getPackageConfig(basePath = process.cwd()) {