@mikro-orm/core 7.0.0-dev.9 → 7.0.0-dev.90

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 (191) hide show
  1. package/EntityManager.d.ts +77 -48
  2. package/EntityManager.js +288 -225
  3. package/MikroORM.d.ts +40 -31
  4. package/MikroORM.js +98 -137
  5. package/README.md +3 -2
  6. package/cache/FileCacheAdapter.d.ts +1 -1
  7. package/cache/FileCacheAdapter.js +6 -5
  8. package/cache/GeneratedCacheAdapter.d.ts +0 -1
  9. package/cache/GeneratedCacheAdapter.js +0 -2
  10. package/cache/index.d.ts +0 -1
  11. package/cache/index.js +0 -1
  12. package/connections/Connection.d.ts +11 -7
  13. package/connections/Connection.js +16 -14
  14. package/drivers/DatabaseDriver.d.ts +11 -5
  15. package/drivers/DatabaseDriver.js +23 -11
  16. package/drivers/IDatabaseDriver.d.ts +25 -4
  17. package/entity/BaseEntity.d.ts +0 -1
  18. package/entity/BaseEntity.js +0 -3
  19. package/entity/Collection.d.ts +95 -30
  20. package/entity/Collection.js +432 -93
  21. package/entity/EntityAssigner.d.ts +1 -1
  22. package/entity/EntityAssigner.js +17 -9
  23. package/entity/EntityFactory.d.ts +7 -0
  24. package/entity/EntityFactory.js +63 -41
  25. package/entity/EntityHelper.js +26 -12
  26. package/entity/EntityLoader.d.ts +5 -4
  27. package/entity/EntityLoader.js +63 -38
  28. package/entity/EntityRepository.d.ts +1 -1
  29. package/entity/Reference.d.ts +6 -5
  30. package/entity/Reference.js +34 -9
  31. package/entity/WrappedEntity.d.ts +2 -7
  32. package/entity/WrappedEntity.js +2 -7
  33. package/entity/defineEntity.d.ts +568 -0
  34. package/entity/defineEntity.js +529 -0
  35. package/entity/index.d.ts +3 -2
  36. package/entity/index.js +3 -2
  37. package/entity/utils.d.ts +7 -0
  38. package/entity/utils.js +16 -4
  39. package/entity/validators.d.ts +11 -0
  40. package/entity/validators.js +65 -0
  41. package/enums.d.ts +21 -6
  42. package/enums.js +14 -1
  43. package/errors.d.ts +10 -2
  44. package/errors.js +29 -10
  45. package/events/EventManager.d.ts +2 -1
  46. package/events/EventManager.js +19 -11
  47. package/events/EventSubscriber.d.ts +3 -1
  48. package/hydration/Hydrator.js +1 -2
  49. package/hydration/ObjectHydrator.d.ts +4 -4
  50. package/hydration/ObjectHydrator.js +35 -25
  51. package/index.d.ts +2 -2
  52. package/index.js +1 -2
  53. package/logging/DefaultLogger.d.ts +1 -1
  54. package/logging/DefaultLogger.js +1 -0
  55. package/logging/SimpleLogger.d.ts +1 -1
  56. package/logging/index.d.ts +1 -0
  57. package/logging/index.js +1 -0
  58. package/logging/inspect.d.ts +2 -0
  59. package/logging/inspect.js +16 -0
  60. package/metadata/EntitySchema.d.ts +9 -13
  61. package/metadata/EntitySchema.js +44 -26
  62. package/metadata/MetadataDiscovery.d.ts +6 -9
  63. package/metadata/MetadataDiscovery.js +165 -205
  64. package/metadata/MetadataProvider.d.ts +11 -2
  65. package/metadata/MetadataProvider.js +44 -2
  66. package/metadata/MetadataStorage.d.ts +1 -6
  67. package/metadata/MetadataStorage.js +6 -18
  68. package/metadata/MetadataValidator.d.ts +0 -7
  69. package/metadata/MetadataValidator.js +0 -10
  70. package/metadata/discover-entities.d.ts +5 -0
  71. package/metadata/discover-entities.js +40 -0
  72. package/metadata/index.d.ts +1 -1
  73. package/metadata/index.js +1 -1
  74. package/metadata/types.d.ts +480 -0
  75. package/metadata/types.js +1 -0
  76. package/naming-strategy/AbstractNamingStrategy.d.ts +5 -1
  77. package/naming-strategy/AbstractNamingStrategy.js +8 -2
  78. package/naming-strategy/NamingStrategy.d.ts +11 -1
  79. package/not-supported.d.ts +2 -0
  80. package/not-supported.js +4 -0
  81. package/package.json +18 -10
  82. package/platforms/ExceptionConverter.js +1 -1
  83. package/platforms/Platform.d.ts +6 -13
  84. package/platforms/Platform.js +15 -41
  85. package/serialization/EntitySerializer.d.ts +2 -0
  86. package/serialization/EntitySerializer.js +32 -14
  87. package/serialization/EntityTransformer.js +22 -12
  88. package/serialization/SerializationContext.js +16 -13
  89. package/types/ArrayType.d.ts +1 -1
  90. package/types/ArrayType.js +2 -3
  91. package/types/BigIntType.d.ts +8 -6
  92. package/types/BigIntType.js +1 -1
  93. package/types/BlobType.d.ts +0 -1
  94. package/types/BlobType.js +0 -3
  95. package/types/BooleanType.d.ts +2 -1
  96. package/types/BooleanType.js +3 -0
  97. package/types/DecimalType.d.ts +6 -4
  98. package/types/DecimalType.js +3 -3
  99. package/types/DoubleType.js +2 -2
  100. package/types/EnumArrayType.js +1 -2
  101. package/types/JsonType.d.ts +1 -1
  102. package/types/JsonType.js +7 -2
  103. package/types/TinyIntType.js +1 -1
  104. package/types/Type.d.ts +2 -4
  105. package/types/Type.js +3 -3
  106. package/types/Uint8ArrayType.d.ts +0 -1
  107. package/types/Uint8ArrayType.js +1 -4
  108. package/types/index.d.ts +1 -1
  109. package/typings.d.ts +109 -73
  110. package/typings.js +38 -35
  111. package/unit-of-work/ChangeSet.d.ts +0 -3
  112. package/unit-of-work/ChangeSet.js +2 -2
  113. package/unit-of-work/ChangeSetComputer.d.ts +1 -3
  114. package/unit-of-work/ChangeSetComputer.js +11 -9
  115. package/unit-of-work/ChangeSetPersister.d.ts +5 -4
  116. package/unit-of-work/ChangeSetPersister.js +51 -19
  117. package/unit-of-work/UnitOfWork.d.ts +8 -1
  118. package/unit-of-work/UnitOfWork.js +91 -49
  119. package/utils/AbstractSchemaGenerator.d.ts +5 -5
  120. package/utils/AbstractSchemaGenerator.js +11 -9
  121. package/utils/Configuration.d.ts +757 -206
  122. package/utils/Configuration.js +140 -188
  123. package/utils/ConfigurationLoader.d.ts +1 -54
  124. package/utils/ConfigurationLoader.js +1 -352
  125. package/utils/Cursor.d.ts +0 -3
  126. package/utils/Cursor.js +6 -3
  127. package/utils/DataloaderUtils.d.ts +15 -5
  128. package/utils/DataloaderUtils.js +54 -8
  129. package/utils/EntityComparator.d.ts +8 -4
  130. package/utils/EntityComparator.js +52 -17
  131. package/utils/QueryHelper.d.ts +9 -1
  132. package/utils/QueryHelper.js +70 -9
  133. package/utils/RawQueryFragment.d.ts +36 -13
  134. package/utils/RawQueryFragment.js +36 -16
  135. package/utils/TransactionManager.d.ts +65 -0
  136. package/utils/TransactionManager.js +223 -0
  137. package/utils/Utils.d.ts +8 -97
  138. package/utils/Utils.js +82 -302
  139. package/utils/clone.js +2 -3
  140. package/utils/env-vars.d.ts +3 -0
  141. package/utils/env-vars.js +87 -0
  142. package/utils/fs-utils.d.ts +12 -0
  143. package/utils/fs-utils.js +97 -0
  144. package/utils/index.d.ts +2 -1
  145. package/utils/index.js +2 -1
  146. package/utils/upsert-utils.d.ts +7 -2
  147. package/utils/upsert-utils.js +55 -4
  148. package/decorators/Check.d.ts +0 -3
  149. package/decorators/Check.js +0 -13
  150. package/decorators/CreateRequestContext.d.ts +0 -3
  151. package/decorators/CreateRequestContext.js +0 -32
  152. package/decorators/Embeddable.d.ts +0 -8
  153. package/decorators/Embeddable.js +0 -11
  154. package/decorators/Embedded.d.ts +0 -18
  155. package/decorators/Embedded.js +0 -18
  156. package/decorators/Entity.d.ts +0 -18
  157. package/decorators/Entity.js +0 -12
  158. package/decorators/Enum.d.ts +0 -9
  159. package/decorators/Enum.js +0 -16
  160. package/decorators/Filter.d.ts +0 -2
  161. package/decorators/Filter.js +0 -8
  162. package/decorators/Formula.d.ts +0 -4
  163. package/decorators/Formula.js +0 -15
  164. package/decorators/Indexed.d.ts +0 -19
  165. package/decorators/Indexed.js +0 -20
  166. package/decorators/ManyToMany.d.ts +0 -40
  167. package/decorators/ManyToMany.js +0 -14
  168. package/decorators/ManyToOne.d.ts +0 -30
  169. package/decorators/ManyToOne.js +0 -14
  170. package/decorators/OneToMany.d.ts +0 -28
  171. package/decorators/OneToMany.js +0 -17
  172. package/decorators/OneToOne.d.ts +0 -24
  173. package/decorators/OneToOne.js +0 -7
  174. package/decorators/PrimaryKey.d.ts +0 -8
  175. package/decorators/PrimaryKey.js +0 -20
  176. package/decorators/Property.d.ts +0 -250
  177. package/decorators/Property.js +0 -32
  178. package/decorators/Transactional.d.ts +0 -13
  179. package/decorators/Transactional.js +0 -28
  180. package/decorators/hooks.d.ts +0 -16
  181. package/decorators/hooks.js +0 -47
  182. package/decorators/index.d.ts +0 -17
  183. package/decorators/index.js +0 -17
  184. package/entity/ArrayCollection.d.ts +0 -116
  185. package/entity/ArrayCollection.js +0 -402
  186. package/entity/EntityValidator.d.ts +0 -19
  187. package/entity/EntityValidator.js +0 -150
  188. package/metadata/ReflectMetadataProvider.d.ts +0 -8
  189. package/metadata/ReflectMetadataProvider.js +0 -44
  190. package/utils/resolveContextProvider.d.ts +0 -10
  191. package/utils/resolveContextProvider.js +0 -28
package/typings.js CHANGED
@@ -32,7 +32,7 @@ export class EntityMetadata {
32
32
  }
33
33
  this.properties[prop.name] = prop;
34
34
  this.propertyOrder.set(prop.name, this.props.length);
35
- /* v8 ignore next 3 */
35
+ /* v8 ignore next */
36
36
  if (sync) {
37
37
  this.sync();
38
38
  }
@@ -40,17 +40,34 @@ export class EntityMetadata {
40
40
  removeProperty(name, sync = true) {
41
41
  delete this.properties[name];
42
42
  this.propertyOrder.delete(name);
43
- /* v8 ignore next 3 */
43
+ /* v8 ignore next */
44
44
  if (sync) {
45
45
  this.sync();
46
46
  }
47
47
  }
48
- getPrimaryProps() {
49
- return this.primaryKeys.map(pk => this.properties[pk]);
48
+ getPrimaryProps(flatten = false) {
49
+ const pks = this.primaryKeys.map(pk => this.properties[pk]);
50
+ if (flatten) {
51
+ return pks.flatMap(pk => {
52
+ if ([ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(pk.kind)) {
53
+ return pk.targetMeta.getPrimaryProps(true);
54
+ }
55
+ return [pk];
56
+ });
57
+ }
58
+ return pks;
50
59
  }
51
60
  getPrimaryProp() {
52
61
  return this.properties[this.primaryKeys[0]];
53
62
  }
63
+ createColumnMappingObject() {
64
+ return Object.values(this.properties).reduce((o, prop) => {
65
+ if (prop.fieldNames) {
66
+ o[prop.name] = prop.fieldNames[0];
67
+ }
68
+ return o;
69
+ }, {});
70
+ }
54
71
  get tableName() {
55
72
  return this.collection;
56
73
  }
@@ -66,23 +83,30 @@ export class EntityMetadata {
66
83
  this.uniqueProps = this.props.filter(prop => prop.unique);
67
84
  this.getterProps = this.props.filter(prop => prop.getter);
68
85
  this.comparableProps = this.props.filter(prop => EntityComparator.isComparable(prop, this));
86
+ this.validateProps = this.props.filter(prop => {
87
+ if (prop.inherited || (prop.persist === false && prop.userDefined !== false)) {
88
+ return false;
89
+ }
90
+ return prop.kind === ReferenceKind.SCALAR && ['string', 'number', 'boolean', 'Date'].includes(prop.type);
91
+ });
69
92
  this.hydrateProps = this.props.filter(prop => {
70
93
  // `prop.userDefined` is either `undefined` or `false`
71
94
  const discriminator = this.root.discriminatorColumn === prop.name && prop.userDefined === false;
72
95
  // even if we don't have a setter, do not ignore value from database!
73
- const onlyGetter = prop.getter && !prop.setter;
96
+ const onlyGetter = prop.getter && !prop.setter && prop.persist === false;
74
97
  return !prop.inherited && prop.hydrate !== false && !discriminator && !prop.embedded && !onlyGetter;
75
98
  });
76
- this.trackingProps = this.hydrateProps
77
- .filter(prop => !prop.getter && !prop.setter && prop.trackChanges !== false)
78
- .filter(prop => ![ReferenceKind.ONE_TO_MANY, ReferenceKind.MANY_TO_MANY].includes(prop.kind))
79
- .filter(prop => !prop.serializedPrimaryKey);
80
- this.selfReferencing = this.relations.some(prop => [this.className, this.root.className].includes(prop.targetMeta?.root.className ?? prop.type));
99
+ this.trackingProps = this.hydrateProps.filter(prop => {
100
+ return !prop.getter && !prop.setter && [ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(prop.kind);
101
+ });
102
+ this.selfReferencing = this.relations.some(prop => {
103
+ return [this.className, this.root.className].includes(prop.targetMeta?.root.className ?? prop.type);
104
+ });
81
105
  this.hasUniqueProps = this.uniques.length + this.uniqueProps.length > 0;
82
106
  this.virtual = !!this.expression;
83
107
  if (config) {
84
108
  for (const prop of this.props) {
85
- if (prop.enum && !prop.nativeEnumName && prop.items?.every(item => Utils.isString(item))) {
109
+ if (prop.enum && !prop.nativeEnumName && prop.items?.every(item => typeof item === 'string')) {
86
110
  const name = config.getNamingStrategy().indexName(this.tableName, prop.fieldNames, 'check');
87
111
  const exists = this.checks.findIndex(check => check.name === name);
88
112
  if (exists !== -1) {
@@ -109,8 +133,7 @@ export class EntityMetadata {
109
133
  this.props.forEach(prop => this.initIndexes(prop));
110
134
  }
111
135
  this.definedProperties = this.trackingProps.reduce((o, prop) => {
112
- const isCollection = [ReferenceKind.ONE_TO_MANY, ReferenceKind.MANY_TO_MANY].includes(prop.kind);
113
- const isReference = [ReferenceKind.ONE_TO_ONE, ReferenceKind.MANY_TO_ONE].includes(prop.kind) && (prop.inversedBy || prop.mappedBy) && !prop.mapToPk;
136
+ const isReference = (prop.inversedBy || prop.mappedBy) && !prop.mapToPk;
114
137
  if (isReference) {
115
138
  // eslint-disable-next-line @typescript-eslint/no-this-alias
116
139
  const meta = this;
@@ -129,10 +152,7 @@ export class EntityMetadata {
129
152
  wrapped.__data[prop.name] = Reference.wrapReference(val, prop);
130
153
  // when propagation from inside hydration, we set the FK to the entity data immediately
131
154
  if (val && hydrator.isRunning() && wrapped.__originalEntityData && prop.owner) {
132
- wrapped.__originalEntityData[prop.name] = Utils.getPrimaryKeyValues(val, prop.targetMeta.primaryKeys, true);
133
- }
134
- else {
135
- wrapped.__touched = !hydrator.isRunning();
155
+ wrapped.__originalEntityData[prop.name] = Utils.getPrimaryKeyValues(val, prop.targetMeta, true);
136
156
  }
137
157
  EntityHelper.propagate(meta, entity, this, prop, Reference.unwrapReference(val), old);
138
158
  },
@@ -140,23 +160,6 @@ export class EntityMetadata {
140
160
  configurable: true,
141
161
  };
142
162
  }
143
- if (prop.inherited || prop.primary || isCollection || prop.persist === false || prop.trackChanges === false || isReference || prop.embedded) {
144
- return o;
145
- }
146
- o[prop.name] = {
147
- get() {
148
- return this.__helper.__data[prop.name];
149
- },
150
- set(val) {
151
- if (typeof val === 'object' && !!val && '__raw' in val) {
152
- val.assign();
153
- }
154
- this.__helper.__data[prop.name] = val;
155
- this.__helper.__touched = !this.__helper.hydrator.isRunning();
156
- },
157
- enumerable: true,
158
- configurable: true,
159
- };
160
163
  return o;
161
164
  }, { __gettersDefined: { value: true, enumerable: false } });
162
165
  }
@@ -178,7 +181,7 @@ export class EntityMetadata {
178
181
  this.indexes.push({ properties: prop.name });
179
182
  prop.index = false;
180
183
  }
181
- /* v8 ignore next 4 */
184
+ /* v8 ignore next */
182
185
  if (owner && prop.fieldNames.length > 1 && prop.unique) {
183
186
  this.uniques.push({ properties: prop.name });
184
187
  prop.unique = false;
@@ -1,4 +1,3 @@
1
- import { inspect } from 'node:util';
2
1
  import type { EntityData, EntityMetadata, EntityDictionary, Primary } from '../typings.js';
3
2
  export declare class ChangeSet<T extends object> {
4
3
  entity: T;
@@ -10,8 +9,6 @@ export declare class ChangeSet<T extends object> {
10
9
  constructor(entity: T, type: ChangeSetType, payload: EntityDictionary<T>, meta: EntityMetadata<T>);
11
10
  getPrimaryKey(object?: boolean): Primary<T> | null;
12
11
  getSerializedPrimaryKey(): string | null;
13
- /** @ignore */
14
- [inspect.custom](depth?: number): string;
15
12
  }
16
13
  export interface ChangeSet<T> {
17
14
  name: string;
@@ -1,6 +1,6 @@
1
- import { inspect } from 'node:util';
2
1
  import { helper } from '../entity/wrap.js';
3
2
  import { Utils } from '../utils/Utils.js';
3
+ import { inspect } from '../logging/inspect.js';
4
4
  export class ChangeSet {
5
5
  entity;
6
6
  type;
@@ -46,7 +46,7 @@ export class ChangeSet {
46
46
  return this.serializedPrimaryKey;
47
47
  }
48
48
  /** @ignore */
49
- [inspect.custom](depth = 2) {
49
+ [Symbol.for('nodejs.util.inspect.custom')](depth = 2) {
50
50
  const object = { ...this };
51
51
  const hidden = ['meta', 'serializedPrimaryKey'];
52
52
  hidden.forEach(k => delete object[k]);
@@ -2,19 +2,17 @@ import { type Configuration } from '../utils/Configuration.js';
2
2
  import type { MetadataStorage } from '../metadata/MetadataStorage.js';
3
3
  import type { AnyEntity } from '../typings.js';
4
4
  import { ChangeSet } from './ChangeSet.js';
5
- import { type EntityValidator } from '../entity/EntityValidator.js';
6
5
  import { type Collection } from '../entity/Collection.js';
7
6
  import type { Platform } from '../platforms/Platform.js';
8
7
  import type { EntityManager } from '../EntityManager.js';
9
8
  export declare class ChangeSetComputer {
10
- private readonly validator;
11
9
  private readonly collectionUpdates;
12
10
  private readonly metadata;
13
11
  private readonly platform;
14
12
  private readonly config;
15
13
  private readonly em;
16
14
  private readonly comparator;
17
- constructor(validator: EntityValidator, collectionUpdates: Set<Collection<AnyEntity>>, metadata: MetadataStorage, platform: Platform, config: Configuration, em: EntityManager);
15
+ constructor(collectionUpdates: Set<Collection<AnyEntity>>, metadata: MetadataStorage, platform: Platform, config: Configuration, em: EntityManager);
18
16
  computeChangeSet<T extends object>(entity: T): ChangeSet<T> | null;
19
17
  /**
20
18
  * Traverses entity graph and executes `onCreate` and `onUpdate` methods, assigning the values to given properties.
@@ -1,17 +1,16 @@
1
1
  import { Utils } from '../utils/Utils.js';
2
2
  import { ChangeSet, ChangeSetType } from './ChangeSet.js';
3
3
  import { helper } from '../entity/wrap.js';
4
+ import { validateEntity } from '../entity/validators.js';
4
5
  import { ReferenceKind } from '../enums.js';
5
6
  export class ChangeSetComputer {
6
- validator;
7
7
  collectionUpdates;
8
8
  metadata;
9
9
  platform;
10
10
  config;
11
11
  em;
12
12
  comparator;
13
- constructor(validator, collectionUpdates, metadata, platform, config, em) {
14
- this.validator = validator;
13
+ constructor(collectionUpdates, metadata, platform, config, em) {
15
14
  this.collectionUpdates = collectionUpdates;
16
15
  this.metadata = metadata;
17
16
  this.platform = platform;
@@ -34,20 +33,21 @@ export class ChangeSetComputer {
34
33
  this.processPropertyInitializers(entity, prop, type, map);
35
34
  }
36
35
  }
37
- if (type === ChangeSetType.UPDATE && !wrapped.__initialized && !wrapped.isTouched()) {
38
- return null;
36
+ if (type === ChangeSetType.UPDATE && !wrapped.__initialized) {
37
+ const data = this.comparator.prepareEntity(entity);
38
+ if (Utils.equals(data, wrapped.__originalEntityData)) {
39
+ return null;
40
+ }
39
41
  }
40
42
  const changeSet = new ChangeSet(entity, type, this.computePayload(entity), meta);
41
43
  changeSet.originalEntity = wrapped.__originalEntityData;
42
- if (this.config.get('validate')) {
43
- this.validator.validate(changeSet.entity, changeSet.payload, meta);
44
- }
45
44
  for (const prop of meta.relations.filter(prop => prop.persist !== false || prop.userDefined === false)) {
46
45
  this.processProperty(changeSet, prop);
47
46
  }
48
47
  if (changeSet.type === ChangeSetType.UPDATE && !Utils.hasObjectKeys(changeSet.payload)) {
49
48
  return null;
50
49
  }
50
+ validateEntity(changeSet.entity, meta);
51
51
  // Execute `onCreate` and `onUpdate` on properties recursively, saves `onUpdate` results
52
52
  // to the `map` as we want to apply those only if something else changed.
53
53
  if (type === ChangeSetType.UPDATE) {
@@ -141,7 +141,9 @@ export class ChangeSetComputer {
141
141
  if (!target.isDirty() && changeSet.type !== ChangeSetType.CREATE) {
142
142
  return;
143
143
  }
144
- this.collectionUpdates.add(target);
144
+ if (target.isDirty()) {
145
+ this.collectionUpdates.add(target);
146
+ }
145
147
  if (prop.owner && !this.platform.usesPivotTable()) {
146
148
  changeSet.payload[prop.name] = target.getItems(false).map((item) => item.__helper.__identifier ?? item.__helper.getPrimaryKey());
147
149
  }
@@ -1,29 +1,30 @@
1
1
  import type { MetadataStorage } from '../metadata/MetadataStorage.js';
2
2
  import type { Dictionary, EntityDictionary, EntityMetadata, IHydrator } from '../typings.js';
3
3
  import { type EntityFactory } from '../entity/EntityFactory.js';
4
- import { type EntityValidator } from '../entity/EntityValidator.js';
5
4
  import { type ChangeSet } from './ChangeSet.js';
6
5
  import { type Configuration } from '../utils/Configuration.js';
7
6
  import type { DriverMethodOptions, IDatabaseDriver } from '../drivers/IDatabaseDriver.js';
7
+ import type { EntityManager } from '../EntityManager.js';
8
8
  export declare class ChangeSetPersister {
9
9
  private readonly driver;
10
10
  private readonly metadata;
11
11
  private readonly hydrator;
12
12
  private readonly factory;
13
- private readonly validator;
14
13
  private readonly config;
14
+ private readonly em;
15
15
  private readonly platform;
16
16
  private readonly comparator;
17
17
  private readonly usesReturningStatement;
18
- constructor(driver: IDatabaseDriver, metadata: MetadataStorage, hydrator: IHydrator, factory: EntityFactory, validator: EntityValidator, config: Configuration);
18
+ constructor(driver: IDatabaseDriver, metadata: MetadataStorage, hydrator: IHydrator, factory: EntityFactory, config: Configuration, em: EntityManager);
19
19
  executeInserts<T extends object>(changeSets: ChangeSet<T>[], options?: DriverMethodOptions, withSchema?: boolean): Promise<void>;
20
20
  executeUpdates<T extends object>(changeSets: ChangeSet<T>[], batched: boolean, options?: DriverMethodOptions, withSchema?: boolean): Promise<void>;
21
21
  executeDeletes<T extends object>(changeSets: ChangeSet<T>[], options?: DriverMethodOptions, withSchema?: boolean): Promise<void>;
22
22
  private runForEachSchema;
23
+ private validateRequired;
23
24
  private processProperties;
24
25
  private persistNewEntity;
25
26
  private persistNewEntities;
26
- private propagateSchemaFromMetadata;
27
+ private prepareOptions;
27
28
  private persistNewEntitiesBatch;
28
29
  private persistManagedEntity;
29
30
  private persistManagedEntities;
@@ -3,25 +3,25 @@ import { helper } from '../entity/wrap.js';
3
3
  import { ChangeSetType } from './ChangeSet.js';
4
4
  import { isRaw } from '../utils/RawQueryFragment.js';
5
5
  import { Utils } from '../utils/Utils.js';
6
- import { OptimisticLockError } from '../errors.js';
6
+ import { OptimisticLockError, ValidationError } from '../errors.js';
7
7
  import { ReferenceKind } from '../enums.js';
8
8
  export class ChangeSetPersister {
9
9
  driver;
10
10
  metadata;
11
11
  hydrator;
12
12
  factory;
13
- validator;
14
13
  config;
14
+ em;
15
15
  platform;
16
16
  comparator;
17
17
  usesReturningStatement;
18
- constructor(driver, metadata, hydrator, factory, validator, config) {
18
+ constructor(driver, metadata, hydrator, factory, config, em) {
19
19
  this.driver = driver;
20
20
  this.metadata = metadata;
21
21
  this.hydrator = hydrator;
22
22
  this.factory = factory;
23
- this.validator = validator;
24
23
  this.config = config;
24
+ this.em = em;
25
25
  this.platform = this.driver.getPlatform();
26
26
  this.comparator = this.config.getComparator(this.metadata);
27
27
  this.usesReturningStatement = this.platform.usesReturningStatement() || this.platform.usesOutputStatement();
@@ -62,7 +62,7 @@ export class ChangeSetPersister {
62
62
  for (let i = 0; i < changeSets.length; i += size) {
63
63
  const chunk = changeSets.slice(i, i + size);
64
64
  const pks = chunk.map(cs => cs.getPrimaryKey());
65
- options = this.propagateSchemaFromMetadata(meta, options);
65
+ options = this.prepareOptions(meta, options);
66
66
  await this.driver.nativeDelete(meta.root.className, { [pk]: { $in: pks } }, options);
67
67
  }
68
68
  }
@@ -79,18 +79,37 @@ export class ChangeSetPersister {
79
79
  await this[method](group, ...args, options, true);
80
80
  }
81
81
  }
82
+ validateRequired(entity) {
83
+ const wrapped = helper(entity);
84
+ for (const prop of wrapped.__meta.props) {
85
+ if (!prop.nullable &&
86
+ !prop.autoincrement &&
87
+ !prop.default &&
88
+ !prop.defaultRaw &&
89
+ !prop.onCreate &&
90
+ !prop.generated &&
91
+ !prop.embedded &&
92
+ ![ReferenceKind.ONE_TO_MANY, ReferenceKind.MANY_TO_MANY].includes(prop.kind) &&
93
+ prop.name !== wrapped.__meta.root.discriminatorColumn &&
94
+ prop.type !== 'ObjectId' &&
95
+ prop.persist !== false &&
96
+ entity[prop.name] == null) {
97
+ throw ValidationError.propertyRequired(entity, prop);
98
+ }
99
+ }
100
+ }
82
101
  processProperties(changeSet) {
83
102
  const meta = this.metadata.find(changeSet.name);
84
103
  for (const prop of meta.relations) {
85
104
  this.processProperty(changeSet, prop);
86
105
  }
87
106
  if (changeSet.type === ChangeSetType.CREATE && this.config.get('validateRequired')) {
88
- this.validator.validateRequired(changeSet.entity);
107
+ this.validateRequired(changeSet.entity);
89
108
  }
90
109
  }
91
110
  async persistNewEntity(meta, changeSet, options) {
92
111
  const wrapped = helper(changeSet.entity);
93
- options = this.propagateSchemaFromMetadata(meta, options, {
112
+ options = this.prepareOptions(meta, options, {
94
113
  convertCustomTypes: false,
95
114
  });
96
115
  const res = await this.driver.nativeInsertMany(meta.className, [changeSet.payload], options);
@@ -116,15 +135,17 @@ export class ChangeSetPersister {
116
135
  }
117
136
  }
118
137
  }
119
- propagateSchemaFromMetadata(meta, options, additionalOptions) {
138
+ prepareOptions(meta, options, additionalOptions) {
139
+ const loggerContext = Utils.merge({ id: this.em._id }, this.em.getLoggerContext({ disableContextResolution: true }));
120
140
  return {
121
141
  ...options,
122
142
  ...additionalOptions,
123
143
  schema: options?.schema ?? meta.schema,
144
+ loggerContext,
124
145
  };
125
146
  }
126
147
  async persistNewEntitiesBatch(meta, changeSets, options) {
127
- options = this.propagateSchemaFromMetadata(meta, options, {
148
+ options = this.prepareOptions(meta, options, {
128
149
  convertCustomTypes: false,
129
150
  processCollections: false,
130
151
  });
@@ -175,7 +196,7 @@ export class ChangeSetPersister {
175
196
  }
176
197
  async persistManagedEntitiesBatch(meta, changeSets, options) {
177
198
  await this.checkOptimisticLocks(meta, changeSets, options);
178
- options = this.propagateSchemaFromMetadata(meta, options, {
199
+ options = this.prepareOptions(meta, options, {
179
200
  convertCustomTypes: false,
180
201
  processCollections: false,
181
202
  });
@@ -235,7 +256,7 @@ export class ChangeSetPersister {
235
256
  }
236
257
  async updateEntity(meta, changeSet, options) {
237
258
  const cond = changeSet.getPrimaryKey(true);
238
- options = this.propagateSchemaFromMetadata(meta, options, {
259
+ options = this.prepareOptions(meta, options, {
239
260
  convertCustomTypes: false,
240
261
  });
241
262
  if (meta.concurrencyCheckKeys.size === 0 && (!meta.versionProperty || changeSet.entity[meta.versionProperty] == null)) {
@@ -262,7 +283,7 @@ export class ChangeSetPersister {
262
283
  return cond;
263
284
  });
264
285
  const primaryKeys = meta.primaryKeys.concat(...meta.concurrencyCheckKeys);
265
- options = this.propagateSchemaFromMetadata(meta, options, {
286
+ options = this.prepareOptions(meta, options, {
266
287
  fields: primaryKeys,
267
288
  });
268
289
  const res = await this.driver.find(meta.root.className, { $or }, options);
@@ -286,11 +307,22 @@ export class ChangeSetPersister {
286
307
  async reloadVersionValues(meta, changeSets, options) {
287
308
  const reloadProps = meta.versionProperty && !this.usesReturningStatement ? [meta.properties[meta.versionProperty]] : [];
288
309
  if (changeSets[0].type === ChangeSetType.CREATE) {
289
- // do not reload things that already had a runtime value
290
- meta.props
291
- .filter(prop => prop.persist !== false && (prop.autoincrement || prop.generated || prop.defaultRaw))
292
- .filter(prop => (changeSets[0].entity[prop.name] == null && prop.defaultRaw !== 'null') || isRaw(changeSets[0].entity[prop.name]))
293
- .forEach(prop => reloadProps.push(prop));
310
+ for (const prop of meta.props) {
311
+ if (prop.persist === false) {
312
+ continue;
313
+ }
314
+ if (isRaw(changeSets[0].entity[prop.name])) {
315
+ reloadProps.push(prop);
316
+ continue;
317
+ }
318
+ // do not reload things that already had a runtime value
319
+ if (changeSets[0].entity[prop.name] != null || prop.defaultRaw === 'null') {
320
+ continue;
321
+ }
322
+ if (prop.autoincrement || prop.generated || prop.defaultRaw) {
323
+ reloadProps.push(prop);
324
+ }
325
+ }
294
326
  }
295
327
  if (changeSets[0].type === ChangeSetType.UPDATE) {
296
328
  const returning = new Set();
@@ -321,12 +353,12 @@ export class ChangeSetPersister {
321
353
  }
322
354
  return val;
323
355
  });
324
- options = this.propagateSchemaFromMetadata(meta, options, {
356
+ options = this.prepareOptions(meta, options, {
325
357
  fields: Utils.unique(reloadProps.map(prop => prop.name)),
326
358
  });
327
359
  const data = await this.driver.find(meta.className, { [pk]: { $in: pks } }, options);
328
360
  const map = new Map();
329
- data.forEach(item => map.set(Utils.getCompositeKeyHash(item, meta, true, this.platform, true), item));
361
+ data.forEach(item => map.set(Utils.getCompositeKeyHash(item, meta, false, this.platform, true), item));
330
362
  for (const changeSet of changeSets) {
331
363
  const data = map.get(helper(changeSet.entity).getSerializedPrimaryKey());
332
364
  this.hydrator.hydrate(changeSet.entity, meta, data, this.factory, 'full', false, true);
@@ -28,6 +28,12 @@ export declare class UnitOfWork {
28
28
  private working;
29
29
  constructor(em: EntityManager);
30
30
  merge<T extends object>(entity: T, visited?: Set<AnyEntity>): void;
31
+ /**
32
+ * Entity data can wary in its shape, e.g. we might get a deep relation graph with joined strategy, but for diffing,
33
+ * we need to normalize the shape, so relation values are only raw FKs. This method handles that.
34
+ * @internal
35
+ */
36
+ normalizeEntityData<T extends object>(meta: EntityMetadata<T>, data: EntityData<T>): void;
31
37
  /**
32
38
  * @internal
33
39
  */
@@ -39,7 +45,7 @@ export declare class UnitOfWork {
39
45
  /**
40
46
  * Returns entity from the identity map. For composite keys, you need to pass an array of PKs in the same order as they are defined in `meta.primaryKeys`.
41
47
  */
42
- getById<T extends object>(entityName: string, id: Primary<T> | Primary<T>[], schema?: string): T | undefined;
48
+ getById<T extends object>(entityName: string, id: Primary<T> | Primary<T>[], schema?: string, convertCustomTypes?: boolean): T | undefined;
43
49
  tryGetById<T extends object>(entityName: string, where: FilterQuery<T>, schema?: string, strict?: boolean): T | null;
44
50
  /**
45
51
  * Returns map of all managed entities.
@@ -103,6 +109,7 @@ export declare class UnitOfWork {
103
109
  private commitDeleteChangeSets;
104
110
  private commitExtraUpdates;
105
111
  private commitCollectionUpdates;
112
+ private filterCollectionUpdates;
106
113
  /**
107
114
  * Orders change sets so FK constrains are maintained, ensures stable order (needed for node < 11)
108
115
  */