@mikro-orm/core 7.2.11-dev.1 → 7.2.11-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
@@ -1932,13 +1932,15 @@ export class EntityManager {
1932
1932
  return em;
1933
1933
  }
1934
1934
  const entities = Utils.asArray(entity, true);
1935
- for (const ent of entities) {
1936
- if (!Utils.isEntity(ent, true)) {
1937
- throw new Error(`You need to pass entity instance or reference to 'em.remove()'. To remove entities by condition, use 'em.nativeDelete()'.`);
1935
+ em.#unitOfWork.batchRemovals(() => {
1936
+ for (const ent of entities) {
1937
+ if (!Utils.isEntity(ent, true)) {
1938
+ throw new Error(`You need to pass entity instance or reference to 'em.remove()'. To remove entities by condition, use 'em.nativeDelete()'.`);
1939
+ }
1940
+ // do not cascade just yet, cascading of entities in remove stack is done when flushing
1941
+ em.#unitOfWork.remove(Reference.unwrapReference(ent), undefined, { cascade: false });
1938
1942
  }
1939
- // do not cascade just yet, cascading of entities in remove stack is done when flushing
1940
- em.#unitOfWork.remove(Reference.unwrapReference(ent), undefined, { cascade: false });
1941
- }
1943
+ });
1942
1944
  return em;
1943
1945
  }
1944
1946
  /**
@@ -2487,6 +2489,11 @@ export class EntityManager {
2487
2489
  ? [meta.schema, meta.tableName, meta.discriminatorValue]
2488
2490
  : Utils.className(entityName);
2489
2491
  const key = [entityKey, method, opts, where];
2492
+ // filters of the root entity are part of `where`, but those of its relations are applied only when loading them
2493
+ const filterParams = this.getContext(false).#filterParams;
2494
+ if (options.filters !== false && Utils.hasObjectKeys(filterParams) && Utils.asArray(opts.populate).length > 0) {
2495
+ key.push({ filterParams });
2496
+ }
2490
2497
  // session context (row level security) scopes cached rows per tenant/role, avoiding cross-context serves
2491
2498
  const sessionContext = this.getContext(false).#sessionContext;
2492
2499
  if (sessionContext) {
@@ -108,7 +108,11 @@ export declare class Collection<T extends object, O extends object = object> {
108
108
  /**
109
109
  * @internal
110
110
  */
111
- removeWithoutPropagation(entity: T): void;
111
+ removeWithoutPropagation(entity: T, reindex?: boolean): boolean;
112
+ /**
113
+ * @internal
114
+ */
115
+ reindex(): void;
112
116
  /**
113
117
  * Extracts a slice of the collection items starting at position start to end (exclusive) of the collection.
114
118
  * If end is null it returns all elements from start to the end of the collection.
@@ -520,14 +520,23 @@ export class Collection {
520
520
  /**
521
521
  * @internal
522
522
  */
523
- removeWithoutPropagation(entity) {
523
+ removeWithoutPropagation(entity, reindex = true) {
524
524
  if (!this.#items.delete(entity)) {
525
- return;
525
+ return false;
526
526
  }
527
527
  this.incrementCount(-1);
528
528
  delete this[this.#items.size];
529
- Object.assign(this, [...this.#items]);
529
+ if (reindex) {
530
+ this.reindex();
531
+ }
530
532
  this.#dirty = true;
533
+ return true;
534
+ }
535
+ /**
536
+ * @internal
537
+ */
538
+ reindex() {
539
+ Object.assign(this, [...this.#items]); // reassign array access
531
540
  }
532
541
  /**
533
542
  * Extracts a slice of the collection items starting at position start to end (exclusive) of the collection.
@@ -39,6 +39,10 @@ export class EntityAssigner {
39
39
  if (DANGEROUS_PROPERTY_NAMES.includes(propName)) {
40
40
  return;
41
41
  }
42
+ // keys that are not entity properties must not replace methods of the entity, e.g. `toJSON`
43
+ if (!Object.hasOwn(props, propName) && typeof entity[propName] === 'function') {
44
+ return;
45
+ }
42
46
  let value = data[propName];
43
47
  const onlyProperties = options.onlyProperties && !(propName in props);
44
48
  const ignoreUndefined = options.ignoreUndefined === true && value === undefined;
@@ -358,7 +358,11 @@ export class EntityLoader {
358
358
  // When targetKey is set, use it for FK lookup instead of the PK
359
359
  let fk = prop.targetKey ?? Utils.getPrimaryKeyHash(meta.primaryKeys);
360
360
  let schema = options.schema;
361
- const partial = !Utils.isEmpty(prop.where) || !Utils.isEmpty(options.where) || !Utils.isEmpty(options.populateFilter);
361
+ const childFilter = options.populateFilter ? await this.extractChildPopulateFilter(options, prop) : undefined;
362
+ // conditions on the populated entity itself have no sink in the child query (the joined strategy puts
363
+ // them on the join), only the nested relation ones can be forwarded as its own `populateFilter`
364
+ const [ownFilter, nestedFilter] = this.splitPopulateFilter(childFilter, meta);
365
+ const partial = !Utils.isEmpty(prop.where) || !Utils.isEmpty(options.where) || !!ownFilter;
362
366
  let polymorphicOwnerProp;
363
367
  const ownerProp = prop.kind === ReferenceKind.ONE_TO_MANY || (prop.kind === ReferenceKind.MANY_TO_MANY && !prop.owner)
364
368
  ? meta.properties[prop.mappedBy]
@@ -418,10 +422,6 @@ export class EntityLoader {
418
422
  if (!Utils.isEmpty(prop.where) || Raw.hasObjectFragments(prop.where)) {
419
423
  where = { $and: [where, prop.where] };
420
424
  }
421
- const childFilter = options.populateFilter ? await this.extractChildPopulateFilter(options, prop) : undefined;
422
- // conditions on the populated entity itself have no sink in the child query (the joined strategy puts
423
- // them on the join), only the nested relation ones can be forwarded as its own `populateFilter`
424
- const [ownFilter, nestedFilter] = this.splitPopulateFilter(childFilter, meta);
425
425
  if (ownFilter) {
426
426
  where = { $and: [where, ownFilter] };
427
427
  }
@@ -905,14 +905,14 @@ export class EntityLoader {
905
905
  .map(c => c.field.split(':'))
906
906
  .filter(parts => parts[1] === 'ref')
907
907
  .map(parts => parts[0]));
908
+ const childFields = options.fields
909
+ .filter(f => f.startsWith(`${field}.`))
910
+ .map(f => f.substring(field.length + 1))
911
+ .filter(cf => !refChildren.has(cf.split('.')[0]));
908
912
  return children
909
913
  .map(e => Reference.unwrapReference(e[field]))
910
914
  .filter(target => {
911
915
  const wrapped = helper(target);
912
- const childFields = options.fields
913
- .filter(f => f.startsWith(`${field}.`))
914
- .map(f => f.substring(field.length + 1))
915
- .filter(cf => !refChildren.has(cf.split('.')[0]));
916
916
  return !wrapped.__initialized || !childFields.every(cf => this.isPropertyLoaded(target, cf));
917
917
  });
918
918
  }
@@ -926,6 +926,8 @@ export class EntityLoader {
926
926
  return entities;
927
927
  }
928
928
  const field = prop.name;
929
+ // the same for every entity, so compute it only once
930
+ let childFields;
929
931
  return entities.filter(e => {
930
932
  const value = e[field];
931
933
  if (value === null) {
@@ -947,7 +949,7 @@ export class EntityLoader {
947
949
  return false;
948
950
  }
949
951
  if (options.fields) {
950
- const childFields = options.fields
952
+ childFields ??= options.fields
951
953
  .filter(f => f.startsWith(`${prop.name}.`))
952
954
  .map(f => f.substring(prop.name.length + 1));
953
955
  return childFields.length > 0 && !childFields.every(f => this.isPropertyLoaded(target, f));
@@ -67,7 +67,7 @@ export declare class ScalarReference<Value> {
67
67
  load(options?: Omit<LoadReferenceOptions<any, any>, 'populate' | 'fields' | 'exclude'>): Promise<Value | undefined>;
68
68
  /**
69
69
  * Ensures the underlying entity is loaded first (without reloading it if it already is loaded).
70
- * Returns the entity or throws an error just like `em.findOneOrFail()` (and respects the same config options).
70
+ * Returns the value or throws an error naming the property, unless a `failHandler` is passed in the options.
71
71
  */
72
72
  loadOrFail(options?: Omit<LoadReferenceOrFailOptions<any, any>, 'populate' | 'fields' | 'exclude'>): Promise<Value>;
73
73
  /** Sets the scalar value and marks the reference as initialized. */
@@ -119,10 +119,10 @@ export class Reference {
119
119
  const ret = await this.load(options);
120
120
  if (!ret) {
121
121
  const wrapped = helper(this.entity);
122
- options.failHandler ??= wrapped.__em.config.get('findOneOrFailHandler');
122
+ const failHandler = options.failHandler ?? wrapped.__em.config.get('findOneOrFailHandler');
123
123
  const entityName = this.entity.constructor.name;
124
124
  const where = wrapped.getPrimaryKey();
125
- throw options.failHandler(entityName, where);
125
+ throw failHandler(entityName, where);
126
126
  }
127
127
  return ret;
128
128
  }
@@ -202,15 +202,16 @@ export class ScalarReference {
202
202
  }
203
203
  /**
204
204
  * Ensures the underlying entity is loaded first (without reloading it if it already is loaded).
205
- * Returns the entity or throws an error just like `em.findOneOrFail()` (and respects the same config options).
205
+ * Returns the value or throws an error naming the property, unless a `failHandler` is passed in the options.
206
206
  */
207
207
  async loadOrFail(options = {}) {
208
208
  const ret = await this.load(options);
209
209
  if (ret == null) {
210
210
  const wrapped = helper(this.entity);
211
- options.failHandler ??= wrapped.__em.config.get('findOneOrFailHandler');
212
211
  const entityName = this.entity.constructor.name;
213
- throw NotFoundError.failedToLoadProperty(entityName, this.#property, wrapped.getPrimaryKey());
212
+ const where = wrapped.getPrimaryKey();
213
+ throw (options.failHandler?.(entityName, where) ??
214
+ NotFoundError.failedToLoadProperty(entityName, this.#property, where));
214
215
  }
215
216
  return ret;
216
217
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mikro-orm/core",
3
- "version": "7.2.11-dev.1",
3
+ "version": "7.2.11-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",
@@ -270,7 +270,10 @@ export declare abstract class Platform {
270
270
  getSchemaGenerator(driver: IDatabaseDriver, em?: EntityManager): ISchemaGenerator;
271
271
  /** Processes a date value before persisting, applying timezone or format conversions. */
272
272
  processDateProperty(value: unknown): string | number | Date;
273
- /** Wraps a table or column identifier with the platform-specific quote character. */
273
+ /**
274
+ * Wraps a table or column identifier with the platform-specific quote character. The result is meant to be embedded
275
+ * in a query template, so question marks in it are escaped as `\?` to not be mistaken for placeholders.
276
+ */
274
277
  quoteIdentifier(id: string | {
275
278
  toString: () => string;
276
279
  }, quote?: string): string;
@@ -279,7 +282,7 @@ export declare abstract class Platform {
279
282
  /** Quotes a string default value for DDL; dialects that escape with backslashes override this. */
280
283
  quoteDefaultValue(value: string): string;
281
284
  escape(value: any): string;
282
- /** Replaces `?` placeholders in SQL with quoted parameter values. */
285
+ /** Replaces `?` placeholders in SQL with quoted parameter values, `\?` stands for a literal question mark. */
283
286
  formatQuery(sql: string, params: readonly any[]): string;
284
287
  /** Deep-clones embeddable data and tags it for JSON serialization. */
285
288
  cloneEmbeddable<T>(data: T): T;
@@ -567,14 +567,21 @@ export class Platform {
567
567
  processDateProperty(value) {
568
568
  return value;
569
569
  }
570
- /** Wraps a table or column identifier with the platform-specific quote character. */
570
+ /**
571
+ * Wraps a table or column identifier with the platform-specific quote character. The result is meant to be embedded
572
+ * in a query template, so question marks in it are escaped as `\?` to not be mistaken for placeholders.
573
+ */
571
574
  quoteIdentifier(id, quote = '`') {
572
575
  const raw = Raw.getKnownFragment(id);
573
576
  if (raw) {
574
- return this.formatQuery(raw.sql, raw.params);
577
+ // fragments without params are kept as is, their placeholders can be bound by the outer query
578
+ return raw.params.length === 0 ? raw.sql : this.formatQuery(raw.sql, raw.params).replaceAll('?', '\\?');
575
579
  }
576
- const escaped = id.toString().replaceAll(quote, quote + quote);
577
- return `${quote}${escaped.replace('.', `${quote}.${quote}`)}${quote}`;
580
+ const escaped = id
581
+ .toString()
582
+ .replaceAll(quote, quote + quote)
583
+ .replaceAll('?', '\\?');
584
+ return `${quote}${escaped.replaceAll('.', `${quote}.${quote}`)}${quote}`;
578
585
  }
579
586
  /** Quotes a literal value for safe embedding in SQL. */
580
587
  quoteValue(value) {
@@ -588,10 +595,10 @@ export class Platform {
588
595
  escape(value) {
589
596
  return value;
590
597
  }
591
- /** Replaces `?` placeholders in SQL with quoted parameter values. */
598
+ /** Replaces `?` placeholders in SQL with quoted parameter values, `\?` stands for a literal question mark. */
592
599
  formatQuery(sql, params) {
593
600
  if (params.length === 0) {
594
- return sql;
601
+ return sql.replaceAll('\\?', '?');
595
602
  }
596
603
  // fast string replace without regexps
597
604
  let j = 0;
@@ -599,7 +606,7 @@ export class Platform {
599
606
  let ret = '';
600
607
  if (sql.startsWith('?')) {
601
608
  if (sql[1] === '?') {
602
- ret += this.quoteIdentifier(params[j++]);
609
+ ret += this.quoteIdentifier(params[j++]).replaceAll('\\?', '?');
603
610
  pos = 2;
604
611
  }
605
612
  else {
@@ -618,7 +625,7 @@ export class Platform {
618
625
  pos = idx + 1;
619
626
  }
620
627
  else if (sql.substring(idx, idx + 2) === '??') {
621
- ret += sql.substring(pos, idx) + this.quoteIdentifier(params[j++]);
628
+ ret += sql.substring(pos, idx) + this.quoteIdentifier(params[j++]).replaceAll('\\?', '?');
622
629
  pos = idx + 2;
623
630
  }
624
631
  else {
@@ -90,6 +90,13 @@ export declare class UnitOfWork {
90
90
  remove<T extends object>(entity: T, visited?: Set<AnyEntity>, options?: {
91
91
  cascade?: boolean;
92
92
  }): void;
93
+ /**
94
+ * Runs `cb` and updates the array indexes of the collections that `remove()` changed only once at the end,
95
+ * so removing many items of one loaded collection stays linear.
96
+ * @internal
97
+ */
98
+ batchRemovals(cb: () => void): void;
99
+ private removeFromCollection;
93
100
  /** Flushes all pending changes to the database within a transaction. */
94
101
  commit(): Promise<void>;
95
102
  private doCommit;
@@ -35,6 +35,7 @@ export class UnitOfWork {
35
35
  #loadedEntities = new Set();
36
36
  #flushQueue = [];
37
37
  #working = false;
38
+ #reindexQueue;
38
39
  #em;
39
40
  /**
40
41
  * UoW lives in `@mikro-orm/core` alongside `EntityManager` and reaches `getAbortOptions`
@@ -249,7 +250,7 @@ export class UnitOfWork {
249
250
  /** Attempts to extract a primary key from the where condition and look up the entity in the identity map. */
250
251
  tryGetById(entityName, where, schema, strict = true, convertCustomTypes) {
251
252
  const pk = Utils.extractPK(where, this.#metadata.find(entityName), strict);
252
- if (!pk) {
253
+ if (pk == null) {
253
254
  return null;
254
255
  }
255
256
  return this.getById(entityName, pk, schema, convertCustomTypes);
@@ -437,20 +438,40 @@ export class UnitOfWork {
437
438
  for (const owner of relation.getItems(false)) {
438
439
  const ownerColl = owner[inverseProp];
439
440
  if (Utils.isCollection(ownerColl)) {
440
- ownerColl.removeWithoutPropagation(entity);
441
+ this.removeFromCollection(ownerColl, entity);
441
442
  }
442
443
  }
443
444
  continue;
444
445
  }
445
446
  const target = relation?.[inverseProp];
446
447
  if (relation && Utils.isCollection(target)) {
447
- target.removeWithoutPropagation(entity);
448
+ this.removeFromCollection(target, entity);
448
449
  }
449
450
  }
450
451
  if (options.cascade ?? true) {
451
452
  this.cascade(entity, Cascade.REMOVE, visited);
452
453
  }
453
454
  }
455
+ /**
456
+ * Runs `cb` and updates the array indexes of the collections that `remove()` changed only once at the end,
457
+ * so removing many items of one loaded collection stays linear.
458
+ * @internal
459
+ */
460
+ batchRemovals(cb) {
461
+ const queue = (this.#reindexQueue = new Set());
462
+ try {
463
+ cb();
464
+ }
465
+ finally {
466
+ this.#reindexQueue = undefined;
467
+ queue.forEach(coll => coll.reindex());
468
+ }
469
+ }
470
+ removeFromCollection(coll, entity) {
471
+ if (coll.removeWithoutPropagation(entity, !this.#reindexQueue)) {
472
+ this.#reindexQueue?.add(coll);
473
+ }
474
+ }
454
475
  /** Flushes all pending changes to the database within a transaction. */
455
476
  async commit() {
456
477
  if (this.#working) {
@@ -580,8 +601,12 @@ export class UnitOfWork {
580
601
  computeChangeSets() {
581
602
  this.#changeSets.clear();
582
603
  const visited = new Set();
583
- for (const entity of this.#removeStack) {
584
- this.cascade(entity, Cascade.REMOVE, visited);
604
+ if (this.#removeStack.size > 0) {
605
+ this.batchRemovals(() => {
606
+ for (const entity of this.#removeStack) {
607
+ this.cascade(entity, Cascade.REMOVE, visited);
608
+ }
609
+ });
585
610
  }
586
611
  visited.clear();
587
612
  const persistOptions = { checkRemoveStack: true };
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.11-dev.1';
156
+ static #ORM_VERSION = '7.2.11-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}`;
@@ -335,23 +335,55 @@ export class Utils {
335
335
  }
336
336
  let depth = 0;
337
337
  let end = start;
338
+ let paramStart = start + 1;
339
+ const params = [];
340
+ let quote;
338
341
  for (; end < source.length; end++) {
339
- if (source[end] === '(') {
342
+ if (quote) {
343
+ if (source[end] === '\\') {
344
+ end++;
345
+ }
346
+ else if (source[end] === quote) {
347
+ quote = undefined;
348
+ }
349
+ continue;
350
+ }
351
+ const commentEnd = source.startsWith('/*', end) ? '*/' : source.startsWith('//', end) ? '\n' : undefined;
352
+ if (commentEnd) {
353
+ const close = source.indexOf(commentEnd, end + 2);
354
+ end = close === -1 ? source.length : close + commentEnd.length - 1;
355
+ continue;
356
+ }
357
+ // a slash that does not follow an operand starts a regex literal
358
+ if (source[end] === '/' && !/[\w$)\]]\s*$/.test(source.slice(start, end))) {
359
+ const regex = /\/(?:\\.|\[(?:\\.|[^\]\\])*\]|[^/\\[\n])+\//y;
360
+ regex.lastIndex = end;
361
+ end += (regex.exec(source)?.[0].length ?? 1) - 1;
362
+ continue;
363
+ }
364
+ if (`'"\``.includes(source[end])) {
365
+ quote = source[end];
366
+ continue;
367
+ }
368
+ if ('([{'.includes(source[end])) {
340
369
  depth++;
341
370
  }
342
- if (source[end] === ')') {
371
+ if (')]}'.includes(source[end])) {
343
372
  depth--;
344
373
  }
345
374
  if (depth === 0) {
346
375
  break;
347
376
  }
377
+ if (depth === 1 && source[end] === ',') {
378
+ params.push(source.slice(paramStart, end));
379
+ paramStart = end + 1;
380
+ }
348
381
  }
349
- const raw = source.slice(start + 1, end);
350
- return raw
351
- .split(',')
352
- .map(s => s.trim().replace(/=.*$/, '').trim())
382
+ params.push(source.slice(paramStart, end));
383
+ return params
384
+ .map(s => s.replace(/\/\*.*?\*\/|\/\/[^\n]*/gs, '').trim())
353
385
  .filter(Boolean)
354
- .map(raw => (raw.startsWith('{') && raw.endsWith('}') ? '' : raw));
386
+ .map(raw => (/^[{[]/.test(raw) ? '' : raw.replace(/=.*$/s, '').trim()));
355
387
  }
356
388
  /**
357
389
  * Checks whether the argument looks like primary key (string, number or ObjectId).