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

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