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

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 +1922 -1895
  3. package/MikroORM.d.ts +103 -74
  4. package/MikroORM.js +178 -179
  5. package/README.md +1 -1
  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 +98 -72
  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 +1315 -636
  43. package/entity/defineEntity.js +527 -518
  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 +481 -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 +1951 -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 +35 -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 +310 -299
  100. package/platforms/Platform.js +663 -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 +1250 -737
  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 +828 -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 +812 -810
  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,494 @@ 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(
162
+ ` const value = entity${entityKey}?.__scalarReference ? entity${entityKey}.unwrap() : entity${entityKey};`,
163
+ );
164
+ ret.push(` entity${entityKey} = oldValue_${idx} ?? new ScalarReference(value);`);
165
+ ret.push(` entity${entityKey}.bind(entity, '${prop.name}');`);
166
+ ret.push(` entity${entityKey}.set(value);`);
167
+ }
168
+ ret.push(` }`);
169
+ if (prop.ref) {
170
+ ret.push(` if (!entity${entityKey}) {`);
171
+ ret.push(` entity${entityKey} = new ScalarReference();`);
172
+ ret.push(` entity${entityKey}.bind(entity, '${prop.name}');`);
173
+ ret.push(` }`);
174
+ }
175
+ return ret;
176
+ };
177
+ const hydrateToOne = (prop, dataKey, entityKey) => {
178
+ const ret = [];
179
+ const method = type === 'reference' ? 'createReference' : 'create';
180
+ const nullVal = this.config.get('forceUndefined') ? 'undefined' : 'null';
181
+ ret.push(` if (data${dataKey} === null) {\n entity${entityKey} = ${nullVal};`);
182
+ ret.push(` } else if (typeof data${dataKey} !== 'undefined') {`);
183
+ // For polymorphic: instanceof check; for regular: isPrimaryKey() check
184
+ const pkCheck = prop.polymorphic
185
+ ? `data${dataKey} instanceof PolymorphicRef`
186
+ : `isPrimaryKey(data${dataKey}, true)`;
187
+ ret.push(` if (${pkCheck}) {`);
188
+ // When targetKey is set, pass the key option to createReference so it uses the alternate key
189
+ const keyOption = prop.targetKey ? `, key: '${prop.targetKey}'` : '';
190
+ if (prop.polymorphic) {
191
+ // For polymorphic: target class from discriminator map, PK from data.id
192
+ const discriminatorMapKey = this.safeKey(`discriminatorMap_${prop.name}_${this.#tmpIndex++}`);
193
+ context.set(discriminatorMapKey, prop.discriminatorMap);
194
+ ret.push(` const targetClass = ${discriminatorMapKey}[data${dataKey}.discriminator];`);
195
+ ret.push(
196
+ ` if (!targetClass) throw new ValidationError(\`Unknown discriminator value '\${data${dataKey}.discriminator}' for polymorphic relation '${prop.name}'. Valid values: \${Object.keys(${discriminatorMapKey}).join(', ')}\`);`,
197
+ );
198
+ if (prop.ref) {
199
+ ret.push(
200
+ ` entity${entityKey} = Reference.create(factory.createReference(targetClass, data${dataKey}.id, { merge: true, convertCustomTypes, normalizeAccessors, schema${keyOption} }));`,
201
+ );
202
+ } else {
203
+ ret.push(
204
+ ` entity${entityKey} = factory.createReference(targetClass, data${dataKey}.id, { merge: true, convertCustomTypes, normalizeAccessors, schema${keyOption} });`,
205
+ );
418
206
  }
207
+ } else {
208
+ // For regular: fixed target class, PK is the data itself
419
209
  const targetKey = this.safeKey(`${prop.targetMeta.tableName}_${this.#tmpIndex++}`);
420
210
  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;
211
+ if (prop.ref) {
212
+ ret.push(
213
+ ` entity${entityKey} = Reference.create(factory.createReference(${targetKey}, data${dataKey}, { merge: true, convertCustomTypes, normalizeAccessors, schema${keyOption} }));`,
214
+ );
215
+ } else {
216
+ ret.push(
217
+ ` entity${entityKey} = factory.createReference(${targetKey}, data${dataKey}, { merge: true, convertCustomTypes, normalizeAccessors, schema${keyOption} });`,
218
+ );
219
+ }
220
+ }
221
+ ret.push(` } else if (data${dataKey} && typeof data${dataKey} === 'object') {`);
222
+ // For full entity hydration, polymorphic needs to determine target class from entity itself
223
+ let hydrateTargetExpr;
224
+ if (prop.polymorphic) {
225
+ hydrateTargetExpr = `data${dataKey}.constructor`;
226
+ } else {
227
+ const targetKey = this.safeKey(`${prop.targetMeta.tableName}_${this.#tmpIndex++}`);
228
+ context.set(targetKey, prop.targetMeta.class);
229
+ hydrateTargetExpr = targetKey;
230
+ }
231
+ if (prop.ref) {
232
+ ret.push(
233
+ ` entity${entityKey} = Reference.create(factory.${method}(${hydrateTargetExpr}, data${dataKey}, { initialized: true, merge: true, newEntity, convertCustomTypes, normalizeAccessors, schema }));`,
234
+ );
235
+ } else {
236
+ ret.push(
237
+ ` entity${entityKey} = factory.${method}(${hydrateTargetExpr}, data${dataKey}, { initialized: true, merge: true, newEntity, convertCustomTypes, normalizeAccessors, schema });`,
238
+ );
239
+ }
240
+ ret.push(` }`);
241
+ ret.push(` }`);
242
+ if (prop.kind === ReferenceKind.ONE_TO_ONE) {
243
+ const meta2 = this.metadata.get(prop.targetMeta.class);
244
+ const prop2 = meta2.properties[prop.inversedBy || prop.mappedBy];
245
+ if (prop2 && !prop2.mapToPk) {
246
+ ret.push(` if (data${dataKey} && entity${entityKey} && !entity${entityKey}.${this.safeKey(prop2.name)}) {`);
247
+ ret.push(
248
+ ` entity${entityKey}.${prop.ref ? 'unwrap().' : ''}${this.safeKey(prop2.name)} = ${prop2.ref ? 'Reference.create(entity)' : 'entity'};`,
249
+ );
250
+ ret.push(` }`);
251
+ }
252
+ }
253
+ if (prop.customType?.ensureComparable(meta, prop)) {
254
+ registerCustomType(prop, this.safeKey(prop.name), 'convertToDatabaseValue', context);
255
+ ret.push(` if (data${dataKey} != null && typeof data${dataKey} !== 'object' && convertCustomTypes) {`);
256
+ ret.push(
257
+ ` data${dataKey} = convertToDatabaseValue_${this.safeKey(prop.name)}(entity${entityKey}.__helper.getPrimaryKey());`,
258
+ );
259
+ ret.push(` }`);
260
+ }
261
+ return ret;
262
+ };
263
+ const hydrateToMany = (prop, dataKey, entityKey) => {
264
+ const ret = [];
265
+ ret.push(...this.createCollectionItemMapper(prop, context));
266
+ ret.push(` if (data${dataKey} && !Array.isArray(data${dataKey}) && typeof data${dataKey} === 'object') {`);
267
+ ret.push(` data${dataKey} = [data${dataKey}];`);
268
+ ret.push(` }`);
269
+ ret.push(` if (Array.isArray(data${dataKey})) {`);
270
+ ret.push(
271
+ ` const items = data${dataKey}.map(value => createCollectionItem_${this.safeKey(prop.name)}(value, entity));`,
272
+ );
273
+ ret.push(` const coll = Collection.create(entity, '${prop.name}', items, newEntity);`);
274
+ ret.push(` if (newEntity) {`);
275
+ ret.push(` coll.setDirty();`);
276
+ ret.push(` } else {`);
277
+ ret.push(` coll.takeSnapshot(true);`);
278
+ ret.push(` }`);
279
+ ret.push(` } else if (!entity${entityKey} && data${dataKey} instanceof Collection) {`);
280
+ ret.push(` entity${entityKey} = data${dataKey};`);
281
+ if (!this.platform.usesPivotTable() && prop.owner && prop.kind === ReferenceKind.MANY_TO_MANY) {
282
+ ret.push(` } else if (!entity${entityKey} && Array.isArray(data${dataKey})) {`);
283
+ const items = this.platform.usesPivotTable() || !prop.owner ? 'undefined' : '[]';
284
+ ret.push(
285
+ ` const coll = Collection.create(entity, '${prop.name}', ${items}, !!data${dataKey} || newEntity);`,
286
+ );
287
+ ret.push(` coll.setDirty(false);`);
288
+ }
289
+ ret.push(` } else if (!entity${entityKey}) {`);
290
+ ret.push(` const coll = Collection.create(entity, '${prop.name}', undefined, newEntity);`);
291
+ ret.push(` coll.setDirty(false);`);
292
+ ret.push(` }`);
293
+ return ret;
294
+ };
295
+ const registerEmbeddedPrototype = (prop, path) => {
296
+ const convertorKey = path
297
+ .filter(k => !/\[idx_\d+]/.exec(k))
298
+ .map(k => this.safeKey(k))
299
+ .join('_');
300
+ if (prop.targetMeta?.polymorphs) {
301
+ prop.targetMeta.polymorphs.forEach(meta => {
302
+ context.set(`prototype_${convertorKey}_${meta.className}`, meta.prototype);
303
+ });
304
+ } else {
305
+ context.set(`prototype_${convertorKey}`, prop.embeddable.prototype);
306
+ }
307
+ };
308
+ const parseObjectEmbeddable = (prop, dataKey, ret) => {
309
+ if (!this.platform.convertsJsonAutomatically() && (prop.object || prop.array)) {
310
+ context.set('parseJsonSafe', parseJsonSafe);
311
+ ret.push(
312
+ ` if (typeof data${dataKey} === 'string') {`,
313
+ ` data${dataKey} = parseJsonSafe(data${dataKey});`,
314
+ ` }`,
315
+ );
316
+ }
317
+ };
318
+ const createCond = (prop, dataKey, cond) => {
319
+ const conds = [];
320
+ if (prop.object) {
321
+ conds.push(`data${dataKey} ${cond ?? '!= null'}`);
322
+ } else {
323
+ const notNull = cond ?? (prop.nullable ? '!= null' : '!== undefined');
324
+ meta.props
325
+ .filter(p => p.embedded?.[0] === prop.name)
326
+ .forEach(p => {
327
+ if (p.kind === ReferenceKind.EMBEDDED && !p.object && !p.array) {
328
+ conds.push(...createCond(p, dataKey + this.wrap(p.embedded[1]), cond));
329
+ return;
330
+ }
331
+ conds.push(`data${this.wrap(p.name)} ${notNull}`);
332
+ });
333
+ }
334
+ return conds;
335
+ };
336
+ const hydrateEmbedded = (prop, path, dataKey) => {
337
+ const entityKey = path.map(k => this.wrap(k)).join('');
338
+ const ret = [];
339
+ registerEmbeddedPrototype(prop, path);
340
+ parseObjectEmbeddable(prop, dataKey, ret);
341
+ ret.push(` if (${createCond(prop, dataKey).join(' || ')}) {`);
342
+ if (prop.object) {
343
+ ret.push(` const embeddedData = data${dataKey};`);
344
+ } else {
345
+ ret.push(` const embeddedData = {`);
346
+ for (const childProp of Object.values(prop.embeddedProps)) {
347
+ const key = /^\w+$/.exec(childProp.embedded[1]) ? childProp.embedded[1] : `'${childProp.embedded[1]}'`;
348
+ ret.push(` ${key}: data${this.wrap(childProp.name)},`);
430
349
  }
431
- return /^\w+$/.exec(key) ? `.${key}` : `['${key}']`;
350
+ ret.push(` };`);
351
+ }
352
+ if (prop.targetMeta?.polymorphs) {
353
+ prop.targetMeta.polymorphs.forEach(childMeta => {
354
+ const childProp = prop.embeddedProps[prop.targetMeta.discriminatorColumn];
355
+ const childDataKey = prop.object ? dataKey + this.wrap(childProp.embedded[1]) : this.wrap(childProp.name);
356
+ context.set(childMeta.className, childMeta.class);
357
+ // weak comparison as we can have numbers that might have been converted to strings due to being object keys
358
+ ret.push(` if (data${childDataKey} == '${childMeta.discriminatorValue}') {`);
359
+ ret.push(` if (entity${entityKey} == null) {`);
360
+ ret.push(
361
+ ` entity${entityKey} = factory.createEmbeddable(${childMeta.className}, embeddedData, { newEntity, convertCustomTypes, normalizeAccessors });`,
362
+ );
363
+ ret.push(` }`);
364
+ meta.props
365
+ .filter(p => p.embedded?.[0] === prop.name)
366
+ .forEach(childProp => {
367
+ const childDataKey = prop.object ? dataKey + this.wrap(childProp.embedded[1]) : this.wrap(childProp.name);
368
+ const prop2 = childMeta.properties[childProp.embedded[1]];
369
+ const prop3 = {
370
+ ...prop2,
371
+ name: childProp.name,
372
+ embedded: childProp.embedded,
373
+ embeddedProps: childProp.embeddedProps,
374
+ };
375
+ ret.push(
376
+ // eslint-disable-next-line @typescript-eslint/no-use-before-define, no-use-before-define
377
+ ...hydrateProperty(prop3, childProp.object, [...path, childProp.embedded[1]], childDataKey).map(
378
+ l => ' ' + l,
379
+ ),
380
+ );
381
+ });
382
+ ret.push(` }`);
383
+ });
384
+ } else {
385
+ const targetKey = this.safeKey(`${prop.targetMeta.tableName}_${this.#tmpIndex++}`);
386
+ context.set(targetKey, prop.targetMeta.class);
387
+ ret.push(` if (entity${entityKey} == null) {`);
388
+ ret.push(
389
+ ` entity${entityKey} = factory.createEmbeddable(${targetKey}, embeddedData, { newEntity, convertCustomTypes, normalizeAccessors });`,
390
+ );
391
+ ret.push(` }`);
392
+ meta.props
393
+ .filter(p => p.embedded?.[0] === prop.name)
394
+ .forEach(childProp => {
395
+ const childDataKey = prop.object ? dataKey + this.wrap(childProp.embedded[1]) : this.wrap(childProp.name);
396
+ ret.push(
397
+ // eslint-disable-next-line @typescript-eslint/no-use-before-define, no-use-before-define
398
+ ...hydrateProperty(childProp, prop.object, [...path, childProp.embedded[1]], childDataKey).map(
399
+ l => ' ' + l,
400
+ ),
401
+ );
402
+ });
403
+ }
404
+ /* v8 ignore next */
405
+ const nullVal = this.config.get('forceUndefined') ? 'undefined' : 'null';
406
+ if (prop.object) {
407
+ ret.push(` } else if (data${dataKey} === null) {`);
408
+ } else {
409
+ ret.push(` } else if (${createCond(prop, dataKey, '=== null').join(' && ')}) {`);
410
+ }
411
+ ret.push(` entity${entityKey} = ${nullVal};`);
412
+ ret.push(` }`);
413
+ return ret;
414
+ };
415
+ const hydrateEmbeddedArray = (prop, path, dataKey) => {
416
+ const entityKey = path.map(k => this.wrap(k)).join('');
417
+ const ret = [];
418
+ const idx = this.#tmpIndex++;
419
+ registerEmbeddedPrototype(prop, path);
420
+ parseObjectEmbeddable(prop, dataKey, ret);
421
+ ret.push(` if (Array.isArray(data${dataKey})) {`);
422
+ ret.push(` entity${entityKey} = [];`);
423
+ ret.push(` data${dataKey}.forEach((_, idx_${idx}) => {`);
424
+ ret.push(...hydrateEmbedded(prop, [...path, `[idx_${idx}]`], `${dataKey}[idx_${idx}]`).map(l => ' ' + l));
425
+ ret.push(` });`);
426
+ ret.push(` }`);
427
+ return ret;
428
+ };
429
+ const hydrateProperty = (prop, object = prop.object, path = [prop.name], dataKey) => {
430
+ const entityKey = path.map(k => this.wrap(k)).join('');
431
+ dataKey =
432
+ dataKey ?? (object ? entityKey : this.wrap(normalizeAccessors ? (prop.accessor ?? prop.name) : prop.name));
433
+ const ret = [];
434
+ if ([ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(prop.kind) && !prop.mapToPk) {
435
+ ret.push(...hydrateToOne(prop, dataKey, entityKey));
436
+ } else if (prop.kind === ReferenceKind.ONE_TO_MANY || prop.kind === ReferenceKind.MANY_TO_MANY) {
437
+ ret.push(...hydrateToMany(prop, dataKey, entityKey));
438
+ } else if (prop.kind === ReferenceKind.EMBEDDED) {
439
+ if (prop.array) {
440
+ ret.push(...hydrateEmbeddedArray(prop, path, dataKey));
441
+ } else {
442
+ ret.push(...hydrateEmbedded(prop, path, dataKey));
443
+ if (!prop.object) {
444
+ ret.push(...hydrateEmbedded({ ...prop, object: true }, path, dataKey));
445
+ }
446
+ }
447
+ } else {
448
+ // ReferenceKind.SCALAR
449
+ ret.push(...hydrateScalar(prop, path, dataKey));
450
+ }
451
+ if (this.config.get('forceUndefined')) {
452
+ ret.push(` if (data${dataKey} === null) entity${entityKey} = undefined;`);
453
+ }
454
+ return ret;
455
+ };
456
+ for (const prop of props) {
457
+ lines.push(...hydrateProperty(prop));
458
+ }
459
+ const code =
460
+ `// compiled hydrator for entity ${meta.className} (${type + normalizeAccessors ? ' normalized' : ''})\n` +
461
+ `return function(entity, data, factory, newEntity, convertCustomTypes, schema, parentSchema, normalizeAccessors) {\n` +
462
+ `${lines.join('\n')}\n}`;
463
+ const fnKey = `hydrator-${meta.uniqueName}-${type}-${normalizeAccessors}`;
464
+ const hydrator = Utils.createFunction(context, code, this.config.get('compiledFunctions'), fnKey);
465
+ this.#hydrators[key].set(meta.class, hydrator);
466
+ return hydrator;
467
+ }
468
+ createCollectionItemMapper(prop, context) {
469
+ const meta = this.metadata.get(prop.targetMeta.class);
470
+ const lines = [];
471
+ lines.push(` const createCollectionItem_${this.safeKey(prop.name)} = (value, entity) => {`);
472
+ const prop2 = prop.targetMeta.properties[prop.mappedBy];
473
+ if (prop.kind === ReferenceKind.ONE_TO_MANY && prop2.primary) {
474
+ lines.push(` if (typeof value === 'object' && value?.['${prop2.name}'] == null) {`);
475
+ lines.push(
476
+ ` value = { ...value, ['${prop2.name}']: Reference.wrapReference(entity, { ref: ${prop2.ref} }) };`,
477
+ );
478
+ lines.push(` }`);
432
479
  }
433
- safeKey(key) {
434
- return key.replace(/\W/g, '_');
480
+ const targetKey = this.safeKey(`${prop.targetMeta.tableName}_${this.#tmpIndex++}`);
481
+ context.set(targetKey, prop.targetMeta.class);
482
+ lines.push(
483
+ ` if (isPrimaryKey(value, ${meta.compositePK})) return factory.createReference(${targetKey}, value, { convertCustomTypes, schema, normalizeAccessors, merge: true });`,
484
+ );
485
+ lines.push(` if (value && value.__entity) return value;`);
486
+ lines.push(
487
+ ` return factory.create(${targetKey}, value, { newEntity, convertCustomTypes, schema, normalizeAccessors, merge: true });`,
488
+ );
489
+ lines.push(` }`);
490
+ return lines;
491
+ }
492
+ wrap(key) {
493
+ if (/^\[.*]$/.exec(key)) {
494
+ return key;
435
495
  }
496
+ return /^\w+$/.exec(key) ? `.${key}` : `['${key}']`;
497
+ }
498
+ safeKey(key) {
499
+ return key.replace(/\W/g, '_');
500
+ }
436
501
  }