@mikro-orm/core 7.0.2 → 7.0.3-dev.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (205) hide show
  1. package/EntityManager.d.ts +583 -883
  2. package/EntityManager.js +1869 -1897
  3. package/MikroORM.d.ts +74 -103
  4. package/MikroORM.js +179 -178
  5. package/cache/CacheAdapter.d.ts +36 -36
  6. package/cache/FileCacheAdapter.d.ts +24 -30
  7. package/cache/FileCacheAdapter.js +78 -80
  8. package/cache/GeneratedCacheAdapter.d.ts +20 -18
  9. package/cache/GeneratedCacheAdapter.js +30 -30
  10. package/cache/MemoryCacheAdapter.d.ts +20 -18
  11. package/cache/MemoryCacheAdapter.js +36 -35
  12. package/cache/NullCacheAdapter.d.ts +16 -16
  13. package/cache/NullCacheAdapter.js +24 -24
  14. package/connections/Connection.d.ts +84 -95
  15. package/connections/Connection.js +168 -165
  16. package/drivers/DatabaseDriver.d.ts +80 -186
  17. package/drivers/DatabaseDriver.js +443 -450
  18. package/drivers/IDatabaseDriver.d.ts +301 -440
  19. package/entity/BaseEntity.d.ts +83 -120
  20. package/entity/BaseEntity.js +43 -43
  21. package/entity/Collection.d.ts +179 -212
  22. package/entity/Collection.js +721 -727
  23. package/entity/EntityAssigner.d.ts +77 -88
  24. package/entity/EntityAssigner.js +230 -231
  25. package/entity/EntityFactory.d.ts +54 -66
  26. package/entity/EntityFactory.js +383 -425
  27. package/entity/EntityHelper.d.ts +22 -34
  28. package/entity/EntityHelper.js +267 -280
  29. package/entity/EntityIdentifier.d.ts +4 -4
  30. package/entity/EntityIdentifier.js +10 -10
  31. package/entity/EntityLoader.d.ts +73 -103
  32. package/entity/EntityLoader.js +723 -753
  33. package/entity/EntityRepository.d.ts +201 -316
  34. package/entity/EntityRepository.js +213 -213
  35. package/entity/PolymorphicRef.d.ts +5 -5
  36. package/entity/PolymorphicRef.js +10 -10
  37. package/entity/Reference.d.ts +82 -126
  38. package/entity/Reference.js +274 -278
  39. package/entity/WrappedEntity.d.ts +72 -115
  40. package/entity/WrappedEntity.js +166 -168
  41. package/entity/defineEntity.d.ts +614 -1280
  42. package/entity/defineEntity.js +511 -520
  43. package/entity/utils.d.ts +3 -13
  44. package/entity/utils.js +73 -71
  45. package/entity/validators.js +43 -43
  46. package/entity/wrap.js +8 -8
  47. package/enums.d.ts +253 -258
  48. package/enums.js +252 -251
  49. package/errors.d.ts +72 -114
  50. package/errors.js +253 -350
  51. package/events/EventManager.d.ts +14 -26
  52. package/events/EventManager.js +77 -79
  53. package/events/EventSubscriber.d.ts +29 -29
  54. package/events/TransactionEventBroadcaster.d.ts +8 -15
  55. package/events/TransactionEventBroadcaster.js +14 -14
  56. package/exceptions.d.ts +40 -23
  57. package/exceptions.js +52 -35
  58. package/hydration/Hydrator.d.ts +17 -42
  59. package/hydration/Hydrator.js +43 -43
  60. package/hydration/ObjectHydrator.d.ts +17 -50
  61. package/hydration/ObjectHydrator.js +416 -479
  62. package/index.d.ts +2 -116
  63. package/index.js +1 -10
  64. package/logging/DefaultLogger.d.ts +32 -34
  65. package/logging/DefaultLogger.js +86 -86
  66. package/logging/Logger.d.ts +41 -41
  67. package/logging/SimpleLogger.d.ts +11 -13
  68. package/logging/SimpleLogger.js +22 -22
  69. package/logging/colors.d.ts +6 -6
  70. package/logging/colors.js +10 -11
  71. package/logging/inspect.js +7 -7
  72. package/metadata/EntitySchema.d.ts +127 -211
  73. package/metadata/EntitySchema.js +398 -397
  74. package/metadata/MetadataDiscovery.d.ts +114 -114
  75. package/metadata/MetadataDiscovery.js +1863 -1947
  76. package/metadata/MetadataProvider.d.ts +21 -24
  77. package/metadata/MetadataProvider.js +84 -82
  78. package/metadata/MetadataStorage.d.ts +32 -38
  79. package/metadata/MetadataStorage.js +118 -118
  80. package/metadata/MetadataValidator.d.ts +39 -39
  81. package/metadata/MetadataValidator.js +338 -381
  82. package/metadata/discover-entities.d.ts +2 -5
  83. package/metadata/discover-entities.js +27 -27
  84. package/metadata/types.d.ts +531 -615
  85. package/naming-strategy/AbstractNamingStrategy.d.ts +39 -54
  86. package/naming-strategy/AbstractNamingStrategy.js +85 -90
  87. package/naming-strategy/EntityCaseNamingStrategy.d.ts +6 -6
  88. package/naming-strategy/EntityCaseNamingStrategy.js +22 -22
  89. package/naming-strategy/MongoNamingStrategy.d.ts +6 -6
  90. package/naming-strategy/MongoNamingStrategy.js +18 -18
  91. package/naming-strategy/NamingStrategy.d.ts +99 -109
  92. package/naming-strategy/UnderscoreNamingStrategy.d.ts +7 -7
  93. package/naming-strategy/UnderscoreNamingStrategy.js +21 -21
  94. package/not-supported.js +4 -7
  95. package/package.json +1 -1
  96. package/platforms/ExceptionConverter.d.ts +1 -1
  97. package/platforms/ExceptionConverter.js +4 -4
  98. package/platforms/Platform.d.ts +299 -308
  99. package/platforms/Platform.js +636 -659
  100. package/serialization/EntitySerializer.d.ts +26 -48
  101. package/serialization/EntitySerializer.js +218 -224
  102. package/serialization/EntityTransformer.d.ts +6 -10
  103. package/serialization/EntityTransformer.js +217 -219
  104. package/serialization/SerializationContext.d.ts +23 -27
  105. package/serialization/SerializationContext.js +105 -105
  106. package/types/ArrayType.d.ts +8 -8
  107. package/types/ArrayType.js +33 -33
  108. package/types/BigIntType.d.ts +10 -17
  109. package/types/BigIntType.js +37 -37
  110. package/types/BlobType.d.ts +3 -3
  111. package/types/BlobType.js +13 -13
  112. package/types/BooleanType.d.ts +4 -4
  113. package/types/BooleanType.js +12 -12
  114. package/types/CharacterType.d.ts +2 -2
  115. package/types/CharacterType.js +6 -6
  116. package/types/DateTimeType.d.ts +5 -5
  117. package/types/DateTimeType.js +15 -15
  118. package/types/DateType.d.ts +5 -5
  119. package/types/DateType.js +15 -15
  120. package/types/DecimalType.d.ts +7 -7
  121. package/types/DecimalType.js +26 -26
  122. package/types/DoubleType.d.ts +3 -3
  123. package/types/DoubleType.js +12 -12
  124. package/types/EnumArrayType.d.ts +5 -5
  125. package/types/EnumArrayType.js +24 -24
  126. package/types/EnumType.d.ts +3 -3
  127. package/types/EnumType.js +11 -11
  128. package/types/FloatType.d.ts +3 -3
  129. package/types/FloatType.js +9 -9
  130. package/types/IntegerType.d.ts +3 -3
  131. package/types/IntegerType.js +9 -9
  132. package/types/IntervalType.d.ts +4 -4
  133. package/types/IntervalType.js +12 -12
  134. package/types/JsonType.d.ts +8 -8
  135. package/types/JsonType.js +32 -32
  136. package/types/MediumIntType.d.ts +1 -1
  137. package/types/MediumIntType.js +3 -3
  138. package/types/SmallIntType.d.ts +3 -3
  139. package/types/SmallIntType.js +9 -9
  140. package/types/StringType.d.ts +4 -4
  141. package/types/StringType.js +12 -12
  142. package/types/TextType.d.ts +3 -3
  143. package/types/TextType.js +9 -9
  144. package/types/TimeType.d.ts +5 -5
  145. package/types/TimeType.js +17 -17
  146. package/types/TinyIntType.d.ts +3 -3
  147. package/types/TinyIntType.js +10 -10
  148. package/types/Type.d.ts +79 -83
  149. package/types/Type.js +82 -82
  150. package/types/Uint8ArrayType.d.ts +4 -4
  151. package/types/Uint8ArrayType.js +21 -21
  152. package/types/UnknownType.d.ts +4 -4
  153. package/types/UnknownType.js +12 -12
  154. package/types/UuidType.d.ts +5 -5
  155. package/types/UuidType.js +19 -19
  156. package/types/index.d.ts +49 -75
  157. package/types/index.js +26 -52
  158. package/typings.d.ts +729 -1211
  159. package/typings.js +231 -244
  160. package/unit-of-work/ChangeSet.d.ts +26 -26
  161. package/unit-of-work/ChangeSet.js +56 -56
  162. package/unit-of-work/ChangeSetComputer.d.ts +12 -12
  163. package/unit-of-work/ChangeSetComputer.js +170 -178
  164. package/unit-of-work/ChangeSetPersister.d.ts +44 -63
  165. package/unit-of-work/ChangeSetPersister.js +421 -442
  166. package/unit-of-work/CommitOrderCalculator.d.ts +40 -40
  167. package/unit-of-work/CommitOrderCalculator.js +88 -89
  168. package/unit-of-work/IdentityMap.d.ts +31 -31
  169. package/unit-of-work/IdentityMap.js +105 -105
  170. package/unit-of-work/UnitOfWork.d.ts +141 -181
  171. package/unit-of-work/UnitOfWork.js +1183 -1200
  172. package/utils/AbstractMigrator.d.ts +91 -111
  173. package/utils/AbstractMigrator.js +275 -275
  174. package/utils/AbstractSchemaGenerator.d.ts +34 -43
  175. package/utils/AbstractSchemaGenerator.js +122 -121
  176. package/utils/AsyncContext.d.ts +3 -3
  177. package/utils/AsyncContext.js +35 -34
  178. package/utils/Configuration.d.ts +808 -852
  179. package/utils/Configuration.js +344 -359
  180. package/utils/Cursor.d.ts +22 -40
  181. package/utils/Cursor.js +127 -135
  182. package/utils/DataloaderUtils.d.ts +43 -58
  183. package/utils/DataloaderUtils.js +198 -203
  184. package/utils/EntityComparator.d.ts +81 -98
  185. package/utils/EntityComparator.js +728 -824
  186. package/utils/NullHighlighter.d.ts +1 -1
  187. package/utils/NullHighlighter.js +3 -3
  188. package/utils/QueryHelper.d.ts +51 -79
  189. package/utils/QueryHelper.js +361 -372
  190. package/utils/RawQueryFragment.d.ts +34 -50
  191. package/utils/RawQueryFragment.js +105 -107
  192. package/utils/RequestContext.d.ts +32 -32
  193. package/utils/RequestContext.js +53 -52
  194. package/utils/TransactionContext.d.ts +16 -16
  195. package/utils/TransactionContext.js +27 -27
  196. package/utils/TransactionManager.d.ts +58 -58
  197. package/utils/TransactionManager.js +197 -199
  198. package/utils/Utils.d.ts +145 -204
  199. package/utils/Utils.js +813 -814
  200. package/utils/clone.js +113 -104
  201. package/utils/env-vars.js +88 -90
  202. package/utils/fs-utils.d.ts +15 -15
  203. package/utils/fs-utils.js +181 -180
  204. package/utils/upsert-utils.d.ts +5 -20
  205. package/utils/upsert-utils.js +116 -114
@@ -8,492 +8,429 @@ import { Raw } from '../utils/RawQueryFragment.js';
8
8
  import { ValidationError } from '../errors.js';
9
9
  /** @internal JIT-compiled hydrator that converts raw database rows into entity instances with optimized generated code. */
10
10
  export class ObjectHydrator extends Hydrator {
11
- #hydrators = {
12
- 'full~true': new Map(),
13
- 'full~false': new Map(),
14
- 'reference~true': new Map(),
15
- 'reference~false': new Map(),
16
- };
17
- #tmpIndex = 0;
18
- /**
19
- * @inheritDoc
20
- */
21
- hydrate(
22
- entity,
23
- meta,
24
- data,
25
- factory,
26
- type,
27
- newEntity = false,
28
- convertCustomTypes = false,
29
- schema,
30
- parentSchema,
31
- normalizeAccessors,
32
- ) {
33
- const hydrate = this.getEntityHydrator(meta, type, normalizeAccessors);
34
- const running = this.running;
35
- // the running state is used to consider propagation as hydration, saving the values directly to the entity data,
36
- // but we don't want that for new entities, their propagation should result in entity updates when flushing
37
- this.running = !newEntity;
38
- Utils.callCompiledFunction(
39
- hydrate,
40
- entity,
41
- data,
42
- factory,
43
- newEntity,
44
- convertCustomTypes,
45
- schema,
46
- parentSchema,
47
- normalizeAccessors,
48
- );
49
- this.running = running;
50
- }
51
- /**
52
- * @inheritDoc
53
- */
54
- hydrateReference(entity, meta, data, factory, convertCustomTypes = false, schema, parentSchema, normalizeAccessors) {
55
- const hydrate = this.getEntityHydrator(meta, 'reference', normalizeAccessors);
56
- const running = this.running;
57
- this.running = true;
58
- Utils.callCompiledFunction(
59
- hydrate,
60
- entity,
61
- data,
62
- factory,
63
- false,
64
- convertCustomTypes,
65
- schema,
66
- parentSchema,
67
- normalizeAccessors,
68
- );
69
- this.running = running;
70
- }
71
- /**
72
- * @internal Highly performance-sensitive method.
73
- */
74
- getEntityHydrator(meta, type, normalizeAccessors = false) {
75
- const key = `${type}~${normalizeAccessors}`;
76
- const exists = this.#hydrators[key].get(meta.class);
77
- if (exists) {
78
- return exists;
79
- }
80
- const lines = [];
81
- const context = new Map();
82
- const props = this.getProperties(meta, type);
83
- context.set('isPrimaryKey', Utils.isPrimaryKey);
84
- context.set('Collection', Collection);
85
- context.set('Reference', Reference);
86
- context.set('PolymorphicRef', PolymorphicRef);
87
- context.set('ValidationError', ValidationError);
88
- const registerCustomType = (prop, convertorKey, method, context) => {
89
- context.set(`${method}_${convertorKey}`, val => {
90
- /* v8 ignore next */
91
- if (Raw.isKnownFragment(val)) {
92
- return val;
93
- }
94
- return prop.customType[method](val, this.platform, { mode: 'serialization' });
95
- });
96
- return convertorKey;
97
- };
98
- const hydrateScalar = (prop, path, dataKey) => {
99
- const entityKey = path.map(k => this.wrap(k)).join('');
100
- const tz = this.platform.getTimezone();
101
- const convertorKey = path
102
- .filter(k => !/\[idx_\d+]/.exec(k))
103
- .map(k => this.safeKey(k))
104
- .join('_');
105
- const ret = [];
106
- const idx = this.#tmpIndex++;
107
- const nullVal = this.config.get('forceUndefined') ? 'undefined' : 'null';
108
- if (prop.getter && !prop.setter && prop.persist === false) {
109
- return [];
110
- }
111
- if (prop.ref) {
112
- context.set('ScalarReference', ScalarReference);
113
- ret.push(` const oldValue_${idx} = entity${entityKey};`);
114
- }
115
- ret.push(` if (data${dataKey} === null) {`);
116
- if (prop.ref) {
117
- ret.push(` entity${entityKey} = new ScalarReference();`);
118
- ret.push(` entity${entityKey}.bind(entity, '${prop.name}');`);
119
- ret.push(` entity${entityKey}.set(${nullVal});`);
120
- } else {
121
- ret.push(` entity${entityKey} = ${nullVal};`);
122
- }
123
- ret.push(` } else if (typeof data${dataKey} !== 'undefined') {`);
124
- if (prop.customType) {
125
- registerCustomType(prop, convertorKey, 'convertToJSValue', context);
126
- registerCustomType(prop, convertorKey, 'convertToDatabaseValue', context);
127
- ret.push(
128
- ` if (convertCustomTypes) {`,
129
- ` const value = convertToJSValue_${convertorKey}(data${dataKey});`,
130
- );
131
- if (prop.customType.ensureComparable(meta, prop)) {
132
- ret.push(` data${dataKey} = convertToDatabaseValue_${convertorKey}(value);`);
133
- }
134
- ret.push(
135
- ` entity${entityKey} = value;`,
136
- ` } else {`,
137
- ` entity${entityKey} = data${dataKey};`,
138
- ` }`,
139
- );
140
- } else if (prop.runtimeType === 'boolean') {
141
- ret.push(` entity${entityKey} = !!data${dataKey};`);
142
- } else if (prop.runtimeType === 'Date' && !this.platform.isNumericProperty(prop)) {
143
- ret.push(` if (data${dataKey} instanceof Date) {`);
144
- ret.push(` entity${entityKey} = data${dataKey};`);
145
- if (!tz || tz === 'local') {
146
- ret.push(` } else {`);
147
- ret.push(` entity${entityKey} = new Date(data${dataKey});`);
148
- } else {
149
- ret.push(
150
- ` } else if (typeof data${dataKey} === 'number' || data${dataKey}.includes('+') || data${dataKey}.lastIndexOf('-') > 10 || data${dataKey}.endsWith('Z')) {`,
151
- );
152
- ret.push(` entity${entityKey} = new Date(data${dataKey});`);
153
- ret.push(` } else {`);
154
- ret.push(` entity${entityKey} = new Date(data${dataKey} + '${tz}');`);
155
- }
156
- ret.push(` }`);
157
- } else {
158
- ret.push(` entity${entityKey} = data${dataKey};`);
159
- }
160
- if (prop.ref) {
161
- ret.push(` const value = entity${entityKey};`);
162
- ret.push(` entity${entityKey} = oldValue_${idx} ?? new ScalarReference(value);`);
163
- ret.push(` entity${entityKey}.bind(entity, '${prop.name}');`);
164
- ret.push(` entity${entityKey}.set(value);`);
165
- }
166
- ret.push(` }`);
167
- if (prop.ref) {
168
- ret.push(` if (!entity${entityKey}) {`);
169
- ret.push(` entity${entityKey} = new ScalarReference();`);
170
- ret.push(` entity${entityKey}.bind(entity, '${prop.name}');`);
171
- ret.push(` }`);
172
- }
173
- return ret;
11
+ #hydrators = {
12
+ 'full~true': new Map(),
13
+ 'full~false': new Map(),
14
+ 'reference~true': new Map(),
15
+ 'reference~false': new Map(),
174
16
  };
175
- const hydrateToOne = (prop, dataKey, entityKey) => {
176
- const ret = [];
177
- const method = type === 'reference' ? 'createReference' : 'create';
178
- const nullVal = this.config.get('forceUndefined') ? 'undefined' : 'null';
179
- ret.push(` if (data${dataKey} === null) {\n entity${entityKey} = ${nullVal};`);
180
- ret.push(` } else if (typeof data${dataKey} !== 'undefined') {`);
181
- // For polymorphic: instanceof check; for regular: isPrimaryKey() check
182
- const pkCheck = prop.polymorphic
183
- ? `data${dataKey} instanceof PolymorphicRef`
184
- : `isPrimaryKey(data${dataKey}, true)`;
185
- ret.push(` if (${pkCheck}) {`);
186
- // When targetKey is set, pass the key option to createReference so it uses the alternate key
187
- const keyOption = prop.targetKey ? `, key: '${prop.targetKey}'` : '';
188
- if (prop.polymorphic) {
189
- // For polymorphic: target class from discriminator map, PK from data.id
190
- const discriminatorMapKey = this.safeKey(`discriminatorMap_${prop.name}_${this.#tmpIndex++}`);
191
- context.set(discriminatorMapKey, prop.discriminatorMap);
192
- ret.push(` const targetClass = ${discriminatorMapKey}[data${dataKey}.discriminator];`);
193
- ret.push(
194
- ` if (!targetClass) throw new ValidationError(\`Unknown discriminator value '\${data${dataKey}.discriminator}' for polymorphic relation '${prop.name}'. Valid values: \${Object.keys(${discriminatorMapKey}).join(', ')}\`);`,
195
- );
196
- if (prop.ref) {
197
- ret.push(
198
- ` entity${entityKey} = Reference.create(factory.createReference(targetClass, data${dataKey}.id, { merge: true, convertCustomTypes, normalizeAccessors, schema${keyOption} }));`,
199
- );
200
- } else {
201
- ret.push(
202
- ` entity${entityKey} = factory.createReference(targetClass, data${dataKey}.id, { merge: true, convertCustomTypes, normalizeAccessors, schema${keyOption} });`,
203
- );
204
- }
205
- } else {
206
- // For regular: fixed target class, PK is the data itself
207
- const targetKey = this.safeKey(`${prop.targetMeta.tableName}_${this.#tmpIndex++}`);
208
- context.set(targetKey, prop.targetMeta.class);
209
- if (prop.ref) {
210
- ret.push(
211
- ` entity${entityKey} = Reference.create(factory.createReference(${targetKey}, data${dataKey}, { merge: true, convertCustomTypes, normalizeAccessors, schema${keyOption} }));`,
212
- );
213
- } else {
214
- ret.push(
215
- ` entity${entityKey} = factory.createReference(${targetKey}, data${dataKey}, { merge: true, convertCustomTypes, normalizeAccessors, schema${keyOption} });`,
216
- );
17
+ #tmpIndex = 0;
18
+ /**
19
+ * @inheritDoc
20
+ */
21
+ hydrate(entity, meta, data, factory, type, newEntity = false, convertCustomTypes = false, schema, parentSchema, normalizeAccessors) {
22
+ const hydrate = this.getEntityHydrator(meta, type, normalizeAccessors);
23
+ const running = this.running;
24
+ // the running state is used to consider propagation as hydration, saving the values directly to the entity data,
25
+ // but we don't want that for new entities, their propagation should result in entity updates when flushing
26
+ this.running = !newEntity;
27
+ Utils.callCompiledFunction(hydrate, entity, data, factory, newEntity, convertCustomTypes, schema, parentSchema, normalizeAccessors);
28
+ this.running = running;
29
+ }
30
+ /**
31
+ * @inheritDoc
32
+ */
33
+ hydrateReference(entity, meta, data, factory, convertCustomTypes = false, schema, parentSchema, normalizeAccessors) {
34
+ const hydrate = this.getEntityHydrator(meta, 'reference', normalizeAccessors);
35
+ const running = this.running;
36
+ this.running = true;
37
+ Utils.callCompiledFunction(hydrate, entity, data, factory, false, convertCustomTypes, schema, parentSchema, normalizeAccessors);
38
+ this.running = running;
39
+ }
40
+ /**
41
+ * @internal Highly performance-sensitive method.
42
+ */
43
+ getEntityHydrator(meta, type, normalizeAccessors = false) {
44
+ const key = `${type}~${normalizeAccessors}`;
45
+ const exists = this.#hydrators[key].get(meta.class);
46
+ if (exists) {
47
+ return exists;
217
48
  }
218
- }
219
- ret.push(` } else if (data${dataKey} && typeof data${dataKey} === 'object') {`);
220
- // For full entity hydration, polymorphic needs to determine target class from entity itself
221
- let hydrateTargetExpr;
222
- if (prop.polymorphic) {
223
- hydrateTargetExpr = `data${dataKey}.constructor`;
224
- } else {
225
- const targetKey = this.safeKey(`${prop.targetMeta.tableName}_${this.#tmpIndex++}`);
226
- context.set(targetKey, prop.targetMeta.class);
227
- hydrateTargetExpr = targetKey;
228
- }
229
- if (prop.ref) {
230
- ret.push(
231
- ` entity${entityKey} = Reference.create(factory.${method}(${hydrateTargetExpr}, data${dataKey}, { initialized: true, merge: true, newEntity, convertCustomTypes, normalizeAccessors, schema }));`,
232
- );
233
- } else {
234
- ret.push(
235
- ` entity${entityKey} = factory.${method}(${hydrateTargetExpr}, data${dataKey}, { initialized: true, merge: true, newEntity, convertCustomTypes, normalizeAccessors, schema });`,
236
- );
237
- }
238
- ret.push(` }`);
239
- ret.push(` }`);
240
- if (prop.kind === ReferenceKind.ONE_TO_ONE) {
241
- const meta2 = this.metadata.get(prop.targetMeta.class);
242
- const prop2 = meta2.properties[prop.inversedBy || prop.mappedBy];
243
- if (prop2 && !prop2.mapToPk) {
244
- ret.push(` if (data${dataKey} && entity${entityKey} && !entity${entityKey}.${this.safeKey(prop2.name)}) {`);
245
- ret.push(
246
- ` entity${entityKey}.${prop.ref ? 'unwrap().' : ''}${this.safeKey(prop2.name)} = ${prop2.ref ? 'Reference.create(entity)' : 'entity'};`,
247
- );
248
- ret.push(` }`);
49
+ const lines = [];
50
+ const context = new Map();
51
+ const props = this.getProperties(meta, type);
52
+ context.set('isPrimaryKey', Utils.isPrimaryKey);
53
+ context.set('Collection', Collection);
54
+ context.set('Reference', Reference);
55
+ context.set('PolymorphicRef', PolymorphicRef);
56
+ context.set('ValidationError', ValidationError);
57
+ const registerCustomType = (prop, convertorKey, method, context) => {
58
+ context.set(`${method}_${convertorKey}`, (val) => {
59
+ /* v8 ignore next */
60
+ if (Raw.isKnownFragment(val)) {
61
+ return val;
62
+ }
63
+ return prop.customType[method](val, this.platform, { mode: 'serialization' });
64
+ });
65
+ return convertorKey;
66
+ };
67
+ const hydrateScalar = (prop, path, dataKey) => {
68
+ const entityKey = path.map(k => this.wrap(k)).join('');
69
+ const tz = this.platform.getTimezone();
70
+ const convertorKey = path
71
+ .filter(k => !/\[idx_\d+]/.exec(k))
72
+ .map(k => this.safeKey(k))
73
+ .join('_');
74
+ const ret = [];
75
+ const idx = this.#tmpIndex++;
76
+ const nullVal = this.config.get('forceUndefined') ? 'undefined' : 'null';
77
+ if (prop.getter && !prop.setter && prop.persist === false) {
78
+ return [];
79
+ }
80
+ if (prop.ref) {
81
+ context.set('ScalarReference', ScalarReference);
82
+ ret.push(` const oldValue_${idx} = entity${entityKey};`);
83
+ }
84
+ ret.push(` if (data${dataKey} === null) {`);
85
+ if (prop.ref) {
86
+ ret.push(` entity${entityKey} = new ScalarReference();`);
87
+ ret.push(` entity${entityKey}.bind(entity, '${prop.name}');`);
88
+ ret.push(` entity${entityKey}.set(${nullVal});`);
89
+ }
90
+ else {
91
+ ret.push(` entity${entityKey} = ${nullVal};`);
92
+ }
93
+ ret.push(` } else if (typeof data${dataKey} !== 'undefined') {`);
94
+ if (prop.customType) {
95
+ registerCustomType(prop, convertorKey, 'convertToJSValue', context);
96
+ registerCustomType(prop, convertorKey, 'convertToDatabaseValue', context);
97
+ ret.push(` if (convertCustomTypes) {`, ` const value = convertToJSValue_${convertorKey}(data${dataKey});`);
98
+ if (prop.customType.ensureComparable(meta, prop)) {
99
+ ret.push(` data${dataKey} = convertToDatabaseValue_${convertorKey}(value);`);
100
+ }
101
+ ret.push(` entity${entityKey} = value;`, ` } else {`, ` entity${entityKey} = data${dataKey};`, ` }`);
102
+ }
103
+ else if (prop.runtimeType === 'boolean') {
104
+ ret.push(` entity${entityKey} = !!data${dataKey};`);
105
+ }
106
+ else if (prop.runtimeType === 'Date' && !this.platform.isNumericProperty(prop)) {
107
+ ret.push(` if (data${dataKey} instanceof Date) {`);
108
+ ret.push(` entity${entityKey} = data${dataKey};`);
109
+ if (!tz || tz === 'local') {
110
+ ret.push(` } else {`);
111
+ ret.push(` entity${entityKey} = new Date(data${dataKey});`);
112
+ }
113
+ else {
114
+ ret.push(` } else if (typeof data${dataKey} === 'number' || data${dataKey}.includes('+') || data${dataKey}.lastIndexOf('-') > 10 || data${dataKey}.endsWith('Z')) {`);
115
+ ret.push(` entity${entityKey} = new Date(data${dataKey});`);
116
+ ret.push(` } else {`);
117
+ ret.push(` entity${entityKey} = new Date(data${dataKey} + '${tz}');`);
118
+ }
119
+ ret.push(` }`);
120
+ }
121
+ else {
122
+ ret.push(` entity${entityKey} = data${dataKey};`);
123
+ }
124
+ if (prop.ref) {
125
+ ret.push(` const value = entity${entityKey};`);
126
+ ret.push(` entity${entityKey} = oldValue_${idx} ?? new ScalarReference(value);`);
127
+ ret.push(` entity${entityKey}.bind(entity, '${prop.name}');`);
128
+ ret.push(` entity${entityKey}.set(value);`);
129
+ }
130
+ ret.push(` }`);
131
+ if (prop.ref) {
132
+ ret.push(` if (!entity${entityKey}) {`);
133
+ ret.push(` entity${entityKey} = new ScalarReference();`);
134
+ ret.push(` entity${entityKey}.bind(entity, '${prop.name}');`);
135
+ ret.push(` }`);
136
+ }
137
+ return ret;
138
+ };
139
+ const hydrateToOne = (prop, dataKey, entityKey) => {
140
+ const ret = [];
141
+ const method = type === 'reference' ? 'createReference' : 'create';
142
+ const nullVal = this.config.get('forceUndefined') ? 'undefined' : 'null';
143
+ ret.push(` if (data${dataKey} === null) {\n entity${entityKey} = ${nullVal};`);
144
+ ret.push(` } else if (typeof data${dataKey} !== 'undefined') {`);
145
+ // For polymorphic: instanceof check; for regular: isPrimaryKey() check
146
+ const pkCheck = prop.polymorphic
147
+ ? `data${dataKey} instanceof PolymorphicRef`
148
+ : `isPrimaryKey(data${dataKey}, true)`;
149
+ ret.push(` if (${pkCheck}) {`);
150
+ // When targetKey is set, pass the key option to createReference so it uses the alternate key
151
+ const keyOption = prop.targetKey ? `, key: '${prop.targetKey}'` : '';
152
+ if (prop.polymorphic) {
153
+ // For polymorphic: target class from discriminator map, PK from data.id
154
+ const discriminatorMapKey = this.safeKey(`discriminatorMap_${prop.name}_${this.#tmpIndex++}`);
155
+ context.set(discriminatorMapKey, prop.discriminatorMap);
156
+ ret.push(` const targetClass = ${discriminatorMapKey}[data${dataKey}.discriminator];`);
157
+ ret.push(` if (!targetClass) throw new ValidationError(\`Unknown discriminator value '\${data${dataKey}.discriminator}' for polymorphic relation '${prop.name}'. Valid values: \${Object.keys(${discriminatorMapKey}).join(', ')}\`);`);
158
+ if (prop.ref) {
159
+ ret.push(` entity${entityKey} = Reference.create(factory.createReference(targetClass, data${dataKey}.id, { merge: true, convertCustomTypes, normalizeAccessors, schema${keyOption} }));`);
160
+ }
161
+ else {
162
+ ret.push(` entity${entityKey} = factory.createReference(targetClass, data${dataKey}.id, { merge: true, convertCustomTypes, normalizeAccessors, schema${keyOption} });`);
163
+ }
164
+ }
165
+ else {
166
+ // For regular: fixed target class, PK is the data itself
167
+ const targetKey = this.safeKey(`${prop.targetMeta.tableName}_${this.#tmpIndex++}`);
168
+ context.set(targetKey, prop.targetMeta.class);
169
+ if (prop.ref) {
170
+ ret.push(` entity${entityKey} = Reference.create(factory.createReference(${targetKey}, data${dataKey}, { merge: true, convertCustomTypes, normalizeAccessors, schema${keyOption} }));`);
171
+ }
172
+ else {
173
+ ret.push(` entity${entityKey} = factory.createReference(${targetKey}, data${dataKey}, { merge: true, convertCustomTypes, normalizeAccessors, schema${keyOption} });`);
174
+ }
175
+ }
176
+ ret.push(` } else if (data${dataKey} && typeof data${dataKey} === 'object') {`);
177
+ // For full entity hydration, polymorphic needs to determine target class from entity itself
178
+ let hydrateTargetExpr;
179
+ if (prop.polymorphic) {
180
+ hydrateTargetExpr = `data${dataKey}.constructor`;
181
+ }
182
+ else {
183
+ const targetKey = this.safeKey(`${prop.targetMeta.tableName}_${this.#tmpIndex++}`);
184
+ context.set(targetKey, prop.targetMeta.class);
185
+ hydrateTargetExpr = targetKey;
186
+ }
187
+ if (prop.ref) {
188
+ ret.push(` entity${entityKey} = Reference.create(factory.${method}(${hydrateTargetExpr}, data${dataKey}, { initialized: true, merge: true, newEntity, convertCustomTypes, normalizeAccessors, schema }));`);
189
+ }
190
+ else {
191
+ ret.push(` entity${entityKey} = factory.${method}(${hydrateTargetExpr}, data${dataKey}, { initialized: true, merge: true, newEntity, convertCustomTypes, normalizeAccessors, schema });`);
192
+ }
193
+ ret.push(` }`);
194
+ ret.push(` }`);
195
+ if (prop.kind === ReferenceKind.ONE_TO_ONE) {
196
+ const meta2 = this.metadata.get(prop.targetMeta.class);
197
+ const prop2 = meta2.properties[prop.inversedBy || prop.mappedBy];
198
+ if (prop2 && !prop2.mapToPk) {
199
+ ret.push(` if (data${dataKey} && entity${entityKey} && !entity${entityKey}.${this.safeKey(prop2.name)}) {`);
200
+ ret.push(` entity${entityKey}.${prop.ref ? 'unwrap().' : ''}${this.safeKey(prop2.name)} = ${prop2.ref ? 'Reference.create(entity)' : 'entity'};`);
201
+ ret.push(` }`);
202
+ }
203
+ }
204
+ if (prop.customType?.ensureComparable(meta, prop)) {
205
+ registerCustomType(prop, this.safeKey(prop.name), 'convertToDatabaseValue', context);
206
+ ret.push(` if (data${dataKey} != null && typeof data${dataKey} !== 'object' && convertCustomTypes) {`);
207
+ ret.push(` data${dataKey} = convertToDatabaseValue_${this.safeKey(prop.name)}(entity${entityKey}.__helper.getPrimaryKey());`);
208
+ ret.push(` }`);
209
+ }
210
+ return ret;
211
+ };
212
+ const hydrateToMany = (prop, dataKey, entityKey) => {
213
+ const ret = [];
214
+ ret.push(...this.createCollectionItemMapper(prop, context));
215
+ ret.push(` if (data${dataKey} && !Array.isArray(data${dataKey}) && typeof data${dataKey} === 'object') {`);
216
+ ret.push(` data${dataKey} = [data${dataKey}];`);
217
+ ret.push(` }`);
218
+ ret.push(` if (Array.isArray(data${dataKey})) {`);
219
+ ret.push(` const items = data${dataKey}.map(value => createCollectionItem_${this.safeKey(prop.name)}(value, entity));`);
220
+ ret.push(` const coll = Collection.create(entity, '${prop.name}', items, newEntity);`);
221
+ ret.push(` if (newEntity) {`);
222
+ ret.push(` coll.setDirty();`);
223
+ ret.push(` } else {`);
224
+ ret.push(` coll.takeSnapshot(true);`);
225
+ ret.push(` }`);
226
+ ret.push(` } else if (!entity${entityKey} && data${dataKey} instanceof Collection) {`);
227
+ ret.push(` entity${entityKey} = data${dataKey};`);
228
+ if (!this.platform.usesPivotTable() && prop.owner && prop.kind === ReferenceKind.MANY_TO_MANY) {
229
+ ret.push(` } else if (!entity${entityKey} && Array.isArray(data${dataKey})) {`);
230
+ const items = this.platform.usesPivotTable() || !prop.owner ? 'undefined' : '[]';
231
+ ret.push(` const coll = Collection.create(entity, '${prop.name}', ${items}, !!data${dataKey} || newEntity);`);
232
+ ret.push(` coll.setDirty(false);`);
233
+ }
234
+ ret.push(` } else if (!entity${entityKey}) {`);
235
+ ret.push(` const coll = Collection.create(entity, '${prop.name}', undefined, newEntity);`);
236
+ ret.push(` coll.setDirty(false);`);
237
+ ret.push(` }`);
238
+ return ret;
239
+ };
240
+ const registerEmbeddedPrototype = (prop, path) => {
241
+ const convertorKey = path
242
+ .filter(k => !/\[idx_\d+]/.exec(k))
243
+ .map(k => this.safeKey(k))
244
+ .join('_');
245
+ if (prop.targetMeta?.polymorphs) {
246
+ prop.targetMeta.polymorphs.forEach(meta => {
247
+ context.set(`prototype_${convertorKey}_${meta.className}`, meta.prototype);
248
+ });
249
+ }
250
+ else {
251
+ context.set(`prototype_${convertorKey}`, prop.embeddable.prototype);
252
+ }
253
+ };
254
+ const parseObjectEmbeddable = (prop, dataKey, ret) => {
255
+ if (!this.platform.convertsJsonAutomatically() && (prop.object || prop.array)) {
256
+ context.set('parseJsonSafe', parseJsonSafe);
257
+ ret.push(` if (typeof data${dataKey} === 'string') {`, ` data${dataKey} = parseJsonSafe(data${dataKey});`, ` }`);
258
+ }
259
+ };
260
+ const createCond = (prop, dataKey, cond) => {
261
+ const conds = [];
262
+ if (prop.object) {
263
+ conds.push(`data${dataKey} ${cond ?? '!= null'}`);
264
+ }
265
+ else {
266
+ const notNull = cond ?? (prop.nullable ? '!= null' : '!== undefined');
267
+ meta.props
268
+ .filter(p => p.embedded?.[0] === prop.name)
269
+ .forEach(p => {
270
+ if (p.kind === ReferenceKind.EMBEDDED && !p.object && !p.array) {
271
+ conds.push(...createCond(p, dataKey + this.wrap(p.embedded[1]), cond));
272
+ return;
273
+ }
274
+ conds.push(`data${this.wrap(p.name)} ${notNull}`);
275
+ });
276
+ }
277
+ return conds;
278
+ };
279
+ const hydrateEmbedded = (prop, path, dataKey) => {
280
+ const entityKey = path.map(k => this.wrap(k)).join('');
281
+ const ret = [];
282
+ registerEmbeddedPrototype(prop, path);
283
+ parseObjectEmbeddable(prop, dataKey, ret);
284
+ ret.push(` if (${createCond(prop, dataKey).join(' || ')}) {`);
285
+ if (prop.object) {
286
+ ret.push(` const embeddedData = data${dataKey};`);
287
+ }
288
+ else {
289
+ ret.push(` const embeddedData = {`);
290
+ for (const childProp of Object.values(prop.embeddedProps)) {
291
+ const key = /^\w+$/.exec(childProp.embedded[1]) ? childProp.embedded[1] : `'${childProp.embedded[1]}'`;
292
+ ret.push(` ${key}: data${this.wrap(childProp.name)},`);
293
+ }
294
+ ret.push(` };`);
295
+ }
296
+ if (prop.targetMeta?.polymorphs) {
297
+ prop.targetMeta.polymorphs.forEach(childMeta => {
298
+ const childProp = prop.embeddedProps[prop.targetMeta.discriminatorColumn];
299
+ const childDataKey = prop.object ? dataKey + this.wrap(childProp.embedded[1]) : this.wrap(childProp.name);
300
+ context.set(childMeta.className, childMeta.class);
301
+ // weak comparison as we can have numbers that might have been converted to strings due to being object keys
302
+ ret.push(` if (data${childDataKey} == '${childMeta.discriminatorValue}') {`);
303
+ ret.push(` if (entity${entityKey} == null) {`);
304
+ ret.push(` entity${entityKey} = factory.createEmbeddable(${childMeta.className}, embeddedData, { newEntity, convertCustomTypes, normalizeAccessors });`);
305
+ ret.push(` }`);
306
+ meta.props
307
+ .filter(p => p.embedded?.[0] === prop.name)
308
+ .forEach(childProp => {
309
+ const childDataKey = prop.object
310
+ ? dataKey + this.wrap(childProp.embedded[1])
311
+ : this.wrap(childProp.name);
312
+ const prop2 = childMeta.properties[childProp.embedded[1]];
313
+ const prop3 = {
314
+ ...prop2,
315
+ name: childProp.name,
316
+ embedded: childProp.embedded,
317
+ embeddedProps: childProp.embeddedProps,
318
+ };
319
+ ret.push(
320
+ // eslint-disable-next-line @typescript-eslint/no-use-before-define, no-use-before-define
321
+ ...hydrateProperty(prop3, childProp.object, [...path, childProp.embedded[1]], childDataKey).map(l => ' ' + l));
322
+ });
323
+ ret.push(` }`);
324
+ });
325
+ }
326
+ else {
327
+ const targetKey = this.safeKey(`${prop.targetMeta.tableName}_${this.#tmpIndex++}`);
328
+ context.set(targetKey, prop.targetMeta.class);
329
+ ret.push(` if (entity${entityKey} == null) {`);
330
+ ret.push(` entity${entityKey} = factory.createEmbeddable(${targetKey}, embeddedData, { newEntity, convertCustomTypes, normalizeAccessors });`);
331
+ ret.push(` }`);
332
+ meta.props
333
+ .filter(p => p.embedded?.[0] === prop.name)
334
+ .forEach(childProp => {
335
+ const childDataKey = prop.object ? dataKey + this.wrap(childProp.embedded[1]) : this.wrap(childProp.name);
336
+ ret.push(
337
+ // eslint-disable-next-line @typescript-eslint/no-use-before-define, no-use-before-define
338
+ ...hydrateProperty(childProp, prop.object, [...path, childProp.embedded[1]], childDataKey).map(l => ' ' + l));
339
+ });
340
+ }
341
+ /* v8 ignore next */
342
+ const nullVal = this.config.get('forceUndefined') ? 'undefined' : 'null';
343
+ if (prop.object) {
344
+ ret.push(` } else if (data${dataKey} === null) {`);
345
+ }
346
+ else {
347
+ ret.push(` } else if (${createCond(prop, dataKey, '=== null').join(' && ')}) {`);
348
+ }
349
+ ret.push(` entity${entityKey} = ${nullVal};`);
350
+ ret.push(` }`);
351
+ return ret;
352
+ };
353
+ const hydrateEmbeddedArray = (prop, path, dataKey) => {
354
+ const entityKey = path.map(k => this.wrap(k)).join('');
355
+ const ret = [];
356
+ const idx = this.#tmpIndex++;
357
+ registerEmbeddedPrototype(prop, path);
358
+ parseObjectEmbeddable(prop, dataKey, ret);
359
+ ret.push(` if (Array.isArray(data${dataKey})) {`);
360
+ ret.push(` entity${entityKey} = [];`);
361
+ ret.push(` data${dataKey}.forEach((_, idx_${idx}) => {`);
362
+ ret.push(...hydrateEmbedded(prop, [...path, `[idx_${idx}]`], `${dataKey}[idx_${idx}]`).map(l => ' ' + l));
363
+ ret.push(` });`);
364
+ ret.push(` }`);
365
+ return ret;
366
+ };
367
+ const hydrateProperty = (prop, object = prop.object, path = [prop.name], dataKey) => {
368
+ const entityKey = path.map(k => this.wrap(k)).join('');
369
+ dataKey =
370
+ dataKey ?? (object ? entityKey : this.wrap(normalizeAccessors ? (prop.accessor ?? prop.name) : prop.name));
371
+ const ret = [];
372
+ if ([ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(prop.kind) && !prop.mapToPk) {
373
+ ret.push(...hydrateToOne(prop, dataKey, entityKey));
374
+ }
375
+ else if (prop.kind === ReferenceKind.ONE_TO_MANY || prop.kind === ReferenceKind.MANY_TO_MANY) {
376
+ ret.push(...hydrateToMany(prop, dataKey, entityKey));
377
+ }
378
+ else if (prop.kind === ReferenceKind.EMBEDDED) {
379
+ if (prop.array) {
380
+ ret.push(...hydrateEmbeddedArray(prop, path, dataKey));
381
+ }
382
+ else {
383
+ ret.push(...hydrateEmbedded(prop, path, dataKey));
384
+ if (!prop.object) {
385
+ ret.push(...hydrateEmbedded({ ...prop, object: true }, path, dataKey));
386
+ }
387
+ }
388
+ }
389
+ else {
390
+ // ReferenceKind.SCALAR
391
+ ret.push(...hydrateScalar(prop, path, dataKey));
392
+ }
393
+ if (this.config.get('forceUndefined')) {
394
+ ret.push(` if (data${dataKey} === null) entity${entityKey} = undefined;`);
395
+ }
396
+ return ret;
397
+ };
398
+ for (const prop of props) {
399
+ lines.push(...hydrateProperty(prop));
249
400
  }
250
- }
251
- if (prop.customType?.ensureComparable(meta, prop)) {
252
- registerCustomType(prop, this.safeKey(prop.name), 'convertToDatabaseValue', context);
253
- ret.push(` if (data${dataKey} != null && typeof data${dataKey} !== 'object' && convertCustomTypes) {`);
254
- ret.push(
255
- ` data${dataKey} = convertToDatabaseValue_${this.safeKey(prop.name)}(entity${entityKey}.__helper.getPrimaryKey());`,
256
- );
257
- ret.push(` }`);
258
- }
259
- return ret;
260
- };
261
- const hydrateToMany = (prop, dataKey, entityKey) => {
262
- const ret = [];
263
- ret.push(...this.createCollectionItemMapper(prop, context));
264
- ret.push(` if (data${dataKey} && !Array.isArray(data${dataKey}) && typeof data${dataKey} === 'object') {`);
265
- ret.push(` data${dataKey} = [data${dataKey}];`);
266
- ret.push(` }`);
267
- ret.push(` if (Array.isArray(data${dataKey})) {`);
268
- ret.push(
269
- ` const items = data${dataKey}.map(value => createCollectionItem_${this.safeKey(prop.name)}(value, entity));`,
270
- );
271
- ret.push(` const coll = Collection.create(entity, '${prop.name}', items, newEntity);`);
272
- ret.push(` if (newEntity) {`);
273
- ret.push(` coll.setDirty();`);
274
- ret.push(` } else {`);
275
- ret.push(` coll.takeSnapshot(true);`);
276
- ret.push(` }`);
277
- ret.push(` } else if (!entity${entityKey} && data${dataKey} instanceof Collection) {`);
278
- ret.push(` entity${entityKey} = data${dataKey};`);
279
- if (!this.platform.usesPivotTable() && prop.owner && prop.kind === ReferenceKind.MANY_TO_MANY) {
280
- ret.push(` } else if (!entity${entityKey} && Array.isArray(data${dataKey})) {`);
281
- const items = this.platform.usesPivotTable() || !prop.owner ? 'undefined' : '[]';
282
- ret.push(
283
- ` const coll = Collection.create(entity, '${prop.name}', ${items}, !!data${dataKey} || newEntity);`,
284
- );
285
- ret.push(` coll.setDirty(false);`);
286
- }
287
- ret.push(` } else if (!entity${entityKey}) {`);
288
- ret.push(` const coll = Collection.create(entity, '${prop.name}', undefined, newEntity);`);
289
- ret.push(` coll.setDirty(false);`);
290
- ret.push(` }`);
291
- return ret;
292
- };
293
- const registerEmbeddedPrototype = (prop, path) => {
294
- const convertorKey = path
295
- .filter(k => !/\[idx_\d+]/.exec(k))
296
- .map(k => this.safeKey(k))
297
- .join('_');
298
- if (prop.targetMeta?.polymorphs) {
299
- prop.targetMeta.polymorphs.forEach(meta => {
300
- context.set(`prototype_${convertorKey}_${meta.className}`, meta.prototype);
301
- });
302
- } else {
303
- context.set(`prototype_${convertorKey}`, prop.embeddable.prototype);
304
- }
305
- };
306
- const parseObjectEmbeddable = (prop, dataKey, ret) => {
307
- if (!this.platform.convertsJsonAutomatically() && (prop.object || prop.array)) {
308
- context.set('parseJsonSafe', parseJsonSafe);
309
- ret.push(
310
- ` if (typeof data${dataKey} === 'string') {`,
311
- ` data${dataKey} = parseJsonSafe(data${dataKey});`,
312
- ` }`,
313
- );
314
- }
315
- };
316
- const createCond = (prop, dataKey, cond) => {
317
- const conds = [];
318
- if (prop.object) {
319
- conds.push(`data${dataKey} ${cond ?? '!= null'}`);
320
- } else {
321
- const notNull = cond ?? (prop.nullable ? '!= null' : '!== undefined');
322
- meta.props
323
- .filter(p => p.embedded?.[0] === prop.name)
324
- .forEach(p => {
325
- if (p.kind === ReferenceKind.EMBEDDED && !p.object && !p.array) {
326
- conds.push(...createCond(p, dataKey + this.wrap(p.embedded[1]), cond));
327
- return;
328
- }
329
- conds.push(`data${this.wrap(p.name)} ${notNull}`);
330
- });
331
- }
332
- return conds;
333
- };
334
- const hydrateEmbedded = (prop, path, dataKey) => {
335
- const entityKey = path.map(k => this.wrap(k)).join('');
336
- const ret = [];
337
- registerEmbeddedPrototype(prop, path);
338
- parseObjectEmbeddable(prop, dataKey, ret);
339
- ret.push(` if (${createCond(prop, dataKey).join(' || ')}) {`);
340
- if (prop.object) {
341
- ret.push(` const embeddedData = data${dataKey};`);
342
- } else {
343
- ret.push(` const embeddedData = {`);
344
- for (const childProp of Object.values(prop.embeddedProps)) {
345
- const key = /^\w+$/.exec(childProp.embedded[1]) ? childProp.embedded[1] : `'${childProp.embedded[1]}'`;
346
- ret.push(` ${key}: data${this.wrap(childProp.name)},`);
401
+ const code = `// compiled hydrator for entity ${meta.className} (${type + normalizeAccessors ? ' normalized' : ''})\n` +
402
+ `return function(entity, data, factory, newEntity, convertCustomTypes, schema, parentSchema, normalizeAccessors) {\n` +
403
+ `${lines.join('\n')}\n}`;
404
+ const fnKey = `hydrator-${meta.uniqueName}-${type}-${normalizeAccessors}`;
405
+ const hydrator = Utils.createFunction(context, code, this.config.get('compiledFunctions'), fnKey);
406
+ this.#hydrators[key].set(meta.class, hydrator);
407
+ return hydrator;
408
+ }
409
+ createCollectionItemMapper(prop, context) {
410
+ const meta = this.metadata.get(prop.targetMeta.class);
411
+ const lines = [];
412
+ lines.push(` const createCollectionItem_${this.safeKey(prop.name)} = (value, entity) => {`);
413
+ const prop2 = prop.targetMeta.properties[prop.mappedBy];
414
+ if (prop.kind === ReferenceKind.ONE_TO_MANY && prop2.primary) {
415
+ lines.push(` if (typeof value === 'object' && value?.['${prop2.name}'] == null) {`);
416
+ lines.push(` value = { ...value, ['${prop2.name}']: Reference.wrapReference(entity, { ref: ${prop2.ref} }) };`);
417
+ lines.push(` }`);
347
418
  }
348
- ret.push(` };`);
349
- }
350
- if (prop.targetMeta?.polymorphs) {
351
- prop.targetMeta.polymorphs.forEach(childMeta => {
352
- const childProp = prop.embeddedProps[prop.targetMeta.discriminatorColumn];
353
- const childDataKey = prop.object ? dataKey + this.wrap(childProp.embedded[1]) : this.wrap(childProp.name);
354
- context.set(childMeta.className, childMeta.class);
355
- // weak comparison as we can have numbers that might have been converted to strings due to being object keys
356
- ret.push(` if (data${childDataKey} == '${childMeta.discriminatorValue}') {`);
357
- ret.push(` if (entity${entityKey} == null) {`);
358
- ret.push(
359
- ` entity${entityKey} = factory.createEmbeddable(${childMeta.className}, embeddedData, { newEntity, convertCustomTypes, normalizeAccessors });`,
360
- );
361
- ret.push(` }`);
362
- meta.props
363
- .filter(p => p.embedded?.[0] === prop.name)
364
- .forEach(childProp => {
365
- const childDataKey = prop.object ? dataKey + this.wrap(childProp.embedded[1]) : this.wrap(childProp.name);
366
- const prop2 = childMeta.properties[childProp.embedded[1]];
367
- const prop3 = {
368
- ...prop2,
369
- name: childProp.name,
370
- embedded: childProp.embedded,
371
- embeddedProps: childProp.embeddedProps,
372
- };
373
- ret.push(
374
- // eslint-disable-next-line @typescript-eslint/no-use-before-define, no-use-before-define
375
- ...hydrateProperty(prop3, childProp.object, [...path, childProp.embedded[1]], childDataKey).map(
376
- l => ' ' + l,
377
- ),
378
- );
379
- });
380
- ret.push(` }`);
381
- });
382
- } else {
383
419
  const targetKey = this.safeKey(`${prop.targetMeta.tableName}_${this.#tmpIndex++}`);
384
420
  context.set(targetKey, prop.targetMeta.class);
385
- ret.push(` if (entity${entityKey} == null) {`);
386
- ret.push(
387
- ` entity${entityKey} = factory.createEmbeddable(${targetKey}, embeddedData, { newEntity, convertCustomTypes, normalizeAccessors });`,
388
- );
389
- ret.push(` }`);
390
- meta.props
391
- .filter(p => p.embedded?.[0] === prop.name)
392
- .forEach(childProp => {
393
- const childDataKey = prop.object ? dataKey + this.wrap(childProp.embedded[1]) : this.wrap(childProp.name);
394
- ret.push(
395
- // eslint-disable-next-line @typescript-eslint/no-use-before-define, no-use-before-define
396
- ...hydrateProperty(childProp, prop.object, [...path, childProp.embedded[1]], childDataKey).map(
397
- l => ' ' + l,
398
- ),
399
- );
400
- });
401
- }
402
- /* v8 ignore next */
403
- const nullVal = this.config.get('forceUndefined') ? 'undefined' : 'null';
404
- if (prop.object) {
405
- ret.push(` } else if (data${dataKey} === null) {`);
406
- } else {
407
- ret.push(` } else if (${createCond(prop, dataKey, '=== null').join(' && ')}) {`);
408
- }
409
- ret.push(` entity${entityKey} = ${nullVal};`);
410
- ret.push(` }`);
411
- return ret;
412
- };
413
- const hydrateEmbeddedArray = (prop, path, dataKey) => {
414
- const entityKey = path.map(k => this.wrap(k)).join('');
415
- const ret = [];
416
- const idx = this.#tmpIndex++;
417
- registerEmbeddedPrototype(prop, path);
418
- parseObjectEmbeddable(prop, dataKey, ret);
419
- ret.push(` if (Array.isArray(data${dataKey})) {`);
420
- ret.push(` entity${entityKey} = [];`);
421
- ret.push(` data${dataKey}.forEach((_, idx_${idx}) => {`);
422
- ret.push(...hydrateEmbedded(prop, [...path, `[idx_${idx}]`], `${dataKey}[idx_${idx}]`).map(l => ' ' + l));
423
- ret.push(` });`);
424
- ret.push(` }`);
425
- return ret;
426
- };
427
- const hydrateProperty = (prop, object = prop.object, path = [prop.name], dataKey) => {
428
- const entityKey = path.map(k => this.wrap(k)).join('');
429
- dataKey =
430
- dataKey ?? (object ? entityKey : this.wrap(normalizeAccessors ? (prop.accessor ?? prop.name) : prop.name));
431
- const ret = [];
432
- if ([ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(prop.kind) && !prop.mapToPk) {
433
- ret.push(...hydrateToOne(prop, dataKey, entityKey));
434
- } else if (prop.kind === ReferenceKind.ONE_TO_MANY || prop.kind === ReferenceKind.MANY_TO_MANY) {
435
- ret.push(...hydrateToMany(prop, dataKey, entityKey));
436
- } else if (prop.kind === ReferenceKind.EMBEDDED) {
437
- if (prop.array) {
438
- ret.push(...hydrateEmbeddedArray(prop, path, dataKey));
439
- } else {
440
- ret.push(...hydrateEmbedded(prop, path, dataKey));
441
- if (!prop.object) {
442
- ret.push(...hydrateEmbedded({ ...prop, object: true }, path, dataKey));
443
- }
444
- }
445
- } else {
446
- // ReferenceKind.SCALAR
447
- ret.push(...hydrateScalar(prop, path, dataKey));
448
- }
449
- if (this.config.get('forceUndefined')) {
450
- ret.push(` if (data${dataKey} === null) entity${entityKey} = undefined;`);
451
- }
452
- return ret;
453
- };
454
- for (const prop of props) {
455
- lines.push(...hydrateProperty(prop));
421
+ lines.push(` if (isPrimaryKey(value, ${meta.compositePK})) return factory.createReference(${targetKey}, value, { convertCustomTypes, schema, normalizeAccessors, merge: true });`);
422
+ lines.push(` if (value && value.__entity) return value;`);
423
+ lines.push(` return factory.create(${targetKey}, value, { newEntity, convertCustomTypes, schema, normalizeAccessors, merge: true });`);
424
+ lines.push(` }`);
425
+ return lines;
456
426
  }
457
- const code =
458
- `// compiled hydrator for entity ${meta.className} (${type + normalizeAccessors ? ' normalized' : ''})\n` +
459
- `return function(entity, data, factory, newEntity, convertCustomTypes, schema, parentSchema, normalizeAccessors) {\n` +
460
- `${lines.join('\n')}\n}`;
461
- const fnKey = `hydrator-${meta.uniqueName}-${type}-${normalizeAccessors}`;
462
- const hydrator = Utils.createFunction(context, code, this.config.get('compiledFunctions'), fnKey);
463
- this.#hydrators[key].set(meta.class, hydrator);
464
- return hydrator;
465
- }
466
- createCollectionItemMapper(prop, context) {
467
- const meta = this.metadata.get(prop.targetMeta.class);
468
- const lines = [];
469
- lines.push(` const createCollectionItem_${this.safeKey(prop.name)} = (value, entity) => {`);
470
- const prop2 = prop.targetMeta.properties[prop.mappedBy];
471
- if (prop.kind === ReferenceKind.ONE_TO_MANY && prop2.primary) {
472
- lines.push(` if (typeof value === 'object' && value?.['${prop2.name}'] == null) {`);
473
- lines.push(
474
- ` value = { ...value, ['${prop2.name}']: Reference.wrapReference(entity, { ref: ${prop2.ref} }) };`,
475
- );
476
- lines.push(` }`);
427
+ wrap(key) {
428
+ if (/^\[.*]$/.exec(key)) {
429
+ return key;
430
+ }
431
+ return /^\w+$/.exec(key) ? `.${key}` : `['${key}']`;
477
432
  }
478
- const targetKey = this.safeKey(`${prop.targetMeta.tableName}_${this.#tmpIndex++}`);
479
- context.set(targetKey, prop.targetMeta.class);
480
- lines.push(
481
- ` if (isPrimaryKey(value, ${meta.compositePK})) return factory.createReference(${targetKey}, value, { convertCustomTypes, schema, normalizeAccessors, merge: true });`,
482
- );
483
- lines.push(` if (value && value.__entity) return value;`);
484
- lines.push(
485
- ` return factory.create(${targetKey}, value, { newEntity, convertCustomTypes, schema, normalizeAccessors, merge: true });`,
486
- );
487
- lines.push(` }`);
488
- return lines;
489
- }
490
- wrap(key) {
491
- if (/^\[.*]$/.exec(key)) {
492
- return key;
433
+ safeKey(key) {
434
+ return key.replace(/\W/g, '_');
493
435
  }
494
- return /^\w+$/.exec(key) ? `.${key}` : `['${key}']`;
495
- }
496
- safeKey(key) {
497
- return key.replace(/\W/g, '_');
498
- }
499
436
  }