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

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.
@@ -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.10",
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());
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.10';
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()) {