@mikro-orm/core 7.0.4 → 7.0.5-dev.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (206) hide show
  1. package/EntityManager.d.ts +583 -884
  2. package/EntityManager.js +1895 -1922
  3. package/MikroORM.d.ts +74 -103
  4. package/MikroORM.js +179 -178
  5. package/README.md +1 -1
  6. package/cache/CacheAdapter.d.ts +36 -36
  7. package/cache/FileCacheAdapter.d.ts +24 -30
  8. package/cache/FileCacheAdapter.js +78 -80
  9. package/cache/GeneratedCacheAdapter.d.ts +20 -18
  10. package/cache/GeneratedCacheAdapter.js +30 -30
  11. package/cache/MemoryCacheAdapter.d.ts +20 -18
  12. package/cache/MemoryCacheAdapter.js +36 -35
  13. package/cache/NullCacheAdapter.d.ts +16 -16
  14. package/cache/NullCacheAdapter.js +24 -24
  15. package/connections/Connection.d.ts +84 -95
  16. package/connections/Connection.js +168 -165
  17. package/drivers/DatabaseDriver.d.ts +80 -186
  18. package/drivers/DatabaseDriver.js +443 -450
  19. package/drivers/IDatabaseDriver.d.ts +301 -440
  20. package/entity/BaseEntity.d.ts +83 -120
  21. package/entity/BaseEntity.js +43 -43
  22. package/entity/Collection.d.ts +179 -212
  23. package/entity/Collection.js +721 -727
  24. package/entity/EntityAssigner.d.ts +77 -88
  25. package/entity/EntityAssigner.js +230 -231
  26. package/entity/EntityFactory.d.ts +54 -66
  27. package/entity/EntityFactory.js +383 -425
  28. package/entity/EntityHelper.d.ts +22 -34
  29. package/entity/EntityHelper.js +267 -280
  30. package/entity/EntityIdentifier.d.ts +4 -4
  31. package/entity/EntityIdentifier.js +10 -10
  32. package/entity/EntityLoader.d.ts +72 -98
  33. package/entity/EntityLoader.js +723 -753
  34. package/entity/EntityRepository.d.ts +201 -316
  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 +82 -126
  39. package/entity/Reference.js +274 -278
  40. package/entity/WrappedEntity.d.ts +72 -115
  41. package/entity/WrappedEntity.js +166 -168
  42. package/entity/defineEntity.d.ts +636 -1315
  43. package/entity/defineEntity.js +518 -527
  44. package/entity/utils.d.ts +3 -13
  45. package/entity/utils.js +73 -71
  46. package/entity/validators.js +43 -43
  47. package/entity/wrap.js +8 -8
  48. package/enums.d.ts +253 -258
  49. package/enums.js +252 -251
  50. package/errors.d.ts +72 -114
  51. package/errors.js +253 -350
  52. package/events/EventManager.d.ts +14 -26
  53. package/events/EventManager.js +77 -79
  54. package/events/EventSubscriber.d.ts +29 -29
  55. package/events/TransactionEventBroadcaster.d.ts +8 -15
  56. package/events/TransactionEventBroadcaster.js +14 -14
  57. package/exceptions.d.ts +40 -23
  58. package/exceptions.js +52 -35
  59. package/hydration/Hydrator.d.ts +17 -42
  60. package/hydration/Hydrator.js +43 -43
  61. package/hydration/ObjectHydrator.d.ts +17 -50
  62. package/hydration/ObjectHydrator.js +416 -481
  63. package/index.d.ts +2 -116
  64. package/index.js +1 -10
  65. package/logging/DefaultLogger.d.ts +32 -34
  66. package/logging/DefaultLogger.js +86 -86
  67. package/logging/Logger.d.ts +41 -41
  68. package/logging/SimpleLogger.d.ts +11 -13
  69. package/logging/SimpleLogger.js +22 -22
  70. package/logging/colors.d.ts +6 -6
  71. package/logging/colors.js +10 -11
  72. package/logging/inspect.js +7 -7
  73. package/metadata/EntitySchema.d.ts +127 -211
  74. package/metadata/EntitySchema.js +398 -397
  75. package/metadata/MetadataDiscovery.d.ts +114 -114
  76. package/metadata/MetadataDiscovery.js +1870 -1951
  77. package/metadata/MetadataProvider.d.ts +21 -24
  78. package/metadata/MetadataProvider.js +84 -82
  79. package/metadata/MetadataStorage.d.ts +32 -38
  80. package/metadata/MetadataStorage.js +118 -118
  81. package/metadata/MetadataValidator.d.ts +39 -39
  82. package/metadata/MetadataValidator.js +338 -381
  83. package/metadata/discover-entities.d.ts +2 -5
  84. package/metadata/discover-entities.js +37 -35
  85. package/metadata/types.d.ts +531 -615
  86. package/naming-strategy/AbstractNamingStrategy.d.ts +39 -54
  87. package/naming-strategy/AbstractNamingStrategy.js +85 -90
  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 +99 -109
  93. package/naming-strategy/UnderscoreNamingStrategy.d.ts +7 -7
  94. package/naming-strategy/UnderscoreNamingStrategy.js +21 -21
  95. package/not-supported.js +4 -7
  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 +301 -310
  100. package/platforms/Platform.js +640 -663
  101. package/serialization/EntitySerializer.d.ts +26 -49
  102. package/serialization/EntitySerializer.js +218 -224
  103. package/serialization/EntityTransformer.d.ts +6 -10
  104. package/serialization/EntityTransformer.js +217 -219
  105. package/serialization/SerializationContext.d.ts +23 -27
  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 +10 -17
  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 +79 -83
  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 +49 -75
  158. package/types/index.js +26 -52
  159. package/typings.d.ts +737 -1250
  160. package/typings.js +231 -244
  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 +170 -178
  165. package/unit-of-work/ChangeSetPersister.d.ts +44 -63
  166. package/unit-of-work/ChangeSetPersister.js +421 -442
  167. package/unit-of-work/CommitOrderCalculator.d.ts +40 -40
  168. package/unit-of-work/CommitOrderCalculator.js +88 -89
  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 +141 -181
  172. package/unit-of-work/UnitOfWork.js +1183 -1200
  173. package/utils/AbstractMigrator.d.ts +91 -111
  174. package/utils/AbstractMigrator.js +275 -275
  175. package/utils/AbstractSchemaGenerator.d.ts +34 -43
  176. package/utils/AbstractSchemaGenerator.js +122 -121
  177. package/utils/AsyncContext.d.ts +3 -3
  178. package/utils/AsyncContext.js +35 -34
  179. package/utils/Configuration.d.ts +808 -852
  180. package/utils/Configuration.js +344 -359
  181. package/utils/Cursor.d.ts +22 -40
  182. package/utils/Cursor.js +127 -135
  183. package/utils/DataloaderUtils.d.ts +43 -58
  184. package/utils/DataloaderUtils.js +198 -203
  185. package/utils/EntityComparator.d.ts +81 -98
  186. package/utils/EntityComparator.js +732 -828
  187. package/utils/NullHighlighter.d.ts +1 -1
  188. package/utils/NullHighlighter.js +3 -3
  189. package/utils/QueryHelper.d.ts +51 -79
  190. package/utils/QueryHelper.js +361 -372
  191. package/utils/RawQueryFragment.d.ts +34 -50
  192. package/utils/RawQueryFragment.js +105 -107
  193. package/utils/RequestContext.d.ts +32 -32
  194. package/utils/RequestContext.js +53 -52
  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 +197 -199
  199. package/utils/Utils.d.ts +145 -204
  200. package/utils/Utils.js +812 -812
  201. package/utils/clone.js +113 -104
  202. package/utils/env-vars.js +88 -90
  203. package/utils/fs-utils.d.ts +15 -15
  204. package/utils/fs-utils.js +181 -180
  205. package/utils/upsert-utils.d.ts +5 -20
  206. package/utils/upsert-utils.js +116 -114
@@ -1,847 +1,751 @@
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)});`);
141
+ }
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});`);
581
194
  }
582
- return `${padding} if (${childCond}) ret${childDataKey} = clone(convertToDatabaseValue_${convertorKey}(entity${childEntityKey}));`;
583
- }
584
- return `${padding} if (${childCond}) ret${childDataKey} = clone(entity${childEntityKey});`;
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)}`;
606
- if (prop.lazy && prop.ref) {
607
- ret += ` && entity${path.map(k => this.wrap(k)).join('')}?.isInitialized()`;
608
- }
609
- ret += `) {\n`;
610
- if (['number', 'string', 'boolean'].includes(prop.type.toLowerCase())) {
611
- return ret + ` ret${dataKey} = entity${entityKey}${unwrap};\n }\n`;
612
- }
613
- if (prop.kind === ReferenceKind.EMBEDDED) {
614
- if (prop.array) {
615
- return this.getEmbeddedArrayPropertySnapshot(meta, prop, context, level, path, dataKey) + '\n';
616
- }
617
- return this.getEmbeddedPropertySnapshot(meta, prop, context, level, path, dataKey, object) + '\n';
618
- }
619
- if (prop.kind === ReferenceKind.ONE_TO_ONE || prop.kind === ReferenceKind.MANY_TO_ONE) {
620
- if (prop.mapToPk) {
621
- if (prop.customType) {
622
- const convertorKey = this.registerCustomType(prop, context);
623
- ret += ` ret${dataKey} = convertToDatabaseValue_${convertorKey}(entity${entityKey});\n`;
624
- } else {
625
- ret += ` ret${dataKey} = entity${entityKey};\n`;
626
- }
627
- } else if (prop.polymorphic) {
628
- const discriminatorMapKey = `discriminatorMapReverse_${prop.name}`;
629
- const reverseMap = new Map();
630
- for (const [key, value] of Object.entries(prop.discriminatorMap)) {
631
- reverseMap.set(value, key);
632
- }
633
- context.set(discriminatorMapKey, reverseMap);
634
- this.setToArrayHelper(context);
635
- 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();
636
289
  context.set('PolymorphicRef', PolymorphicRef);
637
- ret += ` if (entity${entityKey} === null) {\n`;
638
- ret += ` ret${dataKey} = null;\n`;
639
- ret += ` } else if (typeof entity${entityKey} !== 'undefined') {\n`;
640
- ret += ` const val${level} = entity${entityKey}${unwrap};\n`;
641
- ret += ` const discriminator = ${discriminatorMapKey}.get(val${level}?.constructor);\n`;
642
- ret += ` const pk = val${level}?.__helper?.__identifier && !val${level}?.__helper?.hasPrimaryKey()\n`;
643
- ret += ` ? val${level}.__helper.__identifier\n`;
644
- ret += ` : toArray(val${level}?.__helper?.getPrimaryKey(true));\n`;
645
- ret += ` ret${dataKey} = new PolymorphicRef(discriminator, pk);\n`;
646
- ret += ` }\n`;
647
- } else if (prop.targetKey) {
648
- // When targetKey is set, extract that property value instead of the PK
649
- const targetProp = prop.targetMeta?.properties[prop.targetKey];
650
- ret += ` if (entity${entityKey} === null) {\n`;
651
- ret += ` ret${dataKey} = null;\n`;
652
- ret += ` } else if (typeof entity${entityKey} !== 'undefined') {\n`;
653
- ret += ` const val${level} = entity${entityKey}${unwrap};\n`;
654
- if (targetProp?.customType) {
655
- // If targetKey property has a custom type, convert to database value
656
- const convertorKey = this.registerCustomType(targetProp, context);
657
- ret += ` ret${dataKey} = convertToDatabaseValue_${convertorKey}(val${level}?.${prop.targetKey});\n`;
658
- } else {
659
- ret += ` ret${dataKey} = val${level}?.${prop.targetKey};\n`;
660
- }
661
- ret += ` }\n`;
662
- } else {
663
- this.setToArrayHelper(context);
664
- context.set('EntityIdentifier', EntityIdentifier);
665
- ret += ` if (entity${entityKey} === null) {\n`;
666
- ret += ` ret${dataKey} = null;\n`;
667
- ret += ` } else if (entity${entityKey}?.__helper.__identifier && !entity${entityKey}.__helper.hasPrimaryKey()) {\n`;
668
- ret += ` ret${dataKey} = entity${entityKey}?.__helper.__identifier;\n`;
669
- ret += ` } else if (typeof entity${entityKey} !== 'undefined') {\n`;
670
- ret += ` ret${dataKey} = toArray(entity${entityKey}.__helper.getPrimaryKey(true));\n`;
671
- ret += ` }\n`;
672
- }
673
- return ret + ' }\n';
674
- }
675
- if (prop.customType) {
676
- const convertorKey = this.registerCustomType(prop, context);
677
- if (['number', 'string', 'boolean', 'bigint'].includes(prop.customType.compareAsType().toLowerCase())) {
678
- return ret + ` ret${dataKey} = convertToDatabaseValue_${convertorKey}(entity${entityKey}${unwrap});\n }\n`;
679
- }
680
- return (
681
- ret + ` ret${dataKey} = clone(convertToDatabaseValue_${convertorKey}(entity${entityKey}${unwrap}));\n }\n`
682
- );
683
- }
684
- if (prop.runtimeType === 'Date') {
685
- context.set('processDateProperty', this.#platform.processDateProperty.bind(this.#platform));
686
- return ret + ` ret${dataKey} = clone(processDateProperty(entity${entityKey}${unwrap}));\n }\n`;
687
- }
688
- return ret + ` ret${dataKey} = clone(entity${entityKey}${unwrap});\n }\n`;
689
- }
690
- /**
691
- * @internal Highly performance-sensitive method.
692
- */
693
- getEntityComparator(entityName) {
694
- const meta = this.#metadata.find(entityName);
695
- const exists = this.#comparators.get(meta);
696
- if (exists) {
697
- return exists;
698
- }
699
- const lines = [];
700
- const context = new Map();
701
- context.set('compareArrays', compareArrays);
702
- context.set('compareBooleans', compareBooleans);
703
- context.set('compareBuffers', compareBuffers);
704
- context.set('compareObjects', compareObjects);
705
- context.set('equals', equals);
706
- for (const prop of meta.comparableProps) {
707
- lines.push(this.getPropertyComparator(prop, context));
708
- }
709
- // also compare 1:1 inverse sides, important for `factory.mergeData`
710
- lines.push(`if (options?.includeInverseSides) {`);
711
- for (const prop of meta.bidirectionalRelations) {
712
- if (prop.kind === ReferenceKind.ONE_TO_ONE && !prop.owner && prop.hydrate !== false) {
713
- lines.push(this.getPropertyComparator(prop, context));
714
- }
715
- }
716
- lines.push(`}`);
717
- const code =
718
- `// compiled comparator for entity ${meta.className}\n` +
719
- `return function(last, current, options) {\n const diff = {};\n${lines.join('\n')}\n return diff;\n}`;
720
- const fnKey = `comparator-${meta.uniqueName}`;
721
- const comparator = Utils.createFunction(context, code, this.#config?.get('compiledFunctions'), fnKey);
722
- this.#comparators.set(meta, comparator);
723
- return comparator;
724
- }
725
- getGenericComparator(prop, cond) {
726
- return (
727
- ` if (current${prop} === null && last${prop} === undefined) {\n` +
728
- ` diff${prop} = current${prop};\n` +
729
- ` } else if (current${prop} == null && last${prop} == null) {\n\n` +
730
- ` } else if ((current${prop} != null && last${prop} == null) || (current${prop} == null && last${prop} != null)) {\n` +
731
- ` diff${prop} = current${prop};\n` +
732
- ` } else if (${cond}) {\n` +
733
- ` diff${prop} = current${prop};\n` +
734
- ` }\n`
735
- );
736
- }
737
- getPropertyComparator(prop, context) {
738
- let type = prop.type.toLowerCase();
739
- if (prop.kind !== ReferenceKind.SCALAR && prop.kind !== ReferenceKind.EMBEDDED) {
740
- if (prop.polymorphic) {
741
- type = 'object';
742
- } else {
743
- const meta2 = prop.targetMeta;
744
- if (meta2.primaryKeys.length > 1) {
745
- type = 'array';
746
- } else {
747
- type = meta2.getPrimaryProp().type.toLowerCase();
748
- }
749
- }
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(' && ');
750
419
  }
751
- if (prop.customType) {
752
- 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);
753
424
  const idx = this.#tmpIndex++;
754
- context.set(`compareValues_${idx}`, (a, b) => {
755
- if (Raw.isKnownFragment(a) || Raw.isKnownFragment(b)) {
756
- return Raw.getKnownFragment(a) === Raw.getKnownFragment(b);
757
- }
758
- 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' });
759
523
  });
760
- return this.getGenericComparator(
761
- this.wrap(prop.name),
762
- `!compareValues_${idx}(last${this.wrap(prop.name)}, current${this.wrap(prop.name)})`,
763
- );
764
- }
765
- type = prop.customType.compareAsType().toLowerCase();
766
- }
767
- if (type.endsWith('[]')) {
768
- type = 'array';
769
- }
770
- if (['string', 'number', 'bigint'].includes(type)) {
771
- return this.getGenericComparator(
772
- this.wrap(prop.name),
773
- `last${this.wrap(prop.name)} !== current${this.wrap(prop.name)}`,
774
- );
775
- }
776
- if (type === 'boolean') {
777
- return this.getGenericComparator(
778
- this.wrap(prop.name),
779
- `!compareBooleans(last${this.wrap(prop.name)}, current${this.wrap(prop.name)})`,
780
- );
781
- }
782
- if (['array'].includes(type) || type.endsWith('[]')) {
783
- return this.getGenericComparator(
784
- this.wrap(prop.name),
785
- `!compareArrays(last${this.wrap(prop.name)}, current${this.wrap(prop.name)})`,
786
- );
787
- }
788
- if (['buffer', 'uint8array'].includes(type)) {
789
- return this.getGenericComparator(
790
- this.wrap(prop.name),
791
- `!compareBuffers(last${this.wrap(prop.name)}, current${this.wrap(prop.name)})`,
792
- );
793
- }
794
- if (type === 'date') {
795
- return this.getGenericComparator(
796
- this.wrap(prop.name),
797
- `last${this.wrap(prop.name)}.valueOf() !== current${this.wrap(prop.name)}.valueOf()`,
798
- );
524
+ return convertorKey;
799
525
  }
800
- if (type === 'objectid') {
801
- // We might be comparing PK to object, in case we compare with cached data of populated entity
802
- // in such case we just ignore the comparison and fallback to `equals()` (which will still mark
803
- // it as not equal as we compare PK to plain object).
804
- const cond = `last${this.wrap(prop.name)}.toHexString?.() !== current${this.wrap(prop.name)}.toHexString?.()`;
805
- return this.getGenericComparator(this.wrap(prop.name), cond);
806
- }
807
- return this.getGenericComparator(
808
- this.wrap(prop.name),
809
- `!equals(last${this.wrap(prop.name)}, current${this.wrap(prop.name)})`,
810
- );
811
- }
812
- wrap(key) {
813
- if (/^\[.*]$/.exec(key)) {
814
- 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)}`;
529
+ if (prop.lazy && prop.ref) {
530
+ ret += ` && entity${path.map(k => this.wrap(k)).join('')}?.isInitialized()`;
531
+ }
532
+ ret += `) {\n`;
533
+ if (['number', 'string', 'boolean'].includes(prop.type.toLowerCase())) {
534
+ return ret + ` ret${dataKey} = entity${entityKey}${unwrap};\n }\n`;
535
+ }
536
+ if (prop.kind === ReferenceKind.EMBEDDED) {
537
+ if (prop.array) {
538
+ return this.getEmbeddedArrayPropertySnapshot(meta, prop, context, level, path, dataKey) + '\n';
539
+ }
540
+ return this.getEmbeddedPropertySnapshot(meta, prop, context, level, path, dataKey, object) + '\n';
541
+ }
542
+ if (prop.kind === ReferenceKind.ONE_TO_ONE || prop.kind === ReferenceKind.MANY_TO_ONE) {
543
+ if (prop.mapToPk) {
544
+ if (prop.customType) {
545
+ const convertorKey = this.registerCustomType(prop, context);
546
+ ret += ` ret${dataKey} = convertToDatabaseValue_${convertorKey}(entity${entityKey});\n`;
547
+ }
548
+ else {
549
+ ret += ` ret${dataKey} = entity${entityKey};\n`;
550
+ }
551
+ }
552
+ else if (prop.polymorphic) {
553
+ const discriminatorMapKey = `discriminatorMapReverse_${prop.name}`;
554
+ const reverseMap = new Map();
555
+ for (const [key, value] of Object.entries(prop.discriminatorMap)) {
556
+ reverseMap.set(value, key);
557
+ }
558
+ context.set(discriminatorMapKey, reverseMap);
559
+ this.setToArrayHelper(context);
560
+ context.set('EntityIdentifier', EntityIdentifier);
561
+ context.set('PolymorphicRef', PolymorphicRef);
562
+ ret += ` if (entity${entityKey} === null) {\n`;
563
+ ret += ` ret${dataKey} = null;\n`;
564
+ ret += ` } else if (typeof entity${entityKey} !== 'undefined') {\n`;
565
+ ret += ` const val${level} = entity${entityKey}${unwrap};\n`;
566
+ ret += ` const discriminator = ${discriminatorMapKey}.get(val${level}?.constructor);\n`;
567
+ ret += ` const pk = val${level}?.__helper?.__identifier && !val${level}?.__helper?.hasPrimaryKey()\n`;
568
+ ret += ` ? val${level}.__helper.__identifier\n`;
569
+ ret += ` : toArray(val${level}?.__helper?.getPrimaryKey(true));\n`;
570
+ ret += ` ret${dataKey} = new PolymorphicRef(discriminator, pk);\n`;
571
+ ret += ` }\n`;
572
+ }
573
+ else if (prop.targetKey) {
574
+ // When targetKey is set, extract that property value instead of the PK
575
+ const targetProp = prop.targetMeta?.properties[prop.targetKey];
576
+ ret += ` if (entity${entityKey} === null) {\n`;
577
+ ret += ` ret${dataKey} = null;\n`;
578
+ ret += ` } else if (typeof entity${entityKey} !== 'undefined') {\n`;
579
+ ret += ` const val${level} = entity${entityKey}${unwrap};\n`;
580
+ if (targetProp?.customType) {
581
+ // If targetKey property has a custom type, convert to database value
582
+ const convertorKey = this.registerCustomType(targetProp, context);
583
+ ret += ` ret${dataKey} = convertToDatabaseValue_${convertorKey}(val${level}?.${prop.targetKey});\n`;
584
+ }
585
+ else {
586
+ ret += ` ret${dataKey} = val${level}?.${prop.targetKey};\n`;
587
+ }
588
+ ret += ` }\n`;
589
+ }
590
+ else {
591
+ this.setToArrayHelper(context);
592
+ context.set('EntityIdentifier', EntityIdentifier);
593
+ ret += ` if (entity${entityKey} === null) {\n`;
594
+ ret += ` ret${dataKey} = null;\n`;
595
+ ret += ` } else if (entity${entityKey}?.__helper.__identifier && !entity${entityKey}.__helper.hasPrimaryKey()) {\n`;
596
+ ret += ` ret${dataKey} = entity${entityKey}?.__helper.__identifier;\n`;
597
+ ret += ` } else if (typeof entity${entityKey} !== 'undefined') {\n`;
598
+ ret += ` ret${dataKey} = toArray(entity${entityKey}.__helper.getPrimaryKey(true));\n`;
599
+ ret += ` }\n`;
600
+ }
601
+ return ret + ' }\n';
602
+ }
603
+ if (prop.customType) {
604
+ const convertorKey = this.registerCustomType(prop, context);
605
+ if (['number', 'string', 'boolean', 'bigint'].includes(prop.customType.compareAsType().toLowerCase())) {
606
+ return ret + ` ret${dataKey} = convertToDatabaseValue_${convertorKey}(entity${entityKey}${unwrap});\n }\n`;
607
+ }
608
+ return (ret + ` ret${dataKey} = clone(convertToDatabaseValue_${convertorKey}(entity${entityKey}${unwrap}));\n }\n`);
609
+ }
610
+ if (prop.runtimeType === 'Date') {
611
+ context.set('processDateProperty', this.#platform.processDateProperty.bind(this.#platform));
612
+ return ret + ` ret${dataKey} = clone(processDateProperty(entity${entityKey}${unwrap}));\n }\n`;
613
+ }
614
+ return ret + ` ret${dataKey} = clone(entity${entityKey}${unwrap});\n }\n`;
615
+ }
616
+ /**
617
+ * @internal Highly performance-sensitive method.
618
+ */
619
+ getEntityComparator(entityName) {
620
+ const meta = this.#metadata.find(entityName);
621
+ const exists = this.#comparators.get(meta);
622
+ if (exists) {
623
+ return exists;
624
+ }
625
+ const lines = [];
626
+ const context = new Map();
627
+ context.set('compareArrays', compareArrays);
628
+ context.set('compareBooleans', compareBooleans);
629
+ context.set('compareBuffers', compareBuffers);
630
+ context.set('compareObjects', compareObjects);
631
+ context.set('equals', equals);
632
+ for (const prop of meta.comparableProps) {
633
+ lines.push(this.getPropertyComparator(prop, context));
634
+ }
635
+ // also compare 1:1 inverse sides, important for `factory.mergeData`
636
+ lines.push(`if (options?.includeInverseSides) {`);
637
+ for (const prop of meta.bidirectionalRelations) {
638
+ if (prop.kind === ReferenceKind.ONE_TO_ONE && !prop.owner && prop.hydrate !== false) {
639
+ lines.push(this.getPropertyComparator(prop, context));
640
+ }
641
+ }
642
+ lines.push(`}`);
643
+ const code = `// compiled comparator for entity ${meta.className}\n` +
644
+ `return function(last, current, options) {\n const diff = {};\n${lines.join('\n')}\n return diff;\n}`;
645
+ const fnKey = `comparator-${meta.uniqueName}`;
646
+ const comparator = Utils.createFunction(context, code, this.#config?.get('compiledFunctions'), fnKey);
647
+ this.#comparators.set(meta, comparator);
648
+ return comparator;
649
+ }
650
+ getGenericComparator(prop, cond) {
651
+ return (` if (current${prop} === null && last${prop} === undefined) {\n` +
652
+ ` diff${prop} = current${prop};\n` +
653
+ ` } else if (current${prop} == null && last${prop} == null) {\n\n` +
654
+ ` } else if ((current${prop} != null && last${prop} == null) || (current${prop} == null && last${prop} != null)) {\n` +
655
+ ` diff${prop} = current${prop};\n` +
656
+ ` } else if (${cond}) {\n` +
657
+ ` diff${prop} = current${prop};\n` +
658
+ ` }\n`);
659
+ }
660
+ getPropertyComparator(prop, context) {
661
+ let type = prop.type.toLowerCase();
662
+ if (prop.kind !== ReferenceKind.SCALAR && prop.kind !== ReferenceKind.EMBEDDED) {
663
+ if (prop.polymorphic) {
664
+ type = 'object';
665
+ }
666
+ else {
667
+ const meta2 = prop.targetMeta;
668
+ if (meta2.primaryKeys.length > 1) {
669
+ type = 'array';
670
+ }
671
+ else {
672
+ type = meta2.getPrimaryProp().type.toLowerCase();
673
+ }
674
+ }
675
+ }
676
+ if (prop.customType) {
677
+ if (prop.customType.compareValues) {
678
+ const idx = this.#tmpIndex++;
679
+ context.set(`compareValues_${idx}`, (a, b) => {
680
+ if (Raw.isKnownFragment(a) || Raw.isKnownFragment(b)) {
681
+ return Raw.getKnownFragment(a) === Raw.getKnownFragment(b);
682
+ }
683
+ return prop.customType.compareValues(a, b);
684
+ });
685
+ return this.getGenericComparator(this.wrap(prop.name), `!compareValues_${idx}(last${this.wrap(prop.name)}, current${this.wrap(prop.name)})`);
686
+ }
687
+ type = prop.customType.compareAsType().toLowerCase();
688
+ }
689
+ if (type.endsWith('[]')) {
690
+ type = 'array';
691
+ }
692
+ if (['string', 'number', 'bigint'].includes(type)) {
693
+ return this.getGenericComparator(this.wrap(prop.name), `last${this.wrap(prop.name)} !== current${this.wrap(prop.name)}`);
694
+ }
695
+ if (type === 'boolean') {
696
+ return this.getGenericComparator(this.wrap(prop.name), `!compareBooleans(last${this.wrap(prop.name)}, current${this.wrap(prop.name)})`);
697
+ }
698
+ if (['array'].includes(type) || type.endsWith('[]')) {
699
+ return this.getGenericComparator(this.wrap(prop.name), `!compareArrays(last${this.wrap(prop.name)}, current${this.wrap(prop.name)})`);
700
+ }
701
+ if (['buffer', 'uint8array'].includes(type)) {
702
+ return this.getGenericComparator(this.wrap(prop.name), `!compareBuffers(last${this.wrap(prop.name)}, current${this.wrap(prop.name)})`);
703
+ }
704
+ if (type === 'date') {
705
+ return this.getGenericComparator(this.wrap(prop.name), `last${this.wrap(prop.name)}.valueOf() !== current${this.wrap(prop.name)}.valueOf()`);
706
+ }
707
+ if (type === 'objectid') {
708
+ // We might be comparing PK to object, in case we compare with cached data of populated entity
709
+ // in such case we just ignore the comparison and fallback to `equals()` (which will still mark
710
+ // it as not equal as we compare PK to plain object).
711
+ const cond = `last${this.wrap(prop.name)}.toHexString?.() !== current${this.wrap(prop.name)}.toHexString?.()`;
712
+ return this.getGenericComparator(this.wrap(prop.name), cond);
713
+ }
714
+ return this.getGenericComparator(this.wrap(prop.name), `!equals(last${this.wrap(prop.name)}, current${this.wrap(prop.name)})`);
815
715
  }
816
- return /^\w+$/.exec(key) ? `.${key}` : `['${key}']`;
817
- }
818
- safeKey(key) {
819
- return key.replace(/\W/g, '_');
820
- }
821
- /**
822
- * Sets the toArray helper in the context if not already set.
823
- * Used for converting composite PKs to arrays.
824
- */
825
- setToArrayHelper(context) {
826
- if (context.has('toArray')) {
827
- return;
716
+ wrap(key) {
717
+ if (/^\[.*]$/.exec(key)) {
718
+ return key;
719
+ }
720
+ return /^\w+$/.exec(key) ? `.${key}` : `['${key}']`;
721
+ }
722
+ safeKey(key) {
723
+ return key.replace(/\W/g, '_');
724
+ }
725
+ /**
726
+ * Sets the toArray helper in the context if not already set.
727
+ * Used for converting composite PKs to arrays.
728
+ */
729
+ setToArrayHelper(context) {
730
+ if (context.has('toArray')) {
731
+ return;
732
+ }
733
+ const toArray = (val) => {
734
+ if (Utils.isPlainObject(val)) {
735
+ return Object.values(val).map(v => toArray(v));
736
+ }
737
+ return val;
738
+ };
739
+ context.set('toArray', toArray);
740
+ }
741
+ /**
742
+ * perf: used to generate list of comparable properties during discovery, so we speed up the runtime comparison
743
+ */
744
+ static isComparable(prop, root) {
745
+ const virtual = prop.persist === false || (prop.generated && !prop.primary);
746
+ const inverse = prop.kind === ReferenceKind.ONE_TO_ONE && !prop.owner;
747
+ const discriminator = prop.name === root.discriminatorColumn;
748
+ const collection = prop.kind === ReferenceKind.ONE_TO_MANY || prop.kind === ReferenceKind.MANY_TO_MANY;
749
+ return !virtual && !collection && !inverse && !discriminator && !prop.version;
828
750
  }
829
- const toArray = val => {
830
- if (Utils.isPlainObject(val)) {
831
- return Object.values(val).map(v => toArray(v));
832
- }
833
- return val;
834
- };
835
- context.set('toArray', toArray);
836
- }
837
- /**
838
- * perf: used to generate list of comparable properties during discovery, so we speed up the runtime comparison
839
- */
840
- static isComparable(prop, root) {
841
- const virtual = prop.persist === false || (prop.generated && !prop.primary);
842
- const inverse = prop.kind === ReferenceKind.ONE_TO_ONE && !prop.owner;
843
- const discriminator = prop.name === root.discriminatorColumn;
844
- const collection = prop.kind === ReferenceKind.ONE_TO_MANY || prop.kind === ReferenceKind.MANY_TO_MANY;
845
- return !virtual && !collection && !inverse && !discriminator && !prop.version;
846
- }
847
751
  }