@mikro-orm/core 7.3.0-dev.21 → 7.3.0-dev.23

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.
Files changed (40) hide show
  1. package/EntityManager.d.ts +10 -7
  2. package/EntityManager.js +57 -31
  3. package/drivers/DatabaseDriver.d.ts +2 -0
  4. package/drivers/DatabaseDriver.js +9 -1
  5. package/entity/Collection.d.ts +2 -1
  6. package/entity/Collection.js +21 -13
  7. package/entity/EntityAssigner.js +4 -1
  8. package/entity/EntityFactory.js +19 -7
  9. package/entity/EntityHelper.d.ts +8 -3
  10. package/entity/EntityHelper.js +28 -3
  11. package/entity/EntityLoader.js +44 -1
  12. package/entity/Reference.js +6 -5
  13. package/entity/WrappedEntity.js +1 -1
  14. package/entity/utils.js +3 -1
  15. package/entity/validators.d.ts +6 -0
  16. package/entity/validators.js +14 -0
  17. package/errors.d.ts +1 -0
  18. package/errors.js +3 -0
  19. package/hydration/ObjectHydrator.js +16 -10
  20. package/metadata/MetadataDiscovery.js +26 -5
  21. package/package.json +1 -1
  22. package/platforms/Platform.js +4 -1
  23. package/serialization/EntitySerializer.js +53 -44
  24. package/serialization/EntityTransformer.js +86 -78
  25. package/serialization/SerializationContext.js +1 -1
  26. package/typings.d.ts +5 -1
  27. package/typings.js +36 -34
  28. package/unit-of-work/ChangeSetComputer.js +56 -54
  29. package/unit-of-work/ChangeSetPersister.d.ts +2 -0
  30. package/unit-of-work/ChangeSetPersister.js +10 -5
  31. package/unit-of-work/UnitOfWork.js +53 -23
  32. package/utils/Configuration.d.ts +2 -2
  33. package/utils/Configuration.js +2 -2
  34. package/utils/EntityComparator.js +2 -8
  35. package/utils/QueryHelper.d.ts +6 -0
  36. package/utils/QueryHelper.js +42 -0
  37. package/utils/TransactionManager.js +3 -1
  38. package/utils/Utils.js +27 -6
  39. package/utils/clone.js +6 -1
  40. package/utils/upsert-utils.js +13 -6
@@ -546,7 +546,49 @@ export class EntityLoader {
546
546
  return;
547
547
  }
548
548
  options = { ...options, filters: QueryHelper.mergePropertyFilters(prop.filters, options.filters) };
549
+ // collections with unflushed changes, their items would be lost when reloading
550
+ const dirty = options.refresh
551
+ ? []
552
+ : entities
553
+ .map(e => e[field])
554
+ .filter(coll => Utils.isCollection(coll) && coll.isDirty())
555
+ .map(coll => [coll, coll.getItems(false), coll.getSnapshot()]);
556
+ // grouped by type, as a polymorphic collection can hold references of several entity types
557
+ const references = new Map();
558
+ for (const [, items] of populate.field.includes(':') ? [] : dirty) {
559
+ for (const item of items.filter(i => !helper(i).__initialized)) {
560
+ const group = references.get(helper(item).__meta) ?? [];
561
+ group.push(item);
562
+ references.set(helper(item).__meta, group);
563
+ }
564
+ }
565
+ // loading the references directly keeps an initialized collection from being reloaded
566
+ for (const [meta, items] of references) {
567
+ await this.populateScalar(meta, items, {
568
+ ...options,
569
+ where: {},
570
+ populateWhere: undefined,
571
+ fields: this.buildFields(options.fields, prop),
572
+ });
573
+ }
549
574
  const populated = await this.populateMany(entityName, entities, populate, options);
575
+ for (const [coll, items, snapshot] of dirty) {
576
+ // partially loaded collections can be readonly
577
+ if (coll.isPartial()) {
578
+ continue;
579
+ }
580
+ const kept = new Set(items);
581
+ // only the diff against the snapshot is restored, a missing snapshot means the collection was overridden via `set()`
582
+ const known = snapshot && new Set(snapshot);
583
+ const lost = items.filter(item => !coll.contains(item, false) && !known?.has(item));
584
+ const removed = coll.getItems(false).filter(item => !kept.has(item) && (!known || known.has(item)));
585
+ if (lost.length > 0) {
586
+ coll.add(lost);
587
+ }
588
+ if (removed.length > 0) {
589
+ coll.remove(removed);
590
+ }
591
+ }
550
592
  if (!populate.children && !populate.all) {
551
593
  return;
552
594
  }
@@ -689,7 +731,8 @@ export class EntityLoader {
689
731
  convertCustomTypes: true,
690
732
  schema: options.schema ?? this.#em.config.get('schema'),
691
733
  });
692
- return this.#em.getUnitOfWork().register(entity, item, { refresh, loaded: true });
734
+ // the factory already registered the snapshot, the raw row is not comparable
735
+ return this.#em.getUnitOfWork().register(entity, undefined, { loaded: true });
693
736
  });
694
737
  const hasLimit = populate?.limit != null;
695
738
  entity[prop.name].hydrate(items, true, hasLimit, hasLimit);
@@ -5,7 +5,8 @@ import { QueryHelper } from '../utils/QueryHelper.js';
5
5
  import { NotFoundError } from '../errors.js';
6
6
  import { inspect } from '../logging/inspect.js';
7
7
  // Globally registered so the markers survive the CJS/ESM dual-package hazard
8
- // (see entitySymbol rationale in EntityHelper.ts and #7515/#7534).
8
+ // (see entitySymbol rationale in EntityHelper.ts and #7515/#7534). Live on the
9
+ // prototypes; JSON payloads cannot produce symbol keys, so they cannot forge them.
9
10
  const referenceSymbol = Symbol.for('@mikro-orm/core/Reference');
10
11
  const scalarReferenceSymbol = Symbol.for('@mikro-orm/core/ScalarReference');
11
12
  /** Wrapper around an entity that provides lazy loading capabilities and identity-preserving reference semantics. */
@@ -14,7 +15,6 @@ export class Reference {
14
15
  property;
15
16
  constructor(entity) {
16
17
  this.entity = entity;
17
- Object.defineProperty(this, referenceSymbol, { value: true, enumerable: false });
18
18
  this.set(entity);
19
19
  const meta = helper(this.entity).__meta;
20
20
  meta.primaryKeys.forEach(primaryKey => {
@@ -68,7 +68,7 @@ export class Reference {
68
68
  * Checks whether the argument is instance of `Reference` wrapper.
69
69
  */
70
70
  static isReference(data) {
71
- return data != null && Object.hasOwn(data, referenceSymbol);
71
+ return typeof data === 'object' && data !== null && data[referenceSymbol] === true;
72
72
  }
73
73
  /**
74
74
  * Wraps the entity in a `Reference` wrapper if the property is defined as `ref`.
@@ -184,7 +184,6 @@ export class ScalarReference {
184
184
  #initialized;
185
185
  constructor(value, initialized = value != null) {
186
186
  this.value = value;
187
- Object.defineProperty(this, scalarReferenceSymbol, { value: true, enumerable: false });
188
187
  this.#initialized = initialized;
189
188
  }
190
189
  /**
@@ -235,7 +234,7 @@ export class ScalarReference {
235
234
  return this.#initialized;
236
235
  }
237
236
  static isScalarReference(data) {
238
- return data != null && typeof data === 'object' && Object.hasOwn(data, scalarReferenceSymbol);
237
+ return data != null && typeof data === 'object' && data[scalarReferenceSymbol] === true;
239
238
  }
240
239
  /** @ignore */
241
240
  /* v8 ignore next */
@@ -244,6 +243,7 @@ export class ScalarReference {
244
243
  }
245
244
  }
246
245
  Object.defineProperties(Reference.prototype, {
246
+ [referenceSymbol]: { value: true },
247
247
  __meta: {
248
248
  get() {
249
249
  return this.entity.__meta;
@@ -271,6 +271,7 @@ Object.defineProperties(Reference.prototype, {
271
271
  },
272
272
  });
273
273
  Object.defineProperties(ScalarReference.prototype, {
274
+ [scalarReferenceSymbol]: { value: true },
274
275
  $: {
275
276
  get() {
276
277
  return this.value;
@@ -110,7 +110,7 @@ export class WrappedEntity {
110
110
  }
111
111
  /** Returns the primary key value, optionally converting custom types to their database representation. */
112
112
  getPrimaryKey(convertCustomTypes = false) {
113
- const prop = this.__meta.getPrimaryProps()[0];
113
+ const prop = this.__meta.getPrimaryProp();
114
114
  if (!prop) {
115
115
  return null;
116
116
  }
package/entity/utils.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { LoadStrategy, PopulatePath, ReferenceKind } from '../enums.js';
2
2
  import { Utils } from '../utils/Utils.js';
3
+ import { validatePaginationValue } from './validators.js';
3
4
  /**
4
5
  * Expands `books.perex` like populate to use `children` array instead of the dot syntax
5
6
  */
@@ -96,7 +97,8 @@ export function applyPopulateHints(populate, hints) {
96
97
  }
97
98
  for (const key of Object.keys(hint)) {
98
99
  if (hint[key] != null) {
99
- entry[key] = hint[key];
100
+ entry[key] =
101
+ key === 'limit' || key === 'offset' ? validatePaginationValue(hint[key], key) : hint[key];
100
102
  }
101
103
  }
102
104
  }
@@ -5,6 +5,12 @@ export declare function validateProperty<T extends object>(prop: EntityProperty,
5
5
  export declare function validateEntity<T extends object>(entity: T, meta: EntityMetadata<T>): void;
6
6
  /** @internal */
7
7
  export declare function validateParams(params: any, type?: string, field?: string): void;
8
+ /**
9
+ * Converts a numeric string passed as `limit`/`offset`-like value (e.g. from a query string) to a number,
10
+ * other strings are rejected, non-string values are returned as is.
11
+ * @internal
12
+ */
13
+ export declare function validatePaginationValue<T>(value: T, option: string): T;
8
14
  /** @internal */
9
15
  export declare function validatePrimaryKey<T>(entity: EntityData<T>, meta: EntityMetadata<T>): void;
10
16
  /** @internal */
@@ -53,6 +53,20 @@ export function validateParams(params, type = 'search condition', field) {
53
53
  Object.keys(params).forEach(k => validateParams(params[k], type, k));
54
54
  }
55
55
  }
56
+ /**
57
+ * Converts a numeric string passed as `limit`/`offset`-like value (e.g. from a query string) to a number,
58
+ * other strings are rejected, non-string values are returned as is.
59
+ * @internal
60
+ */
61
+ export function validatePaginationValue(value, option) {
62
+ if (typeof value !== 'string') {
63
+ return value;
64
+ }
65
+ if (!/^\d+$/.test(value)) {
66
+ throw ValidationError.invalidPaginationValue(option, value);
67
+ }
68
+ return +value;
69
+ }
56
70
  /** @internal */
57
71
  export function validatePrimaryKey(entity, meta) {
58
72
  const pkExists = meta.primaryKeys.every(pk => entity[pk] != null) ||
package/errors.d.ts CHANGED
@@ -37,6 +37,7 @@ export declare class ValidationError<T extends AnyEntity = AnyEntity> extends Er
37
37
  static cannotUseGroupOperatorsInsideScalars(entityName: EntityName, propName: string, payload: unknown): ValidationError;
38
38
  static invalidEmbeddableQuery(entityName: EntityName, propName: string, embeddableType: string): ValidationError;
39
39
  static invalidQueryCondition(cond: unknown): ValidationError;
40
+ static invalidPaginationValue(option: string, value: unknown): ValidationError;
40
41
  }
41
42
  /** Error thrown when cursor-based pagination encounters missing or invalid cursor values. */
42
43
  export declare class CursorError<T extends AnyEntity = AnyEntity> extends ValidationError<T> {
package/errors.js CHANGED
@@ -134,6 +134,9 @@ export class ValidationError extends Error {
134
134
  static invalidQueryCondition(cond) {
135
135
  return new ValidationError(`Invalid query condition: ${inspect(cond, { depth: 5 })}`);
136
136
  }
137
+ static invalidPaginationValue(option, value) {
138
+ return new ValidationError(`Invalid '${option}' value ${inspect(value)}, expected a number or a string with a non-negative integer.`);
139
+ }
137
140
  }
138
141
  /** Error thrown when cursor-based pagination encounters missing or invalid cursor values. */
139
142
  export class CursorError extends ValidationError {
@@ -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) {
@@ -426,8 +426,18 @@ export class MetadataDiscovery {
426
426
  if (!prop.ownColumns || prop.ownColumns.length === 0) {
427
427
  prop.ownColumns = prop.joinColumns;
428
428
  }
429
+ if (prop.joinColumns.length !== prop.referencedColumnNames.length) {
430
+ throw MetadataError.fromWrongForeignKey(meta, prop, 'referencedColumnNames');
431
+ }
432
+ // the FK can reference other columns than the target PK, e.g. the PK plus a column of a composite unique key
433
+ const referencedProps = prop.referencedColumnNames.map(col => prop.targetMeta.props.find(p => p.fieldNames?.includes(col)));
429
434
  if (prop.joinColumns.length !== prop.columnTypes.length) {
430
- prop.columnTypes = prop.joinColumns.flatMap(field => {
435
+ prop.columnTypes = prop.joinColumns.flatMap((field, idx) => {
436
+ const referenced = referencedProps[idx];
437
+ // the PK columns are already typed by `initColumnType()` (e.g. without autoincrement)
438
+ if (referenced && !referenced.primary) {
439
+ return [referenced.columnTypes[referenced.fieldNames.indexOf(prop.referencedColumnNames[idx])]];
440
+ }
431
441
  const matched = meta.props.find(p => p.fieldNames?.includes(field));
432
442
  /* v8 ignore next */
433
443
  if (!matched) {
@@ -436,8 +446,13 @@ export class MetadataDiscovery {
436
446
  return matched.columnTypes;
437
447
  });
438
448
  }
439
- if (prop.joinColumns.length !== prop.referencedColumnNames.length) {
440
- throw MetadataError.fromWrongForeignKey(meta, prop, 'referencedColumnNames');
449
+ // when the relation owns all the FK columns, the extra ones are filled from the target entity on write
450
+ if (!prop.mapToPk &&
451
+ !prop.embedded &&
452
+ prop.ownColumns.length === prop.joinColumns.length &&
453
+ referencedProps.every((p) => p != null) &&
454
+ referencedProps.some(p => !p.primary)) {
455
+ prop.referencedProps = referencedProps;
441
456
  }
442
457
  }
443
458
  }
@@ -1193,7 +1208,9 @@ export class MetadataDiscovery {
1193
1208
  if (meta.inheritanceType !== 'tpt' || !meta.tptParent) {
1194
1209
  meta.indexes = Utils.unique([...base.indexes, ...meta.indexes], Utils.equals);
1195
1210
  meta.uniques = Utils.unique([...base.uniques, ...meta.uniques], Utils.equals);
1196
- meta.checks = Utils.unique([...base.checks, ...meta.checks], Utils.equals);
1211
+ // the STI root also collects checks bound to properties of other subtypes
1212
+ const baseChecks = base.checks.filter(check => !check.property || meta.properties[check.property]);
1213
+ meta.checks = Utils.unique([...baseChecks, ...meta.checks], Utils.equals);
1197
1214
  meta.triggers = Utils.unique([...base.triggers, ...meta.triggers], Utils.equals);
1198
1215
  }
1199
1216
  // Policies pass down only from inlined abstract bases; STI children share the root table
@@ -1552,11 +1569,15 @@ export class MetadataDiscovery {
1552
1569
  // that as matching so the rename branch below doesn't run (which would
1553
1570
  // crash — `targetMeta` is only populated later, in `initRelation`).
1554
1571
  const narrowedRelationOverride = rootProp != null && rootProp.type !== prop.type && this.sameRelationTargetRoot(rootProp, prop);
1572
+ // The root can hold another instance of the same custom type (e.g. the copy made for a polymorphic embeddable), so those are compared by class.
1573
+ const sameTypeClass = Type.isMappedType(rootProp?.type) &&
1574
+ Type.isMappedType(prop.type) &&
1575
+ rootProp.type.constructor === prop.type.constructor;
1555
1576
  // stiMerged is set during inlineProperties when a property was merged
1556
1577
  // from multiple polymorphic variants with different types. The flag is
1557
1578
  // cleared implicitly when the first child claims the root property via
1558
1579
  // addProperty below, so subsequent children correctly trigger renaming.
1559
- const typesMatch = rootProp?.type === prop.type || rootProp?.stiMerged === true || narrowedRelationOverride;
1580
+ const typesMatch = rootProp?.type === prop.type || sameTypeClass || rootProp?.stiMerged === true || narrowedRelationOverride;
1560
1581
  // Inverse-side relations (1:m, inverse m:n) have no FK column on this
1561
1582
  // entity, so the rename branch — which exists to disambiguate physical
1562
1583
  // columns shared across STI children — doesn't apply. Skipping it also
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mikro-orm/core",
3
- "version": "7.3.0-dev.21",
3
+ "version": "7.3.0-dev.23",
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",
@@ -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() {
@@ -81,57 +81,66 @@ export class EntitySerializer {
81
81
  root = new SerializationContext();
82
82
  contextCreated = true;
83
83
  }
84
- SerializationContext.propagate(root, entity, (meta, prop) => meta.properties[prop]?.kind !== ReferenceKind.SCALAR);
85
84
  const ret = {};
86
- const props = new Set();
87
- if (meta.serializedPrimaryKey && !meta.compositePK) {
88
- props.add(meta.serializedPrimaryKey);
89
- }
90
- else {
91
- meta.primaryKeys.forEach(pk => props.add(pk));
92
- }
93
- if (wrapped.isInitialized() || !wrapped.hasPrimaryKey()) {
94
- const entityKeys = new Set(Object.keys(entity));
95
- for (const prop of meta.props) {
96
- if (entityKeys.has(prop.name) || (prop.getter && prop.accessor === prop.name)) {
97
- props.add(prop.name);
98
- }
85
+ try {
86
+ SerializationContext.propagate(root, entity, (meta, prop) => meta.properties[prop]?.kind !== ReferenceKind.SCALAR);
87
+ const props = new Set();
88
+ if (meta.serializedPrimaryKey && !meta.compositePK) {
89
+ props.add(meta.serializedPrimaryKey);
99
90
  }
100
- for (const key of entityKeys) {
101
- if (!meta.properties[key]) {
102
- props.add(key);
103
- }
104
- }
105
- }
106
- const visited = root.visited.has(entity);
107
- if (!visited) {
108
- root.visited.add(entity);
109
- }
110
- for (const prop of props) {
111
- if (!isVisible(meta, prop, options)) {
112
- continue;
113
- }
114
- const cycle = root.visit(meta.class, prop);
115
- if (cycle && visited) {
116
- continue;
117
- }
118
- const val = this.processProperty(prop, entity, options);
119
- if (!cycle) {
120
- root.leave(meta.class, prop);
91
+ else {
92
+ meta.primaryKeys.forEach(pk => props.add(pk));
121
93
  }
122
- if (options.skipNull && Utils.isPlainObject(val)) {
123
- Utils.dropUndefinedProperties(val, null);
94
+ if (wrapped.isInitialized() || !wrapped.hasPrimaryKey()) {
95
+ for (const prop of meta.props) {
96
+ if (Object.prototype.propertyIsEnumerable.call(entity, prop.name) ||
97
+ (prop.getter && prop.accessor === prop.name)) {
98
+ props.add(prop.name);
99
+ }
100
+ }
101
+ for (const key of Object.keys(entity)) {
102
+ if (!meta.properties[key]) {
103
+ props.add(key);
104
+ }
105
+ }
124
106
  }
125
- if (isRaw(val)) {
126
- throw new Error(`Trying to serialize raw SQL fragment: '${val.sql}'`);
107
+ const visited = root.visited.has(entity);
108
+ if (!visited) {
109
+ root.visited.add(entity);
127
110
  }
128
- const visible = typeof val !== 'undefined' && !(val === null && options.skipNull);
129
- if (visible) {
130
- ret[this.propertyName(meta, prop)] = val;
111
+ for (const prop of props) {
112
+ if (!isVisible(meta, prop, options)) {
113
+ continue;
114
+ }
115
+ const cycle = root.visit(meta.class, prop);
116
+ if (cycle && visited) {
117
+ continue;
118
+ }
119
+ let val;
120
+ try {
121
+ val = this.processProperty(prop, entity, options);
122
+ }
123
+ finally {
124
+ if (!cycle) {
125
+ root.leave(meta.class, prop);
126
+ }
127
+ }
128
+ if (options.skipNull && Utils.isPlainObject(val)) {
129
+ Utils.dropUndefinedProperties(val, null);
130
+ }
131
+ if (isRaw(val)) {
132
+ throw new Error(`Trying to serialize raw SQL fragment: '${val.sql}'`);
133
+ }
134
+ const visible = typeof val !== 'undefined' && !(val === null && options.skipNull);
135
+ if (visible) {
136
+ ret[this.propertyName(meta, prop)] = val;
137
+ }
131
138
  }
132
139
  }
133
- if (contextCreated) {
134
- root.close();
140
+ finally {
141
+ if (contextCreated) {
142
+ root.close();
143
+ }
135
144
  }
136
145
  if (!wrapped.isInitialized()) {
137
146
  return ret;