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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (205) hide show
  1. package/EntityManager.d.ts +583 -883
  2. package/EntityManager.js +1869 -1897
  3. package/MikroORM.d.ts +74 -103
  4. package/MikroORM.js +179 -178
  5. package/cache/CacheAdapter.d.ts +36 -36
  6. package/cache/FileCacheAdapter.d.ts +24 -30
  7. package/cache/FileCacheAdapter.js +78 -80
  8. package/cache/GeneratedCacheAdapter.d.ts +20 -18
  9. package/cache/GeneratedCacheAdapter.js +30 -30
  10. package/cache/MemoryCacheAdapter.d.ts +20 -18
  11. package/cache/MemoryCacheAdapter.js +36 -35
  12. package/cache/NullCacheAdapter.d.ts +16 -16
  13. package/cache/NullCacheAdapter.js +24 -24
  14. package/connections/Connection.d.ts +84 -95
  15. package/connections/Connection.js +168 -165
  16. package/drivers/DatabaseDriver.d.ts +80 -186
  17. package/drivers/DatabaseDriver.js +443 -450
  18. package/drivers/IDatabaseDriver.d.ts +301 -440
  19. package/entity/BaseEntity.d.ts +83 -120
  20. package/entity/BaseEntity.js +43 -43
  21. package/entity/Collection.d.ts +179 -212
  22. package/entity/Collection.js +721 -727
  23. package/entity/EntityAssigner.d.ts +77 -88
  24. package/entity/EntityAssigner.js +230 -231
  25. package/entity/EntityFactory.d.ts +54 -66
  26. package/entity/EntityFactory.js +383 -425
  27. package/entity/EntityHelper.d.ts +22 -34
  28. package/entity/EntityHelper.js +267 -280
  29. package/entity/EntityIdentifier.d.ts +4 -4
  30. package/entity/EntityIdentifier.js +10 -10
  31. package/entity/EntityLoader.d.ts +73 -103
  32. package/entity/EntityLoader.js +723 -753
  33. package/entity/EntityRepository.d.ts +201 -316
  34. package/entity/EntityRepository.js +213 -213
  35. package/entity/PolymorphicRef.d.ts +5 -5
  36. package/entity/PolymorphicRef.js +10 -10
  37. package/entity/Reference.d.ts +82 -126
  38. package/entity/Reference.js +274 -278
  39. package/entity/WrappedEntity.d.ts +72 -115
  40. package/entity/WrappedEntity.js +166 -168
  41. package/entity/defineEntity.d.ts +614 -1280
  42. package/entity/defineEntity.js +511 -520
  43. package/entity/utils.d.ts +3 -13
  44. package/entity/utils.js +73 -71
  45. package/entity/validators.js +43 -43
  46. package/entity/wrap.js +8 -8
  47. package/enums.d.ts +253 -258
  48. package/enums.js +252 -251
  49. package/errors.d.ts +72 -114
  50. package/errors.js +253 -350
  51. package/events/EventManager.d.ts +14 -26
  52. package/events/EventManager.js +77 -79
  53. package/events/EventSubscriber.d.ts +29 -29
  54. package/events/TransactionEventBroadcaster.d.ts +8 -15
  55. package/events/TransactionEventBroadcaster.js +14 -14
  56. package/exceptions.d.ts +40 -23
  57. package/exceptions.js +52 -35
  58. package/hydration/Hydrator.d.ts +17 -42
  59. package/hydration/Hydrator.js +43 -43
  60. package/hydration/ObjectHydrator.d.ts +17 -50
  61. package/hydration/ObjectHydrator.js +416 -479
  62. package/index.d.ts +2 -116
  63. package/index.js +1 -10
  64. package/logging/DefaultLogger.d.ts +32 -34
  65. package/logging/DefaultLogger.js +86 -86
  66. package/logging/Logger.d.ts +41 -41
  67. package/logging/SimpleLogger.d.ts +11 -13
  68. package/logging/SimpleLogger.js +22 -22
  69. package/logging/colors.d.ts +6 -6
  70. package/logging/colors.js +10 -11
  71. package/logging/inspect.js +7 -7
  72. package/metadata/EntitySchema.d.ts +127 -211
  73. package/metadata/EntitySchema.js +398 -397
  74. package/metadata/MetadataDiscovery.d.ts +114 -114
  75. package/metadata/MetadataDiscovery.js +1863 -1947
  76. package/metadata/MetadataProvider.d.ts +21 -24
  77. package/metadata/MetadataProvider.js +84 -82
  78. package/metadata/MetadataStorage.d.ts +32 -38
  79. package/metadata/MetadataStorage.js +118 -118
  80. package/metadata/MetadataValidator.d.ts +39 -39
  81. package/metadata/MetadataValidator.js +338 -381
  82. package/metadata/discover-entities.d.ts +2 -5
  83. package/metadata/discover-entities.js +27 -27
  84. package/metadata/types.d.ts +531 -615
  85. package/naming-strategy/AbstractNamingStrategy.d.ts +39 -54
  86. package/naming-strategy/AbstractNamingStrategy.js +85 -90
  87. package/naming-strategy/EntityCaseNamingStrategy.d.ts +6 -6
  88. package/naming-strategy/EntityCaseNamingStrategy.js +22 -22
  89. package/naming-strategy/MongoNamingStrategy.d.ts +6 -6
  90. package/naming-strategy/MongoNamingStrategy.js +18 -18
  91. package/naming-strategy/NamingStrategy.d.ts +99 -109
  92. package/naming-strategy/UnderscoreNamingStrategy.d.ts +7 -7
  93. package/naming-strategy/UnderscoreNamingStrategy.js +21 -21
  94. package/not-supported.js +4 -7
  95. package/package.json +1 -1
  96. package/platforms/ExceptionConverter.d.ts +1 -1
  97. package/platforms/ExceptionConverter.js +4 -4
  98. package/platforms/Platform.d.ts +299 -308
  99. package/platforms/Platform.js +636 -659
  100. package/serialization/EntitySerializer.d.ts +26 -48
  101. package/serialization/EntitySerializer.js +218 -224
  102. package/serialization/EntityTransformer.d.ts +6 -10
  103. package/serialization/EntityTransformer.js +217 -219
  104. package/serialization/SerializationContext.d.ts +23 -27
  105. package/serialization/SerializationContext.js +105 -105
  106. package/types/ArrayType.d.ts +8 -8
  107. package/types/ArrayType.js +33 -33
  108. package/types/BigIntType.d.ts +10 -17
  109. package/types/BigIntType.js +37 -37
  110. package/types/BlobType.d.ts +3 -3
  111. package/types/BlobType.js +13 -13
  112. package/types/BooleanType.d.ts +4 -4
  113. package/types/BooleanType.js +12 -12
  114. package/types/CharacterType.d.ts +2 -2
  115. package/types/CharacterType.js +6 -6
  116. package/types/DateTimeType.d.ts +5 -5
  117. package/types/DateTimeType.js +15 -15
  118. package/types/DateType.d.ts +5 -5
  119. package/types/DateType.js +15 -15
  120. package/types/DecimalType.d.ts +7 -7
  121. package/types/DecimalType.js +26 -26
  122. package/types/DoubleType.d.ts +3 -3
  123. package/types/DoubleType.js +12 -12
  124. package/types/EnumArrayType.d.ts +5 -5
  125. package/types/EnumArrayType.js +24 -24
  126. package/types/EnumType.d.ts +3 -3
  127. package/types/EnumType.js +11 -11
  128. package/types/FloatType.d.ts +3 -3
  129. package/types/FloatType.js +9 -9
  130. package/types/IntegerType.d.ts +3 -3
  131. package/types/IntegerType.js +9 -9
  132. package/types/IntervalType.d.ts +4 -4
  133. package/types/IntervalType.js +12 -12
  134. package/types/JsonType.d.ts +8 -8
  135. package/types/JsonType.js +32 -32
  136. package/types/MediumIntType.d.ts +1 -1
  137. package/types/MediumIntType.js +3 -3
  138. package/types/SmallIntType.d.ts +3 -3
  139. package/types/SmallIntType.js +9 -9
  140. package/types/StringType.d.ts +4 -4
  141. package/types/StringType.js +12 -12
  142. package/types/TextType.d.ts +3 -3
  143. package/types/TextType.js +9 -9
  144. package/types/TimeType.d.ts +5 -5
  145. package/types/TimeType.js +17 -17
  146. package/types/TinyIntType.d.ts +3 -3
  147. package/types/TinyIntType.js +10 -10
  148. package/types/Type.d.ts +79 -83
  149. package/types/Type.js +82 -82
  150. package/types/Uint8ArrayType.d.ts +4 -4
  151. package/types/Uint8ArrayType.js +21 -21
  152. package/types/UnknownType.d.ts +4 -4
  153. package/types/UnknownType.js +12 -12
  154. package/types/UuidType.d.ts +5 -5
  155. package/types/UuidType.js +19 -19
  156. package/types/index.d.ts +49 -75
  157. package/types/index.js +26 -52
  158. package/typings.d.ts +729 -1211
  159. package/typings.js +231 -244
  160. package/unit-of-work/ChangeSet.d.ts +26 -26
  161. package/unit-of-work/ChangeSet.js +56 -56
  162. package/unit-of-work/ChangeSetComputer.d.ts +12 -12
  163. package/unit-of-work/ChangeSetComputer.js +170 -178
  164. package/unit-of-work/ChangeSetPersister.d.ts +44 -63
  165. package/unit-of-work/ChangeSetPersister.js +421 -442
  166. package/unit-of-work/CommitOrderCalculator.d.ts +40 -40
  167. package/unit-of-work/CommitOrderCalculator.js +88 -89
  168. package/unit-of-work/IdentityMap.d.ts +31 -31
  169. package/unit-of-work/IdentityMap.js +105 -105
  170. package/unit-of-work/UnitOfWork.d.ts +141 -181
  171. package/unit-of-work/UnitOfWork.js +1183 -1200
  172. package/utils/AbstractMigrator.d.ts +91 -111
  173. package/utils/AbstractMigrator.js +275 -275
  174. package/utils/AbstractSchemaGenerator.d.ts +34 -43
  175. package/utils/AbstractSchemaGenerator.js +122 -121
  176. package/utils/AsyncContext.d.ts +3 -3
  177. package/utils/AsyncContext.js +35 -34
  178. package/utils/Configuration.d.ts +808 -852
  179. package/utils/Configuration.js +344 -359
  180. package/utils/Cursor.d.ts +22 -40
  181. package/utils/Cursor.js +127 -135
  182. package/utils/DataloaderUtils.d.ts +43 -58
  183. package/utils/DataloaderUtils.js +198 -203
  184. package/utils/EntityComparator.d.ts +81 -98
  185. package/utils/EntityComparator.js +728 -824
  186. package/utils/NullHighlighter.d.ts +1 -1
  187. package/utils/NullHighlighter.js +3 -3
  188. package/utils/QueryHelper.d.ts +51 -79
  189. package/utils/QueryHelper.js +361 -372
  190. package/utils/RawQueryFragment.d.ts +34 -50
  191. package/utils/RawQueryFragment.js +105 -107
  192. package/utils/RequestContext.d.ts +32 -32
  193. package/utils/RequestContext.js +53 -52
  194. package/utils/TransactionContext.d.ts +16 -16
  195. package/utils/TransactionContext.js +27 -27
  196. package/utils/TransactionManager.d.ts +58 -58
  197. package/utils/TransactionManager.js +197 -199
  198. package/utils/Utils.d.ts +145 -204
  199. package/utils/Utils.js +813 -814
  200. package/utils/clone.js +113 -104
  201. package/utils/env-vars.js +88 -90
  202. package/utils/fs-utils.d.ts +15 -15
  203. package/utils/fs-utils.js +181 -180
  204. package/utils/upsert-utils.d.ts +5 -20
  205. package/utils/upsert-utils.js +116 -114
@@ -1,843 +1,747 @@
1
1
  import { clone } from './clone.js';
2
2
  import { ReferenceKind } from '../enums.js';
3
- import {
4
- compareArrays,
5
- compareBooleans,
6
- compareBuffers,
7
- compareObjects,
8
- equals,
9
- parseJsonSafe,
10
- Utils,
11
- } from './Utils.js';
3
+ import { compareArrays, compareBooleans, compareBuffers, compareObjects, equals, parseJsonSafe, Utils, } from './Utils.js';
12
4
  import { JsonType } from '../types/JsonType.js';
13
5
  import { Raw } from './RawQueryFragment.js';
14
6
  import { EntityIdentifier } from '../entity/EntityIdentifier.js';
15
7
  import { PolymorphicRef } from '../entity/PolymorphicRef.js';
16
8
  /** @internal Generates and caches JIT-compiled functions for comparing, snapshotting, and mapping entity data. */
17
9
  export class EntityComparator {
18
- #comparators = new Map();
19
- #mappers = new Map();
20
- #snapshotGenerators = new Map();
21
- #pkGetters = new Map();
22
- #pkGettersConverted = new Map();
23
- #pkSerializers = new Map();
24
- #tmpIndex = 0;
25
- #metadata;
26
- #platform;
27
- #config;
28
- constructor(metadata, platform, config) {
29
- this.#metadata = metadata;
30
- this.#platform = platform;
31
- this.#config = config;
32
- }
33
- /**
34
- * Computes difference between two entities.
35
- */
36
- diffEntities(entityName, a, b, options) {
37
- const comparator = this.getEntityComparator(entityName);
38
- return Utils.callCompiledFunction(comparator, a, b, options);
39
- }
40
- /** Returns true if two entity snapshots are identical (no differences). */
41
- matching(entityName, a, b) {
42
- const diff = this.diffEntities(entityName, a, b);
43
- return Utils.getObjectKeysSize(diff) === 0;
44
- }
45
- /**
46
- * Removes ORM specific code from entities and prepares it for serializing. Used before change set computation.
47
- * References will be mapped to primary keys, collections to arrays of primary keys.
48
- */
49
- prepareEntity(entity) {
50
- const generator = this.getSnapshotGenerator(entity.constructor);
51
- return Utils.callCompiledFunction(generator, entity);
52
- }
53
- /**
54
- * Maps database columns to properties.
55
- */
56
- mapResult(meta, result) {
57
- const mapper = this.getResultMapper(meta);
58
- return Utils.callCompiledFunction(mapper, result);
59
- }
60
- /**
61
- * @internal Highly performance-sensitive method.
62
- */
63
- getPkGetter(meta) {
64
- const exists = this.#pkGetters.get(meta);
65
- /* v8 ignore next */
66
- if (exists) {
67
- return exists;
68
- }
69
- const lines = [];
70
- const context = new Map();
71
- if (meta.primaryKeys.length > 1) {
72
- lines.push(` const cond = {`);
73
- meta.primaryKeys.forEach(pk => {
74
- if (meta.properties[pk].kind !== ReferenceKind.SCALAR) {
75
- lines.push(
76
- ` ${pk}: (entity${this.wrap(pk)} != null && (entity${this.wrap(pk)}.__entity || entity${this.wrap(pk)}.__reference)) ? entity${this.wrap(pk)}.__helper.getPrimaryKey() : entity${this.wrap(pk)},`,
77
- );
78
- } else {
79
- lines.push(` ${pk}: entity${this.wrap(pk)},`);
80
- }
81
- });
82
- lines.push(` };`);
83
- lines.push(` if (${meta.primaryKeys.map(pk => `cond.${pk} == null`).join(' || ')}) return null;`);
84
- lines.push(` return cond;`);
85
- } else {
86
- const pk = meta.primaryKeys[0];
87
- if (meta.properties[pk].kind !== ReferenceKind.SCALAR) {
88
- lines.push(
89
- ` if (entity${this.wrap(pk)} != null && (entity${this.wrap(pk)}.__entity || entity${this.wrap(pk)}.__reference)) {`,
90
- );
91
- lines.push(` const pk = entity${this.wrap(pk)}.__helper.getPrimaryKey();`);
92
- if (meta.properties[pk].targetMeta.compositePK) {
93
- lines.push(` if (typeof pk === 'object' && pk != null) {`);
94
- lines.push(` return [`);
95
- for (const childPK of meta.properties[pk].targetMeta.primaryKeys) {
96
- lines.push(` pk${this.wrap(childPK)},`);
97
- }
98
- lines.push(` ];`);
99
- lines.push(` }`);
100
- }
101
- lines.push(` return pk;`);
102
- lines.push(` }`);
103
- }
104
- lines.push(` return entity${this.wrap(pk)};`);
105
- }
106
- const code =
107
- `// compiled pk getter for entity ${meta.className}\n` + `return function(entity) {\n${lines.join('\n')}\n}`;
108
- const fnKey = `pkGetter-${meta.uniqueName}`;
109
- const pkSerializer = Utils.createFunction(context, code, this.#config?.get('compiledFunctions'), fnKey);
110
- this.#pkGetters.set(meta, pkSerializer);
111
- return pkSerializer;
112
- }
113
- /**
114
- * @internal Highly performance-sensitive method.
115
- */
116
- getPkGetterConverted(meta) {
117
- const exists = this.#pkGettersConverted.get(meta);
118
- /* v8 ignore next */
119
- if (exists) {
120
- return exists;
121
- }
122
- const lines = [];
123
- const context = new Map();
124
- if (meta.primaryKeys.length > 1) {
125
- lines.push(` const cond = {`);
126
- meta.primaryKeys.forEach(pk => {
127
- if (meta.properties[pk].kind !== ReferenceKind.SCALAR) {
128
- lines.push(
129
- ` ${pk}: (entity${this.wrap(pk)} != null && (entity${this.wrap(pk)}.__entity || entity${this.wrap(pk)}.__reference)) ? entity${this.wrap(pk)}.__helper.getPrimaryKey(true) : entity${this.wrap(pk)},`,
130
- );
131
- } else {
132
- if (meta.properties[pk].customType) {
133
- const convertorKey = this.registerCustomType(meta.properties[pk], context);
134
- lines.push(` ${pk}: convertToDatabaseValue_${convertorKey}(entity${this.wrap(pk)}),`);
135
- } else {
136
- lines.push(` ${pk}: entity${this.wrap(pk)},`);
137
- }
138
- }
139
- });
140
- lines.push(` };`);
141
- lines.push(` if (${meta.primaryKeys.map(pk => `cond.${pk} == null`).join(' || ')}) return null;`);
142
- lines.push(` return cond;`);
143
- } else {
144
- const pk = meta.primaryKeys[0];
145
- if (meta.properties[pk].kind !== ReferenceKind.SCALAR) {
146
- lines.push(
147
- ` if (entity${this.wrap(pk)} != null && (entity${this.wrap(pk)}.__entity || entity${this.wrap(pk)}.__reference)) return entity${this.wrap(pk)}.__helper.getPrimaryKey(true);`,
148
- );
149
- }
150
- if (meta.properties[pk].customType) {
151
- const convertorKey = this.registerCustomType(meta.properties[pk], context);
152
- lines.push(` return convertToDatabaseValue_${convertorKey}(entity${this.wrap(pk)});`);
153
- } else {
154
- lines.push(` return entity${this.wrap(pk)};`);
155
- }
156
- }
157
- const code =
158
- `// compiled pk getter (with converted custom types) for entity ${meta.className}\n` +
159
- `return function(entity) {\n${lines.join('\n')}\n}`;
160
- const fnKey = `pkGetterConverted-${meta.uniqueName}`;
161
- const pkSerializer = Utils.createFunction(context, code, this.#config?.get('compiledFunctions'), fnKey);
162
- this.#pkGettersConverted.set(meta, pkSerializer);
163
- return pkSerializer;
164
- }
165
- /**
166
- * @internal Highly performance-sensitive method.
167
- */
168
- getPkSerializer(meta) {
169
- const exists = this.#pkSerializers.get(meta);
170
- /* v8 ignore next */
171
- if (exists) {
172
- return exists;
173
- }
174
- const lines = [];
175
- const context = new Map();
176
- context.set('getCompositeKeyValue', val =>
177
- Utils.flatten(Utils.getCompositeKeyValue(val, meta, 'convertToDatabaseValue', this.#platform)),
178
- );
179
- context.set('getPrimaryKeyHash', val => Utils.getPrimaryKeyHash(Utils.asArray(val)));
180
- if (meta.primaryKeys.length > 1) {
181
- lines.push(` const pks = entity.__helper.__pk ? getCompositeKeyValue(entity.__helper.__pk) : [`);
182
- meta.primaryKeys.forEach(pk => {
183
- if (meta.properties[pk].kind !== ReferenceKind.SCALAR) {
184
- lines.push(
185
- ` (entity${this.wrap(pk)} != null && (entity${this.wrap(pk)}.__entity || entity${this.wrap(pk)}.__reference)) ? entity${this.wrap(pk)}.__helper.getSerializedPrimaryKey() : entity${this.wrap(pk)},`,
186
- );
187
- } else {
188
- lines.push(` entity${this.wrap(pk)},`);
189
- }
190
- });
191
- lines.push(` ];`);
192
- lines.push(` return pks.join('${Utils.PK_SEPARATOR}');`);
193
- } else {
194
- const pk = meta.primaryKeys[0];
195
- const prop = meta.properties[pk];
196
- if (prop.kind !== ReferenceKind.SCALAR) {
197
- lines.push(
198
- ` if (entity${this.wrap(pk)} != null && (entity${this.wrap(pk)}.__entity || entity${this.wrap(pk)}.__reference)) return entity${this.wrap(pk)}.__helper.getSerializedPrimaryKey();`,
199
- );
200
- }
201
- const serializedPrimaryKey = meta.props.find(p => p.serializedPrimaryKey);
202
- if (serializedPrimaryKey) {
203
- lines.push(` return '' + entity.${serializedPrimaryKey.name};`);
204
- } else if (prop.customType) {
205
- const convertorKey = this.registerCustomType(meta.properties[pk], context);
206
- const idx = this.#tmpIndex++;
207
- lines.push(` const val_${idx} = convertToDatabaseValue_${convertorKey}(entity${this.wrap(pk)});`);
208
- lines.push(` return getPrimaryKeyHash(val_${idx});`);
209
- } else {
210
- lines.push(` return '' + entity${this.wrap(pk)};`);
211
- }
212
- }
213
- const code =
214
- `// compiled pk serializer for entity ${meta.className}\n` + `return function(entity) {\n${lines.join('\n')}\n}`;
215
- const fnKey = `pkSerializer-${meta.uniqueName}`;
216
- const pkSerializer = Utils.createFunction(context, code, this.#config?.get('compiledFunctions'), fnKey);
217
- this.#pkSerializers.set(meta, pkSerializer);
218
- return pkSerializer;
219
- }
220
- /**
221
- * @internal Highly performance-sensitive method.
222
- */
223
- getSnapshotGenerator(entityName) {
224
- const meta = this.#metadata.find(entityName);
225
- const exists = this.#snapshotGenerators.get(meta);
226
- if (exists) {
227
- return exists;
228
- }
229
- const lines = [];
230
- const context = new Map();
231
- context.set('clone', clone);
232
- context.set('cloneEmbeddable', o => this.#platform.cloneEmbeddable(o)); // do not clone prototypes
233
- if (meta.root.inheritanceType === 'sti' && meta.discriminatorValue) {
234
- lines.push(` ret${this.wrap(meta.root.discriminatorColumn)} = '${meta.discriminatorValue}'`);
235
- }
236
- const getRootProperty = prop => (prop.embedded ? getRootProperty(meta.properties[prop.embedded[0]]) : prop);
237
- // copy all comparable props, ignore collections and references, process custom types
238
- meta.comparableProps
239
- .filter(prop => {
240
- const root = getRootProperty(prop);
241
- return prop === root || root.kind !== ReferenceKind.EMBEDDED;
242
- })
243
- .forEach(prop =>
244
- lines.push(
245
- this.getPropertySnapshot(meta, prop, context, this.wrap(prop.name), this.wrap(prop.name), [prop.name]),
246
- ),
247
- );
248
- const code = `return function(entity) {\n const ret = {};\n${lines.join('\n')}\n return ret;\n}`;
249
- const fnKey = `snapshotGenerator-${meta.uniqueName}`;
250
- const snapshotGenerator = Utils.createFunction(context, code, this.#config?.get('compiledFunctions'), fnKey);
251
- this.#snapshotGenerators.set(meta, snapshotGenerator);
252
- return snapshotGenerator;
253
- }
254
- /**
255
- * @internal
256
- */
257
- propName(name, parent = 'result') {
258
- return parent + this.wrap(name);
259
- }
260
- /**
261
- * @internal respects nested composite keys, e.g. `[1, [2, 3]]`
262
- */
263
- createCompositeKeyArray(prop, parents = []) {
264
- if (!prop.targetMeta) {
265
- let fieldName = prop.fieldNames[0];
266
- // traverse all parents, mapping my field name to each parent's field name until we reach the root
267
- for (let i = parents.length - 1; i >= 0; i--) {
268
- const parent = parents[i];
269
- // skip m:n since it does not represent any column directly
270
- if (parent.pivotEntity) {
271
- continue;
272
- }
273
- const idx = parent.referencedColumnNames.indexOf(fieldName);
274
- fieldName = parent.fieldNames[idx];
275
- }
276
- return this.propName(fieldName);
277
- }
278
- const parts = [];
279
- prop.targetMeta.getPrimaryProps().forEach(pk => {
280
- const part = this.createCompositeKeyArray(pk, [...parents, prop]);
281
- parts.push(part);
282
- });
283
- return this.formatCompositeKeyPart(parts);
284
- }
285
- /**
286
- * @internal
287
- */
288
- formatCompositeKeyPart(part) {
289
- if (!Array.isArray(part)) {
290
- return part;
291
- }
292
- if (part.length === 1) {
293
- return this.formatCompositeKeyPart(part[0]);
294
- }
295
- const formatted = part.map(p => this.formatCompositeKeyPart(p)).join(', ');
296
- return `[${formatted}]`;
297
- }
298
- /**
299
- * @internal Highly performance-sensitive method.
300
- */
301
- getResultMapper(meta) {
302
- const exists = this.#mappers.get(meta);
303
- if (exists) {
304
- return exists;
305
- }
306
- const lines = [];
307
- const context = new Map();
308
- context.set('PolymorphicRef', PolymorphicRef);
309
- const tz = this.#platform.getTimezone();
310
- const parseDate = (key, value, padding = '') => {
311
- lines.push(`${padding} if (${value} == null || ${value} instanceof Date) {`);
312
- lines.push(`${padding} ${key} = ${value};`);
313
- if (!tz || tz === 'local') {
314
- lines.push(`${padding} } else if (typeof ${value} === 'bigint') {`);
315
- lines.push(`${padding} ${key} = parseDate(Number(${value}));`);
316
- lines.push(`${padding} } else {`);
317
- lines.push(`${padding} ${key} = parseDate(${value});`);
318
- } else {
319
- lines.push(`${padding} } else if (typeof ${value} === 'bigint') {`);
320
- lines.push(`${padding} ${key} = parseDate(Number(${value}));`);
321
- lines.push(
322
- `${padding} } else if (typeof ${value} === 'number' || ${value}.includes('+') || ${value}.lastIndexOf('-') > 10 || ${value}.endsWith('Z')) {`,
323
- );
324
- lines.push(`${padding} ${key} = parseDate(${value});`);
325
- lines.push(`${padding} } else {`);
326
- lines.push(`${padding} ${key} = parseDate(${value} + '${tz}');`);
327
- }
328
- lines.push(`${padding} }`);
329
- };
330
- lines.push(` const mapped = {};`);
331
- const mapEntityProperties = (meta, padding = '') => {
332
- for (const prop of meta.props) {
333
- if (!prop.fieldNames) {
334
- continue;
335
- }
336
- if (prop.polymorphic && prop.fieldNames.length >= 2) {
337
- const discriminatorField = prop.fieldNames[0];
338
- const idFields = prop.fieldNames.slice(1);
339
- lines.push(
340
- `${padding} if (${prop.fieldNames.map(field => `typeof ${this.propName(field)} === 'undefined'`).join(' && ')}) {`,
341
- );
342
- lines.push(
343
- `${padding} } else if (${prop.fieldNames.map(field => `${this.propName(field)} != null`).join(' && ')}) {`,
344
- );
345
- if (idFields.length === 1) {
346
- lines.push(
347
- `${padding} ret${this.wrap(prop.name)} = new PolymorphicRef(${this.propName(discriminatorField)}, ${this.propName(idFields[0])});`,
348
- );
349
- } else {
350
- lines.push(
351
- `${padding} ret${this.wrap(prop.name)} = new PolymorphicRef(${this.propName(discriminatorField)}, [${idFields.map(f => this.propName(f)).join(', ')}]);`,
352
- );
353
- }
354
- lines.push(...prop.fieldNames.map(field => `${padding} ${this.propName(field, 'mapped')} = true;`));
355
- lines.push(
356
- `${padding} } else if (${prop.fieldNames.map(field => `${this.propName(field)} == null`).join(' && ')}) {\n${padding} ret${this.wrap(prop.name)} = null;`,
357
- );
358
- lines.push(...prop.fieldNames.map(field => `${padding} ${this.propName(field, 'mapped')} = true;`), ' }');
359
- continue;
360
- }
361
- if (prop.targetMeta && prop.fieldNames.length > 1) {
362
- lines.push(
363
- `${padding} if (${prop.fieldNames.map(field => `typeof ${this.propName(field)} === 'undefined'`).join(' && ')}) {`,
364
- );
365
- lines.push(
366
- `${padding} } else if (${prop.fieldNames.map(field => `${this.propName(field)} != null`).join(' && ')}) {`,
367
- );
368
- lines.push(`${padding} ret${this.wrap(prop.name)} = ${this.createCompositeKeyArray(prop)};`);
369
- lines.push(...prop.fieldNames.map(field => `${padding} ${this.propName(field, 'mapped')} = true;`));
370
- lines.push(
371
- `${padding} } else if (${prop.fieldNames.map(field => `${this.propName(field)} == null`).join(' && ')}) {\n${padding} ret${this.wrap(prop.name)} = null;`,
372
- );
373
- lines.push(...prop.fieldNames.map(field => `${padding} ${this.propName(field, 'mapped')} = true;`), ' }');
374
- continue;
375
- }
376
- if (prop.embedded && (meta.embeddable || meta.properties[prop.embedded[0]].object)) {
377
- continue;
378
- }
379
- if (prop.runtimeType === 'boolean') {
380
- lines.push(`${padding} if (typeof ${this.propName(prop.fieldNames[0])} !== 'undefined') {`);
381
- lines.push(
382
- `${padding} ret${this.wrap(prop.name)} = ${this.propName(prop.fieldNames[0])} == null ? ${this.propName(prop.fieldNames[0])} : !!${this.propName(prop.fieldNames[0])};`,
383
- );
384
- lines.push(`${padding} ${this.propName(prop.fieldNames[0], 'mapped')} = true;`);
385
- lines.push(`${padding} }`);
386
- } else if (prop.runtimeType === 'Date' && !this.#platform.isNumericProperty(prop)) {
387
- lines.push(`${padding} if (typeof ${this.propName(prop.fieldNames[0])} !== 'undefined') {`);
388
- context.set('parseDate', value => this.#platform.parseDate(value));
389
- parseDate('ret' + this.wrap(prop.name), this.propName(prop.fieldNames[0]), padding);
390
- lines.push(`${padding} ${this.propName(prop.fieldNames[0], 'mapped')} = true;`);
391
- lines.push(`${padding} }`);
392
- } else if (prop.kind === ReferenceKind.EMBEDDED && (prop.object || meta.embeddable)) {
393
- const idx = this.#tmpIndex++;
394
- context.set(`mapEmbeddedResult_${idx}`, data => {
395
- const item = parseJsonSafe(data);
396
- if (Array.isArray(item)) {
397
- return item.map(row => (row == null ? row : this.getResultMapper(prop.targetMeta)(row)));
10
+ #comparators = new Map();
11
+ #mappers = new Map();
12
+ #snapshotGenerators = new Map();
13
+ #pkGetters = new Map();
14
+ #pkGettersConverted = new Map();
15
+ #pkSerializers = new Map();
16
+ #tmpIndex = 0;
17
+ #metadata;
18
+ #platform;
19
+ #config;
20
+ constructor(metadata, platform, config) {
21
+ this.#metadata = metadata;
22
+ this.#platform = platform;
23
+ this.#config = config;
24
+ }
25
+ /**
26
+ * Computes difference between two entities.
27
+ */
28
+ diffEntities(entityName, a, b, options) {
29
+ const comparator = this.getEntityComparator(entityName);
30
+ return Utils.callCompiledFunction(comparator, a, b, options);
31
+ }
32
+ /** Returns true if two entity snapshots are identical (no differences). */
33
+ matching(entityName, a, b) {
34
+ const diff = this.diffEntities(entityName, a, b);
35
+ return Utils.getObjectKeysSize(diff) === 0;
36
+ }
37
+ /**
38
+ * Removes ORM specific code from entities and prepares it for serializing. Used before change set computation.
39
+ * References will be mapped to primary keys, collections to arrays of primary keys.
40
+ */
41
+ prepareEntity(entity) {
42
+ const generator = this.getSnapshotGenerator(entity.constructor);
43
+ return Utils.callCompiledFunction(generator, entity);
44
+ }
45
+ /**
46
+ * Maps database columns to properties.
47
+ */
48
+ mapResult(meta, result) {
49
+ const mapper = this.getResultMapper(meta);
50
+ return Utils.callCompiledFunction(mapper, result);
51
+ }
52
+ /**
53
+ * @internal Highly performance-sensitive method.
54
+ */
55
+ getPkGetter(meta) {
56
+ const exists = this.#pkGetters.get(meta);
57
+ /* v8 ignore next */
58
+ if (exists) {
59
+ return exists;
60
+ }
61
+ const lines = [];
62
+ const context = new Map();
63
+ if (meta.primaryKeys.length > 1) {
64
+ lines.push(` const cond = {`);
65
+ meta.primaryKeys.forEach(pk => {
66
+ if (meta.properties[pk].kind !== ReferenceKind.SCALAR) {
67
+ lines.push(` ${pk}: (entity${this.wrap(pk)} != null && (entity${this.wrap(pk)}.__entity || entity${this.wrap(pk)}.__reference)) ? entity${this.wrap(pk)}.__helper.getPrimaryKey() : entity${this.wrap(pk)},`);
68
+ }
69
+ else {
70
+ lines.push(` ${pk}: entity${this.wrap(pk)},`);
71
+ }
72
+ });
73
+ lines.push(` };`);
74
+ lines.push(` if (${meta.primaryKeys.map(pk => `cond.${pk} == null`).join(' || ')}) return null;`);
75
+ lines.push(` return cond;`);
76
+ }
77
+ else {
78
+ const pk = meta.primaryKeys[0];
79
+ if (meta.properties[pk].kind !== ReferenceKind.SCALAR) {
80
+ lines.push(` if (entity${this.wrap(pk)} != null && (entity${this.wrap(pk)}.__entity || entity${this.wrap(pk)}.__reference)) {`);
81
+ lines.push(` const pk = entity${this.wrap(pk)}.__helper.getPrimaryKey();`);
82
+ if (meta.properties[pk].targetMeta.compositePK) {
83
+ lines.push(` if (typeof pk === 'object' && pk != null) {`);
84
+ lines.push(` return [`);
85
+ for (const childPK of meta.properties[pk].targetMeta.primaryKeys) {
86
+ lines.push(` pk${this.wrap(childPK)},`);
87
+ }
88
+ lines.push(` ];`);
89
+ lines.push(` }`);
90
+ }
91
+ lines.push(` return pk;`);
92
+ lines.push(` }`);
398
93
  }
399
- return item == null ? item : this.getResultMapper(prop.targetMeta)(item);
400
- });
401
- lines.push(`${padding} if (typeof ${this.propName(prop.fieldNames[0])} !== 'undefined') {`);
402
- lines.push(
403
- `${padding} ret${this.wrap(prop.name)} = ${this.propName(prop.fieldNames[0])} == null ? ${this.propName(prop.fieldNames[0])} : mapEmbeddedResult_${idx}(${this.propName(prop.fieldNames[0])});`,
404
- );
405
- lines.push(`${padding} ${this.propName(prop.fieldNames[0], 'mapped')} = true;`);
406
- lines.push(`${padding} }`);
407
- } else if (prop.kind !== ReferenceKind.EMBEDDED) {
408
- lines.push(`${padding} if (typeof ${this.propName(prop.fieldNames[0])} !== 'undefined') {`);
409
- lines.push(`${padding} ret${this.wrap(prop.name)} = ${this.propName(prop.fieldNames[0])};`);
410
- lines.push(`${padding} ${this.propName(prop.fieldNames[0], 'mapped')} = true;`);
411
- lines.push(`${padding} }`);
412
- }
413
- }
414
- };
415
- if (meta.polymorphs && meta.discriminatorColumn) {
416
- for (const polymorph of meta.polymorphs) {
417
- const first = polymorph === meta.polymorphs[0];
418
- lines.push(
419
- ` ${first ? '' : 'else '}if (${this.propName(meta.discriminatorColumn)} == '${polymorph.discriminatorValue}') {`,
420
- );
421
- mapEntityProperties(polymorph, ' ');
422
- lines.push(` }`);
423
- }
424
- lines.push(` else {`);
425
- mapEntityProperties(meta, ' ');
426
- lines.push(` }`);
427
- } else {
428
- mapEntityProperties(meta);
429
- }
430
- lines.push(
431
- ` for (let k in result) { if (Object.hasOwn(result, k) && !mapped[k] && ret[k] === undefined) ret[k] = result[k]; }`,
432
- );
433
- const code =
434
- `// compiled mapper for entity ${meta.className}\n` +
435
- `return function(result) {\n const ret = {};\n${lines.join('\n')}\n return ret;\n}`;
436
- const fnKey = `resultMapper-${meta.uniqueName}`;
437
- const resultMapper = Utils.createFunction(context, code, this.#config?.get('compiledFunctions'), fnKey);
438
- this.#mappers.set(meta, resultMapper);
439
- return resultMapper;
440
- }
441
- getPropertyCondition(path) {
442
- const parts = path.slice(); // copy first
443
- if (parts.length > 1) {
444
- parts.pop();
445
- }
446
- let tail = '';
447
- return parts
448
- .map(k => {
449
- if (/^\[idx_\d+]$/.exec(k)) {
450
- tail += k;
451
- return '';
452
- }
453
- const mapped = `typeof entity${tail ? '.' + tail : ''}${this.wrap(k)} !== 'undefined'`;
454
- tail += tail ? '.' + k : k;
455
- return mapped;
456
- })
457
- .filter(k => k)
458
- .join(' && ');
459
- }
460
- getEmbeddedArrayPropertySnapshot(meta, prop, context, level, path, dataKey) {
461
- const entityKey = path.map(k => this.wrap(k)).join('');
462
- const ret = [];
463
- const padding = ' '.repeat(level * 2);
464
- const idx = this.#tmpIndex++;
465
- ret.push(`${padding}if (Array.isArray(entity${entityKey})) {`);
466
- ret.push(`${padding} ret${dataKey} = [];`);
467
- ret.push(`${padding} entity${entityKey}.forEach((_, idx_${idx}) => {`);
468
- ret.push(
469
- this.getEmbeddedPropertySnapshot(
470
- meta,
471
- prop,
472
- context,
473
- level + 2,
474
- [...path, `[idx_${idx}]`],
475
- `${dataKey}[idx_${idx}]`,
476
- true,
477
- ),
478
- );
479
- ret.push(`${padding} });`);
480
- if (this.shouldSerialize(prop, dataKey)) {
481
- ret.push(`${padding} ret${dataKey} = cloneEmbeddable(ret${dataKey});`);
482
- }
483
- ret.push(`${padding}}`);
484
- return ret.join('\n');
485
- }
486
- /**
487
- * we need to serialize only object embeddables, and only the top level ones, so root object embeddable
488
- * properties and first child nested object embeddables with inlined parent
489
- */
490
- shouldSerialize(prop, dataKey) {
491
- dataKey = dataKey.replace(/^\./, '');
492
- const contains = (str, re) => (str.match(re) || []).length > 0;
493
- const a = contains(dataKey, /\./g);
494
- const b = contains(dataKey, /\[idx_/g);
495
- return !!prop.object && !a && !b;
496
- }
497
- getEmbeddedPropertySnapshot(meta, prop, context, level, path, dataKey, object = prop.object) {
498
- const padding = ' '.repeat(level * 2);
499
- const nullCond = `entity${path.map(k => this.wrap(k)).join('')} === null`;
500
- let ret = level === 1 ? '' : '\n';
501
- if (object) {
502
- ret += `${padding}if (${nullCond}) ret${dataKey} = null;\n`;
503
- } else {
504
- ret += `${padding}if (${nullCond}) {\n`;
505
- ret +=
506
- meta.props
507
- .filter(
508
- p =>
509
- p.embedded?.[0] === prop.name &&
510
- // object for JSON embeddable
511
- (p.object || p.persist !== false),
512
- )
513
- .map(childProp => {
514
- const childDataKey =
515
- meta.embeddable || prop.object ? dataKey + this.wrap(childProp.embedded[1]) : this.wrap(childProp.name);
516
- return `${padding} ret${childDataKey} = null;`;
517
- })
518
- .join('\n') + `\n`;
519
- ret += `${padding}}\n`;
520
- }
521
- const cond = `entity${path.map(k => this.wrap(k)).join('')} != null`;
522
- ret += `${padding}if (${cond}) {\n`;
523
- if (object) {
524
- ret += `${padding} ret${dataKey} = {};\n`;
525
- }
526
- function shouldProcessCustomType(childProp) {
527
- if (!childProp.customType) {
528
- return false;
529
- }
530
- if (childProp.customType instanceof JsonType) {
531
- return !prop.object;
532
- }
533
- return true;
534
- }
535
- ret +=
536
- meta.props
537
- .filter(
538
- p =>
539
- p.embedded?.[0] === prop.name &&
540
- // object for JSON embeddable
541
- (p.object || p.persist !== false),
542
- )
543
- .map(childProp => {
544
- const childDataKey =
545
- meta.embeddable || prop.object ? dataKey + this.wrap(childProp.embedded[1]) : this.wrap(childProp.name);
546
- const childEntityKey = [...path, childProp.embedded[1]].map(k => this.wrap(k)).join('');
547
- const childCond = `typeof entity${childEntityKey} !== 'undefined'`;
548
- if (childProp.kind === ReferenceKind.EMBEDDED) {
549
- return this.getPropertySnapshot(
550
- meta,
551
- childProp,
552
- context,
553
- childDataKey,
554
- childEntityKey,
555
- [...path, childProp.embedded[1]],
556
- level + 1,
557
- prop.object,
558
- );
559
- }
560
- if (childProp.kind !== ReferenceKind.SCALAR) {
561
- return this.getPropertySnapshot(
562
- meta,
563
- childProp,
564
- context,
565
- childDataKey,
566
- childEntityKey,
567
- [...path, childProp.embedded[1]],
568
- level,
569
- prop.object,
570
- )
571
- .split('\n')
572
- .map(l => padding + l)
573
- .join('\n');
574
- }
575
- if (shouldProcessCustomType(childProp)) {
576
- const convertorKey = this.registerCustomType(childProp, context);
577
- if (
578
- ['number', 'string', 'boolean', 'bigint'].includes(childProp.customType.compareAsType().toLowerCase())
579
- ) {
580
- return `${padding} if (${childCond}) ret${childDataKey} = convertToDatabaseValue_${convertorKey}(entity${childEntityKey});`;
94
+ lines.push(` return entity${this.wrap(pk)};`);
95
+ }
96
+ const code = `// compiled pk getter for entity ${meta.className}\n` + `return function(entity) {\n${lines.join('\n')}\n}`;
97
+ const fnKey = `pkGetter-${meta.uniqueName}`;
98
+ const pkSerializer = Utils.createFunction(context, code, this.#config?.get('compiledFunctions'), fnKey);
99
+ this.#pkGetters.set(meta, pkSerializer);
100
+ return pkSerializer;
101
+ }
102
+ /**
103
+ * @internal Highly performance-sensitive method.
104
+ */
105
+ getPkGetterConverted(meta) {
106
+ const exists = this.#pkGettersConverted.get(meta);
107
+ /* v8 ignore next */
108
+ if (exists) {
109
+ return exists;
110
+ }
111
+ const lines = [];
112
+ const context = new Map();
113
+ if (meta.primaryKeys.length > 1) {
114
+ lines.push(` const cond = {`);
115
+ meta.primaryKeys.forEach(pk => {
116
+ if (meta.properties[pk].kind !== ReferenceKind.SCALAR) {
117
+ lines.push(` ${pk}: (entity${this.wrap(pk)} != null && (entity${this.wrap(pk)}.__entity || entity${this.wrap(pk)}.__reference)) ? entity${this.wrap(pk)}.__helper.getPrimaryKey(true) : entity${this.wrap(pk)},`);
118
+ }
119
+ else {
120
+ if (meta.properties[pk].customType) {
121
+ const convertorKey = this.registerCustomType(meta.properties[pk], context);
122
+ lines.push(` ${pk}: convertToDatabaseValue_${convertorKey}(entity${this.wrap(pk)}),`);
123
+ }
124
+ else {
125
+ lines.push(` ${pk}: entity${this.wrap(pk)},`);
126
+ }
127
+ }
128
+ });
129
+ lines.push(` };`);
130
+ lines.push(` if (${meta.primaryKeys.map(pk => `cond.${pk} == null`).join(' || ')}) return null;`);
131
+ lines.push(` return cond;`);
132
+ }
133
+ else {
134
+ const pk = meta.primaryKeys[0];
135
+ if (meta.properties[pk].kind !== ReferenceKind.SCALAR) {
136
+ lines.push(` if (entity${this.wrap(pk)} != null && (entity${this.wrap(pk)}.__entity || entity${this.wrap(pk)}.__reference)) return entity${this.wrap(pk)}.__helper.getPrimaryKey(true);`);
137
+ }
138
+ if (meta.properties[pk].customType) {
139
+ const convertorKey = this.registerCustomType(meta.properties[pk], context);
140
+ lines.push(` return convertToDatabaseValue_${convertorKey}(entity${this.wrap(pk)});`);
581
141
  }
582
- return `${padding} if (${childCond}) ret${childDataKey} = clone(convertToDatabaseValue_${convertorKey}(entity${childEntityKey}));`;
583
- }
584
- return `${padding} if (${childCond}) ret${childDataKey} = clone(entity${childEntityKey});`;
142
+ else {
143
+ lines.push(` return entity${this.wrap(pk)};`);
144
+ }
145
+ }
146
+ const code = `// compiled pk getter (with converted custom types) for entity ${meta.className}\n` +
147
+ `return function(entity) {\n${lines.join('\n')}\n}`;
148
+ const fnKey = `pkGetterConverted-${meta.uniqueName}`;
149
+ const pkSerializer = Utils.createFunction(context, code, this.#config?.get('compiledFunctions'), fnKey);
150
+ this.#pkGettersConverted.set(meta, pkSerializer);
151
+ return pkSerializer;
152
+ }
153
+ /**
154
+ * @internal Highly performance-sensitive method.
155
+ */
156
+ getPkSerializer(meta) {
157
+ const exists = this.#pkSerializers.get(meta);
158
+ /* v8 ignore next */
159
+ if (exists) {
160
+ return exists;
161
+ }
162
+ const lines = [];
163
+ const context = new Map();
164
+ context.set('getCompositeKeyValue', (val) => Utils.flatten(Utils.getCompositeKeyValue(val, meta, 'convertToDatabaseValue', this.#platform)));
165
+ context.set('getPrimaryKeyHash', (val) => Utils.getPrimaryKeyHash(Utils.asArray(val)));
166
+ if (meta.primaryKeys.length > 1) {
167
+ lines.push(` const pks = entity.__helper.__pk ? getCompositeKeyValue(entity.__helper.__pk) : [`);
168
+ meta.primaryKeys.forEach(pk => {
169
+ if (meta.properties[pk].kind !== ReferenceKind.SCALAR) {
170
+ lines.push(` (entity${this.wrap(pk)} != null && (entity${this.wrap(pk)}.__entity || entity${this.wrap(pk)}.__reference)) ? entity${this.wrap(pk)}.__helper.getSerializedPrimaryKey() : entity${this.wrap(pk)},`);
171
+ }
172
+ else {
173
+ lines.push(` entity${this.wrap(pk)},`);
174
+ }
175
+ });
176
+ lines.push(` ];`);
177
+ lines.push(` return pks.join('${Utils.PK_SEPARATOR}');`);
178
+ }
179
+ else {
180
+ const pk = meta.primaryKeys[0];
181
+ const prop = meta.properties[pk];
182
+ if (prop.kind !== ReferenceKind.SCALAR) {
183
+ lines.push(` if (entity${this.wrap(pk)} != null && (entity${this.wrap(pk)}.__entity || entity${this.wrap(pk)}.__reference)) return entity${this.wrap(pk)}.__helper.getSerializedPrimaryKey();`);
184
+ }
185
+ const serializedPrimaryKey = meta.props.find(p => p.serializedPrimaryKey);
186
+ if (serializedPrimaryKey) {
187
+ lines.push(` return '' + entity.${serializedPrimaryKey.name};`);
188
+ }
189
+ else if (prop.customType) {
190
+ const convertorKey = this.registerCustomType(meta.properties[pk], context);
191
+ const idx = this.#tmpIndex++;
192
+ lines.push(` const val_${idx} = convertToDatabaseValue_${convertorKey}(entity${this.wrap(pk)});`);
193
+ lines.push(` return getPrimaryKeyHash(val_${idx});`);
194
+ }
195
+ else {
196
+ lines.push(` return '' + entity${this.wrap(pk)};`);
197
+ }
198
+ }
199
+ const code = `// compiled pk serializer for entity ${meta.className}\n` + `return function(entity) {\n${lines.join('\n')}\n}`;
200
+ const fnKey = `pkSerializer-${meta.uniqueName}`;
201
+ const pkSerializer = Utils.createFunction(context, code, this.#config?.get('compiledFunctions'), fnKey);
202
+ this.#pkSerializers.set(meta, pkSerializer);
203
+ return pkSerializer;
204
+ }
205
+ /**
206
+ * @internal Highly performance-sensitive method.
207
+ */
208
+ getSnapshotGenerator(entityName) {
209
+ const meta = this.#metadata.find(entityName);
210
+ const exists = this.#snapshotGenerators.get(meta);
211
+ if (exists) {
212
+ return exists;
213
+ }
214
+ const lines = [];
215
+ const context = new Map();
216
+ context.set('clone', clone);
217
+ context.set('cloneEmbeddable', (o) => this.#platform.cloneEmbeddable(o)); // do not clone prototypes
218
+ if (meta.root.inheritanceType === 'sti' && meta.discriminatorValue) {
219
+ lines.push(` ret${this.wrap(meta.root.discriminatorColumn)} = '${meta.discriminatorValue}'`);
220
+ }
221
+ const getRootProperty = (prop) => prop.embedded ? getRootProperty(meta.properties[prop.embedded[0]]) : prop;
222
+ // copy all comparable props, ignore collections and references, process custom types
223
+ meta.comparableProps
224
+ .filter(prop => {
225
+ const root = getRootProperty(prop);
226
+ return prop === root || root.kind !== ReferenceKind.EMBEDDED;
585
227
  })
586
- .join('\n') + `\n`;
587
- if (this.shouldSerialize(prop, dataKey)) {
588
- return `${ret + padding} ret${dataKey} = cloneEmbeddable(ret${dataKey});\n${padding}}`;
589
- }
590
- return `${ret}${padding}}`;
591
- }
592
- registerCustomType(prop, context) {
593
- const convertorKey = this.safeKey(prop.name);
594
- context.set(`convertToDatabaseValue_${convertorKey}`, val => {
595
- /* v8 ignore next */
596
- if (Raw.isKnownFragment(val)) {
597
- return val;
598
- }
599
- return prop.customType.convertToDatabaseValue(val, this.#platform, { mode: 'serialization' });
600
- });
601
- return convertorKey;
602
- }
603
- getPropertySnapshot(meta, prop, context, dataKey, entityKey, path, level = 1, object) {
604
- const unwrap = prop.ref ? '?.unwrap()' : '';
605
- let ret = ` if (${this.getPropertyCondition(path)}) {\n`;
606
- if (['number', 'string', 'boolean'].includes(prop.type.toLowerCase())) {
607
- return ret + ` ret${dataKey} = entity${entityKey}${unwrap};\n }\n`;
608
- }
609
- if (prop.kind === ReferenceKind.EMBEDDED) {
610
- if (prop.array) {
611
- return this.getEmbeddedArrayPropertySnapshot(meta, prop, context, level, path, dataKey) + '\n';
612
- }
613
- return this.getEmbeddedPropertySnapshot(meta, prop, context, level, path, dataKey, object) + '\n';
614
- }
615
- if (prop.kind === ReferenceKind.ONE_TO_ONE || prop.kind === ReferenceKind.MANY_TO_ONE) {
616
- if (prop.mapToPk) {
617
- if (prop.customType) {
618
- const convertorKey = this.registerCustomType(prop, context);
619
- ret += ` ret${dataKey} = convertToDatabaseValue_${convertorKey}(entity${entityKey});\n`;
620
- } else {
621
- ret += ` ret${dataKey} = entity${entityKey};\n`;
622
- }
623
- } else if (prop.polymorphic) {
624
- const discriminatorMapKey = `discriminatorMapReverse_${prop.name}`;
625
- const reverseMap = new Map();
626
- for (const [key, value] of Object.entries(prop.discriminatorMap)) {
627
- reverseMap.set(value, key);
628
- }
629
- context.set(discriminatorMapKey, reverseMap);
630
- this.setToArrayHelper(context);
631
- context.set('EntityIdentifier', EntityIdentifier);
228
+ .forEach(prop => lines.push(this.getPropertySnapshot(meta, prop, context, this.wrap(prop.name), this.wrap(prop.name), [prop.name])));
229
+ const code = `return function(entity) {\n const ret = {};\n${lines.join('\n')}\n return ret;\n}`;
230
+ const fnKey = `snapshotGenerator-${meta.uniqueName}`;
231
+ const snapshotGenerator = Utils.createFunction(context, code, this.#config?.get('compiledFunctions'), fnKey);
232
+ this.#snapshotGenerators.set(meta, snapshotGenerator);
233
+ return snapshotGenerator;
234
+ }
235
+ /**
236
+ * @internal
237
+ */
238
+ propName(name, parent = 'result') {
239
+ return parent + this.wrap(name);
240
+ }
241
+ /**
242
+ * @internal respects nested composite keys, e.g. `[1, [2, 3]]`
243
+ */
244
+ createCompositeKeyArray(prop, parents = []) {
245
+ if (!prop.targetMeta) {
246
+ let fieldName = prop.fieldNames[0];
247
+ // traverse all parents, mapping my field name to each parent's field name until we reach the root
248
+ for (let i = parents.length - 1; i >= 0; i--) {
249
+ const parent = parents[i];
250
+ // skip m:n since it does not represent any column directly
251
+ if (parent.pivotEntity) {
252
+ continue;
253
+ }
254
+ const idx = parent.referencedColumnNames.indexOf(fieldName);
255
+ fieldName = parent.fieldNames[idx];
256
+ }
257
+ return this.propName(fieldName);
258
+ }
259
+ const parts = [];
260
+ prop.targetMeta.getPrimaryProps().forEach(pk => {
261
+ const part = this.createCompositeKeyArray(pk, [...parents, prop]);
262
+ parts.push(part);
263
+ });
264
+ return this.formatCompositeKeyPart(parts);
265
+ }
266
+ /**
267
+ * @internal
268
+ */
269
+ formatCompositeKeyPart(part) {
270
+ if (!Array.isArray(part)) {
271
+ return part;
272
+ }
273
+ if (part.length === 1) {
274
+ return this.formatCompositeKeyPart(part[0]);
275
+ }
276
+ const formatted = part.map(p => this.formatCompositeKeyPart(p)).join(', ');
277
+ return `[${formatted}]`;
278
+ }
279
+ /**
280
+ * @internal Highly performance-sensitive method.
281
+ */
282
+ getResultMapper(meta) {
283
+ const exists = this.#mappers.get(meta);
284
+ if (exists) {
285
+ return exists;
286
+ }
287
+ const lines = [];
288
+ const context = new Map();
632
289
  context.set('PolymorphicRef', PolymorphicRef);
633
- ret += ` if (entity${entityKey} === null) {\n`;
634
- ret += ` ret${dataKey} = null;\n`;
635
- ret += ` } else if (typeof entity${entityKey} !== 'undefined') {\n`;
636
- ret += ` const val${level} = entity${entityKey}${unwrap};\n`;
637
- ret += ` const discriminator = ${discriminatorMapKey}.get(val${level}?.constructor);\n`;
638
- ret += ` const pk = val${level}?.__helper?.__identifier && !val${level}?.__helper?.hasPrimaryKey()\n`;
639
- ret += ` ? val${level}.__helper.__identifier\n`;
640
- ret += ` : toArray(val${level}?.__helper?.getPrimaryKey(true));\n`;
641
- ret += ` ret${dataKey} = new PolymorphicRef(discriminator, pk);\n`;
642
- ret += ` }\n`;
643
- } else if (prop.targetKey) {
644
- // When targetKey is set, extract that property value instead of the PK
645
- const targetProp = prop.targetMeta?.properties[prop.targetKey];
646
- ret += ` if (entity${entityKey} === null) {\n`;
647
- ret += ` ret${dataKey} = null;\n`;
648
- ret += ` } else if (typeof entity${entityKey} !== 'undefined') {\n`;
649
- ret += ` const val${level} = entity${entityKey}${unwrap};\n`;
650
- if (targetProp?.customType) {
651
- // If targetKey property has a custom type, convert to database value
652
- const convertorKey = this.registerCustomType(targetProp, context);
653
- ret += ` ret${dataKey} = convertToDatabaseValue_${convertorKey}(val${level}?.${prop.targetKey});\n`;
654
- } else {
655
- ret += ` ret${dataKey} = val${level}?.${prop.targetKey};\n`;
656
- }
657
- ret += ` }\n`;
658
- } else {
659
- this.setToArrayHelper(context);
660
- context.set('EntityIdentifier', EntityIdentifier);
661
- ret += ` if (entity${entityKey} === null) {\n`;
662
- ret += ` ret${dataKey} = null;\n`;
663
- ret += ` } else if (entity${entityKey}?.__helper.__identifier && !entity${entityKey}.__helper.hasPrimaryKey()) {\n`;
664
- ret += ` ret${dataKey} = entity${entityKey}?.__helper.__identifier;\n`;
665
- ret += ` } else if (typeof entity${entityKey} !== 'undefined') {\n`;
666
- ret += ` ret${dataKey} = toArray(entity${entityKey}.__helper.getPrimaryKey(true));\n`;
667
- ret += ` }\n`;
668
- }
669
- return ret + ' }\n';
670
- }
671
- if (prop.customType) {
672
- const convertorKey = this.registerCustomType(prop, context);
673
- if (['number', 'string', 'boolean', 'bigint'].includes(prop.customType.compareAsType().toLowerCase())) {
674
- return ret + ` ret${dataKey} = convertToDatabaseValue_${convertorKey}(entity${entityKey}${unwrap});\n }\n`;
675
- }
676
- return (
677
- ret + ` ret${dataKey} = clone(convertToDatabaseValue_${convertorKey}(entity${entityKey}${unwrap}));\n }\n`
678
- );
679
- }
680
- if (prop.runtimeType === 'Date') {
681
- context.set('processDateProperty', this.#platform.processDateProperty.bind(this.#platform));
682
- return ret + ` ret${dataKey} = clone(processDateProperty(entity${entityKey}${unwrap}));\n }\n`;
683
- }
684
- return ret + ` ret${dataKey} = clone(entity${entityKey}${unwrap});\n }\n`;
685
- }
686
- /**
687
- * @internal Highly performance-sensitive method.
688
- */
689
- getEntityComparator(entityName) {
690
- const meta = this.#metadata.find(entityName);
691
- const exists = this.#comparators.get(meta);
692
- if (exists) {
693
- return exists;
694
- }
695
- const lines = [];
696
- const context = new Map();
697
- context.set('compareArrays', compareArrays);
698
- context.set('compareBooleans', compareBooleans);
699
- context.set('compareBuffers', compareBuffers);
700
- context.set('compareObjects', compareObjects);
701
- context.set('equals', equals);
702
- for (const prop of meta.comparableProps) {
703
- lines.push(this.getPropertyComparator(prop, context));
704
- }
705
- // also compare 1:1 inverse sides, important for `factory.mergeData`
706
- lines.push(`if (options?.includeInverseSides) {`);
707
- for (const prop of meta.bidirectionalRelations) {
708
- if (prop.kind === ReferenceKind.ONE_TO_ONE && !prop.owner && prop.hydrate !== false) {
709
- lines.push(this.getPropertyComparator(prop, context));
710
- }
711
- }
712
- lines.push(`}`);
713
- const code =
714
- `// compiled comparator for entity ${meta.className}\n` +
715
- `return function(last, current, options) {\n const diff = {};\n${lines.join('\n')}\n return diff;\n}`;
716
- const fnKey = `comparator-${meta.uniqueName}`;
717
- const comparator = Utils.createFunction(context, code, this.#config?.get('compiledFunctions'), fnKey);
718
- this.#comparators.set(meta, comparator);
719
- return comparator;
720
- }
721
- getGenericComparator(prop, cond) {
722
- return (
723
- ` if (current${prop} === null && last${prop} === undefined) {\n` +
724
- ` diff${prop} = current${prop};\n` +
725
- ` } else if (current${prop} == null && last${prop} == null) {\n\n` +
726
- ` } else if ((current${prop} != null && last${prop} == null) || (current${prop} == null && last${prop} != null)) {\n` +
727
- ` diff${prop} = current${prop};\n` +
728
- ` } else if (${cond}) {\n` +
729
- ` diff${prop} = current${prop};\n` +
730
- ` }\n`
731
- );
732
- }
733
- getPropertyComparator(prop, context) {
734
- let type = prop.type.toLowerCase();
735
- if (prop.kind !== ReferenceKind.SCALAR && prop.kind !== ReferenceKind.EMBEDDED) {
736
- if (prop.polymorphic) {
737
- type = 'object';
738
- } else {
739
- const meta2 = prop.targetMeta;
740
- if (meta2.primaryKeys.length > 1) {
741
- type = 'array';
742
- } else {
743
- type = meta2.getPrimaryProp().type.toLowerCase();
744
- }
745
- }
290
+ const tz = this.#platform.getTimezone();
291
+ const parseDate = (key, value, padding = '') => {
292
+ lines.push(`${padding} if (${value} == null || ${value} instanceof Date) {`);
293
+ lines.push(`${padding} ${key} = ${value};`);
294
+ if (!tz || tz === 'local') {
295
+ lines.push(`${padding} } else if (typeof ${value} === 'bigint') {`);
296
+ lines.push(`${padding} ${key} = parseDate(Number(${value}));`);
297
+ lines.push(`${padding} } else {`);
298
+ lines.push(`${padding} ${key} = parseDate(${value});`);
299
+ }
300
+ else {
301
+ lines.push(`${padding} } else if (typeof ${value} === 'bigint') {`);
302
+ lines.push(`${padding} ${key} = parseDate(Number(${value}));`);
303
+ lines.push(`${padding} } else if (typeof ${value} === 'number' || ${value}.includes('+') || ${value}.lastIndexOf('-') > 10 || ${value}.endsWith('Z')) {`);
304
+ lines.push(`${padding} ${key} = parseDate(${value});`);
305
+ lines.push(`${padding} } else {`);
306
+ lines.push(`${padding} ${key} = parseDate(${value} + '${tz}');`);
307
+ }
308
+ lines.push(`${padding} }`);
309
+ };
310
+ lines.push(` const mapped = {};`);
311
+ const mapEntityProperties = (meta, padding = '') => {
312
+ for (const prop of meta.props) {
313
+ if (!prop.fieldNames) {
314
+ continue;
315
+ }
316
+ if (prop.polymorphic && prop.fieldNames.length >= 2) {
317
+ const discriminatorField = prop.fieldNames[0];
318
+ const idFields = prop.fieldNames.slice(1);
319
+ lines.push(`${padding} if (${prop.fieldNames.map(field => `typeof ${this.propName(field)} === 'undefined'`).join(' && ')}) {`);
320
+ lines.push(`${padding} } else if (${prop.fieldNames.map(field => `${this.propName(field)} != null`).join(' && ')}) {`);
321
+ if (idFields.length === 1) {
322
+ lines.push(`${padding} ret${this.wrap(prop.name)} = new PolymorphicRef(${this.propName(discriminatorField)}, ${this.propName(idFields[0])});`);
323
+ }
324
+ else {
325
+ lines.push(`${padding} ret${this.wrap(prop.name)} = new PolymorphicRef(${this.propName(discriminatorField)}, [${idFields.map(f => this.propName(f)).join(', ')}]);`);
326
+ }
327
+ lines.push(...prop.fieldNames.map(field => `${padding} ${this.propName(field, 'mapped')} = true;`));
328
+ lines.push(`${padding} } else if (${prop.fieldNames.map(field => `${this.propName(field)} == null`).join(' && ')}) {\n${padding} ret${this.wrap(prop.name)} = null;`);
329
+ lines.push(...prop.fieldNames.map(field => `${padding} ${this.propName(field, 'mapped')} = true;`), ' }');
330
+ continue;
331
+ }
332
+ if (prop.targetMeta && prop.fieldNames.length > 1) {
333
+ lines.push(`${padding} if (${prop.fieldNames.map(field => `typeof ${this.propName(field)} === 'undefined'`).join(' && ')}) {`);
334
+ lines.push(`${padding} } else if (${prop.fieldNames.map(field => `${this.propName(field)} != null`).join(' && ')}) {`);
335
+ lines.push(`${padding} ret${this.wrap(prop.name)} = ${this.createCompositeKeyArray(prop)};`);
336
+ lines.push(...prop.fieldNames.map(field => `${padding} ${this.propName(field, 'mapped')} = true;`));
337
+ lines.push(`${padding} } else if (${prop.fieldNames.map(field => `${this.propName(field)} == null`).join(' && ')}) {\n${padding} ret${this.wrap(prop.name)} = null;`);
338
+ lines.push(...prop.fieldNames.map(field => `${padding} ${this.propName(field, 'mapped')} = true;`), ' }');
339
+ continue;
340
+ }
341
+ if (prop.embedded && (meta.embeddable || meta.properties[prop.embedded[0]].object)) {
342
+ continue;
343
+ }
344
+ if (prop.runtimeType === 'boolean') {
345
+ lines.push(`${padding} if (typeof ${this.propName(prop.fieldNames[0])} !== 'undefined') {`);
346
+ lines.push(`${padding} ret${this.wrap(prop.name)} = ${this.propName(prop.fieldNames[0])} == null ? ${this.propName(prop.fieldNames[0])} : !!${this.propName(prop.fieldNames[0])};`);
347
+ lines.push(`${padding} ${this.propName(prop.fieldNames[0], 'mapped')} = true;`);
348
+ lines.push(`${padding} }`);
349
+ }
350
+ else if (prop.runtimeType === 'Date' && !this.#platform.isNumericProperty(prop)) {
351
+ lines.push(`${padding} if (typeof ${this.propName(prop.fieldNames[0])} !== 'undefined') {`);
352
+ context.set('parseDate', (value) => this.#platform.parseDate(value));
353
+ parseDate('ret' + this.wrap(prop.name), this.propName(prop.fieldNames[0]), padding);
354
+ lines.push(`${padding} ${this.propName(prop.fieldNames[0], 'mapped')} = true;`);
355
+ lines.push(`${padding} }`);
356
+ }
357
+ else if (prop.kind === ReferenceKind.EMBEDDED && (prop.object || meta.embeddable)) {
358
+ const idx = this.#tmpIndex++;
359
+ context.set(`mapEmbeddedResult_${idx}`, (data) => {
360
+ const item = parseJsonSafe(data);
361
+ if (Array.isArray(item)) {
362
+ return item.map(row => (row == null ? row : this.getResultMapper(prop.targetMeta)(row)));
363
+ }
364
+ return item == null ? item : this.getResultMapper(prop.targetMeta)(item);
365
+ });
366
+ lines.push(`${padding} if (typeof ${this.propName(prop.fieldNames[0])} !== 'undefined') {`);
367
+ lines.push(`${padding} ret${this.wrap(prop.name)} = ${this.propName(prop.fieldNames[0])} == null ? ${this.propName(prop.fieldNames[0])} : mapEmbeddedResult_${idx}(${this.propName(prop.fieldNames[0])});`);
368
+ lines.push(`${padding} ${this.propName(prop.fieldNames[0], 'mapped')} = true;`);
369
+ lines.push(`${padding} }`);
370
+ }
371
+ else if (prop.kind !== ReferenceKind.EMBEDDED) {
372
+ lines.push(`${padding} if (typeof ${this.propName(prop.fieldNames[0])} !== 'undefined') {`);
373
+ lines.push(`${padding} ret${this.wrap(prop.name)} = ${this.propName(prop.fieldNames[0])};`);
374
+ lines.push(`${padding} ${this.propName(prop.fieldNames[0], 'mapped')} = true;`);
375
+ lines.push(`${padding} }`);
376
+ }
377
+ }
378
+ };
379
+ if (meta.polymorphs && meta.discriminatorColumn) {
380
+ for (const polymorph of meta.polymorphs) {
381
+ const first = polymorph === meta.polymorphs[0];
382
+ lines.push(` ${first ? '' : 'else '}if (${this.propName(meta.discriminatorColumn)} == '${polymorph.discriminatorValue}') {`);
383
+ mapEntityProperties(polymorph, ' ');
384
+ lines.push(` }`);
385
+ }
386
+ lines.push(` else {`);
387
+ mapEntityProperties(meta, ' ');
388
+ lines.push(` }`);
389
+ }
390
+ else {
391
+ mapEntityProperties(meta);
392
+ }
393
+ lines.push(` for (let k in result) { if (Object.hasOwn(result, k) && !mapped[k] && ret[k] === undefined) ret[k] = result[k]; }`);
394
+ const code = `// compiled mapper for entity ${meta.className}\n` +
395
+ `return function(result) {\n const ret = {};\n${lines.join('\n')}\n return ret;\n}`;
396
+ const fnKey = `resultMapper-${meta.uniqueName}`;
397
+ const resultMapper = Utils.createFunction(context, code, this.#config?.get('compiledFunctions'), fnKey);
398
+ this.#mappers.set(meta, resultMapper);
399
+ return resultMapper;
400
+ }
401
+ getPropertyCondition(path) {
402
+ const parts = path.slice(); // copy first
403
+ if (parts.length > 1) {
404
+ parts.pop();
405
+ }
406
+ let tail = '';
407
+ return parts
408
+ .map(k => {
409
+ if (/^\[idx_\d+]$/.exec(k)) {
410
+ tail += k;
411
+ return '';
412
+ }
413
+ const mapped = `typeof entity${tail ? '.' + tail : ''}${this.wrap(k)} !== 'undefined'`;
414
+ tail += tail ? '.' + k : k;
415
+ return mapped;
416
+ })
417
+ .filter(k => k)
418
+ .join(' && ');
746
419
  }
747
- if (prop.customType) {
748
- if (prop.customType.compareValues) {
420
+ getEmbeddedArrayPropertySnapshot(meta, prop, context, level, path, dataKey) {
421
+ const entityKey = path.map(k => this.wrap(k)).join('');
422
+ const ret = [];
423
+ const padding = ' '.repeat(level * 2);
749
424
  const idx = this.#tmpIndex++;
750
- context.set(`compareValues_${idx}`, (a, b) => {
751
- if (Raw.isKnownFragment(a) || Raw.isKnownFragment(b)) {
752
- return Raw.getKnownFragment(a) === Raw.getKnownFragment(b);
753
- }
754
- return prop.customType.compareValues(a, b);
425
+ ret.push(`${padding}if (Array.isArray(entity${entityKey})) {`);
426
+ ret.push(`${padding} ret${dataKey} = [];`);
427
+ ret.push(`${padding} entity${entityKey}.forEach((_, idx_${idx}) => {`);
428
+ ret.push(this.getEmbeddedPropertySnapshot(meta, prop, context, level + 2, [...path, `[idx_${idx}]`], `${dataKey}[idx_${idx}]`, true));
429
+ ret.push(`${padding} });`);
430
+ if (this.shouldSerialize(prop, dataKey)) {
431
+ ret.push(`${padding} ret${dataKey} = cloneEmbeddable(ret${dataKey});`);
432
+ }
433
+ ret.push(`${padding}}`);
434
+ return ret.join('\n');
435
+ }
436
+ /**
437
+ * we need to serialize only object embeddables, and only the top level ones, so root object embeddable
438
+ * properties and first child nested object embeddables with inlined parent
439
+ */
440
+ shouldSerialize(prop, dataKey) {
441
+ dataKey = dataKey.replace(/^\./, '');
442
+ const contains = (str, re) => (str.match(re) || []).length > 0;
443
+ const a = contains(dataKey, /\./g);
444
+ const b = contains(dataKey, /\[idx_/g);
445
+ return !!prop.object && !a && !b;
446
+ }
447
+ getEmbeddedPropertySnapshot(meta, prop, context, level, path, dataKey, object = prop.object) {
448
+ const padding = ' '.repeat(level * 2);
449
+ const nullCond = `entity${path.map(k => this.wrap(k)).join('')} === null`;
450
+ let ret = level === 1 ? '' : '\n';
451
+ if (object) {
452
+ ret += `${padding}if (${nullCond}) ret${dataKey} = null;\n`;
453
+ }
454
+ else {
455
+ ret += `${padding}if (${nullCond}) {\n`;
456
+ ret +=
457
+ meta.props
458
+ .filter(p => p.embedded?.[0] === prop.name &&
459
+ // object for JSON embeddable
460
+ (p.object || p.persist !== false))
461
+ .map(childProp => {
462
+ const childDataKey = meta.embeddable || prop.object ? dataKey + this.wrap(childProp.embedded[1]) : this.wrap(childProp.name);
463
+ return `${padding} ret${childDataKey} = null;`;
464
+ })
465
+ .join('\n') + `\n`;
466
+ ret += `${padding}}\n`;
467
+ }
468
+ const cond = `entity${path.map(k => this.wrap(k)).join('')} != null`;
469
+ ret += `${padding}if (${cond}) {\n`;
470
+ if (object) {
471
+ ret += `${padding} ret${dataKey} = {};\n`;
472
+ }
473
+ function shouldProcessCustomType(childProp) {
474
+ if (!childProp.customType) {
475
+ return false;
476
+ }
477
+ if (childProp.customType instanceof JsonType) {
478
+ return !prop.object;
479
+ }
480
+ return true;
481
+ }
482
+ ret +=
483
+ meta.props
484
+ .filter(p => p.embedded?.[0] === prop.name &&
485
+ // object for JSON embeddable
486
+ (p.object || p.persist !== false))
487
+ .map(childProp => {
488
+ const childDataKey = meta.embeddable || prop.object ? dataKey + this.wrap(childProp.embedded[1]) : this.wrap(childProp.name);
489
+ const childEntityKey = [...path, childProp.embedded[1]].map(k => this.wrap(k)).join('');
490
+ const childCond = `typeof entity${childEntityKey} !== 'undefined'`;
491
+ if (childProp.kind === ReferenceKind.EMBEDDED) {
492
+ return this.getPropertySnapshot(meta, childProp, context, childDataKey, childEntityKey, [...path, childProp.embedded[1]], level + 1, prop.object);
493
+ }
494
+ if (childProp.kind !== ReferenceKind.SCALAR) {
495
+ return this.getPropertySnapshot(meta, childProp, context, childDataKey, childEntityKey, [...path, childProp.embedded[1]], level, prop.object)
496
+ .split('\n')
497
+ .map(l => padding + l)
498
+ .join('\n');
499
+ }
500
+ if (shouldProcessCustomType(childProp)) {
501
+ const convertorKey = this.registerCustomType(childProp, context);
502
+ if (['number', 'string', 'boolean', 'bigint'].includes(childProp.customType.compareAsType().toLowerCase())) {
503
+ return `${padding} if (${childCond}) ret${childDataKey} = convertToDatabaseValue_${convertorKey}(entity${childEntityKey});`;
504
+ }
505
+ return `${padding} if (${childCond}) ret${childDataKey} = clone(convertToDatabaseValue_${convertorKey}(entity${childEntityKey}));`;
506
+ }
507
+ return `${padding} if (${childCond}) ret${childDataKey} = clone(entity${childEntityKey});`;
508
+ })
509
+ .join('\n') + `\n`;
510
+ if (this.shouldSerialize(prop, dataKey)) {
511
+ return `${ret + padding} ret${dataKey} = cloneEmbeddable(ret${dataKey});\n${padding}}`;
512
+ }
513
+ return `${ret}${padding}}`;
514
+ }
515
+ registerCustomType(prop, context) {
516
+ const convertorKey = this.safeKey(prop.name);
517
+ context.set(`convertToDatabaseValue_${convertorKey}`, (val) => {
518
+ /* v8 ignore next */
519
+ if (Raw.isKnownFragment(val)) {
520
+ return val;
521
+ }
522
+ return prop.customType.convertToDatabaseValue(val, this.#platform, { mode: 'serialization' });
755
523
  });
756
- return this.getGenericComparator(
757
- this.wrap(prop.name),
758
- `!compareValues_${idx}(last${this.wrap(prop.name)}, current${this.wrap(prop.name)})`,
759
- );
760
- }
761
- type = prop.customType.compareAsType().toLowerCase();
762
- }
763
- if (type.endsWith('[]')) {
764
- type = 'array';
765
- }
766
- if (['string', 'number', 'bigint'].includes(type)) {
767
- return this.getGenericComparator(
768
- this.wrap(prop.name),
769
- `last${this.wrap(prop.name)} !== current${this.wrap(prop.name)}`,
770
- );
771
- }
772
- if (type === 'boolean') {
773
- return this.getGenericComparator(
774
- this.wrap(prop.name),
775
- `!compareBooleans(last${this.wrap(prop.name)}, current${this.wrap(prop.name)})`,
776
- );
777
- }
778
- if (['array'].includes(type) || type.endsWith('[]')) {
779
- return this.getGenericComparator(
780
- this.wrap(prop.name),
781
- `!compareArrays(last${this.wrap(prop.name)}, current${this.wrap(prop.name)})`,
782
- );
783
- }
784
- if (['buffer', 'uint8array'].includes(type)) {
785
- return this.getGenericComparator(
786
- this.wrap(prop.name),
787
- `!compareBuffers(last${this.wrap(prop.name)}, current${this.wrap(prop.name)})`,
788
- );
789
- }
790
- if (type === 'date') {
791
- return this.getGenericComparator(
792
- this.wrap(prop.name),
793
- `last${this.wrap(prop.name)}.valueOf() !== current${this.wrap(prop.name)}.valueOf()`,
794
- );
524
+ return convertorKey;
795
525
  }
796
- if (type === 'objectid') {
797
- // We might be comparing PK to object, in case we compare with cached data of populated entity
798
- // in such case we just ignore the comparison and fallback to `equals()` (which will still mark
799
- // it as not equal as we compare PK to plain object).
800
- const cond = `last${this.wrap(prop.name)}.toHexString?.() !== current${this.wrap(prop.name)}.toHexString?.()`;
801
- return this.getGenericComparator(this.wrap(prop.name), cond);
802
- }
803
- return this.getGenericComparator(
804
- this.wrap(prop.name),
805
- `!equals(last${this.wrap(prop.name)}, current${this.wrap(prop.name)})`,
806
- );
807
- }
808
- wrap(key) {
809
- if (/^\[.*]$/.exec(key)) {
810
- return key;
526
+ getPropertySnapshot(meta, prop, context, dataKey, entityKey, path, level = 1, object) {
527
+ const unwrap = prop.ref ? '?.unwrap()' : '';
528
+ let ret = ` if (${this.getPropertyCondition(path)}) {\n`;
529
+ if (['number', 'string', 'boolean'].includes(prop.type.toLowerCase())) {
530
+ return ret + ` ret${dataKey} = entity${entityKey}${unwrap};\n }\n`;
531
+ }
532
+ if (prop.kind === ReferenceKind.EMBEDDED) {
533
+ if (prop.array) {
534
+ return this.getEmbeddedArrayPropertySnapshot(meta, prop, context, level, path, dataKey) + '\n';
535
+ }
536
+ return this.getEmbeddedPropertySnapshot(meta, prop, context, level, path, dataKey, object) + '\n';
537
+ }
538
+ if (prop.kind === ReferenceKind.ONE_TO_ONE || prop.kind === ReferenceKind.MANY_TO_ONE) {
539
+ if (prop.mapToPk) {
540
+ if (prop.customType) {
541
+ const convertorKey = this.registerCustomType(prop, context);
542
+ ret += ` ret${dataKey} = convertToDatabaseValue_${convertorKey}(entity${entityKey});\n`;
543
+ }
544
+ else {
545
+ ret += ` ret${dataKey} = entity${entityKey};\n`;
546
+ }
547
+ }
548
+ else if (prop.polymorphic) {
549
+ const discriminatorMapKey = `discriminatorMapReverse_${prop.name}`;
550
+ const reverseMap = new Map();
551
+ for (const [key, value] of Object.entries(prop.discriminatorMap)) {
552
+ reverseMap.set(value, key);
553
+ }
554
+ context.set(discriminatorMapKey, reverseMap);
555
+ this.setToArrayHelper(context);
556
+ context.set('EntityIdentifier', EntityIdentifier);
557
+ context.set('PolymorphicRef', PolymorphicRef);
558
+ ret += ` if (entity${entityKey} === null) {\n`;
559
+ ret += ` ret${dataKey} = null;\n`;
560
+ ret += ` } else if (typeof entity${entityKey} !== 'undefined') {\n`;
561
+ ret += ` const val${level} = entity${entityKey}${unwrap};\n`;
562
+ ret += ` const discriminator = ${discriminatorMapKey}.get(val${level}?.constructor);\n`;
563
+ ret += ` const pk = val${level}?.__helper?.__identifier && !val${level}?.__helper?.hasPrimaryKey()\n`;
564
+ ret += ` ? val${level}.__helper.__identifier\n`;
565
+ ret += ` : toArray(val${level}?.__helper?.getPrimaryKey(true));\n`;
566
+ ret += ` ret${dataKey} = new PolymorphicRef(discriminator, pk);\n`;
567
+ ret += ` }\n`;
568
+ }
569
+ else if (prop.targetKey) {
570
+ // When targetKey is set, extract that property value instead of the PK
571
+ const targetProp = prop.targetMeta?.properties[prop.targetKey];
572
+ ret += ` if (entity${entityKey} === null) {\n`;
573
+ ret += ` ret${dataKey} = null;\n`;
574
+ ret += ` } else if (typeof entity${entityKey} !== 'undefined') {\n`;
575
+ ret += ` const val${level} = entity${entityKey}${unwrap};\n`;
576
+ if (targetProp?.customType) {
577
+ // If targetKey property has a custom type, convert to database value
578
+ const convertorKey = this.registerCustomType(targetProp, context);
579
+ ret += ` ret${dataKey} = convertToDatabaseValue_${convertorKey}(val${level}?.${prop.targetKey});\n`;
580
+ }
581
+ else {
582
+ ret += ` ret${dataKey} = val${level}?.${prop.targetKey};\n`;
583
+ }
584
+ ret += ` }\n`;
585
+ }
586
+ else {
587
+ this.setToArrayHelper(context);
588
+ context.set('EntityIdentifier', EntityIdentifier);
589
+ ret += ` if (entity${entityKey} === null) {\n`;
590
+ ret += ` ret${dataKey} = null;\n`;
591
+ ret += ` } else if (entity${entityKey}?.__helper.__identifier && !entity${entityKey}.__helper.hasPrimaryKey()) {\n`;
592
+ ret += ` ret${dataKey} = entity${entityKey}?.__helper.__identifier;\n`;
593
+ ret += ` } else if (typeof entity${entityKey} !== 'undefined') {\n`;
594
+ ret += ` ret${dataKey} = toArray(entity${entityKey}.__helper.getPrimaryKey(true));\n`;
595
+ ret += ` }\n`;
596
+ }
597
+ return ret + ' }\n';
598
+ }
599
+ if (prop.customType) {
600
+ const convertorKey = this.registerCustomType(prop, context);
601
+ if (['number', 'string', 'boolean', 'bigint'].includes(prop.customType.compareAsType().toLowerCase())) {
602
+ return ret + ` ret${dataKey} = convertToDatabaseValue_${convertorKey}(entity${entityKey}${unwrap});\n }\n`;
603
+ }
604
+ return (ret + ` ret${dataKey} = clone(convertToDatabaseValue_${convertorKey}(entity${entityKey}${unwrap}));\n }\n`);
605
+ }
606
+ if (prop.runtimeType === 'Date') {
607
+ context.set('processDateProperty', this.#platform.processDateProperty.bind(this.#platform));
608
+ return ret + ` ret${dataKey} = clone(processDateProperty(entity${entityKey}${unwrap}));\n }\n`;
609
+ }
610
+ return ret + ` ret${dataKey} = clone(entity${entityKey}${unwrap});\n }\n`;
611
+ }
612
+ /**
613
+ * @internal Highly performance-sensitive method.
614
+ */
615
+ getEntityComparator(entityName) {
616
+ const meta = this.#metadata.find(entityName);
617
+ const exists = this.#comparators.get(meta);
618
+ if (exists) {
619
+ return exists;
620
+ }
621
+ const lines = [];
622
+ const context = new Map();
623
+ context.set('compareArrays', compareArrays);
624
+ context.set('compareBooleans', compareBooleans);
625
+ context.set('compareBuffers', compareBuffers);
626
+ context.set('compareObjects', compareObjects);
627
+ context.set('equals', equals);
628
+ for (const prop of meta.comparableProps) {
629
+ lines.push(this.getPropertyComparator(prop, context));
630
+ }
631
+ // also compare 1:1 inverse sides, important for `factory.mergeData`
632
+ lines.push(`if (options?.includeInverseSides) {`);
633
+ for (const prop of meta.bidirectionalRelations) {
634
+ if (prop.kind === ReferenceKind.ONE_TO_ONE && !prop.owner && prop.hydrate !== false) {
635
+ lines.push(this.getPropertyComparator(prop, context));
636
+ }
637
+ }
638
+ lines.push(`}`);
639
+ const code = `// compiled comparator for entity ${meta.className}\n` +
640
+ `return function(last, current, options) {\n const diff = {};\n${lines.join('\n')}\n return diff;\n}`;
641
+ const fnKey = `comparator-${meta.uniqueName}`;
642
+ const comparator = Utils.createFunction(context, code, this.#config?.get('compiledFunctions'), fnKey);
643
+ this.#comparators.set(meta, comparator);
644
+ return comparator;
645
+ }
646
+ getGenericComparator(prop, cond) {
647
+ return (` if (current${prop} === null && last${prop} === undefined) {\n` +
648
+ ` diff${prop} = current${prop};\n` +
649
+ ` } else if (current${prop} == null && last${prop} == null) {\n\n` +
650
+ ` } else if ((current${prop} != null && last${prop} == null) || (current${prop} == null && last${prop} != null)) {\n` +
651
+ ` diff${prop} = current${prop};\n` +
652
+ ` } else if (${cond}) {\n` +
653
+ ` diff${prop} = current${prop};\n` +
654
+ ` }\n`);
655
+ }
656
+ getPropertyComparator(prop, context) {
657
+ let type = prop.type.toLowerCase();
658
+ if (prop.kind !== ReferenceKind.SCALAR && prop.kind !== ReferenceKind.EMBEDDED) {
659
+ if (prop.polymorphic) {
660
+ type = 'object';
661
+ }
662
+ else {
663
+ const meta2 = prop.targetMeta;
664
+ if (meta2.primaryKeys.length > 1) {
665
+ type = 'array';
666
+ }
667
+ else {
668
+ type = meta2.getPrimaryProp().type.toLowerCase();
669
+ }
670
+ }
671
+ }
672
+ if (prop.customType) {
673
+ if (prop.customType.compareValues) {
674
+ const idx = this.#tmpIndex++;
675
+ context.set(`compareValues_${idx}`, (a, b) => {
676
+ if (Raw.isKnownFragment(a) || Raw.isKnownFragment(b)) {
677
+ return Raw.getKnownFragment(a) === Raw.getKnownFragment(b);
678
+ }
679
+ return prop.customType.compareValues(a, b);
680
+ });
681
+ return this.getGenericComparator(this.wrap(prop.name), `!compareValues_${idx}(last${this.wrap(prop.name)}, current${this.wrap(prop.name)})`);
682
+ }
683
+ type = prop.customType.compareAsType().toLowerCase();
684
+ }
685
+ if (type.endsWith('[]')) {
686
+ type = 'array';
687
+ }
688
+ if (['string', 'number', 'bigint'].includes(type)) {
689
+ return this.getGenericComparator(this.wrap(prop.name), `last${this.wrap(prop.name)} !== current${this.wrap(prop.name)}`);
690
+ }
691
+ if (type === 'boolean') {
692
+ return this.getGenericComparator(this.wrap(prop.name), `!compareBooleans(last${this.wrap(prop.name)}, current${this.wrap(prop.name)})`);
693
+ }
694
+ if (['array'].includes(type) || type.endsWith('[]')) {
695
+ return this.getGenericComparator(this.wrap(prop.name), `!compareArrays(last${this.wrap(prop.name)}, current${this.wrap(prop.name)})`);
696
+ }
697
+ if (['buffer', 'uint8array'].includes(type)) {
698
+ return this.getGenericComparator(this.wrap(prop.name), `!compareBuffers(last${this.wrap(prop.name)}, current${this.wrap(prop.name)})`);
699
+ }
700
+ if (type === 'date') {
701
+ return this.getGenericComparator(this.wrap(prop.name), `last${this.wrap(prop.name)}.valueOf() !== current${this.wrap(prop.name)}.valueOf()`);
702
+ }
703
+ if (type === 'objectid') {
704
+ // We might be comparing PK to object, in case we compare with cached data of populated entity
705
+ // in such case we just ignore the comparison and fallback to `equals()` (which will still mark
706
+ // it as not equal as we compare PK to plain object).
707
+ const cond = `last${this.wrap(prop.name)}.toHexString?.() !== current${this.wrap(prop.name)}.toHexString?.()`;
708
+ return this.getGenericComparator(this.wrap(prop.name), cond);
709
+ }
710
+ return this.getGenericComparator(this.wrap(prop.name), `!equals(last${this.wrap(prop.name)}, current${this.wrap(prop.name)})`);
811
711
  }
812
- return /^\w+$/.exec(key) ? `.${key}` : `['${key}']`;
813
- }
814
- safeKey(key) {
815
- return key.replace(/\W/g, '_');
816
- }
817
- /**
818
- * Sets the toArray helper in the context if not already set.
819
- * Used for converting composite PKs to arrays.
820
- */
821
- setToArrayHelper(context) {
822
- if (context.has('toArray')) {
823
- return;
712
+ wrap(key) {
713
+ if (/^\[.*]$/.exec(key)) {
714
+ return key;
715
+ }
716
+ return /^\w+$/.exec(key) ? `.${key}` : `['${key}']`;
717
+ }
718
+ safeKey(key) {
719
+ return key.replace(/\W/g, '_');
720
+ }
721
+ /**
722
+ * Sets the toArray helper in the context if not already set.
723
+ * Used for converting composite PKs to arrays.
724
+ */
725
+ setToArrayHelper(context) {
726
+ if (context.has('toArray')) {
727
+ return;
728
+ }
729
+ const toArray = (val) => {
730
+ if (Utils.isPlainObject(val)) {
731
+ return Object.values(val).map(v => toArray(v));
732
+ }
733
+ return val;
734
+ };
735
+ context.set('toArray', toArray);
736
+ }
737
+ /**
738
+ * perf: used to generate list of comparable properties during discovery, so we speed up the runtime comparison
739
+ */
740
+ static isComparable(prop, root) {
741
+ const virtual = prop.persist === false || (prop.generated && !prop.primary);
742
+ const inverse = prop.kind === ReferenceKind.ONE_TO_ONE && !prop.owner;
743
+ const discriminator = prop.name === root.discriminatorColumn;
744
+ const collection = prop.kind === ReferenceKind.ONE_TO_MANY || prop.kind === ReferenceKind.MANY_TO_MANY;
745
+ return !virtual && !collection && !inverse && !discriminator && !prop.version;
824
746
  }
825
- const toArray = val => {
826
- if (Utils.isPlainObject(val)) {
827
- return Object.values(val).map(v => toArray(v));
828
- }
829
- return val;
830
- };
831
- context.set('toArray', toArray);
832
- }
833
- /**
834
- * perf: used to generate list of comparable properties during discovery, so we speed up the runtime comparison
835
- */
836
- static isComparable(prop, root) {
837
- const virtual = prop.persist === false || (prop.generated && !prop.primary);
838
- const inverse = prop.kind === ReferenceKind.ONE_TO_ONE && !prop.owner;
839
- const discriminator = prop.name === root.discriminatorColumn;
840
- const collection = prop.kind === ReferenceKind.ONE_TO_MANY || prop.kind === ReferenceKind.MANY_TO_MANY;
841
- return !virtual && !collection && !inverse && !discriminator && !prop.version;
842
- }
843
747
  }