@mikro-orm/core 7.0.2-dev.9 → 7.0.2

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 (207) hide show
  1. package/EntityManager.d.ts +883 -579
  2. package/EntityManager.js +1897 -1865
  3. package/MikroORM.d.ts +103 -72
  4. package/MikroORM.js +178 -177
  5. package/README.md +128 -294
  6. package/cache/CacheAdapter.d.ts +38 -36
  7. package/cache/FileCacheAdapter.d.ts +30 -24
  8. package/cache/FileCacheAdapter.js +80 -78
  9. package/cache/GeneratedCacheAdapter.d.ts +19 -20
  10. package/cache/GeneratedCacheAdapter.js +31 -30
  11. package/cache/MemoryCacheAdapter.d.ts +19 -20
  12. package/cache/MemoryCacheAdapter.js +36 -36
  13. package/cache/NullCacheAdapter.d.ts +17 -16
  14. package/cache/NullCacheAdapter.js +25 -24
  15. package/connections/Connection.d.ts +99 -75
  16. package/connections/Connection.js +166 -160
  17. package/drivers/DatabaseDriver.d.ts +187 -69
  18. package/drivers/DatabaseDriver.js +451 -432
  19. package/drivers/IDatabaseDriver.d.ts +464 -281
  20. package/drivers/IDatabaseDriver.js +1 -0
  21. package/entity/BaseEntity.d.ts +121 -73
  22. package/entity/BaseEntity.js +44 -33
  23. package/entity/Collection.d.ts +216 -157
  24. package/entity/Collection.js +728 -707
  25. package/entity/EntityAssigner.d.ts +90 -76
  26. package/entity/EntityAssigner.js +232 -229
  27. package/entity/EntityFactory.d.ts +68 -40
  28. package/entity/EntityFactory.js +427 -366
  29. package/entity/EntityHelper.d.ts +34 -22
  30. package/entity/EntityHelper.js +280 -267
  31. package/entity/EntityIdentifier.d.ts +4 -4
  32. package/entity/EntityIdentifier.js +10 -10
  33. package/entity/EntityLoader.d.ts +105 -56
  34. package/entity/EntityLoader.js +754 -722
  35. package/entity/EntityRepository.d.ts +317 -200
  36. package/entity/EntityRepository.js +214 -212
  37. package/entity/PolymorphicRef.d.ts +5 -5
  38. package/entity/PolymorphicRef.js +10 -10
  39. package/entity/Reference.d.ts +130 -66
  40. package/entity/Reference.js +280 -260
  41. package/entity/WrappedEntity.d.ts +116 -53
  42. package/entity/WrappedEntity.js +169 -147
  43. package/entity/defineEntity.d.ts +1290 -614
  44. package/entity/defineEntity.js +521 -511
  45. package/entity/utils.d.ts +13 -3
  46. package/entity/utils.js +71 -73
  47. package/entity/validators.js +43 -43
  48. package/entity/wrap.js +8 -8
  49. package/enums.d.ts +275 -138
  50. package/enums.js +268 -137
  51. package/errors.d.ts +120 -72
  52. package/errors.js +356 -253
  53. package/events/EventManager.d.ts +27 -10
  54. package/events/EventManager.js +80 -73
  55. package/events/EventSubscriber.d.ts +33 -29
  56. package/events/TransactionEventBroadcaster.d.ts +16 -7
  57. package/events/TransactionEventBroadcaster.js +15 -13
  58. package/exceptions.d.ts +23 -40
  59. package/exceptions.js +35 -52
  60. package/hydration/Hydrator.d.ts +43 -16
  61. package/hydration/Hydrator.js +44 -42
  62. package/hydration/ObjectHydrator.d.ts +51 -17
  63. package/hydration/ObjectHydrator.js +480 -416
  64. package/index.d.ts +116 -2
  65. package/index.js +10 -1
  66. package/logging/DefaultLogger.d.ts +35 -30
  67. package/logging/DefaultLogger.js +87 -84
  68. package/logging/Logger.d.ts +45 -40
  69. package/logging/SimpleLogger.d.ts +13 -11
  70. package/logging/SimpleLogger.js +22 -22
  71. package/logging/colors.d.ts +6 -6
  72. package/logging/colors.js +11 -10
  73. package/logging/inspect.js +7 -7
  74. package/metadata/EntitySchema.d.ts +214 -108
  75. package/metadata/EntitySchema.js +398 -379
  76. package/metadata/MetadataDiscovery.d.ts +115 -111
  77. package/metadata/MetadataDiscovery.js +1948 -1857
  78. package/metadata/MetadataProvider.d.ts +25 -14
  79. package/metadata/MetadataProvider.js +83 -77
  80. package/metadata/MetadataStorage.d.ts +39 -19
  81. package/metadata/MetadataStorage.js +119 -106
  82. package/metadata/MetadataValidator.d.ts +39 -39
  83. package/metadata/MetadataValidator.js +381 -338
  84. package/metadata/discover-entities.d.ts +5 -2
  85. package/metadata/discover-entities.js +27 -27
  86. package/metadata/types.d.ts +615 -531
  87. package/naming-strategy/AbstractNamingStrategy.d.ts +55 -39
  88. package/naming-strategy/AbstractNamingStrategy.js +91 -85
  89. package/naming-strategy/EntityCaseNamingStrategy.d.ts +6 -6
  90. package/naming-strategy/EntityCaseNamingStrategy.js +22 -22
  91. package/naming-strategy/MongoNamingStrategy.d.ts +7 -6
  92. package/naming-strategy/MongoNamingStrategy.js +19 -18
  93. package/naming-strategy/NamingStrategy.d.ts +109 -99
  94. package/naming-strategy/UnderscoreNamingStrategy.d.ts +8 -7
  95. package/naming-strategy/UnderscoreNamingStrategy.js +22 -21
  96. package/not-supported.js +7 -4
  97. package/package.json +1 -1
  98. package/platforms/ExceptionConverter.d.ts +2 -1
  99. package/platforms/ExceptionConverter.js +5 -4
  100. package/platforms/Platform.d.ts +310 -236
  101. package/platforms/Platform.js +661 -573
  102. package/serialization/EntitySerializer.d.ts +49 -25
  103. package/serialization/EntitySerializer.js +224 -216
  104. package/serialization/EntityTransformer.d.ts +11 -5
  105. package/serialization/EntityTransformer.js +220 -216
  106. package/serialization/SerializationContext.d.ts +27 -18
  107. package/serialization/SerializationContext.js +105 -100
  108. package/types/ArrayType.d.ts +9 -8
  109. package/types/ArrayType.js +34 -33
  110. package/types/BigIntType.d.ts +17 -10
  111. package/types/BigIntType.js +37 -37
  112. package/types/BlobType.d.ts +4 -3
  113. package/types/BlobType.js +14 -13
  114. package/types/BooleanType.d.ts +5 -4
  115. package/types/BooleanType.js +13 -12
  116. package/types/CharacterType.d.ts +3 -2
  117. package/types/CharacterType.js +7 -6
  118. package/types/DateTimeType.d.ts +6 -5
  119. package/types/DateTimeType.js +16 -15
  120. package/types/DateType.d.ts +6 -5
  121. package/types/DateType.js +16 -15
  122. package/types/DecimalType.d.ts +7 -7
  123. package/types/DecimalType.js +26 -26
  124. package/types/DoubleType.d.ts +3 -3
  125. package/types/DoubleType.js +12 -12
  126. package/types/EnumArrayType.d.ts +6 -5
  127. package/types/EnumArrayType.js +25 -24
  128. package/types/EnumType.d.ts +4 -3
  129. package/types/EnumType.js +12 -11
  130. package/types/FloatType.d.ts +4 -3
  131. package/types/FloatType.js +10 -9
  132. package/types/IntegerType.d.ts +4 -3
  133. package/types/IntegerType.js +10 -9
  134. package/types/IntervalType.d.ts +5 -4
  135. package/types/IntervalType.js +13 -12
  136. package/types/JsonType.d.ts +9 -8
  137. package/types/JsonType.js +33 -32
  138. package/types/MediumIntType.d.ts +2 -1
  139. package/types/MediumIntType.js +4 -3
  140. package/types/SmallIntType.d.ts +4 -3
  141. package/types/SmallIntType.js +10 -9
  142. package/types/StringType.d.ts +5 -4
  143. package/types/StringType.js +13 -12
  144. package/types/TextType.d.ts +4 -3
  145. package/types/TextType.js +10 -9
  146. package/types/TimeType.d.ts +6 -5
  147. package/types/TimeType.js +18 -17
  148. package/types/TinyIntType.d.ts +4 -3
  149. package/types/TinyIntType.js +11 -10
  150. package/types/Type.d.ts +88 -73
  151. package/types/Type.js +85 -74
  152. package/types/Uint8ArrayType.d.ts +5 -4
  153. package/types/Uint8ArrayType.js +22 -21
  154. package/types/UnknownType.d.ts +5 -4
  155. package/types/UnknownType.js +13 -12
  156. package/types/UuidType.d.ts +6 -5
  157. package/types/UuidType.js +20 -19
  158. package/types/index.d.ts +77 -49
  159. package/types/index.js +64 -26
  160. package/typings.d.ts +1388 -729
  161. package/typings.js +255 -231
  162. package/unit-of-work/ChangeSet.d.ts +28 -24
  163. package/unit-of-work/ChangeSet.js +58 -54
  164. package/unit-of-work/ChangeSetComputer.d.ts +13 -11
  165. package/unit-of-work/ChangeSetComputer.js +180 -159
  166. package/unit-of-work/ChangeSetPersister.d.ts +64 -41
  167. package/unit-of-work/ChangeSetPersister.js +443 -418
  168. package/unit-of-work/CommitOrderCalculator.d.ts +40 -40
  169. package/unit-of-work/CommitOrderCalculator.js +89 -88
  170. package/unit-of-work/IdentityMap.d.ts +32 -25
  171. package/unit-of-work/IdentityMap.js +106 -99
  172. package/unit-of-work/UnitOfWork.d.ts +182 -127
  173. package/unit-of-work/UnitOfWork.js +1201 -1169
  174. package/utils/AbstractMigrator.d.ts +111 -91
  175. package/utils/AbstractMigrator.js +275 -275
  176. package/utils/AbstractSchemaGenerator.d.ts +43 -34
  177. package/utils/AbstractSchemaGenerator.js +121 -122
  178. package/utils/AsyncContext.d.ts +3 -3
  179. package/utils/AsyncContext.js +34 -35
  180. package/utils/Configuration.d.ts +853 -801
  181. package/utils/Configuration.js +360 -337
  182. package/utils/Cursor.d.ts +40 -22
  183. package/utils/Cursor.js +135 -127
  184. package/utils/DataloaderUtils.d.ts +58 -43
  185. package/utils/DataloaderUtils.js +203 -198
  186. package/utils/EntityComparator.d.ts +99 -80
  187. package/utils/EntityComparator.js +825 -727
  188. package/utils/NullHighlighter.d.ts +2 -1
  189. package/utils/NullHighlighter.js +4 -3
  190. package/utils/QueryHelper.d.ts +79 -51
  191. package/utils/QueryHelper.js +372 -361
  192. package/utils/RawQueryFragment.d.ts +54 -28
  193. package/utils/RawQueryFragment.js +110 -99
  194. package/utils/RequestContext.d.ts +33 -32
  195. package/utils/RequestContext.js +52 -53
  196. package/utils/TransactionContext.d.ts +17 -16
  197. package/utils/TransactionContext.js +28 -27
  198. package/utils/TransactionManager.d.ts +58 -58
  199. package/utils/TransactionManager.js +199 -197
  200. package/utils/Utils.d.ts +210 -145
  201. package/utils/Utils.js +820 -813
  202. package/utils/clone.js +104 -113
  203. package/utils/env-vars.js +90 -88
  204. package/utils/fs-utils.d.ts +15 -15
  205. package/utils/fs-utils.js +180 -181
  206. package/utils/upsert-utils.d.ts +20 -5
  207. package/utils/upsert-utils.js +114 -116
package/typings.js CHANGED
@@ -1,263 +1,287 @@
1
- import { ReferenceKind, } from './enums.js';
1
+ import { ReferenceKind } from './enums.js';
2
2
  import { Reference } from './entity/Reference.js';
3
3
  import { EntityHelper } from './entity/EntityHelper.js';
4
4
  import { helper } from './entity/wrap.js';
5
5
  import { Utils } from './utils/Utils.js';
6
6
  import { EntityComparator } from './utils/EntityComparator.js';
7
7
  import { BaseEntity } from './entity/BaseEntity.js';
8
+ /** Symbol used to declare a custom repository type on an entity class (e.g., `[EntityRepositoryType]?: BookRepository`). */
8
9
  export const EntityRepositoryType = Symbol('EntityRepositoryType');
10
+ /** Symbol used to declare the primary key property name(s) on an entity (e.g., `[PrimaryKeyProp]?: 'id'`). */
9
11
  export const PrimaryKeyProp = Symbol('PrimaryKeyProp');
12
+ /** Symbol used to declare which properties are optional in `em.create()` (e.g., `[OptionalProps]?: 'createdAt'`). */
10
13
  export const OptionalProps = Symbol('OptionalProps');
14
+ /** Symbol used to declare which relation properties should be eagerly loaded (e.g., `[EagerProps]?: 'author'`). */
11
15
  export const EagerProps = Symbol('EagerProps');
16
+ /** Symbol used to declare which properties are hidden from serialization (e.g., `[HiddenProps]?: 'password'`). */
12
17
  export const HiddenProps = Symbol('HiddenProps');
18
+ /** Symbol used to declare type-level configuration on an entity (e.g., `[Config]?: DefineConfig<{ forceObject: true }>`). */
13
19
  export const Config = Symbol('Config');
20
+ /** Symbol used to declare the entity name as a string literal type (used by `defineEntity`). */
14
21
  // eslint-disable-next-line @typescript-eslint/no-redeclare
15
22
  export const EntityName = Symbol('EntityName');
23
+ /**
24
+ * Runtime metadata for an entity, holding its properties, relations, indexes, hooks, and more.
25
+ * Created during metadata discovery and used throughout the ORM lifecycle.
26
+ */
16
27
  export class EntityMetadata {
17
- static counter = 0;
18
- _id = 1000 * EntityMetadata.counter++; // keep the id >= 1000 to allow computing cache keys by simple addition
19
- propertyOrder = new Map();
20
- constructor(meta = {}) {
21
- this.properties = {};
22
- this.props = [];
23
- this.primaryKeys = [];
24
- this.filters = {};
25
- this.hooks = {};
26
- this.indexes = [];
27
- this.uniques = [];
28
- this.checks = [];
29
- this.referencingProperties = [];
30
- this.concurrencyCheckKeys = new Set();
31
- Object.assign(this, meta);
32
- const name = meta.className ?? meta.name;
33
- if (!this.class && name) {
34
- const Class = this.extends === BaseEntity ? { [name]: class extends BaseEntity {
35
- } }[name] : { [name]: class {
36
- } }[name];
37
- this.class = Class;
38
- }
28
+ static counter = 0;
29
+ _id = 1000 * EntityMetadata.counter++; // keep the id >= 1000 to allow computing cache keys by simple addition
30
+ propertyOrder = new Map();
31
+ constructor(meta = {}) {
32
+ this.properties = {};
33
+ this.props = [];
34
+ this.primaryKeys = [];
35
+ this.filters = {};
36
+ this.hooks = {};
37
+ this.indexes = [];
38
+ this.uniques = [];
39
+ this.checks = [];
40
+ this.referencingProperties = [];
41
+ this.concurrencyCheckKeys = new Set();
42
+ Object.assign(this, meta);
43
+ const name = meta.className ?? meta.name;
44
+ if (!this.class && name) {
45
+ const Class =
46
+ this.extends === BaseEntity ? { [name]: class extends BaseEntity {} }[name] : { [name]: class {} }[name];
47
+ this.class = Class;
39
48
  }
40
- addProperty(prop) {
41
- this.properties[prop.name] = prop;
42
- this.propertyOrder.set(prop.name, this.props.length);
43
- this.sync();
49
+ }
50
+ addProperty(prop) {
51
+ this.properties[prop.name] = prop;
52
+ this.propertyOrder.set(prop.name, this.props.length);
53
+ this.sync();
54
+ }
55
+ removeProperty(name, sync = true) {
56
+ delete this.properties[name];
57
+ this.propertyOrder.delete(name);
58
+ if (sync) {
59
+ this.sync();
44
60
  }
45
- removeProperty(name, sync = true) {
46
- delete this.properties[name];
47
- this.propertyOrder.delete(name);
48
- if (sync) {
49
- this.sync();
61
+ }
62
+ getPrimaryProps(flatten = false) {
63
+ const pks = this.primaryKeys.map(pk => this.properties[pk]);
64
+ if (flatten) {
65
+ return pks.flatMap(pk => {
66
+ if ([ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(pk.kind)) {
67
+ return pk.targetMeta.getPrimaryProps(true);
50
68
  }
69
+ return [pk];
70
+ });
51
71
  }
52
- getPrimaryProps(flatten = false) {
53
- const pks = this.primaryKeys.map(pk => this.properties[pk]);
54
- if (flatten) {
55
- return pks.flatMap(pk => {
56
- if ([ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(pk.kind)) {
57
- return pk.targetMeta.getPrimaryProps(true);
58
- }
59
- return [pk];
60
- });
72
+ return pks;
73
+ }
74
+ getPrimaryProp() {
75
+ return this.properties[this.primaryKeys[0]];
76
+ }
77
+ /**
78
+ * Creates a mapping from property names to field names.
79
+ * @param alias - Optional alias to prefix field names. Can be a string (same for all) or a function (per-property).
80
+ * When provided, also adds toString() returning the alias for backwards compatibility with formulas.
81
+ * @param toStringAlias - Optional alias to return from toString(). Defaults to `alias` when it's a string.
82
+ */
83
+ createColumnMappingObject(alias, toStringAlias) {
84
+ const resolveAlias = typeof alias === 'function' ? alias : () => alias;
85
+ const defaultAlias = toStringAlias ?? (typeof alias === 'string' ? alias : undefined);
86
+ const result = Object.values(this.properties).reduce((o, prop) => {
87
+ if (prop.fieldNames) {
88
+ const propAlias = resolveAlias(prop);
89
+ o[prop.name] = propAlias ? `${propAlias}.${prop.fieldNames[0]}` : prop.fieldNames[0];
90
+ }
91
+ return o;
92
+ }, {});
93
+ // Add toString() for backwards compatibility when alias is provided
94
+ Object.defineProperty(result, 'toString', {
95
+ value: () => defaultAlias ?? '',
96
+ enumerable: false,
97
+ });
98
+ // Wrap in Proxy to detect old formula signature usage where the first param was FormulaTable.
99
+ // If user accesses `.alias` or `.qualifiedName` (FormulaTable-only properties), warn them.
100
+ const warnedProps = new Set(['alias', 'qualifiedName']);
101
+ return new Proxy(result, {
102
+ get(target, prop, receiver) {
103
+ if (typeof prop === 'string' && warnedProps.has(prop) && !(prop in target)) {
104
+ // eslint-disable-next-line no-console
105
+ console.warn(
106
+ `[MikroORM] Detected old formula callback signature. The first parameter is now 'columns', not 'table'. ` +
107
+ `Accessing '.${prop}' on the columns object will return undefined. ` +
108
+ `Update your formula: formula(cols => quote\`\${cols.propName} ...\`). See the v7 upgrade guide.`,
109
+ );
61
110
  }
62
- return pks;
63
- }
64
- getPrimaryProp() {
65
- return this.properties[this.primaryKeys[0]];
111
+ return Reflect.get(target, prop, receiver);
112
+ },
113
+ });
114
+ }
115
+ /**
116
+ * Creates a column mapping for schema callbacks (indexes, checks, generated columns).
117
+ * For TPT entities, only includes properties that belong to the current table (ownProps).
118
+ */
119
+ createSchemaColumnMappingObject() {
120
+ // For TPT entities, only include properties that belong to this entity's table
121
+ const props = this.inheritanceType === 'tpt' && this.ownProps ? this.ownProps : Object.values(this.properties);
122
+ return props.reduce((o, prop) => {
123
+ if (prop.fieldNames) {
124
+ o[prop.name] = prop.fieldNames[0];
125
+ }
126
+ return o;
127
+ }, {});
128
+ }
129
+ get tableName() {
130
+ return this.collection;
131
+ }
132
+ set tableName(name) {
133
+ this.collection = name;
134
+ }
135
+ get uniqueName() {
136
+ return this.tableName + '_' + this._id;
137
+ }
138
+ sync(initIndexes = false, config) {
139
+ this.root ??= this;
140
+ const props = Object.values(this.properties).sort(
141
+ (a, b) => this.propertyOrder.get(a.name) - this.propertyOrder.get(b.name),
142
+ );
143
+ this.props = [...props.filter(p => p.primary), ...props.filter(p => !p.primary)];
144
+ this.relations = this.props.filter(
145
+ prop =>
146
+ typeof prop.kind !== 'undefined' && prop.kind !== ReferenceKind.SCALAR && prop.kind !== ReferenceKind.EMBEDDED,
147
+ );
148
+ this.bidirectionalRelations = this.relations.filter(prop => prop.mappedBy || prop.inversedBy);
149
+ this.uniqueProps = this.props.filter(prop => prop.unique);
150
+ this.getterProps = this.props.filter(prop => prop.getter);
151
+ this.comparableProps = this.props.filter(prop => EntityComparator.isComparable(prop, this));
152
+ this.validateProps = this.props.filter(prop => {
153
+ if (prop.inherited || (prop.persist === false && prop.userDefined !== false)) {
154
+ return false;
155
+ }
156
+ return prop.kind === ReferenceKind.SCALAR && ['string', 'number', 'boolean', 'Date'].includes(prop.type);
157
+ });
158
+ this.hydrateProps = this.props.filter(prop => {
159
+ // `prop.userDefined` is either `undefined` or `false`
160
+ const discriminator = this.root.discriminatorColumn === prop.name && prop.userDefined === false;
161
+ // even if we don't have a setter, do not ignore value from database!
162
+ const onlyGetter = prop.getter && !prop.setter && prop.persist === false;
163
+ return !prop.inherited && prop.hydrate !== false && !discriminator && !prop.embedded && !onlyGetter;
164
+ });
165
+ this.trackingProps = this.hydrateProps.filter(prop => {
166
+ return !prop.getter && !prop.setter && [ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(prop.kind);
167
+ });
168
+ this.selfReferencing = this.relations.some(prop => {
169
+ return this.root.uniqueName === prop.targetMeta?.root.uniqueName;
170
+ });
171
+ this.hasUniqueProps = this.uniques.length + this.uniqueProps.length > 0;
172
+ // Normalize object-form `view` option: `view: { materialized: true, withData: false }`
173
+ // into flat metadata fields (`view: true`, `materialized: true`, `withData: false`).
174
+ if (typeof this.view === 'object') {
175
+ this.materialized = this.view.materialized;
176
+ this.withData = this.view.withData;
177
+ this.view = true;
66
178
  }
67
- /**
68
- * Creates a mapping from property names to field names.
69
- * @param alias - Optional alias to prefix field names. Can be a string (same for all) or a function (per-property).
70
- * When provided, also adds toString() returning the alias for backwards compatibility with formulas.
71
- * @param toStringAlias - Optional alias to return from toString(). Defaults to `alias` when it's a string.
72
- */
73
- createColumnMappingObject(alias, toStringAlias) {
74
- const resolveAlias = typeof alias === 'function' ? alias : () => alias;
75
- const defaultAlias = toStringAlias ?? (typeof alias === 'string' ? alias : undefined);
76
- const result = Object.values(this.properties).reduce((o, prop) => {
77
- if (prop.fieldNames) {
78
- const propAlias = resolveAlias(prop);
79
- o[prop.name] = propAlias ? `${propAlias}.${prop.fieldNames[0]}` : prop.fieldNames[0];
80
- }
81
- return o;
82
- }, {});
83
- // Add toString() for backwards compatibility when alias is provided
84
- Object.defineProperty(result, 'toString', {
85
- value: () => defaultAlias ?? '',
86
- enumerable: false,
87
- });
88
- // Wrap in Proxy to detect old formula signature usage where the first param was FormulaTable.
89
- // If user accesses `.alias` or `.qualifiedName` (FormulaTable-only properties), warn them.
90
- const warnedProps = new Set(['alias', 'qualifiedName']);
91
- return new Proxy(result, {
92
- get(target, prop, receiver) {
93
- if (typeof prop === 'string' && warnedProps.has(prop) && !(prop in target)) {
94
- // eslint-disable-next-line no-console
95
- console.warn(`[MikroORM] Detected old formula callback signature. The first parameter is now 'columns', not 'table'. ` +
96
- `Accessing '.${prop}' on the columns object will return undefined. ` +
97
- `Update your formula: formula(cols => quote\`\${cols.propName} ...\`). See the v7 upgrade guide.`);
98
- }
99
- return Reflect.get(target, prop, receiver);
100
- },
101
- });
102
- }
103
- /**
104
- * Creates a column mapping for schema callbacks (indexes, checks, generated columns).
105
- * For TPT entities, only includes properties that belong to the current table (ownProps).
106
- */
107
- createSchemaColumnMappingObject() {
108
- // For TPT entities, only include properties that belong to this entity's table
109
- const props = this.inheritanceType === 'tpt' && this.ownProps ? this.ownProps : Object.values(this.properties);
110
- return props.reduce((o, prop) => {
111
- if (prop.fieldNames) {
112
- o[prop.name] = prop.fieldNames[0];
113
- }
114
- return o;
115
- }, {});
179
+ // If `view` is set, this is a database view entity (not a virtual entity).
180
+ // Virtual entities evaluate expressions at query time, view entities create actual database views.
181
+ this.virtual = !!this.expression && !this.view;
182
+ if (config) {
183
+ for (const prop of this.props) {
184
+ if (prop.enum && !prop.nativeEnumName && prop.items?.every(item => typeof item === 'string')) {
185
+ const name = config.getNamingStrategy().indexName(this.tableName, prop.fieldNames, 'check');
186
+ const exists = this.checks.findIndex(check => check.name === name);
187
+ if (exists !== -1) {
188
+ this.checks.splice(exists, 1);
189
+ }
190
+ this.checks.push({
191
+ name,
192
+ property: prop.name,
193
+ expression: `${config.getPlatform().quoteIdentifier(prop.fieldNames[0])} in ('${prop.items.join("', '")}')`,
194
+ });
195
+ }
196
+ }
116
197
  }
117
- get tableName() {
118
- return this.collection;
198
+ this.checks = Utils.removeDuplicates(this.checks);
199
+ this.indexes = Utils.removeDuplicates(this.indexes);
200
+ this.uniques = Utils.removeDuplicates(this.uniques);
201
+ for (const hook of Utils.keys(this.hooks)) {
202
+ this.hooks[hook] = Utils.removeDuplicates(this.hooks[hook]);
119
203
  }
120
- set tableName(name) {
121
- this.collection = name;
204
+ if (this.virtual || this.view) {
205
+ this.readonly = true;
122
206
  }
123
- get uniqueName() {
124
- return this.tableName + '_' + this._id;
207
+ if (initIndexes && this.name) {
208
+ this.props.forEach(prop => this.initIndexes(prop));
125
209
  }
126
- sync(initIndexes = false, config) {
127
- this.root ??= this;
128
- const props = Object.values(this.properties).sort((a, b) => this.propertyOrder.get(a.name) - this.propertyOrder.get(b.name));
129
- this.props = [...props.filter(p => p.primary), ...props.filter(p => !p.primary)];
130
- this.relations = this.props.filter(prop => typeof prop.kind !== 'undefined' && prop.kind !== ReferenceKind.SCALAR && prop.kind !== ReferenceKind.EMBEDDED);
131
- this.bidirectionalRelations = this.relations.filter(prop => prop.mappedBy || prop.inversedBy);
132
- this.uniqueProps = this.props.filter(prop => prop.unique);
133
- this.getterProps = this.props.filter(prop => prop.getter);
134
- this.comparableProps = this.props.filter(prop => EntityComparator.isComparable(prop, this));
135
- this.validateProps = this.props.filter(prop => {
136
- if (prop.inherited || (prop.persist === false && prop.userDefined !== false)) {
137
- return false;
138
- }
139
- return prop.kind === ReferenceKind.SCALAR && ['string', 'number', 'boolean', 'Date'].includes(prop.type);
140
- });
141
- this.hydrateProps = this.props.filter(prop => {
142
- // `prop.userDefined` is either `undefined` or `false`
143
- const discriminator = this.root.discriminatorColumn === prop.name && prop.userDefined === false;
144
- // even if we don't have a setter, do not ignore value from database!
145
- const onlyGetter = prop.getter && !prop.setter && prop.persist === false;
146
- return !prop.inherited && prop.hydrate !== false && !discriminator && !prop.embedded && !onlyGetter;
147
- });
148
- this.trackingProps = this.hydrateProps.filter(prop => {
149
- return !prop.getter && !prop.setter && [ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(prop.kind);
150
- });
151
- this.selfReferencing = this.relations.some(prop => {
152
- return this.root.uniqueName === prop.targetMeta?.root.uniqueName;
153
- });
154
- this.hasUniqueProps = this.uniques.length + this.uniqueProps.length > 0;
155
- // Normalize object-form `view` option: `view: { materialized: true, withData: false }`
156
- // into flat metadata fields (`view: true`, `materialized: true`, `withData: false`).
157
- if (typeof this.view === 'object') {
158
- this.materialized = this.view.materialized;
159
- this.withData = this.view.withData;
160
- this.view = true;
161
- }
162
- // If `view` is set, this is a database view entity (not a virtual entity).
163
- // Virtual entities evaluate expressions at query time, view entities create actual database views.
164
- this.virtual = !!this.expression && !this.view;
165
- if (config) {
166
- for (const prop of this.props) {
167
- if (prop.enum && !prop.nativeEnumName && prop.items?.every(item => typeof item === 'string')) {
168
- const name = config.getNamingStrategy().indexName(this.tableName, prop.fieldNames, 'check');
169
- const exists = this.checks.findIndex(check => check.name === name);
170
- if (exists !== -1) {
171
- this.checks.splice(exists, 1);
172
- }
173
- this.checks.push({
174
- name,
175
- property: prop.name,
176
- expression: `${config.getPlatform().quoteIdentifier(prop.fieldNames[0])} in ('${prop.items.join("', '")}')`,
177
- });
210
+ this.definedProperties = this.trackingProps.reduce(
211
+ (o, prop) => {
212
+ const hasInverse = (prop.inversedBy || prop.mappedBy) && !prop.mapToPk;
213
+ if (hasInverse) {
214
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
215
+ const meta = this;
216
+ o[prop.name] = {
217
+ get() {
218
+ return this.__helper.__data[prop.name];
219
+ },
220
+ set(val) {
221
+ const wrapped = this.__helper;
222
+ const hydrator = wrapped.hydrator;
223
+ const entity = Reference.unwrapReference(val ?? wrapped.__data[prop.name]);
224
+ const old = Reference.unwrapReference(wrapped.__data[prop.name]);
225
+ if (
226
+ old &&
227
+ old !== entity &&
228
+ prop.kind === ReferenceKind.MANY_TO_ONE &&
229
+ prop.inversedBy &&
230
+ old[prop.inversedBy]
231
+ ) {
232
+ old[prop.inversedBy].removeWithoutPropagation(this);
233
+ }
234
+ wrapped.__data[prop.name] = Reference.wrapReference(val, prop);
235
+ // when propagation from inside hydration, we set the FK to the entity data immediately
236
+ if (val && hydrator.isRunning() && wrapped.__originalEntityData && prop.owner) {
237
+ const targetMeta = prop.targetMeta ?? helper(entity)?.__meta;
238
+ if (targetMeta) {
239
+ wrapped.__originalEntityData[prop.name] = Utils.getPrimaryKeyValues(val, targetMeta, true);
178
240
  }
179
- }
180
- }
181
- this.checks = Utils.removeDuplicates(this.checks);
182
- this.indexes = Utils.removeDuplicates(this.indexes);
183
- this.uniques = Utils.removeDuplicates(this.uniques);
184
- for (const hook of Utils.keys(this.hooks)) {
185
- this.hooks[hook] = Utils.removeDuplicates(this.hooks[hook]);
186
- }
187
- if (this.virtual || this.view) {
188
- this.readonly = true;
189
- }
190
- if (initIndexes && this.name) {
191
- this.props.forEach(prop => this.initIndexes(prop));
241
+ }
242
+ EntityHelper.propagate(meta, entity, this, prop, Reference.unwrapReference(val), old);
243
+ },
244
+ enumerable: true,
245
+ configurable: true,
246
+ };
192
247
  }
193
- this.definedProperties = this.trackingProps.reduce((o, prop) => {
194
- const hasInverse = (prop.inversedBy || prop.mappedBy) && !prop.mapToPk;
195
- if (hasInverse) {
196
- // eslint-disable-next-line @typescript-eslint/no-this-alias
197
- const meta = this;
198
- o[prop.name] = {
199
- get() {
200
- return this.__helper.__data[prop.name];
201
- },
202
- set(val) {
203
- const wrapped = this.__helper;
204
- const hydrator = wrapped.hydrator;
205
- const entity = Reference.unwrapReference(val ?? wrapped.__data[prop.name]);
206
- const old = Reference.unwrapReference(wrapped.__data[prop.name]);
207
- if (old &&
208
- old !== entity &&
209
- prop.kind === ReferenceKind.MANY_TO_ONE &&
210
- prop.inversedBy &&
211
- old[prop.inversedBy]) {
212
- old[prop.inversedBy].removeWithoutPropagation(this);
213
- }
214
- wrapped.__data[prop.name] = Reference.wrapReference(val, prop);
215
- // when propagation from inside hydration, we set the FK to the entity data immediately
216
- if (val && hydrator.isRunning() && wrapped.__originalEntityData && prop.owner) {
217
- const targetMeta = prop.targetMeta ?? helper(entity)?.__meta;
218
- if (targetMeta) {
219
- wrapped.__originalEntityData[prop.name] = Utils.getPrimaryKeyValues(val, targetMeta, true);
220
- }
221
- }
222
- EntityHelper.propagate(meta, entity, this, prop, Reference.unwrapReference(val), old);
223
- },
224
- enumerable: true,
225
- configurable: true,
226
- };
227
- }
228
- return o;
229
- }, { __gettersDefined: { value: true, enumerable: false } });
248
+ return o;
249
+ },
250
+ { __gettersDefined: { value: true, enumerable: false } },
251
+ );
252
+ }
253
+ initIndexes(prop) {
254
+ const simpleIndex = this.indexes.find(
255
+ index => index.properties === prop.name && !index.options && !index.type && !index.expression,
256
+ );
257
+ const simpleUnique = this.uniques.find(index => index.properties === prop.name && !index.options);
258
+ const owner = prop.kind === ReferenceKind.MANY_TO_ONE;
259
+ if (!prop.index && simpleIndex) {
260
+ Utils.defaultValue(simpleIndex, 'name', true);
261
+ prop.index = simpleIndex.name;
262
+ this.indexes.splice(this.indexes.indexOf(simpleIndex), 1);
230
263
  }
231
- initIndexes(prop) {
232
- const simpleIndex = this.indexes.find(index => index.properties === prop.name && !index.options && !index.type && !index.expression);
233
- const simpleUnique = this.uniques.find(index => index.properties === prop.name && !index.options);
234
- const owner = prop.kind === ReferenceKind.MANY_TO_ONE;
235
- if (!prop.index && simpleIndex) {
236
- Utils.defaultValue(simpleIndex, 'name', true);
237
- prop.index = simpleIndex.name;
238
- this.indexes.splice(this.indexes.indexOf(simpleIndex), 1);
239
- }
240
- if (!prop.unique && simpleUnique) {
241
- Utils.defaultValue(simpleUnique, 'name', true);
242
- prop.unique = simpleUnique.name;
243
- this.uniques.splice(this.uniques.indexOf(simpleUnique), 1);
244
- }
245
- if (prop.index && owner && prop.fieldNames.length > 1) {
246
- this.indexes.push({ properties: prop.name });
247
- prop.index = false;
248
- }
249
- /* v8 ignore next */
250
- if (owner && prop.fieldNames.length > 1 && prop.unique) {
251
- this.uniques.push({ properties: prop.name });
252
- prop.unique = false;
253
- }
264
+ if (!prop.unique && simpleUnique) {
265
+ Utils.defaultValue(simpleUnique, 'name', true);
266
+ prop.unique = simpleUnique.name;
267
+ this.uniques.splice(this.uniques.indexOf(simpleUnique), 1);
254
268
  }
255
- /** @internal */
256
- clone() {
257
- return this;
269
+ if (prop.index && owner && prop.fieldNames.length > 1) {
270
+ this.indexes.push({ properties: prop.name });
271
+ prop.index = false;
258
272
  }
259
- /** @ignore */
260
- [Symbol.for('nodejs.util.inspect.custom')]() {
261
- return `[${this.constructor.name}<${this.className}>]`;
273
+ /* v8 ignore next */
274
+ if (owner && prop.fieldNames.length > 1 && prop.unique) {
275
+ this.uniques.push({ properties: prop.name });
276
+ prop.unique = false;
262
277
  }
278
+ }
279
+ /** @internal */
280
+ clone() {
281
+ return this;
282
+ }
283
+ /** @ignore */
284
+ [Symbol.for('nodejs.util.inspect.custom')]() {
285
+ return `[${this.constructor.name}<${this.className}>]`;
286
+ }
263
287
  }
@@ -1,31 +1,35 @@
1
1
  import type { EntityData, EntityMetadata, EntityDictionary, Primary } from '../typings.js';
2
+ /** Represents a pending change (create, update, or delete) for a single entity. */
2
3
  export declare class ChangeSet<T extends object> {
3
- entity: T;
4
- type: ChangeSetType;
5
- payload: EntityDictionary<T>;
6
- meta: EntityMetadata<T>;
7
- private primaryKey?;
8
- private serializedPrimaryKey?;
9
- constructor(entity: T, type: ChangeSetType, payload: EntityDictionary<T>, meta: EntityMetadata<T>);
10
- getPrimaryKey(object?: boolean): Primary<T> | null;
11
- getSerializedPrimaryKey(): string | null;
4
+ entity: T;
5
+ type: ChangeSetType;
6
+ payload: EntityDictionary<T>;
7
+ meta: EntityMetadata<T>;
8
+ private primaryKey?;
9
+ private serializedPrimaryKey?;
10
+ constructor(entity: T, type: ChangeSetType, payload: EntityDictionary<T>, meta: EntityMetadata<T>);
11
+ /** Returns the primary key of the entity, optionally as an object for composite keys. */
12
+ getPrimaryKey(object?: boolean): Primary<T> | null;
13
+ /** Returns the serialized (string) form of the primary key. */
14
+ getSerializedPrimaryKey(): string | null;
12
15
  }
13
16
  export interface ChangeSet<T> {
14
- meta: EntityMetadata<T>;
15
- rootMeta: EntityMetadata<T>;
16
- schema?: string;
17
- type: ChangeSetType;
18
- entity: T;
19
- payload: EntityDictionary<T>;
20
- persisted: boolean;
21
- originalEntity?: EntityData<T>;
22
- /** For TPT: changesets for parent tables, ordered from immediate parent to root */
23
- tptChangeSets?: ChangeSet<T>[];
17
+ meta: EntityMetadata<T>;
18
+ rootMeta: EntityMetadata<T>;
19
+ schema?: string;
20
+ type: ChangeSetType;
21
+ entity: T;
22
+ payload: EntityDictionary<T>;
23
+ persisted: boolean;
24
+ originalEntity?: EntityData<T>;
25
+ /** For TPT: changesets for parent tables, ordered from immediate parent to root */
26
+ tptChangeSets?: ChangeSet<T>[];
24
27
  }
28
+ /** Enumeration of change set operation types. */
25
29
  export declare enum ChangeSetType {
26
- CREATE = "create",
27
- UPDATE = "update",
28
- DELETE = "delete",
29
- UPDATE_EARLY = "update_early",
30
- DELETE_EARLY = "delete_early"
30
+ CREATE = 'create',
31
+ UPDATE = 'update',
32
+ DELETE = 'delete',
33
+ UPDATE_EARLY = 'update_early',
34
+ DELETE_EARLY = 'delete_early',
31
35
  }