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