@mikro-orm/core 7.0.2-dev.8 → 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
package/utils/Utils.js CHANGED
@@ -3,843 +3,850 @@ import { GroupOperator, PlainObject, QueryOperator, ReferenceKind } from '../enu
3
3
  import { helper } from '../entity/wrap.js';
4
4
  import { Raw } from './RawQueryFragment.js';
5
5
  function compareConstructors(a, b) {
6
- if (a.constructor === b.constructor) {
7
- return true;
8
- }
9
- if (!a.constructor) {
10
- return b.constructor === Object;
11
- }
12
- if (!b.constructor) {
13
- return a.constructor === Object;
14
- }
15
- return false;
6
+ if (a.constructor === b.constructor) {
7
+ return true;
8
+ }
9
+ if (!a.constructor) {
10
+ return b.constructor === Object;
11
+ }
12
+ if (!b.constructor) {
13
+ return a.constructor === Object;
14
+ }
15
+ return false;
16
16
  }
17
+ /** Deeply compares two objects for equality, handling dates, regexes, and raw fragments. */
17
18
  export function compareObjects(a, b) {
18
- if (a === b || (a == null && b == null)) {
19
- return true;
20
- }
21
- if (!a || !b || typeof a !== 'object' || typeof b !== 'object' || !compareConstructors(a, b)) {
22
- return false;
23
- }
24
- if (a.__raw && b.__raw) {
25
- // eslint-disable-next-line @typescript-eslint/no-use-before-define
26
- return a.sql === b.sql && compareArrays(a.params, b.params);
27
- }
28
- if (a instanceof Date && b instanceof Date) {
29
- const timeA = a.getTime();
30
- const timeB = b.getTime();
31
- if (isNaN(timeA) || isNaN(timeB)) {
32
- throw new Error('Comparing invalid dates is not supported');
33
- }
34
- return timeA === timeB;
35
- }
36
- /* v8 ignore next */
37
- if ((typeof a === 'function' && typeof b === 'function') ||
38
- (a instanceof RegExp && b instanceof RegExp) ||
39
- (a instanceof String && b instanceof String) ||
40
- (a instanceof Number && b instanceof Number)) {
41
- return a.toString() === b.toString();
42
- }
43
- const keys = Object.keys(a);
44
- const length = keys.length;
45
- if (length !== Object.keys(b).length) {
46
- return false;
47
- }
48
- for (let i = length; i-- !== 0;) {
49
- if (!Object.hasOwn(b, keys[i])) {
50
- return false;
51
- }
52
- }
53
- for (let i = length; i-- !== 0;) {
54
- const key = keys[i];
55
- // eslint-disable-next-line @typescript-eslint/no-use-before-define
56
- if (!equals(a[key], b[key])) {
57
- return false;
58
- }
59
- }
19
+ if (a === b || (a == null && b == null)) {
60
20
  return true;
21
+ }
22
+ if (!a || !b || typeof a !== 'object' || typeof b !== 'object' || !compareConstructors(a, b)) {
23
+ return false;
24
+ }
25
+ if (a.__raw && b.__raw) {
26
+ // eslint-disable-next-line @typescript-eslint/no-use-before-define
27
+ return a.sql === b.sql && compareArrays(a.params, b.params);
28
+ }
29
+ if (a instanceof Date && b instanceof Date) {
30
+ const timeA = a.getTime();
31
+ const timeB = b.getTime();
32
+ if (isNaN(timeA) || isNaN(timeB)) {
33
+ throw new Error('Comparing invalid dates is not supported');
34
+ }
35
+ return timeA === timeB;
36
+ }
37
+ /* v8 ignore next */
38
+ if (
39
+ (typeof a === 'function' && typeof b === 'function') ||
40
+ (a instanceof RegExp && b instanceof RegExp) ||
41
+ (a instanceof String && b instanceof String) ||
42
+ (a instanceof Number && b instanceof Number)
43
+ ) {
44
+ return a.toString() === b.toString();
45
+ }
46
+ const keys = Object.keys(a);
47
+ const length = keys.length;
48
+ if (length !== Object.keys(b).length) {
49
+ return false;
50
+ }
51
+ for (let i = length; i-- !== 0; ) {
52
+ if (!Object.hasOwn(b, keys[i])) {
53
+ return false;
54
+ }
55
+ }
56
+ for (let i = length; i-- !== 0; ) {
57
+ const key = keys[i];
58
+ // eslint-disable-next-line @typescript-eslint/no-use-before-define
59
+ if (!equals(a[key], b[key])) {
60
+ return false;
61
+ }
62
+ }
63
+ return true;
61
64
  }
65
+ /** Compares two arrays element-by-element for deep equality. */
62
66
  export function compareArrays(a, b) {
63
- const length = a.length;
64
- if (length !== b.length) {
65
- return false;
66
- }
67
- for (let i = length; i-- !== 0;) {
68
- // eslint-disable-next-line @typescript-eslint/no-use-before-define
69
- if (!equals(a[i], b[i])) {
70
- return false;
71
- }
72
- }
73
- return true;
67
+ const length = a.length;
68
+ if (length !== b.length) {
69
+ return false;
70
+ }
71
+ for (let i = length; i-- !== 0; ) {
72
+ // eslint-disable-next-line @typescript-eslint/no-use-before-define
73
+ if (!equals(a[i], b[i])) {
74
+ return false;
75
+ }
76
+ }
77
+ return true;
74
78
  }
79
+ /** Compares two boolean values, treating numeric 0/1 as false/true. */
75
80
  export function compareBooleans(a, b) {
76
- a = typeof a === 'number' ? Boolean(a) : a;
77
- b = typeof b === 'number' ? Boolean(b) : b;
78
- return a === b;
81
+ a = typeof a === 'number' ? Boolean(a) : a;
82
+ b = typeof b === 'number' ? Boolean(b) : b;
83
+ return a === b;
79
84
  }
85
+ /** Compares two byte arrays element-by-element. */
80
86
  export function compareBuffers(a, b) {
81
- const length = a.length;
82
- if (length !== b.length) {
83
- return false;
84
- }
85
- for (let i = length; i-- !== 0;) {
86
- if (a[i] !== b[i]) {
87
- return false;
88
- }
87
+ const length = a.length;
88
+ if (length !== b.length) {
89
+ return false;
90
+ }
91
+ for (let i = length; i-- !== 0; ) {
92
+ if (a[i] !== b[i]) {
93
+ return false;
89
94
  }
90
- return true;
95
+ }
96
+ return true;
91
97
  }
92
98
  /**
93
99
  * Checks if arguments are deeply (but not strictly) equal.
94
100
  */
95
101
  export function equals(a, b) {
96
- if (a === b) {
97
- return true;
102
+ if (a === b) {
103
+ return true;
104
+ }
105
+ if (a && b && typeof a === 'object' && typeof b === 'object') {
106
+ if (Array.isArray(a)) {
107
+ return compareArrays(a, b);
98
108
  }
99
- if (a && b && typeof a === 'object' && typeof b === 'object') {
100
- if (Array.isArray(a)) {
101
- return compareArrays(a, b);
102
- }
103
- if (ArrayBuffer.isView(a) && ArrayBuffer.isView(b)) {
104
- return compareBuffers(a, b);
105
- }
106
- return compareObjects(a, b);
109
+ if (ArrayBuffer.isView(a) && ArrayBuffer.isView(b)) {
110
+ return compareBuffers(a, b);
107
111
  }
108
- return Number.isNaN(a) && Number.isNaN(b);
112
+ return compareObjects(a, b);
113
+ }
114
+ return Number.isNaN(a) && Number.isNaN(b);
109
115
  }
110
116
  const equalsFn = equals;
117
+ /** Parses a JSON string safely, returning the original value if parsing fails. */
111
118
  export function parseJsonSafe(value) {
112
- if (typeof value === 'string') {
113
- /* v8 ignore next */
114
- try {
115
- return JSON.parse(value);
116
- }
117
- catch {
118
- // ignore and return the value, as sometimes we get the parsed value,
119
- // e.g. when it is a string value in JSON column
120
- }
121
- }
122
- return value;
119
+ if (typeof value === 'string') {
120
+ /* v8 ignore next */
121
+ try {
122
+ return JSON.parse(value);
123
+ } catch {
124
+ // ignore and return the value, as sometimes we get the parsed value,
125
+ // e.g. when it is a string value in JSON column
126
+ }
127
+ }
128
+ return value;
123
129
  }
130
+ /** Collection of general-purpose utility methods used throughout the ORM. */
124
131
  export class Utils {
125
- static PK_SEPARATOR = '~~~';
126
- static #ORM_VERSION = '7.0.2-dev.8';
127
- /**
128
- * Checks if the argument is instance of `Object`. Returns false for arrays.
129
- */
130
- static isObject(o) {
131
- return !!o && typeof o === 'object' && !Array.isArray(o);
132
- }
133
- /**
134
- * Removes `undefined` properties (recursively) so they are not saved as nulls
135
- */
136
- static dropUndefinedProperties(o, value, visited = new Set()) {
137
- if (Array.isArray(o)) {
138
- for (const item of o) {
139
- Utils.dropUndefinedProperties(item, value, visited);
140
- }
141
- return;
142
- }
143
- if (!Utils.isPlainObject(o) || visited.has(o)) {
144
- return;
145
- }
146
- visited.add(o);
147
- for (const key of Object.keys(o)) {
148
- if (o[key] === value) {
149
- delete o[key];
150
- continue;
151
- }
152
- Utils.dropUndefinedProperties(o[key], value, visited);
153
- }
154
- }
155
- /**
156
- * Returns the number of properties on `obj`. This is 20x faster than Object.keys(obj).length.
157
- * @see https://github.com/deepkit/deepkit-framework/blob/master/packages/core/src/core.ts
158
- */
159
- static getObjectKeysSize(object) {
160
- let size = 0;
161
- for (const key in object) {
162
- if (Object.hasOwn(object, key)) {
163
- size++;
164
- }
165
- }
166
- return size;
167
- }
168
- /**
169
- * Returns true if `obj` has at least one property. This is 20x faster than Object.keys(obj).length.
170
- * @see https://github.com/deepkit/deepkit-framework/blob/master/packages/core/src/core.ts
171
- */
172
- static hasObjectKeys(object) {
173
- for (const key in object) {
174
- if (Object.hasOwn(object, key)) {
175
- return true;
176
- }
177
- }
178
- return false;
179
- }
180
- /**
181
- * Checks if arguments are deeply (but not strictly) equal.
182
- */
183
- static equals(a, b) {
184
- return equalsFn(a, b);
185
- }
186
- /**
187
- * Gets array without duplicates.
188
- */
189
- static unique(items) {
190
- if (items.length < 2) {
191
- return items;
192
- }
193
- return [...new Set(items)];
194
- }
195
- /**
196
- * Merges all sources into the target recursively.
197
- */
198
- static merge(target, ...sources) {
199
- return Utils._merge(target, sources, false);
200
- }
201
- /**
202
- * Merges all sources into the target recursively. Ignores `undefined` values.
203
- */
204
- static mergeConfig(target, ...sources) {
205
- return Utils._merge(target, sources, true);
206
- }
207
- /**
208
- * Merges all sources into the target recursively.
209
- */
210
- static _merge(target, sources, ignoreUndefined) {
211
- if (!sources.length) {
212
- return target;
213
- }
214
- const source = sources.shift();
215
- if (Utils.isObject(target) && Utils.isPlainObject(source)) {
216
- for (const [key, value] of Object.entries(source)) {
217
- if (ignoreUndefined && typeof value === 'undefined') {
218
- continue;
219
- }
220
- if (Utils.isPlainObject(value)) {
221
- if (!Utils.isObject(target[key])) {
222
- target[key] = Utils.copy(value);
223
- continue;
224
- }
225
- /* v8 ignore next */
226
- if (!(key in target)) {
227
- Object.assign(target, { [key]: {} });
228
- }
229
- Utils._merge(target[key], [value], ignoreUndefined);
230
- }
231
- else {
232
- Object.assign(target, { [key]: value });
233
- }
234
- }
235
- }
236
- return Utils._merge(target, sources, ignoreUndefined);
237
- }
238
- /**
239
- * Creates deep copy of given object.
240
- */
241
- static copy(entity, respectCustomCloneMethod = true) {
242
- return clone(entity, respectCustomCloneMethod);
243
- }
244
- /**
245
- * Normalize the argument to always be an array.
246
- */
247
- static asArray(data, strict = false) {
248
- if (typeof data === 'undefined' && !strict) {
249
- return [];
250
- }
251
- if (this.isIterable(data)) {
252
- return Array.from(data);
253
- }
254
- return [data];
255
- }
256
- /**
257
- * Checks if the value is iterable, but considers strings and buffers as not iterable.
258
- */
259
- static isIterable(value) {
260
- if (value == null || typeof value === 'string' || ArrayBuffer.isView(value)) {
261
- return false;
262
- }
263
- return typeof Object(value)[Symbol.iterator] === 'function';
264
- }
265
- /**
266
- * Renames object key, keeps order of properties.
267
- */
268
- static renameKey(payload, from, to) {
269
- if (Utils.isObject(payload) && from in payload && !(to in payload)) {
270
- for (const key of Object.keys(payload)) {
271
- const value = payload[key];
272
- delete payload[key];
273
- payload[from === key ? to : key] = value;
274
- }
275
- }
276
- }
277
- /**
278
- * Returns array of functions argument names. Uses basic regex for source code analysis, might not work with advanced syntax.
279
- */
280
- static getConstructorParams(func) {
281
- const source = func.toString();
282
- const i = source.indexOf('constructor');
283
- if (i === -1) {
284
- return undefined;
285
- }
286
- const start = source.indexOf('(', i);
287
- if (start === -1) {
288
- return undefined;
289
- }
290
- let depth = 0;
291
- let end = start;
292
- for (; end < source.length; end++) {
293
- if (source[end] === '(') {
294
- depth++;
295
- }
296
- if (source[end] === ')') {
297
- depth--;
298
- }
299
- if (depth === 0) {
300
- break;
301
- }
302
- }
303
- const raw = source.slice(start + 1, end);
304
- return raw
305
- .split(',')
306
- .map(s => s.trim().replace(/=.*$/, '').trim())
307
- .filter(Boolean)
308
- .map(raw => (raw.startsWith('{') && raw.endsWith('}') ? '' : raw));
309
- }
310
- /**
311
- * Checks whether the argument looks like primary key (string, number or ObjectId).
312
- */
313
- static isPrimaryKey(key, allowComposite = false) {
314
- if (['string', 'number', 'bigint'].includes(typeof key)) {
315
- return true;
316
- }
317
- if (allowComposite && Array.isArray(key) && key.every(v => Utils.isPrimaryKey(v, true))) {
318
- return true;
319
- }
320
- if (Utils.isObject(key)) {
321
- if (key.constructor?.name === 'ObjectId') {
322
- return true;
323
- }
324
- if (!Utils.isPlainObject(key) && !Utils.isEntity(key, true)) {
325
- return true;
326
- }
327
- }
328
- return false;
329
- }
330
- /**
331
- * Extracts primary key from `data`. Accepts objects or primary keys directly.
332
- */
333
- static extractPK(data, meta, strict = false) {
334
- if (Utils.isPrimaryKey(data)) {
335
- return data;
336
- }
337
- if (Utils.isEntity(data, true)) {
338
- const wrapped = helper(data);
339
- if (wrapped.__meta.compositePK) {
340
- return wrapped.getPrimaryKeys();
341
- }
342
- return wrapped.getPrimaryKey();
343
- }
344
- if (strict && meta && Utils.getObjectKeysSize(data) !== meta.primaryKeys.length) {
345
- return null;
346
- }
347
- if (Utils.isPlainObject(data) && meta) {
348
- if (meta.compositePK) {
349
- return this.getCompositeKeyValue(data, meta);
350
- }
351
- return data[meta.primaryKeys[0]] ?? data[meta.serializedPrimaryKey] ?? null;
352
- }
353
- return null;
354
- }
355
- static getCompositeKeyValue(data, meta, convertCustomTypes = false, platform) {
356
- return meta.primaryKeys.map((pk, idx) => {
357
- const value = Array.isArray(data) ? data[idx] : data[pk];
358
- const prop = meta.properties[pk];
359
- if (prop.targetMeta && Utils.isPlainObject(value)) {
360
- return this.getCompositeKeyValue(value, prop.targetMeta);
361
- }
362
- if (prop.customType && platform && convertCustomTypes) {
363
- const method = typeof convertCustomTypes === 'string' ? convertCustomTypes : 'convertToJSValue';
364
- return prop.customType[method](value, platform);
365
- }
366
- return value;
367
- });
368
- }
369
- static getCompositeKeyHash(data, meta, convertCustomTypes = false, platform, flat = false) {
370
- let pks = this.getCompositeKeyValue(data, meta, convertCustomTypes, platform);
371
- if (flat) {
372
- pks = Utils.flatten(pks);
373
- }
374
- return Utils.getPrimaryKeyHash(pks);
375
- }
376
- static getPrimaryKeyHash(pks) {
377
- return pks
378
- .map(pk => {
379
- if (Buffer.isBuffer(pk)) {
380
- return pk.toString('hex');
381
- }
382
- if (pk instanceof Date) {
383
- return pk.toISOString();
384
- }
385
- return pk;
386
- })
387
- .join(this.PK_SEPARATOR);
388
- }
389
- static splitPrimaryKeys(key) {
390
- return key.split(this.PK_SEPARATOR);
391
- }
392
- static getPrimaryKeyValues(entity, meta, allowScalar = false, convertCustomTypes = false) {
393
- /* v8 ignore next */
394
- if (entity == null) {
395
- return entity;
396
- }
397
- function toArray(val) {
398
- if (Utils.isPlainObject(val)) {
399
- return Object.values(val).flatMap(v => toArray(v));
400
- }
401
- return val;
402
- }
403
- let pk;
404
- if (Utils.isEntity(entity, true)) {
405
- pk = helper(entity).getPrimaryKey(convertCustomTypes);
406
- }
407
- else {
408
- pk = meta.primaryKeys.reduce((o, pk) => {
409
- const targetMeta = meta.properties[pk].targetMeta;
410
- if (targetMeta && Utils.isPlainObject(entity[pk])) {
411
- o[pk] = Utils.getPrimaryKeyValues(entity[pk], targetMeta, allowScalar, convertCustomTypes);
412
- }
413
- else {
414
- o[pk] = entity[pk];
415
- }
416
- return o;
417
- }, {});
418
- }
419
- if (meta.primaryKeys.length > 1) {
420
- return toArray(pk);
421
- }
422
- if (allowScalar) {
423
- if (Utils.isPlainObject(pk)) {
424
- return pk[meta.primaryKeys[0]];
425
- }
426
- return pk;
427
- }
428
- return [pk];
429
- }
430
- static getPrimaryKeyCond(entity, primaryKeys) {
431
- const cond = primaryKeys.reduce((o, pk) => {
432
- o[pk] = Utils.extractPK(entity[pk]);
433
- return o;
434
- }, {});
435
- if (Object.values(cond).some(v => v === null)) {
436
- return null;
437
- }
438
- return cond;
439
- }
440
- /**
441
- * Maps nested FKs from `[1, 2, 3]` to `[1, [2, 3]]`.
442
- */
443
- static mapFlatCompositePrimaryKey(fk, prop, fieldNames = prop.fieldNames, idx = 0) {
444
- if (!prop.targetMeta) {
445
- return fk[idx++];
446
- }
447
- const parts = [];
448
- for (const pk of prop.targetMeta.getPrimaryProps()) {
449
- parts.push(this.mapFlatCompositePrimaryKey(fk, pk, fieldNames, idx));
450
- idx += pk.fieldNames.length;
451
- }
452
- if (parts.length < 2) {
453
- return parts[0];
454
- }
455
- return parts;
456
- }
457
- static getPrimaryKeyCondFromArray(pks, meta) {
458
- return meta.getPrimaryProps().reduce((o, pk, idx) => {
459
- if (Array.isArray(pks[idx]) && pk.targetMeta) {
460
- o[pk.name] = pks[idx];
461
- }
462
- else {
463
- o[pk.name] = Utils.extractPK(pks[idx], meta);
464
- }
465
- return o;
466
- }, {});
467
- }
468
- static getOrderedPrimaryKeys(id, meta, platform, convertCustomTypes = false, allowScalar = false) {
469
- const data = (Utils.isPrimaryKey(id) ? { [meta.primaryKeys[0]]: id } : id);
470
- const pks = meta.primaryKeys.map((pk, idx) => {
471
- const prop = meta.properties[pk];
472
- // `data` can be a composite PK in form of array of PKs, or a DTO
473
- let value = Array.isArray(data) ? data[idx] : (data[pk] ?? data);
474
- if (convertCustomTypes && platform && prop.customType && !prop.targetMeta) {
475
- value = prop.customType.convertToJSValue(value, platform);
476
- }
477
- if (prop.kind !== ReferenceKind.SCALAR && prop.targetMeta) {
478
- const value2 = this.getOrderedPrimaryKeys(value, prop.targetMeta, platform, convertCustomTypes, allowScalar);
479
- value = value2.length > 1 ? value2 : value2[0];
480
- }
481
- return value;
482
- });
483
- if (allowScalar && pks.length === 1) {
484
- return pks[0];
485
- }
486
- // we need to flatten the PKs as composite PKs can be build from another composite PKs
487
- // and this method is used to get the PK hash in identity map, that expects flat array
488
- return Utils.flatten(pks);
489
- }
490
- /**
491
- * Checks whether given object is an entity instance.
492
- */
493
- static isEntity(data, allowReference = false) {
494
- if (!Utils.isObject(data)) {
495
- return false;
496
- }
497
- if (allowReference && !!data.__reference) {
498
- return true;
499
- }
500
- return !!data.__entity;
501
- }
502
- /**
503
- * Checks whether given object is a scalar reference.
504
- */
505
- static isScalarReference(data, allowReference = false) {
506
- return typeof data === 'object' && data?.__scalarReference;
507
- }
508
- /**
509
- * Checks whether the argument is empty (array without items, object without keys or falsy value).
510
- */
511
- static isEmpty(data) {
512
- if (Array.isArray(data)) {
513
- return data.length === 0;
514
- }
515
- if (Utils.isObject(data)) {
516
- return !Utils.hasObjectKeys(data);
517
- }
518
- return !data;
519
- }
520
- /**
521
- * Gets string name of given class.
522
- */
523
- static className(classOrName) {
524
- if (typeof classOrName === 'string') {
525
- return classOrName;
526
- }
527
- return classOrName.name;
528
- }
529
- static extractChildElements(items, prefix, allSymbol) {
530
- return items
531
- .filter(field => field === allSymbol || field.startsWith(`${prefix}.`))
532
- .map(field => (field === allSymbol ? allSymbol : field.substring(prefix.length + 1)));
533
- }
534
- /**
535
- * Tries to detect TypeScript support.
536
- */
537
- static detectTypeScriptSupport() {
538
- /* v8 ignore next */
539
- const process = globalThis.process ?? {};
540
- /* v8 ignore next */
541
- return (process.argv?.[0]?.endsWith('ts-node') || // running via ts-node directly
542
- !!process.env?.MIKRO_ORM_CLI_ALWAYS_ALLOW_TS || // forced explicitly or enabled via `registerTypeScriptSupport()`
543
- !!process.env?.TS_JEST || // check if ts-jest is used
544
- !!process.env?.VITEST || // check if vitest is used
545
- !!process.versions?.bun || // check if bun is used
546
- process.argv?.slice(1).some(arg => /\.([mc]?ts|tsx)$/.exec(arg)) || // executing `.ts` file
547
- process.execArgv?.some(arg => {
548
- return (arg.includes('ts-node') || // check for ts-node loader
549
- arg.includes('@swc-node/register') || // check for swc-node/register loader
550
- arg.includes('node_modules/tsx/')); // check for tsx loader
551
- }));
552
- }
553
- /**
554
- * Gets the type of the argument.
555
- */
556
- static getObjectType(value) {
557
- const simple = typeof value;
558
- if (['string', 'number', 'boolean', 'bigint'].includes(simple)) {
559
- return simple;
560
- }
561
- const objectType = Object.prototype.toString.call(value);
562
- const type = /^\[object (.+)]$/.exec(objectType)[1];
563
- if (type === 'Uint8Array') {
564
- return 'Buffer';
565
- }
566
- return type;
567
- }
568
- /**
569
- * Checks whether the value is POJO (e.g. `{ foo: 'bar' }`, and not instance of `Foo`)
570
- */
571
- static isPlainObject(value) {
572
- return ((value !== null &&
573
- typeof value === 'object' &&
574
- typeof value.constructor === 'function' &&
575
- (Object.hasOwn(value.constructor.prototype, 'isPrototypeOf') ||
576
- Object.getPrototypeOf(value.constructor.prototype) === null)) ||
577
- (value && Object.getPrototypeOf(value) === null) ||
578
- value instanceof PlainObject);
579
- }
580
- /**
581
- * Executes the `cb` promise serially on every element of the `items` array and returns array of resolved values.
582
- */
583
- static async runSerial(items, cb) {
584
- const ret = [];
585
- for (const item of items) {
586
- ret.push(await cb(item));
587
- }
588
- return ret;
589
- }
590
- static isCollection(item) {
591
- return item?.__collection;
592
- }
593
- // FNV-1a 64-bit
594
- static hash(data, length) {
595
- let h1 = 0xcbf29ce484222325n;
596
- for (let i = 0; i < data.length; i++) {
597
- h1 ^= BigInt(data.charCodeAt(i));
598
- h1 = (h1 * 0x100000001b3n) & 0xffffffffffffffffn;
599
- }
600
- const hash = h1.toString(16).padStart(16, '0');
601
- if (length) {
602
- return hash.substring(0, length);
603
- }
604
- return hash;
605
- }
606
- static runIfNotEmpty(clause, data) {
607
- if (!Utils.isEmpty(data)) {
608
- clause();
609
- }
610
- }
611
- static defaultValue(prop, option, defaultValue) {
612
- prop[option] = option in prop ? prop[option] : defaultValue;
613
- }
614
- static findDuplicates(items) {
615
- return items.reduce((acc, v, i, arr) => {
616
- return arr.indexOf(v) !== i && !acc.includes(v) ? acc.concat(v) : acc;
617
- }, []);
618
- }
619
- static removeDuplicates(items) {
620
- const ret = [];
621
- const contains = (arr, val) => !!arr.find(v => equals(val, v));
622
- for (const item of items) {
623
- if (!contains(ret, item)) {
624
- ret.push(item);
625
- }
626
- }
627
- return ret;
628
- }
629
- static randomInt(min, max) {
630
- return Math.round(Math.random() * (max - min)) + min;
631
- }
632
- /**
633
- * Extracts all possible values of a TS enum. Works with both string and numeric enums.
634
- */
635
- static extractEnumValues(target) {
636
- const keys = Object.keys(target);
637
- const values = Object.values(target);
638
- const numeric = !!values.find(v => typeof v === 'number');
639
- const constEnum = values.length % 2 === 0 && // const enum will have even number of items
640
- values.slice(0, values.length / 2).every(v => typeof v === 'string') && // first half are strings
641
- values.slice(values.length / 2).every(v => typeof v === 'number') && // second half are numbers
642
- this.equals(keys, values
643
- .slice(values.length / 2)
644
- .concat(values.slice(0, values.length / 2))
645
- .map(v => '' + v)); // and when swapped, it will match the keys
646
- if (numeric || constEnum) {
647
- return values.filter(val => !keys.includes(val));
648
- }
649
- return values;
132
+ static PK_SEPARATOR = '~~~';
133
+ static #ORM_VERSION = '7.0.2';
134
+ /**
135
+ * Checks if the argument is instance of `Object`. Returns false for arrays.
136
+ */
137
+ static isObject(o) {
138
+ return !!o && typeof o === 'object' && !Array.isArray(o);
139
+ }
140
+ /**
141
+ * Removes `undefined` properties (recursively) so they are not saved as nulls
142
+ */
143
+ static dropUndefinedProperties(o, value, visited = new Set()) {
144
+ if (Array.isArray(o)) {
145
+ for (const item of o) {
146
+ Utils.dropUndefinedProperties(item, value, visited);
147
+ }
148
+ return;
149
+ }
150
+ if (!Utils.isPlainObject(o) || visited.has(o)) {
151
+ return;
152
+ }
153
+ visited.add(o);
154
+ for (const key of Object.keys(o)) {
155
+ if (o[key] === value) {
156
+ delete o[key];
157
+ continue;
158
+ }
159
+ Utils.dropUndefinedProperties(o[key], value, visited);
160
+ }
161
+ }
162
+ /**
163
+ * Returns the number of properties on `obj`. This is 20x faster than Object.keys(obj).length.
164
+ * @see https://github.com/deepkit/deepkit-framework/blob/master/packages/core/src/core.ts
165
+ */
166
+ static getObjectKeysSize(object) {
167
+ let size = 0;
168
+ for (const key in object) {
169
+ if (Object.hasOwn(object, key)) {
170
+ size++;
171
+ }
172
+ }
173
+ return size;
174
+ }
175
+ /**
176
+ * Returns true if `obj` has at least one property. This is 20x faster than Object.keys(obj).length.
177
+ * @see https://github.com/deepkit/deepkit-framework/blob/master/packages/core/src/core.ts
178
+ */
179
+ static hasObjectKeys(object) {
180
+ for (const key in object) {
181
+ if (Object.hasOwn(object, key)) {
182
+ return true;
183
+ }
650
184
  }
651
- static flatten(arrays, deep) {
652
- return arrays.flatMap(v => (deep && Array.isArray(v) ? this.flatten(v, true) : v));
185
+ return false;
186
+ }
187
+ /**
188
+ * Checks if arguments are deeply (but not strictly) equal.
189
+ */
190
+ static equals(a, b) {
191
+ return equalsFn(a, b);
192
+ }
193
+ /**
194
+ * Gets array without duplicates.
195
+ */
196
+ static unique(items) {
197
+ if (items.length < 2) {
198
+ return items;
199
+ }
200
+ return [...new Set(items)];
201
+ }
202
+ /**
203
+ * Merges all sources into the target recursively.
204
+ */
205
+ static merge(target, ...sources) {
206
+ return Utils._merge(target, sources, false);
207
+ }
208
+ /**
209
+ * Merges all sources into the target recursively. Ignores `undefined` values.
210
+ */
211
+ static mergeConfig(target, ...sources) {
212
+ return Utils._merge(target, sources, true);
213
+ }
214
+ /**
215
+ * Merges all sources into the target recursively.
216
+ */
217
+ static _merge(target, sources, ignoreUndefined) {
218
+ if (!sources.length) {
219
+ return target;
220
+ }
221
+ const source = sources.shift();
222
+ if (Utils.isObject(target) && Utils.isPlainObject(source)) {
223
+ for (const [key, value] of Object.entries(source)) {
224
+ if (ignoreUndefined && typeof value === 'undefined') {
225
+ continue;
226
+ }
227
+ if (Utils.isPlainObject(value)) {
228
+ if (!Utils.isObject(target[key])) {
229
+ target[key] = Utils.copy(value);
230
+ continue;
231
+ }
232
+ /* v8 ignore next */
233
+ if (!(key in target)) {
234
+ Object.assign(target, { [key]: {} });
235
+ }
236
+ Utils._merge(target[key], [value], ignoreUndefined);
237
+ } else {
238
+ Object.assign(target, { [key]: value });
239
+ }
240
+ }
241
+ }
242
+ return Utils._merge(target, sources, ignoreUndefined);
243
+ }
244
+ /**
245
+ * Creates deep copy of given object.
246
+ */
247
+ static copy(entity, respectCustomCloneMethod = true) {
248
+ return clone(entity, respectCustomCloneMethod);
249
+ }
250
+ /**
251
+ * Normalize the argument to always be an array.
252
+ */
253
+ static asArray(data, strict = false) {
254
+ if (typeof data === 'undefined' && !strict) {
255
+ return [];
256
+ }
257
+ if (this.isIterable(data)) {
258
+ return Array.from(data);
259
+ }
260
+ return [data];
261
+ }
262
+ /**
263
+ * Checks if the value is iterable, but considers strings and buffers as not iterable.
264
+ */
265
+ static isIterable(value) {
266
+ if (value == null || typeof value === 'string' || ArrayBuffer.isView(value)) {
267
+ return false;
268
+ }
269
+ return typeof Object(value)[Symbol.iterator] === 'function';
270
+ }
271
+ /**
272
+ * Renames object key, keeps order of properties.
273
+ */
274
+ static renameKey(payload, from, to) {
275
+ if (Utils.isObject(payload) && from in payload && !(to in payload)) {
276
+ for (const key of Object.keys(payload)) {
277
+ const value = payload[key];
278
+ delete payload[key];
279
+ payload[from === key ? to : key] = value;
280
+ }
281
+ }
282
+ }
283
+ /**
284
+ * Returns array of functions argument names. Uses basic regex for source code analysis, might not work with advanced syntax.
285
+ */
286
+ static getConstructorParams(func) {
287
+ const source = func.toString();
288
+ const i = source.indexOf('constructor');
289
+ if (i === -1) {
290
+ return undefined;
291
+ }
292
+ const start = source.indexOf('(', i);
293
+ if (start === -1) {
294
+ return undefined;
295
+ }
296
+ let depth = 0;
297
+ let end = start;
298
+ for (; end < source.length; end++) {
299
+ if (source[end] === '(') {
300
+ depth++;
301
+ }
302
+ if (source[end] === ')') {
303
+ depth--;
304
+ }
305
+ if (depth === 0) {
306
+ break;
307
+ }
308
+ }
309
+ const raw = source.slice(start + 1, end);
310
+ return raw
311
+ .split(',')
312
+ .map(s => s.trim().replace(/=.*$/, '').trim())
313
+ .filter(Boolean)
314
+ .map(raw => (raw.startsWith('{') && raw.endsWith('}') ? '' : raw));
315
+ }
316
+ /**
317
+ * Checks whether the argument looks like primary key (string, number or ObjectId).
318
+ */
319
+ static isPrimaryKey(key, allowComposite = false) {
320
+ if (['string', 'number', 'bigint'].includes(typeof key)) {
321
+ return true;
322
+ }
323
+ if (allowComposite && Array.isArray(key) && key.every(v => Utils.isPrimaryKey(v, true))) {
324
+ return true;
325
+ }
326
+ if (Utils.isObject(key)) {
327
+ if (key.constructor?.name === 'ObjectId') {
328
+ return true;
329
+ }
330
+ if (!Utils.isPlainObject(key) && !Utils.isEntity(key, true)) {
331
+ return true;
332
+ }
653
333
  }
654
- static isOperator(key, includeGroupOperators = true) {
655
- if (!includeGroupOperators) {
656
- return key in QueryOperator;
657
- }
658
- return key in GroupOperator || key in QueryOperator;
334
+ return false;
335
+ }
336
+ /**
337
+ * Extracts primary key from `data`. Accepts objects or primary keys directly.
338
+ */
339
+ static extractPK(data, meta, strict = false) {
340
+ if (Utils.isPrimaryKey(data)) {
341
+ return data;
342
+ }
343
+ if (Utils.isEntity(data, true)) {
344
+ const wrapped = helper(data);
345
+ if (wrapped.__meta.compositePK) {
346
+ return wrapped.getPrimaryKeys();
347
+ }
348
+ return wrapped.getPrimaryKey();
349
+ }
350
+ if (strict && meta && Utils.getObjectKeysSize(data) !== meta.primaryKeys.length) {
351
+ return null;
352
+ }
353
+ if (Utils.isPlainObject(data) && meta) {
354
+ if (meta.compositePK) {
355
+ return this.getCompositeKeyValue(data, meta);
356
+ }
357
+ return data[meta.primaryKeys[0]] ?? data[meta.serializedPrimaryKey] ?? null;
358
+ }
359
+ return null;
360
+ }
361
+ static getCompositeKeyValue(data, meta, convertCustomTypes = false, platform) {
362
+ return meta.primaryKeys.map((pk, idx) => {
363
+ const value = Array.isArray(data) ? data[idx] : data[pk];
364
+ const prop = meta.properties[pk];
365
+ if (prop.targetMeta && Utils.isPlainObject(value)) {
366
+ return this.getCompositeKeyValue(value, prop.targetMeta);
367
+ }
368
+ if (prop.customType && platform && convertCustomTypes) {
369
+ const method = typeof convertCustomTypes === 'string' ? convertCustomTypes : 'convertToJSValue';
370
+ return prop.customType[method](value, platform);
371
+ }
372
+ return value;
373
+ });
374
+ }
375
+ static getCompositeKeyHash(data, meta, convertCustomTypes = false, platform, flat = false) {
376
+ let pks = this.getCompositeKeyValue(data, meta, convertCustomTypes, platform);
377
+ if (flat) {
378
+ pks = Utils.flatten(pks);
379
+ }
380
+ return Utils.getPrimaryKeyHash(pks);
381
+ }
382
+ static getPrimaryKeyHash(pks) {
383
+ return pks
384
+ .map(pk => {
385
+ if (Buffer.isBuffer(pk)) {
386
+ return pk.toString('hex');
387
+ }
388
+ if (pk instanceof Date) {
389
+ return pk.toISOString();
390
+ }
391
+ return pk;
392
+ })
393
+ .join(this.PK_SEPARATOR);
394
+ }
395
+ static splitPrimaryKeys(key) {
396
+ return key.split(this.PK_SEPARATOR);
397
+ }
398
+ static getPrimaryKeyValues(entity, meta, allowScalar = false, convertCustomTypes = false) {
399
+ /* v8 ignore next */
400
+ if (entity == null) {
401
+ return entity;
402
+ }
403
+ function toArray(val) {
404
+ if (Utils.isPlainObject(val)) {
405
+ return Object.values(val).flatMap(v => toArray(v));
406
+ }
407
+ return val;
408
+ }
409
+ let pk;
410
+ if (Utils.isEntity(entity, true)) {
411
+ pk = helper(entity).getPrimaryKey(convertCustomTypes);
412
+ } else {
413
+ pk = meta.primaryKeys.reduce((o, pk) => {
414
+ const targetMeta = meta.properties[pk].targetMeta;
415
+ if (targetMeta && Utils.isPlainObject(entity[pk])) {
416
+ o[pk] = Utils.getPrimaryKeyValues(entity[pk], targetMeta, allowScalar, convertCustomTypes);
417
+ } else {
418
+ o[pk] = entity[pk];
419
+ }
420
+ return o;
421
+ }, {});
422
+ }
423
+ if (meta.primaryKeys.length > 1) {
424
+ return toArray(pk);
425
+ }
426
+ if (allowScalar) {
427
+ if (Utils.isPlainObject(pk)) {
428
+ return pk[meta.primaryKeys[0]];
429
+ }
430
+ return pk;
431
+ }
432
+ return [pk];
433
+ }
434
+ static getPrimaryKeyCond(entity, primaryKeys) {
435
+ const cond = primaryKeys.reduce((o, pk) => {
436
+ o[pk] = Utils.extractPK(entity[pk]);
437
+ return o;
438
+ }, {});
439
+ if (Object.values(cond).some(v => v === null)) {
440
+ return null;
441
+ }
442
+ return cond;
443
+ }
444
+ /**
445
+ * Maps nested FKs from `[1, 2, 3]` to `[1, [2, 3]]`.
446
+ */
447
+ static mapFlatCompositePrimaryKey(fk, prop, fieldNames = prop.fieldNames, idx = 0) {
448
+ if (!prop.targetMeta) {
449
+ return fk[idx++];
450
+ }
451
+ const parts = [];
452
+ for (const pk of prop.targetMeta.getPrimaryProps()) {
453
+ parts.push(this.mapFlatCompositePrimaryKey(fk, pk, fieldNames, idx));
454
+ idx += pk.fieldNames.length;
455
+ }
456
+ if (parts.length < 2) {
457
+ return parts[0];
458
+ }
459
+ return parts;
460
+ }
461
+ static getPrimaryKeyCondFromArray(pks, meta) {
462
+ return meta.getPrimaryProps().reduce((o, pk, idx) => {
463
+ if (Array.isArray(pks[idx]) && pk.targetMeta) {
464
+ o[pk.name] = pks[idx];
465
+ } else {
466
+ o[pk.name] = Utils.extractPK(pks[idx], meta);
467
+ }
468
+ return o;
469
+ }, {});
470
+ }
471
+ static getOrderedPrimaryKeys(id, meta, platform, convertCustomTypes = false, allowScalar = false) {
472
+ const data = Utils.isPrimaryKey(id) ? { [meta.primaryKeys[0]]: id } : id;
473
+ const pks = meta.primaryKeys.map((pk, idx) => {
474
+ const prop = meta.properties[pk];
475
+ // `data` can be a composite PK in form of array of PKs, or a DTO
476
+ let value = Array.isArray(data) ? data[idx] : (data[pk] ?? data);
477
+ if (convertCustomTypes && platform && prop.customType && !prop.targetMeta) {
478
+ value = prop.customType.convertToJSValue(value, platform);
479
+ }
480
+ if (prop.kind !== ReferenceKind.SCALAR && prop.targetMeta) {
481
+ const value2 = this.getOrderedPrimaryKeys(value, prop.targetMeta, platform, convertCustomTypes, allowScalar);
482
+ value = value2.length > 1 ? value2 : value2[0];
483
+ }
484
+ return value;
485
+ });
486
+ if (allowScalar && pks.length === 1) {
487
+ return pks[0];
488
+ }
489
+ // we need to flatten the PKs as composite PKs can be build from another composite PKs
490
+ // and this method is used to get the PK hash in identity map, that expects flat array
491
+ return Utils.flatten(pks);
492
+ }
493
+ /**
494
+ * Checks whether given object is an entity instance.
495
+ */
496
+ static isEntity(data, allowReference = false) {
497
+ if (!Utils.isObject(data)) {
498
+ return false;
499
+ }
500
+ if (allowReference && !!data.__reference) {
501
+ return true;
502
+ }
503
+ return !!data.__entity;
504
+ }
505
+ /**
506
+ * Checks whether given object is a scalar reference.
507
+ */
508
+ static isScalarReference(data, allowReference = false) {
509
+ return typeof data === 'object' && data?.__scalarReference;
510
+ }
511
+ /**
512
+ * Checks whether the argument is empty (array without items, object without keys or falsy value).
513
+ */
514
+ static isEmpty(data) {
515
+ if (Array.isArray(data)) {
516
+ return data.length === 0;
517
+ }
518
+ if (Utils.isObject(data)) {
519
+ return !Utils.hasObjectKeys(data);
520
+ }
521
+ return !data;
522
+ }
523
+ /**
524
+ * Gets string name of given class.
525
+ */
526
+ static className(classOrName) {
527
+ if (typeof classOrName === 'string') {
528
+ return classOrName;
529
+ }
530
+ return classOrName.name;
531
+ }
532
+ static extractChildElements(items, prefix, allSymbol) {
533
+ return items
534
+ .filter(field => field === allSymbol || field.startsWith(`${prefix}.`))
535
+ .map(field => (field === allSymbol ? allSymbol : field.substring(prefix.length + 1)));
536
+ }
537
+ /**
538
+ * Tries to detect TypeScript support.
539
+ */
540
+ static detectTypeScriptSupport() {
541
+ /* v8 ignore next */
542
+ const process = globalThis.process ?? {};
543
+ /* v8 ignore next */
544
+ return (
545
+ process.argv?.[0]?.endsWith('ts-node') || // running via ts-node directly
546
+ !!process.env?.MIKRO_ORM_CLI_ALWAYS_ALLOW_TS || // forced explicitly or enabled via `registerTypeScriptSupport()`
547
+ !!process.env?.TS_JEST || // check if ts-jest is used
548
+ !!process.env?.VITEST || // check if vitest is used
549
+ !!process.versions?.bun || // check if bun is used
550
+ process.argv?.slice(1).some(arg => /\.([mc]?ts|tsx)$/.exec(arg)) || // executing `.ts` file
551
+ process.execArgv?.some(arg => {
552
+ return (
553
+ arg.includes('ts-node') || // check for ts-node loader
554
+ arg.includes('@swc-node/register') || // check for swc-node/register loader
555
+ arg.includes('node_modules/tsx/')
556
+ ); // check for tsx loader
557
+ })
558
+ );
559
+ }
560
+ /**
561
+ * Gets the type of the argument.
562
+ */
563
+ static getObjectType(value) {
564
+ const simple = typeof value;
565
+ if (['string', 'number', 'boolean', 'bigint'].includes(simple)) {
566
+ return simple;
567
+ }
568
+ const objectType = Object.prototype.toString.call(value);
569
+ const type = /^\[object (.+)]$/.exec(objectType)[1];
570
+ if (type === 'Uint8Array') {
571
+ return 'Buffer';
572
+ }
573
+ return type;
574
+ }
575
+ /**
576
+ * Checks whether the value is POJO (e.g. `{ foo: 'bar' }`, and not instance of `Foo`)
577
+ */
578
+ static isPlainObject(value) {
579
+ return (
580
+ (value !== null &&
581
+ typeof value === 'object' &&
582
+ typeof value.constructor === 'function' &&
583
+ (Object.hasOwn(value.constructor.prototype, 'isPrototypeOf') ||
584
+ Object.getPrototypeOf(value.constructor.prototype) === null)) ||
585
+ (value && Object.getPrototypeOf(value) === null) ||
586
+ value instanceof PlainObject
587
+ );
588
+ }
589
+ /**
590
+ * Executes the `cb` promise serially on every element of the `items` array and returns array of resolved values.
591
+ */
592
+ static async runSerial(items, cb) {
593
+ const ret = [];
594
+ for (const item of items) {
595
+ ret.push(await cb(item));
596
+ }
597
+ return ret;
598
+ }
599
+ static isCollection(item) {
600
+ return item?.__collection;
601
+ }
602
+ // FNV-1a 64-bit
603
+ static hash(data, length) {
604
+ let h1 = 0xcbf29ce484222325n;
605
+ for (let i = 0; i < data.length; i++) {
606
+ h1 ^= BigInt(data.charCodeAt(i));
607
+ h1 = (h1 * 0x100000001b3n) & 0xffffffffffffffffn;
608
+ }
609
+ const hash = h1.toString(16).padStart(16, '0');
610
+ if (length) {
611
+ return hash.substring(0, length);
612
+ }
613
+ return hash;
614
+ }
615
+ static runIfNotEmpty(clause, data) {
616
+ if (!Utils.isEmpty(data)) {
617
+ clause();
618
+ }
619
+ }
620
+ static defaultValue(prop, option, defaultValue) {
621
+ prop[option] = option in prop ? prop[option] : defaultValue;
622
+ }
623
+ static findDuplicates(items) {
624
+ return items.reduce((acc, v, i, arr) => {
625
+ return arr.indexOf(v) !== i && !acc.includes(v) ? acc.concat(v) : acc;
626
+ }, []);
627
+ }
628
+ static removeDuplicates(items) {
629
+ const ret = [];
630
+ const contains = (arr, val) => !!arr.find(v => equals(val, v));
631
+ for (const item of items) {
632
+ if (!contains(ret, item)) {
633
+ ret.push(item);
634
+ }
635
+ }
636
+ return ret;
637
+ }
638
+ static randomInt(min, max) {
639
+ return Math.round(Math.random() * (max - min)) + min;
640
+ }
641
+ /**
642
+ * Extracts all possible values of a TS enum. Works with both string and numeric enums.
643
+ */
644
+ static extractEnumValues(target) {
645
+ const keys = Object.keys(target);
646
+ const values = Object.values(target);
647
+ const numeric = !!values.find(v => typeof v === 'number');
648
+ const constEnum =
649
+ values.length % 2 === 0 && // const enum will have even number of items
650
+ values.slice(0, values.length / 2).every(v => typeof v === 'string') && // first half are strings
651
+ values.slice(values.length / 2).every(v => typeof v === 'number') && // second half are numbers
652
+ this.equals(
653
+ keys,
654
+ values
655
+ .slice(values.length / 2)
656
+ .concat(values.slice(0, values.length / 2))
657
+ .map(v => '' + v),
658
+ ); // and when swapped, it will match the keys
659
+ if (numeric || constEnum) {
660
+ return values.filter(val => !keys.includes(val));
661
+ }
662
+ return values;
663
+ }
664
+ static flatten(arrays, deep) {
665
+ return arrays.flatMap(v => (deep && Array.isArray(v) ? this.flatten(v, true) : v));
666
+ }
667
+ static isOperator(key, includeGroupOperators = true) {
668
+ if (!includeGroupOperators) {
669
+ return key in QueryOperator;
670
+ }
671
+ return key in GroupOperator || key in QueryOperator;
672
+ }
673
+ static hasNestedKey(object, key) {
674
+ if (!object) {
675
+ return false;
676
+ }
677
+ if (Array.isArray(object)) {
678
+ return object.some(o => this.hasNestedKey(o, key));
679
+ }
680
+ if (typeof object === 'object') {
681
+ return Object.entries(object).some(([k, v]) => k === key || this.hasNestedKey(v, key));
659
682
  }
660
- static hasNestedKey(object, key) {
661
- if (!object) {
662
- return false;
663
- }
664
- if (Array.isArray(object)) {
665
- return object.some(o => this.hasNestedKey(o, key));
666
- }
667
- if (typeof object === 'object') {
668
- return Object.entries(object).some(([k, v]) => k === key || this.hasNestedKey(v, key));
669
- }
683
+ return false;
684
+ }
685
+ static getORMVersion() {
686
+ return this.#ORM_VERSION;
687
+ }
688
+ static createFunction(context, code, compiledFunctions, key) {
689
+ if (key && compiledFunctions?.[key]) {
690
+ return compiledFunctions[key](...context.values());
691
+ }
692
+ try {
693
+ // eslint-disable-next-line @typescript-eslint/no-implied-eval
694
+ return new Function(...context.keys(), `'use strict';\n` + code)(...context.values());
695
+ /* v8 ignore next */
696
+ } catch (e) {
697
+ // eslint-disable-next-line no-console
698
+ console.error(code);
699
+ throw e;
700
+ }
701
+ }
702
+ static callCompiledFunction(fn, ...args) {
703
+ try {
704
+ return fn(...args);
705
+ } catch (e) {
706
+ /* v8 ignore next */
707
+ if ([SyntaxError, TypeError, EvalError, ReferenceError].some(t => e instanceof t)) {
708
+ const position = e.stack.match(/<anonymous>:(\d+):(\d+)/);
709
+ let code = fn.toString();
710
+ if (position) {
711
+ const lines = code.split('\n').map((line, idx) => {
712
+ if (idx === +position[1] - 5) {
713
+ return '> ' + line;
714
+ }
715
+ return ' ' + line;
716
+ });
717
+ lines.splice(+position[1] - 4, 0, ' '.repeat(+position[2]) + '^');
718
+ code = lines.join('\n');
719
+ }
720
+ // eslint-disable-next-line no-console
721
+ console.error(`JIT runtime error: ${e.message}\n\n${code}`);
722
+ }
723
+ throw e;
724
+ }
725
+ }
726
+ static unwrapProperty(entity, meta, prop, payload = false) {
727
+ let p = prop;
728
+ const path = [];
729
+ if (!prop.object && !prop.array && !prop.embedded) {
730
+ return entity[prop.name] != null ? [[entity[prop.name], []]] : [];
731
+ }
732
+ while (p.embedded) {
733
+ const child = meta.properties[p.embedded[0]];
734
+ if (payload && !child.object && !child.array) {
735
+ break;
736
+ }
737
+ path.shift();
738
+ path.unshift(p.embedded[0], p.embedded[1]);
739
+ p = child;
740
+ }
741
+ const ret = [];
742
+ const follow = (t, idx = 0, i = []) => {
743
+ const k = path[idx];
744
+ if (Array.isArray(t)) {
745
+ for (const t1 of t) {
746
+ const ii = t.indexOf(t1);
747
+ follow(t1, idx, [...i, ii]);
748
+ }
749
+ return;
750
+ }
751
+ if (t == null) {
752
+ return;
753
+ }
754
+ const target = t[k];
755
+ if (path[++idx]) {
756
+ follow(target, idx, i);
757
+ } else if (target != null) {
758
+ ret.push([target, i]);
759
+ }
760
+ };
761
+ follow(entity);
762
+ return ret;
763
+ }
764
+ static setPayloadProperty(entity, meta, prop, value, idx) {
765
+ if (!prop.object && !prop.array && !prop.embedded) {
766
+ entity[prop.name] = value;
767
+ return;
768
+ }
769
+ let target = entity;
770
+ let p = prop;
771
+ const path = [];
772
+ while (p.embedded) {
773
+ path.shift();
774
+ path.unshift(p.embedded[0], p.embedded[1]);
775
+ const prev = p;
776
+ p = meta.properties[p.embedded[0]];
777
+ if (!p.object) {
778
+ path.shift();
779
+ path[0] = prev.name;
780
+ break;
781
+ }
782
+ }
783
+ let j = 0;
784
+ for (const k of path) {
785
+ const i = path.indexOf(k);
786
+ if (i === path.length - 1) {
787
+ if (Array.isArray(target)) {
788
+ target[idx[j++]][k] = value;
789
+ } else {
790
+ target[k] = value;
791
+ }
792
+ } else {
793
+ if (Array.isArray(target)) {
794
+ target = target[idx[j++]][k];
795
+ } else {
796
+ target = target[k];
797
+ }
798
+ }
799
+ }
800
+ }
801
+ static async tryImport({ module, warning }) {
802
+ try {
803
+ return await import(module);
804
+ } catch (err) {
805
+ if (err.code === 'ERR_MODULE_NOT_FOUND') {
806
+ if (warning) {
807
+ // eslint-disable-next-line no-console
808
+ console.warn(warning);
809
+ }
810
+ return undefined;
811
+ }
812
+ throw err;
813
+ }
814
+ }
815
+ static xor(a, b) {
816
+ return (a || b) && !(a && b);
817
+ }
818
+ static keys(obj) {
819
+ return Object.keys(obj);
820
+ }
821
+ static values(obj) {
822
+ return Object.values(obj);
823
+ }
824
+ static entries(obj) {
825
+ return Object.entries(obj);
826
+ }
827
+ static primaryKeyToObject(meta, primaryKey, visible) {
828
+ const pks =
829
+ meta.compositePK && Utils.isPlainObject(primaryKey) ? Object.values(primaryKey) : Utils.asArray(primaryKey);
830
+ const pkProps = meta.getPrimaryProps();
831
+ return meta.primaryKeys.reduce((o, pk, idx) => {
832
+ const pkProp = pkProps[idx];
833
+ if (visible && !visible.includes(pkProp.name)) {
834
+ return o;
835
+ }
836
+ if (Utils.isPlainObject(pks[idx]) && pkProp.targetMeta) {
837
+ o[pk] = Utils.getOrderedPrimaryKeys(pks[idx], pkProp.targetMeta);
838
+ return o;
839
+ }
840
+ o[pk] = pks[idx];
841
+ return o;
842
+ }, {});
843
+ }
844
+ static getObjectQueryKeys(obj) {
845
+ return Reflect.ownKeys(obj).filter(key => {
846
+ if (!Object.prototype.propertyIsEnumerable.call(obj, key)) {
670
847
  return false;
671
- }
672
- static getORMVersion() {
673
- return this.#ORM_VERSION;
674
- }
675
- static createFunction(context, code, compiledFunctions, key) {
676
- if (key && compiledFunctions?.[key]) {
677
- return compiledFunctions[key](...context.values());
678
- }
679
- try {
680
- // eslint-disable-next-line @typescript-eslint/no-implied-eval
681
- return new Function(...context.keys(), `'use strict';\n` + code)(...context.values());
682
- /* v8 ignore next */
683
- }
684
- catch (e) {
685
- // eslint-disable-next-line no-console
686
- console.error(code);
687
- throw e;
688
- }
689
- }
690
- static callCompiledFunction(fn, ...args) {
691
- try {
692
- return fn(...args);
693
- }
694
- catch (e) {
695
- /* v8 ignore next */
696
- if ([SyntaxError, TypeError, EvalError, ReferenceError].some(t => e instanceof t)) {
697
- const position = e.stack.match(/<anonymous>:(\d+):(\d+)/);
698
- let code = fn.toString();
699
- if (position) {
700
- const lines = code.split('\n').map((line, idx) => {
701
- if (idx === +position[1] - 5) {
702
- return '> ' + line;
703
- }
704
- return ' ' + line;
705
- });
706
- lines.splice(+position[1] - 4, 0, ' '.repeat(+position[2]) + '^');
707
- code = lines.join('\n');
708
- }
709
- // eslint-disable-next-line no-console
710
- console.error(`JIT runtime error: ${e.message}\n\n${code}`);
711
- }
712
- throw e;
713
- }
714
- }
715
- static unwrapProperty(entity, meta, prop, payload = false) {
716
- let p = prop;
717
- const path = [];
718
- if (!prop.object && !prop.array && !prop.embedded) {
719
- return entity[prop.name] != null ? [[entity[prop.name], []]] : [];
720
- }
721
- while (p.embedded) {
722
- const child = meta.properties[p.embedded[0]];
723
- if (payload && !child.object && !child.array) {
724
- break;
725
- }
726
- path.shift();
727
- path.unshift(p.embedded[0], p.embedded[1]);
728
- p = child;
729
- }
730
- const ret = [];
731
- const follow = (t, idx = 0, i = []) => {
732
- const k = path[idx];
733
- if (Array.isArray(t)) {
734
- for (const t1 of t) {
735
- const ii = t.indexOf(t1);
736
- follow(t1, idx, [...i, ii]);
737
- }
738
- return;
739
- }
740
- if (t == null) {
741
- return;
742
- }
743
- const target = t[k];
744
- if (path[++idx]) {
745
- follow(target, idx, i);
746
- }
747
- else if (target != null) {
748
- ret.push([target, i]);
749
- }
750
- };
751
- follow(entity);
752
- return ret;
753
- }
754
- static setPayloadProperty(entity, meta, prop, value, idx) {
755
- if (!prop.object && !prop.array && !prop.embedded) {
756
- entity[prop.name] = value;
757
- return;
758
- }
759
- let target = entity;
760
- let p = prop;
761
- const path = [];
762
- while (p.embedded) {
763
- path.shift();
764
- path.unshift(p.embedded[0], p.embedded[1]);
765
- const prev = p;
766
- p = meta.properties[p.embedded[0]];
767
- if (!p.object) {
768
- path.shift();
769
- path[0] = prev.name;
770
- break;
771
- }
772
- }
773
- let j = 0;
774
- for (const k of path) {
775
- const i = path.indexOf(k);
776
- if (i === path.length - 1) {
777
- if (Array.isArray(target)) {
778
- target[idx[j++]][k] = value;
779
- }
780
- else {
781
- target[k] = value;
782
- }
783
- }
784
- else {
785
- if (Array.isArray(target)) {
786
- target = target[idx[j++]][k];
787
- }
788
- else {
789
- target = target[k];
790
- }
791
- }
792
- }
793
- }
794
- static async tryImport({ module, warning, }) {
795
- try {
796
- return await import(module);
797
- }
798
- catch (err) {
799
- if (err.code === 'ERR_MODULE_NOT_FOUND') {
800
- if (warning) {
801
- // eslint-disable-next-line no-console
802
- console.warn(warning);
803
- }
804
- return undefined;
805
- }
806
- throw err;
807
- }
808
- }
809
- static xor(a, b) {
810
- return (a || b) && !(a && b);
811
- }
812
- static keys(obj) {
813
- return Object.keys(obj);
814
- }
815
- static values(obj) {
816
- return Object.values(obj);
817
- }
818
- static entries(obj) {
819
- return Object.entries(obj);
820
- }
821
- static primaryKeyToObject(meta, primaryKey, visible) {
822
- const pks = meta.compositePK && Utils.isPlainObject(primaryKey) ? Object.values(primaryKey) : Utils.asArray(primaryKey);
823
- const pkProps = meta.getPrimaryProps();
824
- return meta.primaryKeys.reduce((o, pk, idx) => {
825
- const pkProp = pkProps[idx];
826
- if (visible && !visible.includes(pkProp.name)) {
827
- return o;
828
- }
829
- if (Utils.isPlainObject(pks[idx]) && pkProp.targetMeta) {
830
- o[pk] = Utils.getOrderedPrimaryKeys(pks[idx], pkProp.targetMeta);
831
- return o;
832
- }
833
- o[pk] = pks[idx];
834
- return o;
835
- }, {});
836
- }
837
- static getObjectQueryKeys(obj) {
838
- return Reflect.ownKeys(obj).filter(key => {
839
- if (!Object.prototype.propertyIsEnumerable.call(obj, key)) {
840
- return false;
841
- }
842
- return typeof key === 'string' || Raw.isKnownFragmentSymbol(key);
843
- });
844
- }
848
+ }
849
+ return typeof key === 'string' || Raw.isKnownFragmentSymbol(key);
850
+ });
851
+ }
845
852
  }