@mikro-orm/core 7.0.9-dev.8 → 7.0.9

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