@mikro-orm/core 7.0.8 → 7.0.9-dev.1

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 +1899 -1926
  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 +181 -213
  23. package/entity/Collection.js +724 -730
  24. package/entity/EntityAssigner.d.ts +77 -88
  25. package/entity/EntityAssigner.js +230 -231
  26. package/entity/EntityFactory.d.ts +55 -67
  27. package/entity/EntityFactory.js +414 -455
  28. package/entity/EntityHelper.d.ts +23 -35
  29. package/entity/EntityHelper.js +279 -291
  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 +761 -792
  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 +83 -127
  39. package/entity/Reference.js +277 -281
  40. package/entity/WrappedEntity.d.ts +72 -115
  41. package/entity/WrappedEntity.js +166 -168
  42. package/entity/defineEntity.d.ts +654 -1359
  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 +418 -483
  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 +130 -214
  74. package/metadata/EntitySchema.js +412 -411
  75. package/metadata/MetadataDiscovery.d.ts +114 -114
  76. package/metadata/MetadataDiscovery.js +1868 -1944
  77. package/metadata/MetadataProvider.d.ts +26 -29
  78. package/metadata/MetadataProvider.js +97 -95
  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 +303 -312
  100. package/platforms/Platform.js +644 -667
  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 +743 -1254
  160. package/typings.js +235 -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 +179 -187
  165. package/unit-of-work/ChangeSetPersister.d.ts +44 -63
  166. package/unit-of-work/ChangeSetPersister.js +423 -446
  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 +1222 -1236
  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 +82 -99
  186. package/utils/EntityComparator.js +737 -829
  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 +815 -815
  201. package/utils/clone.js +114 -105
  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
@@ -1,4 +1,4 @@
1
- import { EntityMetadata } from '../typings.js';
1
+ import { EntityMetadata, } from '../typings.js';
2
2
  import { compareArrays, Utils } from '../utils/Utils.js';
3
3
  import { QueryHelper } from '../utils/QueryHelper.js';
4
4
  import { MetadataValidator } from './MetadataValidator.js';
@@ -13,1958 +13,1882 @@ import { raw, Raw } from '../utils/RawQueryFragment.js';
13
13
  import { BaseEntity } from '../entity/BaseEntity.js';
14
14
  /** Discovers, validates, and processes entity metadata from configured sources. */
15
15
  export class MetadataDiscovery {
16
- #namingStrategy;
17
- #metadataProvider;
18
- #logger;
19
- #schemaHelper;
20
- #validator = new MetadataValidator();
21
- #discovered = [];
22
- #metadata;
23
- #platform;
24
- #config;
25
- constructor(metadata, platform, config) {
26
- this.#metadata = metadata;
27
- this.#platform = platform;
28
- this.#config = config;
29
- this.#namingStrategy = this.#config.getNamingStrategy();
30
- this.#metadataProvider = this.#config.getMetadataProvider();
31
- this.#logger = this.#config.getLogger();
32
- this.#schemaHelper = this.#platform.getSchemaHelper();
33
- }
34
- /** Discovers all entities asynchronously and returns the populated MetadataStorage. */
35
- async discover(preferTs = true) {
36
- this.#discovered.length = 0;
37
- const startTime = Date.now();
38
- const suffix =
39
- this.#metadataProvider.constructor === MetadataProvider
40
- ? ''
41
- : `, using ${colors.cyan(this.#metadataProvider.constructor.name)}`;
42
- this.#logger.log('discovery', `ORM entity discovery started${suffix}`);
43
- await this.findEntities(preferTs);
44
- for (const meta of this.#discovered) {
45
- /* v8 ignore next */
46
- await this.#config.get('discovery').onMetadata?.(meta, this.#platform);
47
- }
48
- this.processDiscoveredEntities(this.#discovered);
49
- const diff = Date.now() - startTime;
50
- this.#logger.log(
51
- 'discovery',
52
- `- entity discovery finished, found ${colors.green('' + this.#discovered.length)} entities, took ${colors.green(`${diff} ms`)}`,
53
- );
54
- const storage = this.mapDiscoveredEntities();
55
- /* v8 ignore next */
56
- await this.#config.get('discovery').afterDiscovered?.(storage, this.#platform);
57
- return storage;
58
- }
59
- /** Discovers all entities synchronously and returns the populated MetadataStorage. */
60
- discoverSync() {
61
- this.#discovered.length = 0;
62
- const startTime = Date.now();
63
- const suffix =
64
- this.#metadataProvider.constructor === MetadataProvider
65
- ? ''
66
- : `, using ${colors.cyan(this.#metadataProvider.constructor.name)}`;
67
- this.#logger.log('discovery', `ORM entity discovery started${suffix} in sync mode`);
68
- const refs = this.#config.get('entities');
69
- this.discoverReferences(refs);
70
- for (const meta of this.#discovered) {
71
- /* v8 ignore next */
72
- void this.#config.get('discovery').onMetadata?.(meta, this.#platform);
73
- }
74
- this.processDiscoveredEntities(this.#discovered);
75
- const diff = Date.now() - startTime;
76
- this.#logger.log(
77
- 'discovery',
78
- `- entity discovery finished, found ${colors.green('' + this.#discovered.length)} entities, took ${colors.green(`${diff} ms`)}`,
79
- );
80
- const storage = this.mapDiscoveredEntities();
81
- /* v8 ignore next */
82
- void this.#config.get('discovery').afterDiscovered?.(storage, this.#platform);
83
- return storage;
84
- }
85
- mapDiscoveredEntities() {
86
- const discovered = new MetadataStorage();
87
- this.#discovered
88
- .filter(meta => meta.root.name)
89
- .sort((a, b) => b.root.name.localeCompare(a.root.name))
90
- .forEach(meta => {
91
- this.#platform.validateMetadata(meta);
92
- discovered.set(meta.class, meta);
93
- });
94
- for (const meta of discovered) {
95
- meta.root = discovered.get(meta.root.class);
96
- if (meta.inheritanceType === 'tpt') {
97
- this.computeTPTOwnProps(meta);
98
- }
99
- }
100
- return discovered;
101
- }
102
- initAccessors(meta) {
103
- for (const prop of Object.values(meta.properties)) {
104
- if (!prop.accessor || meta.properties[prop.accessor]) {
105
- continue;
106
- }
107
- const desc = Object.getOwnPropertyDescriptor(meta.prototype, prop.name);
108
- if (desc?.get || desc?.set) {
109
- this.initRelation(prop);
110
- this.initFieldName(prop);
111
- const accessor = prop.name;
112
- prop.name = typeof prop.accessor === 'string' ? prop.accessor : prop.name;
113
- if (prop.accessor === true) {
114
- prop.getter = prop.setter = true;
115
- } else {
116
- prop.getter = prop.setter = false;
117
- }
118
- prop.accessor = accessor;
119
- prop.serializedName ??= accessor;
120
- Utils.renameKey(meta.properties, accessor, prop.name);
121
- } else {
122
- const name = prop.name;
123
- if (prop.kind === ReferenceKind.SCALAR || prop.kind === ReferenceKind.EMBEDDED) {
124
- prop.name = prop.accessor;
125
- }
126
- this.initRelation(prop);
127
- this.initFieldName(prop);
128
- prop.serializedName ??= prop.accessor;
129
- prop.name = name;
130
- }
131
- }
132
- }
133
- /** Processes discovered entities: initializes relations, embeddables, indexes, and inheritance. */
134
- processDiscoveredEntities(discovered) {
135
- for (const meta of discovered) {
136
- let i = 1;
137
- Object.values(meta.properties).forEach(prop => meta.propertyOrder.set(prop.name, i++));
138
- Object.values(meta.properties).forEach(prop => this.initPolyEmbeddables(prop, discovered));
139
- this.initAccessors(meta);
140
- }
141
- // ignore base entities (not annotated with @Entity)
142
- const filtered = discovered.filter(meta => meta.root.name);
143
- // sort so we discover entities first to get around issues with nested embeddables
144
- filtered.sort((a, b) => (!a.embeddable === !b.embeddable ? 0 : a.embeddable ? 1 : -1));
145
- filtered.forEach(meta => this.initSingleTableInheritance(meta, filtered));
146
- filtered.forEach(meta => this.initTPTRelationships(meta, filtered));
147
- filtered.forEach(meta => this.defineBaseEntityProperties(meta));
148
- filtered.forEach(meta => {
149
- const newMeta = EntitySchema.fromMetadata(meta).init().meta;
150
- return this.#metadata.set(newMeta.class, newMeta);
151
- });
152
- filtered.forEach(meta => this.initAutoincrement(meta));
153
- const forEachProp = cb => {
154
- filtered.forEach(meta => Object.values(meta.properties).forEach(prop => cb(meta, prop)));
155
- };
156
- forEachProp((m, p) => this.initFactoryField(m, p));
157
- forEachProp((m, p) => this.initPolymorphicRelation(m, p, filtered));
158
- forEachProp((_m, p) => this.initRelation(p));
159
- forEachProp((m, p) => this.initEmbeddables(m, p));
160
- forEachProp((_m, p) => this.initFieldName(p));
161
- filtered.forEach(meta => this.finalizeTPTInheritance(meta, filtered));
162
- filtered.forEach(meta => this.computeTPTOwnProps(meta));
163
- forEachProp((m, p) => this.initVersionProperty(m, p));
164
- forEachProp((m, p) => this.initCustomType(m, p));
165
- forEachProp((m, p) => this.initGeneratedColumn(m, p));
166
- filtered.forEach(meta => this.initAutoincrement(meta)); // once again after we init custom types
167
- filtered.forEach(meta => this.initCheckConstraints(meta));
168
- forEachProp((_m, p) => {
169
- this.initDefaultValue(p);
170
- this.inferTypeFromDefault(p);
171
- this.initRelation(p);
172
- this.initColumnType(p);
173
- });
174
- forEachProp((m, p) => this.initIndexes(m, p));
175
- filtered.forEach(meta => this.autoWireBidirectionalProperties(meta));
176
- for (const meta of filtered) {
177
- discovered.push(...this.processEntity(meta));
178
- }
179
- discovered.forEach(meta => meta.sync(true));
180
- this.#metadataProvider.combineCache();
181
- return discovered.map(meta => {
182
- meta = this.#metadata.get(meta.class);
183
- meta.sync(true);
184
- this.findReferencingProperties(meta, filtered);
185
- if (meta.inheritanceType === 'tpt') {
186
- this.computeTPTOwnProps(meta);
187
- }
188
- return meta;
189
- });
190
- }
191
- async findEntities(preferTs) {
192
- const { entities, entitiesTs, baseDir } = this.#config.getAll();
193
- const targets = preferTs && entitiesTs.length > 0 ? entitiesTs : entities;
194
- const processed = [];
195
- const paths = [];
196
- for (const entity of targets) {
197
- if (typeof entity === 'string') {
198
- paths.push(entity);
199
- } else {
200
- processed.push(entity);
201
- }
202
- }
203
- if (paths.length > 0) {
204
- const { discoverEntities } = await import('@mikro-orm/core/file-discovery');
205
- processed.push(...(await discoverEntities(paths, { baseDir })));
206
- }
207
- return this.discoverReferences(processed);
208
- }
209
- discoverMissingTargets() {
210
- const unwrap = type =>
211
- type
212
- .replace(/Array<(.*)>/, '$1') // unwrap array
213
- .replace(/\[]$/, '') // remove array suffix
214
- .replace(/\((.*)\)/, '$1'); // unwrap union types
215
- const missing = [];
216
- this.#discovered.forEach(meta =>
217
- Object.values(meta.properties).forEach(prop => {
218
- if (prop.kind === ReferenceKind.MANY_TO_MANY && prop.pivotEntity) {
219
- const pivotEntity = prop.pivotEntity;
220
- const target = typeof pivotEntity === 'function' && !pivotEntity.prototype ? pivotEntity() : pivotEntity;
221
- if (!this.#discovered.find(m => m.className === Utils.className(target))) {
222
- missing.push(target);
223
- }
224
- }
225
- if (prop.kind !== ReferenceKind.SCALAR) {
226
- const target = typeof prop.entity === 'function' && !prop.entity.prototype ? prop.entity() : prop.type;
227
- if (
228
- !unwrap(prop.type)
229
- .split(/ ?\| ?/)
230
- .every(type => this.#discovered.find(m => m.className === type))
231
- ) {
232
- missing.push(...Utils.asArray(target));
233
- }
234
- }
235
- }),
236
- );
237
- if (missing.length > 0) {
238
- this.tryDiscoverTargets(missing);
239
- }
240
- }
241
- tryDiscoverTargets(targets) {
242
- for (const target of targets) {
243
- const schema = EntitySchema.is(target) ? target : undefined;
244
- const isDiscoverable = typeof target === 'function' || schema;
245
- if (isDiscoverable && target.name) {
246
- // Get the actual class for EntitySchema, or use target directly for classes
247
- const targetClass = schema ? schema.meta.class : target;
248
- if (!this.#metadata.has(targetClass)) {
249
- this.discoverReferences([target], false);
250
- this.discoverMissingTargets();
251
- }
252
- }
253
- }
254
- }
255
- discoverReferences(refs, validate = true) {
256
- const found = [];
257
- for (const entity of refs) {
258
- if (typeof entity === 'string') {
259
- throw new Error('Folder based discovery requires the async `MikroORM.init()` method.');
260
- }
261
- const schema = this.getSchema(entity);
262
- const meta = schema.init().meta;
263
- this.#metadata.set(meta.class, meta);
264
- found.push(schema);
265
- }
266
- // discover parents (base entities) automatically
267
- for (const meta of this.#metadata) {
268
- let parent = meta.extends;
269
- if (EntitySchema.is(parent) && !this.#metadata.has(parent.init().meta.class)) {
270
- this.discoverReferences([parent], false);
271
- }
272
- if (typeof parent === 'function' && parent.name && !this.#metadata.has(parent)) {
273
- this.discoverReferences([parent], false);
274
- }
275
- /* v8 ignore next */
276
- if (!meta.class) {
277
- continue;
278
- }
279
- parent = Object.getPrototypeOf(meta.class);
280
- // Skip if parent is the auto-generated base class for the same entity (from setClass usage)
281
- if (
282
- parent.name !== '' &&
283
- parent.name !== meta.className &&
284
- !this.#metadata.has(parent) &&
285
- parent !== BaseEntity
286
- ) {
287
- this.discoverReferences([parent], false);
288
- }
289
- }
290
- for (const schema of found) {
291
- this.discoverEntity(schema);
292
- }
293
- this.discoverMissingTargets();
294
- if (validate) {
295
- this.#validator.validateDiscovered(this.#discovered, this.#config.get('discovery'));
296
- }
297
- return this.#discovered.filter(meta => found.find(m => m.name === meta.className));
298
- }
299
- reset(entityName) {
300
- const exists = this.#discovered.findIndex(
301
- m => m.class === entityName || m.className === Utils.className(entityName),
302
- );
303
- if (exists !== -1) {
304
- this.#metadata.reset(this.#discovered[exists].class);
305
- this.#discovered.splice(exists, 1);
306
- }
307
- }
308
- getSchema(entity) {
309
- if (EntitySchema.REGISTRY.has(entity)) {
310
- entity = EntitySchema.REGISTRY.get(entity);
311
- }
312
- if (EntitySchema.is(entity)) {
313
- const meta = Utils.copy(entity.meta, false);
314
- return EntitySchema.fromMetadata(meta);
315
- }
316
- // After the EntitySchema check, entity must be an EntityClass
317
- const cls = entity;
318
- const path = cls[MetadataStorage.PATH_SYMBOL];
319
- if (path) {
320
- const meta = Utils.copy(MetadataStorage.getMetadata(cls.name, path), false);
321
- meta.path = path;
322
- this.#metadata.set(cls, meta);
323
- }
324
- const exists = this.#metadata.has(cls);
325
- const meta = this.#metadata.get(cls, true);
326
- meta.abstract ??= !(exists && meta.name);
327
- const schema = EntitySchema.fromMetadata(meta);
328
- schema.setClass(cls);
329
- return schema;
330
- }
331
- getRootEntity(meta) {
332
- const base = meta.extends && this.#metadata.find(meta.extends);
333
- if (!base || base === meta) {
334
- // make sure we do not fall into infinite loop
335
- return meta;
336
- }
337
- const root = this.getRootEntity(base);
338
- // For STI or TPT, use the root entity.
339
- // Check both `inheritanceType` (set during discovery) and raw `inheritance` option (set before discovery).
340
- if (root.discriminatorColumn || root.inheritanceType || root.inheritance === 'tpt') {
341
- return root;
342
- }
343
- return meta;
344
- }
345
- discoverEntity(schema) {
346
- const meta = schema.meta;
347
- const path = meta.path;
348
- this.#logger.log(
349
- 'discovery',
350
- `- processing entity ${colors.cyan(meta.className)}${colors.grey(path ? ` (${path})` : '')}`,
351
- );
352
- const root = this.getRootEntity(meta);
353
- schema.meta.path = meta.path;
354
- const cache = this.#metadataProvider.getCachedMetadata(meta, root);
355
- if (cache) {
356
- this.#logger.log('discovery', `- using cached metadata for entity ${colors.cyan(meta.className)}`);
357
- this.#discovered.push(meta);
358
- return;
359
- }
360
- // infer default value from property initializer early, as the metadata provider might use some defaults, e.g. string for reflect-metadata
361
- for (const prop of meta.props) {
362
- this.inferDefaultValue(meta, prop);
363
- }
364
- // if the definition is using EntitySchema we still want it to go through the metadata provider to validate no types are missing
365
- this.#metadataProvider.loadEntityMetadata(meta);
366
- if (!meta.tableName && meta.name) {
367
- const entityName = root.discriminatorColumn ? root.name : meta.name;
368
- meta.tableName = this.#namingStrategy.classToTableName(entityName);
369
- }
370
- this.#metadataProvider.saveToCache(meta);
371
- meta.root = root;
372
- this.#discovered.push(meta);
373
- }
374
- initNullability(prop) {
375
- if (prop.kind === ReferenceKind.ONE_TO_ONE) {
376
- return Utils.defaultValue(prop, 'nullable', prop.optional || !prop.owner);
377
- }
378
- return Utils.defaultValue(prop, 'nullable', prop.optional);
379
- }
380
- applyNamingStrategy(meta, prop) {
381
- if (!prop.fieldNames) {
382
- this.initFieldName(prop);
383
- }
384
- if (prop.kind === ReferenceKind.MANY_TO_MANY) {
385
- this.initManyToManyFields(meta, prop);
386
- }
387
- if ([ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(prop.kind)) {
388
- this.initManyToOneFields(prop);
389
- }
390
- if (prop.kind === ReferenceKind.ONE_TO_MANY) {
391
- this.initOneToManyFields(prop);
392
- }
393
- }
394
- initOwnColumns(meta) {
395
- meta.sync();
396
- for (const prop of meta.props) {
397
- if (
398
- !prop.joinColumns ||
399
- !prop.columnTypes ||
400
- prop.ownColumns ||
401
- ![ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(prop.kind)
402
- ) {
403
- continue;
404
- }
405
- // For polymorphic relations, ownColumns should include all fieldNames
406
- // (discriminator + ID columns) since they are all owned by this relation
407
- if (prop.polymorphic) {
408
- prop.ownColumns = prop.fieldNames;
409
- continue;
410
- }
411
- if (prop.joinColumns.length > 1) {
412
- prop.ownColumns = prop.joinColumns.filter(col => {
413
- return !meta.props.find(p => p.name !== prop.name && (!p.fieldNames || p.fieldNames.includes(col)));
16
+ #namingStrategy;
17
+ #metadataProvider;
18
+ #logger;
19
+ #schemaHelper;
20
+ #validator = new MetadataValidator();
21
+ #discovered = [];
22
+ #metadata;
23
+ #platform;
24
+ #config;
25
+ constructor(metadata, platform, config) {
26
+ this.#metadata = metadata;
27
+ this.#platform = platform;
28
+ this.#config = config;
29
+ this.#namingStrategy = this.#config.getNamingStrategy();
30
+ this.#metadataProvider = this.#config.getMetadataProvider();
31
+ this.#logger = this.#config.getLogger();
32
+ this.#schemaHelper = this.#platform.getSchemaHelper();
33
+ }
34
+ /** Discovers all entities asynchronously and returns the populated MetadataStorage. */
35
+ async discover(preferTs = true) {
36
+ this.#discovered.length = 0;
37
+ const startTime = Date.now();
38
+ const suffix = this.#metadataProvider.constructor === MetadataProvider
39
+ ? ''
40
+ : `, using ${colors.cyan(this.#metadataProvider.constructor.name)}`;
41
+ this.#logger.log('discovery', `ORM entity discovery started${suffix}`);
42
+ await this.findEntities(preferTs);
43
+ for (const meta of this.#discovered) {
44
+ /* v8 ignore next */
45
+ await this.#config.get('discovery').onMetadata?.(meta, this.#platform);
46
+ }
47
+ this.processDiscoveredEntities(this.#discovered);
48
+ const diff = Date.now() - startTime;
49
+ this.#logger.log('discovery', `- entity discovery finished, found ${colors.green('' + this.#discovered.length)} entities, took ${colors.green(`${diff} ms`)}`);
50
+ const storage = this.mapDiscoveredEntities();
51
+ /* v8 ignore next */
52
+ await this.#config.get('discovery').afterDiscovered?.(storage, this.#platform);
53
+ return storage;
54
+ }
55
+ /** Discovers all entities synchronously and returns the populated MetadataStorage. */
56
+ discoverSync() {
57
+ this.#discovered.length = 0;
58
+ const startTime = Date.now();
59
+ const suffix = this.#metadataProvider.constructor === MetadataProvider
60
+ ? ''
61
+ : `, using ${colors.cyan(this.#metadataProvider.constructor.name)}`;
62
+ this.#logger.log('discovery', `ORM entity discovery started${suffix} in sync mode`);
63
+ const refs = this.#config.get('entities');
64
+ this.discoverReferences(refs);
65
+ for (const meta of this.#discovered) {
66
+ /* v8 ignore next */
67
+ void this.#config.get('discovery').onMetadata?.(meta, this.#platform);
68
+ }
69
+ this.processDiscoveredEntities(this.#discovered);
70
+ const diff = Date.now() - startTime;
71
+ this.#logger.log('discovery', `- entity discovery finished, found ${colors.green('' + this.#discovered.length)} entities, took ${colors.green(`${diff} ms`)}`);
72
+ const storage = this.mapDiscoveredEntities();
73
+ /* v8 ignore next */
74
+ void this.#config.get('discovery').afterDiscovered?.(storage, this.#platform);
75
+ return storage;
76
+ }
77
+ mapDiscoveredEntities() {
78
+ const discovered = new MetadataStorage();
79
+ this.#discovered
80
+ .filter(meta => meta.root.name)
81
+ .sort((a, b) => b.root.name.localeCompare(a.root.name))
82
+ .forEach(meta => {
83
+ this.#platform.validateMetadata(meta);
84
+ discovered.set(meta.class, meta);
414
85
  });
415
- }
416
- if (!prop.ownColumns || prop.ownColumns.length === 0) {
417
- prop.ownColumns = prop.joinColumns;
418
- }
419
- if (prop.joinColumns.length !== prop.columnTypes.length) {
420
- prop.columnTypes = prop.joinColumns.flatMap(field => {
421
- const matched = meta.props.find(p => p.fieldNames?.includes(field));
422
- /* v8 ignore next */
423
- if (!matched) {
424
- throw MetadataError.fromWrongForeignKey(meta, prop, 'columnTypes');
425
- }
426
- return matched.columnTypes;
86
+ for (const meta of discovered) {
87
+ meta.root = discovered.get(meta.root.class);
88
+ if (meta.inheritanceType === 'tpt') {
89
+ this.computeTPTOwnProps(meta);
90
+ }
91
+ }
92
+ return discovered;
93
+ }
94
+ initAccessors(meta) {
95
+ for (const prop of Object.values(meta.properties)) {
96
+ if (!prop.accessor || meta.properties[prop.accessor]) {
97
+ continue;
98
+ }
99
+ const desc = Object.getOwnPropertyDescriptor(meta.prototype, prop.name);
100
+ if (desc?.get || desc?.set) {
101
+ this.initRelation(prop);
102
+ this.initFieldName(prop);
103
+ const accessor = prop.name;
104
+ prop.name = typeof prop.accessor === 'string' ? prop.accessor : prop.name;
105
+ if (prop.accessor === true) {
106
+ prop.getter = prop.setter = true;
107
+ }
108
+ else {
109
+ prop.getter = prop.setter = false;
110
+ }
111
+ prop.accessor = accessor;
112
+ prop.serializedName ??= accessor;
113
+ Utils.renameKey(meta.properties, accessor, prop.name);
114
+ }
115
+ else {
116
+ const name = prop.name;
117
+ if (prop.kind === ReferenceKind.SCALAR || prop.kind === ReferenceKind.EMBEDDED) {
118
+ prop.name = prop.accessor;
119
+ }
120
+ this.initRelation(prop);
121
+ this.initFieldName(prop);
122
+ prop.serializedName ??= prop.accessor;
123
+ prop.name = name;
124
+ }
125
+ }
126
+ }
127
+ /** Processes discovered entities: initializes relations, embeddables, indexes, and inheritance. */
128
+ processDiscoveredEntities(discovered) {
129
+ for (const meta of discovered) {
130
+ let i = 1;
131
+ Object.values(meta.properties).forEach(prop => meta.propertyOrder.set(prop.name, i++));
132
+ Object.values(meta.properties).forEach(prop => this.initPolyEmbeddables(prop, discovered));
133
+ this.initAccessors(meta);
134
+ }
135
+ // ignore base entities (not annotated with @Entity)
136
+ const filtered = discovered.filter(meta => meta.root.name);
137
+ // sort so we discover entities first to get around issues with nested embeddables
138
+ filtered.sort((a, b) => (!a.embeddable === !b.embeddable ? 0 : a.embeddable ? 1 : -1));
139
+ filtered.forEach(meta => this.initSingleTableInheritance(meta, filtered));
140
+ filtered.forEach(meta => this.initTPTRelationships(meta, filtered));
141
+ filtered.forEach(meta => this.defineBaseEntityProperties(meta));
142
+ filtered.forEach(meta => {
143
+ const newMeta = EntitySchema.fromMetadata(meta).init().meta;
144
+ return this.#metadata.set(newMeta.class, newMeta);
145
+ });
146
+ filtered.forEach(meta => this.initAutoincrement(meta));
147
+ const forEachProp = (cb) => {
148
+ filtered.forEach(meta => Object.values(meta.properties).forEach(prop => cb(meta, prop)));
149
+ };
150
+ forEachProp((m, p) => this.initFactoryField(m, p));
151
+ forEachProp((m, p) => this.initPolymorphicRelation(m, p, filtered));
152
+ forEachProp((_m, p) => this.initRelation(p));
153
+ forEachProp((m, p) => this.initEmbeddables(m, p));
154
+ forEachProp((_m, p) => this.initFieldName(p));
155
+ filtered.forEach(meta => this.finalizeTPTInheritance(meta, filtered));
156
+ filtered.forEach(meta => this.computeTPTOwnProps(meta));
157
+ forEachProp((m, p) => this.initVersionProperty(m, p));
158
+ forEachProp((m, p) => this.initCustomType(m, p));
159
+ forEachProp((m, p) => this.initGeneratedColumn(m, p));
160
+ filtered.forEach(meta => this.initAutoincrement(meta)); // once again after we init custom types
161
+ filtered.forEach(meta => this.initCheckConstraints(meta));
162
+ forEachProp((_m, p) => {
163
+ this.initDefaultValue(p);
164
+ this.inferTypeFromDefault(p);
165
+ this.initRelation(p);
166
+ this.initColumnType(p);
427
167
  });
428
- }
429
- if (prop.joinColumns.length !== prop.referencedColumnNames.length) {
430
- throw MetadataError.fromWrongForeignKey(meta, prop, 'referencedColumnNames');
431
- }
432
- }
433
- }
434
- initFieldName(prop, object = false) {
435
- if (prop.fieldNames && prop.fieldNames.length > 0) {
436
- return;
437
- }
438
- if (prop.kind === ReferenceKind.SCALAR || prop.kind === ReferenceKind.EMBEDDED) {
439
- prop.fieldNames = [this.#namingStrategy.propertyToColumnName(prop.name, object)];
440
- } else if ([ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(prop.kind) && !prop.polymorphic) {
441
- prop.fieldNames = this.initManyToOneFieldName(prop, prop.name);
442
- } else if (prop.kind === ReferenceKind.MANY_TO_MANY && prop.owner) {
443
- prop.fieldNames = this.initManyToManyFieldName(prop, prop.name);
444
- }
445
- }
446
- initManyToOneFieldName(prop, name) {
447
- const meta2 = prop.targetMeta;
448
- const ret = [];
449
- for (const primaryKey of meta2.primaryKeys) {
450
- this.initFieldName(meta2.properties[primaryKey]);
451
- for (const fieldName of meta2.properties[primaryKey].fieldNames) {
452
- ret.push(this.#namingStrategy.joinKeyColumnName(name, fieldName, meta2.compositePK));
453
- }
454
- }
455
- return ret;
456
- }
457
- initManyToManyFieldName(prop, name) {
458
- const meta2 = prop.targetMeta;
459
- return meta2.primaryKeys.map(() => this.#namingStrategy.propertyToColumnName(name));
460
- }
461
- initManyToManyFields(meta, prop) {
462
- const meta2 = prop.targetMeta;
463
- Utils.defaultValue(prop, 'fixedOrder', !!prop.fixedOrderColumn);
464
- const pivotMeta = this.#metadata.find(prop.pivotEntity);
465
- const props = Object.values(pivotMeta?.properties ?? {});
466
- const pks = props.filter(p => p.primary);
467
- const fks = props.filter(p => p.kind === ReferenceKind.MANY_TO_ONE);
468
- if (pivotMeta) {
469
- pivotMeta.pivotTable = true;
470
- prop.pivotTable = pivotMeta.tableName;
471
- if (pks.length === 1) {
472
- prop.fixedOrder = true;
473
- prop.fixedOrderColumn = pks[0].name;
474
- }
475
- }
476
- if (pivotMeta && (pks.length === 2 || fks.length >= 2)) {
477
- const owner = prop.mappedBy ? meta2.properties[prop.mappedBy] : prop;
478
- const [first, second] = this.ensureCorrectFKOrderInPivotEntity(pivotMeta, owner);
479
- prop.joinColumns ??= first.fieldNames;
480
- prop.inverseJoinColumns ??= second.fieldNames;
481
- }
482
- if (!prop.pivotTable && prop.owner && this.#platform.usesPivotTable()) {
483
- prop.pivotTable = this.#namingStrategy.joinTableName(meta.className, meta2.tableName, prop.name, meta.tableName);
484
- }
485
- if (prop.mappedBy) {
486
- const prop2 = meta2.properties[prop.mappedBy];
487
- this.initManyToManyFields(meta2, prop2);
488
- prop.pivotTable = prop2.pivotTable;
489
- prop.pivotEntity = prop2.pivotEntity;
490
- prop.fixedOrder = prop2.fixedOrder;
491
- prop.fixedOrderColumn = prop2.fixedOrderColumn;
492
- prop.joinColumns = prop2.inverseJoinColumns;
493
- prop.inverseJoinColumns = prop2.joinColumns;
494
- prop.polymorphic = prop2.polymorphic;
495
- prop.discriminator = prop2.discriminator;
496
- prop.discriminatorColumn = prop2.discriminatorColumn;
497
- prop.discriminatorValue = prop2.discriminatorValue;
498
- }
499
- prop.referencedColumnNames ??= Utils.flatten(
500
- meta.primaryKeys.map(primaryKey => meta.properties[primaryKey].fieldNames),
501
- );
502
- // For polymorphic M:N, use discriminator base name for FK column (e.g., taggable_id instead of post_id)
503
- if (prop.polymorphic && prop.discriminator) {
504
- prop.joinColumns ??= prop.referencedColumnNames.map(referencedColumnName =>
505
- this.#namingStrategy.joinKeyColumnName(
506
- prop.discriminator,
507
- referencedColumnName,
508
- prop.referencedColumnNames.length > 1,
509
- ),
510
- );
511
- } else {
512
- prop.joinColumns ??= prop.referencedColumnNames.map(referencedColumnName =>
513
- this.#namingStrategy.joinKeyColumnName(meta.root.className, referencedColumnName, meta.compositePK),
514
- );
515
- }
516
- prop.inverseJoinColumns ??= this.initManyToOneFieldName(prop, meta2.root.className);
517
- }
518
- isExplicitTableName(meta) {
519
- return meta.tableName !== this.#namingStrategy.classToTableName(meta.className);
520
- }
521
- initManyToOneFields(prop) {
522
- if (prop.polymorphic && prop.polymorphTargets) {
523
- const fieldNames1 = prop.targetMeta.getPrimaryProps().flatMap(pk => pk.fieldNames);
524
- const idColumns = fieldNames1.map(fieldName =>
525
- this.#namingStrategy.joinKeyColumnName(prop.discriminator, fieldName, fieldNames1.length > 1),
526
- );
527
- prop.fieldNames ??= [prop.discriminatorColumn, ...idColumns];
528
- prop.joinColumns ??= idColumns;
529
- prop.referencedColumnNames ??= fieldNames1;
530
- prop.referencedTableName ??= prop.targetMeta.tableName;
531
- return;
532
- }
533
- const meta2 = prop.targetMeta;
534
- let fieldNames;
535
- // If targetKey is specified, use that property's field names instead of PKs
536
- if (prop.targetKey) {
537
- const targetProp = meta2.properties[prop.targetKey];
538
- fieldNames = targetProp.fieldNames;
539
- } else {
540
- fieldNames = Utils.flatten(meta2.primaryKeys.map(primaryKey => meta2.properties[primaryKey].fieldNames));
541
- }
542
- Utils.defaultValue(prop, 'referencedTableName', meta2.tableName);
543
- if (!prop.joinColumns) {
544
- prop.joinColumns = fieldNames.map(fieldName =>
545
- this.#namingStrategy.joinKeyColumnName(prop.name, fieldName, fieldNames.length > 1),
546
- );
547
- }
548
- if (!prop.referencedColumnNames) {
549
- prop.referencedColumnNames = fieldNames;
550
- }
551
- // Relations to composite PK targets need cascade update by default,
552
- // since composite PKs are more likely to have mutable components
553
- if (meta2.compositePK) {
554
- prop.updateRule ??= 'cascade';
555
- }
556
- // Nullable relations default to 'set null' on delete - when the referenced
557
- // entity is deleted, set the FK to null rather than failing
558
- if (prop.nullable) {
559
- prop.deleteRule ??= 'set null';
560
- }
561
- }
562
- initOneToManyFields(prop) {
563
- const meta2 = prop.targetMeta;
564
- if (!prop.joinColumns) {
565
- prop.joinColumns = [this.#namingStrategy.joinColumnName(prop.name)];
566
- }
567
- if (!prop.referencedColumnNames) {
568
- meta2.getPrimaryProps().forEach(pk => this.applyNamingStrategy(meta2, pk));
569
- prop.referencedColumnNames = Utils.flatten(meta2.getPrimaryProps().map(pk => pk.fieldNames));
570
- }
571
- }
572
- processEntity(meta) {
573
- const pks = Object.values(meta.properties).filter(prop => prop.primary);
574
- meta.primaryKeys = pks.map(prop => prop.name);
575
- meta.compositePK = pks.length > 1;
576
- // FK used as PK, we need to cascade - applies to both single FK-as-PK
577
- // and composite PKs where all PKs are FKs (e.g., pivot-like entities)
578
- const fkPks = pks.filter(pk => pk.kind !== ReferenceKind.SCALAR);
579
- if (fkPks.length > 0 && fkPks.length === pks.length) {
580
- for (const pk of fkPks) {
581
- pk.deleteRule ??= 'cascade';
582
- pk.updateRule ??= 'cascade';
583
- }
584
- }
585
- meta.forceConstructor ??= this.shouldForceConstructorUsage(meta);
586
- this.#validator.validateEntityDefinition(this.#metadata, meta.class, this.#config.get('discovery'));
587
- for (const prop of Object.values(meta.properties)) {
588
- this.initNullability(prop);
589
- this.applyNamingStrategy(meta, prop);
590
- this.initDefaultValue(prop);
591
- this.inferTypeFromDefault(prop);
592
- this.initVersionProperty(meta, prop);
593
- this.initCustomType(meta, prop);
594
- this.initColumnType(prop);
595
- this.initRelation(prop);
596
- }
597
- this.initOwnColumns(meta);
598
- meta.simplePK =
599
- pks.length === 1 && pks[0].kind === ReferenceKind.SCALAR && !pks[0].customType && pks[0].runtimeType !== 'Date';
600
- meta.serializedPrimaryKey ??= meta.props.find(prop => prop.serializedPrimaryKey)?.name;
601
- if (meta.serializedPrimaryKey && meta.serializedPrimaryKey !== meta.primaryKeys[0]) {
602
- meta.properties[meta.serializedPrimaryKey].persist ??= false;
603
- }
604
- if (this.#platform.usesPivotTable()) {
605
- return Object.values(meta.properties)
606
- .filter(prop => prop.kind === ReferenceKind.MANY_TO_MANY && prop.owner && prop.pivotTable)
607
- .map(prop => {
608
- const pivotMeta = this.definePivotTableEntity(meta, prop);
609
- prop.pivotEntity = pivotMeta.class;
610
- if (prop.inversedBy) {
611
- prop.targetMeta.properties[prop.inversedBy].pivotEntity = pivotMeta.class;
612
- }
613
- return pivotMeta;
168
+ forEachProp((m, p) => this.initIndexes(m, p));
169
+ filtered.forEach(meta => this.autoWireBidirectionalProperties(meta));
170
+ for (const meta of filtered) {
171
+ discovered.push(...this.processEntity(meta));
172
+ }
173
+ discovered.forEach(meta => meta.sync(true));
174
+ this.#metadataProvider.combineCache();
175
+ return discovered.map(meta => {
176
+ meta = this.#metadata.get(meta.class);
177
+ meta.sync(true);
178
+ this.findReferencingProperties(meta, filtered);
179
+ if (meta.inheritanceType === 'tpt') {
180
+ this.computeTPTOwnProps(meta);
181
+ }
182
+ return meta;
614
183
  });
615
184
  }
616
- return [];
617
- }
618
- findReferencingProperties(meta, metadata) {
619
- for (const meta2 of metadata) {
620
- for (const prop2 of meta2.relations) {
621
- if (prop2.kind !== ReferenceKind.SCALAR && prop2.type === meta.className) {
622
- meta.referencingProperties.push({ meta: meta2, prop: prop2 });
623
- }
624
- }
625
- }
626
- }
627
- initFactoryField(meta, prop) {
628
- ['mappedBy', 'inversedBy', 'pivotEntity'].forEach(type => {
629
- const value = prop[type];
630
- if (value instanceof Function) {
631
- const meta2 = prop.targetMeta ?? this.#metadata.get(prop.target);
632
- prop[type] = value(meta2.properties)?.name;
633
- if (type === 'pivotEntity' && value) {
634
- prop[type] = value(meta2.properties);
635
- }
636
- if (prop[type] == null) {
637
- throw MetadataError.fromWrongReference(meta, prop, type);
638
- }
639
- }
640
- });
641
- }
642
- ensureCorrectFKOrderInPivotEntity(meta, owner) {
643
- const pks = Object.values(meta.properties).filter(p => p.primary);
644
- const fks = Object.values(meta.properties).filter(p => p.kind === ReferenceKind.MANY_TO_ONE);
645
- let first, second;
646
- if (pks.length === 2) {
647
- [first, second] = pks;
648
- } else if (fks.length >= 2) {
649
- [first, second] = fks;
650
- } else {
651
- /* v8 ignore next */
652
- return [];
653
- }
654
- // wrong FK order, first FK needs to point to the owning side
655
- // (note that we can detect this only if the FKs target different types)
656
- if (owner.type === first.type && first.type !== second.type) {
657
- delete meta.properties[first.name];
658
- meta.removeProperty(first.name, false);
659
- meta.addProperty(first);
660
- [first, second] = [second, first];
661
- }
662
- return [first, second];
663
- }
664
- definePivotTableEntity(meta, prop) {
665
- const pivotMeta = prop.pivotEntity
666
- ? this.#metadata.find(prop.pivotEntity)
667
- : this.#metadata.getByClassName(prop.pivotTable, false);
668
- // ensure inverse side exists so we can join it when populating via pivot tables
669
- if (!prop.inversedBy && prop.targetMeta) {
670
- const inverseName = `${meta.className}_${prop.name}__inverse`;
671
- prop.inversedBy = inverseName;
672
- const inverseProp = {
673
- name: inverseName,
674
- kind: ReferenceKind.MANY_TO_MANY,
675
- type: meta.className,
676
- target: meta.class,
677
- targetMeta: meta,
678
- mappedBy: prop.name,
679
- pivotEntity: prop.pivotEntity,
680
- pivotTable: prop.pivotTable,
681
- persist: false,
682
- hydrate: false,
683
- };
684
- this.applyNamingStrategy(prop.targetMeta, inverseProp);
685
- this.initCustomType(prop.targetMeta, inverseProp);
686
- prop.targetMeta.properties[inverseName] = inverseProp;
687
- }
688
- if (pivotMeta) {
689
- prop.pivotEntity = pivotMeta.class;
690
- this.ensureCorrectFKOrderInPivotEntity(pivotMeta, prop);
691
- if (prop.polymorphic && prop.discriminatorValue) {
185
+ async findEntities(preferTs) {
186
+ const { entities, entitiesTs, baseDir } = this.#config.getAll();
187
+ const targets = preferTs && entitiesTs.length > 0 ? entitiesTs : entities;
188
+ const processed = [];
189
+ const paths = [];
190
+ for (const entity of targets) {
191
+ if (typeof entity === 'string') {
192
+ paths.push(entity);
193
+ }
194
+ else {
195
+ processed.push(entity);
196
+ }
197
+ }
198
+ if (paths.length > 0) {
199
+ const { discoverEntities } = await import('@mikro-orm/core/file-discovery');
200
+ processed.push(...(await discoverEntities(paths, { baseDir })));
201
+ }
202
+ return this.discoverReferences(processed);
203
+ }
204
+ discoverMissingTargets() {
205
+ const unwrap = (type) => type
206
+ .replace(/Array<(.*)>/, '$1') // unwrap array
207
+ .replace(/\[]$/, '') // remove array suffix
208
+ .replace(/\((.*)\)/, '$1'); // unwrap union types
209
+ const missing = [];
210
+ this.#discovered.forEach(meta => Object.values(meta.properties).forEach(prop => {
211
+ if (prop.kind === ReferenceKind.MANY_TO_MANY && prop.pivotEntity) {
212
+ const pivotEntity = prop.pivotEntity;
213
+ const target = typeof pivotEntity === 'function' && !pivotEntity.prototype
214
+ ? pivotEntity()
215
+ : pivotEntity;
216
+ if (!this.#discovered.find(m => m.className === Utils.className(target))) {
217
+ missing.push(target);
218
+ }
219
+ }
220
+ if (prop.kind !== ReferenceKind.SCALAR) {
221
+ const target = typeof prop.entity === 'function' && !prop.entity.prototype ? prop.entity() : prop.type;
222
+ if (!unwrap(prop.type)
223
+ .split(/ ?\| ?/)
224
+ .every(type => this.#discovered.find(m => m.className === type))) {
225
+ missing.push(...Utils.asArray(target));
226
+ }
227
+ }
228
+ }));
229
+ if (missing.length > 0) {
230
+ this.tryDiscoverTargets(missing);
231
+ }
232
+ }
233
+ tryDiscoverTargets(targets) {
234
+ for (const target of targets) {
235
+ const schema = EntitySchema.is(target) ? target : undefined;
236
+ const isDiscoverable = typeof target === 'function' || schema;
237
+ if (isDiscoverable && target.name) {
238
+ // Get the actual class for EntitySchema, or use target directly for classes
239
+ const targetClass = schema ? schema.meta.class : target;
240
+ if (!this.#metadata.has(targetClass)) {
241
+ this.discoverReferences([target], false);
242
+ this.discoverMissingTargets();
243
+ }
244
+ }
245
+ }
246
+ }
247
+ discoverReferences(refs, validate = true) {
248
+ const found = [];
249
+ for (const entity of refs) {
250
+ if (typeof entity === 'string') {
251
+ throw new Error('Folder based discovery requires the async `MikroORM.init()` method.');
252
+ }
253
+ const schema = this.getSchema(entity);
254
+ const meta = schema.init().meta;
255
+ this.#metadata.set(meta.class, meta);
256
+ found.push(schema);
257
+ }
258
+ // discover parents (base entities) automatically
259
+ for (const meta of this.#metadata) {
260
+ let parent = meta.extends;
261
+ if (EntitySchema.is(parent) && !this.#metadata.has(parent.init().meta.class)) {
262
+ this.discoverReferences([parent], false);
263
+ }
264
+ if (typeof parent === 'function' && parent.name && !this.#metadata.has(parent)) {
265
+ this.discoverReferences([parent], false);
266
+ }
267
+ /* v8 ignore next */
268
+ if (!meta.class) {
269
+ continue;
270
+ }
271
+ parent = Object.getPrototypeOf(meta.class);
272
+ // Skip if parent is the auto-generated base class for the same entity (from setClass usage)
273
+ if (parent.name !== '' &&
274
+ parent.name !== meta.className &&
275
+ !this.#metadata.has(parent) &&
276
+ parent !== BaseEntity) {
277
+ this.discoverReferences([parent], false);
278
+ }
279
+ }
280
+ for (const schema of found) {
281
+ this.discoverEntity(schema);
282
+ }
283
+ this.discoverMissingTargets();
284
+ if (validate) {
285
+ this.#validator.validateDiscovered(this.#discovered, this.#config.get('discovery'));
286
+ }
287
+ return this.#discovered.filter(meta => found.find(m => m.name === meta.className));
288
+ }
289
+ reset(entityName) {
290
+ const exists = this.#discovered.findIndex(m => m.class === entityName || m.className === Utils.className(entityName));
291
+ if (exists !== -1) {
292
+ this.#metadata.reset(this.#discovered[exists].class);
293
+ this.#discovered.splice(exists, 1);
294
+ }
295
+ }
296
+ getSchema(entity) {
297
+ if (EntitySchema.REGISTRY.has(entity)) {
298
+ entity = EntitySchema.REGISTRY.get(entity);
299
+ }
300
+ if (EntitySchema.is(entity)) {
301
+ const meta = Utils.copy(entity.meta, false);
302
+ return EntitySchema.fromMetadata(meta);
303
+ }
304
+ // After the EntitySchema check, entity must be an EntityClass
305
+ const cls = entity;
306
+ const path = cls[MetadataStorage.PATH_SYMBOL];
307
+ if (path) {
308
+ const meta = Utils.copy(MetadataStorage.getMetadata(cls.name, path), false);
309
+ meta.path = path;
310
+ this.#metadata.set(cls, meta);
311
+ }
312
+ const exists = this.#metadata.has(cls);
313
+ const meta = this.#metadata.get(cls, true);
314
+ meta.abstract ??= !(exists && meta.name);
315
+ const schema = EntitySchema.fromMetadata(meta);
316
+ schema.setClass(cls);
317
+ return schema;
318
+ }
319
+ getRootEntity(meta) {
320
+ const base = meta.extends && this.#metadata.find(meta.extends);
321
+ if (!base || base === meta) {
322
+ // make sure we do not fall into infinite loop
323
+ return meta;
324
+ }
325
+ const root = this.getRootEntity(base);
326
+ // For STI or TPT, use the root entity.
327
+ // Check both `inheritanceType` (set during discovery) and raw `inheritance` option (set before discovery).
328
+ if (root.discriminatorColumn || root.inheritanceType || root.inheritance === 'tpt') {
329
+ return root;
330
+ }
331
+ return meta;
332
+ }
333
+ discoverEntity(schema) {
334
+ const meta = schema.meta;
335
+ const path = meta.path;
336
+ this.#logger.log('discovery', `- processing entity ${colors.cyan(meta.className)}${colors.grey(path ? ` (${path})` : '')}`);
337
+ const root = this.getRootEntity(meta);
338
+ schema.meta.path = meta.path;
339
+ const cache = this.#metadataProvider.getCachedMetadata(meta, root);
340
+ if (cache) {
341
+ this.#logger.log('discovery', `- using cached metadata for entity ${colors.cyan(meta.className)}`);
342
+ this.#discovered.push(meta);
343
+ return;
344
+ }
345
+ // infer default value from property initializer early, as the metadata provider might use some defaults, e.g. string for reflect-metadata
346
+ for (const prop of meta.props) {
347
+ this.inferDefaultValue(meta, prop);
348
+ }
349
+ // if the definition is using EntitySchema we still want it to go through the metadata provider to validate no types are missing
350
+ this.#metadataProvider.loadEntityMetadata(meta);
351
+ if (!meta.tableName && meta.name) {
352
+ const entityName = root.discriminatorColumn ? root.name : meta.name;
353
+ meta.tableName = this.#namingStrategy.classToTableName(entityName);
354
+ }
355
+ this.#metadataProvider.saveToCache(meta);
356
+ meta.root = root;
357
+ this.#discovered.push(meta);
358
+ }
359
+ initNullability(prop) {
360
+ if (prop.kind === ReferenceKind.ONE_TO_ONE) {
361
+ return Utils.defaultValue(prop, 'nullable', prop.optional || !prop.owner);
362
+ }
363
+ return Utils.defaultValue(prop, 'nullable', prop.optional);
364
+ }
365
+ applyNamingStrategy(meta, prop) {
366
+ if (!prop.fieldNames) {
367
+ this.initFieldName(prop);
368
+ }
369
+ if (prop.kind === ReferenceKind.MANY_TO_MANY) {
370
+ this.initManyToManyFields(meta, prop);
371
+ }
372
+ if ([ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(prop.kind)) {
373
+ this.initManyToOneFields(prop);
374
+ }
375
+ if (prop.kind === ReferenceKind.ONE_TO_MANY) {
376
+ this.initOneToManyFields(prop);
377
+ }
378
+ }
379
+ initOwnColumns(meta) {
380
+ meta.sync();
381
+ for (const prop of meta.props) {
382
+ if (!prop.joinColumns ||
383
+ !prop.columnTypes ||
384
+ prop.ownColumns ||
385
+ ![ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(prop.kind)) {
386
+ continue;
387
+ }
388
+ // For polymorphic relations, ownColumns should include all fieldNames
389
+ // (discriminator + ID columns) since they are all owned by this relation
390
+ if (prop.polymorphic) {
391
+ prop.ownColumns = prop.fieldNames;
392
+ continue;
393
+ }
394
+ if (prop.joinColumns.length > 1) {
395
+ prop.ownColumns = prop.joinColumns.filter(col => {
396
+ return !meta.props.find(p => p.name !== prop.name && (!p.fieldNames || p.fieldNames.includes(col)));
397
+ });
398
+ }
399
+ if (!prop.ownColumns || prop.ownColumns.length === 0) {
400
+ prop.ownColumns = prop.joinColumns;
401
+ }
402
+ if (prop.joinColumns.length !== prop.columnTypes.length) {
403
+ prop.columnTypes = prop.joinColumns.flatMap(field => {
404
+ const matched = meta.props.find(p => p.fieldNames?.includes(field));
405
+ /* v8 ignore next */
406
+ if (!matched) {
407
+ throw MetadataError.fromWrongForeignKey(meta, prop, 'columnTypes');
408
+ }
409
+ return matched.columnTypes;
410
+ });
411
+ }
412
+ if (prop.joinColumns.length !== prop.referencedColumnNames.length) {
413
+ throw MetadataError.fromWrongForeignKey(meta, prop, 'referencedColumnNames');
414
+ }
415
+ }
416
+ }
417
+ initFieldName(prop, object = false) {
418
+ if (prop.fieldNames && prop.fieldNames.length > 0) {
419
+ return;
420
+ }
421
+ if (prop.kind === ReferenceKind.SCALAR || prop.kind === ReferenceKind.EMBEDDED) {
422
+ prop.fieldNames = [this.#namingStrategy.propertyToColumnName(prop.name, object)];
423
+ }
424
+ else if ([ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(prop.kind) && !prop.polymorphic) {
425
+ prop.fieldNames = this.initManyToOneFieldName(prop, prop.name);
426
+ }
427
+ else if (prop.kind === ReferenceKind.MANY_TO_MANY && prop.owner) {
428
+ prop.fieldNames = this.initManyToManyFieldName(prop, prop.name);
429
+ }
430
+ }
431
+ initManyToOneFieldName(prop, name) {
432
+ const meta2 = prop.targetMeta;
433
+ const ret = [];
434
+ for (const primaryKey of meta2.primaryKeys) {
435
+ this.initFieldName(meta2.properties[primaryKey]);
436
+ for (const fieldName of meta2.properties[primaryKey].fieldNames) {
437
+ ret.push(this.#namingStrategy.joinKeyColumnName(name, fieldName, meta2.compositePK));
438
+ }
439
+ }
440
+ return ret;
441
+ }
442
+ initManyToManyFieldName(prop, name) {
443
+ const meta2 = prop.targetMeta;
444
+ return meta2.primaryKeys.map(() => this.#namingStrategy.propertyToColumnName(name));
445
+ }
446
+ initManyToManyFields(meta, prop) {
447
+ const meta2 = prop.targetMeta;
448
+ Utils.defaultValue(prop, 'fixedOrder', !!prop.fixedOrderColumn);
449
+ const pivotMeta = this.#metadata.find(prop.pivotEntity);
450
+ const props = Object.values(pivotMeta?.properties ?? {});
451
+ const pks = props.filter(p => p.primary);
452
+ const fks = props.filter(p => p.kind === ReferenceKind.MANY_TO_ONE);
453
+ if (pivotMeta) {
454
+ pivotMeta.pivotTable = true;
455
+ prop.pivotTable = pivotMeta.tableName;
456
+ if (pks.length === 1) {
457
+ prop.fixedOrder = true;
458
+ prop.fixedOrderColumn = pks[0].name;
459
+ }
460
+ }
461
+ if (pivotMeta && (pks.length === 2 || fks.length >= 2)) {
462
+ const owner = prop.mappedBy ? meta2.properties[prop.mappedBy] : prop;
463
+ const [first, second] = this.ensureCorrectFKOrderInPivotEntity(pivotMeta, owner);
464
+ prop.joinColumns ??= first.fieldNames;
465
+ prop.inverseJoinColumns ??= second.fieldNames;
466
+ }
467
+ if (!prop.pivotTable && prop.owner && this.#platform.usesPivotTable()) {
468
+ prop.pivotTable = this.#namingStrategy.joinTableName(meta.className, meta2.tableName, prop.name, meta.tableName);
469
+ }
470
+ if (prop.mappedBy) {
471
+ const prop2 = meta2.properties[prop.mappedBy];
472
+ this.initManyToManyFields(meta2, prop2);
473
+ prop.pivotTable = prop2.pivotTable;
474
+ prop.pivotEntity = prop2.pivotEntity;
475
+ prop.fixedOrder = prop2.fixedOrder;
476
+ prop.fixedOrderColumn = prop2.fixedOrderColumn;
477
+ prop.joinColumns = prop2.inverseJoinColumns;
478
+ prop.inverseJoinColumns = prop2.joinColumns;
479
+ prop.polymorphic = prop2.polymorphic;
480
+ prop.discriminator = prop2.discriminator;
481
+ prop.discriminatorColumn = prop2.discriminatorColumn;
482
+ prop.discriminatorValue = prop2.discriminatorValue;
483
+ }
484
+ prop.referencedColumnNames ??= Utils.flatten(meta.primaryKeys.map(primaryKey => meta.properties[primaryKey].fieldNames));
485
+ // For polymorphic M:N, use discriminator base name for FK column (e.g., taggable_id instead of post_id)
486
+ if (prop.polymorphic && prop.discriminator) {
487
+ prop.joinColumns ??= prop.referencedColumnNames.map(referencedColumnName => this.#namingStrategy.joinKeyColumnName(prop.discriminator, referencedColumnName, prop.referencedColumnNames.length > 1));
488
+ }
489
+ else {
490
+ prop.joinColumns ??= prop.referencedColumnNames.map(referencedColumnName => this.#namingStrategy.joinKeyColumnName(meta.root.className, referencedColumnName, meta.compositePK));
491
+ }
492
+ prop.inverseJoinColumns ??= this.initManyToOneFieldName(prop, meta2.root.className);
493
+ }
494
+ isExplicitTableName(meta) {
495
+ return meta.tableName !== this.#namingStrategy.classToTableName(meta.className);
496
+ }
497
+ initManyToOneFields(prop) {
498
+ if (prop.polymorphic && prop.polymorphTargets) {
499
+ const fieldNames1 = prop.targetMeta.getPrimaryProps().flatMap(pk => pk.fieldNames);
500
+ const idColumns = fieldNames1.map(fieldName => this.#namingStrategy.joinKeyColumnName(prop.discriminator, fieldName, fieldNames1.length > 1));
501
+ prop.fieldNames ??= [prop.discriminatorColumn, ...idColumns];
502
+ prop.joinColumns ??= idColumns;
503
+ prop.referencedColumnNames ??= fieldNames1;
504
+ prop.referencedTableName ??= prop.targetMeta.tableName;
505
+ return;
506
+ }
507
+ const meta2 = prop.targetMeta;
508
+ let fieldNames;
509
+ // If targetKey is specified, use that property's field names instead of PKs
510
+ if (prop.targetKey) {
511
+ const targetProp = meta2.properties[prop.targetKey];
512
+ fieldNames = targetProp.fieldNames;
513
+ }
514
+ else {
515
+ fieldNames = Utils.flatten(meta2.primaryKeys.map(primaryKey => meta2.properties[primaryKey].fieldNames));
516
+ }
517
+ Utils.defaultValue(prop, 'referencedTableName', meta2.tableName);
518
+ if (!prop.joinColumns) {
519
+ prop.joinColumns = fieldNames.map(fieldName => this.#namingStrategy.joinKeyColumnName(prop.name, fieldName, fieldNames.length > 1));
520
+ }
521
+ if (!prop.referencedColumnNames) {
522
+ prop.referencedColumnNames = fieldNames;
523
+ }
524
+ // Relations to composite PK targets need cascade update by default,
525
+ // since composite PKs are more likely to have mutable components
526
+ if (meta2.compositePK) {
527
+ prop.updateRule ??= 'cascade';
528
+ }
529
+ // Nullable relations default to 'set null' on delete - when the referenced
530
+ // entity is deleted, set the FK to null rather than failing
531
+ if (prop.nullable) {
532
+ prop.deleteRule ??= 'set null';
533
+ }
534
+ }
535
+ initOneToManyFields(prop) {
536
+ const meta2 = prop.targetMeta;
537
+ if (!prop.joinColumns) {
538
+ prop.joinColumns = [this.#namingStrategy.joinColumnName(prop.name)];
539
+ }
540
+ if (!prop.referencedColumnNames) {
541
+ meta2.getPrimaryProps().forEach(pk => this.applyNamingStrategy(meta2, pk));
542
+ prop.referencedColumnNames = Utils.flatten(meta2.getPrimaryProps().map(pk => pk.fieldNames));
543
+ }
544
+ }
545
+ processEntity(meta) {
546
+ const pks = Object.values(meta.properties).filter(prop => prop.primary);
547
+ meta.primaryKeys = pks.map(prop => prop.name);
548
+ meta.compositePK = pks.length > 1;
549
+ // FK used as PK, we need to cascade - applies to both single FK-as-PK
550
+ // and composite PKs where all PKs are FKs (e.g., pivot-like entities)
551
+ const fkPks = pks.filter(pk => pk.kind !== ReferenceKind.SCALAR);
552
+ if (fkPks.length > 0 && fkPks.length === pks.length) {
553
+ for (const pk of fkPks) {
554
+ pk.deleteRule ??= 'cascade';
555
+ pk.updateRule ??= 'cascade';
556
+ }
557
+ }
558
+ meta.forceConstructor ??= this.shouldForceConstructorUsage(meta);
559
+ this.#validator.validateEntityDefinition(this.#metadata, meta.class, this.#config.get('discovery'));
560
+ for (const prop of Object.values(meta.properties)) {
561
+ this.initNullability(prop);
562
+ this.applyNamingStrategy(meta, prop);
563
+ this.initDefaultValue(prop);
564
+ this.inferTypeFromDefault(prop);
565
+ this.initVersionProperty(meta, prop);
566
+ this.initCustomType(meta, prop);
567
+ this.initColumnType(prop);
568
+ this.initRelation(prop);
569
+ }
570
+ this.initOwnColumns(meta);
571
+ meta.simplePK =
572
+ pks.length === 1 && pks[0].kind === ReferenceKind.SCALAR && !pks[0].customType && pks[0].runtimeType !== 'Date';
573
+ meta.serializedPrimaryKey ??= meta.props.find(prop => prop.serializedPrimaryKey)?.name;
574
+ if (meta.serializedPrimaryKey && meta.serializedPrimaryKey !== meta.primaryKeys[0]) {
575
+ meta.properties[meta.serializedPrimaryKey].persist ??= false;
576
+ }
577
+ if (this.#platform.usesPivotTable()) {
578
+ return Object.values(meta.properties)
579
+ .filter(prop => prop.kind === ReferenceKind.MANY_TO_MANY && prop.owner && prop.pivotTable)
580
+ .map(prop => {
581
+ const pivotMeta = this.definePivotTableEntity(meta, prop);
582
+ prop.pivotEntity = pivotMeta.class;
583
+ if (prop.inversedBy) {
584
+ prop.targetMeta.properties[prop.inversedBy].pivotEntity = pivotMeta.class;
585
+ }
586
+ return pivotMeta;
587
+ });
588
+ }
589
+ return [];
590
+ }
591
+ findReferencingProperties(meta, metadata) {
592
+ for (const meta2 of metadata) {
593
+ for (const prop2 of meta2.relations) {
594
+ if (prop2.kind !== ReferenceKind.SCALAR && prop2.type === meta.className) {
595
+ meta.referencingProperties.push({ meta: meta2, prop: prop2 });
596
+ }
597
+ }
598
+ }
599
+ }
600
+ initFactoryField(meta, prop) {
601
+ ['mappedBy', 'inversedBy', 'pivotEntity'].forEach(type => {
602
+ const value = prop[type];
603
+ if (value instanceof Function) {
604
+ const meta2 = prop.targetMeta ?? this.#metadata.get(prop.target);
605
+ prop[type] = value(meta2.properties)?.name;
606
+ if (type === 'pivotEntity' && value) {
607
+ prop[type] = value(meta2.properties);
608
+ }
609
+ if (prop[type] == null) {
610
+ throw MetadataError.fromWrongReference(meta, prop, type);
611
+ }
612
+ }
613
+ });
614
+ }
615
+ ensureCorrectFKOrderInPivotEntity(meta, owner) {
616
+ const pks = Object.values(meta.properties).filter(p => p.primary);
617
+ const fks = Object.values(meta.properties).filter(p => p.kind === ReferenceKind.MANY_TO_ONE);
618
+ let first, second;
619
+ if (pks.length === 2) {
620
+ [first, second] = pks;
621
+ }
622
+ else if (fks.length >= 2) {
623
+ [first, second] = fks;
624
+ }
625
+ else {
626
+ /* v8 ignore next */
627
+ return [];
628
+ }
629
+ // wrong FK order, first FK needs to point to the owning side
630
+ // (note that we can detect this only if the FKs target different types)
631
+ if (owner.type === first.type && first.type !== second.type) {
632
+ delete meta.properties[first.name];
633
+ meta.removeProperty(first.name, false);
634
+ meta.addProperty(first);
635
+ [first, second] = [second, first];
636
+ }
637
+ return [first, second];
638
+ }
639
+ definePivotTableEntity(meta, prop) {
640
+ const pivotMeta = prop.pivotEntity
641
+ ? this.#metadata.find(prop.pivotEntity)
642
+ : this.#metadata.getByClassName(prop.pivotTable, false);
643
+ // ensure inverse side exists so we can join it when populating via pivot tables
644
+ if (!prop.inversedBy && prop.targetMeta) {
645
+ const inverseName = `${meta.className}_${prop.name}__inverse`;
646
+ prop.inversedBy = inverseName;
647
+ const inverseProp = {
648
+ name: inverseName,
649
+ kind: ReferenceKind.MANY_TO_MANY,
650
+ type: meta.className,
651
+ target: meta.class,
652
+ targetMeta: meta,
653
+ mappedBy: prop.name,
654
+ pivotEntity: prop.pivotEntity,
655
+ pivotTable: prop.pivotTable,
656
+ persist: false,
657
+ hydrate: false,
658
+ };
659
+ this.applyNamingStrategy(prop.targetMeta, inverseProp);
660
+ this.initCustomType(prop.targetMeta, inverseProp);
661
+ prop.targetMeta.properties[inverseName] = inverseProp;
662
+ }
663
+ if (pivotMeta) {
664
+ prop.pivotEntity = pivotMeta.class;
665
+ this.ensureCorrectFKOrderInPivotEntity(pivotMeta, prop);
666
+ if (prop.polymorphic && prop.discriminatorValue) {
667
+ pivotMeta.polymorphicDiscriminatorMap ??= {};
668
+ pivotMeta.polymorphicDiscriminatorMap[prop.discriminatorValue] = meta.class;
669
+ // For composite PK entities sharing a polymorphic pivot table,
670
+ // we need to add columns for each entity type's PKs
671
+ this.addPolymorphicPivotColumns(pivotMeta, meta, prop);
672
+ // Add virtual M:1 relation for this polymorphic owner (for join loading)
673
+ const ownerRelationName = `${prop.discriminator}_${meta.tableName}`;
674
+ if (!pivotMeta.properties[ownerRelationName]) {
675
+ pivotMeta.properties[ownerRelationName] = this.definePolymorphicOwnerRelation(prop, ownerRelationName, meta);
676
+ }
677
+ }
678
+ return pivotMeta;
679
+ }
680
+ let tableName = prop.pivotTable;
681
+ let schemaName;
682
+ if (prop.pivotTable.includes('.')) {
683
+ [schemaName, tableName] = prop.pivotTable.split('.');
684
+ }
685
+ schemaName ??= meta.schema;
686
+ const targetMeta = prop.targetMeta;
687
+ const targetType = targetMeta.className;
688
+ const pivotMeta2 = new EntityMetadata({
689
+ name: prop.pivotTable,
690
+ className: prop.pivotTable,
691
+ collection: tableName,
692
+ schema: schemaName,
693
+ pivotTable: true,
694
+ });
695
+ prop.pivotEntity = pivotMeta2.class;
696
+ if (prop.fixedOrder) {
697
+ const primaryProp = this.defineFixedOrderProperty(prop, targetMeta);
698
+ pivotMeta2.properties[primaryProp.name] = primaryProp;
699
+ }
700
+ else {
701
+ pivotMeta2.compositePK = true;
702
+ }
703
+ // handle self-referenced m:n with same default field names
704
+ if (meta.className === targetType &&
705
+ prop.joinColumns.every((joinColumn, idx) => joinColumn === prop.inverseJoinColumns[idx])) {
706
+ // use tableName only when explicitly provided by user, otherwise use className for backwards compatibility
707
+ const baseName = this.isExplicitTableName(meta) ? meta.tableName : meta.className;
708
+ prop.joinColumns = prop.referencedColumnNames.map(name => this.#namingStrategy.joinKeyColumnName(baseName + '_1', name, meta.compositePK));
709
+ prop.inverseJoinColumns = prop.referencedColumnNames.map(name => this.#namingStrategy.joinKeyColumnName(baseName + '_2', name, meta.compositePK));
710
+ if (prop.inversedBy) {
711
+ const prop2 = targetMeta.properties[prop.inversedBy];
712
+ prop2.inverseJoinColumns = prop.joinColumns;
713
+ prop2.joinColumns = prop.inverseJoinColumns;
714
+ }
715
+ // propagate updated joinColumns to all child entities that inherit this property (STI)
716
+ for (const childMeta of this.#discovered.filter(m => m.root === meta && m !== meta)) {
717
+ const childProp = childMeta.properties[prop.name];
718
+ if (childProp) {
719
+ childProp.joinColumns = prop.joinColumns;
720
+ childProp.inverseJoinColumns = prop.inverseJoinColumns;
721
+ }
722
+ }
723
+ }
724
+ // For polymorphic M:N, create discriminator column and polymorphic FK
725
+ if (prop.polymorphic && prop.discriminatorColumn) {
726
+ this.definePolymorphicPivotProperties(pivotMeta2, meta, prop, targetMeta);
727
+ }
728
+ else {
729
+ pivotMeta2.properties[meta.name + '_owner'] = this.definePivotProperty(prop, meta.name + '_owner', meta.class, targetType + '_inverse', true, meta.className === targetType);
730
+ pivotMeta2.properties[targetType + '_inverse'] = this.definePivotProperty(prop, targetType + '_inverse', targetMeta.class, meta.name + '_owner', false, meta.className === targetType);
731
+ }
732
+ return this.#metadata.set(pivotMeta2.class, EntitySchema.fromMetadata(pivotMeta2).init().meta);
733
+ }
734
+ /**
735
+ * Create a scalar property for a pivot table column.
736
+ */
737
+ createPivotScalarProperty(name, columnTypes, fieldNames = [name], options = {}) {
738
+ return {
739
+ name,
740
+ fieldNames,
741
+ columnTypes,
742
+ type: options.type ?? 'number',
743
+ kind: ReferenceKind.SCALAR,
744
+ primary: options.primary ?? false,
745
+ nullable: options.nullable ?? true,
746
+ ...(options.persist !== undefined && { persist: options.persist }),
747
+ };
748
+ }
749
+ /**
750
+ * Get column types for an entity's primary keys, initializing them if needed.
751
+ */
752
+ getPrimaryKeyColumnTypes(meta) {
753
+ const columnTypes = [];
754
+ for (const pk of meta.primaryKeys) {
755
+ const pkProp = meta.properties[pk];
756
+ this.initCustomType(meta, pkProp);
757
+ this.initColumnType(pkProp);
758
+ columnTypes.push(...pkProp.columnTypes);
759
+ }
760
+ return columnTypes;
761
+ }
762
+ /**
763
+ * Add missing FK columns for a polymorphic entity to an existing pivot table.
764
+ */
765
+ addPolymorphicPivotColumns(pivotMeta, meta, prop) {
766
+ const existingFieldNames = new Set(Object.values(pivotMeta.properties).flatMap(p => p.fieldNames ?? []));
767
+ const columnTypes = this.getPrimaryKeyColumnTypes(meta);
768
+ for (let i = 0; i < prop.joinColumns.length; i++) {
769
+ const joinColumn = prop.joinColumns[i];
770
+ if (!existingFieldNames.has(joinColumn)) {
771
+ pivotMeta.properties[joinColumn] = this.createPivotScalarProperty(joinColumn, [columnTypes[i]]);
772
+ }
773
+ }
774
+ }
775
+ /**
776
+ * Define properties for a polymorphic pivot table.
777
+ */
778
+ definePolymorphicPivotProperties(pivotMeta, meta, prop, targetMeta) {
779
+ const discriminatorColumn = prop.discriminatorColumn;
780
+ const isCompositePK = meta.compositePK;
781
+ // For composite PK polymorphic M:N, we need fixedOrder (auto-increment PK)
782
+ if (isCompositePK && !prop.fixedOrder) {
783
+ prop.fixedOrder = true;
784
+ const primaryProp = this.defineFixedOrderProperty(prop, targetMeta);
785
+ pivotMeta.properties[primaryProp.name] = primaryProp;
786
+ pivotMeta.compositePK = false;
787
+ }
788
+ const discriminatorProp = this.createPivotScalarProperty(discriminatorColumn, [this.#platform.getVarcharTypeDeclarationSQL(prop)], [discriminatorColumn], { type: 'string', primary: !isCompositePK, nullable: false });
789
+ this.initFieldName(discriminatorProp);
790
+ pivotMeta.properties[discriminatorColumn] = discriminatorProp;
791
+ const columnTypes = this.getPrimaryKeyColumnTypes(meta);
792
+ if (isCompositePK) {
793
+ // Create separate properties for each PK column (nullable for other entity types)
794
+ for (let i = 0; i < prop.joinColumns.length; i++) {
795
+ pivotMeta.properties[prop.joinColumns[i]] = this.createPivotScalarProperty(prop.joinColumns[i], [
796
+ columnTypes[i],
797
+ ]);
798
+ }
799
+ // Virtual property combining all columns (for compatibility)
800
+ pivotMeta.properties[prop.discriminator] = this.createPivotScalarProperty(prop.discriminator, columnTypes, [...prop.joinColumns], { type: meta.className, persist: false });
801
+ }
802
+ else {
803
+ pivotMeta.properties[prop.discriminator] = this.createPivotScalarProperty(prop.discriminator, columnTypes, [...prop.joinColumns], { type: meta.className, primary: true, nullable: false });
804
+ }
805
+ pivotMeta.properties[targetMeta.className + '_inverse'] = this.definePivotProperty(prop, targetMeta.className + '_inverse', targetMeta.class, prop.discriminator, false, false);
806
+ // Create virtual M:1 relation to the polymorphic owner for single-query join loading
807
+ const ownerRelationName = `${prop.discriminator}_${meta.tableName}`;
808
+ pivotMeta.properties[ownerRelationName] = this.definePolymorphicOwnerRelation(prop, ownerRelationName, meta);
692
809
  pivotMeta.polymorphicDiscriminatorMap ??= {};
693
810
  pivotMeta.polymorphicDiscriminatorMap[prop.discriminatorValue] = meta.class;
694
- // For composite PK entities sharing a polymorphic pivot table,
695
- // we need to add columns for each entity type's PKs
696
- this.addPolymorphicPivotColumns(pivotMeta, meta, prop);
697
- // Add virtual M:1 relation for this polymorphic owner (for join loading)
698
- const ownerRelationName = `${prop.discriminator}_${meta.tableName}`;
699
- if (!pivotMeta.properties[ownerRelationName]) {
700
- pivotMeta.properties[ownerRelationName] = this.definePolymorphicOwnerRelation(prop, ownerRelationName, meta);
701
- }
702
- }
703
- return pivotMeta;
704
- }
705
- let tableName = prop.pivotTable;
706
- let schemaName;
707
- if (prop.pivotTable.includes('.')) {
708
- [schemaName, tableName] = prop.pivotTable.split('.');
709
- }
710
- schemaName ??= meta.schema;
711
- const targetMeta = prop.targetMeta;
712
- const targetType = targetMeta.className;
713
- const pivotMeta2 = new EntityMetadata({
714
- name: prop.pivotTable,
715
- className: prop.pivotTable,
716
- collection: tableName,
717
- schema: schemaName,
718
- pivotTable: true,
719
- });
720
- prop.pivotEntity = pivotMeta2.class;
721
- if (prop.fixedOrder) {
722
- const primaryProp = this.defineFixedOrderProperty(prop, targetMeta);
723
- pivotMeta2.properties[primaryProp.name] = primaryProp;
724
- } else {
725
- pivotMeta2.compositePK = true;
726
- }
727
- // handle self-referenced m:n with same default field names
728
- if (
729
- meta.className === targetType &&
730
- prop.joinColumns.every((joinColumn, idx) => joinColumn === prop.inverseJoinColumns[idx])
731
- ) {
732
- // use tableName only when explicitly provided by user, otherwise use className for backwards compatibility
733
- const baseName = this.isExplicitTableName(meta) ? meta.tableName : meta.className;
734
- prop.joinColumns = prop.referencedColumnNames.map(name =>
735
- this.#namingStrategy.joinKeyColumnName(baseName + '_1', name, meta.compositePK),
736
- );
737
- prop.inverseJoinColumns = prop.referencedColumnNames.map(name =>
738
- this.#namingStrategy.joinKeyColumnName(baseName + '_2', name, meta.compositePK),
739
- );
740
- if (prop.inversedBy) {
741
- const prop2 = targetMeta.properties[prop.inversedBy];
742
- prop2.inverseJoinColumns = prop.joinColumns;
743
- prop2.joinColumns = prop.inverseJoinColumns;
744
- }
745
- // propagate updated joinColumns to all child entities that inherit this property (STI)
746
- for (const childMeta of this.#discovered.filter(m => m.root === meta && m !== meta)) {
747
- const childProp = childMeta.properties[prop.name];
748
- if (childProp) {
749
- childProp.joinColumns = prop.joinColumns;
750
- childProp.inverseJoinColumns = prop.inverseJoinColumns;
751
- }
752
- }
753
- }
754
- // For polymorphic M:N, create discriminator column and polymorphic FK
755
- if (prop.polymorphic && prop.discriminatorColumn) {
756
- this.definePolymorphicPivotProperties(pivotMeta2, meta, prop, targetMeta);
757
- } else {
758
- pivotMeta2.properties[meta.name + '_owner'] = this.definePivotProperty(
759
- prop,
760
- meta.name + '_owner',
761
- meta.class,
762
- targetType + '_inverse',
763
- true,
764
- meta.className === targetType,
765
- );
766
- pivotMeta2.properties[targetType + '_inverse'] = this.definePivotProperty(
767
- prop,
768
- targetType + '_inverse',
769
- targetMeta.class,
770
- meta.name + '_owner',
771
- false,
772
- meta.className === targetType,
773
- );
774
- }
775
- return this.#metadata.set(pivotMeta2.class, EntitySchema.fromMetadata(pivotMeta2).init().meta);
776
- }
777
- /**
778
- * Create a scalar property for a pivot table column.
779
- */
780
- createPivotScalarProperty(name, columnTypes, fieldNames = [name], options = {}) {
781
- return {
782
- name,
783
- fieldNames,
784
- columnTypes,
785
- type: options.type ?? 'number',
786
- kind: ReferenceKind.SCALAR,
787
- primary: options.primary ?? false,
788
- nullable: options.nullable ?? true,
789
- ...(options.persist !== undefined && { persist: options.persist }),
790
- };
791
- }
792
- /**
793
- * Get column types for an entity's primary keys, initializing them if needed.
794
- */
795
- getPrimaryKeyColumnTypes(meta) {
796
- const columnTypes = [];
797
- for (const pk of meta.primaryKeys) {
798
- const pkProp = meta.properties[pk];
799
- this.initCustomType(meta, pkProp);
800
- this.initColumnType(pkProp);
801
- columnTypes.push(...pkProp.columnTypes);
802
- }
803
- return columnTypes;
804
- }
805
- /**
806
- * Add missing FK columns for a polymorphic entity to an existing pivot table.
807
- */
808
- addPolymorphicPivotColumns(pivotMeta, meta, prop) {
809
- const existingFieldNames = new Set(Object.values(pivotMeta.properties).flatMap(p => p.fieldNames ?? []));
810
- const columnTypes = this.getPrimaryKeyColumnTypes(meta);
811
- for (let i = 0; i < prop.joinColumns.length; i++) {
812
- const joinColumn = prop.joinColumns[i];
813
- if (!existingFieldNames.has(joinColumn)) {
814
- pivotMeta.properties[joinColumn] = this.createPivotScalarProperty(joinColumn, [columnTypes[i]]);
815
- }
816
- }
817
- }
818
- /**
819
- * Define properties for a polymorphic pivot table.
820
- */
821
- definePolymorphicPivotProperties(pivotMeta, meta, prop, targetMeta) {
822
- const discriminatorColumn = prop.discriminatorColumn;
823
- const isCompositePK = meta.compositePK;
824
- // For composite PK polymorphic M:N, we need fixedOrder (auto-increment PK)
825
- if (isCompositePK && !prop.fixedOrder) {
826
- prop.fixedOrder = true;
827
- const primaryProp = this.defineFixedOrderProperty(prop, targetMeta);
828
- pivotMeta.properties[primaryProp.name] = primaryProp;
829
- pivotMeta.compositePK = false;
830
- }
831
- const discriminatorProp = this.createPivotScalarProperty(
832
- discriminatorColumn,
833
- [this.#platform.getVarcharTypeDeclarationSQL(prop)],
834
- [discriminatorColumn],
835
- { type: 'string', primary: !isCompositePK, nullable: false },
836
- );
837
- this.initFieldName(discriminatorProp);
838
- pivotMeta.properties[discriminatorColumn] = discriminatorProp;
839
- const columnTypes = this.getPrimaryKeyColumnTypes(meta);
840
- if (isCompositePK) {
841
- // Create separate properties for each PK column (nullable for other entity types)
842
- for (let i = 0; i < prop.joinColumns.length; i++) {
843
- pivotMeta.properties[prop.joinColumns[i]] = this.createPivotScalarProperty(prop.joinColumns[i], [
844
- columnTypes[i],
845
- ]);
846
- }
847
- // Virtual property combining all columns (for compatibility)
848
- pivotMeta.properties[prop.discriminator] = this.createPivotScalarProperty(
849
- prop.discriminator,
850
- columnTypes,
851
- [...prop.joinColumns],
852
- { type: meta.className, persist: false },
853
- );
854
- } else {
855
- pivotMeta.properties[prop.discriminator] = this.createPivotScalarProperty(
856
- prop.discriminator,
857
- columnTypes,
858
- [...prop.joinColumns],
859
- { type: meta.className, primary: true, nullable: false },
860
- );
861
- }
862
- pivotMeta.properties[targetMeta.className + '_inverse'] = this.definePivotProperty(
863
- prop,
864
- targetMeta.className + '_inverse',
865
- targetMeta.class,
866
- prop.discriminator,
867
- false,
868
- false,
869
- );
870
- // Create virtual M:1 relation to the polymorphic owner for single-query join loading
871
- const ownerRelationName = `${prop.discriminator}_${meta.tableName}`;
872
- pivotMeta.properties[ownerRelationName] = this.definePolymorphicOwnerRelation(prop, ownerRelationName, meta);
873
- pivotMeta.polymorphicDiscriminatorMap ??= {};
874
- pivotMeta.polymorphicDiscriminatorMap[prop.discriminatorValue] = meta.class;
875
- }
876
- /**
877
- * Create a virtual M:1 relation from pivot to a polymorphic owner entity.
878
- * This enables single-query join loading for inverse-side polymorphic M:N.
879
- */
880
- definePolymorphicOwnerRelation(prop, name, targetMeta) {
881
- const ret = {
882
- name,
883
- type: targetMeta.className,
884
- target: targetMeta.class,
885
- kind: ReferenceKind.MANY_TO_ONE,
886
- nullable: true,
887
- owner: true,
888
- primary: false,
889
- createForeignKeyConstraint: false,
890
- persist: false,
891
- index: false,
892
- };
893
- ret.targetMeta = targetMeta;
894
- ret.fieldNames = ret.joinColumns = ret.ownColumns = [...prop.joinColumns];
895
- ret.referencedColumnNames = [];
896
- ret.inverseJoinColumns = [];
897
- for (const primaryKey of targetMeta.primaryKeys) {
898
- const pkProp = targetMeta.properties[primaryKey];
899
- ret.referencedColumnNames.push(...pkProp.fieldNames);
900
- ret.inverseJoinColumns.push(...pkProp.fieldNames);
901
- ret.length = pkProp.length;
902
- ret.precision = pkProp.precision;
903
- ret.scale = pkProp.scale;
904
- }
905
- const schema = targetMeta.schema ?? this.#config.get('schema') ?? this.#platform.getDefaultSchemaName();
906
- ret.referencedTableName = schema && schema !== '*' ? schema + '.' + targetMeta.tableName : targetMeta.tableName;
907
- this.initColumnType(ret);
908
- this.initRelation(ret);
909
- return ret;
910
- }
911
- defineFixedOrderProperty(prop, targetMeta) {
912
- const pk = prop.fixedOrderColumn || this.#namingStrategy.referenceColumnName();
913
- const primaryProp = {
914
- name: pk,
915
- type: 'number',
916
- runtimeType: 'number',
917
- kind: ReferenceKind.SCALAR,
918
- primary: true,
919
- autoincrement: true,
920
- unsigned: this.#platform.supportsUnsigned(),
921
- };
922
- this.initFieldName(primaryProp);
923
- this.initColumnType(primaryProp);
924
- prop.fixedOrderColumn = pk;
925
- if (prop.inversedBy) {
926
- const prop2 = targetMeta.properties[prop.inversedBy];
927
- prop2.fixedOrder = true;
928
- prop2.fixedOrderColumn = pk;
929
- }
930
- return primaryProp;
931
- }
932
- definePivotProperty(prop, name, type, inverse, owner, selfReferencing) {
933
- const ret = {
934
- name,
935
- type: Utils.className(type),
936
- target: type,
937
- kind: ReferenceKind.MANY_TO_ONE,
938
- cascade: [Cascade.ALL],
939
- fixedOrder: prop.fixedOrder,
940
- fixedOrderColumn: prop.fixedOrderColumn,
941
- index: this.#platform.indexForeignKeys(),
942
- primary: !prop.fixedOrder,
943
- autoincrement: false,
944
- updateRule: prop.updateRule,
945
- deleteRule: prop.deleteRule,
946
- createForeignKeyConstraint: prop.createForeignKeyConstraint,
947
- };
948
- const defaultRule = selfReferencing && !this.#platform.supportsMultipleCascadePaths() ? 'no action' : 'cascade';
949
- ret.updateRule ??= defaultRule;
950
- ret.deleteRule ??= defaultRule;
951
- const meta = this.#metadata.get(type);
952
- ret.targetMeta = meta;
953
- ret.joinColumns = [];
954
- ret.inverseJoinColumns = [];
955
- const schema = meta.schema ?? this.#config.get('schema') ?? this.#platform.getDefaultSchemaName();
956
- ret.referencedTableName = schema && schema !== '*' ? schema + '.' + meta.tableName : meta.tableName;
957
- if (owner) {
958
- ret.owner = true;
959
- ret.inversedBy = inverse;
960
- ret.referencedColumnNames = prop.referencedColumnNames;
961
- ret.fieldNames = ret.joinColumns = prop.joinColumns;
962
- ret.inverseJoinColumns = prop.referencedColumnNames;
963
- meta.primaryKeys.forEach(primaryKey => {
964
- const prop2 = meta.properties[primaryKey];
965
- ret.length = prop2.length;
966
- ret.precision = prop2.precision;
967
- ret.scale = prop2.scale;
968
- });
969
- } else {
970
- ret.owner = false;
971
- ret.mappedBy = inverse;
972
- ret.fieldNames = ret.joinColumns = prop.inverseJoinColumns;
973
- ret.referencedColumnNames = [];
974
- ret.inverseJoinColumns = [];
975
- meta.primaryKeys.forEach(primaryKey => {
976
- const prop2 = meta.properties[primaryKey];
977
- ret.referencedColumnNames.push(...prop2.fieldNames);
978
- ret.inverseJoinColumns.push(...prop2.fieldNames);
979
- ret.length = prop2.length;
980
- ret.precision = prop2.precision;
981
- ret.scale = prop2.scale;
982
- });
983
- }
984
- this.initColumnType(ret);
985
- this.initRelation(ret);
986
- return ret;
987
- }
988
- autoWireBidirectionalProperties(meta) {
989
- Object.values(meta.properties)
990
- .filter(prop => prop.kind !== ReferenceKind.SCALAR && !prop.owner && prop.mappedBy)
991
- .forEach(prop => {
992
- const meta2 = prop.targetMeta;
993
- const prop2 = meta2.properties[prop.mappedBy];
994
- if (prop2 && !prop2.inversedBy) {
995
- prop2.inversedBy = prop.name;
996
- }
997
- });
998
- }
999
- defineBaseEntityProperties(meta) {
1000
- const base = meta.extends && this.#metadata.get(meta.extends);
1001
- if (!base || base === meta) {
1002
- // make sure we do not fall into infinite loop
1003
- return 0;
1004
- }
1005
- let order = this.defineBaseEntityProperties(base);
1006
- const ownProps = Object.values(meta.properties);
1007
- const old = ownProps.map(x => x.name);
1008
- meta.properties = {};
1009
- Object.values(base.properties).forEach(prop => {
1010
- if (!prop.inherited) {
1011
- meta.properties[prop.name] = prop;
1012
- }
1013
- });
1014
- ownProps.forEach(prop => (meta.properties[prop.name] = prop));
1015
- meta.filters = { ...base.filters, ...meta.filters };
1016
- if (!meta.discriminatorValue) {
1017
- Object.values(base.properties)
1018
- .filter(prop => !old.includes(prop.name))
1019
- .forEach(prop => {
1020
- meta.properties[prop.name] = { ...prop };
1021
- meta.propertyOrder.set(prop.name, (order += 0.01));
811
+ }
812
+ /**
813
+ * Create a virtual M:1 relation from pivot to a polymorphic owner entity.
814
+ * This enables single-query join loading for inverse-side polymorphic M:N.
815
+ */
816
+ definePolymorphicOwnerRelation(prop, name, targetMeta) {
817
+ const ret = {
818
+ name,
819
+ type: targetMeta.className,
820
+ target: targetMeta.class,
821
+ kind: ReferenceKind.MANY_TO_ONE,
822
+ nullable: true,
823
+ owner: true,
824
+ primary: false,
825
+ createForeignKeyConstraint: false,
826
+ persist: false,
827
+ index: false,
828
+ };
829
+ ret.targetMeta = targetMeta;
830
+ ret.fieldNames = ret.joinColumns = ret.ownColumns = [...prop.joinColumns];
831
+ ret.referencedColumnNames = [];
832
+ ret.inverseJoinColumns = [];
833
+ for (const primaryKey of targetMeta.primaryKeys) {
834
+ const pkProp = targetMeta.properties[primaryKey];
835
+ ret.referencedColumnNames.push(...pkProp.fieldNames);
836
+ ret.inverseJoinColumns.push(...pkProp.fieldNames);
837
+ ret.length = pkProp.length;
838
+ ret.precision = pkProp.precision;
839
+ ret.scale = pkProp.scale;
840
+ }
841
+ const schema = targetMeta.schema ?? this.#config.get('schema') ?? this.#platform.getDefaultSchemaName();
842
+ ret.referencedTableName = schema && schema !== '*' ? schema + '.' + targetMeta.tableName : targetMeta.tableName;
843
+ this.initColumnType(ret);
844
+ this.initRelation(ret);
845
+ return ret;
846
+ }
847
+ defineFixedOrderProperty(prop, targetMeta) {
848
+ const pk = prop.fixedOrderColumn || this.#namingStrategy.referenceColumnName();
849
+ const primaryProp = {
850
+ name: pk,
851
+ type: 'number',
852
+ runtimeType: 'number',
853
+ kind: ReferenceKind.SCALAR,
854
+ primary: true,
855
+ autoincrement: true,
856
+ unsigned: this.#platform.supportsUnsigned(),
857
+ };
858
+ this.initFieldName(primaryProp);
859
+ this.initColumnType(primaryProp);
860
+ prop.fixedOrderColumn = pk;
861
+ if (prop.inversedBy) {
862
+ const prop2 = targetMeta.properties[prop.inversedBy];
863
+ prop2.fixedOrder = true;
864
+ prop2.fixedOrderColumn = pk;
865
+ }
866
+ return primaryProp;
867
+ }
868
+ definePivotProperty(prop, name, type, inverse, owner, selfReferencing) {
869
+ const ret = {
870
+ name,
871
+ type: Utils.className(type),
872
+ target: type,
873
+ kind: ReferenceKind.MANY_TO_ONE,
874
+ cascade: [Cascade.ALL],
875
+ fixedOrder: prop.fixedOrder,
876
+ fixedOrderColumn: prop.fixedOrderColumn,
877
+ index: this.#platform.indexForeignKeys(),
878
+ primary: !prop.fixedOrder,
879
+ autoincrement: false,
880
+ updateRule: prop.updateRule,
881
+ deleteRule: prop.deleteRule,
882
+ createForeignKeyConstraint: prop.createForeignKeyConstraint,
883
+ };
884
+ const defaultRule = selfReferencing && !this.#platform.supportsMultipleCascadePaths() ? 'no action' : 'cascade';
885
+ ret.updateRule ??= defaultRule;
886
+ ret.deleteRule ??= defaultRule;
887
+ const meta = this.#metadata.get(type);
888
+ ret.targetMeta = meta;
889
+ ret.joinColumns = [];
890
+ ret.inverseJoinColumns = [];
891
+ const schema = meta.schema ?? this.#config.get('schema') ?? this.#platform.getDefaultSchemaName();
892
+ ret.referencedTableName = schema && schema !== '*' ? schema + '.' + meta.tableName : meta.tableName;
893
+ if (owner) {
894
+ ret.owner = true;
895
+ ret.inversedBy = inverse;
896
+ ret.referencedColumnNames = prop.referencedColumnNames;
897
+ ret.fieldNames = ret.joinColumns = prop.joinColumns;
898
+ ret.inverseJoinColumns = prop.referencedColumnNames;
899
+ meta.primaryKeys.forEach(primaryKey => {
900
+ const prop2 = meta.properties[primaryKey];
901
+ ret.length = prop2.length;
902
+ ret.precision = prop2.precision;
903
+ ret.scale = prop2.scale;
904
+ });
905
+ }
906
+ else {
907
+ ret.owner = false;
908
+ ret.mappedBy = inverse;
909
+ ret.fieldNames = ret.joinColumns = prop.inverseJoinColumns;
910
+ ret.referencedColumnNames = [];
911
+ ret.inverseJoinColumns = [];
912
+ meta.primaryKeys.forEach(primaryKey => {
913
+ const prop2 = meta.properties[primaryKey];
914
+ ret.referencedColumnNames.push(...prop2.fieldNames);
915
+ ret.inverseJoinColumns.push(...prop2.fieldNames);
916
+ ret.length = prop2.length;
917
+ ret.precision = prop2.precision;
918
+ ret.scale = prop2.scale;
919
+ });
920
+ }
921
+ this.initColumnType(ret);
922
+ this.initRelation(ret);
923
+ return ret;
924
+ }
925
+ autoWireBidirectionalProperties(meta) {
926
+ Object.values(meta.properties)
927
+ .filter(prop => prop.kind !== ReferenceKind.SCALAR && !prop.owner && prop.mappedBy)
928
+ .forEach(prop => {
929
+ const meta2 = prop.targetMeta;
930
+ const prop2 = meta2.properties[prop.mappedBy];
931
+ if (prop2 && !prop2.inversedBy) {
932
+ prop2.inversedBy = prop.name;
933
+ }
934
+ });
935
+ }
936
+ defineBaseEntityProperties(meta) {
937
+ const base = meta.extends && this.#metadata.get(meta.extends);
938
+ if (!base || base === meta) {
939
+ // make sure we do not fall into infinite loop
940
+ return 0;
941
+ }
942
+ let order = this.defineBaseEntityProperties(base);
943
+ const ownProps = Object.values(meta.properties);
944
+ const old = ownProps.map(x => x.name);
945
+ meta.properties = {};
946
+ Object.values(base.properties).forEach(prop => {
947
+ if (!prop.inherited) {
948
+ meta.properties[prop.name] = prop;
949
+ }
1022
950
  });
951
+ ownProps.forEach(prop => (meta.properties[prop.name] = prop));
952
+ meta.filters = { ...base.filters, ...meta.filters };
953
+ if (!meta.discriminatorValue) {
954
+ Object.values(base.properties)
955
+ .filter(prop => !old.includes(prop.name))
956
+ .forEach(prop => {
957
+ meta.properties[prop.name] = { ...prop };
958
+ meta.propertyOrder.set(prop.name, (order += 0.01));
959
+ });
960
+ }
961
+ meta.indexes = Utils.unique([...base.indexes, ...meta.indexes]);
962
+ meta.uniques = Utils.unique([...base.uniques, ...meta.uniques]);
963
+ meta.checks = Utils.unique([...base.checks, ...meta.checks]);
964
+ const pks = Object.values(meta.properties)
965
+ .filter(p => p.primary)
966
+ .map(p => p.name);
967
+ if (pks.length > 0 && meta.primaryKeys.length === 0) {
968
+ meta.primaryKeys = pks;
969
+ }
970
+ Utils.keys(base.hooks).forEach(type => {
971
+ meta.hooks[type] = Utils.unique([...base.hooks[type], ...(meta.hooks[type] || [])]);
972
+ });
973
+ if ((meta.constructorParams?.length ?? 0) === 0 && (base.constructorParams?.length ?? 0) > 0) {
974
+ meta.constructorParams = [...base.constructorParams];
975
+ }
976
+ return order;
977
+ }
978
+ initPolyEmbeddables(embeddedProp, discovered, visited = new Set()) {
979
+ if (embeddedProp.kind !== ReferenceKind.EMBEDDED || visited.has(embeddedProp)) {
980
+ return;
981
+ }
982
+ visited.add(embeddedProp);
983
+ const types = embeddedProp.type.split(/ ?\| ?/);
984
+ let embeddable = this.#discovered.find(m => m.name === embeddedProp.type);
985
+ const polymorphs = this.#discovered.filter(m => types.includes(m.name));
986
+ // create virtual polymorphic entity
987
+ if (!embeddable && polymorphs.length > 0) {
988
+ const properties = {};
989
+ let discriminatorColumn;
990
+ const inlineProperties = (meta) => {
991
+ Object.values(meta.properties).forEach(prop => {
992
+ // defaults on db level would mess up with change tracking
993
+ delete prop.default;
994
+ if (properties[prop.name] && properties[prop.name].type !== prop.type) {
995
+ properties[prop.name].type = `${properties[prop.name].type} | ${prop.type}`;
996
+ properties[prop.name].runtimeType = 'any';
997
+ properties[prop.name].stiMerged = true;
998
+ return properties[prop.name];
999
+ }
1000
+ // Deep copy to prevent mutating the original entity's property —
1001
+ // both from the merge path above (GH #6522/#6523) and from
1002
+ // downstream code that mutates nested arrays like fieldNames.
1003
+ return (properties[prop.name] = Utils.copy(prop));
1004
+ });
1005
+ };
1006
+ const processExtensions = (meta) => {
1007
+ const parent = this.#discovered.find(m => {
1008
+ return meta.extends && Utils.className(meta.extends) === m.className;
1009
+ });
1010
+ if (!parent) {
1011
+ return;
1012
+ }
1013
+ discriminatorColumn ??= parent.discriminatorColumn;
1014
+ inlineProperties(parent);
1015
+ processExtensions(parent);
1016
+ };
1017
+ polymorphs.forEach(meta => {
1018
+ inlineProperties(meta);
1019
+ processExtensions(meta);
1020
+ });
1021
+ const name = polymorphs
1022
+ .map(t => t.className)
1023
+ .sort()
1024
+ .join(' | ');
1025
+ embeddable = new EntityMetadata({
1026
+ name,
1027
+ className: name,
1028
+ embeddable: true,
1029
+ abstract: true,
1030
+ properties,
1031
+ polymorphs,
1032
+ discriminatorColumn,
1033
+ });
1034
+ embeddable.sync();
1035
+ discovered.push(embeddable);
1036
+ polymorphs.forEach(meta => (meta.root = embeddable));
1037
+ }
1038
+ }
1039
+ initPolymorphicRelation(meta, prop, discovered) {
1040
+ if (!prop.discriminator && !prop.discriminatorColumn && !prop.discriminatorMap && !Array.isArray(prop.target)) {
1041
+ return;
1042
+ }
1043
+ prop.polymorphic = true;
1044
+ prop.discriminator ??= prop.name;
1045
+ prop.discriminatorColumn ??= this.#namingStrategy.discriminatorColumnName(prop.discriminator);
1046
+ prop.createForeignKeyConstraint = false;
1047
+ const isToOne = [ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(prop.kind);
1048
+ if (isToOne) {
1049
+ const types = prop.type.split(/ ?\| ?/);
1050
+ prop.polymorphTargets = discovered.filter(m => types.includes(m.className) && !m.embeddable);
1051
+ prop.targetMeta = prop.polymorphTargets[0];
1052
+ prop.referencedPKs = prop.targetMeta?.primaryKeys;
1053
+ }
1054
+ if (prop.discriminatorMap) {
1055
+ const normalizedMap = {};
1056
+ for (const [key, value] of Object.entries(prop.discriminatorMap)) {
1057
+ const targetMeta = this.#metadata.getByClassName(value, false);
1058
+ if (!targetMeta) {
1059
+ throw MetadataError.fromUnknownEntity(value, `${meta.className}.${prop.name} discriminatorMap`);
1060
+ }
1061
+ normalizedMap[key] = targetMeta.class;
1062
+ if (targetMeta.class === meta.class) {
1063
+ prop.discriminatorValue = key;
1064
+ }
1065
+ }
1066
+ prop.discriminatorMap = normalizedMap;
1067
+ }
1068
+ else if (isToOne) {
1069
+ prop.discriminatorMap = {};
1070
+ const tableNameToTarget = new Map();
1071
+ for (const target of prop.polymorphTargets) {
1072
+ const existing = tableNameToTarget.get(target.tableName);
1073
+ if (existing) {
1074
+ throw MetadataError.incompatiblePolymorphicTargets(meta, prop, existing, target, `both use table '${target.tableName}'. Use separate properties instead of a single polymorphic relation.`);
1075
+ }
1076
+ tableNameToTarget.set(target.tableName, target);
1077
+ prop.discriminatorMap[target.tableName] = target.class;
1078
+ }
1079
+ }
1080
+ else {
1081
+ prop.discriminatorValue ??= meta.tableName;
1082
+ if (!prop.discriminatorMap) {
1083
+ prop.discriminatorMap = { [prop.discriminatorValue]: meta.class };
1084
+ }
1085
+ }
1086
+ }
1087
+ initEmbeddables(meta, embeddedProp, visited = new Set()) {
1088
+ if (embeddedProp.kind !== ReferenceKind.EMBEDDED || visited.has(embeddedProp)) {
1089
+ return;
1090
+ }
1091
+ visited.add(embeddedProp);
1092
+ const embeddable = this.#discovered.find(m => m.name === embeddedProp.type);
1093
+ if (!embeddable) {
1094
+ throw MetadataError.fromUnknownEntity(embeddedProp.type, `${meta.className}.${embeddedProp.name}`);
1095
+ }
1096
+ embeddedProp.embeddable = embeddable.class;
1097
+ embeddedProp.embeddedProps = {};
1098
+ let order = meta.propertyOrder.get(embeddedProp.name);
1099
+ const getRootProperty = (prop) => prop.embedded ? getRootProperty(meta.properties[prop.embedded[0]]) : prop;
1100
+ const isParentObject = (prop) => {
1101
+ if (prop.object || prop.array) {
1102
+ return true;
1103
+ }
1104
+ return prop.embedded ? isParentObject(meta.properties[prop.embedded[0]]) : false;
1105
+ };
1106
+ const isParentArray = (prop) => {
1107
+ if (prop.array) {
1108
+ return true;
1109
+ }
1110
+ return prop.embedded ? isParentArray(meta.properties[prop.embedded[0]]) : false;
1111
+ };
1112
+ const rootProperty = getRootProperty(embeddedProp);
1113
+ const parentProperty = meta.properties[embeddedProp.embedded?.[0] ?? ''];
1114
+ const object = isParentObject(embeddedProp);
1115
+ const array = isParentArray(embeddedProp);
1116
+ this.initFieldName(embeddedProp, rootProperty !== embeddedProp && object);
1117
+ // the prefix of the parent cannot be a boolean; it already passed here
1118
+ const prefix = this.getPrefix(embeddedProp, parentProperty);
1119
+ const glue = object ? '~' : '_';
1120
+ for (const prop of Object.values(embeddable.properties)) {
1121
+ const name = (embeddedProp.embeddedPath?.join(glue) ?? embeddedProp.fieldNames[0] + glue) + prop.name;
1122
+ meta.properties[name] = Utils.copy(prop);
1123
+ meta.properties[name].name = name;
1124
+ meta.properties[name].embedded = [embeddedProp.name, prop.name];
1125
+ meta.propertyOrder.set(name, (order += 0.01));
1126
+ embeddedProp.embeddedProps[prop.name] = meta.properties[name];
1127
+ meta.properties[name].persist ??= embeddedProp.persist;
1128
+ const refInArray = array && [ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(prop.kind) && prop.owner;
1129
+ if (embeddedProp.nullable || refInArray) {
1130
+ meta.properties[name].nullable = true;
1131
+ }
1132
+ if (meta.properties[name].fieldNames) {
1133
+ meta.properties[name].fieldNames[0] = prefix + meta.properties[name].fieldNames[0];
1134
+ }
1135
+ else {
1136
+ const name2 = meta.properties[name].name;
1137
+ meta.properties[name].name = prefix + prop.name;
1138
+ this.initFieldName(meta.properties[name]);
1139
+ meta.properties[name].name = name2;
1140
+ }
1141
+ if (object) {
1142
+ embeddedProp.object = true;
1143
+ let path = [];
1144
+ let tmp = embeddedProp;
1145
+ while (tmp.embedded && tmp.object) {
1146
+ path.unshift(tmp.embedded[1]);
1147
+ tmp = meta.properties[tmp.embedded[0]];
1148
+ }
1149
+ if (tmp === rootProperty) {
1150
+ path.unshift(rootProperty.fieldNames[0]);
1151
+ }
1152
+ else if (embeddedProp.embeddedPath) {
1153
+ path = [...embeddedProp.embeddedPath];
1154
+ }
1155
+ else {
1156
+ path = [embeddedProp.fieldNames[0]];
1157
+ }
1158
+ this.initFieldName(prop, true);
1159
+ this.initRelation(prop);
1160
+ path.push(prop.fieldNames[0]);
1161
+ meta.properties[name].fieldNames = prop.fieldNames;
1162
+ meta.properties[name].embeddedPath = path;
1163
+ const targetProp = prop.targetMeta?.getPrimaryProp() ?? prop;
1164
+ const fieldName = raw(this.#platform.getSearchJsonPropertySQL(path.join('->'), targetProp.runtimeType ?? targetProp.type, true));
1165
+ meta.properties[name].fieldNameRaw = fieldName.sql; // for querying in SQL drivers
1166
+ meta.properties[name].persist = false; // only virtual as we store the whole object
1167
+ meta.properties[name].userDefined = false; // mark this as a generated/internal property, so we can distinguish from user-defined non-persist properties
1168
+ meta.properties[name].object = true;
1169
+ this.initCustomType(meta, meta.properties[name], false, true);
1170
+ }
1171
+ this.initEmbeddables(meta, meta.properties[name], visited);
1172
+ }
1173
+ for (const index of embeddable.indexes) {
1174
+ meta.indexes.push({
1175
+ ...index,
1176
+ properties: Utils.asArray(index.properties).map(p => {
1177
+ return embeddedProp.embeddedProps[p].name;
1178
+ }),
1179
+ });
1180
+ }
1181
+ for (const unique of embeddable.uniques) {
1182
+ meta.uniques.push({
1183
+ ...unique,
1184
+ properties: Utils.asArray(unique.properties).map(p => {
1185
+ return embeddedProp.embeddedProps[p].name;
1186
+ }),
1187
+ });
1188
+ }
1023
1189
  }
1024
- meta.indexes = Utils.unique([...base.indexes, ...meta.indexes]);
1025
- meta.uniques = Utils.unique([...base.uniques, ...meta.uniques]);
1026
- meta.checks = Utils.unique([...base.checks, ...meta.checks]);
1027
- const pks = Object.values(meta.properties)
1028
- .filter(p => p.primary)
1029
- .map(p => p.name);
1030
- if (pks.length > 0 && meta.primaryKeys.length === 0) {
1031
- meta.primaryKeys = pks;
1032
- }
1033
- Utils.keys(base.hooks).forEach(type => {
1034
- meta.hooks[type] = Utils.unique([...base.hooks[type], ...(meta.hooks[type] || [])]);
1035
- });
1036
- if ((meta.constructorParams?.length ?? 0) === 0 && (base.constructorParams?.length ?? 0) > 0) {
1037
- meta.constructorParams = [...base.constructorParams];
1038
- }
1039
- return order;
1040
- }
1041
- initPolyEmbeddables(embeddedProp, discovered, visited = new Set()) {
1042
- if (embeddedProp.kind !== ReferenceKind.EMBEDDED || visited.has(embeddedProp)) {
1043
- return;
1044
- }
1045
- visited.add(embeddedProp);
1046
- const types = embeddedProp.type.split(/ ?\| ?/);
1047
- let embeddable = this.#discovered.find(m => m.name === embeddedProp.type);
1048
- const polymorphs = this.#discovered.filter(m => types.includes(m.name));
1049
- // create virtual polymorphic entity
1050
- if (!embeddable && polymorphs.length > 0) {
1051
- const properties = {};
1052
- let discriminatorColumn;
1053
- const inlineProperties = meta => {
1190
+ initSingleTableInheritance(meta, metadata) {
1191
+ if (meta.root !== meta && !meta.__processed) {
1192
+ meta.root = metadata.find(m => m.class === meta.root.class);
1193
+ meta.root.__processed = true;
1194
+ }
1195
+ else {
1196
+ delete meta.root.__processed;
1197
+ }
1198
+ if (!meta.root.discriminatorColumn) {
1199
+ return;
1200
+ }
1201
+ meta.root.inheritanceType = 'sti';
1202
+ if (meta.root.discriminatorMap) {
1203
+ const map = meta.root.discriminatorMap;
1204
+ Object.keys(map)
1205
+ .filter(key => typeof map[key] === 'string')
1206
+ .forEach(key => (map[key] = this.#metadata.getByClassName(map[key]).class));
1207
+ }
1208
+ else {
1209
+ meta.root.discriminatorMap = {};
1210
+ const children = metadata
1211
+ .filter(m => m.root.class === meta.root.class && !m.abstract)
1212
+ .sort((a, b) => a.className.localeCompare(b.className));
1213
+ for (const m of children) {
1214
+ const name = m.discriminatorValue ?? this.#namingStrategy.classToTableName(m.className);
1215
+ meta.root.discriminatorMap[name] = m.class;
1216
+ }
1217
+ }
1218
+ meta.discriminatorValue = QueryHelper.findDiscriminatorValue(meta.root.discriminatorMap, meta.class);
1219
+ if (!meta.root.properties[meta.root.discriminatorColumn]) {
1220
+ this.createDiscriminatorProperty(meta.root);
1221
+ }
1222
+ Utils.defaultValue(meta.root.properties[meta.root.discriminatorColumn], 'items', Object.keys(meta.root.discriminatorMap));
1223
+ Utils.defaultValue(meta.root.properties[meta.root.discriminatorColumn], 'index', true);
1224
+ if (meta.root === meta) {
1225
+ return;
1226
+ }
1054
1227
  Object.values(meta.properties).forEach(prop => {
1055
- // defaults on db level would mess up with change tracking
1056
- delete prop.default;
1057
- if (properties[prop.name] && properties[prop.name].type !== prop.type) {
1058
- properties[prop.name].type = `${properties[prop.name].type} | ${prop.type}`;
1059
- properties[prop.name].runtimeType = 'any';
1060
- properties[prop.name].stiMerged = true;
1061
- return properties[prop.name];
1062
- }
1063
- // Deep copy to prevent mutating the original entity's property —
1064
- // both from the merge path above (GH #6522/#6523) and from
1065
- // downstream code that mutates nested arrays like fieldNames.
1066
- return (properties[prop.name] = Utils.copy(prop));
1228
+ const newProp = { ...prop };
1229
+ const rootProp = meta.root.properties[prop.name];
1230
+ // stiMerged is set during inlineProperties when a property was merged
1231
+ // from multiple polymorphic variants with different types. The flag is
1232
+ // cleared implicitly when the first child claims the root property via
1233
+ // addProperty below, so subsequent children correctly trigger renaming.
1234
+ const typesMatch = rootProp?.type === prop.type || rootProp?.stiMerged === true;
1235
+ if (rootProp &&
1236
+ (!typesMatch ||
1237
+ (rootProp.fieldNames && prop.fieldNames && !compareArrays(rootProp.fieldNames, prop.fieldNames)))) {
1238
+ const name = newProp.name;
1239
+ this.initFieldName(newProp, newProp.object);
1240
+ newProp.renamedFrom = name;
1241
+ newProp.name = `${name}_${meta._id}`;
1242
+ meta.root.addProperty(newProp);
1243
+ this.initFieldName(prop, prop.object);
1244
+ // Track all field variants and map discriminator values to field names
1245
+ if (!rootProp.stiFieldNames) {
1246
+ this.initFieldName(rootProp, rootProp.object);
1247
+ rootProp.stiFieldNames = [...rootProp.fieldNames];
1248
+ rootProp.stiFieldNameMap = {};
1249
+ // Find which discriminator owns the original fieldNames
1250
+ for (const [discValue, childClass] of Object.entries(meta.root.discriminatorMap)) {
1251
+ const childMeta = this.#metadata.find(childClass);
1252
+ if (childMeta?.properties[prop.name]?.fieldNames &&
1253
+ compareArrays(childMeta.properties[prop.name].fieldNames, rootProp.fieldNames)) {
1254
+ rootProp.stiFieldNameMap[discValue] = rootProp.fieldNames[0];
1255
+ break;
1256
+ }
1257
+ }
1258
+ }
1259
+ rootProp.stiFieldNameMap[meta.discriminatorValue] = prop.fieldNames[0];
1260
+ rootProp.stiFieldNames.push(...prop.fieldNames);
1261
+ newProp.nullable = true;
1262
+ newProp.name = name;
1263
+ newProp.hydrate = false;
1264
+ newProp.inherited = true;
1265
+ return;
1266
+ }
1267
+ if (prop.enum && prop.items && rootProp?.items) {
1268
+ newProp.items = Utils.unique([...rootProp.items, ...prop.items]);
1269
+ }
1270
+ newProp.nullable = true;
1271
+ newProp.inherited = !rootProp;
1272
+ meta.root.addProperty(newProp);
1067
1273
  });
1068
- };
1069
- const processExtensions = meta => {
1070
- const parent = this.#discovered.find(m => {
1071
- return meta.extends && Utils.className(meta.extends) === m.className;
1274
+ meta.tableName = meta.root.tableName;
1275
+ meta.root.indexes = Utils.unique([...meta.root.indexes, ...meta.indexes]);
1276
+ meta.root.uniques = Utils.unique([...meta.root.uniques, ...meta.uniques]);
1277
+ meta.root.checks = Utils.unique([...meta.root.checks, ...meta.checks]);
1278
+ }
1279
+ /**
1280
+ * First pass of TPT initialization: sets up hierarchy relationships
1281
+ * (inheritanceType, tptParent, tptChildren) before properties have fieldNames.
1282
+ */
1283
+ initTPTRelationships(meta, metadata) {
1284
+ if (meta.root !== meta) {
1285
+ meta.root = metadata.find(m => m.class === meta.root.class);
1286
+ }
1287
+ const inheritance = meta.inheritance;
1288
+ if (inheritance === 'tpt' && meta.root === meta) {
1289
+ meta.inheritanceType = 'tpt';
1290
+ meta.tptChildren = [];
1291
+ }
1292
+ if (meta.root.inheritanceType !== 'tpt') {
1293
+ return;
1294
+ }
1295
+ const parent = this.getTPTParent(meta, metadata);
1296
+ if (parent) {
1297
+ meta.tptParent = parent;
1298
+ meta.inheritanceType = 'tpt';
1299
+ parent.tptChildren ??= [];
1300
+ if (!parent.tptChildren.includes(meta)) {
1301
+ parent.tptChildren.push(meta);
1302
+ }
1303
+ }
1304
+ }
1305
+ /**
1306
+ * Second pass of TPT initialization: re-resolves metadata references after fieldNames
1307
+ * are set, syncs to registry metadata, and sets up discriminators.
1308
+ */
1309
+ finalizeTPTInheritance(meta, metadata) {
1310
+ if (meta.inheritanceType !== 'tpt') {
1311
+ return;
1312
+ }
1313
+ if (meta.tptParent) {
1314
+ meta.tptParent = metadata.find(m => m.class === meta.tptParent.class) ?? meta.tptParent;
1315
+ }
1316
+ if (meta.tptChildren) {
1317
+ meta.tptChildren = meta.tptChildren.map(child => metadata.find(m => m.class === child.class) ?? child);
1318
+ }
1319
+ const registryMeta = this.#metadata.get(meta.class);
1320
+ if (registryMeta && registryMeta !== meta) {
1321
+ registryMeta.inheritanceType = meta.inheritanceType;
1322
+ registryMeta.tptParent = meta.tptParent ? this.#metadata.get(meta.tptParent.class) : undefined;
1323
+ registryMeta.tptChildren = meta.tptChildren?.map(child => this.#metadata.get(child.class));
1324
+ }
1325
+ this.initTPTDiscriminator(meta, metadata);
1326
+ }
1327
+ /**
1328
+ * Initialize TPT discriminator map and virtual discriminator property.
1329
+ * Unlike STI where the discriminator is a persisted column, TPT discriminator is computed
1330
+ * at query time using CASE WHEN expressions based on which child table has data.
1331
+ */
1332
+ initTPTDiscriminator(meta, metadata) {
1333
+ const allDescendants = this.collectAllTPTDescendants(meta, metadata);
1334
+ allDescendants.sort((a, b) => this.getTPTDepth(b) - this.getTPTDepth(a));
1335
+ meta.allTPTDescendants = allDescendants;
1336
+ if (meta.root !== meta) {
1337
+ return;
1338
+ }
1339
+ meta.root.discriminatorMap = {};
1340
+ for (const m of allDescendants) {
1341
+ const name = this.#namingStrategy.classToTableName(m.className);
1342
+ meta.root.discriminatorMap[name] = m.class;
1343
+ m.discriminatorValue = name;
1344
+ }
1345
+ if (!meta.abstract) {
1346
+ const name = this.#namingStrategy.classToTableName(meta.className);
1347
+ meta.root.discriminatorMap[name] = meta.class;
1348
+ meta.discriminatorValue = name;
1349
+ }
1350
+ // Virtual discriminator property - computed at query time via CASE WHEN, not persisted
1351
+ const discriminatorColumn = '__tpt_type';
1352
+ if (!meta.root.properties[discriminatorColumn]) {
1353
+ meta.root.addProperty({
1354
+ name: discriminatorColumn,
1355
+ type: 'string',
1356
+ kind: ReferenceKind.SCALAR,
1357
+ persist: false,
1358
+ userDefined: false,
1359
+ hidden: true,
1360
+ });
1361
+ }
1362
+ meta.root.tptDiscriminatorColumn = discriminatorColumn;
1363
+ }
1364
+ /**
1365
+ * Recursively collect all TPT descendants (children, grandchildren, etc.)
1366
+ */
1367
+ collectAllTPTDescendants(meta, metadata) {
1368
+ const descendants = [];
1369
+ const collect = (parent) => {
1370
+ for (const child of parent.tptChildren ?? []) {
1371
+ const resolved = metadata.find(m => m.class === child.class) ?? child;
1372
+ if (!resolved.abstract) {
1373
+ descendants.push(resolved);
1374
+ }
1375
+ collect(resolved);
1376
+ }
1377
+ };
1378
+ collect(meta);
1379
+ return descendants;
1380
+ }
1381
+ /**
1382
+ * Computes ownProps for TPT entities - only properties defined in THIS entity,
1383
+ * not inherited from parent. Also creates synthetic join properties for parent/child relationships.
1384
+ *
1385
+ * Called multiple times during discovery as metadata is progressively built.
1386
+ * Each pass overwrites earlier results to reflect the final state of properties.
1387
+ */
1388
+ computeTPTOwnProps(meta) {
1389
+ if (meta.inheritanceType !== 'tpt') {
1390
+ return;
1391
+ }
1392
+ const belongsToTable = (prop) => prop.persist !== false || prop.primary;
1393
+ // Use meta.properties (object) since meta.props (array) may not be populated yet
1394
+ const allProps = Object.values(meta.properties);
1395
+ if (!meta.tptParent) {
1396
+ meta.ownProps = allProps.filter(belongsToTable);
1397
+ return;
1398
+ }
1399
+ const parentPropNames = new Set(Object.values(meta.tptParent.properties).map(p => p.name));
1400
+ meta.ownProps = allProps.filter(prop => !parentPropNames.has(prop.name) && belongsToTable(prop));
1401
+ // Create synthetic join properties for the parent-child relationship
1402
+ const childFieldNames = meta.getPrimaryProps().flatMap(p => p.fieldNames);
1403
+ const parentFieldNames = meta.tptParent.getPrimaryProps().flatMap(p => p.fieldNames);
1404
+ meta.tptParentProp = {
1405
+ name: '[tpt:parent]',
1406
+ kind: ReferenceKind.MANY_TO_ONE,
1407
+ targetMeta: meta.tptParent,
1408
+ fieldNames: childFieldNames,
1409
+ referencedColumnNames: parentFieldNames,
1410
+ persist: false,
1411
+ };
1412
+ meta.tptInverseProp = {
1413
+ name: '[tpt:child]',
1414
+ kind: ReferenceKind.ONE_TO_ONE,
1415
+ owner: true,
1416
+ targetMeta: meta,
1417
+ fieldNames: parentFieldNames,
1418
+ joinColumns: parentFieldNames,
1419
+ referencedColumnNames: childFieldNames,
1420
+ persist: false,
1421
+ };
1422
+ }
1423
+ /** Returns the depth of a TPT entity in its hierarchy (0 for root). */
1424
+ getTPTDepth(meta) {
1425
+ let depth = 0;
1426
+ let current = meta;
1427
+ while (current.tptParent) {
1428
+ depth++;
1429
+ current = current.tptParent;
1430
+ }
1431
+ return depth;
1432
+ }
1433
+ /**
1434
+ * Find the direct TPT parent entity for the given entity.
1435
+ */
1436
+ getTPTParent(meta, metadata) {
1437
+ if (meta.root === meta) {
1438
+ return undefined;
1439
+ }
1440
+ return metadata.find(m => {
1441
+ const ext = meta.extends;
1442
+ if (EntitySchema.is(ext)) {
1443
+ return m.class === ext.meta.class || m.className === ext.meta.className;
1444
+ }
1445
+ return m.class === ext || m.className === Utils.className(ext);
1072
1446
  });
1073
- if (!parent) {
1074
- return;
1075
- }
1076
- discriminatorColumn ??= parent.discriminatorColumn;
1077
- inlineProperties(parent);
1078
- processExtensions(parent);
1079
- };
1080
- polymorphs.forEach(meta => {
1081
- inlineProperties(meta);
1082
- processExtensions(meta);
1083
- });
1084
- const name = polymorphs
1085
- .map(t => t.className)
1086
- .sort()
1087
- .join(' | ');
1088
- embeddable = new EntityMetadata({
1089
- name,
1090
- className: name,
1091
- embeddable: true,
1092
- abstract: true,
1093
- properties,
1094
- polymorphs,
1095
- discriminatorColumn,
1096
- });
1097
- embeddable.sync();
1098
- discovered.push(embeddable);
1099
- polymorphs.forEach(meta => (meta.root = embeddable));
1100
- }
1101
- }
1102
- initPolymorphicRelation(meta, prop, discovered) {
1103
- if (!prop.discriminator && !prop.discriminatorColumn && !prop.discriminatorMap && !Array.isArray(prop.target)) {
1104
- return;
1105
- }
1106
- prop.polymorphic = true;
1107
- prop.discriminator ??= prop.name;
1108
- prop.discriminatorColumn ??= this.#namingStrategy.discriminatorColumnName(prop.discriminator);
1109
- prop.createForeignKeyConstraint = false;
1110
- const isToOne = [ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(prop.kind);
1111
- if (isToOne) {
1112
- const types = prop.type.split(/ ?\| ?/);
1113
- prop.polymorphTargets = discovered.filter(m => types.includes(m.className) && !m.embeddable);
1114
- prop.targetMeta = prop.polymorphTargets[0];
1115
- prop.referencedPKs = prop.targetMeta?.primaryKeys;
1116
- }
1117
- if (prop.discriminatorMap) {
1118
- const normalizedMap = {};
1119
- for (const [key, value] of Object.entries(prop.discriminatorMap)) {
1120
- const targetMeta = this.#metadata.getByClassName(value, false);
1121
- if (!targetMeta) {
1122
- throw MetadataError.fromUnknownEntity(value, `${meta.className}.${prop.name} discriminatorMap`);
1123
- }
1124
- normalizedMap[key] = targetMeta.class;
1125
- if (targetMeta.class === meta.class) {
1126
- prop.discriminatorValue = key;
1127
- }
1128
- }
1129
- prop.discriminatorMap = normalizedMap;
1130
- } else if (isToOne) {
1131
- prop.discriminatorMap = {};
1132
- const tableNameToTarget = new Map();
1133
- for (const target of prop.polymorphTargets) {
1134
- const existing = tableNameToTarget.get(target.tableName);
1135
- if (existing) {
1136
- throw MetadataError.incompatiblePolymorphicTargets(
1137
- meta,
1138
- prop,
1139
- existing,
1140
- target,
1141
- `both use table '${target.tableName}'. Use separate properties instead of a single polymorphic relation.`,
1142
- );
1143
- }
1144
- tableNameToTarget.set(target.tableName, target);
1145
- prop.discriminatorMap[target.tableName] = target.class;
1146
- }
1147
- } else {
1148
- prop.discriminatorValue ??= meta.tableName;
1149
- if (!prop.discriminatorMap) {
1150
- prop.discriminatorMap = { [prop.discriminatorValue]: meta.class };
1151
- }
1152
- }
1153
- }
1154
- initEmbeddables(meta, embeddedProp, visited = new Set()) {
1155
- if (embeddedProp.kind !== ReferenceKind.EMBEDDED || visited.has(embeddedProp)) {
1156
- return;
1157
- }
1158
- visited.add(embeddedProp);
1159
- const embeddable = this.#discovered.find(m => m.name === embeddedProp.type);
1160
- if (!embeddable) {
1161
- throw MetadataError.fromUnknownEntity(embeddedProp.type, `${meta.className}.${embeddedProp.name}`);
1162
- }
1163
- embeddedProp.embeddable = embeddable.class;
1164
- embeddedProp.embeddedProps = {};
1165
- let order = meta.propertyOrder.get(embeddedProp.name);
1166
- const getRootProperty = prop => (prop.embedded ? getRootProperty(meta.properties[prop.embedded[0]]) : prop);
1167
- const isParentObject = prop => {
1168
- if (prop.object || prop.array) {
1169
- return true;
1170
- }
1171
- return prop.embedded ? isParentObject(meta.properties[prop.embedded[0]]) : false;
1172
- };
1173
- const isParentArray = prop => {
1174
- if (prop.array) {
1175
- return true;
1176
- }
1177
- return prop.embedded ? isParentArray(meta.properties[prop.embedded[0]]) : false;
1178
- };
1179
- const rootProperty = getRootProperty(embeddedProp);
1180
- const parentProperty = meta.properties[embeddedProp.embedded?.[0] ?? ''];
1181
- const object = isParentObject(embeddedProp);
1182
- const array = isParentArray(embeddedProp);
1183
- this.initFieldName(embeddedProp, rootProperty !== embeddedProp && object);
1184
- // the prefix of the parent cannot be a boolean; it already passed here
1185
- const prefix = this.getPrefix(embeddedProp, parentProperty);
1186
- const glue = object ? '~' : '_';
1187
- for (const prop of Object.values(embeddable.properties)) {
1188
- const name = (embeddedProp.embeddedPath?.join(glue) ?? embeddedProp.fieldNames[0] + glue) + prop.name;
1189
- meta.properties[name] = Utils.copy(prop);
1190
- meta.properties[name].name = name;
1191
- meta.properties[name].embedded = [embeddedProp.name, prop.name];
1192
- meta.propertyOrder.set(name, (order += 0.01));
1193
- embeddedProp.embeddedProps[prop.name] = meta.properties[name];
1194
- meta.properties[name].persist ??= embeddedProp.persist;
1195
- const refInArray =
1196
- array && [ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(prop.kind) && prop.owner;
1197
- if (embeddedProp.nullable || refInArray) {
1198
- meta.properties[name].nullable = true;
1199
- }
1200
- if (meta.properties[name].fieldNames) {
1201
- meta.properties[name].fieldNames[0] = prefix + meta.properties[name].fieldNames[0];
1202
- } else {
1203
- const name2 = meta.properties[name].name;
1204
- meta.properties[name].name = prefix + prop.name;
1205
- this.initFieldName(meta.properties[name]);
1206
- meta.properties[name].name = name2;
1207
- }
1208
- if (object) {
1209
- embeddedProp.object = true;
1210
- let path = [];
1211
- let tmp = embeddedProp;
1212
- while (tmp.embedded && tmp.object) {
1213
- path.unshift(tmp.embedded[1]);
1214
- tmp = meta.properties[tmp.embedded[0]];
1215
- }
1216
- if (tmp === rootProperty) {
1217
- path.unshift(rootProperty.fieldNames[0]);
1218
- } else if (embeddedProp.embeddedPath) {
1219
- path = [...embeddedProp.embeddedPath];
1220
- } else {
1221
- path = [embeddedProp.fieldNames[0]];
1222
- }
1223
- this.initFieldName(prop, true);
1224
- this.initRelation(prop);
1225
- path.push(prop.fieldNames[0]);
1226
- meta.properties[name].fieldNames = prop.fieldNames;
1227
- meta.properties[name].embeddedPath = path;
1228
- const targetProp = prop.targetMeta?.getPrimaryProp() ?? prop;
1229
- const fieldName = raw(
1230
- this.#platform.getSearchJsonPropertySQL(path.join('->'), targetProp.runtimeType ?? targetProp.type, true),
1231
- );
1232
- meta.properties[name].fieldNameRaw = fieldName.sql; // for querying in SQL drivers
1233
- meta.properties[name].persist = false; // only virtual as we store the whole object
1234
- meta.properties[name].userDefined = false; // mark this as a generated/internal property, so we can distinguish from user-defined non-persist properties
1235
- meta.properties[name].object = true;
1236
- this.initCustomType(meta, meta.properties[name], false, true);
1237
- }
1238
- this.initEmbeddables(meta, meta.properties[name], visited);
1239
- }
1240
- for (const index of embeddable.indexes) {
1241
- meta.indexes.push({
1242
- ...index,
1243
- properties: Utils.asArray(index.properties).map(p => {
1244
- return embeddedProp.embeddedProps[p].name;
1245
- }),
1246
- });
1247
- }
1248
- for (const unique of embeddable.uniques) {
1249
- meta.uniques.push({
1250
- ...unique,
1251
- properties: Utils.asArray(unique.properties).map(p => {
1252
- return embeddedProp.embeddedProps[p].name;
1253
- }),
1254
- });
1255
- }
1256
- }
1257
- initSingleTableInheritance(meta, metadata) {
1258
- if (meta.root !== meta && !meta.__processed) {
1259
- meta.root = metadata.find(m => m.class === meta.root.class);
1260
- meta.root.__processed = true;
1261
- } else {
1262
- delete meta.root.__processed;
1263
- }
1264
- if (!meta.root.discriminatorColumn) {
1265
- return;
1266
- }
1267
- meta.root.inheritanceType = 'sti';
1268
- if (meta.root.discriminatorMap) {
1269
- const map = meta.root.discriminatorMap;
1270
- Object.keys(map)
1271
- .filter(key => typeof map[key] === 'string')
1272
- .forEach(key => (map[key] = this.#metadata.getByClassName(map[key]).class));
1273
- } else {
1274
- meta.root.discriminatorMap = {};
1275
- const children = metadata
1276
- .filter(m => m.root.class === meta.root.class && !m.abstract)
1277
- .sort((a, b) => a.className.localeCompare(b.className));
1278
- for (const m of children) {
1279
- const name = m.discriminatorValue ?? this.#namingStrategy.classToTableName(m.className);
1280
- meta.root.discriminatorMap[name] = m.class;
1281
- }
1282
- }
1283
- meta.discriminatorValue = QueryHelper.findDiscriminatorValue(meta.root.discriminatorMap, meta.class);
1284
- if (!meta.root.properties[meta.root.discriminatorColumn]) {
1285
- this.createDiscriminatorProperty(meta.root);
1286
- }
1287
- Utils.defaultValue(
1288
- meta.root.properties[meta.root.discriminatorColumn],
1289
- 'items',
1290
- Object.keys(meta.root.discriminatorMap),
1291
- );
1292
- Utils.defaultValue(meta.root.properties[meta.root.discriminatorColumn], 'index', true);
1293
- if (meta.root === meta) {
1294
- return;
1295
- }
1296
- Object.values(meta.properties).forEach(prop => {
1297
- const newProp = { ...prop };
1298
- const rootProp = meta.root.properties[prop.name];
1299
- // stiMerged is set during inlineProperties when a property was merged
1300
- // from multiple polymorphic variants with different types. The flag is
1301
- // cleared implicitly when the first child claims the root property via
1302
- // addProperty below, so subsequent children correctly trigger renaming.
1303
- const typesMatch = rootProp?.type === prop.type || rootProp?.stiMerged === true;
1304
- if (
1305
- rootProp &&
1306
- (!typesMatch ||
1307
- (rootProp.fieldNames && prop.fieldNames && !compareArrays(rootProp.fieldNames, prop.fieldNames)))
1308
- ) {
1309
- const name = newProp.name;
1310
- this.initFieldName(newProp, newProp.object);
1311
- newProp.renamedFrom = name;
1312
- newProp.name = `${name}_${meta._id}`;
1313
- meta.root.addProperty(newProp);
1314
- this.initFieldName(prop, prop.object);
1315
- // Track all field variants and map discriminator values to field names
1316
- if (!rootProp.stiFieldNames) {
1317
- this.initFieldName(rootProp, rootProp.object);
1318
- rootProp.stiFieldNames = [...rootProp.fieldNames];
1319
- rootProp.stiFieldNameMap = {};
1320
- // Find which discriminator owns the original fieldNames
1321
- for (const [discValue, childClass] of Object.entries(meta.root.discriminatorMap)) {
1322
- const childMeta = this.#metadata.find(childClass);
1323
- if (
1324
- childMeta?.properties[prop.name]?.fieldNames &&
1325
- compareArrays(childMeta.properties[prop.name].fieldNames, rootProp.fieldNames)
1326
- ) {
1327
- rootProp.stiFieldNameMap[discValue] = rootProp.fieldNames[0];
1328
- break;
1329
- }
1330
- }
1331
- }
1332
- rootProp.stiFieldNameMap[meta.discriminatorValue] = prop.fieldNames[0];
1333
- rootProp.stiFieldNames.push(...prop.fieldNames);
1334
- newProp.nullable = true;
1335
- newProp.name = name;
1336
- newProp.hydrate = false;
1337
- newProp.inherited = true;
1338
- return;
1339
- }
1340
- if (prop.enum && prop.items && rootProp?.items) {
1341
- newProp.items = Utils.unique([...rootProp.items, ...prop.items]);
1342
- }
1343
- newProp.nullable = true;
1344
- newProp.inherited = !rootProp;
1345
- meta.root.addProperty(newProp);
1346
- });
1347
- meta.tableName = meta.root.tableName;
1348
- meta.root.indexes = Utils.unique([...meta.root.indexes, ...meta.indexes]);
1349
- meta.root.uniques = Utils.unique([...meta.root.uniques, ...meta.uniques]);
1350
- meta.root.checks = Utils.unique([...meta.root.checks, ...meta.checks]);
1351
- }
1352
- /**
1353
- * First pass of TPT initialization: sets up hierarchy relationships
1354
- * (inheritanceType, tptParent, tptChildren) before properties have fieldNames.
1355
- */
1356
- initTPTRelationships(meta, metadata) {
1357
- if (meta.root !== meta) {
1358
- meta.root = metadata.find(m => m.class === meta.root.class);
1359
- }
1360
- const inheritance = meta.inheritance;
1361
- if (inheritance === 'tpt' && meta.root === meta) {
1362
- meta.inheritanceType = 'tpt';
1363
- meta.tptChildren = [];
1364
- }
1365
- if (meta.root.inheritanceType !== 'tpt') {
1366
- return;
1367
- }
1368
- const parent = this.getTPTParent(meta, metadata);
1369
- if (parent) {
1370
- meta.tptParent = parent;
1371
- meta.inheritanceType = 'tpt';
1372
- parent.tptChildren ??= [];
1373
- if (!parent.tptChildren.includes(meta)) {
1374
- parent.tptChildren.push(meta);
1375
- }
1376
- }
1377
- }
1378
- /**
1379
- * Second pass of TPT initialization: re-resolves metadata references after fieldNames
1380
- * are set, syncs to registry metadata, and sets up discriminators.
1381
- */
1382
- finalizeTPTInheritance(meta, metadata) {
1383
- if (meta.inheritanceType !== 'tpt') {
1384
- return;
1385
- }
1386
- if (meta.tptParent) {
1387
- meta.tptParent = metadata.find(m => m.class === meta.tptParent.class) ?? meta.tptParent;
1388
- }
1389
- if (meta.tptChildren) {
1390
- meta.tptChildren = meta.tptChildren.map(child => metadata.find(m => m.class === child.class) ?? child);
1391
- }
1392
- const registryMeta = this.#metadata.get(meta.class);
1393
- if (registryMeta && registryMeta !== meta) {
1394
- registryMeta.inheritanceType = meta.inheritanceType;
1395
- registryMeta.tptParent = meta.tptParent ? this.#metadata.get(meta.tptParent.class) : undefined;
1396
- registryMeta.tptChildren = meta.tptChildren?.map(child => this.#metadata.get(child.class));
1397
- }
1398
- this.initTPTDiscriminator(meta, metadata);
1399
- }
1400
- /**
1401
- * Initialize TPT discriminator map and virtual discriminator property.
1402
- * Unlike STI where the discriminator is a persisted column, TPT discriminator is computed
1403
- * at query time using CASE WHEN expressions based on which child table has data.
1404
- */
1405
- initTPTDiscriminator(meta, metadata) {
1406
- const allDescendants = this.collectAllTPTDescendants(meta, metadata);
1407
- allDescendants.sort((a, b) => this.getTPTDepth(b) - this.getTPTDepth(a));
1408
- meta.allTPTDescendants = allDescendants;
1409
- if (meta.root !== meta) {
1410
- return;
1411
- }
1412
- meta.root.discriminatorMap = {};
1413
- for (const m of allDescendants) {
1414
- const name = this.#namingStrategy.classToTableName(m.className);
1415
- meta.root.discriminatorMap[name] = m.class;
1416
- m.discriminatorValue = name;
1417
- }
1418
- if (!meta.abstract) {
1419
- const name = this.#namingStrategy.classToTableName(meta.className);
1420
- meta.root.discriminatorMap[name] = meta.class;
1421
- meta.discriminatorValue = name;
1422
- }
1423
- // Virtual discriminator property - computed at query time via CASE WHEN, not persisted
1424
- const discriminatorColumn = '__tpt_type';
1425
- if (!meta.root.properties[discriminatorColumn]) {
1426
- meta.root.addProperty({
1427
- name: discriminatorColumn,
1428
- type: 'string',
1429
- kind: ReferenceKind.SCALAR,
1430
- persist: false,
1431
- userDefined: false,
1432
- hidden: true,
1433
- });
1434
- }
1435
- meta.root.tptDiscriminatorColumn = discriminatorColumn;
1436
- }
1437
- /**
1438
- * Recursively collect all TPT descendants (children, grandchildren, etc.)
1439
- */
1440
- collectAllTPTDescendants(meta, metadata) {
1441
- const descendants = [];
1442
- const collect = parent => {
1443
- for (const child of parent.tptChildren ?? []) {
1444
- const resolved = metadata.find(m => m.class === child.class) ?? child;
1445
- if (!resolved.abstract) {
1446
- descendants.push(resolved);
1447
- }
1448
- collect(resolved);
1449
- }
1450
- };
1451
- collect(meta);
1452
- return descendants;
1453
- }
1454
- /**
1455
- * Computes ownProps for TPT entities - only properties defined in THIS entity,
1456
- * not inherited from parent. Also creates synthetic join properties for parent/child relationships.
1457
- *
1458
- * Called multiple times during discovery as metadata is progressively built.
1459
- * Each pass overwrites earlier results to reflect the final state of properties.
1460
- */
1461
- computeTPTOwnProps(meta) {
1462
- if (meta.inheritanceType !== 'tpt') {
1463
- return;
1464
- }
1465
- const belongsToTable = prop => prop.persist !== false || prop.primary;
1466
- // Use meta.properties (object) since meta.props (array) may not be populated yet
1467
- const allProps = Object.values(meta.properties);
1468
- if (!meta.tptParent) {
1469
- meta.ownProps = allProps.filter(belongsToTable);
1470
- return;
1471
- }
1472
- const parentPropNames = new Set(Object.values(meta.tptParent.properties).map(p => p.name));
1473
- meta.ownProps = allProps.filter(prop => !parentPropNames.has(prop.name) && belongsToTable(prop));
1474
- // Create synthetic join properties for the parent-child relationship
1475
- const childFieldNames = meta.getPrimaryProps().flatMap(p => p.fieldNames);
1476
- const parentFieldNames = meta.tptParent.getPrimaryProps().flatMap(p => p.fieldNames);
1477
- meta.tptParentProp = {
1478
- name: '[tpt:parent]',
1479
- kind: ReferenceKind.MANY_TO_ONE,
1480
- targetMeta: meta.tptParent,
1481
- fieldNames: childFieldNames,
1482
- referencedColumnNames: parentFieldNames,
1483
- persist: false,
1484
- };
1485
- meta.tptInverseProp = {
1486
- name: '[tpt:child]',
1487
- kind: ReferenceKind.ONE_TO_ONE,
1488
- owner: true,
1489
- targetMeta: meta,
1490
- fieldNames: parentFieldNames,
1491
- joinColumns: parentFieldNames,
1492
- referencedColumnNames: childFieldNames,
1493
- persist: false,
1494
- };
1495
- }
1496
- /** Returns the depth of a TPT entity in its hierarchy (0 for root). */
1497
- getTPTDepth(meta) {
1498
- let depth = 0;
1499
- let current = meta;
1500
- while (current.tptParent) {
1501
- depth++;
1502
- current = current.tptParent;
1503
- }
1504
- return depth;
1505
- }
1506
- /**
1507
- * Find the direct TPT parent entity for the given entity.
1508
- */
1509
- getTPTParent(meta, metadata) {
1510
- if (meta.root === meta) {
1511
- return undefined;
1512
- }
1513
- return metadata.find(m => {
1514
- const ext = meta.extends;
1515
- if (EntitySchema.is(ext)) {
1516
- return m.class === ext.meta.class || m.className === ext.meta.className;
1517
- }
1518
- return m.class === ext || m.className === Utils.className(ext);
1519
- });
1520
- }
1521
- createDiscriminatorProperty(meta) {
1522
- meta.addProperty({
1523
- name: meta.discriminatorColumn,
1524
- type: 'string',
1525
- enum: true,
1526
- kind: ReferenceKind.SCALAR,
1527
- userDefined: false,
1528
- });
1529
- }
1530
- initAutoincrement(meta) {
1531
- const pks = meta.getPrimaryProps();
1532
- if (pks.length === 1 && this.#platform.isNumericProperty(pks[0])) {
1533
- /* v8 ignore next */
1534
- pks[0].autoincrement ??= true;
1535
- }
1536
- }
1537
- createSchemaTable(meta) {
1538
- const qualifiedName = meta.schema ? `${meta.schema}.${meta.tableName}` : meta.tableName;
1539
- return {
1540
- name: meta.tableName,
1541
- schema: meta.schema,
1542
- qualifiedName,
1543
- toString: () => qualifiedName,
1544
- };
1545
- }
1546
- initCheckConstraints(meta) {
1547
- const columns = meta.createSchemaColumnMappingObject();
1548
- const table = this.createSchemaTable(meta);
1549
- for (const check of meta.checks) {
1550
- const fieldNames = check.property ? meta.properties[check.property].fieldNames : [];
1551
- check.name ??= this.#namingStrategy.indexName(meta.tableName, fieldNames, 'check');
1552
- if (check.expression instanceof Function) {
1553
- check.expression = check.expression(columns, table);
1554
- }
1555
- }
1556
- if (this.#platform.usesEnumCheckConstraints() && !meta.embeddable) {
1557
- for (const prop of meta.props) {
1558
- if (prop.persist === false || prop.nativeEnumName || !prop.items?.every(item => typeof item === 'string')) {
1559
- continue;
1560
- }
1561
- this.initFieldName(prop);
1562
- let expression = null;
1563
- if (prop.enum) {
1564
- expression = this.#platform.getEnumCheckConstraintExpression(prop.fieldNames[0], prop.items);
1565
- } else if (prop.array) {
1566
- expression = this.#platform.getEnumArrayCheckConstraintExpression(prop.fieldNames[0], prop.items);
1567
- }
1568
- if (expression) {
1569
- meta.checks.push({
1570
- name: this.#namingStrategy.indexName(meta.tableName, prop.fieldNames, 'check'),
1571
- property: prop.name,
1572
- expression,
1573
- });
1574
- }
1575
- }
1576
- }
1577
- }
1578
- initGeneratedColumn(meta, prop) {
1579
- if (!prop.generated && prop.columnTypes) {
1580
- const match = /(.*) generated always as (.*)/i.exec(prop.columnTypes[0]);
1581
- if (match) {
1582
- prop.columnTypes[0] = match[1];
1583
- prop.generated = match[2];
1584
- return;
1585
- }
1586
- const match2 = /^as (.*)/i.exec(prop.columnTypes[0]?.trim());
1587
- if (match2) {
1588
- prop.generated = match2[1];
1589
- }
1590
- return;
1591
- }
1592
- if (prop.generated instanceof Function) {
1593
- const columns = meta.createSchemaColumnMappingObject();
1594
- prop.generated = prop.generated(columns, this.createSchemaTable(meta));
1595
- }
1596
- }
1597
- getDefaultVersionValue(meta, prop) {
1598
- if (typeof prop.defaultRaw !== 'undefined') {
1599
- return prop.defaultRaw;
1600
- }
1601
- /* v8 ignore next */
1602
- if (prop.default != null) {
1603
- return '' + this.#platform.convertVersionValue(prop.default, prop);
1604
- }
1605
- this.initCustomType(meta, prop, true);
1606
- const type = prop.customType?.runtimeType ?? prop.runtimeType ?? prop.type;
1607
- if (type === 'Date') {
1608
- prop.length ??= this.#platform.getDefaultVersionLength();
1609
- return this.#platform.getCurrentTimestampSQL(prop.length);
1610
- }
1611
- return '1';
1612
- }
1613
- inferDefaultValue(meta, prop) {
1614
- try {
1615
- // try to create two entity instances to detect the value is stable
1616
- const now = Date.now();
1617
- const entity1 = new meta.class();
1618
- const entity2 = new meta.class();
1619
- // we compare the two values by reference, this will discard things like `new Date()` or `Date.now()`
1620
- if (
1621
- this.#config.get('discovery').inferDefaultValues &&
1622
- prop.default === undefined &&
1623
- entity1[prop.name] != null &&
1624
- entity1[prop.name] === entity2[prop.name] &&
1625
- entity1[prop.name] !== now
1626
- ) {
1627
- prop.default ??= entity1[prop.name];
1628
- }
1629
- // if the default value is null, infer nullability
1630
- if (entity1[prop.name] === null) {
1631
- prop.nullable ??= true;
1632
- }
1633
- // but still use object values for type inference if not explicitly set, e.g. `createdAt = new Date()`
1634
- if (prop.kind === ReferenceKind.SCALAR && prop.type == null && entity1[prop.name] != null) {
1635
- prop.type = prop.runtimeType = Utils.getObjectType(entity1[prop.name]);
1636
- }
1637
- } catch {
1638
- // ignore
1639
- }
1640
- }
1641
- initDefaultValue(prop) {
1642
- if (prop.defaultRaw || !('default' in prop)) {
1643
- return;
1644
- }
1645
- let val = prop.default;
1646
- const raw = Raw.getKnownFragment(val);
1647
- if (raw) {
1648
- prop.defaultRaw = this.#platform.formatQuery(raw.sql, raw.params);
1649
- return;
1650
- }
1651
- if (Array.isArray(prop.default) && prop.customType) {
1652
- val = prop.customType.convertToDatabaseValue(prop.default, this.#platform);
1653
- }
1654
- prop.defaultRaw = typeof val === 'string' ? `'${val}'` : '' + val;
1655
- }
1656
- inferTypeFromDefault(prop) {
1657
- if ((prop.defaultRaw == null && prop.default == null) || prop.type !== 'any') {
1658
- return;
1659
- }
1660
- switch (typeof prop.default) {
1661
- case 'string':
1662
- prop.type = prop.runtimeType = 'string';
1663
- break;
1664
- case 'number':
1665
- prop.type = prop.runtimeType = 'number';
1666
- break;
1667
- case 'boolean':
1668
- prop.type = prop.runtimeType = 'boolean';
1669
- break;
1670
- }
1671
- if (prop.defaultRaw?.startsWith('current_timestamp')) {
1672
- prop.type = prop.runtimeType = 'Date';
1673
- }
1674
- }
1675
- initVersionProperty(meta, prop) {
1676
- if (prop.version) {
1677
- this.initDefaultValue(prop);
1678
- meta.versionProperty = prop.name;
1679
- prop.defaultRaw = this.getDefaultVersionValue(meta, prop);
1680
- }
1681
- if (prop.concurrencyCheck && !prop.primary) {
1682
- meta.concurrencyCheckKeys.add(prop.name);
1683
- }
1684
- }
1685
- initCustomType(meta, prop, simple = false, objectEmbeddable = false) {
1686
- // `prop.type` might be actually instance of custom type class
1687
- if (Type.isMappedType(prop.type) && !prop.customType) {
1688
- prop.customType = prop.type;
1689
- prop.type = prop.customType.constructor.name;
1690
- }
1691
- // `prop.type` might also be custom type class (not instance), so `typeof MyType` will give us `function`, not `object`
1692
- if (typeof prop.type === 'function' && Type.isMappedType(prop.type.prototype) && !prop.customType) {
1693
- // if the type is an ORM defined mapped type without `ensureComparable: true`,
1694
- // we use just the type name, to have more performant hydration code
1695
- const brand = Type.getOrmType(prop.type);
1696
- const type = Utils.keys(t).find(type => {
1697
- return !Type.getType(t[type]).ensureComparable(meta, prop) && (prop.type === t[type] || brand === type);
1698
- });
1699
- if (type) {
1700
- prop.type = type === 'datetime' ? 'Date' : type;
1701
- } else {
1702
- prop.customType = new prop.type();
1703
- prop.type = prop.customType.constructor.name;
1704
- }
1705
- }
1706
- if (simple) {
1707
- return;
1708
- }
1709
- if (!prop.customType && ['json', 'jsonb'].includes(prop.type?.toLowerCase())) {
1710
- prop.customType = new t.json();
1711
- }
1712
- if (
1713
- prop.kind === ReferenceKind.SCALAR &&
1714
- !prop.customType &&
1715
- prop.columnTypes &&
1716
- ['json', 'jsonb'].includes(prop.columnTypes[0])
1717
- ) {
1718
- prop.customType = new t.json();
1719
- }
1720
- if (prop.kind === ReferenceKind.EMBEDDED && !prop.customType && (prop.object || prop.array)) {
1721
- prop.customType = new t.json();
1722
- }
1723
- if (!prop.customType && prop.array && prop.items) {
1724
- prop.customType = new t.enumArray(`${meta.className}.${prop.name}`, prop.items);
1725
- }
1726
- const isArray = prop.type?.toLowerCase() === 'array' || prop.type?.toString().endsWith('[]');
1727
- if (objectEmbeddable && !prop.customType && isArray) {
1728
- prop.customType = new t.json();
1729
- }
1730
- // for number arrays we make sure to convert the items to numbers
1731
- if (!prop.customType && prop.type === 'number[]') {
1732
- prop.customType = new t.array(i => +i);
1733
- }
1734
- // `string[]` can be returned via ts-morph, while reflect metadata will give us just `array`
1735
- if (!prop.customType && isArray) {
1736
- prop.customType = new t.array();
1737
- }
1738
- if (!prop.customType && prop.type?.toLowerCase() === 'buffer') {
1739
- prop.customType = new t.blob();
1740
- }
1741
- if (!prop.customType && prop.type?.toLowerCase() === 'uint8array') {
1742
- prop.customType = new t.uint8array();
1743
- }
1744
- const mappedType = this.getMappedType(prop);
1745
- if (prop.fieldNames?.length === 1 && !prop.customType) {
1746
- [t.bigint, t.double, t.decimal, t.interval, t.date]
1747
- .filter(type => mappedType instanceof type)
1748
- .forEach(type => (prop.customType = new type()));
1749
- }
1750
- if (prop.customType && !prop.columnTypes) {
1751
- const mappedType = this.getMappedType({
1752
- columnTypes: [prop.customType.getColumnType(prop, this.#platform)],
1753
- });
1754
- if (prop.customType.compareAsType() === 'any' && ![t.json].some(t => prop.customType instanceof t)) {
1755
- prop.runtimeType ??= mappedType.runtimeType;
1756
- } else {
1757
- prop.runtimeType ??= prop.customType.runtimeType;
1758
- }
1759
- } else if (prop.runtimeType === 'object') {
1760
- prop.runtimeType = mappedType.runtimeType;
1761
- } else {
1762
- prop.runtimeType ??= mappedType.runtimeType;
1763
- }
1764
- if (prop.customType) {
1765
- prop.customType.platform = this.#platform;
1766
- prop.customType.meta = meta;
1767
- prop.customType.prop = prop;
1768
- prop.columnTypes ??= [prop.customType.getColumnType(prop, this.#platform)];
1769
- prop.hasConvertToJSValueSQL =
1770
- !!prop.customType.convertToJSValueSQL && prop.customType.convertToJSValueSQL('', this.#platform) !== '';
1771
- prop.hasConvertToDatabaseValueSQL =
1772
- !!prop.customType.convertToDatabaseValueSQL &&
1773
- prop.customType.convertToDatabaseValueSQL('', this.#platform) !== '';
1774
- if (
1775
- prop.customType instanceof t.bigint &&
1776
- ['string', 'bigint', 'number'].includes(prop.runtimeType.toLowerCase())
1777
- ) {
1778
- prop.customType.mode = prop.runtimeType.toLowerCase();
1779
- }
1780
- }
1781
- if (Type.isMappedType(prop.customType) && prop.kind === ReferenceKind.SCALAR && !isArray) {
1782
- prop.type = prop.customType.name;
1783
- }
1784
- if (
1785
- !prop.customType &&
1786
- [ReferenceKind.ONE_TO_ONE, ReferenceKind.MANY_TO_ONE].includes(prop.kind) &&
1787
- !prop.polymorphic &&
1788
- prop.targetMeta.compositePK
1789
- ) {
1790
- prop.customTypes = [];
1791
- for (const pk of prop.targetMeta.getPrimaryProps()) {
1792
- if (pk.customType) {
1793
- prop.customTypes.push(pk.customType);
1794
- prop.hasConvertToJSValueSQL ||=
1795
- !!pk.customType.convertToJSValueSQL && pk.customType.convertToJSValueSQL('', this.#platform) !== '';
1796
- /* v8 ignore next */
1797
- prop.hasConvertToDatabaseValueSQL ||=
1798
- !!pk.customType.convertToDatabaseValueSQL &&
1799
- pk.customType.convertToDatabaseValueSQL('', this.#platform) !== '';
1800
- } else {
1801
- prop.customTypes.push(undefined);
1802
- }
1803
- }
1804
- }
1805
- if (prop.kind === ReferenceKind.SCALAR && !(mappedType instanceof t.unknown)) {
1806
- if (
1807
- prop.nativeEnumName &&
1808
- meta.schema !== this.#platform.getDefaultSchemaName() &&
1809
- meta.schema &&
1810
- !prop.nativeEnumName.includes('.')
1811
- ) {
1812
- const suffix = prop.columnTypes?.[0]?.endsWith('[]') ? '[]' : '';
1813
- prop.columnTypes = [`${meta.schema}.${prop.nativeEnumName}${suffix}`];
1814
- } else {
1815
- prop.columnTypes ??= [mappedType.getColumnType(prop, this.#platform)];
1816
- }
1817
- // use only custom types provided by user, we don't need to use the ones provided by ORM,
1818
- // with exception for ArrayType and JsonType, those two are handled in
1819
- if (!Object.values(t).some(type => type === mappedType.constructor)) {
1820
- prop.customType ??= mappedType;
1821
- }
1822
- }
1823
- }
1824
- initRelation(prop) {
1825
- if (prop.kind === ReferenceKind.SCALAR || prop.polymorphTargets) {
1826
- return;
1827
- }
1828
- // when the target is a polymorphic embedded entity, `prop.target` is an array of classes, we need to get the metadata by the type name instead
1829
- const meta2 = this.#metadata.find(prop.target) ?? this.#metadata.getByClassName(prop.type);
1830
- // If targetKey is specified, use that property instead of PKs for referencedPKs
1831
- prop.referencedPKs = prop.targetKey ? [prop.targetKey] : meta2.primaryKeys;
1832
- prop.targetMeta = meta2;
1833
- if (meta2.view) {
1834
- prop.createForeignKeyConstraint = false;
1835
- }
1836
- // Auto-generate formula for persist: false relations, but only for single-column FKs
1837
- // Composite FK relations need standard JOIN conditions, not formula-based
1838
- if (
1839
- !prop.formula &&
1840
- prop.persist === false &&
1841
- [ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(prop.kind) &&
1842
- !prop.embedded
1843
- ) {
1844
- this.initFieldName(prop);
1845
- if (prop.fieldNames?.length === 1) {
1846
- prop.formula = table => `${table}.${this.#platform.quoteIdentifier(prop.fieldNames[0])}`;
1847
- }
1848
- }
1849
- }
1850
- initColumnType(prop) {
1851
- this.initUnsigned(prop);
1852
- // Get the target properties for FK relations - use targetKey property if specified, otherwise PKs
1853
- const targetProps = prop.targetMeta
1854
- ? prop.targetKey
1855
- ? [prop.targetMeta.properties[prop.targetKey]]
1856
- : prop.targetMeta.getPrimaryProps()
1857
- : [];
1858
- targetProps.map(targetProp => {
1859
- prop.length ??= targetProp.length;
1860
- prop.precision ??= targetProp.precision;
1861
- prop.scale ??= targetProp.scale;
1862
- });
1863
- if (prop.kind === ReferenceKind.SCALAR && (prop.type == null || prop.type === 'object') && prop.columnTypes?.[0]) {
1864
- delete prop.type;
1865
- const mappedType = this.getMappedType(prop);
1866
- prop.type = mappedType.compareAsType();
1867
- }
1868
- if (prop.columnTypes || !this.#schemaHelper) {
1869
- return;
1870
- }
1871
- if (prop.kind === ReferenceKind.SCALAR) {
1872
- const mappedType = this.getMappedType(prop);
1873
- const SCALAR_TYPES = ['string', 'number', 'boolean', 'bigint', 'Date', 'Buffer', 'RegExp', 'any', 'unknown'];
1874
- if (
1875
- mappedType instanceof t.unknown &&
1876
- // it could be a runtime type from reflect-metadata
1877
- !SCALAR_TYPES.includes(prop.type) &&
1878
- // or it might be inferred via ts-morph to some generic type alias
1879
- !/[<>:"';{}]/.exec(prop.type)
1880
- ) {
1881
- const type =
1882
- prop.length != null && !prop.type.endsWith(`(${prop.length})`) ? `${prop.type}(${prop.length})` : prop.type;
1883
- prop.columnTypes = [type];
1884
- } else {
1885
- prop.columnTypes = [mappedType.getColumnType(prop, this.#platform)];
1886
- }
1887
- return;
1888
- }
1889
- /* v8 ignore next */
1890
- if (prop.kind === ReferenceKind.EMBEDDED && prop.object) {
1891
- prop.columnTypes = [this.#platform.getJsonDeclarationSQL()];
1892
- return;
1893
- }
1894
- const targetMeta = prop.targetMeta;
1895
- prop.columnTypes = [];
1896
- // Use targetKey property if specified, otherwise use primary key properties
1897
- const referencedProps = prop.targetKey ? [targetMeta.properties[prop.targetKey]] : targetMeta.getPrimaryProps();
1898
- if (prop.polymorphic && prop.polymorphTargets) {
1899
- prop.columnTypes.push(this.#platform.getVarcharTypeDeclarationSQL(prop));
1900
- }
1901
- for (const referencedProp of referencedProps) {
1902
- this.initCustomType(targetMeta, referencedProp);
1903
- this.initColumnType(referencedProp);
1904
- const mappedType = this.getMappedType(referencedProp);
1905
- let columnTypes = referencedProp.columnTypes;
1906
- if (referencedProp.autoincrement) {
1907
- columnTypes = [mappedType.getColumnType({ ...referencedProp, autoincrement: false }, this.#platform)];
1908
- }
1909
- prop.columnTypes.push(...columnTypes);
1910
- if (!targetMeta.compositePK || prop.targetKey) {
1911
- prop.customType = referencedProp.customType;
1912
- }
1913
- }
1914
- }
1915
- getMappedType(prop) {
1916
- if (prop.customType) {
1917
- return prop.customType;
1918
- }
1919
- /* v8 ignore next */
1920
- let t = prop.columnTypes?.[0] ?? prop.type ?? '';
1921
- if (prop.nativeEnumName) {
1922
- t = 'enum';
1923
- } else if (prop.enum) {
1924
- t = prop.items?.every(item => typeof item === 'string') ? 'enum' : 'tinyint';
1925
- }
1926
- if (t === 'Date') {
1927
- t = 'datetime';
1928
- }
1929
- return this.#platform.getMappedType(t);
1930
- }
1931
- getPrefix(prop, parent) {
1932
- const { embeddedPath = [], fieldNames, prefix = true, prefixMode } = prop;
1933
- if (prefix === true) {
1934
- return (embeddedPath.length ? embeddedPath.join('_') : fieldNames[0]) + '_';
1935
- }
1936
- const prefixParent = parent ? this.getPrefix(parent, null) : '';
1937
- if (prefix === false) {
1938
- return prefixParent;
1939
- }
1940
- const mode = prefixMode ?? this.#config.get('embeddables').prefixMode;
1941
- return mode === 'absolute' ? prefix : prefixParent + prefix;
1942
- }
1943
- initUnsigned(prop) {
1944
- if (prop.unsigned != null) {
1945
- return;
1946
- }
1947
- if ([ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(prop.kind)) {
1948
- prop.unsigned = prop.targetMeta.getPrimaryProps().some(pk => {
1949
- this.initUnsigned(pk);
1950
- return pk.unsigned;
1951
- });
1952
- return;
1953
- }
1954
- prop.unsigned ??=
1955
- (prop.primary || prop.unsigned) && this.#platform.isNumericProperty(prop) && this.#platform.supportsUnsigned();
1956
- }
1957
- initIndexes(meta, prop) {
1958
- const hasIndex = meta.indexes.some(idx => idx.properties?.length === 1 && idx.properties[0] === prop.name);
1959
- if (prop.kind === ReferenceKind.MANY_TO_ONE && this.#platform.indexForeignKeys() && !hasIndex) {
1960
- prop.index ??= true;
1961
- }
1962
- }
1963
- shouldForceConstructorUsage(meta) {
1964
- const forceConstructor = this.#config.get('forceEntityConstructor');
1965
- if (Array.isArray(forceConstructor)) {
1966
- return forceConstructor.some(cls => Utils.className(cls) === meta.className);
1967
- }
1968
- return forceConstructor;
1969
- }
1447
+ }
1448
+ createDiscriminatorProperty(meta) {
1449
+ meta.addProperty({
1450
+ name: meta.discriminatorColumn,
1451
+ type: 'string',
1452
+ enum: true,
1453
+ kind: ReferenceKind.SCALAR,
1454
+ userDefined: false,
1455
+ });
1456
+ }
1457
+ initAutoincrement(meta) {
1458
+ const pks = meta.getPrimaryProps();
1459
+ if (pks.length === 1 && this.#platform.isNumericProperty(pks[0])) {
1460
+ /* v8 ignore next */
1461
+ pks[0].autoincrement ??= true;
1462
+ }
1463
+ }
1464
+ createSchemaTable(meta) {
1465
+ const qualifiedName = meta.schema ? `${meta.schema}.${meta.tableName}` : meta.tableName;
1466
+ return {
1467
+ name: meta.tableName,
1468
+ schema: meta.schema,
1469
+ qualifiedName,
1470
+ toString: () => qualifiedName,
1471
+ };
1472
+ }
1473
+ initCheckConstraints(meta) {
1474
+ const columns = meta.createSchemaColumnMappingObject();
1475
+ const table = this.createSchemaTable(meta);
1476
+ for (const check of meta.checks) {
1477
+ const fieldNames = check.property ? meta.properties[check.property].fieldNames : [];
1478
+ check.name ??= this.#namingStrategy.indexName(meta.tableName, fieldNames, 'check');
1479
+ if (check.expression instanceof Function) {
1480
+ check.expression = check.expression(columns, table);
1481
+ }
1482
+ }
1483
+ if (this.#platform.usesEnumCheckConstraints() && !meta.embeddable) {
1484
+ for (const prop of meta.props) {
1485
+ if (prop.persist === false || prop.nativeEnumName || !prop.items?.every(item => typeof item === 'string')) {
1486
+ continue;
1487
+ }
1488
+ this.initFieldName(prop);
1489
+ let expression = null;
1490
+ if (prop.enum) {
1491
+ expression = this.#platform.getEnumCheckConstraintExpression(prop.fieldNames[0], prop.items);
1492
+ }
1493
+ else if (prop.array) {
1494
+ expression = this.#platform.getEnumArrayCheckConstraintExpression(prop.fieldNames[0], prop.items);
1495
+ }
1496
+ if (expression) {
1497
+ meta.checks.push({
1498
+ name: this.#namingStrategy.indexName(meta.tableName, prop.fieldNames, 'check'),
1499
+ property: prop.name,
1500
+ expression,
1501
+ });
1502
+ }
1503
+ }
1504
+ }
1505
+ }
1506
+ initGeneratedColumn(meta, prop) {
1507
+ if (!prop.generated && prop.columnTypes) {
1508
+ const match = /(.*) generated always as (.*)/i.exec(prop.columnTypes[0]);
1509
+ if (match) {
1510
+ prop.columnTypes[0] = match[1];
1511
+ prop.generated = match[2];
1512
+ return;
1513
+ }
1514
+ const match2 = /^as (.*)/i.exec(prop.columnTypes[0]?.trim());
1515
+ if (match2) {
1516
+ prop.generated = match2[1];
1517
+ }
1518
+ return;
1519
+ }
1520
+ if (prop.generated instanceof Function) {
1521
+ const columns = meta.createSchemaColumnMappingObject();
1522
+ prop.generated = prop.generated(columns, this.createSchemaTable(meta));
1523
+ }
1524
+ }
1525
+ getDefaultVersionValue(meta, prop) {
1526
+ if (typeof prop.defaultRaw !== 'undefined') {
1527
+ return prop.defaultRaw;
1528
+ }
1529
+ /* v8 ignore next */
1530
+ if (prop.default != null) {
1531
+ return '' + this.#platform.convertVersionValue(prop.default, prop);
1532
+ }
1533
+ this.initCustomType(meta, prop, true);
1534
+ const type = prop.customType?.runtimeType ?? prop.runtimeType ?? prop.type;
1535
+ if (type === 'Date') {
1536
+ prop.length ??= this.#platform.getDefaultVersionLength();
1537
+ return this.#platform.getCurrentTimestampSQL(prop.length);
1538
+ }
1539
+ return '1';
1540
+ }
1541
+ inferDefaultValue(meta, prop) {
1542
+ try {
1543
+ // try to create two entity instances to detect the value is stable
1544
+ const now = Date.now();
1545
+ const entity1 = new meta.class();
1546
+ const entity2 = new meta.class();
1547
+ // we compare the two values by reference, this will discard things like `new Date()` or `Date.now()`
1548
+ if (this.#config.get('discovery').inferDefaultValues &&
1549
+ prop.default === undefined &&
1550
+ entity1[prop.name] != null &&
1551
+ entity1[prop.name] === entity2[prop.name] &&
1552
+ entity1[prop.name] !== now) {
1553
+ prop.default ??= entity1[prop.name];
1554
+ }
1555
+ // if the default value is null, infer nullability
1556
+ if (entity1[prop.name] === null) {
1557
+ prop.nullable ??= true;
1558
+ }
1559
+ // but still use object values for type inference if not explicitly set, e.g. `createdAt = new Date()`
1560
+ if (prop.kind === ReferenceKind.SCALAR && prop.type == null && entity1[prop.name] != null) {
1561
+ prop.type = prop.runtimeType = Utils.getObjectType(entity1[prop.name]);
1562
+ }
1563
+ }
1564
+ catch {
1565
+ // ignore
1566
+ }
1567
+ }
1568
+ initDefaultValue(prop) {
1569
+ if (prop.defaultRaw || !('default' in prop)) {
1570
+ return;
1571
+ }
1572
+ let val = prop.default;
1573
+ const raw = Raw.getKnownFragment(val);
1574
+ if (raw) {
1575
+ prop.defaultRaw = this.#platform.formatQuery(raw.sql, raw.params);
1576
+ return;
1577
+ }
1578
+ if (Array.isArray(prop.default) && prop.customType) {
1579
+ val = prop.customType.convertToDatabaseValue(prop.default, this.#platform);
1580
+ }
1581
+ prop.defaultRaw = typeof val === 'string' ? `'${val}'` : '' + val;
1582
+ }
1583
+ inferTypeFromDefault(prop) {
1584
+ if ((prop.defaultRaw == null && prop.default == null) || prop.type !== 'any') {
1585
+ return;
1586
+ }
1587
+ switch (typeof prop.default) {
1588
+ case 'string':
1589
+ prop.type = prop.runtimeType = 'string';
1590
+ break;
1591
+ case 'number':
1592
+ prop.type = prop.runtimeType = 'number';
1593
+ break;
1594
+ case 'boolean':
1595
+ prop.type = prop.runtimeType = 'boolean';
1596
+ break;
1597
+ }
1598
+ if (prop.defaultRaw?.startsWith('current_timestamp')) {
1599
+ prop.type = prop.runtimeType = 'Date';
1600
+ }
1601
+ }
1602
+ initVersionProperty(meta, prop) {
1603
+ if (prop.version) {
1604
+ this.initDefaultValue(prop);
1605
+ meta.versionProperty = prop.name;
1606
+ prop.defaultRaw = this.getDefaultVersionValue(meta, prop);
1607
+ }
1608
+ if (prop.concurrencyCheck && !prop.primary) {
1609
+ meta.concurrencyCheckKeys.add(prop.name);
1610
+ }
1611
+ }
1612
+ initCustomType(meta, prop, simple = false, objectEmbeddable = false) {
1613
+ // `prop.type` might be actually instance of custom type class
1614
+ if (Type.isMappedType(prop.type) && !prop.customType) {
1615
+ prop.customType = prop.type;
1616
+ prop.type = prop.customType.constructor.name;
1617
+ }
1618
+ // `prop.type` might also be custom type class (not instance), so `typeof MyType` will give us `function`, not `object`
1619
+ if (typeof prop.type === 'function' &&
1620
+ Type.isMappedType(prop.type.prototype) &&
1621
+ !prop.customType) {
1622
+ // if the type is an ORM defined mapped type without `ensureComparable: true`,
1623
+ // we use just the type name, to have more performant hydration code
1624
+ const brand = Type.getOrmType(prop.type);
1625
+ const type = Utils.keys(t).find(type => {
1626
+ return (!Type.getType(t[type]).ensureComparable(meta, prop) && (prop.type === t[type] || brand === type));
1627
+ });
1628
+ if (type) {
1629
+ prop.type = type === 'datetime' ? 'Date' : type;
1630
+ }
1631
+ else {
1632
+ prop.customType = new prop.type();
1633
+ prop.type = prop.customType.constructor.name;
1634
+ }
1635
+ }
1636
+ if (simple) {
1637
+ return;
1638
+ }
1639
+ if (!prop.customType && ['json', 'jsonb'].includes(prop.type?.toLowerCase())) {
1640
+ prop.customType = new t.json();
1641
+ }
1642
+ if (prop.kind === ReferenceKind.SCALAR &&
1643
+ !prop.customType &&
1644
+ prop.columnTypes &&
1645
+ ['json', 'jsonb'].includes(prop.columnTypes[0])) {
1646
+ prop.customType = new t.json();
1647
+ }
1648
+ if (prop.kind === ReferenceKind.EMBEDDED && !prop.customType && (prop.object || prop.array)) {
1649
+ prop.customType = new t.json();
1650
+ }
1651
+ if (!prop.customType && prop.array && prop.items) {
1652
+ prop.customType = new t.enumArray(`${meta.className}.${prop.name}`, prop.items);
1653
+ }
1654
+ const isArray = prop.type?.toLowerCase() === 'array' || prop.type?.toString().endsWith('[]');
1655
+ if (objectEmbeddable && !prop.customType && isArray) {
1656
+ prop.customType = new t.json();
1657
+ }
1658
+ // for number arrays we make sure to convert the items to numbers
1659
+ if (!prop.customType && prop.type === 'number[]') {
1660
+ prop.customType = new t.array(i => +i);
1661
+ }
1662
+ // `string[]` can be returned via ts-morph, while reflect metadata will give us just `array`
1663
+ if (!prop.customType && isArray) {
1664
+ prop.customType = new t.array();
1665
+ }
1666
+ if (!prop.customType && prop.type?.toLowerCase() === 'buffer') {
1667
+ prop.customType = new t.blob();
1668
+ }
1669
+ if (!prop.customType && prop.type?.toLowerCase() === 'uint8array') {
1670
+ prop.customType = new t.uint8array();
1671
+ }
1672
+ const mappedType = this.getMappedType(prop);
1673
+ if (prop.fieldNames?.length === 1 && !prop.customType) {
1674
+ [t.bigint, t.double, t.decimal, t.interval, t.date]
1675
+ .filter(type => mappedType instanceof type)
1676
+ .forEach((type) => (prop.customType = new type()));
1677
+ }
1678
+ if (prop.customType && !prop.columnTypes) {
1679
+ const mappedType = this.getMappedType({
1680
+ columnTypes: [prop.customType.getColumnType(prop, this.#platform)],
1681
+ });
1682
+ if (prop.customType.compareAsType() === 'any' && ![t.json].some(t => prop.customType instanceof t)) {
1683
+ prop.runtimeType ??= mappedType.runtimeType;
1684
+ }
1685
+ else {
1686
+ prop.runtimeType ??= prop.customType.runtimeType;
1687
+ }
1688
+ }
1689
+ else if (prop.runtimeType === 'object') {
1690
+ prop.runtimeType = mappedType.runtimeType;
1691
+ }
1692
+ else {
1693
+ prop.runtimeType ??= mappedType.runtimeType;
1694
+ }
1695
+ if (prop.customType) {
1696
+ prop.customType.platform = this.#platform;
1697
+ prop.customType.meta = meta;
1698
+ prop.customType.prop = prop;
1699
+ prop.columnTypes ??= [prop.customType.getColumnType(prop, this.#platform)];
1700
+ prop.hasConvertToJSValueSQL =
1701
+ !!prop.customType.convertToJSValueSQL && prop.customType.convertToJSValueSQL('', this.#platform) !== '';
1702
+ prop.hasConvertToDatabaseValueSQL =
1703
+ !!prop.customType.convertToDatabaseValueSQL &&
1704
+ prop.customType.convertToDatabaseValueSQL('', this.#platform) !== '';
1705
+ if (prop.customType instanceof t.bigint &&
1706
+ ['string', 'bigint', 'number'].includes(prop.runtimeType.toLowerCase())) {
1707
+ prop.customType.mode = prop.runtimeType.toLowerCase();
1708
+ }
1709
+ }
1710
+ if (Type.isMappedType(prop.customType) && prop.kind === ReferenceKind.SCALAR && !isArray) {
1711
+ prop.type = prop.customType.name;
1712
+ }
1713
+ if (!prop.customType &&
1714
+ [ReferenceKind.ONE_TO_ONE, ReferenceKind.MANY_TO_ONE].includes(prop.kind) &&
1715
+ !prop.polymorphic &&
1716
+ prop.targetMeta.compositePK) {
1717
+ prop.customTypes = [];
1718
+ for (const pk of prop.targetMeta.getPrimaryProps()) {
1719
+ if (pk.customType) {
1720
+ prop.customTypes.push(pk.customType);
1721
+ prop.hasConvertToJSValueSQL ||=
1722
+ !!pk.customType.convertToJSValueSQL && pk.customType.convertToJSValueSQL('', this.#platform) !== '';
1723
+ /* v8 ignore next */
1724
+ prop.hasConvertToDatabaseValueSQL ||=
1725
+ !!pk.customType.convertToDatabaseValueSQL &&
1726
+ pk.customType.convertToDatabaseValueSQL('', this.#platform) !== '';
1727
+ }
1728
+ else {
1729
+ prop.customTypes.push(undefined);
1730
+ }
1731
+ }
1732
+ }
1733
+ if (prop.kind === ReferenceKind.SCALAR && !(mappedType instanceof t.unknown)) {
1734
+ if (prop.nativeEnumName &&
1735
+ meta.schema !== this.#platform.getDefaultSchemaName() &&
1736
+ meta.schema &&
1737
+ !prop.nativeEnumName.includes('.')) {
1738
+ const suffix = prop.columnTypes?.[0]?.endsWith('[]') ? '[]' : '';
1739
+ prop.columnTypes = [`${meta.schema}.${prop.nativeEnumName}${suffix}`];
1740
+ }
1741
+ else {
1742
+ prop.columnTypes ??= [mappedType.getColumnType(prop, this.#platform)];
1743
+ }
1744
+ // use only custom types provided by user, we don't need to use the ones provided by ORM,
1745
+ // with exception for ArrayType and JsonType, those two are handled in
1746
+ if (!Object.values(t).some(type => type === mappedType.constructor)) {
1747
+ prop.customType ??= mappedType;
1748
+ }
1749
+ }
1750
+ }
1751
+ initRelation(prop) {
1752
+ if (prop.kind === ReferenceKind.SCALAR || prop.polymorphTargets) {
1753
+ return;
1754
+ }
1755
+ // when the target is a polymorphic embedded entity, `prop.target` is an array of classes, we need to get the metadata by the type name instead
1756
+ const meta2 = this.#metadata.find(prop.target) ?? this.#metadata.getByClassName(prop.type);
1757
+ // If targetKey is specified, use that property instead of PKs for referencedPKs
1758
+ prop.referencedPKs = prop.targetKey ? [prop.targetKey] : meta2.primaryKeys;
1759
+ prop.targetMeta = meta2;
1760
+ if (meta2.view) {
1761
+ prop.createForeignKeyConstraint = false;
1762
+ }
1763
+ // Auto-generate formula for persist: false relations, but only for single-column FKs
1764
+ // Composite FK relations need standard JOIN conditions, not formula-based
1765
+ if (!prop.formula &&
1766
+ prop.persist === false &&
1767
+ [ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(prop.kind) &&
1768
+ !prop.embedded) {
1769
+ this.initFieldName(prop);
1770
+ if (prop.fieldNames?.length === 1) {
1771
+ prop.formula = table => `${table}.${this.#platform.quoteIdentifier(prop.fieldNames[0])}`;
1772
+ }
1773
+ }
1774
+ }
1775
+ initColumnType(prop) {
1776
+ this.initUnsigned(prop);
1777
+ // Get the target properties for FK relations - use targetKey property if specified, otherwise PKs
1778
+ const targetProps = prop.targetMeta
1779
+ ? prop.targetKey
1780
+ ? [prop.targetMeta.properties[prop.targetKey]]
1781
+ : prop.targetMeta.getPrimaryProps()
1782
+ : [];
1783
+ targetProps.map(targetProp => {
1784
+ prop.length ??= targetProp.length;
1785
+ prop.precision ??= targetProp.precision;
1786
+ prop.scale ??= targetProp.scale;
1787
+ });
1788
+ if (prop.kind === ReferenceKind.SCALAR && (prop.type == null || prop.type === 'object') && prop.columnTypes?.[0]) {
1789
+ delete prop.type;
1790
+ const mappedType = this.getMappedType(prop);
1791
+ prop.type = mappedType.compareAsType();
1792
+ }
1793
+ if (prop.columnTypes || !this.#schemaHelper) {
1794
+ return;
1795
+ }
1796
+ if (prop.kind === ReferenceKind.SCALAR) {
1797
+ const mappedType = this.getMappedType(prop);
1798
+ const SCALAR_TYPES = ['string', 'number', 'boolean', 'bigint', 'Date', 'Buffer', 'RegExp', 'any', 'unknown'];
1799
+ if (mappedType instanceof t.unknown &&
1800
+ // it could be a runtime type from reflect-metadata
1801
+ !SCALAR_TYPES.includes(prop.type) &&
1802
+ // or it might be inferred via ts-morph to some generic type alias
1803
+ !/[<>:"';{}]/.exec(prop.type)) {
1804
+ const type = prop.length != null && !prop.type.endsWith(`(${prop.length})`) ? `${prop.type}(${prop.length})` : prop.type;
1805
+ prop.columnTypes = [type];
1806
+ }
1807
+ else {
1808
+ prop.columnTypes = [mappedType.getColumnType(prop, this.#platform)];
1809
+ }
1810
+ return;
1811
+ }
1812
+ /* v8 ignore next */
1813
+ if (prop.kind === ReferenceKind.EMBEDDED && prop.object) {
1814
+ prop.columnTypes = [this.#platform.getJsonDeclarationSQL()];
1815
+ return;
1816
+ }
1817
+ const targetMeta = prop.targetMeta;
1818
+ prop.columnTypes = [];
1819
+ // Use targetKey property if specified, otherwise use primary key properties
1820
+ const referencedProps = prop.targetKey ? [targetMeta.properties[prop.targetKey]] : targetMeta.getPrimaryProps();
1821
+ if (prop.polymorphic && prop.polymorphTargets) {
1822
+ prop.columnTypes.push(this.#platform.getVarcharTypeDeclarationSQL(prop));
1823
+ }
1824
+ for (const referencedProp of referencedProps) {
1825
+ this.initCustomType(targetMeta, referencedProp);
1826
+ this.initColumnType(referencedProp);
1827
+ const mappedType = this.getMappedType(referencedProp);
1828
+ let columnTypes = referencedProp.columnTypes;
1829
+ if (referencedProp.autoincrement) {
1830
+ columnTypes = [mappedType.getColumnType({ ...referencedProp, autoincrement: false }, this.#platform)];
1831
+ }
1832
+ prop.columnTypes.push(...columnTypes);
1833
+ if (!targetMeta.compositePK || prop.targetKey) {
1834
+ prop.customType = referencedProp.customType;
1835
+ }
1836
+ }
1837
+ }
1838
+ getMappedType(prop) {
1839
+ if (prop.customType) {
1840
+ return prop.customType;
1841
+ }
1842
+ /* v8 ignore next */
1843
+ let t = prop.columnTypes?.[0] ?? prop.type ?? '';
1844
+ if (prop.nativeEnumName) {
1845
+ t = 'enum';
1846
+ }
1847
+ else if (prop.enum) {
1848
+ t = prop.items?.every(item => typeof item === 'string') ? 'enum' : 'tinyint';
1849
+ }
1850
+ if (t === 'Date') {
1851
+ t = 'datetime';
1852
+ }
1853
+ return this.#platform.getMappedType(t);
1854
+ }
1855
+ getPrefix(prop, parent) {
1856
+ const { embeddedPath = [], fieldNames, prefix = true, prefixMode } = prop;
1857
+ if (prefix === true) {
1858
+ return (embeddedPath.length ? embeddedPath.join('_') : fieldNames[0]) + '_';
1859
+ }
1860
+ const prefixParent = parent ? this.getPrefix(parent, null) : '';
1861
+ if (prefix === false) {
1862
+ return prefixParent;
1863
+ }
1864
+ const mode = prefixMode ?? this.#config.get('embeddables').prefixMode;
1865
+ return mode === 'absolute' ? prefix : prefixParent + prefix;
1866
+ }
1867
+ initUnsigned(prop) {
1868
+ if (prop.unsigned != null) {
1869
+ return;
1870
+ }
1871
+ if ([ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(prop.kind)) {
1872
+ prop.unsigned = prop.targetMeta.getPrimaryProps().some(pk => {
1873
+ this.initUnsigned(pk);
1874
+ return pk.unsigned;
1875
+ });
1876
+ return;
1877
+ }
1878
+ prop.unsigned ??=
1879
+ (prop.primary || prop.unsigned) && this.#platform.isNumericProperty(prop) && this.#platform.supportsUnsigned();
1880
+ }
1881
+ initIndexes(meta, prop) {
1882
+ const hasIndex = meta.indexes.some(idx => idx.properties?.length === 1 && idx.properties[0] === prop.name);
1883
+ if (prop.kind === ReferenceKind.MANY_TO_ONE && this.#platform.indexForeignKeys() && !hasIndex) {
1884
+ prop.index ??= true;
1885
+ }
1886
+ }
1887
+ shouldForceConstructorUsage(meta) {
1888
+ const forceConstructor = this.#config.get('forceEntityConstructor');
1889
+ if (Array.isArray(forceConstructor)) {
1890
+ return forceConstructor.some(cls => Utils.className(cls) === meta.className);
1891
+ }
1892
+ return forceConstructor;
1893
+ }
1970
1894
  }