/
EntityManager.ts
1730 lines (1452 loc) · 62.9 KB
/
EntityManager.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
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
698
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
729
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
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { inspect } from 'util';
import type { Configuration } from './utils';
import { Cursor, QueryHelper, TransactionContext, Utils } from './utils';
import type { AssignOptions, EntityLoaderOptions, EntityRepository } from './entity';
import { EntityAssigner, EntityFactory, EntityLoader, EntityValidator, helper, Reference } from './entity';
import { ChangeSet, ChangeSetType, UnitOfWork } from './unit-of-work';
import type {
CountOptions,
DeleteOptions,
EntityField,
EntityManagerType,
FindByCursorOptions,
FindOneOptions,
FindOneOrFailOptions,
FindOptions,
GetReferenceOptions,
IDatabaseDriver,
LockOptions,
NativeInsertUpdateOptions,
UpdateOptions,
} from './drivers';
import type {
AnyEntity,
AutoPath,
ConnectionType,
Dictionary,
EntityData,
EntityDictionary,
EntityDTO,
EntityMetadata,
EntityName,
FilterDef,
FilterQuery,
GetRepository,
Loaded,
Populate,
PopulateOptions,
Primary,
RequiredEntityData,
Ref,
EntityKey,
} from './typings';
import type { TransactionOptions } from './enums';
import { FlushMode, LoadStrategy, LockMode, PopulateHint, ReferenceKind, SCALAR_TYPES } from './enums';
import type { MetadataStorage } from './metadata';
import type { Transaction } from './connections';
import type { FlushEventArgs } from './events';
import { EventManager, TransactionEventBroadcaster } from './events';
import type { EntityComparator } from './utils/EntityComparator';
import { OptimisticLockError, ValidationError } from './errors';
/**
* The EntityManager is the central access point to ORM functionality. It is a facade to all different ORM subsystems
* such as UnitOfWork, Query Language and Repository API.
* @template {D} current driver type
*/
export class EntityManager<D extends IDatabaseDriver = IDatabaseDriver> {
private static counter = 1;
readonly _id = EntityManager.counter++;
readonly global = false;
readonly name = this.config.get('contextName');
private readonly validator = new EntityValidator(this.config.get('strict'));
private readonly repositoryMap: Dictionary<EntityRepository<any>> = {};
private readonly entityLoader: EntityLoader = new EntityLoader(this);
private readonly comparator = this.config.getComparator(this.metadata);
private readonly entityFactory: EntityFactory = new EntityFactory(this);
private readonly unitOfWork: UnitOfWork = new UnitOfWork(this);
private readonly resultCache = this.config.getResultCacheAdapter();
private filters: Dictionary<FilterDef> = {};
private filterParams: Dictionary<Dictionary> = {};
private transactionContext?: Transaction;
private flushMode?: FlushMode;
/**
* @internal
*/
constructor(readonly config: Configuration,
private readonly driver: D,
private readonly metadata: MetadataStorage,
private readonly useContext = true,
private readonly eventManager = new EventManager(config.get('subscribers'))) { }
/**
* Gets the Driver instance used by this EntityManager.
* Driver is singleton, for one MikroORM instance, only one driver is created.
*/
getDriver(): D {
return this.driver;
}
/**
* Gets the Connection instance, by default returns write connection
*/
getConnection(type?: ConnectionType): ReturnType<D['getConnection']> {
return this.driver.getConnection(type) as ReturnType<D['getConnection']>;
}
/**
* Gets the platform instance. Just like the driver, platform is singleton, one for a MikroORM instance.
*/
getPlatform(): ReturnType<D['getPlatform']> {
return this.driver.getPlatform() as ReturnType<D['getPlatform']>;
}
/**
* Gets repository for given entity. You can pass either string name or entity class reference.
*/
getRepository<
Entity extends object,
Repository extends EntityRepository<Entity> = EntityRepository<Entity>,
>(entityName: EntityName<Entity>): GetRepository<Entity, Repository> {
entityName = Utils.className(entityName);
if (!this.repositoryMap[entityName]) {
const meta = this.metadata.get(entityName);
const RepositoryClass = this.config.getRepositoryClass(meta.repository)!;
this.repositoryMap[entityName] = new RepositoryClass(this.getContext(false), entityName) as EntityRepository<any>;
}
return this.repositoryMap[entityName] as unknown as GetRepository<Entity, Repository>;
}
/**
* Shortcut for `em.getRepository()`.
*/
repo<
Entity extends object,
Repository extends EntityRepository<Entity> = EntityRepository<Entity>,
>(entityName: EntityName<Entity>): GetRepository<Entity, Repository> {
return this.getRepository(entityName);
}
/**
* Gets EntityValidator instance
*/
getValidator(): EntityValidator {
return this.validator;
}
/**
* Finds all entities matching your `where` query. You can pass additional options via the `options` parameter.
*/
async find<
Entity extends object,
Hint extends string = never,
Fields extends string = '*',
>(entityName: EntityName<Entity>, where: FilterQuery<Entity>, options: FindOptions<Entity, Hint, Fields> = {}): Promise<Loaded<Entity, Hint, Fields>[]> {
if (options.disableIdentityMap) {
const em = this.getContext(false);
const fork = em.fork();
const ret = await fork.find<Entity, Hint, Fields>(entityName, where, { ...options, disableIdentityMap: false });
fork.clear();
return ret;
}
const em = this.getContext();
await em.tryFlush(entityName, options);
entityName = Utils.className(entityName);
where = await em.processWhere(entityName, where, options, 'read') as FilterQuery<Entity>;
em.validator.validateParams(where);
options.orderBy = options.orderBy || {};
options.populate = em.preparePopulate<Entity, Hint, Fields>(entityName, options) as unknown as Populate<Entity, Hint>;
const populate = options.populate as unknown as PopulateOptions<Entity>[];
const cached = await em.tryCache<Entity, Loaded<Entity, Hint, Fields>[]>(entityName, options.cache, [entityName, 'em.find', options, where], options.refresh, true);
if (cached?.data) {
await em.entityLoader.populate<Entity, Hint>(entityName, cached.data as Entity[], populate, {
...options as Dictionary,
...em.getPopulateWhere(where as FilterQuery<Entity>, options),
convertCustomTypes: false,
ignoreLazyScalarProperties: true,
lookup: false,
});
return cached.data;
}
const results = await em.driver.find<Entity, Hint, Fields>(entityName, where, { ctx: em.transactionContext, ...options });
if (results.length === 0) {
await em.storeCache(options.cache, cached!, []);
return [];
}
const meta = this.metadata.get(entityName);
const ret: Loaded<Entity, Hint, Fields>[] = [];
for (const data of results) {
const entity = em.entityFactory.create(entityName, data as EntityData<Entity>, {
merge: true,
refresh: options.refresh,
schema: options.schema,
convertCustomTypes: true,
}) as Loaded<Entity, Hint, Fields>;
if (!meta.virtual) {
em.unitOfWork.registerManaged(entity as Entity, data, { refresh: options.refresh, loaded: true });
}
ret.push(entity);
}
if (meta.virtual) {
await em.unitOfWork.dispatchOnLoadEvent();
await em.storeCache(options.cache, cached!, () => ret);
return ret;
}
const unique = Utils.unique(ret);
await em.entityLoader.populate<Entity, Hint>(entityName, unique as Entity[], populate, {
...options as Dictionary,
...em.getPopulateWhere(where as FilterQuery<Entity>, options),
convertCustomTypes: false,
ignoreLazyScalarProperties: true,
lookup: false,
});
await em.unitOfWork.dispatchOnLoadEvent();
await em.storeCache(options.cache, cached!, () => unique.map(e => helper(e).toPOJO()));
return unique;
}
private getPopulateWhere<
Entity extends object,
Hint extends string,
>(where: FilterQuery<Entity>, options: Pick<FindOptions<Entity, Hint>, 'populateWhere'>): { where: FilterQuery<Entity>; populateWhere?: PopulateHint } {
if (options.populateWhere === undefined) {
options.populateWhere = this.config.get('populateWhere');
}
if (options.populateWhere === PopulateHint.ALL) {
return { where: {} as FilterQuery<Entity>, populateWhere: options.populateWhere };
}
if (options.populateWhere === PopulateHint.INFER) {
return { where, populateWhere: options.populateWhere };
}
return { where: options.populateWhere };
}
/**
* Registers global filter to this entity manager. Global filters are enabled by default (unless disabled via last parameter).
*/
addFilter<T1>(name: string, cond: FilterQuery<T1> | ((args: Dictionary) => FilterQuery<T1>), entityName?: EntityName<T1> | [EntityName<T1>], enabled?: boolean): void;
/**
* Registers global filter to this entity manager. Global filters are enabled by default (unless disabled via last parameter).
*/
addFilter<T1, T2>(name: string, cond: FilterQuery<T1 | T2> | ((args: Dictionary) => FilterQuery<T1 | T2>), entityName?: [EntityName<T1>, EntityName<T2>], enabled?: boolean): void;
/**
* Registers global filter to this entity manager. Global filters are enabled by default (unless disabled via last parameter).
*/
addFilter<T1, T2, T3>(name: string, cond: FilterQuery<T1 | T2 | T3> | ((args: Dictionary) => FilterQuery<T1 | T2 | T3>), entityName?: [EntityName<T1>, EntityName<T2>, EntityName<T3>], enabled?: boolean): void;
/**
* Registers global filter to this entity manager. Global filters are enabled by default (unless disabled via last parameter).
*/
addFilter(name: string, cond: Dictionary | ((args: Dictionary) => FilterQuery<AnyEntity>), entityName?: EntityName<AnyEntity> | EntityName<AnyEntity>[], enabled = true): void {
const options: FilterDef = { name, cond, default: enabled };
if (entityName) {
options.entity = Utils.asArray(entityName).map(n => Utils.className(n));
}
this.getContext(false).filters[name] = options;
}
/**
* Sets filter parameter values globally inside context defined by this entity manager.
* If you want to set shared value for all contexts, be sure to use the root entity manager.
*/
setFilterParams(name: string, args: Dictionary): void {
this.getContext().filterParams[name] = args;
}
/**
* Returns filter parameters for given filter set in this context.
*/
getFilterParams<T extends Dictionary = Dictionary>(name: string): T {
return this.getContext().filterParams[name] as T;
}
setFlushMode(flushMode?: FlushMode): void {
this.getContext(false).flushMode = flushMode;
}
protected async processWhere<
Entity extends object,
Hint extends string = never,
Fields extends string = '*',
>(entityName: string, where: FilterQuery<Entity>, options: FindOptions<Entity, Hint, Fields> | FindOneOptions<Entity, Hint, Fields>, type: 'read' | 'update' | 'delete'): Promise<FilterQuery<Entity>> {
where = QueryHelper.processWhere({
where: where as FilterQuery<Entity>,
entityName,
metadata: this.metadata,
platform: this.driver.getPlatform(),
convertCustomTypes: options.convertCustomTypes,
aliased: type === 'read',
});
where = await this.applyFilters(entityName, where, options.filters ?? {}, type);
where = await this.applyDiscriminatorCondition(entityName, where);
return where;
}
protected applyDiscriminatorCondition<Entity extends object>(entityName: string, where: FilterQuery<Entity>): FilterQuery<Entity> {
const meta = this.metadata.find<Entity>(entityName);
if (!meta?.discriminatorValue) {
return where;
}
const types = Object.values(meta.root.discriminatorMap!).map(cls => this.metadata.find(cls)!);
const children: EntityMetadata[] = [];
const lookUpChildren = (ret: EntityMetadata[], type: string) => {
const children = types.filter(meta2 => meta2.extends === type);
children.forEach(m => lookUpChildren(ret, m.className));
ret.push(...children.filter(c => c.discriminatorValue));
return children;
};
lookUpChildren(children, meta.className);
(where as Dictionary)[meta.root.discriminatorColumn!] = children.length > 0 ? { $in: [meta.discriminatorValue, ...children.map(c => c.discriminatorValue)] } : meta.discriminatorValue;
return where;
}
/**
* @internal
*/
async applyFilters<Entity extends object>(entityName: string, where: FilterQuery<Entity>, options: Dictionary<boolean | Dictionary> | string[] | boolean, type: 'read' | 'update' | 'delete'): Promise<FilterQuery<Entity>> {
const meta = this.metadata.find<Entity>(entityName);
const filters: FilterDef[] = [];
const ret: Dictionary[] = [];
if (!meta) {
return where;
}
const active = new Set<string>();
const push = (source: Dictionary<FilterDef>) => {
const activeFilters = QueryHelper
.getActiveFilters(entityName, options, source)
.filter(f => !active.has(f.name));
filters.push(...activeFilters);
activeFilters.forEach(f => active.add(f.name));
};
push(this.config.get('filters'));
push(this.filters);
push(meta.filters);
if (filters.length === 0) {
return where;
}
for (const filter of filters) {
let cond: Dictionary;
if (filter.cond instanceof Function) {
// @ts-ignore
const args = Utils.isPlainObject(options[filter.name]) ? options[filter.name] : this.getContext().filterParams[filter.name];
if (!args && filter.cond.length > 0 && filter.args !== false) {
throw new Error(`No arguments provided for filter '${filter.name}'`);
}
cond = await filter.cond(args, type, this);
} else {
cond = filter.cond;
}
ret.push(QueryHelper.processWhere({
where: cond,
entityName,
metadata: this.metadata,
platform: this.driver.getPlatform(),
aliased: type === 'read',
}));
}
const conds = [...ret, where as Dictionary].filter(c => Utils.hasObjectKeys(c)) as FilterQuery<Entity>[];
return conds.length > 1 ? { $and: conds } as FilterQuery<Entity> : conds[0];
}
/**
* Calls `em.find()` and `em.count()` with the same arguments (where applicable) and returns the results as tuple
* where first element is the array of entities and the second is the count.
*/
async findAndCount<
Entity extends object,
Hint extends string = never,
Fields extends string = '*',
>(entityName: EntityName<Entity>, where: FilterQuery<Entity>, options: FindOptions<Entity, Hint, Fields> = {}): Promise<[Loaded<Entity, Hint, Fields>[], number]> {
const em = this.getContext(false);
const [entities, count] = await Promise.all([
em.find<Entity, Hint, Fields>(entityName, where, options),
em.count(entityName, where, options),
]);
return [entities, count];
}
/**
* Calls `em.find()` and `em.count()` with the same arguments (where applicable) and returns the results as {@apilink Cursor} object.
* Supports `before`, `after`, `first` and `last` options while disallowing `limit` and `offset`. Explicit `orderBy` option
* is required.
*
* Use `first` and `after` for forward pagination, or `last` and `before` for backward pagination.
*
* - `first` and `last` are numbers and serve as an alternative to `offset`, those options are mutually exclusive, use only one at a time
* - `before` and `after` specify the previous cursor value, it can be one of the:
* - `Cursor` instance
* - opaque string provided by `startCursor/endCursor` properties
* - POJO/entity instance
*
* ```ts
* const currentCursor = await em.findByCursor(User, {}, {
* first: 10,
* after: previousCursor, // cursor instance
* orderBy: { id: 'desc' },
* });
*
* // to fetch next page
* const nextCursor = await em.findByCursor(User, {}, {
* first: 10,
* after: currentCursor.endCursor, // opaque string
* orderBy: { id: 'desc' },
* });
*
* // to fetch next page
* const nextCursor2 = await em.findByCursor(User, {}, {
* first: 10,
* after: { id: lastSeenId }, // entity-like POJO
* orderBy: { id: 'desc' },
* });
* ```
*
* The `Cursor` object provides following interface:
*
* ```ts
* Cursor<User> {
* items: [
* User { ... },
* User { ... },
* User { ... },
* ],
* totalCount: 50,
* startCursor: 'WzRd',
* endCursor: 'WzZd',
* hasPrevPage: true,
* hasNextPage: true,
* }
* ```
*/
async findByCursor<
Entity extends object,
Hint extends string = never,
Fields extends string = '*',
>(entityName: EntityName<Entity>, where: FilterQuery<Entity>, options: FindByCursorOptions<Entity, Hint, Fields> = {}): Promise<Cursor<Entity, Hint, Fields>> {
const em = this.getContext(false);
entityName = Utils.className(entityName);
options.overfetch ??= true;
if (Utils.isEmpty(options.orderBy)) {
throw new Error('Explicit `orderBy` option required');
}
const [entities, count] = await em.findAndCount(entityName, where, options);
return new Cursor<Entity, Hint, Fields>(entities, count, options, this.metadata.get(entityName));
}
/**
* Refreshes the persistent state of an entity from the database, overriding any local changes that have not yet been persisted.
*/
async refresh<
Entity extends object,
Hint extends string = never,
Fields extends string = '*',
>(entity: Entity, options: FindOneOptions<Entity, Hint, Fields> = {}): Promise<Loaded<Entity, Hint, Fields> | null> {
const fork = this.fork();
const entityName = entity.constructor.name;
const reloaded = await fork.findOne(entityName, entity, {
schema: helper(entity).__schema,
...options,
flushMode: FlushMode.COMMIT,
});
if (reloaded) {
this.config.getHydrator(this.metadata).hydrate(entity, helper(entity).__meta, helper(reloaded).toPOJO() as object, this.getEntityFactory(), 'full');
} else {
this.getUnitOfWork().unsetIdentity(entity);
}
return reloaded;
}
/**
* Finds first entity matching your `where` query.
*/
async findOne<
Entity extends object,
Hint extends string = never,
Fields extends string = '*',
>(entityName: EntityName<Entity>, where: FilterQuery<Entity>, options: FindOneOptions<Entity, Hint, Fields> = {}): Promise<Loaded<Entity, Hint, Fields> | null> {
if (options.disableIdentityMap) {
const em = this.getContext(false);
const fork = em.fork();
const ret = await fork.findOne<Entity, Hint, Fields>(entityName, where, { ...options, disableIdentityMap: false });
fork.clear();
return ret;
}
const em = this.getContext();
await em.tryFlush(entityName, options);
entityName = Utils.className(entityName);
const meta = em.metadata.get<Entity>(entityName);
where = await em.processWhere(entityName, where, options, 'read');
em.validator.validateEmptyWhere(where);
em.checkLockRequirements(options.lockMode, meta);
let entity = em.unitOfWork.tryGetById<Entity>(entityName, where, options.schema);
const isOptimisticLocking = !Utils.isDefined(options.lockMode) || options.lockMode === LockMode.OPTIMISTIC;
if (entity && !em.shouldRefresh(meta, entity, options) && isOptimisticLocking) {
return em.lockAndPopulate(entityName, entity, where, options);
}
em.validator.validateParams(where);
options.populate = em.preparePopulate<Entity, Hint, Fields>(entityName, options) as unknown as Populate<Entity, Hint>;
const cached = await em.tryCache<Entity, Loaded<Entity, Hint, Fields>>(entityName, options.cache, [entityName, 'em.findOne', options, where], options.refresh, true);
if (cached?.data) {
await em.entityLoader.populate<Entity, Hint>(entityName, [cached.data as Entity], options.populate as unknown as PopulateOptions<Entity>[], {
...options as Dictionary,
...em.getPopulateWhere(where as FilterQuery<Entity>, options),
convertCustomTypes: false,
ignoreLazyScalarProperties: true,
lookup: false,
});
return cached.data;
}
const data = await em.driver.findOne<Entity, Hint, Fields>(entityName, where, { ctx: em.transactionContext, ...options });
if (!data) {
await em.storeCache(options.cache, cached!, null);
return null;
}
entity = em.entityFactory.create<Entity>(entityName, data as EntityData<Entity>, {
merge: true,
refresh: options.refresh,
schema: options.schema,
convertCustomTypes: true,
});
if (!meta.virtual) {
em.unitOfWork.registerManaged(entity, data, { refresh: options.refresh, loaded: true });
await em.lockAndPopulate(entityName, entity, where, options);
}
await em.unitOfWork.dispatchOnLoadEvent();
await em.storeCache(options.cache, cached!, () => helper(entity!).toPOJO());
return entity as Loaded<Entity, Hint, Fields>;
}
/**
* Finds first entity matching your `where` query. If nothing found, it will throw an error.
* If the `strict` option is specified and nothing is found or more than one matching entity is found, it will throw an error.
* You can override the factory for creating this method via `options.failHandler` locally
* or via `Configuration.findOneOrFailHandler` (`findExactlyOneOrFailHandler` when specifying `strict`) globally.
*/
async findOneOrFail<
Entity extends object,
Hint extends string = never,
Fields extends string = '*',
>(entityName: EntityName<Entity>, where: FilterQuery<Entity>, options: FindOneOrFailOptions<Entity, Hint, Fields> = {}): Promise<Loaded<Entity, Hint, Fields>> {
let entity: Loaded<Entity, Hint, Fields> | null;
let isStrictViolation = false;
if (options.strict) {
const ret = await this.find(entityName, where, { ...options as FindOptions<Entity, Hint, Fields>, limit: 2 });
isStrictViolation = ret.length !== 1;
entity = ret[0];
} else {
entity = await this.findOne(entityName, where, options);
}
if (!entity || isStrictViolation) {
const key = options.strict ? 'findExactlyOneOrFailHandler' : 'findOneOrFailHandler';
options.failHandler ??= this.config.get(key);
entityName = Utils.className(entityName);
throw options.failHandler!(entityName, where);
}
return entity;
}
/**
* Creates or updates the entity, based on whether it is already present in the database.
* This method performs an `insert on conflict merge` query ensuring the database is in sync, returning a managed
* entity instance. The method accepts either `entityName` together with the entity `data`, or just entity instance.
*
* ```ts
* // insert into "author" ("age", "email") values (33, 'foo@bar.com') on conflict ("email") do update set "age" = 41
* const author = await em.upsert(Author, { email: 'foo@bar.com', age: 33 });
* ```
*
* 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:
*
* ```ts
* // insert into "author" ("age", "email") values (33, 'foo@bar.com') on conflict ("email") do update set "age" = 41
* // select "id" from "author" where "email" = 'foo@bar.com'
* const author = await em.upsert(Author, { email: 'foo@bar.com', age: 33 });
* ```
*
* 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`.
*
* 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.
*/
async upsert<Entity extends object>(entityNameOrEntity: EntityName<Entity> | Entity, data?: EntityData<Entity> | Entity, options: NativeInsertUpdateOptions<Entity> = {}): Promise<Entity> {
const em = this.getContext(false);
let entityName: EntityName<Entity>;
let where: FilterQuery<Entity>;
let entity: Entity;
if (data === undefined) {
entityName = (entityNameOrEntity as Dictionary).constructor.name;
data = entityNameOrEntity as Entity;
} else {
entityName = Utils.className(entityNameOrEntity as EntityName<Entity>);
}
const meta = this.metadata.get<Entity>(entityName);
const convertCustomTypes = !Utils.isEntity(data);
if (Utils.isEntity(data)) {
entity = data as Entity;
if (helper(entity).__managed && helper(entity).__em === em) {
em.entityFactory.mergeData(meta, entity, data);
return entity;
}
where = helper(entity).getPrimaryKey() as FilterQuery<Entity>;
data = em.comparator.prepareEntity(entity);
} else {
where = Utils.extractPK(data, meta) as FilterQuery<Entity>;
if (where) {
const exists = em.unitOfWork.getById<Entity>(entityName, where as Primary<Entity>, options.schema);
if (exists) {
return em.assign(exists, data);
}
}
}
const unique = meta.props.filter(p => p.unique).map(p => p.name);
const propIndex = unique.findIndex(p => data![p] != null);
if (where == null) {
if (propIndex >= 0) {
where = { [unique[propIndex]]: data[unique[propIndex]] } as FilterQuery<Entity>;
} else if (meta.uniques.length > 0) {
for (const u of meta.uniques) {
if (Utils.asArray(u.properties).every(p => data![p])) {
where = Utils.asArray(u.properties).reduce((o, key) => {
o[key] = data![key];
return o;
}, {} as any);
break;
}
}
}
}
if (where == null) {
const compositeUniqueProps = meta.uniques.map(u => Utils.asArray(u.properties).join(' + ')) as EntityKey<Entity>[];
const uniqueProps = meta.primaryKeys.concat(...unique).concat(compositeUniqueProps);
throw new Error(`Unique property value required for upsert, provide one of: ${uniqueProps.join(', ')}`);
}
data = QueryHelper.processObjectParams(data) as EntityData<Entity>;
em.validator.validateParams(data, 'insert data');
const ret = await em.driver.nativeUpdate(entityName, where, data, {
ctx: em.transactionContext,
upsert: true,
convertCustomTypes,
...options,
});
entity ??= em.entityFactory.create(entityName, data, {
refresh: true,
initialized: true,
schema: options.schema,
convertCustomTypes: true,
});
em.unitOfWork.getChangeSetPersister().mapReturnedValues(entity, ret.row, meta);
if (!helper(entity).hasPrimaryKey()) {
const pk = await this.driver.findOne(meta.className, where, {
fields: meta.primaryKeys as [],
ctx: em.transactionContext,
convertCustomTypes: true,
});
em.entityFactory.mergeData(meta, entity, pk!);
}
// recompute the data as there might be some values missing (e.g. those with db column defaults)
const snapshot = this.comparator.prepareEntity(entity);
em.unitOfWork.registerManaged(entity, snapshot, { refresh: true });
return entity;
}
/**
* Creates or updates the entity, based on whether it is already present in the database.
* This method performs an `insert on conflict merge` query ensuring the database is in sync, returning a managed
* entity instance. The method accepts either `entityName` together with the entity `data`, or just entity instance.
*
* ```ts
* // insert into "author" ("age", "email") values (33, 'foo@bar.com') on conflict ("email") do update set "age" = 41
* const authors = await em.upsertMany(Author, [{ email: 'foo@bar.com', age: 33 }, ...]);
* ```
*
* 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:
*
* ```ts
* // insert into "author" ("age", "email") values (33, 'foo@bar.com'), (666, 'lol@lol.lol') on conflict ("email") do update set "age" = excluded."age"
* // select "id" from "author" where "email" = 'foo@bar.com'
* const author = await em.upsertMany(Author, [
* { email: 'foo@bar.com', age: 33 },
* { email: 'lol@lol.lol', age: 666 },
* ]);
* ```
*
* 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`.
*
* 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.
*/
async upsertMany<Entity extends object>(entityNameOrEntity: EntityName<Entity> | Entity[], data?: (EntityData<Entity> | Entity)[], options: NativeInsertUpdateOptions<Entity> = {}): Promise<Entity[]> {
const em = this.getContext(false);
let entityName: string;
let propIndex: number;
if (data === undefined) {
entityName = (entityNameOrEntity as Entity[])[0].constructor.name;
data = entityNameOrEntity as Entity[];
} else {
entityName = Utils.className(entityNameOrEntity as EntityName<Entity>);
}
const meta = this.metadata.get<Entity>(entityName);
const convertCustomTypes = !Utils.isEntity(data[0]);
const allData: EntityData<Entity>[] = [];
const allWhere: FilterQuery<Entity>[] = [];
const entities = new Map<Entity, EntityData<Entity>>();
for (let row of data) {
let where: FilterQuery<Entity>;
if (Utils.isEntity(row)) {
const entity = row as Entity;
if (helper(entity).__managed && helper(entity).__em === em) {
em.entityFactory.mergeData(meta, entity, row);
entities.set(entity, row);
continue;
}
where = helper(entity).getPrimaryKey() as FilterQuery<Entity>;
row = em.comparator.prepareEntity(entity);
} else {
where = Utils.extractPK(row, meta) as FilterQuery<Entity>;
if (where) {
const exists = em.unitOfWork.getById<Entity>(entityName, where as Primary<Entity>, options.schema);
if (exists) {
em.assign(exists, row);
entities.set(exists, row);
continue;
}
}
}
const unique = meta.props.filter(p => p.unique).map(p => p.name);
propIndex = unique.findIndex(p => row![p] != null);
if (where == null) {
if (propIndex >= 0) {
where = { [unique[propIndex]]: row[unique[propIndex] as EntityKey<Entity>] } as FilterQuery<Entity>;
} else if (meta.uniques.length > 0) {
for (const u of meta.uniques) {
if (Utils.asArray(u.properties).every(p => row![p])) {
where = Utils.asArray(u.properties).reduce((o, key) => {
o[key] = row![key];
return o;
}, {} as Dictionary) as FilterQuery<Entity>;
break;
}
}
}
}
if (where == null) {
const compositeUniqueProps = meta.uniques.map(u => Utils.asArray(u.properties).join(' + '));
const uniqueProps = (meta.primaryKeys as string[]).concat(...unique).concat(compositeUniqueProps);
throw new Error(`Unique property value required for upsert, provide one of: ${uniqueProps.join(', ')}`);
}
row = QueryHelper.processObjectParams(row) as EntityData<Entity>;
em.validator.validateParams(row, 'insert data');
allData.push(row);
allWhere.push(where);
}
if (entities.size === data.length) {
return [...entities.keys()];
}
const ret = await em.driver.nativeUpdateMany(entityName, allWhere, allData, {
ctx: em.transactionContext,
upsert: true,
convertCustomTypes,
...options,
});
entities.clear();
const loadPK = new Map<Entity, FilterQuery<Entity>>();
allData.forEach((row, i) => {
const entity = Utils.isEntity(data![i]) ? data![i] as Entity : em.entityFactory.create(entityName, row, {
refresh: true,
initialized: true,
schema: options.schema,
convertCustomTypes: true,
});
em.unitOfWork.getChangeSetPersister().mapReturnedValues(entity, ret.rows?.[i], meta);
if (!helper(entity).hasPrimaryKey()) {
loadPK.set(entity, allWhere[i]);
}
entities.set(entity, row);
});
// skip if we got the PKs via returning statement (`rows`)
if (!ret.rows?.length && loadPK.size > 0) {
const unique = meta.props.filter(p => p.unique).map(p => p.name);
const add = propIndex! >= 0 ? [unique[propIndex!]] : [];
const pks = await this.driver.find(meta.className, { $or: [...loadPK.values()] as Dictionary[] }, {
fields: meta.primaryKeys.concat(...add),
ctx: em.transactionContext,
convertCustomTypes: true,
});
let i = 0;
for (const entity of loadPK.keys()) {
em.entityFactory.mergeData(meta, entity, pks[i]);
i++;
}
}
for (const [entity] of entities) {
// recompute the data as there might be some values missing (e.g. those with db column defaults)
const snapshot = this.comparator.prepareEntity(entity);
em.unitOfWork.registerManaged(entity, snapshot, { refresh: true });
}
return [...entities.keys()];
}
/**
* Runs your callback wrapped inside a database transaction.
*/
async transactional<T>(cb: (em: D[typeof EntityManagerType]) => Promise<T>, options: TransactionOptions = {}): Promise<T> {
const em = this.getContext(false);
const fork = em.fork({
clear: false, // state will be merged once resolves
flushMode: options.flushMode,
cloneEventManager: true,
});
options.ctx ??= em.transactionContext;
return TransactionContext.create(fork, async () => {
return fork.getConnection().transactional(async trx => {
fork.transactionContext = trx;
fork.eventManager.registerSubscriber({
afterFlush(args: FlushEventArgs) {
args.uow.getChangeSets()
.filter(cs => [ChangeSetType.DELETE, ChangeSetType.DELETE_EARLY].includes(cs.type))
.forEach(cs => em.unitOfWork.unsetIdentity(cs.entity));
},
});
const ret = await cb(fork);
await fork.flush();
// ensure all entities from inner context are merged to the upper one
for (const entity of fork.unitOfWork.getIdentityMap()) {
em.unitOfWork.registerManaged(entity);
entity.__helper!.__em = em;
}
return ret;
}, { ...options, eventBroadcaster: new TransactionEventBroadcaster(fork) });
});
}
/**
* Starts new transaction bound to this EntityManager. Use `ctx` parameter to provide the parent when nesting transactions.
*/
async begin(options: TransactionOptions = {}): Promise<void> {
const em = this.getContext(false);
em.transactionContext = await em.getConnection('write').begin({
...options,
eventBroadcaster: new TransactionEventBroadcaster(em),
});
}
/**
* Commits the transaction bound to this EntityManager. Flushes before doing the actual commit query.
*/
async commit(): Promise<void> {
const em = this.getContext(false);
if (!em.transactionContext) {
throw ValidationError.transactionRequired();
}
await em.flush();
await em.getConnection('write').commit(em.transactionContext, new TransactionEventBroadcaster(em));
delete em.transactionContext;
}
/**
* Rollbacks the transaction bound to this EntityManager.
*/
async rollback(): Promise<void> {
const em = this.getContext(false);
if (!em.transactionContext) {
throw ValidationError.transactionRequired();
}
await em.getConnection('write').rollback(em.transactionContext, new TransactionEventBroadcaster(em));
delete em.transactionContext;
em.unitOfWork.clearActionsQueue();
}
/**
* Runs your callback wrapped inside a database transaction.
*/
async lock<T extends object>(entity: T, lockMode: LockMode, options: LockOptions | number | Date = {}): Promise<void> {
options = Utils.isPlainObject(options) ? options as LockOptions : { lockVersion: options };
await this.getUnitOfWork().lock(entity, { lockMode, ...options });
}
/**
* Fires native insert query. Calling this has no side effects on the context (identity map).
*/
async insert<Entity extends object>(entityNameOrEntity: EntityName<Entity> | Entity, data?: EntityData<Entity> | Entity, options: NativeInsertUpdateOptions<Entity> = {}): Promise<Primary<Entity>> {
const em = this.getContext(false);
let entityName;
if (data === undefined) {
entityName = (entityNameOrEntity as Dictionary).constructor.name;
data = entityNameOrEntity as Entity;
} else {
entityName = Utils.className(entityNameOrEntity as EntityName<Entity>);
}
if (Utils.isEntity<Entity>(data)) {
const meta = helper(data).__meta;
const payload = em.comparator.prepareEntity(data);
const cs = new ChangeSet(data, ChangeSetType.CREATE, payload, meta);
await em.unitOfWork.getChangeSetPersister().executeInserts([cs], { ctx: em.transactionContext, ...options });
return cs.getPrimaryKey()!;
}
data = QueryHelper.processObjectParams(data) as EntityData<Entity>;
em.validator.validateParams(data, 'insert data');
const res = await em.driver.nativeInsert(entityName, data, { ctx: em.transactionContext, ...options });