@mikro-orm/core 7.0.2-dev.9 → 7.0.2

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