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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (206) hide show
  1. package/EntityManager.d.ts +884 -583
  2. package/EntityManager.js +1910 -1869
  3. package/MikroORM.d.ts +103 -74
  4. package/MikroORM.js +178 -179
  5. package/README.md +2 -2
  6. package/cache/CacheAdapter.d.ts +36 -36
  7. package/cache/FileCacheAdapter.d.ts +30 -24
  8. package/cache/FileCacheAdapter.js +80 -78
  9. package/cache/GeneratedCacheAdapter.d.ts +18 -20
  10. package/cache/GeneratedCacheAdapter.js +30 -30
  11. package/cache/MemoryCacheAdapter.d.ts +18 -20
  12. package/cache/MemoryCacheAdapter.js +35 -36
  13. package/cache/NullCacheAdapter.d.ts +16 -16
  14. package/cache/NullCacheAdapter.js +24 -24
  15. package/connections/Connection.d.ts +95 -84
  16. package/connections/Connection.js +165 -168
  17. package/drivers/DatabaseDriver.d.ts +186 -80
  18. package/drivers/DatabaseDriver.js +450 -443
  19. package/drivers/IDatabaseDriver.d.ts +440 -301
  20. package/entity/BaseEntity.d.ts +120 -83
  21. package/entity/BaseEntity.js +43 -43
  22. package/entity/Collection.d.ts +212 -179
  23. package/entity/Collection.js +727 -721
  24. package/entity/EntityAssigner.d.ts +88 -77
  25. package/entity/EntityAssigner.js +231 -230
  26. package/entity/EntityFactory.d.ts +66 -54
  27. package/entity/EntityFactory.js +425 -383
  28. package/entity/EntityHelper.d.ts +34 -22
  29. package/entity/EntityHelper.js +280 -267
  30. package/entity/EntityIdentifier.d.ts +4 -4
  31. package/entity/EntityIdentifier.js +10 -10
  32. package/entity/EntityLoader.d.ts +99 -73
  33. package/entity/EntityLoader.js +753 -723
  34. package/entity/EntityRepository.d.ts +316 -201
  35. package/entity/EntityRepository.js +213 -213
  36. package/entity/PolymorphicRef.d.ts +5 -5
  37. package/entity/PolymorphicRef.js +10 -10
  38. package/entity/Reference.d.ts +126 -82
  39. package/entity/Reference.js +278 -274
  40. package/entity/WrappedEntity.d.ts +115 -72
  41. package/entity/WrappedEntity.js +168 -166
  42. package/entity/defineEntity.d.ts +1318 -625
  43. package/entity/defineEntity.js +527 -511
  44. package/entity/utils.d.ts +13 -3
  45. package/entity/utils.js +71 -73
  46. package/entity/validators.js +43 -43
  47. package/entity/wrap.js +8 -8
  48. package/enums.d.ts +258 -253
  49. package/enums.js +251 -252
  50. package/errors.d.ts +114 -72
  51. package/errors.js +350 -253
  52. package/events/EventManager.d.ts +26 -14
  53. package/events/EventManager.js +79 -77
  54. package/events/EventSubscriber.d.ts +29 -29
  55. package/events/TransactionEventBroadcaster.d.ts +15 -8
  56. package/events/TransactionEventBroadcaster.js +14 -14
  57. package/exceptions.d.ts +23 -40
  58. package/exceptions.js +35 -52
  59. package/hydration/Hydrator.d.ts +42 -17
  60. package/hydration/Hydrator.js +43 -43
  61. package/hydration/ObjectHydrator.d.ts +50 -17
  62. package/hydration/ObjectHydrator.js +479 -416
  63. package/index.d.ts +116 -2
  64. package/index.js +10 -1
  65. package/logging/DefaultLogger.d.ts +34 -32
  66. package/logging/DefaultLogger.js +86 -86
  67. package/logging/Logger.d.ts +41 -41
  68. package/logging/SimpleLogger.d.ts +13 -11
  69. package/logging/SimpleLogger.js +22 -22
  70. package/logging/colors.d.ts +6 -6
  71. package/logging/colors.js +11 -10
  72. package/logging/inspect.js +7 -7
  73. package/metadata/EntitySchema.d.ts +211 -127
  74. package/metadata/EntitySchema.js +397 -398
  75. package/metadata/MetadataDiscovery.d.ts +114 -114
  76. package/metadata/MetadataDiscovery.js +1947 -1863
  77. package/metadata/MetadataProvider.d.ts +24 -21
  78. package/metadata/MetadataProvider.js +82 -84
  79. package/metadata/MetadataStorage.d.ts +38 -32
  80. package/metadata/MetadataStorage.js +118 -118
  81. package/metadata/MetadataValidator.d.ts +39 -39
  82. package/metadata/MetadataValidator.js +381 -338
  83. package/metadata/discover-entities.d.ts +5 -2
  84. package/metadata/discover-entities.js +27 -27
  85. package/metadata/types.d.ts +615 -531
  86. package/naming-strategy/AbstractNamingStrategy.d.ts +54 -39
  87. package/naming-strategy/AbstractNamingStrategy.js +90 -85
  88. package/naming-strategy/EntityCaseNamingStrategy.d.ts +6 -6
  89. package/naming-strategy/EntityCaseNamingStrategy.js +22 -22
  90. package/naming-strategy/MongoNamingStrategy.d.ts +6 -6
  91. package/naming-strategy/MongoNamingStrategy.js +18 -18
  92. package/naming-strategy/NamingStrategy.d.ts +109 -99
  93. package/naming-strategy/UnderscoreNamingStrategy.d.ts +7 -7
  94. package/naming-strategy/UnderscoreNamingStrategy.js +21 -21
  95. package/not-supported.js +7 -4
  96. package/package.json +1 -1
  97. package/platforms/ExceptionConverter.d.ts +1 -1
  98. package/platforms/ExceptionConverter.js +4 -4
  99. package/platforms/Platform.d.ts +308 -299
  100. package/platforms/Platform.js +659 -636
  101. package/serialization/EntitySerializer.d.ts +49 -26
  102. package/serialization/EntitySerializer.js +224 -218
  103. package/serialization/EntityTransformer.d.ts +10 -6
  104. package/serialization/EntityTransformer.js +219 -217
  105. package/serialization/SerializationContext.d.ts +27 -23
  106. package/serialization/SerializationContext.js +105 -105
  107. package/types/ArrayType.d.ts +8 -8
  108. package/types/ArrayType.js +33 -33
  109. package/types/BigIntType.d.ts +17 -10
  110. package/types/BigIntType.js +37 -37
  111. package/types/BlobType.d.ts +3 -3
  112. package/types/BlobType.js +13 -13
  113. package/types/BooleanType.d.ts +4 -4
  114. package/types/BooleanType.js +12 -12
  115. package/types/CharacterType.d.ts +2 -2
  116. package/types/CharacterType.js +6 -6
  117. package/types/DateTimeType.d.ts +5 -5
  118. package/types/DateTimeType.js +15 -15
  119. package/types/DateType.d.ts +5 -5
  120. package/types/DateType.js +15 -15
  121. package/types/DecimalType.d.ts +7 -7
  122. package/types/DecimalType.js +26 -26
  123. package/types/DoubleType.d.ts +3 -3
  124. package/types/DoubleType.js +12 -12
  125. package/types/EnumArrayType.d.ts +5 -5
  126. package/types/EnumArrayType.js +24 -24
  127. package/types/EnumType.d.ts +3 -3
  128. package/types/EnumType.js +11 -11
  129. package/types/FloatType.d.ts +3 -3
  130. package/types/FloatType.js +9 -9
  131. package/types/IntegerType.d.ts +3 -3
  132. package/types/IntegerType.js +9 -9
  133. package/types/IntervalType.d.ts +4 -4
  134. package/types/IntervalType.js +12 -12
  135. package/types/JsonType.d.ts +8 -8
  136. package/types/JsonType.js +32 -32
  137. package/types/MediumIntType.d.ts +1 -1
  138. package/types/MediumIntType.js +3 -3
  139. package/types/SmallIntType.d.ts +3 -3
  140. package/types/SmallIntType.js +9 -9
  141. package/types/StringType.d.ts +4 -4
  142. package/types/StringType.js +12 -12
  143. package/types/TextType.d.ts +3 -3
  144. package/types/TextType.js +9 -9
  145. package/types/TimeType.d.ts +5 -5
  146. package/types/TimeType.js +17 -17
  147. package/types/TinyIntType.d.ts +3 -3
  148. package/types/TinyIntType.js +10 -10
  149. package/types/Type.d.ts +83 -79
  150. package/types/Type.js +82 -82
  151. package/types/Uint8ArrayType.d.ts +4 -4
  152. package/types/Uint8ArrayType.js +21 -21
  153. package/types/UnknownType.d.ts +4 -4
  154. package/types/UnknownType.js +12 -12
  155. package/types/UuidType.d.ts +5 -5
  156. package/types/UuidType.js +19 -19
  157. package/types/index.d.ts +75 -49
  158. package/types/index.js +52 -26
  159. package/typings.d.ts +1254 -730
  160. package/typings.js +244 -231
  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 +178 -170
  165. package/unit-of-work/ChangeSetPersister.d.ts +63 -44
  166. package/unit-of-work/ChangeSetPersister.js +442 -421
  167. package/unit-of-work/CommitOrderCalculator.d.ts +40 -40
  168. package/unit-of-work/CommitOrderCalculator.js +89 -88
  169. package/unit-of-work/IdentityMap.d.ts +31 -31
  170. package/unit-of-work/IdentityMap.js +105 -105
  171. package/unit-of-work/UnitOfWork.d.ts +181 -141
  172. package/unit-of-work/UnitOfWork.js +1200 -1183
  173. package/utils/AbstractMigrator.d.ts +111 -91
  174. package/utils/AbstractMigrator.js +275 -275
  175. package/utils/AbstractSchemaGenerator.d.ts +43 -34
  176. package/utils/AbstractSchemaGenerator.js +121 -122
  177. package/utils/AsyncContext.d.ts +3 -3
  178. package/utils/AsyncContext.js +34 -35
  179. package/utils/Configuration.d.ts +852 -808
  180. package/utils/Configuration.js +359 -344
  181. package/utils/Cursor.d.ts +40 -22
  182. package/utils/Cursor.js +135 -127
  183. package/utils/DataloaderUtils.d.ts +58 -43
  184. package/utils/DataloaderUtils.js +203 -198
  185. package/utils/EntityComparator.d.ts +98 -81
  186. package/utils/EntityComparator.js +824 -728
  187. package/utils/NullHighlighter.d.ts +1 -1
  188. package/utils/NullHighlighter.js +3 -3
  189. package/utils/QueryHelper.d.ts +79 -51
  190. package/utils/QueryHelper.js +372 -361
  191. package/utils/RawQueryFragment.d.ts +50 -34
  192. package/utils/RawQueryFragment.js +107 -105
  193. package/utils/RequestContext.d.ts +32 -32
  194. package/utils/RequestContext.js +52 -53
  195. package/utils/TransactionContext.d.ts +16 -16
  196. package/utils/TransactionContext.js +27 -27
  197. package/utils/TransactionManager.d.ts +58 -58
  198. package/utils/TransactionManager.js +199 -197
  199. package/utils/Utils.d.ts +204 -145
  200. package/utils/Utils.js +811 -813
  201. package/utils/clone.js +104 -113
  202. package/utils/env-vars.js +90 -88
  203. package/utils/fs-utils.d.ts +15 -15
  204. package/utils/fs-utils.js +180 -181
  205. package/utils/upsert-utils.d.ts +20 -5
  206. package/utils/upsert-utils.js +114 -116
@@ -8,429 +8,492 @@ 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(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;
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;
39
79
  }
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;
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;
48
93
  }
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));
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);`);
400
133
  }
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(` }`);
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;
174
+ };
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
+ );
418
204
  }
205
+ } else {
206
+ // For regular: fixed target class, PK is the data itself
419
207
  const targetKey = this.safeKey(`${prop.targetMeta.tableName}_${this.#tmpIndex++}`);
420
208
  context.set(targetKey, prop.targetMeta.class);
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;
426
- }
427
- wrap(key) {
428
- if (/^\[.*]$/.exec(key)) {
429
- return key;
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
+ );
217
+ }
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(` }`);
249
+ }
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)},`);
430
347
  }
431
- return /^\w+$/.exec(key) ? `.${key}` : `['${key}']`;
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
+ const targetKey = this.safeKey(`${prop.targetMeta.tableName}_${this.#tmpIndex++}`);
384
+ 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));
456
+ }
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(` }`);
432
477
  }
433
- safeKey(key) {
434
- return key.replace(/\W/g, '_');
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;
435
493
  }
494
+ return /^\w+$/.exec(key) ? `.${key}` : `['${key}']`;
495
+ }
496
+ safeKey(key) {
497
+ return key.replace(/\W/g, '_');
498
+ }
436
499
  }