@mikro-orm/core 7.0.4 → 7.0.5-dev.0

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