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

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.
@@ -9,11 +9,13 @@ import { Raw } from '../utils/RawQueryFragment.js';
9
9
  import { ValidationError } from '../errors.js';
10
10
  /** @internal JIT-compiled hydrator that converts raw database rows into entity instances with optimized generated code. */
11
11
  export class ObjectHydrator extends Hydrator {
12
+ // keyed by type and `normalizeAccessors` without building a string key on every lookup
12
13
  #hydrators = {
13
- 'full~true': new Map(),
14
- 'full~false': new Map(),
15
- 'reference~true': new Map(),
16
- 'reference~false': new Map(),
14
+ full: { normalized: new Map(), raw: new Map() },
15
+ reference: {
16
+ normalized: new Map(),
17
+ raw: new Map(),
18
+ },
17
19
  };
18
20
  #tmpIndex = 0;
19
21
  /**
@@ -42,8 +44,8 @@ export class ObjectHydrator extends Hydrator {
42
44
  * @internal Highly performance-sensitive method.
43
45
  */
44
46
  getEntityHydrator(meta, type, normalizeAccessors = false) {
45
- const key = `${type}~${normalizeAccessors}`;
46
- const exists = this.#hydrators[key].get(meta.class);
47
+ const cache = this.#hydrators[type][normalizeAccessors ? 'normalized' : 'raw'];
48
+ const exists = cache.get(meta.class);
47
49
  if (exists) {
48
50
  return exists;
49
51
  }
@@ -107,6 +109,10 @@ export class ObjectHydrator extends Hydrator {
107
109
  else if (prop.runtimeType === 'boolean') {
108
110
  ret.push(` entity${entityKey} = !!data${dataKey};`);
109
111
  }
112
+ else if (prop.formula && prop.runtimeType === 'number') {
113
+ // drivers can return numeric expressions as strings, e.g. `count(*)` is a bigint in postgres
114
+ ret.push(` entity${entityKey} = Number(data${dataKey});`);
115
+ }
110
116
  else if (prop.runtimeType === 'Date' && !this.platform.isNumericProperty(prop)) {
111
117
  ret.push(` if (data${dataKey} instanceof Date) {`);
112
118
  ret.push(` entity${entityKey} = data${dataKey};`);
@@ -220,11 +226,11 @@ export class ObjectHydrator extends Hydrator {
220
226
  ret.push(` }`);
221
227
  ret.push(` if (Array.isArray(data${dataKey})) {`);
222
228
  ret.push(` const items = data${dataKey}.map(value => createCollectionItem_${this.safeKey(prop.name)}(value, entity));`);
223
- ret.push(` const coll = Collection.create(entity, ${this.quote(prop.name)}, items, newEntity);`);
224
229
  ret.push(` if (newEntity) {`);
225
- ret.push(` coll.setDirty();`);
230
+ ret.push(` Collection.create(entity, ${this.quote(prop.name)}, items, true).setDirty();`);
226
231
  ret.push(` } else {`);
227
- ret.push(` coll.takeSnapshot(true);`);
232
+ // 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);`);
228
234
  ret.push(` }`);
229
235
  ret.push(` } else if (!entity${entityKey} && data${dataKey} instanceof Collection) {`);
230
236
  ret.push(` entity${entityKey} = data${dataKey};`);
@@ -410,7 +416,7 @@ export class ObjectHydrator extends Hydrator {
410
416
  `${lines.join('\n')}\n}`;
411
417
  const fnKey = `hydrator-${meta.compiledName}-${type}-${normalizeAccessors}`;
412
418
  const hydrator = Utils.createFunction(context, code, this.config.get('compiledFunctions'), fnKey);
413
- this.#hydrators[key].set(meta.class, hydrator);
419
+ cache.set(meta.class, hydrator);
414
420
  return hydrator;
415
421
  }
416
422
  createCollectionItemMapper(prop, context) {
@@ -88,7 +88,8 @@ export class AbstractNamingStrategy {
88
88
  * @inheritDoc
89
89
  */
90
90
  manyToManyPropertyName(ownerEntityName, targetEntityName, pivotTableName, ownerTableName, schemaName) {
91
- return this.columnNameToProperty(pivotTableName.replace(new RegExp('^' + ownerTableName + '_'), ''));
91
+ const prefix = ownerTableName + '_';
92
+ return this.columnNameToProperty(pivotTableName.startsWith(prefix) ? pivotTableName.slice(prefix.length) : pivotTableName);
92
93
  }
93
94
  /**
94
95
  * @inheritDoc
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mikro-orm/core",
3
- "version": "7.3.0-dev.22",
3
+ "version": "7.3.0-dev.24",
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;
@@ -366,7 +366,7 @@ export class Platform {
366
366
  }
367
367
  /** Serializes a string array into its database storage format. */
368
368
  marshallArray(values) {
369
- return values.map(v => (/[,",\\]/.test(v) ? JSON.stringify(v) : v)).join(',');
369
+ return values.map(v => (/[,",\\]/.test(v) || (v === '' && values.length === 1) ? JSON.stringify(v) : v)).join(',');
370
370
  }
371
371
  /** Deserializes a database-stored array string back into a string array. */
372
372
  unmarshallArray(value) {
@@ -406,6 +406,9 @@ export class Platform {
406
406
  i = comma + 1;
407
407
  }
408
408
  }
409
+ if (value.endsWith(',')) {
410
+ result.push('');
411
+ }
409
412
  return result;
410
413
  }
411
414
  getBlobDeclarationSQL() {
@@ -564,14 +567,21 @@ export class Platform {
564
567
  processDateProperty(value) {
565
568
  return value;
566
569
  }
567
- /** 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
+ */
568
574
  quoteIdentifier(id, quote = '`') {
569
575
  const raw = Raw.getKnownFragment(id);
570
576
  if (raw) {
571
- 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('?', '\\?');
572
579
  }
573
- const escaped = id.toString().replaceAll(quote, quote + quote);
574
- 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}`;
575
585
  }
576
586
  /** Quotes a literal value for safe embedding in SQL. */
577
587
  quoteValue(value) {
@@ -585,10 +595,10 @@ export class Platform {
585
595
  escape(value) {
586
596
  return value;
587
597
  }
588
- /** Replaces `?` placeholders in SQL with quoted parameter values. */
598
+ /** Replaces `?` placeholders in SQL with quoted parameter values, `\?` stands for a literal question mark. */
589
599
  formatQuery(sql, params) {
590
600
  if (params.length === 0) {
591
- return sql;
601
+ return sql.replaceAll('\\?', '?');
592
602
  }
593
603
  // fast string replace without regexps
594
604
  let j = 0;
@@ -596,7 +606,7 @@ export class Platform {
596
606
  let ret = '';
597
607
  if (sql.startsWith('?')) {
598
608
  if (sql[1] === '?') {
599
- ret += this.quoteIdentifier(params[j++]);
609
+ ret += this.quoteIdentifier(params[j++]).replaceAll('\\?', '?');
600
610
  pos = 2;
601
611
  }
602
612
  else {
@@ -615,7 +625,7 @@ export class Platform {
615
625
  pos = idx + 1;
616
626
  }
617
627
  else if (sql.substring(idx, idx + 2) === '??') {
618
- ret += sql.substring(pos, idx) + this.quoteIdentifier(params[j++]);
628
+ ret += sql.substring(pos, idx) + this.quoteIdentifier(params[j++]).replaceAll('\\?', '?');
619
629
  pos = idx + 2;
620
630
  }
621
631
  else {
@@ -92,13 +92,13 @@ export class EntitySerializer {
92
92
  meta.primaryKeys.forEach(pk => props.add(pk));
93
93
  }
94
94
  if (wrapped.isInitialized() || !wrapped.hasPrimaryKey()) {
95
- const entityKeys = new Set(Object.keys(entity));
96
95
  for (const prop of meta.props) {
97
- if (entityKeys.has(prop.name) || (prop.getter && prop.accessor === prop.name)) {
96
+ if (Object.prototype.propertyIsEnumerable.call(entity, prop.name) ||
97
+ (prop.getter && prop.accessor === prop.name)) {
98
98
  props.add(prop.name);
99
99
  }
100
100
  }
101
- for (const key of entityKeys) {
101
+ for (const key of Object.keys(entity)) {
102
102
  if (!meta.properties[key]) {
103
103
  props.add(key);
104
104
  }
@@ -3,11 +3,13 @@ import { Utils } from '../utils/Utils.js';
3
3
  import { ReferenceKind } from '../enums.js';
4
4
  import { SerializationContext } from './SerializationContext.js';
5
5
  import { isRaw } from '../utils/RawQueryFragment.js';
6
- function isVisible(meta, propName, ignoreFields = []) {
6
+ function isPropertyVisible(prop, ignoreFields) {
7
+ const prefixed = !prop.primary && !prop.accessor && prop.name.startsWith('_'); // ignore prefixed properties, if it's not a PK
8
+ return !prop.hidden && !prefixed && !ignoreFields?.includes(prop.name);
9
+ }
10
+ function isVisible(meta, propName) {
7
11
  const prop = meta.properties[propName];
8
- const visible = prop && !prop.hidden;
9
- const prefixed = prop && !prop.primary && !prop.accessor && propName.startsWith('_'); // ignore prefixed properties, if it's not a PK
10
- return visible && !prefixed && !ignoreFields.includes(propName);
12
+ return !!prop && isPropertyVisible(prop);
11
13
  }
12
14
  /** Converts entity instances to plain objects via `toObject()`, respecting populate hints, hidden fields, and serialization context. */
13
15
  export class EntityTransformer {
@@ -30,23 +32,20 @@ export class EntityTransformer {
30
32
  SerializationContext.propagate(root, entity, isVisible);
31
33
  const meta = wrapped.__meta;
32
34
  const ret = {};
33
- const props = new Set();
34
- if (meta.serializedPrimaryKey && !meta.compositePK) {
35
- props.add(meta.serializedPrimaryKey);
36
- }
37
- else {
38
- meta.primaryKeys.forEach(pk => props.add(pk));
35
+ const pks = meta.serializedPrimaryKey && !meta.compositePK ? [meta.serializedPrimaryKey] : meta.primaryKeys;
36
+ const props = [];
37
+ for (const pk of pks) {
38
+ if (meta.properties[pk]) {
39
+ props.push(meta.properties[pk]);
40
+ }
39
41
  }
42
+ // own keys that are not entity properties are never visible, so only the metadata properties are collected
40
43
  if (wrapped.isInitialized() || !wrapped.hasPrimaryKey()) {
41
- const entityKeys = new Set(Object.keys(entity));
42
44
  for (const prop of meta.props) {
43
- if (entityKeys.has(prop.name) || (prop.getter && prop.accessor === prop.name)) {
44
- props.add(prop.name);
45
- }
46
- }
47
- for (const key of entityKeys) {
48
- if (!meta.properties[key]) {
49
- props.add(key);
45
+ if ((Object.prototype.propertyIsEnumerable.call(entity, prop.name) ||
46
+ (prop.getter && prop.accessor === prop.name)) &&
47
+ !pks.includes(prop.name)) {
48
+ props.push(prop);
50
49
  }
51
50
  }
52
51
  }
@@ -55,15 +54,15 @@ export class EntityTransformer {
55
54
  if (!visited) {
56
55
  root.visited.add(entity);
57
56
  }
58
- for (const prop of props) {
59
- const visible = raw ? meta.properties[prop] : isVisible(meta, prop, ignoreFields);
60
- if (!visible) {
57
+ for (const property of props) {
58
+ const prop = property.name;
59
+ if (!raw && !isPropertyVisible(property, ignoreFields)) {
61
60
  continue;
62
61
  }
63
62
  const populated = root.isMarkedAsPopulated(meta.class, prop);
64
63
  if (!raw) {
65
64
  const partiallyLoaded = root.isPartiallyLoaded(meta.class, prop);
66
- const isPrimary = includePrimaryKeys && meta.properties[prop].primary;
65
+ const isPrimary = includePrimaryKeys && property.primary;
67
66
  if (!partiallyLoaded && !populated && !isPrimary) {
68
67
  continue;
69
68
  }
@@ -90,7 +89,7 @@ export class EntityTransformer {
90
89
  if (typeof val === 'undefined') {
91
90
  continue;
92
91
  }
93
- ret[this.propertyName(meta, prop, raw)] = val;
92
+ ret[this.propertyName(meta, property, raw)] = val;
94
93
  }
95
94
  if (!wrapped.isInitialized() && wrapped.hasPrimaryKey()) {
96
95
  return ret;
@@ -101,7 +100,7 @@ export class EntityTransformer {
101
100
  const visible = !prop.hidden && entity[prop.getterName] instanceof Function;
102
101
  const populated = root.isMarkedAsPopulated(meta.class, prop.name);
103
102
  if (visible) {
104
- ret[this.propertyName(meta, prop.name, raw)] = this.processProperty(prop.getterName, entity, raw, populated);
103
+ ret[this.propertyName(meta, prop, raw)] = this.processProperty(prop.getterName, entity, raw, populated);
105
104
  }
106
105
  }
107
106
  else {
@@ -109,7 +108,7 @@ export class EntityTransformer {
109
108
  const visible = !prop.hidden && typeof entity[prop.name] !== 'undefined';
110
109
  const populated = root.isMarkedAsPopulated(meta.class, prop.name);
111
110
  if (visible) {
112
- ret[this.propertyName(meta, prop.name, raw)] = this.processProperty(prop.name, entity, raw, populated);
111
+ ret[this.propertyName(meta, prop, raw)] = this.processProperty(prop.name, entity, raw, populated);
113
112
  }
114
113
  }
115
114
  }
@@ -123,15 +122,15 @@ export class EntityTransformer {
123
122
  }
124
123
  static propertyName(meta, prop, raw) {
125
124
  if (raw) {
126
- return prop;
125
+ return prop.name;
127
126
  }
128
- if (meta.properties[prop].serializedName) {
129
- return meta.properties[prop].serializedName;
127
+ if (prop.serializedName) {
128
+ return prop.serializedName;
130
129
  }
131
- if (meta.properties[prop].primary && meta.serializedPrimaryKey) {
130
+ if (prop.primary && meta.serializedPrimaryKey) {
132
131
  return meta.serializedPrimaryKey;
133
132
  }
134
- return prop;
133
+ return prop.name;
135
134
  }
136
135
  static processProperty(prop, entity, raw, populated) {
137
136
  const wrapped = helper(entity);
@@ -43,7 +43,7 @@ export class SerializationContext {
43
43
  /** Cleans up the serialization context by removing root references from all tracked entities. */
44
44
  close() {
45
45
  for (const entity of this.#entities) {
46
- delete helper(entity).__serializationContext.root;
46
+ helper(entity).__serializationContext.root = undefined;
47
47
  }
48
48
  }
49
49
  /**
package/typings.d.ts CHANGED
@@ -1193,6 +1193,7 @@ export interface EntityMetadata<Entity = any, Class extends EntityCtor<Entity> =
1193
1193
  comparableProps: EntityProperty<Entity>[];
1194
1194
  trackingProps: EntityProperty<Entity>[];
1195
1195
  hydrateProps: EntityProperty<Entity>[];
1196
+ updateHookProps: EntityProperty<Entity>[];
1196
1197
  validateProps: EntityProperty<Entity>[];
1197
1198
  uniqueProps: EntityProperty<Entity>[];
1198
1199
  getterProps: EntityProperty<Entity>[];
package/typings.js CHANGED
@@ -216,8 +216,13 @@ export class EntityMetadata {
216
216
  const onlyGetter = prop.getter && !prop.setter && prop.persist === false;
217
217
  return !prop.inherited && prop.hydrate !== false && !discriminator && !prop.embedded && !onlyGetter;
218
218
  });
219
+ this.updateHookProps = this.hydrateProps.filter(prop => prop.onUpdate || prop.kind === ReferenceKind.EMBEDDED);
219
220
  this.trackingProps = this.hydrateProps.filter(prop => {
220
- return !prop.getter && !prop.setter && [ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(prop.kind);
221
+ return (!prop.getter &&
222
+ !prop.setter &&
223
+ [ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(prop.kind) &&
224
+ (prop.inversedBy || prop.mappedBy) &&
225
+ !prop.mapToPk);
221
226
  });
222
227
  this.selfReferencing = this.relations.some(prop => {
223
228
  return this.root.uniqueName === prop.targetMeta?.root.uniqueName;
@@ -266,40 +271,37 @@ export class EntityMetadata {
266
271
  this.props.forEach(prop => this.initIndexes(prop));
267
272
  }
268
273
  this.definedProperties = this.trackingProps.reduce((o, prop) => {
269
- const hasInverse = (prop.inversedBy || prop.mappedBy) && !prop.mapToPk;
270
- if (hasInverse) {
271
- // eslint-disable-next-line @typescript-eslint/no-this-alias
272
- const meta = this;
273
- o[prop.name] = {
274
- get() {
275
- return this.__helper.__data[prop.name];
276
- },
277
- set(val) {
278
- const wrapped = this.__helper;
279
- const hydrator = wrapped.hydrator;
280
- const entity = Reference.unwrapReference(val ?? wrapped.__data[prop.name]);
281
- const old = Reference.unwrapReference(wrapped.__data[prop.name]);
282
- if (old &&
283
- old !== entity &&
284
- prop.kind === ReferenceKind.MANY_TO_ONE &&
285
- prop.inversedBy &&
286
- old[prop.inversedBy]) {
287
- old[prop.inversedBy].removeWithoutPropagation(this);
288
- }
289
- wrapped.__data[prop.name] = Reference.wrapReference(val, prop);
290
- // when propagation from inside hydration, we set the FK to the entity data immediately
291
- if (val && hydrator.isRunning() && wrapped.__originalEntityData && prop.owner) {
292
- const targetMeta = prop.targetMeta ?? helper(entity)?.__meta;
293
- if (targetMeta) {
294
- wrapped.__originalEntityData[prop.name] = EntityHelper.getForeignKeyValue(entity, prop, targetMeta);
295
- }
274
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
275
+ const meta = this;
276
+ o[prop.name] = {
277
+ get() {
278
+ return this.__helper.__data[prop.name];
279
+ },
280
+ set(val) {
281
+ const wrapped = this.__helper;
282
+ const hydrator = wrapped.hydrator;
283
+ const entity = Reference.unwrapReference(val ?? wrapped.__data[prop.name]);
284
+ const old = Reference.unwrapReference(wrapped.__data[prop.name]);
285
+ if (old &&
286
+ old !== entity &&
287
+ prop.kind === ReferenceKind.MANY_TO_ONE &&
288
+ prop.inversedBy &&
289
+ old[prop.inversedBy]) {
290
+ old[prop.inversedBy].removeWithoutPropagation(this);
291
+ }
292
+ 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);
296
298
  }
297
- EntityHelper.propagate(meta, entity, this, prop, Reference.unwrapReference(val), old);
298
- },
299
- enumerable: true,
300
- configurable: true,
301
- };
302
- }
299
+ }
300
+ EntityHelper.propagate(meta, entity, this, prop, Reference.unwrapReference(val), old);
301
+ },
302
+ enumerable: true,
303
+ configurable: true,
304
+ };
303
305
  return o;
304
306
  }, { __gettersDefined: { value: true, enumerable: false } });
305
307
  }
@@ -33,13 +33,10 @@ export class ChangeSetComputer {
33
33
  }
34
34
  const wrapped = helper(entity);
35
35
  const type = wrapped.__originalEntityData ? ChangeSetType.UPDATE : ChangeSetType.CREATE;
36
- const map = new Map();
37
- // Execute `onCreate` and `onUpdate` on properties recursively, saves `onUpdate` results
38
- // to the `map` as we want to apply those only if something else changed.
36
+ // execute `onCreate` on properties recursively, update hooks run only after we know there are other changes
39
37
  if (type === ChangeSetType.CREATE) {
40
- // run update hooks only after we know there are other changes
41
38
  for (const prop of meta.hydrateProps) {
42
- this.processPropertyInitializers(entity, prop, type, map);
39
+ this.processPropertyInitializers(entity, prop, type);
43
40
  }
44
41
  }
45
42
  if (type === ChangeSetType.UPDATE && !wrapped.__initialized) {
@@ -57,17 +54,20 @@ export class ChangeSetComputer {
57
54
  }
58
55
  const changeSet = new ChangeSet(entity, type, this.computePayload(entity), meta);
59
56
  changeSet.originalEntity = wrapped.__originalEntityData;
60
- for (const prop of meta.relations.filter(prop => prop.persist !== false || prop.userDefined === false)) {
61
- this.processProperty(changeSet, prop);
57
+ for (const prop of meta.relations) {
58
+ if (prop.persist !== false || prop.userDefined === false) {
59
+ this.processProperty(changeSet, prop);
60
+ }
62
61
  }
63
62
  if (changeSet.type === ChangeSetType.UPDATE && !Utils.hasObjectKeys(changeSet.payload)) {
64
63
  return null;
65
64
  }
66
65
  validateEntity(changeSet.entity, meta);
66
+ const map = new Map();
67
67
  // Execute `onCreate` and `onUpdate` on properties recursively, saves `onUpdate` results
68
68
  // to the `map` as we want to apply those only if something else changed.
69
69
  if (type === ChangeSetType.UPDATE) {
70
- for (const prop of meta.hydrateProps) {
70
+ for (const prop of meta.updateHookProps) {
71
71
  this.processPropertyInitializers(entity, prop, type, map);
72
72
  }
73
73
  }
@@ -107,8 +107,9 @@ export class ChangeSetComputer {
107
107
  }
108
108
  if (prop.kind === ReferenceKind.EMBEDDED && entity[prop.name]) {
109
109
  const items = prop.array ? entity[prop.name] : [entity[prop.name]];
110
+ const embeddedProps = type === ChangeSetType.UPDATE ? prop.targetMeta.updateHookProps : prop.targetMeta.hydrateProps;
110
111
  for (const item of items) {
111
- for (const embeddedProp of prop.targetMeta.hydrateProps) {
112
+ for (const embeddedProp of embeddedProps) {
112
113
  this.processPropertyInitializers(item, embeddedProp, type, map, nested || prop.object);
113
114
  }
114
115
  }
@@ -143,54 +144,58 @@ export class ChangeSetComputer {
143
144
  }
144
145
  return data;
145
146
  }
146
- processProperty(changeSet, prop, target) {
147
- // check for `null`/`undefined` explicitly, the target can be a falsy raw PK value like `0` (e.g. with `mapToPk`)
148
- if (target == null) {
149
- const targets = Utils.unwrapProperty(changeSet.entity, changeSet.meta, prop);
150
- targets.forEach(([t]) => this.processProperty(changeSet, prop, t));
147
+ processProperty(changeSet, prop) {
148
+ if (prop.kind !== ReferenceKind.MANY_TO_ONE && prop.kind !== ReferenceKind.ONE_TO_ONE) {
149
+ // m:n or 1:m
150
+ if (Utils.isCollection(changeSet.entity[prop.name])) {
151
+ this.processToMany(prop, changeSet);
152
+ }
151
153
  return;
152
154
  }
153
- if (Utils.isCollection(target)) {
154
- // m:n or 1:m
155
- this.processToMany(prop, changeSet);
155
+ // only owning to-one sides referencing an entity can add an FK value to the payload
156
+ if ((prop.kind === ReferenceKind.ONE_TO_ONE && !prop.owner) || prop.mapToPk) {
157
+ return;
156
158
  }
157
- if ([ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(prop.kind)) {
158
- this.processToOne(prop, changeSet);
159
+ // perf: a relation outside of embeddables has a single target, so skip the allocations of `unwrapProperty`
160
+ if (!prop.object && !prop.array && !prop.embedded) {
161
+ const target = changeSet.entity[prop.name];
162
+ if (target != null) {
163
+ this.processToOne(prop, changeSet, target, []);
164
+ }
165
+ return;
166
+ }
167
+ const targets = Utils.unwrapProperty(changeSet.entity, changeSet.meta, prop);
168
+ for (const [target, idx] of targets) {
169
+ this.processToOne(prop, changeSet, target, idx);
159
170
  }
160
171
  }
161
- processToOne(prop, changeSet) {
162
- const isToOneOwner = prop.kind === ReferenceKind.MANY_TO_ONE || (prop.kind === ReferenceKind.ONE_TO_ONE && prop.owner);
163
- if (!isToOneOwner || prop.mapToPk) {
172
+ processToOne(prop, changeSet, rawTarget, idx) {
173
+ const target = Reference.unwrapReference(rawTarget);
174
+ // a same-named scalar of another polymorphic embeddable variant is not a reference
175
+ const needsProcessing = Utils.isEntity(target) && (prop.targetKey != null || !target.__helper.hasPrimaryKey());
176
+ if (!needsProcessing) {
164
177
  return;
165
178
  }
166
- const targets = Utils.unwrapProperty(changeSet.entity, changeSet.meta, prop);
167
- targets.forEach(([rawTarget, idx]) => {
168
- const target = Reference.unwrapReference(rawTarget);
169
- // a same-named scalar of another polymorphic embeddable variant is not a reference
170
- const needsProcessing = Utils.isEntity(target) && (prop.targetKey != null || !target.__helper.hasPrimaryKey());
171
- if (needsProcessing) {
172
- // a reference known only by its `targetKey` has no PK, and is never inserted to generate one
173
- if (!prop.targetKey && !target.__helper.__initialized) {
174
- throw ValidationError.referenceWithoutPK(target);
175
- }
176
- // use the actual target's meta, a polymorphic relation has several
177
- let value = prop.targetKey
178
- ? EntityHelper.getForeignKeyValue(target, prop, target.__meta)
179
- : target.__helper.__identifier;
180
- if (prop.polymorphic) {
181
- const discriminator = QueryHelper.findDiscriminatorValue(prop.discriminatorMap, target.constructor);
182
- value = new PolymorphicRef(discriminator, value);
183
- }
184
- // an unchanged `targetKey` FK is not part of the diff
185
- if (prop.targetKey &&
186
- changeSet.type === ChangeSetType.UPDATE &&
187
- !(prop.name in changeSet.payload) &&
188
- Utils.equals(changeSet.originalEntity?.[prop.name], value)) {
189
- return;
190
- }
191
- Utils.setPayloadProperty(changeSet.payload, changeSet.meta, prop, value, idx);
192
- }
193
- });
179
+ // a reference known only by its `targetKey` has no PK, and is never inserted to generate one
180
+ if (!prop.targetKey && !target.__helper.__initialized) {
181
+ throw ValidationError.referenceWithoutPK(target);
182
+ }
183
+ // use the actual target's meta, a polymorphic relation has several
184
+ let value = prop.targetKey
185
+ ? EntityHelper.getForeignKeyValue(target, prop, target.__meta)
186
+ : target.__helper.__identifier;
187
+ if (prop.polymorphic) {
188
+ const discriminator = QueryHelper.findDiscriminatorValue(prop.discriminatorMap, target.constructor);
189
+ value = new PolymorphicRef(discriminator, value);
190
+ }
191
+ // an unchanged `targetKey` FK is not part of the diff
192
+ if (prop.targetKey &&
193
+ changeSet.type === ChangeSetType.UPDATE &&
194
+ !(prop.name in changeSet.payload) &&
195
+ Utils.equals(changeSet.originalEntity?.[prop.name], value)) {
196
+ return;
197
+ }
198
+ Utils.setPayloadProperty(changeSet.payload, changeSet.meta, prop, value, idx);
194
199
  }
195
200
  processToMany(prop, changeSet) {
196
201
  const target = changeSet.entity[prop.name];
@@ -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;