@mikro-orm/core 7.0.0-dev.21 → 7.0.0-dev.211

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 (211) hide show
  1. package/EntityManager.d.ts +99 -57
  2. package/EntityManager.js +302 -276
  3. package/MikroORM.d.ts +44 -35
  4. package/MikroORM.js +103 -143
  5. package/README.md +3 -2
  6. package/cache/FileCacheAdapter.d.ts +1 -1
  7. package/cache/FileCacheAdapter.js +8 -7
  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 +16 -7
  13. package/connections/Connection.js +23 -14
  14. package/drivers/DatabaseDriver.d.ts +25 -16
  15. package/drivers/DatabaseDriver.js +80 -35
  16. package/drivers/IDatabaseDriver.d.ts +44 -17
  17. package/entity/BaseEntity.d.ts +2 -2
  18. package/entity/BaseEntity.js +0 -3
  19. package/entity/Collection.d.ts +94 -29
  20. package/entity/Collection.js +434 -97
  21. package/entity/EntityAssigner.d.ts +1 -1
  22. package/entity/EntityAssigner.js +26 -18
  23. package/entity/EntityFactory.d.ts +13 -1
  24. package/entity/EntityFactory.js +84 -53
  25. package/entity/EntityHelper.d.ts +2 -2
  26. package/entity/EntityHelper.js +40 -15
  27. package/entity/EntityLoader.d.ts +6 -6
  28. package/entity/EntityLoader.js +119 -82
  29. package/entity/EntityRepository.d.ts +24 -4
  30. package/entity/EntityRepository.js +8 -2
  31. package/entity/Reference.d.ts +6 -5
  32. package/entity/Reference.js +34 -9
  33. package/entity/WrappedEntity.d.ts +2 -7
  34. package/entity/WrappedEntity.js +3 -8
  35. package/entity/defineEntity.d.ts +594 -0
  36. package/entity/defineEntity.js +533 -0
  37. package/entity/index.d.ts +3 -2
  38. package/entity/index.js +3 -2
  39. package/entity/utils.d.ts +7 -0
  40. package/entity/utils.js +16 -4
  41. package/entity/validators.d.ts +11 -0
  42. package/entity/validators.js +65 -0
  43. package/enums.d.ts +21 -5
  44. package/enums.js +15 -1
  45. package/errors.d.ts +23 -9
  46. package/errors.js +59 -21
  47. package/events/EventManager.d.ts +2 -1
  48. package/events/EventManager.js +19 -11
  49. package/hydration/Hydrator.js +1 -2
  50. package/hydration/ObjectHydrator.d.ts +4 -4
  51. package/hydration/ObjectHydrator.js +52 -33
  52. package/index.d.ts +2 -2
  53. package/index.js +1 -2
  54. package/logging/DefaultLogger.d.ts +1 -1
  55. package/logging/DefaultLogger.js +1 -0
  56. package/logging/SimpleLogger.d.ts +1 -1
  57. package/logging/colors.d.ts +1 -1
  58. package/logging/colors.js +7 -6
  59. package/logging/index.d.ts +1 -0
  60. package/logging/index.js +1 -0
  61. package/logging/inspect.d.ts +2 -0
  62. package/logging/inspect.js +11 -0
  63. package/metadata/EntitySchema.d.ts +40 -23
  64. package/metadata/EntitySchema.js +81 -34
  65. package/metadata/MetadataDiscovery.d.ts +7 -10
  66. package/metadata/MetadataDiscovery.js +391 -331
  67. package/metadata/MetadataProvider.d.ts +11 -2
  68. package/metadata/MetadataProvider.js +46 -2
  69. package/metadata/MetadataStorage.d.ts +13 -11
  70. package/metadata/MetadataStorage.js +70 -37
  71. package/metadata/MetadataValidator.d.ts +17 -9
  72. package/metadata/MetadataValidator.js +97 -40
  73. package/metadata/discover-entities.d.ts +5 -0
  74. package/metadata/discover-entities.js +40 -0
  75. package/metadata/index.d.ts +1 -1
  76. package/metadata/index.js +1 -1
  77. package/metadata/types.d.ts +502 -0
  78. package/metadata/types.js +1 -0
  79. package/naming-strategy/AbstractNamingStrategy.d.ts +12 -4
  80. package/naming-strategy/AbstractNamingStrategy.js +14 -2
  81. package/naming-strategy/EntityCaseNamingStrategy.d.ts +3 -3
  82. package/naming-strategy/EntityCaseNamingStrategy.js +6 -5
  83. package/naming-strategy/MongoNamingStrategy.d.ts +3 -3
  84. package/naming-strategy/MongoNamingStrategy.js +6 -6
  85. package/naming-strategy/NamingStrategy.d.ts +24 -4
  86. package/naming-strategy/UnderscoreNamingStrategy.d.ts +3 -3
  87. package/naming-strategy/UnderscoreNamingStrategy.js +6 -6
  88. package/not-supported.d.ts +2 -0
  89. package/not-supported.js +4 -0
  90. package/package.json +18 -11
  91. package/platforms/ExceptionConverter.js +1 -1
  92. package/platforms/Platform.d.ts +7 -13
  93. package/platforms/Platform.js +20 -43
  94. package/serialization/EntitySerializer.d.ts +5 -0
  95. package/serialization/EntitySerializer.js +47 -27
  96. package/serialization/EntityTransformer.js +28 -18
  97. package/serialization/SerializationContext.d.ts +6 -6
  98. package/serialization/SerializationContext.js +16 -13
  99. package/types/ArrayType.d.ts +1 -1
  100. package/types/ArrayType.js +2 -3
  101. package/types/BigIntType.d.ts +8 -6
  102. package/types/BigIntType.js +1 -1
  103. package/types/BlobType.d.ts +0 -1
  104. package/types/BlobType.js +0 -3
  105. package/types/BooleanType.d.ts +2 -1
  106. package/types/BooleanType.js +3 -0
  107. package/types/DecimalType.d.ts +6 -4
  108. package/types/DecimalType.js +3 -3
  109. package/types/DoubleType.js +2 -2
  110. package/types/EnumArrayType.js +1 -2
  111. package/types/JsonType.d.ts +1 -1
  112. package/types/JsonType.js +7 -2
  113. package/types/TinyIntType.js +1 -1
  114. package/types/Type.d.ts +2 -4
  115. package/types/Type.js +3 -3
  116. package/types/Uint8ArrayType.d.ts +0 -1
  117. package/types/Uint8ArrayType.js +1 -4
  118. package/types/index.d.ts +1 -1
  119. package/typings.d.ts +290 -137
  120. package/typings.js +59 -44
  121. package/unit-of-work/ChangeSet.d.ts +2 -6
  122. package/unit-of-work/ChangeSet.js +4 -5
  123. package/unit-of-work/ChangeSetComputer.d.ts +1 -3
  124. package/unit-of-work/ChangeSetComputer.js +26 -13
  125. package/unit-of-work/ChangeSetPersister.d.ts +5 -4
  126. package/unit-of-work/ChangeSetPersister.js +70 -34
  127. package/unit-of-work/CommitOrderCalculator.d.ts +12 -10
  128. package/unit-of-work/CommitOrderCalculator.js +13 -13
  129. package/unit-of-work/IdentityMap.d.ts +12 -0
  130. package/unit-of-work/IdentityMap.js +39 -1
  131. package/unit-of-work/UnitOfWork.d.ts +23 -3
  132. package/unit-of-work/UnitOfWork.js +175 -98
  133. package/utils/AbstractSchemaGenerator.d.ts +5 -5
  134. package/utils/AbstractSchemaGenerator.js +18 -16
  135. package/utils/AsyncContext.d.ts +6 -0
  136. package/utils/AsyncContext.js +42 -0
  137. package/utils/Configuration.d.ts +785 -207
  138. package/utils/Configuration.js +147 -190
  139. package/utils/ConfigurationLoader.d.ts +1 -54
  140. package/utils/ConfigurationLoader.js +1 -352
  141. package/utils/Cursor.d.ts +0 -3
  142. package/utils/Cursor.js +27 -11
  143. package/utils/DataloaderUtils.d.ts +15 -5
  144. package/utils/DataloaderUtils.js +64 -30
  145. package/utils/EntityComparator.d.ts +13 -9
  146. package/utils/EntityComparator.js +101 -42
  147. package/utils/QueryHelper.d.ts +14 -6
  148. package/utils/QueryHelper.js +87 -25
  149. package/utils/RawQueryFragment.d.ts +48 -25
  150. package/utils/RawQueryFragment.js +66 -70
  151. package/utils/RequestContext.js +2 -2
  152. package/utils/TransactionContext.js +2 -2
  153. package/utils/TransactionManager.d.ts +65 -0
  154. package/utils/TransactionManager.js +223 -0
  155. package/utils/Utils.d.ts +13 -126
  156. package/utils/Utils.js +100 -391
  157. package/utils/clone.js +8 -23
  158. package/utils/env-vars.d.ts +7 -0
  159. package/utils/env-vars.js +97 -0
  160. package/utils/fs-utils.d.ts +32 -0
  161. package/utils/fs-utils.js +178 -0
  162. package/utils/index.d.ts +2 -1
  163. package/utils/index.js +2 -1
  164. package/utils/upsert-utils.d.ts +9 -4
  165. package/utils/upsert-utils.js +55 -4
  166. package/decorators/Check.d.ts +0 -3
  167. package/decorators/Check.js +0 -13
  168. package/decorators/CreateRequestContext.d.ts +0 -3
  169. package/decorators/CreateRequestContext.js +0 -32
  170. package/decorators/Embeddable.d.ts +0 -8
  171. package/decorators/Embeddable.js +0 -11
  172. package/decorators/Embedded.d.ts +0 -12
  173. package/decorators/Embedded.js +0 -18
  174. package/decorators/Entity.d.ts +0 -18
  175. package/decorators/Entity.js +0 -12
  176. package/decorators/Enum.d.ts +0 -9
  177. package/decorators/Enum.js +0 -16
  178. package/decorators/Filter.d.ts +0 -2
  179. package/decorators/Filter.js +0 -8
  180. package/decorators/Formula.d.ts +0 -4
  181. package/decorators/Formula.js +0 -15
  182. package/decorators/Indexed.d.ts +0 -19
  183. package/decorators/Indexed.js +0 -20
  184. package/decorators/ManyToMany.d.ts +0 -40
  185. package/decorators/ManyToMany.js +0 -14
  186. package/decorators/ManyToOne.d.ts +0 -32
  187. package/decorators/ManyToOne.js +0 -14
  188. package/decorators/OneToMany.d.ts +0 -28
  189. package/decorators/OneToMany.js +0 -17
  190. package/decorators/OneToOne.d.ts +0 -26
  191. package/decorators/OneToOne.js +0 -7
  192. package/decorators/PrimaryKey.d.ts +0 -8
  193. package/decorators/PrimaryKey.js +0 -20
  194. package/decorators/Property.d.ts +0 -250
  195. package/decorators/Property.js +0 -32
  196. package/decorators/Transactional.d.ts +0 -13
  197. package/decorators/Transactional.js +0 -28
  198. package/decorators/hooks.d.ts +0 -16
  199. package/decorators/hooks.js +0 -47
  200. package/decorators/index.d.ts +0 -17
  201. package/decorators/index.js +0 -17
  202. package/entity/ArrayCollection.d.ts +0 -116
  203. package/entity/ArrayCollection.js +0 -402
  204. package/entity/EntityValidator.d.ts +0 -19
  205. package/entity/EntityValidator.js +0 -150
  206. package/exports.d.ts +0 -24
  207. package/exports.js +0 -23
  208. package/metadata/ReflectMetadataProvider.d.ts +0 -8
  209. package/metadata/ReflectMetadataProvider.js +0 -44
  210. package/utils/resolveContextProvider.d.ts +0 -10
  211. package/utils/resolveContextProvider.js +0 -28
@@ -0,0 +1,65 @@
1
+ import { Utils } from '../utils/Utils.js';
2
+ import { ValidationError } from '../errors.js';
3
+ import { isRaw, Raw } from '../utils/RawQueryFragment.js';
4
+ import { SCALAR_TYPES } from '../enums.js';
5
+ /** @internal */
6
+ export function validateProperty(prop, givenValue, entity) {
7
+ if (givenValue == null || isRaw(givenValue)) {
8
+ return;
9
+ }
10
+ const expectedType = prop.runtimeType;
11
+ const propName = prop.embedded ? prop.name.replace(/~/g, '.') : prop.name;
12
+ const givenType = Utils.getObjectType(givenValue);
13
+ if (prop.enum && prop.items) {
14
+ /* v8 ignore next */
15
+ if (!prop.items.some(it => it === givenValue)) {
16
+ throw ValidationError.fromWrongPropertyType(entity, propName, expectedType, givenType, givenValue);
17
+ }
18
+ }
19
+ else {
20
+ if (givenType !== expectedType && SCALAR_TYPES.has(expectedType)) {
21
+ throw ValidationError.fromWrongPropertyType(entity, propName, expectedType, givenType, givenValue);
22
+ }
23
+ }
24
+ }
25
+ function getValue(o, prop) {
26
+ if (prop.embedded && prop.embedded[0] in o) {
27
+ return o[prop.embedded[0]]?.[prop.embedded[1]];
28
+ }
29
+ /* v8 ignore next */
30
+ if (prop.ref) {
31
+ return o[prop.name]?.unwrap();
32
+ }
33
+ return o[prop.name];
34
+ }
35
+ /** @internal */
36
+ export function validateEntity(entity, meta) {
37
+ for (const prop of meta.validateProps) {
38
+ validateProperty(prop, getValue(entity, prop), entity);
39
+ }
40
+ }
41
+ /** @internal */
42
+ export function validateParams(params, type = 'search condition', field) {
43
+ if (Utils.isPrimaryKey(params) || Utils.isEntity(params)) {
44
+ return;
45
+ }
46
+ if (Array.isArray(params)) {
47
+ return params.forEach(item => validateParams(item, type, field));
48
+ }
49
+ if (Utils.isPlainObject(params)) {
50
+ Object.keys(params).forEach(k => validateParams(params[k], type, k));
51
+ }
52
+ }
53
+ /** @internal */
54
+ export function validatePrimaryKey(entity, meta) {
55
+ const pkExists = meta.primaryKeys.every(pk => entity[pk] != null) || (meta.serializedPrimaryKey && entity[meta.serializedPrimaryKey] != null);
56
+ if (!entity || !pkExists) {
57
+ throw ValidationError.fromMergeWithoutPK(meta);
58
+ }
59
+ }
60
+ /** @internal */
61
+ export function validateEmptyWhere(where) {
62
+ if (Utils.isEmpty(where) && !Raw.hasObjectFragments(where)) {
63
+ throw new Error(`You cannot call 'EntityManager.findOne()' with empty 'where' parameter`);
64
+ }
65
+ }
package/enums.d.ts CHANGED
@@ -42,6 +42,7 @@ export declare enum QueryOperator {
42
42
  $none = "none",// collection operators, sql only
43
43
  $some = "some",// collection operators, sql only
44
44
  $every = "every",// collection operators, sql only
45
+ $size = "size",// collection operators, sql only
45
46
  $hasKey = "?",// postgres only, json
46
47
  $hasKeys = "?&",// postgres only, json
47
48
  $hasSomeKeys = "?|"
@@ -85,9 +86,11 @@ export declare enum QueryFlag {
85
86
  INCLUDE_LAZY_FORMULAS = "INCLUDE_LAZY_FORMULAS",
86
87
  AUTO_JOIN_ONE_TO_ONE_OWNER = "AUTO_JOIN_ONE_TO_ONE_OWNER",
87
88
  INFER_POPULATE = "INFER_POPULATE",
88
- IDENTITY_INSERT = "IDENTITY_INSERT"
89
+ DISABLE_NESTED_INNER_JOIN = "DISABLE_NESTED_INNER_JOIN",
90
+ IDENTITY_INSERT = "IDENTITY_INSERT",// mssql only
91
+ OUTPUT_TABLE = "OUTPUT_TABLE"
89
92
  }
90
- export declare const SCALAR_TYPES: string[];
93
+ export declare const SCALAR_TYPES: Set<string>;
91
94
  export declare enum ReferenceKind {
92
95
  SCALAR = "scalar",
93
96
  ONE_TO_ONE = "1:1",
@@ -108,7 +111,8 @@ export declare enum Cascade {
108
111
  }
109
112
  export declare enum LoadStrategy {
110
113
  SELECT_IN = "select-in",
111
- JOINED = "joined"
114
+ JOINED = "joined",
115
+ BALANCED = "balanced"
112
116
  }
113
117
  export declare enum DataloaderType {
114
118
  NONE = 0,
@@ -156,12 +160,22 @@ export declare enum EventType {
156
160
  }
157
161
  export declare const EventTypeMap: Record<EventType, number>;
158
162
  export type TransactionEventType = EventType.beforeTransactionStart | EventType.afterTransactionStart | EventType.beforeTransactionCommit | EventType.afterTransactionCommit | EventType.beforeTransactionRollback | EventType.afterTransactionRollback;
163
+ export declare enum TransactionPropagation {
164
+ REQUIRED = "required",
165
+ REQUIRES_NEW = "requires_new",
166
+ NESTED = "nested",
167
+ NOT_SUPPORTED = "not_supported",
168
+ SUPPORTS = "supports",
169
+ MANDATORY = "mandatory",
170
+ NEVER = "never"
171
+ }
159
172
  export interface TransactionOptions {
160
173
  ctx?: Transaction;
161
- isolationLevel?: IsolationLevel;
174
+ propagation?: TransactionPropagation | `${TransactionPropagation}`;
175
+ isolationLevel?: IsolationLevel | `${IsolationLevel}`;
162
176
  readOnly?: boolean;
163
177
  clear?: boolean;
164
- flushMode?: FlushMode;
178
+ flushMode?: FlushMode | `${FlushMode}`;
165
179
  ignoreNestedTransactions?: boolean;
166
180
  loggerContext?: LogContext;
167
181
  }
@@ -171,3 +185,5 @@ export declare enum DeferMode {
171
185
  INITIALLY_IMMEDIATE = "immediate",
172
186
  INITIALLY_DEFERRED = "deferred"
173
187
  }
188
+ /** With `absolute` the prefix is set at the root of the entity (regardless of the nesting level) */
189
+ export type EmbeddedPrefixMode = 'absolute' | 'relative';
package/enums.js CHANGED
@@ -44,6 +44,7 @@ export var QueryOperator;
44
44
  QueryOperator["$none"] = "none";
45
45
  QueryOperator["$some"] = "some";
46
46
  QueryOperator["$every"] = "every";
47
+ QueryOperator["$size"] = "size";
47
48
  QueryOperator["$hasKey"] = "?";
48
49
  QueryOperator["$hasKeys"] = "?&";
49
50
  QueryOperator["$hasSomeKeys"] = "?|";
@@ -95,9 +96,11 @@ export var QueryFlag;
95
96
  QueryFlag["INCLUDE_LAZY_FORMULAS"] = "INCLUDE_LAZY_FORMULAS";
96
97
  QueryFlag["AUTO_JOIN_ONE_TO_ONE_OWNER"] = "AUTO_JOIN_ONE_TO_ONE_OWNER";
97
98
  QueryFlag["INFER_POPULATE"] = "INFER_POPULATE";
99
+ QueryFlag["DISABLE_NESTED_INNER_JOIN"] = "DISABLE_NESTED_INNER_JOIN";
98
100
  QueryFlag["IDENTITY_INSERT"] = "IDENTITY_INSERT";
101
+ QueryFlag["OUTPUT_TABLE"] = "OUTPUT_TABLE";
99
102
  })(QueryFlag || (QueryFlag = {}));
100
- export const SCALAR_TYPES = ['string', 'number', 'boolean', 'bigint', 'Date', 'Buffer', 'RegExp'];
103
+ export const SCALAR_TYPES = new Set(['string', 'number', 'boolean', 'bigint', 'Uint8Array', 'Date', 'Buffer', 'RegExp']);
101
104
  export var ReferenceKind;
102
105
  (function (ReferenceKind) {
103
106
  ReferenceKind["SCALAR"] = "scalar";
@@ -122,6 +125,7 @@ export var LoadStrategy;
122
125
  (function (LoadStrategy) {
123
126
  LoadStrategy["SELECT_IN"] = "select-in";
124
127
  LoadStrategy["JOINED"] = "joined";
128
+ LoadStrategy["BALANCED"] = "balanced";
125
129
  })(LoadStrategy || (LoadStrategy = {}));
126
130
  export var DataloaderType;
127
131
  (function (DataloaderType) {
@@ -175,6 +179,16 @@ export const EventTypeMap = Object.keys(EventType).reduce((a, b, i) => {
175
179
  a[b] = i;
176
180
  return a;
177
181
  }, {});
182
+ export var TransactionPropagation;
183
+ (function (TransactionPropagation) {
184
+ TransactionPropagation["REQUIRED"] = "required";
185
+ TransactionPropagation["REQUIRES_NEW"] = "requires_new";
186
+ TransactionPropagation["NESTED"] = "nested";
187
+ TransactionPropagation["NOT_SUPPORTED"] = "not_supported";
188
+ TransactionPropagation["SUPPORTS"] = "supports";
189
+ TransactionPropagation["MANDATORY"] = "mandatory";
190
+ TransactionPropagation["NEVER"] = "never";
191
+ })(TransactionPropagation || (TransactionPropagation = {}));
178
192
  export class PlainObject {
179
193
  }
180
194
  export var DeferMode;
package/errors.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { AnyEntity, Constructor, Dictionary, EntityMetadata, EntityProperty, IPrimaryKey } from './typings.js';
1
+ import type { AnyEntity, Constructor, Dictionary, EntityMetadata, EntityName, EntityProperty, IPrimaryKey } from './typings.js';
2
2
  export declare class ValidationError<T extends AnyEntity = AnyEntity> extends Error {
3
3
  readonly entity?: T | undefined;
4
4
  constructor(message: string, entity?: T | undefined);
@@ -8,13 +8,14 @@ export declare class ValidationError<T extends AnyEntity = AnyEntity> extends Er
8
8
  getEntity(): AnyEntity | undefined;
9
9
  static fromWrongPropertyType(entity: AnyEntity, property: string, expectedType: string, givenType: string, givenValue: string): ValidationError;
10
10
  static fromWrongRepositoryType(entityName: string, repoType: string, method: string): ValidationError;
11
- static fromCollectionNotInitialized(entity: AnyEntity, prop: EntityProperty): ValidationError;
12
11
  static fromMergeWithoutPK(meta: EntityMetadata): ValidationError;
13
12
  static transactionRequired(): ValidationError;
14
13
  static entityNotManaged(entity: AnyEntity): ValidationError;
15
14
  static notEntity(owner: AnyEntity, prop: EntityProperty, data: any): ValidationError;
16
15
  static notDiscoveredEntity(data: any, meta?: EntityMetadata, action?: string): ValidationError;
17
- static invalidPropertyName(entityName: string, invalid: string): ValidationError;
16
+ static invalidPropertyName(entityName: EntityName, invalid: string): ValidationError;
17
+ static invalidCollectionValues(entityName: string, propName: string, invalid: unknown): ValidationError;
18
+ static invalidEnumArrayItems(entityName: string, invalid: unknown): ValidationError;
18
19
  static invalidType(type: Constructor<any>, value: any, mode: string): ValidationError;
19
20
  static propertyRequired(entity: AnyEntity, property: EntityProperty): ValidationError;
20
21
  static cannotModifyInverseCollection(owner: AnyEntity, property: EntityProperty): ValidationError;
@@ -23,8 +24,10 @@ export declare class ValidationError<T extends AnyEntity = AnyEntity> extends Er
23
24
  static invalidCompositeIdentifier(meta: EntityMetadata): ValidationError;
24
25
  static cannotCommit(): ValidationError;
25
26
  static cannotUseGlobalContext(): ValidationError;
26
- static cannotUseOperatorsInsideEmbeddables(className: string, propName: string, payload: unknown): ValidationError;
27
- static invalidEmbeddableQuery(className: string, propName: string, embeddableType: string): ValidationError;
27
+ static cannotUseOperatorsInsideEmbeddables(entityName: EntityName, propName: string, payload: unknown): ValidationError;
28
+ static cannotUseGroupOperatorsInsideScalars(entityName: EntityName, propName: string, payload: unknown): ValidationError;
29
+ static invalidEmbeddableQuery(entityName: EntityName, propName: string, embeddableType: string): ValidationError;
30
+ static invalidQueryCondition(cond: unknown): ValidationError;
28
31
  }
29
32
  export declare class CursorError<T extends AnyEntity = AnyEntity> extends ValidationError<T> {
30
33
  static entityNotPopulated(entity: AnyEntity, prop: string): ValidationError;
@@ -43,15 +46,14 @@ export declare class MetadataError<T extends AnyEntity = AnyEntity> extends Vali
43
46
  static fromWrongOwnership(meta: EntityMetadata, prop: EntityProperty, key: 'inversedBy' | 'mappedBy'): MetadataError;
44
47
  static fromWrongReferenceKind(meta: EntityMetadata, owner: EntityProperty, prop: EntityProperty): MetadataError;
45
48
  static fromInversideSidePrimary(meta: EntityMetadata, owner: EntityProperty, prop: EntityProperty): MetadataError;
46
- static entityNotFound(name: string, path: string): MetadataError;
47
49
  static unknownIndexProperty(meta: EntityMetadata, prop: string, type: string): MetadataError;
48
50
  static multipleVersionFields(meta: EntityMetadata, fields: string[]): MetadataError;
49
51
  static invalidVersionFieldType(meta: EntityMetadata): MetadataError;
50
- static fromUnknownEntity(className: string, source: string): MetadataError;
52
+ static fromUnknownEntity(entityName: string, source: string): MetadataError;
51
53
  static noEntityDiscovered(): MetadataError;
52
54
  static onlyAbstractEntitiesDiscovered(): MetadataError;
53
- static duplicateEntityDiscovered(paths: string[], subject?: string): MetadataError;
54
- static duplicateFieldName(className: string, names: [string, string][]): MetadataError;
55
+ static duplicateEntityDiscovered(paths: string[]): MetadataError;
56
+ static duplicateFieldName(entityName: EntityName, names: [string, string][]): MetadataError;
55
57
  static multipleDecorators(entityName: string, propertyName: string): MetadataError;
56
58
  static missingMetadata(entity: string): MetadataError;
57
59
  static invalidPrimaryKey(meta: EntityMetadata, prop: EntityProperty, requiredName: string): MetadataError<Partial<any>>;
@@ -60,9 +62,21 @@ export declare class MetadataError<T extends AnyEntity = AnyEntity> extends Vali
60
62
  static nonPersistentCompositeProp(meta: EntityMetadata, prop: EntityProperty): MetadataError<Partial<any>>;
61
63
  static propertyTargetsEntityType(meta: EntityMetadata, prop: EntityProperty, target: EntityMetadata): MetadataError<Partial<any>>;
62
64
  static fromMissingOption(meta: EntityMetadata, prop: EntityProperty, option: string): MetadataError<Partial<any>>;
65
+ static targetKeyOnManyToMany(meta: EntityMetadata, prop: EntityProperty): MetadataError<Partial<any>>;
66
+ static targetKeyNotUnique(meta: EntityMetadata, prop: EntityProperty): MetadataError<Partial<any>>;
67
+ static targetKeyNotFound(meta: EntityMetadata, prop: EntityProperty): MetadataError<Partial<any>>;
68
+ static dangerousPropertyName(meta: EntityMetadata, prop: EntityProperty): MetadataError<Partial<any>>;
69
+ static viewEntityWithoutExpression(meta: EntityMetadata): MetadataError;
70
+ static materializedWithoutView(meta: EntityMetadata): MetadataError;
63
71
  private static fromMessage;
64
72
  }
65
73
  export declare class NotFoundError<T extends AnyEntity = AnyEntity> extends ValidationError<T> {
66
74
  static findOneFailed(name: string, where: Dictionary | IPrimaryKey): NotFoundError;
67
75
  static findExactlyOneFailed(name: string, where: Dictionary | IPrimaryKey): NotFoundError;
76
+ static failedToLoadProperty(name: string, propName: string, where: unknown): NotFoundError;
77
+ }
78
+ export declare class TransactionStateError extends ValidationError {
79
+ static requiredTransactionNotFound(propagation: string): TransactionStateError;
80
+ static transactionNotAllowed(propagation: string): TransactionStateError;
81
+ static invalidPropagation(propagation: string): TransactionStateError;
68
82
  }
package/errors.js CHANGED
@@ -1,4 +1,5 @@
1
- import { inspect } from 'node:util';
1
+ import { inspect } from './logging/inspect.js';
2
+ import { Utils } from './utils/Utils.js';
2
3
  export class ValidationError extends Error {
3
4
  entity;
4
5
  constructor(message, entity) {
@@ -23,11 +24,6 @@ export class ValidationError extends Error {
23
24
  const msg = `Trying to use EntityRepository.${method}() with '${entityName}' entity while the repository is of type '${repoType}'`;
24
25
  return new ValidationError(msg);
25
26
  }
26
- static fromCollectionNotInitialized(entity, prop) {
27
- const entityName = entity.constructor.name;
28
- const msg = `${entityName}.${prop.name} is not initialized, define it as '${prop.name} = new Collection<${prop.type}>(this);'`;
29
- return new ValidationError(msg);
30
- }
31
27
  static fromMergeWithoutPK(meta) {
32
28
  return new ValidationError(`You cannot merge entity '${meta.className}' without identifier!`);
33
29
  }
@@ -51,7 +47,13 @@ export class ValidationError extends Error {
51
47
  return new ValidationError(err);
52
48
  }
53
49
  static invalidPropertyName(entityName, invalid) {
54
- return new ValidationError(`Entity '${entityName}' does not have property '${invalid}'`);
50
+ return new ValidationError(`Entity '${Utils.className(entityName)}' does not have property '${invalid}'`);
51
+ }
52
+ static invalidCollectionValues(entityName, propName, invalid) {
53
+ return new ValidationError(`Invalid collection values provided for '${entityName}.${propName}' in ${entityName}.assign(): ${inspect(invalid)}`);
54
+ }
55
+ static invalidEnumArrayItems(entityName, invalid) {
56
+ return new ValidationError(`Invalid enum array items provided in ${entityName}: ${inspect(invalid)}`);
55
57
  }
56
58
  static invalidType(type, value, mode) {
57
59
  const valueType = Object.prototype.toString.call(value).match(/\[object (\w+)]/)[1].toLowerCase();
@@ -91,11 +93,18 @@ export class ValidationError extends Error {
91
93
  static cannotUseGlobalContext() {
92
94
  return new ValidationError('Using global EntityManager instance methods for context specific actions is disallowed. If you need to work with the global instance\'s identity map, use `allowGlobalContext` configuration option or `fork()` instead.');
93
95
  }
94
- static cannotUseOperatorsInsideEmbeddables(className, propName, payload) {
95
- return new ValidationError(`Using operators inside embeddables is not allowed, move the operator above. (property: ${className}.${propName}, payload: ${inspect(payload)})`);
96
+ static cannotUseOperatorsInsideEmbeddables(entityName, propName, payload) {
97
+ return new ValidationError(`Using operators inside embeddables is not allowed, move the operator above. (property: ${Utils.className(entityName)}.${propName}, payload: ${inspect(payload)})`);
96
98
  }
97
- static invalidEmbeddableQuery(className, propName, embeddableType) {
98
- return new ValidationError(`Invalid query for entity '${className}', property '${propName}' does not exist in embeddable '${embeddableType}'`);
99
+ static cannotUseGroupOperatorsInsideScalars(entityName, propName, payload) {
100
+ return new ValidationError(`Using group operators ($and/$or) inside scalar properties is not allowed, move the operator above. (property: ${Utils.className(entityName)}.${propName}, payload: ${inspect(payload)})`);
101
+ }
102
+ static invalidEmbeddableQuery(entityName, propName, embeddableType) {
103
+ return new ValidationError(`Invalid query for entity '${Utils.className(entityName)}', property '${propName}' does not exist in embeddable '${embeddableType}'`);
104
+ }
105
+ /* v8 ignore next */
106
+ static invalidQueryCondition(cond) {
107
+ return new ValidationError(`Invalid query condition: ${inspect(cond, { depth: 5 })}`);
99
108
  }
100
109
  }
101
110
  export class CursorError extends ValidationError {
@@ -151,10 +160,6 @@ export class MetadataError extends ValidationError {
151
160
  static fromInversideSidePrimary(meta, owner, prop) {
152
161
  return new MetadataError(`${meta.className}.${prop.name} cannot be primary key as it is defined as inverse side. Maybe you should swap the use of 'inversedBy' and 'mappedBy'.`);
153
162
  }
154
- /* v8 ignore next 3 */
155
- static entityNotFound(name, path) {
156
- return new MetadataError(`Entity '${name}' not found in ${path}`);
157
- }
158
163
  static unknownIndexProperty(meta, prop, type) {
159
164
  return new MetadataError(`Entity ${meta.className} has wrong ${type} definition: '${prop}' does not exist. You need to use property name, not column name.`);
160
165
  }
@@ -165,8 +170,8 @@ export class MetadataError extends ValidationError {
165
170
  const prop = meta.properties[meta.versionProperty];
166
171
  return new MetadataError(`Version property ${meta.className}.${prop.name} has unsupported type '${prop.type}'. Only 'number' and 'Date' are allowed.`);
167
172
  }
168
- static fromUnknownEntity(className, source) {
169
- return new MetadataError(`Entity '${className}' was not discovered, please make sure to provide it in 'entities' array when initializing the ORM (used in ${source})`);
173
+ static fromUnknownEntity(entityName, source) {
174
+ return new MetadataError(`Entity '${entityName}' was not discovered, please make sure to provide it in 'entities' array when initializing the ORM (used in ${source})`);
170
175
  }
171
176
  static noEntityDiscovered() {
172
177
  return new MetadataError('No entities were discovered');
@@ -174,11 +179,11 @@ export class MetadataError extends ValidationError {
174
179
  static onlyAbstractEntitiesDiscovered() {
175
180
  return new MetadataError('Only abstract entities were discovered, maybe you forgot to use @Entity() decorator? This can also happen when you have multiple `@mikro-orm/core` packages installed side by side.');
176
181
  }
177
- static duplicateEntityDiscovered(paths, subject = 'entity names') {
178
- return new MetadataError(`Duplicate ${subject} are not allowed: ${paths.join(', ')}`);
182
+ static duplicateEntityDiscovered(paths) {
183
+ return new MetadataError(`Duplicate table names are not allowed: ${paths.join(', ')}`);
179
184
  }
180
- static duplicateFieldName(className, names) {
181
- return new MetadataError(`Duplicate fieldNames are not allowed: ${names.map(n => `${className}.${n[0]} (fieldName: '${n[1]}')`).join(', ')}`);
185
+ static duplicateFieldName(entityName, names) {
186
+ return new MetadataError(`Duplicate fieldNames are not allowed: ${names.map(n => `${Utils.className(entityName)}.${n[0]} (fieldName: '${n[1]}')`).join(', ')}`);
182
187
  }
183
188
  static multipleDecorators(entityName, propertyName) {
184
189
  return new MetadataError(`Multiple property decorators used on '${entityName}.${propertyName}' property`);
@@ -208,6 +213,24 @@ export class MetadataError extends ValidationError {
208
213
  static fromMissingOption(meta, prop, option) {
209
214
  return this.fromMessage(meta, prop, `is missing '${option}' option`);
210
215
  }
216
+ static targetKeyOnManyToMany(meta, prop) {
217
+ return this.fromMessage(meta, prop, `uses 'targetKey' option which is not supported for ManyToMany relations`);
218
+ }
219
+ static targetKeyNotUnique(meta, prop) {
220
+ return this.fromMessage(meta, prop, `has 'targetKey' set to '${prop.targetKey}', but ${prop.type}.${prop.targetKey} is not marked as unique. The target property must have a unique constraint.`);
221
+ }
222
+ static targetKeyNotFound(meta, prop) {
223
+ return this.fromMessage(meta, prop, `has 'targetKey' set to '${prop.targetKey}', but ${prop.type}.${prop.targetKey} does not exist`);
224
+ }
225
+ static dangerousPropertyName(meta, prop) {
226
+ return this.fromMessage(meta, prop, `uses a dangerous property name '${prop.name}' which could lead to prototype pollution. Please use a different property name.`);
227
+ }
228
+ static viewEntityWithoutExpression(meta) {
229
+ return new MetadataError(`View entity ${meta.className} is missing 'expression'. View entities must have an expression defining the SQL query.`);
230
+ }
231
+ static materializedWithoutView(meta) {
232
+ return new MetadataError(`Entity ${meta.className} has 'materialized: true' but is missing 'view: true'. Materialized views must also be marked as views.`);
233
+ }
211
234
  static fromMessage(meta, prop, message) {
212
235
  return new MetadataError(`${meta.className}.${prop.name} ${message}`);
213
236
  }
@@ -219,4 +242,19 @@ export class NotFoundError extends ValidationError {
219
242
  static findExactlyOneFailed(name, where) {
220
243
  return new NotFoundError(`Wrong number of ${name} entities found for query ${inspect(where)}, expected exactly one`);
221
244
  }
245
+ static failedToLoadProperty(name, propName, where) {
246
+ const whereString = typeof where === 'object' ? inspect(where) : where;
247
+ return new NotFoundError(`${name} (${whereString}) failed to load property '${propName}'`);
248
+ }
249
+ }
250
+ export class TransactionStateError extends ValidationError {
251
+ static requiredTransactionNotFound(propagation) {
252
+ return new TransactionStateError(`No existing transaction found for transaction marked with propagation "${propagation}"`);
253
+ }
254
+ static transactionNotAllowed(propagation) {
255
+ return new TransactionStateError(`Existing transaction found for transaction marked with propagation "${propagation}"`);
256
+ }
257
+ static invalidPropagation(propagation) {
258
+ return new TransactionStateError(`Unsupported transaction propagation type: ${propagation}`);
259
+ }
222
260
  }
@@ -6,8 +6,9 @@ export declare class EventManager {
6
6
  private readonly entities;
7
7
  private readonly cache;
8
8
  private readonly subscribers;
9
- constructor(subscribers: EventSubscriber[]);
9
+ constructor(subscribers: Iterable<EventSubscriber>);
10
10
  registerSubscriber(subscriber: EventSubscriber): void;
11
+ getSubscribers(): Set<EventSubscriber>;
11
12
  dispatchEvent<T extends object>(event: TransactionEventType, args: TransactionEventArgs, meta?: EntityMetadata<T>): unknown;
12
13
  dispatchEvent<T extends object>(event: EventType.onInit, args: Partial<EventArgs<T>>, meta?: EntityMetadata<T>): unknown;
13
14
  dispatchEvent<T extends object>(event: EventType, args: Partial<EventArgs<T> | FlushEventArgs>, meta?: EntityMetadata<T>): Promise<unknown>;
@@ -4,21 +4,29 @@ export class EventManager {
4
4
  listeners = {};
5
5
  entities = new Map();
6
6
  cache = new Map();
7
- subscribers = [];
7
+ subscribers = new Set();
8
8
  constructor(subscribers) {
9
- subscribers.forEach(subscriber => this.registerSubscriber(subscriber));
9
+ for (const subscriber of subscribers) {
10
+ this.registerSubscriber(subscriber);
11
+ }
10
12
  }
11
13
  registerSubscriber(subscriber) {
12
- this.subscribers.push(subscriber);
14
+ if (this.subscribers.has(subscriber)) {
15
+ return;
16
+ }
17
+ this.subscribers.add(subscriber);
13
18
  this.entities.set(subscriber, this.getSubscribedEntities(subscriber));
14
19
  this.cache.clear();
15
20
  Utils.keys(EventType)
16
21
  .filter(event => event in subscriber)
17
22
  .forEach(event => {
18
- this.listeners[event] ??= [];
19
- this.listeners[event].push(subscriber);
23
+ this.listeners[event] ??= new Set();
24
+ this.listeners[event].add(subscriber);
20
25
  });
21
26
  }
27
+ getSubscribers() {
28
+ return this.subscribers;
29
+ }
22
30
  dispatchEvent(event, args, meta) {
23
31
  const listeners = [];
24
32
  const entity = args.entity;
@@ -30,9 +38,9 @@ export class EventManager {
30
38
  const handler = typeof hook === 'function' ? hook : entity[hook] ?? prototypeHook;
31
39
  return handler.bind(entity);
32
40
  }));
33
- for (const listener of this.listeners[event] || []) {
41
+ for (const listener of this.listeners[event] ?? new Set()) {
34
42
  const entities = this.entities.get(listener);
35
- if (entities.length === 0 || !entity || entities.includes(entity.constructor.name)) {
43
+ if (entities.size === 0 || !entity || entities.has(entity.constructor.name)) {
36
44
  listeners.push(listener[event].bind(listener));
37
45
  }
38
46
  }
@@ -51,9 +59,9 @@ export class EventManager {
51
59
  this.cache.set(cacheKey, true);
52
60
  return true;
53
61
  }
54
- for (const listener of this.listeners[event] ?? []) {
62
+ for (const listener of this.listeners[event] ?? new Set()) {
55
63
  const entities = this.entities.get(listener);
56
- if (entities.length === 0 || entities.includes(meta.className)) {
64
+ if (entities.size === 0 || entities.has(meta.className)) {
57
65
  this.cache.set(cacheKey, true);
58
66
  return true;
59
67
  }
@@ -66,8 +74,8 @@ export class EventManager {
66
74
  }
67
75
  getSubscribedEntities(listener) {
68
76
  if (!listener.getSubscribedEntities) {
69
- return [];
77
+ return new Set();
70
78
  }
71
- return listener.getSubscribedEntities().map(name => Utils.className(name));
79
+ return new Set(listener.getSubscribedEntities().map(name => Utils.className(name)));
72
80
  }
73
81
  }
@@ -1,4 +1,4 @@
1
- /* v8 ignore start */
1
+ /* v8 ignore next */
2
2
  export class Hydrator {
3
3
  metadata;
4
4
  platform;
@@ -45,4 +45,3 @@ export class Hydrator {
45
45
  entity[prop.name] = data[prop.name];
46
46
  }
47
47
  }
48
- /* v8 ignore stop */
@@ -1,22 +1,22 @@
1
1
  import type { EntityData, EntityMetadata } from '../typings.js';
2
2
  import { Hydrator } from './Hydrator.js';
3
3
  import type { EntityFactory } from '../entity/EntityFactory.js';
4
- type EntityHydrator<T extends object> = (entity: T, data: EntityData<T>, factory: EntityFactory, newEntity: boolean, convertCustomTypes: boolean, schema?: string, parentSchema?: string) => void;
4
+ type EntityHydrator<T extends object> = (entity: T, data: EntityData<T>, factory: EntityFactory, newEntity: boolean, convertCustomTypes: boolean, schema?: string, parentSchema?: string, normalizeAccessors?: boolean) => void;
5
5
  export declare class ObjectHydrator extends Hydrator {
6
6
  private readonly hydrators;
7
7
  private tmpIndex;
8
8
  /**
9
9
  * @inheritDoc
10
10
  */
11
- hydrate<T extends object>(entity: T, meta: EntityMetadata<T>, data: EntityData<T>, factory: EntityFactory, type: 'full' | 'reference', newEntity?: boolean, convertCustomTypes?: boolean, schema?: string, parentSchema?: string): void;
11
+ hydrate<T extends object>(entity: T, meta: EntityMetadata<T>, data: EntityData<T>, factory: EntityFactory, type: 'full' | 'reference', newEntity?: boolean, convertCustomTypes?: boolean, schema?: string, parentSchema?: string, normalizeAccessors?: boolean): void;
12
12
  /**
13
13
  * @inheritDoc
14
14
  */
15
- hydrateReference<T extends object>(entity: T, meta: EntityMetadata<T>, data: EntityData<T>, factory: EntityFactory, convertCustomTypes?: boolean, schema?: string, parentSchema?: string): void;
15
+ hydrateReference<T extends object>(entity: T, meta: EntityMetadata<T>, data: EntityData<T>, factory: EntityFactory, convertCustomTypes?: boolean, schema?: string, parentSchema?: string, normalizeAccessors?: boolean): void;
16
16
  /**
17
17
  * @internal Highly performance-sensitive method.
18
18
  */
19
- getEntityHydrator<T extends object>(meta: EntityMetadata<T>, type: 'full' | 'reference'): EntityHydrator<T>;
19
+ getEntityHydrator<T extends object>(meta: EntityMetadata<T>, type: 'full' | 'reference', normalizeAccessors?: boolean): EntityHydrator<T>;
20
20
  private createCollectionItemMapper;
21
21
  private wrap;
22
22
  private safeKey;