@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
@@ -1,386 +1,405 @@
1
- import { EntityMetadata, } from '../typings.js';
1
+ import { EntityMetadata } from '../typings.js';
2
2
  import { BaseEntity } from '../entity/BaseEntity.js';
3
3
  import { Cascade, ReferenceKind } from '../enums.js';
4
4
  import { Type } from '../types/Type.js';
5
5
  import { Utils } from '../utils/Utils.js';
6
6
  import { EnumArrayType } from '../types/EnumArrayType.js';
7
+ /** Class-less entity definition that provides a programmatic API for defining entities without decorators. */
7
8
  export class EntitySchema {
8
- /**
9
- * When schema links the entity class via `class` option, this registry allows the lookup from opposite side,
10
- * so we can use the class in `entities` option just like the EntitySchema instance.
11
- */
12
- static REGISTRY = new Map();
13
- _meta;
14
- internal = false;
15
- initialized = false;
16
- constructor(meta) {
17
- meta.name = meta.class ? meta.class.name : meta.name;
18
- if (meta.name) {
19
- meta.abstract ??= false;
20
- }
21
- this._meta = new EntityMetadata({
22
- className: meta.name,
23
- ...meta,
24
- });
25
- this._meta.root ??= this._meta;
26
- if (meta.class && !meta.internal) {
27
- EntitySchema.REGISTRY.set(meta.class, this);
28
- }
29
- }
30
- /**
31
- * Checks if the given value is an EntitySchema instance, using duck-typing
32
- * as a fallback when `instanceof` fails due to CJS/ESM dual-package hazard
33
- * (e.g. when using `tsx` or `@swc-node/register` with `"type": "commonjs"` projects).
34
- */
35
- static is(item) {
36
- if (item instanceof EntitySchema) {
37
- return true;
38
- }
39
- return item != null && typeof item === 'object' && item.constructor?.name === 'EntitySchema' && 'meta' in item;
40
- }
41
- static fromMetadata(meta) {
42
- const schema = new EntitySchema({ ...meta, internal: true });
43
- schema.internal = true;
44
- return schema;
45
- }
46
- addProperty(name, type, options = {}) {
47
- this.renameCompositeOptions(name, options);
48
- const prop = {
49
- name,
50
- kind: ReferenceKind.SCALAR,
51
- ...options,
52
- ...this.normalizeType(options, type),
53
- };
54
- if (type && Type.isMappedType(type.prototype)) {
55
- prop.type = type;
56
- }
57
- if (typeof prop.formula === 'string') {
58
- const formula = prop.formula;
59
- prop.formula = () => formula;
60
- }
61
- if (prop.formula) {
62
- prop.persist ??= false;
63
- }
64
- this._meta.properties[name] = prop;
65
- }
66
- addEnum(name, type, options = {}) {
67
- if (options.items instanceof Function) {
68
- options.items = Utils.extractEnumValues(options.items());
69
- }
70
- // enum arrays are simple numeric/string arrays, the constraint is enforced in the custom type only
71
- if (options.array && !options.type) {
72
- options.type = new EnumArrayType(`${this._meta.className}.${name}`, options.items);
73
- options.enum = false;
74
- }
75
- const prop = { enum: true, ...options };
76
- if (prop.array) {
77
- prop.enum = false;
78
- }
79
- // force string labels on native enums
80
- if (prop.nativeEnumName && Array.isArray(prop.items)) {
81
- prop.items = prop.items.map(val => '' + val);
82
- }
83
- this.addProperty(name, this.internal ? type : type || 'enum', prop);
84
- }
85
- addVersion(name, type, options = {}) {
86
- this.addProperty(name, type, { version: true, ...options });
87
- }
88
- addPrimaryKey(name, type, options = {}) {
89
- this.addProperty(name, type, { primary: true, ...options });
90
- }
91
- addSerializedPrimaryKey(name, type, options = {}) {
92
- this._meta.serializedPrimaryKey = name;
93
- this.addProperty(name, type, { serializedPrimaryKey: true, ...options });
94
- }
95
- addEmbedded(name, options) {
96
- this.renameCompositeOptions(name, options);
97
- Utils.defaultValue(options, 'prefix', true);
98
- if (options.array) {
99
- options.object = true; // force object mode for arrays
100
- }
101
- this._meta.properties[name] = {
102
- name,
103
- kind: ReferenceKind.EMBEDDED,
104
- ...this.normalizeType(options),
105
- ...options,
106
- };
107
- }
108
- addManyToOne(name, type, options) {
109
- const prop = this.createProperty(ReferenceKind.MANY_TO_ONE, options);
110
- prop.owner = true;
111
- if (prop.joinColumns && !prop.fieldNames) {
112
- prop.fieldNames = prop.joinColumns;
113
- }
114
- if (prop.fieldNames && !prop.joinColumns) {
115
- prop.joinColumns = prop.fieldNames;
116
- }
117
- // By default, the foreign key constraint is created on the relation
118
- Utils.defaultValue(prop, 'createForeignKeyConstraint', true);
119
- this.addProperty(name, type, prop);
120
- }
121
- addManyToMany(name, type, options) {
122
- options.fixedOrder = options.fixedOrder || !!options.fixedOrderColumn;
123
- if (!options.owner && !options.mappedBy) {
124
- options.owner = true;
125
- }
126
- if (options.owner) {
127
- Utils.renameKey(options, 'mappedBy', 'inversedBy');
128
- // By default, the foreign key constraint is created on the relation
129
- Utils.defaultValue(options, 'createForeignKeyConstraint', true);
130
- }
131
- const prop = this.createProperty(ReferenceKind.MANY_TO_MANY, options);
132
- this.addProperty(name, type, prop);
133
- }
134
- addOneToMany(name, type, options) {
135
- const prop = this.createProperty(ReferenceKind.ONE_TO_MANY, options);
136
- this.addProperty(name, type, prop);
137
- }
138
- addOneToOne(name, type, options) {
139
- const prop = this.createProperty(ReferenceKind.ONE_TO_ONE, options);
140
- Utils.defaultValue(prop, 'owner', !!prop.inversedBy || !prop.mappedBy);
141
- Utils.defaultValue(prop, 'unique', prop.owner);
142
- if (prop.owner) {
143
- if (options.mappedBy) {
144
- Utils.renameKey(prop, 'mappedBy', 'inversedBy');
145
- }
146
- // By default, the foreign key constraint is created on the relation
147
- Utils.defaultValue(prop, 'createForeignKeyConstraint', true);
148
- }
149
- if (prop.joinColumns && !prop.fieldNames) {
150
- prop.fieldNames = prop.joinColumns;
151
- }
152
- if (prop.fieldNames && !prop.joinColumns) {
153
- prop.joinColumns = prop.fieldNames;
154
- }
155
- this.addProperty(name, type, prop);
156
- }
157
- addIndex(options) {
158
- this._meta.indexes.push(options);
159
- }
160
- addUnique(options) {
161
- this._meta.uniques.push(options);
162
- }
163
- setCustomRepository(repository) {
164
- this._meta.repository = repository;
165
- }
166
- setExtends(base) {
167
- this._meta.extends = base;
168
- }
169
- setClass(cls) {
170
- const oldClass = this._meta.class;
171
- const sameClass = this._meta.class === cls;
172
- this._meta.class = cls;
173
- this._meta.prototype = cls.prototype;
174
- this._meta.className = this._meta.name ?? cls.name;
175
- if (!sameClass || !this._meta.constructorParams) {
176
- this._meta.constructorParams = Utils.getConstructorParams(cls);
177
- }
178
- if (!this.internal) {
179
- // Remove old class from registry if it's being replaced with a different class
180
- if (oldClass && oldClass !== cls && EntitySchema.REGISTRY.get(oldClass) === this) {
181
- EntitySchema.REGISTRY.delete(oldClass);
182
- }
183
- EntitySchema.REGISTRY.set(cls, this);
184
- }
185
- const base = Object.getPrototypeOf(cls);
186
- // Only set extends if the parent is NOT the auto-generated class for this same entity.
187
- // When the user extends the auto-generated class (from defineEntity without a class option)
188
- // and registers their custom class via setClass, we don't want to discover the
189
- // auto-generated class as a separate parent entity.
190
- if (base !== BaseEntity && base.name !== this._meta.className) {
191
- this._meta.extends ??= base.name ? base : undefined;
192
- }
193
- }
194
- get meta() {
195
- return this._meta;
196
- }
197
- get name() {
198
- return this._meta.className;
199
- }
200
- get tableName() {
201
- return this._meta.tableName;
202
- }
203
- get class() {
204
- return this._meta.class;
205
- }
206
- get properties() {
207
- return this._meta.properties;
208
- }
209
- new(...params) {
210
- return new this._meta.class(...params);
211
- }
212
- /**
213
- * @internal
214
- */
215
- init() {
216
- if (this.initialized) {
217
- return this;
218
- }
219
- this.setClass(this._meta.class);
220
- // Abstract TPT entities keep their name because they have their own table
221
- const isTPT = this._meta.inheritance === 'tpt' || this.isPartOfTPTHierarchy();
222
- if (this._meta.abstract && !this._meta.discriminatorColumn && !isTPT) {
223
- delete this._meta.name;
224
- }
225
- const tableName = this._meta.collection ?? this._meta.tableName;
226
- if (tableName?.includes('.') && !this._meta.schema) {
227
- this._meta.schema = tableName.substring(0, tableName.indexOf('.'));
228
- this._meta.tableName = tableName.substring(tableName.indexOf('.') + 1);
229
- }
230
- this.initProperties();
231
- this.initPrimaryKeys();
232
- this._meta.props = Object.values(this._meta.properties);
233
- this._meta.relations = this._meta.props.filter(prop => typeof prop.kind !== 'undefined' && prop.kind !== ReferenceKind.SCALAR && prop.kind !== ReferenceKind.EMBEDDED);
234
- this.initialized = true;
235
- return this;
236
- }
237
- /**
238
- * Check if this entity is part of a TPT hierarchy by walking up the extends chain.
239
- * This handles mid-level abstract entities (e.g., Animal -> Mammal -> Dog where Mammal is abstract).
240
- */
241
- isPartOfTPTHierarchy() {
242
- let parent = this._meta.extends;
243
- while (parent) {
244
- const parentSchema = parent instanceof EntitySchema ? parent : EntitySchema.REGISTRY.get(parent);
245
- if (!parentSchema) {
246
- break;
247
- }
248
- if (parentSchema._meta.inheritance === 'tpt') {
249
- return true;
250
- }
251
- parent = parentSchema._meta.extends;
252
- }
253
- return false;
254
- }
255
- initProperties() {
256
- Utils.entries(this._meta.properties).forEach(([name, options]) => {
257
- if (Type.isMappedType(options.type)) {
258
- options.type ??= options.type.constructor.name;
259
- }
260
- switch (options.kind) {
261
- case ReferenceKind.ONE_TO_ONE:
262
- this.addOneToOne(name, options.type, options);
263
- break;
264
- case ReferenceKind.ONE_TO_MANY:
265
- this.addOneToMany(name, options.type, options);
266
- break;
267
- case ReferenceKind.MANY_TO_ONE:
268
- this.addManyToOne(name, options.type, options);
269
- break;
270
- case ReferenceKind.MANY_TO_MANY:
271
- this.addManyToMany(name, options.type, options);
272
- break;
273
- case ReferenceKind.EMBEDDED:
274
- this.addEmbedded(name, options);
275
- break;
276
- default:
277
- if (options.enum) {
278
- this.addEnum(name, options.type, options);
279
- }
280
- else if (options.primary) {
281
- this.addPrimaryKey(name, options.type, options);
282
- }
283
- else if (options.serializedPrimaryKey) {
284
- this.addSerializedPrimaryKey(name, options.type, options);
285
- }
286
- else if (options.version) {
287
- this.addVersion(name, options.type, options);
288
- }
289
- else {
290
- this.addProperty(name, options.type, options);
291
- }
292
- }
293
- });
294
- }
295
- initPrimaryKeys() {
296
- const pks = Object.values(this._meta.properties).filter(prop => prop.primary);
297
- if (pks.length > 0) {
298
- this._meta.primaryKeys = pks.map(prop => prop.name);
299
- this._meta.compositePK = pks.length > 1;
300
- this._meta.simplePK = !this._meta.compositePK && pks[0].kind === ReferenceKind.SCALAR && !pks[0].customType;
301
- }
302
- if (pks.length === 1 && ['number', 'bigint'].includes(pks[0].type)) {
303
- pks[0].autoincrement ??= true;
304
- }
305
- const serializedPrimaryKey = Object.values(this._meta.properties).find(prop => prop.serializedPrimaryKey);
306
- if (serializedPrimaryKey) {
307
- this._meta.serializedPrimaryKey = serializedPrimaryKey.name;
308
- }
309
- }
310
- normalizeType(options, type) {
311
- if ('entity' in options) {
312
- /* v8 ignore next */
313
- if (typeof options.entity === 'string') {
314
- throw new Error(`Relation target needs to be an entity class or EntitySchema instance, string '${options.entity}' given instead for ${this._meta.className}.${options.name}.`);
315
- }
316
- else if (options.entity) {
317
- const tmp = options.entity();
318
- type = options.type = Array.isArray(tmp)
319
- ? tmp
320
- .map(t => Utils.className(t))
321
- .sort()
322
- .join(' | ')
323
- : Utils.className(tmp);
324
- const target = tmp instanceof EntitySchema ? tmp.meta.class : tmp;
325
- return { type, target };
326
- }
327
- }
328
- if (type instanceof Function) {
329
- type = type.name;
330
- }
331
- if (['String', 'Number', 'Boolean', 'Array'].includes(type)) {
332
- type = type.toLowerCase();
333
- }
334
- return { type };
335
- }
336
- createProperty(kind, options) {
337
- return {
338
- kind,
339
- cascade: [Cascade.PERSIST],
340
- ...options,
341
- };
342
- }
343
- rename(data, from, to) {
344
- if (from in data && !(to in data)) {
345
- // @ts-ignore
346
- data[to] = [data[from]];
347
- // @ts-ignore
348
- delete data[from];
349
- }
350
- }
351
- renameCompositeOptions(name, options = {}) {
352
- if (name !== options.name && !options.fieldNames) {
353
- Utils.renameKey(options, 'name', 'fieldName');
354
- }
355
- else if (options.name && (options.fieldNames?.length ?? 0) > 1) {
356
- delete options.name;
357
- }
358
- this.rename(options, 'fieldName', 'fieldNames');
359
- this.rename(options, 'joinColumn', 'joinColumns');
360
- this.rename(options, 'inverseJoinColumn', 'inverseJoinColumns');
361
- this.rename(options, 'referenceColumnName', 'referencedColumnNames');
362
- this.rename(options, 'columnType', 'columnTypes');
363
- }
364
- /**
365
- * Adds a lifecycle hook handler to the entity schema.
366
- * This method allows registering hooks after the entity is defined,
367
- * which can be useful for avoiding circular type references.
368
- *
369
- * @example
370
- * ```ts
371
- * export const Article = defineEntity({
372
- * name: 'Article',
373
- * properties: { ... },
374
- * });
375
- *
376
- * Article.addHook('beforeCreate', async args => {
377
- * args.entity.slug = args.entity.title.toLowerCase();
378
- * });
379
- * ```
380
- */
381
- addHook(event, handler) {
382
- this._meta.hooks[event] ??= [];
383
- this._meta.hooks[event].push(handler);
384
- return this;
385
- }
9
+ /**
10
+ * When schema links the entity class via `class` option, this registry allows the lookup from opposite side,
11
+ * so we can use the class in `entities` option just like the EntitySchema instance.
12
+ */
13
+ static REGISTRY = new Map();
14
+ _meta;
15
+ internal = false;
16
+ initialized = false;
17
+ constructor(meta) {
18
+ meta.name = meta.class ? meta.class.name : meta.name;
19
+ if (meta.name) {
20
+ meta.abstract ??= false;
21
+ }
22
+ this._meta = new EntityMetadata({
23
+ className: meta.name,
24
+ ...meta,
25
+ });
26
+ this._meta.root ??= this._meta;
27
+ if (meta.class && !meta.internal) {
28
+ EntitySchema.REGISTRY.set(meta.class, this);
29
+ }
30
+ }
31
+ /**
32
+ * Checks if the given value is an EntitySchema instance, using duck-typing
33
+ * as a fallback when `instanceof` fails due to CJS/ESM dual-package hazard
34
+ * (e.g. when using `tsx` or `@swc-node/register` with `"type": "commonjs"` projects).
35
+ */
36
+ static is(item) {
37
+ if (item instanceof EntitySchema) {
38
+ return true;
39
+ }
40
+ return item != null && typeof item === 'object' && item.constructor?.name === 'EntitySchema' && 'meta' in item;
41
+ }
42
+ /** Creates an EntitySchema from existing EntityMetadata (used internally). */
43
+ static fromMetadata(meta) {
44
+ const schema = new EntitySchema({ ...meta, internal: true });
45
+ schema.internal = true;
46
+ return schema;
47
+ }
48
+ /** Adds a scalar property to the entity schema. */
49
+ addProperty(name, type, options = {}) {
50
+ this.renameCompositeOptions(name, options);
51
+ const prop = {
52
+ name,
53
+ kind: ReferenceKind.SCALAR,
54
+ ...options,
55
+ ...this.normalizeType(options, type),
56
+ };
57
+ if (type && Type.isMappedType(type.prototype)) {
58
+ prop.type = type;
59
+ }
60
+ if (typeof prop.formula === 'string') {
61
+ const formula = prop.formula;
62
+ prop.formula = () => formula;
63
+ }
64
+ if (prop.formula) {
65
+ prop.persist ??= false;
66
+ }
67
+ this._meta.properties[name] = prop;
68
+ }
69
+ /** Adds an enum property to the entity schema. */
70
+ addEnum(name, type, options = {}) {
71
+ if (options.items instanceof Function) {
72
+ options.items = Utils.extractEnumValues(options.items());
73
+ }
74
+ // enum arrays are simple numeric/string arrays, the constraint is enforced in the custom type only
75
+ if (options.array && !options.type) {
76
+ options.type = new EnumArrayType(`${this._meta.className}.${name}`, options.items);
77
+ options.enum = false;
78
+ }
79
+ const prop = { enum: true, ...options };
80
+ if (prop.array) {
81
+ prop.enum = false;
82
+ }
83
+ // force string labels on native enums
84
+ if (prop.nativeEnumName && Array.isArray(prop.items)) {
85
+ prop.items = prop.items.map(val => '' + val);
86
+ }
87
+ this.addProperty(name, this.internal ? type : type || 'enum', prop);
88
+ }
89
+ /** Adds a version property for optimistic locking. */
90
+ addVersion(name, type, options = {}) {
91
+ this.addProperty(name, type, { version: true, ...options });
92
+ }
93
+ /** Adds a primary key property to the entity schema. */
94
+ addPrimaryKey(name, type, options = {}) {
95
+ this.addProperty(name, type, { primary: true, ...options });
96
+ }
97
+ /** Adds a serialized primary key property (e.g. for MongoDB ObjectId). */
98
+ addSerializedPrimaryKey(name, type, options = {}) {
99
+ this._meta.serializedPrimaryKey = name;
100
+ this.addProperty(name, type, { serializedPrimaryKey: true, ...options });
101
+ }
102
+ /** Adds an embedded property to the entity schema. */
103
+ addEmbedded(name, options) {
104
+ this.renameCompositeOptions(name, options);
105
+ Utils.defaultValue(options, 'prefix', true);
106
+ if (options.array) {
107
+ options.object = true; // force object mode for arrays
108
+ }
109
+ this._meta.properties[name] = {
110
+ name,
111
+ kind: ReferenceKind.EMBEDDED,
112
+ ...this.normalizeType(options),
113
+ ...options,
114
+ };
115
+ }
116
+ /** Adds a many-to-one relation to the entity schema. */
117
+ addManyToOne(name, type, options) {
118
+ const prop = this.createProperty(ReferenceKind.MANY_TO_ONE, options);
119
+ prop.owner = true;
120
+ if (prop.joinColumns && !prop.fieldNames) {
121
+ prop.fieldNames = prop.joinColumns;
122
+ }
123
+ if (prop.fieldNames && !prop.joinColumns) {
124
+ prop.joinColumns = prop.fieldNames;
125
+ }
126
+ // By default, the foreign key constraint is created on the relation
127
+ Utils.defaultValue(prop, 'createForeignKeyConstraint', true);
128
+ this.addProperty(name, type, prop);
129
+ }
130
+ /** Adds a many-to-many relation to the entity schema. */
131
+ addManyToMany(name, type, options) {
132
+ options.fixedOrder = options.fixedOrder || !!options.fixedOrderColumn;
133
+ if (!options.owner && !options.mappedBy) {
134
+ options.owner = true;
135
+ }
136
+ if (options.owner) {
137
+ Utils.renameKey(options, 'mappedBy', 'inversedBy');
138
+ // By default, the foreign key constraint is created on the relation
139
+ Utils.defaultValue(options, 'createForeignKeyConstraint', true);
140
+ }
141
+ const prop = this.createProperty(ReferenceKind.MANY_TO_MANY, options);
142
+ this.addProperty(name, type, prop);
143
+ }
144
+ /** Adds a one-to-many relation to the entity schema. */
145
+ addOneToMany(name, type, options) {
146
+ const prop = this.createProperty(ReferenceKind.ONE_TO_MANY, options);
147
+ this.addProperty(name, type, prop);
148
+ }
149
+ /** Adds a one-to-one relation to the entity schema. */
150
+ addOneToOne(name, type, options) {
151
+ const prop = this.createProperty(ReferenceKind.ONE_TO_ONE, options);
152
+ Utils.defaultValue(prop, 'owner', !!prop.inversedBy || !prop.mappedBy);
153
+ Utils.defaultValue(prop, 'unique', prop.owner);
154
+ if (prop.owner) {
155
+ if (options.mappedBy) {
156
+ Utils.renameKey(prop, 'mappedBy', 'inversedBy');
157
+ }
158
+ // By default, the foreign key constraint is created on the relation
159
+ Utils.defaultValue(prop, 'createForeignKeyConstraint', true);
160
+ }
161
+ if (prop.joinColumns && !prop.fieldNames) {
162
+ prop.fieldNames = prop.joinColumns;
163
+ }
164
+ if (prop.fieldNames && !prop.joinColumns) {
165
+ prop.joinColumns = prop.fieldNames;
166
+ }
167
+ this.addProperty(name, type, prop);
168
+ }
169
+ /** Adds an index definition to the entity schema. */
170
+ addIndex(options) {
171
+ this._meta.indexes.push(options);
172
+ }
173
+ /** Adds a unique constraint definition to the entity schema. */
174
+ addUnique(options) {
175
+ this._meta.uniques.push(options);
176
+ }
177
+ /** Sets a custom repository class for this entity. */
178
+ setCustomRepository(repository) {
179
+ this._meta.repository = repository;
180
+ }
181
+ /** Sets the base entity that this schema extends. */
182
+ setExtends(base) {
183
+ this._meta.extends = base;
184
+ }
185
+ /** Sets or replaces the entity class associated with this schema. */
186
+ setClass(cls) {
187
+ const oldClass = this._meta.class;
188
+ const sameClass = this._meta.class === cls;
189
+ this._meta.class = cls;
190
+ this._meta.prototype = cls.prototype;
191
+ this._meta.className = this._meta.name ?? cls.name;
192
+ if (!sameClass || !this._meta.constructorParams) {
193
+ this._meta.constructorParams = Utils.getConstructorParams(cls);
194
+ }
195
+ if (!this.internal) {
196
+ // Remove old class from registry if it's being replaced with a different class
197
+ if (oldClass && oldClass !== cls && EntitySchema.REGISTRY.get(oldClass) === this) {
198
+ EntitySchema.REGISTRY.delete(oldClass);
199
+ }
200
+ EntitySchema.REGISTRY.set(cls, this);
201
+ }
202
+ const base = Object.getPrototypeOf(cls);
203
+ // Only set extends if the parent is NOT the auto-generated class for this same entity.
204
+ // When the user extends the auto-generated class (from defineEntity without a class option)
205
+ // and registers their custom class via setClass, we don't want to discover the
206
+ // auto-generated class as a separate parent entity.
207
+ if (base !== BaseEntity && base.name !== this._meta.className) {
208
+ this._meta.extends ??= base.name ? base : undefined;
209
+ }
210
+ }
211
+ /** Returns the underlying EntityMetadata. */
212
+ get meta() {
213
+ return this._meta;
214
+ }
215
+ /** Returns the entity class name. */
216
+ get name() {
217
+ return this._meta.className;
218
+ }
219
+ /** Returns the database table name. */
220
+ get tableName() {
221
+ return this._meta.tableName;
222
+ }
223
+ get class() {
224
+ return this._meta.class;
225
+ }
226
+ get properties() {
227
+ return this._meta.properties;
228
+ }
229
+ new(...params) {
230
+ return new this._meta.class(...params);
231
+ }
232
+ /**
233
+ * @internal
234
+ */
235
+ init() {
236
+ if (this.initialized) {
237
+ return this;
238
+ }
239
+ this.setClass(this._meta.class);
240
+ // Abstract TPT entities keep their name because they have their own table
241
+ const isTPT = this._meta.inheritance === 'tpt' || this.isPartOfTPTHierarchy();
242
+ if (this._meta.abstract && !this._meta.discriminatorColumn && !isTPT) {
243
+ delete this._meta.name;
244
+ }
245
+ const tableName = this._meta.collection ?? this._meta.tableName;
246
+ if (tableName?.includes('.') && !this._meta.schema) {
247
+ this._meta.schema = tableName.substring(0, tableName.indexOf('.'));
248
+ this._meta.tableName = tableName.substring(tableName.indexOf('.') + 1);
249
+ }
250
+ this.initProperties();
251
+ this.initPrimaryKeys();
252
+ this._meta.props = Object.values(this._meta.properties);
253
+ this._meta.relations = this._meta.props.filter(
254
+ prop =>
255
+ typeof prop.kind !== 'undefined' && prop.kind !== ReferenceKind.SCALAR && prop.kind !== ReferenceKind.EMBEDDED,
256
+ );
257
+ this.initialized = true;
258
+ return this;
259
+ }
260
+ /**
261
+ * Check if this entity is part of a TPT hierarchy by walking up the extends chain.
262
+ * This handles mid-level abstract entities (e.g., Animal -> Mammal -> Dog where Mammal is abstract).
263
+ */
264
+ isPartOfTPTHierarchy() {
265
+ let parent = this._meta.extends;
266
+ while (parent) {
267
+ const parentSchema = EntitySchema.is(parent) ? parent : EntitySchema.REGISTRY.get(parent);
268
+ if (!parentSchema) {
269
+ break;
270
+ }
271
+ if (parentSchema._meta.inheritance === 'tpt') {
272
+ return true;
273
+ }
274
+ parent = parentSchema._meta.extends;
275
+ }
276
+ return false;
277
+ }
278
+ initProperties() {
279
+ Utils.entries(this._meta.properties).forEach(([name, options]) => {
280
+ if (Type.isMappedType(options.type)) {
281
+ options.type ??= options.type.constructor.name;
282
+ }
283
+ switch (options.kind) {
284
+ case ReferenceKind.ONE_TO_ONE:
285
+ this.addOneToOne(name, options.type, options);
286
+ break;
287
+ case ReferenceKind.ONE_TO_MANY:
288
+ this.addOneToMany(name, options.type, options);
289
+ break;
290
+ case ReferenceKind.MANY_TO_ONE:
291
+ this.addManyToOne(name, options.type, options);
292
+ break;
293
+ case ReferenceKind.MANY_TO_MANY:
294
+ this.addManyToMany(name, options.type, options);
295
+ break;
296
+ case ReferenceKind.EMBEDDED:
297
+ this.addEmbedded(name, options);
298
+ break;
299
+ default:
300
+ if (options.enum) {
301
+ this.addEnum(name, options.type, options);
302
+ } else if (options.primary) {
303
+ this.addPrimaryKey(name, options.type, options);
304
+ } else if (options.serializedPrimaryKey) {
305
+ this.addSerializedPrimaryKey(name, options.type, options);
306
+ } else if (options.version) {
307
+ this.addVersion(name, options.type, options);
308
+ } else {
309
+ this.addProperty(name, options.type, options);
310
+ }
311
+ }
312
+ });
313
+ }
314
+ initPrimaryKeys() {
315
+ const pks = Object.values(this._meta.properties).filter(prop => prop.primary);
316
+ if (pks.length > 0) {
317
+ this._meta.primaryKeys = pks.map(prop => prop.name);
318
+ this._meta.compositePK = pks.length > 1;
319
+ this._meta.simplePK = !this._meta.compositePK && pks[0].kind === ReferenceKind.SCALAR && !pks[0].customType;
320
+ }
321
+ if (pks.length === 1 && ['number', 'bigint'].includes(pks[0].type)) {
322
+ pks[0].autoincrement ??= true;
323
+ }
324
+ const serializedPrimaryKey = Object.values(this._meta.properties).find(prop => prop.serializedPrimaryKey);
325
+ if (serializedPrimaryKey) {
326
+ this._meta.serializedPrimaryKey = serializedPrimaryKey.name;
327
+ }
328
+ }
329
+ normalizeType(options, type) {
330
+ if ('entity' in options) {
331
+ /* v8 ignore next */
332
+ if (typeof options.entity === 'string') {
333
+ throw new Error(
334
+ `Relation target needs to be an entity class or EntitySchema instance, string '${options.entity}' given instead for ${this._meta.className}.${options.name}.`,
335
+ );
336
+ } else if (options.entity) {
337
+ const tmp = options.entity();
338
+ type = options.type = Array.isArray(tmp)
339
+ ? tmp
340
+ .map(t => Utils.className(t))
341
+ .sort()
342
+ .join(' | ')
343
+ : Utils.className(tmp);
344
+ const target = EntitySchema.is(tmp) ? tmp.meta.class : tmp;
345
+ return { type, target };
346
+ }
347
+ }
348
+ if (type instanceof Function) {
349
+ type = type.name;
350
+ }
351
+ if (['String', 'Number', 'Boolean', 'Array'].includes(type)) {
352
+ type = type.toLowerCase();
353
+ }
354
+ return { type };
355
+ }
356
+ createProperty(kind, options) {
357
+ return {
358
+ kind,
359
+ cascade: [Cascade.PERSIST],
360
+ ...options,
361
+ };
362
+ }
363
+ rename(data, from, to) {
364
+ if (from in data && !(to in data)) {
365
+ // @ts-ignore
366
+ data[to] = [data[from]];
367
+ // @ts-ignore
368
+ delete data[from];
369
+ }
370
+ }
371
+ renameCompositeOptions(name, options = {}) {
372
+ if (name !== options.name && !options.fieldNames) {
373
+ Utils.renameKey(options, 'name', 'fieldName');
374
+ } else if (options.name && (options.fieldNames?.length ?? 0) > 1) {
375
+ delete options.name;
376
+ }
377
+ this.rename(options, 'fieldName', 'fieldNames');
378
+ this.rename(options, 'joinColumn', 'joinColumns');
379
+ this.rename(options, 'inverseJoinColumn', 'inverseJoinColumns');
380
+ this.rename(options, 'referenceColumnName', 'referencedColumnNames');
381
+ this.rename(options, 'columnType', 'columnTypes');
382
+ }
383
+ /**
384
+ * Adds a lifecycle hook handler to the entity schema.
385
+ * This method allows registering hooks after the entity is defined,
386
+ * which can be useful for avoiding circular type references.
387
+ *
388
+ * @example
389
+ * ```ts
390
+ * export const Article = defineEntity({
391
+ * name: 'Article',
392
+ * properties: { ... },
393
+ * });
394
+ *
395
+ * Article.addHook('beforeCreate', async args => {
396
+ * args.entity.slug = args.entity.title.toLowerCase();
397
+ * });
398
+ * ```
399
+ */
400
+ addHook(event, handler) {
401
+ this._meta.hooks[event] ??= [];
402
+ this._meta.hooks[event].push(handler);
403
+ return this;
404
+ }
386
405
  }