@mikro-orm/core 7.0.4-dev.8 → 7.0.4
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.
- package/EntityManager.d.ts +884 -583
- package/EntityManager.js +1922 -1895
- package/MikroORM.d.ts +103 -74
- package/MikroORM.js +178 -179
- package/README.md +1 -1
- package/cache/CacheAdapter.d.ts +36 -36
- package/cache/FileCacheAdapter.d.ts +30 -24
- package/cache/FileCacheAdapter.js +80 -78
- package/cache/GeneratedCacheAdapter.d.ts +18 -20
- package/cache/GeneratedCacheAdapter.js +30 -30
- package/cache/MemoryCacheAdapter.d.ts +18 -20
- package/cache/MemoryCacheAdapter.js +35 -36
- package/cache/NullCacheAdapter.d.ts +16 -16
- package/cache/NullCacheAdapter.js +24 -24
- package/connections/Connection.d.ts +95 -84
- package/connections/Connection.js +165 -168
- package/drivers/DatabaseDriver.d.ts +186 -80
- package/drivers/DatabaseDriver.js +450 -443
- package/drivers/IDatabaseDriver.d.ts +440 -301
- package/entity/BaseEntity.d.ts +120 -83
- package/entity/BaseEntity.js +43 -43
- package/entity/Collection.d.ts +212 -179
- package/entity/Collection.js +727 -721
- package/entity/EntityAssigner.d.ts +88 -77
- package/entity/EntityAssigner.js +231 -230
- package/entity/EntityFactory.d.ts +66 -54
- package/entity/EntityFactory.js +425 -383
- package/entity/EntityHelper.d.ts +34 -22
- package/entity/EntityHelper.js +280 -267
- package/entity/EntityIdentifier.d.ts +4 -4
- package/entity/EntityIdentifier.js +10 -10
- package/entity/EntityLoader.d.ts +98 -72
- package/entity/EntityLoader.js +753 -723
- package/entity/EntityRepository.d.ts +316 -201
- package/entity/EntityRepository.js +213 -213
- package/entity/PolymorphicRef.d.ts +5 -5
- package/entity/PolymorphicRef.js +10 -10
- package/entity/Reference.d.ts +126 -82
- package/entity/Reference.js +278 -274
- package/entity/WrappedEntity.d.ts +115 -72
- package/entity/WrappedEntity.js +168 -166
- package/entity/defineEntity.d.ts +1315 -636
- package/entity/defineEntity.js +527 -518
- package/entity/utils.d.ts +13 -3
- package/entity/utils.js +71 -73
- package/entity/validators.js +43 -43
- package/entity/wrap.js +8 -8
- package/enums.d.ts +258 -253
- package/enums.js +251 -252
- package/errors.d.ts +114 -72
- package/errors.js +350 -253
- package/events/EventManager.d.ts +26 -14
- package/events/EventManager.js +79 -77
- package/events/EventSubscriber.d.ts +29 -29
- package/events/TransactionEventBroadcaster.d.ts +15 -8
- package/events/TransactionEventBroadcaster.js +14 -14
- package/exceptions.d.ts +23 -40
- package/exceptions.js +35 -52
- package/hydration/Hydrator.d.ts +42 -17
- package/hydration/Hydrator.js +43 -43
- package/hydration/ObjectHydrator.d.ts +50 -17
- package/hydration/ObjectHydrator.js +481 -416
- package/index.d.ts +116 -2
- package/index.js +10 -1
- package/logging/DefaultLogger.d.ts +34 -32
- package/logging/DefaultLogger.js +86 -86
- package/logging/Logger.d.ts +41 -41
- package/logging/SimpleLogger.d.ts +13 -11
- package/logging/SimpleLogger.js +22 -22
- package/logging/colors.d.ts +6 -6
- package/logging/colors.js +11 -10
- package/logging/inspect.js +7 -7
- package/metadata/EntitySchema.d.ts +211 -127
- package/metadata/EntitySchema.js +397 -398
- package/metadata/MetadataDiscovery.d.ts +114 -114
- package/metadata/MetadataDiscovery.js +1951 -1863
- package/metadata/MetadataProvider.d.ts +24 -21
- package/metadata/MetadataProvider.js +82 -84
- package/metadata/MetadataStorage.d.ts +38 -32
- package/metadata/MetadataStorage.js +118 -118
- package/metadata/MetadataValidator.d.ts +39 -39
- package/metadata/MetadataValidator.js +381 -338
- package/metadata/discover-entities.d.ts +5 -2
- package/metadata/discover-entities.js +35 -27
- package/metadata/types.d.ts +615 -531
- package/naming-strategy/AbstractNamingStrategy.d.ts +54 -39
- package/naming-strategy/AbstractNamingStrategy.js +90 -85
- package/naming-strategy/EntityCaseNamingStrategy.d.ts +6 -6
- package/naming-strategy/EntityCaseNamingStrategy.js +22 -22
- package/naming-strategy/MongoNamingStrategy.d.ts +6 -6
- package/naming-strategy/MongoNamingStrategy.js +18 -18
- package/naming-strategy/NamingStrategy.d.ts +109 -99
- package/naming-strategy/UnderscoreNamingStrategy.d.ts +7 -7
- package/naming-strategy/UnderscoreNamingStrategy.js +21 -21
- package/not-supported.js +7 -4
- package/package.json +1 -1
- package/platforms/ExceptionConverter.d.ts +1 -1
- package/platforms/ExceptionConverter.js +4 -4
- package/platforms/Platform.d.ts +310 -299
- package/platforms/Platform.js +663 -636
- package/serialization/EntitySerializer.d.ts +49 -26
- package/serialization/EntitySerializer.js +224 -218
- package/serialization/EntityTransformer.d.ts +10 -6
- package/serialization/EntityTransformer.js +219 -217
- package/serialization/SerializationContext.d.ts +27 -23
- package/serialization/SerializationContext.js +105 -105
- package/types/ArrayType.d.ts +8 -8
- package/types/ArrayType.js +33 -33
- package/types/BigIntType.d.ts +17 -10
- package/types/BigIntType.js +37 -37
- package/types/BlobType.d.ts +3 -3
- package/types/BlobType.js +13 -13
- package/types/BooleanType.d.ts +4 -4
- package/types/BooleanType.js +12 -12
- package/types/CharacterType.d.ts +2 -2
- package/types/CharacterType.js +6 -6
- package/types/DateTimeType.d.ts +5 -5
- package/types/DateTimeType.js +15 -15
- package/types/DateType.d.ts +5 -5
- package/types/DateType.js +15 -15
- package/types/DecimalType.d.ts +7 -7
- package/types/DecimalType.js +26 -26
- package/types/DoubleType.d.ts +3 -3
- package/types/DoubleType.js +12 -12
- package/types/EnumArrayType.d.ts +5 -5
- package/types/EnumArrayType.js +24 -24
- package/types/EnumType.d.ts +3 -3
- package/types/EnumType.js +11 -11
- package/types/FloatType.d.ts +3 -3
- package/types/FloatType.js +9 -9
- package/types/IntegerType.d.ts +3 -3
- package/types/IntegerType.js +9 -9
- package/types/IntervalType.d.ts +4 -4
- package/types/IntervalType.js +12 -12
- package/types/JsonType.d.ts +8 -8
- package/types/JsonType.js +32 -32
- package/types/MediumIntType.d.ts +1 -1
- package/types/MediumIntType.js +3 -3
- package/types/SmallIntType.d.ts +3 -3
- package/types/SmallIntType.js +9 -9
- package/types/StringType.d.ts +4 -4
- package/types/StringType.js +12 -12
- package/types/TextType.d.ts +3 -3
- package/types/TextType.js +9 -9
- package/types/TimeType.d.ts +5 -5
- package/types/TimeType.js +17 -17
- package/types/TinyIntType.d.ts +3 -3
- package/types/TinyIntType.js +10 -10
- package/types/Type.d.ts +83 -79
- package/types/Type.js +82 -82
- package/types/Uint8ArrayType.d.ts +4 -4
- package/types/Uint8ArrayType.js +21 -21
- package/types/UnknownType.d.ts +4 -4
- package/types/UnknownType.js +12 -12
- package/types/UuidType.d.ts +5 -5
- package/types/UuidType.js +19 -19
- package/types/index.d.ts +75 -49
- package/types/index.js +52 -26
- package/typings.d.ts +1250 -737
- package/typings.js +244 -231
- package/unit-of-work/ChangeSet.d.ts +26 -26
- package/unit-of-work/ChangeSet.js +56 -56
- package/unit-of-work/ChangeSetComputer.d.ts +12 -12
- package/unit-of-work/ChangeSetComputer.js +178 -170
- package/unit-of-work/ChangeSetPersister.d.ts +63 -44
- package/unit-of-work/ChangeSetPersister.js +442 -421
- package/unit-of-work/CommitOrderCalculator.d.ts +40 -40
- package/unit-of-work/CommitOrderCalculator.js +89 -88
- package/unit-of-work/IdentityMap.d.ts +31 -31
- package/unit-of-work/IdentityMap.js +105 -105
- package/unit-of-work/UnitOfWork.d.ts +181 -141
- package/unit-of-work/UnitOfWork.js +1200 -1183
- package/utils/AbstractMigrator.d.ts +111 -91
- package/utils/AbstractMigrator.js +275 -275
- package/utils/AbstractSchemaGenerator.d.ts +43 -34
- package/utils/AbstractSchemaGenerator.js +121 -122
- package/utils/AsyncContext.d.ts +3 -3
- package/utils/AsyncContext.js +34 -35
- package/utils/Configuration.d.ts +852 -808
- package/utils/Configuration.js +359 -344
- package/utils/Cursor.d.ts +40 -22
- package/utils/Cursor.js +135 -127
- package/utils/DataloaderUtils.d.ts +58 -43
- package/utils/DataloaderUtils.js +203 -198
- package/utils/EntityComparator.d.ts +98 -81
- package/utils/EntityComparator.js +828 -728
- package/utils/NullHighlighter.d.ts +1 -1
- package/utils/NullHighlighter.js +3 -3
- package/utils/QueryHelper.d.ts +79 -51
- package/utils/QueryHelper.js +372 -361
- package/utils/RawQueryFragment.d.ts +50 -34
- package/utils/RawQueryFragment.js +107 -105
- package/utils/RequestContext.d.ts +32 -32
- package/utils/RequestContext.js +52 -53
- package/utils/TransactionContext.d.ts +16 -16
- package/utils/TransactionContext.js +27 -27
- package/utils/TransactionManager.d.ts +58 -58
- package/utils/TransactionManager.js +199 -197
- package/utils/Utils.d.ts +204 -145
- package/utils/Utils.js +812 -810
- package/utils/clone.js +104 -113
- package/utils/env-vars.js +90 -88
- package/utils/fs-utils.d.ts +15 -15
- package/utils/fs-utils.js +180 -181
- package/utils/upsert-utils.d.ts +20 -5
- package/utils/upsert-utils.js +114 -116
package/EntityManager.js
CHANGED
|
@@ -12,7 +12,17 @@ import { Reference } from './entity/Reference.js';
|
|
|
12
12
|
import { helper } from './entity/wrap.js';
|
|
13
13
|
import { ChangeSet, ChangeSetType } from './unit-of-work/ChangeSet.js';
|
|
14
14
|
import { UnitOfWork } from './unit-of-work/UnitOfWork.js';
|
|
15
|
-
import {
|
|
15
|
+
import {
|
|
16
|
+
EventType,
|
|
17
|
+
FlushMode,
|
|
18
|
+
LoadStrategy,
|
|
19
|
+
LockMode,
|
|
20
|
+
PopulateHint,
|
|
21
|
+
PopulatePath,
|
|
22
|
+
QueryFlag,
|
|
23
|
+
ReferenceKind,
|
|
24
|
+
SCALAR_TYPES,
|
|
25
|
+
} from './enums.js';
|
|
16
26
|
import { EventManager } from './events/EventManager.js';
|
|
17
27
|
import { TransactionEventBroadcaster } from './events/TransactionEventBroadcaster.js';
|
|
18
28
|
import { OptimisticLockError, ValidationError } from './errors.js';
|
|
@@ -24,1911 +34,1928 @@ import { TransactionManager } from './utils/TransactionManager.js';
|
|
|
24
34
|
* @template {IDatabaseDriver} Driver current driver type
|
|
25
35
|
*/
|
|
26
36
|
export class EntityManager {
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
}
|
|
430
|
-
const strategy = getLoadingStrategy(prop.strategy || hint.strategy || options.strategy || this.config.get('loadStrategy'), prop.kind);
|
|
431
|
-
if (hint.field === `${prop.name}:ref` || (hint.filter && strategy === LoadStrategy.JOINED)) {
|
|
432
|
-
found = true;
|
|
433
|
-
}
|
|
434
|
-
}
|
|
435
|
-
if (!found) {
|
|
436
|
-
ret.push({ field: `${prop.name}:ref`, strategy: LoadStrategy.JOINED, filter: true });
|
|
437
|
-
}
|
|
438
|
-
}
|
|
439
|
-
}
|
|
440
|
-
for (const hint of ret) {
|
|
441
|
-
const [field, ref] = hint.field.split(':');
|
|
442
|
-
const prop = meta?.properties[field];
|
|
443
|
-
if (prop && !ref) {
|
|
444
|
-
hint.children ??= [];
|
|
445
|
-
await this.autoJoinRefsForFilters(prop.targetMeta, { ...options, populate: hint.children }, { class: meta.root.class, propName: prop.name });
|
|
446
|
-
}
|
|
447
|
-
}
|
|
448
|
-
}
|
|
449
|
-
/**
|
|
450
|
-
* @internal
|
|
451
|
-
*/
|
|
452
|
-
async applyFilters(entityName, where, options, type, findOptions) {
|
|
453
|
-
const meta = this.metadata.get(entityName);
|
|
454
|
-
const filters = [];
|
|
455
|
-
const ret = [];
|
|
456
|
-
const active = new Set();
|
|
457
|
-
const push = (source) => {
|
|
458
|
-
const activeFilters = QueryHelper.getActiveFilters(meta, options, source).filter(f => !active.has(f.name));
|
|
459
|
-
filters.push(...activeFilters);
|
|
460
|
-
activeFilters.forEach(f => active.add(f.name));
|
|
461
|
-
};
|
|
462
|
-
push(this.config.get('filters'));
|
|
463
|
-
push(this.#filters);
|
|
464
|
-
push(meta.filters);
|
|
465
|
-
if (filters.length === 0) {
|
|
466
|
-
return where;
|
|
467
|
-
}
|
|
468
|
-
for (const filter of filters) {
|
|
469
|
-
let cond;
|
|
470
|
-
if (filter.cond instanceof Function) {
|
|
471
|
-
// @ts-ignore
|
|
472
|
-
// oxfmt-ignore
|
|
473
|
-
const args = Utils.isPlainObject(options?.[filter.name]) ? options[filter.name] : this.getContext().#filterParams[filter.name];
|
|
474
|
-
if (!args && filter.cond.length > 0 && filter.args !== false) {
|
|
475
|
-
throw new Error(`No arguments provided for filter '${filter.name}'`);
|
|
476
|
-
}
|
|
477
|
-
cond = await filter.cond(args, type, this, findOptions, Utils.className(entityName));
|
|
478
|
-
}
|
|
479
|
-
else {
|
|
480
|
-
cond = filter.cond;
|
|
481
|
-
}
|
|
482
|
-
cond = QueryHelper.processWhere({
|
|
483
|
-
where: cond,
|
|
484
|
-
entityName,
|
|
485
|
-
metadata: this.metadata,
|
|
486
|
-
platform: this.driver.getPlatform(),
|
|
487
|
-
aliased: type === 'read',
|
|
488
|
-
});
|
|
489
|
-
if (filter.strict) {
|
|
490
|
-
Object.defineProperty(cond, '__strict', { value: filter.strict, enumerable: false });
|
|
491
|
-
}
|
|
492
|
-
ret.push(cond);
|
|
493
|
-
}
|
|
494
|
-
const conds = [...ret, where].filter(c => Utils.hasObjectKeys(c) || Raw.hasObjectFragments(c));
|
|
495
|
-
return conds.length > 1 ? { $and: conds } : conds[0];
|
|
496
|
-
}
|
|
497
|
-
/**
|
|
498
|
-
* Calls `em.find()` and `em.count()` with the same arguments (where applicable) and returns the results as tuple
|
|
499
|
-
* where the first element is the array of entities, and the second is the count.
|
|
500
|
-
*/
|
|
501
|
-
async findAndCount(entityName, where, options = {}) {
|
|
502
|
-
const em = this.getContext(false);
|
|
503
|
-
await em.tryFlush(entityName, options);
|
|
504
|
-
options.flushMode = 'commit'; // do not try to auto flush again
|
|
505
|
-
return Promise.all([
|
|
506
|
-
em.find(entityName, where, options),
|
|
507
|
-
em.count(entityName, where, options),
|
|
508
|
-
]);
|
|
509
|
-
}
|
|
510
|
-
/**
|
|
511
|
-
* Calls `em.find()` and `em.count()` with the same arguments (where applicable) and returns the results as {@apilink Cursor} object.
|
|
512
|
-
* Supports `before`, `after`, `first` and `last` options while disallowing `limit` and `offset`. Explicit `orderBy` option
|
|
513
|
-
* is required.
|
|
514
|
-
*
|
|
515
|
-
* Use `first` and `after` for forward pagination, or `last` and `before` for backward pagination.
|
|
516
|
-
*
|
|
517
|
-
* - `first` and `last` are numbers and serve as an alternative to `offset`, those options are mutually exclusive, use only one at a time
|
|
518
|
-
* - `before` and `after` specify the previous cursor value, it can be one of the:
|
|
519
|
-
* - `Cursor` instance
|
|
520
|
-
* - opaque string provided by `startCursor/endCursor` properties
|
|
521
|
-
* - POJO/entity instance
|
|
522
|
-
*
|
|
523
|
-
* ```ts
|
|
524
|
-
* const currentCursor = await em.findByCursor(User, {
|
|
525
|
-
* first: 10,
|
|
526
|
-
* after: previousCursor, // cursor instance
|
|
527
|
-
* orderBy: { id: 'desc' },
|
|
528
|
-
* });
|
|
529
|
-
*
|
|
530
|
-
* // to fetch next page
|
|
531
|
-
* const nextCursor = await em.findByCursor(User, {
|
|
532
|
-
* first: 10,
|
|
533
|
-
* after: currentCursor.endCursor, // opaque string
|
|
534
|
-
* orderBy: { id: 'desc' },
|
|
535
|
-
* });
|
|
536
|
-
*
|
|
537
|
-
* // to fetch next page
|
|
538
|
-
* const nextCursor2 = await em.findByCursor(User, {
|
|
539
|
-
* first: 10,
|
|
540
|
-
* after: { id: lastSeenId }, // entity-like POJO
|
|
541
|
-
* orderBy: { id: 'desc' },
|
|
542
|
-
* });
|
|
543
|
-
* ```
|
|
544
|
-
*
|
|
545
|
-
* The options also support an `includeCount` (true by default) option. If set to false, the `totalCount` is not
|
|
546
|
-
* returned as part of the cursor. This is useful for performance reason, when you don't care about the total number
|
|
547
|
-
* of pages.
|
|
548
|
-
*
|
|
549
|
-
* The `Cursor` object provides the following interface:
|
|
550
|
-
*
|
|
551
|
-
* ```ts
|
|
552
|
-
* Cursor<User> {
|
|
553
|
-
* items: [
|
|
554
|
-
* User { ... },
|
|
555
|
-
* User { ... },
|
|
556
|
-
* User { ... },
|
|
557
|
-
* ],
|
|
558
|
-
* totalCount: 50, // not included if `includeCount: false`
|
|
559
|
-
* startCursor: 'WzRd',
|
|
560
|
-
* endCursor: 'WzZd',
|
|
561
|
-
* hasPrevPage: true,
|
|
562
|
-
* hasNextPage: true,
|
|
563
|
-
* }
|
|
564
|
-
* ```
|
|
565
|
-
*/
|
|
566
|
-
async findByCursor(entityName, options) {
|
|
567
|
-
const em = this.getContext(false);
|
|
568
|
-
options.overfetch ??= true;
|
|
569
|
-
options.where ??= {};
|
|
570
|
-
if (Utils.isEmpty(options.orderBy) && !Raw.hasObjectFragments(options.orderBy)) {
|
|
571
|
-
throw new Error('Explicit `orderBy` option required');
|
|
572
|
-
}
|
|
573
|
-
const [entities, count] = options.includeCount !== false
|
|
574
|
-
? await em.findAndCount(entityName, options.where, options)
|
|
575
|
-
: [await em.find(entityName, options.where, options)];
|
|
576
|
-
return new Cursor(entities, count, options, this.metadata.get(entityName));
|
|
577
|
-
}
|
|
578
|
-
/**
|
|
579
|
-
* Refreshes the persistent state of an entity from the database, overriding any local changes that have not yet been
|
|
580
|
-
* persisted. Returns the same entity instance (same object reference), but re-hydrated. If the entity is no longer
|
|
581
|
-
* in database, the method throws an error just like `em.findOneOrFail()` (and respects the same config options).
|
|
582
|
-
*/
|
|
583
|
-
async refreshOrFail(entity, options = {}) {
|
|
584
|
-
const ret = await this.refresh(entity, options);
|
|
585
|
-
if (!ret) {
|
|
586
|
-
options.failHandler ??= this.config.get('findOneOrFailHandler');
|
|
587
|
-
const wrapped = helper(entity);
|
|
588
|
-
const where = wrapped.getPrimaryKey();
|
|
589
|
-
throw options.failHandler(wrapped.__meta.className, where);
|
|
590
|
-
}
|
|
591
|
-
return ret;
|
|
592
|
-
}
|
|
593
|
-
/**
|
|
594
|
-
* Refreshes the persistent state of an entity from the database, overriding any local changes that have not yet been
|
|
595
|
-
* persisted. Returns the same entity instance (same object reference), but re-hydrated. If the entity is no longer
|
|
596
|
-
* in database, the method returns `null`.
|
|
597
|
-
*/
|
|
598
|
-
async refresh(entity, options = {}) {
|
|
599
|
-
const fork = this.fork({ keepTransactionContext: true });
|
|
600
|
-
const wrapped = helper(entity);
|
|
601
|
-
const reloaded = await fork.findOne(wrapped.__meta.class, entity, {
|
|
602
|
-
schema: wrapped.__schema,
|
|
603
|
-
...options,
|
|
604
|
-
flushMode: FlushMode.COMMIT,
|
|
605
|
-
});
|
|
606
|
-
const em = this.getContext();
|
|
607
|
-
if (!reloaded) {
|
|
608
|
-
em.#unitOfWork.unsetIdentity(entity);
|
|
609
|
-
return null;
|
|
610
|
-
}
|
|
37
|
+
config;
|
|
38
|
+
driver;
|
|
39
|
+
metadata;
|
|
40
|
+
eventManager;
|
|
41
|
+
static #counter = 1;
|
|
42
|
+
/** @internal */
|
|
43
|
+
_id = EntityManager.#counter++;
|
|
44
|
+
/** Whether this is the global (root) EntityManager instance. */
|
|
45
|
+
global = false;
|
|
46
|
+
/** The context name of this EntityManager, derived from the ORM configuration. */
|
|
47
|
+
name;
|
|
48
|
+
#loaders = {};
|
|
49
|
+
#repositoryMap = new Map();
|
|
50
|
+
#entityLoader;
|
|
51
|
+
#comparator;
|
|
52
|
+
#entityFactory;
|
|
53
|
+
#unitOfWork;
|
|
54
|
+
#resultCache;
|
|
55
|
+
#filters = {};
|
|
56
|
+
#filterParams = {};
|
|
57
|
+
loggerContext;
|
|
58
|
+
#transactionContext;
|
|
59
|
+
#disableTransactions;
|
|
60
|
+
#flushMode;
|
|
61
|
+
#schema;
|
|
62
|
+
#useContext;
|
|
63
|
+
/**
|
|
64
|
+
* @internal
|
|
65
|
+
*/
|
|
66
|
+
constructor(config, driver, metadata, useContext = true, eventManager = new EventManager(config.get('subscribers'))) {
|
|
67
|
+
this.config = config;
|
|
68
|
+
this.driver = driver;
|
|
69
|
+
this.metadata = metadata;
|
|
70
|
+
this.eventManager = eventManager;
|
|
71
|
+
this.#useContext = useContext;
|
|
72
|
+
this.#entityLoader = new EntityLoader(this);
|
|
73
|
+
this.name = this.config.get('contextName');
|
|
74
|
+
this.#comparator = this.config.getComparator(this.metadata);
|
|
75
|
+
this.#resultCache = this.config.getResultCacheAdapter();
|
|
76
|
+
this.#disableTransactions = this.config.get('disableTransactions');
|
|
77
|
+
this.#entityFactory = new EntityFactory(this);
|
|
78
|
+
this.#unitOfWork = new UnitOfWork(this);
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Gets the Driver instance used by this EntityManager.
|
|
82
|
+
* Driver is singleton, for one MikroORM instance, only one driver is created.
|
|
83
|
+
*/
|
|
84
|
+
getDriver() {
|
|
85
|
+
return this.driver;
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Gets the Connection instance, by default returns write connection
|
|
89
|
+
*/
|
|
90
|
+
getConnection(type) {
|
|
91
|
+
return this.driver.getConnection(type);
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Gets the platform instance. Just like the driver, platform is singleton, one for a MikroORM instance.
|
|
95
|
+
*/
|
|
96
|
+
getPlatform() {
|
|
97
|
+
return this.driver.getPlatform();
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Gets repository for given entity. You can pass either string name or entity class reference.
|
|
101
|
+
*/
|
|
102
|
+
getRepository(entityName) {
|
|
103
|
+
const meta = this.metadata.get(entityName);
|
|
104
|
+
if (!this.#repositoryMap.has(meta)) {
|
|
105
|
+
const RepositoryClass = this.config.getRepositoryClass(meta.repository);
|
|
106
|
+
this.#repositoryMap.set(meta, new RepositoryClass(this, entityName));
|
|
107
|
+
}
|
|
108
|
+
return this.#repositoryMap.get(meta);
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Shortcut for `em.getRepository()`.
|
|
112
|
+
*/
|
|
113
|
+
repo(entityName) {
|
|
114
|
+
return this.getRepository(entityName);
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* Finds all entities matching your `where` query. You can pass additional options via the `options` parameter.
|
|
118
|
+
*/
|
|
119
|
+
async find(entityName, where, options = {}) {
|
|
120
|
+
if (options.disableIdentityMap ?? this.config.get('disableIdentityMap')) {
|
|
121
|
+
const em = this.getContext(false);
|
|
122
|
+
const fork = em.fork({ keepTransactionContext: true });
|
|
123
|
+
const ret = await fork.find(entityName, where, { ...options, disableIdentityMap: false });
|
|
124
|
+
fork.clear();
|
|
125
|
+
return ret;
|
|
126
|
+
}
|
|
127
|
+
const em = this.getContext();
|
|
128
|
+
em.prepareOptions(options);
|
|
129
|
+
await em.tryFlush(entityName, options);
|
|
130
|
+
where = await em.processWhere(entityName, where, options, 'read');
|
|
131
|
+
validateParams(where);
|
|
132
|
+
const meta = this.metadata.get(entityName);
|
|
133
|
+
if (meta.orderBy) {
|
|
134
|
+
options.orderBy = QueryHelper.mergeOrderBy(options.orderBy, meta.orderBy);
|
|
135
|
+
} else {
|
|
136
|
+
options.orderBy ??= {};
|
|
137
|
+
}
|
|
138
|
+
options.populate = await em.preparePopulate(entityName, options);
|
|
139
|
+
const populate = options.populate;
|
|
140
|
+
const cacheKey = em.cacheKey(entityName, options, 'em.find', where);
|
|
141
|
+
const cached = await em.tryCache(entityName, options.cache, cacheKey, options.refresh, true);
|
|
142
|
+
if (cached?.data) {
|
|
143
|
+
await em.#entityLoader.populate(entityName, cached.data, populate, {
|
|
144
|
+
...options,
|
|
145
|
+
...em.getPopulateWhere(where, options),
|
|
146
|
+
ignoreLazyScalarProperties: true,
|
|
147
|
+
lookup: false,
|
|
148
|
+
});
|
|
149
|
+
return cached.data;
|
|
150
|
+
}
|
|
151
|
+
options = { ...options };
|
|
152
|
+
// save the original hint value so we know it was infer/all
|
|
153
|
+
options._populateWhere = options.populateWhere ?? this.config.get('populateWhere');
|
|
154
|
+
options.populateWhere = this.createPopulateWhere({ ...where }, options);
|
|
155
|
+
options.populateFilter = await this.getJoinedFilters(meta, options);
|
|
156
|
+
await em.processUnionWhere(entityName, options, 'read');
|
|
157
|
+
const results = await em.driver.find(entityName, where, { ctx: em.#transactionContext, em, ...options });
|
|
158
|
+
if (results.length === 0) {
|
|
159
|
+
await em.storeCache(options.cache, cached, []);
|
|
160
|
+
return [];
|
|
161
|
+
}
|
|
162
|
+
const ret = [];
|
|
163
|
+
for (const data of results) {
|
|
164
|
+
const entity = em.#entityFactory.create(entityName, data, {
|
|
165
|
+
merge: true,
|
|
166
|
+
refresh: options.refresh,
|
|
167
|
+
schema: options.schema,
|
|
168
|
+
convertCustomTypes: true,
|
|
169
|
+
});
|
|
170
|
+
ret.push(entity);
|
|
171
|
+
}
|
|
172
|
+
const unique = Utils.unique(ret);
|
|
173
|
+
await em.#entityLoader.populate(entityName, unique, populate, {
|
|
174
|
+
...options,
|
|
175
|
+
...em.getPopulateWhere(where, options),
|
|
176
|
+
ignoreLazyScalarProperties: true,
|
|
177
|
+
lookup: false,
|
|
178
|
+
});
|
|
179
|
+
await em.#unitOfWork.dispatchOnLoadEvent();
|
|
180
|
+
if (meta.virtual) {
|
|
181
|
+
await em.storeCache(options.cache, cached, () => ret);
|
|
182
|
+
} else {
|
|
183
|
+
await em.storeCache(options.cache, cached, () => unique.map(e => helper(e).toPOJO()));
|
|
184
|
+
}
|
|
185
|
+
return unique;
|
|
186
|
+
}
|
|
187
|
+
/**
|
|
188
|
+
* Finds all entities and returns an async iterable (async generator) that yields results one by one.
|
|
189
|
+
* The results are merged and mapped to entity instances, without adding them to the identity map.
|
|
190
|
+
* You can disable merging by passing the options `{ mergeResults: false }`.
|
|
191
|
+
* With `mergeResults` disabled, to-many collections will contain at most one item, and you will get duplicate
|
|
192
|
+
* root entities when there are multiple items in the populated collection.
|
|
193
|
+
* This is useful for processing large datasets without loading everything into memory at once.
|
|
194
|
+
*
|
|
195
|
+
* ```ts
|
|
196
|
+
* const stream = em.stream(Book, { populate: ['author'] });
|
|
197
|
+
*
|
|
198
|
+
* for await (const book of stream) {
|
|
199
|
+
* // book is an instance of Book entity
|
|
200
|
+
* console.log(book.title, book.author.name);
|
|
201
|
+
* }
|
|
202
|
+
* ```
|
|
203
|
+
*/
|
|
204
|
+
async *stream(entityName, options = {}) {
|
|
205
|
+
const em = this.getContext();
|
|
206
|
+
em.prepareOptions(options);
|
|
207
|
+
options.strategy = 'joined';
|
|
208
|
+
await em.tryFlush(entityName, options);
|
|
209
|
+
const where = await em.processWhere(entityName, options.where ?? {}, options, 'read');
|
|
210
|
+
validateParams(where);
|
|
211
|
+
options.orderBy = options.orderBy || {};
|
|
212
|
+
options.populate = await em.preparePopulate(entityName, options);
|
|
213
|
+
const meta = this.metadata.get(entityName);
|
|
214
|
+
options = { ...options };
|
|
215
|
+
// save the original hint value so we know it was infer/all
|
|
216
|
+
options._populateWhere = options.populateWhere ?? this.config.get('populateWhere');
|
|
217
|
+
options.populateWhere = this.createPopulateWhere({ ...where }, options);
|
|
218
|
+
options.populateFilter = await this.getJoinedFilters(meta, options);
|
|
219
|
+
const stream = em.driver.stream(entityName, where, {
|
|
220
|
+
ctx: em.#transactionContext,
|
|
221
|
+
mapResults: false,
|
|
222
|
+
...options,
|
|
223
|
+
});
|
|
224
|
+
for await (const data of stream) {
|
|
225
|
+
const fork = em.fork();
|
|
226
|
+
const entity = fork.#entityFactory.create(entityName, data, {
|
|
227
|
+
refresh: options.refresh,
|
|
228
|
+
schema: options.schema,
|
|
229
|
+
convertCustomTypes: true,
|
|
230
|
+
});
|
|
231
|
+
helper(entity).setSerializationContext({
|
|
232
|
+
populate: options.populate,
|
|
233
|
+
fields: options.fields,
|
|
234
|
+
exclude: options.exclude,
|
|
235
|
+
});
|
|
236
|
+
await fork.#unitOfWork.dispatchOnLoadEvent();
|
|
237
|
+
fork.clear();
|
|
238
|
+
yield entity;
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
/**
|
|
242
|
+
* Finds all entities of given type, optionally matching the `where` condition provided in the `options` parameter.
|
|
243
|
+
*/
|
|
244
|
+
async findAll(entityName, options) {
|
|
245
|
+
return this.find(entityName, options?.where ?? {}, options);
|
|
246
|
+
}
|
|
247
|
+
getPopulateWhere(where, options) {
|
|
248
|
+
if (options.populateWhere === undefined) {
|
|
249
|
+
options.populateWhere = this.config.get('populateWhere');
|
|
250
|
+
}
|
|
251
|
+
if (options.populateWhere === PopulateHint.ALL) {
|
|
252
|
+
return { where: {}, populateWhere: options.populateWhere };
|
|
253
|
+
}
|
|
254
|
+
/* v8 ignore next */
|
|
255
|
+
if (options.populateWhere === PopulateHint.INFER) {
|
|
256
|
+
return { where, populateWhere: options.populateWhere };
|
|
257
|
+
}
|
|
258
|
+
return { where: options.populateWhere };
|
|
259
|
+
}
|
|
260
|
+
/**
|
|
261
|
+
* Registers global filter to this entity manager. Global filters are enabled by default (unless disabled via last parameter).
|
|
262
|
+
*/
|
|
263
|
+
addFilter(options) {
|
|
264
|
+
if (options.entity) {
|
|
265
|
+
options.entity = Utils.asArray(options.entity).map(n => Utils.className(n));
|
|
266
|
+
}
|
|
267
|
+
options.default ??= true;
|
|
268
|
+
this.getContext(false).#filters[options.name] = options;
|
|
269
|
+
}
|
|
270
|
+
/**
|
|
271
|
+
* Sets filter parameter values globally inside context defined by this entity manager.
|
|
272
|
+
* If you want to set shared value for all contexts, be sure to use the root entity manager.
|
|
273
|
+
*/
|
|
274
|
+
setFilterParams(name, args) {
|
|
275
|
+
this.getContext().#filterParams[name] = args;
|
|
276
|
+
}
|
|
277
|
+
/**
|
|
278
|
+
* Returns filter parameters for given filter set in this context.
|
|
279
|
+
*/
|
|
280
|
+
getFilterParams(name) {
|
|
281
|
+
return this.getContext().#filterParams[name];
|
|
282
|
+
}
|
|
283
|
+
/**
|
|
284
|
+
* Sets logger context for this entity manager.
|
|
285
|
+
*/
|
|
286
|
+
setLoggerContext(context) {
|
|
287
|
+
this.getContext().loggerContext = context;
|
|
288
|
+
}
|
|
289
|
+
/**
|
|
290
|
+
* Gets logger context for this entity manager.
|
|
291
|
+
*/
|
|
292
|
+
getLoggerContext(options) {
|
|
293
|
+
const em = options?.disableContextResolution ? this : this.getContext();
|
|
294
|
+
em.loggerContext ??= {};
|
|
295
|
+
return em.loggerContext;
|
|
296
|
+
}
|
|
297
|
+
/** Sets the flush mode for this EntityManager. Pass `undefined` to reset to the global default. */
|
|
298
|
+
setFlushMode(flushMode) {
|
|
299
|
+
this.getContext(false).#flushMode = flushMode;
|
|
300
|
+
}
|
|
301
|
+
async processWhere(entityName, where, options, type) {
|
|
302
|
+
where = QueryHelper.processWhere({
|
|
303
|
+
where,
|
|
304
|
+
entityName,
|
|
305
|
+
metadata: this.metadata,
|
|
306
|
+
platform: this.driver.getPlatform(),
|
|
307
|
+
convertCustomTypes: options.convertCustomTypes,
|
|
308
|
+
aliased: type === 'read',
|
|
309
|
+
});
|
|
310
|
+
where = await this.applyFilters(entityName, where, options.filters ?? {}, type, options);
|
|
311
|
+
where = this.applyDiscriminatorCondition(entityName, where);
|
|
312
|
+
return where;
|
|
313
|
+
}
|
|
314
|
+
async processUnionWhere(entityName, options, type) {
|
|
315
|
+
if (options.unionWhere?.length) {
|
|
316
|
+
if (!this.driver.getPlatform().supportsUnionWhere()) {
|
|
317
|
+
throw new Error(`unionWhere is only supported on SQL drivers`);
|
|
318
|
+
}
|
|
319
|
+
options.unionWhere = await Promise.all(
|
|
320
|
+
options.unionWhere.map(branch => this.processWhere(entityName, branch, options, type)),
|
|
321
|
+
);
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
// this method only handles the problem for mongo driver, SQL drivers have their implementation inside QueryBuilder
|
|
325
|
+
applyDiscriminatorCondition(entityName, where) {
|
|
326
|
+
const meta = this.metadata.find(entityName);
|
|
327
|
+
if (meta?.root.inheritanceType !== 'sti' || !meta?.discriminatorValue) {
|
|
328
|
+
return where;
|
|
329
|
+
}
|
|
330
|
+
const types = Object.values(meta.root.discriminatorMap).map(cls => this.metadata.get(cls));
|
|
331
|
+
const children = [];
|
|
332
|
+
const lookUpChildren = (ret, type) => {
|
|
333
|
+
const children = types.filter(meta2 => meta2.extends === type);
|
|
334
|
+
children.forEach(m => lookUpChildren(ret, m.class));
|
|
335
|
+
ret.push(...children.filter(c => c.discriminatorValue));
|
|
336
|
+
return children;
|
|
337
|
+
};
|
|
338
|
+
lookUpChildren(children, meta.class);
|
|
339
|
+
/* v8 ignore next */
|
|
340
|
+
where[meta.root.discriminatorColumn] =
|
|
341
|
+
children.length > 0
|
|
342
|
+
? { $in: [meta.discriminatorValue, ...children.map(c => c.discriminatorValue)] }
|
|
343
|
+
: meta.discriminatorValue;
|
|
344
|
+
return where;
|
|
345
|
+
}
|
|
346
|
+
createPopulateWhere(cond, options) {
|
|
347
|
+
const ret = {};
|
|
348
|
+
const populateWhere = options.populateWhere ?? this.config.get('populateWhere');
|
|
349
|
+
if (populateWhere === PopulateHint.INFER) {
|
|
350
|
+
Utils.merge(ret, cond);
|
|
351
|
+
} else if (typeof populateWhere === 'object') {
|
|
352
|
+
Utils.merge(ret, populateWhere);
|
|
353
|
+
}
|
|
354
|
+
return ret;
|
|
355
|
+
}
|
|
356
|
+
async getJoinedFilters(meta, options) {
|
|
357
|
+
// If user provided populateFilter, merge it with computed filters
|
|
358
|
+
const userFilter = options.populateFilter;
|
|
359
|
+
if (!this.config.get('filtersOnRelations') || !options.populate) {
|
|
360
|
+
return userFilter;
|
|
361
|
+
}
|
|
362
|
+
const ret = {};
|
|
363
|
+
for (const hint of options.populate) {
|
|
364
|
+
const field = hint.field.split(':')[0];
|
|
365
|
+
const prop = meta.properties[field];
|
|
366
|
+
const strategy = getLoadingStrategy(
|
|
367
|
+
prop.strategy || hint.strategy || options.strategy || this.config.get('loadStrategy'),
|
|
368
|
+
prop.kind,
|
|
369
|
+
);
|
|
370
|
+
const joined = strategy === LoadStrategy.JOINED && prop.kind !== ReferenceKind.SCALAR;
|
|
371
|
+
if (!joined && !hint.filter) {
|
|
372
|
+
continue;
|
|
373
|
+
}
|
|
374
|
+
const filters = QueryHelper.mergePropertyFilters(prop.filters, options.filters);
|
|
375
|
+
const where = await this.applyFilters(prop.targetMeta.class, {}, filters, 'read', {
|
|
376
|
+
...options,
|
|
377
|
+
populate: hint.children,
|
|
378
|
+
});
|
|
379
|
+
const where2 = await this.getJoinedFilters(prop.targetMeta, {
|
|
380
|
+
...options,
|
|
381
|
+
filters,
|
|
382
|
+
populate: hint.children,
|
|
383
|
+
populateWhere: PopulateHint.ALL,
|
|
384
|
+
});
|
|
385
|
+
if (Utils.hasObjectKeys(where)) {
|
|
386
|
+
ret[field] = ret[field] ? { $and: [where, ret[field]] } : where;
|
|
387
|
+
}
|
|
388
|
+
if (where2 && Utils.hasObjectKeys(where2)) {
|
|
389
|
+
if (ret[field]) {
|
|
390
|
+
Utils.merge(ret[field], where2);
|
|
391
|
+
} else {
|
|
392
|
+
ret[field] = where2;
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
// Merge user-provided populateFilter with computed filters
|
|
397
|
+
if (userFilter) {
|
|
398
|
+
Utils.merge(ret, userFilter);
|
|
399
|
+
}
|
|
400
|
+
return Utils.hasObjectKeys(ret) ? ret : undefined;
|
|
401
|
+
}
|
|
402
|
+
/**
|
|
403
|
+
* When filters are active on M:1 or 1:1 relations, we need to ref join them eagerly as they might affect the FK value.
|
|
404
|
+
*/
|
|
405
|
+
async autoJoinRefsForFilters(meta, options, parent) {
|
|
406
|
+
if (!meta || !this.config.get('autoJoinRefsForFilters') || options.filters === false) {
|
|
407
|
+
return;
|
|
408
|
+
}
|
|
409
|
+
const ret = options.populate;
|
|
410
|
+
for (const prop of meta.relations) {
|
|
411
|
+
if (
|
|
412
|
+
prop.object ||
|
|
413
|
+
![ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(prop.kind) ||
|
|
414
|
+
!(
|
|
415
|
+
(options.fields?.length ?? 0) === 0 ||
|
|
416
|
+
options.fields?.some(f => prop.name === f || prop.name.startsWith(`${String(f)}.`))
|
|
417
|
+
) ||
|
|
418
|
+
(parent?.class === prop.targetMeta.root.class && parent.propName === prop.inversedBy)
|
|
419
|
+
) {
|
|
420
|
+
continue;
|
|
421
|
+
}
|
|
422
|
+
options = { ...options, filters: QueryHelper.mergePropertyFilters(prop.filters, options.filters) };
|
|
423
|
+
// For polymorphic relations, check all targets for filters (not just the first targetMeta)
|
|
424
|
+
let hasActiveFilter = false;
|
|
425
|
+
if (prop.polymorphic && prop.polymorphTargets?.length) {
|
|
426
|
+
for (const targetMeta of prop.polymorphTargets) {
|
|
427
|
+
const cond = await this.applyFilters(targetMeta.class, {}, options.filters, 'read', options);
|
|
428
|
+
if (!Utils.isEmpty(cond)) {
|
|
429
|
+
hasActiveFilter = true;
|
|
430
|
+
break;
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
} else {
|
|
434
|
+
const cond = await this.applyFilters(prop.targetMeta.class, {}, options.filters, 'read', options);
|
|
435
|
+
hasActiveFilter = !Utils.isEmpty(cond);
|
|
436
|
+
}
|
|
437
|
+
if (hasActiveFilter) {
|
|
438
|
+
const populated = options.populate.filter(({ field }) => field.split(':')[0] === prop.name);
|
|
611
439
|
let found = false;
|
|
612
|
-
for (const
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
440
|
+
for (const hint of populated) {
|
|
441
|
+
if (!hint.all) {
|
|
442
|
+
hint.filter = true;
|
|
443
|
+
}
|
|
444
|
+
const strategy = getLoadingStrategy(
|
|
445
|
+
prop.strategy || hint.strategy || options.strategy || this.config.get('loadStrategy'),
|
|
446
|
+
prop.kind,
|
|
447
|
+
);
|
|
448
|
+
if (hint.field === `${prop.name}:ref` || (hint.filter && strategy === LoadStrategy.JOINED)) {
|
|
449
|
+
found = true;
|
|
450
|
+
}
|
|
620
451
|
}
|
|
621
452
|
if (!found) {
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
453
|
+
ret.push({ field: `${prop.name}:ref`, strategy: LoadStrategy.JOINED, filter: true });
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
for (const hint of ret) {
|
|
458
|
+
const [field, ref] = hint.field.split(':');
|
|
459
|
+
const prop = meta?.properties[field];
|
|
460
|
+
if (prop && !ref) {
|
|
461
|
+
hint.children ??= [];
|
|
462
|
+
await this.autoJoinRefsForFilters(
|
|
463
|
+
prop.targetMeta,
|
|
464
|
+
{ ...options, populate: hint.children },
|
|
465
|
+
{ class: meta.root.class, propName: prop.name },
|
|
466
|
+
);
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
/**
|
|
471
|
+
* @internal
|
|
472
|
+
*/
|
|
473
|
+
async applyFilters(entityName, where, options, type, findOptions) {
|
|
474
|
+
const meta = this.metadata.get(entityName);
|
|
475
|
+
const filters = [];
|
|
476
|
+
const ret = [];
|
|
477
|
+
const active = new Set();
|
|
478
|
+
const push = source => {
|
|
479
|
+
const activeFilters = QueryHelper.getActiveFilters(meta, options, source).filter(f => !active.has(f.name));
|
|
480
|
+
filters.push(...activeFilters);
|
|
481
|
+
activeFilters.forEach(f => active.add(f.name));
|
|
482
|
+
};
|
|
483
|
+
push(this.config.get('filters'));
|
|
484
|
+
push(this.#filters);
|
|
485
|
+
push(meta.filters);
|
|
486
|
+
if (filters.length === 0) {
|
|
487
|
+
return where;
|
|
488
|
+
}
|
|
489
|
+
for (const filter of filters) {
|
|
490
|
+
let cond;
|
|
491
|
+
if (filter.cond instanceof Function) {
|
|
492
|
+
// @ts-ignore
|
|
493
|
+
// oxfmt-ignore
|
|
494
|
+
const args = Utils.isPlainObject(options?.[filter.name]) ? options[filter.name] : this.getContext().#filterParams[filter.name];
|
|
495
|
+
if (!args && filter.cond.length > 0 && filter.args !== false) {
|
|
496
|
+
throw new Error(`No arguments provided for filter '${filter.name}'`);
|
|
497
|
+
}
|
|
498
|
+
cond = await filter.cond(args, type, this, findOptions, Utils.className(entityName));
|
|
499
|
+
} else {
|
|
500
|
+
cond = filter.cond;
|
|
501
|
+
}
|
|
502
|
+
cond = QueryHelper.processWhere({
|
|
503
|
+
where: cond,
|
|
504
|
+
entityName,
|
|
505
|
+
metadata: this.metadata,
|
|
506
|
+
platform: this.driver.getPlatform(),
|
|
507
|
+
aliased: type === 'read',
|
|
508
|
+
});
|
|
509
|
+
if (filter.strict) {
|
|
510
|
+
Object.defineProperty(cond, '__strict', { value: filter.strict, enumerable: false });
|
|
511
|
+
}
|
|
512
|
+
ret.push(cond);
|
|
513
|
+
}
|
|
514
|
+
const conds = [...ret, where].filter(c => Utils.hasObjectKeys(c) || Raw.hasObjectFragments(c));
|
|
515
|
+
return conds.length > 1 ? { $and: conds } : conds[0];
|
|
516
|
+
}
|
|
517
|
+
/**
|
|
518
|
+
* Calls `em.find()` and `em.count()` with the same arguments (where applicable) and returns the results as tuple
|
|
519
|
+
* where the first element is the array of entities, and the second is the count.
|
|
520
|
+
*/
|
|
521
|
+
async findAndCount(entityName, where, options = {}) {
|
|
522
|
+
const em = this.getContext(false);
|
|
523
|
+
await em.tryFlush(entityName, options);
|
|
524
|
+
options.flushMode = 'commit'; // do not try to auto flush again
|
|
525
|
+
return Promise.all([em.find(entityName, where, options), em.count(entityName, where, options)]);
|
|
526
|
+
}
|
|
527
|
+
/**
|
|
528
|
+
* Calls `em.find()` and `em.count()` with the same arguments (where applicable) and returns the results as {@apilink Cursor} object.
|
|
529
|
+
* Supports `before`, `after`, `first` and `last` options while disallowing `limit` and `offset`. Explicit `orderBy` option
|
|
530
|
+
* is required.
|
|
531
|
+
*
|
|
532
|
+
* Use `first` and `after` for forward pagination, or `last` and `before` for backward pagination.
|
|
533
|
+
*
|
|
534
|
+
* - `first` and `last` are numbers and serve as an alternative to `offset`, those options are mutually exclusive, use only one at a time
|
|
535
|
+
* - `before` and `after` specify the previous cursor value, it can be one of the:
|
|
536
|
+
* - `Cursor` instance
|
|
537
|
+
* - opaque string provided by `startCursor/endCursor` properties
|
|
538
|
+
* - POJO/entity instance
|
|
539
|
+
*
|
|
540
|
+
* ```ts
|
|
541
|
+
* const currentCursor = await em.findByCursor(User, {
|
|
542
|
+
* first: 10,
|
|
543
|
+
* after: previousCursor, // cursor instance
|
|
544
|
+
* orderBy: { id: 'desc' },
|
|
545
|
+
* });
|
|
546
|
+
*
|
|
547
|
+
* // to fetch next page
|
|
548
|
+
* const nextCursor = await em.findByCursor(User, {
|
|
549
|
+
* first: 10,
|
|
550
|
+
* after: currentCursor.endCursor, // opaque string
|
|
551
|
+
* orderBy: { id: 'desc' },
|
|
552
|
+
* });
|
|
553
|
+
*
|
|
554
|
+
* // to fetch next page
|
|
555
|
+
* const nextCursor2 = await em.findByCursor(User, {
|
|
556
|
+
* first: 10,
|
|
557
|
+
* after: { id: lastSeenId }, // entity-like POJO
|
|
558
|
+
* orderBy: { id: 'desc' },
|
|
559
|
+
* });
|
|
560
|
+
* ```
|
|
561
|
+
*
|
|
562
|
+
* The options also support an `includeCount` (true by default) option. If set to false, the `totalCount` is not
|
|
563
|
+
* returned as part of the cursor. This is useful for performance reason, when you don't care about the total number
|
|
564
|
+
* of pages.
|
|
565
|
+
*
|
|
566
|
+
* The `Cursor` object provides the following interface:
|
|
567
|
+
*
|
|
568
|
+
* ```ts
|
|
569
|
+
* Cursor<User> {
|
|
570
|
+
* items: [
|
|
571
|
+
* User { ... },
|
|
572
|
+
* User { ... },
|
|
573
|
+
* User { ... },
|
|
574
|
+
* ],
|
|
575
|
+
* totalCount: 50, // not included if `includeCount: false`
|
|
576
|
+
* startCursor: 'WzRd',
|
|
577
|
+
* endCursor: 'WzZd',
|
|
578
|
+
* hasPrevPage: true,
|
|
579
|
+
* hasNextPage: true,
|
|
580
|
+
* }
|
|
581
|
+
* ```
|
|
582
|
+
*/
|
|
583
|
+
async findByCursor(entityName, options) {
|
|
584
|
+
const em = this.getContext(false);
|
|
585
|
+
options.overfetch ??= true;
|
|
586
|
+
options.where ??= {};
|
|
587
|
+
if (Utils.isEmpty(options.orderBy) && !Raw.hasObjectFragments(options.orderBy)) {
|
|
588
|
+
throw new Error('Explicit `orderBy` option required');
|
|
589
|
+
}
|
|
590
|
+
const [entities, count] =
|
|
591
|
+
options.includeCount !== false
|
|
592
|
+
? await em.findAndCount(entityName, options.where, options)
|
|
593
|
+
: [await em.find(entityName, options.where, options)];
|
|
594
|
+
return new Cursor(entities, count, options, this.metadata.get(entityName));
|
|
595
|
+
}
|
|
596
|
+
/**
|
|
597
|
+
* Refreshes the persistent state of an entity from the database, overriding any local changes that have not yet been
|
|
598
|
+
* persisted. Returns the same entity instance (same object reference), but re-hydrated. If the entity is no longer
|
|
599
|
+
* in database, the method throws an error just like `em.findOneOrFail()` (and respects the same config options).
|
|
600
|
+
*/
|
|
601
|
+
async refreshOrFail(entity, options = {}) {
|
|
602
|
+
const ret = await this.refresh(entity, options);
|
|
603
|
+
if (!ret) {
|
|
604
|
+
options.failHandler ??= this.config.get('findOneOrFailHandler');
|
|
605
|
+
const wrapped = helper(entity);
|
|
606
|
+
const where = wrapped.getPrimaryKey();
|
|
607
|
+
throw options.failHandler(wrapped.__meta.className, where);
|
|
608
|
+
}
|
|
609
|
+
return ret;
|
|
610
|
+
}
|
|
611
|
+
/**
|
|
612
|
+
* Refreshes the persistent state of an entity from the database, overriding any local changes that have not yet been
|
|
613
|
+
* persisted. Returns the same entity instance (same object reference), but re-hydrated. If the entity is no longer
|
|
614
|
+
* in database, the method returns `null`.
|
|
615
|
+
*/
|
|
616
|
+
async refresh(entity, options = {}) {
|
|
617
|
+
const fork = this.fork({ keepTransactionContext: true });
|
|
618
|
+
const wrapped = helper(entity);
|
|
619
|
+
const reloaded = await fork.findOne(wrapped.__meta.class, entity, {
|
|
620
|
+
schema: wrapped.__schema,
|
|
621
|
+
...options,
|
|
622
|
+
flushMode: FlushMode.COMMIT,
|
|
623
|
+
});
|
|
624
|
+
const em = this.getContext();
|
|
625
|
+
if (!reloaded) {
|
|
626
|
+
em.#unitOfWork.unsetIdentity(entity);
|
|
627
|
+
return null;
|
|
628
|
+
}
|
|
629
|
+
let found = false;
|
|
630
|
+
for (const e of fork.#unitOfWork.getIdentityMap()) {
|
|
631
|
+
const ref = em.getReference(e.constructor, helper(e).getPrimaryKey());
|
|
632
|
+
const data = helper(e).serialize({ ignoreSerializers: true, includeHidden: true, convertCustomTypes: false });
|
|
633
|
+
em.config
|
|
634
|
+
.getHydrator(this.metadata)
|
|
635
|
+
.hydrate(ref, helper(ref).__meta, data, em.#entityFactory, 'full', false, false);
|
|
636
|
+
Utils.merge(helper(ref).__originalEntityData, this.#comparator.prepareEntity(e));
|
|
637
|
+
found ||= ref === entity;
|
|
638
|
+
}
|
|
639
|
+
if (!found) {
|
|
640
|
+
const data = helper(reloaded).serialize({
|
|
641
|
+
ignoreSerializers: true,
|
|
642
|
+
includeHidden: true,
|
|
643
|
+
convertCustomTypes: true,
|
|
644
|
+
});
|
|
645
|
+
em.config
|
|
646
|
+
.getHydrator(this.metadata)
|
|
647
|
+
.hydrate(entity, wrapped.__meta, data, em.#entityFactory, 'full', false, true);
|
|
648
|
+
Utils.merge(wrapped.__originalEntityData, this.#comparator.prepareEntity(reloaded));
|
|
649
|
+
}
|
|
650
|
+
return entity;
|
|
651
|
+
}
|
|
652
|
+
/**
|
|
653
|
+
* Finds first entity matching your `where` query.
|
|
654
|
+
*/
|
|
655
|
+
async findOne(entityName, where, options = {}) {
|
|
656
|
+
if (options.disableIdentityMap ?? this.config.get('disableIdentityMap')) {
|
|
657
|
+
const em = this.getContext(false);
|
|
658
|
+
const fork = em.fork({ keepTransactionContext: true });
|
|
659
|
+
const ret = await fork.findOne(entityName, where, { ...options, disableIdentityMap: false });
|
|
660
|
+
fork.clear();
|
|
661
|
+
return ret;
|
|
662
|
+
}
|
|
663
|
+
const em = this.getContext();
|
|
664
|
+
em.prepareOptions(options);
|
|
665
|
+
let entity = em.#unitOfWork.tryGetById(entityName, where, options.schema);
|
|
666
|
+
// query for a not managed entity which is already in the identity map as it
|
|
667
|
+
// was provided with a PK this entity does not exist in the db, there can't
|
|
668
|
+
// be any relations to it, so no need to deal with the populate hint
|
|
669
|
+
if (entity && !helper(entity).__managed) {
|
|
670
|
+
return entity;
|
|
671
|
+
}
|
|
672
|
+
await em.tryFlush(entityName, options);
|
|
673
|
+
const meta = em.metadata.get(entityName);
|
|
674
|
+
where = await em.processWhere(entityName, where, options, 'read');
|
|
675
|
+
validateEmptyWhere(where);
|
|
676
|
+
em.checkLockRequirements(options.lockMode, meta);
|
|
677
|
+
const isOptimisticLocking = options.lockMode == null || options.lockMode === LockMode.OPTIMISTIC;
|
|
678
|
+
if (entity && !em.shouldRefresh(meta, entity, options) && isOptimisticLocking) {
|
|
679
|
+
return em.lockAndPopulate(meta, entity, where, options);
|
|
680
|
+
}
|
|
681
|
+
validateParams(where);
|
|
682
|
+
options.populate = await em.preparePopulate(entityName, options);
|
|
683
|
+
const cacheKey = em.cacheKey(entityName, options, 'em.findOne', where);
|
|
684
|
+
const cached = await em.tryCache(entityName, options.cache, cacheKey, options.refresh, true);
|
|
685
|
+
if (cached?.data !== undefined) {
|
|
686
|
+
if (cached.data) {
|
|
687
|
+
await em.#entityLoader.populate(entityName, [cached.data], options.populate, {
|
|
688
|
+
...options,
|
|
689
|
+
...em.getPopulateWhere(where, options),
|
|
690
|
+
ignoreLazyScalarProperties: true,
|
|
691
|
+
lookup: false,
|
|
698
692
|
});
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
693
|
+
}
|
|
694
|
+
return cached.data;
|
|
695
|
+
}
|
|
696
|
+
options = { ...options };
|
|
697
|
+
// save the original hint value so we know it was infer/all
|
|
698
|
+
options._populateWhere = options.populateWhere ?? this.config.get('populateWhere');
|
|
699
|
+
options.populateWhere = this.createPopulateWhere({ ...where }, options);
|
|
700
|
+
options.populateFilter = await this.getJoinedFilters(meta, options);
|
|
701
|
+
await em.processUnionWhere(entityName, options, 'read');
|
|
702
|
+
const data = await em.driver.findOne(entityName, where, {
|
|
703
|
+
ctx: em.#transactionContext,
|
|
704
|
+
em,
|
|
705
|
+
...options,
|
|
706
|
+
});
|
|
707
|
+
if (!data) {
|
|
708
|
+
await em.storeCache(options.cache, cached, null);
|
|
709
|
+
return null;
|
|
710
|
+
}
|
|
711
|
+
entity = em.#entityFactory.create(entityName, data, {
|
|
712
|
+
merge: true,
|
|
713
|
+
refresh: options.refresh,
|
|
714
|
+
schema: options.schema,
|
|
715
|
+
convertCustomTypes: true,
|
|
716
|
+
});
|
|
717
|
+
await em.lockAndPopulate(meta, entity, where, options);
|
|
718
|
+
await em.#unitOfWork.dispatchOnLoadEvent();
|
|
719
|
+
await em.storeCache(options.cache, cached, () => helper(entity).toPOJO());
|
|
720
|
+
return entity;
|
|
721
|
+
}
|
|
722
|
+
/**
|
|
723
|
+
* Finds first entity matching your `where` query. If nothing found, it will throw an error.
|
|
724
|
+
* If the `strict` option is specified and nothing is found or more than one matching entity is found, it will throw an error.
|
|
725
|
+
* You can override the factory for creating this method via `options.failHandler` locally
|
|
726
|
+
* or via `Configuration.findOneOrFailHandler` (`findExactlyOneOrFailHandler` when specifying `strict`) globally.
|
|
727
|
+
*/
|
|
728
|
+
async findOneOrFail(entityName, where, options = {}) {
|
|
729
|
+
let entity;
|
|
730
|
+
let isStrictViolation = false;
|
|
731
|
+
if (options.strict) {
|
|
732
|
+
const ret = await this.find(entityName, where, { ...options, limit: 2 });
|
|
733
|
+
isStrictViolation = ret.length !== 1;
|
|
734
|
+
entity = ret[0];
|
|
735
|
+
} else {
|
|
736
|
+
entity = await this.findOne(entityName, where, options);
|
|
737
|
+
}
|
|
738
|
+
if (!entity || isStrictViolation) {
|
|
739
|
+
const key = options.strict ? 'findExactlyOneOrFailHandler' : 'findOneOrFailHandler';
|
|
740
|
+
options.failHandler ??= this.config.get(key);
|
|
741
|
+
const name = Utils.className(entityName);
|
|
742
|
+
/* v8 ignore next */
|
|
743
|
+
where = Utils.isEntity(where) ? helper(where).getPrimaryKey() : where;
|
|
744
|
+
throw options.failHandler(name, where);
|
|
745
|
+
}
|
|
746
|
+
return entity;
|
|
747
|
+
}
|
|
748
|
+
/**
|
|
749
|
+
* Creates or updates the entity, based on whether it is already present in the database.
|
|
750
|
+
* This method performs an `insert on conflict merge` query ensuring the database is in sync, returning a managed
|
|
751
|
+
* entity instance. The method accepts either `entityName` together with the entity `data`, or just entity instance.
|
|
752
|
+
*
|
|
753
|
+
* ```ts
|
|
754
|
+
* // insert into "author" ("age", "email") values (33, 'foo@bar.com') on conflict ("email") do update set "age" = 41
|
|
755
|
+
* const author = await em.upsert(Author, { email: 'foo@bar.com', age: 33 });
|
|
756
|
+
* ```
|
|
757
|
+
*
|
|
758
|
+
* The entity data needs to contain either the primary key, or any other unique property. Let's consider the following example, where `Author.email` is a unique property:
|
|
759
|
+
*
|
|
760
|
+
* ```ts
|
|
761
|
+
* // insert into "author" ("age", "email") values (33, 'foo@bar.com') on conflict ("email") do update set "age" = 41
|
|
762
|
+
* // select "id" from "author" where "email" = 'foo@bar.com'
|
|
763
|
+
* const author = await em.upsert(Author, { email: 'foo@bar.com', age: 33 });
|
|
764
|
+
* ```
|
|
765
|
+
*
|
|
766
|
+
* Depending on the driver support, this will either use a returning query, or a separate select query, to fetch the primary key if it's missing from the `data`.
|
|
767
|
+
*
|
|
768
|
+
* If the entity is already present in current context, there won't be any queries - instead, the entity data will be assigned and an explicit `flush` will be required for those changes to be persisted.
|
|
769
|
+
*/
|
|
770
|
+
async upsert(entityNameOrEntity, data, options = {}) {
|
|
771
|
+
if (options.disableIdentityMap ?? this.config.get('disableIdentityMap')) {
|
|
772
|
+
const em = this.getContext(false);
|
|
773
|
+
const fork = em.fork({ keepTransactionContext: true });
|
|
774
|
+
const ret = await fork.upsert(entityNameOrEntity, data, { ...options, disableIdentityMap: false });
|
|
775
|
+
fork.clear();
|
|
776
|
+
return ret;
|
|
777
|
+
}
|
|
778
|
+
const em = this.getContext(false);
|
|
779
|
+
em.prepareOptions(options);
|
|
780
|
+
let entityName;
|
|
781
|
+
let where;
|
|
782
|
+
let entity = null;
|
|
783
|
+
if (data === undefined) {
|
|
784
|
+
entityName = entityNameOrEntity.constructor;
|
|
785
|
+
data = entityNameOrEntity;
|
|
786
|
+
} else {
|
|
787
|
+
entityName = entityNameOrEntity;
|
|
788
|
+
}
|
|
789
|
+
const meta = this.metadata.get(entityName);
|
|
790
|
+
const convertCustomTypes = !Utils.isEntity(data);
|
|
791
|
+
if (Utils.isEntity(data)) {
|
|
792
|
+
entity = data;
|
|
793
|
+
if (helper(entity).__managed && helper(entity).__em === em && !this.config.get('upsertManaged')) {
|
|
794
|
+
em.#entityFactory.mergeData(meta, entity, data, { initialized: true });
|
|
729
795
|
return entity;
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
where =
|
|
782
|
-
|
|
783
|
-
}
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
if (where && !this.config.get('upsertManaged')) {
|
|
788
|
-
const exists = em.#unitOfWork.getById(entityName, where, options.schema);
|
|
789
|
-
if (exists) {
|
|
790
|
-
return em.assign(exists, data);
|
|
791
|
-
}
|
|
792
|
-
}
|
|
793
|
-
for (const key of Object.keys(data)) {
|
|
794
|
-
const prop = meta.properties[key];
|
|
795
|
-
if (prop?.persist === false) {
|
|
796
|
-
delete data[key];
|
|
797
|
-
}
|
|
798
|
-
}
|
|
799
|
-
}
|
|
800
|
-
where = getWhereCondition(meta, options.onConflictFields, data, where).where;
|
|
801
|
-
data = QueryHelper.processObjectParams(data);
|
|
802
|
-
validateParams(data, 'insert data');
|
|
803
|
-
if (em.eventManager.hasListeners(EventType.beforeUpsert, meta)) {
|
|
804
|
-
await em.eventManager.dispatchEvent(EventType.beforeUpsert, { entity: data, em, meta }, meta);
|
|
805
|
-
}
|
|
806
|
-
const ret = await em.driver.nativeUpdate(entityName, where, data, {
|
|
807
|
-
ctx: em.#transactionContext,
|
|
808
|
-
upsert: true,
|
|
809
|
-
convertCustomTypes,
|
|
810
|
-
...options,
|
|
796
|
+
}
|
|
797
|
+
where = helper(entity).getPrimaryKey();
|
|
798
|
+
data = em.#comparator.prepareEntity(entity);
|
|
799
|
+
} else {
|
|
800
|
+
data = Utils.copy(QueryHelper.processParams(data));
|
|
801
|
+
where = Utils.extractPK(data, meta);
|
|
802
|
+
if (where && !this.config.get('upsertManaged')) {
|
|
803
|
+
const exists = em.#unitOfWork.getById(entityName, where, options.schema);
|
|
804
|
+
if (exists) {
|
|
805
|
+
return em.assign(exists, data);
|
|
806
|
+
}
|
|
807
|
+
}
|
|
808
|
+
for (const key of Object.keys(data)) {
|
|
809
|
+
const prop = meta.properties[key];
|
|
810
|
+
if (prop?.persist === false) {
|
|
811
|
+
delete data[key];
|
|
812
|
+
}
|
|
813
|
+
}
|
|
814
|
+
}
|
|
815
|
+
where = getWhereCondition(meta, options.onConflictFields, data, where).where;
|
|
816
|
+
data = QueryHelper.processObjectParams(data);
|
|
817
|
+
validateParams(data, 'insert data');
|
|
818
|
+
if (em.eventManager.hasListeners(EventType.beforeUpsert, meta)) {
|
|
819
|
+
await em.eventManager.dispatchEvent(EventType.beforeUpsert, { entity: data, em, meta }, meta);
|
|
820
|
+
}
|
|
821
|
+
const ret = await em.driver.nativeUpdate(entityName, where, data, {
|
|
822
|
+
ctx: em.#transactionContext,
|
|
823
|
+
upsert: true,
|
|
824
|
+
convertCustomTypes,
|
|
825
|
+
...options,
|
|
826
|
+
});
|
|
827
|
+
em.#unitOfWork.getChangeSetPersister().mapReturnedValues(entity, data, ret.row, meta, true);
|
|
828
|
+
entity ??= em.#entityFactory.create(entityName, data, {
|
|
829
|
+
refresh: true,
|
|
830
|
+
initialized: true,
|
|
831
|
+
schema: options.schema,
|
|
832
|
+
});
|
|
833
|
+
const uniqueFields =
|
|
834
|
+
options.onConflictFields ?? (Utils.isPlainObject(where) ? Object.keys(where) : meta.primaryKeys);
|
|
835
|
+
const returning = getOnConflictReturningFields(meta, data, uniqueFields, options);
|
|
836
|
+
if (
|
|
837
|
+
options.onConflictAction === 'ignore' ||
|
|
838
|
+
!helper(entity).hasPrimaryKey() ||
|
|
839
|
+
(returning.length > 0 && !(this.getPlatform().usesReturningStatement() && ret.row))
|
|
840
|
+
) {
|
|
841
|
+
const where = {};
|
|
842
|
+
if (Array.isArray(uniqueFields)) {
|
|
843
|
+
for (const prop of uniqueFields) {
|
|
844
|
+
if (data[prop] != null) {
|
|
845
|
+
where[prop] = data[prop];
|
|
846
|
+
} else if (meta.primaryKeys.includes(prop) && ret.insertId != null) {
|
|
847
|
+
where[prop] = ret.insertId;
|
|
848
|
+
}
|
|
849
|
+
}
|
|
850
|
+
} else {
|
|
851
|
+
Object.keys(data).forEach(prop => {
|
|
852
|
+
where[prop] = data[prop];
|
|
811
853
|
});
|
|
812
|
-
|
|
813
|
-
|
|
854
|
+
if (meta.simplePK && ret.insertId != null) {
|
|
855
|
+
where[meta.primaryKeys[0]] = ret.insertId;
|
|
856
|
+
}
|
|
857
|
+
}
|
|
858
|
+
const data2 = await this.driver.findOne(meta.class, where, {
|
|
859
|
+
fields: returning,
|
|
860
|
+
ctx: em.#transactionContext,
|
|
861
|
+
convertCustomTypes: true,
|
|
862
|
+
connectionType: 'write',
|
|
863
|
+
schema: options.schema,
|
|
864
|
+
});
|
|
865
|
+
em.getHydrator().hydrate(entity, meta, data2, em.#entityFactory, 'full', false, true);
|
|
866
|
+
}
|
|
867
|
+
// recompute the data as there might be some values missing (e.g. those with db column defaults)
|
|
868
|
+
const snapshot = this.#comparator.prepareEntity(entity);
|
|
869
|
+
em.#unitOfWork.register(entity, snapshot, { refresh: true });
|
|
870
|
+
if (em.eventManager.hasListeners(EventType.afterUpsert, meta)) {
|
|
871
|
+
await em.eventManager.dispatchEvent(EventType.afterUpsert, { entity, em, meta }, meta);
|
|
872
|
+
}
|
|
873
|
+
return entity;
|
|
874
|
+
}
|
|
875
|
+
/**
|
|
876
|
+
* Creates or updates the entity, based on whether it is already present in the database.
|
|
877
|
+
* This method performs an `insert on conflict merge` query ensuring the database is in sync, returning a managed
|
|
878
|
+
* entity instance. The method accepts either `entityName` together with the entity `data`, or just entity instance.
|
|
879
|
+
*
|
|
880
|
+
* ```ts
|
|
881
|
+
* // insert into "author" ("age", "email") values (33, 'foo@bar.com') on conflict ("email") do update set "age" = 41
|
|
882
|
+
* const authors = await em.upsertMany(Author, [{ email: 'foo@bar.com', age: 33 }, ...]);
|
|
883
|
+
* ```
|
|
884
|
+
*
|
|
885
|
+
* The entity data needs to contain either the primary key, or any other unique property. Let's consider the following example, where `Author.email` is a unique property:
|
|
886
|
+
*
|
|
887
|
+
* ```ts
|
|
888
|
+
* // insert into "author" ("age", "email") values (33, 'foo@bar.com'), (666, 'lol@lol.lol') on conflict ("email") do update set "age" = excluded."age"
|
|
889
|
+
* // select "id" from "author" where "email" = 'foo@bar.com'
|
|
890
|
+
* const author = await em.upsertMany(Author, [
|
|
891
|
+
* { email: 'foo@bar.com', age: 33 },
|
|
892
|
+
* { email: 'lol@lol.lol', age: 666 },
|
|
893
|
+
* ]);
|
|
894
|
+
* ```
|
|
895
|
+
*
|
|
896
|
+
* Depending on the driver support, this will either use a returning query, or a separate select query, to fetch the primary key if it's missing from the `data`.
|
|
897
|
+
*
|
|
898
|
+
* If the entity is already present in current context, there won't be any queries - instead, the entity data will be assigned and an explicit `flush` will be required for those changes to be persisted.
|
|
899
|
+
*/
|
|
900
|
+
async upsertMany(entityNameOrEntity, data, options = {}) {
|
|
901
|
+
if (options.disableIdentityMap ?? this.config.get('disableIdentityMap')) {
|
|
902
|
+
const em = this.getContext(false);
|
|
903
|
+
const fork = em.fork({ keepTransactionContext: true });
|
|
904
|
+
const ret = await fork.upsertMany(entityNameOrEntity, data, { ...options, disableIdentityMap: false });
|
|
905
|
+
fork.clear();
|
|
906
|
+
return ret;
|
|
907
|
+
}
|
|
908
|
+
const em = this.getContext(false);
|
|
909
|
+
em.prepareOptions(options);
|
|
910
|
+
let entityName;
|
|
911
|
+
let propIndex;
|
|
912
|
+
if (data === undefined) {
|
|
913
|
+
entityName = entityNameOrEntity[0].constructor;
|
|
914
|
+
data = entityNameOrEntity;
|
|
915
|
+
} else {
|
|
916
|
+
entityName = entityNameOrEntity;
|
|
917
|
+
}
|
|
918
|
+
const batchSize = options.batchSize ?? this.config.get('batchSize');
|
|
919
|
+
if (data.length > batchSize) {
|
|
920
|
+
const ret = [];
|
|
921
|
+
for (let i = 0; i < data.length; i += batchSize) {
|
|
922
|
+
const chunk = data.slice(i, i + batchSize);
|
|
923
|
+
ret.push(...(await this.upsertMany(entityName, chunk, options)));
|
|
924
|
+
}
|
|
925
|
+
return ret;
|
|
926
|
+
}
|
|
927
|
+
const meta = this.metadata.get(entityName);
|
|
928
|
+
const convertCustomTypes = !Utils.isEntity(data[0]);
|
|
929
|
+
const allData = [];
|
|
930
|
+
const allWhere = [];
|
|
931
|
+
const entities = new Map();
|
|
932
|
+
const entitiesByData = new Map();
|
|
933
|
+
for (let i = 0; i < data.length; i++) {
|
|
934
|
+
let row = data[i];
|
|
935
|
+
let where;
|
|
936
|
+
if (Utils.isEntity(row)) {
|
|
937
|
+
const entity = row;
|
|
938
|
+
if (helper(entity).__managed && helper(entity).__em === em && !this.config.get('upsertManaged')) {
|
|
939
|
+
em.#entityFactory.mergeData(meta, entity, row, { initialized: true });
|
|
940
|
+
entities.set(entity, row);
|
|
941
|
+
entitiesByData.set(row, entity);
|
|
942
|
+
continue;
|
|
943
|
+
}
|
|
944
|
+
where = helper(entity).getPrimaryKey();
|
|
945
|
+
row = em.#comparator.prepareEntity(entity);
|
|
946
|
+
} else {
|
|
947
|
+
row = data[i] = Utils.copy(QueryHelper.processParams(row));
|
|
948
|
+
where = Utils.extractPK(row, meta);
|
|
949
|
+
if (where && !this.config.get('upsertManaged')) {
|
|
950
|
+
const exists = em.#unitOfWork.getById(entityName, where, options.schema);
|
|
951
|
+
if (exists) {
|
|
952
|
+
em.assign(exists, row);
|
|
953
|
+
entities.set(exists, row);
|
|
954
|
+
entitiesByData.set(row, exists);
|
|
955
|
+
continue;
|
|
956
|
+
}
|
|
957
|
+
}
|
|
958
|
+
for (const key of Object.keys(row)) {
|
|
959
|
+
const prop = meta.properties[key];
|
|
960
|
+
if (prop?.persist === false) {
|
|
961
|
+
delete row[key];
|
|
962
|
+
}
|
|
963
|
+
}
|
|
964
|
+
}
|
|
965
|
+
const unique = options.onConflictFields ?? meta.props.filter(p => p.unique).map(p => p.name);
|
|
966
|
+
propIndex = !isRaw(unique) && unique.findIndex(p => data[p] ?? data[p.substring(0, p.indexOf('.'))] != null);
|
|
967
|
+
const tmp = getWhereCondition(meta, options.onConflictFields, row, where);
|
|
968
|
+
propIndex = tmp.propIndex;
|
|
969
|
+
where = QueryHelper.processWhere({
|
|
970
|
+
where: tmp.where,
|
|
971
|
+
entityName,
|
|
972
|
+
metadata: this.metadata,
|
|
973
|
+
platform: this.getPlatform(),
|
|
974
|
+
});
|
|
975
|
+
row = QueryHelper.processObjectParams(row);
|
|
976
|
+
validateParams(row, 'insert data');
|
|
977
|
+
allData.push(row);
|
|
978
|
+
allWhere.push(where);
|
|
979
|
+
}
|
|
980
|
+
if (entities.size === data.length) {
|
|
981
|
+
return [...entities.keys()];
|
|
982
|
+
}
|
|
983
|
+
if (em.eventManager.hasListeners(EventType.beforeUpsert, meta)) {
|
|
984
|
+
for (const dto of data) {
|
|
985
|
+
const entity = entitiesByData.get(dto) ?? dto;
|
|
986
|
+
await em.eventManager.dispatchEvent(EventType.beforeUpsert, { entity, em, meta }, meta);
|
|
987
|
+
}
|
|
988
|
+
}
|
|
989
|
+
const res = await em.driver.nativeUpdateMany(entityName, allWhere, allData, {
|
|
990
|
+
ctx: em.#transactionContext,
|
|
991
|
+
upsert: true,
|
|
992
|
+
convertCustomTypes,
|
|
993
|
+
...options,
|
|
994
|
+
});
|
|
995
|
+
entities.clear();
|
|
996
|
+
entitiesByData.clear();
|
|
997
|
+
const loadPK = new Map();
|
|
998
|
+
allData.forEach((row, i) => {
|
|
999
|
+
em.#unitOfWork
|
|
1000
|
+
.getChangeSetPersister()
|
|
1001
|
+
.mapReturnedValues(
|
|
1002
|
+
Utils.isEntity(data[i]) ? data[i] : null,
|
|
1003
|
+
Utils.isEntity(data[i]) ? {} : data[i],
|
|
1004
|
+
res.rows?.[i],
|
|
1005
|
+
meta,
|
|
1006
|
+
true,
|
|
1007
|
+
);
|
|
1008
|
+
const entity = Utils.isEntity(data[i])
|
|
1009
|
+
? data[i]
|
|
1010
|
+
: em.#entityFactory.create(entityName, row, {
|
|
814
1011
|
refresh: true,
|
|
815
1012
|
initialized: true,
|
|
816
1013
|
schema: options.schema,
|
|
1014
|
+
});
|
|
1015
|
+
if (!helper(entity).hasPrimaryKey()) {
|
|
1016
|
+
loadPK.set(entity, allWhere[i]);
|
|
1017
|
+
}
|
|
1018
|
+
entities.set(entity, row);
|
|
1019
|
+
entitiesByData.set(row, entity);
|
|
1020
|
+
});
|
|
1021
|
+
// skip if we got the PKs via returning statement (`rows`)
|
|
1022
|
+
// oxfmt-ignore
|
|
1023
|
+
const uniqueFields = options.onConflictFields ?? (Utils.isPlainObject(allWhere[0]) ? Object.keys(allWhere[0]).flatMap(key => Utils.splitPrimaryKeys(key)) : meta.primaryKeys);
|
|
1024
|
+
const returning = getOnConflictReturningFields(meta, data[0], uniqueFields, options);
|
|
1025
|
+
const reloadFields = returning.length > 0 && !(this.getPlatform().usesReturningStatement() && res.rows?.length);
|
|
1026
|
+
if (options.onConflictAction === 'ignore' || (!res.rows?.length && loadPK.size > 0) || reloadFields) {
|
|
1027
|
+
const unique = meta.hydrateProps.filter(p => !p.lazy).map(p => p.name);
|
|
1028
|
+
const add = new Set(propIndex !== false && propIndex >= 0 ? [unique[propIndex]] : []);
|
|
1029
|
+
for (const cond of loadPK.values()) {
|
|
1030
|
+
Utils.keys(cond).forEach(key => add.add(key));
|
|
1031
|
+
}
|
|
1032
|
+
const where = { $or: [] };
|
|
1033
|
+
data.forEach((item, idx) => {
|
|
1034
|
+
where.$or[idx] = {};
|
|
1035
|
+
const props = Array.isArray(uniqueFields) ? uniqueFields : Object.keys(item);
|
|
1036
|
+
props.forEach(prop => {
|
|
1037
|
+
where.$or[idx][prop] = item[prop];
|
|
817
1038
|
});
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
}
|
|
833
|
-
}
|
|
834
|
-
}
|
|
835
|
-
else {
|
|
836
|
-
Object.keys(data).forEach(prop => {
|
|
837
|
-
where[prop] = data[prop];
|
|
838
|
-
});
|
|
839
|
-
if (meta.simplePK && ret.insertId != null) {
|
|
840
|
-
where[meta.primaryKeys[0]] = ret.insertId;
|
|
841
|
-
}
|
|
1039
|
+
});
|
|
1040
|
+
const data2 = await this.driver.find(meta.class, where, {
|
|
1041
|
+
fields: returning.concat(...add).concat(...(Array.isArray(uniqueFields) ? uniqueFields : [])),
|
|
1042
|
+
ctx: em.#transactionContext,
|
|
1043
|
+
convertCustomTypes: true,
|
|
1044
|
+
connectionType: 'write',
|
|
1045
|
+
schema: options.schema,
|
|
1046
|
+
});
|
|
1047
|
+
for (const [entity, cond] of loadPK.entries()) {
|
|
1048
|
+
const row = data2.find(row => {
|
|
1049
|
+
const tmp = {};
|
|
1050
|
+
add.forEach(k => {
|
|
1051
|
+
if (!meta.properties[k]?.primary) {
|
|
1052
|
+
tmp[k] = row[k];
|
|
842
1053
|
}
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
ctx: em.#transactionContext,
|
|
846
|
-
convertCustomTypes: true,
|
|
847
|
-
connectionType: 'write',
|
|
848
|
-
schema: options.schema,
|
|
849
|
-
});
|
|
850
|
-
em.getHydrator().hydrate(entity, meta, data2, em.#entityFactory, 'full', false, true);
|
|
851
|
-
}
|
|
852
|
-
// recompute the data as there might be some values missing (e.g. those with db column defaults)
|
|
853
|
-
const snapshot = this.#comparator.prepareEntity(entity);
|
|
854
|
-
em.#unitOfWork.register(entity, snapshot, { refresh: true });
|
|
855
|
-
if (em.eventManager.hasListeners(EventType.afterUpsert, meta)) {
|
|
856
|
-
await em.eventManager.dispatchEvent(EventType.afterUpsert, { entity, em, meta }, meta);
|
|
857
|
-
}
|
|
858
|
-
return entity;
|
|
859
|
-
}
|
|
860
|
-
/**
|
|
861
|
-
* Creates or updates the entity, based on whether it is already present in the database.
|
|
862
|
-
* This method performs an `insert on conflict merge` query ensuring the database is in sync, returning a managed
|
|
863
|
-
* entity instance. The method accepts either `entityName` together with the entity `data`, or just entity instance.
|
|
864
|
-
*
|
|
865
|
-
* ```ts
|
|
866
|
-
* // insert into "author" ("age", "email") values (33, 'foo@bar.com') on conflict ("email") do update set "age" = 41
|
|
867
|
-
* const authors = await em.upsertMany(Author, [{ email: 'foo@bar.com', age: 33 }, ...]);
|
|
868
|
-
* ```
|
|
869
|
-
*
|
|
870
|
-
* The entity data needs to contain either the primary key, or any other unique property. Let's consider the following example, where `Author.email` is a unique property:
|
|
871
|
-
*
|
|
872
|
-
* ```ts
|
|
873
|
-
* // insert into "author" ("age", "email") values (33, 'foo@bar.com'), (666, 'lol@lol.lol') on conflict ("email") do update set "age" = excluded."age"
|
|
874
|
-
* // select "id" from "author" where "email" = 'foo@bar.com'
|
|
875
|
-
* const author = await em.upsertMany(Author, [
|
|
876
|
-
* { email: 'foo@bar.com', age: 33 },
|
|
877
|
-
* { email: 'lol@lol.lol', age: 666 },
|
|
878
|
-
* ]);
|
|
879
|
-
* ```
|
|
880
|
-
*
|
|
881
|
-
* Depending on the driver support, this will either use a returning query, or a separate select query, to fetch the primary key if it's missing from the `data`.
|
|
882
|
-
*
|
|
883
|
-
* If the entity is already present in current context, there won't be any queries - instead, the entity data will be assigned and an explicit `flush` will be required for those changes to be persisted.
|
|
884
|
-
*/
|
|
885
|
-
async upsertMany(entityNameOrEntity, data, options = {}) {
|
|
886
|
-
if (options.disableIdentityMap ?? this.config.get('disableIdentityMap')) {
|
|
887
|
-
const em = this.getContext(false);
|
|
888
|
-
const fork = em.fork({ keepTransactionContext: true });
|
|
889
|
-
const ret = await fork.upsertMany(entityNameOrEntity, data, { ...options, disableIdentityMap: false });
|
|
890
|
-
fork.clear();
|
|
891
|
-
return ret;
|
|
892
|
-
}
|
|
893
|
-
const em = this.getContext(false);
|
|
894
|
-
em.prepareOptions(options);
|
|
895
|
-
let entityName;
|
|
896
|
-
let propIndex;
|
|
897
|
-
if (data === undefined) {
|
|
898
|
-
entityName = entityNameOrEntity[0].constructor;
|
|
899
|
-
data = entityNameOrEntity;
|
|
900
|
-
}
|
|
901
|
-
else {
|
|
902
|
-
entityName = entityNameOrEntity;
|
|
903
|
-
}
|
|
904
|
-
const batchSize = options.batchSize ?? this.config.get('batchSize');
|
|
905
|
-
if (data.length > batchSize) {
|
|
906
|
-
const ret = [];
|
|
907
|
-
for (let i = 0; i < data.length; i += batchSize) {
|
|
908
|
-
const chunk = data.slice(i, i + batchSize);
|
|
909
|
-
ret.push(...(await this.upsertMany(entityName, chunk, options)));
|
|
910
|
-
}
|
|
911
|
-
return ret;
|
|
912
|
-
}
|
|
913
|
-
const meta = this.metadata.get(entityName);
|
|
914
|
-
const convertCustomTypes = !Utils.isEntity(data[0]);
|
|
915
|
-
const allData = [];
|
|
916
|
-
const allWhere = [];
|
|
917
|
-
const entities = new Map();
|
|
918
|
-
const entitiesByData = new Map();
|
|
919
|
-
for (let i = 0; i < data.length; i++) {
|
|
920
|
-
let row = data[i];
|
|
921
|
-
let where;
|
|
922
|
-
if (Utils.isEntity(row)) {
|
|
923
|
-
const entity = row;
|
|
924
|
-
if (helper(entity).__managed && helper(entity).__em === em && !this.config.get('upsertManaged')) {
|
|
925
|
-
em.#entityFactory.mergeData(meta, entity, row, { initialized: true });
|
|
926
|
-
entities.set(entity, row);
|
|
927
|
-
entitiesByData.set(row, entity);
|
|
928
|
-
continue;
|
|
929
|
-
}
|
|
930
|
-
where = helper(entity).getPrimaryKey();
|
|
931
|
-
row = em.#comparator.prepareEntity(entity);
|
|
932
|
-
}
|
|
933
|
-
else {
|
|
934
|
-
row = data[i] = Utils.copy(QueryHelper.processParams(row));
|
|
935
|
-
where = Utils.extractPK(row, meta);
|
|
936
|
-
if (where && !this.config.get('upsertManaged')) {
|
|
937
|
-
const exists = em.#unitOfWork.getById(entityName, where, options.schema);
|
|
938
|
-
if (exists) {
|
|
939
|
-
em.assign(exists, row);
|
|
940
|
-
entities.set(exists, row);
|
|
941
|
-
entitiesByData.set(row, exists);
|
|
942
|
-
continue;
|
|
943
|
-
}
|
|
944
|
-
}
|
|
945
|
-
for (const key of Object.keys(row)) {
|
|
946
|
-
const prop = meta.properties[key];
|
|
947
|
-
if (prop?.persist === false) {
|
|
948
|
-
delete row[key];
|
|
949
|
-
}
|
|
950
|
-
}
|
|
951
|
-
}
|
|
952
|
-
const unique = options.onConflictFields ?? meta.props.filter(p => p.unique).map(p => p.name);
|
|
953
|
-
propIndex =
|
|
954
|
-
!isRaw(unique) &&
|
|
955
|
-
unique.findIndex(p => data[p] ?? data[p.substring(0, p.indexOf('.'))] != null);
|
|
956
|
-
const tmp = getWhereCondition(meta, options.onConflictFields, row, where);
|
|
957
|
-
propIndex = tmp.propIndex;
|
|
958
|
-
where = QueryHelper.processWhere({
|
|
959
|
-
where: tmp.where,
|
|
960
|
-
entityName,
|
|
961
|
-
metadata: this.metadata,
|
|
962
|
-
platform: this.getPlatform(),
|
|
963
|
-
});
|
|
964
|
-
row = QueryHelper.processObjectParams(row);
|
|
965
|
-
validateParams(row, 'insert data');
|
|
966
|
-
allData.push(row);
|
|
967
|
-
allWhere.push(where);
|
|
968
|
-
}
|
|
969
|
-
if (entities.size === data.length) {
|
|
970
|
-
return [...entities.keys()];
|
|
971
|
-
}
|
|
972
|
-
if (em.eventManager.hasListeners(EventType.beforeUpsert, meta)) {
|
|
973
|
-
for (const dto of data) {
|
|
974
|
-
const entity = entitiesByData.get(dto) ?? dto;
|
|
975
|
-
await em.eventManager.dispatchEvent(EventType.beforeUpsert, { entity, em, meta }, meta);
|
|
976
|
-
}
|
|
977
|
-
}
|
|
978
|
-
const res = await em.driver.nativeUpdateMany(entityName, allWhere, allData, {
|
|
979
|
-
ctx: em.#transactionContext,
|
|
980
|
-
upsert: true,
|
|
981
|
-
convertCustomTypes,
|
|
982
|
-
...options,
|
|
983
|
-
});
|
|
984
|
-
entities.clear();
|
|
985
|
-
entitiesByData.clear();
|
|
986
|
-
const loadPK = new Map();
|
|
987
|
-
allData.forEach((row, i) => {
|
|
988
|
-
em.#unitOfWork
|
|
989
|
-
.getChangeSetPersister()
|
|
990
|
-
.mapReturnedValues(Utils.isEntity(data[i]) ? data[i] : null, Utils.isEntity(data[i]) ? {} : data[i], res.rows?.[i], meta, true);
|
|
991
|
-
const entity = Utils.isEntity(data[i])
|
|
992
|
-
? data[i]
|
|
993
|
-
: em.#entityFactory.create(entityName, row, {
|
|
994
|
-
refresh: true,
|
|
995
|
-
initialized: true,
|
|
996
|
-
schema: options.schema,
|
|
997
|
-
});
|
|
998
|
-
if (!helper(entity).hasPrimaryKey()) {
|
|
999
|
-
loadPK.set(entity, allWhere[i]);
|
|
1000
|
-
}
|
|
1001
|
-
entities.set(entity, row);
|
|
1002
|
-
entitiesByData.set(row, entity);
|
|
1054
|
+
});
|
|
1055
|
+
return this.#comparator.matching(entityName, cond, tmp);
|
|
1003
1056
|
});
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
});
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
}
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
|
|
1268
|
-
|
|
1269
|
-
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
|
|
1284
|
-
|
|
1285
|
-
|
|
1286
|
-
|
|
1287
|
-
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
|
|
1295
|
-
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
|
|
1312
|
-
|
|
1313
|
-
|
|
1314
|
-
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
|
|
1329
|
-
|
|
1330
|
-
|
|
1331
|
-
|
|
1332
|
-
|
|
1333
|
-
|
|
1334
|
-
|
|
1335
|
-
|
|
1336
|
-
|
|
1337
|
-
|
|
1338
|
-
|
|
1339
|
-
|
|
1340
|
-
|
|
1341
|
-
|
|
1342
|
-
|
|
1343
|
-
|
|
1344
|
-
|
|
1345
|
-
|
|
1346
|
-
|
|
1347
|
-
|
|
1348
|
-
|
|
1349
|
-
|
|
1350
|
-
|
|
1351
|
-
|
|
1352
|
-
|
|
1353
|
-
|
|
1354
|
-
|
|
1355
|
-
|
|
1356
|
-
|
|
1357
|
-
|
|
1358
|
-
|
|
1359
|
-
|
|
1360
|
-
|
|
1361
|
-
|
|
1362
|
-
|
|
1363
|
-
|
|
1364
|
-
|
|
1365
|
-
|
|
1366
|
-
|
|
1367
|
-
|
|
1368
|
-
|
|
1369
|
-
|
|
1370
|
-
|
|
1371
|
-
|
|
1372
|
-
|
|
1373
|
-
|
|
1374
|
-
|
|
1375
|
-
|
|
1376
|
-
|
|
1377
|
-
|
|
1378
|
-
|
|
1379
|
-
|
|
1380
|
-
|
|
1381
|
-
|
|
1382
|
-
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
|
|
1386
|
-
|
|
1387
|
-
|
|
1388
|
-
|
|
1389
|
-
|
|
1390
|
-
|
|
1391
|
-
|
|
1392
|
-
|
|
1393
|
-
|
|
1394
|
-
|
|
1395
|
-
|
|
1396
|
-
|
|
1397
|
-
|
|
1398
|
-
|
|
1399
|
-
|
|
1400
|
-
|
|
1401
|
-
|
|
1402
|
-
|
|
1403
|
-
|
|
1404
|
-
|
|
1405
|
-
|
|
1406
|
-
|
|
1407
|
-
|
|
1408
|
-
|
|
1409
|
-
|
|
1410
|
-
|
|
1411
|
-
|
|
1412
|
-
|
|
1413
|
-
|
|
1414
|
-
|
|
1415
|
-
|
|
1416
|
-
|
|
1417
|
-
|
|
1418
|
-
|
|
1419
|
-
|
|
1420
|
-
|
|
1421
|
-
|
|
1422
|
-
|
|
1423
|
-
|
|
1424
|
-
|
|
1425
|
-
|
|
1426
|
-
|
|
1427
|
-
|
|
1428
|
-
|
|
1429
|
-
|
|
1430
|
-
|
|
1431
|
-
|
|
1432
|
-
|
|
1433
|
-
|
|
1434
|
-
|
|
1435
|
-
|
|
1436
|
-
|
|
1437
|
-
|
|
1438
|
-
|
|
1439
|
-
|
|
1440
|
-
|
|
1441
|
-
|
|
1442
|
-
|
|
1443
|
-
}
|
|
1444
|
-
|
|
1445
|
-
|
|
1446
|
-
|
|
1447
|
-
|
|
1448
|
-
|
|
1449
|
-
|
|
1450
|
-
|
|
1451
|
-
|
|
1452
|
-
|
|
1453
|
-
|
|
1454
|
-
|
|
1455
|
-
|
|
1456
|
-
|
|
1457
|
-
|
|
1458
|
-
|
|
1459
|
-
|
|
1460
|
-
|
|
1461
|
-
|
|
1462
|
-
|
|
1463
|
-
|
|
1464
|
-
|
|
1465
|
-
|
|
1466
|
-
}
|
|
1467
|
-
|
|
1468
|
-
|
|
1469
|
-
|
|
1470
|
-
|
|
1471
|
-
|
|
1472
|
-
|
|
1473
|
-
|
|
1474
|
-
|
|
1475
|
-
|
|
1476
|
-
|
|
1477
|
-
|
|
1478
|
-
|
|
1479
|
-
|
|
1480
|
-
|
|
1481
|
-
|
|
1482
|
-
|
|
1483
|
-
|
|
1484
|
-
|
|
1485
|
-
|
|
1486
|
-
|
|
1487
|
-
|
|
1488
|
-
|
|
1489
|
-
|
|
1490
|
-
|
|
1491
|
-
|
|
1492
|
-
|
|
1493
|
-
|
|
1494
|
-
|
|
1495
|
-
|
|
1496
|
-
|
|
1497
|
-
|
|
1498
|
-
|
|
1499
|
-
|
|
1500
|
-
|
|
1501
|
-
|
|
1502
|
-
|
|
1503
|
-
|
|
1504
|
-
|
|
1505
|
-
|
|
1506
|
-
|
|
1507
|
-
|
|
1508
|
-
|
|
1509
|
-
|
|
1510
|
-
|
|
1511
|
-
|
|
1512
|
-
|
|
1513
|
-
|
|
1514
|
-
|
|
1515
|
-
|
|
1516
|
-
|
|
1517
|
-
|
|
1518
|
-
|
|
1519
|
-
|
|
1520
|
-
|
|
1521
|
-
|
|
1522
|
-
|
|
1523
|
-
|
|
1524
|
-
|
|
1525
|
-
|
|
1526
|
-
|
|
1527
|
-
|
|
1528
|
-
|
|
1529
|
-
|
|
1530
|
-
|
|
1531
|
-
|
|
1532
|
-
|
|
1533
|
-
|
|
1534
|
-
|
|
1535
|
-
|
|
1536
|
-
|
|
1537
|
-
|
|
1538
|
-
|
|
1539
|
-
|
|
1540
|
-
|
|
1541
|
-
|
|
1542
|
-
|
|
1543
|
-
|
|
1544
|
-
|
|
1545
|
-
|
|
1546
|
-
|
|
1547
|
-
|
|
1548
|
-
|
|
1549
|
-
|
|
1550
|
-
|
|
1551
|
-
|
|
1552
|
-
|
|
1553
|
-
|
|
1554
|
-
|
|
1555
|
-
|
|
1556
|
-
|
|
1557
|
-
|
|
1558
|
-
|
|
1559
|
-
|
|
1560
|
-
|
|
1561
|
-
|
|
1562
|
-
|
|
1563
|
-
|
|
1564
|
-
|
|
1565
|
-
|
|
1566
|
-
|
|
1567
|
-
|
|
1568
|
-
|
|
1569
|
-
|
|
1570
|
-
|
|
1571
|
-
|
|
1572
|
-
|
|
1573
|
-
|
|
1574
|
-
|
|
1575
|
-
|
|
1576
|
-
|
|
1577
|
-
|
|
1578
|
-
|
|
1579
|
-
|
|
1580
|
-
|
|
1581
|
-
|
|
1582
|
-
|
|
1583
|
-
|
|
1584
|
-
|
|
1585
|
-
|
|
1586
|
-
|
|
1587
|
-
|
|
1588
|
-
|
|
1589
|
-
|
|
1590
|
-
|
|
1591
|
-
|
|
1592
|
-
|
|
1593
|
-
|
|
1594
|
-
|
|
1595
|
-
|
|
1596
|
-
|
|
1597
|
-
|
|
1598
|
-
|
|
1599
|
-
|
|
1600
|
-
|
|
1601
|
-
|
|
1602
|
-
|
|
1603
|
-
|
|
1604
|
-
|
|
1605
|
-
|
|
1606
|
-
|
|
1607
|
-
|
|
1608
|
-
|
|
1609
|
-
|
|
1610
|
-
|
|
1611
|
-
|
|
1612
|
-
|
|
1613
|
-
|
|
1614
|
-
|
|
1615
|
-
|
|
1616
|
-
|
|
1617
|
-
|
|
1618
|
-
|
|
1619
|
-
|
|
1620
|
-
|
|
1621
|
-
|
|
1622
|
-
|
|
1623
|
-
|
|
1624
|
-
|
|
1625
|
-
|
|
1626
|
-
|
|
1627
|
-
|
|
1628
|
-
|
|
1629
|
-
|
|
1630
|
-
|
|
1631
|
-
|
|
1632
|
-
|
|
1633
|
-
|
|
1634
|
-
|
|
1635
|
-
|
|
1636
|
-
|
|
1637
|
-
|
|
1638
|
-
|
|
1639
|
-
|
|
1640
|
-
|
|
1641
|
-
|
|
1642
|
-
|
|
1643
|
-
|
|
1644
|
-
|
|
1645
|
-
|
|
1646
|
-
|
|
1647
|
-
|
|
1648
|
-
|
|
1649
|
-
|
|
1650
|
-
|
|
1651
|
-
|
|
1652
|
-
|
|
1653
|
-
|
|
1654
|
-
|
|
1655
|
-
|
|
1656
|
-
|
|
1657
|
-
|
|
1658
|
-
|
|
1659
|
-
|
|
1660
|
-
|
|
1661
|
-
|
|
1662
|
-
|
|
1663
|
-
|
|
1664
|
-
|
|
1665
|
-
}
|
|
1666
|
-
|
|
1667
|
-
|
|
1668
|
-
|
|
1669
|
-
|
|
1670
|
-
|
|
1671
|
-
|
|
1672
|
-
|
|
1673
|
-
|
|
1674
|
-
|
|
1675
|
-
|
|
1676
|
-
|
|
1677
|
-
|
|
1678
|
-
|
|
1679
|
-
|
|
1680
|
-
|
|
1681
|
-
|
|
1682
|
-
|
|
1683
|
-
|
|
1684
|
-
|
|
1685
|
-
|
|
1686
|
-
|
|
1687
|
-
|
|
1688
|
-
|
|
1689
|
-
|
|
1690
|
-
|
|
1691
|
-
|
|
1692
|
-
|
|
1693
|
-
|
|
1694
|
-
|
|
1695
|
-
|
|
1696
|
-
|
|
1697
|
-
|
|
1698
|
-
|
|
1699
|
-
|
|
1700
|
-
|
|
1701
|
-
|
|
1702
|
-
|
|
1703
|
-
|
|
1704
|
-
|
|
1705
|
-
|
|
1706
|
-
|
|
1707
|
-
|
|
1057
|
+
/* v8 ignore next */
|
|
1058
|
+
if (!row) {
|
|
1059
|
+
throw new Error(`Cannot find matching entity for condition ${JSON.stringify(cond)}`);
|
|
1060
|
+
}
|
|
1061
|
+
em.getHydrator().hydrate(entity, meta, row, em.#entityFactory, 'full', false, true);
|
|
1062
|
+
}
|
|
1063
|
+
if (loadPK.size !== data2.length && Array.isArray(uniqueFields)) {
|
|
1064
|
+
for (let i = 0; i < allData.length; i++) {
|
|
1065
|
+
const data = allData[i];
|
|
1066
|
+
const cond = uniqueFields.reduce((a, b) => {
|
|
1067
|
+
// @ts-ignore
|
|
1068
|
+
a[b] = data[b];
|
|
1069
|
+
return a;
|
|
1070
|
+
}, {});
|
|
1071
|
+
const entity = entitiesByData.get(data);
|
|
1072
|
+
const row = data2.find(item => {
|
|
1073
|
+
const pk = uniqueFields.reduce((a, b) => {
|
|
1074
|
+
// @ts-ignore
|
|
1075
|
+
a[b] = item[b];
|
|
1076
|
+
return a;
|
|
1077
|
+
}, {});
|
|
1078
|
+
return this.#comparator.matching(entityName, cond, pk);
|
|
1079
|
+
});
|
|
1080
|
+
/* v8 ignore next */
|
|
1081
|
+
if (!row) {
|
|
1082
|
+
throw new Error(`Cannot find matching entity for condition ${JSON.stringify(cond)}`);
|
|
1083
|
+
}
|
|
1084
|
+
em.getHydrator().hydrate(entity, meta, row, em.#entityFactory, 'full');
|
|
1085
|
+
}
|
|
1086
|
+
}
|
|
1087
|
+
}
|
|
1088
|
+
for (const [entity] of entities) {
|
|
1089
|
+
// recompute the data as there might be some values missing (e.g. those with db column defaults)
|
|
1090
|
+
const snapshot = this.#comparator.prepareEntity(entity);
|
|
1091
|
+
em.#unitOfWork.register(entity, snapshot, { refresh: true });
|
|
1092
|
+
}
|
|
1093
|
+
if (em.eventManager.hasListeners(EventType.afterUpsert, meta)) {
|
|
1094
|
+
for (const [entity] of entities) {
|
|
1095
|
+
await em.eventManager.dispatchEvent(EventType.afterUpsert, { entity, em, meta }, meta);
|
|
1096
|
+
}
|
|
1097
|
+
}
|
|
1098
|
+
return [...entities.keys()];
|
|
1099
|
+
}
|
|
1100
|
+
/**
|
|
1101
|
+
* Runs your callback wrapped inside a database transaction.
|
|
1102
|
+
*
|
|
1103
|
+
* If a transaction is already active, a new savepoint (nested transaction) will be created by default. This behavior
|
|
1104
|
+
* can be controlled via the `propagation` option. Use the provided EntityManager instance for all operations that
|
|
1105
|
+
* should be part of the transaction. You can safely use a global EntityManager instance from a DI container, as this
|
|
1106
|
+
* method automatically creates an async context for the transaction.
|
|
1107
|
+
*
|
|
1108
|
+
* **Concurrency note:** When running multiple transactions concurrently (e.g. in parallel requests or jobs), use the
|
|
1109
|
+
* `clear: true` option. This ensures the callback runs in a clear fork of the EntityManager, providing full isolation
|
|
1110
|
+
* between concurrent transactional handlers. Using `clear: true` is an alternative to forking explicitly and calling
|
|
1111
|
+
* the method on the new fork – it already provides the necessary isolation for safe concurrent usage.
|
|
1112
|
+
*
|
|
1113
|
+
* **Propagation note:** Changes made within a transaction (whether top-level or nested) are always propagated to the
|
|
1114
|
+
* parent context, unless the parent context is a global one. If you want to avoid that, fork the EntityManager first
|
|
1115
|
+
* and then call this method on the fork.
|
|
1116
|
+
*
|
|
1117
|
+
* **Example:**
|
|
1118
|
+
* ```ts
|
|
1119
|
+
* await em.transactional(async (em) => {
|
|
1120
|
+
* const author = new Author('Jon');
|
|
1121
|
+
* em.persist(author);
|
|
1122
|
+
* // flush is called automatically at the end of the callback
|
|
1123
|
+
* });
|
|
1124
|
+
* ```
|
|
1125
|
+
*/
|
|
1126
|
+
async transactional(cb, options = {}) {
|
|
1127
|
+
const em = this.getContext(false);
|
|
1128
|
+
if (this.#disableTransactions || em.#disableTransactions) {
|
|
1129
|
+
return cb(em);
|
|
1130
|
+
}
|
|
1131
|
+
const manager = new TransactionManager(this);
|
|
1132
|
+
return manager.handle(cb, options);
|
|
1133
|
+
}
|
|
1134
|
+
/**
|
|
1135
|
+
* Starts new transaction bound to this EntityManager. Use `ctx` parameter to provide the parent when nesting transactions.
|
|
1136
|
+
*/
|
|
1137
|
+
async begin(options = {}) {
|
|
1138
|
+
if (this.#disableTransactions) {
|
|
1139
|
+
return;
|
|
1140
|
+
}
|
|
1141
|
+
const em = this.getContext(false);
|
|
1142
|
+
em.#transactionContext = await em.getConnection('write').begin({
|
|
1143
|
+
...options,
|
|
1144
|
+
eventBroadcaster: new TransactionEventBroadcaster(em, { topLevelTransaction: !options.ctx }),
|
|
1145
|
+
});
|
|
1146
|
+
}
|
|
1147
|
+
/**
|
|
1148
|
+
* Commits the transaction bound to this EntityManager. Flushes before doing the actual commit query.
|
|
1149
|
+
*/
|
|
1150
|
+
async commit() {
|
|
1151
|
+
const em = this.getContext(false);
|
|
1152
|
+
if (this.#disableTransactions) {
|
|
1153
|
+
await em.flush();
|
|
1154
|
+
return;
|
|
1155
|
+
}
|
|
1156
|
+
if (!em.#transactionContext) {
|
|
1157
|
+
throw ValidationError.transactionRequired();
|
|
1158
|
+
}
|
|
1159
|
+
await em.flush();
|
|
1160
|
+
await em.getConnection('write').commit(em.#transactionContext, new TransactionEventBroadcaster(em));
|
|
1161
|
+
em.#transactionContext = undefined;
|
|
1162
|
+
}
|
|
1163
|
+
/**
|
|
1164
|
+
* Rollbacks the transaction bound to this EntityManager.
|
|
1165
|
+
*/
|
|
1166
|
+
async rollback() {
|
|
1167
|
+
if (this.#disableTransactions) {
|
|
1168
|
+
return;
|
|
1169
|
+
}
|
|
1170
|
+
const em = this.getContext(false);
|
|
1171
|
+
if (!em.#transactionContext) {
|
|
1172
|
+
throw ValidationError.transactionRequired();
|
|
1173
|
+
}
|
|
1174
|
+
await em.getConnection('write').rollback(em.#transactionContext, new TransactionEventBroadcaster(em));
|
|
1175
|
+
em.#transactionContext = undefined;
|
|
1176
|
+
em.#unitOfWork.clearActionsQueue();
|
|
1177
|
+
}
|
|
1178
|
+
/**
|
|
1179
|
+
* Runs your callback wrapped inside a database transaction.
|
|
1180
|
+
*/
|
|
1181
|
+
async lock(entity, lockMode, options = {}) {
|
|
1182
|
+
options = Utils.isPlainObject(options) ? options : { lockVersion: options };
|
|
1183
|
+
await this.getUnitOfWork().lock(entity, { lockMode, ...options });
|
|
1184
|
+
}
|
|
1185
|
+
/**
|
|
1186
|
+
* Fires native insert query. Calling this has no side effects on the context (identity map).
|
|
1187
|
+
*/
|
|
1188
|
+
async insert(entityNameOrEntity, data, options = {}) {
|
|
1189
|
+
const em = this.getContext(false);
|
|
1190
|
+
em.prepareOptions(options);
|
|
1191
|
+
let entityName;
|
|
1192
|
+
if (data === undefined) {
|
|
1193
|
+
entityName = entityNameOrEntity.constructor;
|
|
1194
|
+
data = entityNameOrEntity;
|
|
1195
|
+
} else {
|
|
1196
|
+
entityName = entityNameOrEntity;
|
|
1197
|
+
}
|
|
1198
|
+
if (Utils.isEntity(data)) {
|
|
1199
|
+
if (options.schema && helper(data).getSchema() == null) {
|
|
1200
|
+
helper(data).setSchema(options.schema);
|
|
1201
|
+
}
|
|
1202
|
+
if (!helper(data).__managed) {
|
|
1203
|
+
// the entity might have been created via `em.create()`, which adds it to the persist stack automatically
|
|
1204
|
+
em.#unitOfWork.getPersistStack().delete(data);
|
|
1205
|
+
// it can be also in the identity map if it had a PK value already
|
|
1206
|
+
em.#unitOfWork.unsetIdentity(data);
|
|
1207
|
+
}
|
|
1208
|
+
const meta = helper(data).__meta;
|
|
1209
|
+
const payload = em.#comparator.prepareEntity(data);
|
|
1210
|
+
const cs = new ChangeSet(data, ChangeSetType.CREATE, payload, meta);
|
|
1211
|
+
await em.#unitOfWork.getChangeSetPersister().executeInserts([cs], { ctx: em.#transactionContext, ...options });
|
|
1212
|
+
return cs.getPrimaryKey();
|
|
1213
|
+
}
|
|
1214
|
+
data = QueryHelper.processObjectParams(data);
|
|
1215
|
+
validateParams(data, 'insert data');
|
|
1216
|
+
const res = await em.driver.nativeInsert(entityName, data, {
|
|
1217
|
+
ctx: em.#transactionContext,
|
|
1218
|
+
...options,
|
|
1219
|
+
});
|
|
1220
|
+
return res.insertId;
|
|
1221
|
+
}
|
|
1222
|
+
/**
|
|
1223
|
+
* Fires native multi-insert query. Calling this has no side effects on the context (identity map).
|
|
1224
|
+
*/
|
|
1225
|
+
async insertMany(entityNameOrEntities, data, options = {}) {
|
|
1226
|
+
const em = this.getContext(false);
|
|
1227
|
+
em.prepareOptions(options);
|
|
1228
|
+
let entityName;
|
|
1229
|
+
if (data === undefined) {
|
|
1230
|
+
entityName = entityNameOrEntities[0].constructor;
|
|
1231
|
+
data = entityNameOrEntities;
|
|
1232
|
+
} else {
|
|
1233
|
+
entityName = entityNameOrEntities;
|
|
1234
|
+
}
|
|
1235
|
+
if (data.length === 0) {
|
|
1236
|
+
return [];
|
|
1237
|
+
}
|
|
1238
|
+
if (Utils.isEntity(data[0])) {
|
|
1239
|
+
const meta = helper(data[0]).__meta;
|
|
1240
|
+
const css = data.map(row => {
|
|
1241
|
+
if (options.schema && helper(row).getSchema() == null) {
|
|
1242
|
+
helper(row).setSchema(options.schema);
|
|
1243
|
+
}
|
|
1244
|
+
if (!helper(row).__managed) {
|
|
1245
|
+
// the entity might have been created via `em.create()`, which adds it to the persist stack automatically
|
|
1246
|
+
em.#unitOfWork.getPersistStack().delete(row);
|
|
1247
|
+
// it can be also in the identity map if it had a PK value already
|
|
1248
|
+
em.#unitOfWork.unsetIdentity(row);
|
|
1249
|
+
}
|
|
1250
|
+
const payload = em.#comparator.prepareEntity(row);
|
|
1251
|
+
return new ChangeSet(row, ChangeSetType.CREATE, payload, meta);
|
|
1252
|
+
});
|
|
1253
|
+
await em.#unitOfWork.getChangeSetPersister().executeInserts(css, { ctx: em.#transactionContext, ...options });
|
|
1254
|
+
return css.map(cs => cs.getPrimaryKey());
|
|
1255
|
+
}
|
|
1256
|
+
data = data.map(row => QueryHelper.processObjectParams(row));
|
|
1257
|
+
data.forEach(row => validateParams(row, 'insert data'));
|
|
1258
|
+
const res = await em.driver.nativeInsertMany(entityName, data, {
|
|
1259
|
+
ctx: em.#transactionContext,
|
|
1260
|
+
...options,
|
|
1261
|
+
});
|
|
1262
|
+
if (res.insertedIds) {
|
|
1263
|
+
return res.insertedIds;
|
|
1264
|
+
}
|
|
1265
|
+
return [res.insertId];
|
|
1266
|
+
}
|
|
1267
|
+
/**
|
|
1268
|
+
* Fires native update query. Calling this has no side effects on the context (identity map).
|
|
1269
|
+
*/
|
|
1270
|
+
async nativeUpdate(entityName, where, data, options = {}) {
|
|
1271
|
+
const em = this.getContext(false);
|
|
1272
|
+
em.prepareOptions(options);
|
|
1273
|
+
await em.processUnionWhere(entityName, options, 'update');
|
|
1274
|
+
data = QueryHelper.processObjectParams(data);
|
|
1275
|
+
where = await em.processWhere(entityName, where, { ...options, convertCustomTypes: false }, 'update');
|
|
1276
|
+
validateParams(data, 'update data');
|
|
1277
|
+
validateParams(where, 'update condition');
|
|
1278
|
+
const res = await em.driver.nativeUpdate(entityName, where, data, {
|
|
1279
|
+
ctx: em.#transactionContext,
|
|
1280
|
+
em,
|
|
1281
|
+
...options,
|
|
1282
|
+
});
|
|
1283
|
+
return res.affectedRows;
|
|
1284
|
+
}
|
|
1285
|
+
/**
|
|
1286
|
+
* Fires native delete query. Calling this has no side effects on the context (identity map).
|
|
1287
|
+
*/
|
|
1288
|
+
async nativeDelete(entityName, where, options = {}) {
|
|
1289
|
+
const em = this.getContext(false);
|
|
1290
|
+
em.prepareOptions(options);
|
|
1291
|
+
await em.processUnionWhere(entityName, options, 'delete');
|
|
1292
|
+
where = await em.processWhere(entityName, where, options, 'delete');
|
|
1293
|
+
validateParams(where, 'delete condition');
|
|
1294
|
+
const res = await em.driver.nativeDelete(entityName, where, {
|
|
1295
|
+
ctx: em.#transactionContext,
|
|
1296
|
+
em,
|
|
1297
|
+
...options,
|
|
1298
|
+
});
|
|
1299
|
+
return res.affectedRows;
|
|
1300
|
+
}
|
|
1301
|
+
/**
|
|
1302
|
+
* Maps raw database result to an entity and merges it to this EntityManager.
|
|
1303
|
+
*/
|
|
1304
|
+
map(entityName, result, options = {}) {
|
|
1305
|
+
const meta = this.metadata.get(entityName);
|
|
1306
|
+
const data = this.driver.mapResult(result, meta);
|
|
1307
|
+
for (const k of Object.keys(data)) {
|
|
1308
|
+
const prop = meta.properties[k];
|
|
1309
|
+
if (
|
|
1310
|
+
prop?.kind === ReferenceKind.SCALAR &&
|
|
1311
|
+
SCALAR_TYPES.has(prop.runtimeType) &&
|
|
1312
|
+
!prop.customType &&
|
|
1313
|
+
(prop.setter || !prop.getter)
|
|
1314
|
+
) {
|
|
1315
|
+
validateProperty(prop, data[k], data);
|
|
1316
|
+
}
|
|
1317
|
+
}
|
|
1318
|
+
return this.merge(entityName, data, {
|
|
1319
|
+
convertCustomTypes: true,
|
|
1320
|
+
refresh: true,
|
|
1321
|
+
validate: false,
|
|
1322
|
+
...options,
|
|
1323
|
+
});
|
|
1324
|
+
}
|
|
1325
|
+
/**
|
|
1326
|
+
* Merges given entity to this EntityManager so it becomes managed. You can force refreshing of existing entities
|
|
1327
|
+
* via second parameter. By default, it will return already loaded entities without modifying them.
|
|
1328
|
+
*/
|
|
1329
|
+
merge(entityName, data, options = {}) {
|
|
1330
|
+
if (Utils.isEntity(entityName)) {
|
|
1331
|
+
return this.merge(entityName.constructor, entityName, data);
|
|
1332
|
+
}
|
|
1333
|
+
const em = options.disableContextResolution ? this : this.getContext();
|
|
1334
|
+
options.schema ??= em.#schema;
|
|
1335
|
+
options.validate ??= true;
|
|
1336
|
+
options.cascade ??= true;
|
|
1337
|
+
validatePrimaryKey(data, em.metadata.get(entityName));
|
|
1338
|
+
let entity = em.#unitOfWork.tryGetById(entityName, data, options.schema, false);
|
|
1339
|
+
if (entity && helper(entity).__managed && helper(entity).__initialized && !options.refresh) {
|
|
1340
|
+
return entity;
|
|
1341
|
+
}
|
|
1342
|
+
const dataIsEntity = Utils.isEntity(data);
|
|
1343
|
+
entity = dataIsEntity ? data : em.#entityFactory.create(entityName, data, { merge: true, ...options });
|
|
1344
|
+
const visited = options.cascade ? undefined : new Set([entity]);
|
|
1345
|
+
em.#unitOfWork.merge(entity, visited);
|
|
1346
|
+
return entity;
|
|
1347
|
+
}
|
|
1348
|
+
/**
|
|
1349
|
+
* Creates new instance of given entity and populates it with given data.
|
|
1350
|
+
* The entity constructor will be used unless you provide `{ managed: true }` in the `options` parameter.
|
|
1351
|
+
* The constructor will be given parameters based on the defined constructor of the entity. If the constructor
|
|
1352
|
+
* parameter matches a property name, its value will be extracted from `data`. If no matching property exists,
|
|
1353
|
+
* the whole `data` parameter will be passed. This means we can also define `constructor(data: Partial<T>)` and
|
|
1354
|
+
* `em.create()` will pass the data into it (unless we have a property named `data` too).
|
|
1355
|
+
*
|
|
1356
|
+
* The parameters are strictly checked, you need to provide all required properties. You can use `OptionalProps`
|
|
1357
|
+
* symbol to omit some properties from this check without making them optional. Alternatively, use `partial: true`
|
|
1358
|
+
* in the options to disable the strict checks for required properties. This option has no effect on runtime.
|
|
1359
|
+
*
|
|
1360
|
+
* The newly created entity will be automatically marked for persistence via `em.persist` unless you disable this
|
|
1361
|
+
* behavior, either locally via `persist: false` option, or globally via `persistOnCreate` ORM config option.
|
|
1362
|
+
*/
|
|
1363
|
+
create(entityName, data, options = {}) {
|
|
1364
|
+
const em = this.getContext();
|
|
1365
|
+
options.schema ??= em.#schema;
|
|
1366
|
+
const entity = em.#entityFactory.create(entityName, data, {
|
|
1367
|
+
...options,
|
|
1368
|
+
newEntity: !options.managed,
|
|
1369
|
+
merge: options.managed,
|
|
1370
|
+
normalizeAccessors: true,
|
|
1371
|
+
});
|
|
1372
|
+
options.persist ??= em.config.get('persistOnCreate');
|
|
1373
|
+
if (options.persist && !this.getMetadata(entityName).embeddable) {
|
|
1374
|
+
em.persist(entity);
|
|
1375
|
+
}
|
|
1376
|
+
return entity;
|
|
1377
|
+
}
|
|
1378
|
+
/**
|
|
1379
|
+
* Shortcut for `wrap(entity).assign(data, { em })`
|
|
1380
|
+
*/
|
|
1381
|
+
assign(entity, data, options = {}) {
|
|
1382
|
+
return EntityAssigner.assign(entity, data, { em: this.getContext(), ...options });
|
|
1383
|
+
}
|
|
1384
|
+
/**
|
|
1385
|
+
* Gets a reference to the entity identified by the given type and identifier without actually loading it, if the entity is not yet loaded
|
|
1386
|
+
*/
|
|
1387
|
+
getReference(entityName, id, options = {}) {
|
|
1388
|
+
options.schema ??= this.schema;
|
|
1389
|
+
options.convertCustomTypes ??= false;
|
|
1390
|
+
const meta = this.metadata.get(entityName);
|
|
1391
|
+
if (Utils.isPrimaryKey(id)) {
|
|
1392
|
+
if (meta.compositePK) {
|
|
1393
|
+
throw ValidationError.invalidCompositeIdentifier(meta);
|
|
1394
|
+
}
|
|
1395
|
+
id = [id];
|
|
1396
|
+
}
|
|
1397
|
+
const entity = this.getEntityFactory().createReference(entityName, id, { merge: true, ...options });
|
|
1398
|
+
if (options.wrapped) {
|
|
1399
|
+
return Reference.create(entity);
|
|
1400
|
+
}
|
|
1401
|
+
return entity;
|
|
1402
|
+
}
|
|
1403
|
+
/**
|
|
1404
|
+
* Returns total number of entities matching your `where` query.
|
|
1405
|
+
*/
|
|
1406
|
+
async count(entityName, where = {}, options = {}) {
|
|
1407
|
+
const em = this.getContext(false);
|
|
1408
|
+
// Shallow copy options since the object will be modified when deleting orderBy
|
|
1409
|
+
options = { ...options };
|
|
1410
|
+
em.prepareOptions(options);
|
|
1411
|
+
await em.tryFlush(entityName, options);
|
|
1412
|
+
where = await em.processWhere(entityName, where, options, 'read');
|
|
1413
|
+
options.populate = await em.preparePopulate(entityName, options);
|
|
1414
|
+
options = { ...options };
|
|
1415
|
+
// save the original hint value so we know it was infer/all
|
|
1416
|
+
const meta = em.metadata.find(entityName);
|
|
1417
|
+
options._populateWhere = options.populateWhere ?? this.config.get('populateWhere');
|
|
1418
|
+
options.populateWhere = this.createPopulateWhere({ ...where }, options);
|
|
1419
|
+
options.populateFilter = await this.getJoinedFilters(meta, options);
|
|
1420
|
+
validateParams(where);
|
|
1421
|
+
delete options.orderBy;
|
|
1422
|
+
await em.processUnionWhere(entityName, options, 'read');
|
|
1423
|
+
const cacheKey = em.cacheKey(entityName, options, 'em.count', where);
|
|
1424
|
+
const cached = await em.tryCache(entityName, options.cache, cacheKey);
|
|
1425
|
+
if (cached?.data !== undefined) {
|
|
1426
|
+
return cached.data;
|
|
1427
|
+
}
|
|
1428
|
+
const count = await em.driver.count(entityName, where, { ctx: em.#transactionContext, em, ...options });
|
|
1429
|
+
await em.storeCache(options.cache, cached, () => +count);
|
|
1430
|
+
return +count;
|
|
1431
|
+
}
|
|
1432
|
+
/**
|
|
1433
|
+
* Tells the EntityManager to make an instance managed and persistent.
|
|
1434
|
+
* The entity will be entered into the database at or before transaction commit or as a result of the flush operation.
|
|
1435
|
+
*/
|
|
1436
|
+
persist(entity) {
|
|
1437
|
+
const em = this.getContext();
|
|
1438
|
+
if (Utils.isEntity(entity)) {
|
|
1439
|
+
// do not cascade just yet, cascading of entities in persist stack is done when flushing
|
|
1440
|
+
em.#unitOfWork.persist(entity, undefined, { cascade: false });
|
|
1441
|
+
return em;
|
|
1442
|
+
}
|
|
1443
|
+
const entities = Utils.asArray(entity);
|
|
1444
|
+
for (const ent of entities) {
|
|
1445
|
+
if (!Utils.isEntity(ent, true)) {
|
|
1446
|
+
/* v8 ignore next */
|
|
1447
|
+
const meta = typeof ent === 'object' ? em.metadata.find(ent.constructor) : undefined;
|
|
1448
|
+
throw ValidationError.notDiscoveredEntity(ent, meta);
|
|
1449
|
+
}
|
|
1450
|
+
// do not cascade just yet, cascading of entities in persist stack is done when flushing
|
|
1451
|
+
em.#unitOfWork.persist(Reference.unwrapReference(ent), undefined, { cascade: false });
|
|
1452
|
+
}
|
|
1453
|
+
return this;
|
|
1454
|
+
}
|
|
1455
|
+
/**
|
|
1456
|
+
* Marks entity for removal.
|
|
1457
|
+
* A removed entity will be removed from the database at or before transaction commit or as a result of the flush operation.
|
|
1458
|
+
*
|
|
1459
|
+
* To remove entities by condition, use `em.nativeDelete()`.
|
|
1460
|
+
*/
|
|
1461
|
+
remove(entity) {
|
|
1462
|
+
const em = this.getContext();
|
|
1463
|
+
if (Utils.isEntity(entity)) {
|
|
1464
|
+
// do not cascade just yet, cascading of entities in persist stack is done when flushing
|
|
1465
|
+
em.#unitOfWork.remove(entity, undefined, { cascade: false });
|
|
1466
|
+
return em;
|
|
1467
|
+
}
|
|
1468
|
+
const entities = Utils.asArray(entity, true);
|
|
1469
|
+
for (const ent of entities) {
|
|
1470
|
+
if (!Utils.isEntity(ent, true)) {
|
|
1471
|
+
throw new Error(
|
|
1472
|
+
`You need to pass entity instance or reference to 'em.remove()'. To remove entities by condition, use 'em.nativeDelete()'.`,
|
|
1473
|
+
);
|
|
1474
|
+
}
|
|
1475
|
+
// do not cascade just yet, cascading of entities in remove stack is done when flushing
|
|
1476
|
+
em.#unitOfWork.remove(Reference.unwrapReference(ent), undefined, { cascade: false });
|
|
1477
|
+
}
|
|
1478
|
+
return em;
|
|
1479
|
+
}
|
|
1480
|
+
/**
|
|
1481
|
+
* Flushes all changes to objects that have been queued up to now to the database.
|
|
1482
|
+
* This effectively synchronizes the in-memory state of managed objects with the database.
|
|
1483
|
+
*/
|
|
1484
|
+
async flush() {
|
|
1485
|
+
await this.getUnitOfWork().commit();
|
|
1486
|
+
}
|
|
1487
|
+
/**
|
|
1488
|
+
* @internal
|
|
1489
|
+
*/
|
|
1490
|
+
async tryFlush(entityName, options) {
|
|
1491
|
+
const em = this.getContext();
|
|
1492
|
+
const flushMode = options.flushMode ?? em.#flushMode ?? em.config.get('flushMode');
|
|
1493
|
+
const meta = em.metadata.get(entityName);
|
|
1494
|
+
if (flushMode === FlushMode.COMMIT) {
|
|
1495
|
+
return;
|
|
1496
|
+
}
|
|
1497
|
+
if (flushMode === FlushMode.ALWAYS || em.getUnitOfWork().shouldAutoFlush(meta)) {
|
|
1498
|
+
await em.flush();
|
|
1499
|
+
}
|
|
1500
|
+
}
|
|
1501
|
+
/**
|
|
1502
|
+
* Clears the EntityManager. All entities that are currently managed by this EntityManager become detached.
|
|
1503
|
+
*/
|
|
1504
|
+
clear() {
|
|
1505
|
+
this.getContext().#unitOfWork.clear();
|
|
1506
|
+
}
|
|
1507
|
+
/**
|
|
1508
|
+
* Checks whether given property can be populated on the entity.
|
|
1509
|
+
*/
|
|
1510
|
+
canPopulate(entityName, property) {
|
|
1511
|
+
// eslint-disable-next-line prefer-const
|
|
1512
|
+
let [p, ...parts] = property.split('.');
|
|
1513
|
+
const meta = this.metadata.find(entityName);
|
|
1514
|
+
if (!meta) {
|
|
1515
|
+
return true;
|
|
1516
|
+
}
|
|
1517
|
+
if (p.includes(':')) {
|
|
1518
|
+
p = p.split(':', 2)[0];
|
|
1519
|
+
}
|
|
1520
|
+
// For TPT inheritance, check the entity's own properties, not just the root's
|
|
1521
|
+
// For STI, meta.properties includes all properties anyway
|
|
1522
|
+
const ret = p in meta.properties;
|
|
1523
|
+
if (parts.length > 0) {
|
|
1524
|
+
return this.canPopulate(meta.properties[p].targetMeta.class, parts.join('.'));
|
|
1525
|
+
}
|
|
1526
|
+
return ret;
|
|
1527
|
+
}
|
|
1528
|
+
/**
|
|
1529
|
+
* Loads specified relations in batch. This will execute one query for each relation, that will populate it on all the specified entities.
|
|
1530
|
+
*/
|
|
1531
|
+
async populate(entities, populate, options = {}) {
|
|
1532
|
+
const arr = Utils.asArray(entities);
|
|
1533
|
+
if (arr.length === 0) {
|
|
1534
|
+
return entities;
|
|
1535
|
+
}
|
|
1536
|
+
const em = this.getContext();
|
|
1537
|
+
em.prepareOptions(options);
|
|
1538
|
+
const entityName = arr[0].constructor;
|
|
1539
|
+
const preparedPopulate = await em.preparePopulate(
|
|
1540
|
+
entityName,
|
|
1541
|
+
{ populate: populate, filters: options.filters },
|
|
1542
|
+
options.validate,
|
|
1543
|
+
);
|
|
1544
|
+
await em.#entityLoader.populate(entityName, arr, preparedPopulate, options);
|
|
1545
|
+
return entities;
|
|
1546
|
+
}
|
|
1547
|
+
/**
|
|
1548
|
+
* Returns new EntityManager instance with its own identity map
|
|
1549
|
+
*/
|
|
1550
|
+
fork(options = {}) {
|
|
1551
|
+
const em = options.disableContextResolution ? this : this.getContext(false);
|
|
1552
|
+
options.clear ??= true;
|
|
1553
|
+
options.useContext ??= false;
|
|
1554
|
+
options.freshEventManager ??= false;
|
|
1555
|
+
options.cloneEventManager ??= false;
|
|
1556
|
+
const eventManager = options.freshEventManager
|
|
1557
|
+
? new EventManager(em.config.get('subscribers'))
|
|
1558
|
+
: options.cloneEventManager
|
|
1559
|
+
? em.eventManager.clone()
|
|
1560
|
+
: em.eventManager;
|
|
1561
|
+
// we need to allow global context here as forking from global EM is fine
|
|
1562
|
+
const allowGlobalContext = em.config.get('allowGlobalContext');
|
|
1563
|
+
em.config.set('allowGlobalContext', true);
|
|
1564
|
+
const fork = new em.constructor(em.config, em.driver, em.metadata, options.useContext, eventManager);
|
|
1565
|
+
fork.setFlushMode(options.flushMode ?? em.#flushMode);
|
|
1566
|
+
fork.#disableTransactions =
|
|
1567
|
+
options.disableTransactions ?? this.#disableTransactions ?? this.config.get('disableTransactions');
|
|
1568
|
+
em.config.set('allowGlobalContext', allowGlobalContext);
|
|
1569
|
+
if (options.keepTransactionContext) {
|
|
1570
|
+
fork.#transactionContext = em.#transactionContext;
|
|
1571
|
+
}
|
|
1572
|
+
fork.#filters = { ...em.#filters };
|
|
1573
|
+
fork.#filterParams = Utils.copy(em.#filterParams);
|
|
1574
|
+
fork.loggerContext = Utils.merge({}, em.loggerContext, options.loggerContext);
|
|
1575
|
+
fork.#schema = options.schema ?? em.#schema;
|
|
1576
|
+
if (!options.clear) {
|
|
1577
|
+
for (const entity of em.#unitOfWork.getIdentityMap()) {
|
|
1578
|
+
fork.#unitOfWork.register(entity);
|
|
1579
|
+
}
|
|
1580
|
+
for (const entity of em.#unitOfWork.getPersistStack()) {
|
|
1581
|
+
fork.#unitOfWork.persist(entity);
|
|
1582
|
+
}
|
|
1583
|
+
for (const entity of em.#unitOfWork.getOrphanRemoveStack()) {
|
|
1584
|
+
fork.#unitOfWork.getOrphanRemoveStack().add(entity);
|
|
1585
|
+
}
|
|
1586
|
+
}
|
|
1587
|
+
return fork;
|
|
1588
|
+
}
|
|
1589
|
+
/**
|
|
1590
|
+
* Gets the UnitOfWork used by the EntityManager to coordinate operations.
|
|
1591
|
+
*/
|
|
1592
|
+
getUnitOfWork(useContext = true) {
|
|
1593
|
+
if (!useContext) {
|
|
1594
|
+
return this.#unitOfWork;
|
|
1595
|
+
}
|
|
1596
|
+
return this.getContext().#unitOfWork;
|
|
1597
|
+
}
|
|
1598
|
+
/**
|
|
1599
|
+
* Gets the EntityFactory used by the EntityManager.
|
|
1600
|
+
*/
|
|
1601
|
+
getEntityFactory() {
|
|
1602
|
+
return this.getContext().#entityFactory;
|
|
1603
|
+
}
|
|
1604
|
+
/**
|
|
1605
|
+
* @internal use `em.populate()` as the user facing API, this is exposed only for internal usage
|
|
1606
|
+
*/
|
|
1607
|
+
getEntityLoader() {
|
|
1608
|
+
return this.getContext().#entityLoader;
|
|
1609
|
+
}
|
|
1610
|
+
/**
|
|
1611
|
+
* Gets the Hydrator used by the EntityManager.
|
|
1612
|
+
*/
|
|
1613
|
+
getHydrator() {
|
|
1614
|
+
return this.config.getHydrator(this.getMetadata());
|
|
1615
|
+
}
|
|
1616
|
+
/**
|
|
1617
|
+
* Gets the EntityManager based on current transaction/request context.
|
|
1618
|
+
* @internal
|
|
1619
|
+
*/
|
|
1620
|
+
getContext(validate = true) {
|
|
1621
|
+
if (!this.#useContext) {
|
|
1622
|
+
return this;
|
|
1623
|
+
}
|
|
1624
|
+
let em = TransactionContext.getEntityManager(this.name); // prefer the tx context
|
|
1625
|
+
if (em) {
|
|
1626
|
+
return em;
|
|
1627
|
+
}
|
|
1628
|
+
// no explicit tx started
|
|
1629
|
+
em = this.config.get('context')(this.name) ?? this;
|
|
1630
|
+
if (validate && !this.config.get('allowGlobalContext') && em.global) {
|
|
1631
|
+
throw ValidationError.cannotUseGlobalContext();
|
|
1632
|
+
}
|
|
1633
|
+
return em;
|
|
1634
|
+
}
|
|
1635
|
+
/** Gets the EventManager instance used by this EntityManager. */
|
|
1636
|
+
getEventManager() {
|
|
1637
|
+
return this.eventManager;
|
|
1638
|
+
}
|
|
1639
|
+
/**
|
|
1640
|
+
* Checks whether this EntityManager is currently operating inside a database transaction.
|
|
1641
|
+
*/
|
|
1642
|
+
isInTransaction() {
|
|
1643
|
+
return !!this.getContext(false).#transactionContext;
|
|
1644
|
+
}
|
|
1645
|
+
/**
|
|
1646
|
+
* Gets the transaction context (driver dependent object used to make sure queries are executed on same connection).
|
|
1647
|
+
*/
|
|
1648
|
+
getTransactionContext() {
|
|
1649
|
+
return this.getContext(false).#transactionContext;
|
|
1650
|
+
}
|
|
1651
|
+
/**
|
|
1652
|
+
* Sets the transaction context.
|
|
1653
|
+
*/
|
|
1654
|
+
setTransactionContext(ctx) {
|
|
1655
|
+
if (!ctx) {
|
|
1656
|
+
this.resetTransactionContext();
|
|
1657
|
+
} else {
|
|
1658
|
+
this.getContext(false).#transactionContext = ctx;
|
|
1659
|
+
}
|
|
1660
|
+
}
|
|
1661
|
+
/**
|
|
1662
|
+
* Resets the transaction context.
|
|
1663
|
+
*/
|
|
1664
|
+
resetTransactionContext() {
|
|
1665
|
+
this.getContext(false).#transactionContext = undefined;
|
|
1666
|
+
}
|
|
1667
|
+
/**
|
|
1668
|
+
* Gets the `MetadataStorage` (without parameters) or `EntityMetadata` instance when provided with the `entityName` parameter.
|
|
1669
|
+
*/
|
|
1670
|
+
getMetadata(entityName) {
|
|
1671
|
+
if (entityName) {
|
|
1672
|
+
return this.metadata.get(entityName);
|
|
1673
|
+
}
|
|
1674
|
+
return this.metadata;
|
|
1675
|
+
}
|
|
1676
|
+
/**
|
|
1677
|
+
* Gets the EntityComparator.
|
|
1678
|
+
*/
|
|
1679
|
+
getComparator() {
|
|
1680
|
+
return this.#comparator;
|
|
1681
|
+
}
|
|
1682
|
+
checkLockRequirements(mode, meta) {
|
|
1683
|
+
if (!mode) {
|
|
1684
|
+
return;
|
|
1685
|
+
}
|
|
1686
|
+
if (mode === LockMode.OPTIMISTIC && !meta.versionProperty) {
|
|
1687
|
+
throw OptimisticLockError.notVersioned(meta);
|
|
1688
|
+
}
|
|
1689
|
+
if ([LockMode.PESSIMISTIC_READ, LockMode.PESSIMISTIC_WRITE].includes(mode) && !this.isInTransaction()) {
|
|
1690
|
+
throw ValidationError.transactionRequired();
|
|
1691
|
+
}
|
|
1692
|
+
}
|
|
1693
|
+
async lockAndPopulate(meta, entity, where, options) {
|
|
1694
|
+
if (!meta.virtual && options.lockMode === LockMode.OPTIMISTIC) {
|
|
1695
|
+
await this.lock(entity, options.lockMode, {
|
|
1696
|
+
lockVersion: options.lockVersion,
|
|
1697
|
+
lockTableAliases: options.lockTableAliases,
|
|
1698
|
+
});
|
|
1699
|
+
}
|
|
1700
|
+
const preparedPopulate = await this.preparePopulate(meta.class, options);
|
|
1701
|
+
await this.#entityLoader.populate(meta.class, [entity], preparedPopulate, {
|
|
1702
|
+
...options,
|
|
1703
|
+
...this.getPopulateWhere(where, options),
|
|
1704
|
+
orderBy: options.populateOrderBy ?? options.orderBy,
|
|
1705
|
+
ignoreLazyScalarProperties: true,
|
|
1706
|
+
lookup: false,
|
|
1707
|
+
});
|
|
1708
|
+
return entity;
|
|
1709
|
+
}
|
|
1710
|
+
buildFields(fields) {
|
|
1711
|
+
return fields.reduce((ret, f) => {
|
|
1712
|
+
if (Utils.isPlainObject(f)) {
|
|
1713
|
+
Utils.keys(f).forEach(ff => ret.push(...this.buildFields(f[ff]).map(field => `${ff}.${field}`)));
|
|
1714
|
+
} else {
|
|
1715
|
+
ret.push(f);
|
|
1716
|
+
}
|
|
1717
|
+
return ret;
|
|
1718
|
+
}, []);
|
|
1719
|
+
}
|
|
1720
|
+
/** @internal */
|
|
1721
|
+
async preparePopulate(entityName, options, validate = true) {
|
|
1722
|
+
if (options.populate === false) {
|
|
1723
|
+
return [];
|
|
1724
|
+
}
|
|
1725
|
+
const meta = this.metadata.find(entityName);
|
|
1726
|
+
// infer populate hint if only `fields` are available
|
|
1727
|
+
if (!options.populate && options.fields) {
|
|
1728
|
+
// we need to prune the `populate` hint from to-one relations, as partially loading them does not require their population, we want just the FK
|
|
1729
|
+
const pruneToOneRelations = (meta, fields) => {
|
|
1730
|
+
const ret = [];
|
|
1731
|
+
for (let field of fields) {
|
|
1732
|
+
if (field === PopulatePath.ALL || field.startsWith(`${PopulatePath.ALL}.`)) {
|
|
1733
|
+
ret.push(
|
|
1734
|
+
...meta.props
|
|
1735
|
+
.filter(prop => prop.lazy || [ReferenceKind.SCALAR, ReferenceKind.EMBEDDED].includes(prop.kind))
|
|
1736
|
+
.map(prop => prop.name),
|
|
1737
|
+
);
|
|
1738
|
+
continue;
|
|
1739
|
+
}
|
|
1740
|
+
field = field.split(':')[0];
|
|
1741
|
+
if (
|
|
1742
|
+
!field.includes('.') &&
|
|
1743
|
+
![ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(meta.properties[field].kind)
|
|
1744
|
+
) {
|
|
1745
|
+
ret.push(field);
|
|
1746
|
+
continue;
|
|
1747
|
+
}
|
|
1748
|
+
const parts = field.split('.');
|
|
1749
|
+
const key = parts.shift();
|
|
1750
|
+
if (parts.length === 0) {
|
|
1751
|
+
continue;
|
|
1752
|
+
}
|
|
1753
|
+
const prop = meta.properties[key];
|
|
1754
|
+
if (!prop.targetMeta) {
|
|
1755
|
+
ret.push(key);
|
|
1756
|
+
continue;
|
|
1757
|
+
}
|
|
1758
|
+
const inner = pruneToOneRelations(prop.targetMeta, [parts.join('.')]);
|
|
1759
|
+
if (inner.length > 0) {
|
|
1760
|
+
ret.push(...inner.map(c => `${key}.${c}`));
|
|
1761
|
+
}
|
|
1762
|
+
}
|
|
1763
|
+
return Utils.unique(ret);
|
|
1764
|
+
};
|
|
1765
|
+
options.populate = pruneToOneRelations(meta, this.buildFields(options.fields));
|
|
1766
|
+
}
|
|
1767
|
+
if (!options.populate) {
|
|
1768
|
+
const populate = this.#entityLoader.normalizePopulate(entityName, [], options.strategy, true, options.exclude);
|
|
1769
|
+
await this.autoJoinRefsForFilters(meta, { ...options, populate });
|
|
1770
|
+
return populate;
|
|
1771
|
+
}
|
|
1772
|
+
if (typeof options.populate !== 'boolean') {
|
|
1773
|
+
options.populate = Utils.asArray(options.populate)
|
|
1774
|
+
.map(field => {
|
|
1775
|
+
/* v8 ignore next */
|
|
1776
|
+
if (typeof field === 'boolean' || field === PopulatePath.ALL) {
|
|
1777
|
+
return [{ field: meta.primaryKeys[0], strategy: options.strategy, all: !!field }]; //
|
|
1778
|
+
}
|
|
1779
|
+
// will be handled in QueryBuilder when processing the where condition via CriteriaNode
|
|
1780
|
+
if (field === PopulatePath.INFER) {
|
|
1781
|
+
options.flags ??= [];
|
|
1782
|
+
options.flags.push(QueryFlag.INFER_POPULATE);
|
|
1708
1783
|
return [];
|
|
1709
|
-
|
|
1710
|
-
|
|
1711
|
-
|
|
1712
|
-
|
|
1713
|
-
|
|
1714
|
-
|
|
1715
|
-
|
|
1716
|
-
|
|
1717
|
-
|
|
1718
|
-
|
|
1719
|
-
|
|
1720
|
-
|
|
1721
|
-
|
|
1722
|
-
|
|
1723
|
-
|
|
1724
|
-
|
|
1725
|
-
|
|
1726
|
-
|
|
1727
|
-
|
|
1728
|
-
|
|
1729
|
-
|
|
1730
|
-
|
|
1731
|
-
|
|
1732
|
-
|
|
1733
|
-
|
|
1734
|
-
|
|
1735
|
-
|
|
1736
|
-
|
|
1737
|
-
|
|
1738
|
-
|
|
1739
|
-
|
|
1740
|
-
|
|
1741
|
-
|
|
1742
|
-
|
|
1743
|
-
|
|
1744
|
-
|
|
1745
|
-
|
|
1746
|
-
|
|
1747
|
-
|
|
1748
|
-
|
|
1749
|
-
|
|
1750
|
-
|
|
1751
|
-
|
|
1752
|
-
|
|
1753
|
-
|
|
1754
|
-
|
|
1755
|
-
|
|
1756
|
-
|
|
1757
|
-
|
|
1758
|
-
|
|
1759
|
-
|
|
1760
|
-
|
|
1761
|
-
|
|
1762
|
-
|
|
1763
|
-
|
|
1764
|
-
|
|
1765
|
-
|
|
1766
|
-
|
|
1767
|
-
|
|
1768
|
-
|
|
1769
|
-
|
|
1770
|
-
|
|
1771
|
-
|
|
1772
|
-
|
|
1773
|
-
|
|
1774
|
-
|
|
1775
|
-
|
|
1776
|
-
|
|
1777
|
-
|
|
1778
|
-
|
|
1779
|
-
|
|
1780
|
-
|
|
1781
|
-
|
|
1782
|
-
|
|
1783
|
-
|
|
1784
|
-
|
|
1785
|
-
|
|
1786
|
-
|
|
1787
|
-
|
|
1788
|
-
|
|
1789
|
-
|
|
1790
|
-
|
|
1791
|
-
|
|
1792
|
-
|
|
1793
|
-
|
|
1794
|
-
|
|
1795
|
-
|
|
1796
|
-
|
|
1797
|
-
|
|
1798
|
-
|
|
1799
|
-
|
|
1800
|
-
|
|
1801
|
-
|
|
1802
|
-
|
|
1803
|
-
|
|
1804
|
-
|
|
1805
|
-
|
|
1806
|
-
|
|
1807
|
-
|
|
1808
|
-
|
|
1809
|
-
|
|
1810
|
-
|
|
1811
|
-
|
|
1812
|
-
|
|
1813
|
-
|
|
1814
|
-
}
|
|
1815
|
-
|
|
1816
|
-
|
|
1817
|
-
|
|
1818
|
-
|
|
1819
|
-
|
|
1820
|
-
|
|
1821
|
-
|
|
1822
|
-
|
|
1823
|
-
|
|
1824
|
-
|
|
1825
|
-
|
|
1826
|
-
|
|
1827
|
-
|
|
1828
|
-
|
|
1829
|
-
|
|
1830
|
-
|
|
1831
|
-
|
|
1832
|
-
|
|
1833
|
-
|
|
1834
|
-
|
|
1835
|
-
|
|
1836
|
-
|
|
1837
|
-
|
|
1838
|
-
|
|
1839
|
-
|
|
1840
|
-
|
|
1841
|
-
|
|
1842
|
-
|
|
1843
|
-
|
|
1844
|
-
|
|
1845
|
-
|
|
1846
|
-
|
|
1847
|
-
|
|
1848
|
-
|
|
1849
|
-
|
|
1850
|
-
|
|
1851
|
-
|
|
1852
|
-
|
|
1853
|
-
|
|
1854
|
-
|
|
1855
|
-
|
|
1856
|
-
|
|
1857
|
-
|
|
1858
|
-
|
|
1859
|
-
|
|
1860
|
-
|
|
1861
|
-
|
|
1862
|
-
|
|
1863
|
-
|
|
1864
|
-
|
|
1865
|
-
|
|
1866
|
-
|
|
1867
|
-
|
|
1868
|
-
|
|
1869
|
-
|
|
1870
|
-
|
|
1871
|
-
|
|
1872
|
-
|
|
1873
|
-
|
|
1874
|
-
|
|
1875
|
-
|
|
1876
|
-
|
|
1877
|
-
|
|
1878
|
-
|
|
1879
|
-
|
|
1880
|
-
|
|
1881
|
-
|
|
1882
|
-
|
|
1883
|
-
|
|
1884
|
-
|
|
1885
|
-
|
|
1886
|
-
* await em.clearCache('book-cache-key');
|
|
1887
|
-
* ```
|
|
1888
|
-
*/
|
|
1889
|
-
async clearCache(cacheKey) {
|
|
1890
|
-
await this.getContext().#resultCache.remove(cacheKey);
|
|
1891
|
-
}
|
|
1892
|
-
/**
|
|
1893
|
-
* Returns the default schema of this EntityManager. Respects the context, so global EM will give you the contextual schema
|
|
1894
|
-
* if executed inside request context handler.
|
|
1895
|
-
*/
|
|
1896
|
-
get schema() {
|
|
1897
|
-
return this.getContext(false).#schema;
|
|
1898
|
-
}
|
|
1899
|
-
/**
|
|
1900
|
-
* Sets the default schema of this EntityManager. Respects the context, so global EM will set the contextual schema
|
|
1901
|
-
* if executed inside request context handler.
|
|
1902
|
-
*/
|
|
1903
|
-
set schema(schema) {
|
|
1904
|
-
this.getContext(false).#schema = schema ?? undefined;
|
|
1905
|
-
}
|
|
1906
|
-
/** @internal */
|
|
1907
|
-
async getDataLoader(type) {
|
|
1908
|
-
const em = this.getContext();
|
|
1909
|
-
if (em.#loaders[type]) {
|
|
1910
|
-
return em.#loaders[type];
|
|
1911
|
-
}
|
|
1912
|
-
const { DataloaderUtils } = await import('@mikro-orm/core/dataloader');
|
|
1913
|
-
const DataLoader = await DataloaderUtils.getDataLoader();
|
|
1914
|
-
switch (type) {
|
|
1915
|
-
case 'ref':
|
|
1916
|
-
return (em.#loaders[type] ??= new DataLoader(DataloaderUtils.getRefBatchLoadFn(em)));
|
|
1917
|
-
case '1:m':
|
|
1918
|
-
return (em.#loaders[type] ??= new DataLoader(DataloaderUtils.getColBatchLoadFn(em)));
|
|
1919
|
-
case 'm:n':
|
|
1920
|
-
return (em.#loaders[type] ??= new DataLoader(DataloaderUtils.getManyToManyColBatchLoadFn(em)));
|
|
1921
|
-
}
|
|
1922
|
-
}
|
|
1923
|
-
/**
|
|
1924
|
-
* Returns the ID of this EntityManager. Respects the context, so global EM will give you the contextual ID
|
|
1925
|
-
* if executed inside request context handler.
|
|
1926
|
-
*/
|
|
1927
|
-
get id() {
|
|
1928
|
-
return this.getContext(false)._id;
|
|
1929
|
-
}
|
|
1930
|
-
/** @ignore */
|
|
1931
|
-
[Symbol.for('nodejs.util.inspect.custom')]() {
|
|
1932
|
-
return `[EntityManager<${this.id}>]`;
|
|
1933
|
-
}
|
|
1784
|
+
}
|
|
1785
|
+
if (typeof field === 'string') {
|
|
1786
|
+
return [{ field, strategy: options.strategy }];
|
|
1787
|
+
}
|
|
1788
|
+
return [field];
|
|
1789
|
+
})
|
|
1790
|
+
.flat();
|
|
1791
|
+
}
|
|
1792
|
+
const populate = this.#entityLoader.normalizePopulate(
|
|
1793
|
+
entityName,
|
|
1794
|
+
options.populate,
|
|
1795
|
+
options.strategy,
|
|
1796
|
+
true,
|
|
1797
|
+
options.exclude,
|
|
1798
|
+
);
|
|
1799
|
+
const invalid = populate.find(({ field }) => !this.canPopulate(entityName, field));
|
|
1800
|
+
if (validate && invalid) {
|
|
1801
|
+
throw ValidationError.invalidPropertyName(entityName, invalid.field);
|
|
1802
|
+
}
|
|
1803
|
+
await this.autoJoinRefsForFilters(meta, { ...options, populate });
|
|
1804
|
+
for (const field of populate) {
|
|
1805
|
+
// force select-in strategy when populating all relations as otherwise we could cause infinite loops when self-referencing
|
|
1806
|
+
const all = field.all ?? (Array.isArray(options.populate) && options.populate.includes('*'));
|
|
1807
|
+
field.strategy = all ? LoadStrategy.SELECT_IN : (options.strategy ?? field.strategy);
|
|
1808
|
+
}
|
|
1809
|
+
if (options.populateHints) {
|
|
1810
|
+
applyPopulateHints(populate, options.populateHints);
|
|
1811
|
+
}
|
|
1812
|
+
return populate;
|
|
1813
|
+
}
|
|
1814
|
+
/**
|
|
1815
|
+
* when the entity is found in identity map, we check if it was partially loaded or we are trying to populate
|
|
1816
|
+
* some additional lazy properties, if so, we reload and merge the data from database
|
|
1817
|
+
*/
|
|
1818
|
+
shouldRefresh(meta, entity, options) {
|
|
1819
|
+
if (!helper(entity).__initialized || options.refresh) {
|
|
1820
|
+
return true;
|
|
1821
|
+
}
|
|
1822
|
+
let autoRefresh;
|
|
1823
|
+
if (options.fields) {
|
|
1824
|
+
autoRefresh = options.fields.some(field => !helper(entity).__loadedProperties.has(field));
|
|
1825
|
+
} else {
|
|
1826
|
+
autoRefresh = meta.comparableProps.some(prop => {
|
|
1827
|
+
const inlineEmbedded = prop.kind === ReferenceKind.EMBEDDED && !prop.object;
|
|
1828
|
+
return !inlineEmbedded && !prop.lazy && !helper(entity).__loadedProperties.has(prop.name);
|
|
1829
|
+
});
|
|
1830
|
+
}
|
|
1831
|
+
if (autoRefresh || options.filters) {
|
|
1832
|
+
return true;
|
|
1833
|
+
}
|
|
1834
|
+
if (Array.isArray(options.populate)) {
|
|
1835
|
+
return options.populate.some(field => !helper(entity).__loadedProperties.has(field));
|
|
1836
|
+
}
|
|
1837
|
+
return !!options.populate;
|
|
1838
|
+
}
|
|
1839
|
+
prepareOptions(options) {
|
|
1840
|
+
if (!Utils.isEmpty(options.fields) && !Utils.isEmpty(options.exclude)) {
|
|
1841
|
+
throw new ValidationError(`Cannot combine 'fields' and 'exclude' option.`);
|
|
1842
|
+
}
|
|
1843
|
+
options.schema ??= this.#schema;
|
|
1844
|
+
options.logging = options.loggerContext = Utils.merge(
|
|
1845
|
+
{ id: this.id },
|
|
1846
|
+
this.loggerContext,
|
|
1847
|
+
options.loggerContext,
|
|
1848
|
+
options.logging,
|
|
1849
|
+
);
|
|
1850
|
+
}
|
|
1851
|
+
/**
|
|
1852
|
+
* @internal
|
|
1853
|
+
*/
|
|
1854
|
+
cacheKey(entityName, options, method, where) {
|
|
1855
|
+
const { ...opts } = options;
|
|
1856
|
+
// ignore some irrelevant options, e.g. logger context can contain dynamic data for the same query
|
|
1857
|
+
for (const k of ['ctx', 'strategy', 'flushMode', 'logging', 'loggerContext']) {
|
|
1858
|
+
delete opts[k];
|
|
1859
|
+
}
|
|
1860
|
+
return [Utils.className(entityName), method, opts, where];
|
|
1861
|
+
}
|
|
1862
|
+
/**
|
|
1863
|
+
* @internal
|
|
1864
|
+
*/
|
|
1865
|
+
async tryCache(entityName, config, key, refresh, merge) {
|
|
1866
|
+
config ??= this.config.get('resultCache').global;
|
|
1867
|
+
if (!config) {
|
|
1868
|
+
return undefined;
|
|
1869
|
+
}
|
|
1870
|
+
const em = this.getContext();
|
|
1871
|
+
const cacheKey = Array.isArray(config) ? config[0] : JSON.stringify(key);
|
|
1872
|
+
const cached = await em.#resultCache.get(cacheKey);
|
|
1873
|
+
if (!cached) {
|
|
1874
|
+
return { key: cacheKey, data: cached };
|
|
1875
|
+
}
|
|
1876
|
+
let data;
|
|
1877
|
+
const createOptions = {
|
|
1878
|
+
merge: true,
|
|
1879
|
+
convertCustomTypes: false,
|
|
1880
|
+
refresh,
|
|
1881
|
+
recomputeSnapshot: true,
|
|
1882
|
+
};
|
|
1883
|
+
if (Array.isArray(cached) && merge) {
|
|
1884
|
+
data = cached.map(item => em.#entityFactory.create(entityName, item, createOptions));
|
|
1885
|
+
} else if (Utils.isObject(cached) && merge) {
|
|
1886
|
+
data = em.#entityFactory.create(entityName, cached, createOptions);
|
|
1887
|
+
} else {
|
|
1888
|
+
data = cached;
|
|
1889
|
+
}
|
|
1890
|
+
await em.#unitOfWork.dispatchOnLoadEvent();
|
|
1891
|
+
return { key: cacheKey, data };
|
|
1892
|
+
}
|
|
1893
|
+
/**
|
|
1894
|
+
* @internal
|
|
1895
|
+
*/
|
|
1896
|
+
async storeCache(config, key, data) {
|
|
1897
|
+
config ??= this.config.get('resultCache').global;
|
|
1898
|
+
if (config) {
|
|
1899
|
+
const em = this.getContext();
|
|
1900
|
+
const expiration = Array.isArray(config) ? config[1] : typeof config === 'number' ? config : undefined;
|
|
1901
|
+
await em.#resultCache.set(key.key, data instanceof Function ? data() : data, '', expiration);
|
|
1902
|
+
}
|
|
1903
|
+
}
|
|
1904
|
+
/**
|
|
1905
|
+
* Clears result cache for given cache key. If we want to be able to call this method,
|
|
1906
|
+
* we need to set the cache key explicitly when storing the cache.
|
|
1907
|
+
*
|
|
1908
|
+
* ```ts
|
|
1909
|
+
* // set the cache key to 'book-cache-key', with expiration of 60s
|
|
1910
|
+
* const res = await em.find(Book, { ... }, { cache: ['book-cache-key', 60_000] });
|
|
1911
|
+
*
|
|
1912
|
+
* // clear the cache key by name
|
|
1913
|
+
* await em.clearCache('book-cache-key');
|
|
1914
|
+
* ```
|
|
1915
|
+
*/
|
|
1916
|
+
async clearCache(cacheKey) {
|
|
1917
|
+
await this.getContext().#resultCache.remove(cacheKey);
|
|
1918
|
+
}
|
|
1919
|
+
/**
|
|
1920
|
+
* Returns the default schema of this EntityManager. Respects the context, so global EM will give you the contextual schema
|
|
1921
|
+
* if executed inside request context handler.
|
|
1922
|
+
*/
|
|
1923
|
+
get schema() {
|
|
1924
|
+
return this.getContext(false).#schema;
|
|
1925
|
+
}
|
|
1926
|
+
/**
|
|
1927
|
+
* Sets the default schema of this EntityManager. Respects the context, so global EM will set the contextual schema
|
|
1928
|
+
* if executed inside request context handler.
|
|
1929
|
+
*/
|
|
1930
|
+
set schema(schema) {
|
|
1931
|
+
this.getContext(false).#schema = schema ?? undefined;
|
|
1932
|
+
}
|
|
1933
|
+
/** @internal */
|
|
1934
|
+
async getDataLoader(type) {
|
|
1935
|
+
const em = this.getContext();
|
|
1936
|
+
if (em.#loaders[type]) {
|
|
1937
|
+
return em.#loaders[type];
|
|
1938
|
+
}
|
|
1939
|
+
const { DataloaderUtils } = await import('@mikro-orm/core/dataloader');
|
|
1940
|
+
const DataLoader = await DataloaderUtils.getDataLoader();
|
|
1941
|
+
switch (type) {
|
|
1942
|
+
case 'ref':
|
|
1943
|
+
return (em.#loaders[type] ??= new DataLoader(DataloaderUtils.getRefBatchLoadFn(em)));
|
|
1944
|
+
case '1:m':
|
|
1945
|
+
return (em.#loaders[type] ??= new DataLoader(DataloaderUtils.getColBatchLoadFn(em)));
|
|
1946
|
+
case 'm:n':
|
|
1947
|
+
return (em.#loaders[type] ??= new DataLoader(DataloaderUtils.getManyToManyColBatchLoadFn(em)));
|
|
1948
|
+
}
|
|
1949
|
+
}
|
|
1950
|
+
/**
|
|
1951
|
+
* Returns the ID of this EntityManager. Respects the context, so global EM will give you the contextual ID
|
|
1952
|
+
* if executed inside request context handler.
|
|
1953
|
+
*/
|
|
1954
|
+
get id() {
|
|
1955
|
+
return this.getContext(false)._id;
|
|
1956
|
+
}
|
|
1957
|
+
/** @ignore */
|
|
1958
|
+
[Symbol.for('nodejs.util.inspect.custom')]() {
|
|
1959
|
+
return `[EntityManager<${this.id}>]`;
|
|
1960
|
+
}
|
|
1934
1961
|
}
|